commit 60cdd1c49f629dd6703b8dbb7c8aa312516a75b7 Author: zanon <50680967+zanon7@users.noreply.github.com> Date: Sat Nov 14 12:58:29 2026 -0300 wassup diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..ab1f416 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,10 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Ignored default folder with query files +/queries/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml +# Editor-based HTTP Client requests +/httpRequests/ diff --git a/.idea/compiler.xml b/.idea/compiler.xml new file mode 100644 index 0000000..f0525cb --- /dev/null +++ b/.idea/compiler.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/encodings.xml b/.idea/encodings.xml new file mode 100644 index 0000000..d674511 --- /dev/null +++ b/.idea/encodings.xml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/jarRepositories.xml b/.idea/jarRepositories.xml new file mode 100644 index 0000000..a761179 --- /dev/null +++ b/.idea/jarRepositories.xml @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..b73630f --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,11 @@ + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/azurite-api/.gitignore b/azurite-api/.gitignore new file mode 100644 index 0000000..c3faf57 --- /dev/null +++ b/azurite-api/.gitignore @@ -0,0 +1,36 @@ +# Eclipse stuff +/.classpath +/.project +/.settings + +# netbeans +/nbproject + +# we use maven! +/build.xml + +# maven +/target + +# vim +.*.sw[a-p] + +# various other potential build files +/build +/bin +/dist +/manifest.mf + +/world + +# Mac filesystem dust +.DS_Store + +# intellij +*.iml +*.ipr +*.iws +.idea/ + +/src/main/resources/achievement +/src/main/resources/lang diff --git a/azurite-api/pom.xml b/azurite-api/pom.xml new file mode 100644 index 0000000..6859c40 --- /dev/null +++ b/azurite-api/pom.xml @@ -0,0 +1,138 @@ + + 4.0.0 + + + dev.azurite.spigot + AzuriteSpigot + 1.0 + + + azurite-api + 1.8.8-R0.1-SNAPSHOT + jar + + + + -Xdoclint:none + 1.8 + 1.8 + UTF-8 + + + + + + spigotmc-public + https://hub.spigotmc.org/nexus/content/groups/public/ + + + + + + mc-repo + https://maven.elmakers.com/repository/ + + + + + + it.unimi.dsi + fastutil + 8.5.16 + + + com.eatthepath + fast-uuid + 0.2.0 + + + net.sf.trove4j + trove4j + 3.0.3 + + + org.ow2.asm + asm + 9.7.1 + + + org.ow2.asm + asm-commons + 9.7.1 + + + commons-lang + commons-lang + 2.6 + + + com.google.guava + guava + 19.0 + + + com.google.code.gson + gson + 2.8.0 + + + org.avaje + ebean + 2.8.1 + + + org.yaml + snakeyaml + 1.33 + compile + + + net.md-5 + bungeecord-chat + 1.8-SNAPSHOT + + + org.jetbrains + annotations + 26.0.2 + compile + + + com.googlecode.json-simple + json-simple + 1.1.1 + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.14.0 + + 1.8 + 1.8 + + + + org.apache.maven.plugins + maven-shade-plugin + 3.6.0 + + + package + + shade + + + + + false + true + + + + + diff --git a/azurite-api/src/main/java/com/destroystokyo/paper/event/executor/MethodHandleEventExecutor.java b/azurite-api/src/main/java/com/destroystokyo/paper/event/executor/MethodHandleEventExecutor.java new file mode 100644 index 0000000..5b28e9b --- /dev/null +++ b/azurite-api/src/main/java/com/destroystokyo/paper/event/executor/MethodHandleEventExecutor.java @@ -0,0 +1,42 @@ +package com.destroystokyo.paper.event.executor; + +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.reflect.Method; + +import com.destroystokyo.paper.util.SneakyThrow; +import org.bukkit.event.Event; +import org.bukkit.event.EventException; +import org.bukkit.event.Listener; +import org.bukkit.plugin.EventExecutor; +import org.jetbrains.annotations.NotNull; + +public class MethodHandleEventExecutor implements EventExecutor { + private final Class eventClass; + private final MethodHandle handle; + + public MethodHandleEventExecutor(@NotNull Class eventClass, @NotNull MethodHandle handle) { + this.eventClass = eventClass; + this.handle = handle; + } + + public MethodHandleEventExecutor(@NotNull Class eventClass, @NotNull Method m) { + this.eventClass = eventClass; + try { + m.setAccessible(true); + this.handle = MethodHandles.lookup().unreflect(m); + } catch (IllegalAccessException e) { + throw new AssertionError("Unable to set accessible", e); + } + } + + @Override + public void execute(@NotNull Listener listener, @NotNull Event event) throws EventException { + if (!eventClass.isInstance(event)) return; + try { + handle.invoke(listener, event); + } catch (Throwable t) { + SneakyThrow.sneaky(t); + } + } +} diff --git a/azurite-api/src/main/java/com/destroystokyo/paper/event/executor/StaticMethodHandleEventExecutor.java b/azurite-api/src/main/java/com/destroystokyo/paper/event/executor/StaticMethodHandleEventExecutor.java new file mode 100644 index 0000000..59fd769 --- /dev/null +++ b/azurite-api/src/main/java/com/destroystokyo/paper/event/executor/StaticMethodHandleEventExecutor.java @@ -0,0 +1,43 @@ +package com.destroystokyo.paper.event.executor; + +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; + +import com.destroystokyo.paper.util.SneakyThrow; +import com.google.common.base.Preconditions; + +import org.bukkit.Bukkit; +import org.bukkit.event.Event; +import org.bukkit.event.EventException; +import org.bukkit.event.Listener; +import org.bukkit.plugin.EventExecutor; +import org.jetbrains.annotations.NotNull; + +public class StaticMethodHandleEventExecutor implements EventExecutor { + private final Class eventClass; + private final MethodHandle handle; + + public StaticMethodHandleEventExecutor(@NotNull Class eventClass, @NotNull Method m) { + Preconditions.checkArgument(Modifier.isStatic(m.getModifiers()), "Not a static method: %s", m); + Preconditions.checkArgument(true, "eventClass is null"); + this.eventClass = eventClass; + try { + m.setAccessible(true); + this.handle = MethodHandles.lookup().unreflect(m); + } catch (IllegalAccessException e) { + throw new AssertionError("Unable to set accessible", e); + } + } + + @Override + public void execute(@NotNull Listener listener, @NotNull Event event) throws EventException { + if (!eventClass.isInstance(event)) return; + try { + handle.invoke(event); + } catch (Throwable throwable) { + SneakyThrow.sneaky(throwable); + } + } +} diff --git a/azurite-api/src/main/java/com/destroystokyo/paper/event/executor/asm/ASMEventExecutorGenerator.java b/azurite-api/src/main/java/com/destroystokyo/paper/event/executor/asm/ASMEventExecutorGenerator.java new file mode 100644 index 0000000..6c01f4e --- /dev/null +++ b/azurite-api/src/main/java/com/destroystokyo/paper/event/executor/asm/ASMEventExecutorGenerator.java @@ -0,0 +1,60 @@ +package com.destroystokyo.paper.event.executor.asm; + +import java.lang.reflect.Method; +import java.util.concurrent.atomic.AtomicInteger; +import org.bukkit.plugin.EventExecutor; + +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.Type; +import org.objectweb.asm.commons.GeneratorAdapter; + +import static org.objectweb.asm.Opcodes.ACC_PUBLIC; +import static org.objectweb.asm.Opcodes.INVOKEINTERFACE; +import static org.objectweb.asm.Opcodes.INVOKESPECIAL; +import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL; +import static org.objectweb.asm.Opcodes.V1_8; + +public final class ASMEventExecutorGenerator { + + private static final String EXECUTE_DESCRIPTOR = "(Lorg/bukkit/event/Listener;Lorg/bukkit/event/Event;)V"; + + public static byte[] generateEventExecutor(final Method m, final String name) { + final ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); + writer.visit(V1_8, ACC_PUBLIC, name.replace('.', '/'), null, Type.getInternalName(Object.class), new String[]{Type.getInternalName(EventExecutor.class)}); + // Generate constructor + GeneratorAdapter methodGenerator = new GeneratorAdapter(writer.visitMethod(ACC_PUBLIC, "", "()V", null, null), ACC_PUBLIC, "", "()V"); + methodGenerator.loadThis(); + methodGenerator.visitMethodInsn(INVOKESPECIAL, Type.getInternalName(Object.class), "", "()V", false); // Invoke the super class (Object) constructor + methodGenerator.returnValue(); + methodGenerator.endMethod(); + // Generate the execute method + methodGenerator = new GeneratorAdapter(writer.visitMethod(ACC_PUBLIC, "execute", EXECUTE_DESCRIPTOR, null, null), ACC_PUBLIC, "execute", EXECUTE_DESCRIPTOR); + methodGenerator.loadArg(0); + methodGenerator.checkCast(Type.getType(m.getDeclaringClass())); + methodGenerator.loadArg(1); + methodGenerator.checkCast(Type.getType(m.getParameterTypes()[0])); + methodGenerator.visitMethodInsn(m.getDeclaringClass().isInterface() ? INVOKEINTERFACE : INVOKEVIRTUAL, Type.getInternalName(m.getDeclaringClass()), m.getName(), Type.getMethodDescriptor(m), m.getDeclaringClass().isInterface()); + // The only purpose of this switch statement is to generate the correct pop instruction, should the event handler method return something other than void. + // Non-void event handlers will be unsupported in a future release. + switch (Type.getType(m.getReturnType()).getSize()) { + // case 0 is omitted because the only type that has size 0 is void - no pop instruction needed. + case 1: + methodGenerator.pop(); // handles reference types and most primitives + break; + case 2: + methodGenerator.pop2(); // handles long and double + break; + } + methodGenerator.returnValue(); + methodGenerator.endMethod(); + writer.visitEnd(); + return writer.toByteArray(); + } + + public static AtomicInteger NEXT_ID = new AtomicInteger(1); + + public static String generateName() { + final int id = NEXT_ID.getAndIncrement(); + return "com.destroystokyo.paper.event.executor.asm.generated.GeneratedEventExecutor" + id; + } +} \ No newline at end of file diff --git a/azurite-api/src/main/java/com/destroystokyo/paper/event/executor/asm/ClassDefiner.java b/azurite-api/src/main/java/com/destroystokyo/paper/event/executor/asm/ClassDefiner.java new file mode 100644 index 0000000..f79685b --- /dev/null +++ b/azurite-api/src/main/java/com/destroystokyo/paper/event/executor/asm/ClassDefiner.java @@ -0,0 +1,34 @@ +package com.destroystokyo.paper.event.executor.asm; + +import org.jetbrains.annotations.NotNull; + +public interface ClassDefiner { + + /** + * Returns if the defined classes can bypass access checks + * + * @return if classes bypass access checks + */ + public default boolean isBypassAccessChecks() { + return false; + } + + /** + * Define a class + * + * @param parentLoader the parent classloader + * @param name the name of the class + * @param data the class data to load + * @return the defined class + * @throws ClassFormatError if the class data is invalid + * @throws NullPointerException if any of the arguments are null + */ + @NotNull + public Class defineClass(@NotNull ClassLoader parentLoader, @NotNull String name, @NotNull byte[] data); + + @NotNull + public static ClassDefiner getInstance() { + return SafeClassDefiner.INSTANCE; + } + +} diff --git a/azurite-api/src/main/java/com/destroystokyo/paper/event/executor/asm/SafeClassDefiner.java b/azurite-api/src/main/java/com/destroystokyo/paper/event/executor/asm/SafeClassDefiner.java new file mode 100644 index 0000000..ac99477 --- /dev/null +++ b/azurite-api/src/main/java/com/destroystokyo/paper/event/executor/asm/SafeClassDefiner.java @@ -0,0 +1,66 @@ +package com.destroystokyo.paper.event.executor.asm; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +import com.google.common.base.Preconditions; + +import com.google.common.collect.MapMaker; +import org.jetbrains.annotations.NotNull; +import org.objectweb.asm.Type; + +public class SafeClassDefiner implements ClassDefiner { + /* default */ static final SafeClassDefiner INSTANCE = new SafeClassDefiner(); + + private SafeClassDefiner() {} + + private final ConcurrentMap loaders = new MapMaker().weakKeys().makeMap(); + + @NotNull + @Override + public Class defineClass(@NotNull ClassLoader parentLoader, @NotNull String name, @NotNull byte[] data) { + GeneratedClassLoader loader = loaders.computeIfAbsent(parentLoader, GeneratedClassLoader::new); + synchronized (loader.getClassLoadingLock(name)) { + Preconditions.checkState(!loader.hasClass(name), "%s already defined", name); + Class c = loader.define(name, data); + assert c.getName().equals(name); + return c; + } + } + + private static class GeneratedClassLoader extends ClassLoader { + static { + ClassLoader.registerAsParallelCapable(); + } + + protected GeneratedClassLoader(@NotNull ClassLoader parent) { + super(parent); + } + + private Class define(@NotNull String name, byte[] data) { + synchronized (getClassLoadingLock(name)) { + assert !hasClass(name); + Class c = defineClass(name, data, 0, data.length); + resolveClass(c); + return c; + } + } + + @Override + @NotNull + public Object getClassLoadingLock(@NotNull String name) { + return super.getClassLoadingLock(name); + } + + public boolean hasClass(@NotNull String name) { + synchronized (getClassLoadingLock(name)) { + try { + Class.forName(name); + return true; + } catch (ClassNotFoundException e) { + return false; + } + } + } + } +} diff --git a/azurite-api/src/main/java/com/destroystokyo/paper/event/server/ServerTickEndEvent.java b/azurite-api/src/main/java/com/destroystokyo/paper/event/server/ServerTickEndEvent.java new file mode 100644 index 0000000..9fd28e0 --- /dev/null +++ b/azurite-api/src/main/java/com/destroystokyo/paper/event/server/ServerTickEndEvent.java @@ -0,0 +1,59 @@ +package com.destroystokyo.paper.event.server; + +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.jetbrains.annotations.NotNull; + +/** + * Called when the server has finished ticking the main loop + */ +public class ServerTickEndEvent extends Event { + + private static final HandlerList handlers = new HandlerList(); + private final int tickNumber; + private final double tickDuration; + private final long timeEnd; + + public ServerTickEndEvent(int tickNumber, double tickDuration, long timeRemaining) { + this.tickNumber = tickNumber; + this.tickDuration = tickDuration; + this.timeEnd = System.nanoTime() + timeRemaining; + } + + /** + * @return What tick this was since start (first tick = 1) + */ + public int getTickNumber() { + return tickNumber; + } + + /** + * @return Time in milliseconds of how long this tick took + */ + public double getTickDuration() { + return tickDuration; + } + + /** + * Amount of nanoseconds remaining before the next tick should start. + * + * If this value is negative, then that means the server has exceeded the tick time limit and TPS has been lost. + * + * Method will continously return the updated time remaining value. (return value is not static) + * + * @return Amount of nanoseconds remaining before the next tick should start + */ + public long getTimeRemaining() { + return this.timeEnd - System.nanoTime(); + } + + @NotNull + public HandlerList getHandlers() { + return handlers; + } + + @NotNull + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/com/destroystokyo/paper/event/server/ServerTickStartEvent.java b/azurite-api/src/main/java/com/destroystokyo/paper/event/server/ServerTickStartEvent.java new file mode 100644 index 0000000..eac85f1 --- /dev/null +++ b/azurite-api/src/main/java/com/destroystokyo/paper/event/server/ServerTickStartEvent.java @@ -0,0 +1,32 @@ +package com.destroystokyo.paper.event.server; + +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.jetbrains.annotations.NotNull; + +public class ServerTickStartEvent extends Event { + + private static final HandlerList handlers = new HandlerList(); + private final int tickNumber; + + public ServerTickStartEvent(int tickNumber) { + this.tickNumber = tickNumber; + } + + /** + * @return What tick this is going be since start (first tick = 1) + */ + public int getTickNumber() { + return tickNumber; + } + + @NotNull + public HandlerList getHandlers() { + return handlers; + } + + @NotNull + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/com/destroystokyo/paper/util/SneakyThrow.java b/azurite-api/src/main/java/com/destroystokyo/paper/util/SneakyThrow.java new file mode 100644 index 0000000..9db0056 --- /dev/null +++ b/azurite-api/src/main/java/com/destroystokyo/paper/util/SneakyThrow.java @@ -0,0 +1,16 @@ +package com.destroystokyo.paper.util; + +import org.jetbrains.annotations.NotNull; + +public class SneakyThrow { + + public static void sneaky(@NotNull Throwable exception) { + SneakyThrow.throwSneaky(exception); + } + + @SuppressWarnings("unchecked") + private static void throwSneaky(@NotNull Throwable exception) throws T { + throw (T) exception; + } + +} diff --git a/azurite-api/src/main/java/dev/azurite/spigot/IAzurite.java b/azurite-api/src/main/java/dev/azurite/spigot/IAzurite.java new file mode 100644 index 0000000..9249f4d --- /dev/null +++ b/azurite-api/src/main/java/dev/azurite/spigot/IAzurite.java @@ -0,0 +1,31 @@ +package dev.azurite.spigot; + +import dev.azurite.spigot.api.knockback.IKnockbackManager; +import dev.azurite.spigot.api.pearls.PearlHandler; +import dev.azurite.spigot.api.protocol.MovementHandler; +import dev.azurite.spigot.api.protocol.PacketHandler; + +import java.util.List; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public interface IAzurite { + + void addMovementHandler(MovementHandler movementHandler); + + void addPacketHandler(PacketHandler packetHandler); + + void addPearlHandler(PearlHandler pearlHandler); + + List getMovementHandlers(); + + List getPacketHandlers(); + + List getPearlHandlers(); + + IKnockbackManager getKnockbackManager(); + +} \ No newline at end of file diff --git a/azurite-api/src/main/java/dev/azurite/spigot/api/SpigotAPI.java b/azurite-api/src/main/java/dev/azurite/spigot/api/SpigotAPI.java new file mode 100644 index 0000000..1b986be --- /dev/null +++ b/azurite-api/src/main/java/dev/azurite/spigot/api/SpigotAPI.java @@ -0,0 +1,15 @@ +package dev.azurite.spigot.api; + +import dev.azurite.spigot.IAzurite; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public class SpigotAPI { + + public static IAzurite getInstance() { + return null; + } +} \ No newline at end of file diff --git a/azurite-api/src/main/java/dev/azurite/spigot/api/chunk/ChunkSnapshot.java b/azurite-api/src/main/java/dev/azurite/spigot/api/chunk/ChunkSnapshot.java new file mode 100644 index 0000000..0e1fa99 --- /dev/null +++ b/azurite-api/src/main/java/dev/azurite/spigot/api/chunk/ChunkSnapshot.java @@ -0,0 +1,5 @@ +package dev.azurite.spigot.api.chunk; + +public interface ChunkSnapshot { + +} \ No newline at end of file diff --git a/azurite-api/src/main/java/dev/azurite/spigot/api/knockback/IKnockback.java b/azurite-api/src/main/java/dev/azurite/spigot/api/knockback/IKnockback.java new file mode 100644 index 0000000..75a4570 --- /dev/null +++ b/azurite-api/src/main/java/dev/azurite/spigot/api/knockback/IKnockback.java @@ -0,0 +1,109 @@ +package dev.azurite.spigot.api.knockback; + +import dev.azurite.spigot.api.knockback.types.IAdvancedKnockback; +import dev.azurite.spigot.api.knockback.types.IConstantKnockback; +import dev.azurite.spigot.api.knockback.types.ISimpleKnockback; + +import java.util.Map; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public interface IKnockback { + + String getName(); + + String getType(); + + IAdvancedKnockback getAdvancedKnockback(); + + ISimpleKnockback getSimpleKnockback(); + + IConstantKnockback getConstantKnockback(); + + boolean isActive(); + + double getRodHorizontal(); + + void setRodHorizontal(double amount); + + double getRodVertical(); + + void setRodVertical(double amount); + + double getRodSpeed(); + + void setRodSpeed(double amount); + + boolean getBowBoostDirectional(); + + void setBowBoostDirectional(boolean value); + + boolean isBowBoostOnlyShooter(); + + void setBowBoostOnlyShooter(boolean value); + + double getBowHorizontal(); + + void setBowHorizontal(double amount); + + double getBowVertical(); + + void setBowVertical(double amount); + + double getBowPunchMultiplier(); + + void setBowPunchMultiplier(double amount); + + float getPotionFall(); + + void setPotionFall(float amount); + + float getPotionSpeed(); + + void setPotionSpeed(float amount); + + float getPotionOffset(); + + void setPotionOffset(float amount); + double getPotionYOffset(); + + void setPotionYOffset(double amount); + + boolean isPotionFast(); + + void setPotionFast(boolean value); + + int getCpsCapOverride(); + + void setCpsCapOverride(int cps); + + int getHitDelay(); + + void setHitDelay(int amount); + + int getHitDelayArrow(); + + void setHitDelayArrow(int amount); + + boolean isComboMode(); + + void setComboMode(boolean value); + + double getComboHeight(); + + void setComboHeight(double amount); + + int getComboTicks(); + + void setComboTicks(int amount); + + double getComboVelocity(); + + void setComboVelocity(double amount); + + Map getValues(); + +} \ No newline at end of file diff --git a/azurite-api/src/main/java/dev/azurite/spigot/api/knockback/IKnockbackManager.java b/azurite-api/src/main/java/dev/azurite/spigot/api/knockback/IKnockbackManager.java new file mode 100644 index 0000000..98063c9 --- /dev/null +++ b/azurite-api/src/main/java/dev/azurite/spigot/api/knockback/IKnockbackManager.java @@ -0,0 +1,26 @@ +package dev.azurite.spigot.api.knockback; + +import java.util.List; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public interface IKnockbackManager { + + List getProfiles(); + + IKnockback createProfile(String name); + + IKnockback deleteProfile(String name); + + IKnockback getByName(String name); + + IKnockback getActiveProfile(); + + void setActiveProfile(IKnockback knockback); + + void save(boolean async); + +} \ No newline at end of file diff --git a/azurite-api/src/main/java/dev/azurite/spigot/api/knockback/types/IAdvancedKnockback.java b/azurite-api/src/main/java/dev/azurite/spigot/api/knockback/types/IAdvancedKnockback.java new file mode 100644 index 0000000..4ccb06b --- /dev/null +++ b/azurite-api/src/main/java/dev/azurite/spigot/api/knockback/types/IAdvancedKnockback.java @@ -0,0 +1,82 @@ +package dev.azurite.spigot.api.knockback.types; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public interface IAdvancedKnockback { + + double getHorizontal(); + + void setHorizontal(double amount); + + double getHorizontalOnGround(); + + void setHorizontalOnGround(double amount); + + double getHorizontalSprinting(); + + void setHorizontalSprinting(double amount); + + boolean isHorizontalInherit(); + + void setHorizontalInherit(boolean value); + + double getHorizontalFriction(); + + void setHorizontalFriction(double amount); + + double getHorizontalKnockbackDeduction(); + + void setHorizontalKnockbackDeduction(double amount); + + double getVertical(); + + void setVertical(double amount); + + double getVerticalOnGround(); + + void setVerticalOnGround(double amount); + + double getVerticalInAir(); + + void setVerticalInAir(double amount); + + double getVerticalSprinting(); + + void setVerticalSprinting(double amount); + + boolean isVerticalInherit(); + + void setVerticalInherit(boolean value); + + double getVerticalFriction(); + + void setVerticalFriction(double amount); + + boolean isOnePointSevenEnabled(); + + void setOnePointSevenEnabled(boolean value); + + double getOnePointSevenHorizontal(); + + void setOnePointSevenHorizontal(double amount); + + boolean isEnabledVerticalLimit(); + + void setEnableVerticalLimit(boolean value); + + double getVerticalLimit(); + + void setVerticalLimit(double amount); + + double getSlowdown(); + + void setSlowdown(double amount); + + boolean isCancelSprint(); + + void setCancelSprint(boolean value); + +} \ No newline at end of file diff --git a/azurite-api/src/main/java/dev/azurite/spigot/api/knockback/types/IConstantKnockback.java b/azurite-api/src/main/java/dev/azurite/spigot/api/knockback/types/IConstantKnockback.java new file mode 100644 index 0000000..22ecedc --- /dev/null +++ b/azurite-api/src/main/java/dev/azurite/spigot/api/knockback/types/IConstantKnockback.java @@ -0,0 +1,23 @@ +package dev.azurite.spigot.api.knockback.types; + +public interface IConstantKnockback { + void setHorizontal(double amount); + + double getHorizontal(); + + void setVertical(double amount); + + double getVertical(); + + void setVerticalLongAir(double amount); + + double getVerticalLongAir(); + + void setHorizontalSprintReset(double amount); + + double getHorizontalSprintReset(); + + void setYawModifier(double amount); + + double getYawModifier(); +} diff --git a/azurite-api/src/main/java/dev/azurite/spigot/api/knockback/types/ISimpleKnockback.java b/azurite-api/src/main/java/dev/azurite/spigot/api/knockback/types/ISimpleKnockback.java new file mode 100644 index 0000000..37bc6b1 --- /dev/null +++ b/azurite-api/src/main/java/dev/azurite/spigot/api/knockback/types/ISimpleKnockback.java @@ -0,0 +1,46 @@ +package dev.azurite.spigot.api.knockback.types; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public interface ISimpleKnockback { + + void setFriction(double amount); + + double getFriction(); + + void setHorizontal(double amount); + + double getHorizontal(); + + void setVertical(double amount); + + double getVertical(); + + void setVerticalLimit(double amount); + + double getVerticalLimit(); + + void setExtraHorizontal(double amount); + + double getExtraHorizontal(); + + void setExtraVertical(double amount); + + double getExtraVertical(); + + void setSlowdown(double amount); + + double getSlowdown(); + + void setOnePointSevenEnabled(boolean value); + + boolean isOnePointSevenEnabled(); + + void setOnePointSevenMultiplier(double amount); + + double getOnePointSevenMultiplier(); + +} \ No newline at end of file diff --git a/azurite-api/src/main/java/dev/azurite/spigot/api/pearls/PearlHandler.java b/azurite-api/src/main/java/dev/azurite/spigot/api/pearls/PearlHandler.java new file mode 100644 index 0000000..a4abd2e --- /dev/null +++ b/azurite-api/src/main/java/dev/azurite/spigot/api/pearls/PearlHandler.java @@ -0,0 +1,15 @@ +package dev.azurite.spigot.api.pearls; + +import org.bukkit.entity.Player; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public interface PearlHandler { + + default boolean hasCooldown(Player player) { + return false; + } +} \ No newline at end of file diff --git a/azurite-api/src/main/java/dev/azurite/spigot/api/protocol/MovementHandler.java b/azurite-api/src/main/java/dev/azurite/spigot/api/protocol/MovementHandler.java new file mode 100644 index 0000000..c4dca54 --- /dev/null +++ b/azurite-api/src/main/java/dev/azurite/spigot/api/protocol/MovementHandler.java @@ -0,0 +1,19 @@ +package dev.azurite.spigot.api.protocol; + +import org.bukkit.Location; +import org.bukkit.entity.Player; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public interface MovementHandler { + + void handleUpdateLocation(Player player, Location to, Location from, Object packet); + + void handleBlockUpdateLocation(Player player, Location from, Location to); + + void handleUpdateRotation(Player player, Location to, Location from, Object packet); + +} \ No newline at end of file diff --git a/azurite-api/src/main/java/dev/azurite/spigot/api/protocol/PacketHandler.java b/azurite-api/src/main/java/dev/azurite/spigot/api/protocol/PacketHandler.java new file mode 100644 index 0000000..c7a466c --- /dev/null +++ b/azurite-api/src/main/java/dev/azurite/spigot/api/protocol/PacketHandler.java @@ -0,0 +1,17 @@ +package dev.azurite.spigot.api.protocol; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public interface PacketHandler { + + default boolean handleReceivedPacket(Object connection, Object packet) { + return true; + } + + default boolean handleSentPacket(Object connection, Object packet) { + return true; + } +} \ No newline at end of file diff --git a/azurite-api/src/main/java/org/bukkit/Achievement.java b/azurite-api/src/main/java/org/bukkit/Achievement.java new file mode 100644 index 0000000..f9d2a8b --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/Achievement.java @@ -0,0 +1,70 @@ +package org.bukkit; + +/** + * Represents an achievement, which may be given to players. + */ +public enum Achievement { + OPEN_INVENTORY, + MINE_WOOD (OPEN_INVENTORY), + BUILD_WORKBENCH (MINE_WOOD), + BUILD_PICKAXE (BUILD_WORKBENCH), + BUILD_FURNACE (BUILD_PICKAXE), + ACQUIRE_IRON (BUILD_FURNACE), + BUILD_HOE (BUILD_WORKBENCH), + MAKE_BREAD (BUILD_HOE), + BAKE_CAKE (BUILD_HOE), + BUILD_BETTER_PICKAXE (BUILD_PICKAXE), + COOK_FISH (BUILD_FURNACE), + ON_A_RAIL (ACQUIRE_IRON), + BUILD_SWORD (BUILD_WORKBENCH), + KILL_ENEMY (BUILD_SWORD), + KILL_COW (BUILD_SWORD), + FLY_PIG (KILL_COW), + SNIPE_SKELETON (KILL_ENEMY), + GET_DIAMONDS (ACQUIRE_IRON), + NETHER_PORTAL (GET_DIAMONDS), + GHAST_RETURN (NETHER_PORTAL), + GET_BLAZE_ROD (NETHER_PORTAL), + BREW_POTION (GET_BLAZE_ROD), + END_PORTAL (GET_BLAZE_ROD), + THE_END (END_PORTAL), + ENCHANTMENTS (GET_DIAMONDS), + OVERKILL (ENCHANTMENTS), + BOOKCASE (ENCHANTMENTS), + EXPLORE_ALL_BIOMES (END_PORTAL), + SPAWN_WITHER (THE_END), + KILL_WITHER (SPAWN_WITHER), + FULL_BEACON (KILL_WITHER), + BREED_COW (KILL_COW), + DIAMONDS_TO_YOU (GET_DIAMONDS), + OVERPOWERED (BUILD_BETTER_PICKAXE) + ; + + private final Achievement parent; + + Achievement() { + parent = null; + } + + Achievement(Achievement parent) { + this.parent = parent; + } + + /** + * Returns whether or not this achievement has a parent achievement. + * + * @return whether the achievement has a parent achievement + */ + public boolean hasParent() { + return parent != null; + } + + /** + * Returns the parent achievement of this achievement, or null if none. + * + * @return the parent achievement or null + */ + public Achievement getParent() { + return parent; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/Art.java b/azurite-api/src/main/java/org/bukkit/Art.java new file mode 100644 index 0000000..8aeb1b7 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/Art.java @@ -0,0 +1,110 @@ +package org.bukkit; + +import com.google.common.collect.Maps; +import org.apache.commons.lang.Validate; + +import java.util.HashMap; + +/** + * Represents the art on a painting + */ +public enum Art { + KEBAB(0, 1, 1), + AZTEC(1, 1, 1), + ALBAN(2, 1, 1), + AZTEC2(3, 1, 1), + BOMB(4, 1, 1), + PLANT(5, 1, 1), + WASTELAND(6, 1, 1), + POOL(7, 2, 1), + COURBET(8, 2, 1), + SEA(9, 2, 1), + SUNSET(10, 2, 1), + CREEBET(11, 2, 1), + WANDERER(12, 1, 2), + GRAHAM(13, 1, 2), + MATCH(14, 2, 2), + BUST(15, 2, 2), + STAGE(16, 2, 2), + VOID(17, 2, 2), + SKULL_AND_ROSES(18, 2, 2), + WITHER(19, 2, 2), + FIGHTERS(20, 4, 2), + POINTER(21, 4, 4), + PIGSCENE(22, 4, 4), + BURNINGSKULL(23, 4, 4), + SKELETON(24, 4, 3), + DONKEYKONG(25, 4, 3); + + private int id, width, height; + private static final HashMap BY_NAME = Maps.newHashMap(); + private static final HashMap BY_ID = Maps.newHashMap(); + + Art(int id, int width, int height) { + this.id = id; + this.width = width; + this.height = height; + } + + /** + * Gets the width of the painting, in blocks + * + * @return The width of the painting, in blocks + */ + public int getBlockWidth() { + return width; + } + + /** + * Gets the height of the painting, in blocks + * + * @return The height of the painting, in blocks + */ + public int getBlockHeight() { + return height; + } + + /** + * Get the ID of this painting. + * + * @return The ID of this painting + * @deprecated Magic value + */ + @Deprecated + public int getId() { + return id; + } + + /** + * Get a painting by its numeric ID + * + * @param id The ID + * @return The painting + * @deprecated Magic value + */ + @Deprecated + public static Art getById(int id) { + return BY_ID.get(id); + } + + /** + * Get a painting by its unique name + *

+ * This ignores underscores and capitalization + * + * @param name The name + * @return The painting + */ + public static Art getByName(String name) { + Validate.notNull(name, "Name cannot be null"); + + return BY_NAME.get(name.toLowerCase().replaceAll("_", "")); + } + + static { + for (Art art : values()) { + BY_ID.put(art.id, art); + BY_NAME.put(art.toString().toLowerCase().replaceAll("_", ""), art); + } + } +} diff --git a/azurite-api/src/main/java/org/bukkit/BanEntry.java b/azurite-api/src/main/java/org/bukkit/BanEntry.java new file mode 100644 index 0000000..f2072e3 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/BanEntry.java @@ -0,0 +1,128 @@ +package org.bukkit; + +import java.util.Date; + +/** + * A single entry from a ban list. This may represent either a player ban or + * an IP ban. + *

+ * Ban entries include the following properties: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Property information
PropertyDescription
Target Name / IP AddressThe target name or IP address
Creation DateThe creation date of the ban
SourceThe source of the ban, such as a player, console, plugin, etc
Expiration DateThe expiration date of the ban
ReasonThe reason for the ban
+ *

+ * Unsaved information is not automatically written to the implementation's + * ban list, instead, the {@link #save()} method must be called to write the + * changes to the ban list. If this ban entry has expired (such as from an + * unban) and is no longer found in the list, the {@link #save()} call will + * re-add it to the list, therefore banning the victim specified. + *

+ * Likewise, changes to the associated {@link BanList} or other entries may or + * may not be reflected in this entry. + */ +public interface BanEntry { + + /** + * Gets the target involved. This may be in the form of an IP or a player + * name. + * + * @return the target name or IP address + */ + String getTarget(); + + /** + * Gets the date this ban entry was created. + * + * @return the creation date + */ + Date getCreated(); + + /** + * Sets the date this ban entry was created. + * + * @param created the new created date, cannot be null + * @see #save() saving changes + */ + void setCreated(Date created); + + /** + * Gets the source of this ban. + *

+ * Note: A source is considered any String, although this is generally a + * player name. + * + * @return the source of the ban + */ + String getSource(); + + /** + * Sets the source of this ban. + *

+ * Note: A source is considered any String, although this is generally a + * player name. + * + * @param source the new source where null values become empty strings + * @see #save() saving changes + */ + void setSource(String source); + + /** + * Gets the date this ban expires on, or null for no defined end date. + * + * @return the expiration date + */ + Date getExpiration(); + + /** + * Sets the date this ban expires on. Null values are considered + * "infinite" bans. + * + * @param expiration the new expiration date, or null to indicate an + * eternity + * @see #save() saving changes + */ + void setExpiration(Date expiration); + + /** + * Gets the reason for this ban. + * + * @return the ban reason, or null if not set + */ + String getReason(); + + /** + * Sets the reason for this ban. Reasons must not be null. + * + * @param reason the new reason, null values assume the implementation + * default + * @see #save() saving changes + */ + void setReason(String reason); + + /** + * Saves the ban entry, overwriting any previous data in the ban list. + *

+ * Saving the ban entry of an unbanned player will cause the player to be + * banned once again. + */ + void save(); +} diff --git a/azurite-api/src/main/java/org/bukkit/BanList.java b/azurite-api/src/main/java/org/bukkit/BanList.java new file mode 100644 index 0000000..1502a92 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/BanList.java @@ -0,0 +1,71 @@ +package org.bukkit; + +import java.util.Date; +import java.util.Set; + +/** + * A ban list, containing bans of some {@link Type}. + */ +public interface BanList { + + /** + * Represents a ban-type that a {@link BanList} may track. + */ + enum Type { + /** + * Banned player names + */ + NAME, + /** + * Banned player IP addresses + */ + IP, + } + + /** + * Gets a {@link BanEntry} by target. + * + * @param target entry parameter to search for + * @return the corresponding entry, or null if none found + */ + BanEntry getBanEntry(String target); + + /** + * Adds a ban to the this list. If a previous ban exists, this will + * update the previous entry. + * + * @param target the target of the ban + * @param reason reason for the ban, null indicates implementation default + * @param expires date for the ban's expiration (unban), or null to imply + * forever + * @param source source of the ban, null indicates implementation default + * @return the entry for the newly created ban, or the entry for the + * (updated) previous ban + */ + BanEntry addBan(String target, String reason, Date expires, String source); + + /** + * Gets a set containing every {@link BanEntry} in this list. + * + * @return an immutable set containing every entry tracked by this list + */ + Set getBanEntries(); + + /** + * Gets if a {@link BanEntry} exists for the target, indicating an active + * ban status. + * + * @param target the target to find + * @return true if a {@link BanEntry} exists for the name, indicating an + * active ban status, false otherwise + */ + boolean isBanned(String target); + + /** + * Removes the specified target from this list, therefore indicating a + * "not banned" status. + * + * @param target the target to remove from this list + */ + void pardon(String target); +} diff --git a/azurite-api/src/main/java/org/bukkit/BlockChangeDelegate.java b/azurite-api/src/main/java/org/bukkit/BlockChangeDelegate.java new file mode 100644 index 0000000..bf230b3 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/BlockChangeDelegate.java @@ -0,0 +1,104 @@ +package org.bukkit; + +/** + * A delegate for handling block changes. This serves as a direct interface + * between generation algorithms in the server implementation and utilizing + * code. + */ +public interface BlockChangeDelegate { + + /** + * Set a block type at the specified coordinates without doing all world + * updates and notifications. + *

+ * It is safe to have this call World.setTypeId, but it may be slower than + * World.setRawTypeId. + * + * @param x X coordinate + * @param y Y coordinate + * @param z Z coordinate + * @param typeId New block ID + * @return true if the block was set successfully + * @deprecated Magic value + */ + @Deprecated + boolean setRawTypeId(int x, int y, int z, int typeId); + + /** + * Set a block type and data at the specified coordinates without doing + * all world updates and notifications. + *

+ * It is safe to have this call World.setTypeId, but it may be slower than + * World.setRawTypeId. + * + * @param x X coordinate + * @param y Y coordinate + * @param z Z coordinate + * @param typeId New block ID + * @param data Block data + * @return true if the block was set successfully + * @deprecated Magic value + */ + @Deprecated + boolean setRawTypeIdAndData(int x, int y, int z, int typeId, int data); + + /** + * Set a block type at the specified coordinates. + *

+ * This method cannot call World.setRawTypeId, a full update is needed. + * + * @param x X coordinate + * @param y Y coordinate + * @param z Z coordinate + * @param typeId New block ID + * @return true if the block was set successfully + * @deprecated Magic value + */ + @Deprecated + boolean setTypeId(int x, int y, int z, int typeId); + + /** + * Set a block type and data at the specified coordinates. + *

+ * This method cannot call World.setRawTypeId, a full update is needed. + * + * @param x X coordinate + * @param y Y coordinate + * @param z Z coordinate + * @param typeId New block ID + * @param data Block data + * @return true if the block was set successfully + * @deprecated Magic value + */ + @Deprecated + boolean setTypeIdAndData(int x, int y, int z, int typeId, int data); + + /** + * Get the block type at the location. + * + * @param x X coordinate + * @param y Y coordinate + * @param z Z coordinate + * @return The block ID + * @deprecated Magic value + */ + @Deprecated + int getTypeId(int x, int y, int z); + + /** + * Gets the height of the world. + * + * @return Height of the world + */ + int getHeight(); + + /** + * Checks if the specified block is empty (air) or not. + * + * @param x X coordinate + * @param y Y coordinate + * @param z Z coordinate + * @return True if the block is considered empty. + */ + boolean isEmpty(int x, int y, int z); +} diff --git a/azurite-api/src/main/java/org/bukkit/Bukkit.java b/azurite-api/src/main/java/org/bukkit/Bukkit.java new file mode 100644 index 0000000..4af0788 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/Bukkit.java @@ -0,0 +1,1161 @@ +package org.bukkit; + +import com.avaje.ebean.config.ServerConfig; +import com.google.common.collect.ImmutableList; +import org.bukkit.Warning.WarningState; +import org.bukkit.command.*; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryType; +import org.bukkit.event.server.ServerListPingEvent; +import org.bukkit.generator.ChunkGenerator; +import org.bukkit.help.HelpMap; +import org.bukkit.inventory.*; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.map.MapView; +import org.bukkit.permissions.Permissible; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.ServicesManager; +import org.bukkit.plugin.messaging.Messenger; +import org.bukkit.scheduler.BukkitScheduler; +import org.bukkit.scoreboard.ScoreboardManager; +import org.bukkit.util.CachedServerIcon; + +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.Serializable; +import java.util.*; +import java.util.logging.Logger; + +/** + * Represents the Bukkit core, for version and Server singleton handling + */ +public final class Bukkit { + private static Server server; + + /** + * Static class cannot be initialized. + */ + private Bukkit() {} + + /** + * Gets the current {@link Server} singleton + * + * @return Server instance being ran + */ + public static Server getServer() { + return server; + } + + /** + * Attempts to set the {@link Server} singleton. + *

+ * This cannot be done if the Server is already set. + * + * @param server Server instance + */ + public static void setServer(Server server) { + if (Bukkit.server != null) { + throw new UnsupportedOperationException("Cannot redefine singleton Server"); + } + + Bukkit.server = server; + server.getLogger().info("This server is running " + getName() + " version " + getVersion()); + } + + /** + * Gets the name of this server implementation. + * + * @return name of this server implementation + */ + public static String getName() { + return server.getName(); + } + + /** + * Gets the version string of this server implementation. + * + * @return version of this server implementation + */ + public static String getVersion() { + return server.getVersion(); + } + + /** + * Gets the Bukkit version that this server is running. + * + * @return version of Bukkit + */ + public static String getBukkitVersion() { + return server.getBukkitVersion(); + } + + /** + * Gets an array copy of all currently logged in players. + *

+ * This method exists for legacy reasons to provide backwards + * compatibility. It will not exist at runtime and should not be used + * under any circumstances. + * + * @deprecated superseded by {@link #getOnlinePlayers()} + * @return an array of Players that are currently online + */ + @Deprecated + public static Player[] _INVALID_getOnlinePlayers() { + return server._INVALID_getOnlinePlayers(); + } + + /** + * Gets a view of all currently logged in players. This {@linkplain + * Collections#unmodifiableCollection(Collection) view} is a reused + * object, making some operations like {@link Collection#size()} + * zero-allocation. + *

+ * The collection is a view backed by the internal representation, such + * that, changes to the internal state of the server will be reflected + * immediately. However, the reuse of the returned collection (identity) + * is not strictly guaranteed for future or all implementations. Casting + * the collection, or relying on interface implementations (like {@link + * Serializable} or {@link List}), is deprecated. + *

+ * Iteration behavior is undefined outside of self-contained main-thread + * uses. Normal and immediate iterator use without consequences that + * affect the collection are fully supported. The effects following + * (non-exhaustive) {@link Entity#teleport(Location) teleportation}, + * {@link Player#setHealth(double) death}, and {@link Player#kickPlayer( + * String) kicking} are undefined. Any use of this collection from + * asynchronous threads is unsafe. + *

+ * For safe consequential iteration or mimicking the old array behavior, + * using {@link Collection#toArray(Object[])} is recommended. For making + * snapshots, {@link ImmutableList#copyOf(Collection)} is recommended. + * + * @return a view of currently online players. + */ + public static Collection getOnlinePlayers() { + return server.getOnlinePlayers(); + } + + /** + * Get the maximum amount of players which can login to this server. + * + * @return the amount of players this server allows + */ + public static int getMaxPlayers() { + return server.getMaxPlayers(); + } + + public static int setMaxPlayers(int maxPlayers) { + return server.setMaxPlayers(maxPlayers); + } + + /** + * Get the game port that the server runs on. + * + * @return the port number of this server + */ + public static int getPort() { + return server.getPort(); + } + + /** + * Get the view distance from this server. + * + * @return the view distance from this server. + */ + public static int getViewDistance() { + return server.getViewDistance(); + } + + /** + * Get the IP that this server is bound to, or empty string if not + * specified. + * + * @return the IP string that this server is bound to, otherwise empty + * string + */ + public static String getIp() { + return server.getIp(); + } + + /** + * Get the name of this server. + * + * @return the name of this server + */ + public static String getServerName() { + return server.getServerName(); + } + + /** + * Get an ID of this server. The ID is a simple generally alphanumeric ID + * that can be used for uniquely identifying this server. + * + * @return the ID of this server + */ + public static String getServerId() { + return server.getServerId(); + } + + /** + * Get world type (level-type setting) for default world. + * + * @return the value of level-type (e.g. DEFAULT, FLAT, DEFAULT_1_1) + */ + public static String getWorldType() { + return server.getWorldType(); + } + + /** + * Get generate-structures setting. + * + * @return true if structure generation is enabled, false otherwise + */ + public static boolean getGenerateStructures() { + return server.getGenerateStructures(); + } + + /** + * Gets whether this server allows the End or not. + * + * @return whether this server allows the End or not + */ + public static boolean getAllowEnd() { + return server.getAllowEnd(); + } + + /** + * Gets whether this server allows the Nether or not. + * + * @return whether this server allows the Nether or not + */ + public static boolean getAllowNether() { + return server.getAllowNether(); + } + + /** + * Gets whether this server has a whitelist or not. + * + * @return whether this server has a whitelist or not + */ + public static boolean hasWhitelist() { + return server.hasWhitelist(); + } + + /** + * Sets if the server is whitelisted. + * + * @param value true for whitelist on, false for off + */ + public static void setWhitelist(boolean value) { + server.setWhitelist(value); + } + + /** + * Gets a list of whitelisted players. + * + * @return a set containing all whitelisted players + */ + public static Set getWhitelistedPlayers() { + return server.getWhitelistedPlayers(); + } + + /** + * Reloads the whitelist from disk. + */ + public static void reloadWhitelist() { + server.reloadWhitelist(); + } + + /** + * Broadcast a message to all players. + *

+ * This is the same as calling {@link #broadcast(String, + * String)} to {@link Server#BROADCAST_CHANNEL_USERS} + * + * @param message the message + * @return the number of players + */ + public static int broadcastMessage(String message) { + return server.broadcastMessage(message); + } + + // Paper start + /** + * Sends the component to the player + * + * @param component the components to send + */ + public static void broadcast(net.md_5.bungee.api.chat.BaseComponent component) { + server.broadcast(component); + } + + /** + * Sends an array of components as a single message to the player + * + * @param components the components to send + */ + public static void broadcast(net.md_5.bungee.api.chat.BaseComponent... components) { + server.broadcast(components); + } + // Paper end + + /** + * Gets the name of the update folder. The update folder is used to safely + * update plugins at the right moment on a plugin load. + *

+ * The update folder name is relative to the plugins folder. + * + * @return the name of the update folder + */ + public static String getUpdateFolder() { + return server.getUpdateFolder(); + } + + /** + * Gets the update folder. The update folder is used to safely update + * plugins at the right moment on a plugin load. + * + * @return the update folder + */ + public static File getUpdateFolderFile() { + return server.getUpdateFolderFile(); + } + + /** + * Gets the value of the connection throttle setting. + * + * @return the value of the connection throttle setting + */ + public static long getConnectionThrottle() { + return server.getConnectionThrottle(); + } + + /** + * Gets default ticks per animal spawns value. + *

+ * Example Usage: + *

    + *
  • A value of 1 will mean the server will attempt to spawn monsters + * every tick. + *
  • A value of 400 will mean the server will attempt to spawn monsters + * every 400th tick. + *
  • A value below 0 will be reset back to Minecraft's default. + *
+ *

+ * Note: If set to 0, animal spawning will be disabled. We + * recommend using spawn-animals to control this instead. + *

+ * Minecraft default: 400. + * + * @return the default ticks per animal spawns value + */ + public static int getTicksPerAnimalSpawns() { + return server.getTicksPerAnimalSpawns(); + } + + /** + * Gets the default ticks per monster spawns value. + *

+ * Example Usage: + *

    + *
  • A value of 1 will mean the server will attempt to spawn monsters + * every tick. + *
  • A value of 400 will mean the server will attempt to spawn monsters + * every 400th tick. + *
  • A value below 0 will be reset back to Minecraft's default. + *
+ *

+ * Note: If set to 0, monsters spawning will be disabled. We + * recommend using spawn-monsters to control this instead. + *

+ * Minecraft default: 1. + * + * @return the default ticks per monsters spawn value + */ + public static int getTicksPerMonsterSpawns() { + return server.getTicksPerMonsterSpawns(); + } + + /** + * Gets a player object by the given username. + *

+ * This method may not return objects for offline players. + * + * @param name the name to look up + * @return a player if one was found, null otherwise + */ + public static Player getPlayer(String name) { + return server.getPlayer(name); + } + + /** + * Gets the player with the exact given name, case insensitive. + * + * @param name Exact name of the player to retrieve + * @return a player object if one was found, null otherwise + */ + public static Player getPlayerExact(String name) { + return server.getPlayerExact(name); + } + + /** + * Attempts to match any players with the given name, and returns a list + * of all possibly matches. + *

+ * This list is not sorted in any particular order. If an exact match is + * found, the returned list will only contain a single result. + * + * @param name the (partial) name to match + * @return list of all possible players + */ + public static List matchPlayer(String name) { + return server.matchPlayer(name); + } + + /** + * Gets the player with the given UUID. + * + * @param id UUID of the player to retrieve + * @return a player object if one was found, null otherwise + */ + public static Player getPlayer(UUID id) { + return server.getPlayer(id); + } + + /** + * Gets the plugin manager for interfacing with plugins. + * + * @return a plugin manager for this Server instance + */ + public static PluginManager getPluginManager() { + return server.getPluginManager(); + } + + /** + * Gets the scheduler for managing scheduled events. + * + * @return a scheduling service for this server + */ + public static BukkitScheduler getScheduler() { + return server.getScheduler(); + } + + /** + * Gets a services manager. + * + * @return s services manager + */ + public static ServicesManager getServicesManager() { + return server.getServicesManager(); + } + + /** + * Gets a list of all worlds on this server. + * + * @return a list of worlds + */ + public static List getWorlds() { + return server.getWorlds(); + } + + /** + * Creates or loads a world with the given name using the specified + * options. + *

+ * If the world is already loaded, it will just return the equivalent of + * getWorld(creator.name()). + * + * @param creator the options to use when creating the world + * @return newly created or loaded world + */ + public static World createWorld(WorldCreator creator) { + return server.createWorld(creator); + } + + /** + * Unloads a world with the given name. + * + * @param name Name of the world to unload + * @param save whether to save the chunks before unloading + * @return true if successful, false otherwise + */ + public static boolean unloadWorld(String name, boolean save) { + return server.unloadWorld(name, save); + } + + /** + * Unloads the given world. + * + * @param world the world to unload + * @param save whether to save the chunks before unloading + * @return true if successful, false otherwise + */ + public static boolean unloadWorld(World world, boolean save) { + return server.unloadWorld(world, save); + } + + /** + * Gets the world with the given name. + * + * @param name the name of the world to retrieve + * @return a world with the given name, or null if none exists + */ + public static World getWorld(String name) { + return server.getWorld(name); + } + + /** + * Gets the world from the given Unique ID. + * + * @param uid a unique-id of the world to retrieve + * @return a world with the given Unique ID, or null if none exists + */ + public static World getWorld(UUID uid) { + return server.getWorld(uid); + } + + /** + * Gets the map from the given item ID. + * + * @param id the id of the map to get + * @return a map view if it exists, or null otherwise + * @deprecated Magic value + */ + @Deprecated + public static MapView getMap(short id) { + return server.getMap(id); + } + + /** + * Create a new map with an automatically assigned ID. + * + * @param world the world the map will belong to + * @return a newly created map view + */ + public static MapView createMap(World world) { + return server.createMap(world); + } + + /** + * Reloads the server, refreshing settings and plugin information. + */ + public static void reload() { + server.reload(); + } + + public static void reloadConfigs() { + server.reloadConfigs(); + } + + /** + * Returns the primary logger associated with this server instance. + * + * @return Logger associated with this server + */ + public static Logger getLogger() { + return server.getLogger(); + } + + /** + * Gets a {@link PluginCommand} with the given name or alias. + * + * @param name the name of the command to retrieve + * @return a plugin command if found, null otherwise + */ + public static PluginCommand getPluginCommand(String name) { + return server.getPluginCommand(name); + } + + /** + * Writes loaded players to disk. + */ + public static void savePlayers() { + server.savePlayers(); + } + + /** + * Dispatches a command on this server, and executes it if found. + * + * @param sender the apparent sender of the command + * @param commandLine the command + arguments. Example: test abc + * 123 + * @return returns false if no target is found + * @throws CommandException thrown when the executor for the given command + * fails with an unhandled exception + */ + public static boolean dispatchCommand(CommandSender sender, String commandLine) throws CommandException { + return server.dispatchCommand(sender, commandLine); + } + + /** + * Populates a given {@link ServerConfig} with values attributes to this + * server. + * + * @param config the server config to populate + */ + public static void configureDbConfig(ServerConfig config) { + server.configureDbConfig(config); + } + + /** + * Adds a recipe to the crafting manager. + * + * @param recipe the recipe to add + * @return true if the recipe was added, false if it wasn't for some + * reason + */ + public static boolean addRecipe(Recipe recipe) { + return server.addRecipe(recipe); + } + + /** + * Get a list of all recipes for a given item. The stack size is ignored + * in comparisons. If the durability is -1, it will match any data value. + * + * @param result the item to match against recipe results + * @return a list of recipes with the given result + */ + public static List getRecipesFor(ItemStack result) { + return server.getRecipesFor(result); + } + + /** + * Get an iterator through the list of crafting recipes. + * + * @return an iterator + */ + public static Iterator recipeIterator() { + return server.recipeIterator(); + } + + /** + * Clears the list of crafting recipes. + */ + public static void clearRecipes() { + server.clearRecipes(); + } + + /** + * Resets the list of crafting recipes to the default. + */ + public static void resetRecipes() { + server.resetRecipes(); + } + + /** + * Gets a list of command aliases defined in the server properties. + * + * @return a map of aliases to command names + */ + public static Map getCommandAliases() { + return server.getCommandAliases(); + } + + /** + * Gets the radius, in blocks, around each worlds spawn point to protect. + * + * @return spawn radius, or 0 if none + */ + public static int getSpawnRadius() { + return server.getSpawnRadius(); + } + + /** + * Sets the radius, in blocks, around each worlds spawn point to protect. + * + * @param value new spawn radius, or 0 if none + */ + public static void setSpawnRadius(int value) { + server.setSpawnRadius(value); + } + + /** + * Gets whether the Server is in online mode or not. + * + * @return true if the server authenticates clients, false otherwise + */ + public static boolean getOnlineMode() { + return server.getOnlineMode(); + } + + /** + * Gets whether this server allows flying or not. + * + * @return true if the server allows flight, false otherwise + */ + public static boolean getAllowFlight() { + return server.getAllowFlight(); + } + + /** + * Gets whether the server is in hardcore mode or not. + * + * @return true if the server mode is hardcore, false otherwise + */ + public static boolean isHardcore() { + return server.isHardcore(); + } + + /** + * Gets whether to use vanilla (false) or exact behaviour (true). + * + *

    + *
  • Vanilla behaviour: check for collisions and move the player if + * needed. + *
  • Exact behaviour: spawn players exactly where they should be. + *
+ * + * @return true if exact location locations are used for spawning, false + * for vanilla collision detection or otherwise + * + * @deprecated non standard and unused feature. + */ + @Deprecated + public static boolean useExactLoginLocation() { + return server.useExactLoginLocation(); + } + + /** + * Shutdowns the server, stopping everything. + */ + public static void shutdown() { + server.shutdown(); + } + + /** + * Broadcasts the specified message to every user with the given + * permission name. + * + * @param message message to broadcast + * @param permission the required permission {@link Permissible + * permissibles} must have to receive the broadcast + * @return number of message recipients + */ + public static int broadcast(String message, String permission) { + return server.broadcast(message, permission); + } + + /** + * Gets the player by the given name, regardless if they are offline or + * online. + *

+ * This method may involve a blocking web request to get the UUID for the + * given name. + *

+ * This will return an object even if the player does not exist. To this + * method, all players will exist. + * + * @deprecated Persistent storage of users should be by UUID as names are no longer + * unique past a single session. + * @param name the name the player to retrieve + * @return an offline player + * @see #getOfflinePlayer(UUID) + */ + @Deprecated + public static OfflinePlayer getOfflinePlayer(String name) { + return server.getOfflinePlayer(name); + } + + /** + * Gets the player by the given UUID, regardless if they are offline or + * online. + *

+ * This will return an object even if the player does not exist. To this + * method, all players will exist. + * + * @param id the UUID of the player to retrieve + * @return an offline player + */ + public static OfflinePlayer getOfflinePlayer(UUID id) { + return server.getOfflinePlayer(id); + } + + /** + * Gets a set containing all current IPs that are banned. + * + * @return a set containing banned IP addresses + */ + public static Set getIPBans() { + return server.getIPBans(); + } + + /** + * Bans the specified address from the server. + * + * @param address the IP address to ban + */ + public static void banIP(String address) { + server.banIP(address); + } + + /** + * Unbans the specified address from the server. + * + * @param address the IP address to unban + */ + public static void unbanIP(String address) { + server.unbanIP(address); + } + + /** + * Gets a set containing all banned players. + * + * @return a set containing banned players + */ + public static Set getBannedPlayers() { + return server.getBannedPlayers(); + } + + /** + * Gets a ban list for the supplied type. + *

+ * Bans by name are no longer supported and this method will return + * null when trying to request them. The replacement is bans by UUID. + * + * @param type the type of list to fetch, cannot be null + * @return a ban list of the specified type + */ + public static BanList getBanList(BanList.Type type){ + return server.getBanList(type); + } + + /** + * Gets a set containing all player operators. + * + * @return a set containing player operators + */ + public static Set getOperators() { + return server.getOperators(); + } + + /** + * Gets the default {@link GameMode} for new players. + * + * @return the default game mode + */ + public static GameMode getDefaultGameMode() { + return server.getDefaultGameMode(); + } + + /** + * Sets the default {@link GameMode} for new players. + * + * @param mode the new game mode + */ + public static void setDefaultGameMode(GameMode mode) { + server.setDefaultGameMode(mode); + } + + /** + * Gets a {@link ConsoleCommandSender} that may be used as an input source + * for this server. + * + * @return a console command sender + */ + public static ConsoleCommandSender getConsoleSender() { + return server.getConsoleSender(); + } + + /** + * Gets the folder that contains all of the various {@link World}s. + * + * @return folder that contains all worlds + */ + public static File getWorldContainer() { + return server.getWorldContainer(); + } + + /** + * Gets every player that has ever played on this server. + * + * @return an array containing all previous players + */ + public static OfflinePlayer[] getOfflinePlayers() { + return server.getOfflinePlayers(); + } + + /** + * Gets the {@link Messenger} responsible for this server. + * + * @return messenger responsible for this server + */ + public static Messenger getMessenger() { + return server.getMessenger(); + } + + /** + * Gets the {@link HelpMap} providing help topics for this server. + * + * @return a help map for this server + */ + public static HelpMap getHelpMap() { + return server.getHelpMap(); + } + + /** + * Creates an empty inventory of the specified type. If the type is {@link + * InventoryType#CHEST}, the new inventory has a size of 27; otherwise the + * new inventory has the normal size for its type. + * + * @param owner the holder of the inventory, or null to indicate no holder + * @param type the type of inventory to create + * @return a new inventory + */ + public static Inventory createInventory(InventoryHolder owner, InventoryType type) { + return server.createInventory(owner, type); + } + + /** + * Creates an empty inventory with the specified type and title. If the type + * is {@link InventoryType#CHEST}, the new inventory has a size of 27; + * otherwise the new inventory has the normal size for its type.
+ * It should be noted that some inventory types do not support titles and + * may not render with said titles on the Minecraft client. + * + * @param owner The holder of the inventory; can be null if there's no holder. + * @param type The type of inventory to create. + * @param title The title of the inventory, to be displayed when it is viewed. + * @return The new inventory. + */ + public static Inventory createInventory(InventoryHolder owner, InventoryType type, String title) { + return server.createInventory(owner, type, title); + } + + /** + * Creates an empty inventory of type {@link InventoryType#CHEST} with the + * specified size. + * + * @param owner the holder of the inventory, or null to indicate no holder + * @param size a multiple of 9 as the size of inventory to create + * @return a new inventory + * @throws IllegalArgumentException if the size is not a multiple of 9 + */ + public static Inventory createInventory(InventoryHolder owner, int size) throws IllegalArgumentException { + return server.createInventory(owner, size); + } + + /** + * Creates an empty inventory of type {@link InventoryType#CHEST} with the + * specified size and title. + * + * @param owner the holder of the inventory, or null to indicate no holder + * @param size a multiple of 9 as the size of inventory to create + * @param title the title of the inventory, displayed when inventory is + * viewed + * @return a new inventory + * @throws IllegalArgumentException if the size is not a multiple of 9 + */ + public static Inventory createInventory(InventoryHolder owner, int size, String title) throws IllegalArgumentException { + return server.createInventory(owner, size, title); + } + + /** + * Gets user-specified limit for number of monsters that can spawn in a + * chunk. + * + * @return the monster spawn limit + */ + public static int getMonsterSpawnLimit() { + return server.getMonsterSpawnLimit(); + } + + /** + * Gets user-specified limit for number of animals that can spawn in a + * chunk. + * + * @return the animal spawn limit + */ + public static int getAnimalSpawnLimit() { + return server.getAnimalSpawnLimit(); + } + + /** + * Gets user-specified limit for number of water animals that can spawn in + * a chunk. + * + * @return the water animal spawn limit + */ + public static int getWaterAnimalSpawnLimit() { + return server.getWaterAnimalSpawnLimit(); + } + + /** + * Gets user-specified limit for number of ambient mobs that can spawn in + * a chunk. + * + * @return the ambient spawn limit + */ + public static int getAmbientSpawnLimit() { + return server.getAmbientSpawnLimit(); + } + + /** + * Checks the current thread against the expected primary thread for the + * server. + *

+ * Note: this method should not be used to indicate the current + * synchronized state of the runtime. A current thread matching the main + * thread indicates that it is synchronized, but a mismatch does not + * preclude the same assumption. + * + * @return true if the current thread matches the expected primary thread, + * false otherwise + */ + public static boolean isPrimaryThread() { + return server.isPrimaryThread(); + } + + /** + * Gets the message that is displayed on the server list. + * + * @return the servers MOTD + */ + public static String getMotd() { + return server.getMotd(); + } + + /** + * Gets the default message that is displayed when the server is stopped. + * + * @return the shutdown message + */ + public static String getShutdownMessage() { + return server.getShutdownMessage(); + } + + /** + * Gets the current warning state for the server. + * + * @return the configured warning state + */ + public static WarningState getWarningState() { + return server.getWarningState(); + } + + /** + * Gets the instance of the item factory (for {@link ItemMeta}). + * + * @return the item factory + * @see ItemFactory + */ + public static ItemFactory getItemFactory() { + return server.getItemFactory(); + } + + /** + * Gets the instance of the scoreboard manager. + *

+ * This will only exist after the first world has loaded. + * + * @return the scoreboard manager or null if no worlds are loaded. + */ + public static ScoreboardManager getScoreboardManager() { + return server.getScoreboardManager(); + } + + /** + * Gets an instance of the server's default server-icon. + * + * @return the default server-icon; null values may be used by the + * implementation to indicate no defined icon, but this behavior is + * not guaranteed + */ + public static CachedServerIcon getServerIcon() { + return server.getServerIcon(); + } + + /** + * Loads an image from a file, and returns a cached image for the specific + * server-icon. + *

+ * Size and type are implementation defined. An incompatible file is + * guaranteed to throw an implementation-defined {@link Exception}. + * + * @param file the file to load the from + * @throws IllegalArgumentException if image is null + * @throws Exception if the image does not meet current server server-icon + * specifications + * @return a cached server-icon that can be used for a {@link + * ServerListPingEvent#setServerIcon(CachedServerIcon)} + */ + public static CachedServerIcon loadServerIcon(File file) throws IllegalArgumentException, Exception { + return server.loadServerIcon(file); + } + + /** + * Creates a cached server-icon for the specific image. + *

+ * Size and type are implementation defined. An incompatible file is + * guaranteed to throw an implementation-defined {@link Exception}. + * + * @param image the image to use + * @throws IllegalArgumentException if image is null + * @throws Exception if the image does not meet current server + * server-icon specifications + * @return a cached server-icon that can be used for a {@link + * ServerListPingEvent#setServerIcon(CachedServerIcon)} + */ + public static CachedServerIcon loadServerIcon(BufferedImage image) throws IllegalArgumentException, Exception { + return server.loadServerIcon(image); + } + + /** + * Set the idle kick timeout. Any players idle for the specified amount of + * time will be automatically kicked. + *

+ * A value of 0 will disable the idle kick timeout. + * + * @param threshold the idle timeout in minutes + */ + public static void setIdleTimeout(int threshold) { + server.setIdleTimeout(threshold); + } + + /** + * Gets the idle kick timeout. + * + * @return the idle timeout in minutes + */ + public static int getIdleTimeout() { + return server.getIdleTimeout(); + } + + /** + * Create a ChunkData for use in a generator. + * + * See {@link ChunkGenerator#generateChunkData(World, java.util.Random, int, int, ChunkGenerator.BiomeGrid)} + * + * @param world the world to create the ChunkData for + * @return a new ChunkData for the world + * + */ + public static ChunkGenerator.ChunkData createChunkData(World world) { + return server.createChunkData(world); + } + + /** + * @see UnsafeValues + * @return the unsafe values instance + */ + @Deprecated + public static UnsafeValues getUnsafe() { + return server.getUnsafe(); + } + + // Paper start + /** + * Gets the active {@link CommandMap}. + * + * @return the active command map + */ + public static CommandMap getCommandMap() { + return server.getCommandMap(); + } + // Paper end + + public static Server.Spigot spigot() + { + return server.spigot(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/ChatColor.java b/azurite-api/src/main/java/org/bukkit/ChatColor.java new file mode 100644 index 0000000..baa8e79 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/ChatColor.java @@ -0,0 +1,370 @@ +package org.bukkit; + +import com.google.common.collect.Maps; +import org.apache.commons.lang.Validate; + +import java.util.Map; +import java.util.regex.Pattern; + +/** + * All supported color values for chat + */ +public enum ChatColor{ + /** + * Represents black + */ + BLACK('0', 0x00) { + @Override + public net.md_5.bungee.api.ChatColor asBungee() { + return net.md_5.bungee.api.ChatColor.BLACK; + } + }, + /** + * Represents dark blue + */ + DARK_BLUE('1', 0x1){ + @Override + public net.md_5.bungee.api.ChatColor asBungee() { + return net.md_5.bungee.api.ChatColor.DARK_BLUE; + } + }, + /** + * Represents dark green + */ + DARK_GREEN('2', 0x2){ + @Override + public net.md_5.bungee.api.ChatColor asBungee() { + return net.md_5.bungee.api.ChatColor.DARK_GREEN; + } + }, + /** + * Represents dark blue (aqua) + */ + DARK_AQUA('3', 0x3){ + @Override + public net.md_5.bungee.api.ChatColor asBungee() { + return net.md_5.bungee.api.ChatColor.DARK_AQUA; + } + }, + /** + * Represents dark red + */ + DARK_RED('4', 0x4){ + @Override + public net.md_5.bungee.api.ChatColor asBungee() { + return net.md_5.bungee.api.ChatColor.DARK_RED; + } + }, + /** + * Represents dark purple + */ + DARK_PURPLE('5', 0x5){ + @Override + public net.md_5.bungee.api.ChatColor asBungee() { + return net.md_5.bungee.api.ChatColor.DARK_PURPLE; + } + }, + /** + * Represents gold + */ + GOLD('6', 0x6){ + @Override + public net.md_5.bungee.api.ChatColor asBungee() { + return net.md_5.bungee.api.ChatColor.GOLD; + } + }, + /** + * Represents gray + */ + GRAY('7', 0x7){ + @Override + public net.md_5.bungee.api.ChatColor asBungee() { + return net.md_5.bungee.api.ChatColor.GRAY; + } + }, + /** + * Represents dark gray + */ + DARK_GRAY('8', 0x8){ + @Override + public net.md_5.bungee.api.ChatColor asBungee() { + return net.md_5.bungee.api.ChatColor.DARK_GRAY; + } + }, + /** + * Represents blue + */ + BLUE('9', 0x9){ + @Override + public net.md_5.bungee.api.ChatColor asBungee() { + return net.md_5.bungee.api.ChatColor.BLUE; + } + }, + /** + * Represents green + */ + GREEN('a', 0xA){ + @Override + public net.md_5.bungee.api.ChatColor asBungee() { + return net.md_5.bungee.api.ChatColor.GREEN; + } + }, + /** + * Represents aqua + */ + AQUA('b', 0xB){ + @Override + public net.md_5.bungee.api.ChatColor asBungee() { + return net.md_5.bungee.api.ChatColor.AQUA; + } + }, + /** + * Represents red + */ + RED('c', 0xC){ + @Override + public net.md_5.bungee.api.ChatColor asBungee() { + return net.md_5.bungee.api.ChatColor.RED; + } + }, + /** + * Represents light purple + */ + LIGHT_PURPLE('d', 0xD){ + @Override + public net.md_5.bungee.api.ChatColor asBungee() { + return net.md_5.bungee.api.ChatColor.LIGHT_PURPLE; + } + }, + /** + * Represents yellow + */ + YELLOW('e', 0xE){ + @Override + public net.md_5.bungee.api.ChatColor asBungee() { + return net.md_5.bungee.api.ChatColor.YELLOW; + } + }, + /** + * Represents white + */ + WHITE('f', 0xF){ + @Override + public net.md_5.bungee.api.ChatColor asBungee() { + return net.md_5.bungee.api.ChatColor.WHITE; + } + }, + /** + * Represents magical characters that change around randomly + */ + MAGIC('k', 0x10, true){ + @Override + public net.md_5.bungee.api.ChatColor asBungee() { + return net.md_5.bungee.api.ChatColor.MAGIC; + } + }, + /** + * Makes the text bold. + */ + BOLD('l', 0x11, true){ + @Override + public net.md_5.bungee.api.ChatColor asBungee() { + return net.md_5.bungee.api.ChatColor.BOLD; + } + }, + /** + * Makes a line appear through the text. + */ + STRIKETHROUGH('m', 0x12, true){ + @Override + public net.md_5.bungee.api.ChatColor asBungee() { + return net.md_5.bungee.api.ChatColor.STRIKETHROUGH; + } + }, + /** + * Makes the text appear underlined. + */ + UNDERLINE('n', 0x13, true){ + @Override + public net.md_5.bungee.api.ChatColor asBungee() { + return net.md_5.bungee.api.ChatColor.UNDERLINE; + } + }, + /** + * Makes the text italic. + */ + ITALIC('o', 0x14, true){ + @Override + public net.md_5.bungee.api.ChatColor asBungee() { + return net.md_5.bungee.api.ChatColor.ITALIC; + } + }, + /** + * Resets all previous chat colors or formats. + */ + RESET('r', 0x15){ + @Override + public net.md_5.bungee.api.ChatColor asBungee() { + return net.md_5.bungee.api.ChatColor.RESET; + } + }; + + /** + * The special character which prefixes all chat colour codes. Use this if + * you need to dynamically convert colour codes from your custom format. + */ + public static final char COLOR_CHAR = '\u00A7'; + private static final Pattern STRIP_COLOR_PATTERN = Pattern.compile("(?i)" + String.valueOf(COLOR_CHAR) + "[0-9A-FK-OR]"); + + private final int intCode; + private final char code; + private final boolean isFormat; + private final String toString; + private final static Map BY_ID = Maps.newHashMap(); + private final static Map BY_CHAR = Maps.newHashMap(); + + ChatColor(char code, int intCode) { + this(code, intCode, false); + } + + ChatColor(char code, int intCode, boolean isFormat) { + this.code = code; + this.intCode = intCode; + this.isFormat = isFormat; + this.toString = new String(new char[] {COLOR_CHAR, code}); + } + + public net.md_5.bungee.api.ChatColor asBungee() { + return net.md_5.bungee.api.ChatColor.RESET; + } + + /** + * Gets the char value associated with this color + * + * @return A char value of this color code + */ + public char getChar() { + return code; + } + + @Override + public String toString() { + return toString; + } + + /** + * Checks if this code is a format code as opposed to a color code. + * + * @return whether this ChatColor is a format code + */ + public boolean isFormat() { + return isFormat; + } + + /** + * Checks if this code is a color code as opposed to a format code. + * + * @return whether this ChatColor is a color code + */ + public boolean isColor() { + return !isFormat && this != RESET; + } + + /** + * Gets the color represented by the specified color code + * + * @param code Code to check + * @return Associative {@link ChatColor} with the given code, + * or null if it doesn't exist + */ + public static ChatColor getByChar(char code) { + return BY_CHAR.get(code); + } + + /** + * Gets the color represented by the specified color code + * + * @param code Code to check + * @return Associative {@link ChatColor} with the given code, + * or null if it doesn't exist + */ + public static ChatColor getByChar(String code) { + Validate.notNull(code, "Code cannot be null"); + Validate.isTrue(code.length() > 0, "Code must have at least one char"); + + return BY_CHAR.get(code.charAt(0)); + } + + /** + * Strips the given message of all color codes + * + * @param input String to strip of color + * @return A copy of the input string, without any coloring + */ + public static String stripColor(final String input) { + if (input == null) { + return null; + } + + return STRIP_COLOR_PATTERN.matcher(input).replaceAll(""); + } + + /** + * Translates a string using an alternate color code character into a + * string that uses the internal ChatColor.COLOR_CODE color code + * character. The alternate color code character will only be replaced if + * it is immediately followed by 0-9, A-F, a-f, K-O, k-o, R or r. + * + * @param altColorChar The alternate color code character to replace. Ex: {@literal &} + * @param textToTranslate Text containing the alternate color code character. + * @return Text containing the ChatColor.COLOR_CODE color code character. + */ + public static String translateAlternateColorCodes(char altColorChar, String textToTranslate) { + char[] b = textToTranslate.toCharArray(); + for (int i = 0; i < b.length - 1; i++) { + if (b[i] == altColorChar && "0123456789AaBbCcDdEeFfKkLlMmNnOoRr".indexOf(b[i+1]) > -1) { + b[i] = ChatColor.COLOR_CHAR; + b[i+1] = Character.toLowerCase(b[i+1]); + } + } + return new String(b); + } + + /** + * Gets the ChatColors used at the end of the given input string. + * + * @param input Input string to retrieve the colors from. + * @return Any remaining ChatColors to pass onto the next line. + */ + public static String getLastColors(String input) { + String result = ""; + int length = input.length(); + + // Search backwards from the end as it is faster + for (int index = length - 1; index > -1; index--) { + char section = input.charAt(index); + if (section == COLOR_CHAR && index < length - 1) { + char c = input.charAt(index + 1); + ChatColor color = getByChar(c); + + if (color != null) { + result = color.toString() + result; + + // Once we find a color or reset we can stop searching + if (color.isColor() || color.equals(RESET)) { + break; + } + } + } + } + + return result; + } + + static { + for (ChatColor color : values()) { + BY_ID.put(color.intCode, color); + BY_CHAR.put(color.code, color); + } + } +} diff --git a/azurite-api/src/main/java/org/bukkit/Chunk.java b/azurite-api/src/main/java/org/bukkit/Chunk.java new file mode 100644 index 0000000..de19ec4 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/Chunk.java @@ -0,0 +1,130 @@ +package org.bukkit; + +import org.bukkit.block.Block; +import org.bukkit.block.BlockState; +import org.bukkit.entity.Entity; + +/** + * Represents a chunk of blocks + */ +public interface Chunk { + + /** + * Gets the X-coordinate of this chunk + * + * @return X-coordinate + */ + int getX(); + + /** + * Gets the Z-coordinate of this chunk + * + * @return Z-coordinate + */ + int getZ(); + + int getEntityCount(); + + /** + * Gets the world containing this chunk + * + * @return Parent World + */ + World getWorld(); + + /** + * Gets a block from this chunk + * + * @param x 0-15 + * @param y 0-127 + * @param z 0-15 + * @return the Block + */ + Block getBlock(int x, int y, int z); + + /** + * Capture thread-safe read-only snapshot of chunk data + * + * @return ChunkSnapshot + */ + ChunkSnapshot getChunkSnapshot(); + + /** + * Capture thread-safe read-only snapshot of chunk data + * + * @param includeMaxblocky - if true, snapshot includes per-coordinate + * maximum Y values + * @param includeBiome - if true, snapshot includes per-coordinate biome + * type + * @param includeBiomeTempRain - if true, snapshot includes per-coordinate + * raw biome temperature and rainfall + * @return ChunkSnapshot + */ + ChunkSnapshot getChunkSnapshot(boolean includeMaxblocky, boolean includeBiome, boolean includeBiomeTempRain); + + /** + * Get a list of all entities in the chunk. + * + * @return The entities. + */ + Entity[] getEntities(); + + /** + * Get a list of all tile entities in the chunk. + * + * @return The tile entities. + */ + BlockState[] getTileEntities(); + + /** + * Checks if the chunk is loaded. + * + * @return True if it is loaded. + */ + boolean isLoaded(); + + /** + * Loads the chunk. + * + * @param generate Whether or not to generate a chunk if it doesn't + * already exist + * @return true if the chunk has loaded successfully, otherwise false + */ + boolean load(boolean generate); + + /** + * Loads the chunk. + * + * @return true if the chunk has loaded successfully, otherwise false + */ + boolean load(); + + /** + * Unloads and optionally saves the Chunk + * + * @param save Controls whether the chunk is saved + * @param safe Controls whether to unload the chunk when players are + * nearby + * @return true if the chunk has unloaded successfully, otherwise false + */ + boolean unload(boolean save, boolean safe); + + /** + * Unloads and optionally saves the Chunk + * + * @param save Controls whether the chunk is saved + * @return true if the chunk has unloaded successfully, otherwise false + */ + boolean unload(boolean save); + + /** + * Unloads and optionally saves the Chunk + * + * @return true if the chunk has unloaded successfully, otherwise false + */ + boolean unload(); + + dev.azurite.spigot.api.chunk.ChunkSnapshot takeSnapshot(); + + void restoreSnapshot(dev.azurite.spigot.api.chunk.ChunkSnapshot snapshot); +} diff --git a/azurite-api/src/main/java/org/bukkit/ChunkSnapshot.java b/azurite-api/src/main/java/org/bukkit/ChunkSnapshot.java new file mode 100644 index 0000000..83fccc8 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/ChunkSnapshot.java @@ -0,0 +1,129 @@ +package org.bukkit; + +import org.bukkit.block.Biome; + +/** + * Represents a static, thread-safe snapshot of chunk of blocks. + *

+ * Purpose is to allow clean, efficient copy of a chunk data to be made, and + * then handed off for processing in another thread (e.g. map rendering) + */ +public interface ChunkSnapshot { + + /** + * Gets the X-coordinate of this chunk + * + * @return X-coordinate + */ + int getX(); + + /** + * Gets the Z-coordinate of this chunk + * + * @return Z-coordinate + */ + int getZ(); + + /** + * Gets name of the world containing this chunk + * + * @return Parent World Name + */ + String getWorldName(); + + /** + * Get block type for block at corresponding coordinate in the chunk + * + * @param x 0-15 + * @param y 0-127 + * @param z 0-15 + * @return 0-255 + * @deprecated Magic value + */ + @Deprecated + int getBlockTypeId(int x, int y, int z); + + /** + * Get block data for block at corresponding coordinate in the chunk + * + * @param x 0-15 + * @param y 0-127 + * @param z 0-15 + * @return 0-15 + * @deprecated Magic value + */ + @Deprecated + int getBlockData(int x, int y, int z); + + /** + * Get sky light level for block at corresponding coordinate in the chunk + * + * @param x 0-15 + * @param y 0-127 + * @param z 0-15 + * @return 0-15 + */ + int getBlockSkyLight(int x, int y, int z); + + /** + * Get light level emitted by block at corresponding coordinate in the + * chunk + * + * @param x 0-15 + * @param y 0-127 + * @param z 0-15 + * @return 0-15 + */ + int getBlockEmittedLight(int x, int y, int z); + + /** + * Gets the highest non-air coordinate at the given coordinates + * + * @param x X-coordinate of the blocks + * @param z Z-coordinate of the blocks + * @return Y-coordinate of the highest non-air block + */ + int getHighestBlockYAt(int x, int z); + + /** + * Get biome at given coordinates + * + * @param x X-coordinate + * @param z Z-coordinate + * @return Biome at given coordinate + */ + Biome getBiome(int x, int z); + + /** + * Get raw biome temperature (0.0-1.0) at given coordinate + * + * @param x X-coordinate + * @param z Z-coordinate + * @return temperature at given coordinate + */ + double getRawBiomeTemperature(int x, int z); + + /** + * Get raw biome rainfall (0.0-1.0) at given coordinate + * + * @param x X-coordinate + * @param z Z-coordinate + * @return rainfall at given coordinate + */ + double getRawBiomeRainfall(int x, int z); + + /** + * Get world full time when chunk snapshot was captured + * + * @return time in ticks + */ + long getCaptureFullTime(); + + /** + * Test if section is empty + * + * @param sy - section Y coordinate (block Y / 16) + * @return true if empty, false if not + */ + boolean isSectionEmpty(int sy); +} diff --git a/azurite-api/src/main/java/org/bukkit/CoalType.java b/azurite-api/src/main/java/org/bukkit/CoalType.java new file mode 100644 index 0000000..a518594 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/CoalType.java @@ -0,0 +1,50 @@ +package org.bukkit; + +import com.google.common.collect.Maps; + +import java.util.Map; + +/** + * Represents the two types of coal + */ +public enum CoalType { + COAL(0x0), + CHARCOAL(0x1); + + private final byte data; + private final static Map BY_DATA = Maps.newHashMap(); + + CoalType(final int data) { + this.data = (byte) data; + } + + /** + * Gets the associated data value representing this type of coal + * + * @return A byte containing the data value of this coal type + * @deprecated Magic value + */ + @Deprecated + public byte getData() { + return data; + } + + /** + * Gets the type of coal with the given data value + * + * @param data Data value to fetch + * @return The {@link CoalType} representing the given value, or null if + * it doesn't exist + * @deprecated Magic value + */ + @Deprecated + public static CoalType getByData(final byte data) { + return BY_DATA.get(data); + } + + static { + for (CoalType type : values()) { + BY_DATA.put(type.data, type); + } + } +} diff --git a/azurite-api/src/main/java/org/bukkit/Color.java b/azurite-api/src/main/java/org/bukkit/Color.java new file mode 100644 index 0000000..6167f39 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/Color.java @@ -0,0 +1,343 @@ +package org.bukkit; + +import com.google.common.collect.ImmutableMap; +import org.apache.commons.lang.Validate; +import org.bukkit.configuration.serialization.ConfigurationSerializable; +import org.bukkit.configuration.serialization.SerializableAs; + +import java.util.Map; + +/** + * A container for a color palette. This class is immutable; the set methods + * return a new color. The color names listed as fields are HTML4 standards, + * but subject to change. + */ +@SerializableAs("Color") +public final class Color implements ConfigurationSerializable { + private static final int BIT_MASK = 0xff; + + /** + * White, or (0xFF,0xFF,0xFF) in (R,G,B) + */ + public static final Color WHITE = fromRGB(0xFFFFFF); + + /** + * Silver, or (0xC0,0xC0,0xC0) in (R,G,B) + */ + public static final Color SILVER = fromRGB(0xC0C0C0); + + /** + * Gray, or (0x80,0x80,0x80) in (R,G,B) + */ + public static final Color GRAY = fromRGB(0x808080); + + /** + * Black, or (0x00,0x00,0x00) in (R,G,B) + */ + public static final Color BLACK = fromRGB(0x000000); + + /** + * Red, or (0xFF,0x00,0x00) in (R,G,B) + */ + public static final Color RED = fromRGB(0xFF0000); + + /** + * Maroon, or (0x80,0x00,0x00) in (R,G,B) + */ + public static final Color MAROON = fromRGB(0x800000); + + /** + * Yellow, or (0xFF,0xFF,0x00) in (R,G,B) + */ + public static final Color YELLOW = fromRGB(0xFFFF00); + + /** + * Olive, or (0x80,0x80,0x00) in (R,G,B) + */ + public static final Color OLIVE = fromRGB(0x808000); + + /** + * Lime, or (0x00,0xFF,0x00) in (R,G,B) + */ + public static final Color LIME = fromRGB(0x00FF00); + + /** + * Green, or (0x00,0x80,0x00) in (R,G,B) + */ + public static final Color GREEN = fromRGB(0x008000); + + /** + * Aqua, or (0x00,0xFF,0xFF) in (R,G,B) + */ + public static final Color AQUA = fromRGB(0x00FFFF); + + /** + * Teal, or (0x00,0x80,0x80) in (R,G,B) + */ + public static final Color TEAL = fromRGB(0x008080); + + /** + * Blue, or (0x00,0x00,0xFF) in (R,G,B) + */ + public static final Color BLUE = fromRGB(0x0000FF); + + /** + * Navy, or (0x00,0x00,0x80) in (R,G,B) + */ + public static final Color NAVY = fromRGB(0x000080); + + /** + * Fuchsia, or (0xFF,0x00,0xFF) in (R,G,B) + */ + public static final Color FUCHSIA = fromRGB(0xFF00FF); + + /** + * Purple, or (0x80,0x00,0x80) in (R,G,B) + */ + public static final Color PURPLE = fromRGB(0x800080); + + /** + * Orange, or (0xFF,0xA5,0x00) in (R,G,B) + */ + public static final Color ORANGE = fromRGB(0xFFA500); + + private final byte red; + private final byte green; + private final byte blue; + + /** + * Creates a new Color object from a red, green, and blue + * + * @param red integer from 0-255 + * @param green integer from 0-255 + * @param blue integer from 0-255 + * @return a new Color object for the red, green, blue + * @throws IllegalArgumentException if any value is strictly {@literal >255 or <0} + */ + public static Color fromRGB(int red, int green, int blue) throws IllegalArgumentException { + return new Color(red, green, blue); + } + + /** + * Creates a new Color object from a blue, green, and red + * + * @param blue integer from 0-255 + * @param green integer from 0-255 + * @param red integer from 0-255 + * @return a new Color object for the red, green, blue + * @throws IllegalArgumentException if any value is strictly {@literal >255 or <0} + */ + public static Color fromBGR(int blue, int green, int red) throws IllegalArgumentException { + return new Color(red, green, blue); + } + + /** + * Creates a new color object from an integer that contains the red, + * green, and blue bytes in the lowest order 24 bits. + * + * @param rgb the integer storing the red, green, and blue values + * @return a new color object for specified values + * @throws IllegalArgumentException if any data is in the highest order 8 + * bits + */ + public static Color fromRGB(int rgb) throws IllegalArgumentException { + Validate.isTrue((rgb >> 24) == 0, "Extrenuous data in: ", rgb); + return fromRGB(rgb >> 16 & BIT_MASK, rgb >> 8 & BIT_MASK, rgb >> 0 & BIT_MASK); + } + + /** + * Creates a new color object from an integer that contains the blue, + * green, and red bytes in the lowest order 24 bits. + * + * @param bgr the integer storing the blue, green, and red values + * @return a new color object for specified values + * @throws IllegalArgumentException if any data is in the highest order 8 + * bits + */ + public static Color fromBGR(int bgr) throws IllegalArgumentException { + Validate.isTrue((bgr >> 24) == 0, "Extrenuous data in: ", bgr); + return fromBGR(bgr >> 16 & BIT_MASK, bgr >> 8 & BIT_MASK, bgr >> 0 & BIT_MASK); + } + + private Color(int red, int green, int blue) { + Validate.isTrue(red >= 0 && red <= BIT_MASK, "Red is not between 0-255: ", red); + Validate.isTrue(green >= 0 && green <= BIT_MASK, "Green is not between 0-255: ", green); + Validate.isTrue(blue >= 0 && blue <= BIT_MASK, "Blue is not between 0-255: ", blue); + + this.red = (byte) red; + this.green = (byte) green; + this.blue = (byte) blue; + } + + /** + * Gets the red component + * + * @return red component, from 0 to 255 + */ + public int getRed() { + return BIT_MASK & red; + } + + /** + * Creates a new Color object with specified component + * + * @param red the red component, from 0 to 255 + * @return a new color object with the red component + */ + public Color setRed(int red) { + return fromRGB(red, getGreen(), getBlue()); + } + + /** + * Gets the green component + * + * @return green component, from 0 to 255 + */ + public int getGreen() { + return BIT_MASK & green; + } + + /** + * Creates a new Color object with specified component + * + * @param green the red component, from 0 to 255 + * @return a new color object with the red component + */ + public Color setGreen(int green) { + return fromRGB(getRed(), green, getBlue()); + } + + /** + * Gets the blue component + * + * @return blue component, from 0 to 255 + */ + public int getBlue() { + return BIT_MASK & blue; + } + + /** + * Creates a new Color object with specified component + * + * @param blue the red component, from 0 to 255 + * @return a new color object with the red component + */ + public Color setBlue(int blue) { + return fromRGB(getRed(), getGreen(), blue); + } + + /** + * + * @return An integer representation of this color, as 0xRRGGBB + */ + public int asRGB() { + return getRed() << 16 | getGreen() << 8 | getBlue() << 0; + } + + /** + * + * @return An integer representation of this color, as 0xBBGGRR + */ + public int asBGR() { + return getBlue() << 16 | getGreen() << 8 | getRed() << 0; + } + + /** + * Creates a new color with its RGB components changed as if it was dyed + * with the colors passed in, replicating vanilla workbench dyeing + * + * @param colors The DyeColors to dye with + * @return A new color with the changed rgb components + */ + // TODO: Javadoc what this method does, not what it mimics. API != Implementation + public Color mixDyes(DyeColor... colors) { + Validate.noNullElements(colors, "Colors cannot be null"); + + Color[] toPass = new Color[colors.length]; + for (int i = 0; i < colors.length; i++) { + toPass[i] = colors[i].getColor(); + } + + return mixColors(toPass); + } + + /** + * Creates a new color with its RGB components changed as if it was dyed + * with the colors passed in, replicating vanilla workbench dyeing + * + * @param colors The colors to dye with + * @return A new color with the changed rgb components + */ + // TODO: Javadoc what this method does, not what it mimics. API != Implementation + public Color mixColors(Color... colors) { + Validate.noNullElements(colors, "Colors cannot be null"); + + int totalRed = this.getRed(); + int totalGreen = this.getGreen(); + int totalBlue = this.getBlue(); + int totalMax = Math.max(Math.max(totalRed, totalGreen), totalBlue); + for (Color color : colors) { + totalRed += color.getRed(); + totalGreen += color.getGreen(); + totalBlue += color.getBlue(); + totalMax += Math.max(Math.max(color.getRed(), color.getGreen()), color.getBlue()); + } + + float averageRed = totalRed / (colors.length + 1); + float averageGreen = totalGreen / (colors.length + 1); + float averageBlue = totalBlue / (colors.length + 1); + float averageMax = totalMax / (colors.length + 1); + + float maximumOfAverages = Math.max(Math.max(averageRed, averageGreen), averageBlue); + float gainFactor = averageMax / maximumOfAverages; + + return Color.fromRGB((int) (averageRed * gainFactor), (int) (averageGreen * gainFactor), (int) (averageBlue * gainFactor)); + } + + @Override + public boolean equals(Object o) { + if (!(o instanceof Color)) { + return false; + } + final Color that = (Color) o; + return this.blue == that.blue && this.green == that.green && this.red == that.red; + } + + @Override + public int hashCode() { + return asRGB() ^ Color.class.hashCode(); + } + + public Map serialize() { + return ImmutableMap.of( + "RED", getRed(), + "BLUE", getBlue(), + "GREEN", getGreen() + ); + } + + @SuppressWarnings("javadoc") + public static Color deserialize(Map map) { + return fromRGB( + asInt("RED", map), + asInt("GREEN", map), + asInt("BLUE", map) + ); + } + + private static int asInt(String string, Map map) { + Object value = map.get(string); + if (value == null) { + throw new IllegalArgumentException(string + " not in map " + map); + } + if (!(value instanceof Number)) { + throw new IllegalArgumentException(string + '(' + value + ") is not a number"); + } + return ((Number) value).intValue(); + } + + @Override + public String toString() { + return "Color:[rgb0x" + Integer.toHexString(getRed()).toUpperCase() + Integer.toHexString(getGreen()).toUpperCase() + Integer.toHexString(getBlue()).toUpperCase() + "]"; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/CropState.java b/azurite-api/src/main/java/org/bukkit/CropState.java new file mode 100644 index 0000000..1c07933 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/CropState.java @@ -0,0 +1,81 @@ +package org.bukkit; + +import com.google.common.collect.Maps; + +import java.util.Map; + +/** + * Represents the different growth states of crops + */ +public enum CropState { + + /** + * State when first seeded + */ + SEEDED(0x0), + /** + * First growth stage + */ + GERMINATED(0x1), + /** + * Second growth stage + */ + VERY_SMALL(0x2), + /** + * Third growth stage + */ + SMALL(0x3), + /** + * Fourth growth stage + */ + MEDIUM(0x4), + /** + * Fifth growth stage + */ + TALL(0x5), + /** + * Almost ripe stage + */ + VERY_TALL(0x6), + /** + * Ripe stage + */ + RIPE(0x7); + + private final byte data; + private final static Map BY_DATA = Maps.newHashMap(); + + CropState(final int data) { + this.data = (byte) data; + } + + /** + * Gets the associated data value representing this growth state + * + * @return A byte containing the data value of this growth state + * @deprecated Magic value + */ + @Deprecated + public byte getData() { + return data; + } + + /** + * Gets the CropState with the given data value + * + * @param data Data value to fetch + * @return The {@link CropState} representing the given value, or null if + * it doesn't exist + * @deprecated Magic value + */ + @Deprecated + public static CropState getByData(final byte data) { + return BY_DATA.get(data); + } + + static { + for (CropState cropState : values()) { + BY_DATA.put(cropState.getData(), cropState); + } + } +} diff --git a/azurite-api/src/main/java/org/bukkit/Difficulty.java b/azurite-api/src/main/java/org/bukkit/Difficulty.java new file mode 100644 index 0000000..760deca --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/Difficulty.java @@ -0,0 +1,72 @@ +package org.bukkit; + +import com.google.common.collect.Maps; + +import java.util.Map; + +/** + * Represents the various difficulty levels that are available. + */ +public enum Difficulty { + /** + * Players regain health over time, hostile mobs don't spawn, the hunger + * bar does not deplete. + */ + PEACEFUL(0), + + /** + * Hostile mobs spawn, enemies deal less damage than on normal difficulty, + * the hunger bar does deplete and starving deals up to 5 hearts of + * damage. (Default value) + */ + EASY(1), + + /** + * Hostile mobs spawn, enemies deal normal amounts of damage, the hunger + * bar does deplete and starving deals up to 9.5 hearts of damage. + */ + NORMAL(2), + + /** + * Hostile mobs spawn, enemies deal greater damage than on normal + * difficulty, the hunger bar does deplete and starving can kill players. + */ + HARD(3); + + private final int value; + private final static Map BY_ID = Maps.newHashMap(); + + Difficulty(final int value) { + this.value = value; + } + + /** + * Gets the difficulty value associated with this Difficulty. + * + * @return An integer value of this difficulty + * @deprecated Magic value + */ + @Deprecated + public int getValue() { + return value; + } + + /** + * Gets the Difficulty represented by the specified value + * + * @param value Value to check + * @return Associative {@link Difficulty} with the given value, or null if + * it doesn't exist + * @deprecated Magic value + */ + @Deprecated + public static Difficulty getByValue(final int value) { + return BY_ID.get(value); + } + + static { + for (Difficulty diff : values()) { + BY_ID.put(diff.value, diff); + } + } +} diff --git a/azurite-api/src/main/java/org/bukkit/DyeColor.java b/azurite-api/src/main/java/org/bukkit/DyeColor.java new file mode 100644 index 0000000..be6b9fe --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/DyeColor.java @@ -0,0 +1,239 @@ +package org.bukkit; + +import com.google.common.collect.ImmutableMap; + +import java.util.Map; + +/** + * All supported color values for dyes and cloth + */ +public enum DyeColor { + + /** + * Represents white dye. + */ + WHITE(0x0, 0xF, Color.WHITE, Color.fromRGB(0xF0F0F0)), + /** + * Represents orange dye. + */ + ORANGE(0x1, 0xE, Color.fromRGB(0xD87F33), Color.fromRGB(0xEB8844)), + /** + * Represents magenta dye. + */ + MAGENTA(0x2, 0xD, Color.fromRGB(0xB24CD8), Color.fromRGB(0xC354CD)), + /** + * Represents light blue dye. + */ + LIGHT_BLUE(0x3, 0xC, Color.fromRGB(0x6699D8), Color.fromRGB(0x6689D3)), + /** + * Represents yellow dye. + */ + YELLOW(0x4, 0xB, Color.fromRGB(0xE5E533), Color.fromRGB(0xDECF2A)), + /** + * Represents lime dye. + */ + LIME(0x5, 0xA, Color.fromRGB(0x7FCC19), Color.fromRGB(0x41CD34)), + /** + * Represents pink dye. + */ + PINK(0x6, 0x9, Color.fromRGB(0xF27FA5), Color.fromRGB(0xD88198)), + /** + * Represents gray dye. + */ + GRAY(0x7, 0x8, Color.fromRGB(0x4C4C4C), Color.fromRGB(0x434343)), + /** + * Represents silver dye. + */ + SILVER(0x8, 0x7, Color.fromRGB(0x999999), Color.fromRGB(0xABABAB)), + /** + * Represents cyan dye. + */ + CYAN(0x9, 0x6, Color.fromRGB(0x4C7F99), Color.fromRGB(0x287697)), + /** + * Represents purple dye. + */ + PURPLE(0xA, 0x5, Color.fromRGB(0x7F3FB2), Color.fromRGB(0x7B2FBE)), + /** + * Represents blue dye. + */ + BLUE(0xB, 0x4, Color.fromRGB(0x334CB2), Color.fromRGB(0x253192)), + /** + * Represents brown dye. + */ + BROWN(0xC, 0x3, Color.fromRGB(0x664C33), Color.fromRGB(0x51301A)), + /** + * Represents green dye. + */ + GREEN(0xD, 0x2, Color.fromRGB(0x667F33), Color.fromRGB(0x3B511A)), + /** + * Represents red dye. + */ + RED(0xE, 0x1, Color.fromRGB(0x993333), Color.fromRGB(0xB3312C)), + /** + * Represents black dye. + */ + BLACK(0xF, 0x0, Color.fromRGB(0x191919), Color.fromRGB(0x1E1B1B)); + + private final byte woolData; + private final byte dyeData; + private final Color color; + private final Color firework; + private final static DyeColor[] BY_WOOL_DATA; + private final static DyeColor[] BY_DYE_DATA; + private final static Map BY_COLOR; + private final static Map BY_FIREWORK; + + DyeColor(final int woolData, final int dyeData, Color color, Color firework) { + this.woolData = (byte) woolData; + this.dyeData = (byte) dyeData; + this.color = color; + this.firework = firework; + } + + /** + * Gets the associated (wool) data value representing this color. + * + * @return A byte containing the (wool) data value of this color + * @deprecated The name is misleading. It would imply {@link + * Material#INK_SACK} but uses {@link Material#WOOL} + * @see #getWoolData() + * @see #getDyeData() + */ + @Deprecated + public byte getData() { + return getWoolData(); + } + + /** + * Gets the associated wool data value representing this color. + * + * @return A byte containing the wool data value of this color + * @see #getDyeData() + * @deprecated Magic value + */ + @Deprecated + public byte getWoolData() { + return woolData; + } + + /** + * Gets the associated dye data value representing this color. + * + * @return A byte containing the dye data value of this color + * @see #getWoolData() + * @deprecated Magic value + */ + @Deprecated + public byte getDyeData() { + return dyeData; + } + + /** + * Gets the color that this dye represents. + * + * @return The {@link Color} that this dye represents + */ + public Color getColor() { + return color; + } + + /** + * Gets the firework color that this dye represents. + * + * @return The {@link Color} that this dye represents + */ + public Color getFireworkColor() { + return firework; + } + + /** + * Gets the DyeColor with the given (wool) data value. + * + * @param data (wool) data value to fetch + * @return The {@link DyeColor} representing the given value, or null if + * it doesn't exist + * @deprecated The name is misleading. It would imply {@link + * Material#INK_SACK} but uses {@link Material#WOOL} + * @see #getByDyeData(byte) + * @see #getByWoolData(byte) + */ + @Deprecated + public static DyeColor getByData(final byte data) { + return getByWoolData(data); + } + + /** + * Gets the DyeColor with the given wool data value. + * + * @param data Wool data value to fetch + * @return The {@link DyeColor} representing the given value, or null if + * it doesn't exist + * @see #getByDyeData(byte) + * @deprecated Magic value + */ + @Deprecated + public static DyeColor getByWoolData(final byte data) { + int i = 0xff & data; + if (i >= BY_WOOL_DATA.length) { + return null; + } + return BY_WOOL_DATA[i]; + } + + /** + * Gets the DyeColor with the given dye data value. + * + * @param data Dye data value to fetch + * @return The {@link DyeColor} representing the given value, or null if + * it doesn't exist + * @see #getByWoolData(byte) + * @deprecated Magic value + */ + @Deprecated + public static DyeColor getByDyeData(final byte data) { + int i = 0xff & data; + if (i >= BY_DYE_DATA.length) { + return null; + } + return BY_DYE_DATA[i]; + } + + /** + * Gets the DyeColor with the given color value. + * + * @param color Color value to get the dye by + * @return The {@link DyeColor} representing the given value, or null if + * it doesn't exist + */ + public static DyeColor getByColor(final Color color) { + return BY_COLOR.get(color); + } + + /** + * Gets the DyeColor with the given firework color value. + * + * @param color Color value to get dye by + * @return The {@link DyeColor} representing the given value, or null if + * it doesn't exist + */ + public static DyeColor getByFireworkColor(final Color color) { + return BY_FIREWORK.get(color); + } + + static { + BY_WOOL_DATA = values(); + BY_DYE_DATA = values(); + ImmutableMap.Builder byColor = ImmutableMap.builder(); + ImmutableMap.Builder byFirework = ImmutableMap.builder(); + + for (DyeColor color : values()) { + BY_WOOL_DATA[color.woolData & 0xff] = color; + BY_DYE_DATA[color.dyeData & 0xff] = color; + byColor.put(color.getColor(), color); + byFirework.put(color.getFireworkColor(), color); + } + + BY_COLOR = byColor.build(); + BY_FIREWORK = byFirework.build(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/Effect.java b/azurite-api/src/main/java/org/bukkit/Effect.java new file mode 100644 index 0000000..d8b5329 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/Effect.java @@ -0,0 +1,336 @@ +package org.bukkit; + +import com.google.common.collect.Maps; +import org.bukkit.block.BlockFace; +import org.bukkit.material.MaterialData; +import org.bukkit.potion.Potion; + +import java.util.Map; + +/** + * A list of effects that the server is able to send to players. + */ +public enum Effect { + /** + * An alternate click sound. + */ + CLICK2(1000, Type.SOUND), + /** + * A click sound. + */ + CLICK1(1001, Type.SOUND), + /** + * Sound of a bow firing. + */ + BOW_FIRE(1002, Type.SOUND), + /** + * Sound of a door opening/closing. + */ + DOOR_TOGGLE(1003, Type.SOUND), + /** + * Sound of fire being extinguished. + */ + EXTINGUISH(1004, Type.SOUND), + /** + * A song from a record. Needs the record item ID as additional info + */ + RECORD_PLAY(1005, Type.SOUND, Material.class), + /** + * Sound of ghast shrieking. + */ + GHAST_SHRIEK(1007, Type.SOUND), + /** + * Sound of ghast firing. + */ + GHAST_SHOOT(1008, Type.SOUND), + /** + * Sound of blaze firing. + */ + BLAZE_SHOOT(1009, Type.SOUND), + /** + * Sound of zombies chewing on wooden doors. + */ + ZOMBIE_CHEW_WOODEN_DOOR(1010, Type.SOUND), + /** + * Sound of zombies chewing on iron doors. + */ + ZOMBIE_CHEW_IRON_DOOR(1011, Type.SOUND), + /** + * Sound of zombies destroying a door. + */ + ZOMBIE_DESTROY_DOOR(1012, Type.SOUND), + /** + * A visual smoke effect. Needs direction as additional info. + */ + SMOKE(2000, Type.VISUAL, BlockFace.class), + /** + * Sound of a block breaking. Needs block ID as additional info. + */ + STEP_SOUND(2001, Type.SOUND, Material.class), + /** + * Visual effect of a splash potion breaking. Needs potion data value as + * additional info. + */ + POTION_BREAK(2002, Type.VISUAL, Potion.class), + /** + * An ender eye signal; a visual effect. + */ + ENDER_SIGNAL(2003, Type.VISUAL), + /** + * The flames seen on a mobspawner; a visual effect. + */ + MOBSPAWNER_FLAMES(2004, Type.VISUAL), + /** + * The spark that comes off a fireworks + */ + FIREWORKS_SPARK("fireworksSpark", Type.PARTICLE), + /** + * Critical hit particles + */ + CRIT("crit", Type.PARTICLE), + /** + * Blue critical hit particles + */ + MAGIC_CRIT("magicCrit", Type.PARTICLE), + /** + * Multicolored potion effect particles + */ + POTION_SWIRL("mobSpell", Type.PARTICLE), + /** + * Multicolored potion effect particles that are slightly transparent + */ + POTION_SWIRL_TRANSPARENT("mobSpellAmbient", Type.PARTICLE), + /** + * A puff of white potion swirls + */ + SPELL("spell", Type.PARTICLE), + /** + * A puff of white stars + */ + INSTANT_SPELL("instantSpell", Type.PARTICLE), + /** + * A puff of purple particles + */ + WITCH_MAGIC("witchMagic", Type.PARTICLE), + /** + * The note that appears above note blocks + */ + NOTE("note", Type.PARTICLE), + /** + * The particles shown at nether portals + */ + PORTAL("portal", Type.PARTICLE), + /** + * The symbols that fly towards the enchantment table + */ + FLYING_GLYPH("enchantmenttable", Type.PARTICLE), + /** + * Fire particles + */ + FLAME("flame", Type.PARTICLE), + /** + * The particles that pop out of lava + */ + LAVA_POP("lava", Type.PARTICLE), + /** + * A small gray square + */ + FOOTSTEP("footstep", Type.PARTICLE), + /** + * Water particles + */ + SPLASH("splash", Type.PARTICLE), + /** + * Smoke particles + */ + PARTICLE_SMOKE("smoke", Type.PARTICLE), + /** + * The biggest explosion particle effect + */ + EXPLOSION_HUGE("hugeexplosion", Type.PARTICLE), + /** + * A larger version of the explode particle + */ + EXPLOSION_LARGE("largeexplode", Type.PARTICLE), + /** + * Explosion particles + */ + EXPLOSION("explode", Type.PARTICLE), + /** + * Small gray particles + */ + VOID_FOG("depthsuspend", Type.PARTICLE), + /** + * Small gray particles + */ + SMALL_SMOKE("townaura", Type.PARTICLE), + /** + * A puff of white smoke + */ + CLOUD("cloud", Type.PARTICLE), + /** + * Multicolored dust particles + */ + COLOURED_DUST("reddust", Type.PARTICLE), + /** + * Snowball breaking + */ + SNOWBALL_BREAK("snowballpoof", Type.PARTICLE), + /** + * The water drip particle that appears on blocks under water + */ + WATERDRIP("dripWater", Type.PARTICLE), + /** + * The lava drip particle that appears on blocks under lava + */ + LAVADRIP("dripLava", Type.PARTICLE), + /** + * White particles + */ + SNOW_SHOVEL("snowshovel", Type.PARTICLE), + /** + * The particle shown when a slime jumps + */ + SLIME("slime", Type.PARTICLE), + /** + * The particle that appears when breading animals + */ + HEART("heart", Type.PARTICLE), + /** + * The particle that appears when hitting a villager + */ + VILLAGER_THUNDERCLOUD("angryVillager", Type.PARTICLE), + /** + * The particle that appears when trading with a villager + */ + HAPPY_VILLAGER("happyVillager", Type.PARTICLE), + /** + * The smoke particles that appears on blazes, minecarts + * with furnaces and fire + */ + LARGE_SMOKE("largesmoke", Type.PARTICLE), + /** + * The particles generated when a tool breaks. + * This particle requires a Material so that the client can select the correct texture. + */ + ITEM_BREAK("iconcrack", Type.PARTICLE, Material.class), + /** + * The particles generated while breaking a block. + * This particle requires a Material and data value so that the client can select the correct texture. + */ + TILE_BREAK("blockcrack", Type.PARTICLE, MaterialData.class), + /** + * The particles generated while sprinting a block + * This particle requires a Material and data value so that the client can select the correct texture. + */ + TILE_DUST("blockdust", Type.PARTICLE, MaterialData.class); + + private final int id; + private final Type type; + private final Class data; + private static final Map BY_ID = Maps.newHashMap(); + private static final Map BY_NAME = Maps.newHashMap(); + private final String particleName; + + Effect(int id, Type type) { + this(id,type,null); + } + + Effect(int id, Type type, Class data) { + this.id = id; + this.type = type; + this.data = data; + particleName = null; + } + + Effect(String particleName, Type type, Class data) { + this.particleName = particleName; + this.type = type; + id = 0; + this.data = data; + } + + Effect(String particleName, Type type) { + this.particleName = particleName; + this.type = type; + id = 0; + this.data = null; + } + + /** + * Gets the ID for this effect. + * + * @return if this Effect isn't of type PARTICLE it returns ID of this effect + * @deprecated Magic value + */ + @Deprecated + public int getId() { + return this.id; + } + + /** + * Returns the effect's name. This returns null if the effect is not a particle + * + * @return The effect's name + */ + public String getName() { + return particleName; + } + + /** + * @return The type of the effect. + */ + public Type getType() { + return this.type; + } + + /** + * @return if this Effect isn't of type PARTICLE it returns the class which represents data for this effect, or null if none + */ + public Class getData() { + return this.data; + } + + /** + * Gets the Effect associated with the given ID. + * + * @param id ID of the Effect to return + * @return Effect with the given ID + * @deprecated Magic value + */ + @Deprecated + public static Effect getById(int id) { + return BY_ID.get(id); + } + + static { + for (Effect effect : values()) { + if (effect.type != Type.PARTICLE) { + BY_ID.put(effect.id, effect); + } + } + } + + /** + * Gets the Effect associated with the given name. + * + * @param name name of the Effect to return + * @return Effect with the given name + */ + public static Effect getByName(String name) { + return BY_NAME.get(name); + } + + static { + for (Effect effect : values()) { + if (effect.type == Type.PARTICLE) { + BY_NAME.put(effect.particleName, effect); + } + } + } + + /** + * Represents the type of an effect. + */ + public enum Type {SOUND, VISUAL, PARTICLE} +} diff --git a/azurite-api/src/main/java/org/bukkit/EntityEffect.java b/azurite-api/src/main/java/org/bukkit/EntityEffect.java new file mode 100644 index 0000000..a4a6541 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/EntityEffect.java @@ -0,0 +1,136 @@ +package org.bukkit; + +import com.google.common.collect.Maps; + +import java.util.Map; + +/** + * A list of all Effects that can happen to entities. + */ +public enum EntityEffect { + + /** + * When mobs get hurt. + */ + HURT(2), + + /** + * When a mob dies. + *

+ * This will cause client-glitches! + */ + DEATH(3), + + /** + * The smoke when taming a wolf fails. + *

+ * Without client-mods this will be ignored if the entity is not a wolf. + */ + WOLF_SMOKE(6), + + /** + * The hearts when taming a wolf succeeds. + *

+ * Without client-mods this will be ignored if the entity is not a wolf. + */ + WOLF_HEARTS(7), + + /** + * When a wolf shakes (after being wet). + *

+ * Without client-mods this will be ignored if the entity is not a wolf. + */ + WOLF_SHAKE(8), + + /** + * When a sheep eats a LONG_GRASS block. + */ + SHEEP_EAT(10), + + /** + * When an Iron Golem gives a rose. + *

+ * This will not play an effect if the entity is not an iron golem. + */ + IRON_GOLEM_ROSE(11), + + /** + * Hearts from a villager. + *

+ * This will not play an effect if the entity is not a villager. + */ + VILLAGER_HEART(12), + + /** + * When a villager is angry. + *

+ * This will not play an effect if the entity is not a villager. + */ + VILLAGER_ANGRY(13), + + /** + * Happy particles from a villager. + *

+ * This will not play an effect if the entity is not a villager. + */ + VILLAGER_HAPPY(14), + + /** + * Magic particles from a witch. + *

+ * This will not play an effect if the entity is not a witch. + */ + WITCH_MAGIC(15), + + /** + * When a zombie transforms into a villager by shaking violently. + *

+ * This will not play an effect if the entity is not a zombie. + */ + ZOMBIE_TRANSFORM(16), + + /** + * When a firework explodes. + *

+ * This will not play an effect if the entity is not a firework. + */ + FIREWORK_EXPLODE(17); + + private final byte data; + private final static Map BY_DATA = Maps.newHashMap(); + + EntityEffect(final int data) { + this.data = (byte) data; + } + + /** + * Gets the data value of this EntityEffect + * + * @return The data value + * @deprecated Magic value + */ + @Deprecated + public byte getData() { + return data; + } + + /** + * Gets the EntityEffect with the given data value + * + * @param data Data value to fetch + * @return The {@link EntityEffect} representing the given value, or null + * if it doesn't exist + * @deprecated Magic value + */ + @Deprecated + public static EntityEffect getByData(final byte data) { + return BY_DATA.get(data); + } + + + static { + for (EntityEffect entityEffect : values()) { + BY_DATA.put(entityEffect.data, entityEffect); + } + } +} diff --git a/azurite-api/src/main/java/org/bukkit/FireworkEffect.java b/azurite-api/src/main/java/org/bukkit/FireworkEffect.java new file mode 100644 index 0000000..982a363 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/FireworkEffect.java @@ -0,0 +1,422 @@ +package org.bukkit; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import org.apache.commons.lang.Validate; +import org.bukkit.configuration.serialization.ConfigurationSerializable; +import org.bukkit.configuration.serialization.SerializableAs; + +import java.util.List; +import java.util.Map; + +/** + * Represents a single firework effect. + */ +@SerializableAs("Firework") +public final class FireworkEffect implements ConfigurationSerializable { + + /** + * The type or shape of the effect. + */ + public enum Type { + /** + * A small ball effect. + */ + BALL, + /** + * A large ball effect. + */ + BALL_LARGE, + /** + * A star-shaped effect. + */ + STAR, + /** + * A burst effect. + */ + BURST, + /** + * A creeper-face effect. + */ + CREEPER, + } + + /** + * Construct a firework effect. + * + * @return A utility object for building a firework effect + */ + public static Builder builder() { + return new Builder(); + } + + /** + * This is a builder for FireworkEffects. + * + * @see FireworkEffect#builder() + */ + public static final class Builder { + boolean flicker = false; + boolean trail = false; + final ImmutableList.Builder colors = ImmutableList.builder(); + ImmutableList.Builder fadeColors = null; + Type type = Type.BALL; + + Builder() {} + + /** + * Specify the type of the firework effect. + * + * @param type The effect type + * @return This object, for chaining + * @throws IllegalArgumentException If type is null + */ + public Builder with(Type type) throws IllegalArgumentException { + Validate.notNull(type, "Cannot have null type"); + this.type = type; + return this; + } + + /** + * Add a flicker to the firework effect. + * + * @return This object, for chaining + */ + public Builder withFlicker() { + flicker = true; + return this; + } + + /** + * Set whether the firework effect should flicker. + * + * @param flicker true if it should flicker, false if not + * @return This object, for chaining + */ + public Builder flicker(boolean flicker) { + this.flicker = flicker; + return this; + } + + /** + * Add a trail to the firework effect. + * + * @return This object, for chaining + */ + public Builder withTrail() { + trail = true; + return this; + } + + /** + * Set whether the firework effect should have a trail. + * + * @param trail true if it should have a trail, false for no trail + * @return This object, for chaining + */ + public Builder trail(boolean trail) { + this.trail = trail; + return this; + } + + /** + * Add a primary color to the firework effect. + * + * @param color The color to add + * @return This object, for chaining + * @throws IllegalArgumentException If color is null + */ + public Builder withColor(Color color) throws IllegalArgumentException { + Validate.notNull(color, "Cannot have null color"); + + colors.add(color); + + return this; + } + + /** + * Add several primary colors to the firework effect. + * + * @param colors The colors to add + * @return This object, for chaining + * @throws IllegalArgumentException If colors is null + * @throws IllegalArgumentException If any color is null (may be + * thrown after changes have occurred) + */ + public Builder withColor(Color...colors) throws IllegalArgumentException { + Validate.notNull(colors, "Cannot have null colors"); + if (colors.length == 0) { + return this; + } + + ImmutableList.Builder list = this.colors; + for (Color color : colors) { + Validate.notNull(color, "Color cannot be null"); + list.add(color); + } + + return this; + } + + /** + * Add several primary colors to the firework effect. + * + * @param colors An iterable object whose iterator yields the desired + * colors + * @return This object, for chaining + * @throws IllegalArgumentException If colors is null + * @throws IllegalArgumentException If any color is null (may be + * thrown after changes have occurred) + */ + public Builder withColor(Iterable colors) throws IllegalArgumentException { + Validate.notNull(colors, "Cannot have null colors"); + + ImmutableList.Builder list = this.colors; + for (Object color : colors) { + if (!(color instanceof Color)) { + throw new IllegalArgumentException(color + " is not a Color in " + colors); + } + list.add((Color) color); + } + + return this; + } + + /** + * Add a fade color to the firework effect. + * + * @param color The color to add + * @return This object, for chaining + * @throws IllegalArgumentException If colors is null + * @throws IllegalArgumentException If any color is null (may be + * thrown after changes have occurred) + */ + public Builder withFade(Color color) throws IllegalArgumentException { + Validate.notNull(color, "Cannot have null color"); + + if (fadeColors == null) { + fadeColors = ImmutableList.builder(); + } + + fadeColors.add(color); + + return this; + } + + /** + * Add several fade colors to the firework effect. + * + * @param colors The colors to add + * @return This object, for chaining + * @throws IllegalArgumentException If colors is null + * @throws IllegalArgumentException If any color is null (may be + * thrown after changes have occurred) + */ + public Builder withFade(Color...colors) throws IllegalArgumentException { + Validate.notNull(colors, "Cannot have null colors"); + if (colors.length == 0) { + return this; + } + + ImmutableList.Builder list = this.fadeColors; + if (list == null) { + list = this.fadeColors = ImmutableList.builder(); + } + + for (Color color : colors) { + Validate.notNull(color, "Color cannot be null"); + list.add(color); + } + + return this; + } + + /** + * Add several fade colors to the firework effect. + * + * @param colors An iterable object whose iterator yields the desired + * colors + * @return This object, for chaining + * @throws IllegalArgumentException If colors is null + * @throws IllegalArgumentException If any color is null (may be + * thrown after changes have occurred) + */ + public Builder withFade(Iterable colors) throws IllegalArgumentException { + Validate.notNull(colors, "Cannot have null colors"); + + ImmutableList.Builder list = this.fadeColors; + if (list == null) { + list = this.fadeColors = ImmutableList.builder(); + } + + for (Object color : colors) { + if (!(color instanceof Color)) { + throw new IllegalArgumentException(color + " is not a Color in " + colors); + } + list.add((Color) color); + } + + return this; + } + + /** + * Create a {@link FireworkEffect} from the current contents of this + * builder. + *

+ * To successfully build, you must have specified at least one color. + * + * @return The representative firework effect + */ + public FireworkEffect build() { + return new FireworkEffect( + flicker, + trail, + colors.build(), + fadeColors == null ? ImmutableList.of() : fadeColors.build(), + type + ); + } + } + + private static final String FLICKER = "flicker"; + private static final String TRAIL = "trail"; + private static final String COLORS = "colors"; + private static final String FADE_COLORS = "fade-colors"; + private static final String TYPE = "type"; + + private final boolean flicker; + private final boolean trail; + private final ImmutableList colors; + private final ImmutableList fadeColors; + private final Type type; + private String string = null; + + FireworkEffect(boolean flicker, boolean trail, ImmutableList colors, ImmutableList fadeColors, Type type) { + if (colors.isEmpty()) { + throw new IllegalStateException("Cannot make FireworkEffect without any color"); + } + this.flicker = flicker; + this.trail = trail; + this.colors = colors; + this.fadeColors = fadeColors; + this.type = type; + } + + /** + * Get whether the firework effect flickers. + * + * @return true if it flickers, false if not + */ + public boolean hasFlicker() { + return flicker; + } + + /** + * Get whether the firework effect has a trail. + * + * @return true if it has a trail, false if not + */ + public boolean hasTrail() { + return trail; + } + + /** + * Get the primary colors of the firework effect. + * + * @return An immutable list of the primary colors + */ + public List getColors() { + return colors; + } + + /** + * Get the fade colors of the firework effect. + * + * @return An immutable list of the fade colors + */ + public List getFadeColors() { + return fadeColors; + } + + /** + * Get the type of the firework effect. + * + * @return The effect type + */ + public Type getType() { + return type; + } + + /** + * @see ConfigurationSerializable + * @param map the map to deserialize + * @return the resulting serializable + */ + public static ConfigurationSerializable deserialize(Map map) { + Type type = Type.valueOf((String) map.get(TYPE)); + if (type == null) { + throw new IllegalArgumentException(map.get(TYPE) + " is not a valid Type"); + } + + return builder() + .flicker((Boolean) map.get(FLICKER)) + .trail((Boolean) map.get(TRAIL)) + .withColor((Iterable) map.get(COLORS)) + .withFade((Iterable) map.get(FADE_COLORS)) + .with(type) + .build(); + } + + @Override + public Map serialize() { + return ImmutableMap.of( + FLICKER, flicker, + TRAIL, trail, + COLORS, colors, + FADE_COLORS, fadeColors, + TYPE, type.name() + ); + } + + @Override + public String toString() { + final String string = this.string; + if (string == null) { + return this.string = "FireworkEffect:" + serialize(); + } + return string; + } + + @Override + public int hashCode() { + /** + * TRUE and FALSE as per boolean.hashCode() + */ + final int PRIME = 31, TRUE = 1231, FALSE = 1237; + int hash = 1; + hash = hash * PRIME + (flicker ? TRUE : FALSE); + hash = hash * PRIME + (trail ? TRUE : FALSE); + hash = hash * PRIME + type.hashCode(); + hash = hash * PRIME + colors.hashCode(); + hash = hash * PRIME + fadeColors.hashCode(); + return hash; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + + if (!(obj instanceof FireworkEffect)) { + return false; + } + + FireworkEffect that = (FireworkEffect) obj; + return this.flicker == that.flicker + && this.trail == that.trail + && this.type == that.type + && this.colors.equals(that.colors) + && this.fadeColors.equals(that.fadeColors); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/GameMode.java b/azurite-api/src/main/java/org/bukkit/GameMode.java new file mode 100644 index 0000000..4f23a2b --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/GameMode.java @@ -0,0 +1,72 @@ +package org.bukkit; + +import com.google.common.collect.Maps; +import org.bukkit.entity.HumanEntity; + +import java.util.Map; + +/** + * Represents the various type of game modes that {@link HumanEntity}s may + * have + */ +public enum GameMode { + /** + * Creative mode may fly, build instantly, become invulnerable and create + * free items. + */ + CREATIVE(1), + + /** + * Survival mode is the "normal" gameplay type, with no special features. + */ + SURVIVAL(0), + + /** + * Adventure mode cannot break blocks without the correct tools. + */ + ADVENTURE(2), + + /** + * Spectator mode cannot interact with the world in anyway and is + * invisible to normal players. This grants the player the + * ability to no-clip through the world. + */ + SPECTATOR(3); + + private final int value; + private final static Map BY_ID = Maps.newHashMap(); + + GameMode(final int value) { + this.value = value; + } + + /** + * Gets the mode value associated with this GameMode + * + * @return An integer value of this gamemode + * @deprecated Magic value + */ + @Deprecated + public int getValue() { + return value; + } + + /** + * Gets the GameMode represented by the specified value + * + * @param value Value to check + * @return Associative {@link GameMode} with the given value, or null if + * it doesn't exist + * @deprecated Magic value + */ + @Deprecated + public static GameMode getByValue(final int value) { + return BY_ID.get(value); + } + + static { + for (GameMode mode : values()) { + BY_ID.put(mode.getValue(), mode); + } + } +} diff --git a/azurite-api/src/main/java/org/bukkit/GrassSpecies.java b/azurite-api/src/main/java/org/bukkit/GrassSpecies.java new file mode 100644 index 0000000..f873b48 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/GrassSpecies.java @@ -0,0 +1,61 @@ +package org.bukkit; + +import com.google.common.collect.Maps; + +import java.util.Map; + +/** + * Represents the different types of grass. + */ +public enum GrassSpecies { + + /** + * Represents the dead looking grass. + */ + DEAD(0x0), + /** + * Represents the normal grass species. + */ + NORMAL(0x1), + /** + * Represents the fern-looking grass species. + */ + FERN_LIKE(0x2); + + private final byte data; + private final static Map BY_DATA = Maps.newHashMap(); + + GrassSpecies(final int data) { + this.data = (byte) data; + } + + /** + * Gets the associated data value representing this species + * + * @return A byte containing the data value of this grass species + * @deprecated Magic value + */ + @Deprecated + public byte getData() { + return data; + } + + /** + * Gets the GrassSpecies with the given data value + * + * @param data Data value to fetch + * @return The {@link GrassSpecies} representing the given value, or null + * if it doesn't exist + * @deprecated Magic value + */ + @Deprecated + public static GrassSpecies getByData(final byte data) { + return BY_DATA.get(data); + } + + static { + for (GrassSpecies grassSpecies : values()) { + BY_DATA.put(grassSpecies.getData(), grassSpecies); + } + } +} diff --git a/azurite-api/src/main/java/org/bukkit/Instrument.java b/azurite-api/src/main/java/org/bukkit/Instrument.java new file mode 100644 index 0000000..c42d15c --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/Instrument.java @@ -0,0 +1,67 @@ +package org.bukkit; + +import com.google.common.collect.Maps; + +import java.util.Map; + +public enum Instrument { + + /** + * Piano is the standard instrument for a note block. + */ + PIANO(0x0), + /** + * Bass drum is normally played when a note block is on top of a + * stone-like block + */ + BASS_DRUM(0x1), + /** + * Snare drum is normally played when a note block is on top of a sandy + * block. + */ + SNARE_DRUM(0x2), + /** + * Sticks are normally played when a note block is on top of a glass + * block. + */ + STICKS(0x3), + /** + * Bass guitar is normally played when a note block is on top of a wooden + * block. + */ + BASS_GUITAR(0x4); + + private final byte type; + private final static Map BY_DATA = Maps.newHashMap(); + + Instrument(final int type) { + this.type = (byte) type; + } + + /** + * @return The type ID of this instrument. + * @deprecated Magic value + */ + @Deprecated + public byte getType() { + return this.type; + } + + /** + * Get an instrument by its type ID. + * + * @param type The type ID + * @return The instrument + * @deprecated Magic value + */ + @Deprecated + public static Instrument getByType(final byte type) { + return BY_DATA.get(type); + } + + static { + for (Instrument instrument : Instrument.values()) { + BY_DATA.put(instrument.getType(), instrument); + } + } +} diff --git a/azurite-api/src/main/java/org/bukkit/Location.java b/azurite-api/src/main/java/org/bukkit/Location.java new file mode 100644 index 0000000..c6bfd88 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/Location.java @@ -0,0 +1,601 @@ +package org.bukkit; + +import org.bukkit.block.Block; +import org.bukkit.configuration.serialization.ConfigurationSerializable; +import org.bukkit.util.NumberConversions; +import org.bukkit.util.Vector; + +import java.lang.ref.WeakReference; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; + +/** + * Represents a 3-dimensional position in a world + */ +public class Location implements Cloneable, ConfigurationSerializable { + private WeakReference world; + private double x; + private double y; + private double z; + private float pitch; + private float yaw; + + /** + * Constructs a new Location with the given coordinates + * + * @param world The world in which this location resides + * @param x The x-coordinate of this new location + * @param y The y-coordinate of this new location + * @param z The z-coordinate of this new location + */ + public Location(final World world, final double x, final double y, final double z) { + this(world, x, y, z, 0, 0); + } + + /** + * Constructs a new Location with the given coordinates and direction + * + * @param world The world in which this location resides + * @param x The x-coordinate of this new location + * @param y The y-coordinate of this new location + * @param z The z-coordinate of this new location + * @param yaw The absolute rotation on the x-plane, in degrees + * @param pitch The absolute rotation on the y-plane, in degrees + */ + public Location(final World world, final double x, final double y, final double z, final float yaw, final float pitch) { + this.world = new WeakReference<>(world); + this.x = x; + this.y = y; + this.z = z; + this.pitch = pitch; + this.yaw = yaw; + } + + /** + * Sets the world that this location resides in + * + * @param world New world that this location resides in + */ + public void setWorld(World world) { + this.world = new WeakReference<>(world); + } + + /** + * Gets the world that this location resides in + * + * @return World that contains this location + */ + public World getWorld() { + return world.get(); + } + + /** + * Gets the chunk at the represented location + * + * @return Chunk at the represented location + */ + public Chunk getChunk() { + return getWorld().getChunkAt(this); + } + + /** + * Gets the block at the represented location + * + * @return Block at the represented location + */ + public Block getBlock() { + return getWorld().getBlockAt(this); + } + + /** + * Sets the x-coordinate of this location + * + * @param x X-coordinate + */ + public void setX(double x) { + this.x = x; + } + + /** + * Gets the x-coordinate of this location + * + * @return x-coordinate + */ + public double getX() { + return x; + } + + /** + * Gets the floored value of the X component, indicating the block that + * this location is contained with. + * + * @return block X + */ + public int getBlockX() { + return locToBlock(x); + } + + /** + * Sets the y-coordinate of this location + * + * @param y y-coordinate + */ + public void setY(double y) { + this.y = y; + } + + /** + * Gets the y-coordinate of this location + * + * @return y-coordinate + */ + public double getY() { + return y; + } + + /** + * Gets the floored value of the Y component, indicating the block that + * this location is contained with. + * + * @return block y + */ + public int getBlockY() { + return locToBlock(y); + } + + /** + * Sets the z-coordinate of this location + * + * @param z z-coordinate + */ + public void setZ(double z) { + this.z = z; + } + + /** + * Gets the z-coordinate of this location + * + * @return z-coordinate + */ + public double getZ() { + return z; + } + + /** + * Gets the floored value of the Z component, indicating the block that + * this location is contained with. + * + * @return block z + */ + public int getBlockZ() { + return locToBlock(z); + } + + /** + * Sets the yaw of this location, measured in degrees. + *

    + *
  • A yaw of 0 or 360 represents the positive z direction. + *
  • A yaw of 180 represents the negative z direction. + *
  • A yaw of 90 represents the negative x direction. + *
  • A yaw of 270 represents the positive x direction. + *
+ * Increasing yaw values are the equivalent of turning to your + * right-facing, increasing the scale of the next respective axis, and + * decreasing the scale of the previous axis. + * + * @param yaw new rotation's yaw + */ + public void setYaw(float yaw) { + this.yaw = yaw; + } + + /** + * Gets the yaw of this location, measured in degrees. + *
    + *
  • A yaw of 0 or 360 represents the positive z direction. + *
  • A yaw of 180 represents the negative z direction. + *
  • A yaw of 90 represents the negative x direction. + *
  • A yaw of 270 represents the positive x direction. + *
+ * Increasing yaw values are the equivalent of turning to your + * right-facing, increasing the scale of the next respective axis, and + * decreasing the scale of the previous axis. + * + * @return the rotation's yaw + */ + public float getYaw() { + return yaw; + } + + /** + * Sets the pitch of this location, measured in degrees. + *
    + *
  • A pitch of 0 represents level forward facing. + *
  • A pitch of 90 represents downward facing, or negative y + * direction. + *
  • A pitch of -90 represents upward facing, or positive y direction. + *
+ * Increasing pitch values the equivalent of looking down. + * + * @param pitch new incline's pitch + */ + public void setPitch(float pitch) { + this.pitch = pitch; + } + + /** + * Gets the pitch of this location, measured in degrees. + *
    + *
  • A pitch of 0 represents level forward facing. + *
  • A pitch of 90 represents downward facing, or negative y + * direction. + *
  • A pitch of -90 represents upward facing, or positive y direction. + *
+ * Increasing pitch values the equivalent of looking down. + * + * @return the incline's pitch + */ + public float getPitch() { + return pitch; + } + + /** + * Gets a unit-vector pointing in the direction that this Location is + * facing. + * + * @return a vector pointing the direction of this location's {@link + * #getPitch() pitch} and {@link #getYaw() yaw} + */ + public Vector getDirection() { + Vector vector = new Vector(); + + double rotX = this.getYaw(); + double rotY = this.getPitch(); + + vector.setY(-Math.sin(Math.toRadians(rotY))); + + double xz = Math.cos(Math.toRadians(rotY)); + + vector.setX(-xz * Math.sin(Math.toRadians(rotX))); + vector.setZ(xz * Math.cos(Math.toRadians(rotX))); + + return vector; + } + + /** + * Sets the {@link #getYaw() yaw} and {@link #getPitch() pitch} to point + * in the direction of the vector. + * + * @param vector the direction vector + * @return the same location + */ + public Location setDirection(Vector vector) { + /* + * Sin = Opp / Hyp + * Cos = Adj / Hyp + * Tan = Opp / Adj + * + * x = -Opp + * z = Adj + */ + final double _2PI = 2 * Math.PI; + final double x = vector.getX(); + final double z = vector.getZ(); + + if (x == 0 && z == 0) { + pitch = vector.getY() > 0 ? -90 : 90; + return this; + } + + double theta = Math.atan2(-x, z); + yaw = (float) Math.toDegrees((theta + _2PI) % _2PI); + + double x2 = NumberConversions.square(x); + double z2 = NumberConversions.square(z); + double xz = Math.sqrt(x2 + z2); + pitch = (float) Math.toDegrees(Math.atan(-vector.getY() / xz)); + + return this; + } + + /** + * Adds the location by another. + * + * @see Vector + * @param vec The other location + * @return the same location + * @throws IllegalArgumentException for differing worlds + */ + public Location add(Location vec) { + if (vec == null || vec.getWorld() != getWorld()) { + throw new IllegalArgumentException("Cannot add Locations of differing worlds"); + } + + x += vec.x; + y += vec.y; + z += vec.z; + return this; + } + + /** + * Adds the location by a vector. + * + * @see Vector + * @param vec Vector to use + * @return the same location + */ + public Location add(Vector vec) { + this.x += vec.getX(); + this.y += vec.getY(); + this.z += vec.getZ(); + return this; + } + + /** + * Adds the location by another. Not world-aware. + * + * @see Vector + * @param x X coordinate + * @param y Y coordinate + * @param z Z coordinate + * @return the same location + */ + public Location add(double x, double y, double z) { + this.x += x; + this.y += y; + this.z += z; + return this; + } + + /** + * Subtracts the location by another. + * + * @see Vector + * @param vec The other location + * @return the same location + * @throws IllegalArgumentException for differing worlds + */ + public Location subtract(Location vec) { + if (vec == null || vec.getWorld() != getWorld()) { + throw new IllegalArgumentException("Cannot add Locations of differing worlds"); + } + + x -= vec.x; + y -= vec.y; + z -= vec.z; + return this; + } + + /** + * Subtracts the location by a vector. + * + * @see Vector + * @param vec The vector to use + * @return the same location + */ + public Location subtract(Vector vec) { + this.x -= vec.getX(); + this.y -= vec.getY(); + this.z -= vec.getZ(); + return this; + } + + /** + * Subtracts the location by another. Not world-aware and + * orientation independent. + * + * @see Vector + * @param x X coordinate + * @param y Y coordinate + * @param z Z coordinate + * @return the same location + */ + public Location subtract(double x, double y, double z) { + this.x -= x; + this.y -= y; + this.z -= z; + return this; + } + + /** + * Gets the magnitude of the location, defined as sqrt(x^2+y^2+z^2). The + * value of this method is not cached and uses a costly square-root + * function, so do not repeatedly call this method to get the location's + * magnitude. NaN will be returned if the inner result of the sqrt() + * function overflows, which will be caused if the length is too long. Not + * world-aware and orientation independent. + * + * @see Vector + * @return the magnitude + */ + public double length() { + return Math.sqrt(NumberConversions.square(x) + NumberConversions.square(y) + NumberConversions.square(z)); + } + + /** + * Gets the magnitude of the location squared. Not world-aware and + * orientation independent. + * + * @see Vector + * @return the magnitude + */ + public double lengthSquared() { + return NumberConversions.square(x) + NumberConversions.square(y) + NumberConversions.square(z); + } + + /** + * Get the distance between this location and another. The value of this + * method is not cached and uses a costly square-root function, so do not + * repeatedly call this method to get the location's magnitude. NaN will + * be returned if the inner result of the sqrt() function overflows, which + * will be caused if the distance is too long. + * + * @see Vector + * @param o The other location + * @return the distance + * @throws IllegalArgumentException for differing worlds + */ + public double distance(Location o) { + return Math.sqrt(distanceSquared(o)); + } + + /** + * Get the squared distance between this location and another. + * + * @see Vector + * @param o The other location + * @return the distance + * @throws IllegalArgumentException for differing worlds + */ + public double distanceSquared(Location o) { + if (o == null) { + throw new IllegalArgumentException("Cannot measure distance to a null location"); + } else if (o.getWorld() == null || getWorld() == null) { + throw new IllegalArgumentException("Cannot measure distance to a null world"); + } else if (o.getWorld() != getWorld()) { + throw new IllegalArgumentException("Cannot measure distance between " + getWorld().getName() + " and " + o.getWorld().getName()); + } + + return NumberConversions.square(x - o.x) + NumberConversions.square(y - o.y) + NumberConversions.square(z - o.z); + } + + /** + * Performs scalar multiplication, multiplying all components with a + * scalar. Not world-aware. + * + * @param m The factor + * @see Vector + * @return the same location + */ + public Location multiply(double m) { + x *= m; + y *= m; + z *= m; + return this; + } + + /** + * Zero this location's components. Not world-aware. + * + * @see Vector + * @return the same location + */ + public Location zero() { + x = 0; + y = 0; + z = 0; + return this; + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final Location other = (Location) obj; + + if (!Objects.equals(this.world.get(), other.world.get())) { + return false; + } + if (Double.doubleToLongBits(this.x) != Double.doubleToLongBits(other.x)) { + return false; + } + if (Double.doubleToLongBits(this.y) != Double.doubleToLongBits(other.y)) { + return false; + } + if (Double.doubleToLongBits(this.z) != Double.doubleToLongBits(other.z)) { + return false; + } + if (Float.floatToIntBits(this.pitch) != Float.floatToIntBits(other.pitch)) { + return false; + } + if (Float.floatToIntBits(this.yaw) != Float.floatToIntBits(other.yaw)) { + return false; + } + return true; + } + + @Override + public int hashCode() { + int hash = 3; + + hash = 19 * hash + (this.world.get() != null ? this.world.get().hashCode() : 0); + hash = 19 * hash + (int) (Double.doubleToLongBits(this.x) ^ (Double.doubleToLongBits(this.x) >>> 32)); + hash = 19 * hash + (int) (Double.doubleToLongBits(this.y) ^ (Double.doubleToLongBits(this.y) >>> 32)); + hash = 19 * hash + (int) (Double.doubleToLongBits(this.z) ^ (Double.doubleToLongBits(this.z) >>> 32)); + hash = 19 * hash + Float.floatToIntBits(this.pitch); + hash = 19 * hash + Float.floatToIntBits(this.yaw); + return hash; + } + + @Override + public String toString() { + return "Location{" + "world=" + world.get() + ",x=" + x + ",y=" + y + ",z=" + z + ",pitch=" + pitch + ",yaw=" + yaw + '}'; + } + + /** + * Constructs a new {@link Vector} based on this Location + * + * @return New Vector containing the coordinates represented by this + * Location + */ + public Vector toVector() { + return new Vector(x, y, z); + } + + @Override + public Location clone() { + try { + return (Location) super.clone(); + } catch (CloneNotSupportedException e) { + throw new Error(e); + } + } + + /** + * Safely converts a double (location coordinate) to an int (block + * coordinate) + * + * @param loc Precise coordinate + * @return Block coordinate + */ + public static int locToBlock(double loc) { + return NumberConversions.floor(loc); + } + + @Utility + public Map serialize() { + Map data = new HashMap(); + data.put("world", getWorld().getName()); + + data.put("x", this.x); + data.put("y", this.y); + data.put("z", this.z); + + data.put("yaw", this.yaw); + data.put("pitch", this.pitch); + + return data; + } + + /** + * Required method for deserialization + * + * @param args map to deserialize + * @return deserialized location + * @throws IllegalArgumentException if the world don't exists + * @see ConfigurationSerializable + */ + public static Location deserialize(Map args) { + World world = Bukkit.getWorld((String) args.get("world")); + if (world == null) { + throw new IllegalArgumentException("unknown world"); + } + + return new Location(world, NumberConversions.toDouble(args.get("x")), NumberConversions.toDouble(args.get("y")), NumberConversions.toDouble(args.get("z")), NumberConversions.toFloat(args.get("yaw")), NumberConversions.toFloat(args.get("pitch"))); + } +} \ No newline at end of file diff --git a/azurite-api/src/main/java/org/bukkit/Material.java b/azurite-api/src/main/java/org/bukkit/Material.java new file mode 100644 index 0000000..d17f034 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/Material.java @@ -0,0 +1,1102 @@ +package org.bukkit; + +import com.google.common.collect.Maps; +import org.apache.commons.lang.Validate; +import org.bukkit.map.MapView; +import org.bukkit.material.*; +import org.bukkit.potion.Potion; +import org.bukkit.util.Java15Compat; + +import java.lang.reflect.Constructor; +import java.util.Map; + +/** + * An enum of all material IDs accepted by the official server and client + */ +public enum Material { + AIR(0, 0), + STONE(1), + GRASS(2), + DIRT(3), + COBBLESTONE(4), + WOOD(5, Tree.class), + SAPLING(6, Tree.class), + BEDROCK(7), + WATER(8, MaterialData.class), + STATIONARY_WATER(9, MaterialData.class), + LAVA(10, MaterialData.class), + STATIONARY_LAVA(11, MaterialData.class), + SAND(12), + GRAVEL(13), + GOLD_ORE(14), + IRON_ORE(15), + COAL_ORE(16), + LOG(17, Tree.class), + LEAVES(18, Tree.class), + SPONGE(19), + GLASS(20), + LAPIS_ORE(21), + LAPIS_BLOCK(22), + DISPENSER(23, Dispenser.class), + SANDSTONE(24, Sandstone.class), + NOTE_BLOCK(25), + BED_BLOCK(26, Bed.class), + POWERED_RAIL(27, PoweredRail.class), + DETECTOR_RAIL(28, DetectorRail.class), + PISTON_STICKY_BASE(29, PistonBaseMaterial.class), + WEB(30), + LONG_GRASS(31, LongGrass.class), + DEAD_BUSH(32), + PISTON_BASE(33, PistonBaseMaterial.class), + PISTON_EXTENSION(34, PistonExtensionMaterial.class), + WOOL(35, Wool.class), + PISTON_MOVING_PIECE(36), + YELLOW_FLOWER(37), + RED_ROSE(38), + BROWN_MUSHROOM(39), + RED_MUSHROOM(40), + GOLD_BLOCK(41), + IRON_BLOCK(42), + DOUBLE_STEP(43, Step.class), + STEP(44, Step.class), + BRICK(45), + TNT(46), + BOOKSHELF(47), + MOSSY_COBBLESTONE(48), + OBSIDIAN(49), + TORCH(50, Torch.class), + FIRE(51), + MOB_SPAWNER(52), + WOOD_STAIRS(53, Stairs.class), + CHEST(54, Chest.class), + REDSTONE_WIRE(55, RedstoneWire.class), + DIAMOND_ORE(56), + DIAMOND_BLOCK(57), + WORKBENCH(58), + CROPS(59, Crops.class), + SOIL(60, MaterialData.class), + FURNACE(61, Furnace.class), + BURNING_FURNACE(62, Furnace.class), + SIGN_POST(63, 64, Sign.class), + WOODEN_DOOR(64, Door.class), + LADDER(65, Ladder.class), + RAILS(66, Rails.class), + COBBLESTONE_STAIRS(67, Stairs.class), + WALL_SIGN(68, 64, Sign.class), + LEVER(69, Lever.class), + STONE_PLATE(70, PressurePlate.class), + IRON_DOOR_BLOCK(71, Door.class), + WOOD_PLATE(72, PressurePlate.class), + REDSTONE_ORE(73), + GLOWING_REDSTONE_ORE(74), + REDSTONE_TORCH_OFF(75, RedstoneTorch.class), + REDSTONE_TORCH_ON(76, RedstoneTorch.class), + STONE_BUTTON(77, Button.class), + SNOW(78), + ICE(79), + SNOW_BLOCK(80), + CACTUS(81, MaterialData.class), + CLAY(82), + SUGAR_CANE_BLOCK(83, MaterialData.class), + JUKEBOX(84), + FENCE(85), + PUMPKIN(86, Pumpkin.class), + NETHERRACK(87), + SOUL_SAND(88), + GLOWSTONE(89), + PORTAL(90), + JACK_O_LANTERN(91, Pumpkin.class), + CAKE_BLOCK(92, 64, Cake.class), + DIODE_BLOCK_OFF(93, Diode.class), + DIODE_BLOCK_ON(94, Diode.class), + STAINED_GLASS(95), + TRAP_DOOR(96, TrapDoor.class), + MONSTER_EGGS(97, MonsterEggs.class), + SMOOTH_BRICK(98, SmoothBrick.class), + HUGE_MUSHROOM_1(99, Mushroom.class), + HUGE_MUSHROOM_2(100, Mushroom.class), + IRON_FENCE(101), + THIN_GLASS(102), + MELON_BLOCK(103), + PUMPKIN_STEM(104, MaterialData.class), + MELON_STEM(105, MaterialData.class), + VINE(106, Vine.class), + FENCE_GATE(107, Gate.class), + BRICK_STAIRS(108, Stairs.class), + SMOOTH_STAIRS(109, Stairs.class), + MYCEL(110), + WATER_LILY(111), + NETHER_BRICK(112), + NETHER_FENCE(113), + NETHER_BRICK_STAIRS(114, Stairs.class), + NETHER_WARTS(115, NetherWarts.class), + ENCHANTMENT_TABLE(116), + BREWING_STAND(117, MaterialData.class), + CAULDRON(118, Cauldron.class), + ENDER_PORTAL(119), + ENDER_PORTAL_FRAME(120), + ENDER_STONE(121), + DRAGON_EGG(122), + REDSTONE_LAMP_OFF(123), + REDSTONE_LAMP_ON(124), + WOOD_DOUBLE_STEP(125, WoodenStep.class), + WOOD_STEP(126, WoodenStep.class), + COCOA(127, CocoaPlant.class), + SANDSTONE_STAIRS(128, Stairs.class), + EMERALD_ORE(129), + ENDER_CHEST(130, EnderChest.class), + TRIPWIRE_HOOK(131, TripwireHook.class), + TRIPWIRE(132, Tripwire.class), + EMERALD_BLOCK(133), + SPRUCE_WOOD_STAIRS(134, Stairs.class), + BIRCH_WOOD_STAIRS(135, Stairs.class), + JUNGLE_WOOD_STAIRS(136, Stairs.class), + COMMAND(137, Command.class), + BEACON(138), + COBBLE_WALL(139), + FLOWER_POT(140, FlowerPot.class), + CARROT(141), + POTATO(142), + WOOD_BUTTON(143, Button.class), + SKULL(144, Skull.class), + ANVIL(145), + TRAPPED_CHEST(146, Chest.class), + GOLD_PLATE(147), + IRON_PLATE(148), + REDSTONE_COMPARATOR_OFF(149), + REDSTONE_COMPARATOR_ON(150), + DAYLIGHT_DETECTOR(151), + REDSTONE_BLOCK(152), + QUARTZ_ORE(153), + HOPPER(154), + QUARTZ_BLOCK(155), + QUARTZ_STAIRS(156, Stairs.class), + ACTIVATOR_RAIL(157, PoweredRail.class), + DROPPER(158, Dispenser.class), + STAINED_CLAY(159), + STAINED_GLASS_PANE(160), + LEAVES_2(161), + LOG_2(162), + ACACIA_STAIRS(163, Stairs.class), + DARK_OAK_STAIRS(164, Stairs.class), + SLIME_BLOCK(165), + BARRIER(166), + IRON_TRAPDOOR(167, TrapDoor.class), + PRISMARINE(168), + SEA_LANTERN(169), + HAY_BLOCK(170), + CARPET(171), + HARD_CLAY(172), + COAL_BLOCK(173), + PACKED_ICE(174), + DOUBLE_PLANT(175), + STANDING_BANNER(176, Banner.class), + WALL_BANNER(177, Banner.class), + DAYLIGHT_DETECTOR_INVERTED(178), + RED_SANDSTONE(179), + RED_SANDSTONE_STAIRS(180, Stairs.class), + DOUBLE_STONE_SLAB2(181), + STONE_SLAB2(182), + SPRUCE_FENCE_GATE(183, Gate.class), + BIRCH_FENCE_GATE(184, Gate.class), + JUNGLE_FENCE_GATE(185, Gate.class), + DARK_OAK_FENCE_GATE(186, Gate.class), + ACACIA_FENCE_GATE(187, Gate.class), + SPRUCE_FENCE(188), + BIRCH_FENCE(189), + JUNGLE_FENCE(190), + DARK_OAK_FENCE(191), + ACACIA_FENCE(192), + SPRUCE_DOOR(193, Door.class), + BIRCH_DOOR(194, Door.class), + JUNGLE_DOOR(195, Door.class), + ACACIA_DOOR(196, Door.class), + DARK_OAK_DOOR(197, Door.class), + // ----- Item Separator ----- + IRON_SPADE(256, 1, 250), + IRON_PICKAXE(257, 1, 250), + IRON_AXE(258, 1, 250), + FLINT_AND_STEEL(259, 1, 64), + APPLE(260), + BOW(261, 1, 384), + ARROW(262), + COAL(263, Coal.class), + DIAMOND(264), + IRON_INGOT(265), + GOLD_INGOT(266), + IRON_SWORD(267, 1, 250), + WOOD_SWORD(268, 1, 59), + WOOD_SPADE(269, 1, 59), + WOOD_PICKAXE(270, 1, 59), + WOOD_AXE(271, 1, 59), + STONE_SWORD(272, 1, 131), + STONE_SPADE(273, 1, 131), + STONE_PICKAXE(274, 1, 131), + STONE_AXE(275, 1, 131), + DIAMOND_SWORD(276, 1, 1561), + DIAMOND_SPADE(277, 1, 1561), + DIAMOND_PICKAXE(278, 1, 1561), + DIAMOND_AXE(279, 1, 1561), + STICK(280), + BOWL(281), + MUSHROOM_SOUP(282, 1), + GOLD_SWORD(283, 1, 32), + GOLD_SPADE(284, 1, 32), + GOLD_PICKAXE(285, 1, 32), + GOLD_AXE(286, 1, 32), + STRING(287), + FEATHER(288), + SULPHUR(289), + WOOD_HOE(290, 1, 59), + STONE_HOE(291, 1, 131), + IRON_HOE(292, 1, 250), + DIAMOND_HOE(293, 1, 1561), + GOLD_HOE(294, 1, 32), + SEEDS(295), + WHEAT(296), + BREAD(297), + LEATHER_HELMET(298, 1, 55), + LEATHER_CHESTPLATE(299, 1, 80), + LEATHER_LEGGINGS(300, 1, 75), + LEATHER_BOOTS(301, 1, 65), + CHAINMAIL_HELMET(302, 1, 165), + CHAINMAIL_CHESTPLATE(303, 1, 240), + CHAINMAIL_LEGGINGS(304, 1, 225), + CHAINMAIL_BOOTS(305, 1, 195), + IRON_HELMET(306, 1, 165), + IRON_CHESTPLATE(307, 1, 240), + IRON_LEGGINGS(308, 1, 225), + IRON_BOOTS(309, 1, 195), + DIAMOND_HELMET(310, 1, 363), + DIAMOND_CHESTPLATE(311, 1, 528), + DIAMOND_LEGGINGS(312, 1, 495), + DIAMOND_BOOTS(313, 1, 429), + GOLD_HELMET(314, 1, 77), + GOLD_CHESTPLATE(315, 1, 112), + GOLD_LEGGINGS(316, 1, 105), + GOLD_BOOTS(317, 1, 91), + FLINT(318), + PORK(319), + GRILLED_PORK(320), + PAINTING(321), + GOLDEN_APPLE(322), + SIGN(323, 16), + WOOD_DOOR(324, 64), + BUCKET(325, 16), + WATER_BUCKET(326, 1), + LAVA_BUCKET(327, 1), + MINECART(328, 1), + SADDLE(329, 1), + IRON_DOOR(330, 64), + REDSTONE(331), + SNOW_BALL(332, 16), + BOAT(333, 1), + LEATHER(334), + MILK_BUCKET(335, 1), + CLAY_BRICK(336), + CLAY_BALL(337), + SUGAR_CANE(338), + PAPER(339), + BOOK(340), + SLIME_BALL(341), + STORAGE_MINECART(342, 1), + POWERED_MINECART(343, 1), + EGG(344, 16), + COMPASS(345), + FISHING_ROD(346, 1, 64), + WATCH(347), + GLOWSTONE_DUST(348), + RAW_FISH(349), + COOKED_FISH(350), + INK_SACK(351, Dye.class), + BONE(352), + SUGAR(353), + CAKE(354, 1), + BED(355, 1), + DIODE(356), + COOKIE(357), + /** + * @see MapView + */ + MAP(358, MaterialData.class), + SHEARS(359, 1, 238), + MELON(360), + PUMPKIN_SEEDS(361), + MELON_SEEDS(362), + RAW_BEEF(363), + COOKED_BEEF(364), + RAW_CHICKEN(365), + COOKED_CHICKEN(366), + ROTTEN_FLESH(367), + ENDER_PEARL(368, 16), + BLAZE_ROD(369), + GHAST_TEAR(370), + GOLD_NUGGET(371), + NETHER_STALK(372), + /** + * @see Potion + */ + POTION(373, 1, MaterialData.class), + GLASS_BOTTLE(374), + SPIDER_EYE(375), + FERMENTED_SPIDER_EYE(376), + BLAZE_POWDER(377), + MAGMA_CREAM(378), + BREWING_STAND_ITEM(379), + CAULDRON_ITEM(380), + EYE_OF_ENDER(381), + SPECKLED_MELON(382), + MONSTER_EGG(383, 64, SpawnEgg.class), + EXP_BOTTLE(384, 64), + FIREBALL(385, 64), + BOOK_AND_QUILL(386, 1), + WRITTEN_BOOK(387, 16), + EMERALD(388, 64), + ITEM_FRAME(389), + FLOWER_POT_ITEM(390), + CARROT_ITEM(391), + POTATO_ITEM(392), + BAKED_POTATO(393), + POISONOUS_POTATO(394), + EMPTY_MAP(395), + GOLDEN_CARROT(396), + SKULL_ITEM(397), + CARROT_STICK(398, 1, 25), + NETHER_STAR(399), + PUMPKIN_PIE(400), + FIREWORK(401), + FIREWORK_CHARGE(402), + ENCHANTED_BOOK(403, 1), + REDSTONE_COMPARATOR(404), + NETHER_BRICK_ITEM(405), + QUARTZ(406), + EXPLOSIVE_MINECART(407, 1), + HOPPER_MINECART(408, 1), + PRISMARINE_SHARD(409), + PRISMARINE_CRYSTALS(410), + RABBIT(411), + COOKED_RABBIT(412), + RABBIT_STEW(413, 1), + RABBIT_FOOT(414), + RABBIT_HIDE(415), + ARMOR_STAND(416, 16), + IRON_BARDING(417, 1), + GOLD_BARDING(418, 1), + DIAMOND_BARDING(419, 1), + LEASH(420), + NAME_TAG(421), + COMMAND_MINECART(422, 1), + MUTTON(423), + COOKED_MUTTON(424), + BANNER(425, 16), + SPRUCE_DOOR_ITEM(427), + BIRCH_DOOR_ITEM(428), + JUNGLE_DOOR_ITEM(429), + ACACIA_DOOR_ITEM(430), + DARK_OAK_DOOR_ITEM(431), + GOLD_RECORD(2256, 1), + GREEN_RECORD(2257, 1), + RECORD_3(2258, 1), + RECORD_4(2259, 1), + RECORD_5(2260, 1), + RECORD_6(2261, 1), + RECORD_7(2262, 1), + RECORD_8(2263, 1), + RECORD_9(2264, 1), + RECORD_10(2265, 1), + RECORD_11(2266, 1), + RECORD_12(2267, 1), + ; + + private final int id; + private final Constructor ctor; + private static Material[] byId = new Material[383]; + private final static Map BY_NAME = Maps.newHashMap(); + public int maxStack; + private final short durability; + + Material(final int id) { + this(id, 64); + } + + Material(final int id, final int stack) { + this(id, stack, MaterialData.class); + } + + Material(final int id, final int stack, final int durability) { + this(id, stack, durability, MaterialData.class); + } + + Material(final int id, final Class data) { + this(id, 64, data); + } + + Material(final int id, final int stack, final Class data) { + this(id, stack, 0, data); + } + + Material(final int id, final int stack, final int durability, final Class data) { + this.id = id; + this.durability = (short) durability; + this.maxStack = stack; + // try to cache the constructor for this material + try { + this.ctor = data.getConstructor(int.class, byte.class); + } catch (NoSuchMethodException ex) { + throw new AssertionError(ex); + } catch (SecurityException ex) { + throw new AssertionError(ex); + } + } + + /** + * Gets the item ID or block ID of this Material + * + * @return ID of this material + * @deprecated Magic value + */ + @Deprecated + public int getId() { + return id; + } + + /** + * Gets the maximum amount of this material that can be held in a stack + * + * @return Maximum stack size for this material + */ + public int getMaxStackSize() { + return maxStack; + } + + /** + * Gets the maximum durability of this material + * + * @return Maximum durability for this material + */ + public short getMaxDurability() { + return durability; + } + + public boolean isArmor() { + String name = name(); + return name.contains("CHESTPLATE") || name.contains("LEGGINGS") || name.contains("BOOTS") || name.contains("HELMET"); + } + + /** + * Gets the MaterialData class associated with this Material + * + * @return MaterialData associated with this Material + */ + public Class getData() { + return ctor.getDeclaringClass(); + } + + /** + * Constructs a new MaterialData relevant for this Material, with the + * given initial data + * + * @param raw Initial data to construct the MaterialData with + * @return New MaterialData with the given data + * @deprecated Magic value + */ + @Deprecated + public MaterialData getNewData(final byte raw) { + try { + return ctor.newInstance(id, raw); + } catch (InstantiationException ex) { + final Throwable t = ex.getCause(); + if (t instanceof RuntimeException) { + throw (RuntimeException) t; + } + if (t instanceof Error) { + throw (Error) t; + } + throw new AssertionError(t); + } catch (Throwable t) { + throw new AssertionError(t); + } + } + + /** + * Checks if this Material is a placable block + * + * @return true if this material is a block + */ + public boolean isBlock() { + return id < 256; + } + + /** + * Checks if this Material is edible. + * + * @return true if this Material is edible. + */ + public boolean isEdible() { + switch (this) { + case BREAD: + case CARROT_ITEM: + case BAKED_POTATO: + case POTATO_ITEM: + case POISONOUS_POTATO: + case GOLDEN_CARROT: + case PUMPKIN_PIE: + case COOKIE: + case MELON: + case MUSHROOM_SOUP: + case RAW_CHICKEN: + case COOKED_CHICKEN: + case RAW_BEEF: + case COOKED_BEEF: + case RAW_FISH: + case COOKED_FISH: + case PORK: + case GRILLED_PORK: + case APPLE: + case GOLDEN_APPLE: + case ROTTEN_FLESH: + case SPIDER_EYE: + case RABBIT: + case COOKED_RABBIT: + case RABBIT_STEW: + case MUTTON: + case COOKED_MUTTON: + return true; + default: + return false; + } + } + + /** + * Attempts to get the Material with the given ID + * + * @param id ID of the material to get + * @return Material if found, or null + * @deprecated Magic value + */ + @Deprecated + public static Material getMaterial(final int id) { + if (byId.length > id && id >= 0) { + return byId[id]; + } else { + return null; + } + } + + /** + * Attempts to get the Material with the given name. + *

+ * This is a normal lookup, names must be the precise name they are given + * in the enum. + * + * @param name Name of the material to get + * @return Material if found, or null + */ + public static Material getMaterial(final String name) { + return BY_NAME.get(name); + } + + /** + * Attempts to match the Material with the given name. + *

+ * This is a match lookup; names will be converted to uppercase, then + * stripped of special characters in an attempt to format it like the + * enum. + *

+ * Using this for match by ID is deprecated. + * + * @param name Name of the material to get + * @return Material if found, or null + */ + public static Material matchMaterial(final String name) { + Validate.notNull(name, "Name cannot be null"); + + Material result = null; + + try { + result = getMaterial(Integer.parseInt(name)); + } catch (NumberFormatException ignored) {} + + if (result == null) { + String filtered = name.toUpperCase(); + + filtered = filtered.replaceAll("\\s+", "_").replaceAll("\\W", ""); + result = BY_NAME.get(filtered); + } + + return result; + } + + static { + for (Material material : values()) { + if (byId.length > material.id) { + byId[material.id] = material; + } else { + byId = Java15Compat.Arrays_copyOfRange(byId, 0, material.id + 2); + byId[material.id] = material; + } + BY_NAME.put(material.name(), material); + } + } + + /** + * @return True if this material represents a playable music disk. + */ + public boolean isRecord() { + return (this.id >= GOLD_RECORD.id && this.id <= RECORD_12.id); + } + + public boolean isLiquid() { + return (this == WATER || this == STATIONARY_WATER || this == LAVA || this == STATIONARY_LAVA); + } + /** + * Check if the material is a block and solid (cannot be passed through by + * a player) + * + * @return True if this material is a block and solid + */ + public boolean isSolid() { + if (!isBlock() || id == 0) { + return false; + } + switch (this) { + case STONE: + case GRASS: + case DIRT: + case COBBLESTONE: + case WOOD: + case BEDROCK: + case SAND: + case GRAVEL: + case GOLD_ORE: + case IRON_ORE: + case COAL_ORE: + case LOG: + case LEAVES: + case SPONGE: + case GLASS: + case LAPIS_ORE: + case LAPIS_BLOCK: + case DISPENSER: + case SANDSTONE: + case NOTE_BLOCK: + case BED_BLOCK: + case PISTON_STICKY_BASE: + case PISTON_BASE: + case PISTON_EXTENSION: + case WOOL: + case PISTON_MOVING_PIECE: + case GOLD_BLOCK: + case IRON_BLOCK: + case DOUBLE_STEP: + case STEP: + case BRICK: + case TNT: + case BOOKSHELF: + case MOSSY_COBBLESTONE: + case OBSIDIAN: + case MOB_SPAWNER: + case WOOD_STAIRS: + case CHEST: + case DIAMOND_ORE: + case DIAMOND_BLOCK: + case WORKBENCH: + case SOIL: + case FURNACE: + case BURNING_FURNACE: + case SIGN_POST: + case WOODEN_DOOR: + case COBBLESTONE_STAIRS: + case WALL_SIGN: + case STONE_PLATE: + case IRON_DOOR_BLOCK: + case WOOD_PLATE: + case REDSTONE_ORE: + case GLOWING_REDSTONE_ORE: + case ICE: + case SNOW_BLOCK: + case CACTUS: + case CLAY: + case JUKEBOX: + case FENCE: + case PUMPKIN: + case NETHERRACK: + case SOUL_SAND: + case GLOWSTONE: + case JACK_O_LANTERN: + case CAKE_BLOCK: + case STAINED_GLASS: + case TRAP_DOOR: + case MONSTER_EGGS: + case SMOOTH_BRICK: + case HUGE_MUSHROOM_1: + case HUGE_MUSHROOM_2: + case IRON_FENCE: + case THIN_GLASS: + case MELON_BLOCK: + case FENCE_GATE: + case BRICK_STAIRS: + case SMOOTH_STAIRS: + case MYCEL: + case NETHER_BRICK: + case NETHER_FENCE: + case NETHER_BRICK_STAIRS: + case ENCHANTMENT_TABLE: + case BREWING_STAND: + case CAULDRON: + case ENDER_PORTAL_FRAME: + case ENDER_STONE: + case DRAGON_EGG: + case REDSTONE_LAMP_OFF: + case REDSTONE_LAMP_ON: + case WOOD_DOUBLE_STEP: + case WOOD_STEP: + case SANDSTONE_STAIRS: + case EMERALD_ORE: + case ENDER_CHEST: + case EMERALD_BLOCK: + case SPRUCE_WOOD_STAIRS: + case BIRCH_WOOD_STAIRS: + case JUNGLE_WOOD_STAIRS: + case COMMAND: + case BEACON: + case COBBLE_WALL: + case ANVIL: + case TRAPPED_CHEST: + case GOLD_PLATE: + case IRON_PLATE: + case DAYLIGHT_DETECTOR: + case REDSTONE_BLOCK: + case QUARTZ_ORE: + case HOPPER: + case QUARTZ_BLOCK: + case QUARTZ_STAIRS: + case DROPPER: + case STAINED_CLAY: + case HAY_BLOCK: + case HARD_CLAY: + case COAL_BLOCK: + case STAINED_GLASS_PANE: + case LEAVES_2: + case LOG_2: + case ACACIA_STAIRS: + case DARK_OAK_STAIRS: + case PACKED_ICE: + case RED_SANDSTONE: + case SLIME_BLOCK: + case BARRIER: + case IRON_TRAPDOOR: + case PRISMARINE: + case SEA_LANTERN: + case DOUBLE_STONE_SLAB2: + case RED_SANDSTONE_STAIRS: + case STONE_SLAB2: + case SPRUCE_FENCE_GATE: + case BIRCH_FENCE_GATE: + case JUNGLE_FENCE_GATE: + case DARK_OAK_FENCE_GATE: + case ACACIA_FENCE_GATE: + case SPRUCE_FENCE: + case BIRCH_FENCE: + case JUNGLE_FENCE: + case DARK_OAK_FENCE: + case ACACIA_FENCE: + case STANDING_BANNER: + case WALL_BANNER: + case DAYLIGHT_DETECTOR_INVERTED: + case SPRUCE_DOOR: + case BIRCH_DOOR: + case JUNGLE_DOOR: + case ACACIA_DOOR: + case DARK_OAK_DOOR: + return true; + default: + return false; + } + } + + /** + * Check if the material is a block and does not block any light + * + * @return True if this material is a block and does not block any light + */ + public boolean isTransparent() { + if (!isBlock()) { + return false; + } + switch (this) { + case AIR: + case SAPLING: + case POWERED_RAIL: + case DETECTOR_RAIL: + case LONG_GRASS: + case DEAD_BUSH: + case YELLOW_FLOWER: + case RED_ROSE: + case BROWN_MUSHROOM: + case RED_MUSHROOM: + case TORCH: + case FIRE: + case REDSTONE_WIRE: + case CROPS: + case LADDER: + case RAILS: + case LEVER: + case REDSTONE_TORCH_OFF: + case REDSTONE_TORCH_ON: + case STONE_BUTTON: + case SNOW: + case SUGAR_CANE_BLOCK: + case PORTAL: + case DIODE_BLOCK_OFF: + case DIODE_BLOCK_ON: + case PUMPKIN_STEM: + case MELON_STEM: + case VINE: + case WATER_LILY: + case NETHER_WARTS: + case ENDER_PORTAL: + case COCOA: + case TRIPWIRE_HOOK: + case TRIPWIRE: + case FLOWER_POT: + case CARROT: + case POTATO: + case WOOD_BUTTON: + case SKULL: + case REDSTONE_COMPARATOR_OFF: + case REDSTONE_COMPARATOR_ON: + case ACTIVATOR_RAIL: + case CARPET: + case DOUBLE_PLANT: + return true; + default: + return false; + } + } + + /** + * Check if the material is a block and can catch fire + * + * @return True if this material is a block and can catch fire + */ + public boolean isFlammable() { + if (!isBlock()) { + return false; + } + switch (this) { + case WOOD: + case LOG: + case LEAVES: + case NOTE_BLOCK: + case BED_BLOCK: + case LONG_GRASS: + case DEAD_BUSH: + case WOOL: + case TNT: + case BOOKSHELF: + case WOOD_STAIRS: + case CHEST: + case WORKBENCH: + case SIGN_POST: + case WOODEN_DOOR: + case WALL_SIGN: + case WOOD_PLATE: + case JUKEBOX: + case FENCE: + case TRAP_DOOR: + case HUGE_MUSHROOM_1: + case HUGE_MUSHROOM_2: + case VINE: + case FENCE_GATE: + case WOOD_DOUBLE_STEP: + case WOOD_STEP: + case SPRUCE_WOOD_STAIRS: + case BIRCH_WOOD_STAIRS: + case JUNGLE_WOOD_STAIRS: + case TRAPPED_CHEST: + case DAYLIGHT_DETECTOR: + case CARPET: + case LEAVES_2: + case LOG_2: + case ACACIA_STAIRS: + case DARK_OAK_STAIRS: + case DOUBLE_PLANT: + case SPRUCE_FENCE_GATE: + case BIRCH_FENCE_GATE: + case JUNGLE_FENCE_GATE: + case DARK_OAK_FENCE_GATE: + case ACACIA_FENCE_GATE: + case SPRUCE_FENCE: + case BIRCH_FENCE: + case JUNGLE_FENCE: + case DARK_OAK_FENCE: + case ACACIA_FENCE: + case STANDING_BANNER: + case WALL_BANNER: + case DAYLIGHT_DETECTOR_INVERTED: + case SPRUCE_DOOR: + case BIRCH_DOOR: + case JUNGLE_DOOR: + case ACACIA_DOOR: + case DARK_OAK_DOOR: + return true; + default: + return false; + } + } + + /** + * Check if the material is a block and can burn away + * + * @return True if this material is a block and can burn away + */ + public boolean isBurnable() { + if (!isBlock()) { + return false; + } + switch (this) { + case WOOD: + case LOG: + case LEAVES: + case LONG_GRASS: + case WOOL: + case YELLOW_FLOWER: + case RED_ROSE: + case TNT: + case BOOKSHELF: + case WOOD_STAIRS: + case FENCE: + case VINE: + case WOOD_DOUBLE_STEP: + case WOOD_STEP: + case SPRUCE_WOOD_STAIRS: + case BIRCH_WOOD_STAIRS: + case JUNGLE_WOOD_STAIRS: + case HAY_BLOCK: + case COAL_BLOCK: + case LEAVES_2: + case LOG_2: + case CARPET: + case DOUBLE_PLANT: + case DEAD_BUSH: + case FENCE_GATE: + case SPRUCE_FENCE_GATE: + case BIRCH_FENCE_GATE: + case JUNGLE_FENCE_GATE: + case DARK_OAK_FENCE_GATE: + case ACACIA_FENCE_GATE: + case SPRUCE_FENCE: + case BIRCH_FENCE: + case JUNGLE_FENCE: + case DARK_OAK_FENCE: + case ACACIA_FENCE: + return true; + default: + return false; + } + } + + /** + * Check if the material is a block and completely blocks vision + * + * @return True if this material is a block and completely blocks vision + */ + public boolean isOccluding() { + if (!isBlock()) { + return false; + } + switch (this) { + case STONE: + case GRASS: + case DIRT: + case COBBLESTONE: + case WOOD: + case BEDROCK: + case SAND: + case GRAVEL: + case GOLD_ORE: + case IRON_ORE: + case COAL_ORE: + case LOG: + case SPONGE: + case LAPIS_ORE: + case LAPIS_BLOCK: + case DISPENSER: + case SANDSTONE: + case NOTE_BLOCK: + case WOOL: + case GOLD_BLOCK: + case IRON_BLOCK: + case DOUBLE_STEP: + case BRICK: + case BOOKSHELF: + case MOSSY_COBBLESTONE: + case OBSIDIAN: + case MOB_SPAWNER: + case DIAMOND_ORE: + case DIAMOND_BLOCK: + case WORKBENCH: + case FURNACE: + case BURNING_FURNACE: + case REDSTONE_ORE: + case GLOWING_REDSTONE_ORE: + case SNOW_BLOCK: + case CLAY: + case JUKEBOX: + case PUMPKIN: + case NETHERRACK: + case SOUL_SAND: + case JACK_O_LANTERN: + case MONSTER_EGGS: + case SMOOTH_BRICK: + case HUGE_MUSHROOM_1: + case HUGE_MUSHROOM_2: + case MELON_BLOCK: + case MYCEL: + case NETHER_BRICK: + case ENDER_PORTAL_FRAME: + case ENDER_STONE: + case REDSTONE_LAMP_OFF: + case REDSTONE_LAMP_ON: + case WOOD_DOUBLE_STEP: + case EMERALD_ORE: + case EMERALD_BLOCK: + case COMMAND: + case QUARTZ_ORE: + case QUARTZ_BLOCK: + case DROPPER: + case STAINED_CLAY: + case HAY_BLOCK: + case HARD_CLAY: + case COAL_BLOCK: + case LOG_2: + case PACKED_ICE: + case SLIME_BLOCK: + case BARRIER: + case PRISMARINE: + case RED_SANDSTONE: + case DOUBLE_STONE_SLAB2: + return true; + default: + return false; + } + } + + /** + * @return True if this material is affected by gravity. + */ + public boolean hasGravity() { + if (!isBlock()) { + return false; + } + switch (this) { + case SAND: + case GRAVEL: + case ANVIL: + return true; + default: + return false; + } + } +} diff --git a/azurite-api/src/main/java/org/bukkit/NetherWartsState.java b/azurite-api/src/main/java/org/bukkit/NetherWartsState.java new file mode 100644 index 0000000..5362cf3 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/NetherWartsState.java @@ -0,0 +1,21 @@ +package org.bukkit; + +public enum NetherWartsState { + + /** + * State when first seeded + */ + SEEDED, + /** + * First growth stage + */ + STAGE_ONE, + /** + * Second growth stage + */ + STAGE_TWO, + /** + * Ready to harvest + */ + RIPE +} diff --git a/azurite-api/src/main/java/org/bukkit/Note.java b/azurite-api/src/main/java/org/bukkit/Note.java new file mode 100644 index 0000000..0ace930 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/Note.java @@ -0,0 +1,275 @@ +package org.bukkit; + +import com.google.common.collect.Maps; +import org.apache.commons.lang.Validate; + +import java.util.Map; + +/** + * A note class to store a specific note. + */ +public class Note { + + /** + * An enum holding tones. + */ + public enum Tone { + G(0x1, true), + A(0x3, true), + B(0x5, false), + C(0x6, true), + D(0x8, true), + E(0xA, false), + F(0xB, true); + + private final boolean sharpable; + private final byte id; + + private static final Map BY_DATA = Maps.newHashMap(); + /** The number of tones including sharped tones. */ + public static final byte TONES_COUNT = 12; + + Tone(int id, boolean sharpable) { + this.id = (byte) (id % TONES_COUNT); + this.sharpable = sharpable; + } + + /** + * Returns the not sharped id of this tone. + * + * @return the not sharped id of this tone. + * @deprecated Magic value + */ + @Deprecated + public byte getId() { + return getId(false); + } + + /** + * Returns the id of this tone. These method allows to return the + * sharped id of the tone. If the tone couldn't be sharped it always + * return the not sharped id of this tone. + * + * @param sharped Set to true to return the sharped id. + * @return the id of this tone. + * @deprecated Magic value + */ + @Deprecated + public byte getId(boolean sharped) { + byte id = (byte) (sharped && sharpable ? this.id + 1 : this.id); + + return (byte) (id % TONES_COUNT); + } + + /** + * Returns if this tone could be sharped. + * + * @return if this tone could be sharped. + */ + public boolean isSharpable() { + return sharpable; + } + + /** + * Returns if this tone id is the sharped id of the tone. + * + * @param id the id of the tone. + * @return if the tone id is the sharped id of the tone. + * @throws IllegalArgumentException if neither the tone nor the + * semitone have the id. + * @deprecated Magic value + */ + @Deprecated + public boolean isSharped(byte id) { + if (id == getId(false)) { + return false; + } else if (id == getId(true)) { + return true; + } else { + // The id isn't matching to the tone! + throw new IllegalArgumentException("The id isn't matching to the tone."); + } + } + + /** + * Returns the tone to id. Also returning the semitones. + * + * @param id the id of the tone. + * @return the tone to id. + * @deprecated Magic value + */ + @Deprecated + public static Tone getById(byte id) { + return BY_DATA.get(id); + } + + static { + for (Tone tone : values()) { + int id = tone.id % TONES_COUNT; + BY_DATA.put((byte) id, tone); + + if (tone.isSharpable()) { + id = (id + 1) % TONES_COUNT; + BY_DATA.put((byte) id, tone); + } + } + } + } + + private final byte note; + + /** + * Creates a new note. + * + * @param note Internal note id. {@link #getId()} always return this + * value. The value has to be in the interval [0; 24]. + */ + public Note(int note) { + Validate.isTrue(note >= 0 && note <= 24, "The note value has to be between 0 and 24."); + + this.note = (byte) note; + } + + /** + * Creates a new note. + * + * @param octave The octave where the note is in. Has to be 0 - 2. + * @param tone The tone within the octave. If the octave is 2 the note has + * to be F#. + * @param sharped Set if the tone is sharped (e.g. for F#). + */ + public Note(int octave, Tone tone, boolean sharped) { + if (sharped && !tone.isSharpable()) { + tone = Tone.values()[tone.ordinal() + 1]; + sharped = false; + } + if (octave < 0 || octave > 2 || (octave == 2 && !(tone == Tone.F && sharped))) { + throw new IllegalArgumentException("Tone and octave have to be between F#0 and F#2"); + } + + this.note = (byte) (octave * Tone.TONES_COUNT + tone.getId(sharped)); + } + + /** + * Creates a new note for a flat tone, such as A-flat. + * + * @param octave The octave where the note is in. Has to be 0 - 1. + * @param tone The tone within the octave. + * @return The new note. + */ + public static Note flat(int octave, Tone tone) { + Validate.isTrue(octave != 2, "Octave cannot be 2 for flats"); + tone = tone == Tone.G ? Tone.F : Tone.values()[tone.ordinal() - 1]; + return new Note(octave, tone, tone.isSharpable()); + } + + /** + * Creates a new note for a sharp tone, such as A-sharp. + * + * @param octave The octave where the note is in. Has to be 0 - 2. + * @param tone The tone within the octave. If the octave is 2 the note has + * to be F#. + * @return The new note. + */ + public static Note sharp(int octave, Tone tone) { + return new Note(octave, tone, true); + } + + /** + * Creates a new note for a natural tone, such as A-natural. + * + * @param octave The octave where the note is in. Has to be 0 - 1. + * @param tone The tone within the octave. + * @return The new note. + */ + public static Note natural(int octave, Tone tone) { + Validate.isTrue(octave != 2, "Octave cannot be 2 for naturals"); + return new Note(octave, tone, false); + } + + /** + * @return The note a semitone above this one. + */ + public Note sharped() { + Validate.isTrue(note < 24, "This note cannot be sharped because it is the highest known note!"); + return new Note(note + 1); + } + + /** + * @return The note a semitone below this one. + */ + public Note flattened() { + Validate.isTrue(note > 0, "This note cannot be flattened because it is the lowest known note!"); + return new Note(note - 1); + } + + /** + * Returns the internal id of this note. + * + * @return the internal id of this note. + * @deprecated Magic value + */ + @Deprecated + public byte getId() { + return note; + } + + /** + * Returns the octave of this note. + * + * @return the octave of this note. + */ + public int getOctave() { + return note / Tone.TONES_COUNT; + } + + private byte getToneByte() { + return (byte) (note % Tone.TONES_COUNT); + } + + /** + * Returns the tone of this note. + * + * @return the tone of this note. + */ + public Tone getTone() { + return Tone.getById(getToneByte()); + } + + /** + * Returns if this note is sharped. + * + * @return if this note is sharped. + */ + public boolean isSharped() { + byte note = getToneByte(); + return Tone.getById(note).isSharped(note); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + note; + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Note other = (Note) obj; + if (note != other.note) + return false; + return true; + } + + @Override + public String toString() { + return "Note{" + getTone().toString() + (isSharped() ? "#" : "") + "}"; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/OfflinePlayer.java b/azurite-api/src/main/java/org/bukkit/OfflinePlayer.java new file mode 100644 index 0000000..3639dbd --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/OfflinePlayer.java @@ -0,0 +1,118 @@ +package org.bukkit; + +import org.bukkit.configuration.serialization.ConfigurationSerializable; +import org.bukkit.entity.AnimalTamer; +import org.bukkit.entity.Player; +import org.bukkit.permissions.ServerOperator; + +import java.util.Date; +import java.util.UUID; + +public interface OfflinePlayer extends ServerOperator, AnimalTamer, ConfigurationSerializable { + + /** + * Checks if this player is currently online + * + * @return true if they are online + */ + boolean isOnline(); + + /** + * Returns the name of this player + *

+ * Names are no longer unique past a single game session. For persistent storage + * it is recommended that you use {@link #getUniqueId()} instead. + * + * @return Player name or null if we have not seen a name for this player yet + */ + String getName(); + + /** + * Returns the UUID of this player + * + * @return Player UUID + */ + UUID getUniqueId(); + + /** + * Checks if this player is banned or not + * + * @return true if banned, otherwise false + */ + boolean isBanned(); + + /** + * Bans or unbans this player + * + * @param banned true if banned + * @deprecated Use {@link BanList#addBan(String, String, Date, + * String)} or {@link BanList#pardon(String)} to enhance + * functionality + */ + @Deprecated + void setBanned(boolean banned); + + /** + * Checks if this player is whitelisted or not + * + * @return true if whitelisted + */ + boolean isWhitelisted(); + + /** + * Sets if this player is whitelisted or not + * + * @param value true if whitelisted + */ + void setWhitelisted(boolean value); + + /** + * Gets a {@link Player} object that this represents, if there is one + *

+ * If the player is online, this will return that player. Otherwise, + * it will return null. + * + * @return Online player + */ + Player getPlayer(); + + /** + * Gets the first date and time that this player was witnessed on this + * server. + *

+ * If the player has never played before, this will return 0. Otherwise, + * it will be the amount of milliseconds since midnight, January 1, 1970 + * UTC. + * + * @return Date of first log-in for this player, or 0 + */ + long getFirstPlayed(); + + /** + * Gets the last date and time that this player was witnessed on this + * server. + *

+ * If the player has never played before, this will return 0. Otherwise, + * it will be the amount of milliseconds since midnight, January 1, 1970 + * UTC. + * + * @return Date of last log-in for this player, or 0 + */ + long getLastPlayed(); + + /** + * Checks if this player has played on this server before. + * + * @return True if the player has played before, otherwise false + */ + boolean hasPlayedBefore(); + + /** + * Gets the Location where the player will spawn at their bed, null if + * they have not slept in one or their current bed spawn is invalid. + * + * @return Bed Spawn Location if bed exists, otherwise null. + */ + Location getBedSpawnLocation(); + +} diff --git a/azurite-api/src/main/java/org/bukkit/PortalType.java b/azurite-api/src/main/java/org/bukkit/PortalType.java new file mode 100644 index 0000000..7e4627d --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/PortalType.java @@ -0,0 +1,22 @@ +package org.bukkit; + +/** + * Represents various types of portals that can be made in a world. + */ +public enum PortalType { + + /** + * This is a Nether portal, made of obsidian. + */ + NETHER, + + /** + * This is an Ender portal. + */ + ENDER, + + /** + * This is a custom Plugin portal. + */ + CUSTOM +} diff --git a/azurite-api/src/main/java/org/bukkit/Rotation.java b/azurite-api/src/main/java/org/bukkit/Rotation.java new file mode 100644 index 0000000..5d059ea --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/Rotation.java @@ -0,0 +1,63 @@ +package org.bukkit; + +/** + * An enum to specify a rotation based orientation, like that on a clock. + *

+ * It represents how something is viewed, as opposed to cardinal directions. + */ +public enum Rotation { + + /** + * No rotation + */ + NONE, + /** + * Rotated clockwise by 45 degrees + */ + CLOCKWISE_45, + /** + * Rotated clockwise by 90 degrees + */ + CLOCKWISE, + /** + * Rotated clockwise by 135 degrees + */ + CLOCKWISE_135, + /** + * Flipped upside-down, a 180 degree rotation + */ + FLIPPED, + /** + * Flipped upside-down + 45 degree rotation + */ + FLIPPED_45, + /** + * Rotated counter-clockwise by 90 degrees + */ + COUNTER_CLOCKWISE, + /** + * Rotated counter-clockwise by 45 degrees + */ + COUNTER_CLOCKWISE_45 + ; + + private static final Rotation [] rotations = values(); + + /** + * Rotate clockwise by 90 degrees. + * + * @return the relative rotation + */ + public Rotation rotateClockwise() { + return rotations[(this.ordinal() + 1) & 0x7]; + } + + /** + * Rotate counter-clockwise by 90 degrees. + * + * @return the relative rotation + */ + public Rotation rotateCounterClockwise() { + return rotations[(this.ordinal() - 1) & 0x7]; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/SandstoneType.java b/azurite-api/src/main/java/org/bukkit/SandstoneType.java new file mode 100644 index 0000000..5106fde --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/SandstoneType.java @@ -0,0 +1,51 @@ +package org.bukkit; + +import com.google.common.collect.Maps; + +import java.util.Map; + +/** + * Represents the three different types of Sandstone + */ +public enum SandstoneType { + CRACKED(0x0), + GLYPHED(0x1), + SMOOTH(0x2); + + private final byte data; + private final static Map BY_DATA = Maps.newHashMap(); + + SandstoneType(final int data) { + this.data = (byte) data; + } + + /** + * Gets the associated data value representing this type of sandstone + * + * @return A byte containing the data value of this sandstone type + * @deprecated Magic value + */ + @Deprecated + public byte getData() { + return data; + } + + /** + * Gets the type of sandstone with the given data value + * + * @param data Data value to fetch + * @return The {@link SandstoneType} representing the given value, or null + * if it doesn't exist + * @deprecated Magic value + */ + @Deprecated + public static SandstoneType getByData(final byte data) { + return BY_DATA.get(data); + } + + static { + for (SandstoneType type : values()) { + BY_DATA.put(type.data, type); + } + } +} diff --git a/azurite-api/src/main/java/org/bukkit/Server.java b/azurite-api/src/main/java/org/bukkit/Server.java new file mode 100644 index 0000000..fc7e637 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/Server.java @@ -0,0 +1,999 @@ +package org.bukkit; + +import com.avaje.ebean.config.ServerConfig; +import com.google.common.collect.ImmutableList; +import org.bukkit.Warning.WarningState; +import org.bukkit.command.*; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryType; +import org.bukkit.event.server.ServerListPingEvent; +import org.bukkit.generator.ChunkGenerator; +import org.bukkit.help.HelpMap; +import org.bukkit.inventory.*; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.map.MapView; +import org.bukkit.permissions.Permissible; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.ServicesManager; +import org.bukkit.plugin.messaging.Messenger; +import org.bukkit.plugin.messaging.PluginMessageRecipient; +import org.bukkit.scheduler.BukkitScheduler; +import org.bukkit.scoreboard.ScoreboardManager; +import org.bukkit.util.CachedServerIcon; + +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.Serializable; +import java.util.*; +import java.util.logging.Logger; + +/** + * Represents a server implementation. + */ +public interface Server extends PluginMessageRecipient { + + /** + * Used for all administrative messages, such as an operator using a + * command. + *

+ * For use in {@link #broadcast(String, String)}. + */ + String BROADCAST_CHANNEL_ADMINISTRATIVE = "bukkit.broadcast.admin"; + + /** + * Used for all announcement messages, such as informing users that a + * player has joinedge. + *

+ * For use in {@link #broadcast(String, String)}. + */ + String BROADCAST_CHANNEL_USERS = "bukkit.broadcast.user"; + + /** + * Gets the name of this server implementation. + * + * @return name of this server implementation + */ + String getName(); + + /** + * Gets the version string of this server implementation. + * + * @return version of this server implementation + */ + String getVersion(); + + /** + * Gets the Bukkit version that this server is running. + * + * @return version of Bukkit + */ + + int setMaxPlayers(int paramInt); + + String getBukkitVersion(); + + /** + * Gets an array copy of all currently logged in players. + *

+ * This method exists for legacy reasons to provide backwards + * compatibility. It will not exist at runtime and should not be used + * under any circumstances. + * + * @deprecated superseded by {@link #getOnlinePlayers()} + * @return an array of Players that are currently online + */ + @Deprecated + Player[] _INVALID_getOnlinePlayers(); + + /** + * Gets a view of all currently logged in players. This {@linkplain + * Collections#unmodifiableCollection(Collection) view} is a reused + * object, making some operations like {@link Collection#size()} + * zero-allocation. + *

+ * The collection is a view backed by the internal representation, such + * that, changes to the internal state of the server will be reflected + * immediately. However, the reuse of the returned collection (identity) + * is not strictly guaranteed for future or all implementations. Casting + * the collection, or relying on interface implementations (like {@link + * Serializable} or {@link List}), is deprecated. + *

+ * Iteration behavior is undefined outside of self-contained main-thread + * uses. Normal and immediate iterator use without consequences that + * affect the collection are fully supported. The effects following + * (non-exhaustive) {@link Entity#teleport(Location) teleportation}, + * {@link Player#setHealth(double) death}, and {@link Player#kickPlayer( + * String) kicking} are undefined. Any use of this collection from + * asynchronous threads is unsafe. + *

+ * For safe consequential iteration or mimicking the old array behavior, + * using {@link Collection#toArray(Object[])} is recommended. For making + * snapshots, {@link ImmutableList#copyOf(Collection)} is recommended. + * + * @return a view of currently online players. + */ + Collection getOnlinePlayers(); + + /** + * Get the maximum amount of players which can login to this server. + * + * @return the amount of players this server allows + */ + int getMaxPlayers(); + + /** + * Get the game port that the server runs on. + * + * @return the port number of this server + */ + int getPort(); + + /** + * Get the view distance from this server. + * + * @return the view distance from this server. + */ + int getViewDistance(); + + /** + * Get the IP that this server is bound to, or empty string if not + * specified. + * + * @return the IP string that this server is bound to, otherwise empty + * string + */ + String getIp(); + + /** + * Get the name of this server. + * + * @return the name of this server + */ + String getServerName(); + + /** + * Get an ID of this server. The ID is a simple generally alphanumeric ID + * that can be used for uniquely identifying this server. + * + * @return the ID of this server + */ + String getServerId(); + + /** + * Get world type (level-type setting) for default world. + * + * @return the value of level-type (e.g. DEFAULT, FLAT, DEFAULT_1_1) + */ + String getWorldType(); + + /** + * Get generate-structures setting. + * + * @return true if structure generation is enabled, false otherwise + */ + boolean getGenerateStructures(); + + /** + * Gets whether this server allows the End or not. + * + * @return whether this server allows the End or not + */ + boolean getAllowEnd(); + + /** + * Gets whether this server allows the Nether or not. + * + * @return whether this server allows the Nether or not + */ + boolean getAllowNether(); + + /** + * Gets whether this server has a whitelist or not. + * + * @return whether this server has a whitelist or not + */ + boolean hasWhitelist(); + + /** + * Sets if the server is whitelisted. + * + * @param value true for whitelist on, false for off + */ + void setWhitelist(boolean value); + + /** + * Gets a list of whitelisted players. + * + * @return a set containing all whitelisted players + */ + Set getWhitelistedPlayers(); + + /** + * Reloads the whitelist from disk. + */ + void reloadWhitelist(); + + /** + * Broadcast a message to all players. + *

+ * This is the same as calling {@link #broadcast(String, + * String)} to {@link #BROADCAST_CHANNEL_USERS} + * + * @param message the message + * @return the number of players + */ + int broadcastMessage(String message); + + // Paper start + /** + * Sends the component to the player + * + * @param component the components to send + */ + void broadcast(net.md_5.bungee.api.chat.BaseComponent component); + + /** + * Sends an array of components as a single message to the player + * + * @param components the components to send + */ + void broadcast(net.md_5.bungee.api.chat.BaseComponent... components); + // Paper end + + /** + * Gets the name of the update folder. The update folder is used to safely + * update plugins at the right moment on a plugin load. + *

+ * The update folder name is relative to the plugins folder. + * + * @return the name of the update folder + */ + String getUpdateFolder(); + + /** + * Gets the update folder. The update folder is used to safely update + * plugins at the right moment on a plugin load. + * + * @return the update folder + */ + File getUpdateFolderFile(); + + /** + * Gets the value of the connection throttle setting. + * + * @return the value of the connection throttle setting + */ + long getConnectionThrottle(); + + /** + * Gets default ticks per animal spawns value. + *

+ * Example Usage: + *

    + *
  • A value of 1 will mean the server will attempt to spawn monsters + * every tick. + *
  • A value of 400 will mean the server will attempt to spawn monsters + * every 400th tick. + *
  • A value below 0 will be reset back to Minecraft's default. + *
+ *

+ * Note: If set to 0, animal spawning will be disabled. We + * recommend using spawn-animals to control this instead. + *

+ * Minecraft default: 400. + * + * @return the default ticks per animal spawns value + */ + int getTicksPerAnimalSpawns(); + + /** + * Gets the default ticks per monster spawns value. + *

+ * Example Usage: + *

    + *
  • A value of 1 will mean the server will attempt to spawn monsters + * every tick. + *
  • A value of 400 will mean the server will attempt to spawn monsters + * every 400th tick. + *
  • A value below 0 will be reset back to Minecraft's default. + *
+ *

+ * Note: If set to 0, monsters spawning will be disabled. We + * recommend using spawn-monsters to control this instead. + *

+ * Minecraft default: 1. + * + * @return the default ticks per monsters spawn value + */ + int getTicksPerMonsterSpawns(); + + /** + * Gets a player object by the given username. + *

+ * This method may not return objects for offline players. + * + * @param name the name to look up + * @return a player if one was found, null otherwise + */ + Player getPlayer(String name); + + /** + * Gets the player with the exact given name, case insensitive. + * + * @param name Exact name of the player to retrieve + * @return a player object if one was found, null otherwise + */ + Player getPlayerExact(String name); + + /** + * Attempts to match any players with the given name, and returns a list + * of all possibly matches. + *

+ * This list is not sorted in any particular order. If an exact match is + * found, the returned list will only contain a single result. + * + * @param name the (partial) name to match + * @return list of all possible players + */ + List matchPlayer(String name); + + /** + * Gets the player with the given UUID. + * + * @param id UUID of the player to retrieve + * @return a player object if one was found, null otherwise + */ + Player getPlayer(UUID id); + + /** + * Gets the plugin manager for interfacing with plugins. + * + * @return a plugin manager for this Server instance + */ + PluginManager getPluginManager(); + + /** + * Gets the scheduler for managing scheduled events. + * + * @return a scheduling service for this server + */ + BukkitScheduler getScheduler(); + + /** + * Gets a services manager. + * + * @return s services manager + */ + ServicesManager getServicesManager(); + + /** + * Gets a list of all worlds on this server. + * + * @return a list of worlds + */ + List getWorlds(); + + /** + * Creates or loads a world with the given name using the specified + * options. + *

+ * If the world is already loaded, it will just return the equivalent of + * getWorld(creator.name()). + * + * @param creator the options to use when creating the world + * @return newly created or loaded world + */ + World createWorld(WorldCreator creator); + + /** + * Unloads a world with the given name. + * + * @param name Name of the world to unload + * @param save whether to save the chunks before unloading + * @return true if successful, false otherwise + */ + boolean unloadWorld(String name, boolean save); + + /** + * Unloads the given world. + * + * @param world the world to unload + * @param save whether to save the chunks before unloading + * @return true if successful, false otherwise + */ + boolean unloadWorld(World world, boolean save); + + /** + * Gets the world with the given name. + * + * @param name the name of the world to retrieve + * @return a world with the given name, or null if none exists + */ + World getWorld(String name); + + /** + * Gets the world from the given Unique ID. + * + * @param uid a unique-id of the world to retrieve + * @return a world with the given Unique ID, or null if none exists + */ + World getWorld(UUID uid); + + /** + * Gets the map from the given item ID. + * + * @param id the id of the map to get + * @return a map view if it exists, or null otherwise + * @deprecated Magic value + */ + @Deprecated + MapView getMap(short id); + + /** + * Create a new map with an automatically assigned ID. + * + * @param world the world the map will belong to + * @return a newly created map view + */ + MapView createMap(World world); + + /** + * Reloads the server, refreshing settings and plugin information. + */ + void reload(); + + void reloadConfigs(); + + /** + * Returns the primary logger associated with this server instance. + * + * @return Logger associated with this server + */ + Logger getLogger(); + + /** + * Gets a {@link PluginCommand} with the given name or alias. + * + * @param name the name of the command to retrieve + * @return a plugin command if found, null otherwise + */ + PluginCommand getPluginCommand(String name); + + /** + * Writes loaded players to disk. + */ + void savePlayers(); + + /** + * Dispatches a command on this server, and executes it if found. + * + * @param sender the apparent sender of the command + * @param commandLine the command + arguments. Example: test abc + * 123 + * @return returns false if no target is found + * @throws CommandException thrown when the executor for the given command + * fails with an unhandled exception + */ + boolean dispatchCommand(CommandSender sender, String commandLine) throws CommandException; + + /** + * Populates a given {@link ServerConfig} with values attributes to this + * server. + * + * @param config the server config to populate + */ + void configureDbConfig(ServerConfig config); + + /** + * Adds a recipe to the crafting manager. + * + * @param recipe the recipe to add + * @return true if the recipe was added, false if it wasn't for some + * reason + */ + boolean addRecipe(Recipe recipe); + + /** + * Get a list of all recipes for a given item. The stack size is ignored + * in comparisons. If the durability is -1, it will match any data value. + * + * @param result the item to match against recipe results + * @return a list of recipes with the given result + */ + List getRecipesFor(ItemStack result); + + /** + * Get an iterator through the list of crafting recipes. + * + * @return an iterator + */ + Iterator recipeIterator(); + + /** + * Clears the list of crafting recipes. + */ + void clearRecipes(); + + /** + * Resets the list of crafting recipes to the default. + */ + void resetRecipes(); + + /** + * Gets a list of command aliases defined in the server properties. + * + * @return a map of aliases to command names + */ + Map getCommandAliases(); + + /** + * Gets the radius, in blocks, around each worlds spawn point to protect. + * + * @return spawn radius, or 0 if none + */ + int getSpawnRadius(); + + /** + * Sets the radius, in blocks, around each worlds spawn point to protect. + * + * @param value new spawn radius, or 0 if none + */ + void setSpawnRadius(int value); + + /** + * Gets whether the Server is in online mode or not. + * + * @return true if the server authenticates clients, false otherwise + */ + boolean getOnlineMode(); + + /** + * Gets whether this server allows flying or not. + * + * @return true if the server allows flight, false otherwise + */ + boolean getAllowFlight(); + + /** + * Gets whether the server is in hardcore mode or not. + * + * @return true if the server mode is hardcore, false otherwise + */ + boolean isHardcore(); + + /** + * Gets whether to use vanilla (false) or exact behaviour (true). + * + *

    + *
  • Vanilla behaviour: check for collisions and move the player if + * needed. + *
  • Exact behaviour: spawn players exactly where they should be. + *
+ * + * @return true if exact location locations are used for spawning, false + * for vanilla collision detection or otherwise + * + * @deprecated non standard and unused feature. + */ + @Deprecated + boolean useExactLoginLocation(); + + /** + * Shutdowns the server, stopping everything. + */ + void shutdown(); + + /** + * Broadcasts the specified message to every user with the given + * permission name. + * + * @param message message to broadcast + * @param permission the required permission {@link Permissible + * permissibles} must have to receive the broadcast + * @return number of message recipients + */ + int broadcast(String message, String permission); + + /** + * Gets the player by the given name, regardless if they are offline or + * online. + *

+ * This method may involve a blocking web request to get the UUID for the + * given name. + *

+ * This will return an object even if the player does not exist. To this + * method, all players will exist. + * + * @deprecated Persistent storage of users should be by UUID as names are no longer + * unique past a single session. + * @param name the name the player to retrieve + * @return an offline player + * @see #getOfflinePlayer(UUID) + */ + @Deprecated + OfflinePlayer getOfflinePlayer(String name); + + /** + * Gets the player by the given UUID, regardless if they are offline or + * online. + *

+ * This will return an object even if the player does not exist. To this + * method, all players will exist. + * + * @param id the UUID of the player to retrieve + * @return an offline player + */ + OfflinePlayer getOfflinePlayer(UUID id); + + /** + * Gets a set containing all current IPs that are banned. + * + * @return a set containing banned IP addresses + */ + Set getIPBans(); + + /** + * Bans the specified address from the server. + * + * @param address the IP address to ban + */ + void banIP(String address); + + /** + * Unbans the specified address from the server. + * + * @param address the IP address to unban + */ + void unbanIP(String address); + + /** + * Gets a set containing all banned players. + * + * @return a set containing banned players + */ + Set getBannedPlayers(); + + /** + * Gets a ban list for the supplied type. + *

+ * Bans by name are no longer supported and this method will return + * null when trying to request them. The replacement is bans by UUID. + * + * @param type the type of list to fetch, cannot be null + * @return a ban list of the specified type + */ + BanList getBanList(BanList.Type type); + + /** + * Gets a set containing all player operators. + * + * @return a set containing player operators + */ + Set getOperators(); + + /** + * Gets the default {@link GameMode} for new players. + * + * @return the default game mode + */ + GameMode getDefaultGameMode(); + + /** + * Sets the default {@link GameMode} for new players. + * + * @param mode the new game mode + */ + void setDefaultGameMode(GameMode mode); + + /** + * Gets a {@link ConsoleCommandSender} that may be used as an input source + * for this server. + * + * @return a console command sender + */ + ConsoleCommandSender getConsoleSender(); + + /** + * Gets the folder that contains all of the various {@link World}s. + * + * @return folder that contains all worlds + */ + File getWorldContainer(); + + /** + * Gets every player that has ever played on this server. + * + * @return an array containing all previous players + */ + OfflinePlayer[] getOfflinePlayers(); + + /** + * Gets the {@link Messenger} responsible for this server. + * + * @return messenger responsible for this server + */ + Messenger getMessenger(); + + /** + * Gets the {@link HelpMap} providing help topics for this server. + * + * @return a help map for this server + */ + HelpMap getHelpMap(); + + /** + * Creates an empty inventory of the specified type. If the type is {@link + * InventoryType#CHEST}, the new inventory has a size of 27; otherwise the + * new inventory has the normal size for its type. + * + * @param owner the holder of the inventory, or null to indicate no holder + * @param type the type of inventory to create + * @return a new inventory + */ + Inventory createInventory(InventoryHolder owner, InventoryType type); + + /** + * Creates an empty inventory with the specified type and title. If the type + * is {@link InventoryType#CHEST}, the new inventory has a size of 27; + * otherwise the new inventory has the normal size for its type.
+ * It should be noted that some inventory types do not support titles and + * may not render with said titles on the Minecraft client. + * + * @param owner The holder of the inventory; can be null if there's no holder. + * @param type The type of inventory to create. + * @param title The title of the inventory, to be displayed when it is viewed. + * @return The new inventory. + */ + Inventory createInventory(InventoryHolder owner, InventoryType type, String title); + + /** + * Creates an empty inventory of type {@link InventoryType#CHEST} with the + * specified size. + * + * @param owner the holder of the inventory, or null to indicate no holder + * @param size a multiple of 9 as the size of inventory to create + * @return a new inventory + * @throws IllegalArgumentException if the size is not a multiple of 9 + */ + Inventory createInventory(InventoryHolder owner, int size) throws IllegalArgumentException; + + /** + * Creates an empty inventory of type {@link InventoryType#CHEST} with the + * specified size and title. + * + * @param owner the holder of the inventory, or null to indicate no holder + * @param size a multiple of 9 as the size of inventory to create + * @param title the title of the inventory, displayed when inventory is + * viewed + * @return a new inventory + * @throws IllegalArgumentException if the size is not a multiple of 9 + */ + Inventory createInventory(InventoryHolder owner, int size, String title) throws IllegalArgumentException; + + /** + * Gets user-specified limit for number of monsters that can spawn in a + * chunk. + * + * @return the monster spawn limit + */ + int getMonsterSpawnLimit(); + + /** + * Gets user-specified limit for number of animals that can spawn in a + * chunk. + * + * @return the animal spawn limit + */ + int getAnimalSpawnLimit(); + + /** + * Gets user-specified limit for number of water animals that can spawn in + * a chunk. + * + * @return the water animal spawn limit + */ + int getWaterAnimalSpawnLimit(); + + /** + * Gets user-specified limit for number of ambient mobs that can spawn in + * a chunk. + * + * @return the ambient spawn limit + */ + int getAmbientSpawnLimit(); + + /** + * Checks the current thread against the expected primary thread for the + * server. + *

+ * Note: this method should not be used to indicate the current + * synchronized state of the runtime. A current thread matching the main + * thread indicates that it is synchronized, but a mismatch does not + * preclude the same assumption. + * + * @return true if the current thread matches the expected primary thread, + * false otherwise + */ + boolean isPrimaryThread(); + + /** + * Gets the message that is displayed on the server list. + * + * @return the servers MOTD + */ + String getMotd(); + + /** + * Gets the default message that is displayed when the server is stopped. + * + * @return the shutdown message + */ + String getShutdownMessage(); + + /** + * Gets the current warning state for the server. + * + * @return the configured warning state + */ + WarningState getWarningState(); + + /** + * Gets the instance of the item factory (for {@link ItemMeta}). + * + * @return the item factory + * @see ItemFactory + */ + ItemFactory getItemFactory(); + + /** + * Gets the instance of the scoreboard manager. + *

+ * This will only exist after the first world has loaded. + * + * @return the scoreboard manager or null if no worlds are loaded. + */ + ScoreboardManager getScoreboardManager(); + + /** + * Gets an instance of the server's default server-icon. + * + * @return the default server-icon; null values may be used by the + * implementation to indicate no defined icon, but this behavior is + * not guaranteed + */ + CachedServerIcon getServerIcon(); + + /** + * Loads an image from a file, and returns a cached image for the specific + * server-icon. + *

+ * Size and type are implementation defined. An incompatible file is + * guaranteed to throw an implementation-defined {@link Exception}. + * + * @param file the file to load the from + * @throws IllegalArgumentException if image is null + * @throws Exception if the image does not meet current server server-icon + * specifications + * @return a cached server-icon that can be used for a {@link + * ServerListPingEvent#setServerIcon(CachedServerIcon)} + */ + CachedServerIcon loadServerIcon(File file) throws IllegalArgumentException, Exception; + + /** + * Creates a cached server-icon for the specific image. + *

+ * Size and type are implementation defined. An incompatible file is + * guaranteed to throw an implementation-defined {@link Exception}. + * + * @param image the image to use + * @throws IllegalArgumentException if image is null + * @throws Exception if the image does not meet current server + * server-icon specifications + * @return a cached server-icon that can be used for a {@link + * ServerListPingEvent#setServerIcon(CachedServerIcon)} + */ + CachedServerIcon loadServerIcon(BufferedImage image) throws IllegalArgumentException, Exception; + + /** + * Set the idle kick timeout. Any players idle for the specified amount of + * time will be automatically kicked. + *

+ * A value of 0 will disable the idle kick timeout. + * + * @param threshold the idle timeout in minutes + */ + void setIdleTimeout(int threshold); + + /** + * Gets the idle kick timeout. + * + * @return the idle timeout in minutes + */ + int getIdleTimeout(); + + /** + * Create a ChunkData for use in a generator. + * + * See {@link ChunkGenerator#generateChunkData(World, java.util.Random, int, int, ChunkGenerator.BiomeGrid)} + * + * @param world the world to create the ChunkData for + * @return a new ChunkData for the world + * + */ + ChunkGenerator.ChunkData createChunkData(World world); + + /** + * @see UnsafeValues + * @return the unsafe values instance + */ + @Deprecated + UnsafeValues getUnsafe(); + + // Paper start + /** + * Gets the active {@link CommandMap}. + * + * @return the active command map + */ + CommandMap getCommandMap(); + // Paper end + + class Spigot + { + @Deprecated + public org.bukkit.configuration.file.YamlConfiguration getConfig() + { + throw new UnsupportedOperationException( "Not supported yet." ); + } + + public org.bukkit.configuration.file.YamlConfiguration getBukkitConfig() + { + throw new UnsupportedOperationException( "Not supported yet." ); + } + + public org.bukkit.configuration.file.YamlConfiguration getSpigotConfig() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public org.bukkit.configuration.file.YamlConfiguration getPaperSpigotConfig() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + /** + * Sends the component to the player + * + * @param component the components to send + */ + public void broadcast(net.md_5.bungee.api.chat.BaseComponent component) { + throw new UnsupportedOperationException("Not supported yet."); + } + + /** + * Sends an array of components as a single message to the player + * + * @param components the components to send + */ + public void broadcast(net.md_5.bungee.api.chat.BaseComponent... components) { + throw new UnsupportedOperationException("Not supported yet."); + } + + /** + * Restart the server. If the server administrator has not configured restarting, the server will stop. + */ + public void restart() { + throw new UnsupportedOperationException("Not supported yet."); + } + + // PaperSpigot start - Add getTPS method + public double[] getTPS() + { + throw new UnsupportedOperationException( "Not supported yet." ); + } + // PaperSpigot end + } + + Spigot spigot(); +} diff --git a/azurite-api/src/main/java/org/bukkit/SkullType.java b/azurite-api/src/main/java/org/bukkit/SkullType.java new file mode 100644 index 0000000..5854ad4 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/SkullType.java @@ -0,0 +1,12 @@ +package org.bukkit; + +/** + * Represents the different types of skulls. + */ +public enum SkullType { + SKELETON, + WITHER, + ZOMBIE, + PLAYER, + CREEPER +} diff --git a/azurite-api/src/main/java/org/bukkit/Sound.java b/azurite-api/src/main/java/org/bukkit/Sound.java new file mode 100644 index 0000000..281be30 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/Sound.java @@ -0,0 +1,271 @@ +package org.bukkit; + +/** + * An Enum of Sounds the server is able to send to players. + *

+ * WARNING: At any time, sounds may be added/removed from this Enum or even + * MineCraft itself! There is no guarantee the sounds will play. There is no + * guarantee values will not be removed from this Enum. As such, you should + * not depend on the ordinal values of this class. + */ +public enum Sound { + AMBIENCE_CAVE, + AMBIENCE_RAIN, + AMBIENCE_THUNDER, + ANVIL_BREAK, + ANVIL_LAND, + ANVIL_USE, + ARROW_HIT, + BURP, + CHEST_CLOSE, + CHEST_OPEN, + CLICK, + DOOR_CLOSE, + DOOR_OPEN, + DRINK, + EAT, + EXPLODE, + FALL_BIG, + FALL_SMALL, + FIRE, + FIRE_IGNITE, + FIZZ, + FUSE, + GLASS, + HURT_FLESH, + ITEM_BREAK, + ITEM_PICKUP, + LAVA, + LAVA_POP, + LEVEL_UP, + MINECART_BASE, + MINECART_INSIDE, + NOTE_BASS, + NOTE_PIANO, + NOTE_BASS_DRUM, + NOTE_STICKS, + NOTE_BASS_GUITAR, + NOTE_SNARE_DRUM, + NOTE_PLING, + ORB_PICKUP, + PISTON_EXTEND, + PISTON_RETRACT, + PORTAL, + PORTAL_TRAVEL, + PORTAL_TRIGGER, + SHOOT_ARROW, + SPLASH, + SPLASH2, + STEP_GRASS, + STEP_GRAVEL, + STEP_LADDER, + STEP_SAND, + STEP_SNOW, + STEP_STONE, + STEP_WOOD, + STEP_WOOL, + SWIM, + WATER, + WOOD_CLICK, + // Mob sounds + BAT_DEATH, + BAT_HURT, + BAT_IDLE, + BAT_LOOP, + BAT_TAKEOFF, + BLAZE_BREATH, + BLAZE_DEATH, + BLAZE_HIT, + CAT_HISS, + CAT_HIT, + CAT_MEOW, + CAT_PURR, + CAT_PURREOW, + CHICKEN_IDLE, + CHICKEN_HURT, + CHICKEN_EGG_POP, + CHICKEN_WALK, + COW_IDLE, + COW_HURT, + COW_WALK, + CREEPER_HISS, + CREEPER_DEATH, + ENDERDRAGON_DEATH, + ENDERDRAGON_GROWL, + ENDERDRAGON_HIT, + ENDERDRAGON_WINGS, + ENDERMAN_DEATH, + ENDERMAN_HIT, + ENDERMAN_IDLE, + ENDERMAN_TELEPORT, + ENDERMAN_SCREAM, + ENDERMAN_STARE, + GHAST_SCREAM, + GHAST_SCREAM2, + GHAST_CHARGE, + GHAST_DEATH, + GHAST_FIREBALL, + GHAST_MOAN, + IRONGOLEM_DEATH, + IRONGOLEM_HIT, + IRONGOLEM_THROW, + IRONGOLEM_WALK, + MAGMACUBE_WALK, + MAGMACUBE_WALK2, + MAGMACUBE_JUMP, + PIG_IDLE, + PIG_DEATH, + PIG_WALK, + SHEEP_IDLE, + SHEEP_SHEAR, + SHEEP_WALK, + SILVERFISH_HIT, + SILVERFISH_KILL, + SILVERFISH_IDLE, + SILVERFISH_WALK, + SKELETON_IDLE, + SKELETON_DEATH, + SKELETON_HURT, + SKELETON_WALK, + SLIME_ATTACK, + SLIME_WALK, + SLIME_WALK2, + SPIDER_IDLE, + SPIDER_DEATH, + SPIDER_WALK, + WITHER_DEATH, + WITHER_HURT, + WITHER_IDLE, + WITHER_SHOOT, + WITHER_SPAWN, + WOLF_BARK, + WOLF_DEATH, + WOLF_GROWL, + WOLF_HOWL, + WOLF_HURT, + WOLF_PANT, + WOLF_SHAKE, + WOLF_WALK, + WOLF_WHINE, + ZOMBIE_METAL, + ZOMBIE_WOOD, + ZOMBIE_WOODBREAK, + ZOMBIE_IDLE, + ZOMBIE_DEATH, + ZOMBIE_HURT, + ZOMBIE_INFECT, + ZOMBIE_UNFECT, + ZOMBIE_REMEDY, + ZOMBIE_WALK, + ZOMBIE_PIG_IDLE, + ZOMBIE_PIG_ANGRY, + ZOMBIE_PIG_DEATH, + ZOMBIE_PIG_HURT, + // Dig Sounds + DIG_WOOL, + DIG_GRASS, + DIG_GRAVEL, + DIG_SAND, + DIG_SNOW, + DIG_STONE, + DIG_WOOD, + // Fireworks + FIREWORK_BLAST, + FIREWORK_BLAST2, + FIREWORK_LARGE_BLAST, + FIREWORK_LARGE_BLAST2, + FIREWORK_TWINKLE, + FIREWORK_TWINKLE2, + FIREWORK_LAUNCH, + SUCCESSFUL_HIT, + // Horses + HORSE_ANGRY, + HORSE_ARMOR, + HORSE_BREATHE, + HORSE_DEATH, + HORSE_GALLOP, + HORSE_HIT, + HORSE_IDLE, + HORSE_JUMP, + HORSE_LAND, + HORSE_SADDLE, + HORSE_SOFT, + HORSE_WOOD, + DONKEY_ANGRY, + DONKEY_DEATH, + DONKEY_HIT, + DONKEY_IDLE, + HORSE_SKELETON_DEATH, + HORSE_SKELETON_HIT, + HORSE_SKELETON_IDLE, + HORSE_ZOMBIE_DEATH, + HORSE_ZOMBIE_HIT, + HORSE_ZOMBIE_IDLE, + // Villager + VILLAGER_DEATH, + VILLAGER_HAGGLE, + VILLAGER_HIT, + VILLAGER_IDLE, + VILLAGER_NO, + VILLAGER_YES, + // Beanes start - add missing sound + UI_BUTTON_CLICK, + RECORD_11, + RECORD_13, + RECORD_BLOCKS, + RECORD_CAT, + RECORD_CHIRP, + RECORD_FAR, + RECORD_MALL, + RECORD_MELLOHI, + RECORD_STAL, + RECORD_STRAD, + RECORD_WAIT, + RECORD_WARD, + + MUSIC_CREATIVE, + MUSIC_CREDITS, + MUSIC_DRAGON, + MUSIC_END, + MUSIC_GAME, + MUSIC_MENU, + MUSIC_NETHER, + + ITEM_FIRECHARGE_USE, + + + GUARDIAN_ATTACK, + GUARDIAN_IDLE, + GUARDIAN_IDLE_LAND, + GUARDIAN_IDLE_ELDER, + GUARDIAN_HIT, + GUARDIAN_HIT_LAND, + GUARDIAN_HIT_ELDER, + GUARDIAN_DEATH, + GUARDIAN_DEATH_LAND, + GUARDIAN_DEATH_ELDER, + GUARDIAN_FLOP, + GUARDIAN_CURSE, + + RABBIT_DEATH, + RABBIT_IDLE, + RABBIT_HURT, + RABBIT_HOP, + + HOSTILE_DIE, + HOSTILE_HURT, + HOSTILE_HURT_FALL_BIG, + HOSTILE_HURT_FALL_SMALL, + HOSTILE_SWIM, + HOSTILE_SWIM_SPLASH, + NEUTRAL_DIE, + PLAYER_DIE, + PLAYER_HURT, + PLAYER_HURT_FALL_BIG, + PLAYER_HURT_FALL_SMALL, + PLAYER_SWIM, + PLAYER_SWIM_SPLASH, + POTION_SMASH, + TNT_PRIMED + // Beanes end +} diff --git a/azurite-api/src/main/java/org/bukkit/Statistic.java b/azurite-api/src/main/java/org/bukkit/Statistic.java new file mode 100644 index 0000000..111002d --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/Statistic.java @@ -0,0 +1,133 @@ +package org.bukkit; + +/** + * Represents a countable statistic, which is tracked by the server. + */ +public enum Statistic { + DAMAGE_DEALT, + DAMAGE_TAKEN, + DEATHS, + MOB_KILLS, + PLAYER_KILLS, + FISH_CAUGHT, + ANIMALS_BRED, + TREASURE_FISHED, + JUNK_FISHED, + LEAVE_GAME, + JUMP, + DROP, + PLAY_ONE_TICK, + WALK_ONE_CM, + SWIM_ONE_CM, + FALL_ONE_CM, + CLIMB_ONE_CM, + FLY_ONE_CM, + DIVE_ONE_CM, + MINECART_ONE_CM, + BOAT_ONE_CM, + PIG_ONE_CM, + HORSE_ONE_CM, + SPRINT_ONE_CM, + CROUCH_ONE_CM, + MINE_BLOCK(Type.BLOCK), + USE_ITEM(Type.ITEM), + BREAK_ITEM(Type.ITEM), + CRAFT_ITEM(Type.ITEM), + KILL_ENTITY(Type.ENTITY), + ENTITY_KILLED_BY(Type.ENTITY), + TIME_SINCE_DEATH, + TALKED_TO_VILLAGER, + TRADED_WITH_VILLAGER, + CAKE_SLICES_EATEN, + CAULDRON_FILLED, + CAULDRON_USED, + ARMOR_CLEANED, + BANNER_CLEANED, + BREWINGSTAND_INTERACTION, + BEACON_INTERACTION, + DROPPER_INSPECTED, + HOPPER_INSPECTED, + DISPENSER_INSPECTED, + NOTEBLOCK_PLAYED, + NOTEBLOCK_TUNED, + FLOWER_POTTED, + TRAPPED_CHEST_TRIGGERED, + ENDERCHEST_OPENED, + ITEM_ENCHANTED, + RECORD_PLAYED, + FURNACE_INTERACTION, + CRAFTING_TABLE_INTERACTION, + CHEST_OPENED; + + private final Type type; + + Statistic() { + this(Type.UNTYPED); + } + + Statistic(Type type) { + this.type = type; + } + + /** + * Gets the type of this statistic. + * + * @return the type of this statistic + */ + public Type getType() { + return type; + } + + /** + * Checks if this is a substatistic. + *

+ * A substatistic exists en masse for each block, item, or entitytype, depending on + * {@link #getType()}. + *

+ * This is a redundant method and equivalent to checking + * getType() != Type.UNTYPED + * + * @return true if this is a substatistic + */ + public boolean isSubstatistic() { + return type != Type.UNTYPED; + } + + /** + * Checks if this is a substatistic dealing with blocks. + *

+ * This is a redundant method and equivalent to checking + * getType() == Type.BLOCK + * + * @return true if this deals with blocks + */ + public boolean isBlock() { + return type == Type.BLOCK; + } + + /** + * The type of statistic. + * + */ + public enum Type { + /** + * Statistics of this type do not require a qualifier. + */ + UNTYPED, + + /** + * Statistics of this type require an Item Material qualifier. + */ + ITEM, + + /** + * Statistics of this type require a Block Material qualifier. + */ + BLOCK, + + /** + * Statistics of this type require an EntityType qualifier. + */ + ENTITY + } +} diff --git a/azurite-api/src/main/java/org/bukkit/TravelAgent.java b/azurite-api/src/main/java/org/bukkit/TravelAgent.java new file mode 100644 index 0000000..facd829 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/TravelAgent.java @@ -0,0 +1,94 @@ +package org.bukkit; + +/** + * The Travel Agent handles the creation and the research of Nether and End + * portals when Entities try to use one. + *

+ * It is used in {@link org.bukkit.event.entity.EntityPortalEvent} and in + * {@link org.bukkit.event.player.PlayerPortalEvent} to help developers + * reproduce and/or modify Vanilla behaviour. + */ +public interface TravelAgent { + + /** + * Set the Block radius to search in for available portals. + * + * @param radius the radius in which to search for a portal from the + * location + * @return this travel agent + */ + TravelAgent setSearchRadius(int radius); + + /** + * Gets the search radius value for finding an available portal. + * + * @return the currently set search radius + */ + int getSearchRadius(); + + /** + * Sets the maximum radius from the given location to create a portal. + * + * @param radius the radius in which to create a portal from the location + * @return this travel agent + */ + TravelAgent setCreationRadius(int radius); + + /** + * Gets the maximum radius from the given location to create a portal. + * + * @return the currently set creation radius + */ + int getCreationRadius(); + + /** + * Returns whether the TravelAgent will attempt to create a destination + * portal or not. + * + * @return whether the TravelAgent should create a destination portal or + * not + */ + boolean getCanCreatePortal(); + + /** + * Sets whether the TravelAgent should attempt to create a destination + * portal or not. + * + * @param create Sets whether the TravelAgent should create a destination + * portal or not + */ + void setCanCreatePortal(boolean create); + + /** + * Attempt to find a portal near the given location, if a portal is not + * found it will attempt to create one. + * + * @param location the location where the search for a portal should begin + * @return the location of a portal which has been found or returns the + * location passed to the method if unsuccessful + * @see #createPortal(Location) + */ + Location findOrCreate(Location location); + + /** + * Attempt to find a portal near the given location. + * + * @param location the desired location of the portal + * @return the location of the nearest portal to the location + */ + Location findPortal(Location location); + + /** + * Attempt to create a portal near the given location. + *

+ * In the case of a Nether portal teleportation, this will attempt to + * create a Nether portal. + *

+ * In the case of an Ender portal teleportation, this will (re-)create the + * obsidian platform and clean blocks above it. + * + * @param location the desired location of the portal + * @return true if a portal was successfully created + */ + boolean createPortal(Location location); +} diff --git a/azurite-api/src/main/java/org/bukkit/TreeSpecies.java b/azurite-api/src/main/java/org/bukkit/TreeSpecies.java new file mode 100644 index 0000000..0c9eb4d --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/TreeSpecies.java @@ -0,0 +1,74 @@ +package org.bukkit; + +import com.google.common.collect.Maps; + +import java.util.Map; + +/** + * Represents the different species of trees regardless of size. + */ +public enum TreeSpecies { + + /** + * Represents the common tree species. + */ + GENERIC(0x0), + /** + * Represents the darker barked/leaved tree species. + */ + REDWOOD(0x1), + /** + * Represents birches. + */ + BIRCH(0x2), + /** + * Represents jungle trees. + */ + JUNGLE(0x3), + /** + * Represents acacia trees. + */ + ACACIA(0x4), + /** + * Represents dark oak trees. + */ + DARK_OAK(0x5), + ; + + private final byte data; + private final static Map BY_DATA = Maps.newHashMap(); + + TreeSpecies(final int data) { + this.data = (byte) data; + } + + /** + * Gets the associated data value representing this species + * + * @return A byte containing the data value of this tree species + * @deprecated Magic value + */ + @Deprecated + public byte getData() { + return data; + } + + /** + * Gets the TreeSpecies with the given data value + * + * @param data Data value to fetch + * @return The {@link TreeSpecies} representing the given value, or null + * if it doesn't exist + * @deprecated Magic value + */ + @Deprecated + public static TreeSpecies getByData(final byte data) { + return BY_DATA.get(data); + } + + static { + for (TreeSpecies species : values()) { + BY_DATA.put(species.data, species); + } + } +} diff --git a/azurite-api/src/main/java/org/bukkit/TreeType.java b/azurite-api/src/main/java/org/bukkit/TreeType.java new file mode 100644 index 0000000..5a5c4d9 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/TreeType.java @@ -0,0 +1,72 @@ +package org.bukkit; + +/** + * Tree and organic structure types. + */ +public enum TreeType { + + /** + * Regular tree, no branches + */ + TREE, + /** + * Regular tree, extra tall with branches + */ + BIG_TREE, + /** + * Redwood tree, shaped like a pine tree + */ + REDWOOD, + /** + * Tall redwood tree with just a few leaves at the top + */ + TALL_REDWOOD, + /** + * Birch tree + */ + BIRCH, + /** + * Standard jungle tree; 4 blocks wide and tall + */ + JUNGLE, + /** + * Smaller jungle tree; 1 block wide + */ + SMALL_JUNGLE, + /** + * Jungle tree with cocoa plants; 1 block wide + */ + COCOA_TREE, + /** + * Small bush that grows in the jungle + */ + JUNGLE_BUSH, + /** + * Big red mushroom; short and fat + */ + RED_MUSHROOM, + /** + * Big brown mushroom; tall and umbrella-like + */ + BROWN_MUSHROOM, + /** + * Swamp tree (regular with vines on the side) + */ + SWAMP, + /** + * Acacia tree. + */ + ACACIA, + /** + * Dark Oak tree. + */ + DARK_OAK, + /** + * Mega redwood tree; 4 blocks wide and tall + */ + MEGA_REDWOOD, + /** + * Tall birch tree + */ + TALL_BIRCH, +} diff --git a/azurite-api/src/main/java/org/bukkit/UnsafeValues.java b/azurite-api/src/main/java/org/bukkit/UnsafeValues.java new file mode 100644 index 0000000..eee2bb3 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/UnsafeValues.java @@ -0,0 +1,37 @@ +package org.bukkit; + +import org.bukkit.inventory.ItemStack; + +import java.util.List; + +/** + * This interface provides value conversions that may be specific to a + * runtime, or have arbitrary meaning (read: magic values). + *

+ * Their existence and behavior is not guaranteed across future versions. They + * may be poorly named, throw exceptions, have misleading parameters, or any + * other bad programming practice. + *

+ * This interface is unsupported and only for internal use. + * + * @deprecated Unsupported {@literal &} internal use only + */ +@Deprecated +public interface UnsafeValues { + + Material getMaterialFromInternalName(String name); + + List tabCompleteInternalMaterialName(String token, List completions); + + ItemStack modifyItemStack(ItemStack stack, String arguments); + + Statistic getStatisticFromInternalName(String name); + + Achievement getAchievementFromInternalName(String name); + + List tabCompleteInternalStatisticOrAchievementName(String token, List completions); + + byte[] serializeItem(ItemStack item); + + ItemStack deserializeItem(byte[] data); +} diff --git a/azurite-api/src/main/java/org/bukkit/Utility.java b/azurite-api/src/main/java/org/bukkit/Utility.java new file mode 100644 index 0000000..da66853 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/Utility.java @@ -0,0 +1,18 @@ +package org.bukkit; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * This annotation indicates a method (and sometimes constructor) will chain + * its internal operations. + *

+ * This is solely meant for identifying methods that don't need to be + * overridden / handled manually. + */ +@Target({ElementType.CONSTRUCTOR, ElementType.METHOD}) +@Retention(RetentionPolicy.SOURCE) +public @interface Utility { +} diff --git a/azurite-api/src/main/java/org/bukkit/Warning.java b/azurite-api/src/main/java/org/bukkit/Warning.java new file mode 100644 index 0000000..2741cc4 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/Warning.java @@ -0,0 +1,109 @@ +package org.bukkit; + +import com.google.common.collect.ImmutableMap; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import java.util.Map; + +/** + * This designates the warning state for a specific item. + *

+ * When the server settings dictate 'default' warnings, warnings are printed + * if the {@link #value()} is true. + */ +@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +public @interface Warning { + + /** + * This represents the states that server verbose for warnings may be. + */ + enum WarningState { + + /** + * Indicates all warnings should be printed for deprecated items. + */ + ON, + /** + * Indicates no warnings should be printed for deprecated items. + */ + OFF, + /** + * Indicates each warning would default to the configured {@link + * Warning} annotation, or always if annotation not found. + */ + DEFAULT; + + private static final Map values = ImmutableMap.builder() + .put("off", OFF) + .put("false", OFF) + .put("f", OFF) + .put("no", OFF) + .put("n", OFF) + .put("on", ON) + .put("true", ON) + .put("t", ON) + .put("yes", ON) + .put("y", ON) + .put("", DEFAULT) + .put("d", DEFAULT) + .put("default", DEFAULT) + .build(); + + /** + * This method checks the provided warning should be printed for this + * state + * + * @param warning The warning annotation added to a deprecated item + * @return

    + *
  • ON is always True + *
  • OFF is always false + *
  • DEFAULT is false if and only if annotation is not null and + * specifies false for {@link Warning#value()}, true otherwise. + *
+ */ + public boolean printFor(Warning warning) { + if (this == DEFAULT) { + return warning == null || warning.value(); + } + return this == ON; + } + + /** + * This method returns the corresponding warning state for the given + * string value. + * + * @param value The string value to check + * @return {@link #DEFAULT} if not found, or the respective + * WarningState + */ + public static WarningState value(final String value) { + if (value == null) { + return DEFAULT; + } + WarningState state = values.get(value.toLowerCase()); + if (state == null) { + return DEFAULT; + } + return state; + } + } + + /** + * This sets if the deprecation warnings when registering events gets + * printed when the setting is in the default state. + * + * @return false normally, or true to encourage warning printout + */ + boolean value() default false; + + /** + * This can provide detailed information on why the event is deprecated. + * + * @return The reason an event is deprecated + */ + String reason() default ""; +} diff --git a/azurite-api/src/main/java/org/bukkit/WeatherType.java b/azurite-api/src/main/java/org/bukkit/WeatherType.java new file mode 100644 index 0000000..3c96c67 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/WeatherType.java @@ -0,0 +1,16 @@ +package org.bukkit; + +/** + * An enum of all current weather types + */ +public enum WeatherType { + + /** + * Raining or snowing depending on biome. + */ + DOWNFALL, + /** + * Clear weather, clouds but no rain. + */ + CLEAR, +} diff --git a/azurite-api/src/main/java/org/bukkit/World.java b/azurite-api/src/main/java/org/bukkit/World.java new file mode 100644 index 0000000..a171490 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/World.java @@ -0,0 +1,1326 @@ +package org.bukkit; + +import org.bukkit.block.Biome; +import org.bukkit.block.Block; +import org.bukkit.entity.*; +import org.bukkit.generator.BlockPopulator; +import org.bukkit.generator.ChunkGenerator; +import org.bukkit.inventory.ItemStack; +import org.bukkit.metadata.Metadatable; +import org.bukkit.plugin.messaging.PluginMessageRecipient; +import org.bukkit.util.Vector; + +import java.io.File; +import java.util.*; + +/** + * Represents a world, which may contain entities, chunks and blocks + */ +public interface World extends PluginMessageRecipient, Metadatable { + + /** + * Gets the {@link Block} at the given coordinates + * + * @param x X-coordinate of the block + * @param y Y-coordinate of the block + * @param z Z-coordinate of the block + * @return Block at the given coordinates + * @see #getBlockTypeIdAt(int, int, int) Returns the current type ID of + * the block + */ + Block getBlockAt(int x, int y, int z); + + /** + * Gets the {@link Block} at the given {@link Location} + * + * @param location Location of the block + * @return Block at the given location + * @see #getBlockTypeIdAt(Location) Returns the current type ID + * of the block + */ + Block getBlockAt(Location location); + + /** + * Gets the block type ID at the given coordinates + * + * @param x X-coordinate of the block + * @param y Y-coordinate of the block + * @param z Z-coordinate of the block + * @return Type ID of the block at the given coordinates + * @see #getBlockAt(int, int, int) Returns a live Block object at the + * given location + * @deprecated Magic value + */ + @Deprecated + int getBlockTypeIdAt(int x, int y, int z); + + /** + * Gets the block type ID at the given {@link Location} + * + * @param location Location of the block + * @return Type ID of the block at the given location + * @see #getBlockAt(Location) Returns a live Block object at + * the given location + * @deprecated Magic value + */ + @Deprecated + int getBlockTypeIdAt(Location location); + + /** + * Gets the highest non-air coordinate at the given coordinates + * + * @param x X-coordinate of the blocks + * @param z Z-coordinate of the blocks + * @return Y-coordinate of the highest non-air block + */ + int getHighestBlockYAt(int x, int z); + + /** + * Gets the highest non-air coordinate at the given {@link Location} + * + * @param location Location of the blocks + * @return Y-coordinate of the highest non-air block + */ + int getHighestBlockYAt(Location location); + + /** + * Gets the highest non-empty block at the given coordinates + * + * @param x X-coordinate of the block + * @param z Z-coordinate of the block + * @return Highest non-empty block + */ + Block getHighestBlockAt(int x, int z); + + /** + * Gets the highest non-empty block at the given coordinates + * + * @param location Coordinates to get the highest block + * @return Highest non-empty block + */ + Block getHighestBlockAt(Location location); + + /** + * Gets the {@link Chunk} at the given coordinates + * + * @param x X-coordinate of the chunk + * @param z Z-coordinate of the chunk + * @return Chunk at the given coordinates + */ + Chunk getChunkAt(int x, int z); + + /** + * Gets the {@link Chunk} at the given {@link Location} + * + * @param location Location of the chunk + * @return Chunk at the given location + */ + Chunk getChunkAt(Location location); + + /** + * Gets the {@link Chunk} that contains the given {@link Block} + * + * @param block Block to get the containing chunk from + * @return The chunk that contains the given block + */ + Chunk getChunkAt(Block block); + + // PaperSpigot start - Async chunk load API + interface ChunkLoadCallback { + void onLoad(Chunk chunk); + } + void getChunkAtAsync(int x, int z, ChunkLoadCallback cb); + void getChunkAtAsync(Location location, ChunkLoadCallback cb); + void getChunkAtAsync(Block block, ChunkLoadCallback cb); + // PaperSpigot end + + /** + * Checks if the specified {@link Chunk} is loaded + * + * @param chunk The chunk to check + * @return true if the chunk is loaded, otherwise false + */ + boolean isChunkLoaded(Chunk chunk); + + /** + * Gets an array of all loaded {@link Chunk}s + * + * @return Chunk[] containing all loaded chunks + */ + Chunk[] getLoadedChunks(); + + /** + * Loads the specified {@link Chunk} + * + * @param chunk The chunk to load + */ + void loadChunk(Chunk chunk); + + /** + * Checks if the {@link Chunk} at the specified coordinates is loaded + * + * @param x X-coordinate of the chunk + * @param z Z-coordinate of the chunk + * @return true if the chunk is loaded, otherwise false + */ + boolean isChunkLoaded(int x, int z); + + /** + * Checks if the {@link Chunk} at the specified coordinates is loaded and + * in use by one or more players + * + * @param x X-coordinate of the chunk + * @param z Z-coordinate of the chunk + * @return true if the chunk is loaded and in use by one or more players, + * otherwise false + */ + boolean isChunkInUse(int x, int z); + + /** + * Loads the {@link Chunk} at the specified coordinates + *

+ * If the chunk does not exist, it will be generated. + *

+ * This method is analogous to {@link #loadChunk(int, int, boolean)} where + * generate is true. + * + * @param x X-coordinate of the chunk + * @param z Z-coordinate of the chunk + */ + void loadChunk(int x, int z); + + /** + * Loads the {@link Chunk} at the specified coordinates + * + * @param x X-coordinate of the chunk + * @param z Z-coordinate of the chunk + * @param generate Whether or not to generate a chunk if it doesn't + * already exist + * @return true if the chunk has loaded successfully, otherwise false + */ + boolean loadChunk(int x, int z, boolean generate); + + /** + * Safely unloads and saves the {@link Chunk} at the specified coordinates + *

+ * This method is analogous to {@link #unloadChunk(int, int, boolean, + * boolean)} where safe and saveis true + * + * @param chunk the chunk to unload + * @return true if the chunk has unloaded successfully, otherwise false + */ + boolean unloadChunk(Chunk chunk); + + /** + * Safely unloads and saves the {@link Chunk} at the specified coordinates + *

+ * This method is analogous to {@link #unloadChunk(int, int, boolean, + * boolean)} where safe and saveis true + * + * @param x X-coordinate of the chunk + * @param z Z-coordinate of the chunk + * @return true if the chunk has unloaded successfully, otherwise false + */ + boolean unloadChunk(int x, int z); + + /** + * Safely unloads and optionally saves the {@link Chunk} at the specified + * coordinates + *

+ * This method is analogous to {@link #unloadChunk(int, int, boolean, + * boolean)} where save is true + * + * @param x X-coordinate of the chunk + * @param z Z-coordinate of the chunk + * @param save Whether or not to save the chunk + * @return true if the chunk has unloaded successfully, otherwise false + */ + boolean unloadChunk(int x, int z, boolean save); + + /** + * Unloads and optionally saves the {@link Chunk} at the specified + * coordinates + * + * @param x X-coordinate of the chunk + * @param z Z-coordinate of the chunk + * @param save Controls whether the chunk is saved + * @param safe Controls whether to unload the chunk when players are + * nearby + * @return true if the chunk has unloaded successfully, otherwise false + */ + boolean unloadChunk(int x, int z, boolean save, boolean safe); + + /** + * Safely queues the {@link Chunk} at the specified coordinates for + * unloading + *

+ * This method is analogous to {@link #unloadChunkRequest(int, int, + * boolean)} where safe is true + * + * @param x X-coordinate of the chunk + * @param z Z-coordinate of the chunk + * @return true is the queue attempt was successful, otherwise false + */ + boolean unloadChunkRequest(int x, int z); + + /** + * Queues the {@link Chunk} at the specified coordinates for unloading + * + * @param x X-coordinate of the chunk + * @param z Z-coordinate of the chunk + * @param safe Controls whether to queue the chunk when players are nearby + * @return Whether the chunk was actually queued + */ + boolean unloadChunkRequest(int x, int z, boolean safe); + + /** + * Regenerates the {@link Chunk} at the specified coordinates + * + * @param x X-coordinate of the chunk + * @param z Z-coordinate of the chunk + * @return Whether the chunk was actually regenerated + */ + boolean regenerateChunk(int x, int z); + + /** + * Resends the {@link Chunk} to all clients + * + * @param x X-coordinate of the chunk + * @param z Z-coordinate of the chunk + * @return Whether the chunk was actually refreshed + * + * @deprecated This method is not guaranteed to work suitably across all client implementations. + */ + @Deprecated + boolean refreshChunk(int x, int z); + + /** + * Drops an item at the specified {@link Location} + * + * @param location Location to drop the item + * @param item ItemStack to drop + * @return ItemDrop entity created as a result of this method + */ + Item dropItem(Location location, ItemStack item); + + /** + * Drops an item at the specified {@link Location} with a random offset + * + * @param location Location to drop the item + * @param item ItemStack to drop + * @return ItemDrop entity created as a result of this method + */ + Item dropItemNaturally(Location location, ItemStack item); + + /** + * Creates an {@link Arrow} entity at the given {@link Location} + * + * @param location Location to spawn the arrow + * @param direction Direction to shoot the arrow in + * @param speed Speed of the arrow. A recommend speed is 0.6 + * @param spread Spread of the arrow. A recommend spread is 12 + * @return Arrow entity spawned as a result of this method + */ + Arrow spawnArrow(Location location, Vector direction, float speed, float spread); + + /** + * Creates a tree at the given {@link Location} + * + * @param location Location to spawn the tree + * @param type Type of the tree to create + * @return true if the tree was created successfully, otherwise false + */ + boolean generateTree(Location location, TreeType type); + + /** + * Creates a tree at the given {@link Location} + * + * @param loc Location to spawn the tree + * @param type Type of the tree to create + * @param delegate A class to call for each block changed as a result of + * this method + * @return true if the tree was created successfully, otherwise false + */ + boolean generateTree(Location loc, TreeType type, BlockChangeDelegate delegate); + + /** + * Creates a entity at the given {@link Location} + * + * @param loc The location to spawn the entity + * @param type The entity to spawn + * @return Resulting Entity of this method, or null if it was unsuccessful + */ + Entity spawnEntity(Location loc, EntityType type); + + /** + * Creates a creature at the given {@link Location} + * + * @param loc The location to spawn the creature + * @param type The creature to spawn + * @return Resulting LivingEntity of this method, or null if it was + * unsuccessful + * @deprecated Has issues spawning non LivingEntities. Use {@link + * #spawnEntity(Location, EntityType) spawnEntity} instead. + */ + @Deprecated + LivingEntity spawnCreature(Location loc, EntityType type); + + /** + * Creates a creature at the given {@link Location} + * + * @param loc The location to spawn the creature + * @param type The creature to spawn + * @return Resulting LivingEntity of this method, or null if it was + * unsuccessful + */ + @Deprecated + LivingEntity spawnCreature(Location loc, CreatureType type); + + /** + * Strikes lightning at the given {@link Location} + * + * @param loc The location to strike lightning + * @return The lightning entity. + */ + LightningStrike strikeLightning(Location loc); + + /** + * Strikes lightning at the given {@link Location} without doing damage + * + * @param loc The location to strike lightning + * @return The lightning entity. + */ + LightningStrike strikeLightningEffect(Location loc); + + /** + * Get a list of all entities in this World + * + * @return A List of all Entities currently residing in this world + */ + List getEntities(); + + /** + * Get a list of all living entities in this World + * + * @return A List of all LivingEntities currently residing in this world + */ + List getLivingEntities(); + + /** + * Get a collection of all entities in this World matching the given + * class/interface + * + * @param an entity subclass + * @param classes The classes representing the types of entity to match + * @return A List of all Entities currently residing in this world that + * match the given class/interface + */ + @Deprecated + Collection getEntitiesByClass(Class... classes); + + /** + * Get a collection of all entities in this World matching the given + * class/interface + * + * @param an entity subclass + * @param cls The class representing the type of entity to match + * @return A List of all Entities currently residing in this world that + * match the given class/interface + */ + Collection getEntitiesByClass(Class cls); + + /** + * Get a collection of all entities in this World matching any of the + * given classes/interfaces + * + * @param classes The classes representing the types of entity to match + * @return A List of all Entities currently residing in this world that + * match one or more of the given classes/interfaces + */ + Collection getEntitiesByClasses(Class... classes); + + /** + * Get a list of all players in this World + * + * @return A list of all Players currently residing in this world + */ + List getPlayers(); + + /** + * Returns a list of entities within a bounding box centered around a Location. + * + * Some implementations may impose artificial restrictions on the size of the search bounding box. + * + * @param location The center of the bounding box + * @param x 1/2 the size of the box along x axis + * @param y 1/2 the size of the box along y axis + * @param z 1/2 the size of the box along z axis + * @return the collection of entities near location. This will always be a non-null collection. + */ + Collection getNearbyEntities(Location location, double x, double y, double z); + + /** + * Gets the unique name of this world + * + * @return Name of this world + */ + String getName(); + + /** + * Gets the Unique ID of this world + * + * @return Unique ID of this world. + */ + UUID getUID(); + + /** + * Gets the default spawn {@link Location} of this world + * + * @return The spawn location of this world + */ + Location getSpawnLocation(); + + /** + * Sets the spawn location of the world + * + * @param x X coordinate + * @param y Y coordinate + * @param z Z coordinate + * @return True if it was successfully set. + */ + boolean setSpawnLocation(int x, int y, int z); + + /** + * Gets the relative in-game time of this world. + *

+ * The relative time is analogous to hours * 1000 + * + * @return The current relative time + * @see #getFullTime() Returns an absolute time of this world + */ + long getTime(); + + /** + * Sets the relative in-game time on the server. + *

+ * The relative time is analogous to hours * 1000 + *

+ * Note that setting the relative time below the current relative time + * will actually move the clock forward a day. If you require to rewind + * time, please see {@link #setFullTime(long)} + * + * @param time The new relative time to set the in-game time to (in + * hours*1000) + * @see #setFullTime(long) Sets the absolute time of this world + */ + void setTime(long time); + + /** + * Gets the full in-game time on this world + * + * @return The current absolute time + * @see #getTime() Returns a relative time of this world + */ + long getFullTime(); + + /** + * Sets the in-game time on the server + *

+ * Note that this sets the full time of the world, which may cause adverse + * effects such as breaking redstone clocks and any scheduled events + * + * @param time The new absolute time to set this world to + * @see #setTime(long) Sets the relative time of this world + */ + void setFullTime(long time); + + /** + * Returns whether the world has an ongoing storm. + * + * @return Whether there is an ongoing storm + */ + boolean hasStorm(); + + /** + * Set whether there is a storm. A duration will be set for the new + * current conditions. + * + * @param hasStorm Whether there is rain and snow + */ + void setStorm(boolean hasStorm); + + /** + * Get the remaining time in ticks of the current conditions. + * + * @return Time in ticks + */ + int getWeatherDuration(); + + /** + * Set the remaining time in ticks of the current conditions. + * + * @param duration Time in ticks + */ + void setWeatherDuration(int duration); + + /** + * Returns whether there is thunder. + * + * @return Whether there is thunder + */ + boolean isThundering(); + + /** + * Set whether it is thundering. + * + * @param thundering Whether it is thundering + */ + void setThundering(boolean thundering); + + /** + * Get the thundering duration. + * + * @return Duration in ticks + */ + int getThunderDuration(); + + /** + * Set the thundering duration. + * + * @param duration Duration in ticks + */ + void setThunderDuration(int duration); + + /** + * Creates explosion at given coordinates with given power + * + * @param x X coordinate + * @param y Y coordinate + * @param z Z coordinate + * @param power The power of explosion, where 4F is TNT + * @return false if explosion was canceled, otherwise true + */ + boolean createExplosion(double x, double y, double z, float power); + + /** + * Creates explosion at given coordinates with given power and optionally + * setting blocks on fire. + * + * @param x X coordinate + * @param y Y coordinate + * @param z Z coordinate + * @param power The power of explosion, where 4F is TNT + * @param setFire Whether or not to set blocks on fire + * @return false if explosion was canceled, otherwise true + */ + boolean createExplosion(double x, double y, double z, float power, boolean setFire); + + /** + * Creates explosion at given coordinates with given power and optionally + * setting blocks on fire or breaking blocks. + * + * @param x X coordinate + * @param y Y coordinate + * @param z Z coordinate + * @param power The power of explosion, where 4F is TNT + * @param setFire Whether or not to set blocks on fire + * @param breakBlocks Whether or not to have blocks be destroyed + * @return false if explosion was canceled, otherwise true + */ + boolean createExplosion(double x, double y, double z, float power, boolean setFire, boolean breakBlocks); + + /** + * Creates explosion at given coordinates with given power + * + * @param loc Location to blow up + * @param power The power of explosion, where 4F is TNT + * @return false if explosion was canceled, otherwise true + */ + boolean createExplosion(Location loc, float power); + + /** + * Creates explosion at given coordinates with given power and optionally + * setting blocks on fire. + * + * @param loc Location to blow up + * @param power The power of explosion, where 4F is TNT + * @param setFire Whether or not to set blocks on fire + * @return false if explosion was canceled, otherwise true + */ + boolean createExplosion(Location loc, float power, boolean setFire); + + /** + * Gets the {@link Environment} type of this world + * + * @return This worlds Environment type + */ + Environment getEnvironment(); + + /** + * Gets the Seed for this world. + * + * @return This worlds Seed + */ + long getSeed(); + + /** + * Gets the current PVP setting for this world. + * + * @return True if PVP is enabled + */ + boolean getPVP(); + + /** + * Sets the PVP setting for this world. + * + * @param pvp True/False whether PVP should be Enabled. + */ + void setPVP(boolean pvp); + + /** + * Gets the chunk generator for this world + * + * @return ChunkGenerator associated with this world + */ + ChunkGenerator getGenerator(); + + /** + * Saves world to disk + */ + void save(); + + /** + * Gets a list of all applied {@link BlockPopulator}s for this World + * + * @return List containing any or none BlockPopulators + */ + List getPopulators(); + + /** + * Spawn an entity of a specific class at the given {@link Location} + * + * @param location the {@link Location} to spawn the entity at + * @param clazz the class of the {@link Entity} to spawn + * @param the class of the {@link Entity} to spawn + * @return an instance of the spawned {@link Entity} + * @throws IllegalArgumentException if either parameter is null or the + * {@link Entity} requested cannot be spawned + */ + T spawn(Location location, Class clazz) throws IllegalArgumentException; + + /** + * Spawn a {@link FallingBlock} entity at the given {@link Location} of + * the specified {@link Material}. The material dictates what is falling. + * When the FallingBlock hits the ground, it will place that block. + *

+ * The Material must be a block type, check with {@link Material#isBlock() + * material.isBlock()}. The Material may not be air. + * + * @param location The {@link Location} to spawn the FallingBlock + * @param material The block {@link Material} type + * @param data The block data + * @return The spawned {@link FallingBlock} instance + * @throws IllegalArgumentException if {@link Location} or {@link + * Material} are null or {@link Material} is not a block + * @deprecated Magic value + */ + @Deprecated + FallingBlock spawnFallingBlock(Location location, Material material, byte data) throws IllegalArgumentException; + + /** + * Spawn a {@link FallingBlock} entity at the given {@link Location} of + * the specified blockId (converted to {@link Material}) + * + * @param location The {@link Location} to spawn the FallingBlock + * @param blockId The id of the intended material + * @param blockData The block data + * @return The spawned FallingBlock instance + * @throws IllegalArgumentException if location is null, or blockId is + * invalid + * @see #spawnFallingBlock(Location, Material, byte) + * @deprecated Magic value + */ + @Deprecated + FallingBlock spawnFallingBlock(Location location, int blockId, byte blockData) throws IllegalArgumentException; + + /** + * Plays an effect to all players within a default radius around a given + * location. + * + * @param location the {@link Location} around which players must be to + * hear the sound + * @param effect the {@link Effect} + * @param data a data bit needed for some effects + */ + void playEffect(Location location, Effect effect, int data); + + /** + * Plays an effect to all players within a given radius around a location. + * + * @param location the {@link Location} around which players must be to + * hear the effect + * @param effect the {@link Effect} + * @param data a data bit needed for some effects + * @param radius the radius around the location + */ + void playEffect(Location location, Effect effect, int data, int radius); + + /** + * Plays an effect to all players within a default radius around a given + * location. + * + * @param data dependant on the type of effect + * @param location the {@link Location} around which players must be to + * hear the sound + * @param effect the {@link Effect} + * @param data a data bit needed for some effects + */ + void playEffect(Location location, Effect effect, T data); + + /** + * Plays an effect to all players within a given radius around a location. + * + * @param data dependant on the type of effect + * @param location the {@link Location} around which players must be to + * hear the effect + * @param effect the {@link Effect} + * @param data a data bit needed for some effects + * @param radius the radius around the location + */ + void playEffect(Location location, Effect effect, T data, int radius); + + /** + * Get empty chunk snapshot (equivalent to all air blocks), optionally + * including valid biome data. Used for representing an ungenerated chunk, + * or for fetching only biome data without loading a chunk. + * + * @param x - chunk x coordinate + * @param z - chunk z coordinate + * @param includeBiome - if true, snapshot includes per-coordinate biome + * type + * @param includeBiomeTempRain - if true, snapshot includes per-coordinate + * raw biome temperature and rainfall + * @return The empty snapshot. + */ + ChunkSnapshot getEmptyChunkSnapshot(int x, int z, boolean includeBiome, boolean includeBiomeTempRain); + + /** + * Sets the spawn flags for this. + * + * @param allowMonsters - if true, monsters are allowed to spawn in this + * world. + * @param allowAnimals - if true, animals are allowed to spawn in this + * world. + */ + void setSpawnFlags(boolean allowMonsters, boolean allowAnimals); + + /** + * Gets whether animals can spawn in this world. + * + * @return whether animals can spawn in this world. + */ + boolean getAllowAnimals(); + + /** + * Gets whether monsters can spawn in this world. + * + * @return whether monsters can spawn in this world. + */ + boolean getAllowMonsters(); + + /** + * Gets the biome for the given block coordinates. + * + * @param x X coordinate of the block + * @param z Z coordinate of the block + * @return Biome of the requested block + */ + Biome getBiome(int x, int z); + + /** + * Sets the biome for the given block coordinates + * + * @param x X coordinate of the block + * @param z Z coordinate of the block + * @param bio new Biome type for this block + */ + void setBiome(int x, int z, Biome bio); + + /** + * Gets the temperature for the given block coordinates. + *

+ * It is safe to run this method when the block does not exist, it will + * not create the block. + * + * @param x X coordinate of the block + * @param z Z coordinate of the block + * @return Temperature of the requested block + */ + double getTemperature(int x, int z); + + /** + * Gets the humidity for the given block coordinates. + *

+ * It is safe to run this method when the block does not exist, it will + * not create the block. + * + * @param x X coordinate of the block + * @param z Z coordinate of the block + * @return Humidity of the requested block + */ + double getHumidity(int x, int z); + + /** + * Gets the maximum height of this world. + *

+ * If the max height is 100, there are only blocks from y=0 to y=99. + * + * @return Maximum height of the world + */ + int getMaxHeight(); + + /** + * Gets the sea level for this world. + *

+ * This is often half of {@link #getMaxHeight()} + * + * @return Sea level + */ + int getSeaLevel(); + + /** + * Gets whether the world's spawn area should be kept loaded into memory + * or not. + * + * @return true if the world's spawn area will be kept loaded into memory. + */ + boolean getKeepSpawnInMemory(); + + /** + * Sets whether the world's spawn area should be kept loaded into memory + * or not. + * + * @param keepLoaded if true then the world's spawn area will be kept + * loaded into memory. + */ + void setKeepSpawnInMemory(boolean keepLoaded); + + /** + * Gets whether or not the world will automatically save + * + * @return true if the world will automatically save, otherwise false + */ + boolean isAutoSave(); + + /** + * Sets whether or not the world will automatically save + * + * @param value true if the world should automatically save, otherwise + * false + */ + void setAutoSave(boolean value); + + /** + * Sets the Difficulty of the world. + * + * @param difficulty the new difficulty you want to set the world to + */ + void setDifficulty(Difficulty difficulty); + + /** + * Gets the Difficulty of the world. + * + * @return The difficulty of the world. + */ + Difficulty getDifficulty(); + + /** + * Gets the folder of this world on disk. + * + * @return The folder of this world. + */ + File getWorldFolder(); + + /** + * Gets the type of this world. + * + * @return Type of this world. + */ + WorldType getWorldType(); + + /** + * Gets whether or not structures are being generated. + * + * @return True if structures are being generated. + */ + boolean canGenerateStructures(); + + /** + * Gets the world's ticks per animal spawns value + *

+ * This value determines how many ticks there are between attempts to + * spawn animals. + *

+ * Example Usage: + *

    + *
  • A value of 1 will mean the server will attempt to spawn animals in + * this world every tick. + *
  • A value of 400 will mean the server will attempt to spawn animals + * in this world every 400th tick. + *
  • A value below 0 will be reset back to Minecraft's default. + *
+ *

+ * Note: + * If set to 0, animal spawning will be disabled for this world. We + * recommend using {@link #setSpawnFlags(boolean, boolean)} to control + * this instead. + *

+ * Minecraft default: 400. + * + * @return The world's ticks per animal spawns value + */ + long getTicksPerAnimalSpawns(); + + /** + * Sets the world's ticks per animal spawns value + *

+ * This value determines how many ticks there are between attempts to + * spawn animals. + *

+ * Example Usage: + *

    + *
  • A value of 1 will mean the server will attempt to spawn animals in + * this world every tick. + *
  • A value of 400 will mean the server will attempt to spawn animals + * in this world every 400th tick. + *
  • A value below 0 will be reset back to Minecraft's default. + *
+ *

+ * Note: + * If set to 0, animal spawning will be disabled for this world. We + * recommend using {@link #setSpawnFlags(boolean, boolean)} to control + * this instead. + *

+ * Minecraft default: 400. + * + * @param ticksPerAnimalSpawns the ticks per animal spawns value you want + * to set the world to + */ + void setTicksPerAnimalSpawns(int ticksPerAnimalSpawns); + + /** + * Gets the world's ticks per monster spawns value + *

+ * This value determines how many ticks there are between attempts to + * spawn monsters. + *

+ * Example Usage: + *

    + *
  • A value of 1 will mean the server will attempt to spawn monsters in + * this world every tick. + *
  • A value of 400 will mean the server will attempt to spawn monsters + * in this world every 400th tick. + *
  • A value below 0 will be reset back to Minecraft's default. + *
+ *

+ * Note: + * If set to 0, monsters spawning will be disabled for this world. We + * recommend using {@link #setSpawnFlags(boolean, boolean)} to control + * this instead. + *

+ * Minecraft default: 1. + * + * @return The world's ticks per monster spawns value + */ + long getTicksPerMonsterSpawns(); + + /** + * Sets the world's ticks per monster spawns value + *

+ * This value determines how many ticks there are between attempts to + * spawn monsters. + *

+ * Example Usage: + *

    + *
  • A value of 1 will mean the server will attempt to spawn monsters in + * this world on every tick. + *
  • A value of 400 will mean the server will attempt to spawn monsters + * in this world every 400th tick. + *
  • A value below 0 will be reset back to Minecraft's default. + *
+ *

+ * Note: + * If set to 0, monsters spawning will be disabled for this world. We + * recommend using {@link #setSpawnFlags(boolean, boolean)} to control + * this instead. + *

+ * Minecraft default: 1. + * + * @param ticksPerMonsterSpawns the ticks per monster spawns value you + * want to set the world to + */ + void setTicksPerMonsterSpawns(int ticksPerMonsterSpawns); + + /** + * Gets limit for number of monsters that can spawn in a chunk in this + * world + * + * @return The monster spawn limit + */ + int getMonsterSpawnLimit(); + + /** + * Sets the limit for number of monsters that can spawn in a chunk in this + * world + *

+ * Note: If set to a negative number the world will use the + * server-wide spawn limit instead. + * + * @param limit the new mob limit + */ + void setMonsterSpawnLimit(int limit); + + /** + * Gets the limit for number of animals that can spawn in a chunk in this + * world + * + * @return The animal spawn limit + */ + int getAnimalSpawnLimit(); + + /** + * Sets the limit for number of animals that can spawn in a chunk in this + * world + *

+ * Note: If set to a negative number the world will use the + * server-wide spawn limit instead. + * + * @param limit the new mob limit + */ + void setAnimalSpawnLimit(int limit); + + /** + * Gets the limit for number of water animals that can spawn in a chunk in + * this world + * + * @return The water animal spawn limit + */ + int getWaterAnimalSpawnLimit(); + + /** + * Sets the limit for number of water animals that can spawn in a chunk in + * this world + *

+ * Note: If set to a negative number the world will use the + * server-wide spawn limit instead. + * + * @param limit the new mob limit + */ + void setWaterAnimalSpawnLimit(int limit); + + /** + * Gets the limit for number of ambient mobs that can spawn in a chunk in + * this world + * + * @return The ambient spawn limit + */ + int getAmbientSpawnLimit(); + + /** + * Sets the limit for number of ambient mobs that can spawn in a chunk in + * this world + *

+ * Note: If set to a negative number the world will use the + * server-wide spawn limit instead. + * + * @param limit the new mob limit + */ + void setAmbientSpawnLimit(int limit); + + /** + * Play a Sound at the provided Location in the World + *

+ * This function will fail silently if Location or Sound are null. + * + * @param location The location to play the sound + * @param sound The sound to play + * @param volume The volume of the sound + * @param pitch The pitch of the sound + */ + void playSound(Location location, Sound sound, float volume, float pitch); + + /** + * Get existing rules + * + * @return An array of rules + */ + String[] getGameRules(); + + /** + * Gets the current state of the specified rule + *

+ * Will return null if rule passed is null + * + * @param rule Rule to look up value of + * @return String value of rule + */ + String getGameRuleValue(String rule); + + /** + * Set the specified gamerule to specified value. + *

+ * The rule may attempt to validate the value passed, will return true if + * value was set. + *

+ * If rule is null, the function will return false. + * + * @param rule Rule to set + * @param value Value to set rule to + * @return True if rule was set + */ + boolean setGameRuleValue(String rule, String value); + + /** + * Checks if string is a valid game rule + * + * @param rule Rule to check + * @return True if rule exists + */ + boolean isGameRule(String rule); + + // Spigot start + class Spigot + { + + /** + * Plays an effect to all players within a default radius around a given + * location. + * + * @param location the {@link Location} around which players must be to + * see the effect + * @param effect the {@link Effect} + * @throws IllegalArgumentException if the location or effect is null. + * It also throws when the effect requires a material or a material data + */ + public void playEffect(Location location, Effect effect) + { + throw new UnsupportedOperationException( "Not supported yet." ); + } + + /** + * Plays an effect to all players within a default radius around a given + * location. The effect will use the provided material (and material + * data if required). The particle's position on the client will be the + * given location, adjusted on each axis by a normal distribution with + * mean 0 and standard deviation given in the offset parameters, each + * particle has independently calculated offsets. The effect will have + * the given speed and particle count if the effect is a particle. Some + * effect will create multiple particles. + * + * @param location the {@link Location} around which players must be to + * see the effect + * @param effect effect the {@link Effect} + * @param id the item/block/data id for the effect + * @param data the data value of the block/item for the effect + * @param offsetX the amount to be randomly offset by in the X axis + * @param offsetY the amount to be randomly offset by in the Y axis + * @param offsetZ the amount to be randomly offset by in the Z axis + * @param speed the speed of the particles + * @param particleCount the number of particles + * @param radius the radius around the location + */ + public void playEffect(Location location, Effect effect, int id, int data, float offsetX, float offsetY, float offsetZ, float speed, int particleCount, int radius) + { + throw new UnsupportedOperationException( "Not supported yet." ); + } + + /** + * Strikes lightning at the given {@link Location} and possibly without sound + * + * @param loc The location to strike lightning + * @param isSilent Whether this strike makes no sound + * @return The lightning entity. + */ + public LightningStrike strikeLightning(Location loc, boolean isSilent) + { + throw new UnsupportedOperationException( "Not supported yet." ); + } + + /** + * Strikes lightning at the given {@link Location} without doing damage and possibly without sound + * + * @param loc The location to strike lightning + * @param isSilent Whether this strike makes no sound + * @return The lightning entity. + */ + public LightningStrike strikeLightningEffect(Location loc, boolean isSilent) + { + throw new UnsupportedOperationException( "Not supported yet." ); + } + } + + Spigot spigot(); + // Spigot end + + /** + * Gets the world border for this world. + * + * @return The world border for this world. + */ + WorldBorder getWorldBorder(); + + /** + * Represents various map environment types that a world may be + */ + enum Environment { + + /** + * Represents the "normal"/"surface world" map + */ + NORMAL(0), + /** + * Represents a nether based map ("hell") + */ + NETHER(-1), + /** + * Represents the "end" map + */ + THE_END(1); + + private final int id; + private static final Map lookup = new HashMap(); + + Environment(int id) { + this.id = id; + } + + /** + * Gets the dimension ID of this environment + * + * @return dimension ID + * @deprecated Magic value + */ + @Deprecated + public int getId() { + return id; + } + + /** + * Get an environment by ID + * + * @param id The ID of the environment + * @return The environment + * @deprecated Magic value + */ + @Deprecated + public static Environment getEnvironment(int id) { + return lookup.get(id); + } + + static { + for (Environment env : values()) { + lookup.put(env.getId(), env); + } + } + } +} diff --git a/azurite-api/src/main/java/org/bukkit/WorldBorder.java b/azurite-api/src/main/java/org/bukkit/WorldBorder.java new file mode 100644 index 0000000..291282c --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/WorldBorder.java @@ -0,0 +1,109 @@ +package org.bukkit; + +public interface WorldBorder { + + /** + * Resets the border to default values. + */ + void reset(); + + /** + * Gets the current side length of the border. + * + * @return The current side length of the border. + */ + double getSize(); + + /** + * Sets the border to a square region with the specified side length in blocks. + * + * @param newSize The new size of the border. + */ + void setSize(double newSize); + + /** + * Sets the border to a square region with the specified side length in blocks. + * + * @param newSize The new side length of the border. + * @param seconds The time in seconds in which the border grows or shrinks from the previous size to that being set. + */ + void setSize(double newSize, long seconds); + + /** + * Gets the current border center. + * + * @return The current border center. + */ + Location getCenter(); + + /** + * Sets the new border center. + * + * @param x The new center x-coordinate. + * @param z The new center z-coordinate. + */ + void setCenter(double x, double z); + + /** + * Sets the new border center. + * + * @param location The new location of the border center. (Only x/z used) + */ + void setCenter(Location location); + + /** + * Gets the current border damage buffer. + * + * @return The current border damage buffer. + */ + double getDamageBuffer(); + + /** + * Sets the amount of blocks a player may safely be outside the border before taking damage. + * + * @param blocks The amount of blocks. (The default is 5 blocks.) + */ + void setDamageBuffer(double blocks); + + /** + * Gets the current border damage amount. + * + * @return The current border damage amount. + */ + double getDamageAmount(); + + /** + * Sets the amount of damage a player takes when outside the border plus the border buffer. + * + * @param damage The amount of damage. (The default is 0.2 damage per second per block.) + */ + void setDamageAmount(double damage); + + /** + * Gets the current border warning time in seconds. + * + * @return The current border warning time in seconds. + */ + int getWarningTime(); + + /** + * Sets the warning time that causes the screen to be tinted red when a contracting border will reach the player within the specified time. + * + * @param seconds The amount of time in seconds. (The default is 15 seconds.) + */ + void setWarningTime(int seconds); + + /** + * Gets the current border warning distance. + * + * @return The current border warning distance. + */ + int getWarningDistance(); + + /** + * Sets the warning distance that causes the screen to be tinted red when the player is within the specified number of blocks from the border. + * + * @param distance The distance in blocks. (The default is 5 blocks.) + */ + void setWarningDistance(int distance); +} diff --git a/azurite-api/src/main/java/org/bukkit/WorldCreator.java b/azurite-api/src/main/java/org/bukkit/WorldCreator.java new file mode 100644 index 0000000..bcfe27a --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/WorldCreator.java @@ -0,0 +1,318 @@ +package org.bukkit; + +import org.bukkit.command.CommandSender; +import org.bukkit.generator.ChunkGenerator; +import org.bukkit.plugin.Plugin; + +import java.util.Random; + +/** + * Represents various types of options that may be used to create a world. + */ +public class WorldCreator { + private final String name; + private long seed; + private World.Environment environment = World.Environment.NORMAL; + private ChunkGenerator generator = null; + private WorldType type = WorldType.NORMAL; + private boolean generateStructures = true; + private String generatorSettings = ""; + + /** + * Creates an empty WorldCreationOptions for the given world name + * + * @param name Name of the world that will be created + */ + public WorldCreator(String name) { + if (name == null) { + throw new IllegalArgumentException("World name cannot be null"); + } + + this.name = name; + this.seed = (new Random()).nextLong(); + } + + /** + * Copies the options from the specified world + * + * @param world World to copy options from + * @return This object, for chaining + */ + public WorldCreator copy(World world) { + if (world == null) { + throw new IllegalArgumentException("World cannot be null"); + } + + seed = world.getSeed(); + environment = world.getEnvironment(); + generator = world.getGenerator(); + + return this; + } + + /** + * Copies the options from the specified {@link WorldCreator} + * + * @param creator World creator to copy options from + * @return This object, for chaining + */ + public WorldCreator copy(WorldCreator creator) { + if (creator == null) { + throw new IllegalArgumentException("Creator cannot be null"); + } + + seed = creator.seed(); + environment = creator.environment(); + generator = creator.generator(); + + return this; + } + + /** + * Gets the name of the world that is to be loaded or created. + * + * @return World name + */ + public String name() { + return name; + } + + /** + * Gets the seed that will be used to create this world + * + * @return World seed + */ + public long seed() { + return seed; + } + + /** + * Sets the seed that will be used to create this world + * + * @param seed World seed + * @return This object, for chaining + */ + public WorldCreator seed(long seed) { + this.seed = seed; + + return this; + } + + /** + * Gets the environment that will be used to create or load the world + * + * @return World environment + */ + public World.Environment environment() { + return environment; + } + + /** + * Sets the environment that will be used to create or load the world + * + * @param env World environment + * @return This object, for chaining + */ + public WorldCreator environment(World.Environment env) { + this.environment = env; + + return this; + } + + /** + * Gets the type of the world that will be created or loaded + * + * @return World type + */ + public WorldType type() { + return type; + } + + /** + * Sets the type of the world that will be created or loaded + * + * @param type World type + * @return This object, for chaining + */ + public WorldCreator type(WorldType type) { + this.type = type; + + return this; + } + + /** + * Gets the generator that will be used to create or load the world. + *

+ * This may be null, in which case the "natural" generator for this + * environment will be used. + * + * @return Chunk generator + */ + public ChunkGenerator generator() { + return generator; + } + + /** + * Sets the generator that will be used to create or load the world. + *

+ * This may be null, in which case the "natural" generator for this + * environment will be used. + * + * @param generator Chunk generator + * @return This object, for chaining + */ + public WorldCreator generator(ChunkGenerator generator) { + this.generator = generator; + + return this; + } + + /** + * Sets the generator that will be used to create or load the world. + *

+ * This may be null, in which case the "natural" generator for this + * environment will be used. + *

+ * If the generator cannot be found for the given name, the natural + * environment generator will be used instead and a warning will be + * printed to the console. + * + * @param generator Name of the generator to use, in "plugin:id" notation + * @return This object, for chaining + */ + public WorldCreator generator(String generator) { + this.generator = getGeneratorForName(name, generator, Bukkit.getConsoleSender()); + + return this; + } + + /** + * Sets the generator that will be used to create or load the world. + *

+ * This may be null, in which case the "natural" generator for this + * environment will be used. + *

+ * If the generator cannot be found for the given name, the natural + * environment generator will be used instead and a warning will be + * printed to the specified output + * + * @param generator Name of the generator to use, in "plugin:id" notation + * @param output {@link CommandSender} that will receive any error + * messages + * @return This object, for chaining + */ + public WorldCreator generator(String generator, CommandSender output) { + this.generator = getGeneratorForName(name, generator, output); + + return this; + } + + /** + * Sets the generator settings of the world that will be created or loaded + * + * @param generatorSettings The settings that should be used by the generator + * @return This object, for chaining + */ + public WorldCreator generatorSettings(String generatorSettings) { + this.generatorSettings = generatorSettings; + + return this; + } + + /** + * Gets the generator settings of the world that will be created or loaded + * + * @return The settings that should be used by the generator + */ + public String generatorSettings() { + return generatorSettings; + } + + /** + * Sets whether or not worlds created or loaded with this creator will + * have structures. + * + * @param generate Whether to generate structures + * @return This object, for chaining + */ + public WorldCreator generateStructures(boolean generate) { + this.generateStructures = generate; + + return this; + } + + /** + * Gets whether or not structures will be generated in the world. + * + * @return True if structures will be generated + */ + public boolean generateStructures() { + return generateStructures; + } + + /** + * Creates a world with the specified options. + *

+ * If the world already exists, it will be loaded from disk and some + * options may be ignored. + * + * @return Newly created or loaded world + */ + public World createWorld() { + return Bukkit.createWorld(this); + } + + /** + * Creates a new {@link WorldCreator} for the given world name + * + * @param name Name of the world to load or create + * @return Resulting WorldCreator + */ + public static WorldCreator name(String name) { + return new WorldCreator(name); + } + + /** + * Attempts to get the {@link ChunkGenerator} with the given name. + *

+ * If the generator is not found, null will be returned and a message will + * be printed to the specified {@link CommandSender} explaining why. + *

+ * The name must be in the "plugin:id" notation, or optionally just + * "plugin", where "plugin" is the safe-name of a plugin and "id" is an + * optional unique identifier for the generator you wish to request from + * the plugin. + * + * @param world Name of the world this will be used for + * @param name Name of the generator to retrieve + * @param output Where to output if errors are present + * @return Resulting generator, or null + */ + public static ChunkGenerator getGeneratorForName(String world, String name, CommandSender output) { + ChunkGenerator result = null; + + if (world == null) { + throw new IllegalArgumentException("World name must be specified"); + } + + if (output == null) { + output = Bukkit.getConsoleSender(); + } + + if (name != null) { + String[] split = name.split(":", 2); + String id = (split.length > 1) ? split[1] : null; + Plugin plugin = Bukkit.getPluginManager().getPlugin(split[0]); + + if (plugin == null) { + output.sendMessage("Could not set generator for world '" + world + "': Plugin '" + split[0] + "' does not exist"); + } else if (!plugin.isEnabled()) { + output.sendMessage("Could not set generator for world '" + world + "': Plugin '" + plugin.getDescription().getFullName() + "' is not enabled"); + } else { + result = plugin.getDefaultWorldGenerator(world, id); + } + } + + return result; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/WorldType.java b/azurite-api/src/main/java/org/bukkit/WorldType.java new file mode 100644 index 0000000..db8edd6 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/WorldType.java @@ -0,0 +1,49 @@ +package org.bukkit; + +import com.google.common.collect.Maps; + +import java.util.Map; + +/** + * Represents various types of worlds that may exist + */ +public enum WorldType { + NORMAL("DEFAULT"), + FLAT("FLAT"), + VERSION_1_1("DEFAULT_1_1"), + LARGE_BIOMES("LARGEBIOMES"), + AMPLIFIED("AMPLIFIED"), + CUSTOMIZED("CUSTOMIZED"); + + private final static Map BY_NAME = Maps.newHashMap(); + private final String name; + + WorldType(String name) { + this.name = name; + } + + /** + * Gets the name of this WorldType + * + * @return Name of this type + */ + public String getName() { + return name; + } + + /** + * Gets a Worldtype by its name + * + * @param name Name of the WorldType to get + * @return Requested WorldType, or null if not found + */ + public static WorldType getByName(String name) { + return BY_NAME.get(name.toUpperCase()); + } + + static { + for (WorldType type : values()) { + BY_NAME.put(type.name, type); + } + } +} diff --git a/azurite-api/src/main/java/org/bukkit/block/Banner.java b/azurite-api/src/main/java/org/bukkit/block/Banner.java new file mode 100644 index 0000000..723b883 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/block/Banner.java @@ -0,0 +1,77 @@ +package org.bukkit.block; + +import org.bukkit.DyeColor; +import org.bukkit.block.banner.Pattern; + +import java.util.List; + +public interface Banner extends BlockState { + + /** + * Returns the base color for this banner + * + * @return the base color + */ + DyeColor getBaseColor(); + + /** + * Sets the base color for this banner + * + * @param color the base color + */ + void setBaseColor(DyeColor color); + + /** + * Returns a list of patterns on this banner + * + * @return the patterns + */ + List getPatterns(); + + /** + * Sets the patterns used on this banner + * + * @param patterns the new list of patterns + */ + void setPatterns(List patterns); + + /** + * Adds a new pattern on top of the existing + * patterns + * + * @param pattern the new pattern to add + */ + void addPattern(Pattern pattern); + + /** + * Returns the pattern at the specified index + * + * @param i the index + * @return the pattern + */ + Pattern getPattern(int i); + + /** + * Removes the pattern at the specified index + * + * @param i the index + * @return the removed pattern + */ + Pattern removePattern(int i); + + /** + * Sets the pattern at the specified index + * + * @param i the index + * @param pattern the new pattern + */ + void setPattern(int i, Pattern pattern); + + /** + * Returns the number of patterns on this + * banner + * + * @return the number of patterns + */ + int numberOfPatterns(); +} diff --git a/azurite-api/src/main/java/org/bukkit/block/Beacon.java b/azurite-api/src/main/java/org/bukkit/block/Beacon.java new file mode 100644 index 0000000..2de0583 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/block/Beacon.java @@ -0,0 +1,9 @@ +package org.bukkit.block; + +import org.bukkit.inventory.InventoryHolder; + +/** + * Represents a beacon. + */ +public interface Beacon extends BlockState, InventoryHolder { +} diff --git a/azurite-api/src/main/java/org/bukkit/block/Biome.java b/azurite-api/src/main/java/org/bukkit/block/Biome.java new file mode 100644 index 0000000..8b902f4 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/block/Biome.java @@ -0,0 +1,68 @@ +package org.bukkit.block; + +/** + * Holds all accepted Biomes in the default server + */ +public enum Biome { + SWAMPLAND, + FOREST, + TAIGA, + DESERT, + PLAINS, + HELL, + SKY, + OCEAN, + RIVER, + EXTREME_HILLS, + FROZEN_OCEAN, + FROZEN_RIVER, + ICE_PLAINS, + ICE_MOUNTAINS, + MUSHROOM_ISLAND, + MUSHROOM_SHORE, + BEACH, + DESERT_HILLS, + FOREST_HILLS, + TAIGA_HILLS, + SMALL_MOUNTAINS, + JUNGLE, + JUNGLE_HILLS, + JUNGLE_EDGE, + DEEP_OCEAN, + STONE_BEACH, + COLD_BEACH, + BIRCH_FOREST, + BIRCH_FOREST_HILLS, + ROOFED_FOREST, + COLD_TAIGA, + COLD_TAIGA_HILLS, + MEGA_TAIGA, + MEGA_TAIGA_HILLS, + EXTREME_HILLS_PLUS, + SAVANNA, + SAVANNA_PLATEAU, + MESA, + MESA_PLATEAU_FOREST, + MESA_PLATEAU, + SUNFLOWER_PLAINS, + DESERT_MOUNTAINS, + FLOWER_FOREST, + TAIGA_MOUNTAINS, + SWAMPLAND_MOUNTAINS, + ICE_PLAINS_SPIKES, + JUNGLE_MOUNTAINS, + JUNGLE_EDGE_MOUNTAINS, + COLD_TAIGA_MOUNTAINS, + SAVANNA_MOUNTAINS, + SAVANNA_PLATEAU_MOUNTAINS, + MESA_BRYCE, + MESA_PLATEAU_FOREST_MOUNTAINS, + MESA_PLATEAU_MOUNTAINS, + BIRCH_FOREST_MOUNTAINS, + BIRCH_FOREST_HILLS_MOUNTAINS, + ROOFED_FOREST_MOUNTAINS, + MEGA_SPRUCE_TAIGA, + EXTREME_HILLS_MOUNTAINS, + EXTREME_HILLS_PLUS_MOUNTAINS, + MEGA_SPRUCE_TAIGA_HILLS, +} diff --git a/azurite-api/src/main/java/org/bukkit/block/Block.java b/azurite-api/src/main/java/org/bukkit/block/Block.java new file mode 100644 index 0000000..1595eec --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/block/Block.java @@ -0,0 +1,413 @@ +package org.bukkit.block; + +import org.bukkit.Chunk; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.inventory.ItemStack; +import org.bukkit.metadata.Metadatable; + +import java.util.Collection; + +/** + * Represents a block. This is a live object, and only one Block may exist for + * any given location in a world. The state of the block may change + * concurrently to your own handling of it; use block.getState() to get a + * snapshot state of a block which will not be modified. + */ +public interface Block extends Metadatable { + + /** + * Gets the durability for this block + *

+ * This method only supported in spigots + * that have an explosion destroyer + * + * @return Durability for this block or -1 + */ + int getDurability(); + + /** + * Sets the durability of this block + *

+ * This method only supported in spigots + * that have an explosion destroyer + * + * @param durability Durability to change this block to + */ + void setDurability(int durability); + + /** + * Gets the metadata for this block + * + * @return block specific metadata + * @deprecated Magic value + */ + @Deprecated + byte getData(); + + /** + * Gets the block at the given offsets + * + * @param modX X-coordinate offset + * @param modY Y-coordinate offset + * @param modZ Z-coordinate offset + * @return Block at the given offsets + */ + Block getRelative(int modX, int modY, int modZ); + + /** + * Gets the block at the given face + *

+ * This method is equal to getRelative(face, 1) + * + * @param face Face of this block to return + * @return Block at the given face + * @see #getRelative(BlockFace, int) + */ + Block getRelative(BlockFace face); + + /** + * Gets the block at the given distance of the given face + *

+ * For example, the following method places water at 100,102,100; two + * blocks above 100,100,100. + * + *

+     * Block block = world.getBlockAt(100, 100, 100);
+     * Block shower = block.getRelative(BlockFace.UP, 2);
+     * shower.setType(Material.WATER);
+     * 
+ * + * @param face Face of this block to return + * @param distance Distance to get the block at + * @return Block at the given face + */ + Block getRelative(BlockFace face, int distance); + + /** + * Gets the type of this block + * + * @return block type + */ + Material getType(); + + /** + * Gets the type-id of this block + * + * @return block type-id + * @deprecated Magic value + */ + @Deprecated + int getTypeId(); + + /** + * Gets the light level between 0-15 + * + * @return light level + */ + byte getLightLevel(); + + /** + * Get the amount of light at this block from the sky. + *

+ * Any light given from other sources (such as blocks like torches) will + * be ignored. + * + * @return Sky light level + */ + byte getLightFromSky(); + + /** + * Get the amount of light at this block from nearby blocks. + *

+ * Any light given from other sources (such as the sun) will be ignored. + * + * @return Block light level + */ + byte getLightFromBlocks(); + + /** + * Gets the world which contains this Block + * + * @return World containing this block + */ + World getWorld(); + + /** + * Gets the x-coordinate of this block + * + * @return x-coordinate + */ + int getX(); + + /** + * Gets the y-coordinate of this block + * + * @return y-coordinate + */ + int getY(); + + /** + * Gets the z-coordinate of this block + * + * @return z-coordinate + */ + int getZ(); + + /** + * Gets the Location of the block + * + * @return Location of block + */ + Location getLocation(); + + /** + * Stores the location of the block in the provided Location object. + *

+ * If the provided Location is null this method does nothing and returns + * null. + * + * @param loc the location to copy into + * @return The Location object provided or null + */ + Location getLocation(Location loc); + + /** + * Gets the chunk which contains this block + * + * @return Containing Chunk + */ + Chunk getChunk(); + + /** + * Sets the metadata for this block + * + * @param data New block specific metadata + * @deprecated Magic value + */ + @Deprecated + void setData(byte data); + + /** + * Sets the metadata for this block + * + * @param data New block specific metadata + * @param applyPhysics False to cancel physics from the changed block. + * @deprecated Magic value + */ + @Deprecated + void setData(byte data, boolean applyPhysics); + + /** + * Sets the type of this block + * + * @param type Material to change this block to + */ + void setType(Material type); + + /** + * Sets the type of this block + * + * @param type Material to change this block to + * @param applyPhysics False to cancel physics on the changed block. + */ + void setType(Material type, boolean applyPhysics); + + /** + * Sets the type-id of this block + * + * @param type Type-Id to change this block to + * @return whether the block was changed + * @deprecated Magic value + */ + @Deprecated + boolean setTypeId(int type); + + /** + * Sets the type-id of this block + * + * @param type Type-Id to change this block to + * @param applyPhysics False to cancel physics on the changed block. + * @return whether the block was changed + * @deprecated Magic value + */ + @Deprecated + boolean setTypeId(int type, boolean applyPhysics); + + /** + * Sets the type-id of this block + * + * @param type Type-Id to change this block to + * @param data The data value to change this block to + * @param applyPhysics False to cancel physics on the changed block + * @return whether the block was changed + * @deprecated Magic value + */ + @Deprecated + boolean setTypeIdAndData(int type, byte data, boolean applyPhysics); + + /** + * Gets the face relation of this block compared to the given block. + *

+ * For example: + *

{@code
+     * Block current = world.getBlockAt(100, 100, 100);
+     * Block target = world.getBlockAt(100, 101, 100);
+     *
+     * current.getFace(target) == BlockFace.Up;
+     * }
+ *
+ * If the given block is not connected to this block, null may be returned + * + * @param block Block to compare against this block + * @return BlockFace of this block which has the requested block, or null + */ + BlockFace getFace(Block block); + + /** + * Captures the current state of this block. You may then cast that state + * into any accepted type, such as Furnace or Sign. + *

+ * The returned object will never be updated, and you are not guaranteed + * that (for example) a sign is still a sign after you capture its state. + * + * @return BlockState with the current state of this block. + */ + BlockState getState(); + + /** + * Returns the biome that this block resides in + * + * @return Biome type containing this block + */ + Biome getBiome(); + + /** + * Sets the biome that this block resides in + * + * @param bio new Biome type for this block + */ + void setBiome(Biome bio); + + /** + * Returns true if the block is being powered by Redstone. + * + * @return True if the block is powered. + */ + boolean isBlockPowered(); + + /** + * Returns true if the block is being indirectly powered by Redstone. + * + * @return True if the block is indirectly powered. + */ + boolean isBlockIndirectlyPowered(); + + /** + * Returns true if the block face is being powered by Redstone. + * + * @param face The block face + * @return True if the block face is powered. + */ + boolean isBlockFacePowered(BlockFace face); + + /** + * Returns true if the block face is being indirectly powered by Redstone. + * + * @param face The block face + * @return True if the block face is indirectly powered. + */ + boolean isBlockFaceIndirectlyPowered(BlockFace face); + + /** + * Returns the redstone power being provided to this block face + * + * @param face the face of the block to query or BlockFace.SELF for the + * block itself + * @return The power level. + */ + int getBlockPower(BlockFace face); + + /** + * Returns the redstone power being provided to this block + * + * @return The power level. + */ + int getBlockPower(); + + /** + * Checks if this block is empty. + *

+ * A block is considered empty when {@link #getType()} returns {@link + * Material#AIR}. + * + * @return true if this block is empty + */ + boolean isEmpty(); + + /** + * Checks if this block is liquid. + *

+ * A block is considered liquid when {@link #getType()} returns {@link + * Material#WATER}, {@link Material#STATIONARY_WATER}, {@link + * Material#LAVA} or {@link Material#STATIONARY_LAVA}. + * + * @return true if this block is liquid + */ + boolean isLiquid(); + + /** + * Gets the temperature of the biome of this block + * + * @return Temperature of this block + */ + double getTemperature(); + + /** + * Gets the humidity of the biome of this block + * + * @return Humidity of this block + */ + double getHumidity(); + + /** + * Returns the reaction of the block when moved by a piston + * + * @return reaction + */ + PistonMoveReaction getPistonMoveReaction(); + + /** + * Breaks the block and spawns items as if a player had digged it + * + * @return true if the block was destroyed + */ + boolean breakNaturally(); + + /** + * Breaks the block and spawns items as if a player had digged it with a + * specific tool + * + * @param tool The tool or item in hand used for digging + * @return true if the block was destroyed + */ + boolean breakNaturally(ItemStack tool); + + /** + * Returns a list of items which would drop by destroying this block + * + * @return a list of dropped items for this type of block + */ + Collection getDrops(); + + /** + * Returns a list of items which would drop by destroying this block with + * a specific tool + * + * @param tool The tool or item in hand used for digging + * @return a list of dropped items for this type of block + */ + Collection getDrops(ItemStack tool); + +} diff --git a/azurite-api/src/main/java/org/bukkit/block/BlockFace.java b/azurite-api/src/main/java/org/bukkit/block/BlockFace.java new file mode 100644 index 0000000..b4af576 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/block/BlockFace.java @@ -0,0 +1,149 @@ +package org.bukkit.block; + +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; + +/** + * Represents the face of a block + */ +public enum BlockFace { + NORTH(0, 0, -1), + EAST(1, 0, 0), + SOUTH(0, 0, 1), + WEST(-1, 0, 0), + UP(0, 1, 0), + DOWN(0, -1, 0), + NORTH_EAST(NORTH, EAST), + NORTH_WEST(NORTH, WEST), + SOUTH_EAST(SOUTH, EAST), + SOUTH_WEST(SOUTH, WEST), + WEST_NORTH_WEST(WEST, NORTH_WEST), + NORTH_NORTH_WEST(NORTH, NORTH_WEST), + NORTH_NORTH_EAST(NORTH, NORTH_EAST), + EAST_NORTH_EAST(EAST, NORTH_EAST), + EAST_SOUTH_EAST(EAST, SOUTH_EAST), + SOUTH_SOUTH_EAST(SOUTH, SOUTH_EAST), + SOUTH_SOUTH_WEST(SOUTH, SOUTH_WEST), + WEST_SOUTH_WEST(WEST, SOUTH_WEST), + SELF(0, 0, 0); + + private final int modX; + private final int modY; + private final int modZ; + + BlockFace(final int modX, final int modY, final int modZ) { + this.modX = modX; + this.modY = modY; + this.modZ = modZ; + } + + BlockFace(final BlockFace face1, final BlockFace face2) { + this.modX = face1.getModX() + face2.getModX(); + this.modY = face1.getModY() + face2.getModY(); + this.modZ = face1.getModZ() + face2.getModZ(); + } + + /** + * Get the amount of X-coordinates to modify to get the represented block + * + * @return Amount of X-coordinates to modify + */ + public int getModX() { + return modX; + } + + /** + * Get the amount of Y-coordinates to modify to get the represented block + * + * @return Amount of Y-coordinates to modify + */ + public int getModY() { + return modY; + } + + /** + * Get the amount of Z-coordinates to modify to get the represented block + * + * @return Amount of Z-coordinates to modify + */ + public int getModZ() { + return modZ; + } + + /** + * Gets the normal vector corresponding to this block face. + * + * @return the normal vector + */ + @NotNull + public Vector getDirection() { + Vector direction = new Vector(modX, modY, modZ); + if (modX != 0 || modY != 0 || modZ != 0) { + direction.normalize(); + } + return direction; + } + + public BlockFace getOppositeFace() { + switch (this) { + case NORTH: + return BlockFace.SOUTH; + + case SOUTH: + return BlockFace.NORTH; + + case EAST: + return BlockFace.WEST; + + case WEST: + return BlockFace.EAST; + + case UP: + return BlockFace.DOWN; + + case DOWN: + return BlockFace.UP; + + case NORTH_EAST: + return BlockFace.SOUTH_WEST; + + case NORTH_WEST: + return BlockFace.SOUTH_EAST; + + case SOUTH_EAST: + return BlockFace.NORTH_WEST; + + case SOUTH_WEST: + return BlockFace.NORTH_EAST; + + case WEST_NORTH_WEST: + return BlockFace.EAST_SOUTH_EAST; + + case NORTH_NORTH_WEST: + return BlockFace.SOUTH_SOUTH_EAST; + + case NORTH_NORTH_EAST: + return BlockFace.SOUTH_SOUTH_WEST; + + case EAST_NORTH_EAST: + return BlockFace.WEST_SOUTH_WEST; + + case EAST_SOUTH_EAST: + return BlockFace.WEST_NORTH_WEST; + + case SOUTH_SOUTH_EAST: + return BlockFace.NORTH_NORTH_WEST; + + case SOUTH_SOUTH_WEST: + return BlockFace.NORTH_NORTH_EAST; + + case WEST_SOUTH_WEST: + return BlockFace.EAST_NORTH_EAST; + + case SELF: + return BlockFace.SELF; + } + + return BlockFace.SELF; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/block/BlockState.java b/azurite-api/src/main/java/org/bukkit/block/BlockState.java new file mode 100644 index 0000000..03e636a --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/block/BlockState.java @@ -0,0 +1,206 @@ +package org.bukkit.block; + +import org.bukkit.Chunk; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.material.MaterialData; +import org.bukkit.metadata.Metadatable; + +/** + * Represents a captured state of a block, which will not change + * automatically. + *

+ * Unlike Block, which only one object can exist per coordinate, BlockState + * can exist multiple times for any given Block. Note that another plugin may + * change the state of the block and you will not know, or they may change the + * block to another type entirely, causing your BlockState to become invalid. + */ +public interface BlockState extends Metadatable { + + /** + * Gets the block represented by this BlockState + * + * @return Block that this BlockState represents + */ + Block getBlock(); + + /** + * Gets the metadata for this block + * + * @return block specific metadata + */ + MaterialData getData(); + + /** + * Gets the type of this block + * + * @return block type + */ + Material getType(); + + /** + * Gets the type-id of this block + * + * @return block type-id + * @deprecated Magic value + */ + @Deprecated + int getTypeId(); + + /** + * Gets the light level between 0-15 + * + * @return light level + */ + byte getLightLevel(); + + /** + * Gets the world which contains this Block + * + * @return World containing this block + */ + World getWorld(); + + /** + * Gets the x-coordinate of this block + * + * @return x-coordinate + */ + int getX(); + + /** + * Gets the y-coordinate of this block + * + * @return y-coordinate + */ + int getY(); + + /** + * Gets the z-coordinate of this block + * + * @return z-coordinate + */ + int getZ(); + + /** + * Gets the location of this block + * + * @return location + */ + Location getLocation(); + + /** + * Stores the location of this block in the provided Location object. + *

+ * If the provided Location is null this method does nothing and returns + * null. + * + * @param loc the location to copy into + * @return The Location object provided or null + */ + Location getLocation(Location loc); + + /** + * Gets the chunk which contains this block + * + * @return Containing Chunk + */ + Chunk getChunk(); + + /** + * Sets the metadata for this block + * + * @param data New block specific metadata + */ + void setData(MaterialData data); + + /** + * Sets the type of this block + * + * @param type Material to change this block to + */ + void setType(Material type); + + /** + * Sets the type-id of this block + * + * @param type Type-Id to change this block to + * @return Whether it worked? + * @deprecated Magic value + */ + @Deprecated + boolean setTypeId(int type); + + /** + * Attempts to update the block represented by this state, setting it to + * the new values as defined by this state. + *

+ * This has the same effect as calling update(false). That is to say, + * this will not modify the state of a block if it is no longer the same + * type as it was when this state was taken. It will return false in this + * eventuality. + * + * @return true if the update was successful, otherwise false + * @see #update(boolean) + */ + boolean update(); + + /** + * Attempts to update the block represented by this state, setting it to + * the new values as defined by this state. + *

+ * This has the same effect as calling update(force, true). That is to + * say, this will trigger a physics update to surrounding blocks. + * + * @param force true to forcefully set the state + * @return true if the update was successful, otherwise false + */ + boolean update(boolean force); + + /** + * Attempts to update the block represented by this state, setting it to + * the new values as defined by this state. + *

+ * Unless force is true, this will not modify the state of a block if it + * is no longer the same type as it was when this state was taken. It will + * return false in this eventuality. + *

+ * If force is true, it will set the type of the block to match the new + * state, set the state data and then return true. + *

+ * If applyPhysics is true, it will trigger a physics update on + * surrounding blocks which could cause them to update or disappear. + * + * @param force true to forcefully set the state + * @param applyPhysics false to cancel updating physics on surrounding + * blocks + * @return true if the update was successful, otherwise false + */ + boolean update(boolean force, boolean applyPhysics); + + /** + * @return The data as a raw byte. + * @deprecated Magic value + */ + @Deprecated + byte getRawData(); + + /** + * @param data The new data value for the block. + * @deprecated Magic value + */ + @Deprecated + void setRawData(byte data); + + /** + * Returns whether this state is placed in the world. + * + * Some methods will not work if the blockState isn't + * placed in the world. + * + * @return whether the state is placed in the world + * or 'virtual' (e.g. on an itemstack) + */ + boolean isPlaced(); +} diff --git a/azurite-api/src/main/java/org/bukkit/block/BrewingStand.java b/azurite-api/src/main/java/org/bukkit/block/BrewingStand.java new file mode 100644 index 0000000..3f6ab6a --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/block/BrewingStand.java @@ -0,0 +1,25 @@ +package org.bukkit.block; + +import org.bukkit.inventory.BrewerInventory; + +/** + * Represents a brewing stand. + */ +public interface BrewingStand extends BlockState, ContainerBlock { + + /** + * How much time is left in the brewing cycle + * + * @return Brew Time + */ + int getBrewingTime(); + + /** + * Set the time left before brewing completes. + * + * @param brewTime Brewing time + */ + void setBrewingTime(int brewTime); + + BrewerInventory getInventory(); +} diff --git a/azurite-api/src/main/java/org/bukkit/block/Chest.java b/azurite-api/src/main/java/org/bukkit/block/Chest.java new file mode 100644 index 0000000..125d5e7 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/block/Chest.java @@ -0,0 +1,17 @@ +package org.bukkit.block; + +import org.bukkit.inventory.Inventory; + +/** + * Represents a chest. + */ +public interface Chest extends BlockState, ContainerBlock { + + /** + * Returns the chest's inventory. If this is a double chest, it returns + * just the portion of the inventory linked to this half of the chest. + * + * @return The inventory. + */ + Inventory getBlockInventory(); +} diff --git a/azurite-api/src/main/java/org/bukkit/block/CommandBlock.java b/azurite-api/src/main/java/org/bukkit/block/CommandBlock.java new file mode 100644 index 0000000..e53aeb7 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/block/CommandBlock.java @@ -0,0 +1,40 @@ +package org.bukkit.block; + +public interface CommandBlock extends BlockState { + + /** + * Gets the command that this CommandBlock will run when powered. + * This will never return null. If the CommandBlock does not have a + * command, an empty String will be returned instead. + * + * @return Command that this CommandBlock will run when powered. + */ + String getCommand(); + + /** + * Sets the command that this CommandBlock will run when powered. + * Setting the command to null is the same as setting it to an empty + * String. + * + * @param command Command that this CommandBlock will run when powered. + */ + void setCommand(String command); + + /** + * Gets the name of this CommandBlock. The name is used with commands + * that this CommandBlock executes. This name will never be null, and + * by default is "@". + * + * @return Name of this CommandBlock. + */ + String getName(); + + /** + * Sets the name of this CommandBlock. The name is used with commands + * that this CommandBlock executes. Setting the name to null is the + * same as setting it to "@". + * + * @param name New name for this CommandBlock. + */ + void setName(String name); +} diff --git a/azurite-api/src/main/java/org/bukkit/block/ContainerBlock.java b/azurite-api/src/main/java/org/bukkit/block/ContainerBlock.java new file mode 100644 index 0000000..c69ac9e --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/block/ContainerBlock.java @@ -0,0 +1,11 @@ +package org.bukkit.block; + +import org.bukkit.inventory.InventoryHolder; + +/** + * Indicates a block type that has inventory. + * + * @deprecated in favour of {@link InventoryHolder} + */ +@Deprecated +public interface ContainerBlock extends InventoryHolder {} diff --git a/azurite-api/src/main/java/org/bukkit/block/CreatureSpawner.java b/azurite-api/src/main/java/org/bukkit/block/CreatureSpawner.java new file mode 100644 index 0000000..93a1497 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/block/CreatureSpawner.java @@ -0,0 +1,88 @@ +package org.bukkit.block; + +import org.bukkit.entity.CreatureType; +import org.bukkit.entity.EntityType; + +/** + * Represents a creature spawner. + */ +public interface CreatureSpawner extends BlockState { + + /** + * Get the spawner's creature type. + * + * @return The creature type. + * @deprecated In favour of {@link #getSpawnedType()}. + */ + @Deprecated + CreatureType getCreatureType(); + + /** + * Get the spawner's creature type. + * + * @return The creature type. + */ + EntityType getSpawnedType(); + + /** + * Set the spawner's creature type. + * + * @param creatureType The creature type. + */ + void setSpawnedType(EntityType creatureType); + + /** + * Set the spawner creature type. + * + * @param creatureType The creature type. + * @deprecated In favour of {@link #setSpawnedType(EntityType)}. + */ + @Deprecated + void setCreatureType(CreatureType creatureType); + + /** + * Get the spawner's creature type. + * + * @return The creature type's name. + * @deprecated Use {@link #getCreatureTypeName()}. + */ + @Deprecated + String getCreatureTypeId(); + + /** + * Set the spawner mob type. + * + * @param creatureType The creature type's name. + */ + void setCreatureTypeByName(String creatureType); + + /** + * Get the spawner's creature type. + * + * @return The creature type's name. + */ + String getCreatureTypeName(); + + /** + * Set the spawner mob type. + * + * @param creatureType The creature type's name. + * @deprecated Use {@link #setCreatureTypeByName(String)}. + */ + @Deprecated + void setCreatureTypeId(String creatureType); + + /** + * Get the spawner's delay. + * + * @return The delay. + */ + int getDelay(); + + /** + * Set the spawner's delay. + * + * @param delay The delay. + */ + void setDelay(int delay); +} diff --git a/azurite-api/src/main/java/org/bukkit/block/Dispenser.java b/azurite-api/src/main/java/org/bukkit/block/Dispenser.java new file mode 100644 index 0000000..e2dd08c --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/block/Dispenser.java @@ -0,0 +1,27 @@ +package org.bukkit.block; + +import org.bukkit.projectiles.BlockProjectileSource; + +/** + * Represents a dispenser. + */ +public interface Dispenser extends BlockState, ContainerBlock { + + /** + * Gets the BlockProjectileSource object for this dispenser. + *

+ * If the block is no longer a dispenser, this will return null. + * + * @return a BlockProjectileSource if valid, otherwise null + */ + BlockProjectileSource getBlockProjectileSource(); + + /** + * Attempts to dispense the contents of this block. + *

+ * If the block is no longer a dispenser, this will return false. + * + * @return true if successful, otherwise false + */ + boolean dispense(); +} diff --git a/azurite-api/src/main/java/org/bukkit/block/DoubleChest.java b/azurite-api/src/main/java/org/bukkit/block/DoubleChest.java new file mode 100644 index 0000000..5bee3da --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/block/DoubleChest.java @@ -0,0 +1,50 @@ +package org.bukkit.block; + +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.inventory.DoubleChestInventory; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryHolder; + +/** + * Represents a double chest. + */ +public class DoubleChest implements InventoryHolder { + private final DoubleChestInventory inventory; + + public DoubleChest(DoubleChestInventory chest) { + inventory = chest; + } + + public Inventory getInventory() { + return inventory; + } + + public InventoryHolder getLeftSide() { + return inventory.getLeftSide().getHolder(); + } + + public InventoryHolder getRightSide() { + return inventory.getRightSide().getHolder(); + } + + public Location getLocation() { + return new Location(getWorld(), getX(), getY(), getZ()); + } + + public World getWorld() { + return ((Chest)getLeftSide()).getWorld(); + } + + public double getX() { + return 0.5 * (((Chest)getLeftSide()).getX() + ((Chest)getRightSide()).getX()); + } + + public double getY() { + return 0.5 * (((Chest)getLeftSide()).getY() + ((Chest)getRightSide()).getY()); + } + + public double getZ() { + return 0.5 * (((Chest)getLeftSide()).getZ() + ((Chest)getRightSide()).getZ()); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/block/Dropper.java b/azurite-api/src/main/java/org/bukkit/block/Dropper.java new file mode 100644 index 0000000..ede3ec6 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/block/Dropper.java @@ -0,0 +1,25 @@ +package org.bukkit.block; + +import org.bukkit.inventory.InventoryHolder; + +/** + * Represents a dropper. + */ +public interface Dropper extends BlockState, InventoryHolder { + /** + * Tries to drop a randomly selected item from the Dropper's inventory, + * following the normal behavior of a Dropper. + *

+ * Normal behavior of a Dropper is as follows: + *

+ * If the block that the Dropper is facing is an InventoryHolder or + * ContainerBlock the randomly selected ItemStack is placed within that + * Inventory in the first slot that's available, starting with 0 and + * counting up. If the inventory is full, nothing happens. + *

+ * If the block that the Dropper is facing is not an InventoryHolder or + * ContainerBlock, the randomly selected ItemStack is dropped on + * the ground in the form of an {@link org.bukkit.entity.Item Item}. + */ + void drop(); +} diff --git a/azurite-api/src/main/java/org/bukkit/block/Furnace.java b/azurite-api/src/main/java/org/bukkit/block/Furnace.java new file mode 100644 index 0000000..bf7e9ec --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/block/Furnace.java @@ -0,0 +1,15 @@ +package org.bukkit.block; + +import org.bukkit.inventory.FurnaceInventory; + +public interface Furnace extends BlockState, ContainerBlock { + short getBurnTime(); + + void setBurnTime(short paramShort); + + short getCookTime(); + + void setCookTime(short paramShort); + + FurnaceInventory getInventory(); +} diff --git a/azurite-api/src/main/java/org/bukkit/block/Hopper.java b/azurite-api/src/main/java/org/bukkit/block/Hopper.java new file mode 100644 index 0000000..e097157 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/block/Hopper.java @@ -0,0 +1,10 @@ +package org.bukkit.block; + +import org.bukkit.inventory.InventoryHolder; + +/** + * Represents a hopper. + */ +public interface Hopper extends BlockState, InventoryHolder { + +} diff --git a/azurite-api/src/main/java/org/bukkit/block/Jukebox.java b/azurite-api/src/main/java/org/bukkit/block/Jukebox.java new file mode 100644 index 0000000..19a3705 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/block/Jukebox.java @@ -0,0 +1,36 @@ +package org.bukkit.block; + +import org.bukkit.Material; + +/** + * Represents a Jukebox + */ +public interface Jukebox extends BlockState { + /** + * Get the record currently playing + * + * @return The record Material, or AIR if none is playing + */ + Material getPlaying(); + + /** + * Set the record currently playing + * + * @param record The record Material, or null/AIR to stop playing + */ + void setPlaying(Material record); + + /** + * Check if the jukebox is currently playing a record + * + * @return True if there is a record playing + */ + boolean isPlaying(); + + /** + * Stop the jukebox playing and eject the current record + * + * @return True if a record was ejected; false if there was none playing + */ + boolean eject(); +} diff --git a/azurite-api/src/main/java/org/bukkit/block/NoteBlock.java b/azurite-api/src/main/java/org/bukkit/block/NoteBlock.java new file mode 100644 index 0000000..bc6c536 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/block/NoteBlock.java @@ -0,0 +1,72 @@ +package org.bukkit.block; + +import org.bukkit.Instrument; +import org.bukkit.Note; + +/** + * Represents a note. + */ +public interface NoteBlock extends BlockState { + + /** + * Gets the note. + * + * @return The note. + */ + Note getNote(); + + /** + * Gets the note. + * + * @return The note ID. + * @deprecated Magic value + */ + @Deprecated + byte getRawNote(); + + /** + * Set the note. + * + * @param note The note. + */ + void setNote(Note note); + + /** + * Set the note. + * + * @param note The note ID. + * @deprecated Magic value + */ + @Deprecated + void setRawNote(byte note); + + /** + * Attempts to play the note at block + *

+ * If the block is no longer a note block, this will return false + * + * @return true if successful, otherwise false + */ + boolean play(); + + /** + * Plays an arbitrary note with an arbitrary instrument + * + * @param instrument Instrument ID + * @param note Note ID + * @return true if successful, otherwise false + * @deprecated Magic value + */ + @Deprecated + boolean play(byte instrument, byte note); + + /** + * Plays an arbitrary note with an arbitrary instrument + * + * @param instrument The instrument + * @param note The note + * @return true if successful, otherwise false + * @see Instrument Note + */ + boolean play(Instrument instrument, Note note); +} diff --git a/azurite-api/src/main/java/org/bukkit/block/PistonMoveReaction.java b/azurite-api/src/main/java/org/bukkit/block/PistonMoveReaction.java new file mode 100644 index 0000000..d1995c8 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/block/PistonMoveReaction.java @@ -0,0 +1,51 @@ +package org.bukkit.block; + +import java.util.HashMap; +import java.util.Map; + +public enum PistonMoveReaction { + + /** + * Indicates that the block can be pushed or pulled. + */ + MOVE(0), + /** + * Indicates the block is fragile and will break if pushed on. + */ + BREAK(1), + /** + * Indicates that the block will resist being pushed or pulled. + */ + BLOCK(2); + + private final int id; + private static final Map byId = new HashMap<>(); + static { + for (PistonMoveReaction reaction : PistonMoveReaction.values()) { + byId.put(reaction.id, reaction); + } + } + + PistonMoveReaction(int id) { + this.id = id; + } + + /** + * @return The ID of the move reaction + * @deprecated Magic value + */ + @Deprecated + public int getId() { + return this.id; + } + + /** + * @param id An ID + * @return The move reaction with that ID + * @deprecated Magic value + */ + @Deprecated + public static PistonMoveReaction getById(int id) { + return byId.get(id); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/block/Sign.java b/azurite-api/src/main/java/org/bukkit/block/Sign.java new file mode 100644 index 0000000..cdd8cf8 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/block/Sign.java @@ -0,0 +1,37 @@ +package org.bukkit.block; + +/** + * Represents either a SignPost or a WallSign + */ +public interface Sign extends BlockState { + + /** + * Gets all the lines of text currently on this sign. + * + * @return Array of Strings containing each line of text + */ + String[] getLines(); + + /** + * Gets the line of text at the specified index. + *

+ * For example, getLine(0) will return the first line of text. + * + * @param index Line number to get the text from, starting at 0 + * @throws IndexOutOfBoundsException Thrown when the line does not exist + * @return Text on the given line + */ + String getLine(int index) throws IndexOutOfBoundsException; + + /** + * Sets the line of text at the specified index. + *

+ * For example, setLine(0, "Line One") will set the first line of text to + * "Line One". + * + * @param index Line number to set the text at, starting from 0 + * @param line New text to set at the specified index + * @throws IndexOutOfBoundsException If the index is out of the range 0..3 + */ + void setLine(int index, String line) throws IndexOutOfBoundsException; +} diff --git a/azurite-api/src/main/java/org/bukkit/block/Skull.java b/azurite-api/src/main/java/org/bukkit/block/Skull.java new file mode 100644 index 0000000..a5fcb2a --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/block/Skull.java @@ -0,0 +1,62 @@ +package org.bukkit.block; + +import org.bukkit.SkullType; + +/** + * Represents a Skull + */ +public interface Skull extends BlockState { + + /** + * Checks to see if the skull has an owner + * + * @return true if the skull has an owner + */ + boolean hasOwner(); + + /** + * Gets the owner of the skull, if one exists + * + * @return the owner of the skull or null if the skull does not have an owner + */ + String getOwner(); + + /** + * Sets the owner of the skull + *

+ * Involves a potentially blocking web request to acquire the profile data for + * the provided name. + * + * @param name the new owner of the skull + * @return true if the owner was successfully set + */ + boolean setOwner(String name); + + /** + * Gets the rotation of the skull in the world + * + * @return the rotation of the skull + */ + BlockFace getRotation(); + + /** + * Sets the rotation of the skull in the world + * + * @param rotation the rotation of the skull + */ + void setRotation(BlockFace rotation); + + /** + * Gets the type of skull + * + * @return the type of skull + */ + SkullType getSkullType(); + + /** + * Sets the type of skull + * + * @param skullType the type of skull + */ + void setSkullType(SkullType skullType); +} diff --git a/azurite-api/src/main/java/org/bukkit/block/banner/Pattern.java b/azurite-api/src/main/java/org/bukkit/block/banner/Pattern.java new file mode 100644 index 0000000..d7842ce --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/block/banner/Pattern.java @@ -0,0 +1,95 @@ +package org.bukkit.block.banner; + +import com.google.common.collect.ImmutableMap; +import org.bukkit.DyeColor; +import org.bukkit.configuration.serialization.ConfigurationSerializable; +import org.bukkit.configuration.serialization.SerializableAs; + +import java.util.Map; +import java.util.NoSuchElementException; + +@SerializableAs("Pattern") +public class Pattern implements ConfigurationSerializable { + + private static final String COLOR = "color"; + private static final String PATTERN = "pattern"; + + private final DyeColor color; + private final PatternType pattern; + + /** + * Creates a new pattern from the specified color and + * pattern type + * + * @param color the pattern color + * @param pattern the pattern type + */ + public Pattern(DyeColor color, PatternType pattern) { + this.color = color; + this.pattern = pattern; + } + + /** + * Constructor for deserialization. + * + * @param map the map to deserialize from + */ + public Pattern(Map map) { + color = DyeColor.valueOf(getString(map, COLOR)); + pattern = PatternType.getByIdentifier(getString(map, PATTERN)); + } + + private static String getString(Map map, Object key) { + Object str = map.get(key); + if (str instanceof String) { + return (String) str; + } + throw new NoSuchElementException(map + " does not contain " + key); + } + + @Override + public Map serialize() { + return ImmutableMap.of( + COLOR, color.toString(), + PATTERN, pattern.getIdentifier() + ); + } + + /** + * Returns the color of the pattern + * + * @return the color of the pattern + */ + public DyeColor getColor() { + return color; + } + + /** + * Returns the type of pattern + * + * @return the pattern type + */ + public PatternType getPattern() { + return pattern; + } + + @Override + public int hashCode() { + int hash = 3; + hash = 97 * hash + (this.color != null ? this.color.hashCode() : 0); + hash = 97 * hash + (this.pattern != null ? this.pattern.hashCode() : 0); + return hash; + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final Pattern other = (Pattern) obj; + return this.color == other.color && this.pattern == other.pattern; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/block/banner/PatternType.java b/azurite-api/src/main/java/org/bukkit/block/banner/PatternType.java new file mode 100644 index 0000000..cdfdfde --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/block/banner/PatternType.java @@ -0,0 +1,80 @@ +package org.bukkit.block.banner; + +import java.util.HashMap; +import java.util.Map; + +public enum PatternType { + BASE("b"), + SQUARE_BOTTOM_LEFT("bl"), + SQUARE_BOTTOM_RIGHT("br"), + SQUARE_TOP_LEFT("tl"), + SQUARE_TOP_RIGHT("tr"), + STRIPE_BOTTOM("bs"), + STRIPE_TOP("ts"), + STRIPE_LEFT("ls"), + STRIPE_RIGHT("rs"), + STRIPE_CENTER("cs"), + STRIPE_MIDDLE("ms"), + STRIPE_DOWNRIGHT("drs"), + STRIPE_DOWNLEFT("dls"), + STRIPE_SMALL("ss"), + CROSS("cr"), + STRAIGHT_CROSS("sc"), + TRIANGLE_BOTTOM("bt"), + TRIANGLE_TOP("tt"), + TRIANGLES_BOTTOM("bts"), + TRIANGLES_TOP("tts"), + DIAGONAL_LEFT("ld"), + DIAGONAL_RIGHT("rd"), + DIAGONAL_LEFT_MIRROR("lud"), + DIAGONAL_RIGHT_MIRROR("rud"), + CIRCLE_MIDDLE("mc"), + RHOMBUS_MIDDLE("mr"), + HALF_VERTICAL("vh"), + HALF_HORIZONTAL("hh"), + HALF_VERTICAL_MIRROR("vhr"), + HALF_HORIZONTAL_MIRROR("hhb"), + BORDER("bo"), + CURLY_BORDER("cbo"), + CREEPER("cre"), + GRADIENT("gra"), + GRADIENT_UP("gru"), + BRICKS("bri"), + SKULL("sku"), + FLOWER("flo"), + MOJANG("moj"); + + private final String identifier; + private static final Map byString = new HashMap(); + + static { + for (PatternType p : values()) { + byString.put(p.identifier, p); + } + } + + PatternType(String key) { + this.identifier = key; + } + + /** + * Returns the identifier used to represent + * this pattern type + * + * @return the pattern's identifier + */ + public String getIdentifier() { + return identifier; + } + + /** + * Returns the pattern type which matches the passed + * identifier or null if no matches are found + * + * @param identifier the identifier + * @return the matched pattern type or null + */ + public static PatternType getByIdentifier(String identifier) { + return byString.get(identifier); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/command/BlockCommandSender.java b/azurite-api/src/main/java/org/bukkit/command/BlockCommandSender.java new file mode 100644 index 0000000..881912d --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/BlockCommandSender.java @@ -0,0 +1,13 @@ +package org.bukkit.command; + +import org.bukkit.block.Block; + +public interface BlockCommandSender extends CommandSender { + + /** + * Returns the block this command sender belongs to + * + * @return Block for the command sender + */ + Block getBlock(); +} diff --git a/azurite-api/src/main/java/org/bukkit/command/Command.java b/azurite-api/src/main/java/org/bukkit/command/Command.java new file mode 100644 index 0000000..9797839 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/Command.java @@ -0,0 +1,449 @@ +package org.bukkit.command; + +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.Server; +import org.bukkit.entity.Player; +import org.bukkit.entity.minecart.CommandMinecart; +import org.bukkit.permissions.Permissible; +import org.bukkit.plugin.PluginDescriptionFile; +import org.bukkit.util.StringUtil; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +/** + * Represents a Command, which executes various tasks upon user input + */ +public abstract class Command { + private String name; + private String nextLabel; + private String label; + private List aliases; + private List activeAliases; + private CommandMap commandMap = null; + protected String description = ""; + protected String usageMessage; + private String permission; + private String permissionMessage; + + public String getTimingName() {return getName();} // Spigot + + protected Command(String name) { + this(name, "", "/" + name, new ArrayList<>()); + } + + protected Command(String name, String description, String usageMessage, List aliases) { + this.name = name; + this.nextLabel = name; + this.label = name; + this.description = description; + this.usageMessage = usageMessage; + this.aliases = aliases; + this.activeAliases = new ArrayList<>(aliases); + } + + /** + * Executes the command, returning its success + * + * @param sender Source object which is executing this command + * @param commandLabel The alias of the command used + * @param args All arguments passed to the command, split via ' ' + * @return true if the command was successful, otherwise false + */ + public abstract boolean execute(CommandSender sender, String commandLabel, String[] args); + + /** + * Executed on tab completion for this command, returning a list of + * options the player can tab through. + * + * @deprecated This method is not supported and returns null + * @param sender Source object which is executing this command + * @param args All arguments passed to the command, split via ' ' + * @return a list of tab-completions for the specified arguments. This + * will never be null. List may be immutable. + */ + @Deprecated + public List tabComplete(CommandSender sender, String[] args) { + return null; + } + + /** + * Executed on tab completion for this command, returning a list of + * options the player can tab through. + * + * @param sender Source object which is executing this command + * @param alias the alias being used + * @param args All arguments passed to the command, split via ' ' + * @return a list of tab-completions for the specified arguments. This + * will never be null. List may be immutable. + * @throws IllegalArgumentException if sender, alias, or args is null + */ + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length == 0) { + return ImmutableList.of(); + } + + String lastWord = args[args.length - 1]; + + Player senderPlayer = sender instanceof Player ? (Player) sender : null; + + ArrayList matchedPlayers = new ArrayList<>(); + for (Player player : sender.getServer().getOnlinePlayers()) { + String name = player.getName(); + //if ((senderPlayer == null || senderPlayer.canSee(player)) && StringUtil.startsWithIgnoreCase(name, lastWord)) { + if ((senderPlayer == null || senderPlayer.canSee(player)) && StringUtil.startsWithIgnoreCase(name, lastWord)) { + matchedPlayers.add(name); + } + } + + matchedPlayers.sort(String.CASE_INSENSITIVE_ORDER); + return matchedPlayers; + } + + // PaperSpigot start - location tab-completes + /** + * Executed on tab completion for this command, returning a list of options the player can tab through. This method + * returns the {@link Location} of the block the player is looking at at the time of the tab complete. + *

+ * Commands that want to use the Location information in their tab-complete implementations need to override this + * method. The Location provided by this method is the block that the player is currently looking at when the player + * attempts the tab complete. For this to be valid, the block must be highlighted by the player (i.e. the player is + * close enough to interact with the block). + * + * @param sender Source object which is executing this command + * @param alias the alias being used + * @param args All arguments passed to the command, split via ' ' + * @param location the location of the block the player is looking at + * @return a list of tab-completions for the specified arguments. This + * will never be null. List may be immutable. + * @throws IllegalArgumentException if sender, alias, or args is null + */ + public List tabComplete(CommandSender sender, String alias, String[] args, Location location) throws IllegalArgumentException { + // Simply default to the standard tab-complete, subclasses can override this if needed + return tabComplete(sender, alias, args); + } + // PaperSpigot end + + /** + * Returns the name of this command + * + * @return Name of this command + */ + public String getName() { + return name; + } + + /** + * Sets the name of this command. + *

+ * May only be used before registering the command. + * Will return true if the new name is set, and false + * if the command has already been registered. + * + * @param name New command name + * @return returns true if the name change happened instantly or false if + * the command was already registered + */ + public boolean setName(String name) { + if (!isRegistered()) { + this.name = name; + return true; + } + return false; + } + + /** + * Gets the permission required by users to be able to perform this + * command + * + * @return Permission name, or null if none + */ + public String getPermission() { + return permission; + } + + /** + * Sets the permission required by users to be able to perform this + * command + * + * @param permission Permission name or null + */ + public void setPermission(String permission) { + this.permission = permission; + } + + /** + * Tests the given {@link CommandSender} to see if they can perform this + * command. + *

+ * If they do not have permission, they will be informed that they cannot + * do this. + * + * @param target User to test + * @return true if they can use it, otherwise false + */ + public boolean testPermission(CommandSender target) { + if (testPermissionSilent(target)) { + return true; + } + + if (permissionMessage == null) { + target.sendMessage(ChatColor.RED + "I'm sorry, but you do not have permission to perform this command. Please contact the server administrators if you believe that this is in error."); + } else if (permissionMessage.length() != 0) { + for (String line : permissionMessage.replace("", permission).split("\n")) { + target.sendMessage(line); + } + } + + return false; + } + + /** + * Tests the given {@link CommandSender} to see if they can perform this + * command. + *

+ * No error is sent to the sender. + * + * @param target User to test + * @return true if they can use it, otherwise false + */ + public boolean testPermissionSilent(CommandSender target) { + if ((permission == null) || (permission.length() == 0)) { + return true; + } + + for (String p : permission.split(";")) { + if (target.hasPermission(p)) { + return true; + } + } + + return false; + } + + /** + * Returns the label for this command + * + * @return Label of this command + */ + public String getLabel() { + return label; + } + + /** + * Sets the label of this command. + *

+ * May only be used before registering the command. + * Will return true if the new name is set, and false + * if the command has already been registered. + * + * @param name The command's name + * @return returns true if the name change happened instantly or false if + * the command was already registered + */ + public boolean setLabel(String name) { + this.nextLabel = name; + if (!isRegistered()) { + this.label = name; + return true; + } + return false; + } + + /** + * Registers this command to a CommandMap. + * Once called it only allows changes the registered CommandMap + * + * @param commandMap the CommandMap to register this command to + * @return true if the registration was successful (the current registered + * CommandMap was the passed CommandMap or null) false otherwise + */ + public boolean register(CommandMap commandMap) { + if (allowChangesFrom(commandMap)) { + this.commandMap = commandMap; + return true; + } + + return false; + } + + /** + * Unregisters this command from the passed CommandMap applying any + * outstanding changes + * + * @param commandMap the CommandMap to unregister + * @return true if the unregistration was successfull (the current + * registered CommandMap was the passed CommandMap or null) false + * otherwise + */ + public boolean unregister(CommandMap commandMap) { + if (allowChangesFrom(commandMap)) { + this.commandMap = null; + this.activeAliases = new ArrayList<>(this.aliases); + this.label = this.nextLabel; + return true; + } + + return false; + } + + private boolean allowChangesFrom(CommandMap commandMap) { + return (null == this.commandMap || this.commandMap == commandMap); + } + + /** + * Returns the current registered state of this command + * + * @return true if this command is currently registered false otherwise + */ + public boolean isRegistered() { + return (null != this.commandMap); + } + + /** + * Returns a list of active aliases of this command + * + * @return List of aliases + */ + public List getAliases() { + return activeAliases; + } + + /** + * Returns a message to be displayed on a failed permission check for this + * command + * + * @return Permission check failed message + */ + public String getPermissionMessage() { + return permissionMessage; + } + + /** + * Gets a brief description of this command + * + * @return Description of this command + */ + public String getDescription() { + return description; + } + + /** + * Gets an example usage of this command + * + * @return One or more example usages + */ + public String getUsage() { + return usageMessage; + } + + /** + * Sets the list of aliases to request on registration for this command. + * This is not effective outside of defining aliases in the {@link + * PluginDescriptionFile#getCommands()} (under the + * `aliases' node) is equivalent to this method. + * + * @param aliases aliases to register to this command + * @return this command object, for chaining + */ + public Command setAliases(List aliases) { + this.aliases = aliases; + if (!isRegistered()) { + this.activeAliases = new ArrayList<>(aliases); + } + return this; + } + + /** + * Sets a brief description of this command. Defining a description in the + * {@link PluginDescriptionFile#getCommands()} (under the + * `description' node) is equivalent to this method. + * + * @param description new command description + * @return this command object, for chaining + */ + public Command setDescription(String description) { + this.description = description; + return this; + } + + /** + * Sets the message sent when a permission check fails + * + * @param permissionMessage new permission message, null to indicate + * default message, or an empty string to indicate no message + * @return this command object, for chaining + */ + public Command setPermissionMessage(String permissionMessage) { + this.permissionMessage = permissionMessage; + return this; + } + + /** + * Sets the example usage of this command + * + * @param usage new example usage + * @return this command object, for chaining + */ + public Command setUsage(String usage) { + this.usageMessage = usage; + return this; + } + + public static void broadcastCommandMessage(CommandSender source, String message) { + broadcastCommandMessage(source, message, true); + } + + public static void broadcastCommandMessage(CommandSender source, String message, boolean sendToSource) { + String result = source.getName() + ": " + message; + + if (source instanceof BlockCommandSender) { + BlockCommandSender blockCommandSender = (BlockCommandSender) source; + + if (blockCommandSender.getBlock().getWorld().getGameRuleValue("commandBlockOutput").equalsIgnoreCase("false")) { + Bukkit.getConsoleSender().sendMessage(result); + return; + } + } else if (source instanceof CommandMinecart) { + CommandMinecart commandMinecart = (CommandMinecart) source; + + if (commandMinecart.getWorld().getGameRuleValue("commandBlockOutput").equalsIgnoreCase("false")) { + Bukkit.getConsoleSender().sendMessage(result); + return; + } + } + + Set users = Bukkit.getPluginManager().getPermissionSubscriptions(Server.BROADCAST_CHANNEL_ADMINISTRATIVE); + String colored = ChatColor.GRAY + "" + ChatColor.ITALIC + "[" + result + ChatColor.GRAY + ChatColor.ITALIC + "]"; + + if (sendToSource && !(source instanceof ConsoleCommandSender)) { + source.sendMessage(message); + } + + for (Permissible user : users) { + if (user instanceof CommandSender) { + CommandSender target = (CommandSender) user; + + if (target instanceof ConsoleCommandSender) { + target.sendMessage(result); + } else if (target != source) { + target.sendMessage(colored); + } + } + } + } + + @Override + public String toString() { + return getClass().getName() + '(' + name + ')'; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/command/CommandException.java b/azurite-api/src/main/java/org/bukkit/command/CommandException.java new file mode 100644 index 0000000..b63015f --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/CommandException.java @@ -0,0 +1,28 @@ +package org.bukkit.command; + +/** + * Thrown when an unhandled exception occurs during the execution of a Command + */ +@SuppressWarnings("serial") +public class CommandException extends RuntimeException { + + /** + * Creates a new instance of CommandException without detail + * message. + */ + public CommandException() {} + + /** + * Constructs an instance of CommandException with the + * specified detail message. + * + * @param msg the detail message. + */ + public CommandException(String msg) { + super(msg); + } + + public CommandException(String msg, Throwable cause) { + super(msg, cause); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/command/CommandExecutor.java b/azurite-api/src/main/java/org/bukkit/command/CommandExecutor.java new file mode 100644 index 0000000..b292a1b --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/CommandExecutor.java @@ -0,0 +1,18 @@ +package org.bukkit.command; + +/** + * Represents a class which contains a single method for executing commands + */ +public interface CommandExecutor { + + /** + * Executes the given command, returning its success + * + * @param sender Source of the command + * @param command Command which was executed + * @param label Alias of the command which was used + * @param args Passed command arguments + * @return true if a valid command, otherwise false + */ + boolean onCommand(CommandSender sender, Command command, String label, String[] args); +} diff --git a/azurite-api/src/main/java/org/bukkit/command/CommandMap.java b/azurite-api/src/main/java/org/bukkit/command/CommandMap.java new file mode 100644 index 0000000..6be965e --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/CommandMap.java @@ -0,0 +1,109 @@ +package org.bukkit.command; + +import java.util.List; + +public interface CommandMap { + + /** + * Registers all the commands belonging to a certain plugin. + *

+ * Caller can use:- + *

    + *
  • command.getName() to determine the label registered for this + * command + *
  • command.getAliases() to determine the aliases which where + * registered + *
+ * + * @param fallbackPrefix a prefix which is prepended to each command with + * a ':' one or more times to make the command unique + * @param commands a list of commands to register + */ + void registerAll(String fallbackPrefix, List commands); + + /** + * Registers a command. Returns true on success; false if name is already + * taken and fallback had to be used. + *

+ * Caller can use:- + *

    + *
  • command.getName() to determine the label registered for this + * command + *
  • command.getAliases() to determine the aliases which where + * registered + *
+ * + * @param label the label of the command, without the '/'-prefix. + * @param fallbackPrefix a prefix which is prepended to the command with a + * ':' one or more times to make the command unique + * @param command the command to register + * @return true if command was registered with the passed in label, false + * otherwise, which indicates the fallbackPrefix was used one or more + * times + */ + boolean register(String label, String fallbackPrefix, Command command); + + /** + * Registers a command. Returns true on success; false if name is already + * taken and fallback had to be used. + *

+ * Caller can use:- + *

    + *
  • command.getName() to determine the label registered for this + * command + *
  • command.getAliases() to determine the aliases which where + * registered + *
+ * + * @param fallbackPrefix a prefix which is prepended to the command with a + * ':' one or more times to make the command unique + * @param command the command to register, from which label is determined + * from the command name + * @return true if command was registered with the passed in label, false + * otherwise, which indicates the fallbackPrefix was used one or more + * times + */ + boolean register(String fallbackPrefix, Command command); + + /** + * Looks for the requested command and executes it if found. + * + * @param sender The command's sender + * @param cmdLine command + arguments. Example: "/test abc 123" + * @return returns false if no target is found, true otherwise. + * @throws CommandException Thrown when the executor for the given command + * fails with an unhandled exception + */ + boolean dispatch(CommandSender sender, String cmdLine) throws CommandException; + + /** + * Clears all registered commands. + */ + void clearCommands(); + + /** + * Gets the command registered to the specified name + * + * @param name Name of the command to retrieve + * @return Command with the specified name or null if a command with that + * label doesn't exist + */ + Command getCommand(String name); + + + /** + * Looks for the requested command and executes an appropriate + * tab-completer if found. This method will also tab-complete partial + * commands. + * + * @param sender The command's sender. + * @param cmdLine The entire command string to tab-complete, excluding + * initial slash. + * @return a list of possible tab-completions. This list may be immutable. + * Will be null if no matching command of which sender has permission. + * @throws CommandException Thrown when the tab-completer for the given + * command fails with an unhandled exception + * @throws IllegalArgumentException if either sender or cmdLine are null + */ + List tabComplete(CommandSender sender, String cmdLine) throws IllegalArgumentException; +} diff --git a/azurite-api/src/main/java/org/bukkit/command/CommandSender.java b/azurite-api/src/main/java/org/bukkit/command/CommandSender.java new file mode 100644 index 0000000..978b1cf --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/CommandSender.java @@ -0,0 +1,61 @@ +package org.bukkit.command; + +import org.bukkit.Server; +import org.bukkit.permissions.Permissible; + +public interface CommandSender extends Permissible { + + /** + * Sends this sender a message + * + * @param message Message to be displayed + */ + void sendMessage(String message); + + /** + * Sends this sender multiple messages + * + * @param messages An array of messages to be displayed + */ + void sendMessage(String[] messages); + + /** + * Returns the server instance that this command is running on + * + * @return Server instance + */ + Server getServer(); + + /** + * Gets the name of this command sender + * + * @return Name of the sender + */ + String getName(); + + // Paper start + /** + * Sends the component to the sender + * + *

If this sender does not support sending full components then + * the component will be sent as legacy text.

+ * + * @param component the component to send + */ + default void sendMessage(net.md_5.bungee.api.chat.BaseComponent component) { + this.sendMessage(component.toLegacyText()); + } + + /** + * Sends an array of components as a single message to the sender + * + *

If this sender does not support sending full components then + * the components will be sent as legacy text.

+ * + * @param components the components to send + */ + default void sendMessage(net.md_5.bungee.api.chat.BaseComponent... components) { + this.sendMessage(new net.md_5.bungee.api.chat.TextComponent(components).toLegacyText()); + } + // Paper end +} diff --git a/azurite-api/src/main/java/org/bukkit/command/ConsoleCommandSender.java b/azurite-api/src/main/java/org/bukkit/command/ConsoleCommandSender.java new file mode 100644 index 0000000..f309c2e --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/ConsoleCommandSender.java @@ -0,0 +1,6 @@ +package org.bukkit.command; + +import org.bukkit.conversations.Conversable; + +public interface ConsoleCommandSender extends CommandSender, Conversable { +} diff --git a/azurite-api/src/main/java/org/bukkit/command/FormattedCommandAlias.java b/azurite-api/src/main/java/org/bukkit/command/FormattedCommandAlias.java new file mode 100644 index 0000000..21c6e0b --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/FormattedCommandAlias.java @@ -0,0 +1,122 @@ +package org.bukkit.command; + +import org.bukkit.Bukkit; + +import java.util.ArrayList; + +public class FormattedCommandAlias extends Command { + private final String[] formatStrings; + + public FormattedCommandAlias(String alias, String[] formatStrings) { + super(alias); + this.formatStrings = formatStrings; + } + + @Override + public boolean execute(CommandSender sender, String commandLabel, String[] args) { + boolean result = false; + ArrayList commands = new ArrayList(); + for (String formatString : formatStrings) { + try { + commands.add(buildCommand(formatString, args)); + } catch (Throwable throwable) { + if (throwable instanceof IllegalArgumentException) { + sender.sendMessage(throwable.getMessage()); + } else { + sender.sendMessage(org.bukkit.ChatColor.RED + "An internal error occurred while attempting to perform this command"); + } + return false; + } + } + + for (String command : commands) { + result |= Bukkit.dispatchCommand(sender, command); + } + + return result; + } + + private String buildCommand(String formatString, String[] args) { + int index = formatString.indexOf("$"); + while (index != -1) { + int start = index; + + if (index > 0 && formatString.charAt(start - 1) == '\\') { + formatString = formatString.substring(0, start - 1) + formatString.substring(start); + index = formatString.indexOf("$", index); + continue; + } + + boolean required = false; + if (formatString.charAt(index + 1) == '$') { + required = true; + // Move index past the second $ + index++; + } + + // Move index past the $ + index++; + int argStart = index; + while (index < formatString.length() && inRange(((int) formatString.charAt(index)) - 48, 0, 9)) { + // Move index past current digit + index++; + } + + // No numbers found + if (argStart == index) { + throw new IllegalArgumentException("Invalid replacement token"); + } + + int position = Integer.parseInt(formatString.substring(argStart, index)); + + // Arguments are not 0 indexed + if (position == 0) { + throw new IllegalArgumentException("Invalid replacement token"); + } + + // Convert position to 0 index + position--; + + boolean rest = false; + if (index < formatString.length() && formatString.charAt(index) == '-') { + rest = true; + // Move index past the - + index++; + } + + int end = index; + + if (required && position >= args.length) { + throw new IllegalArgumentException("Missing required argument " + (position + 1)); + } + + StringBuilder replacement = new StringBuilder(); + if (rest && position < args.length) { + for (int i = position; i < args.length; i++) { + if (i != position) { + replacement.append(' '); + } + replacement.append(args[i]); + } + } else if (position < args.length) { + replacement.append(args[position]); + } + + formatString = formatString.substring(0, start) + replacement.toString() + formatString.substring(end); + // Move index past the replaced data so we don't process it again + index = start + replacement.length(); + + // Move to the next replacement token + index = formatString.indexOf("$", index); + } + + return formatString; + } + + @Override // Spigot + public String getTimingName() {return "Command Forwarder - " + super.getTimingName();} // Spigot + + private static boolean inRange(int i, int j, int k) { + return i >= j && i <= k; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/command/MultipleCommandAlias.java b/azurite-api/src/main/java/org/bukkit/command/MultipleCommandAlias.java new file mode 100644 index 0000000..a0a4129 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/MultipleCommandAlias.java @@ -0,0 +1,33 @@ +package org.bukkit.command; + +/** + * Represents a command that delegates to one or more other commands + */ +public class MultipleCommandAlias extends Command { + private Command[] commands; + + public MultipleCommandAlias(String name, Command[] commands) { + super(name); + this.commands = commands; + } + + /** + * Gets the commands associated with the multi-command alias. + * + * @return commands associated with alias + */ + public Command[] getCommands() { + return commands; + } + + @Override + public boolean execute(CommandSender sender, String commandLabel, String[] args) { + boolean result = false; + + for (Command command : commands) { + result |= command.execute(sender, commandLabel, args); + } + + return result; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/command/PluginCommand.java b/azurite-api/src/main/java/org/bukkit/command/PluginCommand.java new file mode 100644 index 0000000..885d206 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/PluginCommand.java @@ -0,0 +1,171 @@ +package org.bukkit.command; + +import org.apache.commons.lang.Validate; +import org.bukkit.Location; +import org.bukkit.plugin.Plugin; + +import java.util.List; + +/** + * Represents a {@link Command} belonging to a plugin + */ +public final class PluginCommand extends Command implements PluginIdentifiableCommand { + private final Plugin owningPlugin; + private CommandExecutor executor; + private TabCompleter completer; + + protected PluginCommand(String name, Plugin owner) { + super(name); + this.executor = owner; + this.owningPlugin = owner; + this.usageMessage = ""; + } + + /** + * Executes the command, returning its success + * + * @param sender Source object which is executing this command + * @param commandLabel The alias of the command used + * @param args All arguments passed to the command, split via ' ' + * @return true if the command was successful, otherwise false + */ + @Override + public boolean execute(CommandSender sender, String commandLabel, String[] args) { + boolean success = false; + + if (!owningPlugin.isEnabled()) { + return false; + } + + if (!testPermission(sender)) { + return true; + } + + try { + success = executor.onCommand(sender, this, commandLabel, args); + } catch (Throwable ex) { + throw new CommandException("Unhandled exception executing command '" + commandLabel + "' in plugin " + owningPlugin.getDescription().getFullName(), ex); + } + + if (!success && usageMessage.length() > 0) { + for (String line : usageMessage.replace("", commandLabel).split("\n")) { + sender.sendMessage(line); + } + } + + return success; + } + + /** + * Sets the {@link CommandExecutor} to run when parsing this command + * + * @param executor New executor to run + */ + public void setExecutor(CommandExecutor executor) { + this.executor = executor == null ? owningPlugin : executor; + } + + /** + * Gets the {@link CommandExecutor} associated with this command + * + * @return CommandExecutor object linked to this command + */ + public CommandExecutor getExecutor() { + return executor; + } + + /** + * Sets the {@link TabCompleter} to run when tab-completing this command. + *

+ * If no TabCompleter is specified, and the command's executor implements + * TabCompleter, then the executor will be used for tab completion. + * + * @param completer New tab completer + */ + public void setTabCompleter(TabCompleter completer) { + this.completer = completer; + } + + /** + * Gets the {@link TabCompleter} associated with this command. + * + * @return TabCompleter object linked to this command + */ + public TabCompleter getTabCompleter() { + return completer; + } + + /** + * Gets the owner of this PluginCommand + * + * @return Plugin that owns this command + */ + public Plugin getPlugin() { + return owningPlugin; + } + + /** + * {@inheritDoc} + *

+ * Delegates to the tab completer if present. + *

+ * If it is not present or returns null, will delegate to the current + * command executor if it implements {@link TabCompleter}. If a non-null + * list has not been found, will default to standard player name + * completion in {@link + * Command#tabComplete(CommandSender, String, String[])}. + *

+ * This method does not consider permissions. + * + * @throws CommandException if the completer or executor throw an + * exception during the process of tab-completing. + * @throws IllegalArgumentException if sender, alias, or args is null + */ + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws CommandException, IllegalArgumentException { + return tabComplete(sender, alias, args, null); // PaperSpigot - The code from this method has been (slightly modified) moved to the Location method. + } + + // PaperSpigot start - location tab-completes + /** + * This code was copied from tabComplete(CommandSender sender, String alias, String[] args) + */ + @Override + public List tabComplete(CommandSender sender, String alias, String[] args, Location location) throws CommandException, IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + List completions = null; + try { + if (completer != null) { + completions = completer.onTabComplete(sender, this, alias, args, location); // PaperSpigot - add location argument + } + if (completions == null && executor instanceof TabCompleter) { + completions = ((TabCompleter) executor).onTabComplete(sender, this, alias, args, location); // PaperSpigot - add location argument + } + } catch (Throwable ex) { + StringBuilder message = new StringBuilder(); + message.append("Unhandled exception during tab completion for command '/").append(alias).append(' '); + for (String arg : args) { + message.append(arg).append(' '); + } + message.deleteCharAt(message.length() - 1).append("' in plugin ").append(owningPlugin.getDescription().getFullName()); + throw new CommandException(message.toString(), ex); + } + + if (completions == null) { + return super.tabComplete(sender, alias, args); + } + return completions; + } + // PaperSpigot end + + @Override + public String toString() { + StringBuilder stringBuilder = new StringBuilder(super.toString()); + stringBuilder.deleteCharAt(stringBuilder.length() - 1); + stringBuilder.append(", ").append(owningPlugin.getDescription().getFullName()).append(')'); + return stringBuilder.toString(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/command/PluginCommandYamlParser.java b/azurite-api/src/main/java/org/bukkit/command/PluginCommandYamlParser.java new file mode 100644 index 0000000..aa9adba --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/PluginCommandYamlParser.java @@ -0,0 +1,76 @@ +package org.bukkit.command; + +import org.bukkit.Bukkit; +import org.bukkit.plugin.Plugin; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +public class PluginCommandYamlParser { + + public static List parse(Plugin plugin) { + List pluginCmds = new ArrayList(); + + Map> map = plugin.getDescription().getCommands(); + + if (map == null) { + return pluginCmds; + } + + for (Entry> entry : map.entrySet()) { + if (entry.getKey().contains(":")) { + Bukkit.getServer().getLogger().severe("Could not load command " + entry.getKey() + " for plugin " + plugin.getName() + ": Illegal Characters"); + continue; + } + Command newCmd = new PluginCommand(entry.getKey(), plugin); + Object description = entry.getValue().get("description"); + Object usage = entry.getValue().get("usage"); + Object aliases = entry.getValue().get("aliases"); + Object permission = entry.getValue().get("permission"); + Object permissionMessage = entry.getValue().get("permission-message"); + + if (description != null) { + newCmd.setDescription(description.toString()); + } + + if (usage != null) { + newCmd.setUsage(usage.toString()); + } + + if (aliases != null) { + List aliasList = new ArrayList(); + + if (aliases instanceof List) { + for (Object o : (List) aliases) { + if (o.toString().contains(":")) { + Bukkit.getServer().getLogger().severe("Could not load alias " + o.toString() + " for plugin " + plugin.getName() + ": Illegal Characters"); + continue; + } + aliasList.add(o.toString()); + } + } else { + if (aliases.toString().contains(":")) { + Bukkit.getServer().getLogger().severe("Could not load alias " + aliases.toString() + " for plugin " + plugin.getName() + ": Illegal Characters"); + } else { + aliasList.add(aliases.toString()); + } + } + + newCmd.setAliases(aliasList); + } + + if (permission != null) { + newCmd.setPermission(permission.toString()); + } + + if (permissionMessage != null) { + newCmd.setPermissionMessage(permissionMessage.toString()); + } + + pluginCmds.add(newCmd); + } + return pluginCmds; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/command/PluginIdentifiableCommand.java b/azurite-api/src/main/java/org/bukkit/command/PluginIdentifiableCommand.java new file mode 100644 index 0000000..5777b76 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/PluginIdentifiableCommand.java @@ -0,0 +1,19 @@ +package org.bukkit.command; + +import org.bukkit.plugin.Plugin; + +/** + * This interface is used by the help system to group commands into + * sub-indexes based on the {@link Plugin} they are a part of. Custom command + * implementations will need to implement this interface to have a sub-index + * automatically generated on the plugin's behalf. + */ +public interface PluginIdentifiableCommand { + + /** + * Gets the owner of this PluginIdentifiableCommand. + * + * @return Plugin that owns this PluginIdentifiableCommand. + */ + Plugin getPlugin(); +} diff --git a/azurite-api/src/main/java/org/bukkit/command/ProxiedCommandSender.java b/azurite-api/src/main/java/org/bukkit/command/ProxiedCommandSender.java new file mode 100644 index 0000000..24c4eba --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/ProxiedCommandSender.java @@ -0,0 +1,20 @@ + +package org.bukkit.command; + +public interface ProxiedCommandSender extends CommandSender { + + /** + * Returns the CommandSender which triggered this proxied command + * + * @return the caller which triggered the command + */ + CommandSender getCaller(); + + /** + * Returns the CommandSender which is being used to call the command + * + * @return the caller which the command is being run as + */ + CommandSender getCallee(); + +} diff --git a/azurite-api/src/main/java/org/bukkit/command/RemoteConsoleCommandSender.java b/azurite-api/src/main/java/org/bukkit/command/RemoteConsoleCommandSender.java new file mode 100644 index 0000000..dc3bc1d --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/RemoteConsoleCommandSender.java @@ -0,0 +1,4 @@ +package org.bukkit.command; + +public interface RemoteConsoleCommandSender extends CommandSender { +} diff --git a/azurite-api/src/main/java/org/bukkit/command/SimpleCommandMap.java b/azurite-api/src/main/java/org/bukkit/command/SimpleCommandMap.java new file mode 100644 index 0000000..b217b6e --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/SimpleCommandMap.java @@ -0,0 +1,261 @@ +package org.bukkit.command; + +import org.apache.commons.lang.Validate; +import org.bukkit.Location; +import org.bukkit.Server; +import org.bukkit.command.defaults.HelpCommand; +import org.bukkit.command.defaults.PluginsCommand; +import org.bukkit.command.defaults.ReloadCommand; +import org.bukkit.command.defaults.VanillaCommand; +import org.bukkit.entity.Player; +import org.bukkit.util.StringUtil; + +import java.util.*; +import java.util.regex.Pattern; + +import static org.bukkit.util.Java15Compat.Arrays_copyOfRange; + +public class SimpleCommandMap implements CommandMap { + private static final Pattern PATTERN_ON_SPACE = Pattern.compile(" ", Pattern.LITERAL); + protected final Map knownCommands = new HashMap<>(); + private final Server server; + + public SimpleCommandMap(final Server server) { + this.server = server; + setDefaultCommands(); + } + + private void setDefaultCommands() { + register("bukkit", new ReloadCommand("reload")); + register("bukkit", new PluginsCommand("plugins")); + } + + public void setFallbackCommands() { + register("bukkit", new HelpCommand()); + } + + /** + * {@inheritDoc} + */ + public void registerAll(String fallbackPrefix, List commands) { + if (commands != null) { + for (Command c : commands) { + register(fallbackPrefix, c); + } + } + } + + /** + * {@inheritDoc} + */ + public boolean register(String fallbackPrefix, Command command) { + return register(command.getName(), fallbackPrefix, command); + } + + /** + * {@inheritDoc} + */ + public boolean register(String label, String fallbackPrefix, Command command) { + label = label.toLowerCase().trim(); + fallbackPrefix = fallbackPrefix.toLowerCase().trim(); + boolean registered = register(label, command, false, fallbackPrefix); + + Iterator iterator = command.getAliases().iterator(); + while (iterator.hasNext()) { + if (!register(iterator.next(), command, true, fallbackPrefix)) { + iterator.remove(); + } + } + + // If we failed to register under the real name, we need to set the command label to the direct address + if (!registered) { + command.setLabel(fallbackPrefix + ":" + label); + } + + // Register to us so further updates of the commands label and aliases are postponed until its reregistered + command.register(this); + + return registered; + } + + /** + * Registers a command with the given name is possible. Also uses + * fallbackPrefix to create a unique name. + * + * @param label the name of the command, without the '/'-prefix. + * @param command the command to register + * @param isAlias whether the command is an alias + * @param fallbackPrefix a prefix which is prepended to the command for a + * unique address + * @return true if command was registered, false otherwise. + */ + private synchronized boolean register(String label, Command command, boolean isAlias, String fallbackPrefix) { + knownCommands.put(fallbackPrefix + ":" + label, command); + if ((command instanceof VanillaCommand || isAlias) && knownCommands.containsKey(label)) { + // Request is for an alias/fallback command and it conflicts with + // a existing command or previous alias ignore it + // Note: This will mean it gets removed from the commands list of active aliases + return false; + } + + // If the command exists but is an alias we overwrite it, otherwise we return + Command conflict = knownCommands.get(label); + if (conflict != null && conflict.getLabel().equals(label)) { + return false; + } + + if (!isAlias) { + command.setLabel(label); + } + knownCommands.put(label, command); + + return true; + } + + /** + * {@inheritDoc} + */ + public boolean dispatch(CommandSender sender, String commandLine) throws CommandException { + String[] args = PATTERN_ON_SPACE.split(commandLine); + + if (args.length == 0) { + return false; + } + + String sentCommandLabel = args[0].toLowerCase(); + Command target = getCommand(sentCommandLabel); + + if (target == null) { + return false; + } + + try { + // Note: we don't return the result of target.execute as thats success / failure, we return handled (true) or not handled (false) + target.execute(sender, sentCommandLabel, Arrays_copyOfRange(args, 1, args.length)); + } catch (CommandException ex) { + throw ex; + } catch (Throwable ex) { + throw new CommandException("Unhandled exception executing '" + commandLine + "' in " + target, ex); + } + + // return true as command was handled + return true; + } + + public synchronized void clearCommands() { + for (Map.Entry entry : knownCommands.entrySet()) { + entry.getValue().unregister(this); + } + knownCommands.clear(); + setDefaultCommands(); + } + + public Command getCommand(String name) { + return knownCommands.get(name.toLowerCase()); + } + + public List tabComplete(CommandSender sender, String cmdLine) { + return tabComplete(sender, cmdLine, null); // PaperSpigot - location tab-completes, code moved below + } + + // PaperSpigot start - location tab-completes + /* + this code was copied, except for the noted change, from tabComplete(CommandSender sender, String cmdLine) + */ + public List tabComplete(CommandSender sender, String cmdLine, Location location) { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(cmdLine, "Command line cannot null"); + + int spaceIndex = cmdLine.indexOf(' '); + + if (spaceIndex == -1) { + ArrayList completions = new ArrayList<>(); + Map knownCommands = this.knownCommands; + + final String prefix = (sender instanceof Player ? "/" : ""); + + for (Map.Entry commandEntry : knownCommands.entrySet()) { + Command command = commandEntry.getValue(); + + if (!command.testPermissionSilent(sender)) { + continue; + } + + String name = commandEntry.getKey(); // Use the alias, not command name + + if (StringUtil.startsWithIgnoreCase(name, cmdLine)) { + completions.add(prefix + name); + } + } + + completions.sort(String.CASE_INSENSITIVE_ORDER); + return completions; + } + + String commandName = cmdLine.substring(0, spaceIndex); + Command target = getCommand(commandName); + + if (target == null) { + return null; + } + + if (!target.testPermissionSilent(sender)) { + return null; + } + + String argLine = cmdLine.substring(spaceIndex + 1); + String[] args = PATTERN_ON_SPACE.split(argLine, -1); + + try { + return target.tabComplete(sender, commandName, args, location); // PaperSpigot - add location argument + } catch (CommandException ex) { + throw ex; + } catch (Throwable ex) { + throw new CommandException("Unhandled exception executing tab-completer for '" + cmdLine + "' in " + target, ex); + } + } + // PaperSpigot end + + public Collection getCommands() { + return Collections.unmodifiableCollection(knownCommands.values()); + } + + public void registerServerAliases() { + Map values = server.getCommandAliases(); + + for (String alias : values.keySet()) { + if (alias.contains(":") || alias.contains(" ")) { + continue; + } + + String[] commandStrings = values.get(alias); + List targets = new ArrayList<>(); + StringBuilder bad = new StringBuilder(); + + for (String commandString : commandStrings) { + String[] commandArgs = commandString.split(" "); + Command command = getCommand(commandArgs[0]); + + if (command == null) { + if (bad.length() > 0) { + bad.append(", "); + } + bad.append(commandString); + } else { + targets.add(commandString); + } + } + + if (bad.length() > 0) { + continue; + } + + // We register these as commands so they have absolute priority. + if (!targets.isEmpty()) { + knownCommands.put(alias.toLowerCase(), new FormattedCommandAlias(alias.toLowerCase(), targets.toArray(new String[0]))); + } else { + knownCommands.remove(alias.toLowerCase()); + } + } + } +} diff --git a/azurite-api/src/main/java/org/bukkit/command/TabCommandExecutor.java b/azurite-api/src/main/java/org/bukkit/command/TabCommandExecutor.java new file mode 100644 index 0000000..35bb34c --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/TabCommandExecutor.java @@ -0,0 +1,16 @@ +package org.bukkit.command; + +import java.util.List; + +/** + * Represents a class which can handle command tab completion and commands + * + * @deprecated Remains for plugins that would have implemented it even without + * functionality + * @see TabExecutor + */ +@Deprecated +public interface TabCommandExecutor extends CommandExecutor { + List onTabComplete(); + +} diff --git a/azurite-api/src/main/java/org/bukkit/command/TabCompleter.java b/azurite-api/src/main/java/org/bukkit/command/TabCompleter.java new file mode 100644 index 0000000..c3ddad2 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/TabCompleter.java @@ -0,0 +1,30 @@ +package org.bukkit.command; + +import org.bukkit.Location; + +import java.util.List; + +/** + * Represents a class which can suggest tab completions for commands. + */ +public interface TabCompleter { + + /** + * Requests a list of possible completions for a command argument. + * + * @param sender Source of the command + * @param command Command which was executed + * @param alias The alias used + * @param args The arguments passed to the command, including final + * partial argument to be completed and command label + * @return A List of possible completions for the final argument, or null + * to default to the command executor + */ + List onTabComplete(CommandSender sender, Command command, String alias, String[] args); + + // PaperSpigot start - location tab-completes + default List onTabComplete(CommandSender sender, Command command, String alias, String[] args, Location location) { + return onTabComplete(sender, command, alias, args); + } + // PaperSpigot end +} diff --git a/azurite-api/src/main/java/org/bukkit/command/TabExecutor.java b/azurite-api/src/main/java/org/bukkit/command/TabExecutor.java new file mode 100644 index 0000000..6b8e3fb --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/TabExecutor.java @@ -0,0 +1,8 @@ +package org.bukkit.command; + +/** + * This class is provided as a convenience to implement both TabCompleter and + * CommandExecutor. + */ +public interface TabExecutor extends TabCompleter, CommandExecutor { +} diff --git a/azurite-api/src/main/java/org/bukkit/command/defaults/AchievementCommand.java b/azurite-api/src/main/java/org/bukkit/command/defaults/AchievementCommand.java new file mode 100644 index 0000000..46b690e --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/defaults/AchievementCommand.java @@ -0,0 +1,183 @@ +package org.bukkit.command.defaults; + +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang.Validate; +import org.bukkit.*; +import org.bukkit.Statistic.Type; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import org.bukkit.event.player.PlayerAchievementAwardedEvent; +import org.bukkit.event.player.PlayerStatisticIncrementEvent; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +@Deprecated +public class AchievementCommand extends VanillaCommand { + public AchievementCommand() { + super("achievement"); + this.description = "Gives the specified player an achievement or changes a statistic value. Use '*' to give all achievements."; + this.usageMessage = "/achievement give [player]"; + this.setPermission("bukkit.command.achievement"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + + if (args.length < 2) { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + if (!args[0].equalsIgnoreCase("give")) { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + String statisticString = args[1]; + Player player = null; + + if (args.length > 2) { + player = Bukkit.getPlayer(args[1]); + } else if (sender instanceof Player) { + player = (Player) sender; + } + + if (player == null) { + sender.sendMessage("You must specify which player you wish to perform this action on."); + return true; + } + + if (statisticString.equals("*")) { + for (Achievement achievement : Achievement.values()) { + if (player.hasAchievement(achievement)) { + continue; + } + PlayerAchievementAwardedEvent event = new PlayerAchievementAwardedEvent(player, achievement); + Bukkit.getServer().getPluginManager().callEvent(event); + if (!event.isCancelled()) { + player.awardAchievement(achievement); + } + } + Command.broadcastCommandMessage(sender, String.format("Successfully given all achievements to %s", player.getName())); + return true; + } + + Achievement achievement = Bukkit.getUnsafe().getAchievementFromInternalName(statisticString); + Statistic statistic = Bukkit.getUnsafe().getStatisticFromInternalName(statisticString); + + if (achievement != null) { + if (player.hasAchievement(achievement)) { + sender.sendMessage(String.format("%s already has achievement %s", player.getName(), statisticString)); + return true; + } + + PlayerAchievementAwardedEvent event = new PlayerAchievementAwardedEvent(player, achievement); + Bukkit.getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { + sender.sendMessage(String.format("Unable to award %s the achievement %s", player.getName(), statisticString)); + return true; + } + player.awardAchievement(achievement); + + Command.broadcastCommandMessage(sender, String.format("Successfully given %s the stat %s", player.getName(), statisticString)); + return true; + } + + if (statistic == null) { + sender.sendMessage(String.format("Unknown achievement or statistic '%s'", statisticString)); + return true; + } + + if (statistic.getType() == Type.UNTYPED) { + PlayerStatisticIncrementEvent event = new PlayerStatisticIncrementEvent(player, statistic, player.getStatistic(statistic), player.getStatistic(statistic) + 1); + Bukkit.getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { + sender.sendMessage(String.format("Unable to increment %s for %s", statisticString, player.getName())); + return true; + } + player.incrementStatistic(statistic); + Command.broadcastCommandMessage(sender, String.format("Successfully given %s the stat %s", player.getName(), statisticString)); + return true; + } + + if (statistic.getType() == Type.ENTITY) { + EntityType entityType = EntityType.fromName(statisticString.substring(statisticString.lastIndexOf(".") + 1)); + + if (entityType == null) { + sender.sendMessage(String.format("Unknown achievement or statistic '%s'", statisticString)); + return true; + } + + PlayerStatisticIncrementEvent event = new PlayerStatisticIncrementEvent(player, statistic, player.getStatistic(statistic), player.getStatistic(statistic) + 1, entityType); + Bukkit.getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { + sender.sendMessage(String.format("Unable to increment %s for %s", statisticString, player.getName())); + return true; + } + + try { + player.incrementStatistic(statistic, entityType); + } catch (IllegalArgumentException e) { + sender.sendMessage(String.format("Unknown achievement or statistic '%s'", statisticString)); + return true; + } + } else { + int id; + try { + id = getInteger(sender, statisticString.substring(statisticString.lastIndexOf(".") + 1), 0, Integer.MAX_VALUE, true); + } catch (NumberFormatException e) { + sender.sendMessage(e.getMessage()); + return true; + } + + Material material = Material.getMaterial(id); + + if (material == null) { + sender.sendMessage(String.format("Unknown achievement or statistic '%s'", statisticString)); + return true; + } + + PlayerStatisticIncrementEvent event = new PlayerStatisticIncrementEvent(player, statistic, player.getStatistic(statistic), player.getStatistic(statistic) + 1, material); + Bukkit.getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { + sender.sendMessage(String.format("Unable to increment %s for %s", statisticString, player.getName())); + return true; + } + + try { + player.incrementStatistic(statistic, material); + } catch (IllegalArgumentException e) { + sender.sendMessage(String.format("Unknown achievement or statistic '%s'", statisticString)); + return true; + } + } + + Command.broadcastCommandMessage(sender, String.format("Successfully given %s the stat %s", player.getName(), statisticString)); + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length == 1) { + return Arrays.asList("give"); + } + + if (args.length == 2) { + return Bukkit.getUnsafe().tabCompleteInternalStatisticOrAchievementName(args[1], new ArrayList()); + } + + if (args.length == 3) { + return super.tabComplete(sender, alias, args); + } + return ImmutableList.of(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/command/defaults/BanCommand.java b/azurite-api/src/main/java/org/bukkit/command/defaults/BanCommand.java new file mode 100644 index 0000000..ab784a7 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/defaults/BanCommand.java @@ -0,0 +1,55 @@ +package org.bukkit.command.defaults; + +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang.Validate; +import org.bukkit.BanList; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.List; + +@Deprecated +public class BanCommand extends VanillaCommand { + public BanCommand() { + super("ban"); + this.description = "Prevents the specified player from using this server"; + this.usageMessage = "/ban [reason ...]"; + this.setPermission("bukkit.command.ban.player"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + if (args.length == 0) { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + String reason = args.length > 0 ? StringUtils.join(args, ' ', 1, args.length) : null; + Bukkit.getBanList(BanList.Type.NAME).addBan(args[0], reason, null, sender.getName()); + + Player player = Bukkit.getPlayer(args[0]); + if (player != null) { + player.kickPlayer("Banned by admin."); + } + + Command.broadcastCommandMessage(sender, "Banned player " + args[0]); + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length >= 1) { + return super.tabComplete(sender, alias, args); + } + return ImmutableList.of(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/command/defaults/BanIpCommand.java b/azurite-api/src/main/java/org/bukkit/command/defaults/BanIpCommand.java new file mode 100644 index 0000000..a6b6342 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/defaults/BanIpCommand.java @@ -0,0 +1,77 @@ +package org.bukkit.command.defaults; + +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang.Validate; +import org.bukkit.BanList; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.List; +import java.util.regex.Pattern; + +@Deprecated +public class BanIpCommand extends VanillaCommand { + public static final Pattern ipValidity = Pattern.compile("^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"); + + public BanIpCommand() { + super("ban-ip"); + this.description = "Prevents the specified IP address from using this server"; + this.usageMessage = "/ban-ip [reason ...]"; + this.setPermission("bukkit.command.ban.ip"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + if (args.length < 1) { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + String reason = args.length > 0 ? StringUtils.join(args, ' ', 1, args.length) : null; + + if (ipValidity.matcher(args[0]).matches()) { + processIPBan(args[0], sender, reason); + } else { + Player player = Bukkit.getPlayer(args[0]); + + if (player == null) { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + processIPBan(player.getAddress().getAddress().getHostAddress(), sender, reason); + } + + return true; + } + + private void processIPBan(String ip, CommandSender sender, String reason) { + Bukkit.getBanList(BanList.Type.IP).addBan(ip, reason, null, sender.getName()); + + // Find all matching players and kick + for (Player player : Bukkit.getOnlinePlayers()) { + if (player.getAddress().getAddress().getHostAddress().equals(ip)) { + player.kickPlayer("You have been IP banned."); + } + } + + Command.broadcastCommandMessage(sender, "Banned IP Address " + ip); + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length == 1) { + return super.tabComplete(sender, alias, args); + } + return ImmutableList.of(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/command/defaults/BanListCommand.java b/azurite-api/src/main/java/org/bukkit/command/defaults/BanListCommand.java new file mode 100644 index 0000000..9e090c7 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/defaults/BanListCommand.java @@ -0,0 +1,71 @@ +package org.bukkit.command.defaults; + +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang.Validate; +import org.bukkit.BanEntry; +import org.bukkit.BanList; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.util.StringUtil; + +import java.util.ArrayList; +import java.util.List; + +@Deprecated +public class BanListCommand extends VanillaCommand { + private static final List BANLIST_TYPES = ImmutableList.of("ips", "players"); + + public BanListCommand() { + super("banlist"); + this.description = "View all players banned from this server"; + this.usageMessage = "/banlist [ips|players]"; + this.setPermission("bukkit.command.ban.list"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + + BanList.Type banType = BanList.Type.NAME; + if (args.length > 0) { + if (args[0].equalsIgnoreCase("ips")) { + banType = BanList.Type.IP; + } else if (!args[0].equalsIgnoreCase("players")) { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + } + + StringBuilder message = new StringBuilder(); + BanEntry[] banlist = Bukkit.getBanList(banType).getBanEntries().toArray(new BanEntry[0]); + + for (int x = 0; x < banlist.length; x++) { + if (x != 0) { + if (x == banlist.length - 1) { + message.append(" and "); + } else { + message.append(", "); + } + } + + message.append(banlist[x].getTarget()); + } + + sender.sendMessage("There are " + banlist.length + " total banned players:"); + sender.sendMessage(message.toString()); + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length == 1) { + return StringUtil.copyPartialMatches(args[0], BANLIST_TYPES, new ArrayList(BANLIST_TYPES.size())); + } + return ImmutableList.of(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/command/defaults/BukkitCommand.java b/azurite-api/src/main/java/org/bukkit/command/defaults/BukkitCommand.java new file mode 100644 index 0000000..4149bf9 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/defaults/BukkitCommand.java @@ -0,0 +1,15 @@ +package org.bukkit.command.defaults; + +import org.bukkit.command.Command; + +import java.util.List; + +public abstract class BukkitCommand extends Command { + protected BukkitCommand(String name) { + super(name); + } + + protected BukkitCommand(String name, String description, String usageMessage, List aliases) { + super(name, description, usageMessage, aliases); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/command/defaults/ClearCommand.java b/azurite-api/src/main/java/org/bukkit/command/defaults/ClearCommand.java new file mode 100644 index 0000000..05317e1 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/defaults/ClearCommand.java @@ -0,0 +1,115 @@ +package org.bukkit.command.defaults; + +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.util.StringUtil; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +@Deprecated +public class ClearCommand extends VanillaCommand { + private static List materials; + static { + ArrayList materialList = new ArrayList(); + for (Material material : Material.values()) { + materialList.add(material.name()); + } + Collections.sort(materialList); + materials = ImmutableList.copyOf(materialList); + } + + public ClearCommand() { + super("clear"); + this.description = "Clears the player's inventory. Can specify item and data filters too."; + this.usageMessage = "/clear [item] [data]"; + this.setPermission("bukkit.command.clear"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + + Player player = null; + if (args.length > 0) { + player = Bukkit.getPlayer(args[0]); + } else if (sender instanceof Player) { + player = (Player) sender; + } + + if (player != null) { + int id; + + if (args.length > 1 && !(args[1].equals("-1"))) { + Material material = Material.matchMaterial(args[1]); + if (material == null) { + sender.sendMessage(ChatColor.RED + "There's no item called " + args[1]); + return false; + } + + id = material.getId(); + } else { + id = -1; + } + + int data = args.length >= 3 ? getInteger(sender, args[2], 0) : -1; + int count = player.getInventory().clear(id, data); + + Command.broadcastCommandMessage(sender, "Cleared the inventory of " + player.getDisplayName() + ", removing " + count + " items"); + } else if (args.length == 0) { + sender.sendMessage(ChatColor.RED + "Please provide a player!"); + } else { + sender.sendMessage(ChatColor.RED + "Can't find player " + args[0]); + } + + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length == 1) { + return super.tabComplete(sender, alias, args); + } + if (args.length == 2) { + final String arg = args[1]; + final List materials = ClearCommand.materials; + List completion = null; + + final int size = materials.size(); + int i = Collections.binarySearch(materials, arg, String.CASE_INSENSITIVE_ORDER); + + if (i < 0) { + // Insertion (start) index + i = -1 - i; + } + + for ( ; i < size; i++) { + String material = materials.get(i); + if (StringUtil.startsWithIgnoreCase(material, arg)) { + if (completion == null) { + completion = new ArrayList(); + } + completion.add(material); + } else { + break; + } + } + + if (completion != null) { + return completion; + } + } + return ImmutableList.of(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/command/defaults/DefaultGameModeCommand.java b/azurite-api/src/main/java/org/bukkit/command/defaults/DefaultGameModeCommand.java new file mode 100644 index 0000000..3e9dba9 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/defaults/DefaultGameModeCommand.java @@ -0,0 +1,70 @@ +package org.bukkit.command.defaults; + +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.util.StringUtil; + +import java.util.ArrayList; +import java.util.List; + +@Deprecated +public class DefaultGameModeCommand extends VanillaCommand { + private static final List GAMEMODE_NAMES = ImmutableList.of("adventure", "creative", "survival"); + + public DefaultGameModeCommand() { + super("defaultgamemode"); + this.description = "Set the default gamemode"; + this.usageMessage = "/defaultgamemode "; + this.setPermission("bukkit.command.defaultgamemode"); + } + + @Override + public boolean execute(CommandSender sender, String commandLabel, String[] args) { + if (!testPermission(sender)) return true; + if (args.length == 0) { + sender.sendMessage("Usage: " + usageMessage); + return false; + } + + String modeArg = args[0]; + int value = -1; + + try { + value = Integer.parseInt(modeArg); + } catch (NumberFormatException ignored) {} + + GameMode mode = GameMode.getByValue(value); + + if (mode == null) { + if (modeArg.equalsIgnoreCase("creative") || modeArg.equalsIgnoreCase("c")) { + mode = GameMode.CREATIVE; + } else if (modeArg.equalsIgnoreCase("adventure") || modeArg.equalsIgnoreCase("a")) { + mode = GameMode.ADVENTURE; + } else { + mode = GameMode.SURVIVAL; + } + } + + Bukkit.getServer().setDefaultGameMode(mode); + Command.broadcastCommandMessage(sender, "Default game mode set to " + mode.toString().toLowerCase()); + + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length == 1) { + return StringUtil.copyPartialMatches(args[0], GAMEMODE_NAMES, new ArrayList(GAMEMODE_NAMES.size())); + } + + return ImmutableList.of(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/command/defaults/DeopCommand.java b/azurite-api/src/main/java/org/bukkit/command/defaults/DeopCommand.java new file mode 100644 index 0000000..70063f9 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/defaults/DeopCommand.java @@ -0,0 +1,62 @@ +package org.bukkit.command.defaults; + +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.util.StringUtil; + +import java.util.ArrayList; +import java.util.List; + +@Deprecated +public class DeopCommand extends VanillaCommand { + public DeopCommand() { + super("deop"); + this.description = "Takes the specified player's operator status"; + this.usageMessage = "/deop "; + this.setPermission("bukkit.command.op.take"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + if (args.length != 1 || args[0].length() == 0) { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + OfflinePlayer player = Bukkit.getOfflinePlayer(args[0]); + player.setOp(false); + + if (player instanceof Player) { + ((Player) player).sendMessage(ChatColor.YELLOW + "You are no longer op!"); + } + + Command.broadcastCommandMessage(sender, "De-opped " + args[0]); + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length == 1) { + List completions = new ArrayList(); + for (OfflinePlayer player : Bukkit.getOperators()) { + String playerName = player.getName(); + if (StringUtil.startsWithIgnoreCase(playerName, args[0])) { + completions.add(playerName); + } + } + return completions; + } + return ImmutableList.of(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/command/defaults/DifficultyCommand.java b/azurite-api/src/main/java/org/bukkit/command/defaults/DifficultyCommand.java new file mode 100644 index 0000000..0d6d033 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/defaults/DifficultyCommand.java @@ -0,0 +1,82 @@ +package org.bukkit.command.defaults; + +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Difficulty; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.util.StringUtil; + +import java.util.ArrayList; +import java.util.List; + +@Deprecated +public class DifficultyCommand extends VanillaCommand { + private static final List DIFFICULTY_NAMES = ImmutableList.of("peaceful", "easy", "normal", "hard"); + + public DifficultyCommand() { + super("difficulty"); + this.description = "Sets the game difficulty"; + this.usageMessage = "/difficulty "; + this.setPermission("bukkit.command.difficulty"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + if (args.length != 1 || args[0].length() == 0) { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + Difficulty difficulty = Difficulty.getByValue(getDifficultyForString(sender, args[0])); + + if (Bukkit.isHardcore()) { + difficulty = Difficulty.HARD; + } + + Bukkit.getWorlds().get(0).setDifficulty(difficulty); + + int levelCount = 1; + if (Bukkit.getAllowNether()) { + Bukkit.getWorlds().get(levelCount).setDifficulty(difficulty); + levelCount++; + } + + if (Bukkit.getAllowEnd()) { + Bukkit.getWorlds().get(levelCount).setDifficulty(difficulty); + } + + Command.broadcastCommandMessage(sender, "Set difficulty to " + difficulty.toString()); + return true; + } + + protected int getDifficultyForString(CommandSender sender, String name) { + if (name.equalsIgnoreCase("peaceful") || name.equalsIgnoreCase("p")) { + return 0; + } else if (name.equalsIgnoreCase("easy") || name.equalsIgnoreCase("e")) { + return 1; + } else if (name.equalsIgnoreCase("normal") || name.equalsIgnoreCase("n")) { + return 2; + } else if (name.equalsIgnoreCase("hard") || name.equalsIgnoreCase("h")) { + return 3; + } else { + return getInteger(sender, name, 0, 3); + } + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length == 1) { + return StringUtil.copyPartialMatches(args[0], DIFFICULTY_NAMES, new ArrayList(DIFFICULTY_NAMES.size())); + } + + return ImmutableList.of(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/command/defaults/EffectCommand.java b/azurite-api/src/main/java/org/bukkit/command/defaults/EffectCommand.java new file mode 100644 index 0000000..91af354 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/defaults/EffectCommand.java @@ -0,0 +1,121 @@ +package org.bukkit.command.defaults; + +import com.google.common.collect.ImmutableList; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.util.StringUtil; + +import java.util.ArrayList; +import java.util.List; + +@Deprecated +public class EffectCommand extends VanillaCommand { + private static final List effects; + + public EffectCommand() { + super("effect"); + this.description = "Adds/Removes effects on players"; + this.usageMessage = "/effect [seconds] [amplifier]"; + this.setPermission("bukkit.command.effect"); + } + + static { + ImmutableList.Builder builder = ImmutableList.builder(); + + for (PotionEffectType type : PotionEffectType.values()) { + if (type != null) { + builder.add(type.getName()); + } + } + + effects = builder.build(); + } + + @Override + public boolean execute(CommandSender sender, String commandLabel, String[] args) { + if (!testPermission(sender)) { + return true; + } + + if (args.length < 2) { + sender.sendMessage(getUsage()); + return true; + } + + final Player player = sender.getServer().getPlayer(args[0]); + + if (player == null) { + sender.sendMessage(ChatColor.RED + String.format("Player, %s, not found", args[0])); + return true; + } + + if ("clear".equalsIgnoreCase(args[1])) { + for (PotionEffect effect : player.getActivePotionEffects()) { + player.removePotionEffect(effect.getType()); + } + sender.sendMessage(String.format("Took all effects from %s", args[0])); + return true; + } + + PotionEffectType effect = PotionEffectType.getByName(args[1]); + + if (effect == null) { + effect = PotionEffectType.getById(getInteger(sender, args[1], 0)); + } + + if (effect == null) { + sender.sendMessage(ChatColor.RED + String.format("Effect, %s, not found", args[1])); + return true; + } + + int duration = 600; + int duration_temp = 30; + int amplification = 0; + + if (args.length >= 3) { + duration_temp = getInteger(sender, args[2], 0, 1000000); + if (effect.isInstant()) { + duration = duration_temp; + } else { + duration = duration_temp * 20; + } + } else if (effect.isInstant()) { + duration = 1; + } + + if (args.length >= 4) { + amplification = getInteger(sender, args[3], 0, 255); + } + + if (duration_temp == 0) { + if (!player.hasPotionEffect(effect)) { + sender.sendMessage(String.format("Couldn't take %s from %s as they do not have the effect", effect.getName(), args[0])); + return true; + } + + player.removePotionEffect(effect); + broadcastCommandMessage(sender, String.format("Took %s from %s", effect.getName(), args[0])); + } else { + final PotionEffect applyEffect = new PotionEffect(effect, duration, amplification); + + player.addPotionEffect(applyEffect, true); + broadcastCommandMessage(sender, String.format("Given %s (ID %d) * %d to %s for %d seconds", effect.getName(), effect.getId(), amplification, args[0], duration_temp)); + } + + return true; + } + + @Override + public List tabComplete(CommandSender sender, String commandLabel, String[] args) { + if (args.length == 1) { + return super.tabComplete(sender, commandLabel, args); + } else if (args.length == 2) { + return StringUtil.copyPartialMatches(args[1], effects, new ArrayList(effects.size())); + } + + return ImmutableList.of(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/command/defaults/EnchantCommand.java b/azurite-api/src/main/java/org/bukkit/command/defaults/EnchantCommand.java new file mode 100644 index 0000000..5c13fbe --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/defaults/EnchantCommand.java @@ -0,0 +1,169 @@ +package org.bukkit.command.defaults; + +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang.Validate; +import org.apache.commons.lang.WordUtils; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.StringUtil; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +@Deprecated +public class EnchantCommand extends VanillaCommand { + private static final List ENCHANTMENT_NAMES = new ArrayList(); + + public EnchantCommand() { + super("enchant"); + this.description = "Adds enchantments to the item the player is currently holding. Specify 0 for the level to remove an enchantment. Specify force to ignore normal enchantment restrictions"; + this.usageMessage = "/enchant [level|max|0] [force]"; + this.setPermission("bukkit.command.enchant"); + } + + @Override + public boolean execute(CommandSender sender, String commandLabel, String[] args) { + if (!testPermission(sender)) return true; + if (args.length < 2) { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + boolean force = false; + if (args.length > 2) { + force = args[args.length > 3 ? 3 : 2].equalsIgnoreCase("force"); + } + + Player player = Bukkit.getPlayerExact(args[0]); + if (player == null) { + sender.sendMessage("Can't find player " + args[0]); + } else { + ItemStack item = player.getItemInHand(); + if (item.getType() == Material.AIR) { + sender.sendMessage("The player isn't holding an item"); + } else { + String itemName = item.getType().toString().replaceAll("_", " "); + itemName = WordUtils.capitalizeFully(itemName); + + Enchantment enchantment = getEnchantment(args[1].toUpperCase()); + if (enchantment == null) { + sender.sendMessage(String.format("Enchantment does not exist: %s", args[1])); + } else { + String enchantmentName = enchantment.getName().replaceAll("_", " "); + enchantmentName = WordUtils.capitalizeFully(enchantmentName); + + if (!force && !enchantment.canEnchantItem(item)) { + sender.sendMessage(String.format("%s cannot be applied to %s", enchantmentName, itemName)); + } else { + int level = 1; + if (args.length > 2) { + Integer integer = getInteger(args[2]); + int minLevel = enchantment.getStartLevel(); + int maxLevel = force ? Short.MAX_VALUE : enchantment.getMaxLevel(); + + if (integer != null) { + if (integer == 0) { + item.removeEnchantment(enchantment); + Command.broadcastCommandMessage(sender, String.format("Removed %s on %s's %s", enchantmentName, player.getName(), itemName)); + return true; + } + + if (integer < minLevel || integer > maxLevel) { + sender.sendMessage(String.format("Level for enchantment %s must be between %d and %d", enchantmentName, minLevel, maxLevel)); + sender.sendMessage("Specify 0 for level to remove an enchantment"); + return true; + } + + level = integer; + } + + if ("max".equals(args[2])) { + level = maxLevel; + } + } + + Map enchantments = item.getEnchantments(); + boolean conflicts = false; + + if (!force && !enchantments.isEmpty()) { // TODO: Improve this to use a "hasEnchantments" call + for (Map.Entry entry : enchantments.entrySet()) { + Enchantment enchant = entry.getKey(); + + if (enchant.equals(enchantment)) continue; + if (enchant.conflictsWith(enchantment)) { + sender.sendMessage(String.format("Can't apply the enchantment %s on an item with the enchantment %s", enchantmentName, WordUtils.capitalizeFully(enchant.getName().replaceAll("_", " ")))); + conflicts = true; + break; + } + } + } + + if (!conflicts) { + item.addUnsafeEnchantment(enchantment, level); + + Command.broadcastCommandMessage(sender, String.format("Applied %s (Lvl %d) on %s's %s", enchantmentName, level, player.getName(), itemName), false); + sender.sendMessage(String.format("Enchanting succeeded, applied %s (Lvl %d) onto your %s", enchantmentName, level, itemName)); + } + } + } + } + } + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length == 1) { + return super.tabComplete(sender, alias, args); + } + + if (args.length == 2) { + return StringUtil.copyPartialMatches(args[1], ENCHANTMENT_NAMES, new ArrayList(ENCHANTMENT_NAMES.size())); + } + + if (args.length == 3 || args.length == 4) { + if (!args[args.length - 2].equalsIgnoreCase("force")) { + return ImmutableList.of("force"); + } + } + + return ImmutableList.of(); + } + + private Enchantment getEnchantment(String lookup) { + Enchantment enchantment = Enchantment.getByName(lookup); + + if (enchantment == null) { + Integer id = getInteger(lookup); + if (id != null) { + enchantment = Enchantment.getById(id); + } + } + + return enchantment; + } + + public static void buildEnchantments() { + if (!ENCHANTMENT_NAMES.isEmpty()) { + throw new IllegalStateException("Enchantments have already been built!"); + } + + for (Enchantment enchantment : Enchantment.values()) { + ENCHANTMENT_NAMES.add(enchantment.getName()); + } + + Collections.sort(ENCHANTMENT_NAMES); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/command/defaults/ExpCommand.java b/azurite-api/src/main/java/org/bukkit/command/defaults/ExpCommand.java new file mode 100644 index 0000000..baf892f --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/defaults/ExpCommand.java @@ -0,0 +1,89 @@ +package org.bukkit.command.defaults; + +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.List; + +@Deprecated +public class ExpCommand extends VanillaCommand { + public ExpCommand() { + super("xp"); + this.description = "Gives the specified player a certain amount of experience. Specify L to give levels instead, with a negative amount resulting in taking levels."; + this.usageMessage = "/xp [player] OR /xp L [player]"; + this.setPermission("bukkit.command.xp"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + + if (args.length > 0) { + String inputAmount = args[0]; + Player player = null; + + boolean isLevel = inputAmount.endsWith("l") || inputAmount.endsWith("L"); + if (isLevel && inputAmount.length() > 1) { + inputAmount = inputAmount.substring(0, inputAmount.length() - 1); + } + + int amount = getInteger(sender, inputAmount, Integer.MIN_VALUE, Integer.MAX_VALUE); + boolean isTaking = amount < 0; + + if (isTaking) { + amount *= -1; + } + + if (args.length > 1) { + player = Bukkit.getPlayer(args[1]); + } else if (sender instanceof Player) { + player = (Player) sender; + } + + if (player != null) { + if (isLevel) { + if (isTaking) { + player.giveExpLevels(-amount); + Command.broadcastCommandMessage(sender, "Taken " + amount + " level(s) from " + player.getName()); + } else { + player.giveExpLevels(amount); + Command.broadcastCommandMessage(sender, "Given " + amount + " level(s) to " + player.getName()); + } + } else { + if (isTaking) { + sender.sendMessage(ChatColor.RED + "Taking experience can only be done by levels, cannot give players negative experience points"); + return false; + } else { + player.giveExp(amount); + Command.broadcastCommandMessage(sender, "Given " + amount + " experience to " + player.getName()); + } + } + } else { + sender.sendMessage("Can't find player, was one provided?\n" + ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + return true; + } + + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length == 2) { + return super.tabComplete(sender, alias, args); + } + return ImmutableList.of(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/command/defaults/GameModeCommand.java b/azurite-api/src/main/java/org/bukkit/command/defaults/GameModeCommand.java new file mode 100644 index 0000000..e1763a3 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/defaults/GameModeCommand.java @@ -0,0 +1,100 @@ +package org.bukkit.command.defaults; + +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.GameMode; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.util.StringUtil; + +import java.util.ArrayList; +import java.util.List; + +@Deprecated +public class GameModeCommand extends VanillaCommand { + private static final List GAMEMODE_NAMES = ImmutableList.of("adventure", "creative", "survival", "spectator"); + + public GameModeCommand() { + super("gamemode"); + this.description = "Changes the player to a specific game mode"; + this.usageMessage = "/gamemode [player]"; + this.setPermission("bukkit.command.gamemode"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + if (args.length == 0) { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + String modeArg = args[0]; + String playerArg = sender.getName(); + + if (args.length == 2) { + playerArg = args[1]; + } + + Player player = Bukkit.getPlayerExact(playerArg); + + if (player != null) { + int value = -1; + + try { + value = Integer.parseInt(modeArg); + } catch (NumberFormatException ignored) {} + + GameMode mode = GameMode.getByValue(value); + + if (mode == null) { + if (modeArg.equalsIgnoreCase("creative") || modeArg.equalsIgnoreCase("c")) { + mode = GameMode.CREATIVE; + } else if (modeArg.equalsIgnoreCase("adventure") || modeArg.equalsIgnoreCase("a")) { + mode = GameMode.ADVENTURE; + } else if (modeArg.equalsIgnoreCase("spectator") || modeArg.equalsIgnoreCase("sp")) { + mode = GameMode.SPECTATOR; + } else { + mode = GameMode.SURVIVAL; + } + } + + if (mode != player.getGameMode()) { + player.setGameMode(mode); + + if (mode != player.getGameMode()) { + sender.sendMessage("Game mode change for " + player.getName() + " failed!"); + } else { + if (player == sender) { + Command.broadcastCommandMessage(sender, "Set own game mode to " + mode.toString() + " mode"); + } else { + Command.broadcastCommandMessage(sender, "Set " + player.getName() + "'s game mode to " + mode.toString() + " mode"); + } + } + } else { + sender.sendMessage(player.getName() + " already has game mode " + mode.getValue()); + } + } else { + sender.sendMessage("Can't find player " + playerArg); + } + + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length == 1) { + return StringUtil.copyPartialMatches(args[0], GAMEMODE_NAMES, new ArrayList(GAMEMODE_NAMES.size())); + } else if (args.length == 2) { + return super.tabComplete(sender, alias, args); + } + return ImmutableList.of(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/command/defaults/GameRuleCommand.java b/azurite-api/src/main/java/org/bukkit/command/defaults/GameRuleCommand.java new file mode 100644 index 0000000..bce171b --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/defaults/GameRuleCommand.java @@ -0,0 +1,89 @@ +package org.bukkit.command.defaults; + +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.World; +import org.bukkit.command.BlockCommandSender; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.HumanEntity; +import org.bukkit.util.StringUtil; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +@Deprecated +public class GameRuleCommand extends VanillaCommand { + private static final List GAMERULE_STATES = ImmutableList.of("true", "false"); + + public GameRuleCommand() { + super("gamerule"); + this.description = "Sets a server's game rules"; + this.usageMessage = "/gamerule OR /gamerule "; + this.setPermission("bukkit.command.gamerule"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + + if (args.length > 0) { + String rule = args[0]; + World world = getGameWorld(sender); + + if (world.isGameRule(rule)) { + if (args.length > 1) { + String value = args[1]; + + world.setGameRuleValue(rule, value); + Command.broadcastCommandMessage(sender, "Game rule " + rule + " has been set to: " + value); + } else { + String value = world.getGameRuleValue(rule); + sender.sendMessage(rule + " = " + value); + } + } else { + sender.sendMessage(ChatColor.RED + "No game rule called " + rule + " is available"); + } + + return true; + } else { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + sender.sendMessage("Rules: " + this.createString(getGameWorld(sender).getGameRules(), 0, ", ")); + + return true; + } + } + + private World getGameWorld(CommandSender sender) { + if (sender instanceof HumanEntity) { + World world = ((HumanEntity) sender).getWorld(); + if (world != null) { + return world; + } + } else if (sender instanceof BlockCommandSender) { + return ((BlockCommandSender) sender).getBlock().getWorld(); + } + + return Bukkit.getWorlds().get(0); + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length == 1) { + return StringUtil.copyPartialMatches(args[0], Arrays.asList(getGameWorld(sender).getGameRules()), new ArrayList()); + } + + if (args.length == 2) { + return StringUtil.copyPartialMatches(args[1], GAMERULE_STATES, new ArrayList(GAMERULE_STATES.size())); + } + + return ImmutableList.of(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/command/defaults/GiveCommand.java b/azurite-api/src/main/java/org/bukkit/command/defaults/GiveCommand.java new file mode 100644 index 0000000..7426073 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/defaults/GiveCommand.java @@ -0,0 +1,129 @@ +package org.bukkit.command.defaults; + +import com.google.common.base.Joiner; +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.StringUtil; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +@Deprecated +public class GiveCommand extends VanillaCommand { + private static List materials; + static { + ArrayList materialList = new ArrayList(); + for (Material material : Material.values()) { + materialList.add(material.name()); + } + Collections.sort(materialList); + materials = ImmutableList.copyOf(materialList); + } + + public GiveCommand() { + super("give"); + this.description = "Gives the specified player a certain amount of items"; + this.usageMessage = "/give [amount [data]]"; + this.setPermission("bukkit.command.give"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + if ((args.length < 2)) { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + Player player = Bukkit.getPlayerExact(args[0]); + + if (player != null) { + Material material = Material.matchMaterial(args[1]); + + if (material == null) { + material = Bukkit.getUnsafe().getMaterialFromInternalName(args[1]); + } + + if (material != null) { + int amount = 1; + short data = 0; + + if (args.length >= 3) { + amount = this.getInteger(sender, args[2], 1, 64); + + if (args.length >= 4) { + try { + data = Short.parseShort(args[3]); + } catch (NumberFormatException ignored) {} + } + } + + ItemStack stack = new ItemStack(material, amount, data); + + if (args.length >= 5) { + try { + stack = Bukkit.getUnsafe().modifyItemStack(stack, Joiner.on(' ').join(Arrays.asList(args).subList(4, args.length))); + } catch (Throwable t) { + player.sendMessage("Not a valid tag"); + return true; + } + } + + player.getInventory().addItem(stack); + + Command.broadcastCommandMessage(sender, "Gave " + player.getName() + " some " + material.getId() + " (" + material + ")"); + } else { + sender.sendMessage("There's no item called " + args[1]); + } + } else { + sender.sendMessage("Can't find player " + args[0]); + } + + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length == 1) { + return super.tabComplete(sender, alias, args); + } + if (args.length == 2) { + final String arg = args[1]; + final List materials = GiveCommand.materials; + List completion = new ArrayList(); + + final int size = materials.size(); + int i = Collections.binarySearch(materials, arg, String.CASE_INSENSITIVE_ORDER); + + if (i < 0) { + // Insertion (start) index + i = -1 - i; + } + + for ( ; i < size; i++) { + String material = materials.get(i); + if (StringUtil.startsWithIgnoreCase(material, arg)) { + completion.add(material); + } else { + break; + } + } + + return Bukkit.getUnsafe().tabCompleteInternalMaterialName(arg, completion); + } + return ImmutableList.of(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/command/defaults/HelpCommand.java b/azurite-api/src/main/java/org/bukkit/command/defaults/HelpCommand.java new file mode 100644 index 0000000..03c1338 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/defaults/HelpCommand.java @@ -0,0 +1,221 @@ +package org.bukkit.command.defaults; + +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang.ArrayUtils; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang.Validate; +import org.apache.commons.lang.math.NumberUtils; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.command.ConsoleCommandSender; +import org.bukkit.help.HelpMap; +import org.bukkit.help.HelpTopic; +import org.bukkit.help.HelpTopicComparator; +import org.bukkit.help.IndexHelpTopic; +import org.bukkit.util.ChatPaginator; + +import java.util.*; + +public class HelpCommand extends VanillaCommand { + public HelpCommand() { + super("help"); + this.description = "Shows the help menu"; + this.usageMessage = "/help \n/help \n/help "; + this.setAliases(Arrays.asList(new String[] { "?" })); + this.setPermission("bukkit.command.help"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + + String command; + int pageNumber; + int pageHeight; + int pageWidth; + + if (args.length == 0) { + command = ""; + pageNumber = 1; + } else if (NumberUtils.isDigits(args[args.length - 1])) { + command = StringUtils.join(ArrayUtils.subarray(args, 0, args.length - 1), " "); + try { + pageNumber = NumberUtils.createInteger(args[args.length - 1]); + } catch (NumberFormatException exception) { + pageNumber = 1; + } + if (pageNumber <= 0) { + pageNumber = 1; + } + } else { + command = StringUtils.join(args, " "); + pageNumber = 1; + } + + if (sender instanceof ConsoleCommandSender) { + pageHeight = ChatPaginator.UNBOUNDED_PAGE_HEIGHT; + pageWidth = ChatPaginator.UNBOUNDED_PAGE_WIDTH; + } else { + pageHeight = ChatPaginator.CLOSED_CHAT_PAGE_HEIGHT - 1; + pageWidth = ChatPaginator.GUARANTEED_NO_WRAP_CHAT_PAGE_WIDTH; + } + + HelpMap helpMap = Bukkit.getServer().getHelpMap(); + HelpTopic topic = helpMap.getHelpTopic(command); + + if (topic == null) { + topic = helpMap.getHelpTopic("/" + command); + } + + if (topic == null) { + topic = findPossibleMatches(command); + } + + if (topic == null || !topic.canSee(sender)) { + sender.sendMessage(ChatColor.RED + "No help for " + command); + return true; + } + + ChatPaginator.ChatPage page = ChatPaginator.paginate(topic.getFullText(sender), pageNumber, pageWidth, pageHeight); + + StringBuilder header = new StringBuilder(); + header.append(ChatColor.YELLOW); + header.append("--------- "); + header.append(ChatColor.WHITE); + header.append("Help: "); + header.append(topic.getName()); + header.append(" "); + if (page.getTotalPages() > 1) { + header.append("("); + header.append(page.getPageNumber()); + header.append("/"); + header.append(page.getTotalPages()); + header.append(") "); + } + header.append(ChatColor.YELLOW); + for (int i = header.length(); i < ChatPaginator.GUARANTEED_NO_WRAP_CHAT_PAGE_WIDTH; i++) { + header.append("-"); + } + sender.sendMessage(header.toString()); + + sender.sendMessage(page.getLines()); + + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length == 1) { + List matchedTopics = new ArrayList(); + String searchString = args[0]; + for (HelpTopic topic : Bukkit.getServer().getHelpMap().getHelpTopics()) { + String trimmedTopic = topic.getName().startsWith("/") ? topic.getName().substring(1) : topic.getName(); + + if (trimmedTopic.startsWith(searchString)) { + matchedTopics.add(trimmedTopic); + } + } + return matchedTopics; + } + return ImmutableList.of(); + } + + protected HelpTopic findPossibleMatches(String searchString) { + int maxDistance = (searchString.length() / 5) + 3; + Set possibleMatches = new TreeSet(HelpTopicComparator.helpTopicComparatorInstance()); + + if (searchString.startsWith("/")) { + searchString = searchString.substring(1); + } + + for (HelpTopic topic : Bukkit.getServer().getHelpMap().getHelpTopics()) { + String trimmedTopic = topic.getName().startsWith("/") ? topic.getName().substring(1) : topic.getName(); + + if (trimmedTopic.length() < searchString.length()) { + continue; + } + + if (Character.toLowerCase(trimmedTopic.charAt(0)) != Character.toLowerCase(searchString.charAt(0))) { + continue; + } + + if (damerauLevenshteinDistance(searchString, trimmedTopic.substring(0, searchString.length())) < maxDistance) { + possibleMatches.add(topic); + } + } + + if (possibleMatches.size() > 0) { + return new IndexHelpTopic("Search", null, null, possibleMatches, "Search for: " + searchString); + } else { + return null; + } + } + + /** + * Computes the Dameraur-Levenshtein Distance between two strings. Adapted + * from the algorithm at Wikipedia: Damerau–Levenshtein distance + * + * @param s1 The first string being compared. + * @param s2 The second string being compared. + * @return The number of substitutions, deletions, insertions, and + * transpositions required to get from s1 to s2. + */ + protected static int damerauLevenshteinDistance(String s1, String s2) { + if (s1 == null && s2 == null) { + return 0; + } + if (s1 != null && s2 == null) { + return s1.length(); + } + if (s1 == null && s2 != null) { + return s2.length(); + } + + int s1Len = s1.length(); + int s2Len = s2.length(); + int[][] H = new int[s1Len + 2][s2Len + 2]; + + int INF = s1Len + s2Len; + H[0][0] = INF; + for (int i = 0; i <= s1Len; i++) { + H[i + 1][1] = i; + H[i + 1][0] = INF; + } + for (int j = 0; j <= s2Len; j++) { + H[1][j + 1] = j; + H[0][j + 1] = INF; + } + + Map sd = new HashMap(); + for (char Letter : (s1 + s2).toCharArray()) { + if (!sd.containsKey(Letter)) { + sd.put(Letter, 0); + } + } + + for (int i = 1; i <= s1Len; i++) { + int DB = 0; + for (int j = 1; j <= s2Len; j++) { + int i1 = sd.get(s2.charAt(j - 1)); + int j1 = DB; + + if (s1.charAt(i - 1) == s2.charAt(j - 1)) { + H[i + 1][j + 1] = H[i][j]; + DB = j; + } else { + H[i + 1][j + 1] = Math.min(H[i][j], Math.min(H[i + 1][j], H[i][j + 1])) + 1; + } + + H[i + 1][j + 1] = Math.min(H[i + 1][j + 1], H[i1][j1] + (i - i1 - 1) + 1 + (j - j1 - 1)); + } + sd.put(s1.charAt(i - 1), i); + } + + return H[s1Len + 1][s2Len + 1]; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/command/defaults/KickCommand.java b/azurite-api/src/main/java/org/bukkit/command/defaults/KickCommand.java new file mode 100644 index 0000000..02930f8 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/defaults/KickCommand.java @@ -0,0 +1,59 @@ +package org.bukkit.command.defaults; + +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.List; + +@Deprecated +public class KickCommand extends VanillaCommand { + public KickCommand() { + super("kick"); + this.description = "Removes the specified player from the server"; + this.usageMessage = "/kick [reason ...]"; + this.setPermission("bukkit.command.kick"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + if (args.length < 1 || args[0].length() == 0) { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + Player player = Bukkit.getPlayerExact(args[0]); + + if (player != null) { + String reason = "Kicked by an operator."; + + if (args.length > 1) { + reason = createString(args, 1); + } + + player.kickPlayer(reason); + Command.broadcastCommandMessage(sender, "Kicked player " + player.getName() + ". With reason:\n" + reason); + } else { + sender.sendMessage( args[0] + " not found."); + } + + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length >= 1) { + return super.tabComplete(sender, alias, args); + } + return ImmutableList.of(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/command/defaults/KillCommand.java b/azurite-api/src/main/java/org/bukkit/command/defaults/KillCommand.java new file mode 100644 index 0000000..e323f76 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/defaults/KillCommand.java @@ -0,0 +1,50 @@ +package org.bukkit.command.defaults; + +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageEvent; + +import java.util.List; + +@Deprecated +public class KillCommand extends VanillaCommand { + public KillCommand() { + super("kill"); + this.description = "Commits suicide, only usable as a player"; + this.usageMessage = "/kill"; + this.setPermission("bukkit.command.kill"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + + if (sender instanceof Player) { + Player player = (Player) sender; + + EntityDamageEvent ede = new EntityDamageEvent(player, EntityDamageEvent.DamageCause.SUICIDE, 1000); + Bukkit.getPluginManager().callEvent(ede); + if (ede.isCancelled()) return true; + + ede.getEntity().setLastDamageCause(ede); + player.setHealth(0); + sender.sendMessage("Ouch. That look like it hurt."); + } else { + sender.sendMessage("You can only perform this command as a player"); + } + + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + return ImmutableList.of(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/command/defaults/ListCommand.java b/azurite-api/src/main/java/org/bukkit/command/defaults/ListCommand.java new file mode 100644 index 0000000..f1c3d9c --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/defaults/ListCommand.java @@ -0,0 +1,54 @@ +package org.bukkit.command.defaults; + +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.Collection; +import java.util.List; + +@Deprecated +public class ListCommand extends VanillaCommand { + public ListCommand() { + super("list"); + this.description = "Lists all online players"; + this.usageMessage = "/list"; + this.setPermission("bukkit.command.list"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + + StringBuilder online = new StringBuilder(); + + final Collection players = Bukkit.getOnlinePlayers(); + + for (Player player : players) { + // If a player is hidden from the sender don't show them in the list + if (sender instanceof Player && !((Player) sender).canSee(player)) + continue; + + if (online.length() > 0) { + online.append(", "); + } + + online.append(player.getDisplayName()); + } + + sender.sendMessage("There are " + players.size() + "/" + Bukkit.getMaxPlayers() + " players online:\n" + online.toString()); + + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + return ImmutableList.of(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/command/defaults/MeCommand.java b/azurite-api/src/main/java/org/bukkit/command/defaults/MeCommand.java new file mode 100644 index 0000000..2a029cb --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/defaults/MeCommand.java @@ -0,0 +1,36 @@ +package org.bukkit.command.defaults; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; + +@Deprecated +public class MeCommand extends VanillaCommand { + public MeCommand() { + super("me"); + this.description = "Performs the specified action in chat"; + this.usageMessage = "/me "; + this.setPermission("bukkit.command.me"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + if (args.length < 1) { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + StringBuilder message = new StringBuilder(); + message.append(sender.getName()); + + for (String arg : args) { + message.append(" "); + message.append(arg); + } + + Bukkit.broadcastMessage("* " + message); + + return true; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/command/defaults/OpCommand.java b/azurite-api/src/main/java/org/bukkit/command/defaults/OpCommand.java new file mode 100644 index 0000000..4ecc765 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/defaults/OpCommand.java @@ -0,0 +1,75 @@ +package org.bukkit.command.defaults; + +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.util.StringUtil; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +@Deprecated +public class OpCommand extends VanillaCommand { + public OpCommand() { + super("op"); + this.description = "Gives the specified player operator status"; + this.usageMessage = "/op "; + this.setPermission("bukkit.command.op.give"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + if (args.length != 1 || args[0].length() == 0) { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + OfflinePlayer player = Bukkit.getOfflinePlayer(args[0]); + player.setOp(true); + + Command.broadcastCommandMessage(sender, "Opped " + args[0]); + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length == 1) { + if (!(sender instanceof Player)) { + return ImmutableList.of(); + } + + String lastWord = args[0]; + if (lastWord.length() == 0) { + return ImmutableList.of(); + } + + Player senderPlayer = (Player) sender; + + ArrayList matchedPlayers = new ArrayList(); + for (Player player : sender.getServer().getOnlinePlayers()) { + String name = player.getName(); + if (!senderPlayer.canSee(player) || player.isOp()) { + continue; + } + if (StringUtil.startsWithIgnoreCase(name, lastWord)) { + matchedPlayers.add(name); + } + } + + Collections.sort(matchedPlayers, String.CASE_INSENSITIVE_ORDER); + return matchedPlayers; + } + return ImmutableList.of(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/command/defaults/PardonCommand.java b/azurite-api/src/main/java/org/bukkit/command/defaults/PardonCommand.java new file mode 100644 index 0000000..91d8b1a --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/defaults/PardonCommand.java @@ -0,0 +1,56 @@ +package org.bukkit.command.defaults; + +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang.Validate; +import org.bukkit.BanList; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.util.StringUtil; + +import java.util.ArrayList; +import java.util.List; + +@Deprecated +public class PardonCommand extends VanillaCommand { + public PardonCommand() { + super("pardon"); + this.description = "Allows the specified player to use this server"; + this.usageMessage = "/pardon "; + this.setPermission("bukkit.command.unban.player"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + if (args.length != 1) { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + Bukkit.getBanList(BanList.Type.NAME).pardon(args[0]); + Command.broadcastCommandMessage(sender, "Pardoned " + args[0]); + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length == 1) { + List completions = new ArrayList(); + for (OfflinePlayer player : Bukkit.getBannedPlayers()) { + String name = player.getName(); + if (StringUtil.startsWithIgnoreCase(name, args[0])) { + completions.add(name); + } + } + return completions; + } + return ImmutableList.of(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/command/defaults/PardonIpCommand.java b/azurite-api/src/main/java/org/bukkit/command/defaults/PardonIpCommand.java new file mode 100644 index 0000000..0ff1bae --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/defaults/PardonIpCommand.java @@ -0,0 +1,52 @@ +package org.bukkit.command.defaults; + +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.util.StringUtil; + +import java.util.ArrayList; +import java.util.List; + +@Deprecated +public class PardonIpCommand extends VanillaCommand { + public PardonIpCommand() { + super("pardon-ip"); + this.description = "Allows the specified IP address to use this server"; + this.usageMessage = "/pardon-ip

"; + this.setPermission("bukkit.command.unban.ip"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + if (args.length != 1) { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + if (BanIpCommand.ipValidity.matcher(args[0]).matches()) { + Bukkit.unbanIP(args[0]); + Command.broadcastCommandMessage(sender, "Pardoned ip " + args[0]); + } else { + sender.sendMessage("Invalid ip"); + } + + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length == 1) { + return StringUtil.copyPartialMatches(args[0], Bukkit.getIPBans(), new ArrayList()); + } + return ImmutableList.of(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/command/defaults/PlaySoundCommand.java b/azurite-api/src/main/java/org/bukkit/command/defaults/PlaySoundCommand.java new file mode 100644 index 0000000..a7737ad --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/defaults/PlaySoundCommand.java @@ -0,0 +1,88 @@ +package org.bukkit.command.defaults; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +@Deprecated +public class PlaySoundCommand extends VanillaCommand { + public PlaySoundCommand() { + super("playsound"); + this.description = "Plays a sound to a given player"; + this.usageMessage = "/playsound [x] [y] [z] [volume] [pitch] [minimumVolume]"; + this.setPermission("bukkit.command.playsound"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) { + return true; + } + + if (args.length < 2) { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + final String soundArg = args[0]; + final String playerArg = args[1]; + + final Player player = Bukkit.getPlayerExact(playerArg); + if (player == null) { + sender.sendMessage(ChatColor.RED + "Can't find player " + playerArg); + return false; + } + + final Location location = player.getLocation(); + + double x = Math.floor(location.getX()); + double y = Math.floor(location.getY() + 0.5D); + double z = Math.floor(location.getZ()); + double volume = 1.0D; + double pitch = 1.0D; + double minimumVolume = 0.0D; + + switch (args.length) { + default: + case 8: + minimumVolume = getDouble(sender, args[7], 0.0D, 1.0D); + case 7: + pitch = getDouble(sender, args[6], 0.0D, 2.0D); + case 6: + volume = getDouble(sender, args[5], 0.0D, Float.MAX_VALUE); + case 5: + z = getRelativeDouble(z, sender, args[4]); + case 4: + y = getRelativeDouble(y, sender, args[3]); + case 3: + x = getRelativeDouble(x, sender, args[2]); + case 2: + // Noop + } + + final double fixedVolume = volume > 1.0D ? volume * 16.0D : 16.0D; + final Location soundLocation = new Location(player.getWorld(), x, y, z); + if (location.distanceSquared(soundLocation) > fixedVolume * fixedVolume) { + if (minimumVolume <= 0.0D) { + sender.sendMessage(ChatColor.RED + playerArg + " is too far away to hear the sound"); + return false; + } + + final double deltaX = x - location.getX(); + final double deltaY = y - location.getY(); + final double deltaZ = z - location.getZ(); + final double delta = Math.sqrt(deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ) / 2.0D; + + if (delta > 0.0D) { + location.add(deltaX / delta, deltaY / delta, deltaZ / delta); + } + + player.playSound(location, soundArg, (float) minimumVolume, (float) pitch); + } else { + player.playSound(soundLocation, soundArg, (float) volume, (float) pitch); + } + sender.sendMessage(String.format("Played '%s' to %s", soundArg, playerArg)); + return true; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/command/defaults/PluginsCommand.java b/azurite-api/src/main/java/org/bukkit/command/defaults/PluginsCommand.java new file mode 100644 index 0000000..d266970 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/defaults/PluginsCommand.java @@ -0,0 +1,51 @@ +package org.bukkit.command.defaults; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.plugin.Plugin; + +import java.util.Arrays; + +public class PluginsCommand extends BukkitCommand { + public PluginsCommand(String name) { + super(name); + this.description = "Gets a list of plugins running on the server"; + this.usageMessage = "/plugins"; + this.setPermission("bukkit.command.plugins"); + this.setAliases(Arrays.asList("pl")); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + + sender.sendMessage("Plugins " + getPluginList()); + return true; + } + + private String getPluginList() { + StringBuilder pluginList = new StringBuilder(); + Plugin[] plugins = Bukkit.getPluginManager().getPlugins(); + + for (Plugin plugin : plugins) { + if (pluginList.length() > 0) { + pluginList.append(ChatColor.WHITE); + pluginList.append(", "); + } + + pluginList.append(plugin.isEnabled() ? ChatColor.GREEN : ChatColor.RED); + pluginList.append(plugin.getDescription().getName()); + } + + return "(" + plugins.length + "): " + pluginList.toString(); + } + + // Spigot Start + @Override + public java.util.List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException + { + return java.util.Collections.emptyList(); + } + // Spigot End +} diff --git a/azurite-api/src/main/java/org/bukkit/command/defaults/ReloadCommand.java b/azurite-api/src/main/java/org/bukkit/command/defaults/ReloadCommand.java new file mode 100644 index 0000000..5a3a2ea --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/defaults/ReloadCommand.java @@ -0,0 +1,43 @@ +package org.bukkit.command.defaults; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; + +import java.util.Arrays; + +public class ReloadCommand extends BukkitCommand { + public ReloadCommand(String name) { + super(name); + this.description = "Reloads the server configuration and plugins"; + this.usageMessage = "/reload"; + this.setPermission("bukkit.command.reload"); + this.setAliases(Arrays.asList("rl")); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + + Command.broadcastCommandMessage(sender, "§cAzurite Spigot does not recommend reloading (this can break your server!). Please restart the server instead. If you still wish to reload use §7/" + currentAlias + " confirm§c."); + + if (args.length >= 1 && args[0].toLowerCase().equals("confirm")) { + Command.broadcastCommandMessage(sender, ChatColor.RED + "The reload command is known to cause memory leaks and break things. Be careful."); + Command.broadcastCommandMessage(sender, ChatColor.RED + "Please note that this command is not supported and may cause issues when using some plugins."); + Command.broadcastCommandMessage(sender, ChatColor.RED + "If you encounter any issues please use the /stop command to restart your server."); + Bukkit.reload(); + Command.broadcastCommandMessage(sender, ChatColor.GREEN + "Reload complete."); + } + + return true; + } + + // Spigot Start + @Override + public java.util.List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException + { + return java.util.Collections.emptyList(); + } + // Spigot End +} diff --git a/azurite-api/src/main/java/org/bukkit/command/defaults/SaveCommand.java b/azurite-api/src/main/java/org/bukkit/command/defaults/SaveCommand.java new file mode 100644 index 0000000..0d15c14 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/defaults/SaveCommand.java @@ -0,0 +1,46 @@ +package org.bukkit.command.defaults; + +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.World; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; + +import java.util.List; + +@Deprecated +public class SaveCommand extends VanillaCommand { + public SaveCommand() { + super("save-all"); + this.description = "Saves the server to disk"; + this.usageMessage = "/save-all"; + this.setPermission("bukkit.command.save.perform"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + + Command.broadcastCommandMessage(sender, "Forcing save.."); + + Bukkit.savePlayers(); + + for (World world : Bukkit.getWorlds()) { + world.save(); + } + + Command.broadcastCommandMessage(sender, "Save complete."); + + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + return ImmutableList.of(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/command/defaults/SaveOffCommand.java b/azurite-api/src/main/java/org/bukkit/command/defaults/SaveOffCommand.java new file mode 100644 index 0000000..a34e6aa --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/defaults/SaveOffCommand.java @@ -0,0 +1,41 @@ +package org.bukkit.command.defaults; + +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.World; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; + +import java.util.List; + +@Deprecated +public class SaveOffCommand extends VanillaCommand { + public SaveOffCommand() { + super("save-off"); + this.description = "Disables server autosaving"; + this.usageMessage = "/save-off"; + this.setPermission("bukkit.command.save.disable"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + + for (World world : Bukkit.getWorlds()) { + world.setAutoSave(false); + } + + Command.broadcastCommandMessage(sender, "Disabled level saving.."); + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + return ImmutableList.of(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/command/defaults/SaveOnCommand.java b/azurite-api/src/main/java/org/bukkit/command/defaults/SaveOnCommand.java new file mode 100644 index 0000000..1cd0730 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/defaults/SaveOnCommand.java @@ -0,0 +1,41 @@ +package org.bukkit.command.defaults; + +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.World; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; + +import java.util.List; + +@Deprecated +public class SaveOnCommand extends VanillaCommand { + public SaveOnCommand() { + super("save-on"); + this.description = "Enables server autosaving"; + this.usageMessage = "/save-on"; + this.setPermission("bukkit.command.save.enable"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + + for (World world : Bukkit.getWorlds()) { + world.setAutoSave(true); + } + + Command.broadcastCommandMessage(sender, "Enabled level saving.."); + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + return ImmutableList.of(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/command/defaults/SayCommand.java b/azurite-api/src/main/java/org/bukkit/command/defaults/SayCommand.java new file mode 100644 index 0000000..eaab280 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/defaults/SayCommand.java @@ -0,0 +1,62 @@ +package org.bukkit.command.defaults; + +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.command.ConsoleCommandSender; +import org.bukkit.entity.Player; + +import java.util.List; + +@Deprecated +public class SayCommand extends VanillaCommand { + public SayCommand() { + super("say"); + this.description = "Broadcasts the given message as the sender"; + this.usageMessage = "/say "; + this.setPermission("bukkit.command.say"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + if (args.length == 0) { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + StringBuilder message = new StringBuilder(); + message.append(ChatColor.LIGHT_PURPLE).append("["); + if (sender instanceof ConsoleCommandSender) { + message.append("Server"); + } else if (sender instanceof Player) { + message.append(((Player) sender).getDisplayName()); + } else { + message.append(sender.getName()); + } + message.append(ChatColor.LIGHT_PURPLE).append("] "); + + if (args.length > 0) { + message.append(args[0]); + for (int i = 1; i < args.length; i++) { + message.append(" ").append(args[i]); + } + } + + Bukkit.broadcastMessage(message.toString()); + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + + if (args.length >= 1) { + return super.tabComplete(sender, alias, args); + } + return ImmutableList.of(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/command/defaults/ScoreboardCommand.java b/azurite-api/src/main/java/org/bukkit/command/defaults/ScoreboardCommand.java new file mode 100644 index 0000000..049f5c7 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/defaults/ScoreboardCommand.java @@ -0,0 +1,607 @@ +package org.bukkit.command.defaults; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import org.apache.commons.lang.ArrayUtils; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.scoreboard.*; +import org.bukkit.util.StringUtil; + +import java.util.*; + +@Deprecated +public class ScoreboardCommand extends VanillaCommand { + + private static final List MAIN_CHOICES = ImmutableList.of("objectives", "players", "teams"); + private static final List OBJECTIVES_CHOICES = ImmutableList.of("list", "add", "remove", "setdisplay"); + private static final List OBJECTIVES_CRITERIA = ImmutableList.of("health", "playerKillCount", "totalKillCount", "deathCount", "dummy"); + private static final List PLAYERS_CHOICES = ImmutableList.of("set", "add", "remove", "reset", "list"); + private static final List TEAMS_CHOICES = ImmutableList.of("add", "remove", "join", "leave", "empty", "list", "option"); + private static final List TEAMS_OPTION_CHOICES = ImmutableList.of("color", "friendlyfire", "seeFriendlyInvisibles"); + private static final Map OBJECTIVES_DISPLAYSLOT = ImmutableMap.of("belowName", DisplaySlot.BELOW_NAME, "list", DisplaySlot.PLAYER_LIST, "sidebar", DisplaySlot.SIDEBAR); + private static final Map TEAMS_OPTION_COLOR = ImmutableMap.builder() + .put("aqua", ChatColor.AQUA) + .put("black", ChatColor.BLACK) + .put("blue", ChatColor.BLUE) + .put("bold", ChatColor.BOLD) + .put("dark_aqua", ChatColor.DARK_AQUA) + .put("dark_blue", ChatColor.DARK_BLUE) + .put("dark_gray", ChatColor.DARK_GRAY) + .put("dark_green", ChatColor.DARK_GREEN) + .put("dark_purple", ChatColor.DARK_PURPLE) + .put("dark_red", ChatColor.DARK_RED) + .put("gold", ChatColor.GOLD) + .put("gray", ChatColor.GRAY) + .put("green", ChatColor.GREEN) + .put("italic", ChatColor.ITALIC) + .put("light_purple", ChatColor.LIGHT_PURPLE) + .put("obfuscated", ChatColor.MAGIC) // This is the important line + .put("red", ChatColor.RED) + .put("reset", ChatColor.RESET) + .put("strikethrough", ChatColor.STRIKETHROUGH) + .put("underline", ChatColor.UNDERLINE) + .put("white", ChatColor.WHITE) + .put("yellow", ChatColor.YELLOW) + .build(); + private static final List BOOLEAN = ImmutableList.of("true", "false"); + + public ScoreboardCommand() { + super("scoreboard"); + this.description = "Scoreboard control"; + this.usageMessage = "/scoreboard"; + this.setPermission("bukkit.command.scoreboard"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) + return true; + if (args.length < 1 || args[0].length() == 0) { + sender.sendMessage(ChatColor.RED + "Usage: /scoreboard "); + return false; + } + + final Scoreboard mainScoreboard = Bukkit.getScoreboardManager().getMainScoreboard(); + + if (args[0].equalsIgnoreCase("objectives")) { + if (args.length == 1) { + sender.sendMessage(ChatColor.RED + "Usage: /scoreboard objectives "); + return false; + } + if (args[1].equalsIgnoreCase("list")) { + Set objectives = mainScoreboard.getObjectives(); + if (objectives.isEmpty()) { + sender.sendMessage(ChatColor.RED + "There are no objectives on the scoreboard"); + return false; + } + sender.sendMessage(ChatColor.DARK_GREEN + "Showing " + objectives.size() + " objective(s) on scoreboard"); + for (Objective objective : objectives) { + sender.sendMessage("- " + objective.getName() + ": displays as '" + objective.getDisplayName() + "' and is type '" + objective.getCriteria() + "'"); + } + } else if (args[1].equalsIgnoreCase("add")) { + if (args.length < 4) { + sender.sendMessage(ChatColor.RED + "/scoreboard objectives add [display name ...]"); + return false; + } + String name = args[2]; + String criteria = args[3]; + + if (criteria == null) { + sender.sendMessage(ChatColor.RED + "Invalid objective criteria type. Valid types are: " + stringCollectionToString(OBJECTIVES_CRITERIA)); + } else if (name.length() > 16) { + sender.sendMessage(ChatColor.RED + "The name '" + name + "' is too long for an objective, it can be at most 16 characters long"); + } else if (mainScoreboard.getObjective(name) != null) { + sender.sendMessage(ChatColor.RED + "An objective with the name '" + name + "' already exists"); + } else { + String displayName = null; + if (args.length > 4) { + displayName = StringUtils.join(ArrayUtils.subarray(args, 4, args.length), ' '); + if (displayName.length() > 32) { + sender.sendMessage(ChatColor.RED + "The name '" + displayName + "' is too long for an objective, it can be at most 32 characters long"); + return false; + } + } + Objective objective = mainScoreboard.registerNewObjective(name, criteria); + if (displayName != null && displayName.length() > 0) { + objective.setDisplayName(displayName); + } + sender.sendMessage("Added new objective '" + name + "' successfully"); + } + } else if (args[1].equalsIgnoreCase("remove")) { + if (args.length != 3) { + sender.sendMessage(ChatColor.RED + "/scoreboard objectives remove "); + return false; + } + String name = args[2]; + Objective objective = mainScoreboard.getObjective(name); + if (objective == null) { + sender.sendMessage(ChatColor.RED + "No objective was found by the name '" + name + "'"); + } else { + objective.unregister(); + sender.sendMessage("Removed objective '" + name + "' successfully"); + } + } else if (args[1].equalsIgnoreCase("setdisplay")) { + if (args.length != 3 && args.length != 4) { + sender.sendMessage(ChatColor.RED + "/scoreboard objectives setdisplay [objective]"); + return false; + } + String slotName = args[2]; + DisplaySlot slot = OBJECTIVES_DISPLAYSLOT.get(slotName); + if (slot == null) { + sender.sendMessage(ChatColor.RED + "No such display slot '" + slotName + "'"); + } else { + if (args.length == 4) { + String objectiveName = args[3]; + Objective objective = mainScoreboard.getObjective(objectiveName); + if (objective == null) { + sender.sendMessage(ChatColor.RED + "No objective was found by the name '" + objectiveName + "'"); + return false; + } + + objective.setDisplaySlot(slot); + sender.sendMessage("Set the display objective in slot '" + slotName + "' to '" + objective.getName() + "'"); + } else { + Objective objective = mainScoreboard.getObjective(slot); + if (objective != null) { + objective.setDisplaySlot(null); + } + sender.sendMessage("Cleared objective display slot '" + slotName + "'"); + } + } + } + } else if (args[0].equalsIgnoreCase("players")) { + if (args.length == 1) { + sender.sendMessage(ChatColor.RED + "/scoreboard players "); + return false; + } + if (args[1].equalsIgnoreCase("set") || args[1].equalsIgnoreCase("add") || args[1].equalsIgnoreCase("remove")) { + if (args.length != 5) { + if (args[1].equalsIgnoreCase("set")) { + sender.sendMessage(ChatColor.RED + "/scoreboard players set "); + } else if (args[1].equalsIgnoreCase("add")) { + sender.sendMessage(ChatColor.RED + "/scoreboard players add "); + } else { + sender.sendMessage(ChatColor.RED + "/scoreboard players remove "); + } + return false; + } + String objectiveName = args[3]; + Objective objective = mainScoreboard.getObjective(objectiveName); + if (objective == null) { + sender.sendMessage(ChatColor.RED + "No objective was found by the name '" + objectiveName + "'"); + return false; + } else if (!objective.isModifiable()) { + sender.sendMessage(ChatColor.RED + "The objective '" + objectiveName + "' is read-only and cannot be set"); + return false; + } + + String valueString = args[4]; + int value; + try { + value = Integer.parseInt(valueString); + } catch (NumberFormatException e) { + sender.sendMessage(ChatColor.RED + "'" + valueString + "' is not a valid number"); + return false; + } + if (value < 1 && !args[1].equalsIgnoreCase("set")) { + sender.sendMessage(ChatColor.RED + "The number you have entered (" + value + ") is too small, it must be at least 1"); + return false; + } + + String playerName = args[2]; + if (playerName.length() > 16) { + sender.sendMessage(ChatColor.RED + "'" + playerName + "' is too long for a player name"); + return false; + } + Score score = objective.getScore(playerName); + int newScore; + if (args[1].equalsIgnoreCase("set")) { + newScore = value; + } else if (args[1].equalsIgnoreCase("add")) { + newScore = score.getScore() + value; + } else { + newScore = score.getScore() - value; + } + score.setScore(newScore); + sender.sendMessage("Set score of " + objectiveName + " for player " + playerName + " to " + newScore); + } else if (args[1].equalsIgnoreCase("reset")) { + if (args.length != 3) { + sender.sendMessage(ChatColor.RED + "/scoreboard players reset "); + return false; + } + String playerName = args[2]; + if (playerName.length() > 16) { + sender.sendMessage(ChatColor.RED + "'" + playerName + "' is too long for a player name"); + return false; + } + mainScoreboard.resetScores(playerName); + sender.sendMessage("Reset all scores of player " + playerName); + } else if (args[1].equalsIgnoreCase("list")) { + if (args.length > 3) { + sender.sendMessage(ChatColor.RED + "/scoreboard players list "); + return false; + } + if (args.length == 2) { + Set entries = mainScoreboard.getEntries(); + if (entries.isEmpty()) { + sender.sendMessage(ChatColor.RED + "There are no tracked players on the scoreboard"); + } else { + sender.sendMessage(ChatColor.DARK_GREEN + "Showing " + entries.size() + " tracked players on the scoreboard"); + sender.sendMessage(stringCollectionToString(entries)); + } + } else { + String playerName = args[2]; + if (playerName.length() > 16) { + sender.sendMessage(ChatColor.RED + "'" + playerName + "' is too long for a player name"); + return false; + } + Set scores = mainScoreboard.getScores(playerName); + if (scores.isEmpty()) { + sender.sendMessage(ChatColor.RED + "Player " + playerName + " has no scores recorded"); + } else { + sender.sendMessage(ChatColor.DARK_GREEN + "Showing " + scores.size() + " tracked objective(s) for " + playerName); + for (Score score : scores) { + sender.sendMessage("- " + score.getObjective().getDisplayName() + ": " + score.getScore() + " (" + score.getObjective().getName() + ")"); + } + } + } + } + } else if (args[0].equalsIgnoreCase("teams")) { + if (args.length == 1) { + sender.sendMessage(ChatColor.RED + "/scoreboard teams "); + return false; + } + if (args[1].equalsIgnoreCase("list")) { + if (args.length == 2) { + Set teams = mainScoreboard.getTeams(); + if (teams.isEmpty()) { + sender.sendMessage(ChatColor.RED + "There are no teams registered on the scoreboard"); + } else { + sender.sendMessage(ChatColor.DARK_GREEN + "Showing " + teams.size() + " teams on the scoreboard"); + for (Team team : teams) { + sender.sendMessage("- " + team.getName() + ": '" + team.getDisplayName() + "' has " + team.getSize() + " players"); + } + } + } else if (args.length == 3) { + String teamName = args[2]; + Team team = mainScoreboard.getTeam(teamName); + if (team == null) { + sender.sendMessage(ChatColor.RED + "No team was found by the name '" + teamName + "'"); + } else { + Set players = team.getPlayers(); + if (players.isEmpty()) { + sender.sendMessage(ChatColor.RED + "Team " + team.getName() + " has no players"); + } else { + sender.sendMessage(ChatColor.DARK_GREEN + "Showing " + players.size() + " player(s) in team " + team.getName()); + sender.sendMessage(offlinePlayerSetToString(players)); + } + } + } else { + sender.sendMessage(ChatColor.RED + "/scoreboard teams list [name]"); + return false; + } + } else if (args[1].equalsIgnoreCase("add")) { + if (args.length < 3) { + sender.sendMessage(ChatColor.RED + "/scoreboard teams add [display name ...]"); + return false; + } + String name = args[2]; + if (name.length() > 16) { + sender.sendMessage(ChatColor.RED + "The name '" + name + "' is too long for a team, it can be at most 16 characters long"); + } else if (mainScoreboard.getTeam(name) != null) { + sender.sendMessage(ChatColor.RED + "A team with the name '" + name + "' already exists"); + } else { + String displayName = null; + if (args.length > 3) { + displayName = StringUtils.join(ArrayUtils.subarray(args, 3, args.length), ' '); + if (displayName.length() > 32) { + sender.sendMessage(ChatColor.RED + "The display name '" + displayName + "' is too long for a team, it can be at most 32 characters long"); + return false; + } + } + Team team = mainScoreboard.registerNewTeam(name); + if (displayName != null && displayName.length() > 0) { + team.setDisplayName(displayName); + } + sender.sendMessage("Added new team '" + team.getName() + "' successfully"); + } + } else if (args[1].equalsIgnoreCase("remove")) { + if (args.length != 3) { + sender.sendMessage(ChatColor.RED + "/scoreboard teams remove "); + return false; + } + String name = args[2]; + Team team = mainScoreboard.getTeam(name); + if (team == null) { + sender.sendMessage(ChatColor.RED + "No team was found by the name '" + name + "'"); + } else { + team.unregister(); + sender.sendMessage("Removed team " + name); + } + } else if (args[1].equalsIgnoreCase("empty")) { + if (args.length != 3) { + sender.sendMessage(ChatColor.RED + "/scoreboard teams clear "); + return false; + } + String name = args[2]; + Team team = mainScoreboard.getTeam(name); + if (team == null) { + sender.sendMessage(ChatColor.RED + "No team was found by the name '" + name + "'"); + } else { + Set players = team.getPlayers(); + if (players.isEmpty()) { + sender.sendMessage(ChatColor.RED + "Team " + team.getName() + " is already empty, cannot remove nonexistant players"); + } else { + for (OfflinePlayer player : players) { + team.removePlayer(player); + } + sender.sendMessage("Removed all " + players.size() + " player(s) from team " + team.getName()); + } + } + } else if (args[1].equalsIgnoreCase("join")) { + if ((sender instanceof Player) ? args.length < 3 : args.length < 4) { + sender.sendMessage(ChatColor.RED + "/scoreboard teams join [player...]"); + return false; + } + String teamName = args[2]; + Team team = mainScoreboard.getTeam(teamName); + if (team == null) { + sender.sendMessage(ChatColor.RED + "No team was found by the name '" + teamName + "'"); + } else { + Set addedPlayers = new HashSet(); + if ((sender instanceof Player) && args.length == 3) { + team.addPlayer((Player) sender); + addedPlayers.add(sender.getName()); + } else { + for (int i = 3; i < args.length; i++) { + String playerName = args[i]; + OfflinePlayer offlinePlayer; + Player player = Bukkit.getPlayerExact(playerName); + if (player != null) { + offlinePlayer = player; + } else { + offlinePlayer = Bukkit.getOfflinePlayer(playerName); + } + team.addPlayer(offlinePlayer); + addedPlayers.add(offlinePlayer.getName()); + } + } + sender.sendMessage("Added " + addedPlayers.size() + " player(s) to team " + team.getName() + ": " + stringCollectionToString(addedPlayers)); + } + } else if (args[1].equalsIgnoreCase("leave")) { + if (!(sender instanceof Player) && args.length < 3) { + sender.sendMessage(ChatColor.RED + "/scoreboard teams leave [player...]"); + return false; + } + Set left = new HashSet(); + Set noTeam = new HashSet(); + if ((sender instanceof Player) && args.length == 2) { + Team team = mainScoreboard.getPlayerTeam((Player) sender); + if (team != null) { + team.removePlayer((Player) sender); + left.add(sender.getName()); + } else { + noTeam.add(sender.getName()); + } + } else { + for (int i = 2; i < args.length; i++) { + String playerName = args[i]; + OfflinePlayer offlinePlayer; + Player player = Bukkit.getPlayerExact(playerName); + if (player != null) { + offlinePlayer = player; + } else { + offlinePlayer = Bukkit.getOfflinePlayer(playerName); + } + Team team = mainScoreboard.getPlayerTeam(offlinePlayer); + if (team != null) { + team.removePlayer(offlinePlayer); + left.add(offlinePlayer.getName()); + } else { + noTeam.add(offlinePlayer.getName()); + } + } + } + if (!left.isEmpty()) { + sender.sendMessage("Removed " + left.size() + " player(s) from their teams: " + stringCollectionToString(left)); + } + if (!noTeam.isEmpty()) { + sender.sendMessage("Could not remove " + noTeam.size() + " player(s) from their teams: " + stringCollectionToString(noTeam)); + } + } else if (args[1].equalsIgnoreCase("option")) { + if (args.length != 4 && args.length != 5) { + sender.sendMessage(ChatColor.RED + "/scoreboard teams option "); + return false; + } + String teamName = args[2]; + Team team = mainScoreboard.getTeam(teamName); + if (team == null) { + sender.sendMessage(ChatColor.RED + "No team was found by the name '" + teamName + "'"); + return false; + } + String option = args[3].toLowerCase(); + if (!option.equals("friendlyfire") && !option.equals("color") && !option.equals("seefriendlyinvisibles")) { + sender.sendMessage(ChatColor.RED + "/scoreboard teams option "); + return false; + } + if (args.length == 4) { + if (option.equals("color")) { + sender.sendMessage(ChatColor.RED + "Valid values for option color are: " + stringCollectionToString(TEAMS_OPTION_COLOR.keySet())); + } else { + sender.sendMessage(ChatColor.RED + "Valid values for option " + option + " are: true and false"); + } + } else { + String value = args[4].toLowerCase(); + if (option.equals("color")) { + ChatColor color = TEAMS_OPTION_COLOR.get(value); + if (color == null) { + sender.sendMessage(ChatColor.RED + "Valid values for option color are: " + stringCollectionToString(TEAMS_OPTION_COLOR.keySet())); + return false; + } + team.setPrefix(color.toString()); + team.setSuffix(ChatColor.RESET.toString()); + } else { + if (!value.equals("true") && !value.equals("false")) { + sender.sendMessage(ChatColor.RED + "Valid values for option " + option + " are: true and false"); + return false; + } + if (option.equals("friendlyfire")) { + team.setAllowFriendlyFire(value.equals("true")); + } else { + team.setCanSeeFriendlyInvisibles(value.equals("true")); + } + } + sender.sendMessage("Set option " + option + " for team " + team.getName() + " to " + value); + } + } + } else { + sender.sendMessage(ChatColor.RED + "Usage: /scoreboard "); + return false; + } + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length == 1) { + return StringUtil.copyPartialMatches(args[0], MAIN_CHOICES, new ArrayList()); + } + if (args.length > 1) { + if (args[0].equalsIgnoreCase("objectives")) { + if (args.length == 2) { + return StringUtil.copyPartialMatches(args[1], OBJECTIVES_CHOICES, new ArrayList()); + } + if (args[1].equalsIgnoreCase("add")) { + if (args.length == 4) { + return StringUtil.copyPartialMatches(args[3], OBJECTIVES_CRITERIA, new ArrayList()); + } + } else if (args[1].equalsIgnoreCase("remove")) { + if (args.length == 3) { + return StringUtil.copyPartialMatches(args[2], this.getCurrentObjectives(), new ArrayList()); + } + } else if (args[1].equalsIgnoreCase("setdisplay")) { + if (args.length == 3) { + return StringUtil.copyPartialMatches(args[2], OBJECTIVES_DISPLAYSLOT.keySet(), new ArrayList()); + } + if (args.length == 4) { + return StringUtil.copyPartialMatches(args[3], this.getCurrentObjectives(), new ArrayList()); + } + } + } else if (args[0].equalsIgnoreCase("players")) { + if (args.length == 2) { + return StringUtil.copyPartialMatches(args[1], PLAYERS_CHOICES, new ArrayList()); + } + if (args[1].equalsIgnoreCase("set") || args[1].equalsIgnoreCase("add") || args[1].equalsIgnoreCase("remove")) { + if (args.length == 3) { + return super.tabComplete(sender, alias, args); + } + if (args.length == 4) { + return StringUtil.copyPartialMatches(args[3], this.getCurrentObjectives(), new ArrayList()); + } + } else { + if (args.length == 3) { + return StringUtil.copyPartialMatches(args[2], this.getCurrentEntries(), new ArrayList()); + } + } + } else if (args[0].equalsIgnoreCase("teams")) { + if (args.length == 2) { + return StringUtil.copyPartialMatches(args[1], TEAMS_CHOICES, new ArrayList()); + } + if (args[1].equalsIgnoreCase("join")) { + if (args.length == 3) { + return StringUtil.copyPartialMatches(args[2], this.getCurrentTeams(), new ArrayList()); + } + if (args.length >= 4) { + return super.tabComplete(sender, alias, args); + } + } else if (args[1].equalsIgnoreCase("leave")) { + return super.tabComplete(sender, alias, args); + } else if (args[1].equalsIgnoreCase("option")) { + if (args.length == 3) { + return StringUtil.copyPartialMatches(args[2], this.getCurrentTeams(), new ArrayList()); + } + if (args.length == 4) { + return StringUtil.copyPartialMatches(args[3], TEAMS_OPTION_CHOICES, new ArrayList()); + } + if (args.length == 5) { + if (args[3].equalsIgnoreCase("color")) { + return StringUtil.copyPartialMatches(args[4], TEAMS_OPTION_COLOR.keySet(), new ArrayList()); + } else { + return StringUtil.copyPartialMatches(args[4], BOOLEAN, new ArrayList()); + } + } + } else { + if (args.length == 3) { + return StringUtil.copyPartialMatches(args[2], this.getCurrentTeams(), new ArrayList()); + } + } + } + } + + return ImmutableList.of(); + } + + private static String offlinePlayerSetToString(Set set) { + StringBuilder string = new StringBuilder(); + String lastValue = null; + for (OfflinePlayer value : set) { + string.append(lastValue = value.getName()).append(", "); + } + string.delete(string.length() - 2, Integer.MAX_VALUE); + if (string.length() != lastValue.length()) { + string.insert(string.length() - lastValue.length(), "and "); + } + return string.toString(); + + } + + private static String stringCollectionToString(Collection set) { + StringBuilder string = new StringBuilder(); + String lastValue = null; + for (String value : set) { + string.append(lastValue = value).append(", "); + } + string.delete(string.length() - 2, Integer.MAX_VALUE); + if (string.length() != lastValue.length()) { + string.insert(string.length() - lastValue.length(), "and "); + } + return string.toString(); + } + + private List getCurrentObjectives() { + List list = new ArrayList(); + for (Objective objective : Bukkit.getScoreboardManager().getMainScoreboard().getObjectives()) { + list.add(objective.getName()); + } + Collections.sort(list, String.CASE_INSENSITIVE_ORDER); + return list; + } + + private List getCurrentEntries() { + List list = new ArrayList(); + for (String entry : Bukkit.getScoreboardManager().getMainScoreboard().getEntries()) { + list.add(entry); + } + Collections.sort(list, String.CASE_INSENSITIVE_ORDER); + return list; + } + + private List getCurrentTeams() { + List list = new ArrayList(); + for (Team team : Bukkit.getScoreboardManager().getMainScoreboard().getTeams()) { + list.add(team.getName()); + } + Collections.sort(list, String.CASE_INSENSITIVE_ORDER); + return list; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/command/defaults/SeedCommand.java b/azurite-api/src/main/java/org/bukkit/command/defaults/SeedCommand.java new file mode 100644 index 0000000..d159b37 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/defaults/SeedCommand.java @@ -0,0 +1,41 @@ +package org.bukkit.command.defaults; + +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.List; + +@Deprecated +public class SeedCommand extends VanillaCommand { + public SeedCommand() { + super("seed"); + this.description = "Shows the world seed"; + this.usageMessage = "/seed"; + this.setPermission("bukkit.command.seed"); + } + + @Override + public boolean execute(CommandSender sender, String commandLabel, String[] args) { + if (!testPermission(sender)) return true; + long seed; + if (sender instanceof Player) { + seed = ((Player) sender).getWorld().getSeed(); + } else { + seed = Bukkit.getWorlds().get(0).getSeed(); + } + sender.sendMessage("Seed: " + seed); + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + return ImmutableList.of(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/command/defaults/SetIdleTimeoutCommand.java b/azurite-api/src/main/java/org/bukkit/command/defaults/SetIdleTimeoutCommand.java new file mode 100644 index 0000000..6d7b273 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/defaults/SetIdleTimeoutCommand.java @@ -0,0 +1,53 @@ +package org.bukkit.command.defaults; + +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; + +import java.util.List; + +@Deprecated +public class SetIdleTimeoutCommand extends VanillaCommand { + + public SetIdleTimeoutCommand() { + super("setidletimeout"); + this.description = "Sets the server's idle timeout"; + this.usageMessage = "/setidletimeout "; + this.setPermission("bukkit.command.setidletimeout"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + + if (args.length == 1) { + int minutes; + + try { + minutes = getInteger(sender, args[0], 0, Integer.MAX_VALUE, true); + } catch (NumberFormatException ex) { + sender.sendMessage(ex.getMessage()); + return true; + } + + Bukkit.getServer().setIdleTimeout(minutes); + + Command.broadcastCommandMessage(sender, "Successfully set the idle timeout to " + minutes + " minutes."); + return true; + } + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + return ImmutableList.of(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/command/defaults/SetWorldSpawnCommand.java b/azurite-api/src/main/java/org/bukkit/command/defaults/SetWorldSpawnCommand.java new file mode 100644 index 0000000..8bec19c --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/defaults/SetWorldSpawnCommand.java @@ -0,0 +1,80 @@ +package org.bukkit.command.defaults; + +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.List; + +@Deprecated +public class SetWorldSpawnCommand extends VanillaCommand { + + public SetWorldSpawnCommand() { + super("setworldspawn"); + this.description = "Sets a worlds's spawn point. If no coordinates are specified, the player's coordinates will be used."; + this.usageMessage = "/setworldspawn OR /setworldspawn "; + this.setPermission("bukkit.command.setworldspawn"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + + Player player = null; + World world; + if (sender instanceof Player) { + player = (Player) sender; + world = player.getWorld(); + } else { + world = Bukkit.getWorlds().get(0); + } + + final int x, y, z; + + if (args.length == 0) { + if (player == null) { + sender.sendMessage("You can only perform this command as a player"); + return true; + } + + Location location = player.getLocation(); + + x = location.getBlockX(); + y = location.getBlockY(); + z = location.getBlockZ(); + } else if (args.length == 3) { + try { + x = getInteger(sender, args[0], MIN_COORD, MAX_COORD, true); + y = getInteger(sender, args[1], 0, world.getMaxHeight(), true); + z = getInteger(sender, args[2], MIN_COORD, MAX_COORD, true); + } catch (NumberFormatException ex) { + sender.sendMessage(ex.getMessage()); + return true; + } + } else { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + world.setSpawnLocation(x, y, z); + + Command.broadcastCommandMessage(sender, "Set world " + world.getName() + "'s spawnpoint to (" + x + ", " + y + ", " + z + ")"); + return true; + + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + return ImmutableList.of(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/command/defaults/SpawnpointCommand.java b/azurite-api/src/main/java/org/bukkit/command/defaults/SpawnpointCommand.java new file mode 100644 index 0000000..be15f7e --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/defaults/SpawnpointCommand.java @@ -0,0 +1,88 @@ +package org.bukkit.command.defaults; + +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.List; + +@Deprecated +public class SpawnpointCommand extends VanillaCommand { + + public SpawnpointCommand() { + super("spawnpoint"); + this.description = "Sets a player's spawn point"; + this.usageMessage = "/spawnpoint OR /spawnpoint OR /spawnpoint "; + this.setPermission("bukkit.command.spawnpoint"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + + Player player; + + if (args.length == 0) { + if (sender instanceof Player) { + player = (Player) sender; + } else { + sender.sendMessage("Please provide a player!"); + return true; + } + } else { + player = Bukkit.getPlayerExact(args[0]); + if (player == null) { + sender.sendMessage("Can't find player " + args[0]); + return true; + } + } + + World world = player.getWorld(); + + if (args.length == 4) { + if (world != null) { + int pos = 1; + final int x, y, z; + try { + x = getInteger(sender, args[pos++], MIN_COORD, MAX_COORD, true); + y = getInteger(sender, args[pos++], 0, world.getMaxHeight()); + z = getInteger(sender, args[pos], MIN_COORD, MAX_COORD, true); + } catch(NumberFormatException ex) { + sender.sendMessage(ex.getMessage()); + return true; + } + + player.setBedSpawnLocation(new Location(world, x, y, z), true); + Command.broadcastCommandMessage(sender, "Set " + player.getDisplayName() + "'s spawnpoint to " + x + ", " + y + ", " + z); + } + } else if (args.length <= 1) { + Location location = player.getLocation(); + player.setBedSpawnLocation(location, true); + Command.broadcastCommandMessage(sender, "Set " + player.getDisplayName() + "'s spawnpoint to " + location.getX() + ", " + location.getY() + ", " + location.getZ()); + } else { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length == 1) { + return super.tabComplete(sender, alias, args); + } + + return ImmutableList.of(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/command/defaults/SpreadPlayersCommand.java b/azurite-api/src/main/java/org/bukkit/command/defaults/SpreadPlayersCommand.java new file mode 100644 index 0000000..da82b92 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/defaults/SpreadPlayersCommand.java @@ -0,0 +1,266 @@ +package org.bukkit.command.defaults; + +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import com.google.common.collect.Sets; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.scoreboard.Team; + +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.Set; + +@Deprecated +public class SpreadPlayersCommand extends VanillaCommand { + private static final Random random = new Random(); + + public SpreadPlayersCommand() { + super("spreadplayers"); + this.description = "Spreads players around a point"; + this.usageMessage = "/spreadplayers "; + this.setPermission("bukkit.command.spreadplayers"); + } + + @Override + public boolean execute(CommandSender sender, String commandLabel, String[] args) { + if (!testPermission(sender)) { + return true; + } + + if (args.length < 6) { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + final double x = getDouble(sender, args[0], -30000000, 30000000); + final double z = getDouble(sender, args[1], -30000000, 30000000); + final double distance = getDouble(sender, args[2]); + final double range = getDouble(sender, args[3]); + + if (distance < 0.0D) { + sender.sendMessage(ChatColor.RED + "Distance is too small."); + return false; + } + + if (range < distance + 1.0D) { + sender.sendMessage(ChatColor.RED + "Max range is too small."); + return false; + } + + final String respectTeams = args[4]; + boolean teams = false; + + if (respectTeams.equalsIgnoreCase("true")) { + teams = true; + } else if (!respectTeams.equalsIgnoreCase("false")) { + sender.sendMessage(String.format(ChatColor.RED + "'%s' is not true or false", args[4])); + return false; + } + + List players = Lists.newArrayList(); + World world = null; + + for (int i = 5; i < args.length; i++) { + Player player = Bukkit.getPlayerExact(args[i]); + if (player == null) { + continue; + } + + if (world == null) { + world = player.getWorld(); + } + players.add(player); + } + + if (world == null) { + return true; + } + + final double xRangeMin = x - range; + final double zRangeMin = z - range; + final double xRangeMax = x + range; + final double zRangeMax = z + range; + + final int spreadSize = teams ? getTeams(players) : players.size(); + + final Location[] locations = getSpreadLocations(world, spreadSize, xRangeMin, zRangeMin, xRangeMax, zRangeMax); + final int rangeSpread = range(world, distance, xRangeMin, zRangeMin, xRangeMax, zRangeMax, locations); + + if (rangeSpread == -1) { + sender.sendMessage(String.format("Could not spread %d %s around %s,%s (too many players for space - try using spread of at most %s)", spreadSize, teams ? "teams" : "players", x, z)); + return false; + } + + final double distanceSpread = spread(world, players, locations, teams); + + sender.sendMessage(String.format("Succesfully spread %d %s around %s,%s", locations.length, teams ? "teams" : "players", x, z)); + if (locations.length > 1) { + sender.sendMessage(String.format("(Average distance between %s is %s blocks apart after %s iterations)", teams ? "teams" : "players", String.format("%.2f", distanceSpread), rangeSpread)); + } + return true; + } + + private int range(World world, double distance, double xRangeMin, double zRangeMin, double xRangeMax, double zRangeMax, Location[] locations) { + boolean flag = true; + double max; + + int i; + + for (i = 0; i < 10000 && flag; ++i) { + flag = false; + max = Float.MAX_VALUE; + + Location loc1; + int j; + + for (int k = 0; k < locations.length; ++k) { + Location loc2 = locations[k]; + + j = 0; + loc1 = new Location(world, 0, 0, 0); + + for (int l = 0; l < locations.length; ++l) { + if (k != l) { + Location loc3 = locations[l]; + double dis = loc2.distanceSquared(loc3); + + max = Math.min(dis, max); + if (dis < distance) { + ++j; + loc1.add(loc3.getX() - loc2.getX(), 0, 0); + loc1.add(loc3.getZ() - loc2.getZ(), 0, 0); + } + } + } + + if (j > 0) { + loc2.setX(loc2.getX() / j); + loc2.setZ(loc2.getZ() / j); + double d7 = Math.sqrt(loc1.getX() * loc1.getX() + loc1.getZ() * loc1.getZ()); + + if (d7 > 0.0D) { + loc1.setX(loc1.getX() / d7); + loc2.add(-loc1.getX(), 0, -loc1.getZ()); + } else { + double x = xRangeMin >= xRangeMax ? xRangeMin : random.nextDouble() * (xRangeMax - xRangeMin) + xRangeMin; + double z = zRangeMin >= zRangeMax ? zRangeMin : random.nextDouble() * (zRangeMax - zRangeMin) + zRangeMin; + loc2.setX(x); + loc2.setZ(z); + } + + flag = true; + } + + boolean swap = false; + + if (loc2.getX() < xRangeMin) { + loc2.setX(xRangeMin); + swap = true; + } else if (loc2.getX() > xRangeMax) { + loc2.setX(xRangeMax); + swap = true; + } + + if (loc2.getZ() < zRangeMin) { + loc2.setZ(zRangeMin); + swap = true; + } else if (loc2.getZ() > zRangeMax) { + loc2.setZ(zRangeMax); + swap = true; + } + if (swap) { + flag = true; + } + } + + if (!flag) { + Location[] locs = locations; + int i1 = locations.length; + + for (j = 0; j < i1; ++j) { + loc1 = locs[j]; + if (world.getHighestBlockYAt(loc1) == 0) { + double x = xRangeMin >= xRangeMax ? xRangeMin : random.nextDouble() * (xRangeMax - xRangeMin) + xRangeMin; + double z = zRangeMin >= zRangeMax ? zRangeMin : random.nextDouble() * (zRangeMax - zRangeMin) + zRangeMin; + locations[i] = (new Location(world, x, 0, z)); + loc1.setX(x); + loc1.setZ(z); + flag = true; + } + } + } + } + + if (i >= 10000) { + return -1; + } else { + return i; + } + } + + private double spread(World world, List list, Location[] locations, boolean teams) { + double distance = 0.0D; + int i = 0; + Map hashmap = Maps.newHashMap(); + + for (int j = 0; j < list.size(); ++j) { + Player player = list.get(j); + Location location; + + if (teams) { + Team team = player.getScoreboard().getPlayerTeam(player); + + if (!hashmap.containsKey(team)) { + hashmap.put(team, locations[i++]); + } + + location = hashmap.get(team); + } else { + location = locations[i++]; + } + + player.teleport(new Location(world, Math.floor(location.getX()) + 0.5D, world.getHighestBlockYAt((int) location.getX(), (int) location.getZ()), Math.floor(location.getZ()) + 0.5D)); + double value = Double.MAX_VALUE; + + for (int k = 0; k < locations.length; ++k) { + if (location != locations[k]) { + double d = location.distanceSquared(locations[k]); + value = Math.min(d, value); + } + } + + distance += value; + } + + distance /= list.size(); + return distance; + } + + private int getTeams(List players) { + Set teams = Sets.newHashSet(); + + for (Player player : players) { + teams.add(player.getScoreboard().getPlayerTeam(player)); + } + + return teams.size(); + } + + private Location[] getSpreadLocations(World world, int size, double xRangeMin, double zRangeMin, double xRangeMax, double zRangeMax) { + Location[] locations = new Location[size]; + + for (int i = 0; i < size; ++i) { + double x = xRangeMin >= xRangeMax ? xRangeMin : random.nextDouble() * (xRangeMax - xRangeMin) + xRangeMin; + double z = zRangeMin >= zRangeMax ? zRangeMin : random.nextDouble() * (zRangeMax - zRangeMin) + zRangeMin; + locations[i] = (new Location(world, x, 0, z)); + } + + return locations; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/command/defaults/StopCommand.java b/azurite-api/src/main/java/org/bukkit/command/defaults/StopCommand.java new file mode 100644 index 0000000..699d803 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/defaults/StopCommand.java @@ -0,0 +1,47 @@ +package org.bukkit.command.defaults; + +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.List; + +@Deprecated +public class StopCommand extends VanillaCommand { + public StopCommand() { + super("stop"); + this.description = "Stops the server with optional reason"; + this.usageMessage = "/stop [reason]"; + this.setPermission("bukkit.command.stop"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + + Command.broadcastCommandMessage(sender, "Stopping the server.."); + Bukkit.shutdown(); + + String reason = this.createString(args, 0); + if (StringUtils.isNotEmpty(reason)) { + for (Player player : Bukkit.getOnlinePlayers()) { + player.kickPlayer(reason); + } + } + + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + return ImmutableList.of(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/command/defaults/TeleportCommand.java b/azurite-api/src/main/java/org/bukkit/command/defaults/TeleportCommand.java new file mode 100644 index 0000000..d1deed6 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/defaults/TeleportCommand.java @@ -0,0 +1,124 @@ +package org.bukkit.command.defaults; + +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; + +import java.util.List; + +@Deprecated +public class TeleportCommand extends VanillaCommand { + + public TeleportCommand() { + super("tp"); + this.description = "Teleports the given player (or yourself) to another player or coordinates"; + this.usageMessage = "/tp [player] and/or "; + this.setPermission("bukkit.command.teleport"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + if (args.length < 1 || args.length > 4) { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + Player player; + + if (args.length == 1 || args.length == 3) { + if (sender instanceof Player) { + player = (Player) sender; + } else { + sender.sendMessage("Please provide a player!"); + return true; + } + } else { + player = Bukkit.getPlayerExact(args[0]); + } + + if (player == null) { + sender.sendMessage("Player not found: " + args[0]); + return true; + } + + if (args.length < 3) { + Player target = Bukkit.getPlayerExact(args[args.length - 1]); + if (target == null) { + sender.sendMessage("Can't find player " + args[args.length - 1] + ". No tp."); + return true; + } + player.teleport(target, TeleportCause.COMMAND); + Command.broadcastCommandMessage(sender, "Teleported " + player.getDisplayName() + " to " + target.getDisplayName()); + } else if (player.getWorld() != null) { + Location playerLocation = player.getLocation(); + double x = getCoordinate(sender, playerLocation.getX(), args[args.length - 3]); + double y = getCoordinate(sender, playerLocation.getY(), args[args.length - 2], 0, 0); + double z = getCoordinate(sender, playerLocation.getZ(), args[args.length - 1]); + + if (x == MIN_COORD_MINUS_ONE || y == MIN_COORD_MINUS_ONE || z == MIN_COORD_MINUS_ONE) { + sender.sendMessage("Please provide a valid location!"); + return true; + } + + playerLocation.setX(x); + playerLocation.setY(y); + playerLocation.setZ(z); + + player.teleport(playerLocation, TeleportCause.COMMAND); + Command.broadcastCommandMessage(sender, String.format("Teleported %s to %.2f, %.2f, %.2f", player.getDisplayName(), x, y, z)); + } + return true; + } + + private double getCoordinate(CommandSender sender, double current, String input) { + return getCoordinate(sender, current, input, MIN_COORD, MAX_COORD); + } + + private double getCoordinate(CommandSender sender, double current, String input, int min, int max) { + boolean relative = input.startsWith("~"); + double result = relative ? current : 0; + + if (!relative || input.length() > 1) { + boolean exact = input.contains("."); + if (relative) input = input.substring(1); + + double testResult = getDouble(sender, input); + if (testResult == MIN_COORD_MINUS_ONE) { + return MIN_COORD_MINUS_ONE; + } + result += testResult; + + if (!exact && !relative) result += 0.5f; + } + if (min != 0 || max != 0) { + if (result < min) { + result = MIN_COORD_MINUS_ONE; + } + + if (result > max) { + result = MIN_COORD_MINUS_ONE; + } + } + + return result; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length == 1 || args.length == 2) { + return super.tabComplete(sender, alias, args); + } + return ImmutableList.of(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/command/defaults/TellCommand.java b/azurite-api/src/main/java/org/bukkit/command/defaults/TellCommand.java new file mode 100644 index 0000000..6c19245 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/defaults/TellCommand.java @@ -0,0 +1,61 @@ +package org.bukkit.command.defaults; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.Arrays; + +@Deprecated +public class TellCommand extends VanillaCommand { + public TellCommand() { + super("tell"); + this.description = "Sends a private message to the given player"; + this.usageMessage = "/tell "; + this.setAliases(Arrays.asList(new String[] { "w", "msg" })); + this.setPermission("bukkit.command.tell"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + if (args.length < 2) { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + Player player = Bukkit.getPlayerExact(args[0]); + + // If a player is hidden from the sender pretend they are offline + if (player == null || (sender instanceof Player && !((Player) sender).canSee(player))) { + sender.sendMessage("There's no player by that name online."); + } else { + StringBuilder message = new StringBuilder(); + + for (int i = 1; i < args.length; i++) { + if (i > 1) message.append(" "); + message.append(args[i]); + } + + String result = ChatColor.GRAY + sender.getName() + " whispers " + message; + + sender.sendMessage("[" + sender.getName() + "->" + player.getName() + "] " + message); + player.sendMessage(result); + } + + return true; + } + + // Spigot Start + @Override + public java.util.List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException + { + if ( args.length == 0 ) + { + return super.tabComplete( sender, alias, args ); + } + return java.util.Collections.emptyList(); + } + // Spigot End +} diff --git a/azurite-api/src/main/java/org/bukkit/command/defaults/TestForCommand.java b/azurite-api/src/main/java/org/bukkit/command/defaults/TestForCommand.java new file mode 100644 index 0000000..b5758a9 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/defaults/TestForCommand.java @@ -0,0 +1,38 @@ +package org.bukkit.command.defaults; + +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; + +@Deprecated +public class TestForCommand extends VanillaCommand { + public TestForCommand() { + super("testfor"); + this.description = "Tests whether a specifed player is online"; + this.usageMessage = "/testfor "; + this.setPermission("bukkit.command.testfor"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + if (args.length < 1) { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + sender.sendMessage(ChatColor.RED + "/testfor is only usable by commandblocks with analog output."); + return true; + } + + // Spigot Start + @Override + public java.util.List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException + { + if ( args.length == 0 ) + { + return super.tabComplete( sender, alias, args ); + } + return java.util.Collections.emptyList(); + } + // Spigot End +} diff --git a/azurite-api/src/main/java/org/bukkit/command/defaults/TimeCommand.java b/azurite-api/src/main/java/org/bukkit/command/defaults/TimeCommand.java new file mode 100644 index 0000000..80c3a69 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/defaults/TimeCommand.java @@ -0,0 +1,88 @@ +package org.bukkit.command.defaults; + +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.World; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.util.StringUtil; + +import java.util.ArrayList; +import java.util.List; + +@Deprecated +public class TimeCommand extends VanillaCommand { + private static final List TABCOMPLETE_ADD_SET = ImmutableList.of("add", "set"); + private static final List TABCOMPLETE_DAY_NIGHT = ImmutableList.of("day", "night"); + + public TimeCommand() { + super("time"); + this.description = "Changes the time on each world"; + this.usageMessage = "/time set \n/time add "; + this.setPermission("bukkit.command.time.add;bukkit.command.time.set"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (args.length < 2) { + sender.sendMessage(ChatColor.RED + "Incorrect usage. Correct usage:\n" + usageMessage); + return false; + } + + int value; + + if (args[0].equals("set")) { + if (!sender.hasPermission("bukkit.command.time.set")) { + sender.sendMessage(ChatColor.RED + "You don't have permission to set the time"); + return true; + } + + if (args[1].equals("day")) { + value = 0; + } else if (args[1].equals("night")) { + value = 12500; + } else { + value = getInteger(sender, args[1], 0); + } + + for (World world : Bukkit.getWorlds()) { + world.setTime(value); + } + + Command.broadcastCommandMessage(sender, "Set time to " + value); + } else if (args[0].equals("add")) { + if (!sender.hasPermission("bukkit.command.time.add")) { + sender.sendMessage(ChatColor.RED + "You don't have permission to set the time"); + return true; + } + + value = getInteger(sender, args[1], 0); + + for (World world : Bukkit.getWorlds()) { + world.setFullTime(world.getFullTime() + value); + } + + Command.broadcastCommandMessage(sender, "Added " + value + " to time"); + } else { + sender.sendMessage("Unknown method. Usage: " + usageMessage); + } + + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length == 1) { + return StringUtil.copyPartialMatches(args[0], TABCOMPLETE_ADD_SET, new ArrayList(TABCOMPLETE_ADD_SET.size())); + } else if (args.length == 2 && args[0].equalsIgnoreCase("set")) { + return StringUtil.copyPartialMatches(args[1], TABCOMPLETE_DAY_NIGHT, new ArrayList(TABCOMPLETE_DAY_NIGHT.size())); + } + return ImmutableList.of(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/command/defaults/ToggleDownfallCommand.java b/azurite-api/src/main/java/org/bukkit/command/defaults/ToggleDownfallCommand.java new file mode 100644 index 0000000..2b0dd33 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/defaults/ToggleDownfallCommand.java @@ -0,0 +1,56 @@ +package org.bukkit.command.defaults; + +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.World; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.List; + +@Deprecated +public class ToggleDownfallCommand extends VanillaCommand { + public ToggleDownfallCommand() { + super("toggledownfall"); + this.description = "Toggles rain on/off on a given world"; + this.usageMessage = "/toggledownfall"; + this.setPermission("bukkit.command.toggledownfall"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + + World world = null; + + if (args.length == 1) { + world = Bukkit.getWorld(args[0]); + + if (world == null) { + sender.sendMessage(ChatColor.RED + "No world exists with the name '" + args[0] + "'"); + return true; + } + } else if (sender instanceof Player) { + world = ((Player) sender).getWorld(); + } else { + world = Bukkit.getWorlds().get(0); + } + + Command.broadcastCommandMessage(sender, "Toggling downfall " + (world.hasStorm() ? "off" : "on") + " for world '" + world.getName() + "'"); + world.setStorm(!world.hasStorm()); + + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + return ImmutableList.of(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/command/defaults/VanillaCommand.java b/azurite-api/src/main/java/org/bukkit/command/defaults/VanillaCommand.java new file mode 100644 index 0000000..e13073f --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/defaults/VanillaCommand.java @@ -0,0 +1,111 @@ +package org.bukkit.command.defaults; + +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; + +import java.util.List; + +@Deprecated +public abstract class VanillaCommand extends Command { + static final int MAX_COORD = 30000000; + static final int MIN_COORD_MINUS_ONE = -30000001; + static final int MIN_COORD = -30000000; + + protected VanillaCommand(String name) { + super(name); + } + + protected VanillaCommand(String name, String description, String usageMessage, List aliases) { + super(name, description, usageMessage, aliases); + } + + public boolean matches(String input) { + return input.equalsIgnoreCase(this.getName()); + } + + protected int getInteger(CommandSender sender, String value, int min) { + return getInteger(sender, value, min, Integer.MAX_VALUE); + } + + int getInteger(CommandSender sender, String value, int min, int max) { + return getInteger(sender, value, min, max, false); + } + + int getInteger(CommandSender sender, String value, int min, int max, boolean Throws) { + int i = min; + + try { + i = Integer.parseInt(value); + } catch (NumberFormatException ex) { + if (Throws) { + throw new NumberFormatException(String.format("%s is not a valid number", value)); + } + } + + if (i < min) { + i = min; + } else if (i > max) { + i = max; + } + + return i; + } + + Integer getInteger(String value) { + try { + return Integer.valueOf(value); + } catch (NumberFormatException ex) { + return null; + } + } + + public static double getRelativeDouble(double original, CommandSender sender, String input) { + if (input.startsWith("~")) { + double value = getDouble(sender, input.substring(1)); + if (value == MIN_COORD_MINUS_ONE) { + return MIN_COORD_MINUS_ONE; + } + return original + value; + } else { + return getDouble(sender, input); + } + } + + public static double getDouble(CommandSender sender, String input) { + try { + return Double.parseDouble(input); + } catch (NumberFormatException ex) { + return MIN_COORD_MINUS_ONE; + } + } + + public static double getDouble(CommandSender sender, String input, double min, double max) { + double result = getDouble(sender, input); + + // TODO: This should throw an exception instead. + if (result < min) { + result = min; + } else if (result > max) { + result = max; + } + + return result; + } + + String createString(String[] args, int start) { + return createString(args, start, " "); + } + + String createString(String[] args, int start, String glue) { + StringBuilder string = new StringBuilder(); + + for (int x = start; x < args.length; x++) { + string.append(args[x]); + if (x != args.length - 1) { + string.append(glue); + } + } + + return string.toString(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/command/defaults/WeatherCommand.java b/azurite-api/src/main/java/org/bukkit/command/defaults/WeatherCommand.java new file mode 100644 index 0000000..b86a508 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/defaults/WeatherCommand.java @@ -0,0 +1,74 @@ +package org.bukkit.command.defaults; + +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.World; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.util.StringUtil; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +@Deprecated +public class WeatherCommand extends VanillaCommand { + private static final List WEATHER_TYPES = ImmutableList.of("clear", "rain", "thunder"); + + public WeatherCommand() { + super("weather"); + this.description = "Changes the weather"; + this.usageMessage = "/weather [duration in seconds]"; + this.setPermission("bukkit.command.weather"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + if (args.length == 0) { + sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); + return false; + } + + int duration = (300 + new Random().nextInt(600)) * 20; + if (args.length >= 2) { + duration = getInteger(sender, args[1], 1, 1000000) * 20; + } + + World world = Bukkit.getWorlds().get(0); + + world.setWeatherDuration(duration); + world.setThunderDuration(duration); + + if ("clear".equalsIgnoreCase(args[0])) { + world.setStorm(false); + world.setThundering(false); + Command.broadcastCommandMessage(sender, "Changed weather to clear for " + (duration / 20) + " seconds."); + } else if ("rain".equalsIgnoreCase(args[0])) { + world.setStorm(true); + world.setThundering(false); + Command.broadcastCommandMessage(sender, "Changed weather to rainy for " + (duration / 20) + " seconds."); + } else if ("thunder".equalsIgnoreCase(args[0])) { + world.setStorm(true); + world.setThundering(true); + Command.broadcastCommandMessage(sender, "Changed weather to thundering " + (duration / 20) + " seconds."); + } + + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length == 1) { + return StringUtil.copyPartialMatches(args[0], WEATHER_TYPES, new ArrayList(WEATHER_TYPES.size())); + } + + return ImmutableList.of(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/command/defaults/WhitelistCommand.java b/azurite-api/src/main/java/org/bukkit/command/defaults/WhitelistCommand.java new file mode 100644 index 0000000..8292210 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/command/defaults/WhitelistCommand.java @@ -0,0 +1,127 @@ +package org.bukkit.command.defaults; + +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.util.StringUtil; + +import java.util.ArrayList; +import java.util.List; + +@Deprecated +public class WhitelistCommand extends VanillaCommand { + private static final List WHITELIST_SUBCOMMANDS = ImmutableList.of("add", "remove", "on", "off", "list", "reload"); + + public WhitelistCommand() { + super("whitelist"); + this.description = "Manages the list of players allowed to use this server"; + this.usageMessage = "/whitelist (add|remove) \n/whitelist (on|off|list|reload)"; + this.setPermission("bukkit.command.whitelist.reload;bukkit.command.whitelist.enable;bukkit.command.whitelist.disable;bukkit.command.whitelist.list;bukkit.command.whitelist.add;bukkit.command.whitelist.remove"); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) { + if (!testPermission(sender)) return true; + + if (args.length == 1) { + if (args[0].equalsIgnoreCase("reload")) { + if (badPerm(sender, "reload")) return true; + + Bukkit.reloadWhitelist(); + Command.broadcastCommandMessage(sender, "Reloaded white-list from file"); + return true; + } else if (args[0].equalsIgnoreCase("on")) { + if (badPerm(sender, "enable")) return true; + + Bukkit.setWhitelist(true); + Command.broadcastCommandMessage(sender, "Turned on white-listing"); + return true; + } else if (args[0].equalsIgnoreCase("off")) { + if (badPerm(sender, "disable")) return true; + + Bukkit.setWhitelist(false); + Command.broadcastCommandMessage(sender, "Turned off white-listing"); + return true; + } else if (args[0].equalsIgnoreCase("list")) { + if (badPerm(sender, "list")) return true; + + StringBuilder result = new StringBuilder(); + + for (OfflinePlayer player : Bukkit.getWhitelistedPlayers()) { + if (result.length() > 0) { + result.append(", "); + } + + result.append(player.getName()); + } + + sender.sendMessage("White-listed players: " + result.toString()); + return true; + } + } else if (args.length == 2) { + if (args[0].equalsIgnoreCase("add")) { + if (badPerm(sender, "add")) return true; + + Bukkit.getOfflinePlayer(args[1]).setWhitelisted(true); + + Command.broadcastCommandMessage(sender, "Added " + args[1] + " to white-list"); + return true; + } else if (args[0].equalsIgnoreCase("remove")) { + if (badPerm(sender, "remove")) return true; + + Bukkit.getOfflinePlayer(args[1]).setWhitelisted(false); + + Command.broadcastCommandMessage(sender, "Removed " + args[1] + " from white-list"); + return true; + } + } + + sender.sendMessage(ChatColor.RED + "Correct command usage:\n" + usageMessage); + return false; + } + + private boolean badPerm(CommandSender sender, String perm) { + if (!sender.hasPermission("bukkit.command.whitelist." + perm)) { + sender.sendMessage(ChatColor.RED + "You do not have permission to perform this action."); + return true; + } + + return false; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length == 1) { + return StringUtil.copyPartialMatches(args[0], WHITELIST_SUBCOMMANDS, new ArrayList(WHITELIST_SUBCOMMANDS.size())); + } else if (args.length == 2) { + if (args[0].equalsIgnoreCase("add")) { + List completions = new ArrayList(); + for (OfflinePlayer player : Bukkit.getOnlinePlayers()) { // Spigot - well maybe sometimes you haven't turned the whitelist on just yet. + String name = player.getName(); + if (StringUtil.startsWithIgnoreCase(name, args[1]) && !player.isWhitelisted()) { + completions.add(name); + } + } + return completions; + } else if (args[0].equalsIgnoreCase("remove")) { + List completions = new ArrayList(); + for (OfflinePlayer player : Bukkit.getWhitelistedPlayers()) { + String name = player.getName(); + if (StringUtil.startsWithIgnoreCase(name, args[1])) { + completions.add(name); + } + } + return completions; + } + } + return ImmutableList.of(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/configuration/Configuration.java b/azurite-api/src/main/java/org/bukkit/configuration/Configuration.java new file mode 100644 index 0000000..22ab321 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/configuration/Configuration.java @@ -0,0 +1,84 @@ +package org.bukkit.configuration; + +import java.util.Map; + +/** + * Represents a source of configurable options and settings + */ +public interface Configuration extends ConfigurationSection { + /** + * Sets the default value of the given path as provided. + *

+ * If no source {@link Configuration} was provided as a default + * collection, then a new {@link MemoryConfiguration} will be created to + * hold the new default value. + *

+ * If value is null, the value will be removed from the default + * Configuration source. + * + * @param path Path of the value to set. + * @param value Value to set the default to. + * @throws IllegalArgumentException Thrown if path is null. + */ + void addDefault(String path, Object value); + + /** + * Sets the default values of the given paths as provided. + *

+ * If no source {@link Configuration} was provided as a default + * collection, then a new {@link MemoryConfiguration} will be created to + * hold the new default values. + * + * @param defaults A map of Path{@literal ->}Values to add to defaults. + * @throws IllegalArgumentException Thrown if defaults is null. + */ + void addDefaults(Map defaults); + + /** + * Sets the default values of the given paths as provided. + *

+ * If no source {@link Configuration} was provided as a default + * collection, then a new {@link MemoryConfiguration} will be created to + * hold the new default value. + *

+ * This method will not hold a reference to the specified Configuration, + * nor will it automatically update if that Configuration ever changes. If + * you require this, you should set the default source with {@link + * #setDefaults(Configuration)}. + * + * @param defaults A configuration holding a list of defaults to copy. + * @throws IllegalArgumentException Thrown if defaults is null or this. + */ + void addDefaults(Configuration defaults); + + /** + * Sets the source of all default values for this {@link Configuration}. + *

+ * If a previous source was set, or previous default values were defined, + * then they will not be copied to the new source. + * + * @param defaults New source of default values for this configuration. + * @throws IllegalArgumentException Thrown if defaults is null or this. + */ + void setDefaults(Configuration defaults); + + /** + * Gets the source {@link Configuration} for this configuration. + *

+ * If no configuration source was set, but default values were added, then + * a {@link MemoryConfiguration} will be returned. If no source was set + * and no defaults were set, then this method will return null. + * + * @return Configuration source for default values, or null if none exist. + */ + Configuration getDefaults(); + + /** + * Gets the {@link ConfigurationOptions} for this {@link Configuration}. + *

+ * All setters through this method are chainable. + * + * @return Options for this configuration + */ + ConfigurationOptions options(); +} diff --git a/azurite-api/src/main/java/org/bukkit/configuration/ConfigurationOptions.java b/azurite-api/src/main/java/org/bukkit/configuration/ConfigurationOptions.java new file mode 100644 index 0000000..31a644a --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/configuration/ConfigurationOptions.java @@ -0,0 +1,90 @@ +package org.bukkit.configuration; + +/** + * Various settings for controlling the input and output of a {@link + * Configuration} + */ +public class ConfigurationOptions { + private char pathSeparator = '.'; + private boolean copyDefaults = false; + private final Configuration configuration; + + protected ConfigurationOptions(Configuration configuration) { + this.configuration = configuration; + } + + /** + * Returns the {@link Configuration} that this object is responsible for. + * + * @return Parent configuration + */ + public Configuration configuration() { + return configuration; + } + + /** + * Gets the char that will be used to separate {@link + * ConfigurationSection}s + *

+ * This value does not affect how the {@link Configuration} is stored, + * only in how you access the data. The default value is '.'. + * + * @return Path separator + */ + public char pathSeparator() { + return pathSeparator; + } + + /** + * Sets the char that will be used to separate {@link + * ConfigurationSection}s + *

+ * This value does not affect how the {@link Configuration} is stored, + * only in how you access the data. The default value is '.'. + * + * @param value Path separator + * @return This object, for chaining + */ + public ConfigurationOptions pathSeparator(char value) { + this.pathSeparator = value; + return this; + } + + /** + * Checks if the {@link Configuration} should copy values from its default + * {@link Configuration} directly. + *

+ * If this is true, all values in the default Configuration will be + * directly copied, making it impossible to distinguish between values + * that were set and values that are provided by default. As a result, + * {@link ConfigurationSection#contains(String)} will always + * return the same value as {@link + * ConfigurationSection#isSet(String)}. The default value is + * false. + * + * @return Whether or not defaults are directly copied + */ + public boolean copyDefaults() { + return copyDefaults; + } + + /** + * Sets if the {@link Configuration} should copy values from its default + * {@link Configuration} directly. + *

+ * If this is true, all values in the default Configuration will be + * directly copied, making it impossible to distinguish between values + * that were set and values that are provided by default. As a result, + * {@link ConfigurationSection#contains(String)} will always + * return the same value as {@link + * ConfigurationSection#isSet(String)}. The default value is + * false. + * + * @param value Whether or not defaults are directly copied + * @return This object, for chaining + */ + public ConfigurationOptions copyDefaults(boolean value) { + this.copyDefaults = value; + return this; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/configuration/ConfigurationSection.java b/azurite-api/src/main/java/org/bukkit/configuration/ConfigurationSection.java new file mode 100644 index 0000000..5771aa3 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/configuration/ConfigurationSection.java @@ -0,0 +1,851 @@ +package org.bukkit.configuration; + +import org.bukkit.Color; +import org.bukkit.OfflinePlayer; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.Vector; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Represents a section of a {@link Configuration} + */ +public interface ConfigurationSection { + /** + * Gets a set containing all keys in this section. + *

+ * If deep is set to true, then this will contain all the keys within any + * child {@link ConfigurationSection}s (and their children, etc). These + * will be in a valid path notation for you to use. + *

+ * If deep is set to false, then this will contain only the keys of any + * direct children, and not their own children. + * + * @param deep Whether or not to get a deep list, as opposed to a shallow + * list. + * @return Set of keys contained within this ConfigurationSection. + */ + Set getKeys(boolean deep); + + /** + * Gets a Map containing all keys and their values for this section. + *

+ * If deep is set to true, then this will contain all the keys and values + * within any child {@link ConfigurationSection}s (and their children, + * etc). These keys will be in a valid path notation for you to use. + *

+ * If deep is set to false, then this will contain only the keys and + * values of any direct children, and not their own children. + * + * @param deep Whether or not to get a deep list, as opposed to a shallow + * list. + * @return Map of keys and values of this section. + */ + Map getValues(boolean deep); + + /** + * Checks if this {@link ConfigurationSection} contains the given path. + *

+ * If the value for the requested path does not exist but a default value + * has been specified, this will return true. + * + * @param path Path to check for existence. + * @return True if this section contains the requested path, either via + * default or being set. + * @throws IllegalArgumentException Thrown when path is null. + */ + boolean contains(String path); + + /** + * Checks if this {@link ConfigurationSection} has a value set for the + * given path. + *

+ * If the value for the requested path does not exist but a default value + * has been specified, this will still return false. + * + * @param path Path to check for existence. + * @return True if this section contains the requested path, regardless of + * having a default. + * @throws IllegalArgumentException Thrown when path is null. + */ + boolean isSet(String path); + + /** + * Gets the path of this {@link ConfigurationSection} from its root {@link + * Configuration} + *

+ * For any {@link Configuration} themselves, this will return an empty + * string. + *

+ * If the section is no longer contained within its root for any reason, + * such as being replaced with a different value, this may return null. + *

+ * To retrieve the single name of this section, that is, the final part of + * the path returned by this method, you may use {@link #getName()}. + * + * @return Path of this section relative to its root + */ + String getCurrentPath(); + + /** + * Gets the name of this individual {@link ConfigurationSection}, in the + * path. + *

+ * This will always be the final part of {@link #getCurrentPath()}, unless + * the section is orphaned. + * + * @return Name of this section + */ + String getName(); + + /** + * Gets the root {@link Configuration} that contains this {@link + * ConfigurationSection} + *

+ * For any {@link Configuration} themselves, this will return its own + * object. + *

+ * If the section is no longer contained within its root for any reason, + * such as being replaced with a different value, this may return null. + * + * @return Root configuration containing this section. + */ + Configuration getRoot(); + + /** + * Gets the parent {@link ConfigurationSection} that directly contains + * this {@link ConfigurationSection}. + *

+ * For any {@link Configuration} themselves, this will return null. + *

+ * If the section is no longer contained within its parent for any reason, + * such as being replaced with a different value, this may return null. + * + * @return Parent section containing this section. + */ + ConfigurationSection getParent(); + + /** + * Gets the requested Object by path. + *

+ * If the Object does not exist but a default value has been specified, + * this will return the default value. If the Object does not exist and no + * default value was specified, this will return null. + * + * @param path Path of the Object to get. + * @return Requested Object. + */ + Object get(String path); + + /** + * Gets the requested Object by path, returning a default value if not + * found. + *

+ * If the Object does not exist then the specified default value will + * returned regardless of if a default has been identified in the root + * {@link Configuration}. + * + * @param path Path of the Object to get. + * @param def The default value to return if the path is not found. + * @return Requested Object. + */ + Object get(String path, Object def); + + /** + * Sets the specified path to the given value. + *

+ * If value is null, the entry will be removed. Any existing entry will be + * replaced, regardless of what the new value is. + *

+ * Some implementations may have limitations on what you may store. See + * their individual javadocs for details. No implementations should allow + * you to store {@link Configuration}s or {@link ConfigurationSection}s, + * please use {@link #createSection(String)} for that. + * + * @param path Path of the object to set. + * @param value New value to set the path to. + */ + void set(String path, Object value); + + /** + * Creates an empty {@link ConfigurationSection} at the specified path. + *

+ * Any value that was previously set at this path will be overwritten. If + * the previous value was itself a {@link ConfigurationSection}, it will + * be orphaned. + * + * @param path Path to create the section at. + * @return Newly created section + */ + ConfigurationSection createSection(String path); + + /** + * Creates a {@link ConfigurationSection} at the specified path, with + * specified values. + *

+ * Any value that was previously set at this path will be overwritten. If + * the previous value was itself a {@link ConfigurationSection}, it will + * be orphaned. + * + * @param path Path to create the section at. + * @param map The values to used. + * @return Newly created section + */ + ConfigurationSection createSection(String path, Map map); + + // Primitives + /** + * Gets the requested String by path. + *

+ * If the String does not exist but a default value has been specified, + * this will return the default value. If the String does not exist and no + * default value was specified, this will return null. + * + * @param path Path of the String to get. + * @return Requested String. + */ + String getString(String path); + + /** + * Gets the requested String by path, returning a default value if not + * found. + *

+ * If the String does not exist then the specified default value will + * returned regardless of if a default has been identified in the root + * {@link Configuration}. + * + * @param path Path of the String to get. + * @param def The default value to return if the path is not found or is + * not a String. + * @return Requested String. + */ + String getString(String path, String def); + + /** + * Checks if the specified path is a String. + *

+ * If the path exists but is not a String, this will return false. If the + * path does not exist, this will return false. If the path does not exist + * but a default value has been specified, this will check if that default + * value is a String and return appropriately. + * + * @param path Path of the String to check. + * @return Whether or not the specified path is a String. + */ + boolean isString(String path); + + /** + * Gets the requested int by path. + *

+ * If the int does not exist but a default value has been specified, this + * will return the default value. If the int does not exist and no default + * value was specified, this will return 0. + * + * @param path Path of the int to get. + * @return Requested int. + */ + int getInt(String path); + + /** + * Gets the requested int by path, returning a default value if not found. + *

+ * If the int does not exist then the specified default value will + * returned regardless of if a default has been identified in the root + * {@link Configuration}. + * + * @param path Path of the int to get. + * @param def The default value to return if the path is not found or is + * not an int. + * @return Requested int. + */ + int getInt(String path, int def); + + /** + * Checks if the specified path is an int. + *

+ * If the path exists but is not a int, this will return false. If the + * path does not exist, this will return false. If the path does not exist + * but a default value has been specified, this will check if that default + * value is a int and return appropriately. + * + * @param path Path of the int to check. + * @return Whether or not the specified path is an int. + */ + boolean isInt(String path); + + /** + * Gets the requested boolean by path. + *

+ * If the boolean does not exist but a default value has been specified, + * this will return the default value. If the boolean does not exist and + * no default value was specified, this will return false. + * + * @param path Path of the boolean to get. + * @return Requested boolean. + */ + boolean getBoolean(String path); + + /** + * Gets the requested boolean by path, returning a default value if not + * found. + *

+ * If the boolean does not exist then the specified default value will + * returned regardless of if a default has been identified in the root + * {@link Configuration}. + * + * @param path Path of the boolean to get. + * @param def The default value to return if the path is not found or is + * not a boolean. + * @return Requested boolean. + */ + boolean getBoolean(String path, boolean def); + + /** + * Checks if the specified path is a boolean. + *

+ * If the path exists but is not a boolean, this will return false. If the + * path does not exist, this will return false. If the path does not exist + * but a default value has been specified, this will check if that default + * value is a boolean and return appropriately. + * + * @param path Path of the boolean to check. + * @return Whether or not the specified path is a boolean. + */ + boolean isBoolean(String path); + + /** + * Gets the requested double by path. + *

+ * If the double does not exist but a default value has been specified, + * this will return the default value. If the double does not exist and no + * default value was specified, this will return 0. + * + * @param path Path of the double to get. + * @return Requested double. + */ + double getDouble(String path); + + /** + * Gets the requested double by path, returning a default value if not + * found. + *

+ * If the double does not exist then the specified default value will + * returned regardless of if a default has been identified in the root + * {@link Configuration}. + * + * @param path Path of the double to get. + * @param def The default value to return if the path is not found or is + * not a double. + * @return Requested double. + */ + double getDouble(String path, double def); + + /** + * Checks if the specified path is a double. + *

+ * If the path exists but is not a double, this will return false. If the + * path does not exist, this will return false. If the path does not exist + * but a default value has been specified, this will check if that default + * value is a double and return appropriately. + * + * @param path Path of the double to check. + * @return Whether or not the specified path is a double. + */ + boolean isDouble(String path); + + // PaperSpigot start - Add getFloat + /** + * Gets the requested float by path. + *

+ * If the float does not exist but a default value has been specified, + * this will return the default value. If the float does not exist and no + * default value was specified, this will return 0. + * + * @param path Path of the float to get. + * @return Requested float. + */ + float getFloat(String path); + + /** + * Gets the requested float by path, returning a default value if not + * found. + *

+ * If the float does not exist then the specified default value will + * returned regardless of if a default has been identified in the root + * {@link Configuration}. + * + * @param path Path of the float to get. + * @param def The default value to return if the path is not found or is + * not a float. + * @return Requested float. + */ + float getFloat(String path, float def); + + /** + * Checks if the specified path is a float. + *

+ * If the path exists but is not a float, this will return false. If the + * path does not exist, this will return false. If the path does not exist + * but a default value has been specified, this will check if that default + * value is a gloat and return appropriately. + * + * @param path Path of the float to check. + * @return Whether or not the specified path is a float. + */ + boolean isFloat(String path); + // PaperSpigot end + + /** + * Gets the requested long by path. + *

+ * If the long does not exist but a default value has been specified, this + * will return the default value. If the long does not exist and no + * default value was specified, this will return 0. + * + * @param path Path of the long to get. + * @return Requested long. + */ + long getLong(String path); + + /** + * Gets the requested long by path, returning a default value if not + * found. + *

+ * If the long does not exist then the specified default value will + * returned regardless of if a default has been identified in the root + * {@link Configuration}. + * + * @param path Path of the long to get. + * @param def The default value to return if the path is not found or is + * not a long. + * @return Requested long. + */ + long getLong(String path, long def); + + /** + * Checks if the specified path is a long. + *

+ * If the path exists but is not a long, this will return false. If the + * path does not exist, this will return false. If the path does not exist + * but a default value has been specified, this will check if that default + * value is a long and return appropriately. + * + * @param path Path of the long to check. + * @return Whether or not the specified path is a long. + */ + boolean isLong(String path); + + // Java + /** + * Gets the requested List by path. + *

+ * If the List does not exist but a default value has been specified, this + * will return the default value. If the List does not exist and no + * default value was specified, this will return null. + * + * @param path Path of the List to get. + * @return Requested List. + */ + List getList(String path); + + /** + * Gets the requested List by path, returning a default value if not + * found. + *

+ * If the List does not exist then the specified default value will + * returned regardless of if a default has been identified in the root + * {@link Configuration}. + * + * @param path Path of the List to get. + * @param def The default value to return if the path is not found or is + * not a List. + * @return Requested List. + */ + List getList(String path, List def); + + /** + * Checks if the specified path is a List. + *

+ * If the path exists but is not a List, this will return false. If the + * path does not exist, this will return false. If the path does not exist + * but a default value has been specified, this will check if that default + * value is a List and return appropriately. + * + * @param path Path of the List to check. + * @return Whether or not the specified path is a List. + */ + boolean isList(String path); + + /** + * Gets the requested List of String by path. + *

+ * If the List does not exist but a default value has been specified, this + * will return the default value. If the List does not exist and no + * default value was specified, this will return an empty List. + *

+ * This method will attempt to cast any values into a String if possible, + * but may miss any values out if they are not compatible. + * + * @param path Path of the List to get. + * @return Requested List of String. + */ + List getStringList(String path); + + /** + * Gets the requested List of Integer by path. + *

+ * If the List does not exist but a default value has been specified, this + * will return the default value. If the List does not exist and no + * default value was specified, this will return an empty List. + *

+ * This method will attempt to cast any values into a Integer if possible, + * but may miss any values out if they are not compatible. + * + * @param path Path of the List to get. + * @return Requested List of Integer. + */ + List getIntegerList(String path); + + /** + * Gets the requested List of Boolean by path. + *

+ * If the List does not exist but a default value has been specified, this + * will return the default value. If the List does not exist and no + * default value was specified, this will return an empty List. + *

+ * This method will attempt to cast any values into a Boolean if possible, + * but may miss any values out if they are not compatible. + * + * @param path Path of the List to get. + * @return Requested List of Boolean. + */ + List getBooleanList(String path); + + /** + * Gets the requested List of Double by path. + *

+ * If the List does not exist but a default value has been specified, this + * will return the default value. If the List does not exist and no + * default value was specified, this will return an empty List. + *

+ * This method will attempt to cast any values into a Double if possible, + * but may miss any values out if they are not compatible. + * + * @param path Path of the List to get. + * @return Requested List of Double. + */ + List getDoubleList(String path); + + /** + * Gets the requested List of Float by path. + *

+ * If the List does not exist but a default value has been specified, this + * will return the default value. If the List does not exist and no + * default value was specified, this will return an empty List. + *

+ * This method will attempt to cast any values into a Float if possible, + * but may miss any values out if they are not compatible. + * + * @param path Path of the List to get. + * @return Requested List of Float. + */ + List getFloatList(String path); + + /** + * Gets the requested List of Long by path. + *

+ * If the List does not exist but a default value has been specified, this + * will return the default value. If the List does not exist and no + * default value was specified, this will return an empty List. + *

+ * This method will attempt to cast any values into a Long if possible, + * but may miss any values out if they are not compatible. + * + * @param path Path of the List to get. + * @return Requested List of Long. + */ + List getLongList(String path); + + /** + * Gets the requested List of Byte by path. + *

+ * If the List does not exist but a default value has been specified, this + * will return the default value. If the List does not exist and no + * default value was specified, this will return an empty List. + *

+ * This method will attempt to cast any values into a Byte if possible, + * but may miss any values out if they are not compatible. + * + * @param path Path of the List to get. + * @return Requested List of Byte. + */ + List getByteList(String path); + + /** + * Gets the requested List of Character by path. + *

+ * If the List does not exist but a default value has been specified, this + * will return the default value. If the List does not exist and no + * default value was specified, this will return an empty List. + *

+ * This method will attempt to cast any values into a Character if + * possible, but may miss any values out if they are not compatible. + * + * @param path Path of the List to get. + * @return Requested List of Character. + */ + List getCharacterList(String path); + + /** + * Gets the requested List of Short by path. + *

+ * If the List does not exist but a default value has been specified, this + * will return the default value. If the List does not exist and no + * default value was specified, this will return an empty List. + *

+ * This method will attempt to cast any values into a Short if possible, + * but may miss any values out if they are not compatible. + * + * @param path Path of the List to get. + * @return Requested List of Short. + */ + List getShortList(String path); + + /** + * Gets the requested List of Maps by path. + *

+ * If the List does not exist but a default value has been specified, this + * will return the default value. If the List does not exist and no + * default value was specified, this will return an empty List. + *

+ * This method will attempt to cast any values into a Map if possible, but + * may miss any values out if they are not compatible. + * + * @param path Path of the List to get. + * @return Requested List of Maps. + */ + List> getMapList(String path); + + // Bukkit + /** + * Gets the requested Vector by path. + *

+ * If the Vector does not exist but a default value has been specified, + * this will return the default value. If the Vector does not exist and no + * default value was specified, this will return null. + * + * @param path Path of the Vector to get. + * @return Requested Vector. + */ + Vector getVector(String path); + + /** + * Gets the requested {@link Vector} by path, returning a default value if + * not found. + *

+ * If the Vector does not exist then the specified default value will + * returned regardless of if a default has been identified in the root + * {@link Configuration}. + * + * @param path Path of the Vector to get. + * @param def The default value to return if the path is not found or is + * not a Vector. + * @return Requested Vector. + */ + Vector getVector(String path, Vector def); + + /** + * Checks if the specified path is a Vector. + *

+ * If the path exists but is not a Vector, this will return false. If the + * path does not exist, this will return false. If the path does not exist + * but a default value has been specified, this will check if that default + * value is a Vector and return appropriately. + * + * @param path Path of the Vector to check. + * @return Whether or not the specified path is a Vector. + */ + boolean isVector(String path); + + /** + * Gets the requested OfflinePlayer by path. + *

+ * If the OfflinePlayer does not exist but a default value has been + * specified, this will return the default value. If the OfflinePlayer + * does not exist and no default value was specified, this will return + * null. + * + * @param path Path of the OfflinePlayer to get. + * @return Requested OfflinePlayer. + */ + OfflinePlayer getOfflinePlayer(String path); + + /** + * Gets the requested {@link OfflinePlayer} by path, returning a default + * value if not found. + *

+ * If the OfflinePlayer does not exist then the specified default value + * will returned regardless of if a default has been identified in the + * root {@link Configuration}. + * + * @param path Path of the OfflinePlayer to get. + * @param def The default value to return if the path is not found or is + * not an OfflinePlayer. + * @return Requested OfflinePlayer. + */ + OfflinePlayer getOfflinePlayer(String path, OfflinePlayer def); + + /** + * Checks if the specified path is an OfflinePlayer. + *

+ * If the path exists but is not a OfflinePlayer, this will return false. + * If the path does not exist, this will return false. If the path does + * not exist but a default value has been specified, this will check if + * that default value is a OfflinePlayer and return appropriately. + * + * @param path Path of the OfflinePlayer to check. + * @return Whether or not the specified path is an OfflinePlayer. + */ + boolean isOfflinePlayer(String path); + + /** + * Gets the requested ItemStack by path. + *

+ * If the ItemStack does not exist but a default value has been specified, + * this will return the default value. If the ItemStack does not exist and + * no default value was specified, this will return null. + * + * @param path Path of the ItemStack to get. + * @return Requested ItemStack. + */ + ItemStack getItemStack(String path); + + /** + * Gets the requested {@link ItemStack} by path, returning a default value + * if not found. + *

+ * If the ItemStack does not exist then the specified default value will + * returned regardless of if a default has been identified in the root + * {@link Configuration}. + * + * @param path Path of the ItemStack to get. + * @param def The default value to return if the path is not found or is + * not an ItemStack. + * @return Requested ItemStack. + */ + ItemStack getItemStack(String path, ItemStack def); + + /** + * Checks if the specified path is an ItemStack. + *

+ * If the path exists but is not a ItemStack, this will return false. If + * the path does not exist, this will return false. If the path does not + * exist but a default value has been specified, this will check if that + * default value is a ItemStack and return appropriately. + * + * @param path Path of the ItemStack to check. + * @return Whether or not the specified path is an ItemStack. + */ + boolean isItemStack(String path); + + /** + * Gets the requested Color by path. + *

+ * If the Color does not exist but a default value has been specified, + * this will return the default value. If the Color does not exist and no + * default value was specified, this will return null. + * + * @param path Path of the Color to get. + * @return Requested Color. + */ + Color getColor(String path); + + /** + * Gets the requested {@link Color} by path, returning a default value if + * not found. + *

+ * If the Color does not exist then the specified default value will + * returned regardless of if a default has been identified in the root + * {@link Configuration}. + * + * @param path Path of the Color to get. + * @param def The default value to return if the path is not found or is + * not a Color. + * @return Requested Color. + */ + Color getColor(String path, Color def); + + /** + * Checks if the specified path is a Color. + *

+ * If the path exists but is not a Color, this will return false. If the + * path does not exist, this will return false. If the path does not exist + * but a default value has been specified, this will check if that default + * value is a Color and return appropriately. + * + * @param path Path of the Color to check. + * @return Whether or not the specified path is a Color. + */ + boolean isColor(String path); + + /** + * Gets the requested ConfigurationSection by path. + *

+ * If the ConfigurationSection does not exist but a default value has been + * specified, this will return the default value. If the + * ConfigurationSection does not exist and no default value was specified, + * this will return null. + * + * @param path Path of the ConfigurationSection to get. + * @return Requested ConfigurationSection. + */ + ConfigurationSection getConfigurationSection(String path); + + /** + * Checks if the specified path is a ConfigurationSection. + *

+ * If the path exists but is not a ConfigurationSection, this will return + * false. If the path does not exist, this will return false. If the path + * does not exist but a default value has been specified, this will check + * if that default value is a ConfigurationSection and return + * appropriately. + * + * @param path Path of the ConfigurationSection to check. + * @return Whether or not the specified path is a ConfigurationSection. + */ + boolean isConfigurationSection(String path); + + /** + * Gets the equivalent {@link ConfigurationSection} from the default + * {@link Configuration} defined in {@link #getRoot()}. + *

+ * If the root contains no defaults, or the defaults doesn't contain a + * value for this path, or the value at this path is not a {@link + * ConfigurationSection} then this will return null. + * + * @return Equivalent section in root configuration + */ + ConfigurationSection getDefaultSection(); + + /** + * Sets the default value in the root at the given path as provided. + *

+ * If no source {@link Configuration} was provided as a default + * collection, then a new {@link MemoryConfiguration} will be created to + * hold the new default value. + *

+ * If value is null, the value will be removed from the default + * Configuration source. + *

+ * If the value as returned by {@link #getDefaultSection()} is null, then + * this will create a new section at the path, replacing anything that may + * have existed there previously. + * + * @param path Path of the value to set. + * @param value Value to set the default to. + * @throws IllegalArgumentException Thrown if path is null. + */ + void addDefault(String path, Object value); +} diff --git a/azurite-api/src/main/java/org/bukkit/configuration/InvalidConfigurationException.java b/azurite-api/src/main/java/org/bukkit/configuration/InvalidConfigurationException.java new file mode 100644 index 0000000..d23480e --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/configuration/InvalidConfigurationException.java @@ -0,0 +1,45 @@ +package org.bukkit.configuration; + +/** + * Exception thrown when attempting to load an invalid {@link Configuration} + */ +@SuppressWarnings("serial") +public class InvalidConfigurationException extends Exception { + + /** + * Creates a new instance of InvalidConfigurationException without a + * message or cause. + */ + public InvalidConfigurationException() {} + + /** + * Constructs an instance of InvalidConfigurationException with the + * specified message. + * + * @param msg The details of the exception. + */ + public InvalidConfigurationException(String msg) { + super(msg); + } + + /** + * Constructs an instance of InvalidConfigurationException with the + * specified cause. + * + * @param cause The cause of the exception. + */ + public InvalidConfigurationException(Throwable cause) { + super(cause); + } + + /** + * Constructs an instance of InvalidConfigurationException with the + * specified message and cause. + * + * @param cause The cause of the exception. + * @param msg The details of the exception. + */ + public InvalidConfigurationException(String msg, Throwable cause) { + super(msg, cause); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/configuration/MemoryConfiguration.java b/azurite-api/src/main/java/org/bukkit/configuration/MemoryConfiguration.java new file mode 100644 index 0000000..bd915ae --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/configuration/MemoryConfiguration.java @@ -0,0 +1,79 @@ +package org.bukkit.configuration; + +import org.apache.commons.lang.Validate; + +import java.util.Map; + +/** + * This is a {@link Configuration} implementation that does not save or load + * from any source, and stores all values in memory only. + * This is useful for temporary Configurations for providing defaults. + */ +public class MemoryConfiguration extends MemorySection implements Configuration { + protected Configuration defaults; + protected MemoryConfigurationOptions options; + + /** + * Creates an empty {@link MemoryConfiguration} with no default values. + */ + public MemoryConfiguration() {} + + /** + * Creates an empty {@link MemoryConfiguration} using the specified {@link + * Configuration} as a source for all default values. + * + * @param defaults Default value provider + * @throws IllegalArgumentException Thrown if defaults is null + */ + public MemoryConfiguration(Configuration defaults) { + this.defaults = defaults; + } + + @Override + public void addDefault(String path, Object value) { + Validate.notNull(path, "Path may not be null"); + + if (defaults == null) { + defaults = new MemoryConfiguration(); + } + + defaults.set(path, value); + } + + public void addDefaults(Map defaults) { + Validate.notNull(defaults, "Defaults may not be null"); + + for (Map.Entry entry : defaults.entrySet()) { + addDefault(entry.getKey(), entry.getValue()); + } + } + + public void addDefaults(Configuration defaults) { + Validate.notNull(defaults, "Defaults may not be null"); + + addDefaults(defaults.getValues(true)); + } + + public void setDefaults(Configuration defaults) { + Validate.notNull(defaults, "Defaults may not be null"); + + this.defaults = defaults; + } + + public Configuration getDefaults() { + return defaults; + } + + @Override + public ConfigurationSection getParent() { + return null; + } + + public MemoryConfigurationOptions options() { + if (options == null) { + options = new MemoryConfigurationOptions(this); + } + + return options; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/configuration/MemoryConfigurationOptions.java b/azurite-api/src/main/java/org/bukkit/configuration/MemoryConfigurationOptions.java new file mode 100644 index 0000000..44c046c --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/configuration/MemoryConfigurationOptions.java @@ -0,0 +1,28 @@ +package org.bukkit.configuration; + +/** + * Various settings for controlling the input and output of a {@link + * MemoryConfiguration} + */ +public class MemoryConfigurationOptions extends ConfigurationOptions { + protected MemoryConfigurationOptions(MemoryConfiguration configuration) { + super(configuration); + } + + @Override + public MemoryConfiguration configuration() { + return (MemoryConfiguration) super.configuration(); + } + + @Override + public MemoryConfigurationOptions copyDefaults(boolean value) { + super.copyDefaults(value); + return this; + } + + @Override + public MemoryConfigurationOptions pathSeparator(char value) { + super.pathSeparator(value); + return this; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/configuration/MemorySection.java b/azurite-api/src/main/java/org/bukkit/configuration/MemorySection.java new file mode 100644 index 0000000..238588c --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/configuration/MemorySection.java @@ -0,0 +1,832 @@ +package org.bukkit.configuration; + +import org.apache.commons.lang.Validate; +import org.bukkit.Color; +import org.bukkit.OfflinePlayer; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.Vector; + +import java.util.*; + +import static org.bukkit.util.NumberConversions.*; + +/** + * A type of {@link ConfigurationSection} that is stored in memory. + */ +public class MemorySection implements ConfigurationSection { + protected final Map map = new LinkedHashMap(); + private final Configuration root; + private final ConfigurationSection parent; + private final String path; + private final String fullPath; + + /** + * Creates an empty MemorySection for use as a root {@link Configuration} + * section. + *

+ * Note that calling this without being yourself a {@link Configuration} + * will throw an exception! + * + * @throws IllegalStateException Thrown if this is not a {@link + * Configuration} root. + */ + protected MemorySection() { + if (!(this instanceof Configuration)) { + throw new IllegalStateException("Cannot construct a root MemorySection when not a Configuration"); + } + + this.path = ""; + this.fullPath = ""; + this.parent = null; + this.root = (Configuration) this; + } + + /** + * Creates an empty MemorySection with the specified parent and path. + * + * @param parent Parent section that contains this own section. + * @param path Path that you may access this section from via the root + * {@link Configuration}. + * @throws IllegalArgumentException Thrown is parent or path is null, or + * if parent contains no root Configuration. + */ + protected MemorySection(ConfigurationSection parent, String path) { + Validate.notNull(parent, "Parent cannot be null"); + Validate.notNull(path, "Path cannot be null"); + + this.path = path; + this.parent = parent; + this.root = parent.getRoot(); + + Validate.notNull(root, "Path cannot be orphaned"); + + this.fullPath = createPath(parent, path); + } + + public Set getKeys(boolean deep) { + Set result = new LinkedHashSet<>(); + + Configuration root = getRoot(); + if (root != null && root.options().copyDefaults()) { + ConfigurationSection defaults = getDefaultSection(); + + if (defaults != null) { + result.addAll(defaults.getKeys(deep)); + } + } + + mapChildrenKeys(result, this, deep); + + return result; + } + + public Map getValues(boolean deep) { + Map result = new LinkedHashMap(); + + Configuration root = getRoot(); + if (root != null && root.options().copyDefaults()) { + ConfigurationSection defaults = getDefaultSection(); + + if (defaults != null) { + result.putAll(defaults.getValues(deep)); + } + } + + mapChildrenValues(result, this, deep); + + return result; + } + + public boolean contains(String path) { + return get(path) != null; + } + + public boolean isSet(String path) { + Configuration root = getRoot(); + if (root == null) { + return false; + } + if (root.options().copyDefaults()) { + return contains(path); + } + return get(path, null) != null; + } + + public String getCurrentPath() { + return fullPath; + } + + public String getName() { + return path; + } + + public Configuration getRoot() { + return root; + } + + public ConfigurationSection getParent() { + return parent; + } + + public void addDefault(String path, Object value) { + Validate.notNull(path, "Path cannot be null"); + + Configuration root = getRoot(); + if (root == null) { + throw new IllegalStateException("Cannot add default without root"); + } + if (root == this) { + throw new UnsupportedOperationException("Unsupported addDefault(String, Object) implementation"); + } + root.addDefault(createPath(this, path), value); + } + + public ConfigurationSection getDefaultSection() { + Configuration root = getRoot(); + Configuration defaults = root == null ? null : root.getDefaults(); + + if (defaults != null) { + if (defaults.isConfigurationSection(getCurrentPath())) { + return defaults.getConfigurationSection(getCurrentPath()); + } + } + + return null; + } + + public void set(String path, Object value) { + Validate.notEmpty(path, "Cannot set to an empty path"); + + Configuration root = getRoot(); + if (root == null) { + throw new IllegalStateException("Cannot use section without a root"); + } + + final char separator = root.options().pathSeparator(); + // i1 is the leading (higher) index + // i2 is the trailing (lower) index + int i1 = -1, i2; + ConfigurationSection section = this; + while ((i1 = path.indexOf(separator, i2 = i1 + 1)) != -1) { + String node = path.substring(i2, i1); + ConfigurationSection subSection = section.getConfigurationSection(node); + if (subSection == null) { + section = section.createSection(node); + } else { + section = subSection; + } + } + + String key = path.substring(i2); + if (section == this) { + if (value == null) { + map.remove(key); + } else { + map.put(key, value); + } + } else { + section.set(key, value); + } + } + + public Object get(String path) { + return get(path, getDefault(path)); + } + + public Object get(String path, Object def) { + Validate.notNull(path, "Path cannot be null"); + + if (path.length() == 0) { + return this; + } + + Configuration root = getRoot(); + if (root == null) { + throw new IllegalStateException("Cannot access section without a root"); + } + + final char separator = root.options().pathSeparator(); + // i1 is the leading (higher) index + // i2 is the trailing (lower) index + int i1 = -1, i2; + ConfigurationSection section = this; + while ((i1 = path.indexOf(separator, i2 = i1 + 1)) != -1) { + section = section.getConfigurationSection(path.substring(i2, i1)); + if (section == null) { + return def; + } + } + + String key = path.substring(i2); + if (section == this) { + Object result = map.get(key); + return (result == null) ? def : result; + } + return section.get(key, def); + } + + public ConfigurationSection createSection(String path) { + Validate.notEmpty(path, "Cannot create section at empty path"); + Configuration root = getRoot(); + if (root == null) { + throw new IllegalStateException("Cannot create section without a root"); + } + + final char separator = root.options().pathSeparator(); + // i1 is the leading (higher) index + // i2 is the trailing (lower) index + int i1 = -1, i2; + ConfigurationSection section = this; + while ((i1 = path.indexOf(separator, i2 = i1 + 1)) != -1) { + String node = path.substring(i2, i1); + ConfigurationSection subSection = section.getConfigurationSection(node); + if (subSection == null) { + section = section.createSection(node); + } else { + section = subSection; + } + } + + String key = path.substring(i2); + if (section == this) { + ConfigurationSection result = new MemorySection(this, key); + map.put(key, result); + return result; + } + return section.createSection(key); + } + + public ConfigurationSection createSection(String path, Map map) { + ConfigurationSection section = createSection(path); + + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() instanceof Map) { + section.createSection(entry.getKey().toString(), (Map) entry.getValue()); + } else { + section.set(entry.getKey().toString(), entry.getValue()); + } + } + + return section; + } + + // Primitives + public String getString(String path) { + Object def = getDefault(path); + return getString(path, def != null ? def.toString() : null); + } + + public String getString(String path, String def) { + Object val = get(path, def); + return (val != null) ? val.toString() : def; + } + + public boolean isString(String path) { + Object val = get(path); + return val instanceof String; + } + + public int getInt(String path) { + Object def = getDefault(path); + return getInt(path, (def instanceof Number) ? toInt(def) : 0); + } + + public int getInt(String path, int def) { + Object val = get(path, def); + return (val instanceof Number) ? toInt(val) : def; + } + + public boolean isInt(String path) { + Object val = get(path); + return val instanceof Integer; + } + + public boolean getBoolean(String path) { + Object def = getDefault(path); + return getBoolean(path, (def instanceof Boolean) ? (Boolean) def : false); + } + + public boolean getBoolean(String path, boolean def) { + Object val = get(path, def); + return (val instanceof Boolean) ? (Boolean) val : def; + } + + public boolean isBoolean(String path) { + Object val = get(path); + return val instanceof Boolean; + } + + public double getDouble(String path) { + Object def = getDefault(path); + return getDouble(path, (def instanceof Number) ? toDouble(def) : 0); + } + + public double getDouble(String path, double def) { + Object val = get(path, def); + return (val instanceof Number) ? toDouble(val) : def; + } + + public boolean isDouble(String path) { + Object val = get(path); + return val instanceof Double; + } + + // PaperSpigot start - Add getFloat + public float getFloat(String path) { + Object def = getDefault(path); + return getFloat(path, (def instanceof Float) ? toFloat(def) : 0); + } + + public float getFloat(String path, float def) { + Object val = get(path, def); + return (val instanceof Float) ? toFloat(val) : def; + } + + public boolean isFloat(String path) { + Object val = get(path); + return val instanceof Float; + } + // PaperSpigot end + + public long getLong(String path) { + Object def = getDefault(path); + return getLong(path, (def instanceof Number) ? toLong(def) : 0); + } + + public long getLong(String path, long def) { + Object val = get(path, def); + return (val instanceof Number) ? toLong(val) : def; + } + + public boolean isLong(String path) { + Object val = get(path); + return val instanceof Long; + } + + // Java + public List getList(String path) { + Object def = getDefault(path); + return getList(path, (def instanceof List) ? (List) def : null); + } + + public List getList(String path, List def) { + Object val = get(path, def); + return (List) ((val instanceof List) ? val : def); + } + + public boolean isList(String path) { + Object val = get(path); + return val instanceof List; + } + + public List getStringList(String path) { + List list = getList(path); + + if (list == null) { + return new ArrayList(0); + } + + List result = new ArrayList(); + + for (Object object : list) { + if ((object instanceof String) || (isPrimitiveWrapper(object))) { + result.add(String.valueOf(object)); + } + } + + return result; + } + + public List getIntegerList(String path) { + List list = getList(path); + + if (list == null) { + return new ArrayList(0); + } + + List result = new ArrayList(); + + for (Object object : list) { + if (object instanceof Integer) { + result.add((Integer) object); + } else if (object instanceof String) { + try { + result.add(Integer.valueOf((String) object)); + } catch (Exception ignored) { + } + } else if (object instanceof Character) { + result.add((int) ((Character) object).charValue()); + } else if (object instanceof Number) { + result.add(((Number) object).intValue()); + } + } + + return result; + } + + public List getBooleanList(String path) { + List list = getList(path); + + if (list == null) { + return new ArrayList(0); + } + + List result = new ArrayList(); + + for (Object object : list) { + if (object instanceof Boolean) { + result.add((Boolean) object); + } else if (object instanceof String) { + if (Boolean.TRUE.toString().equals(object)) { + result.add(true); + } else if (Boolean.FALSE.toString().equals(object)) { + result.add(false); + } + } + } + + return result; + } + + public List getDoubleList(String path) { + List list = getList(path); + + if (list == null) { + return new ArrayList(0); + } + + List result = new ArrayList(); + + for (Object object : list) { + if (object instanceof Double) { + result.add((Double) object); + } else if (object instanceof String) { + try { + result.add(Double.valueOf((String) object)); + } catch (Exception ignored) { + } + } else if (object instanceof Character) { + result.add((double) ((Character) object).charValue()); + } else if (object instanceof Number) { + result.add(((Number) object).doubleValue()); + } + } + + return result; + } + + public List getFloatList(String path) { + List list = getList(path); + + if (list == null) { + return new ArrayList(0); + } + + List result = new ArrayList(); + + for (Object object : list) { + if (object instanceof Float) { + result.add((Float) object); + } else if (object instanceof String) { + try { + result.add(Float.valueOf((String) object)); + } catch (Exception ignored) { + } + } else if (object instanceof Character) { + result.add((float) ((Character) object).charValue()); + } else if (object instanceof Number) { + result.add(((Number) object).floatValue()); + } + } + + return result; + } + + public List getLongList(String path) { + List list = getList(path); + + if (list == null) { + return new ArrayList(0); + } + + List result = new ArrayList(); + + for (Object object : list) { + if (object instanceof Long) { + result.add((Long) object); + } else if (object instanceof String) { + try { + result.add(Long.valueOf((String) object)); + } catch (Exception ignored) { + } + } else if (object instanceof Character) { + result.add((long) ((Character) object).charValue()); + } else if (object instanceof Number) { + result.add(((Number) object).longValue()); + } + } + + return result; + } + + public List getByteList(String path) { + List list = getList(path); + + if (list == null) { + return new ArrayList(0); + } + + List result = new ArrayList(); + + for (Object object : list) { + if (object instanceof Byte) { + result.add((Byte) object); + } else if (object instanceof String) { + try { + result.add(Byte.valueOf((String) object)); + } catch (Exception ignored) { + } + } else if (object instanceof Character) { + result.add((byte) ((Character) object).charValue()); + } else if (object instanceof Number) { + result.add(((Number) object).byteValue()); + } + } + + return result; + } + + public List getCharacterList(String path) { + List list = getList(path); + + if (list == null) { + return new ArrayList(0); + } + + List result = new ArrayList(); + + for (Object object : list) { + if (object instanceof Character) { + result.add((Character) object); + } else if (object instanceof String) { + String str = (String) object; + + if (str.length() == 1) { + result.add(str.charAt(0)); + } + } else if (object instanceof Number) { + result.add((char) ((Number) object).intValue()); + } + } + + return result; + } + + public List getShortList(String path) { + List list = getList(path); + + if (list == null) { + return new ArrayList(0); + } + + List result = new ArrayList(); + + for (Object object : list) { + if (object instanceof Short) { + result.add((Short) object); + } else if (object instanceof String) { + try { + result.add(Short.valueOf((String) object)); + } catch (Exception ignored) { + } + } else if (object instanceof Character) { + result.add((short) ((Character) object).charValue()); + } else if (object instanceof Number) { + result.add(((Number) object).shortValue()); + } + } + + return result; + } + + public List> getMapList(String path) { + List list = getList(path); + List> result = new ArrayList>(); + + if (list == null) { + return result; + } + + for (Object object : list) { + if (object instanceof Map) { + result.add((Map) object); + } + } + + return result; + } + + // Bukkit + public Vector getVector(String path) { + Object def = getDefault(path); + return getVector(path, (def instanceof Vector) ? (Vector) def : null); + } + + public Vector getVector(String path, Vector def) { + Object val = get(path, def); + return (val instanceof Vector) ? (Vector) val : def; + } + + public boolean isVector(String path) { + Object val = get(path); + return val instanceof Vector; + } + + public OfflinePlayer getOfflinePlayer(String path) { + Object def = getDefault(path); + return getOfflinePlayer(path, (def instanceof OfflinePlayer) ? (OfflinePlayer) def : null); + } + + public OfflinePlayer getOfflinePlayer(String path, OfflinePlayer def) { + Object val = get(path, def); + return (val instanceof OfflinePlayer) ? (OfflinePlayer) val : def; + } + + public boolean isOfflinePlayer(String path) { + Object val = get(path); + return val instanceof OfflinePlayer; + } + + public ItemStack getItemStack(String path) { + Object def = getDefault(path); + return getItemStack(path, (def instanceof ItemStack) ? (ItemStack) def : null); + } + + public ItemStack getItemStack(String path, ItemStack def) { + Object val = get(path, def); + return (val instanceof ItemStack) ? (ItemStack) val : def; + } + + public boolean isItemStack(String path) { + Object val = get(path); + return val instanceof ItemStack; + } + + public Color getColor(String path) { + Object def = getDefault(path); + return getColor(path, (def instanceof Color) ? (Color) def : null); + } + + public Color getColor(String path, Color def) { + Object val = get(path, def); + return (val instanceof Color) ? (Color) val : def; + } + + public boolean isColor(String path) { + Object val = get(path); + return val instanceof Color; + } + + public ConfigurationSection getConfigurationSection(String path) { + Object val = get(path, null); + if (val != null) { + return (val instanceof ConfigurationSection) ? (ConfigurationSection) val : null; + } + + val = get(path, getDefault(path)); + return (val instanceof ConfigurationSection) ? createSection(path) : null; + } + + public boolean isConfigurationSection(String path) { + Object val = get(path); + return val instanceof ConfigurationSection; + } + + protected boolean isPrimitiveWrapper(Object input) { + return input instanceof Integer || input instanceof Boolean || + input instanceof Character || input instanceof Byte || + input instanceof Short || input instanceof Double || + input instanceof Long || input instanceof Float; + } + + protected Object getDefault(String path) { + Validate.notNull(path, "Path cannot be null"); + + Configuration root = getRoot(); + Configuration defaults = root == null ? null : root.getDefaults(); + return (defaults == null) ? null : defaults.get(createPath(this, path)); + } + + protected void mapChildrenKeys(Set output, ConfigurationSection section, boolean deep) { + if (section instanceof MemorySection) { + MemorySection sec = (MemorySection) section; + + for (Map.Entry entry : sec.map.entrySet()) { + output.add(createPath(section, entry.getKey(), this)); + + if ((deep) && (entry.getValue() instanceof ConfigurationSection)) { + ConfigurationSection subsection = (ConfigurationSection) entry.getValue(); + mapChildrenKeys(output, subsection, deep); + } + } + } else { + Set keys = section.getKeys(deep); + + for (String key : keys) { + output.add(createPath(section, key, this)); + } + } + } + + protected void mapChildrenValues(Map output, ConfigurationSection section, boolean deep) { + if (section instanceof MemorySection) { + MemorySection sec = (MemorySection) section; + + for (Map.Entry entry : sec.map.entrySet()) { + output.put(createPath(section, entry.getKey(), this), entry.getValue()); + + if (entry.getValue() instanceof ConfigurationSection) { + if (deep) { + mapChildrenValues(output, (ConfigurationSection) entry.getValue(), deep); + } + } + } + } else { + Map values = section.getValues(deep); + + for (Map.Entry entry : values.entrySet()) { + output.put(createPath(section, entry.getKey(), this), entry.getValue()); + } + } + } + + /** + * Creates a full path to the given {@link ConfigurationSection} from its + * root {@link Configuration}. + *

+ * You may use this method for any given {@link ConfigurationSection}, not + * only {@link MemorySection}. + * + * @param section Section to create a path for. + * @param key Name of the specified section. + * @return Full path of the section from its root. + */ + public static String createPath(ConfigurationSection section, String key) { + return createPath(section, key, (section == null) ? null : section.getRoot()); + } + + /** + * Creates a relative path to the given {@link ConfigurationSection} from + * the given relative section. + *

+ * You may use this method for any given {@link ConfigurationSection}, not + * only {@link MemorySection}. + * + * @param section Section to create a path for. + * @param key Name of the specified section. + * @param relativeTo Section to create the path relative to. + * @return Full path of the section from its root. + */ + public static String createPath(ConfigurationSection section, String key, ConfigurationSection relativeTo) { + Validate.notNull(section, "Cannot create path without a section"); + Configuration root = section.getRoot(); + if (root == null) { + throw new IllegalStateException("Cannot create path without a root"); + } + char separator = root.options().pathSeparator(); + + StringBuilder builder = new StringBuilder(); + if (section != null) { + for (ConfigurationSection parent = section; (parent != null) && (parent != relativeTo); parent = parent.getParent()) { + if (builder.length() > 0) { + builder.insert(0, separator); + } + + builder.insert(0, parent.getName()); + } + } + + if ((key != null) && (key.length() > 0)) { + if (builder.length() > 0) { + builder.append(separator); + } + + builder.append(key); + } + + return builder.toString(); + } + + @Override + public String toString() { + Configuration root = getRoot(); + return new StringBuilder() + .append(getClass().getSimpleName()) + .append("[path='") + .append(getCurrentPath()) + .append("', root='") + .append(root == null ? null : root.getClass().getSimpleName()) + .append("']") + .toString(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/configuration/file/FileConfiguration.java b/azurite-api/src/main/java/org/bukkit/configuration/file/FileConfiguration.java new file mode 100644 index 0000000..49883d6 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/configuration/file/FileConfiguration.java @@ -0,0 +1,279 @@ +package org.bukkit.configuration.file; + +import com.google.common.base.Charsets; +import com.google.common.io.Files; +import org.apache.commons.lang.Validate; +import org.bukkit.configuration.Configuration; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.MemoryConfiguration; +import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; + +import java.io.*; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; + +/** + * This is a base class for all File based implementations of {@link + * Configuration} + */ +public abstract class FileConfiguration extends MemoryConfiguration { + /** + * This value specified that the system default encoding should be + * completely ignored, as it cannot handle the ASCII character set, or it + * is a strict-subset of UTF8 already (plain ASCII). + * + * @deprecated temporary compatibility measure + */ + @Deprecated + public static final boolean UTF8_OVERRIDE; + /** + * This value specifies if the system default encoding is unicode, but + * cannot parse standard ASCII. + * + * @deprecated temporary compatibility measure + */ + @Deprecated + public static final boolean UTF_BIG; + /** + * This value specifies if the system supports unicode. + * + * @deprecated temporary compatibility measure + */ + @Deprecated + public static final boolean SYSTEM_UTF; + static { + final byte[] testBytes = Base64Coder.decode("ICEiIyQlJicoKSorLC0uLzAxMjM0NTY3ODk6Ozw9Pj9AQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVpbXF1eX2BhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ent8fX4NCg=="); + final String testString = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\r\n"; + final Charset defaultCharset = Charset.defaultCharset(); + final String resultString = new String(testBytes, defaultCharset); + final boolean trueUTF = defaultCharset.name().contains("UTF"); + UTF8_OVERRIDE = !testString.equals(resultString) || defaultCharset.equals(StandardCharsets.US_ASCII); + SYSTEM_UTF = trueUTF || UTF8_OVERRIDE; + UTF_BIG = trueUTF && UTF8_OVERRIDE; + } + + /** + * Creates an empty {@link FileConfiguration} with no default values. + */ + public FileConfiguration() { + super(); + } + + /** + * Creates an empty {@link FileConfiguration} using the specified {@link + * Configuration} as a source for all default values. + * + * @param defaults Default value provider + */ + public FileConfiguration(Configuration defaults) { + super(defaults); + } + + /** + * Saves this {@link FileConfiguration} to the specified location. + *

+ * If the file does not exist, it will be created. If already exists, it + * will be overwritten. If it cannot be overwritten or created, an + * exception will be thrown. + *

+ * This method will save using the system default encoding, or possibly + * using UTF8. + * + * @param file File to save to. + * @throws IOException Thrown when the given file cannot be written to for + * any reason. + * @throws IllegalArgumentException Thrown when file is null. + */ + public void save(File file) throws IOException { + Validate.notNull(file, "File cannot be null"); + + Files.createParentDirs(file); + + String data = saveToString(); + + Writer writer = new OutputStreamWriter(new FileOutputStream(file), UTF8_OVERRIDE && !UTF_BIG ? Charsets.UTF_8 : Charset.defaultCharset()); + + try { + writer.write(data); + } finally { + writer.close(); + } + } + + /** + * Saves this {@link FileConfiguration} to the specified location. + *

+ * If the file does not exist, it will be created. If already exists, it + * will be overwritten. If it cannot be overwritten or created, an + * exception will be thrown. + *

+ * This method will save using the system default encoding, or possibly + * using UTF8. + * + * @param file File to save to. + * @throws IOException Thrown when the given file cannot be written to for + * any reason. + * @throws IllegalArgumentException Thrown when file is null. + */ + public void save(String file) throws IOException { + Validate.notNull(file, "File cannot be null"); + + save(new File(file)); + } + + /** + * Saves this {@link FileConfiguration} to a string, and returns it. + * + * @return String containing this configuration. + */ + public abstract String saveToString(); + + /** + * Loads this {@link FileConfiguration} from the specified location. + *

+ * All the values contained within this configuration will be removed, + * leaving only settings and defaults, and the new values will be loaded + * from the given file. + *

+ * If the file cannot be loaded for any reason, an exception will be + * thrown. + *

+ * This will attempt to use the {@link Charset#defaultCharset()} for + * files, unless {@link #UTF8_OVERRIDE} but not {@link #UTF_BIG} is + * specified. + * + * @param file File to load from. + * @throws FileNotFoundException Thrown when the given file cannot be + * opened. + * @throws IOException Thrown when the given file cannot be read. + * @throws InvalidConfigurationException Thrown when the given file is not + * a valid Configuration. + * @throws IllegalArgumentException Thrown when file is null. + */ + public void load(File file) throws FileNotFoundException, IOException, InvalidConfigurationException { + Validate.notNull(file, "File cannot be null"); + + final FileInputStream stream = new FileInputStream(file); + + load(new InputStreamReader(stream, UTF8_OVERRIDE && !UTF_BIG ? Charsets.UTF_8 : Charset.defaultCharset())); + } + + /** + * Loads this {@link FileConfiguration} from the specified stream. + *

+ * All the values contained within this configuration will be removed, + * leaving only settings and defaults, and the new values will be loaded + * from the given stream. + *

+ * This will attempt to use the {@link Charset#defaultCharset()}, unless + * {@link #UTF8_OVERRIDE} or {@link #UTF_BIG} is specified. + * + * @param stream Stream to load from + * @throws IOException Thrown when the given file cannot be read. + * @throws InvalidConfigurationException Thrown when the given file is not + * a valid Configuration. + * @throws IllegalArgumentException Thrown when stream is null. + * @deprecated This does not consider encoding + * @see #load(Reader) + */ + @Deprecated + public void load(InputStream stream) throws IOException, InvalidConfigurationException { + Validate.notNull(stream, "Stream cannot be null"); + + load(new InputStreamReader(stream, UTF8_OVERRIDE ? Charsets.UTF_8 : Charset.defaultCharset())); + } + + /** + * Loads this {@link FileConfiguration} from the specified reader. + *

+ * All the values contained within this configuration will be removed, + * leaving only settings and defaults, and the new values will be loaded + * from the given stream. + * + * @param reader the reader to load from + * @throws IOException thrown when underlying reader throws an IOException + * @throws InvalidConfigurationException thrown when the reader does not + * represent a valid Configuration + * @throws IllegalArgumentException thrown when reader is null + */ + public void load(Reader reader) throws IOException, InvalidConfigurationException { + BufferedReader input = reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader); + + StringBuilder builder = new StringBuilder(); + + try { + String line; + + while ((line = input.readLine()) != null) { + builder.append(line); + builder.append('\n'); + } + } finally { + input.close(); + } + + loadFromString(builder.toString()); + } + + /** + * Loads this {@link FileConfiguration} from the specified location. + *

+ * All the values contained within this configuration will be removed, + * leaving only settings and defaults, and the new values will be loaded + * from the given file. + *

+ * If the file cannot be loaded for any reason, an exception will be + * thrown. + * + * @param file File to load from. + * @throws FileNotFoundException Thrown when the given file cannot be + * opened. + * @throws IOException Thrown when the given file cannot be read. + * @throws InvalidConfigurationException Thrown when the given file is not + * a valid Configuration. + * @throws IllegalArgumentException Thrown when file is null. + */ + public void load(String file) throws FileNotFoundException, IOException, InvalidConfigurationException { + Validate.notNull(file, "File cannot be null"); + + load(new File(file)); + } + + /** + * Loads this {@link FileConfiguration} from the specified string, as + * opposed to from file. + *

+ * All the values contained within this configuration will be removed, + * leaving only settings and defaults, and the new values will be loaded + * from the given string. + *

+ * If the string is invalid in any way, an exception will be thrown. + * + * @param contents Contents of a Configuration to load. + * @throws InvalidConfigurationException Thrown if the specified string is + * invalid. + * @throws IllegalArgumentException Thrown if contents is null. + */ + public abstract void loadFromString(String contents) throws InvalidConfigurationException; + + /** + * Compiles the header for this {@link FileConfiguration} and returns the + * result. + *

+ * This will use the header from {@link #options()} -> {@link + * FileConfigurationOptions#header()}, respecting the rules of {@link + * FileConfigurationOptions#copyHeader()} if set. + * + * @return Compiled header + */ + protected abstract String buildHeader(); + + @Override + public FileConfigurationOptions options() { + if (options == null) { + options = new FileConfigurationOptions(this); + } + + return (FileConfigurationOptions) options; + } +} \ No newline at end of file diff --git a/azurite-api/src/main/java/org/bukkit/configuration/file/FileConfigurationOptions.java b/azurite-api/src/main/java/org/bukkit/configuration/file/FileConfigurationOptions.java new file mode 100644 index 0000000..adfae5c --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/configuration/file/FileConfigurationOptions.java @@ -0,0 +1,120 @@ +package org.bukkit.configuration.file; + +import org.bukkit.configuration.Configuration; +import org.bukkit.configuration.MemoryConfiguration; +import org.bukkit.configuration.MemoryConfigurationOptions; + +/** + * Various settings for controlling the input and output of a {@link + * FileConfiguration} + */ +public class FileConfigurationOptions extends MemoryConfigurationOptions { + private String header = null; + private boolean copyHeader = true; + + protected FileConfigurationOptions(MemoryConfiguration configuration) { + super(configuration); + } + + @Override + public FileConfiguration configuration() { + return (FileConfiguration) super.configuration(); + } + + @Override + public FileConfigurationOptions copyDefaults(boolean value) { + super.copyDefaults(value); + return this; + } + + @Override + public FileConfigurationOptions pathSeparator(char value) { + super.pathSeparator(value); + return this; + } + + /** + * Gets the header that will be applied to the top of the saved output. + *

+ * This header will be commented out and applied directly at the top of + * the generated output of the {@link FileConfiguration}. It is not + * required to include a newline at the end of the header as it will + * automatically be applied, but you may include one if you wish for extra + * spacing. + *

+ * Null is a valid value which will indicate that no header is to be + * applied. The default value is null. + * + * @return Header + */ + public String header() { + return header; + } + + /** + * Sets the header that will be applied to the top of the saved output. + *

+ * This header will be commented out and applied directly at the top of + * the generated output of the {@link FileConfiguration}. It is not + * required to include a newline at the end of the header as it will + * automatically be applied, but you may include one if you wish for extra + * spacing. + *

+ * Null is a valid value which will indicate that no header is to be + * applied. + * + * @param value New header + * @return This object, for chaining + */ + public FileConfigurationOptions header(String value) { + this.header = value; + return this; + } + + /** + * Gets whether or not the header should be copied from a default source. + *

+ * If this is true, if a default {@link FileConfiguration} is passed to + * {@link + * FileConfiguration#setDefaults(Configuration)} + * then upon saving it will use the header from that config, instead of + * the one provided here. + *

+ * If no default is set on the configuration, or the default is not of + * type FileConfiguration, or that config has no header ({@link #header()} + * returns null) then the header specified in this configuration will be + * used. + *

+ * Defaults to true. + * + * @return Whether or not to copy the header + */ + public boolean copyHeader() { + return copyHeader; + } + + /** + * Sets whether or not the header should be copied from a default source. + *

+ * If this is true, if a default {@link FileConfiguration} is passed to + * {@link + * FileConfiguration#setDefaults(Configuration)} + * then upon saving it will use the header from that config, instead of + * the one provided here. + *

+ * If no default is set on the configuration, or the default is not of + * type FileConfiguration, or that config has no header ({@link #header()} + * returns null) then the header specified in this configuration will be + * used. + *

+ * Defaults to true. + * + * @param value Whether or not to copy the header + * @return This object, for chaining + */ + public FileConfigurationOptions copyHeader(boolean value) { + copyHeader = value; + + return this; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/configuration/file/YamlConfiguration.java b/azurite-api/src/main/java/org/bukkit/configuration/file/YamlConfiguration.java new file mode 100644 index 0000000..c09ac1a --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/configuration/file/YamlConfiguration.java @@ -0,0 +1,249 @@ +package org.bukkit.configuration.file; + +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.configuration.Configuration; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.InvalidConfigurationException; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.LoaderOptions; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.error.YAMLException; +import org.yaml.snakeyaml.representer.Representer; + +import java.io.*; +import java.util.Map; +import java.util.logging.Level; + +/** + * An implementation of {@link Configuration} which saves all files in Yaml. + * Note that this implementation is not synchronized. + */ +public class YamlConfiguration extends FileConfiguration { + + protected static final String COMMENT_PREFIX = "# "; + protected static final String BLANK_CONFIG = "{}\n"; + private final DumperOptions yamlOptions = new DumperOptions(); + private final Representer yamlRepresenter = new YamlRepresenter(); + private final Yaml yaml; + + { + new Yaml(new YamlConstructor(), this.yamlRepresenter, this.yamlOptions); + LoaderOptions options = new LoaderOptions(); + options.setMaxAliasesForCollections(500); + yaml = new Yaml(new YamlConstructor(), this.yamlRepresenter, this.yamlOptions, options); + } + + @Override + public String saveToString() { + this.yamlOptions.setIndent(options().indent()); + this.yamlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + this.yamlOptions.setAllowUnicode(SYSTEM_UTF); + this.yamlRepresenter.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + String header = buildHeader(); + String dump = this.yaml.dump(getValues(false)); + if (dump.equals("{}\n")) + dump = ""; + return header + dump; + } + + @Override + public void loadFromString(String contents) throws InvalidConfigurationException { + Validate.notNull(contents, "Contents cannot be null"); + + Map input; + Validate.notNull(contents, "Contents cannot be null"); + try { + input = (Map)this.yaml.load(contents); + } catch (YAMLException e) { + throw new InvalidConfigurationException(e); + } catch (ClassCastException e) { + throw new InvalidConfigurationException("Top level is not a Map."); + } + + String header = parseHeader(contents); + if (header.length() > 0) { + options().header(header); + } + + if (input != null) { + convertMapsToSections(input, this); + } + } + + protected void convertMapsToSections(Map input, ConfigurationSection section) { + for (Map.Entry entry : input.entrySet()) { + String key = entry.getKey().toString(); + Object value = entry.getValue(); + + if (value instanceof Map) { + convertMapsToSections((Map) value, section.createSection(key)); + } else { + section.set(key, value); + } + } + } + + protected String parseHeader(String input) { + String[] lines = input.split("\r?\n", -1); + StringBuilder result = new StringBuilder(); + boolean readingHeader = true; + boolean foundHeader = false; + + for (int i = 0; (i < lines.length) && (readingHeader); i++) { + String line = lines[i]; + + if (line.startsWith(COMMENT_PREFIX)) { + if (i > 0) { + result.append("\n"); + } + + if (line.length() > COMMENT_PREFIX.length()) { + result.append(line.substring(COMMENT_PREFIX.length())); + } + + foundHeader = true; + } else if ((foundHeader) && (line.length() == 0)) { + result.append("\n"); + } else if (foundHeader) { + readingHeader = false; + } + } + + return result.toString(); + } + + @Override + protected String buildHeader() { + String header = options().header(); + + if (options().copyHeader()) { + Configuration def = getDefaults(); + + if (def instanceof FileConfiguration) { + FileConfiguration filedefaults = (FileConfiguration) def; + String defaultsHeader = filedefaults.buildHeader(); + + if ((defaultsHeader != null) && (defaultsHeader.length() > 0)) { + return defaultsHeader; + } + } + } + + if (header == null) { + return ""; + } + + StringBuilder builder = new StringBuilder(); + String[] lines = header.split("\r?\n", -1); + boolean startedHeader = false; + + for (int i = lines.length - 1; i >= 0; i--) { + builder.insert(0, "\n"); + + if ((startedHeader) || (lines[i].length() != 0)) { + builder.insert(0, lines[i]); + builder.insert(0, COMMENT_PREFIX); + startedHeader = true; + } + } + + return builder.toString(); + } + + @Override + public YamlConfigurationOptions options() { + if (options == null) { + options = new YamlConfigurationOptions(this); + } + + return (YamlConfigurationOptions) options; + } + + /** + * Creates a new {@link YamlConfiguration}, loading from the given file. + *

+ * Any errors loading the Configuration will be logged and then ignored. + * If the specified input is not a valid config, a blank config will be + * returned. + *

+ * The encoding used may follow the system dependent default. + * + * @param file Input file + * @return Resulting configuration + * @throws IllegalArgumentException Thrown if file is null + */ + public static YamlConfiguration loadConfiguration(File file) { + Validate.notNull(file, "File cannot be null"); + + YamlConfiguration config = new YamlConfiguration(); + + try { + config.load(file); + } catch (FileNotFoundException ignored) { + } catch (IOException | InvalidConfigurationException ex) { + try { + Bukkit.getLogger().log(Level.SEVERE, "Cannot load " + file, ex); + } catch (Exception e) { // Azurite - Spigot configs are loaded before bukkit logger causing it to error + ex.printStackTrace(); + } + } + + return config; + } + + /** + * Creates a new {@link YamlConfiguration}, loading from the given stream. + *

+ * Any errors loading the Configuration will be logged and then ignored. + * If the specified input is not a valid config, a blank config will be + * returned. + * + * @param stream Input stream + * @return Resulting configuration + * @throws IllegalArgumentException Thrown if stream is null + * @deprecated does not properly consider encoding + * @see #load(InputStream) + * @see #loadConfiguration(Reader) + */ + @Deprecated + public static YamlConfiguration loadConfiguration(InputStream stream) { + Validate.notNull(stream, "Stream cannot be null"); + + YamlConfiguration config = new YamlConfiguration(); + + try { + config.load(stream); + } catch (IOException | InvalidConfigurationException ex) { + Bukkit.getLogger().log(Level.SEVERE, "Cannot load configuration from stream", ex); + } + + return config; + } + + + /** + * Creates a new {@link YamlConfiguration}, loading from the given reader. + *

+ * Any errors loading the Configuration will be logged and then ignored. + * If the specified input is not a valid config, a blank config will be + * returned. + * + * @param reader input + * @return resulting configuration + * @throws IllegalArgumentException Thrown if stream is null + */ + public static YamlConfiguration loadConfiguration(Reader reader) { + Validate.notNull(reader, "Stream cannot be null"); + + YamlConfiguration config = new YamlConfiguration(); + + try { + config.load(reader); + } catch (IOException | InvalidConfigurationException ex) { + Bukkit.getLogger().log(Level.SEVERE, "Cannot load configuration from stream", ex); + } + + return config; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/configuration/file/YamlConfigurationOptions.java b/azurite-api/src/main/java/org/bukkit/configuration/file/YamlConfigurationOptions.java new file mode 100644 index 0000000..57894e3 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/configuration/file/YamlConfigurationOptions.java @@ -0,0 +1,71 @@ +package org.bukkit.configuration.file; + +import org.apache.commons.lang.Validate; + +/** + * Various settings for controlling the input and output of a {@link + * YamlConfiguration} + */ +public class YamlConfigurationOptions extends FileConfigurationOptions { + private int indent = 2; + + protected YamlConfigurationOptions(YamlConfiguration configuration) { + super(configuration); + } + + @Override + public YamlConfiguration configuration() { + return (YamlConfiguration) super.configuration(); + } + + @Override + public YamlConfigurationOptions copyDefaults(boolean value) { + super.copyDefaults(value); + return this; + } + + @Override + public YamlConfigurationOptions pathSeparator(char value) { + super.pathSeparator(value); + return this; + } + + @Override + public YamlConfigurationOptions header(String value) { + super.header(value); + return this; + } + + @Override + public YamlConfigurationOptions copyHeader(boolean value) { + super.copyHeader(value); + return this; + } + + /** + * Gets how much spaces should be used to indent each line. + *

+ * The minimum value this may be is 2, and the maximum is 9. + * + * @return How much to indent by + */ + public int indent() { + return indent; + } + + /** + * Sets how much spaces should be used to indent each line. + *

+ * The minimum value this may be is 2, and the maximum is 9. + * + * @param value New indent + * @return This object, for chaining + */ + public YamlConfigurationOptions indent(int value) { + Validate.isTrue(value >= 2, "Indent must be at least 2 characters"); + Validate.isTrue(value <= 9, "Indent cannot be greater than 9 characters"); + + this.indent = value; + return this; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/configuration/file/YamlConstructor.java b/azurite-api/src/main/java/org/bukkit/configuration/file/YamlConstructor.java new file mode 100644 index 0000000..d85b026 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/configuration/file/YamlConstructor.java @@ -0,0 +1,48 @@ +package org.bukkit.configuration.file; + +import org.bukkit.configuration.serialization.ConfigurationSerialization; +import org.yaml.snakeyaml.constructor.SafeConstructor; +import org.yaml.snakeyaml.error.YAMLException; +import org.yaml.snakeyaml.nodes.Node; +import org.yaml.snakeyaml.nodes.Tag; + +import java.util.LinkedHashMap; +import java.util.Map; + +public class YamlConstructor extends SafeConstructor { + + public YamlConstructor() { + this.yamlConstructors.put(Tag.MAP, new ConstructCustomObject()); + } + + private class ConstructCustomObject extends ConstructYamlMap { + @Override + public Object construct(Node node) { + if (node.isTwoStepsConstruction()) { + throw new YAMLException("Unexpected referential mapping structure. Node: " + node); + } + + Map raw = (Map) super.construct(node); + + if (raw.containsKey(ConfigurationSerialization.SERIALIZED_TYPE_KEY)) { + Map typed = new LinkedHashMap(raw.size()); + for (Map.Entry entry : raw.entrySet()) { + typed.put(entry.getKey().toString(), entry.getValue()); + } + + try { + return ConfigurationSerialization.deserializeObject(typed); + } catch (IllegalArgumentException ex) { + throw new YAMLException("Could not deserialize object", ex); + } + } + + return raw; + } + + @Override + public void construct2ndStep(Node node, Object object) { + throw new YAMLException("Unexpected referential mapping structure. Node: " + node); + } + } +} diff --git a/azurite-api/src/main/java/org/bukkit/configuration/file/YamlRepresenter.java b/azurite-api/src/main/java/org/bukkit/configuration/file/YamlRepresenter.java new file mode 100644 index 0000000..5c76766 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/configuration/file/YamlRepresenter.java @@ -0,0 +1,37 @@ +package org.bukkit.configuration.file; + +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.serialization.ConfigurationSerializable; +import org.bukkit.configuration.serialization.ConfigurationSerialization; +import org.yaml.snakeyaml.nodes.Node; +import org.yaml.snakeyaml.representer.Representer; + +import java.util.LinkedHashMap; +import java.util.Map; + +public class YamlRepresenter extends Representer { + + public YamlRepresenter() { + this.multiRepresenters.put(ConfigurationSection.class, new RepresentConfigurationSection()); + this.multiRepresenters.put(ConfigurationSerializable.class, new RepresentConfigurationSerializable()); + } + + private class RepresentConfigurationSection extends RepresentMap { + @Override + public Node representData(Object data) { + return super.representData(((ConfigurationSection) data).getValues(false)); + } + } + + private class RepresentConfigurationSerializable extends RepresentMap { + @Override + public Node representData(Object data) { + ConfigurationSerializable serializable = (ConfigurationSerializable) data; + Map values = new LinkedHashMap<>(); + values.put(ConfigurationSerialization.SERIALIZED_TYPE_KEY, ConfigurationSerialization.getAlias(serializable.getClass())); + values.putAll(serializable.serialize()); + + return super.representData(values); + } + } +} diff --git a/azurite-api/src/main/java/org/bukkit/configuration/serialization/ConfigurationSerializable.java b/azurite-api/src/main/java/org/bukkit/configuration/serialization/ConfigurationSerializable.java new file mode 100644 index 0000000..8f7c893 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/configuration/serialization/ConfigurationSerializable.java @@ -0,0 +1,35 @@ +package org.bukkit.configuration.serialization; + +import java.util.Map; + +/** + * Represents an object that may be serialized. + *

+ * These objects MUST implement one of the following, in addition to the + * methods as defined by this interface: + *

    + *
  • A static method "deserialize" that accepts a single {@link Map}< + * {@link String}, {@link Object}> and returns the class.
  • + *
  • A static method "valueOf" that accepts a single {@link Map}<{@link + * String}, {@link Object}> and returns the class.
  • + *
  • A constructor that accepts a single {@link Map}<{@link String}, + * {@link Object}>.
  • + *
+ * In addition to implementing this interface, you must register the class + * with {@link ConfigurationSerialization#registerClass(Class)}. + * + * @see DelegateDeserialization + * @see SerializableAs + */ +public interface ConfigurationSerializable { + + /** + * Creates a Map representation of this class. + *

+ * This class must provide a method to restore this class, as defined in + * the {@link ConfigurationSerializable} interface javadocs. + * + * @return Map containing the current state of this class + */ + Map serialize(); +} diff --git a/azurite-api/src/main/java/org/bukkit/configuration/serialization/ConfigurationSerialization.java b/azurite-api/src/main/java/org/bukkit/configuration/serialization/ConfigurationSerialization.java new file mode 100644 index 0000000..48e7a5b --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/configuration/serialization/ConfigurationSerialization.java @@ -0,0 +1,280 @@ +package org.bukkit.configuration.serialization; + +import org.apache.commons.lang.Validate; +import org.bukkit.Color; +import org.bukkit.FireworkEffect; +import org.bukkit.Location; +import org.bukkit.block.banner.Pattern; +import org.bukkit.configuration.Configuration; +import org.bukkit.inventory.ItemStack; +import org.bukkit.potion.PotionEffect; +import org.bukkit.util.BlockVector; +import org.bukkit.util.Vector; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.HashMap; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * Utility class for storing and retrieving classes for {@link Configuration}. + */ +public class ConfigurationSerialization { + public static final String SERIALIZED_TYPE_KEY = "=="; + private final Class clazz; + private static Map> aliases = new HashMap>(); + + static { + registerClass(Vector.class); + registerClass(BlockVector.class); + registerClass(ItemStack.class); + registerClass(Color.class); + registerClass(PotionEffect.class); + registerClass(FireworkEffect.class); + registerClass(Pattern.class); + registerClass(Location.class); + } + + protected ConfigurationSerialization(Class clazz) { + this.clazz = clazz; + } + + protected Method getMethod(String name, boolean isStatic) { + try { + Method method = clazz.getDeclaredMethod(name, Map.class); + + if (!ConfigurationSerializable.class.isAssignableFrom(method.getReturnType())) { + return null; + } + if (Modifier.isStatic(method.getModifiers()) != isStatic) { + return null; + } + + return method; + } catch (NoSuchMethodException | SecurityException ex) { + return null; + } + } + + protected Constructor getConstructor() { + try { + return clazz.getConstructor(Map.class); + } catch (NoSuchMethodException | SecurityException ex) { + return null; + } + } + + protected ConfigurationSerializable deserializeViaMethod(Method method, Map args) { + try { + ConfigurationSerializable result = (ConfigurationSerializable) method.invoke(null, args); + + if (result == null) { + Logger.getLogger(ConfigurationSerialization.class.getName()).log(Level.SEVERE, "Could not call method '" + method.toString() + "' of " + clazz + " for deserialization: method returned null"); + } else { + return result; + } + } catch (Throwable ex) { + Logger.getLogger(ConfigurationSerialization.class.getName()).log( + Level.SEVERE, + "Could not call method '" + method.toString() + "' of " + clazz + " for deserialization", + ex instanceof InvocationTargetException ? ex.getCause() : ex); + } + + return null; + } + + protected ConfigurationSerializable deserializeViaCtor(Constructor ctor, Map args) { + try { + return ctor.newInstance(args); + } catch (Throwable ex) { + Logger.getLogger(ConfigurationSerialization.class.getName()).log( + Level.SEVERE, + "Could not call constructor '" + ctor.toString() + "' of " + clazz + " for deserialization", + ex instanceof InvocationTargetException ? ex.getCause() : ex); + } + + return null; + } + + public ConfigurationSerializable deserialize(Map args) { + Validate.notNull(args, "Args must not be null"); + + ConfigurationSerializable result = null; + Method method = null; + + if (result == null) { + method = getMethod("deserialize", true); + + if (method != null) { + result = deserializeViaMethod(method, args); + } + } + + if (result == null) { + method = getMethod("valueOf", true); + + if (method != null) { + result = deserializeViaMethod(method, args); + } + } + + if (result == null) { + Constructor constructor = getConstructor(); + + if (constructor != null) { + result = deserializeViaCtor(constructor, args); + } + } + + return result; + } + + /** + * Attempts to deserialize the given arguments into a new instance of the + * given class. + *

+ * The class must implement {@link ConfigurationSerializable}, including + * the extra methods as specified in the javadoc of + * ConfigurationSerializable. + *

+ * If a new instance could not be made, an example being the class not + * fully implementing the interface, null will be returned. + * + * @param args Arguments for deserialization + * @param clazz Class to deserialize into + * @return New instance of the specified class + */ + public static ConfigurationSerializable deserializeObject(Map args, Class clazz) { + return new ConfigurationSerialization(clazz).deserialize(args); + } + + /** + * Attempts to deserialize the given arguments into a new instance of the + * given class. + *

+ * The class must implement {@link ConfigurationSerializable}, including + * the extra methods as specified in the javadoc of + * ConfigurationSerializable. + *

+ * If a new instance could not be made, an example being the class not + * fully implementing the interface, null will be returned. + * + * @param args Arguments for deserialization + * @return New instance of the specified class + */ + public static ConfigurationSerializable deserializeObject(Map args) { + Class clazz = null; + + if (args.containsKey(SERIALIZED_TYPE_KEY)) { + try { + String alias = (String) args.get(SERIALIZED_TYPE_KEY); + + if (alias == null) { + throw new IllegalArgumentException("Cannot have null alias"); + } + clazz = getClassByAlias(alias); + if (clazz == null) { + throw new IllegalArgumentException("Specified class does not exist ('" + alias + "')"); + } + } catch (ClassCastException ex) { + ex.fillInStackTrace(); + throw ex; + } + } else { + throw new IllegalArgumentException("Args doesn't contain type key ('" + SERIALIZED_TYPE_KEY + "')"); + } + + return new ConfigurationSerialization(clazz).deserialize(args); + } + + /** + * Registers the given {@link ConfigurationSerializable} class by its + * alias + * + * @param clazz Class to register + */ + public static void registerClass(Class clazz) { + DelegateDeserialization delegate = clazz.getAnnotation(DelegateDeserialization.class); + + if (delegate == null) { + registerClass(clazz, getAlias(clazz)); + registerClass(clazz, clazz.getName()); + } + } + + /** + * Registers the given alias to the specified {@link + * ConfigurationSerializable} class + * + * @param clazz Class to register + * @param alias Alias to register as + * @see SerializableAs + */ + public static void registerClass(Class clazz, String alias) { + aliases.put(alias, clazz); + } + + /** + * Unregisters the specified alias to a {@link ConfigurationSerializable} + * + * @param alias Alias to unregister + */ + public static void unregisterClass(String alias) { + aliases.remove(alias); + } + + /** + * Unregisters any aliases for the specified {@link + * ConfigurationSerializable} class + * + * @param clazz Class to unregister + */ + public static void unregisterClass(Class clazz) { + while (aliases.values().remove(clazz)) { + } + } + + /** + * Attempts to get a registered {@link ConfigurationSerializable} class by + * its alias + * + * @param alias Alias of the serializable + * @return Registered class, or null if not found + */ + public static Class getClassByAlias(String alias) { + return aliases.get(alias); + } + + /** + * Gets the correct alias for the given {@link ConfigurationSerializable} + * class + * + * @param clazz Class to get alias for + * @return Alias to use for the class + */ + public static String getAlias(Class clazz) { + DelegateDeserialization delegate = clazz.getAnnotation(DelegateDeserialization.class); + + if (delegate != null) { + if ((delegate.value() == null) || (delegate.value() == clazz)) { + delegate = null; + } else { + return getAlias(delegate.value()); + } + } + + if (delegate == null) { + SerializableAs alias = clazz.getAnnotation(SerializableAs.class); + + if ((alias != null) && (alias.value() != null)) { + return alias.value(); + } + } + + return clazz.getName(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/configuration/serialization/DelegateDeserialization.java b/azurite-api/src/main/java/org/bukkit/configuration/serialization/DelegateDeserialization.java new file mode 100644 index 0000000..559ca0a --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/configuration/serialization/DelegateDeserialization.java @@ -0,0 +1,22 @@ +package org.bukkit.configuration.serialization; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Applies to a {@link ConfigurationSerializable} that will delegate all + * deserialization to another {@link ConfigurationSerializable}. + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface DelegateDeserialization { + /** + * Which class should be used as a delegate for this classes + * deserialization + * + * @return Delegate class + */ + Class value(); +} diff --git a/azurite-api/src/main/java/org/bukkit/configuration/serialization/SerializableAs.java b/azurite-api/src/main/java/org/bukkit/configuration/serialization/SerializableAs.java new file mode 100644 index 0000000..721d426 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/configuration/serialization/SerializableAs.java @@ -0,0 +1,34 @@ +package org.bukkit.configuration.serialization; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Represents an "alias" that a {@link ConfigurationSerializable} may be + * stored as. + * If this is not present on a {@link ConfigurationSerializable} class, it + * will use the fully qualified name of the class. + *

+ * This value will be stored in the configuration so that the configuration + * deserialization can determine what type it is. + *

+ * Using this annotation on any other class than a {@link + * ConfigurationSerializable} will have no effect. + * + * @see ConfigurationSerialization#registerClass(Class, String) + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface SerializableAs { + /** + * This is the name your class will be stored and retrieved as. + *

+ * This name MUST be unique. We recommend using names such as + * "MyPluginThing" instead of "Thing". + * + * @return Name to serialize the class as. + */ + String value(); +} diff --git a/azurite-api/src/main/java/org/bukkit/conversations/BooleanPrompt.java b/azurite-api/src/main/java/org/bukkit/conversations/BooleanPrompt.java new file mode 100644 index 0000000..81ef78c --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/conversations/BooleanPrompt.java @@ -0,0 +1,37 @@ +package org.bukkit.conversations; + +import org.apache.commons.lang.ArrayUtils; +import org.apache.commons.lang.BooleanUtils; + +/** + * BooleanPrompt is the base class for any prompt that requires a boolean + * response from the user. + */ +public abstract class BooleanPrompt extends ValidatingPrompt{ + + public BooleanPrompt() { + super(); + } + + @Override + protected boolean isInputValid(ConversationContext context, String input) { + String[] accepted = {"true", "false", "on", "off", "yes", "no" /* Spigot: */, "y", "n", "1", "0", "right", "wrong", "correct", "incorrect", "valid", "invalid"}; // Spigot + return ArrayUtils.contains(accepted, input.toLowerCase()); + } + + @Override + protected Prompt acceptValidatedInput(ConversationContext context, String input) { + if (input.equalsIgnoreCase("y") || input.equals("1") || input.equalsIgnoreCase("right") || input.equalsIgnoreCase("correct") || input.equalsIgnoreCase("valid")) input = "true"; // Spigot + return acceptValidatedInput(context, BooleanUtils.toBoolean(input)); + } + + /** + * Override this method to perform some action with the user's boolean + * response. + * + * @param context Context information about the conversation. + * @param input The user's boolean response. + * @return The next {@link Prompt} in the prompt graph. + */ + protected abstract Prompt acceptValidatedInput(ConversationContext context, boolean input); +} diff --git a/azurite-api/src/main/java/org/bukkit/conversations/Conversable.java b/azurite-api/src/main/java/org/bukkit/conversations/Conversable.java new file mode 100644 index 0000000..f86b6d6 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/conversations/Conversable.java @@ -0,0 +1,55 @@ +package org.bukkit.conversations; + +/** + * The Conversable interface is used to indicate objects that can have + * conversations. + */ +public interface Conversable { + + /** + * Tests to see of a Conversable object is actively engaged in a + * conversation. + * + * @return True if a conversation is in progress + */ + boolean isConversing(); + + /** + * Accepts input into the active conversation. If no conversation is in + * progress, this method does nothing. + * + * @param input The input message into the conversation + */ + void acceptConversationInput(String input); + + /** + * Enters into a dialog with a Conversation object. + * + * @param conversation The conversation to begin + * @return True if the conversation should proceed, false if it has been + * enqueued + */ + boolean beginConversation(Conversation conversation); + + /** + * Abandons an active conversation. + * + * @param conversation The conversation to abandon + */ + void abandonConversation(Conversation conversation); + + /** + * Abandons an active conversation. + * + * @param conversation The conversation to abandon + * @param details Details about why the conversation was abandoned + */ + void abandonConversation(Conversation conversation, ConversationAbandonedEvent details); + + /** + * Sends this sender a message raw + * + * @param message Message to be displayed + */ + void sendRawMessage(String message); +} diff --git a/azurite-api/src/main/java/org/bukkit/conversations/Conversation.java b/azurite-api/src/main/java/org/bukkit/conversations/Conversation.java new file mode 100644 index 0000000..46912c8 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/conversations/Conversation.java @@ -0,0 +1,304 @@ +package org.bukkit.conversations; + +import org.bukkit.plugin.Plugin; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * The Conversation class is responsible for tracking the current state of a + * conversation, displaying prompts to the user, and dispatching the user's + * response to the appropriate place. Conversation objects are not typically + * instantiated directly. Instead a {@link ConversationFactory} is used to + * construct identical conversations on demand. + *

+ * Conversation flow consists of a directed graph of {@link Prompt} objects. + * Each time a prompt gets input from the user, it must return the next prompt + * in the graph. Since each Prompt chooses the next Prompt, complex + * conversation trees can be implemented where the nature of the player's + * response directs the flow of the conversation. + *

+ * Each conversation has a {@link ConversationPrefix} that prepends all output + * from the conversation to the player. The ConversationPrefix can be used to + * display the plugin name or conversation status as the conversation evolves. + *

+ * Each conversation has a timeout measured in the number of inactive seconds + * to wait before abandoning the conversation. If the inactivity timeout is + * reached, the conversation is abandoned and the user's incoming and outgoing + * chat is returned to normal. + *

+ * You should not construct a conversation manually. Instead, use the {@link + * ConversationFactory} for access to all available options. + */ +public class Conversation { + + private Prompt firstPrompt; + private boolean abandoned; + protected Prompt currentPrompt; + protected ConversationContext context; + protected boolean modal; + protected boolean localEchoEnabled; + protected ConversationPrefix prefix; + protected List cancellers; + protected List abandonedListeners; + + /** + * Initializes a new Conversation. + * + * @param plugin The plugin that owns this conversation. + * @param forWhom The entity for whom this conversation is mediating. + * @param firstPrompt The first prompt in the conversation graph. + */ + public Conversation(Plugin plugin, Conversable forWhom, Prompt firstPrompt) { + this(plugin, forWhom, firstPrompt, new HashMap()); + } + + /** + * Initializes a new Conversation. + * + * @param plugin The plugin that owns this conversation. + * @param forWhom The entity for whom this conversation is mediating. + * @param firstPrompt The first prompt in the conversation graph. + * @param initialSessionData Any initial values to put in the conversation + * context sessionData map. + */ + public Conversation(Plugin plugin, Conversable forWhom, Prompt firstPrompt, Map initialSessionData) { + this.firstPrompt = firstPrompt; + this.context = new ConversationContext(plugin, forWhom, initialSessionData); + this.modal = true; + this.localEchoEnabled = true; + this.prefix = new NullConversationPrefix(); + this.cancellers = new ArrayList(); + this.abandonedListeners = new ArrayList(); + } + + /** + * Gets the entity for whom this conversation is mediating. + * + * @return The entity. + */ + public Conversable getForWhom() { + return context.getForWhom(); + } + + /** + * Gets the modality of this conversation. If a conversation is modal, all + * messages directed to the player are suppressed for the duration of the + * conversation. + * + * @return The conversation modality. + */ + public boolean isModal() { + return modal; + } + + /** + * Sets the modality of this conversation. If a conversation is modal, + * all messages directed to the player are suppressed for the duration of + * the conversation. + * + * @param modal The new conversation modality. + */ + void setModal(boolean modal) { + this.modal = modal; + } + + /** + * Gets the status of local echo for this conversation. If local echo is + * enabled, any text submitted to a conversation gets echoed back into the + * submitter's chat window. + * + * @return The status of local echo. + */ + public boolean isLocalEchoEnabled() { + return localEchoEnabled; + } + + /** + * Sets the status of local echo for this conversation. If local echo is + * enabled, any text submitted to a conversation gets echoed back into the + * submitter's chat window. + * + * @param localEchoEnabled The status of local echo. + */ + public void setLocalEchoEnabled(boolean localEchoEnabled) { + this.localEchoEnabled = localEchoEnabled; + } + + /** + * Gets the {@link ConversationPrefix} that prepends all output from this + * conversation. + * + * @return The ConversationPrefix in use. + */ + public ConversationPrefix getPrefix() { + return prefix; + } + + /** + * Sets the {@link ConversationPrefix} that prepends all output from this + * conversation. + * + * @param prefix The ConversationPrefix to use. + */ + void setPrefix(ConversationPrefix prefix) { + this.prefix = prefix; + } + + /** + * Adds a {@link ConversationCanceller} to the cancellers collection. + * + * @param canceller The {@link ConversationCanceller} to add. + */ + void addConversationCanceller(ConversationCanceller canceller) { + canceller.setConversation(this); + this.cancellers.add(canceller); + } + + /** + * Gets the list of {@link ConversationCanceller}s + * + * @return The list. + */ + public List getCancellers() { + return cancellers; + } + + /** + * Returns the Conversation's {@link ConversationContext}. + * + * @return The ConversationContext. + */ + public ConversationContext getContext() { + return context; + } + + /** + * Displays the first prompt of this conversation and begins redirecting + * the user's chat responses. + */ + public void begin() { + if (currentPrompt == null) { + abandoned = false; + currentPrompt = firstPrompt; + context.getForWhom().beginConversation(this); + } + } + + /** + * Returns Returns the current state of the conversation. + * + * @return The current state of the conversation. + */ + public ConversationState getState() { + if (currentPrompt != null) { + return ConversationState.STARTED; + } else if (abandoned) { + return ConversationState.ABANDONED; + } else { + return ConversationState.UNSTARTED; + } + } + + /** + * Passes player input into the current prompt. The next prompt (as + * determined by the current prompt) is then displayed to the user. + * + * @param input The user's chat text. + */ + public void acceptInput(String input) { + try { // Spigot + if (currentPrompt != null) { + + // Echo the user's input + if (localEchoEnabled) { + context.getForWhom().sendRawMessage(prefix.getPrefix(context) + input); + } + + // Test for conversation abandonment based on input + for(ConversationCanceller canceller : cancellers) { + if (canceller.cancelBasedOnInput(context, input)) { + abandon(new ConversationAbandonedEvent(this, canceller)); + return; + } + } + + // Not abandoned, output the next prompt + currentPrompt = currentPrompt.acceptInput(context, input); + outputNextPrompt(); + } + // Spigot Start + } catch ( Throwable t ) + { + org.bukkit.Bukkit.getLogger().log( java.util.logging.Level.SEVERE, "Error handling conversation prompt", t ); + } + // Spigot End + } + + /** + * Adds a {@link ConversationAbandonedListener}. + * + * @param listener The listener to add. + */ + public synchronized void addConversationAbandonedListener(ConversationAbandonedListener listener) { + abandonedListeners.add(listener); + } + + /** + * Removes a {@link ConversationAbandonedListener}. + * + * @param listener The listener to remove. + */ + public synchronized void removeConversationAbandonedListener(ConversationAbandonedListener listener) { + abandonedListeners.remove(listener); + } + + /** + * Abandons and resets the current conversation. Restores the user's + * normal chat behavior. + */ + public void abandon() { + abandon(new ConversationAbandonedEvent(this, new ManuallyAbandonedConversationCanceller())); + } + + /** + * Abandons and resets the current conversation. Restores the user's + * normal chat behavior. + * + * @param details Details about why the conversation was abandoned + */ + public synchronized void abandon(ConversationAbandonedEvent details) { + if (!abandoned) { + abandoned = true; + currentPrompt = null; + context.getForWhom().abandonConversation(this); + for (ConversationAbandonedListener listener : abandonedListeners) { + listener.conversationAbandoned(details); + } + } + } + + /** + * Displays the next user prompt and abandons the conversation if the next + * prompt is null. + */ + public void outputNextPrompt() { + if (currentPrompt == null) { + abandon(new ConversationAbandonedEvent(this)); + } else { + context.getForWhom().sendRawMessage(prefix.getPrefix(context) + currentPrompt.getPromptText(context)); + if (!currentPrompt.blocksForInput(context)) { + currentPrompt = currentPrompt.acceptInput(context, null); + outputNextPrompt(); + } + } + } + + public enum ConversationState { + UNSTARTED, + STARTED, + ABANDONED + } +} diff --git a/azurite-api/src/main/java/org/bukkit/conversations/ConversationAbandonedEvent.java b/azurite-api/src/main/java/org/bukkit/conversations/ConversationAbandonedEvent.java new file mode 100644 index 0000000..63c4a2a --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/conversations/ConversationAbandonedEvent.java @@ -0,0 +1,53 @@ +package org.bukkit.conversations; + +import java.util.EventObject; + +/** + * ConversationAbandonedEvent contains information about an abandoned + * conversation. + */ +public class ConversationAbandonedEvent extends EventObject { + + private ConversationContext context; + private ConversationCanceller canceller; + + public ConversationAbandonedEvent(Conversation conversation) { + this(conversation, null); + } + + public ConversationAbandonedEvent(Conversation conversation, ConversationCanceller canceller) { + super(conversation); + this.context = conversation.getContext(); + this.canceller = canceller; + } + + /** + * Gets the object that caused the conversation to be abandoned. + * + * @return The object that abandoned the conversation. + */ + public ConversationCanceller getCanceller() { + return canceller; + } + + /** + * Gets the abandoned conversation's conversation context. + * + * @return The abandoned conversation's conversation context. + */ + public ConversationContext getContext() { + return context; + } + + /** + * Indicates how the conversation was abandoned - naturally as part of the + * prompt chain or prematurely via a {@link ConversationCanceller}. + * + * @return True if the conversation is abandoned gracefully by a {@link + * Prompt} returning null or the next prompt. False of the + * conversations is abandoned prematurely by a ConversationCanceller. + */ + public boolean gracefulExit() { + return canceller == null; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/conversations/ConversationAbandonedListener.java b/azurite-api/src/main/java/org/bukkit/conversations/ConversationAbandonedListener.java new file mode 100644 index 0000000..406d48e --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/conversations/ConversationAbandonedListener.java @@ -0,0 +1,15 @@ +package org.bukkit.conversations; + +import java.util.EventListener; + +/** + */ +public interface ConversationAbandonedListener extends EventListener { + /** + * Called whenever a {@link Conversation} is abandoned. + * + * @param abandonedEvent Contains details about the abandoned + * conversation. + */ + void conversationAbandoned(ConversationAbandonedEvent abandonedEvent); +} diff --git a/azurite-api/src/main/java/org/bukkit/conversations/ConversationCanceller.java b/azurite-api/src/main/java/org/bukkit/conversations/ConversationCanceller.java new file mode 100644 index 0000000..946fc88 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/conversations/ConversationCanceller.java @@ -0,0 +1,34 @@ +package org.bukkit.conversations; + +/** + * A ConversationCanceller is a class that cancels an active {@link + * Conversation}. A Conversation can have more than one ConversationCanceller. + */ +public interface ConversationCanceller extends Cloneable { + + /** + * Sets the conversation this ConversationCanceller can optionally cancel. + * + * @param conversation A conversation. + */ + void setConversation(Conversation conversation); + + /** + * Cancels a conversation based on user input. + * + * @param context Context information about the conversation. + * @param input The input text from the user. + * @return True to cancel the conversation, False otherwise. + */ + boolean cancelBasedOnInput(ConversationContext context, String input); + + /** + * Allows the {@link ConversationFactory} to duplicate this + * ConversationCanceller when creating a new {@link Conversation}. + *

+ * Implementing this method should reset any internal object state. + * + * @return A clone. + */ + ConversationCanceller clone(); +} diff --git a/azurite-api/src/main/java/org/bukkit/conversations/ConversationContext.java b/azurite-api/src/main/java/org/bukkit/conversations/ConversationContext.java new file mode 100644 index 0000000..7390a77 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/conversations/ConversationContext.java @@ -0,0 +1,79 @@ +package org.bukkit.conversations; + +import org.bukkit.plugin.Plugin; + +import java.util.Map; + +/** + * A ConversationContext provides continuity between nodes in the prompt graph + * by giving the developer access to the subject of the conversation and a + * generic map for storing values that are shared between all {@link Prompt} + * invocations. + */ +public class ConversationContext { + private Conversable forWhom; + private Map sessionData; + private Plugin plugin; + + /** + * @param plugin The owning plugin. + * @param forWhom The subject of the conversation. + * @param initialSessionData Any initial values to put in the sessionData + * map. + */ + public ConversationContext(Plugin plugin, Conversable forWhom, Map initialSessionData) { + this.plugin = plugin; + this.forWhom = forWhom; + this.sessionData = initialSessionData; + } + + /** + * Gets the plugin that owns this conversation. + * + * @return The owning plugin. + */ + public Plugin getPlugin() { + return plugin; + } + + /** + * Gets the subject of the conversation. + * + * @return The subject of the conversation. + */ + public Conversable getForWhom() { + return forWhom; + } + + /** + * Gets the entire sessionData map. + * @return The full sessionData map. + */ + public Map getAllSessionData() { + return sessionData; + } + + /** + * Gets session data shared between all {@link Prompt} invocations. Use + * this as a way to pass data through each Prompt as the conversation + * develops. + * + * @param key The session data key. + * @return The requested session data. + */ + public Object getSessionData(Object key) { + return sessionData.get(key); + } + + /** + * Sets session data shared between all {@link Prompt} invocations. Use + * this as a way to pass data through each prompt as the conversation + * develops. + * + * @param key The session data key. + * @param value The session data value. + */ + public void setSessionData(Object key, Object value) { + sessionData.put(key, value); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/conversations/ConversationFactory.java b/azurite-api/src/main/java/org/bukkit/conversations/ConversationFactory.java new file mode 100644 index 0000000..e7cbd52 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/conversations/ConversationFactory.java @@ -0,0 +1,228 @@ +package org.bukkit.conversations; + +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * A ConversationFactory is responsible for creating a {@link Conversation} + * from a predefined template. A ConversationFactory is typically created when + * a plugin is instantiated and builds a Conversation each time a user + * initiates a conversation with the plugin. Each Conversation maintains its + * own state and calls back as needed into the plugin. + *

+ * The ConversationFactory implements a fluid API, allowing parameters to be + * set as an extension to the constructor. + */ +public class ConversationFactory { + + protected Plugin plugin; + protected boolean isModal; + protected boolean localEchoEnabled; + protected ConversationPrefix prefix; + protected Prompt firstPrompt; + protected Map initialSessionData; + protected String playerOnlyMessage; + protected List cancellers; + protected List abandonedListeners; + + /** + * Constructs a ConversationFactory. + * + * @param plugin The plugin that owns the factory. + */ + public ConversationFactory(Plugin plugin) + { + this.plugin = plugin; + isModal = true; + localEchoEnabled = true; + prefix = new NullConversationPrefix(); + firstPrompt = Prompt.END_OF_CONVERSATION; + initialSessionData = new HashMap(); + playerOnlyMessage = null; + cancellers = new ArrayList(); + abandonedListeners = new ArrayList(); + } + + /** + * Sets the modality of all {@link Conversation}s created by this factory. + * If a conversation is modal, all messages directed to the player are + * suppressed for the duration of the conversation. + *

+ * The default is True. + * + * @param modal The modality of all conversations to be created. + * @return This object. + */ + public ConversationFactory withModality(boolean modal) + { + isModal = modal; + return this; + } + + /** + * Sets the local echo status for all {@link Conversation}s created by + * this factory. If local echo is enabled, any text submitted to a + * conversation gets echoed back into the submitter's chat window. + * + * @param localEchoEnabled The status of local echo. + * @return This object. + */ + public ConversationFactory withLocalEcho(boolean localEchoEnabled) { + this.localEchoEnabled = localEchoEnabled; + return this; + } + + /** + * Sets the {@link ConversationPrefix} that prepends all output from all + * generated conversations. + *

+ * The default is a {@link NullConversationPrefix}; + * + * @param prefix The ConversationPrefix to use. + * @return This object. + */ + public ConversationFactory withPrefix(ConversationPrefix prefix) { + this.prefix = prefix; + return this; + } + + /** + * Sets the number of inactive seconds to wait before automatically + * abandoning all generated conversations. + *

+ * The default is 600 seconds (5 minutes). + * + * @param timeoutSeconds The number of seconds to wait. + * @return This object. + */ + public ConversationFactory withTimeout(int timeoutSeconds) { + return withConversationCanceller(new InactivityConversationCanceller(plugin, timeoutSeconds)); + } + + /** + * Sets the first prompt to use in all generated conversations. + *

+ * The default is Prompt.END_OF_CONVERSATION. + * + * @param firstPrompt The first prompt. + * @return This object. + */ + public ConversationFactory withFirstPrompt(Prompt firstPrompt) { + this.firstPrompt = firstPrompt; + return this; + } + + /** + * Sets any initial data with which to populate the conversation context + * sessionData map. + * + * @param initialSessionData The conversation context's initial + * sessionData. + * @return This object. + */ + public ConversationFactory withInitialSessionData(Map initialSessionData) { + this.initialSessionData = initialSessionData; + return this; + } + + /** + * Sets the player input that, when received, will immediately terminate + * the conversation. + * + * @param escapeSequence Input to terminate the conversation. + * @return This object. + */ + public ConversationFactory withEscapeSequence(String escapeSequence) { + return withConversationCanceller(new ExactMatchConversationCanceller(escapeSequence)); + } + + + /** + * Adds a {@link ConversationCanceller} to constructed conversations. + * + * @param canceller The {@link ConversationCanceller} to add. + * @return This object. + */ + public ConversationFactory withConversationCanceller(ConversationCanceller canceller) { + cancellers.add(canceller); + return this; + } + + /** + * Prevents this factory from creating a conversation for non-player + * {@link Conversable} objects. + * + * @param playerOnlyMessage The message to return to a non-play in lieu of + * starting a conversation. + * @return This object. + */ + public ConversationFactory thatExcludesNonPlayersWithMessage(String playerOnlyMessage) { + this.playerOnlyMessage = playerOnlyMessage; + return this; + } + + /** + * Adds a {@link ConversationAbandonedListener} to all conversations + * constructed by this factory. + * + * @param listener The listener to add. + * @return This object. + */ + public ConversationFactory addConversationAbandonedListener(ConversationAbandonedListener listener) { + abandonedListeners.add(listener); + return this; + } + + /** + * Constructs a {@link Conversation} in accordance with the defaults set + * for this factory. + * + * @param forWhom The entity for whom the new conversation is mediating. + * @return A new conversation. + */ + public Conversation buildConversation(Conversable forWhom) { + //Abort conversation construction if we aren't supposed to talk to non-players + if (playerOnlyMessage != null && !(forWhom instanceof Player)) { + return new Conversation(plugin, forWhom, new NotPlayerMessagePrompt()); + } + + //Clone any initial session data + Map copiedInitialSessionData = new HashMap(); + copiedInitialSessionData.putAll(initialSessionData); + + //Build and return a conversation + Conversation conversation = new Conversation(plugin, forWhom, firstPrompt, copiedInitialSessionData); + conversation.setModal(isModal); + conversation.setLocalEchoEnabled(localEchoEnabled); + conversation.setPrefix(prefix); + + //Clone the conversation cancellers + for (ConversationCanceller canceller : cancellers) { + conversation.addConversationCanceller(canceller.clone()); + } + + //Add the ConversationAbandonedListeners + for (ConversationAbandonedListener listener : abandonedListeners) { + conversation.addConversationAbandonedListener(listener); + } + + return conversation; + } + + private class NotPlayerMessagePrompt extends MessagePrompt { + + public String getPromptText(ConversationContext context) { + return playerOnlyMessage; + } + + @Override + protected Prompt getNextPrompt(ConversationContext context) { + return Prompt.END_OF_CONVERSATION; + } + } +} diff --git a/azurite-api/src/main/java/org/bukkit/conversations/ConversationPrefix.java b/azurite-api/src/main/java/org/bukkit/conversations/ConversationPrefix.java new file mode 100644 index 0000000..3febfa6 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/conversations/ConversationPrefix.java @@ -0,0 +1,17 @@ +package org.bukkit.conversations; + +/** + * A ConversationPrefix implementation prepends all output from the + * conversation to the player. The ConversationPrefix can be used to display + * the plugin name or conversation status as the conversation evolves. + */ +public interface ConversationPrefix { + + /** + * Gets the prefix to use before each message to the player. + * + * @param context Context information about the conversation. + * @return The prefix text. + */ + String getPrefix(ConversationContext context); +} diff --git a/azurite-api/src/main/java/org/bukkit/conversations/ExactMatchConversationCanceller.java b/azurite-api/src/main/java/org/bukkit/conversations/ExactMatchConversationCanceller.java new file mode 100644 index 0000000..327b9d9 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/conversations/ExactMatchConversationCanceller.java @@ -0,0 +1,29 @@ +package org.bukkit.conversations; + +/** + * An ExactMatchConversationCanceller cancels a conversation if the user + * enters an exact input string + */ +public class ExactMatchConversationCanceller implements ConversationCanceller { + private String escapeSequence; + + /** + * Builds an ExactMatchConversationCanceller. + * + * @param escapeSequence The string that, if entered by the user, will + * cancel the conversation. + */ + public ExactMatchConversationCanceller(String escapeSequence) { + this.escapeSequence = escapeSequence; + } + + public void setConversation(Conversation conversation) {} + + public boolean cancelBasedOnInput(ConversationContext context, String input) { + return input.equals(escapeSequence); + } + + public ConversationCanceller clone() { + return new ExactMatchConversationCanceller(escapeSequence); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/conversations/FixedSetPrompt.java b/azurite-api/src/main/java/org/bukkit/conversations/FixedSetPrompt.java new file mode 100644 index 0000000..b867c11 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/conversations/FixedSetPrompt.java @@ -0,0 +1,46 @@ +package org.bukkit.conversations; + +import org.apache.commons.lang.StringUtils; + +import java.util.Arrays; +import java.util.List; + +/** + * FixedSetPrompt is the base class for any prompt that requires a fixed set + * response from the user. + */ +public abstract class FixedSetPrompt extends ValidatingPrompt { + + protected List fixedSet; + + /** + * Creates a FixedSetPrompt from a set of strings. + *

+ * foo = new FixedSetPrompt("bar", "cheese", "panda"); + * + * @param fixedSet A fixed set of strings, one of which the user must + * type. + */ + public FixedSetPrompt(String... fixedSet) { + super(); + this.fixedSet = Arrays.asList(fixedSet); + } + + private FixedSetPrompt() {} + + @Override + protected boolean isInputValid(ConversationContext context, String input) { + return fixedSet.contains(input); + } + + /** + * Utility function to create a formatted string containing all the + * options declared in the constructor. + * + * @return the options formatted like "[bar, cheese, panda]" if bar, + * cheese, and panda were the options used + */ + protected String formatFixedSet() { + return "[" + StringUtils.join(fixedSet, ", ") + "]"; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/conversations/InactivityConversationCanceller.java b/azurite-api/src/main/java/org/bukkit/conversations/InactivityConversationCanceller.java new file mode 100644 index 0000000..740f1d8 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/conversations/InactivityConversationCanceller.java @@ -0,0 +1,78 @@ +package org.bukkit.conversations; + +import org.bukkit.plugin.Plugin; + +/** + * An InactivityConversationCanceller will cancel a {@link Conversation} after + * a period of inactivity by the user. + */ +public class InactivityConversationCanceller implements ConversationCanceller { + protected Plugin plugin; + protected int timeoutSeconds; + protected Conversation conversation; + private int taskId = -1; + + /** + * Creates an InactivityConversationCanceller. + * + * @param plugin The owning plugin. + * @param timeoutSeconds The number of seconds of inactivity to wait. + */ + public InactivityConversationCanceller(Plugin plugin, int timeoutSeconds) { + this.plugin = plugin; + this.timeoutSeconds = timeoutSeconds; + } + + public void setConversation(Conversation conversation) { + this.conversation = conversation; + startTimer(); + } + + public boolean cancelBasedOnInput(ConversationContext context, String input) { + // Reset the inactivity timer + stopTimer(); + startTimer(); + return false; + } + + public ConversationCanceller clone() { + return new InactivityConversationCanceller(plugin, timeoutSeconds); + } + + /** + * Starts an inactivity timer. + */ + private void startTimer() { + taskId = plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { + public void run() { + if (conversation.getState() == Conversation.ConversationState.UNSTARTED) { + startTimer(); + } else if (conversation.getState() == Conversation.ConversationState.STARTED) { + cancelling(conversation); + conversation.abandon(new ConversationAbandonedEvent(conversation, InactivityConversationCanceller.this)); + } + } + }, timeoutSeconds * 20); + } + + /** + * Stops the active inactivity timer. + */ + private void stopTimer() { + if (taskId != -1) { + plugin.getServer().getScheduler().cancelTask(taskId); + taskId = -1; + } + } + + /** + * Subclasses of InactivityConversationCanceller can override this method + * to take additional actions when the inactivity timer abandons the + * conversation. + * + * @param conversation The conversation being abandoned. + */ + protected void cancelling(Conversation conversation) { + + } +} diff --git a/azurite-api/src/main/java/org/bukkit/conversations/ManuallyAbandonedConversationCanceller.java b/azurite-api/src/main/java/org/bukkit/conversations/ManuallyAbandonedConversationCanceller.java new file mode 100644 index 0000000..3e80de1 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/conversations/ManuallyAbandonedConversationCanceller.java @@ -0,0 +1,20 @@ +package org.bukkit.conversations; + +/** + * The ManuallyAbandonedConversationCanceller is only used as part of a {@link + * ConversationAbandonedEvent} to indicate that the conversation was manually + * abandoned by programmatically calling the abandon() method on it. + */ +public class ManuallyAbandonedConversationCanceller implements ConversationCanceller{ + public void setConversation(Conversation conversation) { + throw new UnsupportedOperationException(); + } + + public boolean cancelBasedOnInput(ConversationContext context, String input) { + throw new UnsupportedOperationException(); + } + + public ConversationCanceller clone() { + throw new UnsupportedOperationException(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/conversations/MessagePrompt.java b/azurite-api/src/main/java/org/bukkit/conversations/MessagePrompt.java new file mode 100644 index 0000000..fa1775a --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/conversations/MessagePrompt.java @@ -0,0 +1,42 @@ +package org.bukkit.conversations; + +/** + * MessagePrompt is the base class for any prompt that only displays a message + * to the user and requires no input. + */ +public abstract class MessagePrompt implements Prompt{ + + public MessagePrompt() { + super(); + } + + /** + * Message prompts never wait for user input before continuing. + * + * @param context Context information about the conversation. + * @return Always false. + */ + public boolean blocksForInput(ConversationContext context) { + return false; + } + + /** + * Accepts and ignores any user input, returning the next prompt in the + * prompt graph instead. + * + * @param context Context information about the conversation. + * @param input Ignored. + * @return The next prompt in the prompt graph. + */ + public Prompt acceptInput(ConversationContext context, String input) { + return getNextPrompt(context); + } + + /** + * Override this method to return the next prompt in the prompt graph. + * + * @param context Context information about the conversation. + * @return The next prompt in the prompt graph. + */ + protected abstract Prompt getNextPrompt(ConversationContext context); +} diff --git a/azurite-api/src/main/java/org/bukkit/conversations/NullConversationPrefix.java b/azurite-api/src/main/java/org/bukkit/conversations/NullConversationPrefix.java new file mode 100644 index 0000000..a462112 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/conversations/NullConversationPrefix.java @@ -0,0 +1,18 @@ +package org.bukkit.conversations; + +/** + * NullConversationPrefix is a {@link ConversationPrefix} implementation that + * displays nothing in front of conversation output. + */ +public class NullConversationPrefix implements ConversationPrefix{ + + /** + * Prepends each conversation message with an empty string. + * + * @param context Context information about the conversation. + * @return An empty string. + */ + public String getPrefix(ConversationContext context) { + return ""; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/conversations/NumericPrompt.java b/azurite-api/src/main/java/org/bukkit/conversations/NumericPrompt.java new file mode 100644 index 0000000..f0fdea1 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/conversations/NumericPrompt.java @@ -0,0 +1,83 @@ +package org.bukkit.conversations; + +import org.apache.commons.lang.math.NumberUtils; + +/** + * NumericPrompt is the base class for any prompt that requires a {@link + * Number} response from the user. + */ +public abstract class NumericPrompt extends ValidatingPrompt{ + public NumericPrompt() { + super(); + } + + @Override + protected boolean isInputValid(ConversationContext context, String input) { + return NumberUtils.isNumber(input) && isNumberValid(context, NumberUtils.createNumber(input)); + } + + /** + * Override this method to do further validation on the numeric player + * input after the input has been determined to actually be a number. + * + * @param context Context information about the conversation. + * @param input The number the player provided. + * @return The validity of the player's input. + */ + protected boolean isNumberValid(ConversationContext context, Number input) { + return true; + } + + @Override + protected Prompt acceptValidatedInput(ConversationContext context, String input) { + try + { + return acceptValidatedInput(context, NumberUtils.createNumber(input)); + } catch (NumberFormatException e) { + return acceptValidatedInput(context, NumberUtils.INTEGER_ZERO); + } + } + + /** + * Override this method to perform some action with the user's integer + * response. + * + * @param context Context information about the conversation. + * @param input The user's response as a {@link Number}. + * @return The next {@link Prompt} in the prompt graph. + */ + protected abstract Prompt acceptValidatedInput(ConversationContext context, Number input); + + @Override + protected String getFailedValidationText(ConversationContext context, String invalidInput) { + if (NumberUtils.isNumber(invalidInput)) { + return getFailedValidationText(context, NumberUtils.createNumber(invalidInput)); + } else { + return getInputNotNumericText(context, invalidInput); + } + } + + /** + * Optionally override this method to display an additional message if the + * user enters an invalid number. + * + * @param context Context information about the conversation. + * @param invalidInput The invalid input provided by the user. + * @return A message explaining how to correct the input. + */ + protected String getInputNotNumericText(ConversationContext context, String invalidInput) { + return null; + } + + /** + * Optionally override this method to display an additional message if the + * user enters an invalid numeric input. + * + * @param context Context information about the conversation. + * @param invalidInput The invalid input provided by the user. + * @return A message explaining how to correct the input. + */ + protected String getFailedValidationText(ConversationContext context, Number invalidInput) { + return null; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/conversations/PlayerNamePrompt.java b/azurite-api/src/main/java/org/bukkit/conversations/PlayerNamePrompt.java new file mode 100644 index 0000000..feeb715 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/conversations/PlayerNamePrompt.java @@ -0,0 +1,38 @@ +package org.bukkit.conversations; + +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; + +/** + * PlayerNamePrompt is the base class for any prompt that requires the player + * to enter another player's name. + */ +public abstract class PlayerNamePrompt extends ValidatingPrompt{ + private Plugin plugin; + + public PlayerNamePrompt(Plugin plugin) { + super(); + this.plugin = plugin; + } + + @Override + protected boolean isInputValid(ConversationContext context, String input) { + return plugin.getServer().getPlayer(input) != null; + + } + + @Override + protected Prompt acceptValidatedInput(ConversationContext context, String input) { + return acceptValidatedInput(context, plugin.getServer().getPlayer(input)); + } + + /** + * Override this method to perform some action with the user's player name + * response. + * + * @param context Context information about the conversation. + * @param input The user's player name response. + * @return The next {@link Prompt} in the prompt graph. + */ + protected abstract Prompt acceptValidatedInput(ConversationContext context, Player input); +} diff --git a/azurite-api/src/main/java/org/bukkit/conversations/PluginNameConversationPrefix.java b/azurite-api/src/main/java/org/bukkit/conversations/PluginNameConversationPrefix.java new file mode 100644 index 0000000..dcb7e24 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/conversations/PluginNameConversationPrefix.java @@ -0,0 +1,39 @@ +package org.bukkit.conversations; + +import org.bukkit.ChatColor; +import org.bukkit.plugin.Plugin; + +/** + * PluginNameConversationPrefix is a {@link ConversationPrefix} implementation + * that displays the plugin name in front of conversation output. + */ +public class PluginNameConversationPrefix implements ConversationPrefix { + + protected String separator; + protected ChatColor prefixColor; + protected Plugin plugin; + + private String cachedPrefix; + + public PluginNameConversationPrefix(Plugin plugin) { + this(plugin, " > ", ChatColor.LIGHT_PURPLE); + } + + public PluginNameConversationPrefix(Plugin plugin, String separator, ChatColor prefixColor) { + this.separator = separator; + this.prefixColor = prefixColor; + this.plugin = plugin; + + cachedPrefix = prefixColor + plugin.getDescription().getName() + separator + ChatColor.WHITE; + } + + /** + * Prepends each conversation message with the plugin name. + * + * @param context Context information about the conversation. + * @return An empty string. + */ + public String getPrefix(ConversationContext context) { + return cachedPrefix; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/conversations/Prompt.java b/azurite-api/src/main/java/org/bukkit/conversations/Prompt.java new file mode 100644 index 0000000..2b1dafe --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/conversations/Prompt.java @@ -0,0 +1,45 @@ +package org.bukkit.conversations; + +/** + * A Prompt is the main constituent of a {@link Conversation}. Each prompt + * displays text to the user and optionally waits for a user's response. + * Prompts are chained together into a directed graph that represents the + * conversation flow. To halt a conversation, END_OF_CONVERSATION is returned + * in liu of another Prompt object. + */ +public interface Prompt extends Cloneable { + + /** + * A convenience constant for indicating the end of a conversation. + */ + Prompt END_OF_CONVERSATION = null; + + /** + * Gets the text to display to the user when this prompt is first + * presented. + * + * @param context Context information about the conversation. + * @return The text to display. + */ + String getPromptText(ConversationContext context); + + /** + * Checks to see if this prompt implementation should wait for user input + * or immediately display the next prompt. + * + * @param context Context information about the conversation. + * @return If true, the {@link Conversation} will wait for input before + * continuing. + */ + boolean blocksForInput(ConversationContext context); + + /** + * Accepts and processes input from the user. Using the input, the next + * Prompt in the prompt graph is returned. + * + * @param context Context information about the conversation. + * @param input The input text from the user. + * @return The next Prompt in the prompt graph. + */ + Prompt acceptInput(ConversationContext context, String input); +} diff --git a/azurite-api/src/main/java/org/bukkit/conversations/RegexPrompt.java b/azurite-api/src/main/java/org/bukkit/conversations/RegexPrompt.java new file mode 100644 index 0000000..a3c7d1f --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/conversations/RegexPrompt.java @@ -0,0 +1,28 @@ +package org.bukkit.conversations; + +import java.util.regex.Pattern; + +/** + * RegexPrompt is the base class for any prompt that requires an input + * validated by a regular expression. + */ +public abstract class RegexPrompt extends ValidatingPrompt { + + private Pattern pattern; + + public RegexPrompt(String regex) { + this(Pattern.compile(regex)); + } + + public RegexPrompt(Pattern pattern) { + super(); + this.pattern = pattern; + } + + private RegexPrompt() {} + + @Override + protected boolean isInputValid(ConversationContext context, String input) { + return pattern.matcher(input).matches(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/conversations/StringPrompt.java b/azurite-api/src/main/java/org/bukkit/conversations/StringPrompt.java new file mode 100644 index 0000000..2934459 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/conversations/StringPrompt.java @@ -0,0 +1,18 @@ +package org.bukkit.conversations; + +/** + * StringPrompt is the base class for any prompt that accepts an arbitrary + * string from the user. + */ +public abstract class StringPrompt implements Prompt{ + + /** + * Ensures that the prompt waits for the user to provide input. + * + * @param context Context information about the conversation. + * @return True. + */ + public boolean blocksForInput(ConversationContext context) { + return true; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/conversations/ValidatingPrompt.java b/azurite-api/src/main/java/org/bukkit/conversations/ValidatingPrompt.java new file mode 100644 index 0000000..f41adb4 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/conversations/ValidatingPrompt.java @@ -0,0 +1,78 @@ +package org.bukkit.conversations; + +import org.bukkit.ChatColor; + +/** + * ValidatingPrompt is the base class for any prompt that requires validation. + * ValidatingPrompt will keep replaying the prompt text until the user enters + * a valid response. + */ +public abstract class ValidatingPrompt implements Prompt { + public ValidatingPrompt() { + super(); + } + + /** + * Accepts and processes input from the user and validates it. If + * validation fails, this prompt is returned for re-execution, otherwise + * the next Prompt in the prompt graph is returned. + * + * @param context Context information about the conversation. + * @param input The input text from the user. + * @return This prompt or the next Prompt in the prompt graph. + */ + public Prompt acceptInput(ConversationContext context, String input) { + if (isInputValid(context, input)) { + return acceptValidatedInput(context, input); + } else { + String failPrompt = getFailedValidationText(context, input); + if (failPrompt != null) { + context.getForWhom().sendRawMessage(ChatColor.RED + failPrompt); + } + // Redisplay this prompt to the user to re-collect input + return this; + } + } + + /** + * Ensures that the prompt waits for the user to provide input. + * + * @param context Context information about the conversation. + * @return True. + */ + public boolean blocksForInput(ConversationContext context) { + return true; + } + + /** + * Override this method to check the validity of the player's input. + * + * @param context Context information about the conversation. + * @param input The player's raw console input. + * @return True or false depending on the validity of the input. + */ + protected abstract boolean isInputValid(ConversationContext context, String input); + + /** + * Override this method to accept and processes the validated input from + * the user. Using the input, the next Prompt in the prompt graph should + * be returned. + * + * @param context Context information about the conversation. + * @param input The validated input text from the user. + * @return The next Prompt in the prompt graph. + */ + protected abstract Prompt acceptValidatedInput(ConversationContext context, String input); + + /** + * Optionally override this method to display an additional message if the + * user enters an invalid input. + * + * @param context Context information about the conversation. + * @param invalidInput The invalid input provided by the user. + * @return A message explaining how to correct the input. + */ + protected String getFailedValidationText(ConversationContext context, String invalidInput) { + return null; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/enchantments/Enchantment.java b/azurite-api/src/main/java/org/bukkit/enchantments/Enchantment.java new file mode 100644 index 0000000..e55e0c7 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/enchantments/Enchantment.java @@ -0,0 +1,297 @@ +package org.bukkit.enchantments; + +import org.bukkit.command.defaults.EnchantCommand; +import org.bukkit.inventory.ItemStack; + +import java.util.HashMap; +import java.util.Map; + +/** + * The various type of enchantments that may be added to armour or weapons + */ +public abstract class Enchantment { + /** + * Provides protection against environmental damage + */ + public static final Enchantment PROTECTION_ENVIRONMENTAL = new EnchantmentWrapper(0); + + /** + * Provides protection against fire damage + */ + public static final Enchantment PROTECTION_FIRE = new EnchantmentWrapper(1); + + /** + * Provides protection against fall damage + */ + public static final Enchantment PROTECTION_FALL = new EnchantmentWrapper(2); + + /** + * Provides protection against explosive damage + */ + public static final Enchantment PROTECTION_EXPLOSIONS = new EnchantmentWrapper(3); + + /** + * Provides protection against projectile damage + */ + public static final Enchantment PROTECTION_PROJECTILE = new EnchantmentWrapper(4); + + /** + * Decreases the rate of air loss whilst underwater + */ + public static final Enchantment OXYGEN = new EnchantmentWrapper(5); + + /** + * Increases the speed at which a player may mine underwater + */ + public static final Enchantment WATER_WORKER = new EnchantmentWrapper(6); + + /** + * Damages the attacker + */ + public static final Enchantment THORNS = new EnchantmentWrapper(7); + + /** + * Increases walking speed while in water + */ + public static final Enchantment DEPTH_STRIDER = new EnchantmentWrapper(8); + + /** + * Increases damage against all targets + */ + public static final Enchantment DAMAGE_ALL = new EnchantmentWrapper(16); + + /** + * Increases damage against undead targets + */ + public static final Enchantment DAMAGE_UNDEAD = new EnchantmentWrapper(17); + + /** + * Increases damage against arthropod targets + */ + public static final Enchantment DAMAGE_ARTHROPODS = new EnchantmentWrapper(18); + + /** + * All damage to other targets will knock them back when hit + */ + public static final Enchantment KNOCKBACK = new EnchantmentWrapper(19); + + /** + * When attacking a target, has a chance to set them on fire + */ + public static final Enchantment FIRE_ASPECT = new EnchantmentWrapper(20); + + /** + * Provides a chance of gaining extra loot when killing monsters + */ + public static final Enchantment LOOT_BONUS_MOBS = new EnchantmentWrapper(21); + + /** + * Increases the rate at which you mine/dig + */ + public static final Enchantment DIG_SPEED = new EnchantmentWrapper(32); + + /** + * Allows blocks to drop themselves instead of fragments (for example, + * stone instead of cobblestone) + */ + public static final Enchantment SILK_TOUCH = new EnchantmentWrapper(33); + + /** + * Decreases the rate at which a tool looses durability + */ + public static final Enchantment DURABILITY = new EnchantmentWrapper(34); + + /** + * Provides a chance of gaining extra loot when destroying blocks + */ + public static final Enchantment LOOT_BONUS_BLOCKS = new EnchantmentWrapper(35); + + /** + * Provides extra damage when shooting arrows from bows + */ + public static final Enchantment ARROW_DAMAGE = new EnchantmentWrapper(48); + + /** + * Provides a knockback when an entity is hit by an arrow from a bow + */ + public static final Enchantment ARROW_KNOCKBACK = new EnchantmentWrapper(49); + + /** + * Sets entities on fire when hit by arrows shot from a bow + */ + public static final Enchantment ARROW_FIRE = new EnchantmentWrapper(50); + + /** + * Provides infinite arrows when shooting a bow + */ + public static final Enchantment ARROW_INFINITE = new EnchantmentWrapper(51); + + /** + * Decreases odds of catching worthless junk + */ + public static final Enchantment LUCK = new EnchantmentWrapper(61); + + /** + * Increases rate of fish biting your hook + */ + public static final Enchantment LURE = new EnchantmentWrapper(62); + + private static final Map byId = new HashMap(); + private static final Map byName = new HashMap(); + private static boolean acceptingNew = true; + private final int id; + + public Enchantment(int id) { + this.id = id; + } + + /** + * Gets the unique ID of this enchantment + * + * @return Unique ID + * @deprecated Magic value + */ + @Deprecated + public int getId() { + return id; + } + + /** + * Gets the unique name of this enchantment + * + * @return Unique name + */ + public abstract String getName(); + + /** + * Gets the maximum level that this Enchantment may become. + * + * @return Maximum level of the Enchantment + */ + public abstract int getMaxLevel(); + + /** + * Gets the level that this Enchantment should start at + * + * @return Starting level of the Enchantment + */ + public abstract int getStartLevel(); + + /** + * Gets the type of {@link ItemStack} that may fit this Enchantment. + * + * @return Target type of the Enchantment + */ + public abstract EnchantmentTarget getItemTarget(); + + /** + * Check if this enchantment conflicts with another enchantment. + * + * @param other The enchantment to check against + * @return True if there is a conflict. + */ + public abstract boolean conflictsWith(Enchantment other); + + /** + * Checks if this Enchantment may be applied to the given {@link + * ItemStack}. + *

+ * This does not check if it conflicts with any enchantments already + * applied to the item. + * + * @param item Item to test + * @return True if the enchantment may be applied, otherwise False + */ + public abstract boolean canEnchantItem(ItemStack item); + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (!(obj instanceof Enchantment)) { + return false; + } + final Enchantment other = (Enchantment) obj; + if (this.id != other.id) { + return false; + } + return true; + } + + @Override + public int hashCode() { + return id; + } + + @Override + public String toString() { + return "Enchantment[" + id + ", " + getName() + "]"; + } + + /** + * Registers an enchantment with the given ID and object. + *

+ * Generally not to be used from within a plugin. + * + * @param enchantment Enchantment to register + */ + public static void registerEnchantment(Enchantment enchantment) { + if (byId.containsKey(enchantment.id) || byName.containsKey(enchantment.getName())) { + throw new IllegalArgumentException("Cannot set already-set enchantment"); + } else if (!isAcceptingRegistrations()) { + throw new IllegalStateException("No longer accepting new enchantments (can only be done by the server implementation)"); + } + + byId.put(enchantment.id, enchantment); + byName.put(enchantment.getName(), enchantment); + } + + /** + * Checks if this is accepting Enchantment registrations. + * + * @return True if the server Implementation may add enchantments + */ + public static boolean isAcceptingRegistrations() { + return acceptingNew; + } + + /** + * Stops accepting any enchantment registrations + */ + public static void stopAcceptingRegistrations() { + acceptingNew = false; + EnchantCommand.buildEnchantments(); + } + + /** + * Gets the Enchantment at the specified ID + * + * @param id ID to fetch + * @return Resulting Enchantment, or null if not found + * @deprecated Magic value + */ + @Deprecated + public static Enchantment getById(int id) { + return byId.get(id); + } + + /** + * Gets the Enchantment at the specified name + * + * @param name Name to fetch + * @return Resulting Enchantment, or null if not found + */ + public static Enchantment getByName(String name) { + return byName.get(name); + } + + /** + * Gets an array of all the registered {@link Enchantment}s + * + * @return Array of enchantments + */ + public static Enchantment[] values() { + return byId.values().toArray(new Enchantment[byId.size()]); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/enchantments/EnchantmentTarget.java b/azurite-api/src/main/java/org/bukkit/enchantments/EnchantmentTarget.java new file mode 100644 index 0000000..d9b98ed --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/enchantments/EnchantmentTarget.java @@ -0,0 +1,172 @@ +package org.bukkit.enchantments; + +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +/** + * Represents the applicable target for a {@link Enchantment} + */ +public enum EnchantmentTarget { + /** + * Allows the Enchantment to be placed on all items + */ + ALL { + @Override + public boolean includes(Material item) { + return true; + } + }, + + /** + * Allows the Enchantment to be placed on armor + */ + ARMOR { + @Override + public boolean includes(Material item) { + return ARMOR_FEET.includes(item) + || ARMOR_LEGS.includes(item) + || ARMOR_HEAD.includes(item) + || ARMOR_TORSO.includes(item); + } + }, + + /** + * Allows the Enchantment to be placed on feet slot armor + */ + ARMOR_FEET { + @Override + public boolean includes(Material item) { + return item.equals(Material.LEATHER_BOOTS) + || item.equals(Material.CHAINMAIL_BOOTS) + || item.equals(Material.IRON_BOOTS) + || item.equals(Material.DIAMOND_BOOTS) + || item.equals(Material.GOLD_BOOTS); + } + }, + + /** + * Allows the Enchantment to be placed on leg slot armor + */ + ARMOR_LEGS { + @Override + public boolean includes(Material item) { + return item.equals(Material.LEATHER_LEGGINGS) + || item.equals(Material.CHAINMAIL_LEGGINGS) + || item.equals(Material.IRON_LEGGINGS) + || item.equals(Material.DIAMOND_LEGGINGS) + || item.equals(Material.GOLD_LEGGINGS); + } + }, + + /** + * Allows the Enchantment to be placed on torso slot armor + */ + ARMOR_TORSO { + @Override + public boolean includes(Material item) { + return item.equals(Material.LEATHER_CHESTPLATE) + || item.equals(Material.CHAINMAIL_CHESTPLATE) + || item.equals(Material.IRON_CHESTPLATE) + || item.equals(Material.DIAMOND_CHESTPLATE) + || item.equals(Material.GOLD_CHESTPLATE); + } + }, + + /** + * Allows the Enchantment to be placed on head slot armor + */ + ARMOR_HEAD { + @Override + public boolean includes(Material item) { + return item.equals(Material.LEATHER_HELMET) + || item.equals(Material.CHAINMAIL_HELMET) + || item.equals(Material.DIAMOND_HELMET) + || item.equals(Material.IRON_HELMET) + || item.equals(Material.GOLD_HELMET); + } + }, + + /** + * Allows the Enchantment to be placed on weapons (swords) + */ + WEAPON { + @Override + public boolean includes(Material item) { + return item.equals(Material.WOOD_SWORD) + || item.equals(Material.STONE_SWORD) + || item.equals(Material.IRON_SWORD) + || item.equals(Material.DIAMOND_SWORD) + || item.equals(Material.GOLD_SWORD); + } + }, + + /** + * Allows the Enchantment to be placed on tools (spades, pickaxe, hoes, + * axes) + */ + TOOL { + @Override + public boolean includes(Material item) { + return item.equals(Material.WOOD_SPADE) + || item.equals(Material.STONE_SPADE) + || item.equals(Material.IRON_SPADE) + || item.equals(Material.DIAMOND_SPADE) + || item.equals(Material.GOLD_SPADE) + || item.equals(Material.WOOD_PICKAXE) + || item.equals(Material.STONE_PICKAXE) + || item.equals(Material.IRON_PICKAXE) + || item.equals(Material.DIAMOND_PICKAXE) + || item.equals(Material.GOLD_PICKAXE) + || item.equals(Material.WOOD_HOE) // NOTE: No vanilla enchantments for this + || item.equals(Material.STONE_HOE) // NOTE: No vanilla enchantments for this + || item.equals(Material.IRON_HOE) // NOTE: No vanilla enchantments for this + || item.equals(Material.DIAMOND_HOE) // NOTE: No vanilla enchantments for this + || item.equals(Material.GOLD_HOE) // NOTE: No vanilla enchantments for this + || item.equals(Material.WOOD_AXE) + || item.equals(Material.STONE_AXE) + || item.equals(Material.IRON_AXE) + || item.equals(Material.DIAMOND_AXE) + || item.equals(Material.GOLD_AXE) + || item.equals(Material.SHEARS) // NOTE: No vanilla enchantments for this + || item.equals(Material.FLINT_AND_STEEL); // NOTE: No vanilla enchantments for this + } + }, + + /** + * Allows the Enchantment to be placed on bows. + */ + BOW { + @Override + public boolean includes(Material item) { + return item.equals(Material.BOW); + } + }, + + /** + * Allows the Enchantment to be placed on fishing rods. + */ + FISHING_ROD { + @Override + public boolean includes(Material item) { + return item.equals(Material.FISHING_ROD); + } + }; + + /** + * Check whether this target includes the specified item. + * + * @param item The item to check + * @return True if the target includes the item + */ + public abstract boolean includes(Material item); + + /** + * Check whether this target includes the specified item. + * + * @param item The item to check + * @return True if the target includes the item + */ + public boolean includes(ItemStack item) { + return includes(item.getType()); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/enchantments/EnchantmentWrapper.java b/azurite-api/src/main/java/org/bukkit/enchantments/EnchantmentWrapper.java new file mode 100644 index 0000000..6a0aeb3 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/enchantments/EnchantmentWrapper.java @@ -0,0 +1,51 @@ +package org.bukkit.enchantments; + +import org.bukkit.inventory.ItemStack; + +/** + * A simple wrapper for ease of selecting {@link Enchantment}s + */ +public class EnchantmentWrapper extends Enchantment { + public EnchantmentWrapper(int id) { + super(id); + } + + /** + * Gets the enchantment bound to this wrapper + * + * @return Enchantment + */ + public Enchantment getEnchantment() { + return Enchantment.getById(getId()); + } + + @Override + public int getMaxLevel() { + return getEnchantment().getMaxLevel(); + } + + @Override + public int getStartLevel() { + return getEnchantment().getStartLevel(); + } + + @Override + public EnchantmentTarget getItemTarget() { + return getEnchantment().getItemTarget(); + } + + @Override + public boolean canEnchantItem(ItemStack item) { + return getEnchantment().canEnchantItem(item); + } + + @Override + public String getName() { + return getEnchantment().getName(); + } + + @Override + public boolean conflictsWith(Enchantment other) { + return getEnchantment().conflictsWith(other); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Ageable.java b/azurite-api/src/main/java/org/bukkit/entity/Ageable.java new file mode 100644 index 0000000..cd89bb6 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Ageable.java @@ -0,0 +1,67 @@ +package org.bukkit.entity; + +/** + * Represents an entity that can age and breed. + */ +public interface Ageable extends Creature { + /** + * Gets the age of this animal. + * + * @return Age + */ + int getAge(); + + /** + * Sets the age of this animal. + * + * @param age New age + */ + void setAge(int age); + + /** + * Lock the age of the animal, setting this will prevent the animal from + * maturing or getting ready for mating. + * + * @param lock new lock + */ + void setAgeLock(boolean lock); + + /** + * Gets the current agelock. + * + * @return the current agelock + */ + boolean getAgeLock(); + + /** + * Sets the age of the animal to a baby + */ + void setBaby(); + + /** + * Sets the age of the animal to an adult + */ + void setAdult(); + + /** + * Returns true if the animal is an adult. + * + * @return return true if the animal is an adult + */ + boolean isAdult(); + + /** + * Return the ability to breed of the animal. + * + * @return the ability to breed of the animal + */ + boolean canBreed(); + + /** + * Set breedability of the animal, if the animal is a baby and set to + * breed it will instantly grow up. + * + * @param breed breedability of the animal + */ + void setBreed(boolean breed); +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Ambient.java b/azurite-api/src/main/java/org/bukkit/entity/Ambient.java new file mode 100644 index 0000000..779e389 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Ambient.java @@ -0,0 +1,6 @@ +package org.bukkit.entity; + +/** + * Represents an ambient mob + */ +public interface Ambient extends LivingEntity {} diff --git a/azurite-api/src/main/java/org/bukkit/entity/AnimalTamer.java b/azurite-api/src/main/java/org/bukkit/entity/AnimalTamer.java new file mode 100644 index 0000000..5eb87cc --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/AnimalTamer.java @@ -0,0 +1,20 @@ +package org.bukkit.entity; + +import java.util.UUID; + +public interface AnimalTamer { + + /** + * This is the name of the specified AnimalTamer. + * + * @return The name to reference on tamed animals or null if a name cannot be obtained + */ + String getName(); + + /** + * This is the UUID of the specified AnimalTamer. + * + * @return The UUID to reference on tamed animals + */ + UUID getUniqueId(); +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Animals.java b/azurite-api/src/main/java/org/bukkit/entity/Animals.java new file mode 100644 index 0000000..f0dc157 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Animals.java @@ -0,0 +1,6 @@ +package org.bukkit.entity; + +/** + * Represents an Animal. + */ +public interface Animals extends Ageable {} diff --git a/azurite-api/src/main/java/org/bukkit/entity/ArmorStand.java b/azurite-api/src/main/java/org/bukkit/entity/ArmorStand.java new file mode 100644 index 0000000..2495e1d --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/ArmorStand.java @@ -0,0 +1,277 @@ +package org.bukkit.entity; + +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.EulerAngle; + +public interface ArmorStand extends LivingEntity { + + /** + * Returns the item the armor stand is + * currently holding + * + * @return the held item + */ + ItemStack getItemInHand(); + + /** + * Sets the item the armor stand is currently + * holding + * + * @param item the item to hold + */ + void setItemInHand(ItemStack item); + + /** + * Returns the item currently being worn + * by the armor stand on its feet + * + * @return the worn item + */ + ItemStack getBoots(); + + /** + * Sets the item currently being worn + * by the armor stand on its feet + * + * @param item the item to wear + */ + void setBoots(ItemStack item); + + /** + * Returns the item currently being worn + * by the armor stand on its legs + * + * @return the worn item + */ + ItemStack getLeggings(); + + /** + * Sets the item currently being worn + * by the armor stand on its legs + * + * @param item the item to wear + */ + void setLeggings(ItemStack item); + + /** + * Returns the item currently being worn + * by the armor stand on its chest + * + * @return the worn item + */ + ItemStack getChestplate(); + + /** + * Sets the item currently being worn + * by the armor stand on its chest + * + * @param item the item to wear + */ + void setChestplate(ItemStack item); + + /** + * Returns the item currently being worn + * by the armor stand on its head + * + * @return the worn item + */ + ItemStack getHelmet(); + + /** + * Sets the item currently being worn + * by the armor stand on its head + * + * @param item the item to wear + */ + void setHelmet(ItemStack item); + + /** + * Returns the armor stand's body's + * current pose as a {@link EulerAngle} + * + * @return the current pose + */ + EulerAngle getBodyPose(); + + /** + * Sets the armor stand's body's + * current pose as a {@link EulerAngle} + * + * @param pose the current pose + */ + void setBodyPose(EulerAngle pose); + + /** + * Returns the armor stand's left arm's + * current pose as a {@link EulerAngle} + * + * @return the current pose + */ + EulerAngle getLeftArmPose(); + + /** + * Sets the armor stand's left arm's + * current pose as a {@link EulerAngle} + * + * @param pose the current pose + */ + void setLeftArmPose(EulerAngle pose); + + /** + * Returns the armor stand's right arm's + * current pose as a {@link EulerAngle} + * + * @return the current pose + */ + EulerAngle getRightArmPose(); + + /** + * Sets the armor stand's right arm's + * current pose as a {@link EulerAngle} + * + * @param pose the current pose + */ + void setRightArmPose(EulerAngle pose); + + /** + * Returns the armor stand's left leg's + * current pose as a {@link EulerAngle} + * + * @return the current pose + */ + EulerAngle getLeftLegPose(); + + /** + * Sets the armor stand's left leg's + * current pose as a {@link EulerAngle} + * + * @param pose the current pose + */ + void setLeftLegPose(EulerAngle pose); + + /** + * Returns the armor stand's right leg's + * current pose as a {@link EulerAngle} + * + * @return the current pose + */ + EulerAngle getRightLegPose(); + + /** + * Sets the armor stand's right leg's + * current pose as a {@link EulerAngle} + * + * @param pose the current pose + */ + void setRightLegPose(EulerAngle pose); + + /** + * Returns the armor stand's head's + * current pose as a {@link EulerAngle} + * + * @return the current pose + */ + EulerAngle getHeadPose(); + + /** + * Sets the armor stand's head's + * current pose as a {@link EulerAngle} + * + * @param pose the current pose + */ + void setHeadPose(EulerAngle pose); + + /** + * Returns whether the armor stand has + * a base plate + * + * @return whether it has a base plate + */ + boolean hasBasePlate(); + + /** + * Sets whether the armor stand has a + * base plate + * + * @param basePlate whether is has a base plate + */ + void setBasePlate(boolean basePlate); + + /** + * Returns whether gravity applies to + * this armor stand + * + * @return whether gravity applies + */ + boolean hasGravity(); + + /** + * Sets whether gravity applies to + * this armor stand + * + * @param gravity whether gravity should apply + */ + void setGravity(boolean gravity); + + /** + * Returns whether the armor stand should be + * visible or not + * + * @return whether the stand is visible or not + */ + boolean isVisible(); + + /** + * Sets whether the armor stand should be + * visible or not + * + * @param visible whether the stand is visible or not + */ + void setVisible(boolean visible); + + /** + * Returns whether this armor stand has arms + * + * @return whether this has arms or not + */ + boolean hasArms(); + + /** + * Sets whether this armor stand has arms + * + * @param arms whether this has arms or not + */ + void setArms(boolean arms); + + /** + * Returns whether this armor stand is scaled + * down + * + * @return whether this is scaled down + */ + boolean isSmall(); + + /** + * Sets whether this armor stand is scaled + * down + * + * @param small whether this is scaled down + */ + void setSmall(boolean small); + + /** + * Returns whether this armor stand is a marker, + * meaning it has a very small collision box + * + * @return whether this is a marker + */ + boolean isMarker(); + + /** + * Sets whether this armor stand is a marker, + * meaning it has a very small collision box + * + * @param marker whether this is a marker + */ + void setMarker(boolean marker); +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Arrow.java b/azurite-api/src/main/java/org/bukkit/entity/Arrow.java new file mode 100644 index 0000000..5edb514 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Arrow.java @@ -0,0 +1,58 @@ +package org.bukkit.entity; + +/** + * Represents an arrow. + */ +public interface Arrow extends Projectile { + + /** + * Gets the knockback strength for an arrow, which is the + * {@link org.bukkit.enchantments.Enchantment#KNOCKBACK KnockBack} level + * of the bow that shot it. + * + * @return the knockback strength value + */ + int getKnockbackStrength(); + + /** + * Sets the knockback strength for an arrow. + * + * @param knockbackStrength the knockback strength value + */ + void setKnockbackStrength(int knockbackStrength); + + /** + * Gets whether this arrow is critical. + *

+ * Critical arrows have increased damage and cause particle effects. + *

+ * Critical arrows generally occur when a player fully draws a bow before + * firing. + * + * @return true if it is critical + */ + boolean isCritical(); + + /** + * Sets whether or not this arrow should be critical. + * + * @param critical whether or not it should be critical + */ + void setCritical(boolean critical); + + class Spigot extends Entity.Spigot + { + + public double getDamage() + { + throw new UnsupportedOperationException( "Not supported yet." ); + } + + public void setDamage(double damage) + { + throw new UnsupportedOperationException( "Not supported yet." ); + } + } + + Spigot spigot(); +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Bat.java b/azurite-api/src/main/java/org/bukkit/entity/Bat.java new file mode 100644 index 0000000..bd73f22 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Bat.java @@ -0,0 +1,27 @@ +package org.bukkit.entity; + +/** + * Represents a Bat + */ +public interface Bat extends Ambient { + + /** + * Checks the current waking state of this bat. + *

+ * This does not imply any persistence of state past the method call. + * + * @return true if the bat is awake or false if it is currently hanging + * from a block + */ + boolean isAwake(); + + /** + * This method modifies the current waking state of this bat. + *

+ * This does not prevent a bat from spontaneously awaking itself, or from + * reattaching itself to a block. + * + * @param state the new state + */ + void setAwake(boolean state); +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Blaze.java b/azurite-api/src/main/java/org/bukkit/entity/Blaze.java new file mode 100644 index 0000000..7a5505b --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Blaze.java @@ -0,0 +1,8 @@ +package org.bukkit.entity; + +/** + * Represents a Blaze monster + */ +public interface Blaze extends Monster { + +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Boat.java b/azurite-api/src/main/java/org/bukkit/entity/Boat.java new file mode 100644 index 0000000..1395cd3 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Boat.java @@ -0,0 +1,72 @@ +package org.bukkit.entity; + +/** + * Represents a boat entity. + */ +public interface Boat extends Vehicle { + + /** + * Gets the maximum speed of a boat. The speed is unrelated to the + * velocity. + * + * @return The max speed. + */ + double getMaxSpeed(); + + /** + * Sets the maximum speed of a boat. Must be nonnegative. Default is 0.4D. + * + * @param speed The max speed. + */ + void setMaxSpeed(double speed); + + /** + * Gets the deceleration rate (newSpeed = curSpeed * rate) of occupied + * boats. The default is 0.2. + * + * @return The rate of deceleration + */ + double getOccupiedDeceleration(); + + /** + * Sets the deceleration rate (newSpeed = curSpeed * rate) of occupied + * boats. Setting this to a higher value allows for quicker acceleration. + * The default is 0.2. + * + * @param rate deceleration rate + */ + void setOccupiedDeceleration(double rate); + + /** + * Gets the deceleration rate (newSpeed = curSpeed * rate) of unoccupied + * boats. The default is -1. Values below 0 indicate that no additional + * deceleration is imposed. + * + * @return The rate of deceleration + */ + double getUnoccupiedDeceleration(); + + /** + * Sets the deceleration rate (newSpeed = curSpeed * rate) of unoccupied + * boats. Setting this to a higher value allows for quicker deceleration + * of boats when a player disembarks. The default is -1. Values below 0 + * indicate that no additional deceleration is imposed. + * + * @param rate deceleration rate + */ + void setUnoccupiedDeceleration(double rate); + + /** + * Get whether boats can work on land. + * + * @return whether boats can work on land + */ + boolean getWorkOnLand(); + + /** + * Set whether boats can work on land. + * + * @param workOnLand whether boats can work on land + */ + void setWorkOnLand(boolean workOnLand); +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/CaveSpider.java b/azurite-api/src/main/java/org/bukkit/entity/CaveSpider.java new file mode 100644 index 0000000..9c37646 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/CaveSpider.java @@ -0,0 +1,6 @@ +package org.bukkit.entity; + +/** + * Represents a Spider. + */ +public interface CaveSpider extends Spider {} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Chicken.java b/azurite-api/src/main/java/org/bukkit/entity/Chicken.java new file mode 100644 index 0000000..cb3ec6e --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Chicken.java @@ -0,0 +1,6 @@ +package org.bukkit.entity; + +/** + * Represents a Chicken. + */ +public interface Chicken extends Animals {} diff --git a/azurite-api/src/main/java/org/bukkit/entity/ComplexEntityPart.java b/azurite-api/src/main/java/org/bukkit/entity/ComplexEntityPart.java new file mode 100644 index 0000000..ced75ec --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/ComplexEntityPart.java @@ -0,0 +1,14 @@ +package org.bukkit.entity; + +/** + * Represents a single part of a {@link ComplexLivingEntity} + */ +public interface ComplexEntityPart extends Entity { + + /** + * Gets the parent {@link ComplexLivingEntity} of this part. + * + * @return Parent complex entity + */ + ComplexLivingEntity getParent(); +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/ComplexLivingEntity.java b/azurite-api/src/main/java/org/bukkit/entity/ComplexLivingEntity.java new file mode 100644 index 0000000..3b3aaa7 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/ComplexLivingEntity.java @@ -0,0 +1,16 @@ +package org.bukkit.entity; + +import java.util.Set; + +/** + * Represents a complex living entity - one that is made up of various smaller + * parts + */ +public interface ComplexLivingEntity extends LivingEntity { + /** + * Gets a list of parts that belong to this complex entity + * + * @return List of parts + */ + Set getParts(); +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Cow.java b/azurite-api/src/main/java/org/bukkit/entity/Cow.java new file mode 100644 index 0000000..cd4ed4d --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Cow.java @@ -0,0 +1,6 @@ +package org.bukkit.entity; + +/** + * Represents a Cow. + */ +public interface Cow extends Animals {} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Creature.java b/azurite-api/src/main/java/org/bukkit/entity/Creature.java new file mode 100644 index 0000000..337b7bd --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Creature.java @@ -0,0 +1,26 @@ +package org.bukkit.entity; + +/** + * Represents a Creature. Creatures are non-intelligent monsters or animals + * which have very simple abilities. + */ +public interface Creature extends LivingEntity { + + /** + * Instructs this Creature to set the specified LivingEntity as its + * target. + *

+ * Hostile creatures may attack their target, and friendly creatures may + * follow their target. + * + * @param target New LivingEntity to target, or null to clear the target + */ + void setTarget(LivingEntity target); + + /** + * Gets the current target of this Creature + * + * @return Current target of this creature, or null if none exists + */ + LivingEntity getTarget(); +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/CreatureType.java b/azurite-api/src/main/java/org/bukkit/entity/CreatureType.java new file mode 100644 index 0000000..ea1f72e --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/CreatureType.java @@ -0,0 +1,108 @@ +package org.bukkit.entity; + +import java.util.EnumSet; +import java.util.HashMap; +import java.util.Map; + +/** + * Represents a type of creature. + * + * @deprecated Use EntityType instead. + */ +@Deprecated +public enum CreatureType { + // These strings MUST match the strings in nms.EntityTypes and are case sensitive. + CREEPER("Creeper", Creeper.class, 50), + SKELETON("Skeleton", Skeleton.class, 51), + SPIDER("Spider", Spider.class, 52), + GIANT("Giant", Giant.class, 53), + ZOMBIE("Zombie", Zombie.class, 54), + SLIME("Slime", Slime.class, 55), + GHAST("Ghast", Ghast.class, 56), + PIG_ZOMBIE("PigZombie", PigZombie.class, 57), + ENDERMAN("Enderman", Enderman.class, 58), + CAVE_SPIDER("CaveSpider", CaveSpider.class, 59), + SILVERFISH("Silverfish", Silverfish.class, 60), + BLAZE("Blaze", Blaze.class, 61), + MAGMA_CUBE("LavaSlime", MagmaCube.class, 62), + ENDER_DRAGON("EnderDragon", EnderDragon.class, 63), + ENDERMITE("Endermite", Endermite.class, 67), + GUARDIAN("Guardian", Guardian.class, 68), + PIG("Pig", Pig.class, 90), + SHEEP("Sheep", Sheep.class, 91), + COW("Cow", Cow.class, 92), + CHICKEN("Chicken", Chicken.class, 93), + SQUID("Squid", Squid.class, 94), + WOLF("Wolf", Wolf.class, 95), + MUSHROOM_COW("MushroomCow", MushroomCow.class, 96), + SNOWMAN("SnowMan", Snowman.class, 97), + RABBIT("Rabbit", Rabbit.class, 101), + VILLAGER("Villager", Villager.class, 120); + + private String name; + private Class clazz; + private short typeId; + + private static final Map NAME_MAP = new HashMap(); + private static final Map ID_MAP = new HashMap(); + + static { + for (CreatureType type : EnumSet.allOf(CreatureType.class)) { + NAME_MAP.put(type.name, type); + if (type.typeId != 0) { + ID_MAP.put(type.typeId, type); + } + } + } + + CreatureType(String name, Class clazz, int typeId) { + this.name = name; + this.clazz = clazz; + this.typeId = (short) typeId; + } + + public String getName() { + return name; + } + + public Class getEntityClass() { + return clazz; + } + + /** + * + * @return the raw type id + * @deprecated Magic value + */ + @Deprecated + public short getTypeId() { + return typeId; + } + + public static CreatureType fromName(String name) { + return NAME_MAP.get(name); + } + + /** + * + * @param id the raw type id + * @return the matching CreatureType or null + * @deprecated Magic value + */ + @Deprecated + public static CreatureType fromId(int id) { + if (id > Short.MAX_VALUE) { + return null; + } + return ID_MAP.get((short) id); + } + + @Deprecated + public EntityType toEntityType() { + return EntityType.fromName(getName()); + } + + public static CreatureType fromEntityType(EntityType creatureType) { + return fromName(creatureType.getName()); + } +} \ No newline at end of file diff --git a/azurite-api/src/main/java/org/bukkit/entity/Creeper.java b/azurite-api/src/main/java/org/bukkit/entity/Creeper.java new file mode 100644 index 0000000..c31505a --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Creeper.java @@ -0,0 +1,21 @@ +package org.bukkit.entity; + +/** + * Represents a Creeper + */ +public interface Creeper extends Monster { + + /** + * Checks if this Creeper is powered (Electrocuted) + * + * @return true if this creeper is powered + */ + boolean isPowered(); + + /** + * Sets the Powered status of this Creeper + * + * @param value New Powered status + */ + void setPowered(boolean value); +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Damageable.java b/azurite-api/src/main/java/org/bukkit/entity/Damageable.java new file mode 100644 index 0000000..d0599cf --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Damageable.java @@ -0,0 +1,127 @@ +package org.bukkit.entity; + +/** + * Represents an {@link Entity} that has health and can take damage. + */ +public interface Damageable extends Entity { + /** + * Deals the given amount of damage to this entity. + * + * @param amount Amount of damage to deal + */ + void damage(double amount); + + /** + * This method exists for legacy reasons to provide backwards + * compatibility. It will not exist at runtime and should not be used + * under any circumstances. + * + * @param amount Amount of damage to deal + */ + @Deprecated + void _INVALID_damage(int amount); + + /** + * Deals the given amount of damage to this entity, from a specified + * entity. + * + * @param amount Amount of damage to deal + * @param source Entity which to attribute this damage from + */ + void damage(double amount, Entity source); + + /** + * This method exists for legacy reasons to provide backwards + * compatibility. It will not exist at runtime and should not be used + * under any circumstances. + * + * @param amount Amount of damage to deal + * @param source Entity which to attribute this damage from + */ + @Deprecated + void _INVALID_damage(int amount, Entity source); + + /** + * Gets the entity's health from 0 to {@link #getMaxHealth()}, where 0 is dead. + * + * @return Health represented from 0 to max + */ + double getHealth(); + + /** + * This method exists for legacy reasons to provide backwards + * compatibility. It will not exist at runtime and should not be used + * under any circumstances. + * + * @return Health represented from 0 to max + */ + @Deprecated + int _INVALID_getHealth(); + + /** + * Sets the entity's health from 0 to {@link #getMaxHealth()}, where 0 is + * dead. + * + * @param health New health represented from 0 to max + * @throws IllegalArgumentException Thrown if the health is {@literal < 0 or >} + * {@link #getMaxHealth()} + */ + void setHealth(double health); + + /** + * This method exists for legacy reasons to provide backwards + * compatibility. It will not exist at runtime and should not be used + * under any circumstances. + * + * @param health New health represented from 0 to max + * @throws IllegalArgumentException Thrown if the health is {@literal < 0 or >} + * {@link #getMaxHealth()} + */ + @Deprecated + void _INVALID_setHealth(int health); + + /** + * Gets the maximum health this entity has. + * + * @return Maximum health + */ + double getMaxHealth(); + + /** + * This method exists for legacy reasons to provide backwards + * compatibility. It will not exist at runtime and should not be used + * under any circumstances. + * + * @return Maximum health + */ + @Deprecated + int _INVALID_getMaxHealth(); + + /** + * Sets the maximum health this entity can have. + *

+ * If the health of the entity is above the value provided it will be set + * to that value. + *

+ * Note: An entity with a health bar ({@link Player}, {@link EnderDragon}, + * {@link Wither}, etc...} will have their bar scaled accordingly. + * + * @param health amount of health to set the maximum to + */ + void setMaxHealth(double health); + + /** + * This method exists for legacy reasons to provide backwards + * compatibility. It will not exist at runtime and should not be used + * under any circumstances. + * + * @param health amount of health to set the maximum to + */ + @Deprecated + void _INVALID_setMaxHealth(int health); + + /** + * Resets the max health to the original amount. + */ + void resetMaxHealth(); +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Egg.java b/azurite-api/src/main/java/org/bukkit/entity/Egg.java new file mode 100644 index 0000000..2dcc00b --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Egg.java @@ -0,0 +1,6 @@ +package org.bukkit.entity; + +/** + * Represents a thrown egg. + */ +public interface Egg extends Projectile {} diff --git a/azurite-api/src/main/java/org/bukkit/entity/EnderCrystal.java b/azurite-api/src/main/java/org/bukkit/entity/EnderCrystal.java new file mode 100644 index 0000000..bac547e --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/EnderCrystal.java @@ -0,0 +1,7 @@ +package org.bukkit.entity; + +/** + * A crystal that heals nearby EnderDragons + */ +public interface EnderCrystal extends Entity { +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/EnderDragon.java b/azurite-api/src/main/java/org/bukkit/entity/EnderDragon.java new file mode 100644 index 0000000..609f3ba --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/EnderDragon.java @@ -0,0 +1,8 @@ +package org.bukkit.entity; + +/** + * Represents an Ender Dragon + */ +public interface EnderDragon extends ComplexLivingEntity { + +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/EnderDragonPart.java b/azurite-api/src/main/java/org/bukkit/entity/EnderDragonPart.java new file mode 100644 index 0000000..4b35ee7 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/EnderDragonPart.java @@ -0,0 +1,8 @@ +package org.bukkit.entity; + +/** + * Represents an ender dragon part + */ +public interface EnderDragonPart extends ComplexEntityPart, Damageable { + EnderDragon getParent(); +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/EnderPearl.java b/azurite-api/src/main/java/org/bukkit/entity/EnderPearl.java new file mode 100644 index 0000000..db18a90 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/EnderPearl.java @@ -0,0 +1,8 @@ +package org.bukkit.entity; + +/** + * Represents a thrown Ender Pearl entity + */ +public interface EnderPearl extends Projectile { + +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/EnderSignal.java b/azurite-api/src/main/java/org/bukkit/entity/EnderSignal.java new file mode 100644 index 0000000..3d2d76c --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/EnderSignal.java @@ -0,0 +1,9 @@ +package org.bukkit.entity; + +/** + * Represents an Ender Signal, which is often created upon throwing an ender + * eye + */ +public interface EnderSignal extends Entity { + +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Enderman.java b/azurite-api/src/main/java/org/bukkit/entity/Enderman.java new file mode 100644 index 0000000..3e286ea --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Enderman.java @@ -0,0 +1,23 @@ +package org.bukkit.entity; + +import org.bukkit.material.MaterialData; + +/** + * Represents an Enderman. + */ +public interface Enderman extends Monster { + + /** + * Get the id and data of the block that the Enderman is carrying. + * + * @return MaterialData containing the id and data of the block + */ + MaterialData getCarriedMaterial(); + + /** + * Set the id and data of the block that the Enderman is carring. + * + * @param material data to set the carried block to + */ + void setCarriedMaterial(MaterialData material); +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Endermite.java b/azurite-api/src/main/java/org/bukkit/entity/Endermite.java new file mode 100644 index 0000000..dc1fa54 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Endermite.java @@ -0,0 +1,4 @@ +package org.bukkit.entity; + +public interface Endermite extends Monster { +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Entity.java b/azurite-api/src/main/java/org/bukkit/entity/Entity.java new file mode 100644 index 0000000..0d7754b --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Entity.java @@ -0,0 +1,407 @@ +package org.bukkit.entity; + +import org.bukkit.EntityEffect; +import org.bukkit.Location; +import org.bukkit.Server; +import org.bukkit.World; +import org.bukkit.command.CommandSender; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; +import org.bukkit.metadata.Metadatable; +import org.bukkit.util.Vector; + +import java.util.List; +import java.util.UUID; + +/** + * Represents a base entity in the world + */ +public interface Entity extends Metadatable, CommandSender { + + /** + * Gets the entity's current position + * + * @return a new copy of Location containing the position of this entity + */ + Location getLocation(); + + /** + * Stores the entity's current position in the provided Location object. + *

+ * If the provided Location is null this method does nothing and returns + * null. + * + * @param loc the location to copy into + * @return The Location object provided or null + */ + Location getLocation(Location loc); + + /** + * Sets this entity's velocity + * + * @param velocity New velocity to travel with + */ + void setVelocity(Vector velocity); + + /** + * Gets this entity's current velocity + * + * @return Current travelling velocity of this entity + */ + Vector getVelocity(); + + /** + * Returns true if the entity is supported by a block. This value is a + * state updated by the server and is not recalculated unless the entity + * moves. + * + * @return True if entity is on ground. + */ + boolean isOnGround(); + + /** + * Gets the current world this entity resides in + * + * @return World + */ + World getWorld(); + + /** + * Teleports this entity to the given location. If this entity is riding a + * vehicle, it will be dismounted prior to teleportation. + * + * @param location New location to teleport this entity to + * @return true if the teleport was successful + */ + boolean teleport(Location location); + + /** + * Teleports this entity to the given location. If this entity is riding a + * vehicle, it will be dismounted prior to teleportation. + * + * @param location New location to teleport this entity to + * @param cause The cause of this teleportation + * @return true if the teleport was successful + */ + boolean teleport(Location location, TeleportCause cause); + + /** + * Teleports this entity to the target Entity. If this entity is riding a + * vehicle, it will be dismounted prior to teleportation. + * + * @param destination Entity to teleport this entity to + * @return true if the teleport was successful + */ + boolean teleport(Entity destination); + + /** + * Teleports this entity to the target Entity. If this entity is riding a + * vehicle, it will be dismounted prior to teleportation. + * + * @param destination Entity to teleport this entity to + * @param cause The cause of this teleportation + * @return true if the teleport was successful + */ + boolean teleport(Entity destination, TeleportCause cause); + + /** + * Returns a list of entities within a bounding box centered around this + * entity + * + * @param x 1/2 the size of the box along x axis + * @param y 1/2 the size of the box along y axis + * @param z 1/2 the size of the box along z axis + * @return {@code List} List of entities nearby + */ + List getNearbyEntities(double x, double y, double z); + + /** + * Returns a unique id for this entity + * + * @return Entity id + */ + int getEntityId(); + + /** + * Returns the entity's current fire ticks (ticks before the entity stops + * being on fire). + * + * @return int fireTicks + */ + int getFireTicks(); + + /** + * Returns the entity's maximum fire ticks. + * + * @return int maxFireTicks + */ + int getMaxFireTicks(); + + /** + * Sets the entity's current fire ticks (ticks before the entity stops + * being on fire). + * + * @param ticks Current ticks remaining + */ + void setFireTicks(int ticks); + + /** + * Mark the entity's removal. + */ + void remove(); + + /** + * Returns true if this entity has been marked for removal. + * + * @return True if it is dead. + */ + boolean isDead(); + + /** + * Returns false if the entity has died or been despawned for some other + * reason. + * + * @return True if valid. + */ + boolean isValid(); + + /** + * Gets the {@link Server} that contains this Entity + * + * @return Server instance running this Entity + */ + Server getServer(); + + /** + * Gets the primary passenger of a vehicle. For vehicles that could have + * multiple passengers, this will only return the primary passenger. + * + * @return an entity + */ + Entity getPassenger(); + + /** + * Set the passenger of a vehicle. + * + * @param passenger The new passenger. + * @return false if it could not be done for whatever reason + */ + boolean setPassenger(Entity passenger); + + /** + * Check if a vehicle has passengers. + * + * @return True if the vehicle has no passengers. + */ + boolean isEmpty(); + + /** + * Eject any passenger. + * + * @return True if there was a passenger. + */ + boolean eject(); + + /** + * Returns the distance this entity has fallen + * + * @return The distance. + */ + float getFallDistance(); + + /** + * Sets the fall distance for this entity + * + * @param distance The new distance. + */ + void setFallDistance(float distance); + + /** + * Record the last {@link EntityDamageEvent} inflicted on this entity + * + * @param event a {@link EntityDamageEvent} + */ + void setLastDamageCause(EntityDamageEvent event); + + /** + * Retrieve the last {@link EntityDamageEvent} inflicted on this entity. + * This event may have been cancelled. + * + * @return the last known {@link EntityDamageEvent} or null if hitherto + * unharmed + */ + EntityDamageEvent getLastDamageCause(); + + /** + * Returns a unique and persistent id for this entity + * + * @return unique id + */ + UUID getUniqueId(); + + /** + * Gets the amount of ticks this entity has lived for. + *

+ * This is the equivalent to "age" in entities. + * + * @return Age of entity + */ + int getTicksLived(); + + /** + * Sets the amount of ticks this entity has lived for. + *

+ * This is the equivalent to "age" in entities. May not be less than one + * tick. + * + * @param value Age of entity + */ + void setTicksLived(int value); + + /** + * Performs the specified {@link EntityEffect} for this entity. + *

+ * This will be viewable to all players near the entity. + * + * @param type Effect to play. + */ + void playEffect(EntityEffect type); + + /** + * Get the type of the entity. + * + * @return The entity type. + */ + EntityType getType(); + + /** + * Returns whether this entity is inside a vehicle. + * + * @return True if the entity is in a vehicle. + */ + boolean isInsideVehicle(); + + /** + * Leave the current vehicle. If the entity is currently in a vehicle (and + * is removed from it), true will be returned, otherwise false will be + * returned. + * + * @return True if the entity was in a vehicle. + */ + boolean leaveVehicle(); + + /** + * Get the vehicle that this player is inside. If there is no vehicle, + * null will be returned. + * + * @return The current vehicle. + */ + Entity getVehicle(); + + /** + * Sets a custom name on a mob. This name will be used in death messages + * and can be sent to the client as a nameplate over the mob. + *

+ * Setting the name to null or an empty string will clear it. + *

+ * This value has no effect on players, they will always use their real + * name. + * + * @param name the name to set + */ + void setCustomName(String name); + + /** + * Gets the custom name on a mob. If there is no name this method will + * return null. + *

+ * This value has no effect on players, they will always use their real + * name. + * + * @return name of the mob or null + */ + String getCustomName(); + + /** + * Sets whether or not to display the mob's custom name client side. The + * name will be displayed above the mob similarly to a player. + *

+ * This value has no effect on players, they will always display their + * name. + * + * @param flag custom name or not + */ + void setCustomNameVisible(boolean flag); + + /** + * Gets whether or not the mob's custom name is displayed client side. + *

+ * This value has no effect on players, they will always display their + * name. + * + * @return if the custom name is displayed + */ + boolean isCustomNameVisible(); + + // Spigot Start + class Spigot + { + + /** + * Returns whether this entity is invulnerable. + * + * @return True if the entity is invulnerable. + */ + public boolean isInvulnerable() + { + throw new UnsupportedOperationException( "Not supported yet." ); + } + } + + Spigot spigot(); + // Spigot End + + // Rivals start + /** + * Can the entity be collided + * + * @return true if can be collided + */ + public boolean isCollidable(); + + /** + * Set if the entity can be collided + * + * @param collidable true if can be collided + */ + public void setCollidable(boolean collidable); + + /** + * Should disable knockback for this entity + * + * @return true if knockback is disabled + */ + public boolean isDisableKnockback(); + + /** + * Set if the entity should disable knockback + * + * @param disableKnockback true if knockback should be disabled + */ + public void setDisableKnockback(boolean disableKnockback); + + /** + * Should disable water movement for this entity + * + * @return true if water movement is disabled + */ + public boolean isDisableWaterMovement(); + + /** + * Set if the entity should disable water movement + * + * @param disableWaterMovement true if water movement should be disabled + */ + public void setDisableWaterMovement(boolean disableWaterMovement); + // Rivals end +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/EntityType.java b/azurite-api/src/main/java/org/bukkit/entity/EntityType.java new file mode 100644 index 0000000..75cc27c --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/EntityType.java @@ -0,0 +1,296 @@ +package org.bukkit.entity; + +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.entity.minecart.PoweredMinecart; +import org.bukkit.entity.minecart.StorageMinecart; +import org.bukkit.entity.minecart.*; +import org.bukkit.inventory.ItemStack; + +import java.util.HashMap; +import java.util.Map; + +public enum EntityType { + + // These strings MUST match the strings in nms.EntityTypes and are case sensitive. + /** + * An item resting on the ground. + *

+ * Spawn with {@link World#dropItem(Location, ItemStack)} or {@link + * World#dropItemNaturally(Location, ItemStack)} + */ + DROPPED_ITEM("Item", Item.class, 1, false), + /** + * An experience orb. + */ + EXPERIENCE_ORB("XPOrb", ExperienceOrb.class, 2), + /** + * A leash attached to a fencepost. + */ + LEASH_HITCH("LeashKnot", LeashHitch.class, 8), + /** + * A painting on a wall. + */ + PAINTING("Painting", Painting.class, 9), + /** + * An arrow projectile; may get stuck in the ground. + */ + ARROW("Arrow", Arrow.class, 10), + /** + * A flying snowball. + */ + SNOWBALL("Snowball", Snowball.class, 11), + /** + * A flying large fireball, as thrown by a Ghast for example. + */ + FIREBALL("Fireball", LargeFireball.class, 12), + /** + * A flying small fireball, such as thrown by a Blaze or player. + */ + SMALL_FIREBALL("SmallFireball", SmallFireball.class, 13), + /** + * A flying ender pearl. + */ + ENDER_PEARL("ThrownEnderpearl", EnderPearl.class, 14), + /** + * An ender eye signal. + */ + ENDER_SIGNAL("EyeOfEnderSignal", EnderSignal.class, 15), + /** + * A flying experience bottle. + */ + THROWN_EXP_BOTTLE("ThrownExpBottle", ThrownExpBottle.class, 17), + /** + * An item frame on a wall. + */ + ITEM_FRAME("ItemFrame", ItemFrame.class, 18), + /** + * A flying wither skull projectile. + */ + WITHER_SKULL("WitherSkull", WitherSkull.class, 19), + /** + * Primed TNT that is about to explode. + */ + PRIMED_TNT("PrimedTnt", TNTPrimed.class, 20), + /** + * A block that is going to or is about to fall. + */ + FALLING_BLOCK("FallingSand", FallingBlock.class, 21, false), + FIREWORK("FireworksRocketEntity", Firework.class, 22, false), + ARMOR_STAND("ArmorStand", ArmorStand.class, 30, false), + /** + * @see CommandMinecart + */ + MINECART_COMMAND("MinecartCommandBlock", CommandMinecart.class, 40), + /** + * A placed boat. + */ + BOAT("Boat", Boat.class, 41), + /** + * @see RideableMinecart + */ + MINECART("MinecartRideable", RideableMinecart.class, 42), + /** + * @see StorageMinecart + */ + MINECART_CHEST("MinecartChest", StorageMinecart.class, 43), + /** + * @see PoweredMinecart + */ + MINECART_FURNACE("MinecartFurnace", PoweredMinecart.class, 44), + /** + * @see ExplosiveMinecart + */ + MINECART_TNT("MinecartTNT", ExplosiveMinecart.class, 45), + /** + * @see HopperMinecart + */ + MINECART_HOPPER("MinecartHopper", HopperMinecart.class, 46), + /** + * @see SpawnerMinecart + */ + MINECART_MOB_SPAWNER("MinecartMobSpawner", SpawnerMinecart.class, 47), + CREEPER("Creeper", Creeper.class, 50, "Creeper"), + SKELETON("Skeleton", Skeleton.class, 51, "Skeleton"), + SPIDER("Spider", Spider.class, 52, "Spider"), + GIANT("Giant", Giant.class, 53, "Giant"), + ZOMBIE("Zombie", Zombie.class, 54, "Zombie"), + SLIME("Slime", Slime.class, 55, "Slime"), + GHAST("Ghast", Ghast.class, 56, "Ghast"), + PIG_ZOMBIE("PigZombie", PigZombie.class, 57, "Zombie Pigman"), + ENDERMAN("Enderman", Enderman.class, 58, "Enderman"), + CAVE_SPIDER("CaveSpider", CaveSpider.class, 59, "Cave Spider"), + SILVERFISH("Silverfish", Silverfish.class, 60, "Silverfish"), + BLAZE("Blaze", Blaze.class, 61, "Blaze"), + MAGMA_CUBE("LavaSlime", MagmaCube.class, 62, "Magma Cube"), + ENDER_DRAGON("EnderDragon", EnderDragon.class, 63, "Enderdragon"), + WITHER("WitherBoss", Wither.class, 64, "Wither"), + BAT("Bat", Bat.class, 65, "Bat"), + WITCH("Witch", Witch.class, 66, "Witch"), + ENDERMITE("Endermite", Endermite.class, 67, "Endermite"), + GUARDIAN("Guardian", Guardian.class, 68, "Guardian"), + PIG("Pig", Pig.class, 90, "Pig"), + SHEEP("Sheep", Sheep.class, 91, "Sheep"), + COW("Cow", Cow.class, 92, "Cow"), + CHICKEN("Chicken", Chicken.class, 93, "Chicken"), + SQUID("Squid", Squid.class, 94, "Squid"), + WOLF("Wolf", Wolf.class, 95, "Wolf"), + MUSHROOM_COW("MushroomCow", MushroomCow.class, 96, "Mooshroom"), + SNOWMAN("SnowMan", Snowman.class, 97, "Snowman"), + OCELOT("Ozelot", Ocelot.class, 98, "Ocelot"), + IRON_GOLEM("VillagerGolem", IronGolem.class, 99, "Iron Golem"), + HORSE("EntityHorse", Horse.class, 100, "Horse"), + RABBIT("Rabbit", Rabbit.class, 101, "Rabbit"), + VILLAGER("Villager", Villager.class, 120, "Villager"), + ENDER_CRYSTAL("EnderCrystal", EnderCrystal.class, 200), + // These don't have an entity ID in nms.EntityTypes. + /** + * A flying splash potion. + */ + SPLASH_POTION(null, ThrownPotion.class, -1, false), + /** + * A flying chicken egg. + */ + EGG(null, Egg.class, -1, false), + /** + * A fishing line and bobber. + */ + FISHING_HOOK(null, Fish.class, -1, false), + /** + * A bolt of lightning. + *

+ * Spawn with {@link World#strikeLightning(Location)}. + */ + LIGHTNING(null, LightningStrike.class, -1, false), + WEATHER(null, Weather.class, -1, false), + PLAYER(null, Player.class, -1, false), + COMPLEX_PART(null, ComplexEntityPart.class, -1, false), + /** + * An unknown entity without an Entity Class + */ + UNKNOWN(null, null, -1, false); + + private String name; + private Class clazz; + private short typeId; + private boolean independent, living; + private String displayName; + + private static final Map NAME_MAP = new HashMap(); + private static final Map DISPLAYNAME_MAP = new HashMap(); + private static final Map ID_MAP = new HashMap(); + + static { + for (EntityType type : values()) { + if (type.name != null) { + NAME_MAP.put(type.name.toLowerCase(), type); + } + if (type.typeId > 0) { + ID_MAP.put(type.typeId, type); + } + if (type.displayName != null) { + DISPLAYNAME_MAP.put(type.displayName.toLowerCase(), type); + } + } + } + + EntityType(String name, Class clazz, int typeId) { + this(name, clazz, typeId, true, ""); + } + + EntityType(String name, Class clazz, int typeId, String displayName) { + this(name, clazz, typeId, true, displayName); + } + + EntityType(String name, Class clazz, int typeId, boolean independent) { + this(name, clazz, typeId, independent, ""); + } + + EntityType(String name, Class clazz, int typeId, boolean independent, String displayName) { + this.name = name; + this.clazz = clazz; + this.typeId = (short) typeId; + this.independent = independent; + if (clazz != null) { + this.living = LivingEntity.class.isAssignableFrom(clazz); + } + this.displayName = displayName; + } + + /** + * + * @return the entity type's name + * @deprecated Magic value + */ + @Deprecated + public String getName() { + return name; + } + + public Class getEntityClass() { + return clazz; + } + + public String getDisplayName() { return displayName; } + + /** + * + * @return the raw type id + * @deprecated Magic value + */ + @Deprecated + public short getTypeId() { + return typeId; + } + + /** + * + * @param name the entity type's name + * @return the matching entity type or null + * @deprecated Magic value + */ + @Deprecated + public static EntityType fromName(String name) { + if (name == null) { + return null; + } + return NAME_MAP.get(name.toLowerCase()); + } + + public static EntityType fromDisplayName(String displayName) { + if (displayName == null) { + return null; + } + return DISPLAYNAME_MAP.get(displayName.toLowerCase()); + } + + /** + * + * @param id the raw type id + * @return the matching entity type or null + * @deprecated Magic value + */ + @Deprecated + public static EntityType fromId(int id) { + if (id > Short.MAX_VALUE) { + return null; + } + return ID_MAP.get((short) id); + } + + /** + * Some entities cannot be spawned using {@link + * World#spawnEntity(Location, EntityType)} or {@link + * World#spawn(Location, Class)}, usually because they require additional + * information in order to spawn. + * + * @return False if the entity type cannot be spawned + */ + public boolean isSpawnable() { + return independent; + } + + public boolean isAlive() { + return living; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/ExperienceOrb.java b/azurite-api/src/main/java/org/bukkit/entity/ExperienceOrb.java new file mode 100644 index 0000000..b63c5b1 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/ExperienceOrb.java @@ -0,0 +1,21 @@ +package org.bukkit.entity; + +/** + * Represents an Experience Orb. + */ +public interface ExperienceOrb extends Entity { + + /** + * Gets how much experience is contained within this orb + * + * @return Amount of experience + */ + int getExperience(); + + /** + * Sets how much experience is contained within this orb + * + * @param value Amount of experience + */ + void setExperience(int value); +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Explosive.java b/azurite-api/src/main/java/org/bukkit/entity/Explosive.java new file mode 100644 index 0000000..af92008 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Explosive.java @@ -0,0 +1,35 @@ +package org.bukkit.entity; + +/** + * A representation of an explosive entity + */ +public interface Explosive extends Entity { + + /** + * Set the radius affected by this explosive's explosion + * + * @param yield The explosive yield + */ + void setYield(float yield); + + /** + * Return the radius or yield of this explosive's explosion + * + * @return the radius of blocks affected + */ + float getYield(); + + /** + * Set whether or not this explosive's explosion causes fire + * + * @param isIncendiary Whether it should cause fire + */ + void setIsIncendiary(boolean isIncendiary); + + /** + * Return whether or not this explosive creates a fire when exploding + * + * @return true if the explosive creates fire, false otherwise + */ + boolean isIncendiary(); +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/FallingBlock.java b/azurite-api/src/main/java/org/bukkit/entity/FallingBlock.java new file mode 100644 index 0000000..240a278 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/FallingBlock.java @@ -0,0 +1,69 @@ +package org.bukkit.entity; + +import org.bukkit.Material; + +/** + * Represents a falling block + */ +public interface FallingBlock extends Entity { + + /** + * Get the Material of the falling block + * + * @return Material of the block + */ + Material getMaterial(); + + /** + * Get the ID of the falling block + * + * @return ID type of the block + * @deprecated Magic value + */ + @Deprecated + int getBlockId(); + + /** + * Get the data for the falling block + * + * @return data of the block + * @deprecated Magic value + */ + @Deprecated + byte getBlockData(); + + /** + * Get if the falling block will break into an item if it cannot be placed + * + * @return true if the block will break into an item when obstructed + */ + boolean getDropItem(); + + /** + * Set if the falling block will break into an item if it cannot be placed + * + * @param drop true to break into an item when obstructed + */ + void setDropItem(boolean drop); + + /** + * Get the HurtEntities state of this block. + * + * @return whether entities will be damaged by this block. + */ + boolean canHurtEntities(); + + /** + * Set the HurtEntities state of this block. + * + * @param hurtEntities whether entities will be damaged by this block. + */ + void setHurtEntities(boolean hurtEntities); + + /** + * Gets the source block location of the falling block + * + * @return the source block location the falling block was spawned from + */ + org.bukkit.Location getSourceLoc(); // PaperSpigot - Add FallingBlock source location API +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/FallingSand.java b/azurite-api/src/main/java/org/bukkit/entity/FallingSand.java new file mode 100644 index 0000000..758d47d --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/FallingSand.java @@ -0,0 +1,9 @@ +package org.bukkit.entity; + +/** + * Represents a falling block. + * + * @deprecated See {@link FallingBlock} + */ +@Deprecated +public interface FallingSand extends FallingBlock {} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Fireball.java b/azurite-api/src/main/java/org/bukkit/entity/Fireball.java new file mode 100644 index 0000000..918dd9e --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Fireball.java @@ -0,0 +1,24 @@ +package org.bukkit.entity; + +import org.bukkit.util.Vector; + +/** + * Represents a Fireball. + */ +public interface Fireball extends Projectile, Explosive { + + /** + * Fireballs fly straight and do not take setVelocity(...) well. + * + * @param direction the direction this fireball is flying toward + */ + void setDirection(Vector direction); + + /** + * Retrieve the direction this fireball is heading toward + * + * @return the direction + */ + Vector getDirection(); + +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Firework.java b/azurite-api/src/main/java/org/bukkit/entity/Firework.java new file mode 100644 index 0000000..b8a8c07 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Firework.java @@ -0,0 +1,26 @@ +package org.bukkit.entity; + +import org.bukkit.inventory.meta.FireworkMeta; + +public interface Firework extends Entity { + + /** + * Get a copy of the fireworks meta + * + * @return A copy of the current Firework meta + */ + FireworkMeta getFireworkMeta(); + + /** + * Apply the provided meta to the fireworks + * + * @param meta The FireworkMeta to apply + */ + void setFireworkMeta(FireworkMeta meta); + + /** + * Cause this firework to explode at earliest opportunity, as if it has no + * remaining fuse. + */ + void detonate(); +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Fish.java b/azurite-api/src/main/java/org/bukkit/entity/Fish.java new file mode 100644 index 0000000..12ed1ed --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Fish.java @@ -0,0 +1,8 @@ +package org.bukkit.entity; + +/** + * Represents a fishing hook. + * @deprecated in favor of {@link FishHook} + */ +public interface Fish extends FishHook { +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/FishHook.java b/azurite-api/src/main/java/org/bukkit/entity/FishHook.java new file mode 100644 index 0000000..a75311d --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/FishHook.java @@ -0,0 +1,28 @@ +package org.bukkit.entity; + +/** + * Represents a fishing hook. + */ +public interface FishHook extends Projectile { + /** + * Gets the chance of a fish biting. + *

+ * 0.0 = No Chance.
+ * 1.0 = Instant catch. + * + * @return chance the bite chance + */ + double getBiteChance(); + + /** + * Sets the chance of a fish biting. + *

+ * 0.0 = No Chance.
+ * 1.0 = Instant catch. + * + * @param chance the bite chance + * @throws IllegalArgumentException if the bite chance is not between 0 + * and 1 + */ + void setBiteChance(double chance) throws IllegalArgumentException; +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Flying.java b/azurite-api/src/main/java/org/bukkit/entity/Flying.java new file mode 100644 index 0000000..4f16a26 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Flying.java @@ -0,0 +1,6 @@ +package org.bukkit.entity; + +/** + * Represents a Flying Entity. + */ +public interface Flying extends LivingEntity {} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Ghast.java b/azurite-api/src/main/java/org/bukkit/entity/Ghast.java new file mode 100644 index 0000000..3f5edf7 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Ghast.java @@ -0,0 +1,6 @@ +package org.bukkit.entity; + +/** + * Represents a Ghast. + */ +public interface Ghast extends Flying {} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Giant.java b/azurite-api/src/main/java/org/bukkit/entity/Giant.java new file mode 100644 index 0000000..610de57 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Giant.java @@ -0,0 +1,6 @@ +package org.bukkit.entity; + +/** + * Represents a Giant. + */ +public interface Giant extends Monster {} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Golem.java b/azurite-api/src/main/java/org/bukkit/entity/Golem.java new file mode 100644 index 0000000..4165977 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Golem.java @@ -0,0 +1,8 @@ +package org.bukkit.entity; + +/** + * A mechanical creature that may harm enemies. + */ +public interface Golem extends Creature { + +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Guardian.java b/azurite-api/src/main/java/org/bukkit/entity/Guardian.java new file mode 100644 index 0000000..751300e --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Guardian.java @@ -0,0 +1,18 @@ +package org.bukkit.entity; + +public interface Guardian extends Monster { + + /** + * Check if the Guardian is an elder Guardian + * + * @return true if the Guardian is an Elder Guardian, false if not + */ + boolean isElder(); + + /** + * Set the Guardian to an elder Guardian or not + * + * @param shouldBeElder True if this Guardian should be a elder Guardian, false if not + */ + void setElder(boolean shouldBeElder); +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Hanging.java b/azurite-api/src/main/java/org/bukkit/entity/Hanging.java new file mode 100644 index 0000000..4c36fbb --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Hanging.java @@ -0,0 +1,22 @@ +package org.bukkit.entity; + +import org.bukkit.block.BlockFace; +import org.bukkit.material.Attachable; + +/** + * Represents a Hanging entity + */ +public interface Hanging extends Entity, Attachable { + + /** + * Sets the direction of the hanging entity, potentially overriding rules + * of placement. Note that if the result is not valid the object would + * normally drop as an item. + * + * @param face The new direction. + * @param force Whether to force it. + * @return False if force was false and there was no block for it to + * attach to in order to face the given direction. + */ + boolean setFacingDirection(BlockFace face, boolean force); +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Horse.java b/azurite-api/src/main/java/org/bukkit/entity/Horse.java new file mode 100644 index 0000000..66a194f --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Horse.java @@ -0,0 +1,253 @@ +package org.bukkit.entity; + +import org.bukkit.inventory.HorseInventory; +import org.bukkit.inventory.InventoryHolder; + +/** + * Represents a Horse. + */ +public interface Horse extends Animals, Vehicle, InventoryHolder, Tameable { + + /** + * Represents the different types of horses that may exist. + */ + enum Variant { + /** + * A normal horse + */ + HORSE, + /** + * A donkey + */ + DONKEY, + /** + * A mule + */ + MULE, + /** + * An undead horse + */ + UNDEAD_HORSE, + /** + * A skeleton horse + */ + SKELETON_HORSE, + } + + /** + * Represents the base color that the horse has. + */ + enum Color { + /** + * Snow white + */ + WHITE, + /** + * Very light brown + */ + CREAMY, + /** + * Chestnut + */ + CHESTNUT, + /** + * Light brown + */ + BROWN, + /** + * Pitch black + */ + BLACK, + /** + * Gray + */ + GRAY, + /** + * Dark brown + */ + DARK_BROWN, + } + + /** + * Represents the style, or markings, that the horse has. + */ + enum Style { + /** + * No markings + */ + NONE, + /** + * White socks or stripes + */ + WHITE, + /** + * Milky splotches + */ + WHITEFIELD, + /** + * Round white dots + */ + WHITE_DOTS, + /** + * Small black dots + */ + BLACK_DOTS, + } + + /** + * Gets the horse's variant. + *

+ * A horse's variant defines its physical appearance and capabilities. + * Whether a horse is a regular horse, donkey, mule, or other kind of + * horse is determined using the variant. + * + * @return a {@link Variant} representing the horse's variant + */ + Variant getVariant(); + + /** + * Sets the horse's variant. + *

+ * A horse's variant defines its physical appearance and capabilities. + * Whether a horse is a regular horse, donkey, mule, or other kind of + * horse can be set using the variant. + *

+ * Setting a horse's variant does not change its attributes such as + * its owner and its tamed status, but changing a mule or donkey + * with a chest to another variant which does not support a chest + * will remove the chest and its contents. + * + * @param variant a {@link Variant} for this horse + */ + void setVariant(Variant variant); + + /** + * Gets the horse's color. + *

+ * Colors only apply to horses, not to donkeys, mules, skeleton horses + * or undead horses. + * + * @return a {@link Color} representing the horse's group + */ + Color getColor(); + + /** + * Sets the horse's color. + *

+ * Attempting to set a color for any donkey, mule, skeleton horse or + * undead horse will not result in a change. + * + * @param color a {@link Color} for this horse + */ + void setColor(Color color); + + /** + * Gets the horse's style. + * Styles determine what kind of markings or patterns a horse has. + *

+ * Styles only apply to horses, not to donkeys, mules, skeleton horses + * or undead horses. + * + * @return a {@link Style} representing the horse's style + */ + Style getStyle(); + + /** + * Sets the style of this horse. + * Styles determine what kind of markings or patterns a horse has. + *

+ * Attempting to set a style for any donkey, mule, skeleton horse or + * undead horse will not result in a change. + * + * @param style a {@link Style} for this horse + */ + void setStyle(Style style); + + /** + * Gets whether the horse has a chest equipped. + * + * @return true if the horse has chest storage + */ + boolean isCarryingChest(); + + /** + * Sets whether the horse has a chest equipped. + * Removing a chest will also clear the chest's inventory. + * + * @param chest true if the horse should have a chest + */ + void setCarryingChest(boolean chest); + + /** + * Gets the domestication level of this horse. + *

+ * A higher domestication level indicates that the horse is closer to + * becoming tame. As the domestication level gets closer to the max + * domestication level, the chance of the horse becoming tame increases. + * + * @return domestication level + */ + int getDomestication(); + + /** + * Sets the domestication level of this horse. + *

+ * Setting the domestication level to a high value will increase the + * horse's chances of becoming tame. + *

+ * Domestication level must be greater than zero and no greater than + * the max domestication level of the horse, determined with + * {@link #getMaxDomestication()} + * + * @param level domestication level + */ + void setDomestication(int level); + + /** + * Gets the maximum domestication level of this horse. + *

+ * The higher this level is, the longer it will likely take + * for the horse to be tamed. + * + * @return the max domestication level + */ + int getMaxDomestication(); + + /** + * Sets the maximum domestication level of this horse. + *

+ * Setting a higher max domestication will increase the amount of + * domesticating (feeding, riding, etc.) necessary in order to tame it, + * while setting a lower max value will have the opposite effect. + *

+ * Maximum domestication must be greater than zero. + * + * @param level the max domestication level + */ + void setMaxDomestication(int level); + + /** + * Gets the jump strength of this horse. + *

+ * Jump strength defines how high the horse can jump. A higher jump strength + * increases how high a jump will go. + * + * @return the horse's jump strength + */ + double getJumpStrength(); + + /** + * Sets the jump strength of this horse. + *

+ * A higher jump strength increases how high a jump will go. + * Setting a jump strength to 0 will result in no jump. + * You cannot set a jump strength to a value below 0 or + * above 2. + * + * @param strength jump strength for this horse + */ + void setJumpStrength(double strength); + + @Override + HorseInventory getInventory(); +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/HumanEntity.java b/azurite-api/src/main/java/org/bukkit/entity/HumanEntity.java new file mode 100644 index 0000000..76e9bd6 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/HumanEntity.java @@ -0,0 +1,173 @@ +package org.bukkit.entity; + +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.inventory.*; +import org.bukkit.permissions.Permissible; + +/** + * Represents a human entity, such as an NPC or a player + */ +public interface HumanEntity extends LivingEntity, AnimalTamer, Permissible, InventoryHolder { + + /** + * Returns the name of this player + * + * @return Player name + */ + String getName(); + + /** + * Get the player's inventory. + * + * @return The inventory of the player, this also contains the armor + * slots. + */ + PlayerInventory getInventory(); + + /** + * Get the player's EnderChest inventory + * + * @return The EnderChest of the player + */ + Inventory getEnderChest(); + + /** + * If the player currently has an inventory window open, this method will + * set a property of that window, such as the state of a progress bar. + * + * @param prop The property. + * @param value The value to set the property to. + * @return True if the property was successfully set. + */ + boolean setWindowProperty(InventoryView.Property prop, int value); + + /** + * Gets the inventory view the player is currently viewing. If they do not + * have an inventory window open, it returns their internal crafting view. + * + * @return The inventory view. + */ + InventoryView getOpenInventory(); + + /** + * Opens an inventory window with the specified inventory on the top and + * the player's inventory on the bottom. + * + * @param inventory The inventory to open + * @return The newly opened inventory view + */ + InventoryView openInventory(Inventory inventory); + + /** + * Opens an empty workbench inventory window with the player's inventory + * on the bottom. + * + * @param location The location to attach it to. If null, the player's + * location is used. + * @param force If false, and there is no workbench block at the location, + * no inventory will be opened and null will be returned. + * @return The newly opened inventory view, or null if it could not be + * opened. + */ + InventoryView openWorkbench(Location location, boolean force); + + /** + * Opens an empty enchanting inventory window with the player's inventory + * on the bottom. + * + * @param location The location to attach it to. If null, the player's + * location is used. + * @param force If false, and there is no enchanting table at the + * location, no inventory will be opened and null will be returned. + * @return The newly opened inventory view, or null if it could not be + * opened. + */ + InventoryView openEnchanting(Location location, boolean force); + + /** + * Opens an inventory window to the specified inventory view. + * + * @param inventory The view to open + */ + void openInventory(InventoryView inventory); + + /** + * Force-closes the currently open inventory view for this player, if any. + */ + void closeInventory(); + + /** + * Returns the ItemStack currently in your hand, can be empty. + * + * @return The ItemStack of the item you are currently holding. + */ + ItemStack getItemInHand(); + + /** + * Sets the item to the given ItemStack, this will replace whatever the + * user was holding. + * + * @param item The ItemStack which will end up in the hand + */ + void setItemInHand(ItemStack item); + + /** + * Returns the ItemStack currently on your cursor, can be empty. Will + * always be empty if the player currently has no open window. + * + * @return The ItemStack of the item you are currently moving around. + */ + ItemStack getItemOnCursor(); + + /** + * Sets the item to the given ItemStack, this will replace whatever the + * user was moving. Will always be empty if the player currently has no + * open window. + * + * @param item The ItemStack which will end up in the hand + */ + void setItemOnCursor(ItemStack item); + + /** + * Returns whether this player is slumbering. + * + * @return slumber state + */ + boolean isSleeping(); + + /** + * Get the sleep ticks of the player. This value may be capped. + * + * @return slumber ticks + */ + int getSleepTicks(); + + /** + * Gets this human's current {@link GameMode} + * + * @return Current game mode + */ + GameMode getGameMode(); + + /** + * Sets this human's current {@link GameMode} + * + * @param mode New game mode + */ + void setGameMode(GameMode mode); + + /** + * Check if the player is currently blocking (ie with a sword). + * + * @return Whether they are blocking. + */ + boolean isBlocking(); + + /** + * Get the total amount of experience required for the player to level + * + * @return Experience required to level up + */ + int getExpToLevel(); +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/IronGolem.java b/azurite-api/src/main/java/org/bukkit/entity/IronGolem.java new file mode 100644 index 0000000..1eee51a --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/IronGolem.java @@ -0,0 +1,22 @@ +package org.bukkit.entity; + +/** + * An iron Golem that protects Villages. + */ +public interface IronGolem extends Golem { + + /** + * Gets whether this iron golem was built by a player. + * + * @return Whether this iron golem was built by a player + */ + boolean isPlayerCreated(); + + /** + * Sets whether this iron golem was built by a player or not. + * + * @param playerCreated true if you want to set the iron golem as being + * player created, false if you want it to be a natural village golem. + */ + void setPlayerCreated(boolean playerCreated); +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Item.java b/azurite-api/src/main/java/org/bukkit/entity/Item.java new file mode 100644 index 0000000..8002f6a --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Item.java @@ -0,0 +1,41 @@ +package org.bukkit.entity; + +import org.bukkit.inventory.ItemStack; + +/** + * Represents an Item. + */ +public interface Item extends Entity { + + /** + * Gets the item stack associated with this item drop. + * + * @return An item stack. + */ + ItemStack getItemStack(); + + /** + * Sets the item stack associated with this item drop. + * + * @param stack An item stack. + */ + void setItemStack(ItemStack stack); + + /** + * Gets the delay before this Item is available to be picked up by players + * + * @return Remaining delay + */ + int getPickupDelay(); + + /** + * Sets the delay before this Item is available to be picked up by players + * + * @param delay New delay + */ + void setPickupDelay(int delay); + + Entity getOwner(); + + void setOwner(Entity paramEntity); +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/ItemFrame.java b/azurite-api/src/main/java/org/bukkit/entity/ItemFrame.java new file mode 100644 index 0000000..6af5ab9 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/ItemFrame.java @@ -0,0 +1,39 @@ +package org.bukkit.entity; + +import org.bukkit.Rotation; +import org.bukkit.inventory.ItemStack; + +/** + * Represents an Item Frame + */ +public interface ItemFrame extends Hanging { + + /** + * Get the item in this frame + * + * @return a defensive copy the item in this item frame + */ + ItemStack getItem(); + + /** + * Set the item in this frame + * + * @param item the new item + */ + void setItem(ItemStack item); + + /** + * Get the rotation of the frame's item + * + * @return the direction + */ + Rotation getRotation(); + + /** + * Set the rotation of the frame's item + * + * @param rotation the new rotation + * @throws IllegalArgumentException if rotation is null + */ + void setRotation(Rotation rotation) throws IllegalArgumentException; +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/LargeFireball.java b/azurite-api/src/main/java/org/bukkit/entity/LargeFireball.java new file mode 100644 index 0000000..fc3a109 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/LargeFireball.java @@ -0,0 +1,7 @@ +package org.bukkit.entity; + +/** + * Represents a large {@link Fireball} + */ +public interface LargeFireball extends Fireball { +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/LeashHitch.java b/azurite-api/src/main/java/org/bukkit/entity/LeashHitch.java new file mode 100644 index 0000000..9ac04c1 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/LeashHitch.java @@ -0,0 +1,7 @@ +package org.bukkit.entity; + +/** + * Represents a Leash Hitch on a fence + */ +public interface LeashHitch extends Hanging { +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/LightningStrike.java b/azurite-api/src/main/java/org/bukkit/entity/LightningStrike.java new file mode 100644 index 0000000..0966d77 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/LightningStrike.java @@ -0,0 +1,32 @@ +package org.bukkit.entity; + +/** + * Represents an instance of a lightning strike. May or may not do damage. + */ +public interface LightningStrike extends Weather { + + /** + * Returns whether the strike is an effect that does no damage. + * + * @return whether the strike is an effect + */ + boolean isEffect(); + + + class Spigot extends Entity.Spigot + { + + /* + * Returns whether the strike is silent. + * + * @return whether the strike is silent. + */ + public boolean isSilent() + { + throw new UnsupportedOperationException( "Not supported yet." ); + } + + } + + Spigot spigot(); +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/LivingEntity.java b/azurite-api/src/main/java/org/bukkit/entity/LivingEntity.java new file mode 100644 index 0000000..882a7ca --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/LivingEntity.java @@ -0,0 +1,355 @@ +package org.bukkit.entity; + +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.event.entity.PotionEffectAddEvent; +import org.bukkit.inventory.EntityEquipment; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.projectiles.ProjectileSource; + +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/** + * Represents a living entity, such as a monster or player + */ +public interface LivingEntity extends Entity, Damageable, ProjectileSource { + + /** + * Gets the height of the living entity's eyes above its Location. + * + * @return height of the living entity's eyes above its location + */ + double getEyeHeight(); + + /** + * Gets the height of the living entity's eyes above its Location. + * + * @param ignoreSneaking if set to true, the effects of sneaking will be + * ignored + * @return height of the living entity's eyes above its location + */ + double getEyeHeight(boolean ignoreSneaking); + + /** + * Get a Location detailing the current eye position of the living entity. + * + * @return a location at the eyes of the living entity + */ + Location getEyeLocation(); + + /** + * Gets all blocks along the living entity's line of sight. + *

+ * This list contains all blocks from the living entity's eye position to + * target inclusive. + * + * @param transparent HashSet containing all transparent block IDs (set to + * null for only air) + * @param maxDistance this is the maximum distance to scan (may be limited + * by server by at least 100 blocks, no less) + * @return list containing all blocks along the living entity's line of + * sight + * @deprecated Magic value + */ + @Deprecated + List getLineOfSight(HashSet transparent, int maxDistance); + + /** + * Gets all blocks along the living entity's line of sight. + *

+ * This list contains all blocks from the living entity's eye position to + * target inclusive. + * + * @param transparent HashSet containing all transparent block Materials (set to + * null for only air) + * @param maxDistance this is the maximum distance to scan (may be limited + * by server by at least 100 blocks, no less) + * @return list containing all blocks along the living entity's line of + * sight + */ + List getLineOfSight(Set transparent, int maxDistance); + + /** + * Gets the block that the living entity has targeted. + * + * @param transparent HashSet containing all transparent block IDs (set to + * null for only air) + * @param maxDistance this is the maximum distance to scan (may be limited + * by server by at least 100 blocks, no less) + * @return block that the living entity has targeted + * @deprecated Magic value + */ + @Deprecated + Block getTargetBlock(HashSet transparent, int maxDistance); + + /** + * Gets the block that the living entity has targeted. + * + * @param transparent HashSet containing all transparent block Materials (set to + * null for only air) + * @param maxDistance this is the maximum distance to scan (may be limited + * by server by at least 100 blocks, no less) + * @return block that the living entity has targeted + */ + Block getTargetBlock(Set transparent, int maxDistance); + + /** + * Gets the last two blocks along the living entity's line of sight. + *

+ * The target block will be the last block in the list. + * + * @param transparent HashSet containing all transparent block IDs (set to + * null for only air) + * @param maxDistance this is the maximum distance to scan. This may be + * further limited by the server, but never to less than 100 blocks + * @return list containing the last 2 blocks along the living entity's + * line of sight + * @deprecated Magic value + */ + @Deprecated + List getLastTwoTargetBlocks(HashSet transparent, int maxDistance); + + /** + * Gets the last two blocks along the living entity's line of sight. + *

+ * The target block will be the last block in the list. + * + * @param transparent HashSet containing all transparent block Materials (set to + * null for only air) + * @param maxDistance this is the maximum distance to scan. This may be + * further limited by the server, but never to less than 100 blocks + * @return list containing the last 2 blocks along the living entity's + * line of sight + */ + List getLastTwoTargetBlocks(Set transparent, int maxDistance); + + /** + * Throws an egg from the living entity. + * + * @return the egg thrown + * @deprecated use launchProjectile(Egg.class) instead + */ + @Deprecated + Egg throwEgg(); + + /** + * Throws a snowball from the living entity. + * + * @return the snowball thrown + * @deprecated use launchProjectile(Snowball.class) instead + */ + @Deprecated + Snowball throwSnowball(); + + /** + * Shoots an arrow from the living entity. + * + * @return the arrow shot + * @deprecated use launchProjectile(Arrow.class) instead + */ + @Deprecated + Arrow shootArrow(); + + /** + * Returns the amount of air that the living entity has remaining, in + * ticks. + * + * @return amount of air remaining + */ + int getRemainingAir(); + + /** + * Sets the amount of air that the living entity has remaining, in ticks. + * + * @param ticks amount of air remaining + */ + void setRemainingAir(int ticks); + + /** + * Returns the maximum amount of air the living entity can have, in ticks. + * + * @return maximum amount of air + */ + int getMaximumAir(); + + /** + * Sets the maximum amount of air the living entity can have, in ticks. + * + * @param ticks maximum amount of air + */ + void setMaximumAir(int ticks); + + /** + * Returns the living entity's current maximum no damage ticks. + *

+ * This is the maximum duration in which the living entity will not take + * damage. + * + * @return maximum no damage ticks + */ + int getMaximumNoDamageTicks(); + + /** + * Sets the living entity's current maximum no damage ticks. + * + * @param ticks maximum amount of no damage ticks + */ + void setMaximumNoDamageTicks(int ticks); + + /** + * Returns the living entity's last damage taken in the current no damage + * ticks time. + *

+ * Only damage higher than this amount will further damage the living + * entity. + * + * @return damage taken since the last no damage ticks time period + */ + double getLastDamage(); + + /** + * Sets the damage dealt within the current no damage ticks time period. + * + * @param damage amount of damage + */ + void setLastDamage(double damage); + + /** + * This method exists for legacy reasons to provide backwards + * compatibility. It will not exist at runtime and should not be used + * under any circumstances. + * + * @return damage taken since the last no damage ticks time period + */ + @Deprecated + int _INVALID_getLastDamage(); + + /** + * This method exists for legacy reasons to provide backwards + * compatibility. It will not exist at runtime and should not be used + * under any circumstances. + * + * @param damage amount of damage + */ + @Deprecated + void _INVALID_setLastDamage(int damage); + + /** + * Returns the living entity's current no damage ticks. + * + * @return amount of no damage ticks + */ + int getNoDamageTicks(); + + /** + * Sets the living entity's current no damage ticks. + * + * @param ticks amount of no damage ticks + */ + void setNoDamageTicks(int ticks); + + /** + * Gets the player identified as the killer of the living entity. + *

+ * May be null. + * + * @return killer player, or null if none found + */ + Player getKiller(); + + boolean addPotionEffect(PotionEffect paramPotionEffect); + + boolean addPotionEffect(PotionEffect paramPotionEffect, boolean paramBoolean); + + boolean addPotionEffect(PotionEffect paramPotionEffect, boolean paramBoolean, PotionEffectAddEvent.EffectCause paramEffectCause); + + boolean addPotionEffects(Collection paramCollection); + + boolean hasPotionEffect(PotionEffectType paramPotionEffectType); + + void removePotionEffect(PotionEffectType paramPotionEffectType); + + Collection getActivePotionEffects(); + + /** + * Checks whether the living entity has block line of sight to another. + *

+ * This uses the same algorithm that hostile mobs use to find the closest + * player. + * + * @param other the entity to determine line of sight to + * @return true if there is a line of sight, false if not + */ + boolean hasLineOfSight(Entity other); + + /** + * Returns if the living entity despawns when away from players or not. + *

+ * By default, animals are not removed while other mobs are. + * + * @return true if the living entity is removed when away from players + */ + boolean getRemoveWhenFarAway(); + + /** + * Sets whether or not the living entity despawns when away from players + * or not. + * + * @param remove the removal status + */ + void setRemoveWhenFarAway(boolean remove); + + /** + * Gets the inventory with the equipment worn by the living entity. + * + * @return the living entity's inventory + */ + EntityEquipment getEquipment(); + + /** + * Gets if the living entity can pick up items. + * + * @return whether or not the living entity can pick up items + */ + boolean getCanPickupItems(); + + /** + * Sets whether or not the living entity can pick up items. + * + * @param pickup whether or not the living entity can pick up items + */ + void setCanPickupItems(boolean pickup); + + /** + * Returns whether the entity is currently leashed. + * + * @return whether the entity is leashed + */ + boolean isLeashed(); + + /** + * Gets the entity that is currently leading this entity. + * + * @return the entity holding the leash + * @throws IllegalStateException if not currently leashed + */ + Entity getLeashHolder() throws IllegalStateException; + + /** + * Sets the leash on this entity to be held by the supplied entity. + *

+ * This method has no effect on EnderDragons, Withers, Players, or Bats. + * Non-living entities excluding leashes will not persist as leash + * holders. + * + * @param holder the entity to leash this entity to + * @return whether the operation was successful + */ + boolean setLeashHolder(Entity holder); + +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/MagmaCube.java b/azurite-api/src/main/java/org/bukkit/entity/MagmaCube.java new file mode 100644 index 0000000..714b442 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/MagmaCube.java @@ -0,0 +1,7 @@ +package org.bukkit.entity; + +/** + * Represents a MagmaCube. + */ +public interface MagmaCube extends Slime { +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Minecart.java b/azurite-api/src/main/java/org/bukkit/entity/Minecart.java new file mode 100644 index 0000000..fadbbff --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Minecart.java @@ -0,0 +1,143 @@ +package org.bukkit.entity; + +import org.bukkit.material.MaterialData; +import org.bukkit.util.Vector; + +/** + * Represents a minecart entity. + */ +public interface Minecart extends Vehicle { + + /** + * This method exists for legacy reasons to provide backwards + * compatibility. It will not exist at runtime and should not be used + * under any circumstances. + * + * @param damage over 40 to "kill" a minecart + */ + @Deprecated + void _INVALID_setDamage(int damage); + + /** + * Sets a minecart's damage. + * + * @param damage over 40 to "kill" a minecart + */ + void setDamage(double damage); + + /** + * This method exists for legacy reasons to provide backwards + * compatibility. It will not exist at runtime and should not be used + * under any circumstances. + * + * @return The damage + */ + @Deprecated + int _INVALID_getDamage(); + + /** + * Gets a minecart's damage. + * + * @return The damage + */ + double getDamage(); + + /** + * Gets the maximum speed of a minecart. The speed is unrelated to the + * velocity. + * + * @return The max speed + */ + double getMaxSpeed(); + + /** + * Sets the maximum speed of a minecart. Must be nonnegative. Default is + * 0.4D. + * + * @param speed The max speed + */ + void setMaxSpeed(double speed); + + /** + * Returns whether this minecart will slow down faster without a passenger + * occupying it + * + * @return Whether it decelerates faster + */ + boolean isSlowWhenEmpty(); + + /** + * Sets whether this minecart will slow down faster without a passenger + * occupying it + * + * @param slow Whether it will decelerate faster + */ + void setSlowWhenEmpty(boolean slow); + + /** + * Gets the flying velocity modifier. Used for minecarts that are in + * mid-air. A flying minecart's velocity is multiplied by this factor each + * tick. + * + * @return The vector factor + */ + Vector getFlyingVelocityMod(); + + /** + * Sets the flying velocity modifier. Used for minecarts that are in + * mid-air. A flying minecart's velocity is multiplied by this factor each + * tick. + * + * @param flying velocity modifier vector + */ + void setFlyingVelocityMod(Vector flying); + + /** + * Gets the derailed velocity modifier. Used for minecarts that are on the + * ground, but not on rails. + *

+ * A derailed minecart's velocity is multiplied by this factor each tick. + * + * @return derailed visible speed + */ + Vector getDerailedVelocityMod(); + + /** + * Sets the derailed velocity modifier. Used for minecarts that are on the + * ground, but not on rails. A derailed minecart's velocity is multiplied + * by this factor each tick. + * + * @param derailed visible speed + */ + void setDerailedVelocityMod(Vector derailed); + + /** + * Sets the display block for this minecart. + * Passing a null value will set the minecart to have no display block. + * + * @param material the material to set as display block. + */ + void setDisplayBlock(MaterialData material); + + /** + * Gets the display block for this minecart. + * This function will return the type AIR if none is set. + * + * @return the block displayed by this minecart. + */ + MaterialData getDisplayBlock(); + + /** + * Sets the offset of the display block. + * + * @param offset the block offset to set for this minecart. + */ + void setDisplayBlockOffset(int offset); + + /** + * Gets the offset of the display block. + * + * @return the current block offset for this minecart. + */ + int getDisplayBlockOffset(); +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Monster.java b/azurite-api/src/main/java/org/bukkit/entity/Monster.java new file mode 100644 index 0000000..fce2efd --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Monster.java @@ -0,0 +1,6 @@ +package org.bukkit.entity; + +/** + * Represents a Monster. + */ +public interface Monster extends Creature {} diff --git a/azurite-api/src/main/java/org/bukkit/entity/MushroomCow.java b/azurite-api/src/main/java/org/bukkit/entity/MushroomCow.java new file mode 100644 index 0000000..84154de --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/MushroomCow.java @@ -0,0 +1,8 @@ +package org.bukkit.entity; + +/** + * Represents a mushroom {@link Cow} + */ +public interface MushroomCow extends Cow { + +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/NPC.java b/azurite-api/src/main/java/org/bukkit/entity/NPC.java new file mode 100644 index 0000000..0c6b175 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/NPC.java @@ -0,0 +1,8 @@ +package org.bukkit.entity; + +/** + * Represents a non-player character + */ +public interface NPC extends Creature { + +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Ocelot.java b/azurite-api/src/main/java/org/bukkit/entity/Ocelot.java new file mode 100644 index 0000000..81e32f9 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Ocelot.java @@ -0,0 +1,83 @@ + +package org.bukkit.entity; + +/** + * A wild tameable cat + */ +public interface Ocelot extends Animals, Tameable { + + /** + * Gets the current type of this cat. + * + * @return Type of the cat. + */ + Type getCatType(); + + /** + * Sets the current type of this cat. + * + * @param type New type of this cat. + */ + void setCatType(Type type); + + /** + * Checks if this ocelot is sitting + * + * @return true if sitting + */ + boolean isSitting(); + + /** + * Sets if this ocelot is sitting. Will remove any path that the ocelot + * was following beforehand. + * + * @param sitting true if sitting + */ + void setSitting(boolean sitting); + + /** + * Represents the various different cat types there are. + */ + enum Type { + WILD_OCELOT(0), + BLACK_CAT(1), + RED_CAT(2), + SIAMESE_CAT(3); + + private static final Type[] types = new Type[Type.values().length]; + private final int id; + + static { + for (Type type : values()) { + types[type.getId()] = type; + } + } + + Type(int id) { + this.id = id; + } + + /** + * Gets the ID of this cat type. + * + * @return Type ID. + * @deprecated Magic value + */ + @Deprecated + public int getId() { + return id; + } + + /** + * Gets a cat type by its ID. + * + * @param id ID of the cat type to get. + * @return Resulting type, or null if not found. + * @deprecated Magic value + */ + @Deprecated + public static Type getType(int id) { + return (id >= types.length) ? null : types[id]; + } + } +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Painting.java b/azurite-api/src/main/java/org/bukkit/entity/Painting.java new file mode 100644 index 0000000..4c6d4ce --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Painting.java @@ -0,0 +1,39 @@ +package org.bukkit.entity; + +import org.bukkit.Art; +import org.bukkit.event.painting.PaintingBreakEvent; + +/** + * Represents a Painting. + */ +public interface Painting extends Hanging { + + /** + * Get the art on this painting + * + * @return The art + */ + Art getArt(); + + /** + * Set the art on this painting + * + * @param art The new art + * @return False if the new art won't fit at the painting's current + * location + */ + boolean setArt(Art art); + + /** + * Set the art on this painting + * + * @param art The new art + * @param force If true, force the new art regardless of whether it fits + * at the current location. Note that forcing it where it can't fit + * normally causes it to drop as an item unless you override this by + * catching the {@link PaintingBreakEvent}. + * @return False if force was false and the new art won't fit at the + * painting's current location + */ + boolean setArt(Art art, boolean force); +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Pig.java b/azurite-api/src/main/java/org/bukkit/entity/Pig.java new file mode 100644 index 0000000..ec3d217 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Pig.java @@ -0,0 +1,21 @@ +package org.bukkit.entity; + +/** + * Represents a Pig. + */ +public interface Pig extends Animals, Vehicle { + + /** + * Check if the pig has a saddle. + * + * @return if the pig has been saddled. + */ + boolean hasSaddle(); + + /** + * Sets if the pig has a saddle or not + * + * @param saddled set if the pig has a saddle or not. + */ + void setSaddle(boolean saddled); +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/PigZombie.java b/azurite-api/src/main/java/org/bukkit/entity/PigZombie.java new file mode 100644 index 0000000..2f08672 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/PigZombie.java @@ -0,0 +1,36 @@ +package org.bukkit.entity; + +/** + * Represents a Pig Zombie. + */ +public interface PigZombie extends Zombie { + + /** + * Get the pig zombie's current anger level. + * + * @return The anger level. + */ + int getAnger(); + + /** + * Set the pig zombie's current anger level. + * + * @param level The anger level. Higher levels of anger take longer to + * wear off. + */ + void setAnger(int level); + + /** + * Shorthand; sets to either 0 or the default level. + * + * @param angry Whether the zombie should be angry. + */ + void setAngry(boolean angry); + + /** + * Shorthand; gets whether the zombie is angry. + * + * @return True if the zombie is angry, otherwise false. + */ + boolean isAngry(); +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Player.java b/azurite-api/src/main/java/org/bukkit/entity/Player.java new file mode 100644 index 0000000..8e774b0 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Player.java @@ -0,0 +1,1334 @@ +package org.bukkit.entity; + +import dev.azurite.spigot.api.knockback.IKnockback; +import org.bukkit.*; +import org.bukkit.command.CommandSender; +import org.bukkit.conversations.Conversable; +import org.bukkit.map.MapView; +import org.bukkit.plugin.messaging.PluginMessageRecipient; +import org.bukkit.scoreboard.Scoreboard; +import org.github.paperspigot.Title; + +import java.net.InetSocketAddress; + +/** + * Represents a player, connected or not + */ +public interface Player extends HumanEntity, Conversable, CommandSender, OfflinePlayer, PluginMessageRecipient { + + /** + * Gets the "friendly" name to display of this player. This may include + * color. + *

+ * Note that this name will not be displayed in game, only in chat and + * places defined by plugins. + * + * @return the friendly name + */ + String getDisplayName(); + + void sendPacket(Object packet); + + // Azurite start + void setKnockbackProfile(IKnockback knockbackProfile); + + IKnockback getKnockbackProfile(); + // Azurite end + + void sendActionBar(String message); + + int getPing(); + + /** + * Sets the "friendly" name to display of this player. This may include + * color. + *

+ * Note that this name will not be displayed in game, only in chat and + * places defined by plugins. + * + * @param name The new display name. + */ + void setDisplayName(String name); + + /** + * Gets the name that is shown on the player list. + * + * @return the player list name + */ + String getPlayerListName(); + + /** + * Sets the name that is shown on the in-game player list. + *

+ * The name cannot be longer than 16 characters, but {@link ChatColor} is + * supported. + *

+ * If the value is null, the name will be identical to {@link #getName()}. + *

+ * This name is case sensitive and unique, two names with different casing + * will appear as two different people. If a player joins afterwards with + * a name that conflicts with a player's custom list name, the joining + * player's player list name will have a random number appended to it (1-2 + * characters long in the default implementation). If the joining player's + * name is 15 or 16 characters long, part of the name will be truncated at + * the end to allow the addition of the two digits. + * + * @param name new player list name + * @throws IllegalArgumentException if the name is already used by someone + * else + * @throws IllegalArgumentException if the length of the name is too long + */ + void setPlayerListName(String name); + + /** + * Set the target of the player's compass. + * + * @param loc Location to point to + */ + void setCompassTarget(Location loc); + + /** + * Get the previously set compass target. + * + * @return location of the target + */ + Location getCompassTarget(); + + /** + * Gets the socket address of this player + * + * @return the player's address + */ + InetSocketAddress getAddress(); + + /** + * Sends this sender a message raw + * + * @param message Message to be displayed + */ + void sendRawMessage(String message); + + /** + * Kicks player with custom kick message. + * + * @param message kick message + */ + void kickPlayer(String message); + + /** + * Says a message (or runs a command). + * + * @param msg message to print + */ + void chat(String msg); + + /** + * Makes the player perform the given command + * + * @param command Command to perform + * @return true if the command was successful, otherwise false + */ + boolean performCommand(String command); + + /** + * Returns if the player is in sneak mode + * + * @return true if player is in sneak mode + */ + boolean isSneaking(); + + /** + * Sets the sneak mode the player + * + * @param sneak true if player should appear sneaking + */ + void setSneaking(boolean sneak); + + /** + * Gets whether the player is sprinting or not. + * + * @return true if player is sprinting. + */ + boolean isSprinting(); + + /** + * Sets whether the player is sprinting or not. + * + * @param sprinting true if the player should be sprinting + */ + void setSprinting(boolean sprinting); + + /** + * Saves the players current location, health, inventory, motion, and + * other information into the username.dat file, in the world/player + * folder + */ + void saveData(); + + /** + * Loads the players current location, health, inventory, motion, and + * other information from the username.dat file, in the world/player + * folder. + *

+ * Note: This will overwrite the players current inventory, health, + * motion, etc, with the state from the saved dat file. + */ + void loadData(); + + /** + * Sets whether the player is ignored as not sleeping. If everyone is + * either sleeping or has this flag set, then time will advance to the + * next day. If everyone has this flag set but no one is actually in bed, + * then nothing will happen. + * + * @param isSleeping Whether to ignore. + */ + void setSleepingIgnored(boolean isSleeping); + + /** + * Returns whether the player is sleeping ignored. + * + * @return Whether player is ignoring sleep. + */ + boolean isSleepingIgnored(); + + /** + * Play a note for a player at a location. This requires a note block + * at the particular location (as far as the client is concerned). This + * will not work without a note block. This will not work with cake. + * + * @param loc The location of a note block. + * @param instrument The instrument ID. + * @param note The note ID. + * @deprecated Magic value + */ + @Deprecated + void playNote(Location loc, byte instrument, byte note); + + /** + * Play a note for a player at a location. This requires a note block + * at the particular location (as far as the client is concerned). This + * will not work without a note block. This will not work with cake. + * + * @param loc The location of a note block + * @param instrument The instrument + * @param note The note + */ + void playNote(Location loc, Instrument instrument, Note note); + + + /** + * Play a sound for a player at the location. + *

+ * This function will fail silently if Location or Sound are null. + * + * @param location The location to play the sound + * @param sound The sound to play + * @param volume The volume of the sound + * @param pitch The pitch of the sound + */ + void playSound(Location location, Sound sound, float volume, float pitch); + + /** + * Play a sound for a player at the location. + *

+ * This function will fail silently if Location or Sound are null. No + * sound will be heard by the player if their client does not have the + * respective sound for the value passed. + * + * @param location the location to play the sound + * @param sound the internal sound name to play + * @param volume the volume of the sound + * @param pitch the pitch of the sound + */ + void playSound(Location location, String sound, float volume, float pitch); + + default void playSound(Sound sound, float volume, float pitch) { + playSound(getLocation(), sound, volume, pitch); + } + + /** + * Plays an effect to just this player. + * + * @param loc the location to play the effect at + * @param effect the {@link Effect} + * @param data a data bit needed for some effects + * @deprecated Magic value + */ + @Deprecated + void playEffect(Location loc, Effect effect, int data); + + /** + * Plays an effect to just this player. + * + * @param the data based based on the type of the effect + * @param loc the location to play the effect at + * @param effect the {@link Effect} + * @param data a data bit needed for some effects + */ + void playEffect(Location loc, Effect effect, T data); + + /** + * Send a block change. This fakes a block change packet for a user at a + * certain location. This will not actually change the world in any way. + * + * @param loc The location of the changed block + * @param material The new block + * @param data The block data + * @deprecated Magic value + */ + @Deprecated + void sendBlockChange(Location loc, Material material, byte data); + + /** + * Send a chunk change. This fakes a chunk change packet for a user at a + * certain location. The updated cuboid must be entirely within a single + * chunk. This will not actually change the world in any way. + *

+ * At least one of the dimensions of the cuboid must be even. The size of + * the data buffer must be 2.5*sx*sy*sz and formatted in accordance with + * the Packet51 format. + * + * @param loc The location of the cuboid + * @param sx The x size of the cuboid + * @param sy The y size of the cuboid + * @param sz The z size of the cuboid + * @param data The data to be sent + * @return true if the chunk change packet was sent + * @deprecated Magic value + */ + @Deprecated + boolean sendChunkChange(Location loc, int sx, int sy, int sz, byte[] data); + + /** + * Send a block change. This fakes a block change packet for a user at a + * certain location. This will not actually change the world in any way. + * + * @param loc The location of the changed block + * @param material The new block ID + * @param data The block data + * @deprecated Magic value + */ + @Deprecated + void sendBlockChange(Location loc, int material, byte data); + + /** + * Send a sign change. This fakes a sign change packet for a user at + * a certain location. This will not actually change the world in any way. + * This method will use a sign at the location's block or a faked sign + * sent via {@link #sendBlockChange(Location, int, byte)} or + * {@link #sendBlockChange(Location, Material, byte)}. + *

+ * If the client does not have a sign at the given location it will + * display an error message to the user. + * + * @param loc the location of the sign + * @param lines the new text on the sign or null to clear it + * @throws IllegalArgumentException if location is null + * @throws IllegalArgumentException if lines is non-null and has a length less than 4 + */ + void sendSignChange(Location loc, String[] lines) throws IllegalArgumentException; + + /** + * Render a map and send it to the player in its entirety. This may be + * used when streaming the map in the normal manner is not desirable. + * + * @param map The map to be sent + */ + void sendMap(MapView map); + + // Paper start + + /** + * Sends the component to the player + * + * @param component the components to send + */ + @Override + void sendMessage(net.md_5.bungee.api.chat.BaseComponent component); + + /** + * Sends an array of components as a single message to the player + * + * @param components the components to send + */ + @Override + void sendMessage(net.md_5.bungee.api.chat.BaseComponent... components); + + /** + * Set the text displayed in the player list header and footer for this player + * + * @param header content for the top of the player list + * @param footer content for the bottom of the player list + */ + void setPlayerListHeaderFooter(net.md_5.bungee.api.chat.BaseComponent[] header, net.md_5.bungee.api.chat.BaseComponent[] footer); + + /** + * Set the text displayed in the player list header and footer for this player + * + * @param header content for the top of the player list + * @param footer content for the bottom of the player list + */ + void setPlayerListHeaderFooter(net.md_5.bungee.api.chat.BaseComponent header, net.md_5.bungee.api.chat.BaseComponent footer); + + /** + * Update the times for titles displayed to the player + * + * @param fadeInTicks ticks to fade-in + * @param stayTicks ticks to stay visible + * @param fadeOutTicks ticks to fade-out + * @deprecated Use {@link #updateTitle(Title)} + */ + @Deprecated + void setTitleTimes(int fadeInTicks, int stayTicks, int fadeOutTicks); + + /** + * Update the subtitle of titles displayed to the player + * + * @deprecated Use {@link #updateTitle(Title)} + */ + @Deprecated + void setSubtitle(net.md_5.bungee.api.chat.BaseComponent[] subtitle); + + /** + * Update the subtitle of titles displayed to the player + * + * @deprecated Use {@link #updateTitle(Title)} + */ + @Deprecated + void setSubtitle(net.md_5.bungee.api.chat.BaseComponent subtitle); + + /** + * Show the given title to the player, along with the last subtitle set, using the last set times + * + * @deprecated Use {@link #sendTitle(Title)} or {@link #updateTitle(Title)} + */ + @Deprecated + void showTitle(net.md_5.bungee.api.chat.BaseComponent[] title); + + /** + * Show the given title to the player, along with the last subtitle set, using the last set times + * + * @deprecated Use {@link #sendTitle(Title)} or {@link #updateTitle(Title)} + */ + @Deprecated + void showTitle(net.md_5.bungee.api.chat.BaseComponent title); + + /** + * Show the given title and subtitle to the player using the given times + * + * @param title big text + * @param subtitle little text under it + * @param fadeInTicks ticks to fade-in + * @param stayTicks ticks to stay visible + * @param fadeOutTicks ticks to fade-out + * @deprecated Use {@link #sendTitle(Title)} or {@link #updateTitle(Title)} + */ + @Deprecated + void showTitle(net.md_5.bungee.api.chat.BaseComponent[] title, net.md_5.bungee.api.chat.BaseComponent[] subtitle, int fadeInTicks, int stayTicks, int fadeOutTicks); + + /** + * Show the given title and subtitle to the player using the given times + * + * @param title big text + * @param subtitle little text under it + * @param fadeInTicks ticks to fade-in + * @param stayTicks ticks to stay visible + * @param fadeOutTicks ticks to fade-out + * @deprecated Use {@link #sendTitle(Title)} or {@link #updateTitle(Title)} + */ + @Deprecated + void showTitle(net.md_5.bungee.api.chat.BaseComponent title, net.md_5.bungee.api.chat.BaseComponent subtitle, int fadeInTicks, int stayTicks, int fadeOutTicks); + + /** + * Show the title to the player, overriding any previously displayed title. + * + *

This method overrides any previous title, use {@link #updateTitle(Title)} to change the existing one.

+ * + * @param title the title to send + * @throws NullPointerException if the title is null + */ + void sendTitle(Title title); + + /** + * Show the title to the player, overriding any previously displayed title. + * + *

This method doesn't override previous titles, but changes their values.

+ * + * @param title the title to send + * @throws NullPointerException if title is null + */ + void updateTitle(Title title); + + /** + * Hide any title that is currently visible to the player + */ + void hideTitle(); + // Paper end + + /** + * Forces an update of the player's entire inventory. + */ + //@Deprecated // Spigot - undeprecate + void updateInventory(); + + /** + * Awards the given achievement and any parent achievements that the + * player does not have. + * + * @param achievement Achievement to award + * @throws IllegalArgumentException if achievement is null + */ + void awardAchievement(Achievement achievement); + + /** + * Removes the given achievement and any children achievements that the + * player has. + * + * @param achievement Achievement to remove + * @throws IllegalArgumentException if achievement is null + */ + void removeAchievement(Achievement achievement); + + /** + * Gets whether this player has the given achievement. + * + * @param achievement the achievement to check + * @return whether the player has the achievement + * @throws IllegalArgumentException if achievement is null + */ + boolean hasAchievement(Achievement achievement); + + /** + * Increments the given statistic for this player. + *

+ * This is equivalent to the following code: + * incrementStatistic(Statistic, 1) + * + * @param statistic Statistic to increment + * @throws IllegalArgumentException if statistic is null + * @throws IllegalArgumentException if the statistic requires an + * additional parameter + */ + void incrementStatistic(Statistic statistic) throws IllegalArgumentException; + + /** + * Decrements the given statistic for this player. + *

+ * This is equivalent to the following code: + * decrementStatistic(Statistic, 1) + * + * @param statistic Statistic to decrement + * @throws IllegalArgumentException if statistic is null + * @throws IllegalArgumentException if the statistic requires an + * additional parameter + */ + void decrementStatistic(Statistic statistic) throws IllegalArgumentException; + + /** + * Increments the given statistic for this player. + * + * @param statistic Statistic to increment + * @param amount Amount to increment this statistic by + * @throws IllegalArgumentException if statistic is null + * @throws IllegalArgumentException if amount is negative + * @throws IllegalArgumentException if the statistic requires an + * additional parameter + */ + void incrementStatistic(Statistic statistic, int amount) throws IllegalArgumentException; + + /** + * Decrements the given statistic for this player. + * + * @param statistic Statistic to decrement + * @param amount Amount to decrement this statistic by + * @throws IllegalArgumentException if statistic is null + * @throws IllegalArgumentException if amount is negative + * @throws IllegalArgumentException if the statistic requires an + * additional parameter + */ + void decrementStatistic(Statistic statistic, int amount) throws IllegalArgumentException; + + /** + * Sets the given statistic for this player. + * + * @param statistic Statistic to set + * @param newValue The value to set this statistic to + * @throws IllegalArgumentException if statistic is null + * @throws IllegalArgumentException if newValue is negative + * @throws IllegalArgumentException if the statistic requires an + * additional parameter + */ + void setStatistic(Statistic statistic, int newValue) throws IllegalArgumentException; + + /** + * Gets the value of the given statistic for this player. + * + * @param statistic Statistic to check + * @return the value of the given statistic + * @throws IllegalArgumentException if statistic is null + * @throws IllegalArgumentException if the statistic requires an + * additional parameter + */ + int getStatistic(Statistic statistic) throws IllegalArgumentException; + + /** + * Increments the given statistic for this player for the given material. + *

+ * This is equivalent to the following code: + * incrementStatistic(Statistic, Material, 1) + * + * @param statistic Statistic to increment + * @param material Material to offset the statistic with + * @throws IllegalArgumentException if statistic is null + * @throws IllegalArgumentException if material is null + * @throws IllegalArgumentException if the given parameter is not valid + * for the statistic + */ + void incrementStatistic(Statistic statistic, Material material) throws IllegalArgumentException; + + /** + * Decrements the given statistic for this player for the given material. + *

+ * This is equivalent to the following code: + * decrementStatistic(Statistic, Material, 1) + * + * @param statistic Statistic to decrement + * @param material Material to offset the statistic with + * @throws IllegalArgumentException if statistic is null + * @throws IllegalArgumentException if material is null + * @throws IllegalArgumentException if the given parameter is not valid + * for the statistic + */ + void decrementStatistic(Statistic statistic, Material material) throws IllegalArgumentException; + + /** + * Gets the value of the given statistic for this player. + * + * @param statistic Statistic to check + * @param material Material offset of the statistic + * @return the value of the given statistic + * @throws IllegalArgumentException if statistic is null + * @throws IllegalArgumentException if material is null + * @throws IllegalArgumentException if the given parameter is not valid + * for the statistic + */ + int getStatistic(Statistic statistic, Material material) throws IllegalArgumentException; + + /** + * Increments the given statistic for this player for the given material. + * + * @param statistic Statistic to increment + * @param material Material to offset the statistic with + * @param amount Amount to increment this statistic by + * @throws IllegalArgumentException if statistic is null + * @throws IllegalArgumentException if material is null + * @throws IllegalArgumentException if amount is negative + * @throws IllegalArgumentException if the given parameter is not valid + * for the statistic + */ + void incrementStatistic(Statistic statistic, Material material, int amount) throws IllegalArgumentException; + + /** + * Decrements the given statistic for this player for the given material. + * + * @param statistic Statistic to decrement + * @param material Material to offset the statistic with + * @param amount Amount to decrement this statistic by + * @throws IllegalArgumentException if statistic is null + * @throws IllegalArgumentException if material is null + * @throws IllegalArgumentException if amount is negative + * @throws IllegalArgumentException if the given parameter is not valid + * for the statistic + */ + void decrementStatistic(Statistic statistic, Material material, int amount) throws IllegalArgumentException; + + /** + * Sets the given statistic for this player for the given material. + * + * @param statistic Statistic to set + * @param material Material to offset the statistic with + * @param newValue The value to set this statistic to + * @throws IllegalArgumentException if statistic is null + * @throws IllegalArgumentException if material is null + * @throws IllegalArgumentException if newValue is negative + * @throws IllegalArgumentException if the given parameter is not valid + * for the statistic + */ + void setStatistic(Statistic statistic, Material material, int newValue) throws IllegalArgumentException; + + /** + * Increments the given statistic for this player for the given entity. + *

+ * This is equivalent to the following code: + * incrementStatistic(Statistic, EntityType, 1) + * + * @param statistic Statistic to increment + * @param entityType EntityType to offset the statistic with + * @throws IllegalArgumentException if statistic is null + * @throws IllegalArgumentException if entityType is null + * @throws IllegalArgumentException if the given parameter is not valid + * for the statistic + */ + void incrementStatistic(Statistic statistic, EntityType entityType) throws IllegalArgumentException; + + /** + * Decrements the given statistic for this player for the given entity. + *

+ * This is equivalent to the following code: + * decrementStatistic(Statistic, EntityType, 1) + * + * @param statistic Statistic to decrement + * @param entityType EntityType to offset the statistic with + * @throws IllegalArgumentException if statistic is null + * @throws IllegalArgumentException if entityType is null + * @throws IllegalArgumentException if the given parameter is not valid + * for the statistic + */ + void decrementStatistic(Statistic statistic, EntityType entityType) throws IllegalArgumentException; + + /** + * Gets the value of the given statistic for this player. + * + * @param statistic Statistic to check + * @param entityType EntityType offset of the statistic + * @return the value of the given statistic + * @throws IllegalArgumentException if statistic is null + * @throws IllegalArgumentException if entityType is null + * @throws IllegalArgumentException if the given parameter is not valid + * for the statistic + */ + int getStatistic(Statistic statistic, EntityType entityType) throws IllegalArgumentException; + + /** + * Increments the given statistic for this player for the given entity. + * + * @param statistic Statistic to increment + * @param entityType EntityType to offset the statistic with + * @param amount Amount to increment this statistic by + * @throws IllegalArgumentException if statistic is null + * @throws IllegalArgumentException if entityType is null + * @throws IllegalArgumentException if amount is negative + * @throws IllegalArgumentException if the given parameter is not valid + * for the statistic + */ + void incrementStatistic(Statistic statistic, EntityType entityType, int amount) throws IllegalArgumentException; + + /** + * Decrements the given statistic for this player for the given entity. + * + * @param statistic Statistic to decrement + * @param entityType EntityType to offset the statistic with + * @param amount Amount to decrement this statistic by + * @throws IllegalArgumentException if statistic is null + * @throws IllegalArgumentException if entityType is null + * @throws IllegalArgumentException if amount is negative + * @throws IllegalArgumentException if the given parameter is not valid + * for the statistic + */ + void decrementStatistic(Statistic statistic, EntityType entityType, int amount); + + /** + * Sets the given statistic for this player for the given entity. + * + * @param statistic Statistic to set + * @param entityType EntityType to offset the statistic with + * @param newValue The value to set this statistic to + * @throws IllegalArgumentException if statistic is null + * @throws IllegalArgumentException if entityType is null + * @throws IllegalArgumentException if newValue is negative + * @throws IllegalArgumentException if the given parameter is not valid + * for the statistic + */ + void setStatistic(Statistic statistic, EntityType entityType, int newValue); + + /** + * Sets the current time on the player's client. When relative is true the + * player's time will be kept synchronized to its world time with the + * specified offset. + *

+ * When using non relative time the player's time will stay fixed at the + * specified time parameter. It's up to the caller to continue updating + * the player's time. To restore player time to normal use + * resetPlayerTime(). + * + * @param time The current player's perceived time or the player's time + * offset from the server time. + * @param relative When true the player time is kept relative to its world + * time. + */ + void setPlayerTime(long time, boolean relative); + + /** + * Returns the player's current timestamp. + * + * @return The player's time + */ + long getPlayerTime(); + + /** + * Returns the player's current time offset relative to server time, or + * the current player's fixed time if the player's time is absolute. + * + * @return The player's time + */ + long getPlayerTimeOffset(); + + /** + * Returns true if the player's time is relative to the server time, + * otherwise the player's time is absolute and will not change its current + * time unless done so with setPlayerTime(). + * + * @return true if the player's time is relative to the server time. + */ + boolean isPlayerTimeRelative(); + + /** + * Restores the normal condition where the player's time is synchronized + * with the server time. + *

+ * Equivalent to calling setPlayerTime(0, true). + */ + void resetPlayerTime(); + + /** + * Sets the type of weather the player will see. When used, the weather + * status of the player is locked until {@link #resetPlayerWeather()} is + * used. + * + * @param type The WeatherType enum type the player should experience + */ + void setPlayerWeather(WeatherType type); + + /** + * Returns the type of weather the player is currently experiencing. + * + * @return The WeatherType that the player is currently experiencing or + * null if player is seeing server weather. + */ + WeatherType getPlayerWeather(); + + /** + * Restores the normal condition where the player's weather is controlled + * by server conditions. + */ + void resetPlayerWeather(); + + /** + * Gives the player the amount of experience specified. + * + * @param amount Exp amount to give + */ + void giveExp(int amount); + + /** + * Gives the player the amount of experience levels specified. Levels can + * be taken by specifying a negative amount. + * + * @param amount amount of experience levels to give or take + */ + void giveExpLevels(int amount); + + /** + * Gets the players current experience points towards the next level. + *

+ * This is a percentage value. 0 is "no progress" and 1 is "next level". + * + * @return Current experience points + */ + float getExp(); + + /** + * Sets the players current experience points towards the next level + *

+ * This is a percentage value. 0 is "no progress" and 1 is "next level". + * + * @param exp New experience points + */ + void setExp(float exp); + + /** + * Gets the players current experience level + * + * @return Current experience level + */ + int getLevel(); + + /** + * Sets the players current experience level + * + * @param level New experience level + */ + void setLevel(int level); + + /** + * Gets the players total experience points + * + * @return Current total experience points + */ + int getTotalExperience(); + + /** + * Sets the players current experience level + * + * @param exp New experience level + */ + void setTotalExperience(int exp); + + /** + * Gets the players current exhaustion level. + *

+ * Exhaustion controls how fast the food level drops. While you have a + * certain amount of exhaustion, your saturation will drop to zero, and + * then your food will drop to zero. + * + * @return Exhaustion level + */ + float getExhaustion(); + + /** + * Sets the players current exhaustion level + * + * @param value Exhaustion level + */ + void setExhaustion(float value); + + /** + * Gets the players current saturation level. + *

+ * Saturation is a buffer for food level. Your food level will not drop if + * you are saturated {@literal >} 0. + * + * @return Saturation level + */ + float getSaturation(); + + /** + * Sets the players current saturation level + * + * @param value Saturation level + */ + void setSaturation(float value); + + /** + * Gets the players current food level + * + * @return Food level + */ + int getFoodLevel(); + + /** + * Sets the players current food level + * + * @param value New food level + */ + void setFoodLevel(int value); + + /** + * Gets the Location where the player will spawn at their bed, null if + * they have not slept in one or their current bed spawn is invalid. + * + * @return Bed Spawn Location if bed exists, otherwise null. + */ + Location getBedSpawnLocation(); + + /** + * Sets the Location where the player will spawn at their bed. + * + * @param location where to set the respawn location + */ + void setBedSpawnLocation(Location location); + + /** + * Sets the Location where the player will spawn at their bed. + * + * @param location where to set the respawn location + * @param force whether to forcefully set the respawn location even if a + * valid bed is not present + */ + void setBedSpawnLocation(Location location, boolean force); + + /** + * Determines if the Player is allowed to fly via jump key double-tap like + * in creative mode. + * + * @return True if the player is allowed to fly. + */ + boolean getAllowFlight(); + + /** + * Sets if the Player is allowed to fly via jump key double-tap like in + * creative mode. + * + * @param flight If flight should be allowed. + */ + void setAllowFlight(boolean flight); + + /** + * Hides a player from this player + * + * @param player Player to hide + */ + void hidePlayer(Player player); + + /** + * Allows this player to see a player that was previously hidden + * + * @param player Player to show + */ + void showPlayer(Player player); + + /** + * Checks to see if a player has been hidden from this player + * + * @param player Player to check + * @return True if the provided player is not being hidden from this + * player + */ + boolean canSee(Player player); + + /** + * Checks to see if this player is currently standing on a block. This + * information may not be reliable, as it is a state provided by the + * client, and may therefore not be accurate. + * + * @return True if the player standing on a solid block, else false. + * @deprecated Inconsistent with {@link + * Entity#isOnGround()} + */ + @Deprecated + boolean isOnGround(); + + /** + * Checks to see if this player is currently flying or not. + * + * @return True if the player is flying, else false. + */ + boolean isFlying(); + + /** + * Makes this player start or stop flying. + * + * @param value True to fly. + */ + void setFlying(boolean value); + + /** + * Sets the speed at which a client will fly. Negative values indicate + * reverse directions. + * + * @param value The new speed, from -1 to 1. + * @throws IllegalArgumentException If new speed is less than -1 or + * greater than 1 + */ + void setFlySpeed(float value) throws IllegalArgumentException; + + /** + * Sets the speed at which a client will walk. Negative values indicate + * reverse directions. + * + * @param value The new speed, from -1 to 1. + * @throws IllegalArgumentException If new speed is less than -1 or + * greater than 1 + */ + void setWalkSpeed(float value) throws IllegalArgumentException; + + /** + * Gets the current allowed speed that a client can fly. + * + * @return The current allowed speed, from -1 to 1 + */ + float getFlySpeed(); + + /** + * Gets the current allowed speed that a client can walk. + * + * @return The current allowed speed, from -1 to 1 + */ + float getWalkSpeed(); + + /** + * Request that the player's client download and switch texture packs. + *

+ * The player's client will download the new texture pack asynchronously + * in the background, and will automatically switch to it once the + * download is complete. If the client has downloaded and cached the same + * texture pack in the past, it will perform a quick timestamp check over + * the network to determine if the texture pack has changed and needs to + * be downloaded again. When this request is sent for the very first time + * from a given server, the client will first display a confirmation GUI + * to the player before proceeding with the download. + *

+ * Notes: + *

    + *
  • Players can disable server textures on their client, in which + * case this method will have no affect on them. + *
  • There is no concept of resetting texture packs back to default + * within Minecraft, so players will have to relog to do so. + *
+ * + * @param url The URL from which the client will download the texture + * pack. The string must contain only US-ASCII characters and should + * be encoded as per RFC 1738. + * @throws IllegalArgumentException Thrown if the URL is null. + * @throws IllegalArgumentException Thrown if the URL is too long. + * @deprecated Minecraft no longer uses textures packs. Instead you + * should use {@link #setResourcePack(String)}. + */ + @Deprecated + void setTexturePack(String url); + + /** + * Request that the player's client download and switch resource packs. + *

+ * The player's client will download the new resource pack asynchronously + * in the background, and will automatically switch to it once the + * download is complete. If the client has downloaded and cached the same + * resource pack in the past, it will perform a quick timestamp check + * over the network to determine if the resource pack has changed and + * needs to be downloaded again. When this request is sent for the very + * first time from a given server, the client will first display a + * confirmation GUI to the player before proceeding with the download. + *

+ * Notes: + *

    + *
  • Players can disable server resources on their client, in which + * case this method will have no affect on them. + *
  • There is no concept of resetting resource packs back to default + * within Minecraft, so players will have to relog to do so. + *
+ * + * @param url The URL from which the client will download the resource + * pack. The string must contain only US-ASCII characters and should + * be encoded as per RFC 1738. + * @throws IllegalArgumentException Thrown if the URL is null. + * @throws IllegalArgumentException Thrown if the URL is too long. The + * length restriction is an implementation specific arbitrary value. + * @deprecated use + */ + @Deprecated + // TacoSpigot + void setResourcePack(String url); + + /** + * Gets the Scoreboard displayed to this player + * + * @return The current scoreboard seen by this player + */ + Scoreboard getScoreboard(); + + /** + * Sets the player's visible Scoreboard. + * + * @param scoreboard New Scoreboard for the player + * @throws IllegalArgumentException if scoreboard is null + * @throws IllegalArgumentException if scoreboard was not created by the + * {@link org.bukkit.scoreboard.ScoreboardManager scoreboard manager} + * @throws IllegalStateException if this is a player that is not logged + * yet or has logged out + */ + void setScoreboard(Scoreboard scoreboard) throws IllegalArgumentException, IllegalStateException; + + /** + * Gets if the client is displayed a 'scaled' health, that is, health on a + * scale from 0-{@link #getHealthScale()}. + * + * @return if client health display is scaled + * @see Player#setHealthScaled(boolean) + */ + boolean isHealthScaled(); + + /** + * Sets if the client is displayed a 'scaled' health, that is, health on a + * scale from 0-{@link #getHealthScale()}. + *

+ * Displayed health follows a simple formula displayedHealth = + * getHealth() / getMaxHealth() * getHealthScale(). + * + * @param scale if the client health display is scaled + */ + void setHealthScaled(boolean scale); + + /** + * Sets the number to scale health to for the client; this will also + * {@link #setHealthScaled(boolean) setHealthScaled(true)}. + *

+ * Displayed health follows a simple formula displayedHealth = + * getHealth() / getMaxHealth() * getHealthScale(). + * + * @param scale the number to scale health to + * @throws IllegalArgumentException if scale is <0 + * @throws IllegalArgumentException if scale is {@link Double#NaN} + * @throws IllegalArgumentException if scale is too high + */ + void setHealthScale(double scale) throws IllegalArgumentException; + + /** + * Gets the number that health is scaled to for the client. + * + * @return the number that health would be scaled to for the client if + * HealthScaling is set to true + * @see Player#setHealthScale(double) + * @see Player#setHealthScaled(boolean) + */ + double getHealthScale(); + + /** + * Gets the entity which is followed by the camera when in + * {@link GameMode#SPECTATOR}. + * + * @return the followed entity, or null if not in spectator mode or not + * following a specific entity. + */ + Entity getSpectatorTarget(); + + /** + * Sets the entity which is followed by the camera when in + * {@link GameMode#SPECTATOR}. + * + * @param entity the entity to follow or null to reset + * @throws IllegalStateException if the player is not in + * {@link GameMode#SPECTATOR} + */ + void setSpectatorTarget(Entity entity); + + /** + * Sends a title and a subtitle message to the player. If either of these + * values are null, they will not be sent and the display will remain + * unchanged. If they are empty strings, the display will be updated as + * such. If the strings contain a new line, only the first line will be + * sent. + * + * @param title Title text + * @param subtitle Subtitle text + * @deprecated API subject to change + */ + @Deprecated + void sendTitle(String title, String subtitle); + + /** + * Resets the title displayed to the player. + */ + // Paper - Undeprecate + void resetTitle(); + + // Spigot start + class Spigot extends Entity.Spigot { + + /** + * Gets the connection address of this player, regardless of whether it + * has been spoofed or not. + * + * @return the player's connection address + */ + public InetSocketAddress getRawAddress() { + throw new UnsupportedOperationException("Not supported yet."); + } + + public void playEffect(Location location, Effect effect, int id, int data, float offsetX, float offsetY, float offsetZ, float speed, int particleCount, int radius) { + throw new UnsupportedOperationException("Not supported yet."); + } + + /** + * Gets whether the player collides with entities + * + * @return the player's collision toggle state + */ + public boolean getCollidesWithEntities() { + throw new UnsupportedOperationException("Not supported yet."); + } + + /** + * Sets whether the player collides with entities + * + * @param collides whether the player should collide with entities or + * not. + */ + public void setCollidesWithEntities(boolean collides) { + throw new UnsupportedOperationException("Not supported yet."); + } + + /** + * Respawns the player if dead. + */ + public void respawn() { + throw new UnsupportedOperationException("Not supported yet."); + } + + /** + * Gets player locale language. + * + * @return the player's client language settings + */ + public String getLocale() { + throw new UnsupportedOperationException("Not supported yet."); + } + + public java.util.Set getHiddenPlayers() { + throw new UnsupportedOperationException("Not supported yet."); + } + + /** + * Sends the component to the player + * + * @param component the components to send + */ + public void sendMessage(net.md_5.bungee.api.chat.BaseComponent component) { + throw new UnsupportedOperationException("Not supported yet."); + } + + /** + * Sends an array of components as a single message to the player + * + * @param components the components to send + */ + public void sendMessage(net.md_5.bungee.api.chat.BaseComponent... components) { + throw new UnsupportedOperationException("Not supported yet."); + } + + /** + * Get whether the player affects mob spawning + * + * @return whether or not the player affects + * mob spawning. + */ + public boolean getAffectsSpawning() { + throw new UnsupportedOperationException("Not supported yet."); + } + + /** + * Set whether or not the player affects mob spawning + * + * @param affects whether or not the player should affect + * spawning or not. + */ + public void setAffectsSpawning(boolean affects) { + throw new UnsupportedOperationException("Not supported yet"); + } + + /** + * Get the view distance for this player + * + * @return View distance + */ + public int getViewDistance() { + throw new UnsupportedOperationException("Not supported yet"); + } + + /** + * Set the view distance for this player + * + * @param viewDistance View distance + */ + public void setViewDistance(int viewDistance) { + throw new UnsupportedOperationException("Not supported yet"); + } + + public int getPing() { + throw new UnsupportedOperationException("Not supported yet."); + } + } + + Spigot spigot(); + // Spigot end +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/PoweredMinecart.java b/azurite-api/src/main/java/org/bukkit/entity/PoweredMinecart.java new file mode 100644 index 0000000..38240a9 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/PoweredMinecart.java @@ -0,0 +1,9 @@ +package org.bukkit.entity; + +/** + * @deprecated This class has been moved into a sub package; {@link + * org.bukkit.entity.minecart.PoweredMinecart} should be used instead. + * @see org.bukkit.entity.minecart.PoweredMinecart + */ +@Deprecated +public interface PoweredMinecart extends org.bukkit.entity.minecart.PoweredMinecart {} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Projectile.java b/azurite-api/src/main/java/org/bukkit/entity/Projectile.java new file mode 100644 index 0000000..a7eaead --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Projectile.java @@ -0,0 +1,60 @@ +package org.bukkit.entity; + +import org.bukkit.projectiles.ProjectileSource; + +/** + * Represents a shootable entity. + */ +public interface Projectile extends Entity { + + /** + * This method exists for legacy reasons to provide backwards + * compatibility. It will not exist at runtime and should not be used + * under any circumstances. + * + * @return the {@link LivingEntity} that shot this projectile + */ + @Deprecated + LivingEntity _INVALID_getShooter(); + + /** + * Retrieve the shooter of this projectile. + * + * @return the {@link ProjectileSource} that shot this projectile + */ + ProjectileSource getShooter(); + + /** + * This method exists for legacy reasons to provide backwards + * compatibility. It will not exist at runtime and should not be used + * under any circumstances. + * + * @param shooter the {@link LivingEntity} that shot this projectile + */ + @Deprecated + void _INVALID_setShooter(LivingEntity shooter); + + /** + * Set the shooter of this projectile. + * + * @param source the {@link ProjectileSource} that shot this projectile + */ + void setShooter(ProjectileSource source); + + /** + * Determine if this projectile should bounce or not when it hits. + *

+ * If a small fireball does not bounce it will set the target on fire. + * + * @return true if it should bounce. + */ + boolean doesBounce(); + + /** + * Set whether or not this projectile should bounce or not when it hits + * something. + * + * @param doesBounce whether or not it should bounce. + */ + void setBounce(boolean doesBounce); +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Rabbit.java b/azurite-api/src/main/java/org/bukkit/entity/Rabbit.java new file mode 100644 index 0000000..7fa47fd --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Rabbit.java @@ -0,0 +1,49 @@ +package org.bukkit.entity; + +public interface Rabbit extends Animals { + + /** + * @return The type of rabbit. + */ + Type getRabbitType(); + + /** + * @param type Sets the type of rabbit for this entity. + */ + void setRabbitType(Type type); + + /** + * Represents the various types a Rabbit might be. + */ + enum Type { + + /** + * Chocolate colored rabbit. + */ + BROWN, + /** + * Pure white rabbit. + */ + WHITE, + /** + * Black rabbit. + */ + BLACK, + /** + * Black with white patches, or white with black patches? + */ + BLACK_AND_WHITE, + /** + * Golden bunny. + */ + GOLD, + /** + * Salt and pepper colored, whatever that means. + */ + SALT_AND_PEPPER, + /** + * Rabbit with pure white fur, blood red horizontal eyes, and is hostile to players. + */ + THE_KILLER_BUNNY + } +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Sheep.java b/azurite-api/src/main/java/org/bukkit/entity/Sheep.java new file mode 100644 index 0000000..83f0721 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Sheep.java @@ -0,0 +1,19 @@ +package org.bukkit.entity; + +import org.bukkit.material.Colorable; + +/** + * Represents a Sheep. + */ +public interface Sheep extends Animals, Colorable { + + /** + * @return Whether the sheep is sheared. + */ + boolean isSheared(); + + /** + * @param flag Whether to shear the sheep + */ + void setSheared(boolean flag); +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Silverfish.java b/azurite-api/src/main/java/org/bukkit/entity/Silverfish.java new file mode 100644 index 0000000..fe01007 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Silverfish.java @@ -0,0 +1,6 @@ +package org.bukkit.entity; + +/** + * Represents a Silverfish. + */ +public interface Silverfish extends Monster {} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Skeleton.java b/azurite-api/src/main/java/org/bukkit/entity/Skeleton.java new file mode 100644 index 0000000..32b795f --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Skeleton.java @@ -0,0 +1,65 @@ +package org.bukkit.entity; + +/** + * Represents a Skeleton. + */ +public interface Skeleton extends Monster { + + /** + * Gets the current type of this skeleton. + * + * @return Current type + */ + SkeletonType getSkeletonType(); + + /** + * Sets the new type of this skeleton. + * + * @param type New type + */ + void setSkeletonType(SkeletonType type); + + /* + * Represents the various different Skeleton types. + */ + enum SkeletonType { + NORMAL(0), + WITHER(1); + + private static final SkeletonType[] types = new SkeletonType[SkeletonType.values().length]; + private final int id; + + static { + for (SkeletonType type : values()) { + types[type.getId()] = type; + } + } + + SkeletonType(int id) { + this.id = id; + } + + /** + * Gets the ID of this skeleton type. + * + * @return Skeleton type ID + * @deprecated Magic value + */ + @Deprecated + public int getId() { + return id; + } + + /** + * Gets a skeleton type by its ID. + * + * @param id ID of the skeleton type to get. + * @return Resulting skeleton type, or null if not found. + * @deprecated Magic value + */ + @Deprecated + public static SkeletonType getType(int id) { + return (id >= types.length) ? null : types[id]; + } + } +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Slime.java b/azurite-api/src/main/java/org/bukkit/entity/Slime.java new file mode 100644 index 0000000..f11c31c --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Slime.java @@ -0,0 +1,17 @@ +package org.bukkit.entity; + +/** + * Represents a Slime. + */ +public interface Slime extends LivingEntity { + + /** + * @return The size of the slime + */ + int getSize(); + + /** + * @param sz The new size of the slime. + */ + void setSize(int sz); +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/SmallFireball.java b/azurite-api/src/main/java/org/bukkit/entity/SmallFireball.java new file mode 100644 index 0000000..33f54d3 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/SmallFireball.java @@ -0,0 +1,8 @@ +package org.bukkit.entity; + +/** + * Represents a small {@link Fireball} + */ +public interface SmallFireball extends Fireball { + +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Snowball.java b/azurite-api/src/main/java/org/bukkit/entity/Snowball.java new file mode 100644 index 0000000..8c6b433 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Snowball.java @@ -0,0 +1,6 @@ +package org.bukkit.entity; + +/** + * Represents a snowball. + */ +public interface Snowball extends Projectile {} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Snowman.java b/azurite-api/src/main/java/org/bukkit/entity/Snowman.java new file mode 100644 index 0000000..c8070ff --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Snowman.java @@ -0,0 +1,8 @@ +package org.bukkit.entity; + +/** + * Represents a snowman entity + */ +public interface Snowman extends Golem { + +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Spider.java b/azurite-api/src/main/java/org/bukkit/entity/Spider.java new file mode 100644 index 0000000..f9ee8cc --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Spider.java @@ -0,0 +1,6 @@ +package org.bukkit.entity; + +/** + * Represents a Spider. + */ +public interface Spider extends Monster {} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Squid.java b/azurite-api/src/main/java/org/bukkit/entity/Squid.java new file mode 100644 index 0000000..fb47968 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Squid.java @@ -0,0 +1,6 @@ +package org.bukkit.entity; + +/** + * Represents a Squid. + */ +public interface Squid extends WaterMob {} diff --git a/azurite-api/src/main/java/org/bukkit/entity/StorageMinecart.java b/azurite-api/src/main/java/org/bukkit/entity/StorageMinecart.java new file mode 100644 index 0000000..5436d70 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/StorageMinecart.java @@ -0,0 +1,9 @@ +package org.bukkit.entity; + +/** + * @deprecated This class has been moved into a sub package; {@link + * org.bukkit.entity.minecart.StorageMinecart} should be used instead. + * @see org.bukkit.entity.minecart.StorageMinecart + */ +@Deprecated +public interface StorageMinecart extends org.bukkit.entity.minecart.StorageMinecart {} diff --git a/azurite-api/src/main/java/org/bukkit/entity/TNTPrimed.java b/azurite-api/src/main/java/org/bukkit/entity/TNTPrimed.java new file mode 100644 index 0000000..48f3101 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/TNTPrimed.java @@ -0,0 +1,45 @@ +package org.bukkit.entity; + +/** + * Represents a Primed TNT. + */ +public interface TNTPrimed extends Explosive { + + /** + * Set the number of ticks until the TNT blows up after being primed. + * + * @param fuseTicks The fuse ticks + */ + void setFuseTicks(int fuseTicks); + + /** + * Retrieve the number of ticks until the explosion of this TNTPrimed + * entity + * + * @return the number of ticks until this TNTPrimed explodes + */ + int getFuseTicks(); + + /** + * Gets the source of this primed TNT. The source is the entity + * responsible for the creation of this primed TNT. (I.E. player ignites + * TNT with flint and steel.) Take note that this can be null if there is + * no suitable source. (created by the {@link + * org.bukkit.World#spawn(Location, Class)} method, for example.) + *

+ * The source will become null if the chunk this primed TNT is in is + * unloaded then reloaded. If the source Entity becomes invalidated for + * any reason, such being removed from the world, the returned value will + * be null. + * + * @return the source of this primed TNT + */ + Entity getSource(); + + /** + * Gets the source block location of the primed TNT. + * + * @return the source block location the TNT was spawned from + */ + org.bukkit.Location getSourceLoc(); +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Tameable.java b/azurite-api/src/main/java/org/bukkit/entity/Tameable.java new file mode 100644 index 0000000..96f6f95 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Tameable.java @@ -0,0 +1,44 @@ +package org.bukkit.entity; + +public interface Tameable { + + /** + * Check if this is tamed + *

+ * If something is tamed then a player can not tame it through normal + * methods, even if it does not belong to anyone in particular. + * + * @return true if this has been tamed + */ + boolean isTamed(); + + /** + * Sets if this has been tamed. Not necessary if the method setOwner has + * been used, as it tames automatically. + *

+ * If something is tamed then a player can not tame it through normal + * methods, even if it does not belong to anyone in particular. + * + * @param tame true if tame + */ + void setTamed(boolean tame); + + /** + * Gets the current owning AnimalTamer + * + * @return the owning AnimalTamer, or null if not owned + */ + AnimalTamer getOwner(); + + /** + * Set this to be owned by given AnimalTamer. + *

+ * If the owner is not null, this will be tamed and will have any current + * path it is following removed. If the owner is set to null, this will be + * untamed, and the current owner removed. + * + * @param tamer the AnimalTamer who should own this + */ + void setOwner(AnimalTamer tamer); + +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/ThrownExpBottle.java b/azurite-api/src/main/java/org/bukkit/entity/ThrownExpBottle.java new file mode 100644 index 0000000..671282e --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/ThrownExpBottle.java @@ -0,0 +1,8 @@ +package org.bukkit.entity; + +/** + * Represents a thrown Experience bottle. + */ +public interface ThrownExpBottle extends Projectile { + +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/ThrownPotion.java b/azurite-api/src/main/java/org/bukkit/entity/ThrownPotion.java new file mode 100644 index 0000000..db05c4c --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/ThrownPotion.java @@ -0,0 +1,39 @@ +package org.bukkit.entity; + +import org.bukkit.inventory.ItemStack; +import org.bukkit.potion.PotionEffect; + +import java.util.Collection; + +/** + * Represents a thrown potion bottle + */ +public interface ThrownPotion extends Projectile { + + /** + * Returns the effects that are applied by this potion. + * + * @return The potion effects + */ + Collection getEffects(); + + /** + * Returns a copy of the ItemStack for this thrown potion. + *

+ * Altering this copy will not alter the thrown potion directly. If you + * want to alter the thrown potion, you must use the {@link + * #setItem(ItemStack) setItemStack} method. + * + * @return A copy of the ItemStack for this thrown potion. + */ + ItemStack getItem(); + + /** + * Set the ItemStack for this thrown potion. + *

+ * The ItemStack must be a potion, otherwise an exception is thrown. + * + * @param item New ItemStack + */ + void setItem(ItemStack item); +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Vehicle.java b/azurite-api/src/main/java/org/bukkit/entity/Vehicle.java new file mode 100644 index 0000000..d80dfde --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Vehicle.java @@ -0,0 +1,23 @@ +package org.bukkit.entity; + +import org.bukkit.util.Vector; + +/** + * Represents a vehicle entity. + */ +public interface Vehicle extends Entity { + + /** + * Gets the vehicle's velocity. + * + * @return velocity vector + */ + Vector getVelocity(); + + /** + * Sets the vehicle's velocity. + * + * @param vel velocity vector + */ + void setVelocity(Vector vel); +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Villager.java b/azurite-api/src/main/java/org/bukkit/entity/Villager.java new file mode 100644 index 0000000..e5b5dc3 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Villager.java @@ -0,0 +1,69 @@ +package org.bukkit.entity; + +/** + * Represents a villager NPC + */ +public interface Villager extends Ageable, NPC { + + /** + * Gets the current profession of this villager. + * + * @return Current profession. + */ + Profession getProfession(); + + /** + * Sets the new profession of this villager. + * + * @param profession New profession. + */ + void setProfession(Profession profession); + + + /** + * Represents the various different Villager professions there may be. + */ + enum Profession { + FARMER(0), + LIBRARIAN(1), + PRIEST(2), + BLACKSMITH(3), + BUTCHER(4); + + private static final Profession[] professions = new Profession[Profession.values().length]; + private final int id; + + static { + for (Profession type : values()) { + professions[type.getId()] = type; + } + } + + Profession(int id) { + this.id = id; + } + + /** + * Gets the ID of this profession. + * + * @return Profession ID. + * @deprecated Magic value + */ + @Deprecated + public int getId() { + return id; + } + + /** + * Gets a profession by its ID. + * + * @param id ID of the profession to get. + * @return Resulting profession, or null if not found. + * @deprecated Magic value + */ + @Deprecated + public static Profession getProfession(int id) { + return (id >= professions.length) ? null : professions[id]; + } + } +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/WaterMob.java b/azurite-api/src/main/java/org/bukkit/entity/WaterMob.java new file mode 100644 index 0000000..3e89ca0 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/WaterMob.java @@ -0,0 +1,6 @@ +package org.bukkit.entity; + +/** + * Represents a Water Mob + */ +public interface WaterMob extends LivingEntity {} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Weather.java b/azurite-api/src/main/java/org/bukkit/entity/Weather.java new file mode 100644 index 0000000..6d77851 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Weather.java @@ -0,0 +1,6 @@ +package org.bukkit.entity; + +/** + * Represents a Weather related entity, such as a storm + */ +public interface Weather extends Entity {} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Witch.java b/azurite-api/src/main/java/org/bukkit/entity/Witch.java new file mode 100644 index 0000000..9c5dc1f --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Witch.java @@ -0,0 +1,7 @@ +package org.bukkit.entity; + +/** + * Represents a Witch + */ +public interface Witch extends Monster { +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Wither.java b/azurite-api/src/main/java/org/bukkit/entity/Wither.java new file mode 100644 index 0000000..0922c5c --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Wither.java @@ -0,0 +1,7 @@ +package org.bukkit.entity; + +/** + * Represents a Wither boss + */ +public interface Wither extends Monster { +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/WitherSkull.java b/azurite-api/src/main/java/org/bukkit/entity/WitherSkull.java new file mode 100644 index 0000000..baa5e32 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/WitherSkull.java @@ -0,0 +1,21 @@ +package org.bukkit.entity; + +/** + * Represents a wither skull {@link Fireball}. + */ +public interface WitherSkull extends Fireball { + + /** + * Sets the charged status of the wither skull. + * + * @param charged whether it should be charged + */ + void setCharged(boolean charged); + + /** + * Gets whether or not the wither skull is charged. + * + * @return whether the wither skull is charged + */ + boolean isCharged(); +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Wolf.java b/azurite-api/src/main/java/org/bukkit/entity/Wolf.java new file mode 100644 index 0000000..53f6af9 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Wolf.java @@ -0,0 +1,56 @@ +package org.bukkit.entity; + +import org.bukkit.DyeColor; + +/** + * Represents a Wolf + */ +public interface Wolf extends Animals, Tameable { + + /** + * Checks if this wolf is angry + * + * @return Anger true if angry + */ + boolean isAngry(); + + /** + * Sets the anger of this wolf. + *

+ * An angry wolf can not be fed or tamed, and will actively look for + * targets to attack. + * + * @param angry true if angry + */ + void setAngry(boolean angry); + + /** + * Checks if this wolf is sitting + * + * @return true if sitting + */ + boolean isSitting(); + + /** + * Sets if this wolf is sitting. + *

+ * Will remove any path that the wolf was following beforehand. + * + * @param sitting true if sitting + */ + void setSitting(boolean sitting); + + /** + * Get the collar color of this wolf + * + * @return the color of the collar + */ + DyeColor getCollarColor(); + + /** + * Set the collar color of this wolf + * + * @param color the color to apply + */ + void setCollarColor(DyeColor color); +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/Zombie.java b/azurite-api/src/main/java/org/bukkit/entity/Zombie.java new file mode 100644 index 0000000..e906a16 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/Zombie.java @@ -0,0 +1,35 @@ +package org.bukkit.entity; + +/** + * Represents a Zombie. + */ +public interface Zombie extends Monster { + + /** + * Gets whether the zombie is a baby + * + * @return Whether the zombie is a baby + */ + boolean isBaby(); + + /** + * Sets whether the zombie is a baby + * + * @param flag Whether the zombie is a baby + */ + void setBaby(boolean flag); + + /** + * Gets whether the zombie is a villager + * + * @return Whether the zombie is a villager + */ + boolean isVillager(); + + /** + * Sets whether the zombie is a villager + * + * @param flag Whether the zombie is a villager + */ + void setVillager(boolean flag); +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/minecart/CommandMinecart.java b/azurite-api/src/main/java/org/bukkit/entity/minecart/CommandMinecart.java new file mode 100644 index 0000000..d64d70b --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/minecart/CommandMinecart.java @@ -0,0 +1,36 @@ +package org.bukkit.entity.minecart; + +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Minecart; + +public interface CommandMinecart extends Minecart, CommandSender { + + /** + * Gets the command that this CommandMinecart will run when activated. + * This will never return null. If the CommandMinecart does not have a + * command, an empty String will be returned instead. + * + * @return Command that this CommandMinecart will run when powered. + */ + String getCommand(); + + /** + * Sets the command that this CommandMinecart will run when activated. + * Setting the command to null is the same as setting it to an empty + * String. + * + * @param command Command that this CommandMinecart will run when + * activated. + */ + void setCommand(String command); + + /** + * Sets the name of this CommandMinecart. The name is used with commands + * that this CommandMinecart executes. Setting the name to null is the + * same as setting it to "@". + * + * @param name New name for this CommandMinecart. + */ + void setName(String name); + +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/minecart/ExplosiveMinecart.java b/azurite-api/src/main/java/org/bukkit/entity/minecart/ExplosiveMinecart.java new file mode 100644 index 0000000..a4411da --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/minecart/ExplosiveMinecart.java @@ -0,0 +1,9 @@ +package org.bukkit.entity.minecart; + +import org.bukkit.entity.Minecart; + +/** + * Represents a Minecart with TNT inside it that can explode when triggered. + */ +public interface ExplosiveMinecart extends Minecart { +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/minecart/HopperMinecart.java b/azurite-api/src/main/java/org/bukkit/entity/minecart/HopperMinecart.java new file mode 100644 index 0000000..5da9ce4 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/minecart/HopperMinecart.java @@ -0,0 +1,10 @@ +package org.bukkit.entity.minecart; + +import org.bukkit.entity.Minecart; +import org.bukkit.inventory.InventoryHolder; + +/** + * Represents a Minecart with a Hopper inside it + */ +public interface HopperMinecart extends Minecart, InventoryHolder { +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/minecart/PoweredMinecart.java b/azurite-api/src/main/java/org/bukkit/entity/minecart/PoweredMinecart.java new file mode 100644 index 0000000..57e8b1d --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/minecart/PoweredMinecart.java @@ -0,0 +1,10 @@ +package org.bukkit.entity.minecart; + +import org.bukkit.entity.Minecart; + +/** + * Represents a powered minecart. A powered minecart moves on its own when a + * player deposits {@link org.bukkit.Material#COAL fuel}. + */ +public interface PoweredMinecart extends Minecart { +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/minecart/RideableMinecart.java b/azurite-api/src/main/java/org/bukkit/entity/minecart/RideableMinecart.java new file mode 100644 index 0000000..1b82645 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/minecart/RideableMinecart.java @@ -0,0 +1,14 @@ +package org.bukkit.entity.minecart; + +import org.bukkit.entity.Minecart; + +/** + * Represents a minecart that can have certain {@link + * org.bukkit.entity.Entity entities} as passengers. Normal passengers + * include all {@link org.bukkit.entity.LivingEntity living entities} with + * the exception of {@link org.bukkit.entity.IronGolem iron golems}. + * Non-player entities that meet normal passenger criteria automatically + * mount these minecarts when close enough. + */ +public interface RideableMinecart extends Minecart { +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/minecart/SpawnerMinecart.java b/azurite-api/src/main/java/org/bukkit/entity/minecart/SpawnerMinecart.java new file mode 100644 index 0000000..0ce3592 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/minecart/SpawnerMinecart.java @@ -0,0 +1,10 @@ +package org.bukkit.entity.minecart; + +import org.bukkit.entity.Minecart; + +/** + * Represents a Minecart with an {@link org.bukkit.block.CreatureSpawner + * entity spawner} inside it. + */ +public interface SpawnerMinecart extends Minecart { +} diff --git a/azurite-api/src/main/java/org/bukkit/entity/minecart/StorageMinecart.java b/azurite-api/src/main/java/org/bukkit/entity/minecart/StorageMinecart.java new file mode 100644 index 0000000..4f04ab4 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/entity/minecart/StorageMinecart.java @@ -0,0 +1,12 @@ +package org.bukkit.entity.minecart; + +import org.bukkit.entity.Minecart; +import org.bukkit.inventory.InventoryHolder; + +/** + * Represents a minecart with a chest. These types of {@link Minecart + * minecarts} have their own inventory that can be accessed using methods + * from the {@link InventoryHolder} interface. + */ +public interface StorageMinecart extends Minecart, InventoryHolder { +} diff --git a/azurite-api/src/main/java/org/bukkit/event/Cancellable.java b/azurite-api/src/main/java/org/bukkit/event/Cancellable.java new file mode 100644 index 0000000..fb1bc05 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/Cancellable.java @@ -0,0 +1,20 @@ +package org.bukkit.event; + +public interface Cancellable { + + /** + * Gets the cancellation state of this event. A cancelled event will not + * be executed in the server, but will still pass to other plugins + * + * @return true if this event is cancelled + */ + boolean isCancelled(); + + /** + * Sets the cancellation state of this event. A cancelled event will not + * be executed in the server, but will still pass to other plugins. + * + * @param cancel true if you wish to cancel this event + */ + void setCancelled(boolean cancel); +} diff --git a/azurite-api/src/main/java/org/bukkit/event/Event.java b/azurite-api/src/main/java/org/bukkit/event/Event.java new file mode 100644 index 0000000..01a6f21 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/Event.java @@ -0,0 +1,115 @@ +package org.bukkit.event; + +import org.bukkit.Bukkit; +import org.bukkit.plugin.PluginManager; + +/** + * Represents an event. + * + * All events require a static method named getHandlerList() which returns the same {@link HandlerList} as {@link #getHandlers()}. + * + * @see PluginManager#callEvent(Event) + * @see PluginManager#registerEvents(Listener,Plugin) + */ +public abstract class Event { + private String name; + private final boolean async; + + /** + * The default constructor is defined for cleaner code. This constructor + * assumes the event is synchronous. + */ + public Event() { + this(false); + } + + /** + * This constructor is used to explicitly declare an event as synchronous + * or asynchronous. + * + * @param isAsync true indicates the event will fire asynchronously, false + * by default from default constructor + */ + public Event(boolean isAsync) { + this.async = isAsync; + } + + // Alphheim start - Paper end + /** + * Calls the event and tests if cancelled. + * + * @return if event was cancelled, if cancellable. otherwise true. + */ + public boolean callEvent() { + Bukkit.getPluginManager().callEvent(this); + if (this instanceof Cancellable) { + return !((Cancellable) this).isCancelled(); + } else { + return true; + } + } + // Alphheim end - Paper end + + /** + * Convenience method for providing a user-friendly identifier. By + * default, it is the event's class's {@linkplain Class#getSimpleName() + * simple name}. + * + * @return name of this event + */ + public String getEventName() { + if (name == null) { + name = getClass().getSimpleName(); + } + return name; + } + + public abstract HandlerList getHandlers(); + + /** + * Any custom event that should not by synchronized with other events must + * use the specific constructor. These are the caveats of using an + * asynchronous event: + *

    + *
  • The event is never fired from inside code triggered by a + * synchronous event. Attempting to do so results in an {@link + * IllegalStateException}. + *
  • However, asynchronous event handlers may fire synchronous or + * asynchronous events + *
  • The event may be fired multiple times simultaneously and in any + * order. + *
  • Any newly registered or unregistered handler is ignored after an + * event starts execution. + *
  • The handlers for this event may block for any length of time. + *
  • Some implementations may selectively declare a specific event use + * as asynchronous. This behavior should be clearly defined. + *
  • Asynchronous calls are not calculated in the plugin timing system. + *
+ * + * @return false by default, true if the event fires asynchronously + */ + public final boolean isAsynchronous() { + return async; + } + + public enum Result { + + /** + * Deny the event. Depending on the event, the action indicated by the + * event will either not take place or will be reverted. Some actions + * may not be denied. + */ + DENY, + /** + * Neither deny nor allow the event. The server will proceed with its + * normal handling. + */ + DEFAULT, + /** + * Allow / Force the event. The action indicated by the event will + * take place if possible, even if the server would not normally allow + * the action. Some actions may not be allowed. + */ + ALLOW + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/EventException.java b/azurite-api/src/main/java/org/bukkit/event/EventException.java new file mode 100644 index 0000000..84638e8 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/EventException.java @@ -0,0 +1,53 @@ +package org.bukkit.event; + +public class EventException extends Exception { + private static final long serialVersionUID = 3532808232324183999L; + private final Throwable cause; + + /** + * Constructs a new EventException based on the given Exception + * + * @param throwable Exception that triggered this Exception + */ + public EventException(Throwable throwable) { + cause = throwable; + } + + /** + * Constructs a new EventException + */ + public EventException() { + cause = null; + } + + /** + * Constructs a new EventException with the given message + * + * @param cause The exception that caused this + * @param message The message + */ + public EventException(Throwable cause, String message) { + super(message); + this.cause = cause; + } + + /** + * Constructs a new EventException with the given message + * + * @param message The message + */ + public EventException(String message) { + super(message); + cause = null; + } + + /** + * If applicable, returns the Exception that triggered this Exception + * + * @return Inner exception, or null if one does not exist + */ + @Override + public Throwable getCause() { + return cause; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/EventHandler.java b/azurite-api/src/main/java/org/bukkit/event/EventHandler.java new file mode 100644 index 0000000..4c9fb3c --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/EventHandler.java @@ -0,0 +1,41 @@ +package org.bukkit.event; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * An annotation to mark methods as being event handler methods + */ +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +public @interface EventHandler { + + /** + * Define the priority of the event. + *

+ * First priority to the last priority executed: + *

    + *
  1. LOWEST + *
  2. LOW + *
  3. NORMAL + *
  4. HIGH + *
  5. HIGHEST + *
  6. MONITOR + *
+ * + * @return the priority + */ + EventPriority priority() default EventPriority.NORMAL; + + /** + * Define if the handler ignores a cancelled event. + *

+ * If ignoreCancelled is true and the event is cancelled, the method is + * not called. Otherwise, the method is always called. + * + * @return whether cancelled events should be ignored + */ + boolean ignoreCancelled() default false; +} diff --git a/azurite-api/src/main/java/org/bukkit/event/EventPriority.java b/azurite-api/src/main/java/org/bukkit/event/EventPriority.java new file mode 100644 index 0000000..7bc7e0a --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/EventPriority.java @@ -0,0 +1,47 @@ +package org.bukkit.event; + +/** + * Represents an event's priority in execution + */ +public enum EventPriority { + + /** + * Event call is of very low importance and should be ran first, to allow + * other plugins to further customise the outcome + */ + LOWEST(0), + /** + * Event call is of low importance + */ + LOW(1), + /** + * Event call is neither important nor unimportant, and may be ran + * normally + */ + NORMAL(2), + /** + * Event call is of high importance + */ + HIGH(3), + /** + * Event call is critical and must have the final say in what happens + * to the event + */ + HIGHEST(4), + /** + * Event is listened to purely for monitoring the outcome of an event. + *

+ * No modifications to the event should be made under this priority + */ + MONITOR(5); + + private final int slot; + + EventPriority(int slot) { + this.slot = slot; + } + + public int getSlot() { + return slot; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/HandlerList.java b/azurite-api/src/main/java/org/bukkit/event/HandlerList.java new file mode 100644 index 0000000..e42e0d2 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/HandlerList.java @@ -0,0 +1,231 @@ +package org.bukkit.event; + +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.RegisteredListener; + +import java.util.*; +import java.util.Map.Entry; + +/** + * A list of event handlers, stored per-event. Based on lahwran's fevents. + */ +public class HandlerList { + + /** + * Handler array. This field being an array is the key to this system's + * speed. + */ + private volatile RegisteredListener[] handlers = null; + + /** + * Dynamic handler lists. These are changed using register() and + * unregister() and are automatically baked to the handlers array any time + * they have changed. + */ + private final EnumMap> handlerslots; + + /** + * List of all HandlerLists which have been created, for use in bakeAll() + */ + private static ArrayList allLists = new ArrayList(); + + /** + * Bake all handler lists. Best used just after all normal event + * registration is complete, ie just after all plugins are loaded if + * you're using fevents in a plugin system. + */ + public static void bakeAll() { + synchronized (allLists) { + for (HandlerList h : allLists) { + h.bake(); + } + } + } + + /** + * Unregister all listeners from all handler lists. + */ + public static void unregisterAll() { + synchronized (allLists) { + for (HandlerList h : allLists) { + synchronized (h) { + for (List list : h.handlerslots.values()) { + list.clear(); + } + h.handlers = null; + } + } + } + } + + /** + * Unregister a specific plugin's listeners from all handler lists. + * + * @param plugin plugin to unregister + */ + public static void unregisterAll(Plugin plugin) { + synchronized (allLists) { + for (HandlerList h : allLists) { + h.unregister(plugin); + } + } + } + + /** + * Unregister a specific listener from all handler lists. + * + * @param listener listener to unregister + */ + public static void unregisterAll(Listener listener) { + synchronized (allLists) { + for (HandlerList h : allLists) { + h.unregister(listener); + } + } + } + + /** + * Create a new handler list and initialize using EventPriority. + *

+ * The HandlerList is then added to meta-list for use in bakeAll() + */ + public HandlerList() { + handlerslots = new EnumMap>(EventPriority.class); + for (EventPriority o : EventPriority.values()) { + handlerslots.put(o, new ArrayList()); + } + synchronized (allLists) { + allLists.add(this); + } + } + + /** + * Register a new listener in this handler list + * + * @param listener listener to register + */ + public synchronized void register(RegisteredListener listener) { + if (handlerslots.get(listener.getPriority()).contains(listener)) + throw new IllegalStateException("This listener is already registered to priority " + listener.getPriority().toString()); + handlers = null; + handlerslots.get(listener.getPriority()).add(listener); + } + + /** + * Register a collection of new listeners in this handler list + * + * @param listeners listeners to register + */ + public void registerAll(Collection listeners) { + for (RegisteredListener listener : listeners) { + register(listener); + } + } + + /** + * Remove a listener from a specific order slot + * + * @param listener listener to remove + */ + public synchronized void unregister(RegisteredListener listener) { + if (handlerslots.get(listener.getPriority()).remove(listener)) { + handlers = null; + } + } + + /** + * Remove a specific plugin's listeners from this handler + * + * @param plugin plugin to remove + */ + public synchronized void unregister(Plugin plugin) { + boolean changed = false; + for (List list : handlerslots.values()) { + for (ListIterator i = list.listIterator(); i.hasNext();) { + if (i.next().getPlugin().equals(plugin)) { + i.remove(); + changed = true; + } + } + } + if (changed) handlers = null; + } + + /** + * Remove a specific listener from this handler + * + * @param listener listener to remove + */ + public synchronized void unregister(Listener listener) { + boolean changed = false; + for (List list : handlerslots.values()) { + for (ListIterator i = list.listIterator(); i.hasNext();) { + if (i.next().getListener().equals(listener)) { + i.remove(); + changed = true; + } + } + } + if (changed) handlers = null; + } + + /** + * Bake HashMap and ArrayLists to 2d array - does nothing if not necessary + */ + public synchronized void bake() { + if (handlers != null) return; // don't re-bake when still valid + List entries = new ArrayList<>(); + for (Entry> entry : handlerslots.entrySet()) { + entries.addAll(entry.getValue()); + } + handlers = entries.toArray(new RegisteredListener[entries.size()]); + } + + /** + * Get the baked registered listeners associated with this handler list + * + * @return the array of registered listeners + */ + public RegisteredListener[] getRegisteredListeners() { + RegisteredListener[] handlers; + while ((handlers = this.handlers) == null) bake(); // This prevents fringe cases of returning null + return handlers; + } + + /** + * Get a specific plugin's registered listeners associated with this + * handler list + * + * @param plugin the plugin to get the listeners of + * @return the list of registered listeners + */ + public static ArrayList getRegisteredListeners(Plugin plugin) { + ArrayList listeners = new ArrayList(); + synchronized (allLists) { + for (HandlerList h : allLists) { + synchronized (h) { + for (List list : h.handlerslots.values()) { + for (RegisteredListener listener : list) { + if (listener.getPlugin().equals(plugin)) { + listeners.add(listener); + } + } + } + } + } + } + return listeners; + } + + /** + * Get a list of all handler lists for every event type + * + * @return the list of all handler lists + */ + @SuppressWarnings("unchecked") + public static ArrayList getHandlerLists() { + synchronized (allLists) { + return (ArrayList) allLists.clone(); + } + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/Listener.java b/azurite-api/src/main/java/org/bukkit/event/Listener.java new file mode 100644 index 0000000..ff083e6 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/Listener.java @@ -0,0 +1,6 @@ +package org.bukkit.event; + +/** + * Simple interface for tagging all EventListeners + */ +public interface Listener {} diff --git a/azurite-api/src/main/java/org/bukkit/event/block/Action.java b/azurite-api/src/main/java/org/bukkit/event/block/Action.java new file mode 100644 index 0000000..25d26e3 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/block/Action.java @@ -0,0 +1,33 @@ +package org.bukkit.event.block; + +public enum Action { + + /** + * Left-clicking a block + */ + LEFT_CLICK_BLOCK, + /** + * Right-clicking a block + */ + RIGHT_CLICK_BLOCK, + /** + * Left-clicking the air + */ + LEFT_CLICK_AIR, + /** + * Right-clicking the air + */ + RIGHT_CLICK_AIR, + /** + * Stepping onto or into a block (Ass-pressure) + * + * Examples: + *

    + *
  • Jumping on soil + *
  • Standing on pressure plate + *
  • Triggering redstone ore + *
  • Triggering tripwire + *
+ */ + PHYSICAL, +} diff --git a/azurite-api/src/main/java/org/bukkit/event/block/BlockBreakEvent.java b/azurite-api/src/main/java/org/bukkit/event/block/BlockBreakEvent.java new file mode 100644 index 0000000..1567503 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/block/BlockBreakEvent.java @@ -0,0 +1,54 @@ +package org.bukkit.event.block; + +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; + +/** + * Called when a block is broken by a player. + *

+ * If you wish to have the block drop experience, you must set the experience + * value above 0. By default, experience will be set in the event if: + *

    + *
  1. The player is not in creative or adventure mode + *
  2. The player can loot the block (ie: does not destroy it completely, by + * using the correct tool) + *
  3. The player does not have silk touch + *
  4. The block drops experience in vanilla Minecraft + *
+ *

+ * Note: + * Plugins wanting to simulate a traditional block drop should set the block + * to air and utilize their own methods for determining what the default drop + * for the block being broken is and what to do about it, if anything. + *

+ * If a Block Break event is cancelled, the block will not break and + * experience will not drop. + */ +public class BlockBreakEvent extends BlockExpEvent implements Cancellable { + private final Player player; + private boolean cancel; + + public BlockBreakEvent(final Block theBlock, final Player player) { + super(theBlock, 0); + + this.player = player; + } + + /** + * Gets the Player that is breaking the block involved in this event. + * + * @return The Player that is breaking the block involved in this event + */ + public Player getPlayer() { + return player; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/block/BlockBurnEvent.java b/azurite-api/src/main/java/org/bukkit/event/block/BlockBurnEvent.java new file mode 100644 index 0000000..1592a15 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/block/BlockBurnEvent.java @@ -0,0 +1,38 @@ +package org.bukkit.event.block; + +import org.bukkit.block.Block; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a block is destroyed as a result of being burnt by fire. + *

+ * If a Block Burn event is cancelled, the block will not be destroyed as a + * result of being burnt by fire. + */ +public class BlockBurnEvent extends BlockEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled; + + public BlockBurnEvent(final Block block) { + super(block); + this.cancelled = false; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/block/BlockCanBuildEvent.java b/azurite-api/src/main/java/org/bukkit/event/block/BlockCanBuildEvent.java new file mode 100644 index 0000000..04198cf --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/block/BlockCanBuildEvent.java @@ -0,0 +1,93 @@ +package org.bukkit.event.block; + +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.event.HandlerList; + +/** + * Called when we try to place a block, to see if we can build it here or not. + *

+ * Note: + *

    + *
  • The Block returned by getBlock() is the block we are trying to place + * on, not the block we are trying to place. + *
  • If you want to figure out what is being placed, use {@link + * #getMaterial()} or {@link #getMaterialId()} instead. + *
+ */ +public class BlockCanBuildEvent extends BlockEvent { + private static final HandlerList handlers = new HandlerList(); + protected boolean buildable; + + /** + * + * @deprecated Magic value + */ + @Deprecated + protected int material; + + /** + * + * @deprecated Magic value + * @param block the block involved in this event + * @param id the id of the block to place + * @param canBuild whether we can build + */ + @Deprecated + public BlockCanBuildEvent(final Block block, final int id, final boolean canBuild) { + super(block); + buildable = canBuild; + material = id; + } + + /** + * Gets whether or not the block can be built here. + *

+ * By default, returns Minecraft's answer on whether the block can be + * built here or not. + * + * @return boolean whether or not the block can be built + */ + public boolean isBuildable() { + return buildable; + } + + /** + * Sets whether the block can be built here or not. + * + * @param cancel true if you want to allow the block to be built here + * despite Minecraft's default behaviour + */ + public void setBuildable(boolean cancel) { + this.buildable = cancel; + } + + /** + * Gets the Material that we are trying to place. + * + * @return The Material that we are trying to place + */ + public Material getMaterial() { + return Material.getMaterial(material); + } + + /** + * Gets the Material ID for the Material that we are trying to place. + * + * @return The Material ID for the Material that we are trying to place + * @deprecated Magic value + */ + @Deprecated + public int getMaterialId() { + return material; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/block/BlockDamageEvent.java b/azurite-api/src/main/java/org/bukkit/event/block/BlockDamageEvent.java new file mode 100644 index 0000000..d80e00e --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/block/BlockDamageEvent.java @@ -0,0 +1,83 @@ +package org.bukkit.event.block; + +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; +import org.bukkit.inventory.ItemStack; + +/** + * Called when a block is damaged by a player. + *

+ * If a Block Damage event is cancelled, the block will not be damaged. + */ +public class BlockDamageEvent extends BlockEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final Player player; + private boolean instaBreak; + private boolean cancel; + private final ItemStack itemstack; + + public BlockDamageEvent(final Player player, final Block block, final ItemStack itemInHand, final boolean instaBreak) { + super(block); + this.instaBreak = instaBreak; + this.player = player; + this.itemstack = itemInHand; + this.cancel = false; + } + + /** + * Gets the player damaging the block involved in this event. + * + * @return The player damaging the block involved in this event + */ + public Player getPlayer() { + return player; + } + + /** + * Gets if the block is set to instantly break when damaged by the player. + * + * @return true if the block should instantly break when damaged by the + * player + */ + public boolean getInstaBreak() { + return instaBreak; + } + + /** + * Sets if the block should instantly break when damaged by the player. + * + * @param bool true if you want the block to instantly break when damaged + * by the player + */ + public void setInstaBreak(boolean bool) { + this.instaBreak = bool; + } + + /** + * Gets the ItemStack for the item currently in the player's hand. + * + * @return The ItemStack for the item currently in the player's hand + */ + public ItemStack getItemInHand() { + return itemstack; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/block/BlockDispenseArmorEvent.java b/azurite-api/src/main/java/org/bukkit/event/block/BlockDispenseArmorEvent.java new file mode 100644 index 0000000..1727c5d --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/block/BlockDispenseArmorEvent.java @@ -0,0 +1,34 @@ +package org.bukkit.event.block; + +import org.bukkit.block.Block; +import org.bukkit.entity.LivingEntity; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; + +/** + * Called when an equippable item is dispensed from a block and equipped on a + * nearby entity. + *

+ * If a Block Dispense Armor event is cancelled, the equipment will not be + * equipped on the target entity. + */ +public class BlockDispenseArmorEvent extends BlockDispenseEvent { + + private final LivingEntity target; + + public BlockDispenseArmorEvent(@NotNull Block block, @NotNull ItemStack dispensed, @NotNull LivingEntity target) { + super(block, dispensed, new Vector(0, 0, 0)); + this.target = target; + } + + /** + * Get the living entity on which the armor was dispensed. + * + * @return the target entity + */ + @NotNull + public LivingEntity getTargetEntity() { + return target; + } +} \ No newline at end of file diff --git a/azurite-api/src/main/java/org/bukkit/event/block/BlockDispenseEvent.java b/azurite-api/src/main/java/org/bukkit/event/block/BlockDispenseEvent.java new file mode 100644 index 0000000..253c09d --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/block/BlockDispenseEvent.java @@ -0,0 +1,84 @@ +package org.bukkit.event.block; + +import org.bukkit.block.Block; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.Vector; + +/** + * Called when an item is dispensed from a block. + *

+ * If a Block Dispense event is cancelled, the block will not dispense the + * item. + */ +public class BlockDispenseEvent extends BlockEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled = false; + private ItemStack item; + private Vector velocity; + + public BlockDispenseEvent(final Block block, final ItemStack dispensed, final Vector velocity) { + super(block); + this.item = dispensed; + this.velocity = velocity; + } + + /** + * Gets the item that is being dispensed. Modifying the returned item will + * have no effect, you must use {@link + * #setItem(ItemStack)} instead. + * + * @return An ItemStack for the item being dispensed + */ + public ItemStack getItem() { + return item.clone(); + } + + /** + * Sets the item being dispensed. + * + * @param item the item being dispensed + */ + public void setItem(ItemStack item) { + this.item = item; + } + + /** + * Gets the velocity. + *

+ * Note: Modifying the returned Vector will not change the velocity, you + * must use {@link #setVelocity(Vector)} instead. + * + * @return A Vector for the dispensed item's velocity + */ + public Vector getVelocity() { + return velocity.clone(); + } + + /** + * Sets the velocity of the item being dispensed. + * + * @param vel the velocity of the item being dispensed + */ + public void setVelocity(Vector vel) { + velocity = vel; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + cancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/block/BlockDropItemsEvent.java b/azurite-api/src/main/java/org/bukkit/event/block/BlockDropItemsEvent.java new file mode 100644 index 0000000..c37a6f1 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/block/BlockDropItemsEvent.java @@ -0,0 +1,57 @@ +package org.bukkit.event.block; + +import org.bukkit.block.Block; +import org.bukkit.entity.Item; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +import java.util.List; + +public class BlockDropItemsEvent extends Event implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + + private final Block block; + private final Player player; + private final List toDrop; + private boolean cancelled = false; + + public BlockDropItemsEvent(Block block, Player player, List toDrop) { + this.block = block; + this.player = player; + this.toDrop = toDrop; + } + + public Block getBlock() { + return this.block; + } + + public Player getPlayer() { + return this.player; + } + + public List getToDrop() { + return this.toDrop; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + @Override + public boolean isCancelled() { + return this.cancelled; + } + + @Override + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } +} \ No newline at end of file diff --git a/azurite-api/src/main/java/org/bukkit/event/block/BlockEvent.java b/azurite-api/src/main/java/org/bukkit/event/block/BlockEvent.java new file mode 100644 index 0000000..2405205 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/block/BlockEvent.java @@ -0,0 +1,24 @@ +package org.bukkit.event.block; + +import org.bukkit.block.Block; +import org.bukkit.event.Event; + +/** + * Represents a block related event. + */ +public abstract class BlockEvent extends Event { + protected Block block; + + public BlockEvent(final Block theBlock) { + block = theBlock; + } + + /** + * Gets the block involved in this event. + * + * @return The Block which block is involved in this event + */ + public final Block getBlock() { + return block; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/block/BlockExpEvent.java b/azurite-api/src/main/java/org/bukkit/event/block/BlockExpEvent.java new file mode 100644 index 0000000..08636a2 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/block/BlockExpEvent.java @@ -0,0 +1,45 @@ +package org.bukkit.event.block; + +import org.bukkit.block.Block; +import org.bukkit.event.HandlerList; + +/** + * An event that's called when a block yields experience. + */ +public class BlockExpEvent extends BlockEvent { + private static final HandlerList handlers = new HandlerList(); + private int exp; + + public BlockExpEvent(Block block, int exp) { + super(block); + + this.exp = exp; + } + + /** + * Get the experience dropped by the block after the event has processed + * + * @return The experience to drop + */ + public int getExpToDrop() { + return exp; + } + + /** + * Set the amount of experience dropped by the block after the event has + * processed + * + * @param exp 1 or higher to drop experience, else nothing will drop + */ + public void setExpToDrop(int exp) { + this.exp = exp; + } + + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/block/BlockExplodeEvent.java b/azurite-api/src/main/java/org/bukkit/event/block/BlockExplodeEvent.java new file mode 100644 index 0000000..5f15e29 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/block/BlockExplodeEvent.java @@ -0,0 +1,69 @@ +package org.bukkit.event.block; + +import org.bukkit.block.Block; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +import java.util.List; + +/** + * Called when a block explodes + */ +public class BlockExplodeEvent extends BlockEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancel; + private final List blocks; + private float yield; + + public BlockExplodeEvent(final Block what, final List blocks, final float yield) { + super(what); + this.blocks = blocks; + this.yield = yield; + this.cancel = false; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + /** + * Returns the list of blocks that would have been removed or were removed + * from the explosion event. + * + * @return All blown-up blocks + */ + public List blockList() { + return blocks; + } + + /** + * Returns the percentage of blocks to drop from this explosion + * + * @return The yield. + */ + public float getYield() { + return yield; + } + + /** + * Sets the percentage of blocks to drop from this explosion + * + * @param yield The new yield percentage + */ + public void setYield(float yield) { + this.yield = yield; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/block/BlockFadeEvent.java b/azurite-api/src/main/java/org/bukkit/event/block/BlockFadeEvent.java new file mode 100644 index 0000000..673bc5f --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/block/BlockFadeEvent.java @@ -0,0 +1,59 @@ +package org.bukkit.event.block; + +import org.bukkit.block.Block; +import org.bukkit.block.BlockState; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a block fades, melts or disappears based on world conditions + *

+ * Examples: + *

    + *
  • Snow melting due to being near a light source. + *
  • Ice melting due to being near a light source. + *
  • Fire burning out after time, without destroying fuel block. + *
+ *

+ * If a Block Fade event is cancelled, the block will not fade, melt or + * disappear. + */ +public class BlockFadeEvent extends BlockEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled; + private final BlockState newState; + + public BlockFadeEvent(final Block block, final BlockState newState) { + super(block); + this.newState = newState; + this.cancelled = false; + } + + /** + * Gets the state of the block that will be fading, melting or + * disappearing. + * + * @return The block state of the block that will be fading, melting or + * disappearing + */ + public BlockState getNewState() { + return newState; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/block/BlockFormEvent.java b/azurite-api/src/main/java/org/bukkit/event/block/BlockFormEvent.java new file mode 100644 index 0000000..df0401f --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/block/BlockFormEvent.java @@ -0,0 +1,39 @@ +package org.bukkit.event.block; + +import org.bukkit.block.Block; +import org.bukkit.block.BlockState; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a block is formed or spreads based on world conditions. + *

+ * Use {@link BlockSpreadEvent} to catch blocks that actually spread and don't + * just "randomly" form. + *

+ * Examples: + *

    + *
  • Snow forming due to a snow storm. + *
  • Ice forming in a snowy Biome like Taiga or Tundra. + *
+ *

+ * If a Block Form event is cancelled, the block will not be formed. + * + * @see BlockSpreadEvent + */ +public class BlockFormEvent extends BlockGrowEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + + public BlockFormEvent(final Block block, final BlockState newState) { + super(block, newState); + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/block/BlockFromToEvent.java b/azurite-api/src/main/java/org/bukkit/event/block/BlockFromToEvent.java new file mode 100644 index 0000000..f976bea --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/block/BlockFromToEvent.java @@ -0,0 +1,71 @@ +package org.bukkit.event.block; + +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Represents events with a source block and a destination block, currently + * only applies to liquid (lava and water) and teleporting dragon eggs. + *

+ * If a Block From To event is cancelled, the block will not move (the liquid + * will not flow). + */ +public class BlockFromToEvent extends BlockEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + protected Block to; + protected BlockFace face; + protected boolean cancel; + + public BlockFromToEvent(final Block block, final BlockFace face) { + super(block); + this.face = face; + this.cancel = false; + } + + public BlockFromToEvent(final Block block, final Block toBlock) { + super(block); + this.to = toBlock; + this.face = BlockFace.SELF; + this.cancel = false; + } + + /** + * Gets the BlockFace that the block is moving to. + * + * @return The BlockFace that the block is moving to + */ + public BlockFace getFace() { + return face; + } + + /** + * Convenience method for getting the faced Block. + * + * @return The faced Block + */ + public Block getToBlock() { + if (to == null) { + to = block.getRelative(face); + } + return to; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/block/BlockGrowEvent.java b/azurite-api/src/main/java/org/bukkit/event/block/BlockGrowEvent.java new file mode 100644 index 0000000..2a959fd --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/block/BlockGrowEvent.java @@ -0,0 +1,56 @@ +package org.bukkit.event.block; + +import org.bukkit.block.Block; +import org.bukkit.block.BlockState; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a block grows naturally in the world. + *

+ * Examples: + *

    + *
  • Wheat + *
  • Sugar Cane + *
  • Cactus + *
  • Watermelon + *
  • Pumpkin + *
+ *

+ * If a Block Grow event is cancelled, the block will not grow. + */ +public class BlockGrowEvent extends BlockEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final BlockState newState; + private boolean cancelled = false; + + public BlockGrowEvent(final Block block, final BlockState newState) { + super(block); + this.newState = newState; + } + + /** + * Gets the state of the block where it will form or spread to. + * + * @return The block state for this events block + */ + public BlockState getNewState() { + return newState; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/block/BlockIgniteEvent.java b/azurite-api/src/main/java/org/bukkit/event/block/BlockIgniteEvent.java new file mode 100644 index 0000000..5ea8b07 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/block/BlockIgniteEvent.java @@ -0,0 +1,134 @@ +package org.bukkit.event.block; + +import org.bukkit.block.Block; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a block is ignited. If you want to catch when a Player places + * fire, you need to use {@link BlockPlaceEvent}. + *

+ * If a Block Ignite event is cancelled, the block will not be ignited. + */ +public class BlockIgniteEvent extends BlockEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final IgniteCause cause; + private final Entity ignitingEntity; + private final Block ignitingBlock; + private boolean cancel; + + @Deprecated + public BlockIgniteEvent(final Block theBlock, final IgniteCause cause, final Player thePlayer) { + this(theBlock, cause, (Entity) thePlayer); + } + + public BlockIgniteEvent(final Block theBlock, final IgniteCause cause, final Entity ignitingEntity) { + this(theBlock, cause, ignitingEntity, null); + } + + public BlockIgniteEvent(final Block theBlock, final IgniteCause cause, final Block ignitingBlock) { + this(theBlock, cause, null, ignitingBlock); + } + + public BlockIgniteEvent(final Block theBlock, final IgniteCause cause, final Entity ignitingEntity, final Block ignitingBlock) { + super(theBlock); + this.cause = cause; + this.ignitingEntity = ignitingEntity; + this.ignitingBlock = ignitingBlock; + this.cancel = false; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + /** + * Gets the cause of block ignite. + * + * @return An IgniteCause value detailing the cause of block ignition + */ + public IgniteCause getCause() { + return cause; + } + + /** + * Gets the player who ignited this block + * + * @return The Player that placed/ignited the fire block, or null if not ignited by a Player. + */ + public Player getPlayer() { + if (ignitingEntity instanceof Player) { + return (Player) ignitingEntity; + } + + return null; + } + + /** + * Gets the entity who ignited this block + * + * @return The Entity that placed/ignited the fire block, or null if not ignited by a Entity. + */ + public Entity getIgnitingEntity() { + return ignitingEntity; + } + + /** + * Gets the block who ignited this block + * + * @return The Block that placed/ignited the fire block, or null if not ignited by a Block. + */ + public Block getIgnitingBlock() { + return ignitingBlock; + } + + /** + * An enum to specify the cause of the ignite + */ + public enum IgniteCause { + + /** + * Block ignition caused by lava. + */ + LAVA, + /** + * Block ignition caused by a player or dispenser using flint-and-steel. + */ + FLINT_AND_STEEL, + /** + * Block ignition caused by dynamic spreading of fire. + */ + SPREAD, + /** + * Block ignition caused by lightning. + */ + LIGHTNING, + /** + * Block ignition caused by an entity using a fireball. + */ + FIREBALL, + /** + * Block ignition caused by an Ender Crystal. + */ + ENDER_CRYSTAL, + /** + * Block ignition caused by explosion. + */ + EXPLOSION, + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/block/BlockMultiPlaceEvent.java b/azurite-api/src/main/java/org/bukkit/event/block/BlockMultiPlaceEvent.java new file mode 100644 index 0000000..d16e4be --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/block/BlockMultiPlaceEvent.java @@ -0,0 +1,36 @@ +package org.bukkit.event.block; + +import com.google.common.collect.ImmutableList; +import org.bukkit.block.Block; +import org.bukkit.block.BlockState; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.List; + +/** + * Fired when a single block placement action of a player triggers the + * creation of multiple blocks(e.g. placing a bed block). The block returned + * by {@link #getBlockPlaced()} and its related methods is the block where + * the placed block would exist if the placement only affected a single + * block. + */ +public class BlockMultiPlaceEvent extends BlockPlaceEvent { + private final List states; + + public BlockMultiPlaceEvent(List states, Block clicked, ItemStack itemInHand, Player thePlayer, boolean canBuild) { + super(states.get(0).getBlock(), states.get(0), clicked, itemInHand, thePlayer, canBuild); + this.states = ImmutableList.copyOf(states); + } + + /** + * Gets a list of blockstates for all blocks which were replaced by the + * placement of the new blocks. Most of these blocks will just have a + * Material type of AIR. + * + * @return immutable list of replaced BlockStates + */ + public List getReplacedBlockStates() { + return states; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/block/BlockPhysicsEvent.java b/azurite-api/src/main/java/org/bukkit/event/block/BlockPhysicsEvent.java new file mode 100644 index 0000000..d973b69 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/block/BlockPhysicsEvent.java @@ -0,0 +1,64 @@ +package org.bukkit.event.block; + +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Thrown when a block physics check is called + */ +public class BlockPhysicsEvent extends BlockEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final int changed; + private boolean cancel = false; + + /** + * + * @deprecated Magic value + * @param block the block involved in this event + * @param changed the changed block's type id + */ + @Deprecated + public BlockPhysicsEvent(final Block block, final int changed) { + super(block); + this.changed = changed; + } + + /** + * Gets the type of block that changed, causing this event + * + * @return Changed block's type id + * @deprecated Magic value + */ + @Deprecated + public int getChangedTypeId() { + return changed; + } + + /** + * Gets the type of block that changed, causing this event + * + * @return Changed block's type + */ + public Material getChangedType() { + return Material.getMaterial(changed); + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/block/BlockPistonEvent.java b/azurite-api/src/main/java/org/bukkit/event/block/BlockPistonEvent.java new file mode 100644 index 0000000..074d71c --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/block/BlockPistonEvent.java @@ -0,0 +1,48 @@ +package org.bukkit.event.block; + +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.event.Cancellable; + +/** + * Called when a piston block is triggered + */ +public abstract class BlockPistonEvent extends BlockEvent implements Cancellable { + private boolean cancelled; + private final BlockFace direction; + + public BlockPistonEvent(final Block block, final BlockFace direction) { + super(block); + this.direction = direction; + } + + public boolean isCancelled() { + return this.cancelled; + } + + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + + /** + * Returns true if the Piston in the event is sticky. + * + * @return stickiness of the piston + */ + public boolean isSticky() { + return block.getType() == Material.PISTON_STICKY_BASE || block.getType() == Material.PISTON_MOVING_PIECE; + } + + /** + * Return the direction in which the piston will operate. + * + * @return direction of the piston + */ + public BlockFace getDirection() { + // Both are meh! + // return ((PistonBaseMaterial) block.getType().getNewData(block.getData())).getFacing(); + // return ((PistonBaseMaterial) block.getState().getData()).getFacing(); + return direction; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/block/BlockPistonExtendEvent.java b/azurite-api/src/main/java/org/bukkit/event/block/BlockPistonExtendEvent.java new file mode 100644 index 0000000..e35a05e --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/block/BlockPistonExtendEvent.java @@ -0,0 +1,70 @@ +package org.bukkit.event.block; + +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.event.HandlerList; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * Called when a piston extends + */ +public class BlockPistonExtendEvent extends BlockPistonEvent { + private static final HandlerList handlers = new HandlerList(); + private final int length; + private List blocks; + + @Deprecated + public BlockPistonExtendEvent(final Block block, final int length, final BlockFace direction) { + super(block, direction); + + this.length = length; + } + + public BlockPistonExtendEvent(final Block block, final List blocks, final BlockFace direction) { + super(block, direction); + + this.length = blocks.size(); + this.blocks = blocks; + } + + /** + * Get the amount of blocks which will be moved while extending. + * + * @return the amount of moving blocks + * @deprecated slime blocks make the value of this method + * inaccurate due to blocks being pushed at the side + */ + @Deprecated + public int getLength() { + return this.length; + } + + /** + * Get an immutable list of the blocks which will be moved by the + * extending. + * + * @return Immutable list of the moved blocks. + */ + public List getBlocks() { + if (blocks == null) { + ArrayList tmp = new ArrayList(); + for (int i = 0; i < this.getLength(); i++) { + tmp.add(block.getRelative(getDirection(), i + 1)); + } + blocks = Collections.unmodifiableList(tmp); + } + return blocks; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/block/BlockPistonRetractEvent.java b/azurite-api/src/main/java/org/bukkit/event/block/BlockPistonRetractEvent.java new file mode 100644 index 0000000..8474482 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/block/BlockPistonRetractEvent.java @@ -0,0 +1,52 @@ +package org.bukkit.event.block; + +import org.bukkit.Location; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.event.HandlerList; + +import java.util.List; + +/** + * Called when a piston retracts + */ +public class BlockPistonRetractEvent extends BlockPistonEvent { + private static final HandlerList handlers = new HandlerList(); + private final List blocks; + + public BlockPistonRetractEvent(final Block block, final List blocks, final BlockFace direction) { + super(block, direction); + + this.blocks = blocks; + } + + /** + * Gets the location where the possible moving block might be if the + * retracting piston is sticky. + * + * @return The possible location of the possibly moving block. + */ + @Deprecated + public Location getRetractLocation() { + return getBlock().getRelative(getDirection(), 2).getLocation(); + } + + /** + * Get an immutable list of the blocks which will be moved by the + * extending. + * + * @return Immutable list of the moved blocks. + */ + public List getBlocks() { + return blocks; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/block/BlockPlaceEvent.java b/azurite-api/src/main/java/org/bukkit/event/block/BlockPlaceEvent.java new file mode 100644 index 0000000..6d0ffe8 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/block/BlockPlaceEvent.java @@ -0,0 +1,121 @@ +package org.bukkit.event.block; + +import org.bukkit.block.Block; +import org.bukkit.block.BlockState; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; +import org.bukkit.inventory.ItemStack; + +/** + * Called when a block is placed by a player. + *

+ * If a Block Place event is cancelled, the block will not be placed. + */ +public class BlockPlaceEvent extends BlockEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + protected boolean cancel; + protected boolean canBuild; + protected Block placedAgainst; + protected BlockState replacedBlockState; + protected ItemStack itemInHand; + protected Player player; + + public BlockPlaceEvent(final Block placedBlock, final BlockState replacedBlockState, final Block placedAgainst, final ItemStack itemInHand, final Player thePlayer, final boolean canBuild) { + super(placedBlock); + this.placedAgainst = placedAgainst; + this.itemInHand = itemInHand; + this.player = thePlayer; + this.replacedBlockState = replacedBlockState; + this.canBuild = canBuild; + cancel = false; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + /** + * Gets the player who placed the block involved in this event. + * + * @return The Player who placed the block involved in this event + */ + public Player getPlayer() { + return player; + } + + /** + * Clarity method for getting the placed block. Not really needed except + * for reasons of clarity. + * + * @return The Block that was placed + */ + public Block getBlockPlaced() { + return getBlock(); + } + + /** + * Gets the BlockState for the block which was replaced. Material type air + * mostly. + * + * @return The BlockState for the block which was replaced. + */ + public BlockState getBlockReplacedState() { + return this.replacedBlockState; + } + + /** + * Gets the block that this block was placed against + * + * @return Block the block that the new block was placed against + */ + public Block getBlockAgainst() { + return placedAgainst; + } + + /** + * Gets the item in the player's hand when they placed the block. + * + * @return The ItemStack for the item in the player's hand when they + * placed the block + */ + public ItemStack getItemInHand() { + return itemInHand; + } + + /** + * Gets the value whether the player would be allowed to build here. + * Defaults to spawn if the server was going to stop them (such as, the + * player is in Spawn). Note that this is an entirely different check + * than BLOCK_CANBUILD, as this refers to a player, not universe-physics + * rule like cactus on dirt. + * + * @return boolean whether the server would allow a player to build here + */ + public boolean canBuild() { + return this.canBuild; + } + + /** + * Sets the canBuild state of this event. Set to true if you want the + * player to be able to build. + * + * @param canBuild true if you want the player to be able to build + */ + public void setBuild(boolean canBuild) { + this.canBuild = canBuild; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/block/BlockRedstoneEvent.java b/azurite-api/src/main/java/org/bukkit/event/block/BlockRedstoneEvent.java new file mode 100644 index 0000000..625ec90 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/block/BlockRedstoneEvent.java @@ -0,0 +1,55 @@ +package org.bukkit.event.block; + +import org.bukkit.block.Block; +import org.bukkit.event.HandlerList; + +/** + * Called when a redstone current changes + */ +public class BlockRedstoneEvent extends BlockEvent { + private static final HandlerList handlers = new HandlerList(); + private final int oldCurrent; + private int newCurrent; + + public BlockRedstoneEvent(final Block block, final int oldCurrent, final int newCurrent) { + super(block); + this.oldCurrent = oldCurrent; + this.newCurrent = newCurrent; + } + + /** + * Gets the old current of this block + * + * @return The previous current + */ + public int getOldCurrent() { + return oldCurrent; + } + + /** + * Gets the new current of this block + * + * @return The new current + */ + public int getNewCurrent() { + return newCurrent; + } + + /** + * Sets the new current of this block + * + * @param newCurrent The new current to set + */ + public void setNewCurrent(int newCurrent) { + this.newCurrent = newCurrent; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/block/BlockSpreadEvent.java b/azurite-api/src/main/java/org/bukkit/event/block/BlockSpreadEvent.java new file mode 100644 index 0000000..a1fb363 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/block/BlockSpreadEvent.java @@ -0,0 +1,49 @@ +package org.bukkit.event.block; + +import org.bukkit.block.Block; +import org.bukkit.block.BlockState; +import org.bukkit.event.HandlerList; + +/** + * Called when a block spreads based on world conditions. + *

+ * Use {@link BlockFormEvent} to catch blocks that "randomly" form instead of + * actually spread. + *

+ * Examples: + *

    + *
  • Mushrooms spreading. + *
  • Fire spreading. + *
+ *

+ * If a Block Spread event is cancelled, the block will not spread. + * + * @see BlockFormEvent + */ +public class BlockSpreadEvent extends BlockFormEvent { + private static final HandlerList handlers = new HandlerList(); + private final Block source; + + public BlockSpreadEvent(final Block block, final Block source, final BlockState newState) { + super(block, newState); + this.source = source; + } + + /** + * Gets the source block involved in this event. + * + * @return the Block for the source block involved in this event. + */ + public Block getSource() { + return source; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/block/EntityBlockFormEvent.java b/azurite-api/src/main/java/org/bukkit/event/block/EntityBlockFormEvent.java new file mode 100644 index 0000000..45efc32 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/block/EntityBlockFormEvent.java @@ -0,0 +1,32 @@ +package org.bukkit.event.block; + +import org.bukkit.block.Block; +import org.bukkit.block.BlockState; +import org.bukkit.entity.Entity; + +/** + * Called when a block is formed by entities. + *

+ * Examples: + *

    + *
  • Snow formed by a {@link org.bukkit.entity.Snowman}. + *
+ */ +public class EntityBlockFormEvent extends BlockFormEvent { + private final Entity entity; + + public EntityBlockFormEvent(final Entity entity, final Block block, final BlockState blockstate) { + super(block, blockstate); + + this.entity = entity; + } + + /** + * Get the entity that formed the block. + * + * @return Entity involved in event + */ + public Entity getEntity() { + return entity; + } +} \ No newline at end of file diff --git a/azurite-api/src/main/java/org/bukkit/event/block/LeavesDecayEvent.java b/azurite-api/src/main/java/org/bukkit/event/block/LeavesDecayEvent.java new file mode 100644 index 0000000..84d8cfd --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/block/LeavesDecayEvent.java @@ -0,0 +1,36 @@ +package org.bukkit.event.block; + +import org.bukkit.block.Block; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when leaves are decaying naturally. + *

+ * If a Leaves Decay event is cancelled, the leaves will not decay. + */ +public class LeavesDecayEvent extends BlockEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancel = false; + + public LeavesDecayEvent(final Block block) { + super(block); + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/block/NotePlayEvent.java b/azurite-api/src/main/java/org/bukkit/event/block/NotePlayEvent.java new file mode 100644 index 0000000..d4d4381 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/block/NotePlayEvent.java @@ -0,0 +1,83 @@ +package org.bukkit.event.block; + +import org.bukkit.Instrument; +import org.bukkit.Note; +import org.bukkit.block.Block; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a note block is being played through player interaction or a + * redstone current. + */ +public class NotePlayEvent extends BlockEvent implements Cancellable { + + private static HandlerList handlers = new HandlerList(); + private Instrument instrument; + private Note note; + private boolean cancelled = false; + + public NotePlayEvent(Block block, Instrument instrument, Note note) { + super(block); + this.instrument = instrument; + this.note = note; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + /** + * Gets the {@link Instrument} to be used. + * + * @return the Instrument; + */ + public Instrument getInstrument() { + return instrument; + } + + /** + * Gets the {@link Note} to be played. + * + * @return the Note. + */ + public Note getNote() { + return note; + } + + /** + * Overrides the {@link Instrument} to be used. + * + * @param instrument the Instrument. Has no effect if null. + */ + public void setInstrument(Instrument instrument) { + if (instrument != null) { + this.instrument = instrument; + } + + } + + /** + * Overrides the {@link Note} to be played. + * + * @param note the Note. Has no effect if null. + */ + public void setNote(Note note) { + if (note != null) { + this.note = note; + } + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/block/SignChangeEvent.java b/azurite-api/src/main/java/org/bukkit/event/block/SignChangeEvent.java new file mode 100644 index 0000000..83188cf --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/block/SignChangeEvent.java @@ -0,0 +1,84 @@ +package org.bukkit.event.block; + +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a sign is changed by a player. + *

+ * If a Sign Change event is cancelled, the sign will not be changed. + */ +public class SignChangeEvent extends BlockEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancel = false; + private final Player player; + private final String[] lines; + + public SignChangeEvent(final Block theBlock, final Player thePlayer, final String[] theLines) { + super(theBlock); + this.player = thePlayer; + this.lines = theLines; + } + + /** + * Gets the player changing the sign involved in this event. + * + * @return the Player involved in this event + */ + public Player getPlayer() { + return player; + } + + /** + * Gets all of the lines of text from the sign involved in this event. + * + * @return the String array for the sign's lines new text + */ + public String[] getLines() { + return lines; + } + + /** + * Gets a single line of text from the sign involved in this event. + * + * @param index index of the line to get + * @return the String containing the line of text associated with the + * provided index + * @throws IndexOutOfBoundsException thrown when the provided index is {@literal > 3 + * or < 0} + */ + public String getLine(int index) throws IndexOutOfBoundsException { + return lines[index]; + } + + /** + * Sets a single line for the sign involved in this event + * + * @param index index of the line to set + * @param line text to set + * @throws IndexOutOfBoundsException thrown when the provided index is {@literal > 3 + * or < 0} + */ + public void setLine(int index, String line) throws IndexOutOfBoundsException { + lines[index] = line; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/enchantment/EnchantItemEvent.java b/azurite-api/src/main/java/org/bukkit/event/enchantment/EnchantItemEvent.java new file mode 100644 index 0000000..86e2063 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/enchantment/EnchantItemEvent.java @@ -0,0 +1,121 @@ +package org.bukkit.event.enchantment; + +import org.bukkit.block.Block; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; +import org.bukkit.event.inventory.InventoryEvent; +import org.bukkit.inventory.InventoryView; +import org.bukkit.inventory.ItemStack; + +import java.util.HashMap; +import java.util.Map; + +/** + * Called when an ItemStack is successfully enchanted (currently at + * enchantment table) + */ +public class EnchantItemEvent extends InventoryEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final Block table; + private final ItemStack item; + private int level; + private boolean cancelled; + private final Map enchants; + private final Player enchanter; + private int button; + + public EnchantItemEvent(final Player enchanter, final InventoryView view, final Block table, final ItemStack item, final int level, final Map enchants, final int i) { + super(view); + this.enchanter = enchanter; + this.table = table; + this.item = item; + this.level = level; + this.enchants = new HashMap(enchants); + this.cancelled = false; + this.button = i; + } + + /** + * Gets the player enchanting the item + * + * @return enchanting player + */ + public Player getEnchanter() { + return enchanter; + } + + /** + * Gets the block being used to enchant the item + * + * @return the block used for enchanting + */ + public Block getEnchantBlock() { + return table; + } + + /** + * Gets the item to be enchanted (can be modified) + * + * @return ItemStack of item + */ + public ItemStack getItem() { + return item; + } + + /** + * Get cost in exp levels of the enchantment + * + * @return experience level cost + */ + public int getExpLevelCost() { + return level; + } + + /** + * Set cost in exp levels of the enchantment + * + * @param level - cost in levels + */ + public void setExpLevelCost(int level) { + this.level = level; + } + + /** + * Get map of enchantment (levels, keyed by type) to be added to item + * (modify map returned to change values). Note: Any enchantments not + * allowed for the item will be ignored + * + * @return map of enchantment levels, keyed by enchantment + */ + public Map getEnchantsToAdd() { + return enchants; + } + + /** + * Which button was pressed to initiate the enchanting. + * + * @return The button index (0, 1, or 2). + */ + public int whichButton() { + return button; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/enchantment/PrepareItemEnchantEvent.java b/azurite-api/src/main/java/org/bukkit/event/enchantment/PrepareItemEnchantEvent.java new file mode 100644 index 0000000..6c0aa9f --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/enchantment/PrepareItemEnchantEvent.java @@ -0,0 +1,96 @@ +package org.bukkit.event.enchantment; + +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; +import org.bukkit.event.inventory.InventoryEvent; +import org.bukkit.inventory.InventoryView; +import org.bukkit.inventory.ItemStack; + +/** + * Called when an ItemStack is inserted in an enchantment table - can be + * called multiple times + */ +public class PrepareItemEnchantEvent extends InventoryEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final Block table; + private final ItemStack item; + private final int[] levelsOffered; + private final int bonus; + private boolean cancelled; + private final Player enchanter; + + public PrepareItemEnchantEvent(final Player enchanter, InventoryView view, final Block table, final ItemStack item, final int[] levelsOffered, final int bonus) { + super(view); + this.enchanter = enchanter; + this.table = table; + this.item = item; + this.levelsOffered = levelsOffered; + this.bonus = bonus; + this.cancelled = false; + } + + /** + * Gets the player enchanting the item + * + * @return enchanting player + */ + public Player getEnchanter() { + return enchanter; + } + + /** + * Gets the block being used to enchant the item + * + * @return the block used for enchanting + */ + public Block getEnchantBlock() { + return table; + } + + /** + * Gets the item to be enchanted (can be modified) + * + * @return ItemStack of item + */ + public ItemStack getItem() { + return item; + } + + /** + * Get list of offered exp level costs of the enchantment (modify values + * to change offer) + * + * @return experience level costs offered + */ + public int[] getExpLevelCostsOffered() { + return levelsOffered; + } + + /** + * Get enchantment bonus in effect - corresponds to number of bookshelves + * + * @return enchantment bonus + */ + public int getEnchantmentBonus() { + return bonus; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/CreatureSpawnEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/CreatureSpawnEvent.java new file mode 100644 index 0000000..8883157 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/CreatureSpawnEvent.java @@ -0,0 +1,165 @@ +package org.bukkit.event.entity; + +import org.bukkit.Location; +import org.bukkit.entity.CreatureType; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; + +/** + * Called when a creature is spawned into a world. + *

+ * If a Creature Spawn event is cancelled, the creature will not spawn. + */ +public class CreatureSpawnEvent extends EntitySpawnEvent { + private final SpawnReason spawnReason; + + public CreatureSpawnEvent(final LivingEntity spawnee, final SpawnReason spawnReason) { + super(spawnee); + this.spawnReason = spawnReason; + } + + @Deprecated + public CreatureSpawnEvent(Entity spawnee, CreatureType type, Location loc, SpawnReason reason) { + super(spawnee); + spawnReason = reason; + } + + @Override + public LivingEntity getEntity() { + return (LivingEntity) entity; + } + + /** + * Gets the type of creature being spawned. + * + * @return A CreatureType value detailing the type of creature being + * spawned + * @deprecated In favour of {@link #getEntityType()}. + */ + @Deprecated + public CreatureType getCreatureType() { + return CreatureType.fromEntityType(getEntityType()); + } + + /** + * Gets the reason for why the creature is being spawned. + * + * @return A SpawnReason value detailing the reason for the creature being + * spawned + */ + public SpawnReason getSpawnReason() { + return spawnReason; + } + + /** + * An enum to specify the type of spawning + */ + public enum SpawnReason { + + /** + * When something spawns from natural means + */ + NATURAL, + /** + * When an entity spawns as a jockey of another entity (mostly spider + * jockeys) + */ + JOCKEY, + /** + * When a creature spawns due to chunk generation + */ + CHUNK_GEN, + /** + * When a creature spawns from a spawner + */ + SPAWNER, + /** + * When a creature spawns from an egg + */ + EGG, + /** + * When a creature spawns from a Spawner Egg + */ + SPAWNER_EGG, + /** + * When a creature spawns because of a lightning strike + */ + LIGHTNING, + /** + * When a creature is spawned by a player that is sleeping + * + * @deprecated No longer used + */ + @Deprecated + BED, + /** + * When a snowman is spawned by being built + */ + BUILD_SNOWMAN, + /** + * When an iron golem is spawned by being built + */ + BUILD_IRONGOLEM, + /** + * When a wither boss is spawned by being built + */ + BUILD_WITHER, + /** + * When an iron golem is spawned to defend a village + */ + VILLAGE_DEFENSE, + /** + * When a zombie is spawned to invade a village + */ + VILLAGE_INVASION, + /** + * When an animal breeds to create a child + */ + BREEDING, + /** + * When a slime splits + */ + SLIME_SPLIT, + /** + * When an entity calls for reinforcements + */ + REINFORCEMENTS, + /** + * When a creature is spawned by nether portal + */ + NETHER_PORTAL, + /** + * When a creature is spawned by a dispenser dispensing an egg + */ + DISPENSE_EGG, + /** + * When a zombie infects a villager + */ + INFECTION, + /** + * When a villager is cured from infection + */ + CURED, + /** + * When an ocelot has a baby spawned along with them + */ + OCELOT_BABY, + /** + * When a silverfish spawns from a block + */ + SILVERFISH_BLOCK, + /** + * When an entity spawns as a mount of another entity (mostly chicken + * jockeys) + */ + MOUNT, + /** + * When a creature is spawned by plugins + */ + CUSTOM, + /** + * When an entity is missing a SpawnReason + */ + DEFAULT + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/CreeperPowerEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/CreeperPowerEvent.java new file mode 100644 index 0000000..b103a6a --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/CreeperPowerEvent.java @@ -0,0 +1,93 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.Creeper; +import org.bukkit.entity.LightningStrike; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a Creeper is struck by lightning. + *

+ * If a Creeper Power event is cancelled, the Creeper will not be powered. + */ +public class CreeperPowerEvent extends EntityEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean canceled; + private final PowerCause cause; + private LightningStrike bolt; + + public CreeperPowerEvent(final Creeper creeper, final LightningStrike bolt, final PowerCause cause) { + this(creeper, cause); + this.bolt = bolt; + } + + public CreeperPowerEvent(final Creeper creeper, final PowerCause cause) { + super(creeper); + this.cause = cause; + } + + public boolean isCancelled() { + return canceled; + } + + public void setCancelled(boolean cancel) { + canceled = cancel; + } + + @Override + public Creeper getEntity() { + return (Creeper) entity; + } + + /** + * Gets the lightning bolt which is striking the Creeper. + * + * @return The Entity for the lightning bolt which is striking the Creeper + */ + public LightningStrike getLightning() { + return bolt; + } + + /** + * Gets the cause of the creeper being (un)powered. + * + * @return A PowerCause value detailing the cause of change in power. + */ + public PowerCause getCause() { + return cause; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + /** + * An enum to specify the cause of the change in power + */ + public enum PowerCause { + + /** + * Power change caused by a lightning bolt + *

+ * Powered state: true + */ + LIGHTNING, + /** + * Power change caused by something else (probably a plugin) + *

+ * Powered state: true + */ + SET_ON, + /** + * Power change caused by something else (probably a plugin) + *

+ * Powered state: false + */ + SET_OFF + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/EntityAnimationEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/EntityAnimationEvent.java new file mode 100644 index 0000000..cf12c71 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/EntityAnimationEvent.java @@ -0,0 +1,28 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.Entity; +import org.bukkit.event.HandlerList; + +public class EntityAnimationEvent extends EntityEvent { + private static final HandlerList handlers = new HandlerList(); + private Animation animation; + + public EntityAnimationEvent(Entity what, Animation animation) { + super(what); + this.animation = animation; + } + + public Animation getAnimation() { + return this.animation; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public enum Animation { + SHARPNESS, + CRITICAL + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/EntityBreakDoorEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/EntityBreakDoorEvent.java new file mode 100644 index 0000000..2cbbc69 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/EntityBreakDoorEvent.java @@ -0,0 +1,22 @@ +package org.bukkit.event.entity; + +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; + +/** + * Called when an {@link Entity} breaks a door + *

+ * Cancelling the event will cause the event to be delayed + */ +public class EntityBreakDoorEvent extends EntityChangeBlockEvent { + public EntityBreakDoorEvent(final LivingEntity entity, final Block targetBlock) { + super(entity, targetBlock, Material.AIR, (byte) 0); + } + + @Override + public LivingEntity getEntity() { + return (LivingEntity) entity; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/EntityChangeBlockEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/EntityChangeBlockEvent.java new file mode 100644 index 0000000..41be9ca --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/EntityChangeBlockEvent.java @@ -0,0 +1,95 @@ +package org.bukkit.event.entity; + +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when any Entity, excluding players, changes a block. + */ +public class EntityChangeBlockEvent extends EntityEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final Block block; + private boolean cancel; + private final Material to; + private final byte data; + + /** + * + * @param what the LivingEntity causing the change + * @param block the block (before the change) + * @param to the future material being changed to + * @deprecated Provided as a backward compatibility before the data byte + * was provided, and type increased to all entities + */ + @Deprecated + public EntityChangeBlockEvent(final LivingEntity what, final Block block, final Material to) { + this (what, block, to, (byte) 0); + } + + /** + * + * @param what the Entity causing the change + * @param block the block (before the change) + * @param to the future material being changed to + * @param data the future block data + * @deprecated Magic value + */ + @Deprecated + public EntityChangeBlockEvent(final Entity what, final Block block, final Material to, final byte data) { + super(what); + this.block = block; + this.cancel = false; + this.to = to; + this.data = data; + } + + /** + * Gets the block the entity is changing + * + * @return the block that is changing + */ + public Block getBlock() { + return block; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + /** + * Gets the Material that the block is changing into + * + * @return the material that the block is changing into + */ + public Material getTo() { + return to; + } + + /** + * Gets the data for the block that would be changed into + * + * @return the data for the block that would be changed into + * @deprecated Magic value + */ + @Deprecated + public byte getData() { + return data; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/EntityCollectEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/EntityCollectEvent.java new file mode 100644 index 0000000..c61a1e2 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/EntityCollectEvent.java @@ -0,0 +1,28 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.event.HandlerList; + +public class EntityCollectEvent extends EntityEvent { + private static final HandlerList handlers = new HandlerList(); + private final LivingEntity collector; + + public EntityCollectEvent(Entity what, LivingEntity collector) { + super(what); + this.collector = collector; + } + + public LivingEntity getCollector() { + return collector; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/EntityCombustByBlockEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/EntityCombustByBlockEvent.java new file mode 100644 index 0000000..c84bda9 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/EntityCombustByBlockEvent.java @@ -0,0 +1,27 @@ +package org.bukkit.event.entity; + +import org.bukkit.block.Block; +import org.bukkit.entity.Entity; + +/** + * Called when a block causes an entity to combust. + */ +public class EntityCombustByBlockEvent extends EntityCombustEvent { + private final Block combuster; + + public EntityCombustByBlockEvent(final Block combuster, final Entity combustee, final int duration) { + super(combustee, duration); + this.combuster = combuster; + } + + /** + * The combuster can be lava or a block that is on fire. + *

+ * WARNING: block may be null. + * + * @return the Block that set the combustee alight. + */ + public Block getCombuster() { + return combuster; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/EntityCombustByEntityEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/EntityCombustByEntityEvent.java new file mode 100644 index 0000000..639567b --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/EntityCombustByEntityEvent.java @@ -0,0 +1,24 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.Entity; + +/** + * Called when an entity causes another entity to combust. + */ +public class EntityCombustByEntityEvent extends EntityCombustEvent { + private final Entity combuster; + + public EntityCombustByEntityEvent(final Entity combuster, final Entity combustee, final int duration) { + super(combustee, duration); + this.combuster = combuster; + } + + /** + * Get the entity that caused the combustion event. + * + * @return the Entity that set the combustee alight. + */ + public Entity getCombuster() { + return combuster; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/EntityCombustEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/EntityCombustEvent.java new file mode 100644 index 0000000..43c4482 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/EntityCombustEvent.java @@ -0,0 +1,59 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.Entity; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when an entity combusts. + *

+ * If an Entity Combust event is cancelled, the entity will not combust. + */ +public class EntityCombustEvent extends EntityEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private int duration; + private boolean cancel; + + public EntityCombustEvent(final Entity combustee, final int duration) { + super(combustee); + this.duration = duration; + this.cancel = false; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + /** + * @return the amount of time (in seconds) the combustee should be alight + * for + */ + public int getDuration() { + return duration; + } + + /** + * The number of seconds the combustee should be alight for. + *

+ * This value will only ever increase the combustion time, not decrease + * existing combustion times. + * + * @param duration the time in seconds to be alight for. + */ + public void setDuration(int duration) { + this.duration = duration; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/EntityCreatePortalEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/EntityCreatePortalEvent.java new file mode 100644 index 0000000..75dd925 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/EntityCreatePortalEvent.java @@ -0,0 +1,66 @@ +package org.bukkit.event.entity; + +import org.bukkit.PortalType; +import org.bukkit.block.BlockState; +import org.bukkit.entity.LivingEntity; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +import java.util.List; + +/** + * Thrown when a Living Entity creates a portal in a world. + */ +public class EntityCreatePortalEvent extends EntityEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final List blocks; + private boolean cancelled = false; + private PortalType type = PortalType.CUSTOM; + + public EntityCreatePortalEvent(final LivingEntity what, final List blocks, final PortalType type) { + super(what); + + this.blocks = blocks; + this.type = type; + } + + @Override + public LivingEntity getEntity() { + return (LivingEntity) entity; + } + + /** + * Gets a list of all blocks associated with the portal. + * + * @return List of blocks that will be changed. + */ + public List getBlocks() { + return blocks; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + /** + * Gets the type of portal that is trying to be created. + * + * @return Type of portal. + */ + public PortalType getPortalType() { + return type; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/EntityDamageByBlockEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/EntityDamageByBlockEvent.java new file mode 100644 index 0000000..21183d5 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/EntityDamageByBlockEvent.java @@ -0,0 +1,43 @@ +package org.bukkit.event.entity; + +import com.google.common.base.Function; +import org.bukkit.block.Block; +import org.bukkit.entity.Entity; + +import java.util.Map; + +/** + * Called when an entity is damaged by a block + */ +public class EntityDamageByBlockEvent extends EntityDamageEvent { + private final Block damager; + + @Deprecated + public EntityDamageByBlockEvent(final Block damager, final Entity damagee, final DamageCause cause, final int damage) { + this(damager, damagee, cause, (double) damage); + } + + @Deprecated + public EntityDamageByBlockEvent(final Block damager, final Entity damagee, final DamageCause cause, final double damage) { + super(damagee, cause, damage); + this.damager = damager; + } + + public EntityDamageByBlockEvent(final Block damager, final Entity damagee, final DamageCause cause, final Map modifiers, final Map> modifierFunctions) { + this(damager, damagee, cause, modifiers, modifierFunctions, false); + } + + public EntityDamageByBlockEvent(final Block damager, final Entity damagee, final DamageCause cause, final Map modifiers, final Map> modifierFunctions, boolean upgrade) { + super(damagee, cause, modifiers, modifierFunctions); + this.damager = damager; + } + + /** + * Returns the block that damaged the player. + * + * @return Block that damaged the player + */ + public Block getDamager() { + return damager; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/EntityDamageByEntityEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/EntityDamageByEntityEvent.java new file mode 100644 index 0000000..02f225a --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/EntityDamageByEntityEvent.java @@ -0,0 +1,42 @@ +package org.bukkit.event.entity; + +import com.google.common.base.Function; +import org.bukkit.entity.Entity; + +import java.util.Map; + +/** + * Called when an entity is damaged by an entity + */ +public class EntityDamageByEntityEvent extends EntityDamageEvent { + private final Entity damager; + + @Deprecated + public EntityDamageByEntityEvent(final Entity damager, final Entity damagee, final DamageCause cause, final int damage) { + this(damager, damagee, cause, (double) damage); + } + + @Deprecated + public EntityDamageByEntityEvent(final Entity damager, final Entity damagee, final DamageCause cause, final double damage) { + super(damagee, cause, damage); + this.damager = damager; + } + + public EntityDamageByEntityEvent(final Entity damager, final Entity damagee, final DamageCause cause, final Map modifiers, final Map> modifierFunctions) { + this(damager, damagee, cause, modifiers, modifierFunctions, false); + } + + public EntityDamageByEntityEvent(final Entity damager, final Entity damagee, final DamageCause cause, final Map modifiers, final Map> modifierFunctions, boolean upgrade) { + super(damagee, cause, modifiers, modifierFunctions, upgrade); + this.damager = damager; + } + + /** + * Returns the entity that damaged the defender. + * + * @return Entity that damaged the defender. + */ + public Entity getDamager() { + return damager; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/EntityDamageEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/EntityDamageEvent.java new file mode 100644 index 0000000..cf4a182 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/EntityDamageEvent.java @@ -0,0 +1,427 @@ +package org.bukkit.event.entity; + +import com.google.common.base.Function; +import com.google.common.base.Functions; +import com.google.common.collect.ImmutableMap; +import org.apache.commons.lang.Validate; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; +import org.bukkit.util.NumberConversions; + +import java.util.EnumMap; +import java.util.Map; + +/** + * Stores data for damage events + */ +public class EntityDamageEvent extends EntityEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private static final DamageModifier[] MODIFIERS = DamageModifier.values(); + private static final Function ZERO = Functions.constant(-0.0); + private final Map modifiers; + private final Map> modifierFunctions; + private final Map originals; + private boolean upgrade; // Beanes - add damage upgrade to event + private boolean cancelled; + private final DamageCause cause; + + @Deprecated + public EntityDamageEvent(final Entity damagee, final DamageCause cause, final int damage) { + this(damagee, cause, (double) damage); + } + + @Deprecated + public EntityDamageEvent(final Entity damagee, final DamageCause cause, final double damage) { + this(damagee, cause, new EnumMap<>(ImmutableMap.of(DamageModifier.BASE, damage)), new EnumMap>(ImmutableMap.of(DamageModifier.BASE, ZERO))); + } + + public EntityDamageEvent(final Entity damagee, final DamageCause cause, final Map modifiers, final Map> modifierFunctions) { + this(damagee, cause, modifiers, modifierFunctions, false); + } + + public EntityDamageEvent(final Entity damagee, final DamageCause cause, final Map modifiers, final Map> modifierFunctions, boolean upgrade) { + super(damagee); + Validate.isTrue(modifiers.containsKey(DamageModifier.BASE), "BASE DamageModifier missing"); + Validate.isTrue(!modifiers.containsKey(null), "Cannot have null DamageModifier"); + Validate.noNullElements(modifiers.values(), "Cannot have null modifier values"); + Validate.isTrue(modifiers.keySet().equals(modifierFunctions.keySet()), "Must have a modifier function for each DamageModifier"); + Validate.noNullElements(modifierFunctions.values(), "Cannot have null modifier function"); + this.originals = new EnumMap<>(modifiers); + this.cause = cause; + this.modifiers = modifiers; + this.modifierFunctions = modifierFunctions; + this.upgrade = upgrade; + } + + // Beanes - add damage upgrade + public boolean isDamageUpgrade() { + return this.upgrade; + } + + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + cancelled = cancel; + } + + /** + * Gets the original damage for the specified modifier, as defined at this + * event's construction. + * + * @param type the modifier + * @return the original damage + * @throws IllegalArgumentException if type is null + */ + public double getOriginalDamage(DamageModifier type) throws IllegalArgumentException { + final Double damage = originals.get(type); + if (damage != null) { + return damage; + } + if (type == null) { + throw new IllegalArgumentException("Cannot have null DamageModifier"); + } + return 0; + } + + /** + * Sets the damage for the specified modifier. + * + * @param type the damage modifier + * @param damage the scalar value of the damage's modifier + * @see #getFinalDamage() + * @throws IllegalArgumentException if type is null + * @throws UnsupportedOperationException if the caller does not support + * the particular DamageModifier, or to rephrase, when {@link + * #isApplicable(DamageModifier)} returns false + */ + public void setDamage(DamageModifier type, double damage) throws IllegalArgumentException, UnsupportedOperationException { + if (!modifiers.containsKey(type)) { + throw type == null ? new IllegalArgumentException("Cannot have null DamageModifier") : new UnsupportedOperationException(type + " is not applicable to " + getEntity()); + } + modifiers.put(type, damage); + } + + /** + * Gets the damage change for some modifier + * + * @param type the damage modifier + * @return The raw amount of damage caused by the event + * @throws IllegalArgumentException if type is null + * @see DamageModifier#BASE + */ + public double getDamage(DamageModifier type) throws IllegalArgumentException { + Validate.notNull(type, "Cannot have null DamageModifier"); + final Double damage = modifiers.get(type); + return damage == null ? 0 : damage; + } + + /** + * This checks to see if a particular modifier is valid for this event's + * caller, such that, {@link #setDamage(DamageModifier, double)} will not + * throw an {@link UnsupportedOperationException}. + *

+ * {@link DamageModifier#BASE} is always applicable. + * + * @param type the modifier + * @return true if the modifier is supported by the caller, false otherwise + * @throws IllegalArgumentException if type is null + */ + public boolean isApplicable(DamageModifier type) throws IllegalArgumentException { + Validate.notNull(type, "Cannot have null DamageModifier"); + return modifiers.containsKey(type); + } + + /** + * Gets the raw amount of damage caused by the event + * + * @return The raw amount of damage caused by the event + * @see DamageModifier#BASE + */ + public double getDamage() { + return getDamage(DamageModifier.BASE); + } + + /** + * Gets the amount of damage caused by the event after all damage + * reduction is applied. + * + * @return the amount of damage caused by the event + */ + public final double getFinalDamage() { + double damage = 0; + for (DamageModifier modifier : MODIFIERS) { + damage += getDamage(modifier); + } + return damage; + } + + /** + * This method exists for legacy reasons to provide backwards + * compatibility. It will not exist at runtime and should not be used + * under any circumstances. + * + * @return the (rounded) damage + */ + @Deprecated + public int _INVALID_getDamage() { + return NumberConversions.ceil(getDamage()); + } + + /** + * Sets the raw amount of damage caused by the event. + *

+ * For compatibility this also recalculates the modifiers and scales + * them by the difference between the modifier for the previous damage + * value and the new one. + * + * @param damage The raw amount of damage caused by the event + */ + public void setDamage(double damage) { + // These have to happen in the same order as the server calculates them, keep the enum sorted + double remaining = damage; + double oldRemaining = getDamage(DamageModifier.BASE); + for (DamageModifier modifier : MODIFIERS) { + if (!isApplicable(modifier)) { + continue; + } + + Function modifierFunction = modifierFunctions.get(modifier); + double newVanilla = modifierFunction.apply(remaining); + double oldVanilla = modifierFunction.apply(oldRemaining); + double difference = oldVanilla - newVanilla; + + // Don't allow value to cross zero, assume zero values should be negative + double old = getDamage(modifier); + if (old > 0) { + setDamage(modifier, Math.max(0, old - difference)); + } else { + setDamage(modifier, Math.min(0, old - difference)); + } + remaining += newVanilla; + oldRemaining += oldVanilla; + } + + setDamage(DamageModifier.BASE, damage); + } + + /** + * This method exists for legacy reasons to provide backwards + * compatibility. It will not exist at runtime and should not be used + * under any circumstances. + * + * @param damage the new damage value + */ + @Deprecated + public void _INVALID_setDamage(int damage) { + setDamage(damage); + } + + /** + * Gets the cause of the damage. + * + * @return A DamageCause value detailing the cause of the damage. + */ + public DamageCause getCause() { + return cause; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + /** + * An enum to specify the types of modifier + */ + public enum DamageModifier { + /** + * This represents the amount of damage being done, also known as the + * raw {@link EntityDamageEvent#getDamage()}. + */ + BASE, + /** + * This represents the damage reduced by a wearing a helmet when hit + * by a falling block. + */ + HARD_HAT, + /** + * This represents the damage reduction caused by blocking, only present for + * {@link Player Players}. + */ + BLOCKING, + /** + * This represents the damage reduction caused by wearing armor. + */ + ARMOR, + /** + * This represents the damage reduction caused by the Resistance potion effect. + */ + RESISTANCE, + /** + * This represents the damage reduction caused by the combination of: + *

    + *
  • + * Armor enchantments + *
  • + * Witch's potion resistance + *
  • + *
+ */ + MAGIC, + /** + * This represents the damage reduction caused by the absorption potion + * effect. + */ + ABSORPTION, + } + + /** + * An enum to specify the cause of the damage + */ + public enum DamageCause { + + /** + * Damage caused when an entity contacts a block such as a Cactus. + *

+ * Damage: 1 (Cactus) + */ + CONTACT, + /** + * Damage caused when an entity attacks another entity. + *

+ * Damage: variable + */ + ENTITY_ATTACK, + /** + * Damage caused when attacked by a projectile. + *

+ * Damage: variable + */ + PROJECTILE, + /** + * Damage caused by being put in a block + *

+ * Damage: 1 + */ + SUFFOCATION, + /** + * Damage caused when an entity falls a distance greater than 3 blocks + *

+ * Damage: fall height - 3.0 + */ + FALL, + /** + * Damage caused by direct exposure to fire + *

+ * Damage: 1 + */ + FIRE, + /** + * Damage caused due to burns caused by fire + *

+ * Damage: 1 + */ + FIRE_TICK, + /** + * Damage caused due to a snowman melting + *

+ * Damage: 1 + */ + MELTING, + /** + * Damage caused by direct exposure to lava + *

+ * Damage: 4 + */ + LAVA, + /** + * Damage caused by running out of air while in water + *

+ * Damage: 2 + */ + DROWNING, + /** + * Damage caused by being in the area when a block explodes. + *

+ * Damage: variable + */ + BLOCK_EXPLOSION, + /** + * Damage caused by being in the area when an entity, such as a + * Creeper, explodes. + *

+ * Damage: variable + */ + ENTITY_EXPLOSION, + /** + * Damage caused by falling into the void + *

+ * Damage: 4 for players + */ + VOID, + /** + * Damage caused by being struck by lightning + *

+ * Damage: 5 + */ + LIGHTNING, + /** + * Damage caused by committing suicide using the command "/kill" + *

+ * Damage: 1000 + */ + SUICIDE, + /** + * Damage caused by starving due to having an empty hunger bar + *

+ * Damage: 1 + */ + STARVATION, + /** + * Damage caused due to an ongoing poison effect + *

+ * Damage: 1 + */ + POISON, + /** + * Damage caused by being hit by a damage potion or spell + *

+ * Damage: variable + */ + MAGIC, + /** + * Damage caused by Wither potion effect + */ + WITHER, + /** + * Damage caused by being hit by a falling block which deals damage + *

+ * Note: Not every block deals damage + *

+ * Damage: variable + */ + FALLING_BLOCK, + /** + * Damage caused in retaliation to another attack by the Thorns + * enchantment. + *

+ * Damage: 1-4 (Thorns) + */ + THORNS, + /** + * Custom damage. + *

+ * Damage: variable + */ + CUSTOM + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/EntityDeathEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/EntityDeathEvent.java new file mode 100644 index 0000000..97e7346 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/EntityDeathEvent.java @@ -0,0 +1,73 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.LivingEntity; +import org.bukkit.event.HandlerList; +import org.bukkit.inventory.ItemStack; + +import java.util.List; + +/** + * Thrown whenever a LivingEntity dies + */ +public class EntityDeathEvent extends EntityEvent { + private static final HandlerList handlers = new HandlerList(); + private final List drops; + private int dropExp = 0; + + public EntityDeathEvent(final LivingEntity entity, final List drops) { + this(entity, drops, 0); + } + + public EntityDeathEvent(final LivingEntity what, final List drops, final int droppedExp) { + super(what); + this.drops = drops; + this.dropExp = droppedExp; + } + + @Override + public LivingEntity getEntity() { + return (LivingEntity) entity; + } + + /** + * Gets how much EXP should be dropped from this death. + *

+ * This does not indicate how much EXP should be taken from the entity in + * question, merely how much should be created after its death. + * + * @return Amount of EXP to drop. + */ + public int getDroppedExp() { + return dropExp; + } + + /** + * Sets how much EXP should be dropped from this death. + *

+ * This does not indicate how much EXP should be taken from the entity in + * question, merely how much should be created after its death. + * + * @param exp Amount of EXP to drop. + */ + public void setDroppedExp(int exp) { + this.dropExp = exp; + } + + /** + * Gets all the items which will drop when the entity dies + * + * @return Items to drop when the entity dies + */ + public List getDrops() { + return drops; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/EntityEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/EntityEvent.java new file mode 100644 index 0000000..c9a4ab3 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/EntityEvent.java @@ -0,0 +1,34 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.event.Event; + +/** + * Represents an Entity-related event + */ +public abstract class EntityEvent extends Event { + protected Entity entity; + + public EntityEvent(final Entity what) { + entity = what; + } + + /** + * Returns the Entity involved in this event + * + * @return Entity who is involved in this event + */ + public Entity getEntity() { + return entity; + } + + /** + * Gets the EntityType of the Entity involved in this event. + * + * @return EntityType of the Entity involved in this event + */ + public EntityType getEntityType() { + return entity.getType(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/EntityExplodeEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/EntityExplodeEvent.java new file mode 100644 index 0000000..287035d --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/EntityExplodeEvent.java @@ -0,0 +1,85 @@ +package org.bukkit.event.entity; + +import org.bukkit.Location; +import org.bukkit.block.Block; +import org.bukkit.entity.Entity; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +import java.util.List; + +/** + * Called when an entity explodes + */ +public class EntityExplodeEvent extends EntityEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancel; + private final Location location; + private final List blocks; + private float yield; + + public EntityExplodeEvent(final Entity what, final Location location, final List blocks, final float yield) { + super(what); + this.location = location; + this.blocks = blocks; + this.yield = yield; + this.cancel = false; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + /** + * Returns the list of blocks that would have been removed or were removed + * from the explosion event. + * + * @return All blown-up blocks + */ + public List blockList() { + return blocks; + } + + /** + * Returns the location where the explosion happened. + *

+ * It is not possible to get this value from the Entity as the Entity no + * longer exists in the world. + * + * @return The location of the explosion + */ + public Location getLocation() { + return location; + } + + /** + * Returns the percentage of blocks to drop from this explosion + * + * @return The yield. + */ + public float getYield() { + return yield; + } + + /** + * Sets the percentage of blocks to drop from this explosion + * + * @param yield The new yield percentage + */ + public void setYield(float yield) { + this.yield = yield; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/EntityInteractEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/EntityInteractEvent.java new file mode 100644 index 0000000..1c4e100 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/EntityInteractEvent.java @@ -0,0 +1,46 @@ +package org.bukkit.event.entity; + +import org.bukkit.block.Block; +import org.bukkit.entity.Entity; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when an entity interacts with an object + */ +public class EntityInteractEvent extends EntityEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + protected Block block; + private boolean cancelled; + + public EntityInteractEvent(final Entity entity, final Block block) { + super(entity); + this.block = block; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + cancelled = cancel; + } + + /** + * Returns the involved block + * + * @return the block clicked with this item. + */ + public Block getBlock() { + return block; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/EntityPickupItemEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/EntityPickupItemEvent.java new file mode 100644 index 0000000..b583acc --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/EntityPickupItemEvent.java @@ -0,0 +1,67 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.Item; +import org.bukkit.entity.LivingEntity; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; +import org.jetbrains.annotations.NotNull; + +/** + * Thrown when a entity picks an item up from the ground + */ +public class EntityPickupItemEvent extends EntityEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final Item item; + private boolean cancel = false; + private final int remaining; + + public EntityPickupItemEvent(@NotNull final LivingEntity entity, @NotNull final Item item, final int remaining) { + super(entity); + this.item = item; + this.remaining = remaining; + } + + @NotNull + @Override + public LivingEntity getEntity() { + return (LivingEntity) entity; + } + + /** + * Gets the Item picked up by the entity. + * + * @return Item + */ + @NotNull + public Item getItem() { + return item; + } + + /** + * Gets the amount remaining on the ground, if any + * + * @return amount remaining on the ground + */ + public int getRemaining() { + return remaining; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + @NotNull + @Override + public HandlerList getHandlers() { + return handlers; + } + + @NotNull + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/EntityPortalEnterEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/EntityPortalEnterEvent.java new file mode 100644 index 0000000..77fdbb3 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/EntityPortalEnterEvent.java @@ -0,0 +1,36 @@ +package org.bukkit.event.entity; + +import org.bukkit.Location; +import org.bukkit.entity.Entity; +import org.bukkit.event.HandlerList; + +/** + * Called when an entity comes into contact with a portal + */ +public class EntityPortalEnterEvent extends EntityEvent { + private static final HandlerList handlers = new HandlerList(); + private final Location location; + + public EntityPortalEnterEvent(final Entity entity, final Location location) { + super(entity); + this.location = location; + } + + /** + * Gets the portal block the entity is touching + * + * @return The portal block the entity is touching + */ + public Location getLocation() { + return location; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/EntityPortalEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/EntityPortalEvent.java new file mode 100644 index 0000000..835c054 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/EntityPortalEvent.java @@ -0,0 +1,82 @@ +package org.bukkit.event.entity; + +import org.bukkit.Location; +import org.bukkit.TravelAgent; +import org.bukkit.entity.Entity; +import org.bukkit.event.HandlerList; + +/** + * Called when a non-player entity is about to teleport because it is in + * contact with a portal. + *

+ * For players see {@link org.bukkit.event.player.PlayerPortalEvent} + */ +public class EntityPortalEvent extends EntityTeleportEvent { + private static final HandlerList handlers = new HandlerList(); + protected boolean useTravelAgent = true; + protected TravelAgent travelAgent; + + public EntityPortalEvent(final Entity entity, final Location from, final Location to, final TravelAgent pta) { + super(entity, from, to); + this.travelAgent = pta; + } + + /** + * Sets whether or not the Travel Agent will be used. + *

+ * If this is set to true, the TravelAgent will try to find a Portal at + * the {@link #getTo()} Location, and will try to create one if there is + * none. + *

+ * If this is set to false, the {@link #getEntity()} will only be + * teleported to the {@link #getTo()} Location. + * + * @param useTravelAgent whether to use the Travel Agent + */ + public void useTravelAgent(boolean useTravelAgent) { + this.useTravelAgent = useTravelAgent; + } + + /** + * Gets whether or not the Travel Agent will be used. + *

+ * If this is set to true, the TravelAgent will try to find a Portal at + * the {@link #getTo()} Location, and will try to create one if there is + * none. + *

+ * If this is set to false, the {@link #getEntity()} will only be + * teleported to the {@link #getTo()} Location. + * + * @return whether to use the Travel Agent + */ + public boolean useTravelAgent() { + return useTravelAgent; + } + + /** + * Gets the Travel Agent used (or not) in this event. + * + * @return the Travel Agent used (or not) in this event + */ + public TravelAgent getPortalTravelAgent() { + return this.travelAgent; + } + + /** + * Sets the Travel Agent used (or not) in this event. + * + * @param travelAgent the Travel Agent used (or not) in this event + */ + public void setPortalTravelAgent(TravelAgent travelAgent) { + this.travelAgent = travelAgent; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} \ No newline at end of file diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/EntityPortalExitEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/EntityPortalExitEvent.java new file mode 100644 index 0000000..41edef6 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/EntityPortalExitEvent.java @@ -0,0 +1,62 @@ +package org.bukkit.event.entity; + +import org.bukkit.Location; +import org.bukkit.entity.Entity; +import org.bukkit.event.HandlerList; +import org.bukkit.util.Vector; + +/** + * Called before an entity exits a portal. + *

+ * This event allows you to modify the velocity of the entity after they have + * successfully exited the portal. + */ +public class EntityPortalExitEvent extends EntityTeleportEvent { + private static final HandlerList handlers = new HandlerList(); + private Vector before; + private Vector after; + + public EntityPortalExitEvent(final Entity entity, final Location from, final Location to, final Vector before, final Vector after) { + super(entity, from, to); + this.before = before; + this.after = after; + } + + /** + * Gets a copy of the velocity that the entity has before entering the + * portal. + * + * @return velocity of entity before entering the portal + */ + public Vector getBefore() { + return this.before.clone(); + } + + /** + * Gets a copy of the velocity that the entity will have after exiting the + * portal. + * + * @return velocity of entity after exiting the portal + */ + public Vector getAfter() { + return this.after.clone(); + } + + /** + * Sets the velocity that the entity will have after exiting the portal. + * + * @param after the velocity after exiting the portal + */ + public void setAfter(Vector after) { + this.after = after.clone(); + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} \ No newline at end of file diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/EntityRegainHealthEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/EntityRegainHealthEvent.java new file mode 100644 index 0000000..a7b3517 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/EntityRegainHealthEvent.java @@ -0,0 +1,143 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.Entity; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; +import org.bukkit.util.NumberConversions; + +/** + * Stores data for health-regain events + */ +public class EntityRegainHealthEvent extends EntityEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled; + private double amount; + private final RegainReason regainReason; + + @Deprecated + public EntityRegainHealthEvent(final Entity entity, final int amount, final RegainReason regainReason) { + this(entity, (double) amount, regainReason); + } + + public EntityRegainHealthEvent(final Entity entity, final double amount, final RegainReason regainReason) { + super(entity); + this.amount = amount; + this.regainReason = regainReason; + } + + /** + * Gets the amount of regained health + * + * @return The amount of health regained + */ + public double getAmount() { + return amount; + } + + /** + * This method exists for legacy reasons to provide backwards + * compatibility. It will not exist at runtime and should not be used + * under any circumstances. + * + * @return the (rounded) amount regained + */ + @Deprecated + public int _INVALID_getAmount() { + return NumberConversions.ceil(getAmount()); + } + + /** + * Sets the amount of regained health + * + * @param amount the amount of health the entity will regain + */ + public void setAmount(double amount) { + this.amount = amount; + } + + /** + * This method exists for legacy reasons to provide backwards + * compatibility. It will not exist at runtime and should not be used + * under any circumstances. + * + * @param amount the amount that will be regained + */ + @Deprecated + public void _INVALID_setAmount(int amount) { + setAmount(amount); + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @Override + public void setCancelled(boolean cancel) { + cancelled = cancel; + } + + /** + * Gets the reason for why the entity is regaining health + * + * @return A RegainReason detailing the reason for the entity regaining + * health + */ + public RegainReason getRegainReason() { + return regainReason; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + /** + * An enum to specify the type of health regaining that is occurring + */ + public enum RegainReason { + + /** + * When a player regains health from regenerating due to Peaceful mode + * (difficulty=0) + */ + REGEN, + /** + * When a player regains health from regenerating due to their hunger + * being satisfied + */ + SATIATED, + /** + * When a player regains health from eating consumables + */ + EATING, + /** + * When an ender dragon regains health from an ender crystal + */ + ENDER_CRYSTAL, + /** + * When a player is healed by a potion or spell + */ + MAGIC, + /** + * When a player is healed over time by a potion or spell + */ + MAGIC_REGEN, + /** + * When a wither is filling its health during spawning + */ + WITHER_SPAWN, + /** + * When an entity is damaged by the Wither potion effect + */ + WITHER, + /** + * Any other reason not covered by the reasons above + */ + CUSTOM + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/EntityShootBowEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/EntityShootBowEvent.java new file mode 100644 index 0000000..1f9dc59 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/EntityShootBowEvent.java @@ -0,0 +1,100 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Projectile; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; +import org.bukkit.inventory.ItemStack; + +/** + * Called when a LivingEntity shoots a bow firing an arrow + */ +public class EntityShootBowEvent extends EntityEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final ItemStack bow; + private Entity projectile; + private final float force; + private final int ticksInUse; // Beanes - add ticks in use to entity shoot bow event + private boolean cancelled; + + public EntityShootBowEvent(final LivingEntity shooter, final ItemStack bow, final Projectile projectile, final float force) { + this(shooter, bow, projectile, force, 0); + } + + public EntityShootBowEvent(final LivingEntity shooter, final ItemStack bow, final Projectile projectile, final float force, int ticksInUse) { + super(shooter); + this.bow = bow; + this.projectile = projectile; + this.force = force; + this.ticksInUse = ticksInUse; + } + + @Override + public LivingEntity getEntity() { + return (LivingEntity) entity; + } + + /** + * Gets the bow ItemStack used to fire the arrow. + * + * @return the bow involved in this event + */ + public ItemStack getBow() { + return bow; + } + + /** + * Gets the projectile which will be launched by this event + * + * @return the launched projectile + */ + public Entity getProjectile() { + return projectile; + } + + /** + * Replaces the projectile which will be launched + * + * @param projectile the new projectile + */ + public void setProjectile(Entity projectile) { + this.projectile = projectile; + } + + /** + * Gets the force the arrow was launched with + * + * @return bow shooting force, up to 1.0 + */ + public float getForce() { + return force; + } + + + /** + * Gets the amount of ticks the arrow was drawn for + * + * @return drawn ticks + */ + public int getTicksInUse() { + return ticksInUse; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + cancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/EntitySpawnEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/EntitySpawnEvent.java new file mode 100644 index 0000000..5dcf98f --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/EntitySpawnEvent.java @@ -0,0 +1,45 @@ +package org.bukkit.event.entity; + +import org.bukkit.Location; +import org.bukkit.entity.Entity; +import org.bukkit.event.HandlerList; + +/** + * Called when an entity is spawned into a world. + *

+ * If an Entity Spawn event is cancelled, the entity will not spawn. + */ +public class EntitySpawnEvent extends EntityEvent implements org.bukkit.event.Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean canceled; + + public EntitySpawnEvent(final Entity spawnee) { + super(spawnee); + } + + public boolean isCancelled() { + return canceled; + } + + public void setCancelled(boolean cancel) { + canceled = cancel; + } + + /** + * Gets the location at which the entity is spawning. + * + * @return The location at which the entity is spawning + */ + public Location getLocation() { + return getEntity().getLocation(); + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/EntityTameEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/EntityTameEvent.java new file mode 100644 index 0000000..f105817 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/EntityTameEvent.java @@ -0,0 +1,51 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.AnimalTamer; +import org.bukkit.entity.LivingEntity; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Thrown when a LivingEntity is tamed + */ +public class EntityTameEvent extends EntityEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled; + private final AnimalTamer owner; + + public EntityTameEvent(final LivingEntity entity, final AnimalTamer owner) { + super(entity); + this.owner = owner; + } + + @Override + public LivingEntity getEntity() { + return (LivingEntity) entity; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + cancelled = cancel; + } + + /** + * Gets the owning AnimalTamer + * + * @return the owning AnimalTamer + */ + public AnimalTamer getOwner() { + return owner; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/EntityTargetEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/EntityTargetEvent.java new file mode 100644 index 0000000..73617e8 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/EntityTargetEvent.java @@ -0,0 +1,150 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.Entity; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a creature targets or untargets another entity + */ +public class EntityTargetEvent extends EntityEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancel = false; + private Entity target; + private final TargetReason reason; + + public EntityTargetEvent(final Entity entity, final Entity target, final TargetReason reason) { + super(entity); + this.target = target; + this.reason = reason; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + /** + * Returns the reason for the targeting + * + * @return The reason + */ + public TargetReason getReason() { + return reason; + } + + /** + * Get the entity that this is targeting. + *

+ * This will be null in the case that the event is called when the mob + * forgets its target. + * + * @return The entity + */ + public Entity getTarget() { + return target; + } + + /** + * Set the entity that you want the mob to target instead. + *

+ * It is possible to be null, null will cause the entity to be + * target-less. + *

+ * This is different from cancelling the event. Cancelling the event will + * cause the entity to keep an original target, while setting to be null + * will cause the entity to be reset. + * + * @param target The entity to target + */ + public void setTarget(Entity target) { + this.target = target; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + /** + * An enum to specify the reason for the targeting + */ + public enum TargetReason { + + /** + * When the entity's target has died, and so it no longer targets it + */ + TARGET_DIED, + /** + * When the entity doesn't have a target, so it attacks the nearest + * player + */ + CLOSEST_PLAYER, + /** + * When the target attacks the entity, so entity targets it + */ + TARGET_ATTACKED_ENTITY, + /** + * When the target attacks a fellow pig zombie, so the whole group + * will target him with this reason. + */ + PIG_ZOMBIE_TARGET, + /** + * When the target is forgotten for whatever reason. + *

+ * Currently only occurs in with spiders when there is a high + * brightness. + */ + FORGOT_TARGET, + /** + * When the target attacks the owner of the entity, so the entity + * targets it. + */ + TARGET_ATTACKED_OWNER, + /** + * When the owner of the entity attacks the target attacks, so the + * entity targets it. + */ + OWNER_ATTACKED_TARGET, + /** + * When the entity has no target, so the entity randomly chooses one. + */ + RANDOM_TARGET, + /** + * When an entity selects a target while defending a village. + */ + DEFEND_VILLAGE, + /** + * When the target attacks a nearby entity of the same type, so the entity targets it + */ + TARGET_ATTACKED_NEARBY_ENTITY, + /** + * When a zombie targeting an entity summons reinforcements, so the reinforcements target the same entity + */ + REINFORCEMENT_TARGET, + /** + * When an entity targets another entity after colliding with it. + */ + COLLISION, + /** + * For custom calls to the event. + */ + CUSTOM, + /** + * When the entity doesn't have a target, so it attacks the nearest + * entity + */ + CLOSEST_ENTITY, + /** + * A currently unknown reason for the entity changing target. + */ + UNKNOWN + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/EntityTargetLivingEntityEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/EntityTargetLivingEntityEvent.java new file mode 100644 index 0000000..cd9aea1 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/EntityTargetLivingEntityEvent.java @@ -0,0 +1,34 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; + +/** + * Called when an Entity targets a {@link LivingEntity} and can only target + * LivingEntity's. + */ +public class EntityTargetLivingEntityEvent extends EntityTargetEvent{ + public EntityTargetLivingEntityEvent(final Entity entity, final LivingEntity target, final TargetReason reason) { + super(entity, target, reason); + } + + public LivingEntity getTarget() { + return (LivingEntity) super.getTarget(); + } + + /** + * Set the Entity that you want the mob to target. + *

+ * It is possible to be null, null will cause the entity to be + * target-less. + *

+ * Must be a LivingEntity, or null. + * + * @param target The entity to target + */ + public void setTarget(Entity target) { + if (target == null || target instanceof LivingEntity) { + super.setTarget(target); + } + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/EntityTeleportEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/EntityTeleportEvent.java new file mode 100644 index 0000000..619f8d4 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/EntityTeleportEvent.java @@ -0,0 +1,77 @@ +package org.bukkit.event.entity; + +import org.bukkit.Location; +import org.bukkit.entity.Entity; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Thrown when a non-player entity (such as an Enderman) tries to teleport + * from one location to another. + */ +public class EntityTeleportEvent extends EntityEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancel; + private Location from; + private Location to; + + public EntityTeleportEvent(Entity what, Location from, Location to) { + super(what); + this.from = from; + this.to = to; + this.cancel = false; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + /** + * Gets the location that this entity moved from + * + * @return Location this entity moved from + */ + public Location getFrom() { + return from; + } + + /** + * Sets the location that this entity moved from + * + * @param from New location this entity moved from + */ + public void setFrom(Location from) { + this.from = from; + } + + /** + * Gets the location that this entity moved to + * + * @return Location the entity moved to + */ + public Location getTo() { + return to; + } + + /** + * Sets the location that this entity moved to + * + * @param to New Location this entity moved to + */ + public void setTo(Location to) { + this.to = to; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} \ No newline at end of file diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/EntityUnleashEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/EntityUnleashEvent.java new file mode 100644 index 0000000..edb7ecb --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/EntityUnleashEvent.java @@ -0,0 +1,52 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.Entity; +import org.bukkit.event.HandlerList; + +/** + * Called immediately prior to an entity being unleashed. + */ +public class EntityUnleashEvent extends EntityEvent { + private static final HandlerList handlers = new HandlerList(); + private final UnleashReason reason; + + public EntityUnleashEvent(Entity entity, UnleashReason reason) { + super(entity); + this.reason = reason; + } + + /** + * Returns the reason for the unleashing. + * + * @return The reason + */ + public UnleashReason getReason() { + return reason; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + public enum UnleashReason { + /** + * When the entity's leashholder has died or logged out, and so is + * unleashed + */ + HOLDER_GONE, + /** + * When the entity's leashholder attempts to unleash it + */ + PLAYER_UNLEASH, + /** + * When the entity's leashholder is more than 10 blocks away + */ + DISTANCE, + UNKNOWN + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/ExpBottleEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/ExpBottleEvent.java new file mode 100644 index 0000000..4f64424 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/ExpBottleEvent.java @@ -0,0 +1,75 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.ThrownExpBottle; +import org.bukkit.event.HandlerList; + +/** + * Called when a ThrownExpBottle hits and releases experience. + */ +public class ExpBottleEvent extends ProjectileHitEvent { + private static final HandlerList handlers = new HandlerList(); + private int exp; + private boolean showEffect = true; + + public ExpBottleEvent(final ThrownExpBottle bottle, final int exp) { + super(bottle); + this.exp = exp; + } + + @Override + public ThrownExpBottle getEntity() { + return (ThrownExpBottle) entity; + } + + /** + * This method indicates if the particle effect should be shown. + * + * @return true if the effect will be shown, false otherwise + */ + public boolean getShowEffect() { + return this.showEffect; + } + + /** + * This method sets if the particle effect will be shown. + *

+ * This does not change the experience created. + * + * @param showEffect true indicates the effect will be shown, false + * indicates no effect will be shown + */ + public void setShowEffect(final boolean showEffect) { + this.showEffect = showEffect; + } + + /** + * This method retrieves the amount of experience to be created. + *

+ * The number indicates a total amount to be divided into orbs. + * + * @return the total amount of experience to be created + */ + public int getExperience() { + return exp; + } + + /** + * This method sets the amount of experience to be created. + *

+ * The number indicates a total amount to be divided into orbs. + * + * @param exp the total amount of experience to be created + */ + public void setExperience(final int exp) { + this.exp = exp; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/ExplosionPrimeEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/ExplosionPrimeEvent.java new file mode 100644 index 0000000..7ca6a55 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/ExplosionPrimeEvent.java @@ -0,0 +1,80 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.Entity; +import org.bukkit.entity.Explosive; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when an entity has made a decision to explode. + */ +public class ExplosionPrimeEvent extends EntityEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancel; + private float radius; + private boolean fire; + + public ExplosionPrimeEvent(final Entity what, final float radius, final boolean fire) { + super(what); + this.cancel = false; + this.radius = radius; + this.fire = fire; + } + + public ExplosionPrimeEvent(final Explosive explosive) { + this(explosive, explosive.getYield(), explosive.isIncendiary()); + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + /** + * Gets the radius of the explosion + * + * @return returns the radius of the explosion + */ + public float getRadius() { + return radius; + } + + /** + * Sets the radius of the explosion + * + * @param radius the radius of the explosion + */ + public void setRadius(float radius) { + this.radius = radius; + } + + /** + * Gets whether this explosion will create fire or not + * + * @return true if this explosion will create fire + */ + public boolean getFire() { + return fire; + } + + /** + * Sets whether this explosion will create fire or not + * + * @param fire true if you want this explosion to create fire + */ + public void setFire(boolean fire) { + this.fire = fire; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/FireworkExplodeEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/FireworkExplodeEvent.java new file mode 100644 index 0000000..81b1c48 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/FireworkExplodeEvent.java @@ -0,0 +1,49 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.Firework; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a firework explodes. + */ +public class FireworkExplodeEvent extends EntityEvent implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + private boolean cancel; + + public FireworkExplodeEvent(final Firework what) { + super(what); + } + + @Override + public boolean isCancelled() { + return cancel; + } + + /** + * Set the cancelled state of this event. If the firework explosion is + * cancelled, the firework will still be removed, but no particles will be + * displayed. + * + * @param cancel whether to cancel or not. + */ + @Override + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + @Override + public Firework getEntity() { + return (Firework) super.getEntity(); + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/FoodLevelChangeEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/FoodLevelChangeEvent.java new file mode 100644 index 0000000..f6e2472 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/FoodLevelChangeEvent.java @@ -0,0 +1,67 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.HumanEntity; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a human entity's food level changes + */ +public class FoodLevelChangeEvent extends EntityEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancel = false; + private int level; + + public FoodLevelChangeEvent(final HumanEntity what, final int level) { + super(what); + this.level = level; + } + + @Override + public HumanEntity getEntity() { + return (HumanEntity) entity; + } + + /** + * Gets the resultant food level that the entity involved in this event + * should be set to. + *

+ * Where 20 is a full food bar and 0 is an empty one. + * + * @return The resultant food level + */ + public int getFoodLevel() { + return level; + } + + /** + * Sets the resultant food level that the entity involved in this event + * should be set to + * + * @param level the resultant food level that the entity involved in this + * event should be set to + */ + public void setFoodLevel(int level) { + if (level > 20) level = 20; + else if (level < 0) level = 0; + + this.level = level; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/HorseJumpEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/HorseJumpEvent.java new file mode 100644 index 0000000..fad2468 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/HorseJumpEvent.java @@ -0,0 +1,78 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.Horse; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a horse jumps. + */ +public class HorseJumpEvent extends EntityEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled; + private float power; + + public HorseJumpEvent(final Horse horse, final float power) { + super(horse); + this.power = power; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + cancelled = cancel; + } + + @Override + public Horse getEntity() { + return (Horse) entity; + } + + /** + * Gets the power of the jump. + *

+ * Power is a value that defines how much of the horse's jump strength + * should be used for the jump. Power is effectively multiplied times + * the horse's jump strength to determine how high the jump is; 0 + * represents no jump strength while 1 represents full jump strength. + * Setting power to a value above 1 will use additional jump strength + * that the horse does not usually have. + *

+ * Power does not affect how high the horse is capable of jumping, only + * how much of its jumping capability will be used in this jump. To set + * the horse's overall jump strength, see {@link + * Horse#setJumpStrength(double)}. + * + * @return jump strength + */ + public float getPower() { + return power; + } + + /** + * Sets the power of the jump. + *

+ * Jump power can be set to a value above 1.0 which will increase the + * strength of this jump above the horse's actual jump strength. + *

+ * Setting the jump power to 0 will result in the jump animation still + * playing, but the horse not leaving the ground. Only canceling this + * event will result in no jump animation at all. + * + * @param power power of the jump + */ + public void setPower(float power) { + this.power = power; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/ItemDespawnEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/ItemDespawnEvent.java new file mode 100644 index 0000000..23b9112 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/ItemDespawnEvent.java @@ -0,0 +1,55 @@ +package org.bukkit.event.entity; + +import org.bukkit.Location; +import org.bukkit.entity.Item; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * This event is called when a {@link Item} is removed from + * the world because it has existed for 5 minutes. + *

+ * Cancelling the event results in the item being allowed to exist for 5 more + * minutes. This behavior is not guaranteed and may change in future versions. + */ +public class ItemDespawnEvent extends EntityEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean canceled; + private final Location location; + + public ItemDespawnEvent(final Item despawnee, final Location loc) { + super(despawnee); + location = loc; + } + + public boolean isCancelled() { + return canceled; + } + + public void setCancelled(boolean cancel) { + canceled = cancel; + } + + @Override + public Item getEntity() { + return (Item) entity; + } + + /** + * Gets the location at which the item is despawning. + * + * @return The location at which the item is despawning + */ + public Location getLocation() { + return location; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/ItemMergeEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/ItemMergeEvent.java new file mode 100644 index 0000000..dadf221 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/ItemMergeEvent.java @@ -0,0 +1,50 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.Item; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +public class ItemMergeEvent extends EntityEvent implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled; + private final Item target; + + public ItemMergeEvent(Item item, Item target) { + super(item); + this.target = target; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + + @Override + public Item getEntity() { + return (Item) entity; + } + + /** + * Gets the Item entity the main Item is being merged into. + * + * @return The Item being merged with + */ + public Item getTarget() { + return target; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/ItemSpawnEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/ItemSpawnEvent.java new file mode 100644 index 0000000..776f8e7 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/ItemSpawnEvent.java @@ -0,0 +1,23 @@ +package org.bukkit.event.entity; + +import org.bukkit.Location; +import org.bukkit.entity.Item; + +/** + * Called when an item is spawned into a world + */ +public class ItemSpawnEvent extends EntitySpawnEvent { + public ItemSpawnEvent(final Item spawnee) { + super(spawnee); + } + + @Deprecated + public ItemSpawnEvent(final Item spawnee, final Location loc) { + this(spawnee); + } + + @Override + public Item getEntity() { + return (Item) entity; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/PigZapEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/PigZapEvent.java new file mode 100644 index 0000000..aa80ebf --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/PigZapEvent.java @@ -0,0 +1,64 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.LightningStrike; +import org.bukkit.entity.Pig; +import org.bukkit.entity.PigZombie; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Stores data for pigs being zapped + */ +public class PigZapEvent extends EntityEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean canceled; + private final PigZombie pigzombie; + private final LightningStrike bolt; + + public PigZapEvent(final Pig pig, final LightningStrike bolt, final PigZombie pigzombie) { + super(pig); + this.bolt = bolt; + this.pigzombie = pigzombie; + } + + public boolean isCancelled() { + return canceled; + } + + public void setCancelled(boolean cancel) { + canceled = cancel; + } + + @Override + public Pig getEntity() { + return (Pig) entity; + } + + /** + * Gets the bolt which is striking the pig. + * + * @return lightning entity + */ + public LightningStrike getLightning() { + return bolt; + } + + /** + * Gets the zombie pig that will replace the pig, provided the event is + * not cancelled first. + * + * @return resulting entity + */ + public PigZombie getPigZombie() { + return pigzombie; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/PlayerDeathEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/PlayerDeathEvent.java new file mode 100644 index 0000000..286b7f2 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/PlayerDeathEvent.java @@ -0,0 +1,161 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.List; + +/** + * Thrown whenever a {@link Player} dies + */ +public class PlayerDeathEvent extends EntityDeathEvent { + private int newExp = 0; + private String deathMessage = ""; + private int newLevel = 0; + private int newTotalExp = 0; + private boolean keepLevel = false; + private boolean keepInventory = false; + + public PlayerDeathEvent(final Player player, final List drops, final int droppedExp, final String deathMessage) { + this(player, drops, droppedExp, 0, deathMessage); + } + + public PlayerDeathEvent(final Player player, final List drops, final int droppedExp, final int newExp, final String deathMessage) { + this(player, drops, droppedExp, newExp, 0, 0, deathMessage); + } + + public PlayerDeathEvent(final Player player, final List drops, final int droppedExp, final int newExp, final int newTotalExp, final int newLevel, final String deathMessage) { + super(player, drops, droppedExp); + this.newExp = newExp; + this.newTotalExp = newTotalExp; + this.newLevel = newLevel; + this.deathMessage = deathMessage; + } + + @Override + public Player getEntity() { + return (Player) entity; + } + + /** + * Set the death message that will appear to everyone on the server. + * + * @param deathMessage Message to appear to other players on the server. + */ + public void setDeathMessage(String deathMessage) { + this.deathMessage = deathMessage; + } + + /** + * Get the death message that will appear to everyone on the server. + * + * @return Message to appear to other players on the server. + */ + public String getDeathMessage() { + return deathMessage; + } + + /** + * Gets how much EXP the Player should have at respawn. + *

+ * This does not indicate how much EXP should be dropped, please see + * {@link #getDroppedExp()} for that. + * + * @return New EXP of the respawned player + */ + public int getNewExp() { + return newExp; + } + + /** + * Sets how much EXP the Player should have at respawn. + *

+ * This does not indicate how much EXP should be dropped, please see + * {@link #setDroppedExp(int)} for that. + * + * @param exp New EXP of the respawned player + */ + public void setNewExp(int exp) { + newExp = exp; + } + + /** + * Gets the Level the Player should have at respawn. + * + * @return New Level of the respawned player + */ + public int getNewLevel() { + return newLevel; + } + + /** + * Sets the Level the Player should have at respawn. + * + * @param level New Level of the respawned player + */ + public void setNewLevel(int level) { + newLevel = level; + } + + /** + * Gets the Total EXP the Player should have at respawn. + * + * @return New Total EXP of the respawned player + */ + public int getNewTotalExp() { + return newTotalExp; + } + + /** + * Sets the Total EXP the Player should have at respawn. + * + * @param totalExp New Total EXP of the respawned player + */ + public void setNewTotalExp(int totalExp) { + newTotalExp = totalExp; + } + + /** + * Gets if the Player should keep all EXP at respawn. + *

+ * This flag overrides other EXP settings + * + * @return True if Player should keep all pre-death exp + */ + public boolean getKeepLevel() { + return keepLevel; + } + + /** + * Sets if the Player should keep all EXP at respawn. + *

+ * This overrides all other EXP settings + *

+ * This doesn't prevent prevent the EXP from dropping. + * {@link #setDroppedExp(int)} should be used stop the + * EXP from dropping. + * + * @param keepLevel True to keep all current value levels + */ + public void setKeepLevel(boolean keepLevel) { + this.keepLevel = keepLevel; + } + + /** + * Sets if the Player keeps inventory on death. + * + * @param keepInventory True to keep the inventory + */ + public void setKeepInventory(boolean keepInventory) { + this.keepInventory = keepInventory; + } + + /** + * Gets if the Player keeps inventory on death. + * + * @return True if the player keeps inventory on death + */ + public boolean getKeepInventory() { + return keepInventory; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/PlayerLeashEntityEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/PlayerLeashEntityEvent.java new file mode 100644 index 0000000..74d458a --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/PlayerLeashEntityEvent.java @@ -0,0 +1,68 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +/** + * Called immediately prior to a creature being leashed by a player. + */ +public class PlayerLeashEntityEvent extends Event implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final Entity leashHolder; + private final Entity entity; + private boolean cancelled = false; + private final Player player; + + public PlayerLeashEntityEvent(Entity what, Entity leashHolder, Player leasher) { + this.leashHolder = leashHolder; + this.entity = what; + this.player = leasher; + } + + /** + * Returns the entity that is holding the leash. + * + * @return The leash holder + */ + public Entity getLeashHolder() { + return leashHolder; + } + + /** + * Returns the entity being leashed. + * + * @return The entity + */ + public Entity getEntity() { + return entity; + } + + /** + * Returns the player involved in this event + * + * @return Player who is involved in this event + */ + public final Player getPlayer() { + return player; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + public boolean isCancelled() { + return this.cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/PotionEffectAddEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/PotionEffectAddEvent.java new file mode 100644 index 0000000..7fd1ef3 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/PotionEffectAddEvent.java @@ -0,0 +1,46 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.LivingEntity; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; +import org.bukkit.potion.PotionEffect; + +public class PotionEffectAddEvent extends PotionEffectEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + protected final EffectCause effectCause; + private boolean cancelled; + + public PotionEffectAddEvent(LivingEntity entity, PotionEffect effect, EffectCause effectCause) { + super(entity, effect); + this.effectCause = effectCause; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + public EffectCause getCause() { + return this.effectCause; + } + + public boolean isCancelled() { + return this.cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + public HandlerList getHandlers() { + return handlers; + } + + public enum EffectCause { + POTION_SPLASH, + BEACON, + WITHER_SKELETON, + WITHER_SKULL, + PLUGIN, + UNKNOWN + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/PotionEffectEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/PotionEffectEvent.java new file mode 100644 index 0000000..9aab309 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/PotionEffectEvent.java @@ -0,0 +1,21 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.LivingEntity; +import org.bukkit.potion.PotionEffect; + +public abstract class PotionEffectEvent extends EntityEvent { + private final PotionEffect effect; + + public PotionEffectEvent(LivingEntity what, PotionEffect effect) { + super(what); + this.effect = effect; + } + + public LivingEntity getEntity() { + return (LivingEntity) super.getEntity(); + } + + public PotionEffect getEffect() { + return this.effect; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/PotionEffectExpireEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/PotionEffectExpireEvent.java new file mode 100644 index 0000000..6663d78 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/PotionEffectExpireEvent.java @@ -0,0 +1,28 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.LivingEntity; +import org.bukkit.potion.PotionEffect; + +public class PotionEffectExpireEvent extends PotionEffectRemoveEvent { + private int duration = 0; + + public PotionEffectExpireEvent(LivingEntity entity, PotionEffect effect) { + super(entity, effect); + } + + public int getDuration() { + return this.duration; + } + + public void setDuration(int duration) { + this.duration = Math.max(0, duration); + } + + public boolean isCancelled() { + return this.duration > 0; + } + + public void setCancelled(boolean cancel) { + this.duration = cancel ? 2147483647 : 0; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/PotionEffectExtendEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/PotionEffectExtendEvent.java new file mode 100644 index 0000000..21fcfe6 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/PotionEffectExtendEvent.java @@ -0,0 +1,17 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.LivingEntity; +import org.bukkit.potion.PotionEffect; + +public class PotionEffectExtendEvent extends PotionEffectAddEvent { + private final PotionEffect oldEffect; + + public PotionEffectExtendEvent(LivingEntity entity, PotionEffect effect, PotionEffect oldEffect, PotionEffectAddEvent.EffectCause cause) { + super(entity, effect, cause); + this.oldEffect = oldEffect; + } + + public PotionEffect getOldEffect() { + return this.oldEffect; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/PotionEffectRemoveEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/PotionEffectRemoveEvent.java new file mode 100644 index 0000000..eb1e787 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/PotionEffectRemoveEvent.java @@ -0,0 +1,31 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.LivingEntity; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; +import org.bukkit.potion.PotionEffect; + +public class PotionEffectRemoveEvent extends PotionEffectEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled; + + public PotionEffectRemoveEvent(LivingEntity entity, PotionEffect effect) { + super(entity, effect); + } + + public static HandlerList getHandlerList() { + return handlers; + } + + public boolean isCancelled() { + return this.cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + public HandlerList getHandlers() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/PotionSplashEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/PotionSplashEvent.java new file mode 100644 index 0000000..4599d2d --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/PotionSplashEvent.java @@ -0,0 +1,94 @@ +package org.bukkit.event.entity; + +import org.apache.commons.lang.Validate; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.ThrownPotion; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Map; + +/** + * Called when a splash potion hits an area + */ +public class PotionSplashEvent extends ProjectileHitEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled; + private final Map affectedEntities; + + public PotionSplashEvent(final ThrownPotion potion, final Map affectedEntities) { + super(potion); + + this.affectedEntities = affectedEntities; + } + + @Override + public ThrownPotion getEntity() { + return (ThrownPotion) entity; + } + + /** + * Gets the potion which caused this event + * + * @return The thrown potion entity + */ + public ThrownPotion getPotion() { + return (ThrownPotion) getEntity(); + } + + /** + * Retrieves a list of all effected entities + * + * @return A fresh copy of the affected entity list + */ + public Collection getAffectedEntities() { + return new ArrayList(affectedEntities.keySet()); + } + + /** + * Gets the intensity of the potion's effects for given entity; This + * depends on the distance to the impact center + * + * @param entity Which entity to get intensity for + * @return intensity relative to maximum effect; 0.0: not affected; 1.0: + * fully hit by potion effects + */ + public double getIntensity(LivingEntity entity) { + Double intensity = affectedEntities.get(entity); + return intensity != null ? intensity : 0.0; + } + + /** + * Overwrites the intensity for a given entity + * + * @param entity For which entity to define a new intensity + * @param intensity relative to maximum effect + */ + public void setIntensity(LivingEntity entity, double intensity) { + Validate.notNull(entity, "You must specify a valid entity."); + if (intensity <= 0.0) { + affectedEntities.remove(entity); + } else { + affectedEntities.put(entity, Math.min(intensity, 1.0)); + } + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + cancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/PrePearlLaunchEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/PrePearlLaunchEvent.java new file mode 100644 index 0000000..832ec2e --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/PrePearlLaunchEvent.java @@ -0,0 +1,37 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.Entity; +import org.bukkit.entity.Projectile; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +public class PrePearlLaunchEvent extends EntityEvent implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + + private boolean cancelled; + + public PrePearlLaunchEvent(Entity what) { + super(what); + } + + public static HandlerList getHandlerList() { + return handlers; + } + + public Projectile getEntity() { + return (Projectile) entity; + } + + public HandlerList getHandlers() { + return handlers; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/ProjectileHitEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/ProjectileHitEvent.java new file mode 100644 index 0000000..25ae832 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/ProjectileHitEvent.java @@ -0,0 +1,30 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.Projectile; +import org.bukkit.event.HandlerList; + +/** + * Called when a projectile hits an object + */ +public class ProjectileHitEvent extends EntityEvent { + private static final HandlerList handlers = new HandlerList(); + + public ProjectileHitEvent(final Projectile projectile) { + super(projectile); + } + + @Override + public Projectile getEntity() { + return (Projectile) entity; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + +} diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/ProjectileLaunchEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/ProjectileLaunchEvent.java new file mode 100644 index 0000000..0c9190c --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/ProjectileLaunchEvent.java @@ -0,0 +1,40 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.Entity; +import org.bukkit.entity.Projectile; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a projectile is launched. + */ +public class ProjectileLaunchEvent extends EntityEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled; + + public ProjectileLaunchEvent(Entity what) { + super(what); + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + cancelled = cancel; + } + + @Override + public Projectile getEntity() { + return (Projectile) entity; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/SheepDyeWoolEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/SheepDyeWoolEvent.java new file mode 100644 index 0000000..4c17fea --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/SheepDyeWoolEvent.java @@ -0,0 +1,62 @@ +package org.bukkit.event.entity; + +import org.bukkit.DyeColor; +import org.bukkit.entity.Sheep; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a sheep's wool is dyed + */ +public class SheepDyeWoolEvent extends EntityEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancel; + private DyeColor color; + + public SheepDyeWoolEvent(final Sheep sheep, final DyeColor color) { + super(sheep); + this.cancel = false; + this.color = color; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + @Override + public Sheep getEntity() { + return (Sheep) entity; + } + + /** + * Gets the DyeColor the sheep is being dyed + * + * @return the DyeColor the sheep is being dyed + */ + public DyeColor getColor() { + return color; + } + + /** + * Sets the DyeColor the sheep is being dyed + * + * @param color the DyeColor the sheep will be dyed + */ + public void setColor(DyeColor color) { + this.color = color; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + +} diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/SheepRegrowWoolEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/SheepRegrowWoolEvent.java new file mode 100644 index 0000000..e836f7b --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/SheepRegrowWoolEvent.java @@ -0,0 +1,41 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.Sheep; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a sheep regrows its wool + */ +public class SheepRegrowWoolEvent extends EntityEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancel; + + public SheepRegrowWoolEvent(final Sheep sheep) { + super(sheep); + this.cancel = false; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + @Override + public Sheep getEntity() { + return (Sheep) entity; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + +} diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/SlimeSplitEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/SlimeSplitEvent.java new file mode 100644 index 0000000..4b99587 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/SlimeSplitEvent.java @@ -0,0 +1,59 @@ +package org.bukkit.event.entity; + +import org.bukkit.entity.Slime; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a Slime splits into smaller Slimes upon death + */ +public class SlimeSplitEvent extends EntityEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancel = false; + private int count; + + public SlimeSplitEvent(final Slime slime, final int count) { + super(slime); + this.count = count; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + @Override + public Slime getEntity() { + return (Slime) entity; + } + + /** + * Gets the amount of smaller slimes to spawn + * + * @return the amount of slimes to spawn + */ + public int getCount() { + return count; + } + + /** + * Sets how many smaller slimes will spawn on the split + * + * @param count the amount of slimes to spawn + */ + public void setCount(int count) { + this.count = count; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} \ No newline at end of file diff --git a/azurite-api/src/main/java/org/bukkit/event/entity/SpawnerSpawnEvent.java b/azurite-api/src/main/java/org/bukkit/event/entity/SpawnerSpawnEvent.java new file mode 100644 index 0000000..1acb3c4 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/entity/SpawnerSpawnEvent.java @@ -0,0 +1,22 @@ +package org.bukkit.event.entity; + +import org.bukkit.block.CreatureSpawner; +import org.bukkit.entity.Entity; + +/** + * Called when an entity is spawned into a world by a spawner. + *

+ * If a Spawner Spawn event is cancelled, the entity will not spawn. + */ +public class SpawnerSpawnEvent extends EntitySpawnEvent { + private final CreatureSpawner spawner; + + public SpawnerSpawnEvent(final Entity spawnee, final CreatureSpawner spawner) { + super(spawnee); + this.spawner = spawner; + } + + public CreatureSpawner getSpawner() { + return spawner; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/hanging/HangingBreakByEntityEvent.java b/azurite-api/src/main/java/org/bukkit/event/hanging/HangingBreakByEntityEvent.java new file mode 100644 index 0000000..10cb780 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/hanging/HangingBreakByEntityEvent.java @@ -0,0 +1,25 @@ +package org.bukkit.event.hanging; + +import org.bukkit.entity.Entity; +import org.bukkit.entity.Hanging; + +/** + * Triggered when a hanging entity is removed by an entity + */ +public class HangingBreakByEntityEvent extends HangingBreakEvent { + private final Entity remover; + + public HangingBreakByEntityEvent(final Hanging hanging, final Entity remover) { + super(hanging, RemoveCause.ENTITY); + this.remover = remover; + } + + /** + * Gets the entity that removed the hanging entity + * + * @return the entity that removed the hanging entity + */ + public Entity getRemover() { + return remover; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/hanging/HangingBreakEvent.java b/azurite-api/src/main/java/org/bukkit/event/hanging/HangingBreakEvent.java new file mode 100644 index 0000000..45e320a --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/hanging/HangingBreakEvent.java @@ -0,0 +1,71 @@ +package org.bukkit.event.hanging; + +import org.bukkit.entity.Hanging; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Triggered when a hanging entity is removed + */ +public class HangingBreakEvent extends HangingEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled; + private final RemoveCause cause; + + public HangingBreakEvent(final Hanging hanging, final RemoveCause cause) { + super(hanging); + this.cause = cause; + } + + /** + * Gets the cause for the hanging entity's removal + * + * @return the RemoveCause for the hanging entity's removal + */ + public RemoveCause getCause() { + return cause; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + /** + * An enum to specify the cause of the removal + */ + public enum RemoveCause { + /** + * Removed by an entity + */ + ENTITY, + /** + * Removed by an explosion + */ + EXPLOSION, + /** + * Removed by placing a block on it + */ + OBSTRUCTION, + /** + * Removed by destroying the block behind it, etc + */ + PHYSICS, + /** + * Removed by an uncategorised cause + */ + DEFAULT, + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/hanging/HangingEvent.java b/azurite-api/src/main/java/org/bukkit/event/hanging/HangingEvent.java new file mode 100644 index 0000000..b370afe --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/hanging/HangingEvent.java @@ -0,0 +1,24 @@ +package org.bukkit.event.hanging; + +import org.bukkit.entity.Hanging; +import org.bukkit.event.Event; + +/** + * Represents a hanging entity-related event. + */ +public abstract class HangingEvent extends Event { + protected Hanging hanging; + + protected HangingEvent(final Hanging painting) { + this.hanging = painting; + } + + /** + * Gets the hanging entity involved in this event. + * + * @return the hanging entity + */ + public Hanging getEntity() { + return hanging; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/hanging/HangingPlaceEvent.java b/azurite-api/src/main/java/org/bukkit/event/hanging/HangingPlaceEvent.java new file mode 100644 index 0000000..b511c55 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/hanging/HangingPlaceEvent.java @@ -0,0 +1,70 @@ +package org.bukkit.event.hanging; + +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.entity.Hanging; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Triggered when a hanging entity is created in the world + */ +public class HangingPlaceEvent extends HangingEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled; + private final Player player; + private final Block block; + private final BlockFace blockFace; + + public HangingPlaceEvent(final Hanging hanging, final Player player, final Block block, final BlockFace blockFace) { + super(hanging); + this.player = player; + this.block = block; + this.blockFace = blockFace; + } + + /** + * Returns the player placing the hanging entity + * + * @return the player placing the hanging entity + */ + public Player getPlayer() { + return player; + } + + /** + * Returns the block that the hanging entity was placed on + * + * @return the block that the hanging entity was placed on + */ + public Block getBlock() { + return block; + } + + /** + * Returns the face of the block that the hanging entity was placed on + * + * @return the face of the block that the hanging entity was placed on + */ + public BlockFace getBlockFace() { + return blockFace; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/inventory/BrewEvent.java b/azurite-api/src/main/java/org/bukkit/event/inventory/BrewEvent.java new file mode 100644 index 0000000..2295c2d --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/inventory/BrewEvent.java @@ -0,0 +1,48 @@ +package org.bukkit.event.inventory; + +import org.bukkit.block.Block; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; +import org.bukkit.event.block.BlockEvent; +import org.bukkit.inventory.BrewerInventory; + +/** + * Called when the brewing of the contents inside the Brewing Stand is + * complete. + */ +public class BrewEvent extends BlockEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private BrewerInventory contents; + private boolean cancelled; + + public BrewEvent(Block brewer, BrewerInventory contents) { + super(brewer); + this.contents = contents; + } + + /** + * Gets the contents of the Brewing Stand. + * + * @return the contents + */ + public BrewerInventory getContents() { + return contents; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + cancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/inventory/ClickType.java b/azurite-api/src/main/java/org/bukkit/event/inventory/ClickType.java new file mode 100644 index 0000000..a7440aa --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/inventory/ClickType.java @@ -0,0 +1,115 @@ +package org.bukkit.event.inventory; + +/** + * What the client did to trigger this action (not the result). + */ +public enum ClickType { + + /** + * The left (or primary) mouse button. + */ + LEFT, + /** + * Holding shift while pressing the left mouse button. + */ + SHIFT_LEFT, + /** + * The right mouse button. + */ + RIGHT, + /** + * Holding shift while pressing the right mouse button. + */ + SHIFT_RIGHT, + /** + * Clicking the left mouse button on the grey area around the inventory. + */ + WINDOW_BORDER_LEFT, + /** + * Clicking the right mouse button on the grey area around the inventory. + */ + WINDOW_BORDER_RIGHT, + /** + * The middle mouse button, or a "scrollwheel click". + */ + MIDDLE, + /** + * One of the number keys 1-9, correspond to slots on the hotbar. + */ + NUMBER_KEY, + /** + * Pressing the left mouse button twice in quick succession. + */ + DOUBLE_CLICK, + /** + * The "Drop" key (defaults to Q). + */ + DROP, + /** + * Holding Ctrl while pressing the "Drop" key (defaults to Q). + */ + CONTROL_DROP, + /** + * Any action done with the Creative inventory open. + */ + CREATIVE, + /** + * A type of inventory manipulation not yet recognized by Bukkit. + *

+ * This is only for transitional purposes on a new Minecraft update, and + * should never be relied upon. + *

+ * Any ClickType.UNKNOWN is called on a best-effort basis. + */ + UNKNOWN, + ; + + /** + * Gets whether this ClickType represents the pressing of a key on a + * keyboard. + * + * @return true if this ClickType represents the pressing of a key + */ + public boolean isKeyboardClick() { + return (this == ClickType.NUMBER_KEY) || (this == ClickType.DROP) || (this == ClickType.CONTROL_DROP); + } + + /** + * Gets whether this ClickType represents an action that can only be + * performed by a Player in creative mode. + * + * @return true if this action requires Creative mode + */ + public boolean isCreativeAction() { + // Why use middle click? + return (this == ClickType.MIDDLE) || (this == ClickType.CREATIVE); + } + + /** + * Gets whether this ClickType represents a right click. + * + * @return true if this ClickType represents a right click + */ + public boolean isRightClick() { + return (this == ClickType.RIGHT) || (this == ClickType.SHIFT_RIGHT); + } + + /** + * Gets whether this ClickType represents a left click. + * + * @return true if this ClickType represents a left click + */ + public boolean isLeftClick() { + return (this == ClickType.LEFT) || (this == ClickType.SHIFT_LEFT) || (this == ClickType.DOUBLE_CLICK) || (this == ClickType.CREATIVE); + } + + /** + * Gets whether this ClickType indicates that the shift key was pressed + * down when the click was made. + * + * @return true if the action uses Shift. + */ + public boolean isShiftClick() { + return (this == ClickType.SHIFT_LEFT) || (this == ClickType.SHIFT_RIGHT) || (this == ClickType.CONTROL_DROP); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/inventory/CraftItemEvent.java b/azurite-api/src/main/java/org/bukkit/event/inventory/CraftItemEvent.java new file mode 100644 index 0000000..ba3f5e5 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/inventory/CraftItemEvent.java @@ -0,0 +1,40 @@ +package org.bukkit.event.inventory; + +import org.bukkit.event.inventory.InventoryType.SlotType; +import org.bukkit.inventory.CraftingInventory; +import org.bukkit.inventory.InventoryView; +import org.bukkit.inventory.Recipe; + +/** + * Called when the recipe of an Item is completed inside a crafting matrix. + */ +public class CraftItemEvent extends InventoryClickEvent { + private Recipe recipe; + + @Deprecated + public CraftItemEvent(Recipe recipe, InventoryView what, SlotType type, int slot, boolean right, boolean shift) { + this(recipe, what, type, slot, right ? (shift ? ClickType.SHIFT_RIGHT : ClickType.RIGHT) : (shift ? ClickType.SHIFT_LEFT : ClickType.LEFT), InventoryAction.PICKUP_ALL); + } + + public CraftItemEvent(Recipe recipe, InventoryView what, SlotType type, int slot, ClickType click, InventoryAction action) { + super(what, type, slot, click, action); + this.recipe = recipe; + } + + public CraftItemEvent(Recipe recipe, InventoryView what, SlotType type, int slot, ClickType click, InventoryAction action, int key) { + super(what, type, slot, click, action, key); + this.recipe = recipe; + } + + /** + * @return A copy of the current recipe on the crafting matrix. + */ + public Recipe getRecipe() { + return recipe; + } + + @Override + public CraftingInventory getInventory() { + return (CraftingInventory) super.getInventory(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/inventory/DragType.java b/azurite-api/src/main/java/org/bukkit/event/inventory/DragType.java new file mode 100644 index 0000000..72c2bed --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/inventory/DragType.java @@ -0,0 +1,17 @@ +package org.bukkit.event.inventory; + +/** + * Represents the effect of a drag that will be applied to an Inventory in an + * InventoryDragEvent. + */ +public enum DragType { + /** + * One item from the cursor is placed in each selected slot. + */ + SINGLE, + /** + * The cursor is split evenly across all selected slots, not to exceed the + * Material's max stack size, with the remainder going to the cursor. + */ + EVEN, +} diff --git a/azurite-api/src/main/java/org/bukkit/event/inventory/EquipmentSetEvent.java b/azurite-api/src/main/java/org/bukkit/event/inventory/EquipmentSetEvent.java new file mode 100644 index 0000000..b4e9c18 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/inventory/EquipmentSetEvent.java @@ -0,0 +1,48 @@ +package org.bukkit.event.inventory; + +import org.bukkit.entity.HumanEntity; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.bukkit.inventory.ItemStack; + +import java.beans.ConstructorProperties; + +public class EquipmentSetEvent extends Event { + private static final HandlerList handlerList = new HandlerList(); + private final HumanEntity humanEntity; + private final int slot; + private final ItemStack previousItem; + private final ItemStack newItem; + + @ConstructorProperties({"humanEntity", "slot", "previousItem", "newItem"}) + public EquipmentSetEvent(HumanEntity humanEntity, int slot, ItemStack previousItem, ItemStack newItem) { + this.humanEntity = humanEntity; + this.slot = slot; + this.previousItem = previousItem; + this.newItem = newItem; + } + + public static HandlerList getHandlerList() { + return handlerList; + } + + public HumanEntity getHumanEntity() { + return this.humanEntity; + } + + public int getSlot() { + return this.slot; + } + + public ItemStack getPreviousItem() { + return this.previousItem; + } + + public ItemStack getNewItem() { + return this.newItem; + } + + public HandlerList getHandlers() { + return handlerList; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/inventory/FurnaceBurnEvent.java b/azurite-api/src/main/java/org/bukkit/event/inventory/FurnaceBurnEvent.java new file mode 100644 index 0000000..8ca1ff7 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/inventory/FurnaceBurnEvent.java @@ -0,0 +1,99 @@ +package org.bukkit.event.inventory; + +import org.bukkit.block.Block; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; +import org.bukkit.event.block.BlockEvent; +import org.bukkit.inventory.ItemStack; + +/** + * Called when an ItemStack is successfully burned as fuel in a furnace. + */ +public class FurnaceBurnEvent extends BlockEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final ItemStack fuel; + private int burnTime; + private boolean cancelled; + private boolean burning; + + public FurnaceBurnEvent(final Block furnace, final ItemStack fuel, final int burnTime) { + super(furnace); + this.fuel = fuel; + this.burnTime = burnTime; + this.cancelled = false; + this.burning = true; + } + + /** + * Gets the block for the furnace involved in this event + * + * @return the block of the furnace + * @deprecated In favour of {@link #getBlock()}. + */ + @Deprecated + public Block getFurnace() { + return getBlock(); + } + + /** + * Gets the fuel ItemStack for this event + * + * @return the fuel ItemStack + */ + public ItemStack getFuel() { + return fuel; + } + + /** + * Gets the burn time for this fuel + * + * @return the burn time for this fuel + */ + public int getBurnTime() { + return burnTime; + } + + /** + * Sets the burn time for this fuel + * + * @param burnTime the burn time for this fuel + */ + public void setBurnTime(int burnTime) { + this.burnTime = burnTime; + } + + /** + * Gets whether the furnace's fuel is burning or not. + * + * @return whether the furnace's fuel is burning or not. + */ + public boolean isBurning() { + return this.burning; + } + + /** + * Sets whether the furnace's fuel is burning or not. + * + * @param burning true if the furnace's fuel is burning + */ + public void setBurning(boolean burning) { + this.burning = burning; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/inventory/FurnaceExtractEvent.java b/azurite-api/src/main/java/org/bukkit/event/inventory/FurnaceExtractEvent.java new file mode 100644 index 0000000..b7381fa --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/inventory/FurnaceExtractEvent.java @@ -0,0 +1,49 @@ +package org.bukkit.event.inventory; + +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.event.block.BlockExpEvent; + +/** + * This event is called when a player takes items out of the furnace + */ +public class FurnaceExtractEvent extends BlockExpEvent { + private final Player player; + private final Material itemType; + private final int itemAmount; + + public FurnaceExtractEvent(Player player, Block block, Material itemType, int itemAmount, int exp) { + super(block, exp); + this.player = player; + this.itemType = itemType; + this.itemAmount = itemAmount; + } + + /** + * Get the player that triggered the event + * + * @return the relevant player + */ + public Player getPlayer() { + return player; + } + + /** + * Get the Material of the item being retrieved + * + * @return the material of the item + */ + public Material getItemType() { + return itemType; + } + + /** + * Get the item count being retrieved + * + * @return the amount of the item + */ + public int getItemAmount() { + return itemAmount; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/inventory/FurnaceSmeltEvent.java b/azurite-api/src/main/java/org/bukkit/event/inventory/FurnaceSmeltEvent.java new file mode 100644 index 0000000..e9d1a54 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/inventory/FurnaceSmeltEvent.java @@ -0,0 +1,79 @@ +package org.bukkit.event.inventory; + +import org.bukkit.block.Block; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; +import org.bukkit.event.block.BlockEvent; +import org.bukkit.inventory.ItemStack; + +/** + * Called when an ItemStack is successfully smelted in a furnace. + */ +public class FurnaceSmeltEvent extends BlockEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final ItemStack source; + private ItemStack result; + private boolean cancelled; + + public FurnaceSmeltEvent(final Block furnace, final ItemStack source, final ItemStack result) { + super(furnace); + this.source = source; + this.result = result; + this.cancelled = false; + } + + /** + * Gets the block for the furnace involved in this event + * + * @return the block of the furnace + * @deprecated In favour of {@link #getBlock()}. + */ + @Deprecated + public Block getFurnace() { + return getBlock(); + } + + /** + * Gets the smelted ItemStack for this event + * + * @return smelting source ItemStack + */ + public ItemStack getSource() { + return source; + } + + /** + * Gets the resultant ItemStack for this event + * + * @return smelting result ItemStack + */ + public ItemStack getResult() { + return result; + } + + /** + * Sets the resultant ItemStack for this event + * + * @param result new result ItemStack + */ + public void setResult(ItemStack result) { + this.result = result; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/inventory/InventoryAction.java b/azurite-api/src/main/java/org/bukkit/event/inventory/InventoryAction.java new file mode 100644 index 0000000..bb2a30f --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/inventory/InventoryAction.java @@ -0,0 +1,90 @@ +package org.bukkit.event.inventory; + +/** + * An estimation of what the result will be. + */ +public enum InventoryAction { + + /** + * Nothing will happen from the click. + *

+ * There may be cases where nothing will happen and this is value is not + * provided, but it is guaranteed that this value is accurate when given. + */ + NOTHING, + /** + * All of the items on the clicked slot are moved to the cursor. + */ + PICKUP_ALL, + /** + * Some of the items on the clicked slot are moved to the cursor. + */ + PICKUP_SOME, + /** + * Half of the items on the clicked slot are moved to the cursor. + */ + PICKUP_HALF, + /** + * One of the items on the clicked slot are moved to the cursor. + */ + PICKUP_ONE, + /** + * All of the items on the cursor are moved to the clicked slot. + */ + PLACE_ALL, + /** + * Some of the items from the cursor are moved to the clicked slot + * (usually up to the max stack size). + */ + PLACE_SOME, + /** + * A single item from the cursor is moved to the clicked slot. + */ + PLACE_ONE, + /** + * The clicked item and the cursor are exchanged. + */ + SWAP_WITH_CURSOR, + /** + * The entire cursor item is dropped. + */ + DROP_ALL_CURSOR, + /** + * One item is dropped from the cursor. + */ + DROP_ONE_CURSOR, + /** + * The entire clicked slot is dropped. + */ + DROP_ALL_SLOT, + /** + * One item is dropped from the clicked slot. + */ + DROP_ONE_SLOT, + /** + * The item is moved to the opposite inventory if a space is found. + */ + MOVE_TO_OTHER_INVENTORY, + /** + * The clicked item is moved to the hotbar, and the item currently there + * is re-added to the player's inventory. + */ + HOTBAR_MOVE_AND_READD, + /** + * The clicked slot and the picked hotbar slot are swapped. + */ + HOTBAR_SWAP, + /** + * A max-size stack of the clicked item is put on the cursor. + */ + CLONE_STACK, + /** + * The inventory is searched for the same material, and they are put on + * the cursor up to {@link org.bukkit.Material#getMaxStackSize()}. + */ + COLLECT_TO_CURSOR, + /** + * An unrecognized ClickType. + */ + UNKNOWN, +} diff --git a/azurite-api/src/main/java/org/bukkit/event/inventory/InventoryClickEvent.java b/azurite-api/src/main/java/org/bukkit/event/inventory/InventoryClickEvent.java new file mode 100644 index 0000000..a5ea216 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/inventory/InventoryClickEvent.java @@ -0,0 +1,245 @@ +package org.bukkit.event.inventory; + +import org.bukkit.Location; +import org.bukkit.entity.HumanEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; +import org.bukkit.event.inventory.InventoryType.SlotType; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryView; +import org.bukkit.inventory.ItemStack; +import org.bukkit.plugin.Plugin; +import org.bukkit.scheduler.BukkitScheduler; + +/** + * This event is called when a player clicks a slot in an inventory. + *

+ * Because InventoryClickEvent occurs within a modification of the Inventory, + * not all Inventory related methods are safe to use. + *

+ * The following should never be invoked by an EventHandler for + * InventoryClickEvent using the HumanEntity or InventoryView associated with + * this event: + *

    + *
  • {@link HumanEntity#closeInventory()} + *
  • {@link HumanEntity#openInventory(Inventory)} + *
  • {@link HumanEntity#openWorkbench(Location, boolean)} + *
  • {@link HumanEntity#openEnchanting(Location, boolean)} + *
  • {@link InventoryView#close()} + *
+ * To invoke one of these methods, schedule a task using + * {@link BukkitScheduler#runTask(Plugin, Runnable)}, which will run the task + * on the next tick. Also be aware that this is not an exhaustive list, and + * other methods could potentially create issues as well. + *

+ * Assuming the EntityHuman associated with this event is an instance of a + * Player, manipulating the MaxStackSize or contents of an Inventory will + * require an Invocation of {@link Player#updateInventory()}. + *

+ * Modifications to slots that are modified by the results of this + * InventoryClickEvent can be overwritten. To change these slots, this event + * should be cancelled and all desired changes to the inventory applied. + * Alternatively, scheduling a task using {@link BukkitScheduler#runTask( + * Plugin, Runnable)}, which would execute the task on the next tick, would + * work as well. + */ +public class InventoryClickEvent extends InventoryInteractEvent { + private static final HandlerList handlers = new HandlerList(); + private final ClickType click; + private final InventoryAction action; + private final Inventory clickedInventory; + private SlotType slot_type; + private int whichSlot; + private int rawSlot; + private ItemStack current = null; + private int hotbarKey = -1; + + @Deprecated + public InventoryClickEvent(InventoryView view, SlotType type, int slot, boolean right, boolean shift) { + this(view, type, slot, right ? (shift ? ClickType.SHIFT_RIGHT : ClickType.RIGHT) : (shift ? ClickType.SHIFT_LEFT : ClickType.LEFT), InventoryAction.SWAP_WITH_CURSOR); + } + + public InventoryClickEvent(InventoryView view, SlotType type, int slot, ClickType click, InventoryAction action) { + super(view); + this.slot_type = type; + this.rawSlot = slot; + if (slot < 0) { + this.clickedInventory = null; + } else if (view.getTopInventory() != null && slot < view.getTopInventory().getSize()) { + this.clickedInventory = view.getTopInventory(); + } else { + this.clickedInventory = view.getBottomInventory(); + } + this.whichSlot = view.convertSlot(slot); + this.click = click; + this.action = action; + } + + public InventoryClickEvent(InventoryView view, SlotType type, int slot, ClickType click, InventoryAction action, int key) { + this(view, type, slot, click, action); + this.hotbarKey = key; + } + + /** + * Gets the inventory that was clicked, or null if outside of window + * @return The clicked inventory + */ + public Inventory getClickedInventory() { + return clickedInventory; + } + + /** + * Gets the type of slot that was clicked. + * + * @return the slot type + */ + public SlotType getSlotType() { + return slot_type; + } + + /** + * Gets the current ItemStack on the cursor. + * + * @return the cursor ItemStack + */ + public ItemStack getCursor() { + return getView().getCursor(); + } + + /** + * Gets the ItemStack currently in the clicked slot. + * + * @return the item in the clicked + */ + public ItemStack getCurrentItem() { + if (slot_type == SlotType.OUTSIDE) { + return current; + } + return getView().getItem(rawSlot); + } + + /** + * Gets whether or not the ClickType for this event represents a right + * click. + * + * @return true if the ClickType uses the right mouse button. + * @see ClickType#isRightClick() + */ + public boolean isRightClick() { + return click.isRightClick(); + } + + /** + * Gets whether or not the ClickType for this event represents a left + * click. + * + * @return true if the ClickType uses the left mouse button. + * @see ClickType#isLeftClick() + */ + public boolean isLeftClick() { + return click.isLeftClick(); + } + + /** + * Gets whether the ClickType for this event indicates that the key was + * pressed down when the click was made. + * + * @return true if the ClickType uses Shift or Ctrl. + * @see ClickType#isShiftClick() + */ + public boolean isShiftClick() { + return click.isShiftClick(); + } + + /** + * Sets the item on the cursor. + * + * @param stack the new cursor item + * @deprecated This changes the ItemStack in their hand before any + * calculations are applied to the Inventory, which has a tendency to + * create inconsistencies between the Player and the server, and to + * make unexpected changes in the behavior of the clicked Inventory. + */ + @Deprecated + public void setCursor(ItemStack stack) { + getView().setCursor(stack); + } + + /** + * Sets the ItemStack currently in the clicked slot. + * + * @param stack the item to be placed in the current slot + */ + public void setCurrentItem(ItemStack stack) { + if (slot_type == SlotType.OUTSIDE) { + current = stack; + } else { + getView().setItem(rawSlot, stack); + } + } + + /** + * The slot number that was clicked, ready for passing to + * {@link Inventory#getItem(int)}. Note that there may be two slots with + * the same slot number, since a view links two different inventories. + * + * @return The slot number. + */ + public int getSlot() { + return whichSlot; + } + + /** + * The raw slot number clicked, ready for passing to {@link InventoryView + * #getItem(int)} This slot number is unique for the view. + * + * @return the slot number + */ + public int getRawSlot() { + return rawSlot; + } + + /** + * If the ClickType is NUMBER_KEY, this method will return the index of + * the pressed key (0-8). + * + * @return the number on the key minus 1 (range 0-8); or -1 if not + * a NUMBER_KEY action + */ + public int getHotbarButton() { + return hotbarKey; + } + + /** + * Gets the InventoryAction that triggered this event. + *

+ * This action cannot be changed, and represents what the normal outcome + * of the event will be. To change the behavior of this + * InventoryClickEvent, changes must be manually applied. + * + * @return the InventoryAction that triggered this event. + */ + public InventoryAction getAction() { + return action; + } + + /** + * Gets the ClickType for this event. + *

+ * This is insulated against changes to the inventory by other plugins. + * + * @return the type of inventory click + */ + public ClickType getClick() { + return click; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/inventory/InventoryCloseEvent.java b/azurite-api/src/main/java/org/bukkit/event/inventory/InventoryCloseEvent.java new file mode 100644 index 0000000..19889b2 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/inventory/InventoryCloseEvent.java @@ -0,0 +1,35 @@ + +package org.bukkit.event.inventory; + +import org.bukkit.entity.HumanEntity; +import org.bukkit.event.HandlerList; +import org.bukkit.inventory.InventoryView; + +/** + * Represents a player related inventory event + */ +public class InventoryCloseEvent extends InventoryEvent { + private static final HandlerList handlers = new HandlerList(); + + public InventoryCloseEvent(InventoryView transaction) { + super(transaction); + } + + /** + * Returns the player involved in this event + * + * @return Player who is involved in this event + */ + public final HumanEntity getPlayer() { + return transaction.getPlayer(); + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/inventory/InventoryCreativeEvent.java b/azurite-api/src/main/java/org/bukkit/event/inventory/InventoryCreativeEvent.java new file mode 100644 index 0000000..da7dffc --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/inventory/InventoryCreativeEvent.java @@ -0,0 +1,27 @@ +package org.bukkit.event.inventory; + +import org.bukkit.event.inventory.InventoryType.SlotType; +import org.bukkit.inventory.InventoryView; +import org.bukkit.inventory.ItemStack; + +/** + * This event is called when a player in creative mode puts down or picks up + * an item in their inventory / hotbar and when they drop items from their + * Inventory while in creative mode. + */ +public class InventoryCreativeEvent extends InventoryClickEvent { + private ItemStack item; + + public InventoryCreativeEvent(InventoryView what, SlotType type, int slot, ItemStack newItem) { + super(what, type, slot, ClickType.CREATIVE, InventoryAction.PLACE_ALL); + this.item = newItem; + } + + public ItemStack getCursor() { + return item; + } + + public void setCursor(ItemStack item) { + this.item = item; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/inventory/InventoryDragEvent.java b/azurite-api/src/main/java/org/bukkit/event/inventory/InventoryDragEvent.java new file mode 100644 index 0000000..0ce7cd5 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/inventory/InventoryDragEvent.java @@ -0,0 +1,163 @@ +package org.bukkit.event.inventory; + +import com.google.common.collect.ImmutableSet; +import org.apache.commons.lang.Validate; +import org.bukkit.Location; +import org.bukkit.entity.HumanEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryView; +import org.bukkit.inventory.ItemStack; +import org.bukkit.plugin.Plugin; +import org.bukkit.scheduler.BukkitScheduler; + +import java.util.Collections; +import java.util.Map; +import java.util.Set; + +/** + * This event is called when the player drags an item in their cursor across + * the inventory. The ItemStack is distributed across the slots the + * HumanEntity dragged over. The method of distribution is described by the + * DragType returned by {@link #getType()}. + *

+ * Canceling this event will result in none of the changes described in + * {@link #getNewItems()} being applied to the Inventory. + *

+ * Because InventoryDragEvent occurs within a modification of the Inventory, + * not all Inventory related methods are safe to use. + *

+ * The following should never be invoked by an EventHandler for + * InventoryDragEvent using the HumanEntity or InventoryView associated with + * this event. + *

    + *
  • {@link HumanEntity#closeInventory()} + *
  • {@link HumanEntity#openInventory(Inventory)} + *
  • {@link HumanEntity#openWorkbench(Location, boolean)} + *
  • {@link HumanEntity#openEnchanting(Location, boolean)} + *
  • {@link InventoryView#close()} + *
+ * To invoke one of these methods, schedule a task using + * {@link BukkitScheduler#runTask(Plugin, Runnable)}, which will run the task + * on the next tick. Also be aware that this is not an exhaustive list, and + * other methods could potentially create issues as well. + *

+ * Assuming the EntityHuman associated with this event is an instance of a + * Player, manipulating the MaxStackSize or contents of an Inventory will + * require an Invocation of {@link Player#updateInventory()}. + *

+ * Any modifications to slots that are modified by the results of this + * InventoryDragEvent will be overwritten. To change these slots, this event + * should be cancelled and the changes applied. Alternatively, scheduling a + * task using {@link BukkitScheduler#runTask(Plugin, Runnable)}, which would + * execute the task on the next tick, would work as well. + */ +public class InventoryDragEvent extends InventoryInteractEvent { + private static final HandlerList handlers = new HandlerList(); + private final DragType type; + private final Map addedItems; + private final Set containerSlots; + private final ItemStack oldCursor; + private ItemStack newCursor; + + public InventoryDragEvent(InventoryView what, ItemStack newCursor, ItemStack oldCursor, boolean right, Map slots) { + super(what); + + Validate.notNull(oldCursor); + Validate.notNull(slots); + + type = right ? DragType.SINGLE : DragType.EVEN; + this.newCursor = newCursor; + this.oldCursor = oldCursor; + this.addedItems = slots; + ImmutableSet.Builder b = ImmutableSet.builder(); + for (Integer slot : slots.keySet()) { + b.add(what.convertSlot(slot)); + } + this.containerSlots = b.build(); + } + + /** + * Gets all items to be added to the inventory in this drag. + * + * @return map from raw slot id to new ItemStack + */ + public Map getNewItems() { + return Collections.unmodifiableMap(addedItems); + } + + /** + * Gets the raw slot ids to be changed in this drag. + * + * @return list of raw slot ids, suitable for getView().getItem(int) + */ + public Set getRawSlots() { + return addedItems.keySet(); + } + + /** + * Gets the slots to be changed in this drag. + * + * @return list of converted slot ids, suitable for {@link + * Inventory#getItem(int)}. + */ + public Set getInventorySlots() { + return containerSlots; + } + + /** + * Gets the result cursor after the drag is done. The returned value is + * mutable. + * + * @return the result cursor + */ + public ItemStack getCursor() { + return newCursor; + } + + /** + * Sets the result cursor after the drag is done. + *

+ * Changing this item stack changes the cursor item. Note that changing + * the affected "dragged" slots does not change this ItemStack, nor does + * changing this ItemStack affect the "dragged" slots. + * + * @param newCursor the new cursor ItemStack + */ + public void setCursor(ItemStack newCursor) { + this.newCursor = newCursor; + } + + /** + * Gets an ItemStack representing the cursor prior to any modifications + * as a result of this drag. + * + * @return the original cursor + */ + public ItemStack getOldCursor() { + return oldCursor.clone(); + } + + /** + * Gets the DragType that describes the behavior of ItemStacks placed + * after this InventoryDragEvent. + *

+ * The ItemStacks and the raw slots that they're being applied to can be + * found using {@link #getNewItems()}. + * + * @return the DragType of this InventoryDragEvent + */ + public DragType getType() { + return type; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/inventory/InventoryEvent.java b/azurite-api/src/main/java/org/bukkit/event/inventory/InventoryEvent.java new file mode 100644 index 0000000..4266d9a --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/inventory/InventoryEvent.java @@ -0,0 +1,59 @@ + +package org.bukkit.event.inventory; + +import org.bukkit.entity.HumanEntity; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryView; + +import java.util.List; + +/** + * Represents a player related inventory event + */ +public class InventoryEvent extends Event { + private static final HandlerList handlers = new HandlerList(); + protected InventoryView transaction; + + public InventoryEvent(InventoryView transaction) { + this.transaction = transaction; + } + + /** + * Gets the primary Inventory involved in this transaction + * + * @return The upper inventory. + */ + public Inventory getInventory() { + return transaction.getTopInventory(); + } + + /** + * Gets the list of players viewing the primary (upper) inventory involved + * in this event + * + * @return A list of people viewing. + */ + public List getViewers() { + return transaction.getTopInventory().getViewers(); + } + + /** + * Gets the view object itself + * + * @return InventoryView + */ + public InventoryView getView() { + return transaction; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/inventory/InventoryInteractEvent.java b/azurite-api/src/main/java/org/bukkit/event/inventory/InventoryInteractEvent.java new file mode 100644 index 0000000..627cd0f --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/inventory/InventoryInteractEvent.java @@ -0,0 +1,76 @@ +package org.bukkit.event.inventory; + +import org.bukkit.entity.HumanEntity; +import org.bukkit.event.Cancellable; +import org.bukkit.inventory.InventoryView; + +/** + * An abstract base class for events that describe an interaction between a + * HumanEntity and the contents of an Inventory. + */ +public abstract class InventoryInteractEvent extends InventoryEvent implements Cancellable { + private Result result = Result.DEFAULT; + + public InventoryInteractEvent(InventoryView transaction) { + super(transaction); + } + + /** + * Gets the player who performed the click. + * + * @return The clicking player. + */ + public HumanEntity getWhoClicked() { + return getView().getPlayer(); + } + + /** + * Sets the result of this event. This will change whether or not this + * event is considered cancelled. + * + * @see #isCancelled() + * @param newResult the new {@link Result} for this event + */ + public void setResult(Result newResult) { + result = newResult; + } + + /** + * Gets the {@link Result} of this event. The Result describes the + * behavior that will be applied to the inventory in relation to this + * event. + * + * @return the Result of this event. + */ + public Result getResult() { + return result; + } + + /** + * Gets whether or not this event is cancelled. This is based off of the + * Result value returned by {@link #getResult()}. Result.ALLOW and + * Result.DEFAULT will result in a returned value of false, but + * Result.DENY will result in a returned value of true. + *

+ * {@inheritDoc} + * + * @return whether the event is cancelled + */ + public boolean isCancelled() { + return getResult() == Result.DENY; + } + + /** + * Proxy method to {@link #setResult(Event.Result)} for the Cancellable + * interface. {@link #setResult(Event.Result)} is preferred, as it allows + * you to specify the Result beyond Result.DENY and Result.ALLOW. + *

+ * {@inheritDoc} + * + * @param toCancel result becomes DENY if true, ALLOW if false + */ + public void setCancelled(boolean toCancel) { + setResult(toCancel ? Result.DENY : Result.ALLOW); + } + +} diff --git a/azurite-api/src/main/java/org/bukkit/event/inventory/InventoryMoveItemEvent.java b/azurite-api/src/main/java/org/bukkit/event/inventory/InventoryMoveItemEvent.java new file mode 100644 index 0000000..b44cc45 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/inventory/InventoryMoveItemEvent.java @@ -0,0 +1,112 @@ +package org.bukkit.event.inventory; + +import org.apache.commons.lang.Validate; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; + +/** + * Called when some entity or block (e.g. hopper) tries to move items directly + * from one inventory to another. + *

+ * When this event is called, the initiator may already have removed the item + * from the source inventory and is ready to move it into the destination + * inventory. + *

+ * If this event is cancelled, the items will be returned to the source + * inventory, if needed. + *

+ * If this event is not cancelled, the initiator will try to put the ItemStack + * into the destination inventory. If this is not possible and the ItemStack + * has not been modified, the source inventory slot will be restored to its + * former state. Otherwise any additional items will be discarded. + */ +public class InventoryMoveItemEvent extends Event implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled; + private final Inventory sourceInventory; + private final Inventory destinationInventory; + private ItemStack itemStack; + private final boolean didSourceInitiate; + public boolean calledGetItem; // Paper + public boolean calledSetItem; // Paper + + public InventoryMoveItemEvent(final Inventory sourceInventory, final ItemStack itemStack, final Inventory destinationInventory, final boolean didSourceInitiate) { + Validate.notNull(itemStack, "ItemStack cannot be null"); + this.sourceInventory = sourceInventory; + this.itemStack = itemStack; + this.destinationInventory = destinationInventory; + this.didSourceInitiate = didSourceInitiate; + } + + /** + * Gets the Inventory that the ItemStack is being taken from + * + * @return Inventory that the ItemStack is being taken from + */ + public Inventory getSource() { + return sourceInventory; + } + + /** + * Gets the ItemStack being moved; if modified, the original item will not + * be removed from the source inventory. + * + * @return ItemStack + */ + public ItemStack getItem() { + calledGetItem = true; // Paper - record this method was used for auto detection of mode + return itemStack; // Paper - Removed clone, handled better in Server + } + + /** + * Sets the ItemStack being moved; if this is different from the original + * ItemStack, the original item will not be removed from the source + * inventory. + * + * @param itemStack The ItemStack + */ + public void setItem(ItemStack itemStack) { + Validate.notNull(itemStack, "ItemStack cannot be null. Cancel the event if you want nothing to be transferred."); + calledSetItem = true; // Paper - record this method was used for auto detection of mode + this.itemStack = itemStack.clone(); + } + + /** + * Gets the Inventory that the ItemStack is being put into + * + * @return Inventory that the ItemStack is being put into + */ + public Inventory getDestination() { + return destinationInventory; + } + + /** + * Gets the Inventory that initiated the transfer. This will always be + * either the destination or source Inventory. + * + * @return Inventory that initiated the transfer + */ + public Inventory getInitiator() { + return didSourceInitiate ? sourceInventory : destinationInventory; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/inventory/InventoryOpenEvent.java b/azurite-api/src/main/java/org/bukkit/event/inventory/InventoryOpenEvent.java new file mode 100644 index 0000000..a1a03c8 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/inventory/InventoryOpenEvent.java @@ -0,0 +1,63 @@ +package org.bukkit.event.inventory; + +import org.bukkit.entity.HumanEntity; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; +import org.bukkit.inventory.InventoryView; + +/** + * Represents a player related inventory event + */ +public class InventoryOpenEvent extends InventoryEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled; + + public InventoryOpenEvent(InventoryView transaction) { + super(transaction); + this.cancelled = false; + } + + /** + * Returns the player involved in this event + * + * @return Player who is involved in this event + */ + public final HumanEntity getPlayer() { + return transaction.getPlayer(); + } + + /** + * Gets the cancellation state of this event. A cancelled event will not + * be executed in the server, but will still pass to other plugins. + *

+ * If an inventory open event is cancelled, the inventory screen will not + * show. + * + * @return true if this event is cancelled + */ + public boolean isCancelled() { + return cancelled; + } + + /** + * Sets the cancellation state of this event. A cancelled event will not + * be executed in the server, but will still pass to other plugins. + *

+ * If an inventory open event is cancelled, the inventory screen will not + * show. + * + * @param cancel true if you wish to cancel this event + */ + public void setCancelled(boolean cancel) { + cancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/inventory/InventoryPickupItemEvent.java b/azurite-api/src/main/java/org/bukkit/event/inventory/InventoryPickupItemEvent.java new file mode 100644 index 0000000..af6ad5b --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/inventory/InventoryPickupItemEvent.java @@ -0,0 +1,58 @@ +package org.bukkit.event.inventory; + +import org.bukkit.entity.Item; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.bukkit.inventory.Inventory; + +/** + * Called when a hopper or hopper minecart picks up a dropped item. + */ +public class InventoryPickupItemEvent extends Event implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled; + private final Inventory inventory; + private final Item item; + + public InventoryPickupItemEvent(final Inventory inventory, final Item item) { + super(); + this.inventory = inventory; + this.item = item; + } + + /** + * Gets the Inventory that picked up the item + * + * @return Inventory + */ + public Inventory getInventory() { + return inventory; + } + + /** + * Gets the Item entity that was picked up + * + * @return Item + */ + public Item getItem() { + return item; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/inventory/InventoryType.java b/azurite-api/src/main/java/org/bukkit/event/inventory/InventoryType.java new file mode 100644 index 0000000..6816d89 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/inventory/InventoryType.java @@ -0,0 +1,124 @@ +package org.bukkit.event.inventory; + +public enum InventoryType { + + /** + * A chest inventory, with 0, 9, 18, 27, 36, 45, or 54 slots of type + * CONTAINER. + */ + CHEST(27,"Chest"), + /** + * A dispenser inventory, with 9 slots of type CONTAINER. + */ + DISPENSER(9,"Dispenser"), + /** + * A dropper inventory, with 9 slots of type CONTAINER. + */ + DROPPER(9, "Dropper"), + /** + * A furnace inventory, with a RESULT slot, a CRAFTING slot, and a FUEL + * slot. + */ + FURNACE(3,"Furnace"), + /** + * A workbench inventory, with 9 CRAFTING slots and a RESULT slot. + */ + WORKBENCH(10,"Crafting"), + /** + * A player's crafting inventory, with 4 CRAFTING slots and a RESULT slot. + * Also implies that the 4 ARMOR slots are accessible. + */ + CRAFTING(5,"Crafting"), + /** + * An enchantment table inventory, with two CRAFTING slots and three + * enchanting buttons. + */ + ENCHANTING(2,"Enchanting"), + /** + * A brewing stand inventory, with one FUEL slot and three CRAFTING slots. + */ + BREWING(4,"Brewing"), + /** + * A player's inventory, with 9 QUICKBAR slots, 27 CONTAINER slots, and 4 + * ARMOR slots. The ARMOUR slots may not be visible to the player, though. + */ + PLAYER(36,"Player"), + /** + * The creative mode inventory, with only 9 QUICKBAR slots and nothing + * else. (The actual creative interface with the items is client-side and + * cannot be altered by the server.) + */ + CREATIVE(9,"Creative"), + /** + * The merchant inventory, with 2 TRADE-IN slots, and 1 RESULT slot. + */ + MERCHANT(3,"Villager"), + /** + * The ender chest inventory, with 27 slots. + */ + ENDER_CHEST(27,"Ender Chest"), + /** + * An anvil inventory, with 2 CRAFTING slots and 1 RESULT slot + */ + ANVIL(3, "Repairing"), + /** + * A beacon inventory, with 1 CRAFTING slot + */ + BEACON(1, "container.beacon"), + /** + * A hopper inventory, with 5 slots of type CONTAINER. + */ + HOPPER(5, "Item Hopper"), + ; + + private final int size; + private final String title; + + InventoryType(int defaultSize, String defaultTitle) { + size = defaultSize; + title = defaultTitle; + } + + public int getDefaultSize() { + return size; + } + + public String getDefaultTitle() { + return title; + } + + public enum SlotType { + /** + * A result slot in a furnace or crafting inventory. + */ + RESULT, + /** + * A slot in the crafting matrix, or the input slot in a furnace + * inventory, the potion slot in the brewing stand, or the enchanting + * slot. + */ + CRAFTING, + /** + * An armour slot in the player's inventory. + */ + ARMOR, + /** + * A regular slot in the container or the player's inventory; anything + * not covered by the other enum values. + */ + CONTAINER, + /** + * A slot in the bottom row or quickbar. + */ + QUICKBAR, + /** + * A pseudo-slot representing the area outside the inventory window. + */ + OUTSIDE, + /** + * The fuel slot in a furnace inventory, or the ingredient slot in a + * brewing stand inventory. + */ + FUEL + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/inventory/PrepareItemAnvilRepairEvent.java b/azurite-api/src/main/java/org/bukkit/event/inventory/PrepareItemAnvilRepairEvent.java new file mode 100644 index 0000000..f4ef13f --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/inventory/PrepareItemAnvilRepairEvent.java @@ -0,0 +1,77 @@ +package org.bukkit.event.inventory; + +import org.bukkit.block.Block; +import org.bukkit.entity.HumanEntity; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; +import org.bukkit.inventory.InventoryView; +import org.bukkit.inventory.ItemStack; + +public class PrepareItemAnvilRepairEvent extends InventoryEvent implements Cancellable { + private static final HandlerList handlerList = new HandlerList(); + private final HumanEntity repairer; + private final Block anvil; + private final ItemStack first; + private final ItemStack second; + private int repairCost; + private ItemStack result; + private boolean cancelled; + + public PrepareItemAnvilRepairEvent(InventoryView view, HumanEntity repairer, Block anvil, int repairCost, ItemStack first, ItemStack second, ItemStack result) { + super(view); + this.repairer = repairer; + this.anvil = anvil; + this.repairCost = repairCost; + this.first = first; + this.second = second; + this.result = result; + } + + public static HandlerList getHandlerList() { + return handlerList; + } + + public HumanEntity getRepairer() { + return this.repairer; + } + + public Block getAnvil() { + return this.anvil; + } + + public int getRepairCost() { + return this.repairCost; + } + + public void setRepairCost(int repairCost) { + this.repairCost = repairCost; + } + + public ItemStack getFirst() { + return this.first; + } + + public ItemStack getSecond() { + return this.second; + } + + public ItemStack getResult() { + return this.result; + } + + public void setResult(ItemStack result) { + this.result = result; + } + + public boolean isCancelled() { + return this.cancelled; + } + + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + + public HandlerList getHandlers() { + return handlerList; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/inventory/PrepareItemCraftEvent.java b/azurite-api/src/main/java/org/bukkit/event/inventory/PrepareItemCraftEvent.java new file mode 100644 index 0000000..5731190 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/inventory/PrepareItemCraftEvent.java @@ -0,0 +1,56 @@ +package org.bukkit.event.inventory; + +import org.bukkit.event.HandlerList; +import org.bukkit.inventory.CraftingInventory; +import org.bukkit.inventory.InventoryView; +import org.bukkit.inventory.Recipe; + +public class PrepareItemCraftEvent extends InventoryEvent { + private static final HandlerList handlers = new HandlerList(); + private boolean repair; + private CraftingInventory matrix; + + public PrepareItemCraftEvent(CraftingInventory what, InventoryView view, boolean isRepair) { + super(view); + this.matrix = what; + this.repair = isRepair; + } + + /** + * Get the recipe that has been formed. If this event was triggered by a + * tool repair, this will be a temporary shapeless recipe representing the + * repair. + * + * @return The recipe being crafted. + */ + public Recipe getRecipe() { + return matrix.getRecipe(); + } + + /** + * @return The crafting inventory on which the recipe was formed. + */ + @Override + public CraftingInventory getInventory() { + return matrix; + } + + /** + * Check if this event was triggered by a tool repair operation rather + * than a crafting recipe. + * + * @return True if this is a repair. + */ + public boolean isRepair() { + return repair; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/painting/PaintingBreakByEntityEvent.java b/azurite-api/src/main/java/org/bukkit/event/painting/PaintingBreakByEntityEvent.java new file mode 100644 index 0000000..1dc4987 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/painting/PaintingBreakByEntityEvent.java @@ -0,0 +1,31 @@ +package org.bukkit.event.painting; + +import org.bukkit.Warning; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Painting; + +/** + * Triggered when a painting is removed by an entity + * + * @deprecated Use {@link org.bukkit.event.hanging.HangingBreakByEntityEvent} + * instead. + */ +@Deprecated +@Warning(reason="This event has been replaced by HangingBreakByEntityEvent") +public class PaintingBreakByEntityEvent extends PaintingBreakEvent { + private final Entity remover; + + public PaintingBreakByEntityEvent(final Painting painting, final Entity remover) { + super(painting, RemoveCause.ENTITY); + this.remover = remover; + } + + /** + * Gets the entity that removed the painting + * + * @return the entity that removed the painting. + */ + public Entity getRemover() { + return remover; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/painting/PaintingBreakEvent.java b/azurite-api/src/main/java/org/bukkit/event/painting/PaintingBreakEvent.java new file mode 100644 index 0000000..3e27c69 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/painting/PaintingBreakEvent.java @@ -0,0 +1,76 @@ +package org.bukkit.event.painting; + +import org.bukkit.Warning; +import org.bukkit.entity.Painting; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Triggered when a painting is removed + * + * @deprecated Use {@link org.bukkit.event.hanging.HangingBreakEvent} instead. + */ +@Deprecated +@Warning(reason="This event has been replaced by HangingBreakEvent") +public class PaintingBreakEvent extends PaintingEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled; + private final RemoveCause cause; + + public PaintingBreakEvent(final Painting painting, final RemoveCause cause) { + super(painting); + this.cause = cause; + } + + /** + * Gets the cause for the painting's removal + * + * @return the RemoveCause for the painting's removal + */ + public RemoveCause getCause() { + return cause; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + /** + * An enum to specify the cause of the removal + */ + public enum RemoveCause { + /** + * Removed by an entity + */ + ENTITY, + /** + * Removed by fire + */ + FIRE, + /** + * Removed by placing a block on it + */ + OBSTRUCTION, + /** + * Removed by water flowing over it + */ + WATER, + /** + * Removed by destroying the block behind it, etc + */ + PHYSICS, + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/painting/PaintingEvent.java b/azurite-api/src/main/java/org/bukkit/event/painting/PaintingEvent.java new file mode 100644 index 0000000..3a51348 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/painting/PaintingEvent.java @@ -0,0 +1,29 @@ +package org.bukkit.event.painting; + +import org.bukkit.Warning; +import org.bukkit.entity.Painting; +import org.bukkit.event.Event; + +/** + * Represents a painting-related event. + * + * @deprecated Use {@link org.bukkit.event.hanging.HangingEvent} instead. + */ +@Deprecated +@Warning(reason="This event has been replaced by HangingEvent") +public abstract class PaintingEvent extends Event { + protected Painting painting; + + protected PaintingEvent(final Painting painting) { + this.painting = painting; + } + + /** + * Gets the painting involved in this event. + * + * @return the painting + */ + public Painting getPainting() { + return painting; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/painting/PaintingPlaceEvent.java b/azurite-api/src/main/java/org/bukkit/event/painting/PaintingPlaceEvent.java new file mode 100644 index 0000000..3250b29 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/painting/PaintingPlaceEvent.java @@ -0,0 +1,76 @@ +package org.bukkit.event.painting; + +import org.bukkit.Warning; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.entity.Painting; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Triggered when a painting is created in the world + * + * @deprecated Use {@link org.bukkit.event.hanging.HangingPlaceEvent} instead. + */ +@Deprecated +@Warning(reason="This event has been replaced by HangingPlaceEvent") +public class PaintingPlaceEvent extends PaintingEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled; + private final Player player; + private final Block block; + private final BlockFace blockFace; + + public PaintingPlaceEvent(final Painting painting, final Player player, final Block block, final BlockFace blockFace) { + super(painting); + this.player = player; + this.block = block; + this.blockFace = blockFace; + } + + /** + * Returns the player placing the painting + * + * @return Entity returns the player placing the painting + */ + public Player getPlayer() { + return player; + } + + /** + * Returns the block that the painting was placed on + * + * @return Block returns the block painting placed on + */ + public Block getBlock() { + return block; + } + + /** + * Returns the face of the block that the painting was placed on + * + * @return BlockFace returns the face of the block the painting was placed + * on + */ + public BlockFace getBlockFace() { + return blockFace; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/AsyncPlayerChatEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/AsyncPlayerChatEvent.java new file mode 100644 index 0000000..a8b80f0 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/AsyncPlayerChatEvent.java @@ -0,0 +1,140 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +import java.util.IllegalFormatException; +import java.util.Set; + +/** + * This event will sometimes fire synchronously, depending on how it was + * triggered. + *

+ * The constructor provides a boolean to indicate if the event was fired + * synchronously or asynchronously. When asynchronous, this event can be + * called from any thread, sans the main thread, and has limited access to the + * API. + *

+ * If a player is the direct cause of this event by an incoming packet, this + * event will be asynchronous. If a plugin triggers this event by compelling a + * player to chat, this event will be synchronous. + *

+ * Care should be taken to check {@link #isAsynchronous()} and treat the event + * appropriately. + */ +public class AsyncPlayerChatEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancel = false; + private String message; + private String format = "<%1$s> %2$s"; + private final Set recipients; + + /** + * + * @param async This changes the event to a synchronous state. + * @param who the chat sender + * @param message the message sent + * @param players the players to receive the message. This may be a lazy + * or unmodifiable collection. + */ + public AsyncPlayerChatEvent(final boolean async, final Player who, final String message, final Set players) { + super(who, async); + this.message = message; + recipients = players; + } + + /** + * Gets the message that the player is attempting to send. This message + * will be used with {@link #getFormat()}. + * + * @return Message the player is attempting to send + */ + public String getMessage() { + return message; + } + + /** + * Sets the message that the player will send. This message will be used + * with {@link #getFormat()}. + * + * @param message New message that the player will send + */ + public void setMessage(String message) { + this.message = message; + } + + /** + * Gets the format to use to display this chat message. + *

+ * When this event finishes execution, the first format parameter is the + * {@link Player#getDisplayName()} and the second parameter is {@link + * #getMessage()} + * + * @return {@link String#format(String, Object...)} compatible format + * string + */ + public String getFormat() { + return format; + } + + /** + * Sets the format to use to display this chat message. + *

+ * When this event finishes execution, the first format parameter is the + * {@link Player#getDisplayName()} and the second parameter is {@link + * #getMessage()} + * + * @param format {@link String#format(String, Object...)} compatible + * format string + * @throws IllegalFormatException if the underlying API throws the + * exception + * @throws NullPointerException if format is null + * @see String#format(String, Object...) + */ + public void setFormat(final String format) throws IllegalFormatException, NullPointerException { + // Oh for a better way to do this! + try { + String.format(format, player, message); + } catch (RuntimeException ex) { + ex.fillInStackTrace(); + throw ex; + } + + this.format = format; + } + + /** + * Gets a set of recipients that this chat message will be displayed to. + *

+ * The set returned is not guaranteed to be mutable and may auto-populate + * on access. Any listener accessing the returned set should be aware that + * it may reduce performance for a lazy set implementation. + *

+ * Listeners should be aware that modifying the list may throw {@link + * UnsupportedOperationException} if the event caller provides an + * unmodifiable set. + * + * @return All Players who will see this chat message + */ + public Set getRecipients() { + return recipients; + } + + public boolean isCancelled() { + return cancel ; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/AsyncPlayerPreLoginEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/AsyncPlayerPreLoginEvent.java new file mode 100644 index 0000000..1550f19 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/AsyncPlayerPreLoginEvent.java @@ -0,0 +1,201 @@ +package org.bukkit.event.player; + +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +import java.net.InetAddress; +import java.util.UUID; + +/** + * Stores details for players attempting to log in. + *

+ * This event is asynchronous, and not run using main thread. + */ +public class AsyncPlayerPreLoginEvent extends Event { + private static final HandlerList handlers = new HandlerList(); + private Result result; + private String message; + private final String name; + private final InetAddress ipAddress; + private final UUID uniqueId; + + @Deprecated + public AsyncPlayerPreLoginEvent(final String name, final InetAddress ipAddress) { + this(name, ipAddress, null); + } + + public AsyncPlayerPreLoginEvent(final String name, final InetAddress ipAddress, final UUID uniqueId) { + super(true); + this.result = Result.ALLOWED; + this.message = ""; + this.name = name; + this.ipAddress = ipAddress; + this.uniqueId = uniqueId; + } + + /** + * Gets the current result of the login, as an enum + * + * @return Current Result of the login + */ + public Result getLoginResult() { + return result; + } + + /** + * Gets the current result of the login, as an enum + * + * @return Current Result of the login + * @deprecated This method uses a deprecated enum from {@link + * PlayerPreLoginEvent} + * @see #getLoginResult() + */ + @Deprecated + public PlayerPreLoginEvent.Result getResult() { + return result == null ? null : result.old(); + } + + /** + * Sets the new result of the login, as an enum + * + * @param result New result to set + */ + public void setLoginResult(final Result result) { + this.result = result; + } + + /** + * Sets the new result of the login, as an enum + * + * @param result New result to set + * @deprecated This method uses a deprecated enum from {@link + * PlayerPreLoginEvent} + * @see #setLoginResult(Result) + */ + @Deprecated + public void setResult(final PlayerPreLoginEvent.Result result) { + this.result = result == null ? null : Result.valueOf(result.name()); + } + + /** + * Gets the current kick message that will be used if getResult() != + * Result.ALLOWED + * + * @return Current kick message + */ + public String getKickMessage() { + return message; + } + + /** + * Sets the kick message to display if getResult() != Result.ALLOWED + * + * @param message New kick message + */ + public void setKickMessage(final String message) { + this.message = message; + } + + /** + * Allows the player to log in + */ + public void allow() { + result = Result.ALLOWED; + message = ""; + } + + /** + * Disallows the player from logging in, with the given reason + * + * @param result New result for disallowing the player + * @param message Kick message to display to the user + */ + public void disallow(final Result result, final String message) { + this.result = result; + this.message = message; + } + + /** + * Disallows the player from logging in, with the given reason + * + * @param result New result for disallowing the player + * @param message Kick message to display to the user + * @deprecated This method uses a deprecated enum from {@link + * PlayerPreLoginEvent} + * @see #disallow(Result, String) + */ + @Deprecated + public void disallow(final PlayerPreLoginEvent.Result result, final String message) { + this.result = result == null ? null : Result.valueOf(result.name()); + this.message = message; + } + + /** + * Gets the player's name. + * + * @return the player's name + */ + public String getName() { + return name; + } + + /** + * Gets the player IP address. + * + * @return The IP address + */ + public InetAddress getAddress() { + return ipAddress; + } + + /** + * Gets the player's unique ID. + * + * @return The unique ID + */ + public UUID getUniqueId() { + return uniqueId; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + /** + * Basic kick reasons for communicating to plugins + */ + public enum Result { + + /** + * The player is allowed to log in + */ + ALLOWED, + /** + * The player is not allowed to log in, due to the server being full + */ + KICK_FULL, + /** + * The player is not allowed to log in, due to them being banned + */ + KICK_BANNED, + /** + * The player is not allowed to log in, due to them not being on the + * white list + */ + KICK_WHITELIST, + /** + * The player is not allowed to log in, for reasons undefined + */ + KICK_OTHER; + + @Deprecated + private PlayerPreLoginEvent.Result old() { + return PlayerPreLoginEvent.Result.valueOf(name()); + } + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerAchievementAwardedEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerAchievementAwardedEvent.java new file mode 100644 index 0000000..e33fade --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerAchievementAwardedEvent.java @@ -0,0 +1,46 @@ +package org.bukkit.event.player; + +import org.bukkit.Achievement; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a player earns an achievement. + */ +public class PlayerAchievementAwardedEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final Achievement achievement; + private boolean isCancelled = false; + + public PlayerAchievementAwardedEvent(Player player, Achievement achievement) { + super(player); + this.achievement = achievement; + } + + /** + * Gets the Achievement being awarded. + * + * @return the achievement being awarded + */ + public Achievement getAchievement() { + return achievement; + } + + public boolean isCancelled() { + return isCancelled; + } + + public void setCancelled(boolean cancel) { + this.isCancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerAnimationEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerAnimationEvent.java new file mode 100644 index 0000000..cabe77d --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerAnimationEvent.java @@ -0,0 +1,52 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Represents a player animation event + */ +public class PlayerAnimationEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final PlayerAnimationType animationType; + private boolean isCancelled = false; + + /** + * Construct a new PlayerAnimation event + * + * @param player The player instance + */ + public PlayerAnimationEvent(final Player player) { + super(player); + + // Only supported animation type for now: + animationType = PlayerAnimationType.ARM_SWING; + } + + /** + * Get the type of this animation event + * + * @return the animation type + */ + public PlayerAnimationType getAnimationType() { + return animationType; + } + + public boolean isCancelled() { + return this.isCancelled; + } + + public void setCancelled(boolean cancel) { + this.isCancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerAnimationType.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerAnimationType.java new file mode 100644 index 0000000..ea4bf26 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerAnimationType.java @@ -0,0 +1,8 @@ +package org.bukkit.event.player; + +/** + * Different types of player animations + */ +public enum PlayerAnimationType { + ARM_SWING +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerArmorStandManipulateEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerArmorStandManipulateEvent.java new file mode 100644 index 0000000..c0c0451 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerArmorStandManipulateEvent.java @@ -0,0 +1,75 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.ArmorStand; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.inventory.ItemStack; + +/** + * Called when a player interacts with an armor stand and will either swap, retrieve or place an item. + */ +public class PlayerArmorStandManipulateEvent extends PlayerInteractEntityEvent { + + private static final HandlerList handlers = new HandlerList(); + + private final ItemStack playerItem; + private final ItemStack armorStandItem; + private final EquipmentSlot slot; + + public PlayerArmorStandManipulateEvent(final Player who, final ArmorStand clickedEntity, final ItemStack playerItem, final ItemStack armorStandItem, final EquipmentSlot slot) { + super(who, clickedEntity); + this.playerItem = playerItem; + this.armorStandItem = armorStandItem; + this.slot = slot; + } + + /** + * Returns the item held by the player. If this Item is null and the armor stand Item is also null, + * there will be no transaction between the player and the armor stand. + * If the Player's item is null, but the armor stand item is not then the player will obtain the armor stand item. + * In the case that the Player's item is not null, but the armor stand item is null, the players item will be placed on the armor stand. + * If both items are not null, the items will be swapped. + * In the case that the event is cancelled the original items will remain the same. + * @return the item held by the player. + */ + public ItemStack getPlayerItem() { + return this.playerItem; + } + + /** + * Returns the item held by the armor stand. + * If this Item is null and the player's Item is also null, there will be no transaction between the player and the armor stand. + * If the Player's item is null, but the armor stand item is not then the player will obtain the armor stand item. + * In the case that the Player's item is not null, but the armor stand item is null, the players item will be placed on the armor stand. + * If both items are not null, the items will be swapped. + * In the case that the event is cancelled the original items will remain the same. + * @return the item held by the armor stand. + */ + public ItemStack getArmorStandItem() { + return this.armorStandItem; + } + + /** + * Returns the raw item slot of the armor stand in this event. + * + * @return the index of the item obtained or placed of the armor stand. + */ + public EquipmentSlot getSlot() { + return this.slot; + } + + @Override + public ArmorStand getRightClicked() { + return (ArmorStand) this.clickedEntity; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerBedEnterEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerBedEnterEvent.java new file mode 100644 index 0000000..09f1a66 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerBedEnterEvent.java @@ -0,0 +1,46 @@ +package org.bukkit.event.player; + +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * This event is fired when the player is almost about to enter the bed. + */ +public class PlayerBedEnterEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancel = false; + private final Block bed; + + public PlayerBedEnterEvent(final Player who, final Block bed) { + super(who); + this.bed = bed; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + /** + * Returns the bed block involved in this event. + * + * @return the bed block involved in this event + */ + public Block getBed() { + return bed; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerBedLeaveEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerBedLeaveEvent.java new file mode 100644 index 0000000..628ab0b --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerBedLeaveEvent.java @@ -0,0 +1,36 @@ +package org.bukkit.event.player; + +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; + +/** + * This event is fired when the player is leaving a bed. + */ +public class PlayerBedLeaveEvent extends PlayerEvent { + private static final HandlerList handlers = new HandlerList(); + private final Block bed; + + public PlayerBedLeaveEvent(final Player who, final Block bed) { + super(who); + this.bed = bed; + } + + /** + * Returns the bed block involved in this event. + * + * @return the bed block involved in this event + */ + public Block getBed() { + return bed; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerBucketEmptyEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerBucketEmptyEvent.java new file mode 100644 index 0000000..8fb121a --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerBucketEmptyEvent.java @@ -0,0 +1,28 @@ +package org.bukkit.event.player; + +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; +import org.bukkit.inventory.ItemStack; + +/** + * Called when a player empties a bucket + */ +public class PlayerBucketEmptyEvent extends PlayerBucketEvent { + private static final HandlerList handlers = new HandlerList(); + + public PlayerBucketEmptyEvent(final Player who, final Block blockClicked, final BlockFace blockFace, final Material bucket, final ItemStack itemInHand) { + super(who, blockClicked, blockFace, bucket, itemInHand); + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerBucketEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerBucketEvent.java new file mode 100644 index 0000000..d32c55e --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerBucketEvent.java @@ -0,0 +1,80 @@ +package org.bukkit.event.player; + +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.inventory.ItemStack; + +/** + * Called when a player interacts with a Bucket + */ +public abstract class PlayerBucketEvent extends PlayerEvent implements Cancellable { + private ItemStack itemStack; + private boolean cancelled = false; + private final Block blockClicked; + private final BlockFace blockFace; + private final Material bucket; + + public PlayerBucketEvent(final Player who, final Block blockClicked, final BlockFace blockFace, final Material bucket, final ItemStack itemInHand) { + super(who); + this.blockClicked = blockClicked; + this.blockFace = blockFace; + this.itemStack = itemInHand; + this.bucket = bucket; + } + + /** + * Returns the bucket used in this event + * + * @return the used bucket + */ + public Material getBucket() { + return bucket; + } + + /** + * Get the resulting item in hand after the bucket event + * + * @return Itemstack hold in hand after the event. + */ + public ItemStack getItemStack() { + return itemStack; + } + + /** + * Set the item in hand after the event + * + * @param itemStack the new held itemstack after the bucket event. + */ + public void setItemStack(ItemStack itemStack) { + this.itemStack = itemStack; + } + + /** + * Return the block clicked + * + * @return the blicked block + */ + public Block getBlockClicked() { + return blockClicked; + } + + /** + * Get the face on the clicked block + * + * @return the clicked face + */ + public BlockFace getBlockFace() { + return blockFace; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } +} \ No newline at end of file diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerBucketFillEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerBucketFillEvent.java new file mode 100644 index 0000000..94e042a --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerBucketFillEvent.java @@ -0,0 +1,28 @@ +package org.bukkit.event.player; + +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; +import org.bukkit.inventory.ItemStack; + +/** + * Called when a player fills a bucket + */ +public class PlayerBucketFillEvent extends PlayerBucketEvent { + private static final HandlerList handlers = new HandlerList(); + + public PlayerBucketFillEvent(final Player who, final Block blockClicked, final BlockFace blockFace, final Material bucket, final ItemStack itemInHand) { + super(who, blockClicked, blockFace, bucket, itemInHand); + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerCanBlockEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerCanBlockEvent.java new file mode 100644 index 0000000..5035101 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerCanBlockEvent.java @@ -0,0 +1,31 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +public class PlayerCanBlockEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean isCancelled = false; + + public PlayerCanBlockEvent(Player player) { + super(player); + } + + public boolean isCancelled() { + return isCancelled; + } + + public void setCancelled(boolean cancel) { + this.isCancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerCanCritEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerCanCritEvent.java new file mode 100644 index 0000000..f1aae3f --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerCanCritEvent.java @@ -0,0 +1,31 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +public class PlayerCanCritEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean isCancelled = false; + + public PlayerCanCritEvent(Player player) { + super(player); + } + + public boolean isCancelled() { + return isCancelled; + } + + public void setCancelled(boolean cancel) { + this.isCancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerChangedWorldEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerChangedWorldEvent.java new file mode 100644 index 0000000..76c9c20 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerChangedWorldEvent.java @@ -0,0 +1,36 @@ +package org.bukkit.event.player; + +import org.bukkit.World; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; + +/** + * Called when a player switches to another world. + */ +public class PlayerChangedWorldEvent extends PlayerEvent { + private static final HandlerList handlers = new HandlerList(); + private final World from; + + public PlayerChangedWorldEvent(final Player player, final World from) { + super(player); + this.from = from; + } + + /** + * Gets the world the player is switching from. + * + * @return player's previous world + */ + public World getFrom() { + return from; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerChannelEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerChannelEvent.java new file mode 100644 index 0000000..054efbc --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerChannelEvent.java @@ -0,0 +1,31 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; + +/** + * This event is called after a player registers or unregisters a new plugin + * channel. + */ +public abstract class PlayerChannelEvent extends PlayerEvent { + private static final HandlerList handlers = new HandlerList(); + private final String channel; + + public PlayerChannelEvent(final Player player, final String channel) { + super(player); + this.channel = channel; + } + + public final String getChannel() { + return channel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerChatEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerChatEvent.java new file mode 100644 index 0000000..255a0a3 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerChatEvent.java @@ -0,0 +1,125 @@ +package org.bukkit.event.player; + +import org.apache.commons.lang.Validate; +import org.bukkit.Warning; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +import java.util.HashSet; +import java.util.Set; + +/** + * Holds information for player chat and commands + * + * @deprecated This event will fire from the main thread and allows the use of + * all of the Bukkit API, unlike the {@link AsyncPlayerChatEvent}. + *

+ * Listening to this event forces chat to wait for the main thread which + * causes delays for chat. {@link AsyncPlayerChatEvent} is the encouraged + * alternative for thread safe implementations. + */ +@Deprecated +@Warning(reason="Listening to this event forces chat to wait for the main thread, delaying chat messages.") +public class PlayerChatEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancel = false; + private String message; + private String format; + private final Set recipients; + + public PlayerChatEvent(final Player player, final String message) { + super(player); + this.message = message; + this.format = "<%1$s> %2$s"; + this.recipients = new HashSet(player.getServer().getOnlinePlayers()); + } + + public PlayerChatEvent(final Player player, final String message, final String format, final Set recipients) { + super(player); + this.message = message; + this.format = format; + this.recipients = recipients; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + /** + * Gets the message that the player is attempting to send + * + * @return Message the player is attempting to send + */ + public String getMessage() { + return message; + } + + /** + * Sets the message that the player will send + * + * @param message New message that the player will send + */ + public void setMessage(String message) { + this.message = message; + } + + /** + * Sets the player that this message will display as, or command will be + * executed as + * + * @param player New player which this event will execute as + */ + public void setPlayer(final Player player) { + Validate.notNull(player, "Player cannot be null"); + this.player = player; + } + + /** + * Gets the format to use to display this chat message + * + * @return String.Format compatible format string + */ + public String getFormat() { + return format; + } + + /** + * Sets the format to use to display this chat message + * + * @param format String.Format compatible format string + */ + public void setFormat(final String format) { + // Oh for a better way to do this! + try { + String.format(format, player, message); + } catch (RuntimeException ex) { + ex.fillInStackTrace(); + throw ex; + } + + this.format = format; + } + + /** + * Gets a set of recipients that this chat message will be displayed to + * + * @return All Players who will see this chat message + */ + public Set getRecipients() { + return recipients; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerChatTabCompleteEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerChatTabCompleteEvent.java new file mode 100644 index 0000000..1e072eb --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerChatTabCompleteEvent.java @@ -0,0 +1,70 @@ +package org.bukkit.event.player; + +import org.apache.commons.lang.Validate; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; + +import java.util.Collection; + +/** + * Called when a player attempts to tab-complete a chat message. + */ +public class PlayerChatTabCompleteEvent extends PlayerEvent { + private static final HandlerList handlers = new HandlerList(); + private final String message; + private final String lastToken; + private final Collection completions; + + public PlayerChatTabCompleteEvent(final Player who, final String message, final Collection completions) { + super(who); + Validate.notNull(message, "Message cannot be null"); + Validate.notNull(completions, "Completions cannot be null"); + this.message = message; + int i = message.lastIndexOf(' '); + if (i < 0) { + this.lastToken = message; + } else { + this.lastToken = message.substring(i + 1); + } + this.completions = completions; + } + + /** + * Gets the chat message being tab-completed. + * + * @return the chat message + */ + public String getChatMessage() { + return message; + } + + /** + * Gets the last 'token' of the message being tab-completed. + *

+ * The token is the substring starting with the character after the last + * space in the message. + * + * @return The last token for the chat message + */ + public String getLastToken() { + return lastToken; + } + + /** + * This is the collection of completions for this event. + * + * @return the current completions + */ + public Collection getTabCompletions() { + return completions; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerCommandPreprocessEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerCommandPreprocessEvent.java new file mode 100644 index 0000000..3e33ce1 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerCommandPreprocessEvent.java @@ -0,0 +1,172 @@ +package org.bukkit.event.player; + +import org.apache.commons.lang.Validate; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +import java.util.HashSet; +import java.util.Set; + +/** + * This event is called whenever a player runs a command (by placing a slash + * at the start of their message). It is called early in the command handling + * process, and modifications in this event (via {@link #setMessage(String)}) + * will be shown in the behavior. + *

+ * Many plugins will have no use for this event, and you should + * attempt to avoid using it if it is not necessary. + *

+ * Some examples of valid uses for this event are: + *

    + *
  • Logging executed commands to a separate file + *
  • Variable substitution. For example, replacing + * ${nearbyPlayer} with the name of the nearest other + * player, or simulating the @a and @p + * decorators used by Command Blocks in plugins that do not handle it. + *
  • Conditionally blocking commands belonging to other plugins. For + * example, blocking the use of the /home command in a + * combat arena. + *
  • Per-sender command aliases. For example, after a player runs the + * command /calias cr gamemode creative, the next time they + * run /cr, it gets replaced into + * /gamemode creative. (Global command aliases should be + * done by registering the alias.) + *
+ *

+ * Examples of incorrect uses are: + *

    + *
  • Using this event to run command logic + *
+ *

+ * If the event is cancelled, processing of the command will halt. + *

+ * The state of whether or not there is a slash (/) at the + * beginning of the message should be preserved. If a slash is added or + * removed, unexpected behavior may result. + */ +public class PlayerCommandPreprocessEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancel = false; + private String message; + private String format = "<%1$s> %2$s"; + private final Set recipients; + + public PlayerCommandPreprocessEvent(final Player player, final String message) { + super(player); + this.recipients = new HashSet(player.getServer().getOnlinePlayers()); + this.message = message; + } + + public PlayerCommandPreprocessEvent(final Player player, final String message, final Set recipients) { + super(player); + this.recipients = recipients; + this.message = message; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + /** + * Gets the command that the player is attempting to send. + *

+ * All commands begin with a special character; implementations do not + * consider the first character when executing the content. + * + * @return Message the player is attempting to send + */ + public String getMessage() { + return message; + } + + /** + * Sets the command that the player will send. + *

+ * All commands begin with a special character; implementations do not + * consider the first character when executing the content. + * + * @param command New message that the player will send + * @throws IllegalArgumentException if command is null or empty + */ + public void setMessage(String command) throws IllegalArgumentException { + Validate.notNull(command, "Command cannot be null"); + Validate.notEmpty(command, "Command cannot be empty"); + this.message = command; + } + + /** + * Sets the player that this command will be executed as. + * + * @param player New player which this event will execute as + * @throws IllegalArgumentException if the player provided is null + */ + public void setPlayer(final Player player) throws IllegalArgumentException { + Validate.notNull(player, "Player cannot be null"); + this.player = player; + } + + /** + * Gets the format to use to display this chat message + * + * @deprecated This method is provided for backward compatibility with no + * guarantee to the use of the format. + * @return String.Format compatible format string + */ + @Deprecated + public String getFormat() { + return format; + } + + /** + * Sets the format to use to display this chat message + * + * @deprecated This method is provided for backward compatibility with no + * guarantee to the effect of modifying the format. + * @param format String.Format compatible format string + */ + @Deprecated + public void setFormat(final String format) { + // Oh for a better way to do this! + try { + String.format(format, player, message); + } catch (RuntimeException ex) { + ex.fillInStackTrace(); + throw ex; + } + + this.format = format; + } + + /** + * Gets a set of recipients that this chat message will be displayed to. + *

+ * The set returned is not guaranteed to be mutable and may auto-populate + * on access. Any listener accessing the returned set should be aware that + * it may reduce performance for a lazy set implementation. Listeners + * should be aware that modifying the list may throw {@link + * UnsupportedOperationException} if the event caller provides an + * unmodifiable set. + * + * @deprecated This method is provided for backward compatibility with no + * guarantee to the effect of viewing or modifying the set. + * @return All Players who will see this chat message + */ + @Deprecated + public Set getRecipients() { + return recipients; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerCrossPearlEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerCrossPearlEvent.java new file mode 100644 index 0000000..8487a1c --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerCrossPearlEvent.java @@ -0,0 +1,56 @@ +package org.bukkit.event.player; + +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +public class PlayerCrossPearlEvent extends PlayerEvent implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + + private final Location from; + + private boolean cancelled; + + private Location to; + + public PlayerCrossPearlEvent(final Player player, final Location from, final Location to) { + super(player); + this.from = from; + this.to = to; + } + + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + public Location getFrom() { + return from; + } + + public void setFrom(Location to) { + this.to = to; + } + + public Location getTo() { + return to; + } + + public void setTo(Location to) { + this.to = to; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerDropItemEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerDropItemEvent.java new file mode 100644 index 0000000..5b41b65 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerDropItemEvent.java @@ -0,0 +1,46 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Item; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Thrown when a player drops an item from their inventory + */ +public class PlayerDropItemEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final Item drop; + private boolean cancel = false; + + public PlayerDropItemEvent(final Player player, final Item drop) { + super(player); + this.drop = drop; + } + + /** + * Gets the ItemDrop created by the player + * + * @return ItemDrop created by the player + */ + public Item getItemDrop() { + return drop; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerEditBookEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerEditBookEvent.java new file mode 100644 index 0000000..ea7ecef --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerEditBookEvent.java @@ -0,0 +1,124 @@ +package org.bukkit.event.player; + +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; +import org.bukkit.inventory.meta.BookMeta; + +/** + * Called when a player edits or signs a book and quill item. If the event is + * cancelled, no changes are made to the BookMeta + */ +public class PlayerEditBookEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + + private final BookMeta previousBookMeta; + private final int slot; + private BookMeta newBookMeta; + private boolean isSigning; + private boolean cancel; + + public PlayerEditBookEvent(Player who, int slot, BookMeta previousBookMeta, BookMeta newBookMeta, boolean isSigning) { + super(who); + + Validate.isTrue(slot >= 0 && slot <=8, "Slot must be in range 0-8 inclusive"); + Validate.notNull(previousBookMeta, "Previous book meta must not be null"); + Validate.notNull(newBookMeta, "New book meta must not be null"); + + Bukkit.getItemFactory().equals(previousBookMeta, newBookMeta); + + this.previousBookMeta = previousBookMeta; + this.newBookMeta = newBookMeta; + this.slot = slot; + this.isSigning = isSigning; + this.cancel = false; + } + + /** + * Gets the book meta currently on the book. + *

+ * Note: this is a copy of the book meta. You cannot use this object to + * change the existing book meta. + * + * @return the book meta currently on the book + */ + public BookMeta getPreviousBookMeta() { + return previousBookMeta.clone(); + } + + /** + * Gets the book meta that the player is attempting to add to the book. + *

+ * Note: this is a copy of the proposed new book meta. Use {@link + * #setNewBookMeta(BookMeta)} to change what will actually be added to the + * book. + * + * @return the book meta that the player is attempting to add + */ + public BookMeta getNewBookMeta() { + return newBookMeta.clone(); + } + + /** + * Gets the inventory slot number for the book item that triggered this + * event. + *

+ * This is a slot number on the player's hotbar in the range 0-8. + * + * @return the inventory slot number that the book item occupies + */ + public int getSlot() { + return slot; + } + + /** + * Sets the book meta that will actually be added to the book. + * + * @param newBookMeta new book meta + * @throws IllegalArgumentException if the new book meta is null + */ + public void setNewBookMeta(BookMeta newBookMeta) throws IllegalArgumentException { + Validate.notNull(newBookMeta, "New book meta must not be null"); + Bukkit.getItemFactory().equals(newBookMeta, null); + this.newBookMeta = newBookMeta.clone(); + } + + /** + * Gets whether or not the book is being signed. If a book is signed the + * Material changes from BOOK_AND_QUILL to WRITTEN_BOOK. + * + * @return true if the book is being signed + */ + public boolean isSigning() { + return isSigning; + } + + /** + * Sets whether or not the book is being signed. If a book is signed the + * Material changes from BOOK_AND_QUILL to WRITTEN_BOOK. + * + * @param signing whether or not the book is being signed. + */ + public void setSigning(boolean signing) { + isSigning = signing; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerEggThrowEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerEggThrowEvent.java new file mode 100644 index 0000000..896347e --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerEggThrowEvent.java @@ -0,0 +1,137 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.CreatureType; +import org.bukkit.entity.Egg; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; + +/** + * Called when a player throws an egg and it might hatch + */ +public class PlayerEggThrowEvent extends PlayerEvent { + private static final HandlerList handlers = new HandlerList(); + private final Egg egg; + private boolean hatching; + private EntityType hatchType; + private byte numHatches; + + public PlayerEggThrowEvent(final Player player, final Egg egg, final boolean hatching, final byte numHatches, final EntityType hatchingType) { + super(player); + this.egg = egg; + this.hatching = hatching; + this.numHatches = numHatches; + this.hatchType = hatchingType; + } + + @Deprecated + public PlayerEggThrowEvent(Player player, Egg egg, boolean hatching, byte numHatches, CreatureType hatchingType) { + this(player, egg, hatching, numHatches, hatchingType.toEntityType()); + } + + /** + * Gets the egg involved in this event. + * + * @return the egg involved in this event + */ + public Egg getEgg() { + return egg; + } + + /** + * Gets whether the egg is hatching or not. Will be what the server + * would've done without interaction. + * + * @return boolean Whether the egg is going to hatch or not + */ + public boolean isHatching() { + return hatching; + } + + /** + * Sets whether the egg will hatch or not. + * + * @param hatching true if you want the egg to hatch, false if you want it + * not to + */ + public void setHatching(boolean hatching) { + this.hatching = hatching; + } + + /** + * Get the type of the mob being hatched (EntityType.CHICKEN by default) + * + * @return The type of the mob being hatched by the egg + * @deprecated In favour of {@link #getHatchingType()}. + */ + @Deprecated + public CreatureType getHatchType() { + return CreatureType.fromEntityType(hatchType); + } + + /** + * Get the type of the mob being hatched (EntityType.CHICKEN by default) + * + * @return The type of the mob being hatched by the egg + */ + public EntityType getHatchingType() { + return hatchType; + } + + /** + * Change the type of mob being hatched by the egg + * + * @param hatchType The type of the mob being hatched by the egg + * @deprecated In favour of {@link #setHatchingType(EntityType)}. + */ + @Deprecated + public void setHatchType(CreatureType hatchType) { + this.hatchType = hatchType.toEntityType(); + } + + /** + * Change the type of mob being hatched by the egg + * + * @param hatchType The type of the mob being hatched by the egg + */ + public void setHatchingType(EntityType hatchType) { + if(!hatchType.isSpawnable()) throw new IllegalArgumentException("Can't spawn that entity type from an egg!"); + this.hatchType = hatchType; + } + + /** + * Get the number of mob hatches from the egg. By default the number will + * be the number the server would've done + *

    + *
  • 7/8 chance of being 0 + *
  • 31/256 ~= 1/8 chance to be 1 + *
  • 1/256 chance to be 4 + *
+ * + * @return The number of mobs going to be hatched by the egg + */ + public byte getNumHatches() { + return numHatches; + } + + /** + * Change the number of mobs coming out of the hatched egg + *

+ * The boolean hatching will override this number. Ie. If hatching = + * false, this number will not matter + * + * @param numHatches The number of mobs coming out of the egg + */ + public void setNumHatches(byte numHatches) { + this.numHatches = numHatches; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerEvent.java new file mode 100644 index 0000000..0d4833f --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerEvent.java @@ -0,0 +1,30 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Player; +import org.bukkit.event.Event; + +/** + * Represents a player related event + */ +public abstract class PlayerEvent extends Event { + protected Player player; + + public PlayerEvent(final Player who) { + player = who; + } + + PlayerEvent(final Player who, boolean async) { + super(async); + player = who; + + } + + /** + * Returns the player involved in this event + * + * @return Player who is involved in this event + */ + public final Player getPlayer() { + return player; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerExpChangeEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerExpChangeEvent.java new file mode 100644 index 0000000..f37491d --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerExpChangeEvent.java @@ -0,0 +1,44 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; + +/** + * Called when a players experience changes naturally + */ +public class PlayerExpChangeEvent extends PlayerEvent { + private static final HandlerList handlers = new HandlerList(); + private int exp; + + public PlayerExpChangeEvent(final Player player, final int expAmount) { + super(player); + exp = expAmount; + } + + /** + * Get the amount of experience the player will receive + * + * @return The amount of experience + */ + public int getAmount() { + return exp; + } + + /** + * Set the amount of experience the player will receive + * + * @param amount The amount of experience to set + */ + public void setAmount(int amount) { + exp = amount; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerFishEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerFishEvent.java new file mode 100644 index 0000000..bcfb7f3 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerFishEvent.java @@ -0,0 +1,138 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Entity; +import org.bukkit.entity.Fish; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Thrown when a player is fishing + */ +public class PlayerFishEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final Entity entity; + private boolean cancel = false; + private int exp; + private final State state; + private final Fish hookEntity; + + /** + * @deprecated replaced by {@link #PlayerFishEvent(Player, Entity, Fish, + * State)} to include the {@link Fish} hook entity. + * @param player the player fishing + * @param entity the caught entity + * @param state the state of fishing + */ + @Deprecated + public PlayerFishEvent(final Player player, final Entity entity, final State state) { + this(player, entity, null, state); + } + + public PlayerFishEvent(final Player player, final Entity entity, final Fish hookEntity, final State state) { + super(player); + this.entity = entity; + this.hookEntity = hookEntity; + this.state = state; + } + + /** + * Gets the entity caught by the player. + *

+ * If player has fished successfully, the result may be cast to {@link + * org.bukkit.entity.Item}. + * + * @return Entity caught by the player, Entity if fishing, and null if + * bobber has gotten stuck in the ground or nothing has been caught + */ + public Entity getCaught() { + return entity; + } + + /** + * Gets the fishing hook. + * + * @return Fish the entity representing the fishing hook/bobber. + */ + public Fish getHook() { + return hookEntity; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + /** + * Gets the amount of experience received when fishing. + *

+ * Note: This value has no default effect unless the event state is {@link + * State#CAUGHT_FISH}. + * + * @return the amount of experience to drop + */ + public int getExpToDrop() { + return exp; + } + + /** + * Sets the amount of experience received when fishing. + *

+ * Note: This value has no default effect unless the event state is {@link + * State#CAUGHT_FISH}. + * + * @param amount the amount of experience to drop + */ + public void setExpToDrop(int amount) { + exp = amount; + } + + /** + * Gets the state of the fishing + * + * @return A State detailing the state of the fishing + */ + public State getState() { + return state; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + /** + * An enum to specify the state of the fishing + */ + public enum State { + + /** + * When a player is fishing, ie casting the line out. + */ + FISHING, + /** + * When a player has successfully caught a fish and is reeling it in. + */ + CAUGHT_FISH, + /** + * When a player has successfully caught an entity + */ + CAUGHT_ENTITY, + /** + * When a bobber is stuck in the ground + */ + IN_GROUND, + /** + * When a player fails to catch anything while fishing usually due to + * poor aiming or timing + */ + FAILED_ATTEMPT, + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerGameModeChangeEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerGameModeChangeEvent.java new file mode 100644 index 0000000..8c9afa8 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerGameModeChangeEvent.java @@ -0,0 +1,46 @@ +package org.bukkit.event.player; + +import org.bukkit.GameMode; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when the GameMode of the player is changed. + */ +public class PlayerGameModeChangeEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled; + private final GameMode newGameMode; + + public PlayerGameModeChangeEvent(final Player player, final GameMode newGameMode) { + super(player); + this.newGameMode = newGameMode; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + /** + * Gets the GameMode the player is switched to. + * + * @return player's new GameMode + */ + public GameMode getNewGameMode() { + return newGameMode; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerInitialSpawnEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerInitialSpawnEvent.java new file mode 100644 index 0000000..be82593 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerInitialSpawnEvent.java @@ -0,0 +1,42 @@ +package org.bukkit.event.player; + +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; + +public class PlayerInitialSpawnEvent extends PlayerEvent { + private static final HandlerList handlers = new HandlerList(); + private Location spawnLocation; + + public PlayerInitialSpawnEvent(final Player player, final Location spawnLocation) { + super(player); + this.spawnLocation = spawnLocation; + } + + /** + * Gets the current spawn location + * + * @return Location current spawn location + */ + public Location getSpawnLocation() { + return this.spawnLocation; + } + + /** + * Sets the new spawn location + * + * @param spawnLocation new location for the spawn + */ + public void setSpawnLocation(Location spawnLocation) { + this.spawnLocation = spawnLocation; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} \ No newline at end of file diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerInteractAtEntityEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerInteractAtEntityEvent.java new file mode 100644 index 0000000..3293b11 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerInteractAtEntityEvent.java @@ -0,0 +1,33 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; +import org.bukkit.util.Vector; + +/** + * Represents an event that is called when a player right clicks an entity + * with a location on the entity the was clicked. + */ +public class PlayerInteractAtEntityEvent extends PlayerInteractEntityEvent { + private static final HandlerList handlers = new HandlerList(); + private final Vector position; + + public PlayerInteractAtEntityEvent(Player who, Entity clickedEntity, Vector position) { + super(who, clickedEntity); + this.position = position; + } + + public Vector getClickedPosition() { + return position.clone(); + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerInteractEntityEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerInteractEntityEvent.java new file mode 100644 index 0000000..935211d --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerInteractEntityEvent.java @@ -0,0 +1,46 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Represents an event that is called when a player right clicks an entity. + */ +public class PlayerInteractEntityEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + protected Entity clickedEntity; + boolean cancelled = false; + + public PlayerInteractEntityEvent(final Player who, final Entity clickedEntity) { + super(who); + this.clickedEntity = clickedEntity; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + /** + * Gets the entity that was rightclicked by the player. + * + * @return entity right clicked by player + */ + public Entity getRightClicked() { + return this.clickedEntity; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerInteractEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerInteractEvent.java new file mode 100644 index 0000000..7c6cc96 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerInteractEvent.java @@ -0,0 +1,185 @@ +package org.bukkit.event.player; + +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; +import org.bukkit.event.block.Action; +import org.bukkit.inventory.ItemStack; + +/** + * Called when a player interacts with an object or air. + *

+ * This event will fire as cancelled if the vanilla behavior + * is to do nothing (e.g interacting with air) + */ +public class PlayerInteractEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + protected ItemStack item; + protected Action action; + protected Block blockClicked; + protected BlockFace blockFace; + private Result useClickedBlock; + private Result useItemInHand; + + public PlayerInteractEvent(final Player who, final Action action, final ItemStack item, final Block clickedBlock, BlockFace clickedFace) { + super(who); + this.action = action; + this.item = item; + this.blockClicked = clickedBlock; + this.blockFace = clickedFace; + + useItemInHand = Result.DEFAULT; + useClickedBlock = clickedBlock == null ? Result.DENY : Result.ALLOW; + } + + /** + * Returns the action type + * + * @return Action returns the type of interaction + */ + public Action getAction() { + return action; + } + + /** + * Gets the cancellation state of this event. Set to true if you want to + * prevent buckets from placing water and so forth + * + * @return boolean cancellation state + */ + public boolean isCancelled() { + return useInteractedBlock() == Result.DENY; + } + + public BlockFace getBlockFace() { + return this.blockFace; + } + + /** + * Sets the cancellation state of this event. A canceled event will not be + * executed in the server, but will still pass to other plugins + *

+ * Canceling this event will prevent use of food (player won't lose the + * food item), prevent bows/snowballs/eggs from firing, etc. (player won't + * lose the ammo) + * + * @param cancel true if you wish to cancel this event + */ + public void setCancelled(boolean cancel) { + setUseInteractedBlock(cancel ? Result.DENY : useInteractedBlock() == Result.DENY ? Result.DEFAULT : useInteractedBlock()); + setUseItemInHand(cancel ? Result.DENY : useItemInHand() == Result.DENY ? Result.DEFAULT : useItemInHand()); + } + + /** + * Returns the item in hand represented by this event + * + * @return ItemStack the item used + */ + public ItemStack getItem() { + return this.item; + } + + /** + * Convenience method. Returns the material of the item represented by + * this event + * + * @return Material the material of the item used + */ + public Material getMaterial() { + if (!hasItem()) { + return Material.AIR; + } + + return item.getType(); + } + + /** + * Check if this event involved a block + * + * @return boolean true if it did + */ + public boolean hasBlock() { + return this.blockClicked != null; + } + + /** + * Check if this event involved an item + * + * @return boolean true if it did + */ + public boolean hasItem() { + return this.item != null; + } + + /** + * Convenience method to inform the user whether this was a block + * placement event. + * + * @return boolean true if the item in hand was a block + */ + public boolean isBlockInHand() { + if (!hasItem()) { + return false; + } + + return item.getType().isBlock(); + } + + /** + * Returns the clicked block + * + * @return Block returns the block clicked with this item. + */ + public Block getClickedBlock() { + return blockClicked; + } + + /** + * This controls the action to take with the block (if any) that was + * clicked on. This event gets processed for all blocks, but most don't + * have a default action + * + * @return the action to take with the interacted block + */ + public Result useInteractedBlock() { + return useClickedBlock; + } + + /** + * @param useInteractedBlock the action to take with the interacted block + */ + public void setUseInteractedBlock(Result useInteractedBlock) { + this.useClickedBlock = useInteractedBlock; + } + + /** + * This controls the action to take with the item the player is holding. + * This includes both blocks and items (such as flint and steel or + * records). When this is set to default, it will be allowed if no action + * is taken on the interacted block. + * + * @return the action to take with the item in hand + */ + public Result useItemInHand() { + return useItemInHand; + } + + /** + * @param useItemInHand the action to take with the item in hand + */ + public void setUseItemInHand(Result useItemInHand) { + this.useItemInHand = useItemInHand; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerInventoryEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerInventoryEvent.java new file mode 100644 index 0000000..2ec69d7 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerInventoryEvent.java @@ -0,0 +1,44 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryOpenEvent; +import org.bukkit.inventory.Inventory; + +/** + * Represents a player related inventory event; note that this event never + * actually did anything + * + * @deprecated Use {@link InventoryClickEvent} or {@link InventoryOpenEvent} + * instead, or one of the other inventory events in {@link + * org.bukkit.event.inventory}. + */ +@Deprecated +public class PlayerInventoryEvent extends PlayerEvent { + private static final HandlerList handlers = new HandlerList(); + protected Inventory inventory; + + public PlayerInventoryEvent(final Player player, final Inventory inventory) { + super(player); + this.inventory = inventory; + } + + /** + * Gets the Inventory involved in this event + * + * @return Inventory + */ + public Inventory getInventory() { + return inventory; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerItemBreakEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerItemBreakEvent.java new file mode 100644 index 0000000..176cd91 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerItemBreakEvent.java @@ -0,0 +1,39 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; +import org.bukkit.inventory.ItemStack; + +/** + * Fired when a player's item breaks (such as a shovel or flint and steel). + *

+ * The item that's breaking will exist in the inventory with a stack size of + * 0. After the event, the item's durability will be reset to 0. + */ +public class PlayerItemBreakEvent extends PlayerEvent { + private static final HandlerList handlers = new HandlerList(); + private final ItemStack brokenItem; + + public PlayerItemBreakEvent(final Player player, final ItemStack brokenItem) { + super(player); + this.brokenItem = brokenItem; + } + + /** + * Gets the item that broke + * + * @return The broken item + */ + public ItemStack getBrokenItem() { + return brokenItem; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerItemConsumeEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerItemConsumeEvent.java new file mode 100644 index 0000000..b8da5cc --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerItemConsumeEvent.java @@ -0,0 +1,74 @@ +package org.bukkit.event.player; + +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; +import org.bukkit.inventory.ItemStack; + +/** + * This event will fire when a player is finishing consuming an item (food, + * potion, milk bucket). + *
+ * If the ItemStack is modified the server will use the effects of the new + * item and not remove the original one from the player's inventory. + *
+ * If the event is cancelled the effect will not be applied and the item will + * not be removed from the player's inventory. + */ +public class PlayerItemConsumeEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean isCancelled = false; + private ItemStack item; + + /** + * @param player the player consuming + * @param item the ItemStack being consumed + */ + public PlayerItemConsumeEvent(final Player player, final ItemStack item) { + super(player); + + this.item = item; + } + + /** + * Gets the item that is being consumed. Modifying the returned item will + * have no effect, you must use {@link + * #setItem(ItemStack)} instead. + * + * @return an ItemStack for the item being consumed + */ + public ItemStack getItem() { + return item.clone(); + } + + /** + * Set the item being consumed + * + * @param item the item being consumed + */ + public void setItem(ItemStack item) { + if (item == null) { + this.item = new ItemStack(Material.AIR); + } else { + this.item = item; + } + } + + public boolean isCancelled() { + return this.isCancelled; + } + + public void setCancelled(boolean cancel) { + this.isCancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerItemDamageEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerItemDamageEvent.java new file mode 100644 index 0000000..38a72ab --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerItemDamageEvent.java @@ -0,0 +1,54 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; +import org.bukkit.inventory.ItemStack; + +public class PlayerItemDamageEvent extends PlayerEvent implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + private final ItemStack item; + private int damage; + private boolean cancelled = false; + + public PlayerItemDamageEvent(Player player, ItemStack what, int damage) { + super(player); + this.item = what; + this.damage = damage; + } + + public ItemStack getItem() { + return item; + } + + /** + * Gets the amount of durability damage this item will be taking. + * + * @return durability change + */ + public int getDamage() { + return damage; + } + + public void setDamage(int damage) { + this.damage = damage; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerItemHeldEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerItemHeldEvent.java new file mode 100644 index 0000000..f0d055a --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerItemHeldEvent.java @@ -0,0 +1,56 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Fired when a player changes their currently held item + */ +public class PlayerItemHeldEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancel = false; + private final int previous; + private final int current; + + public PlayerItemHeldEvent(final Player player, final int previous, final int current) { + super(player); + this.previous = previous; + this.current = current; + } + + /** + * Gets the previous held slot index + * + * @return Previous slot index + */ + public int getPreviousSlot() { + return previous; + } + + /** + * Gets the new held slot index + * + * @return New slot index + */ + public int getNewSlot() { + return current; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerJoinEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerJoinEvent.java new file mode 100644 index 0000000..e7481f9 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerJoinEvent.java @@ -0,0 +1,44 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; + +/** + * Called when a player joins a server + */ +public class PlayerJoinEvent extends PlayerEvent { + private static final HandlerList handlers = new HandlerList(); + private String joinMessage; + + public PlayerJoinEvent(final Player playerJoined, final String joinMessage) { + super(playerJoined); + this.joinMessage = joinMessage; + } + + /** + * Gets the join message to send to all online players + * + * @return string join message + */ + public String getJoinMessage() { + return joinMessage; + } + + /** + * Sets the join message to send to all online players + * + * @param joinMessage join message + */ + public void setJoinMessage(String joinMessage) { + this.joinMessage = joinMessage; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerKickEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerKickEvent.java new file mode 100644 index 0000000..39e81b6 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerKickEvent.java @@ -0,0 +1,75 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a player gets kicked from the server + */ +public class PlayerKickEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private String leaveMessage; + private String kickReason; + private Boolean cancel; + + public PlayerKickEvent(final Player playerKicked, final String kickReason, final String leaveMessage) { + super(playerKicked); + this.kickReason = kickReason; + this.leaveMessage = leaveMessage; + this.cancel = false; + } + + /** + * Gets the reason why the player is getting kicked + * + * @return string kick reason + */ + public String getReason() { + return kickReason; + } + + /** + * Gets the leave message send to all online players + * + * @return string kick reason + */ + public String getLeaveMessage() { + return leaveMessage; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + /** + * Sets the reason why the player is getting kicked + * + * @param kickReason kick reason + */ + public void setReason(String kickReason) { + this.kickReason = kickReason; + } + + /** + * Sets the leave message send to all online players + * + * @param leaveMessage leave message + */ + public void setLeaveMessage(String leaveMessage) { + this.leaveMessage = leaveMessage; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerLevelChangeEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerLevelChangeEvent.java new file mode 100644 index 0000000..730a776 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerLevelChangeEvent.java @@ -0,0 +1,46 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; + +/** + * Called when a players level changes + */ +public class PlayerLevelChangeEvent extends PlayerEvent { + private static final HandlerList handlers = new HandlerList(); + private final int oldLevel; + private final int newLevel; + + public PlayerLevelChangeEvent(final Player player, final int oldLevel, final int newLevel) { + super(player); + this.oldLevel = oldLevel; + this.newLevel = newLevel; + } + + /** + * Gets the old level of the player + * + * @return The old level of the player + */ + public int getOldLevel() { + return oldLevel; + } + + /** + * Gets the new level of the player + * + * @return The new (current) level of the player + */ + public int getNewLevel() { + return newLevel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerLocaleChangeEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerLocaleChangeEvent.java new file mode 100644 index 0000000..3efd159 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerLocaleChangeEvent.java @@ -0,0 +1,46 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; + +/** + * Called when the locale of the player is changed. + */ +public class PlayerLocaleChangeEvent extends PlayerEvent { + private static final HandlerList handlers = new HandlerList(); + private final String oldLocale; + private final String newLocale; + + public PlayerLocaleChangeEvent(final Player player, final String oldLocale, final String newLocale) { + super(player); + this.oldLocale = oldLocale; + this.newLocale = newLocale; + } + + /** + * Gets the locale the player switched from. + * + * @return player's old locale + */ + public String getOldLocale() { + return oldLocale; + } + + /** + * Gets the locale the player is changed to. + * + * @return player's new locale + */ + public String getNewLocale() { + return newLocale; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} \ No newline at end of file diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerLoginEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerLoginEvent.java new file mode 100644 index 0000000..3efe86d --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerLoginEvent.java @@ -0,0 +1,213 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; + +import java.net.InetAddress; + +/** + * Stores details for players attempting to log in + */ +public class PlayerLoginEvent extends PlayerEvent { + private static final HandlerList handlers = new HandlerList(); + private final InetAddress address; + private final String hostname; + private Result result = Result.ALLOWED; + private String message = ""; + private final InetAddress realAddress; // Spigot + + /** + * @deprecated Address should be provided in other constructor + * @param player The {@link Player} for this event + */ + @Deprecated + public PlayerLoginEvent(final Player player) { + this(player, "", null); + } + + /** + * @deprecated Address should be provided in other constructor + * @param player The {@link Player} for this event + * @param hostname The hostname that was used to connect to the server + */ + @Deprecated + public PlayerLoginEvent(final Player player, final String hostname) { + this(player, hostname, null); + } + + /** + * This constructor defaults message to an empty string, and result to + * ALLOWED + * + * @param player The {@link Player} for this event + * @param hostname The hostname that was used to connect to the server + * @param address The address the player used to connect, provided for + * timing issues + */ + public PlayerLoginEvent(final Player player, final String hostname, final InetAddress address, final InetAddress realAddress) { // Spigot + super(player); + this.hostname = hostname; + this.address = address; + // Spigot start + this.realAddress = realAddress; + } + + public PlayerLoginEvent(final Player player, final String hostname, final InetAddress address) { + this(player, hostname, address, address); + // Spigot end + } + + /** + * @deprecated Address and hostname should be provided in other + * constructor + * @param player The {@link Player} for this event + * @param result The result status for this event + * @param message The message to be displayed if result denies login + */ + @Deprecated + public PlayerLoginEvent(final Player player, final Result result, final String message) { + this(player, "", null, result, message, null); // Spigot + } + + /** + * This constructor pre-configures the event with a result and message + * + * @param player The {@link Player} for this event + * @param hostname The hostname that was used to connect to the server + * @param address The address the player used to connect, provided for + * timing issues + * @param result The result status for this event + * @param message The message to be displayed if result denies login + */ + public PlayerLoginEvent(final Player player, String hostname, final InetAddress address, final Result result, final String message, final InetAddress realAddress) { // Spigot + this(player, hostname, address, realAddress); // Spigot + this.result = result; + this.message = message; + } + + // Spigot start + /** + * Gets the connection address of this player, regardless of whether it has been spoofed or not. + * + * @return the player's connection address + */ + public InetAddress getRealAddress() { + return realAddress; + } + // Spigot end + + /** + * Gets the current result of the login, as an enum + * + * @return Current Result of the login + */ + public Result getResult() { + return result; + } + + /** + * Sets the new result of the login, as an enum + * + * @param result New result to set + */ + public void setResult(final Result result) { + this.result = result; + } + + /** + * Gets the current kick message that will be used if getResult() != + * Result.ALLOWED + * + * @return Current kick message + */ + public String getKickMessage() { + return message; + } + + /** + * Sets the kick message to display if getResult() != Result.ALLOWED + * + * @param message New kick message + */ + public void setKickMessage(final String message) { + this.message = message; + } + + /** + * Gets the hostname that the player used to connect to the server, or + * blank if unknown + * + * @return The hostname + */ + public String getHostname() { + return hostname; + } + + /** + * Allows the player to log in + */ + public void allow() { + result = Result.ALLOWED; + message = ""; + } + + /** + * Disallows the player from logging in, with the given reason + * + * @param result New result for disallowing the player + * @param message Kick message to display to the user + */ + public void disallow(final Result result, final String message) { + this.result = result; + this.message = message; + } + + /** + * Gets the {@link InetAddress} for the Player associated with this event. + * This method is provided as a workaround for player.getAddress() + * returning null during PlayerLoginEvent. + * + * @return The address for this player. For legacy compatibility, this may + * be null. + */ + public InetAddress getAddress() { + return address; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + /** + * Basic kick reasons for communicating to plugins + */ + public enum Result { + + /** + * The player is allowed to log in + */ + ALLOWED, + /** + * The player is not allowed to log in, due to the server being full + */ + KICK_FULL, + /** + * The player is not allowed to log in, due to them being banned + */ + KICK_BANNED, + /** + * The player is not allowed to log in, due to them not being on the + * white list + */ + KICK_WHITELIST, + /** + * The player is not allowed to log in, for reasons undefined + */ + KICK_OTHER + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerMoveEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerMoveEvent.java new file mode 100644 index 0000000..d56b7e4 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerMoveEvent.java @@ -0,0 +1,103 @@ +package org.bukkit.event.player; + +import com.google.common.base.Preconditions; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Holds information for player movement events + */ +public class PlayerMoveEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancel = false; + private Location from; + private Location to; + + public PlayerMoveEvent(final Player player, final Location from, final Location to) { + super(player); + this.from = from; + this.to = to; + } + + /** + * Gets the cancellation state of this event. A cancelled event will not + * be executed in the server, but will still pass to other plugins + *

+ * If a move or teleport event is cancelled, the player will be moved or + * teleported back to the Location as defined by getFrom(). This will not + * fire an event + * + * @return true if this event is cancelled + */ + public boolean isCancelled() { + return cancel; + } + + /** + * Sets the cancellation state of this event. A cancelled event will not + * be executed in the server, but will still pass to other plugins + *

+ * If a move or teleport event is cancelled, the player will be moved or + * teleported back to the Location as defined by getFrom(). This will not + * fire an event + * + * @param cancel true if you wish to cancel this event + */ + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + /** + * Gets the location this player moved from + * + * @return Location the player moved from + */ + public Location getFrom() { + return from; + } + + /** + * Sets the location to mark as where the player moved from + * + * @param from New location to mark as the players previous location + */ + public void setFrom(Location from) { + validateLocation(from); + this.from = from; + } + + /** + * Gets the location this player moved to + * + * @return Location the player moved to + */ + public Location getTo() { + return to; + } + + /** + * Sets the location that this player will move to + * + * @param to New Location this player will move to + */ + public void setTo(Location to) { + validateLocation(to); + this.to = to; + } + + private void validateLocation(Location loc) { + Preconditions.checkArgument(loc != null, "Cannot use null location!"); + Preconditions.checkArgument(loc.getWorld() != null, "Cannot use null location with null world!"); + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerPearlRefundEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerPearlRefundEvent.java new file mode 100644 index 0000000..9416b24 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerPearlRefundEvent.java @@ -0,0 +1,22 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; + +public class PlayerPearlRefundEvent extends PlayerEvent { + + private static final HandlerList handlers = new HandlerList(); + + public PlayerPearlRefundEvent(Player who) { + super(who); + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerPickupItemEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerPickupItemEvent.java new file mode 100644 index 0000000..dfba816 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerPickupItemEvent.java @@ -0,0 +1,57 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Item; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Thrown when a player picks an item up from the ground + */ +public class PlayerPickupItemEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final Item item; + private boolean cancel = false; + private final int remaining; + + public PlayerPickupItemEvent(final Player player, final Item item, final int remaining) { + super(player); + this.item = item; + this.remaining = remaining; + } + + /** + * Gets the Item picked up by the player. + * + * @return Item + */ + public Item getItem() { + return item; + } + + /** + * Gets the amount remaining on the ground, if any + * + * @return amount remaining on the ground + */ + public int getRemaining() { + return remaining; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerPortalEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerPortalEvent.java new file mode 100644 index 0000000..93752f7 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerPortalEvent.java @@ -0,0 +1,87 @@ +package org.bukkit.event.player; + +import org.bukkit.Location; +import org.bukkit.TravelAgent; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; + +/** + * Called when a player is about to teleport because it is in contact with a + * portal. + *

+ * For other entities see {@link org.bukkit.event.entity.EntityPortalEvent} + */ +public class PlayerPortalEvent extends PlayerTeleportEvent { + private static final HandlerList handlers = new HandlerList(); + protected boolean useTravelAgent = true; + protected TravelAgent travelAgent; + + public PlayerPortalEvent(final Player player, final Location from, final Location to, final TravelAgent pta) { + super(player, from, to); + this.travelAgent = pta; + } + + public PlayerPortalEvent(Player player, Location from, Location to, TravelAgent pta, TeleportCause cause) { + super(player, from, to, cause); + this.travelAgent = pta; + } + + /** + * Sets whether or not the Travel Agent will be used. + *

+ * If this is set to true, the TravelAgent will try to find a Portal at + * the {@link #getTo()} Location, and will try to create one if there is + * none. + *

+ * If this is set to false, the {@link #getPlayer()} will only be + * teleported to the {@link #getTo()} Location. + * + * @param useTravelAgent whether to use the Travel Agent + */ + public void useTravelAgent(boolean useTravelAgent) { + this.useTravelAgent = useTravelAgent; + } + + /** + * Gets whether or not the Travel Agent will be used. + *

+ * If this is set to true, the TravelAgent will try to find a Portal at + * the {@link #getTo()} Location, and will try to create one if there is + * none. + *

+ * If this is set to false, the {@link #getPlayer()}} will only be + * teleported to the {@link #getTo()} Location. + * + * @return whether to use the Travel Agent + */ + public boolean useTravelAgent() { + return useTravelAgent && travelAgent != null; + } + + /** + * Gets the Travel Agent used (or not) in this event. + * + * @return the Travel Agent used (or not) in this event + */ + public TravelAgent getPortalTravelAgent() { + return this.travelAgent; + } + + /** + * Sets the Travel Agent used (or not) in this event. + * + * @param travelAgent the Travel Agent used (or not) in this event + */ + public void setPortalTravelAgent(TravelAgent travelAgent) { + this.travelAgent = travelAgent; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} \ No newline at end of file diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerPreLoginEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerPreLoginEvent.java new file mode 100644 index 0000000..fc91a1c --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerPreLoginEvent.java @@ -0,0 +1,159 @@ +package org.bukkit.event.player; + +import org.bukkit.Warning; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +import java.net.InetAddress; +import java.util.UUID; + +/** + * Stores details for players attempting to log in + * + * @deprecated This event causes synchronization from the login thread; {@link + * AsyncPlayerPreLoginEvent} is preferred to keep the secondary threads + * asynchronous. + */ +@Deprecated +@Warning(reason="This event causes a login thread to synchronize with the main thread") +public class PlayerPreLoginEvent extends Event { + private static final HandlerList handlers = new HandlerList(); + private Result result; + private String message; + private final String name; + private final InetAddress ipAddress; + private final UUID uniqueId; + + @Deprecated + public PlayerPreLoginEvent(final String name, final InetAddress ipAddress) { + this(name, ipAddress, null); + } + + public PlayerPreLoginEvent(final String name, final InetAddress ipAddress, final UUID uniqueId) { + this.result = Result.ALLOWED; + this.message = ""; + this.name = name; + this.ipAddress = ipAddress; + this.uniqueId = uniqueId; + } + + /** + * Gets the current result of the login, as an enum + * + * @return Current Result of the login + */ + public Result getResult() { + return result; + } + + /** + * Sets the new result of the login, as an enum + * + * @param result New result to set + */ + public void setResult(final Result result) { + this.result = result; + } + + /** + * Gets the current kick message that will be used if getResult() != + * Result.ALLOWED + * + * @return Current kick message + */ + public String getKickMessage() { + return message; + } + + /** + * Sets the kick message to display if getResult() != Result.ALLOWED + * + * @param message New kick message + */ + public void setKickMessage(final String message) { + this.message = message; + } + + /** + * Allows the player to log in + */ + public void allow() { + result = Result.ALLOWED; + message = ""; + } + + /** + * Disallows the player from logging in, with the given reason + * + * @param result New result for disallowing the player + * @param message Kick message to display to the user + */ + public void disallow(final Result result, final String message) { + this.result = result; + this.message = message; + } + + /** + * Gets the player's name. + * + * @return the player's name + */ + public String getName() { + return name; + } + + /** + * Gets the player IP address. + * + * @return The IP address + */ + public InetAddress getAddress() { + return ipAddress; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + /** + * Gets the player's unique ID. + * + * @return The unique ID + */ + public UUID getUniqueId() { + return uniqueId; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + /** + * Basic kick reasons for communicating to plugins + */ + public enum Result { + + /** + * The player is allowed to log in + */ + ALLOWED, + /** + * The player is not allowed to log in, due to the server being full + */ + KICK_FULL, + /** + * The player is not allowed to log in, due to them being banned + */ + KICK_BANNED, + /** + * The player is not allowed to log in, due to them not being on the + * white list + */ + KICK_WHITELIST, + /** + * The player is not allowed to log in, for reasons undefined + */ + KICK_OTHER + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerQuitEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerQuitEvent.java new file mode 100644 index 0000000..5c8dc1b --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerQuitEvent.java @@ -0,0 +1,44 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; + +/** + * Called when a player leaves a server + */ +public class PlayerQuitEvent extends PlayerEvent { + private static final HandlerList handlers = new HandlerList(); + private String quitMessage; + + public PlayerQuitEvent(final Player who, final String quitMessage) { + super(who); + this.quitMessage = quitMessage; + } + + /** + * Gets the quit message to send to all online players + * + * @return string quit message + */ + public String getQuitMessage() { + return quitMessage; + } + + /** + * Sets the quit message to send to all online players + * + * @param quitMessage quit message + */ + public void setQuitMessage(String quitMessage) { + this.quitMessage = quitMessage; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerRegisterChannelEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerRegisterChannelEvent.java new file mode 100644 index 0000000..442ac7f --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerRegisterChannelEvent.java @@ -0,0 +1,13 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Player; + +/** + * This is called immediately after a player registers for a plugin channel. + */ +public class PlayerRegisterChannelEvent extends PlayerChannelEvent { + + public PlayerRegisterChannelEvent(final Player player, final String channel) { + super(player, channel); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerResourcePackStatusEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerResourcePackStatusEvent.java new file mode 100644 index 0000000..24726c4 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerResourcePackStatusEvent.java @@ -0,0 +1,76 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; + +/** + * Called when a player takes action on a resource pack request sent via + * {@link Player#setResourcePack(String)}. + */ +public class PlayerResourcePackStatusEvent extends PlayerEvent { + + private static final HandlerList handlers = new HandlerList(); + private final String hash; // TacoSpigot + private final Status status; + + @Deprecated // TacoSpigot + public PlayerResourcePackStatusEvent(final Player who, Status resourcePackStatus) { + super(who); + this.hash = null; // TacoSpigot + this.status = resourcePackStatus; + } + + // TacoSpigot start + public PlayerResourcePackStatusEvent(final Player who, Status resourcePackStatus, String hash) { + super(who); + this.hash = hash; + this.status = resourcePackStatus; + } + + public String getHash() { + return this.hash; + } + // TacoSpigot end + + /** + * Gets the status of this pack. + * + * @return the current status + */ + public Status getStatus() { + return status; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + /** + * Status of the resource pack. + */ + public enum Status { + + /** + * The resource pack has been successfully downloaded and applied to the + * client. + */ + SUCCESSFULLY_LOADED, + /** + * The client refused to accept the resource pack. + */ + DECLINED, + /** + * The client accepted the pack, but download failed. + */ + FAILED_DOWNLOAD, + /** + * The client accepted the pack and is beginning a download of it. + */ + ACCEPTED + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerRespawnEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerRespawnEvent.java new file mode 100644 index 0000000..35900dd --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerRespawnEvent.java @@ -0,0 +1,60 @@ +package org.bukkit.event.player; + +import org.apache.commons.lang.Validate; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; + +/** + * Called when a player respawns. + */ +public class PlayerRespawnEvent extends PlayerEvent { + private static final HandlerList handlers = new HandlerList(); + private Location respawnLocation; + private final boolean isBedSpawn; + + public PlayerRespawnEvent(final Player respawnPlayer, final Location respawnLocation, final boolean isBedSpawn) { + super(respawnPlayer); + this.respawnLocation = respawnLocation; + this.isBedSpawn = isBedSpawn; + } + + /** + * Gets the current respawn location + * + * @return Location current respawn location + */ + public Location getRespawnLocation() { + return this.respawnLocation; + } + + /** + * Sets the new respawn location + * + * @param respawnLocation new location for the respawn + */ + public void setRespawnLocation(Location respawnLocation) { + Validate.notNull(respawnLocation, "Respawn location can not be null"); + Validate.notNull(respawnLocation.getWorld(), "Respawn world can not be null"); + + this.respawnLocation = respawnLocation; + } + + /** + * Gets whether the respawn location is the player's bed. + * + * @return true if the respawn location is the player's bed. + */ + public boolean isBedSpawn() { + return this.isBedSpawn; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerShearEntityEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerShearEntityEvent.java new file mode 100644 index 0000000..38afb3c --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerShearEntityEvent.java @@ -0,0 +1,48 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a player shears an entity + */ +public class PlayerShearEntityEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancel; + private final Entity what; + + public PlayerShearEntityEvent(final Player who, final Entity what) { + super(who); + this.cancel = false; + this.what = what; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + /** + * Gets the entity the player is shearing + * + * @return the entity the player is shearing + */ + public Entity getEntity() { + return what; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerStatisticIncrementEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerStatisticIncrementEvent.java new file mode 100644 index 0000000..cec7e77 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerStatisticIncrementEvent.java @@ -0,0 +1,116 @@ +package org.bukkit.event.player; + +import org.bukkit.Material; +import org.bukkit.Statistic; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a player statistic is incremented. + *

+ * This event is not called for {@link Statistic#PLAY_ONE_TICK} or + * movement based statistics. + * + */ +public class PlayerStatisticIncrementEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + protected final Statistic statistic; + private final int initialValue; + private final int newValue; + private boolean isCancelled = false; + private final EntityType entityType; + private final Material material; + + public PlayerStatisticIncrementEvent(Player player, Statistic statistic, int initialValue, int newValue) { + super (player); + this.statistic = statistic; + this.initialValue = initialValue; + this.newValue = newValue; + this.entityType = null; + this.material = null; + } + + public PlayerStatisticIncrementEvent(Player player, Statistic statistic, int initialValue, int newValue, EntityType entityType) { + super (player); + this.statistic = statistic; + this.initialValue = initialValue; + this.newValue = newValue; + this.entityType = entityType; + this.material = null; + } + + public PlayerStatisticIncrementEvent(Player player, Statistic statistic, int initialValue, int newValue, Material material) { + super (player); + this.statistic = statistic; + this.initialValue = initialValue; + this.newValue = newValue; + this.entityType = null; + this.material = material; + } + + /** + * Gets the statistic that is being incremented. + * + * @return the incremented statistic + */ + public Statistic getStatistic() { + return statistic; + } + + /** + * Gets the previous value of the statistic. + * + * @return the previous value of the statistic + */ + public int getPreviousValue() { + return initialValue; + } + + /** + * Gets the new value of the statistic. + * + * @return the new value of the statistic + */ + public int getNewValue() { + return newValue; + } + + /** + * Gets the EntityType if {@link #getStatistic() getStatistic()} is an + * entity statistic otherwise returns null. + * + * @return the EntityType of the statistic + */ + public EntityType getEntityType() { + return entityType; + } + + /** + * Gets the Material if {@link #getStatistic() getStatistic()} is a block + * or item statistic otherwise returns null. + * + * @return the Material of the statistic + */ + public Material getMaterial() { + return material; + } + + public boolean isCancelled() { + return isCancelled; + } + + public void setCancelled(boolean cancel) { + this.isCancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerTeleportEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerTeleportEvent.java new file mode 100644 index 0000000..74d0b13 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerTeleportEvent.java @@ -0,0 +1,82 @@ +package org.bukkit.event.player; + +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; + +/** + * Holds information for player teleport events + */ +public class PlayerTeleportEvent extends PlayerMoveEvent { + private static final HandlerList handlers = new HandlerList(); + private TeleportCause cause = TeleportCause.UNKNOWN; + + public PlayerTeleportEvent(final Player player, final Location from, final Location to) { + super(player, from, to); + } + + public PlayerTeleportEvent(final Player player, final Location from, final Location to, final TeleportCause cause) { + this(player, from, to); + + this.cause = cause; + } + + /** + * Gets the cause of this teleportation event + * + * @return Cause of the event + */ + public TeleportCause getCause() { + return cause; + } + + public enum TeleportCause { + /** + * Indicates the teleporation was caused by a player throwing an Ender + * Pearl + */ + ENDER_PEARL, + /** + * Indicates the teleportation was caused by a player executing a + * command + */ + COMMAND, + /** + * Indicates the teleportation was caused by a plugin + */ + PLUGIN, + /** + * Indicates the teleportation was caused by a player entering a + * Nether portal + */ + NETHER_PORTAL, + /** + * Indicates the teleportation was caused by a player entering an End + * portal + */ + END_PORTAL, + /** + * Indicates the teleportation was caused by a player teleporting to a + * Entity/Player via the specatator menu + */ + SPECTATE, + /** + * Indicates the teleportation was caused by an event not covered by + * this enum + */ + UNKNOWN, + /** + * Add support for anti-cheats to call upon + */ + ANTI_CHEAT + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerToggleFlightEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerToggleFlightEvent.java new file mode 100644 index 0000000..1c5ec37 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerToggleFlightEvent.java @@ -0,0 +1,45 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a player toggles their flying state + */ +public class PlayerToggleFlightEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final boolean isFlying; + private boolean cancel = false; + + public PlayerToggleFlightEvent(final Player player, final boolean isFlying) { + super(player); + this.isFlying = isFlying; + } + + /** + * Returns whether the player is trying to start or stop flying. + * + * @return flying state + */ + public boolean isFlying() { + return isFlying; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerToggleSneakEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerToggleSneakEvent.java new file mode 100644 index 0000000..667acad --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerToggleSneakEvent.java @@ -0,0 +1,45 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a player toggles their sneaking state + */ +public class PlayerToggleSneakEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final boolean isSneaking; + private boolean cancel = false; + + public PlayerToggleSneakEvent(final Player player, final boolean isSneaking) { + super(player); + this.isSneaking = isSneaking; + } + + /** + * Returns whether the player is now sneaking or not. + * + * @return sneaking state + */ + public boolean isSneaking() { + return isSneaking; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerToggleSprintEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerToggleSprintEvent.java new file mode 100644 index 0000000..cf065e1 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerToggleSprintEvent.java @@ -0,0 +1,45 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a player toggles their sprinting state + */ +public class PlayerToggleSprintEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final boolean isSprinting; + private boolean cancel = false; + + public PlayerToggleSprintEvent(final Player player, final boolean isSprinting) { + super(player); + this.isSprinting = isSprinting; + } + + /** + * Gets whether the player is now sprinting or not. + * + * @return sprinting state + */ + public boolean isSprinting() { + return isSprinting; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} \ No newline at end of file diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerUnleashEntityEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerUnleashEntityEvent.java new file mode 100644 index 0000000..f6aebef --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerUnleashEntityEvent.java @@ -0,0 +1,36 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.entity.EntityUnleashEvent; + +/** + * Called prior to an entity being unleashed due to a player's action. + */ +public class PlayerUnleashEntityEvent extends EntityUnleashEvent implements Cancellable { + private final Player player; + private boolean cancelled = false; + + public PlayerUnleashEntityEvent(Entity entity, Player player) { + super(entity, UnleashReason.PLAYER_UNLEASH); + this.player = player; + } + + /** + * Returns the player who is unleashing the entity. + * + * @return The player + */ + public Player getPlayer() { + return player; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerUnregisterChannelEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerUnregisterChannelEvent.java new file mode 100644 index 0000000..11c77e3 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerUnregisterChannelEvent.java @@ -0,0 +1,13 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Player; + +/** + * This is called immediately after a player unregisters for a plugin channel. + */ +public class PlayerUnregisterChannelEvent extends PlayerChannelEvent { + + public PlayerUnregisterChannelEvent(final Player player, final String channel) { + super(player, channel); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/player/PlayerVelocityEvent.java b/azurite-api/src/main/java/org/bukkit/event/player/PlayerVelocityEvent.java new file mode 100644 index 0000000..69d2fce --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/player/PlayerVelocityEvent.java @@ -0,0 +1,55 @@ +package org.bukkit.event.player; + +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; +import org.bukkit.util.Vector; + +/** + * Called when the velocity of a player changes. + */ +public class PlayerVelocityEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancel = false; + private Vector velocity; + + public PlayerVelocityEvent(final Player player, final Vector velocity) { + super(player); + this.velocity = velocity; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + /** + * Gets the velocity vector that will be sent to the player + * + * @return Vector the player will get + */ + public Vector getVelocity() { + return velocity; + } + + /** + * Sets the velocity vector that will be sent to the player + * + * @param velocity The velocity vector that will be sent to the player + */ + public void setVelocity(Vector velocity) { + this.velocity = velocity; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/server/MapInitializeEvent.java b/azurite-api/src/main/java/org/bukkit/event/server/MapInitializeEvent.java new file mode 100644 index 0000000..8834489 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/server/MapInitializeEvent.java @@ -0,0 +1,34 @@ +package org.bukkit.event.server; + +import org.bukkit.event.HandlerList; +import org.bukkit.map.MapView; + +/** + * Called when a map is initialized. + */ +public class MapInitializeEvent extends ServerEvent { + private static final HandlerList handlers = new HandlerList(); + private final MapView mapView; + + public MapInitializeEvent(final MapView mapView) { + this.mapView = mapView; + } + + /** + * Gets the map initialized in this event. + * + * @return Map for this event + */ + public MapView getMap() { + return mapView; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/server/PluginDisableEvent.java b/azurite-api/src/main/java/org/bukkit/event/server/PluginDisableEvent.java new file mode 100644 index 0000000..932c4fd --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/server/PluginDisableEvent.java @@ -0,0 +1,24 @@ +package org.bukkit.event.server; + +import org.bukkit.event.HandlerList; +import org.bukkit.plugin.Plugin; + +/** + * Called when a plugin is disabled. + */ +public class PluginDisableEvent extends PluginEvent { + private static final HandlerList handlers = new HandlerList(); + + public PluginDisableEvent(final Plugin plugin) { + super(plugin); + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/server/PluginEnableEvent.java b/azurite-api/src/main/java/org/bukkit/event/server/PluginEnableEvent.java new file mode 100644 index 0000000..865316d --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/server/PluginEnableEvent.java @@ -0,0 +1,24 @@ +package org.bukkit.event.server; + +import org.bukkit.event.HandlerList; +import org.bukkit.plugin.Plugin; + +/** + * Called when a plugin is enabled. + */ +public class PluginEnableEvent extends PluginEvent { + private static final HandlerList handlers = new HandlerList(); + + public PluginEnableEvent(final Plugin plugin) { + super(plugin); + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/server/PluginEvent.java b/azurite-api/src/main/java/org/bukkit/event/server/PluginEvent.java new file mode 100644 index 0000000..1ad656d --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/server/PluginEvent.java @@ -0,0 +1,23 @@ +package org.bukkit.event.server; + +import org.bukkit.plugin.Plugin; + +/** + * Used for plugin enable and disable events + */ +public abstract class PluginEvent extends ServerEvent { + private final Plugin plugin; + + public PluginEvent(final Plugin plugin) { + this.plugin = plugin; + } + + /** + * Gets the plugin involved in this event + * + * @return Plugin for this event + */ + public Plugin getPlugin() { + return plugin; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/server/RemoteServerCommandEvent.java b/azurite-api/src/main/java/org/bukkit/event/server/RemoteServerCommandEvent.java new file mode 100644 index 0000000..2a49237 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/server/RemoteServerCommandEvent.java @@ -0,0 +1,25 @@ +package org.bukkit.event.server; + +import org.bukkit.command.CommandSender; +import org.bukkit.event.HandlerList; + +/** + * This event is called when a command is recieved over RCON. See the javadocs + * of {@link ServerCommandEvent} for more information. + */ +public class RemoteServerCommandEvent extends ServerCommandEvent { + private static final HandlerList handlers = new HandlerList(); + + public RemoteServerCommandEvent(final CommandSender sender, final String command) { + super(sender, command); + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/server/ServerCommandEvent.java b/azurite-api/src/main/java/org/bukkit/event/server/ServerCommandEvent.java new file mode 100644 index 0000000..10ea0f0 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/server/ServerCommandEvent.java @@ -0,0 +1,98 @@ +package org.bukkit.event.server; + +import org.bukkit.command.CommandSender; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * This event is called when a command is run from the server console. It is + * called early in the command handling process, and modifications in this + * event (via {@link #setCommand(String)}) will be shown in the behavior. + *

+ * Many plugins will have no use for this event, and you should + * attempt to avoid using it if it is not necessary. + *

+ * Some examples of valid uses for this event are: + *

    + *
  • Logging executed commands to a separate file + *
  • Variable substitution. For example, replacing ${ip:Steve} + * with the connection IP of the player named Steve, or simulating the + * @a and @p decorators used by Command Blocks + * for plugins that do not handle it. + *
  • Conditionally blocking commands belonging to other plugins. + *
  • Per-sender command aliases. For example, after the console runs the + * command /calias cr gamemode creative, the next time they + * run /cr, it gets replaced into + * /gamemode creative. (Global command aliases should be + * done by registering the alias.) + *
+ *

+ * Examples of incorrect uses are: + *

    + *
  • Using this event to run command logic + *
+ *

+ * If the event is cancelled, processing of the command will halt. + *

+ * The state of whether or not there is a slash (/) at the + * beginning of the message should be preserved. If a slash is added or + * removed, unexpected behavior may result. + */ +public class ServerCommandEvent extends ServerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private String command; + private final CommandSender sender; + private boolean cancel = false; + + public ServerCommandEvent(final CommandSender sender, final String command) { + this.command = command; + this.sender = sender; + } + + /** + * Gets the command that the user is attempting to execute from the + * console + * + * @return Command the user is attempting to execute + */ + public String getCommand() { + return command; + } + + /** + * Sets the command that the server will execute + * + * @param message New message that the server will execute + */ + public void setCommand(String message) { + this.command = message; + } + + /** + * Get the command sender. + * + * @return The sender + */ + public CommandSender getSender() { + return sender; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + @Override + public boolean isCancelled() { + return cancel; + } + + @Override + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/server/ServerEvent.java b/azurite-api/src/main/java/org/bukkit/event/server/ServerEvent.java new file mode 100644 index 0000000..70416c8 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/server/ServerEvent.java @@ -0,0 +1,19 @@ +package org.bukkit.event.server; + +import org.bukkit.Bukkit; +import org.bukkit.event.Event; + +/** + * Miscellaneous server events + */ +public abstract class ServerEvent extends Event { + // Paper start + public ServerEvent(boolean isAsync) { + super(isAsync); + } + + public ServerEvent() { + super(!Bukkit.isPrimaryThread()); + } + // Paper end +} diff --git a/azurite-api/src/main/java/org/bukkit/event/server/ServerListPingEvent.java b/azurite-api/src/main/java/org/bukkit/event/server/ServerListPingEvent.java new file mode 100644 index 0000000..181da32 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/server/ServerListPingEvent.java @@ -0,0 +1,148 @@ +package org.bukkit.event.server; + +import org.apache.commons.lang.Validate; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; +import org.bukkit.util.CachedServerIcon; + +import java.net.InetAddress; +import java.util.Iterator; + +/** + * Called when a server list ping is coming in. Displayed players can be + * checked and removed by {@link #iterator() iterating} over this event. + */ +public class ServerListPingEvent extends ServerEvent implements Iterable { + private static final int MAGIC_PLAYER_COUNT = Integer.MIN_VALUE; + private static final HandlerList handlers = new HandlerList(); + private final InetAddress address; + private String motd; + private final int numPlayers; + private int maxPlayers; + + public ServerListPingEvent(final InetAddress address, final String motd, final int numPlayers, final int maxPlayers) { + super(); // Paper - Is this event being fired async? + Validate.isTrue(numPlayers >= 0, "Cannot have negative number of players online", numPlayers); + this.address = address; + this.motd = motd; + this.numPlayers = numPlayers; + this.maxPlayers = maxPlayers; + } + + /** + * This constructor is intended for implementations that provide the + * {@link #iterator()} method, thus provided the {@link #getNumPlayers()} + * count. + * + * @param address the address of the pinger + * @param motd the message of the day + * @param maxPlayers the max number of players + */ + protected ServerListPingEvent(final InetAddress address, final String motd, final int maxPlayers) { + super(); // Paper - Is this event being fired async? + this.numPlayers = MAGIC_PLAYER_COUNT; + this.address = address; + this.motd = motd; + this.maxPlayers = maxPlayers; + } + + /** + * Get the address the ping is coming from. + * + * @return the address + */ + public InetAddress getAddress() { + return address; + } + + /** + * Get the message of the day message. + * + * @return the message of the day + */ + public String getMotd() { + return motd; + } + + /** + * Change the message of the day message. + * + * @param motd the message of the day + */ + public void setMotd(String motd) { + this.motd = motd; + } + + /** + * Get the number of players sent. + * + * @return the number of players + */ + public int getNumPlayers() { + int numPlayers = this.numPlayers; + if (numPlayers == MAGIC_PLAYER_COUNT) { + numPlayers = 0; + for (@SuppressWarnings("unused") final Player player : this) { + numPlayers++; + } + } + return numPlayers; + } + + /** + * Get the maximum number of players sent. + * + * @return the maximum number of players + */ + public int getMaxPlayers() { + return maxPlayers; + } + + /** + * Set the maximum number of players sent. + * + * @param maxPlayers the maximum number of player + */ + public void setMaxPlayers(int maxPlayers) { + this.maxPlayers = maxPlayers; + } + + /** + * Sets the server-icon sent to the client. + * + * @param icon the icon to send to the client + * @throws IllegalArgumentException if the {@link CachedServerIcon} is not + * created by the caller of this event; null may be accepted for some + * implementations + * @throws UnsupportedOperationException if the caller of this event does + * not support setting the server icon + */ + public void setServerIcon(CachedServerIcon icon) throws IllegalArgumentException, UnsupportedOperationException { + throw new UnsupportedOperationException(); + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + /** + * {@inheritDoc} + *

+ * Calling the {@link Iterator#remove()} method will force that particular + * player to not be displayed on the player list, decrease the size + * returned by {@link #getNumPlayers()}, and will not be returned again by + * any new iterator. + * + * @throws UnsupportedOperationException if the caller of this event does + * not support removing players + */ + @Override + public Iterator iterator() throws UnsupportedOperationException { + throw new UnsupportedOperationException(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/server/ServerShutdownEvent.java b/azurite-api/src/main/java/org/bukkit/event/server/ServerShutdownEvent.java new file mode 100644 index 0000000..40a9b5e --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/server/ServerShutdownEvent.java @@ -0,0 +1,28 @@ +package org.bukkit.event.server; + +import org.bukkit.Server; +import org.bukkit.event.HandlerList; + +import java.beans.ConstructorProperties; + +public final class ServerShutdownEvent extends ServerEvent { + private static final HandlerList handlerList = new HandlerList(); + private final Server server; + + @ConstructorProperties({"server"}) + public ServerShutdownEvent(Server server) { + this.server = server; + } + + public static HandlerList getHandlerList() { + return handlerList; + } + + public Server getServer() { + return this.server; + } + + public HandlerList getHandlers() { + return handlerList; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/server/ServiceEvent.java b/azurite-api/src/main/java/org/bukkit/event/server/ServiceEvent.java new file mode 100644 index 0000000..69bf872 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/server/ServiceEvent.java @@ -0,0 +1,19 @@ +package org.bukkit.event.server; + +import org.bukkit.plugin.RegisteredServiceProvider; + +/** + * An event relating to a registered service. This is called in a {@link + * org.bukkit.plugin.ServicesManager} + */ +public abstract class ServiceEvent extends ServerEvent { + private final RegisteredServiceProvider provider; + + public ServiceEvent(final RegisteredServiceProvider provider) { + this.provider = provider; + } + + public RegisteredServiceProvider getProvider() { + return provider; + } +} \ No newline at end of file diff --git a/azurite-api/src/main/java/org/bukkit/event/server/ServiceRegisterEvent.java b/azurite-api/src/main/java/org/bukkit/event/server/ServiceRegisterEvent.java new file mode 100644 index 0000000..7dfadde --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/server/ServiceRegisterEvent.java @@ -0,0 +1,27 @@ +package org.bukkit.event.server; + +import org.bukkit.event.HandlerList; +import org.bukkit.plugin.RegisteredServiceProvider; + +/** + * This event is called when a service is registered. + *

+ * Warning: The order in which register and unregister events are called + * should not be relied upon. + */ +public class ServiceRegisterEvent extends ServiceEvent { + private static final HandlerList handlers = new HandlerList(); + + public ServiceRegisterEvent(RegisteredServiceProvider registeredProvider) { + super(registeredProvider); + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/server/ServiceUnregisterEvent.java b/azurite-api/src/main/java/org/bukkit/event/server/ServiceUnregisterEvent.java new file mode 100644 index 0000000..db61d23 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/server/ServiceUnregisterEvent.java @@ -0,0 +1,27 @@ +package org.bukkit.event.server; + +import org.bukkit.event.HandlerList; +import org.bukkit.plugin.RegisteredServiceProvider; + +/** + * This event is called when a service is unregistered. + *

+ * Warning: The order in which register and unregister events are called + * should not be relied upon. + */ +public class ServiceUnregisterEvent extends ServiceEvent { + private static final HandlerList handlers = new HandlerList(); + + public ServiceUnregisterEvent(RegisteredServiceProvider serviceProvider) { + super(serviceProvider); + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/vehicle/VehicleBlockCollisionEvent.java b/azurite-api/src/main/java/org/bukkit/event/vehicle/VehicleBlockCollisionEvent.java new file mode 100644 index 0000000..b643b57 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/vehicle/VehicleBlockCollisionEvent.java @@ -0,0 +1,36 @@ +package org.bukkit.event.vehicle; + +import org.bukkit.block.Block; +import org.bukkit.entity.Vehicle; +import org.bukkit.event.HandlerList; + +/** + * Raised when a vehicle collides with a block. + */ +public class VehicleBlockCollisionEvent extends VehicleCollisionEvent { + private static final HandlerList handlers = new HandlerList(); + private final Block block; + + public VehicleBlockCollisionEvent(final Vehicle vehicle, final Block block) { + super(vehicle); + this.block = block; + } + + /** + * Gets the block the vehicle collided with + * + * @return the block the vehicle collided with + */ + public Block getBlock() { + return block; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/vehicle/VehicleCollisionEvent.java b/azurite-api/src/main/java/org/bukkit/event/vehicle/VehicleCollisionEvent.java new file mode 100644 index 0000000..9dd0579 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/vehicle/VehicleCollisionEvent.java @@ -0,0 +1,12 @@ +package org.bukkit.event.vehicle; + +import org.bukkit.entity.Vehicle; + +/** + * Raised when a vehicle collides. + */ +public abstract class VehicleCollisionEvent extends VehicleEvent { + public VehicleCollisionEvent(final Vehicle vehicle) { + super(vehicle); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/vehicle/VehicleCreateEvent.java b/azurite-api/src/main/java/org/bukkit/event/vehicle/VehicleCreateEvent.java new file mode 100644 index 0000000..22eda72 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/vehicle/VehicleCreateEvent.java @@ -0,0 +1,24 @@ +package org.bukkit.event.vehicle; + +import org.bukkit.entity.Vehicle; +import org.bukkit.event.HandlerList; + +/** + * Raised when a vehicle is created. + */ +public class VehicleCreateEvent extends VehicleEvent { + private static final HandlerList handlers = new HandlerList(); + + public VehicleCreateEvent(final Vehicle vehicle) { + super(vehicle); + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/vehicle/VehicleDamageEvent.java b/azurite-api/src/main/java/org/bukkit/event/vehicle/VehicleDamageEvent.java new file mode 100644 index 0000000..c7b9c1a --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/vehicle/VehicleDamageEvent.java @@ -0,0 +1,96 @@ +package org.bukkit.event.vehicle; + +import org.bukkit.entity.Entity; +import org.bukkit.entity.Vehicle; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; +import org.bukkit.util.NumberConversions; + +/** + * Raised when a vehicle receives damage. + */ +public class VehicleDamageEvent extends VehicleEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final Entity attacker; + private double damage; + private boolean cancelled; + + @Deprecated + public VehicleDamageEvent(final Vehicle vehicle, final Entity attacker, final int damage) { + this(vehicle, attacker, (double) damage); + } + + public VehicleDamageEvent(final Vehicle vehicle, final Entity attacker, final double damage) { + super(vehicle); + this.attacker = attacker; + this.damage = damage; + } + + /** + * Gets the Entity that is attacking the vehicle + * + * @return the Entity that is attacking the vehicle + */ + public Entity getAttacker() { + return attacker; + } + + /** + * Gets the damage done to the vehicle + * + * @return the damage done to the vehicle + */ + public double getDamage() { + return damage; + } + + /** + * This method exists for legacy reasons to provide backwards + * compatibility. It will not exist at runtime and should not be used + * under any circumstances. + * + * @return the damage + */ + @Deprecated + public int _INVALID_getDamage() { + return NumberConversions.ceil(getDamage()); + } + + /** + * Sets the damage done to the vehicle + * + * @param damage The damage + */ + public void setDamage(double damage) { + this.damage = damage; + } + + /** + * This method exists for legacy reasons to provide backwards + * compatibility. It will not exist at runtime and should not be used + * under any circumstances. + * + * @param damage the damage + */ + @Deprecated + public void _INVALID_setDamage(int damage) { + setDamage(damage); + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/vehicle/VehicleDestroyEvent.java b/azurite-api/src/main/java/org/bukkit/event/vehicle/VehicleDestroyEvent.java new file mode 100644 index 0000000..f1176fd --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/vehicle/VehicleDestroyEvent.java @@ -0,0 +1,48 @@ +package org.bukkit.event.vehicle; + +import org.bukkit.entity.Entity; +import org.bukkit.entity.Vehicle; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Raised when a vehicle is destroyed, which could be caused by either a + * player or the environment. This is not raised if the boat is simply + * 'removed' due to other means. + */ +public class VehicleDestroyEvent extends VehicleEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final Entity attacker; + private boolean cancelled; + + public VehicleDestroyEvent(final Vehicle vehicle, final Entity attacker) { + super(vehicle); + this.attacker = attacker; + } + + /** + * Gets the Entity that has destroyed the vehicle, potentially null + * + * @return the Entity that has destroyed the vehicle, potentially null + */ + public Entity getAttacker() { + return attacker; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/vehicle/VehicleEnterEvent.java b/azurite-api/src/main/java/org/bukkit/event/vehicle/VehicleEnterEvent.java new file mode 100644 index 0000000..85c9b21 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/vehicle/VehicleEnterEvent.java @@ -0,0 +1,46 @@ +package org.bukkit.event.vehicle; + +import org.bukkit.entity.Entity; +import org.bukkit.entity.Vehicle; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Raised when an entity enters a vehicle. + */ +public class VehicleEnterEvent extends VehicleEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled; + private final Entity entered; + + public VehicleEnterEvent(final Vehicle vehicle, final Entity entered) { + super(vehicle); + this.entered = entered; + } + + /** + * Gets the Entity that entered the vehicle. + * + * @return the Entity that entered the vehicle + */ + public Entity getEntered() { + return entered; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/vehicle/VehicleEntityCollisionEvent.java b/azurite-api/src/main/java/org/bukkit/event/vehicle/VehicleEntityCollisionEvent.java new file mode 100644 index 0000000..4d4d0e2 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/vehicle/VehicleEntityCollisionEvent.java @@ -0,0 +1,59 @@ +package org.bukkit.event.vehicle; + +import org.bukkit.entity.Entity; +import org.bukkit.entity.Vehicle; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Raised when a vehicle collides with an entity. + */ +public class VehicleEntityCollisionEvent extends VehicleCollisionEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final Entity entity; + private boolean cancelled = false; + private boolean cancelledPickup = false; + private boolean cancelledCollision = false; + + public VehicleEntityCollisionEvent(final Vehicle vehicle, final Entity entity) { + super(vehicle); + this.entity = entity; + } + + public Entity getEntity() { + return entity; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + public boolean isPickupCancelled() { + return cancelledPickup; + } + + public void setPickupCancelled(boolean cancel) { + cancelledPickup = cancel; + } + + public boolean isCollisionCancelled() { + return cancelledCollision; + } + + public void setCollisionCancelled(boolean cancel) { + cancelledCollision = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/vehicle/VehicleEvent.java b/azurite-api/src/main/java/org/bukkit/event/vehicle/VehicleEvent.java new file mode 100644 index 0000000..b8255c0 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/vehicle/VehicleEvent.java @@ -0,0 +1,24 @@ +package org.bukkit.event.vehicle; + +import org.bukkit.entity.Vehicle; +import org.bukkit.event.Event; + +/** + * Represents a vehicle-related event. + */ +public abstract class VehicleEvent extends Event { + protected Vehicle vehicle; + + public VehicleEvent(final Vehicle vehicle) { + this.vehicle = vehicle; + } + + /** + * Get the vehicle. + * + * @return the vehicle + */ + public final Vehicle getVehicle() { + return vehicle; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/vehicle/VehicleExitEvent.java b/azurite-api/src/main/java/org/bukkit/event/vehicle/VehicleExitEvent.java new file mode 100644 index 0000000..364451b --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/vehicle/VehicleExitEvent.java @@ -0,0 +1,46 @@ +package org.bukkit.event.vehicle; + +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Vehicle; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Raised when a living entity exits a vehicle. + */ +public class VehicleExitEvent extends VehicleEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled; + private final LivingEntity exited; + + public VehicleExitEvent(final Vehicle vehicle, final LivingEntity exited) { + super(vehicle); + this.exited = exited; + } + + /** + * Get the living entity that exited the vehicle. + * + * @return The entity. + */ + public LivingEntity getExited() { + return exited; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/vehicle/VehicleMoveEvent.java b/azurite-api/src/main/java/org/bukkit/event/vehicle/VehicleMoveEvent.java new file mode 100644 index 0000000..9a13e29 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/vehicle/VehicleMoveEvent.java @@ -0,0 +1,49 @@ +package org.bukkit.event.vehicle; + +import org.bukkit.Location; +import org.bukkit.entity.Vehicle; +import org.bukkit.event.HandlerList; + +/** + * Raised when a vehicle moves. + */ +public class VehicleMoveEvent extends VehicleEvent { + private static final HandlerList handlers = new HandlerList(); + private final Location from; + private final Location to; + + public VehicleMoveEvent(final Vehicle vehicle, final Location from, final Location to) { + super(vehicle); + + this.from = from; + this.to = to; + } + + /** + * Get the previous position. + * + * @return Old position. + */ + public Location getFrom() { + return from; + } + + /** + * Get the next position. + * + * @return New position. + */ + public Location getTo() { + return to; + } + + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/vehicle/VehicleUpdateEvent.java b/azurite-api/src/main/java/org/bukkit/event/vehicle/VehicleUpdateEvent.java new file mode 100644 index 0000000..eebfdb1 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/vehicle/VehicleUpdateEvent.java @@ -0,0 +1,24 @@ +package org.bukkit.event.vehicle; + +import org.bukkit.entity.Vehicle; +import org.bukkit.event.HandlerList; + +/** + * Called when a vehicle updates + */ +public class VehicleUpdateEvent extends VehicleEvent { + private static final HandlerList handlers = new HandlerList(); + + public VehicleUpdateEvent(final Vehicle vehicle) { + super(vehicle); + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/weather/LightningStrikeEvent.java b/azurite-api/src/main/java/org/bukkit/event/weather/LightningStrikeEvent.java new file mode 100644 index 0000000..66fd763 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/weather/LightningStrikeEvent.java @@ -0,0 +1,46 @@ +package org.bukkit.event.weather; + +import org.bukkit.World; +import org.bukkit.entity.LightningStrike; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Stores data for lightning striking + */ +public class LightningStrikeEvent extends WeatherEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean canceled; + private final LightningStrike bolt; + + public LightningStrikeEvent(final World world, final LightningStrike bolt) { + super(world); + this.bolt = bolt; + } + + public boolean isCancelled() { + return canceled; + } + + public void setCancelled(boolean cancel) { + canceled = cancel; + } + + /** + * Gets the bolt which is striking the earth. + * + * @return lightning entity + */ + public LightningStrike getLightning() { + return bolt; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/weather/ThunderChangeEvent.java b/azurite-api/src/main/java/org/bukkit/event/weather/ThunderChangeEvent.java new file mode 100644 index 0000000..5e3716e --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/weather/ThunderChangeEvent.java @@ -0,0 +1,45 @@ +package org.bukkit.event.weather; + +import org.bukkit.World; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Stores data for thunder state changing in a world + */ +public class ThunderChangeEvent extends WeatherEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean canceled; + private final boolean to; + + public ThunderChangeEvent(final World world, final boolean to) { + super(world); + this.to = to; + } + + public boolean isCancelled() { + return canceled; + } + + public void setCancelled(boolean cancel) { + canceled = cancel; + } + + /** + * Gets the state of thunder that the world is being set to + * + * @return true if the weather is being set to thundering, false otherwise + */ + public boolean toThunderState() { + return to; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/weather/WeatherChangeEvent.java b/azurite-api/src/main/java/org/bukkit/event/weather/WeatherChangeEvent.java new file mode 100644 index 0000000..5d1234e --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/weather/WeatherChangeEvent.java @@ -0,0 +1,45 @@ +package org.bukkit.event.weather; + +import org.bukkit.World; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Stores data for weather changing in a world + */ +public class WeatherChangeEvent extends WeatherEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean canceled; + private final boolean to; + + public WeatherChangeEvent(final World world, final boolean to) { + super(world); + this.to = to; + } + + public boolean isCancelled() { + return canceled; + } + + public void setCancelled(boolean cancel) { + canceled = cancel; + } + + /** + * Gets the state of weather that the world is being set to + * + * @return true if the weather is being set to raining, false otherwise + */ + public boolean toWeatherState() { + return to; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/weather/WeatherEvent.java b/azurite-api/src/main/java/org/bukkit/event/weather/WeatherEvent.java new file mode 100644 index 0000000..0cae9bc --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/weather/WeatherEvent.java @@ -0,0 +1,24 @@ +package org.bukkit.event.weather; + +import org.bukkit.World; +import org.bukkit.event.Event; + +/** + * Represents a Weather-related event + */ +public abstract class WeatherEvent extends Event { + protected World world; + + public WeatherEvent(final World where) { + world = where; + } + + /** + * Returns the World where this event is occurring + * + * @return World this event is occurring in + */ + public final World getWorld() { + return world; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/world/ChunkEvent.java b/azurite-api/src/main/java/org/bukkit/event/world/ChunkEvent.java new file mode 100644 index 0000000..4710d40 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/world/ChunkEvent.java @@ -0,0 +1,24 @@ +package org.bukkit.event.world; + +import org.bukkit.Chunk; + +/** + * Represents a Chunk related event + */ +public abstract class ChunkEvent extends WorldEvent { + protected Chunk chunk; + + protected ChunkEvent(final Chunk chunk) { + super(chunk.getWorld()); + this.chunk = chunk; + } + + /** + * Gets the chunk being loaded/unloaded + * + * @return Chunk that triggered this event + */ + public Chunk getChunk() { + return chunk; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/world/ChunkLoadEvent.java b/azurite-api/src/main/java/org/bukkit/event/world/ChunkLoadEvent.java new file mode 100644 index 0000000..a45b1cd --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/world/ChunkLoadEvent.java @@ -0,0 +1,37 @@ +package org.bukkit.event.world; + +import org.bukkit.Chunk; +import org.bukkit.event.HandlerList; + +/** + * Called when a chunk is loaded + */ +public class ChunkLoadEvent extends ChunkEvent { + private static final HandlerList handlers = new HandlerList(); + private final boolean newChunk; + + public ChunkLoadEvent(final Chunk chunk, final boolean newChunk) { + super(chunk); + this.newChunk = newChunk; + } + + /** + * Gets if this chunk was newly created or not. + *

+ * Note that if this chunk is new, it will not be populated at this time. + * + * @return true if the chunk is new, otherwise false + */ + public boolean isNewChunk() { + return newChunk; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/world/ChunkPopulateEvent.java b/azurite-api/src/main/java/org/bukkit/event/world/ChunkPopulateEvent.java new file mode 100644 index 0000000..705d955 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/world/ChunkPopulateEvent.java @@ -0,0 +1,28 @@ +package org.bukkit.event.world; + +import org.bukkit.Chunk; +import org.bukkit.event.HandlerList; +import org.bukkit.generator.BlockPopulator; + +/** + * Thrown when a new chunk has finished being populated. + *

+ * If your intent is to populate the chunk using this event, please see {@link + * BlockPopulator} + */ +public class ChunkPopulateEvent extends ChunkEvent { + private static final HandlerList handlers = new HandlerList(); + + public ChunkPopulateEvent(final Chunk chunk) { + super(chunk); + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/world/ChunkUnloadEvent.java b/azurite-api/src/main/java/org/bukkit/event/world/ChunkUnloadEvent.java new file mode 100644 index 0000000..f59d091 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/world/ChunkUnloadEvent.java @@ -0,0 +1,34 @@ +package org.bukkit.event.world; + +import org.bukkit.Chunk; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a chunk is unloaded + */ +public class ChunkUnloadEvent extends ChunkEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancel = false; + + public ChunkUnloadEvent(final Chunk chunk) { + super(chunk); + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/world/PortalCreateEvent.java b/azurite-api/src/main/java/org/bukkit/event/world/PortalCreateEvent.java new file mode 100644 index 0000000..7a9799c --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/world/PortalCreateEvent.java @@ -0,0 +1,77 @@ +package org.bukkit.event.world; + +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +import java.util.ArrayList; +import java.util.Collection; + +/** + * Called when a portal is created + */ +public class PortalCreateEvent extends WorldEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancel = false; + private final ArrayList blocks = new ArrayList(); + private CreateReason reason = CreateReason.FIRE; + + public PortalCreateEvent(final Collection blocks, final World world, CreateReason reason) { + super(world); + + this.blocks.addAll(blocks); + this.reason = reason; + } + + /** + * Gets an array list of all the blocks associated with the created portal + * + * @return array list of all the blocks associated with the created portal + */ + public ArrayList getBlocks() { + return this.blocks; + } + + public boolean isCancelled() { + return cancel; + } + + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + /** + * Gets the reason for the portal's creation + * + * @return CreateReason for the portal's creation + */ + public CreateReason getReason() { + return reason; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + /** + * An enum to specify the various reasons for a portal's creation + */ + public enum CreateReason { + /** + * When a portal is created 'traditionally' due to a portal frame + * being set on fire. + */ + FIRE, + /** + * When a portal is created as a destination for an existing portal + * when using the custom PortalTravelAgent + */ + OBC_DESTINATION + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/world/SpawnChangeEvent.java b/azurite-api/src/main/java/org/bukkit/event/world/SpawnChangeEvent.java new file mode 100644 index 0000000..d03b029 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/world/SpawnChangeEvent.java @@ -0,0 +1,37 @@ +package org.bukkit.event.world; + +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.event.HandlerList; + +/** + * An event that is called when a world's spawn changes. The world's previous + * spawn location is included. + */ +public class SpawnChangeEvent extends WorldEvent { + private static final HandlerList handlers = new HandlerList(); + private final Location previousLocation; + + public SpawnChangeEvent(final World world, final Location previousLocation) { + super(world); + this.previousLocation = previousLocation; + } + + /** + * Gets the previous spawn location + * + * @return Location that used to be spawn + */ + public Location getPreviousLocation() { + return previousLocation; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/world/StructureGrowEvent.java b/azurite-api/src/main/java/org/bukkit/event/world/StructureGrowEvent.java new file mode 100644 index 0000000..a26aa49 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/world/StructureGrowEvent.java @@ -0,0 +1,97 @@ +package org.bukkit.event.world; + +import org.bukkit.Location; +import org.bukkit.TreeType; +import org.bukkit.block.BlockState; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +import java.util.List; + +/** + * Event that is called when an organic structure attempts to grow (Sapling {@literal ->} + * Tree), (Mushroom {@literal ->} Huge Mushroom), naturally or using bonemeal. + */ +public class StructureGrowEvent extends WorldEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled = false; + private final Location location; + private final TreeType species; + private final boolean bonemeal; + private final Player player; + private final List blocks; + + public StructureGrowEvent(final Location location, final TreeType species, final boolean bonemeal, final Player player, final List blocks) { + super(location.getWorld()); + this.location = location; + this.species = species; + this.bonemeal = bonemeal; + this.player = player; + this.blocks = blocks; + } + + /** + * Gets the location of the structure. + * + * @return Location of the structure + */ + public Location getLocation() { + return location; + } + + /** + * Gets the species type (birch, normal, pine, red mushroom, brown + * mushroom) + * + * @return Structure species + */ + public TreeType getSpecies() { + return species; + } + + /** + * Checks if structure was grown using bonemeal. + * + * @return True if the structure was grown using bonemeal. + */ + public boolean isFromBonemeal() { + return bonemeal; + } + + /** + * Gets the player that created the structure. + * + * @return Player that created the structure, null if was not created + * manually + */ + public Player getPlayer() { + return player; + } + + /** + * Gets an ArrayList of all blocks associated with the structure. + * + * @return ArrayList of all blocks associated with the structure. + */ + public List getBlocks() { + return blocks; + } + + public boolean isCancelled() { + return cancelled; + } + + public void setCancelled(boolean cancel) { + cancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/world/WorldEffectEvent.java b/azurite-api/src/main/java/org/bukkit/event/world/WorldEffectEvent.java new file mode 100644 index 0000000..fbebc42 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/world/WorldEffectEvent.java @@ -0,0 +1,56 @@ +package org.bukkit.event.world; + +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.event.HandlerList; + +public class WorldEffectEvent extends WorldEvent { + private static final HandlerList handlers = new HandlerList(); + private final int type; + private final int blockX, blockY, blockZ; + private final int data; + private final boolean serverWide; + + public WorldEffectEvent(World world, int type, int blockX, int blockY, int blockZ, int data, boolean serverWide) { + super(world); + this.type = type; + this.blockX = blockX; + this.blockY = blockY; + this.blockZ = blockZ; + this.data = data; + this.serverWide = serverWide; + } + + public int getType() { + return type; + } + + public int getBlockX() { + return blockX; + } + + public int getBlockY() { + return blockY; + } + + public int getBlockZ() { + return blockZ; + } + + public int getData() { + return data; + } + + public boolean isServerWide() { + return serverWide; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/world/WorldEvent.java b/azurite-api/src/main/java/org/bukkit/event/world/WorldEvent.java new file mode 100644 index 0000000..bd89b81 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/world/WorldEvent.java @@ -0,0 +1,24 @@ +package org.bukkit.event.world; + +import org.bukkit.World; +import org.bukkit.event.Event; + +/** + * Represents events within a world + */ +public abstract class WorldEvent extends Event { + private final World world; + + public WorldEvent(final World world) { + this.world = world; + } + + /** + * Gets the world primarily involved with this event + * + * @return World which caused this event + */ + public World getWorld() { + return world; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/world/WorldInitEvent.java b/azurite-api/src/main/java/org/bukkit/event/world/WorldInitEvent.java new file mode 100644 index 0000000..6bf13e0 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/world/WorldInitEvent.java @@ -0,0 +1,24 @@ +package org.bukkit.event.world; + +import org.bukkit.World; +import org.bukkit.event.HandlerList; + +/** + * Called when a World is initializing + */ +public class WorldInitEvent extends WorldEvent { + private static final HandlerList handlers = new HandlerList(); + + public WorldInitEvent(final World world) { + super(world); + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/world/WorldLoadEvent.java b/azurite-api/src/main/java/org/bukkit/event/world/WorldLoadEvent.java new file mode 100644 index 0000000..c5545aa --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/world/WorldLoadEvent.java @@ -0,0 +1,24 @@ +package org.bukkit.event.world; + +import org.bukkit.World; +import org.bukkit.event.HandlerList; + +/** + * Called when a World is loaded + */ +public class WorldLoadEvent extends WorldEvent { + private static final HandlerList handlers = new HandlerList(); + + public WorldLoadEvent(final World world) { + super(world); + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/world/WorldSaveEvent.java b/azurite-api/src/main/java/org/bukkit/event/world/WorldSaveEvent.java new file mode 100644 index 0000000..d46b413 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/world/WorldSaveEvent.java @@ -0,0 +1,24 @@ +package org.bukkit.event.world; + +import org.bukkit.World; +import org.bukkit.event.HandlerList; + +/** + * Called when a World is saved. + */ +public class WorldSaveEvent extends WorldEvent { + private static final HandlerList handlers = new HandlerList(); + + public WorldSaveEvent(final World world) { + super(world); + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/event/world/WorldUnloadEvent.java b/azurite-api/src/main/java/org/bukkit/event/world/WorldUnloadEvent.java new file mode 100644 index 0000000..110544b --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/event/world/WorldUnloadEvent.java @@ -0,0 +1,34 @@ +package org.bukkit.event.world; + +import org.bukkit.World; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a World is unloaded + */ +public class WorldUnloadEvent extends WorldEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean isCancelled; + + public WorldUnloadEvent(final World world) { + super(world); + } + + public boolean isCancelled() { + return this.isCancelled; + } + + public void setCancelled(boolean cancel) { + this.isCancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/generator/BlockPopulator.java b/azurite-api/src/main/java/org/bukkit/generator/BlockPopulator.java new file mode 100644 index 0000000..593dfac --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/generator/BlockPopulator.java @@ -0,0 +1,30 @@ +package org.bukkit.generator; + +import org.bukkit.Chunk; +import org.bukkit.World; + +import java.util.Random; + +/** + * A block populator is responsible for generating a small area of blocks. + *

+ * For example, generating glowstone inside the nether or generating dungeons + * full of treasure + */ +public abstract class BlockPopulator { + + /** + * Populates an area of blocks at or around the given chunk. + *

+ * The chunks on each side of the specified chunk must already exist; that + * is, there must be one north, east, south and west of the specified + * chunk. The "corner" chunks may not exist, in which scenario the + * populator should record any changes required for those chunks and + * perform the changes when they are ready. + * + * @param world The world to generate in + * @param random The random generator to use + * @param source The chunk to generate for + */ + public abstract void populate(World world, Random random, Chunk source); +} diff --git a/azurite-api/src/main/java/org/bukkit/generator/ChunkGenerator.java b/azurite-api/src/main/java/org/bukkit/generator/ChunkGenerator.java new file mode 100644 index 0000000..f941b07 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/generator/ChunkGenerator.java @@ -0,0 +1,496 @@ +package org.bukkit.generator; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.block.Biome; +import org.bukkit.block.Block; +import org.bukkit.material.MaterialData; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +/** + * A chunk generator is responsible for the initial shaping of an entire + * chunk. For example, the nether chunk generator should shape netherrack and + * soulsand + */ +public abstract class ChunkGenerator { + + /** + * Interface to biome section for chunk to be generated: initialized with + * default values for world type and seed. + *

+ * Custom generator is free to access and tailor values during + * generateBlockSections() or generateExtBlockSections(). + */ + public interface BiomeGrid { + + /** + * Get biome at x, z within chunk being generated + * + * @param x - 0-15 + * @param z - 0-15 + * @return Biome value + */ + Biome getBiome(int x, int z); + + /** + * Set biome at x, z within chunk being generated + * + * @param x - 0-15 + * @param z - 0-15 + * @param bio - Biome value + */ + void setBiome(int x, int z, Biome bio); + } + @Deprecated + /** + * Shapes the chunk for the given coordinates. + *

+ * This method should return a byte[32768] in the following format: + *

+     * for (int x = 0; x < 16; x++) {
+     *     for (int z = 0; z < 16; z++) {
+     *         for (int y = 0; y < 128; y++) {
+     *             // result[(x * 16 + z) * 128 + y] = ??;
+     *         }
+     *     }
+     * }
+     * 
+ *

+ * Note that this method should never attempt to get the Chunk at + * the passed coordinates, as doing so may cause an infinite loop + *

+ * Note this deprecated method will only be called when both + * generateExtBlockSections() and generateBlockSections() are + * unimplemented and return null. + * + * @param world The world this chunk will be used for + * @param random The random generator to use + * @param x The X-coordinate of the chunk + * @param z The Z-coordinate of the chunk + * @return byte[] containing the types for each block created by this + * generator + */ + public byte[] generate(World world, Random random, int x, int z) { + throw new UnsupportedOperationException("Custom generator is missing required methods: generate(), generateBlockSections() and generateExtBlockSections()"); + } + + /** + * Shapes the chunk for the given coordinates, with extended block IDs + * supported (0-4095). + *

+ * As of 1.2, chunks are represented by a vertical array of chunk + * sections, each of which is 16 x 16 x 16 blocks. If a section is empty + * (all zero), the section does not need to be supplied, reducing memory + * usage. + *

+ * This method must return a short[][] array in the following format: + *

+     *     short[][] result = new short[world-height / 16][];
+     * 
+ * Each section {@code (sectionID = (Y>>4))} that has blocks needs to be allocated + * space for the 4096 blocks in that section: + *
+     *     result[sectionID] = new short[4096];
+     * 
+ * while sections that are not populated can be left null. + *

+ * Setting a block at X, Y, Z within the chunk can be done with the + * following mapping function: + *

+     *    void setBlock(short[][] result, int x, int y, int z, short blkid) {
+     *        {@code if (result[y >> 4] == null) {}
+     *            {@code result[y >> 4] = new short[4096];}
+     *        }
+     *        {@code result[y >> 4][((y & 0xF) << 8) | (z << 4) | x] = blkid;}
+     *    }
+     * 
+ * while reading a block ID can be done with the following mapping + * function: + *
+     *    short getBlock(short[][] result, int x, int y, int z) {
+     *        {@code if (result[y >> 4] == null) {}
+     *            return (short)0;
+     *        }
+     *        {@code return result[y >> 4][((y & 0xF) << 8) | (z << 4) | x];}
+     *    }
+     * 
+ * while sections that are not populated can be left null. + *

+ * Setting a block at X, Y, Z within the chunk can be done with the + * following mapping function: + *

+     *    void setBlock(short[][] result, int x, int y, int z, short blkid) {
+     *        {@code if (result[y >> 4) == null) {}
+     *            {@code result[y >> 4] = new short[4096];}
+     *        }
+     *        {@code result[y >> 4][((y & 0xF) << 8) | (z << 4) | x] = blkid;}
+     *    }
+     * 
+ * while reading a block ID can be done with the following mapping + * function: + *
+     *    short getBlock(short[][] result, int x, int y, int z) {
+     *        {@code if (result[y >> 4) == null) {}
+     *            return (short)0;
+     *        }
+     *        {@code return result[y >> 4][((y & 0xF) << 8) | (z << 4) | x];}
+     *    }
+     * 
+ *

+ * Note that this method should never attempt to get the Chunk at + * the passed coordinates, as doing so may cause an infinite loop + *

+ * Note generators that do not return block IDs above 255 should not + * implement this method, or should have it return null (which will result + * in the generateBlockSections() method being called). + * + * @param world The world this chunk will be used for + * @param random The random generator to use + * @param x The X-coordinate of the chunk + * @param z The Z-coordinate of the chunk + * @param biomes Proposed biome values for chunk - can be updated by + * generator + * @return short[][] containing the types for each block created by this + * generator + * @deprecated Magic value + */ + @Deprecated + public short[][] generateExtBlockSections(World world, Random random, int x, int z, BiomeGrid biomes) { + return null; // Default - returns null, which drives call to generateBlockSections() + } + + /** + * Shapes the chunk for the given coordinates. + *

+ * As of 1.2, chunks are represented by a vertical array of chunk + * sections, each of which is 16 x 16 x 16 blocks. If a section is empty + * (all zero), the section does not need to be supplied, reducing memory + * usage. + *

+ * This method must return a byte[][] array in the following format: + *

+     *     byte[][] result = new byte[world-height / 16][];
+     * 
+ * Each section {@code (sectionID = (Y>>4))} that has blocks needs to be allocated + * space for the 4096 blocks in that section: + *
+     *     result[sectionID] = new byte[4096];
+     * 
+ * while sections that are not populated can be left null. + *

+ * Setting a block at X, Y, Z within the chunk can be done with the + * following mapping function: + *

+     *    void setBlock(byte[][] result, int x, int y, int z, byte blkid) {
+     *        {@code if (result[y >> 4) == null) {}
+     *            {@code result[y >> 4] = new byte[4096];}
+     *        }
+     *        {@code result[y >> 4][((y & 0xF) << 8) | (z << 4) | x] = blkid;}
+     *    }
+     * 
+ * while reading a block ID can be done with the following mapping + * function: + *
+     *    byte getBlock(byte[][] result, int x, int y, int z) {
+     *        {@code if (result[y >> 4) == null) {}
+     *            return (byte)0;
+     *        }
+     *        {@code return result[y >> 4][((y & 0xF) << 8) | (z << 4) | x];}
+     *    }
+     * 
+ * + * Note that this method should never attempt to get the Chunk at + * the passed coordinates, as doing so may cause an infinite loop + * + * @param world The world this chunk will be used for + * @param random The random generator to use + * @param x The X-coordinate of the chunk + * @param z The Z-coordinate of the chunk + * @param biomes Proposed biome values for chunk - can be updated by + * generator + * @return short[][] containing the types for each block created by this + * generator + * @deprecated Magic value + */ + @Deprecated + public byte[][] generateBlockSections(World world, Random random, int x, int z, BiomeGrid biomes) { + return null; // Default - returns null, which drives call to generate() + } + + /** + * Shapes the chunk for the given coordinates. + * + * This method must return a ChunkData. + *

+ * Notes: + *

+ * This method should never attempt to get the Chunk at + * the passed coordinates, as doing so may cause an infinite loop + *

+ * This method should never modify a ChunkData after it has + * been returned. + *

+ * This method must return a ChunkData returned by {@link ChunkGenerator#createChunkData(World)} + * + * @param world The world this chunk will be used for + * @param random The random generator to use + * @param x The X-coordinate of the chunk + * @param z The Z-coordinate of the chunk + * @param biome Proposed biome values for chunk - can be updated by + * generator + * @return ChunkData containing the types for each block created by this + * generator + */ + public ChunkData generateChunkData(World world, Random random, int x, int z, BiomeGrid biome) { + return null; // Default - returns null, which drives call to generateExtBlockSections() + } + + /** + * Create a ChunkData for a world. + * @param world the world the ChunkData is for + * @return a new ChunkData for world + */ + protected final ChunkData createChunkData(World world) { + return Bukkit.getServer().createChunkData(world); + } + + /** + * Tests if the specified location is valid for a natural spawn position + * + * @param world The world we're testing on + * @param x X-coordinate of the block to test + * @param z Z-coordinate of the block to test + * @return true if the location is valid, otherwise false + */ + public boolean canSpawn(World world, int x, int z) { + Block highest = world.getBlockAt(x, world.getHighestBlockYAt(x, z), z); + + switch (world.getEnvironment()) { + case NETHER: + return true; + case THE_END: + return highest.getType() != Material.AIR && highest.getType() != Material.WATER && highest.getType() != Material.LAVA; + case NORMAL: + default: + return highest.getType() == Material.SAND || highest.getType() == Material.GRAVEL; + } + } + + /** + * Gets a list of default {@link BlockPopulator}s to apply to a given + * world + * + * @param world World to apply to + * @return List containing any amount of BlockPopulators + */ + public List getDefaultPopulators(World world) { + return new ArrayList(); + } + + /** + * Gets a fixed spawn location to use for a given world. + *

+ * A null value is returned if a world should not use a fixed spawn point, + * and will instead attempt to find one randomly. + * + * @param world The world to locate a spawn point for + * @param random Random generator to use in the calculation + * @return Location containing a new spawn point, otherwise null + */ + public Location getFixedSpawnLocation(World world, Random random) { + return null; + } + + /** + * Data for a Chunk. + */ + public interface ChunkData { + /** + * Get the maximum height for the chunk. + * + * Setting blocks at or above this height will do nothing. + * + * @return the maximum height + */ + int getMaxHeight(); + + /** + * Set the block at x,y,z in the chunk data to material. + * + * Note: setting blocks outside the chunk's bounds does nothing. + * + * @param x the x location in the chunk from 0-15 inclusive + * @param y the y location in the chunk from 0 (inclusive) - maxHeight (exclusive) + * @param z the z location in the chunk from 0-15 inclusive + * @param material the type to set the block to + */ + void setBlock(int x, int y, int z, Material material); + + /** + * Set the block at x,y,z in the chunk data to material. + * + * Setting blocks outside the chunk's bounds does nothing. + * + * @param x the x location in the chunk from 0-15 inclusive + * @param y the y location in the chunk from 0 (inclusive) - maxHeight (exclusive) + * @param z the z location in the chunk from 0-15 inclusive + * @param material the type to set the block to + */ + void setBlock(int x, int y, int z, MaterialData material); + + /** + * Set a region of this chunk from xMin, yMin, zMin (inclusive) + * to xMax, yMax, zMax (exclusive) to material. + * + * Setting blocks outside the chunk's bounds does nothing. + * + * @param xMin minimum x location (inclusive) in the chunk to set + * @param yMin minimum y location (inclusive) in the chunk to set + * @param zMin minimum z location (inclusive) in the chunk to set + * @param xMax maximum x location (exclusive) in the chunk to set + * @param yMax maximum y location (exclusive) in the chunk to set + * @param zMax maximum z location (exclusive) in the chunk to set + * @param material the type to set the blocks to + */ + void setRegion(int xMin, int yMin, int zMin, int xMax, int yMax, int zMax, Material material); + + /** + * Set a region of this chunk from xMin, yMin, zMin (inclusive) + * to xMax, yMax, zMax (exclusive) to material. + * + * Setting blocks outside the chunk's bounds does nothing. + * + * @param xMin minimum x location (inclusive) in the chunk to set + * @param yMin minimum y location (inclusive) in the chunk to set + * @param zMin minimum z location (inclusive) in the chunk to set + * @param xMax maximum x location (exclusive) in the chunk to set + * @param yMax maximum y location (exclusive) in the chunk to set + * @param zMax maximum z location (exclusive) in the chunk to set + * @param material the type to set the blocks to + */ + void setRegion(int xMin, int yMin, int zMin, int xMax, int yMax, int zMax, MaterialData material); + + /** + * Get the type of the block at x, y, z. + * + * Getting blocks outside the chunk's bounds returns air. + * + * @param x the x location in the chunk from 0-15 inclusive + * @param y the y location in the chunk from 0 (inclusive) - maxHeight (exclusive) + * @param z the z location in the chunk from 0-15 inclusive + * @return the type of the block or Material.AIR if x, y or z are outside the chunk's bounds + */ + Material getType(int x, int y, int z); + + /** + * Get the type and data of the block at x, y ,z. + * + * Getting blocks outside the chunk's bounds returns air. + * + * @param x the x location in the chunk from 0-15 inclusive + * @param y the y location in the chunk from 0 (inclusive) - maxHeight (exclusive) + * @param z the z location in the chunk from 0-15 inclusive + * @return the type and data of the block or the MaterialData for air if x, y or z are outside the chunk's bounds + */ + MaterialData getTypeAndData(int x, int y, int z); + + /** + * Set a region of this chunk from xMin, yMin, zMin (inclusive) + * to xMax, yMax, zMax (exclusive) to block id. + * + * Setting blocks outside the chunk's bounds does nothing. + * + * @param xMin minimum x location (inclusive) in the chunk to set + * @param yMin minimum y location (inclusive) in the chunk to set + * @param zMin minimum z location (inclusive) in the chunk to set + * @param xMax maximum x location (exclusive) in the chunk to set + * @param yMax maximum y location (exclusive) in the chunk to set + * @param zMax maximum z location (exclusive) in the chunk to set + * @param blockId the block id to set the blocks to + * @deprecated Uses magic values. + */ + @Deprecated + void setRegion(int xMin, int yMin, int zMin, int xMax, int yMax, int zMax, int blockId); + + /** + * Set a region of this chunk from xMin, yMin, zMin (inclusive) + * to xMax, yMax, zMax (exclusive) to block id and data. + * + * Setting blocks outside the chunk's bounds does nothing. + * + * @param xMin minimum x location (inclusive) in the chunk to set + * @param yMin minimum y location (inclusive) in the chunk to set + * @param zMin minimum z location (inclusive) in the chunk to set + * @param xMax maximum x location (exclusive) in the chunk to set + * @param yMax maximum y location (exclusive) in the chunk to set + * @param zMax maximum z location (exclusive) in the chunk to set + * @param blockId the block id to set the blocks to + * @param data the block data to set the blocks to + * @deprecated Uses magic values. + */ + @Deprecated + void setRegion(int xMin, int yMin, int zMin, int xMax, int yMax, int zMax, int blockId, int data); + + /** + * Set the block at x,y,z in the chunk data to blockId. + * + * Setting blocks outside the chunk's bounds does nothing. + * + * @param x the x location in the chunk from 0-15 inclusive + * @param y the y location in the chunk from 0 (inclusive) - maxHeight (exclusive) + * @param z the z location in the chunk from 0-15 inclusive + * @param blockId the blockId to set the block to + * @deprecated Uses magic values + */ + @Deprecated + void setBlock(int x, int y, int z, int blockId); + + /** + * Set the block at x,y,z in the chunk data to blockId. + * + * Setting blocks outside the chunk's bounds does nothing. + * + * @param x the x location in the chunk from 0-15 inclusive + * @param y the y location in the chunk from 0 (inclusive) - maxHeight (exclusive) + * @param z the z location in the chunk from 0-15 inclusive + * @param blockId the blockId to set the block to + * @param data the block data to set the block to + * @deprecated Uses magic values + */ + @Deprecated + void setBlock(int x, int y, int z, int blockId, byte data); + + /** + * Get the blockId at x,y,z in the chunk data. + * + * Getting blocks outside the chunk's bounds returns 0. + * + * @param x the x location in the chunk from 0-15 inclusive + * @param y the y location in the chunk from 0 (inclusive) - maxHeight (exclusive) + * @param z the z location in the chunk from 0-15 inclusive + * @return the block id or 0 if x, y or z are outside the chunk's bounds + * @deprecated Uses magic values + */ + @Deprecated + int getTypeId(int x, int y, int z); + + /** + * Get the block data at x,y,z in the chunk data. + * + * Getting blocks outside the chunk's bounds returns 0. + * + * @param x the x location in the chunk from 0-15 inclusive + * @param y the y location in the chunk from 0 (inclusive) - maxHeight (exclusive) + * @param z the z location in the chunk from 0-15 inclusive + * @return the block data value or air if x, y or z are outside the chunk's bounds + * @deprecated Uses magic values + */ + @Deprecated + byte getData(int x, int y, int z); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/help/GenericCommandHelpTopic.java b/azurite-api/src/main/java/org/bukkit/help/GenericCommandHelpTopic.java new file mode 100644 index 0000000..32f93e9 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/help/GenericCommandHelpTopic.java @@ -0,0 +1,78 @@ +package org.bukkit.help; + +import org.apache.commons.lang.StringUtils; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.command.ConsoleCommandSender; +import org.bukkit.command.defaults.VanillaCommand; + +/** + * Lacking an alternative, the help system will create instances of + * GenericCommandHelpTopic for each command in the server's CommandMap. You + * can use this class as a base class for custom help topics, or as an example + * for how to write your own. + */ +public class GenericCommandHelpTopic extends HelpTopic { + + protected Command command; + + public GenericCommandHelpTopic(Command command) { + this.command = command; + + if (command.getLabel().startsWith("/")) { + name = command.getLabel(); + } else { + name = "/" + command.getLabel(); + } + + // The short text is the first line of the description + int i = command.getDescription().indexOf("\n"); + if (i > 1) { + shortText = command.getDescription().substring(0, i - 1); + } else { + shortText = command.getDescription(); + } + + // Build full text + StringBuffer sb = new StringBuffer(); + + sb.append(ChatColor.GOLD); + sb.append("Description: "); + sb.append(ChatColor.WHITE); + sb.append(command.getDescription()); + + sb.append("\n"); + + sb.append(ChatColor.GOLD); + sb.append("Usage: "); + sb.append(ChatColor.WHITE); + sb.append(command.getUsage().replace("", name.substring(1))); + + if (command.getAliases().size() > 0) { + sb.append("\n"); + sb.append(ChatColor.GOLD); + sb.append("Aliases: "); + sb.append(ChatColor.WHITE); + sb.append(ChatColor.WHITE + StringUtils.join(command.getAliases(), ", ")); + } + fullText = sb.toString(); + } + + public boolean canSee(CommandSender sender) { + if (!command.isRegistered() && !(command instanceof VanillaCommand)) { + // Unregistered commands should not show up in the help (ignore VanillaCommands) + return false; + } + + if (sender instanceof ConsoleCommandSender) { + return true; + } + + if (amendedPermission != null) { + return sender.hasPermission(amendedPermission); + } else { + return command.testPermissionSilent(sender); + } + } +} diff --git a/azurite-api/src/main/java/org/bukkit/help/HelpMap.java b/azurite-api/src/main/java/org/bukkit/help/HelpMap.java new file mode 100644 index 0000000..af129da --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/help/HelpMap.java @@ -0,0 +1,79 @@ +package org.bukkit.help; + +import java.util.Collection; +import java.util.List; + +/** + * The HelpMap tracks all help topics registered in a Bukkit server. When the + * server starts up or is reloaded, help is processed and topics are added in + * the following order: + * + *

    + *
  1. General topics are loaded from the help.yml + *
  2. Plugins load and optionally call {@code addTopic()} + *
  3. Registered plugin commands are processed by {@link HelpTopicFactory} + * objects to create topics + *
  4. Topic contents are amended as directed in help.yml + *
+ */ +public interface HelpMap { + /** + * Returns a help topic for a given topic name. + * + * @param topicName The help topic name to look up. + * @return A {@link HelpTopic} object matching the topic name or null if + * none can be found. + */ + HelpTopic getHelpTopic(String topicName); + + /** + * Returns a collection of all the registered help topics. + * + * @return All the registered help topics. + */ + Collection getHelpTopics(); + + /** + * Adds a topic to the server's help index. + * + * @param topic The new help topic to add. + */ + void addTopic(HelpTopic topic); + + /** + * Clears out the contents of the help index. Normally called during + * server reload. + */ + void clear(); + + /** + * Associates a {@link HelpTopicFactory} object with given command base + * class. Plugins typically call this method during {@code onLoad()}. Once + * registered, the custom HelpTopicFactory will be used to create a custom + * {@link HelpTopic} for all commands deriving from the {@code + * commandClass} base class, or all commands deriving from {@link + * org.bukkit.command.PluginCommand} who's executor derives from {@code + * commandClass} base class. + * + * @param commandClass The class for which the custom HelpTopicFactory + * applies. Must derive from either {@link org.bukkit.command.Command} + * or {@link org.bukkit.command.CommandExecutor}. + * @param factory The {@link HelpTopicFactory} implementation to associate + * with the {@code commandClass}. + * @throws IllegalArgumentException Thrown if {@code commandClass} does + * not derive from a legal base class. + */ + void registerHelpTopicFactory(Class commandClass, HelpTopicFactory factory); + + /** + * Gets the list of plugins the server administrator has chosen to exclude + * from the help index. Plugin authors who choose to directly extend + * {@link org.bukkit.command.Command} instead of {@link + * org.bukkit.command.PluginCommand} will need to check this collection in + * their {@link HelpTopicFactory} implementations to ensure they meet the + * server administrator's expectations. + * + * @return A list of plugins that should be excluded from the help index. + */ + List getIgnoredPlugins(); +} diff --git a/azurite-api/src/main/java/org/bukkit/help/HelpTopic.java b/azurite-api/src/main/java/org/bukkit/help/HelpTopic.java new file mode 100644 index 0000000..7900a1b --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/help/HelpTopic.java @@ -0,0 +1,121 @@ +package org.bukkit.help; + +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +/** + * HelpTopic implementations are displayed to the user when the user uses the + * /help command. + *

+ * Custom implementations of this class can work at two levels. A simple + * implementation only needs to set the value of {@code name}, {@code + * shortText}, and {@code fullText} in the constructor. This base class will + * take care of the rest. + *

+ * Complex implementations can be created by overriding the behavior of all + * the methods in this class. + */ +public abstract class HelpTopic { + protected String name; + protected String shortText; + protected String fullText; + protected String amendedPermission; + + /** + * Determines if a {@link Player} is allowed to see this help topic. + *

+ * HelpTopic implementations should take server administrator wishes into + * account as set by the {@link HelpTopic#amendCanSee(String)} function. + * + * @param player The Player in question. + * @return True of the Player can see this help topic, false otherwise. + */ + public abstract boolean canSee(CommandSender player); + + /** + * Allows the server administrator to override the permission required to + * see a help topic. + *

+ * HelpTopic implementations should take this into account when + * determining topic visibility on the {@link + * HelpTopic#canSee(CommandSender)} function. + * + * @param amendedPermission The permission node the server administrator + * wishes to apply to this topic. + */ + public void amendCanSee(String amendedPermission) { + this.amendedPermission = amendedPermission; + } + + /** + * Returns the name of this help topic. + * + * @return The topic name. + */ + public String getName() { + return name; + } + + /** + * Returns a brief description that will be displayed in the topic index. + * + * @return A brief topic description. + */ + public String getShortText() { + return shortText; + } + + /** + * Returns the full description of this help topic that is displayed when + * the user requests this topic's details. + *

+ * The result will be paginated to properly fit the user's client. + * + * @param forWho The player or console requesting the full text. Useful + * for further security trimming the command's full text based on + * sub-permissions in custom implementations. + * + * @return A full topic description. + */ + public String getFullText(CommandSender forWho) { + return fullText; + } + + /** + * Allows the server admin (or another plugin) to add or replace the + * contents of a help topic. + *

+ * A null in either parameter will leave that part of the topic unchanged. + * In either amending parameter, the string {@literal } is replaced + * with the existing contents in the help topic. Use this to append or + * prepend additional content into an automatically generated help topic. + * + * @param amendedShortText The new topic short text to use, or null to + * leave alone. + * @param amendedFullText The new topic full text to use, or null to leave + * alone. + */ + public void amendTopic(String amendedShortText, String amendedFullText) { + shortText = applyAmendment(shortText, amendedShortText); + fullText = applyAmendment(fullText, amendedFullText); + } + + /** + * Developers implementing their own custom HelpTopic implementations can + * use this utility method to ensure their implementations comply with the + * expected behavior of the {@link HelpTopic#amendTopic(String, String)} + * method. + * + * @param baseText The existing text of the help topic. + * @param amendment The amending text from the amendTopic() method. + * @return The application of the amending text to the existing text, + * according to the expected rules of amendTopic(). + */ + protected String applyAmendment(String baseText, String amendment) { + if (amendment == null) { + return baseText; + } else { + return amendment.replaceAll("", baseText); + } + } +} diff --git a/azurite-api/src/main/java/org/bukkit/help/HelpTopicComparator.java b/azurite-api/src/main/java/org/bukkit/help/HelpTopicComparator.java new file mode 100644 index 0000000..cfc0fbf --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/help/HelpTopicComparator.java @@ -0,0 +1,46 @@ +package org.bukkit.help; + +import java.util.Comparator; + +/** + * Used to impose a custom total ordering on help topics. + *

+ * All topics are listed in alphabetic order, but topics that start with a + * slash come after topics that don't. + */ +public class HelpTopicComparator implements Comparator { + + // Singleton implementations + private static final TopicNameComparator tnc = new TopicNameComparator(); + public static TopicNameComparator topicNameComparatorInstance() { + return tnc; + } + + private static final HelpTopicComparator htc = new HelpTopicComparator(); + public static HelpTopicComparator helpTopicComparatorInstance() { + return htc; + } + + private HelpTopicComparator() {} + + public int compare(HelpTopic lhs, HelpTopic rhs) { + return tnc.compare(lhs.getName(), rhs.getName()); + } + + public static class TopicNameComparator implements Comparator { + private TopicNameComparator(){} + + public int compare(String lhs, String rhs) { + boolean lhsStartSlash = lhs.startsWith("/"); + boolean rhsStartSlash = rhs.startsWith("/"); + + if (lhsStartSlash && !rhsStartSlash) { + return 1; + } else if (!lhsStartSlash && rhsStartSlash) { + return -1; + } else { + return lhs.compareToIgnoreCase(rhs); + } + } + } +} diff --git a/azurite-api/src/main/java/org/bukkit/help/HelpTopicFactory.java b/azurite-api/src/main/java/org/bukkit/help/HelpTopicFactory.java new file mode 100644 index 0000000..03a2839 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/help/HelpTopicFactory.java @@ -0,0 +1,42 @@ +package org.bukkit.help; + +import org.bukkit.command.Command; + +/** + * A HelpTopicFactory is used to create custom {@link HelpTopic} objects from + * commands that inherit from a common base class or have executors that + * inherit from a common base class. You can use a custom HelpTopic to change + * the way all the commands in your plugin display in the help. If your plugin + * implements a complex permissions system, a custom help topic may also be + * appropriate. + *

+ * To automatically bind your plugin's commands to your custom HelpTopic + * implementation, first make sure all your commands or executors derive from + * a custom base class (it doesn't have to do anything). Next implement a + * custom HelpTopicFactory that accepts your custom command base class and + * instantiates an instance of your custom HelpTopic from it. Finally, + * register your HelpTopicFactory against your command base class using the + * {@link HelpMap#registerHelpTopicFactory(Class, HelpTopicFactory)} method. + *

+ * As the help system iterates over all registered commands to make help + * topics, it first checks to see if there is a HelpTopicFactory registered + * for the command's base class. If so, the factory is used to make a help + * topic rather than a generic help topic. If no factory is found for the + * command's base class and the command derives from {@link + * org.bukkit.command.PluginCommand}, then the type of the command's executor + * is inspected looking for a registered HelpTopicFactory. Finally, if no + * factory is found, a generic help topic is created for the command. + * + * @param The base class for your custom commands. + */ +public interface HelpTopicFactory { + /** + * This method accepts a command deriving from a custom command base class + * and constructs a custom HelpTopic for it. + * + * @param command The custom command to build a help topic for. + * @return A new custom help topic or {@code null} to intentionally NOT + * create a topic. + */ + HelpTopic createTopic(TCommand command); +} diff --git a/azurite-api/src/main/java/org/bukkit/help/IndexHelpTopic.java b/azurite-api/src/main/java/org/bukkit/help/IndexHelpTopic.java new file mode 100644 index 0000000..c474031 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/help/IndexHelpTopic.java @@ -0,0 +1,112 @@ +package org.bukkit.help; + +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.command.ConsoleCommandSender; +import org.bukkit.entity.Player; +import org.bukkit.util.ChatPaginator; + +import java.util.Collection; + +/** + * This help topic generates a list of other help topics. This class is useful + * for adding your own index help topics. To enforce a particular order, use a + * sorted collection. + *

+ * If a preamble is provided to the constructor, that text will be displayed + * before the first item in the index. + */ +public class IndexHelpTopic extends HelpTopic { + + protected String permission; + protected String preamble; + protected Collection allTopics; + + public IndexHelpTopic(String name, String shortText, String permission, Collection topics) { + this(name, shortText, permission, topics, null); + } + + public IndexHelpTopic(String name, String shortText, String permission, Collection topics, String preamble) { + this.name = name; + this.shortText = shortText; + this.permission = permission; + this.preamble = preamble; + setTopicsCollection(topics); + } + + /** + * Sets the contents of the internal allTopics collection. + * + * @param topics The topics to set. + */ + protected void setTopicsCollection(Collection topics) { + this.allTopics = topics; + } + + public boolean canSee(CommandSender sender) { + if (sender instanceof ConsoleCommandSender) { + return true; + } + if (permission == null) { + return true; + } + return sender.hasPermission(permission); + } + + @Override + public void amendCanSee(String amendedPermission) { + permission = amendedPermission; + } + + public String getFullText(CommandSender sender) { + StringBuilder sb = new StringBuilder(); + + if (preamble != null) { + sb.append(buildPreamble(sender)); + sb.append("\n"); + } + + for (HelpTopic topic : allTopics) { + if (topic.canSee(sender)) { + String lineStr = buildIndexLine(sender, topic).replace("\n", ". "); + if (sender instanceof Player && lineStr.length() > ChatPaginator.GUARANTEED_NO_WRAP_CHAT_PAGE_WIDTH) { + sb.append(lineStr.substring(0, ChatPaginator.GUARANTEED_NO_WRAP_CHAT_PAGE_WIDTH - 3)); + sb.append("..."); + } else { + sb.append(lineStr); + } + sb.append("\n"); + } + } + return sb.toString(); + } + + /** + * Builds the topic preamble. Override this method to change how the index + * preamble looks. + * + * @param sender The command sender requesting the preamble. + * @return The topic preamble. + */ + protected String buildPreamble(CommandSender sender) { + return ChatColor.GRAY + preamble; + } + + /** + * Builds individual lines in the index topic. Override this method to + * change how index lines are rendered. + * + * @param sender The command sender requesting the index line. + * @param topic The topic to render into an index line. + * @return The rendered index line. + */ + protected String buildIndexLine(CommandSender sender, HelpTopic topic) { + StringBuilder line = new StringBuilder(); + line.append(ChatColor.GOLD); + line.append(topic.getName()); + line.append(": "); + line.append(ChatColor.WHITE); + line.append(topic.getShortText()); + return line.toString(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/inventory/AnvilInventory.java b/azurite-api/src/main/java/org/bukkit/inventory/AnvilInventory.java new file mode 100644 index 0000000..70fae71 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/inventory/AnvilInventory.java @@ -0,0 +1,7 @@ +package org.bukkit.inventory; + +/** + * Interface to the inventory of an Anvil. + */ +public interface AnvilInventory extends Inventory { +} diff --git a/azurite-api/src/main/java/org/bukkit/inventory/BeaconInventory.java b/azurite-api/src/main/java/org/bukkit/inventory/BeaconInventory.java new file mode 100644 index 0000000..2f8769e --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/inventory/BeaconInventory.java @@ -0,0 +1,21 @@ +package org.bukkit.inventory; + +/** + * Interface to the inventory of a Beacon. + */ +public interface BeaconInventory extends Inventory { + + /** + * Set the item powering the beacon. + * + * @param item The new item + */ + void setItem(ItemStack item); + + /** + * Get the item powering the beacon. + * + * @return The current item. + */ + ItemStack getItem(); +} diff --git a/azurite-api/src/main/java/org/bukkit/inventory/BrewerInventory.java b/azurite-api/src/main/java/org/bukkit/inventory/BrewerInventory.java new file mode 100644 index 0000000..9cc31c9 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/inventory/BrewerInventory.java @@ -0,0 +1,25 @@ +package org.bukkit.inventory; + +import org.bukkit.block.BrewingStand; + +/** + * Interface to the inventory of a Brewing Stand. + */ +public interface BrewerInventory extends Inventory { + + /** + * Get the current ingredient for brewing. + * + * @return The ingredient. + */ + ItemStack getIngredient(); + + /** + * Set the current ingredient for brewing. + * + * @param ingredient The ingredient + */ + void setIngredient(ItemStack ingredient); + + BrewingStand getHolder(); +} diff --git a/azurite-api/src/main/java/org/bukkit/inventory/CraftingInventory.java b/azurite-api/src/main/java/org/bukkit/inventory/CraftingInventory.java new file mode 100644 index 0000000..f71533c --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/inventory/CraftingInventory.java @@ -0,0 +1,45 @@ +package org.bukkit.inventory; + +/** + * Interface to the crafting inventories + */ +public interface CraftingInventory extends Inventory { + + /** + * Check what item is in the result slot of this crafting inventory. + * + * @return The result item. + */ + ItemStack getResult(); + + /** + * Get the contents of the crafting matrix. + * + * @return The contents. + */ + ItemStack[] getMatrix(); + + /** + * Set the item in the result slot of the crafting inventory. + * + * @param newResult The new result item. + */ + void setResult(ItemStack newResult); + + /** + * Replace the contents of the crafting matrix + * + * @param contents The new contents. + * @throws IllegalArgumentException if the length of contents is greater + * than the size of the crafting matrix. + */ + void setMatrix(ItemStack[] contents); + + /** + * Get the current recipe formed on the crafting inventory, if any. + * + * @return The recipe, or null if the current contents don't match any + * recipe. + */ + Recipe getRecipe(); +} \ No newline at end of file diff --git a/azurite-api/src/main/java/org/bukkit/inventory/DoubleChestInventory.java b/azurite-api/src/main/java/org/bukkit/inventory/DoubleChestInventory.java new file mode 100644 index 0000000..c03ad53 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/inventory/DoubleChestInventory.java @@ -0,0 +1,25 @@ +package org.bukkit.inventory; + +import org.bukkit.block.DoubleChest; + +/** + * Interface to the inventory of a Double Chest. + */ +public interface DoubleChestInventory extends Inventory { + + /** + * Get the left half of this double chest. + * + * @return The left side inventory + */ + Inventory getLeftSide(); + + /** + * Get the right side of this double chest. + * + * @return The right side inventory + */ + Inventory getRightSide(); + + DoubleChest getHolder(); +} diff --git a/azurite-api/src/main/java/org/bukkit/inventory/EnchantingInventory.java b/azurite-api/src/main/java/org/bukkit/inventory/EnchantingInventory.java new file mode 100644 index 0000000..6551a16 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/inventory/EnchantingInventory.java @@ -0,0 +1,35 @@ +package org.bukkit.inventory; + +/** + * Interface to the inventory of an Enchantment Table. + */ +public interface EnchantingInventory extends Inventory { + + /** + * Set the item being enchanted. + * + * @param item The new item + */ + void setItem(ItemStack item); + + /** + * Get the item being enchanted. + * + * @return The current item. + */ + ItemStack getItem(); + + /** + * Set the secondary item being used for the enchant. + * + * @param item The new item + */ + void setSecondary(ItemStack item); + + /** + * Get the secondary item being used for the enchant. + * + * @return The second item + */ + ItemStack getSecondary(); +} diff --git a/azurite-api/src/main/java/org/bukkit/inventory/EntityEquipment.java b/azurite-api/src/main/java/org/bukkit/inventory/EntityEquipment.java new file mode 100644 index 0000000..24dfd20 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/inventory/EntityEquipment.java @@ -0,0 +1,236 @@ +package org.bukkit.inventory; + +import org.bukkit.entity.Entity; + +/** + * An interface to a creatures inventory + */ +public interface EntityEquipment { + + /** + * Gets a copy of the item the entity is currently holding + * + * @return the currently held item + */ + ItemStack getItemInHand(); + + /** + * Sets the item the entity is holding + * + * @param stack The item to put into the entities hand + */ + void setItemInHand(ItemStack stack); + + /** + * Gets a copy of the helmet currently being worn by the entity + * + * @return The helmet being worn + */ + ItemStack getHelmet(); + + /** + * Sets the helmet worn by the entity + * + * @param helmet The helmet to put on the entity + */ + void setHelmet(ItemStack helmet); + + /** + * Gets a copy of the chest plate currently being worn by the entity + * + * @return The chest plate being worn + */ + ItemStack getChestplate(); + + /** + * Sets the chest plate worn by the entity + * + * @param chestplate The chest plate to put on the entity + */ + void setChestplate(ItemStack chestplate); + + /** + * Gets a copy of the leggings currently being worn by the entity + * + * @return The leggings being worn + */ + ItemStack getLeggings(); + + /** + * Sets the leggings worn by the entity + * + * @param leggings The leggings to put on the entity + */ + void setLeggings(ItemStack leggings); + + /** + * Gets a copy of the boots currently being worn by the entity + * + * @return The boots being worn + */ + ItemStack getBoots(); + + /** + * Sets the boots worn by the entity + * + * @param boots The boots to put on the entity + */ + void setBoots(ItemStack boots); + + /** + * Gets a copy of all worn armor + * + * @return The array of worn armor + */ + ItemStack[] getArmorContents(); + + /** + * Sets the entities armor to the provided array of ItemStacks + * + * @param items The items to set the armor as + */ + void setArmorContents(ItemStack[] items); + + /** + * Clears the entity of all armor and held items + */ + void clear(); + + /** + * Gets the chance of the currently held item being dropped upon this + * creature's death. + * + *

    + *
  • A drop chance of 0F will never drop + *
  • A drop chance of 1F will always drop + *
+ * + * @return chance of the currently held item being dropped (1 for players) + */ + float getItemInHandDropChance(); + + /** + * Sets the chance of the item this creature is currently holding being + * dropped upon this creature's death. + * + *
    + *
  • A drop chance of 0F will never drop + *
  • A drop chance of 1F will always drop + *
+ * + * @param chance the chance of the currently held item being dropped + * @throws UnsupportedOperationException when called on players + */ + void setItemInHandDropChance(float chance); + + /** + * Gets the chance of the helmet being dropped upon this creature's death. + * + *
    + *
  • A drop chance of 0F will never drop + *
  • A drop chance of 1F will always drop + *
+ * + * @return the chance of the helmet being dropped (1 for players) + */ + float getHelmetDropChance(); + + /** + * Sets the chance of the helmet being dropped upon this creature's death. + * + *
    + *
  • A drop chance of 0F will never drop + *
  • A drop chance of 1F will always drop + *
+ * + * @param chance of the helmet being dropped + * @throws UnsupportedOperationException when called on players + */ + void setHelmetDropChance(float chance); + + /** + * Gets the chance of the chest plate being dropped upon this creature's + * death. + * + *
    + *
  • A drop chance of 0F will never drop + *
  • A drop chance of 1F will always drop + *
+ * + * @return the chance of the chest plate being dropped (1 for players) + */ + float getChestplateDropChance(); + + /** + * Sets the chance of the chest plate being dropped upon this creature's + * death. + * + *
    + *
  • A drop chance of 0F will never drop + *
  • A drop chance of 1F will always drop + *
+ * + * @param chance of the chest plate being dropped + * @throws UnsupportedOperationException when called on players + */ + void setChestplateDropChance(float chance); + + /** + * Gets the chance of the leggings being dropped upon this creature's + * death. + * + *
    + *
  • A drop chance of 0F will never drop + *
  • A drop chance of 1F will always drop + *
+ * + * @return the chance of the leggings being dropped (1 for players) + */ + float getLeggingsDropChance(); + + /** + * Sets the chance of the leggings being dropped upon this creature's + * death. + * + *
    + *
  • A drop chance of 0F will never drop + *
  • A drop chance of 1F will always drop + *
+ * + * @param chance chance of the leggings being dropped + * @throws UnsupportedOperationException when called on players + */ + void setLeggingsDropChance(float chance); + + /** + * Gets the chance of the boots being dropped upon this creature's death. + * + *
    + *
  • A drop chance of 0F will never drop + *
  • A drop chance of 1F will always drop + *
+ * + * @return the chance of the boots being dropped (1 for players) + */ + float getBootsDropChance(); + + /** + * Sets the chance of the boots being dropped upon this creature's death. + * + *
    + *
  • A drop chance of 0F will never drop + *
  • A drop chance of 1F will always drop + *
+ * + * @param chance of the boots being dropped + * @throws UnsupportedOperationException when called on players + */ + void setBootsDropChance(float chance); + + /** + * Get the entity this EntityEquipment belongs to + * + * @return the entity this EntityEquipment belongs to + */ + Entity getHolder(); +} diff --git a/azurite-api/src/main/java/org/bukkit/inventory/EquipmentSlot.java b/azurite-api/src/main/java/org/bukkit/inventory/EquipmentSlot.java new file mode 100644 index 0000000..0b2eb98 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/inventory/EquipmentSlot.java @@ -0,0 +1,10 @@ +package org.bukkit.inventory; + +public enum EquipmentSlot { + + HAND, + FEET, + LEGS, + CHEST, + HEAD +} diff --git a/azurite-api/src/main/java/org/bukkit/inventory/FurnaceInventory.java b/azurite-api/src/main/java/org/bukkit/inventory/FurnaceInventory.java new file mode 100644 index 0000000..93b41d3 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/inventory/FurnaceInventory.java @@ -0,0 +1,53 @@ +package org.bukkit.inventory; + +import org.bukkit.block.Furnace; + +/** + * Interface to the inventory of a Furnace. + */ +public interface FurnaceInventory extends Inventory { + + /** + * Get the current item in the result slot. + * + * @return The item + */ + ItemStack getResult(); + + /** + * Get the current fuel. + * + * @return The item + */ + ItemStack getFuel(); + + /** + * Get the item currently smelting. + * + * @return The item + */ + ItemStack getSmelting(); + + /** + * Set the current fuel. + * + * @param stack The item + */ + void setFuel(ItemStack stack); + + /** + * Set the current item in the result slot. + * + * @param stack The item + */ + void setResult(ItemStack stack); + + /** + * Set the item currently smelting. + * + * @param stack The item + */ + void setSmelting(ItemStack stack); + + Furnace getHolder(); +} diff --git a/azurite-api/src/main/java/org/bukkit/inventory/FurnaceRecipe.java b/azurite-api/src/main/java/org/bukkit/inventory/FurnaceRecipe.java new file mode 100644 index 0000000..8075323 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/inventory/FurnaceRecipe.java @@ -0,0 +1,100 @@ +package org.bukkit.inventory; + +import org.bukkit.Material; +import org.bukkit.material.MaterialData; + +/** + * Represents a smelting recipe. + */ +public class FurnaceRecipe implements Recipe { + private ItemStack output; + private ItemStack ingredient; + + /** + * Create a furnace recipe to craft the specified ItemStack. + * + * @param result The item you want the recipe to create. + * @param source The input material. + */ + public FurnaceRecipe(ItemStack result, Material source) { + this(result, source, 0); + } + + /** + * Create a furnace recipe to craft the specified ItemStack. + * + * @param result The item you want the recipe to create. + * @param source The input material. + */ + public FurnaceRecipe(ItemStack result, MaterialData source) { + this(result, source.getItemType(), source.getData()); + } + + /** + * Create a furnace recipe to craft the specified ItemStack. + * + * @param result The item you want the recipe to create. + * @param source The input material. + * @param data The data value. (Note: This is currently ignored by the + * CraftBukkit server.) + * @deprecated Magic value + */ + @Deprecated + public FurnaceRecipe(ItemStack result, Material source, int data) { + this.output = new ItemStack(result); + this.ingredient = new ItemStack(source, 1, (short) data); + } + + /** + * Sets the input of this furnace recipe. + * + * @param input The input material. + * @return The changed recipe, so you can chain calls. + */ + public FurnaceRecipe setInput(MaterialData input) { + return setInput(input.getItemType(), input.getData()); + } + + /** + * Sets the input of this furnace recipe. + * + * @param input The input material. + * @return The changed recipe, so you can chain calls. + */ + public FurnaceRecipe setInput(Material input) { + return setInput(input, 0); + } + + /** + * Sets the input of this furnace recipe. + * + * @param input The input material. + * @param data The data value. (Note: This is currently ignored by the + * CraftBukkit server.) + * @return The changed recipe, so you can chain calls. + * @deprecated Magic value + */ + @Deprecated + public FurnaceRecipe setInput(Material input, int data) { + this.ingredient = new ItemStack(input, 1, (short) data); + return this; + } + + /** + * Get the input material. + * + * @return The input material. + */ + public ItemStack getInput() { + return this.ingredient.clone(); + } + + /** + * Get the result of this recipe. + * + * @return The resulting stack. + */ + public ItemStack getResult() { + return output.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/inventory/HorseInventory.java b/azurite-api/src/main/java/org/bukkit/inventory/HorseInventory.java new file mode 100644 index 0000000..a71efb8 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/inventory/HorseInventory.java @@ -0,0 +1,35 @@ +package org.bukkit.inventory; + +/** + * An interface to the inventory of a Horse. + */ +public interface HorseInventory extends Inventory { + + /** + * Gets the item in the horse's saddle slot. + * + * @return the saddle item + */ + ItemStack getSaddle(); + + /** + * Gets the item in the horse's armor slot. + * + * @return the armor item + */ + ItemStack getArmor(); + + /** + * Sets the item in the horse's saddle slot. + * + * @param stack the new item + */ + void setSaddle(ItemStack stack); + + /** + * Sets the item in the horse's armor slot. + * + * @param stack the new item + */ + void setArmor(ItemStack stack); +} diff --git a/azurite-api/src/main/java/org/bukkit/inventory/Inventory.java b/azurite-api/src/main/java/org/bukkit/inventory/Inventory.java new file mode 100644 index 0000000..77eefd6 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/inventory/Inventory.java @@ -0,0 +1,381 @@ +package org.bukkit.inventory; + +import org.bukkit.Material; +import org.bukkit.entity.HumanEntity; +import org.bukkit.event.inventory.InventoryType; + +import java.util.HashMap; +import java.util.List; +import java.util.ListIterator; + +/** + * Interface to the various inventories. Behavior relating to {@link + * Material#AIR} is unspecified. + */ +public interface Inventory extends Iterable { + + /** + * Returns the size of the inventory + * + * @return The size of the inventory + */ + int getSize(); + + /** + * Returns the maximum stack size for an ItemStack in this inventory. + * + * @return The maximum size for an ItemStack in this inventory. + */ + int getMaxStackSize(); + + /** + * This method allows you to change the maximum stack size for an + * inventory. + *

+ * Caveats: + *

    + *
  • Not all inventories respect this value. + *
  • Stacks larger than 127 may be clipped when the world is saved. + *
  • This value is not guaranteed to be preserved; be sure to set it + * before every time you want to set a slot over the max stack size. + *
  • Stacks larger than the default max size for this type of inventory + * may not display correctly in the client. + *
+ * + * @param size The new maximum stack size for items in this inventory. + */ + void setMaxStackSize(int size); + + /** + * Returns the name of the inventory + * + * @return The String with the name of the inventory + */ + String getName(); + + /** + * Returns the ItemStack found in the slot at the given index + * + * @param index The index of the Slot's ItemStack to return + * @return The ItemStack in the slot + */ + ItemStack getItem(int index); + + /** + * Stores the ItemStack at the given index of the inventory. + * + * @param index The index where to put the ItemStack + * @param item The ItemStack to set + */ + void setItem(int index, ItemStack item); + + /** + * Stores the given ItemStacks in the inventory. This will try to fill + * existing stacks and empty slots as well as it can. + *

+ * The returned HashMap contains what it couldn't store, where the key is + * the index of the parameter, and the value is the ItemStack at that + * index of the varargs parameter. If all items are stored, it will return + * an empty HashMap. + *

+ * If you pass in ItemStacks which exceed the maximum stack size for the + * Material, first they will be added to partial stacks where + * Material.getMaxStackSize() is not exceeded, up to + * Material.getMaxStackSize(). When there are no partial stacks left + * stacks will be split on Inventory.getMaxStackSize() allowing you to + * exceed the maximum stack size for that material. + * + * @param items The ItemStacks to add + * @return A HashMap containing items that didn't fit. + * @throws IllegalArgumentException if items or any element in it is null + */ + HashMap addItem(ItemStack... items) throws IllegalArgumentException; + + /** + * Removes the given ItemStacks from the inventory. + *

+ * It will try to remove 'as much as possible' from the types and amounts + * you give as arguments. + *

+ * The returned HashMap contains what it couldn't remove, where the key is + * the index of the parameter, and the value is the ItemStack at that + * index of the varargs parameter. If all the given ItemStacks are + * removed, it will return an empty HashMap. + * + * @param items The ItemStacks to remove + * @return A HashMap containing items that couldn't be removed. + * @throws IllegalArgumentException if items is null + */ + HashMap removeItem(ItemStack... items) throws IllegalArgumentException; + + /** + * Returns all ItemStacks from the inventory + * + * @return An array of ItemStacks from the inventory. + */ + ItemStack[] getContents(); + + /** + * Completely replaces the inventory's contents. Removes all existing + * contents and replaces it with the ItemStacks given in the array. + * + * @param items A complete replacement for the contents; the length must + * be less than or equal to {@link #getSize()}. + * @throws IllegalArgumentException If the array has more items than the + * inventory. + */ + void setContents(ItemStack[] items) throws IllegalArgumentException; + + /** + * Checks if the inventory contains any ItemStacks with the given + * materialId + * + * @param materialId The materialId to check for + * @return true if an ItemStack in this inventory contains the materialId + * @deprecated Magic value + */ + @Deprecated + boolean contains(int materialId); + + /** + * Checks if the inventory contains any ItemStacks with the given + * material. + * + * @param material The material to check for + * @return true if an ItemStack is found with the given Material + * @throws IllegalArgumentException if material is null + */ + boolean contains(Material material) throws IllegalArgumentException; + + /** + * Checks if the inventory contains any ItemStacks matching the given + * ItemStack. + *

+ * This will only return true if both the type and the amount of the stack + * match. + * + * @param item The ItemStack to match against + * @return false if item is null, true if any exactly matching ItemStacks + * were found + */ + boolean contains(ItemStack item); + + /** + * Checks if the inventory contains any ItemStacks with the given + * materialId, adding to at least the minimum amount specified. + * + * @param materialId The materialId to check for + * @param amount The minimum amount to look for + * @return true if this contains any matching ItemStack with the given + * materialId and amount + * @deprecated Magic value + */ + @Deprecated + boolean contains(int materialId, int amount); + + /** + * Checks if the inventory contains any ItemStacks with the given + * material, adding to at least the minimum amount specified. + * + * @param material The material to check for + * @param amount The minimum amount + * @return true if amount is less than 1, true if enough ItemStacks were + * found to add to the given amount + * @throws IllegalArgumentException if material is null + */ + boolean contains(Material material, int amount) throws IllegalArgumentException; + + /** + * Checks if the inventory contains at least the minimum amount specified + * of exactly matching ItemStacks. + *

+ * An ItemStack only counts if both the type and the amount of the stack + * match. + * + * @param item the ItemStack to match against + * @param amount how many identical stacks to check for + * @return false if item is null, true if amount less than 1, true if + * amount of exactly matching ItemStacks were found + * @see #containsAtLeast(ItemStack, int) + */ + boolean contains(ItemStack item, int amount); + + /** + * Checks if the inventory contains ItemStacks matching the given + * ItemStack whose amounts sum to at least the minimum amount specified. + * + * @param item the ItemStack to match against + * @param amount the minimum amount + * @return false if item is null, true if amount less than 1, true if + * enough ItemStacks were found to add to the given amount + */ + boolean containsAtLeast(ItemStack item, int amount); + + /** + * Returns a HashMap with all slots and ItemStacks in the inventory with + * given materialId. + *

+ * The HashMap contains entries where, the key is the slot index, and the + * value is the ItemStack in that slot. If no matching ItemStack with the + * given materialId is found, an empty map is returned. + * + * @param materialId The materialId to look for + * @return A HashMap containing the slot index, ItemStack pairs + * @deprecated Magic value + */ + @Deprecated + HashMap all(int materialId); + + /** + * Returns a HashMap with all slots and ItemStacks in the inventory with + * the given Material. + *

+ * The HashMap contains entries where, the key is the slot index, and the + * value is the ItemStack in that slot. If no matching ItemStack with the + * given Material is found, an empty map is returned. + * + * @param material The material to look for + * @return A HashMap containing the slot index, ItemStack pairs + * @throws IllegalArgumentException if material is null + */ + HashMap all(Material material) throws IllegalArgumentException; + + /** + * Finds all slots in the inventory containing any ItemStacks with the + * given ItemStack. This will only match slots if both the type and the + * amount of the stack match + *

+ * The HashMap contains entries where, the key is the slot index, and the + * value is the ItemStack in that slot. If no matching ItemStack with the + * given Material is found, an empty map is returned. + * + * @param item The ItemStack to match against + * @return A map from slot indexes to item at index + */ + HashMap all(ItemStack item); + + /** + * Finds the first slot in the inventory containing an ItemStack with the + * given materialId. + * + * @param materialId The materialId to look for + * @return The slot index of the given materialId or -1 if not found + * @deprecated Magic value + */ + @Deprecated + int first(int materialId); + + /** + * Finds the first slot in the inventory containing an ItemStack with the + * given material + * + * @param material The material to look for + * @return The slot index of the given Material or -1 if not found + * @throws IllegalArgumentException if material is null + */ + int first(Material material) throws IllegalArgumentException; + + /** + * Returns the first slot in the inventory containing an ItemStack with + * the given stack. This will only match a slot if both the type and the + * amount of the stack match + * + * @param item The ItemStack to match against + * @return The slot index of the given ItemStack or -1 if not found + */ + int first(ItemStack item); + + /** + * Returns the first empty Slot. + * + * @return The first empty Slot found, or -1 if no empty slots. + */ + int firstEmpty(); + + /** + * Removes all stacks in the inventory matching the given materialId. + * + * @param materialId The material to remove + * @deprecated Magic value + */ + @Deprecated + void remove(int materialId); + + /** + * Removes all stacks in the inventory matching the given material. + * + * @param material The material to remove + * @throws IllegalArgumentException if material is null + */ + void remove(Material material) throws IllegalArgumentException; + + /** + * Removes all stacks in the inventory matching the given stack. + *

+ * This will only match a slot if both the type and the amount of the + * stack match + * + * @param item The ItemStack to match against + */ + void remove(ItemStack item); + + /** + * Clears out a particular slot in the index. + * + * @param index The index to empty. + */ + void clear(int index); + + /** + * Clears out the whole Inventory. + */ + void clear(); + + /** + * Gets a list of players viewing the inventory. Note that a player is + * considered to be viewing their own inventory and internal crafting + * screen even when said inventory is not open. They will normally be + * considered to be viewing their inventory even when they have a + * different inventory screen open, but it's possible for customized + * inventory screens to exclude the viewer's inventory, so this should + * never be assumed to be non-empty. + * + * @return A list of HumanEntities who are viewing this Inventory. + */ + List getViewers(); + + /** + * Returns the title of this inventory. + * + * @return A String with the title. + */ + String getTitle(); + + /** + * Returns what type of inventory this is. + * + * @return The InventoryType representing the type of inventory. + */ + InventoryType getType(); + + /** + * Gets the block or entity belonging to the open inventory + * + * @return The holder of the inventory; null if it has no holder. + */ + InventoryHolder getHolder(); + + @Override + ListIterator iterator(); + + /** + * Returns an iterator starting at the given index. If the index is + * positive, then the first call to next() will return the item at that + * index; if it is negative, the first call to previous will return the + * item at index (getSize() + index). + * + * @param index The index. + * @return An iterator. + */ + ListIterator iterator(int index); +} diff --git a/azurite-api/src/main/java/org/bukkit/inventory/InventoryHolder.java b/azurite-api/src/main/java/org/bukkit/inventory/InventoryHolder.java new file mode 100644 index 0000000..5a32b59 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/inventory/InventoryHolder.java @@ -0,0 +1,11 @@ +package org.bukkit.inventory; + +public interface InventoryHolder { + + /** + * Get the object's inventory. + * + * @return The inventory. + */ + Inventory getInventory(); +} diff --git a/azurite-api/src/main/java/org/bukkit/inventory/InventoryView.java b/azurite-api/src/main/java/org/bukkit/inventory/InventoryView.java new file mode 100644 index 0000000..19ed440 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/inventory/InventoryView.java @@ -0,0 +1,232 @@ +package org.bukkit.inventory; + +import org.bukkit.GameMode; +import org.bukkit.entity.HumanEntity; +import org.bukkit.event.inventory.InventoryType; + +/** + * Represents a view linking two inventories and a single player (whose + * inventory may or may not be one of the two). + *

+ * Note: If you implement this interface but fail to satisfy the expected + * contracts of certain methods, there's no guarantee that the game will work + * as it should. + */ +public abstract class InventoryView { + public final static int OUTSIDE = -999; + /** + * Represents various extra properties of certain inventory windows. + */ + public enum Property { + /** + * The progress of the down-pointing arrow in a brewing inventory. + */ + BREW_TIME(0, InventoryType.BREWING), + /** + * The progress of the right-pointing arrow in a furnace inventory. + */ + COOK_TIME(0, InventoryType.FURNACE), + /** + * The progress of the flame in a furnace inventory. + */ + BURN_TIME(1, InventoryType.FURNACE), + /** + * How many total ticks the current fuel should last. + */ + TICKS_FOR_CURRENT_FUEL(2, InventoryType.FURNACE), + /** + * In an enchanting inventory, the top button's experience level + * value. + */ + ENCHANT_BUTTON1(0, InventoryType.ENCHANTING), + /** + * In an enchanting inventory, the middle button's experience level + * value. + */ + ENCHANT_BUTTON2(1, InventoryType.ENCHANTING), + /** + * In an enchanting inventory, the bottom button's experience level + * value. + */ + ENCHANT_BUTTON3(2, InventoryType.ENCHANTING); + int id; + InventoryType style; + Property(int id, InventoryType appliesTo) { + this.id = id; + style = appliesTo; + } + + public InventoryType getType() { + return style; + } + + /** + * + * @return the id of this view + * @deprecated Magic value + */ + @Deprecated + public int getId() { + return id; + } + } + /** + * Get the upper inventory involved in this transaction. + * + * @return the inventory + */ + public abstract Inventory getTopInventory(); + + /** + * Get the lower inventory involved in this transaction. + * + * @return the inventory + */ + public abstract Inventory getBottomInventory(); + + /** + * Get the player viewing. + * + * @return the player + */ + public abstract HumanEntity getPlayer(); + + /** + * Determine the type of inventory involved in the transaction. This + * indicates the window style being shown. It will never return PLAYER, + * since that is common to all windows. + * + * @return the inventory type + */ + public abstract InventoryType getType(); + + /** + * Sets one item in this inventory view by its raw slot ID. + *

+ * Note: If slot ID -999 is chosen, it may be expected that the item is + * dropped on the ground. This is not required behaviour, however. + * + * @param slot The ID as returned by InventoryClickEvent.getRawSlot() + * @param item The new item to put in the slot, or null to clear it. + */ + public void setItem(int slot, ItemStack item) { + if (slot != OUTSIDE) { + if (slot < getTopInventory().getSize()) { + getTopInventory().setItem(convertSlot(slot),item); + } else { + getBottomInventory().setItem(convertSlot(slot),item); + } + } else { + getPlayer().getWorld().dropItemNaturally(getPlayer().getLocation(), item); + } + } + + /** + * Gets one item in this inventory view by its raw slot ID. + * + * @param slot The ID as returned by InventoryClickEvent.getRawSlot() + * @return The item currently in the slot. + */ + public ItemStack getItem(int slot) { + if (slot == OUTSIDE) { + return null; + } + if (slot < getTopInventory().getSize()) { + return getTopInventory().getItem(convertSlot(slot)); + } else { + return getBottomInventory().getItem(convertSlot(slot)); + } + } + + /** + * Sets the item on the cursor of one of the viewing players. + * + * @param item The item to put on the cursor, or null to remove the item + * on their cursor. + */ + public final void setCursor(ItemStack item) { + getPlayer().setItemOnCursor(item); + } + + /** + * Get the item on the cursor of one of the viewing players. + * + * @return The item on the player's cursor, or null if they aren't holding + * one. + */ + public final ItemStack getCursor() { + return getPlayer().getItemOnCursor(); + } + + /** + * Converts a raw slot ID into its local slot ID into whichever of the two + * inventories the slot points to. + *

+ * If the raw slot refers to the upper inventory, it will be returned + * unchanged and thus be suitable for getTopInventory().getItem(); if it + * refers to the lower inventory, the output will differ from the input + * and be suitable for getBottomInventory().getItem(). + * + * @param rawSlot The raw slot ID. + * @return The converted slot ID. + */ + public final int convertSlot(int rawSlot) { + int numInTop = getTopInventory().getSize(); + if (rawSlot < numInTop) { + return rawSlot; + } + int slot = rawSlot - numInTop; + if (getPlayer().getGameMode() == GameMode.CREATIVE && getType() == InventoryType.PLAYER) { + return slot; + } + if (getType() == InventoryType.CRAFTING) { + if(slot < 4) return 39 - slot; + else slot -= 4; + } + if (slot >= 27) slot -= 27; + else slot += 9; + return slot; + } + + /** + * Closes the inventory view. + */ + public final void close() { + getPlayer().closeInventory(); + } + + /** + * Check the total number of slots in this view, combining the upper and + * lower inventories. + *

+ * Note though that it's possible for this to be greater than the sum of + * the two inventories if for example some slots are not being used. + * + * @return The total size + */ + public final int countSlots() { + return getTopInventory().getSize() + getBottomInventory().getSize(); + } + + /** + * Sets an extra property of this inventory if supported by that + * inventory, for example the state of a progress bar. + * + * @param prop the window property to update + * @param value the new value for the window property + * @return true if the property was updated successfully, false if the + * property is not supported by that inventory + */ + public final boolean setProperty(Property prop, int value) { + return getPlayer().setWindowProperty(prop, value); + } + + /** + * Get the title of this inventory window. + * + * @return The title. + */ + public final String getTitle() { + return getTopInventory().getTitle(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/inventory/ItemFactory.java b/azurite-api/src/main/java/org/bukkit/inventory/ItemFactory.java new file mode 100644 index 0000000..52a8d4d --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/inventory/ItemFactory.java @@ -0,0 +1,124 @@ +package org.bukkit.inventory; + +import org.bukkit.Color; +import org.bukkit.Material; +import org.bukkit.Server; +import org.bukkit.inventory.meta.BookMeta; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.inventory.meta.SkullMeta; + +/** + * An instance of the ItemFactory can be obtained with {@link + * Server#getItemFactory()}. + *

+ * The ItemFactory is solely responsible for creating item meta containers to + * apply on item stacks. + */ +public interface ItemFactory { + + /** + * This creates a new item meta for the material. + * + * @param material The material to consider as base for the meta + * @return a new ItemMeta that could be applied to an item stack of the + * specified material + */ + ItemMeta getItemMeta(final Material material); + + /** + * This method checks the item meta to confirm that it is applicable (no + * data lost if applied) to the specified ItemStack. + *

+ * A {@link SkullMeta} would not be valid for a sword, but a normal {@link + * ItemMeta} from an enchanted dirt block would. + * + * @param meta Meta to check + * @param stack Item that meta will be applied to + * @return true if the meta can be applied without losing data, false + * otherwise + * @throws IllegalArgumentException if the meta was not created by this + * factory + */ + boolean isApplicable(final ItemMeta meta, final ItemStack stack) throws IllegalArgumentException; + + /** + * This method checks the item meta to confirm that it is applicable (no + * data lost if applied) to the specified Material. + *

+ * A {@link SkullMeta} would not be valid for a sword, but a normal {@link + * ItemMeta} from an enchanted dirt block would. + * + * @param meta Meta to check + * @param material Material that meta will be applied to + * @return true if the meta can be applied without losing data, false + * otherwise + * @throws IllegalArgumentException if the meta was not created by this + * factory + */ + boolean isApplicable(final ItemMeta meta, final Material material) throws IllegalArgumentException; + + /** + * This method is used to compare two item meta data objects. + * + * @param meta1 First meta to compare, and may be null to indicate no data + * @param meta2 Second meta to compare, and may be null to indicate no + * data + * @return false if one of the meta has data the other does not, otherwise + * true + * @throws IllegalArgumentException if either meta was not created by this + * factory + */ + boolean equals(final ItemMeta meta1, final ItemMeta meta2) throws IllegalArgumentException; + + /** + * Returns an appropriate item meta for the specified stack. + *

+ * The item meta returned will always be a valid meta for a given + * ItemStack of the specified material. It may be a more or less specific + * meta, and could also be the same meta or meta type as the parameter. + * The item meta returned will also always be the most appropriate meta. + *

+ * Example, if a {@link SkullMeta} is being applied to a book, this method + * would return a {@link BookMeta} containing all information in the + * specified meta that is applicable to an {@link ItemMeta}, the highest + * common interface. + * + * @param meta the meta to convert + * @param stack the stack to convert the meta for + * @return An appropriate item meta for the specified item stack. No + * guarantees are made as to if a copy is returned. This will be null + * for a stack of air. + * @throws IllegalArgumentException if the specified meta was not created + * by this factory + */ + ItemMeta asMetaFor(final ItemMeta meta, final ItemStack stack) throws IllegalArgumentException; + + /** + * Returns an appropriate item meta for the specified material. + *

+ * The item meta returned will always be a valid meta for a given + * ItemStack of the specified material. It may be a more or less specific + * meta, and could also be the same meta or meta type as the parameter. + * The item meta returned will also always be the most appropriate meta. + *

+ * Example, if a {@link SkullMeta} is being applied to a book, this method + * would return a {@link BookMeta} containing all information in the + * specified meta that is applicable to an {@link ItemMeta}, the highest + * common interface. + * + * @param meta the meta to convert + * @param material the material to convert the meta for + * @return An appropriate item meta for the specified item material. No + * guarantees are made as to if a copy is returned. This will be null for air. + * @throws IllegalArgumentException if the specified meta was not created + * by this factory + */ + ItemMeta asMetaFor(final ItemMeta meta, final Material material) throws IllegalArgumentException; + + /** + * Returns the default color for all leather armor. + * + * @return the default color for leather armor + */ + Color getDefaultLeatherColor(); +} diff --git a/azurite-api/src/main/java/org/bukkit/inventory/ItemFlag.java b/azurite-api/src/main/java/org/bukkit/inventory/ItemFlag.java new file mode 100644 index 0000000..b5540ae --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/inventory/ItemFlag.java @@ -0,0 +1,32 @@ +package org.bukkit.inventory; + +/** + * A ItemFlag can hide some Attributes from ItemStacks + */ +public enum ItemFlag { + + /** + * Setting to show/hide enchants + */ + HIDE_ENCHANTS, + /** + * Setting to show/hide Attributes like Damage + */ + HIDE_ATTRIBUTES, + /** + * Setting to show/hide the unbreakable State + */ + HIDE_UNBREAKABLE, + /** + * Setting to show/hide what the ItemStack can break/destroy + */ + HIDE_DESTROYS, + /** + * Setting to show/hide where this ItemStack can be build/placed on + */ + HIDE_PLACED_ON, + /** + * Setting to show/hide potion effects on this ItemStack + */ + HIDE_POTION_EFFECTS +} diff --git a/azurite-api/src/main/java/org/bukkit/inventory/ItemStack.java b/azurite-api/src/main/java/org/bukkit/inventory/ItemStack.java new file mode 100644 index 0000000..3334905 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/inventory/ItemStack.java @@ -0,0 +1,611 @@ +package org.bukkit.inventory; + +import com.google.common.collect.ImmutableMap; +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.Utility; +import org.bukkit.configuration.serialization.ConfigurationSerializable; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.material.MaterialData; + +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * Represents a stack of items + */ +public class ItemStack implements Cloneable, ConfigurationSerializable { + private int type = 0; + private int amount = 0; + private MaterialData data = null; + private short durability = 0; + private ItemMeta meta; + + @Utility + protected ItemStack() {} + + /** + * Defaults stack size to 1, with no extra data + * + * @param type item material id + * @deprecated Magic value + */ + @Deprecated + public ItemStack(final int type) { + this(type, 1); + } + + /** + * Defaults stack size to 1, with no extra data + * + * @param type item material + */ + public ItemStack(final Material type) { + this(type, 1); + } + + /** + * An item stack with no extra data + * + * @param type item material id + * @param amount stack size + * @deprecated Magic value + */ + @Deprecated + public ItemStack(final int type, final int amount) { + this(type, amount, (short) 0); + } + + /** + * An item stack with no extra data + * + * @param type item material + * @param amount stack size + */ + public ItemStack(final Material type, final int amount) { + this(type.getId(), amount); + } + + /** + * An item stack with the specified damage / durability + * + * @param type item material id + * @param amount stack size + * @param damage durability / damage + * @deprecated Magic value + */ + @Deprecated + public ItemStack(final int type, final int amount, final short damage) { + this.type = type; + this.amount = amount; + this.durability = damage; + } + + /** + * An item stack with the specified damage / durabiltiy + * + * @param type item material + * @param amount stack size + * @param damage durability / damage + */ + public ItemStack(final Material type, final int amount, final short damage) { + this(type.getId(), amount, damage); + } + + /** + * @param type the raw type id + * @param amount the amount in the stack + * @param damage the damage value of the item + * @param data the data value or null + * @deprecated this method uses an ambiguous data byte object + */ + @Deprecated + public ItemStack(final int type, final int amount, final short damage, final Byte data) { + this.type = type; + this.amount = amount; + this.durability = damage; + if (data != null) { + createData(data); + this.durability = data; + } + } + + /** + * @param type the type + * @param amount the amount in the stack + * @param damage the damage value of the item + * @param data the data value or null + * @deprecated this method uses an ambiguous data byte object + */ + @Deprecated + public ItemStack(final Material type, final int amount, final short damage, final Byte data) { + this(type.getId(), amount, damage, data); + } + + /** + * Creates a new item stack derived from the specified stack + * + * @param stack the stack to copy + * @throws IllegalArgumentException if the specified stack is null or + * returns an item meta not created by the item factory + */ + public ItemStack(final ItemStack stack) throws IllegalArgumentException { + Validate.notNull(stack, "Cannot copy null stack"); + this.type = stack.getTypeId(); + this.amount = stack.getAmount(); + this.durability = stack.getDurability(); + this.data = stack.getData(); + if (stack.hasItemMeta()) { + setItemMeta0(stack.getItemMeta(), getType0()); + } + } + + /** + * Gets the type of this item + * + * @return Type of the items in this stack + */ + @Utility + public Material getType() { + return getType0(getTypeId()); + } + + private Material getType0() { + return getType0(this.type); + } + + private static Material getType0(int id) { + Material material = Material.getMaterial(id); + return material == null ? Material.AIR : material; + } + + /** + * Sets the type of this item + *

+ * Note that in doing so you will reset the MaterialData for this stack + * + * @param type New type to set the items in this stack to + */ + @Utility + public void setType(Material type) { + Validate.notNull(type, "Material cannot be null"); + setTypeId(type.getId()); + } + + /** + * Gets the type id of this item + * + * @return Type Id of the items in this stack + * @deprecated Magic value + */ + @Deprecated + public int getTypeId() { + return type; + } + + /** + * Sets the type id of this item + *

+ * Note that in doing so you will reset the MaterialData for this stack + * + * @param type New type id to set the items in this stack to + * @deprecated Magic value + */ + @Deprecated + public void setTypeId(int type) { + this.type = type; + if (this.meta != null) { + this.meta = Bukkit.getItemFactory().asMetaFor(meta, getType0()); + } + createData((byte) 0); + } + + /** + * Gets the amount of items in this stack + * + * @return Amount of items in this stick + */ + public int getAmount() { + return amount; + } + + /** + * Sets the amount of items in this stack + * + * @param amount New amount of items in this stack + */ + public void setAmount(int amount) { + this.amount = amount; + } + + /** + * Gets the MaterialData for this stack of items + * + * @return MaterialData for this item + */ + public MaterialData getData() { + Material mat = getType(); + if (data == null && mat != null && mat.getData() != null) { + data = mat.getNewData((byte) this.getDurability()); + } + + return data; + } + + /** + * Sets the MaterialData for this stack of items + * + * @param data New MaterialData for this item + */ + public void setData(MaterialData data) { + Material mat = getType(); + + if (data == null || mat == null || mat.getData() == null) { + this.data = data; + } else { + if ((data.getClass() == mat.getData()) || (data.getClass() == MaterialData.class)) { + this.data = data; + } else { + throw new IllegalArgumentException("Provided data is not of type " + mat.getData().getName() + ", found " + data.getClass().getName()); + } + } + } + + /** + * Sets the durability of this item + * + * @param durability Durability of this item + */ + public void setDurability(final short durability) { + this.durability = durability; + } + + /** + * Gets the durability of this item + * + * @return Durability of this item + */ + public short getDurability() { + return durability; + } + + /** + * Get the maximum stacksize for the material hold in this ItemStack. + * (Returns -1 if it has no idea) + * + * @return The maximum you can stack this material to. + */ + @Utility + public int getMaxStackSize() { + Material material = getType(); + if (material != null) { + return material.getMaxStackSize(); + } + return -1; + } + + private void createData(final byte data) { + Material mat = Material.getMaterial(type); + + if (mat == null) { + this.data = new MaterialData(type, data); + } else { + this.data = mat.getNewData(data); + } + } + + @Override + @Utility + public String toString() { + StringBuilder toString = new StringBuilder("ItemStack{").append(getType().name()).append(" x ").append(getAmount()); + if (hasItemMeta()) { + toString.append(", ").append(getItemMeta()); + } + return toString.append('}').toString(); + } + + @Override + @Utility + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (!(obj instanceof ItemStack)) { + return false; + } + + ItemStack stack = (ItemStack) obj; + return getAmount() == stack.getAmount() && isSimilar(stack); + } + + /** + * This method is the same as equals, but does not consider stack size + * (amount). + * + * @param stack the item stack to compare to + * @return true if the two stacks are equal, ignoring the amount + */ + @Utility + public boolean isSimilar(ItemStack stack) { + if (stack == null) { + return false; + } + if (stack == this) { + return true; + } + return getTypeId() == stack.getTypeId() && getDurability() == stack.getDurability() && hasItemMeta() == stack.hasItemMeta() && (hasItemMeta() ? Bukkit.getItemFactory().equals(getItemMeta(), stack.getItemMeta()) : true); + } + + @Override + public ItemStack clone() { + try { + ItemStack itemStack = (ItemStack) super.clone(); + + if (this.meta != null) { + itemStack.meta = this.meta.clone(); + } + + if (this.data != null) { + itemStack.data = this.data.clone(); + } + + return itemStack; + } catch (CloneNotSupportedException e) { + throw new Error(e); + } + } + + @Override + @Utility + public final int hashCode() { + int hash = 1; + + hash = hash * 31 + getTypeId(); + hash = hash * 31 + getAmount(); + hash = hash * 31 + (getDurability() & 0xffff); + hash = hash * 31 + (hasItemMeta() ? (meta == null ? getItemMeta().hashCode() : meta.hashCode()) : 0); + + return hash; + } + + /** + * Checks if this ItemStack contains the given {@link Enchantment} + * + * @param ench Enchantment to test + * @return True if this has the given enchantment + */ + public boolean containsEnchantment(Enchantment ench) { + return meta == null ? false : meta.hasEnchant(ench); + } + + /** + * Gets the level of the specified enchantment on this item stack + * + * @param ench Enchantment to check + * @return Level of the enchantment, or 0 + */ + public int getEnchantmentLevel(Enchantment ench) { + return meta == null ? 0 : meta.getEnchantLevel(ench); + } + + /** + * Gets a map containing all enchantments and their levels on this item. + * + * @return Map of enchantments. + */ + public Map getEnchantments() { + return meta == null ? ImmutableMap.of() : meta.getEnchants(); + } + + /** + * Adds the specified enchantments to this item stack. + *

+ * This method is the same as calling {@link + * #addEnchantment(Enchantment, int)} for each + * element of the map. + * + * @param enchantments Enchantments to add + * @throws IllegalArgumentException if the specified enchantments is null + * @throws IllegalArgumentException if any specific enchantment or level + * is null. Warning: Some enchantments may be added before this + * exception is thrown. + */ + @Utility + public void addEnchantments(Map enchantments) { + Validate.notNull(enchantments, "Enchantments cannot be null"); + for (Map.Entry entry : enchantments.entrySet()) { + addEnchantment(entry.getKey(), entry.getValue()); + } + } + + /** + * Adds the specified {@link Enchantment} to this item stack. + *

+ * If this item stack already contained the given enchantment (at any + * level), it will be replaced. + * + * @param ench Enchantment to add + * @param level Level of the enchantment + * @throws IllegalArgumentException if enchantment null, or enchantment is + * not applicable + */ + @Utility + public void addEnchantment(Enchantment ench, int level) { + Validate.notNull(ench, "Enchantment cannot be null"); + if ((level < ench.getStartLevel()) || (level > ench.getMaxLevel())) { + throw new IllegalArgumentException("Enchantment level is either too low or too high (given " + level + ", bounds are " + ench.getStartLevel() + " to " + ench.getMaxLevel() + ")"); + } else if (!ench.canEnchantItem(this)) { + throw new IllegalArgumentException("Specified enchantment cannot be applied to this itemstack"); + } + + addUnsafeEnchantment(ench, level); + } + + /** + * Adds the specified enchantments to this item stack in an unsafe manner. + *

+ * This method is the same as calling {@link + * #addUnsafeEnchantment(Enchantment, int)} for + * each element of the map. + * + * @param enchantments Enchantments to add + */ + @Utility + public void addUnsafeEnchantments(Map enchantments) { + for (Map.Entry entry : enchantments.entrySet()) { + addUnsafeEnchantment(entry.getKey(), entry.getValue()); + } + } + + /** + * Adds the specified {@link Enchantment} to this item stack. + *

+ * If this item stack already contained the given enchantment (at any + * level), it will be replaced. + *

+ * This method is unsafe and will ignore level restrictions or item type. + * Use at your own discretion. + * + * @param ench Enchantment to add + * @param level Level of the enchantment + */ + public void addUnsafeEnchantment(Enchantment ench, int level) { + (meta == null ? meta = Bukkit.getItemFactory().getItemMeta(getType0()) : meta).addEnchant(ench, level, true); + } + + /** + * Removes the specified {@link Enchantment} if it exists on this + * ItemStack + * + * @param ench Enchantment to remove + * @return Previous level, or 0 + */ + public int removeEnchantment(Enchantment ench) { + int level = getEnchantmentLevel(ench); + if (level == 0 || meta == null) { + return level; + } + meta.removeEnchant(ench); + return level; + } + + @Utility + public Map serialize() { + Map result = new LinkedHashMap(); + + result.put("type", getType().name()); + + if (getDurability() != 0) { + result.put("damage", getDurability()); + } + + if (getAmount() != 1) { + result.put("amount", getAmount()); + } + + ItemMeta meta = getItemMeta(); + if (!Bukkit.getItemFactory().equals(meta, null)) { + result.put("meta", meta); + } + + return result; + } + + /** + * Required method for configuration serialization + * + * @param args map to deserialize + * @return deserialized item stack + * @see ConfigurationSerializable + */ + public static ItemStack deserialize(Map args) { + Material type = Material.getMaterial((String) args.get("type")); + short damage = 0; + int amount = 1; + + if (args.containsKey("damage")) { + damage = ((Number) args.get("damage")).shortValue(); + } + + if (args.containsKey("amount")) { + amount = ((Number) args.get("amount")).intValue(); + } + + ItemStack result = new ItemStack(type, amount, damage); + + if (args.containsKey("enchantments")) { // Backward compatiblity, @deprecated + Object raw = args.get("enchantments"); + + if (raw instanceof Map) { + Map map = (Map) raw; + + for (Map.Entry entry : map.entrySet()) { + Enchantment enchantment = Enchantment.getByName(entry.getKey().toString()); + + if ((enchantment != null) && (entry.getValue() instanceof Integer)) { + result.addUnsafeEnchantment(enchantment, (Integer) entry.getValue()); + } + } + } + } else if (args.containsKey("meta")) { // We cannot and will not have meta when enchantments (pre-ItemMeta) exist + Object raw = args.get("meta"); + if (raw instanceof ItemMeta) { + result.setItemMeta((ItemMeta) raw); + } + } + + return result; + } + + /** + * Get a copy of this ItemStack's {@link ItemMeta}. + * + * @return a copy of the current ItemStack's ItemData + */ + public ItemMeta getItemMeta() { + return this.meta == null ? Bukkit.getItemFactory().getItemMeta(getType0()) : this.meta.clone(); + } + + /** + * Checks to see if any meta data has been defined. + * + * @return Returns true if some meta data has been set for this item + */ + public boolean hasItemMeta() { + return !Bukkit.getItemFactory().equals(meta, null); + } + + /** + * Set the ItemMeta of this ItemStack. + * + * @param itemMeta new ItemMeta, or null to indicate meta data be cleared. + * @return True if successfully applied ItemMeta, see {@link + * ItemFactory#isApplicable(ItemMeta, ItemStack)} + * @throws IllegalArgumentException if the item meta was not created by + * the {@link ItemFactory} + */ + public boolean setItemMeta(ItemMeta itemMeta) { + return setItemMeta0(itemMeta, getType0()); + } + + /* + * Cannot be overridden, so it's safe for constructor call + */ + private boolean setItemMeta0(ItemMeta itemMeta, Material material) { + if (itemMeta == null) { + this.meta = null; + return true; + } + if (!Bukkit.getItemFactory().isApplicable(itemMeta, material)) { + return false; + } + this.meta = Bukkit.getItemFactory().asMetaFor(itemMeta, material); + if (this.meta == itemMeta) { + this.meta = itemMeta.clone(); + } + + return true; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/inventory/MerchantInventory.java b/azurite-api/src/main/java/org/bukkit/inventory/MerchantInventory.java new file mode 100644 index 0000000..163f459 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/inventory/MerchantInventory.java @@ -0,0 +1,4 @@ +package org.bukkit.inventory; + +public interface MerchantInventory extends Inventory { +} diff --git a/azurite-api/src/main/java/org/bukkit/inventory/PlayerInventory.java b/azurite-api/src/main/java/org/bukkit/inventory/PlayerInventory.java new file mode 100644 index 0000000..2f0e843 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/inventory/PlayerInventory.java @@ -0,0 +1,154 @@ +package org.bukkit.inventory; + +import org.bukkit.entity.HumanEntity; + +/** + * Interface to the inventory of a Player, including the four armor slots. + */ +public interface PlayerInventory extends Inventory { + + /** + * Get all ItemStacks from the armor slots + * + * @return All the ItemStacks from the armor slots + */ + ItemStack[] getArmorContents(); + + /** + * Return the ItemStack from the helmet slot + * + * @return The ItemStack in the helmet slot + */ + ItemStack getHelmet(); + + /** + * Return the ItemStack from the chestplate slot + * + * @return The ItemStack in the chestplate slot + */ + ItemStack getChestplate(); + + /** + * Return the ItemStack from the leg slot + * + * @return The ItemStack in the leg slot + */ + ItemStack getLeggings(); + + /** + * Return the ItemStack from the boots slot + * + * @return The ItemStack in the boots slot + */ + ItemStack getBoots(); + + /** + * Stores the ItemStack at the given index of the inventory. + *

+ * Indexes 0 through 8 refer to the hotbar. 9 through 35 refer to the main inventory, counting up from 9 at the top + * left corner of the inventory, moving to the right, and moving to the row below it back on the left side when it + * reaches the end of the row. It follows the same path in the inventory like you would read a book. + *

+ * Indexes 36 through 39 refer to the armor slots. Though you can set armor with this method using these indexes, + * you are encouraged to use the provided methods for those slots. + *

+ * If you attempt to use this method with an index less than 0 or greater than 39, an ArrayIndexOutOfBounds + * exception will be thrown. + * + * @param index The index where to put the ItemStack + * @param item The ItemStack to set + * @throws ArrayIndexOutOfBoundsException when index < 0 || index > 39 + * @see #setBoots(ItemStack) + * @see #setChestplate(ItemStack) + * @see #setHelmet(ItemStack) + * @see #setLeggings(ItemStack) + */ + @Override + void setItem(int index, ItemStack item); + + /** + * Put the given ItemStacks into the armor slots + * + * @param items The ItemStacks to use as armour + */ + void setArmorContents(ItemStack[] items); + + /** + * Put the given ItemStack into the helmet slot. This does not check if + * the ItemStack is a helmet + * + * @param helmet The ItemStack to use as helmet + */ + void setHelmet(ItemStack helmet); + + /** + * Put the given ItemStack into the chestplate slot. This does not check + * if the ItemStack is a chestplate + * + * @param chestplate The ItemStack to use as chestplate + */ + void setChestplate(ItemStack chestplate); + + /** + * Put the given ItemStack into the leg slot. This does not check if the + * ItemStack is a pair of leggings + * + * @param leggings The ItemStack to use as leggings + */ + void setLeggings(ItemStack leggings); + + /** + * Put the given ItemStack into the boots slot. This does not check if the + * ItemStack is a boots + * + * @param boots The ItemStack to use as boots + */ + void setBoots(ItemStack boots); + + /** + * Returns the ItemStack currently hold + * + * @return The currently held ItemStack + */ + ItemStack getItemInHand(); + + /** + * Sets the item in hand + * + * @param stack Stack to set + */ + void setItemInHand(ItemStack stack); + + /** + * Get the slot number of the currently held item + * + * @return Held item slot number + */ + int getHeldItemSlot(); + + /** + * Set the slot number of the currently held item. + *

+ * This validates whether the slot is between 0 and 8 inclusive. + * + * @param slot The new slot number + * @throws IllegalArgumentException Thrown if slot is not between 0 and 8 + * inclusive + */ + void setHeldItemSlot(int slot); + + /** + * Clears all matching items from the inventory. Setting either value to + * -1 will skip it's check, while setting both to -1 will clear all items + * in your inventory unconditionally. + * + * @param id the id of the item you want to clear from the inventory + * @param data the data of the item you want to clear from the inventory + * @return The number of items cleared + * @deprecated Magic value + */ + @Deprecated + int clear(int id, int data); + + HumanEntity getHolder(); +} diff --git a/azurite-api/src/main/java/org/bukkit/inventory/Recipe.java b/azurite-api/src/main/java/org/bukkit/inventory/Recipe.java new file mode 100644 index 0000000..7977ce2 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/inventory/Recipe.java @@ -0,0 +1,14 @@ +package org.bukkit.inventory; + +/** + * Represents some type of crafting recipe. + */ +public interface Recipe { + + /** + * Get the result of this recipe. + * + * @return The result stack + */ + ItemStack getResult(); +} diff --git a/azurite-api/src/main/java/org/bukkit/inventory/ShapedRecipe.java b/azurite-api/src/main/java/org/bukkit/inventory/ShapedRecipe.java new file mode 100644 index 0000000..0d5f652 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/inventory/ShapedRecipe.java @@ -0,0 +1,147 @@ +package org.bukkit.inventory; + +import org.apache.commons.lang.Validate; +import org.bukkit.Material; +import org.bukkit.material.MaterialData; + +import java.util.HashMap; +import java.util.Map; + +/** + * Represents a shaped (ie normal) crafting recipe. + */ +public class ShapedRecipe implements Recipe { + private ItemStack output; + private String[] rows; + private Map ingredients = new HashMap(); + + /** + * Create a shaped recipe to craft the specified ItemStack. The + * constructor merely determines the result and type; to set the actual + * recipe, you'll need to call the appropriate methods. + * + * @param result The item you want the recipe to create. + * @see ShapedRecipe#shape(String...) + * @see ShapedRecipe#setIngredient(char, Material) + * @see ShapedRecipe#setIngredient(char, Material, int) + * @see ShapedRecipe#setIngredient(char, MaterialData) + */ + public ShapedRecipe(ItemStack result) { + this.output = new ItemStack(result); + } + + /** + * Set the shape of this recipe to the specified rows. Each character + * represents a different ingredient; exactly what each character + * represents is set separately. The first row supplied corresponds with + * the upper most part of the recipe on the workbench e.g. if all three + * rows are supplies the first string represents the top row on the + * workbench. + * + * @param shape The rows of the recipe (up to 3 rows). + * @return The changed recipe, so you can chain calls. + */ + public ShapedRecipe shape(final String... shape) { + Validate.notNull(shape, "Must provide a shape"); + Validate.isTrue(shape.length > 0 && shape.length < 4, "Crafting recipes should be 1, 2, 3 rows, not ", shape.length); + + for (String row : shape) { + Validate.notNull(row, "Shape cannot have null rows"); + Validate.isTrue(row.length() > 0 && row.length() < 4, "Crafting rows should be 1, 2, or 3 characters, not ", row.length()); + } + this.rows = new String[shape.length]; + for (int i = 0; i < shape.length; i++) { + this.rows[i] = shape[i]; + } + + // Remove character mappings for characters that no longer exist in the shape + HashMap newIngredients = new HashMap(); + for (String row : shape) { + for (Character c : row.toCharArray()) { + newIngredients.put(c, ingredients.get(c)); + } + } + this.ingredients = newIngredients; + + return this; + } + + /** + * Sets the material that a character in the recipe shape refers to. + * + * @param key The character that represents the ingredient in the shape. + * @param ingredient The ingredient. + * @return The changed recipe, so you can chain calls. + */ + public ShapedRecipe setIngredient(char key, MaterialData ingredient) { + return setIngredient(key, ingredient.getItemType(), ingredient.getData()); + } + + /** + * Sets the material that a character in the recipe shape refers to. + * + * @param key The character that represents the ingredient in the shape. + * @param ingredient The ingredient. + * @return The changed recipe, so you can chain calls. + */ + public ShapedRecipe setIngredient(char key, Material ingredient) { + return setIngredient(key, ingredient, 0); + } + + /** + * Sets the material that a character in the recipe shape refers to. + * + * @param key The character that represents the ingredient in the shape. + * @param ingredient The ingredient. + * @param raw The raw material data as an integer. + * @return The changed recipe, so you can chain calls. + * @deprecated Magic value + */ + @Deprecated + public ShapedRecipe setIngredient(char key, Material ingredient, int raw) { + Validate.isTrue(ingredients.containsKey(key), "Symbol does not appear in the shape:", key); + + // -1 is the old wildcard, map to Short.MAX_VALUE as the new one + if (raw == -1) { + raw = Short.MAX_VALUE; + } + + ingredients.put(key, new ItemStack(ingredient, 1, (short) raw)); + return this; + } + + /** + * Get a copy of the ingredients map. + * + * @return The mapping of character to ingredients. + */ + public Map getIngredientMap() { + HashMap result = new HashMap(); + for (Map.Entry ingredient : ingredients.entrySet()) { + if (ingredient.getValue() == null) { + result.put(ingredient.getKey(), null); + } else { + result.put(ingredient.getKey(), ingredient.getValue().clone()); + } + } + return result; + } + + /** + * Get the shape. + * + * @return The recipe's shape. + */ + public String[] getShape() { + return rows.clone(); + } + + /** + * Get the result. + * + * @return The result stack. + */ + public ItemStack getResult() { + return output.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/inventory/ShapelessRecipe.java b/azurite-api/src/main/java/org/bukkit/inventory/ShapelessRecipe.java new file mode 100644 index 0000000..3f1c00d --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/inventory/ShapelessRecipe.java @@ -0,0 +1,225 @@ +package org.bukkit.inventory; + +import org.apache.commons.lang.Validate; +import org.bukkit.Material; +import org.bukkit.material.MaterialData; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +/** + * Represents a shapeless recipe, where the arrangement of the ingredients on + * the crafting grid does not matter. + */ +public class ShapelessRecipe implements Recipe { + private ItemStack output; + private List ingredients = new ArrayList(); + + /** + * Create a shapeless recipe to craft the specified ItemStack. The + * constructor merely determines the result and type; to set the actual + * recipe, you'll need to call the appropriate methods. + * + * @param result The item you want the recipe to create. + * @see ShapelessRecipe#addIngredient(Material) + * @see ShapelessRecipe#addIngredient(MaterialData) + * @see ShapelessRecipe#addIngredient(Material,int) + * @see ShapelessRecipe#addIngredient(int,Material) + * @see ShapelessRecipe#addIngredient(int,MaterialData) + * @see ShapelessRecipe#addIngredient(int,Material,int) + */ + public ShapelessRecipe(ItemStack result) { + this.output = new ItemStack(result); + } + + /** + * Adds the specified ingredient. + * + * @param ingredient The ingredient to add. + * @return The changed recipe, so you can chain calls. + */ + public ShapelessRecipe addIngredient(MaterialData ingredient) { + return addIngredient(1, ingredient); + } + + /** + * Adds the specified ingredient. + * + * @param ingredient The ingredient to add. + * @return The changed recipe, so you can chain calls. + */ + public ShapelessRecipe addIngredient(Material ingredient) { + return addIngredient(1, ingredient, 0); + } + + /** + * Adds the specified ingredient. + * + * @param ingredient The ingredient to add. + * @param rawdata The data value, or -1 to allow any data value. + * @return The changed recipe, so you can chain calls. + * @deprecated Magic value + */ + @Deprecated + public ShapelessRecipe addIngredient(Material ingredient, int rawdata) { + return addIngredient(1, ingredient, rawdata); + } + + /** + * Adds multiples of the specified ingredient. + * + * @param count How many to add (can't be more than 9!) + * @param ingredient The ingredient to add. + * @return The changed recipe, so you can chain calls. + */ + public ShapelessRecipe addIngredient(int count, MaterialData ingredient) { + return addIngredient(count, ingredient.getItemType(), ingredient.getData()); + } + + /** + * Adds multiples of the specified ingredient. + * + * @param count How many to add (can't be more than 9!) + * @param ingredient The ingredient to add. + * @return The changed recipe, so you can chain calls. + */ + public ShapelessRecipe addIngredient(int count, Material ingredient) { + return addIngredient(count, ingredient, 0); + } + + /** + * Adds multiples of the specified ingredient. + * + * @param count How many to add (can't be more than 9!) + * @param ingredient The ingredient to add. + * @param rawdata The data value, or -1 to allow any data value. + * @return The changed recipe, so you can chain calls. + * @deprecated Magic value + */ + @Deprecated + public ShapelessRecipe addIngredient(int count, Material ingredient, int rawdata) { + Validate.isTrue(ingredients.size() + count <= 9, "Shapeless recipes cannot have more than 9 ingredients"); + + // -1 is the old wildcard, map to Short.MAX_VALUE as the new one + if (rawdata == -1) { + rawdata = Short.MAX_VALUE; + } + + while (count-- > 0) { + ingredients.add(new ItemStack(ingredient, 1, (short) rawdata)); + } + return this; + } + + /** + * Removes an ingredient from the list. If the ingredient occurs multiple + * times, only one instance of it is removed. Only removes exact matches, + * with a data value of 0. + * + * @param ingredient The ingredient to remove + * @return The changed recipe. + */ + public ShapelessRecipe removeIngredient(Material ingredient) { + return removeIngredient(ingredient, 0); + } + + /** + * Removes an ingredient from the list. If the ingredient occurs multiple + * times, only one instance of it is removed. If the data value is -1, + * only ingredients with a -1 data value will be removed. + * + * @param ingredient The ingredient to remove + * @return The changed recipe. + */ + public ShapelessRecipe removeIngredient(MaterialData ingredient) { + return removeIngredient(ingredient.getItemType(), ingredient.getData()); + } + + /** + * Removes multiple instances of an ingredient from the list. If there are + * less instances then specified, all will be removed. Only removes exact + * matches, with a data value of 0. + * + * @param count The number of copies to remove. + * @param ingredient The ingredient to remove + * @return The changed recipe. + */ + public ShapelessRecipe removeIngredient(int count, Material ingredient) { + return removeIngredient(count, ingredient, 0); + } + + /** + * Removes multiple instances of an ingredient from the list. If there are + * less instances then specified, all will be removed. If the data value + * is -1, only ingredients with a -1 data value will be removed. + * + * @param count The number of copies to remove. + * @param ingredient The ingredient to remove. + * @return The changed recipe. + */ + public ShapelessRecipe removeIngredient(int count, MaterialData ingredient) { + return removeIngredient(count, ingredient.getItemType(), ingredient.getData()); + } + + /** + * Removes an ingredient from the list. If the ingredient occurs multiple + * times, only one instance of it is removed. If the data value is -1, + * only ingredients with a -1 data value will be removed. + * + * @param ingredient The ingredient to remove + * @param rawdata The data value; + * @return The changed recipe. + * @deprecated Magic value + */ + @Deprecated + public ShapelessRecipe removeIngredient(Material ingredient, int rawdata) { + return removeIngredient(1, ingredient, rawdata); + } + + /** + * Removes multiple instances of an ingredient from the list. If there are + * less instances then specified, all will be removed. If the data value + * is -1, only ingredients with a -1 data value will be removed. + * + * @param count The number of copies to remove. + * @param ingredient The ingredient to remove. + * @param rawdata The data value. + * @return The changed recipe. + * @deprecated Magic value + */ + @Deprecated + public ShapelessRecipe removeIngredient(int count, Material ingredient, int rawdata) { + Iterator iterator = ingredients.iterator(); + while (count > 0 && iterator.hasNext()) { + ItemStack stack = iterator.next(); + if (stack.getType() == ingredient && stack.getDurability() == rawdata) { + iterator.remove(); + count--; + } + } + return this; + } + + /** + * Get the result of this recipe. + * + * @return The result stack. + */ + public ItemStack getResult() { + return output.clone(); + } + + /** + * Get the list of ingredients used for this recipe. + * + * @return The input list + */ + public List getIngredientList() { + ArrayList result = new ArrayList(ingredients.size()); + for (ItemStack ingredient : ingredients) { + result.add(ingredient.clone()); + } + return result; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/inventory/meta/BannerMeta.java b/azurite-api/src/main/java/org/bukkit/inventory/meta/BannerMeta.java new file mode 100644 index 0000000..5b429b1 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/inventory/meta/BannerMeta.java @@ -0,0 +1,77 @@ +package org.bukkit.inventory.meta; + +import org.bukkit.DyeColor; +import org.bukkit.block.banner.Pattern; + +import java.util.List; + +public interface BannerMeta extends ItemMeta { + + /** + * Returns the base color for this banner + * + * @return the base color + */ + DyeColor getBaseColor(); + + /** + * Sets the base color for this banner + * + * @param color the base color + */ + void setBaseColor(DyeColor color); + + /** + * Returns a list of patterns on this banner + * + * @return the patterns + */ + List getPatterns(); + + /** + * Sets the patterns used on this banner + * + * @param patterns the new list of patterns + */ + void setPatterns(List patterns); + + /** + * Adds a new pattern on top of the existing + * patterns + * + * @param pattern the new pattern to add + */ + void addPattern(Pattern pattern); + + /** + * Returns the pattern at the specified index + * + * @param i the index + * @return the pattern + */ + Pattern getPattern(int i); + + /** + * Removes the pattern at the specified index + * + * @param i the index + * @return the removed pattern + */ + Pattern removePattern(int i); + + /** + * Sets the pattern at the specified index + * + * @param i the index + * @param pattern the new pattern + */ + void setPattern(int i, Pattern pattern); + + /** + * Returns the number of patterns on this + * banner + * + * @return the number of patterns + */ + int numberOfPatterns(); +} diff --git a/azurite-api/src/main/java/org/bukkit/inventory/meta/BlockStateMeta.java b/azurite-api/src/main/java/org/bukkit/inventory/meta/BlockStateMeta.java new file mode 100644 index 0000000..25c7eba --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/inventory/meta/BlockStateMeta.java @@ -0,0 +1,35 @@ + +package org.bukkit.inventory.meta; + +import org.bukkit.block.BlockState; + +public interface BlockStateMeta extends ItemMeta { + + /** + * Returns whether the item has a block state currently + * attached to it. + * + * @return whether a block state is already attached + */ + boolean hasBlockState(); + + /** + * Returns the currently attached block state for this + * item or creates a new one if one doesn't exist. + * + * The state is a copy, it must be set back (or to another + * item) with {@link #setBlockState(BlockState)} + * + * @return the attached state or a new state + */ + BlockState getBlockState(); + + /** + * Attaches a copy of the passed block state to the item. + * + * @param blockState the block state to attach to the block. + * @throws IllegalArgumentException if the blockState is null + * or invalid for this item. + */ + void setBlockState(BlockState blockState); +} diff --git a/azurite-api/src/main/java/org/bukkit/inventory/meta/BookMeta.java b/azurite-api/src/main/java/org/bukkit/inventory/meta/BookMeta.java new file mode 100644 index 0000000..2c1e36e --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/inventory/meta/BookMeta.java @@ -0,0 +1,130 @@ +package org.bukkit.inventory.meta; + +import org.bukkit.Material; + +import java.util.List; + +/** + * Represents a book ({@link Material#BOOK_AND_QUILL} or {@link + * Material#WRITTEN_BOOK}) that can have a title, an author, and pages. + */ +public interface BookMeta extends ItemMeta { + + /** + * Checks for the existence of a title in the book. + * + * @return true if the book has a title + */ + boolean hasTitle(); + + /** + * Gets the title of the book. + *

+ * Plugins should check that hasTitle() returns true before calling this + * method. + * + * @return the title of the book + */ + String getTitle(); + + /** + * Sets the title of the book. + *

+ * Limited to 16 characters. Removes title when given null. + * + * @param title the title to set + * @return true if the title was successfully set + */ + boolean setTitle(String title); + + /** + * Checks for the existence of an author in the book. + * + * @return the author of the book + */ + boolean hasAuthor(); + + /** + * Gets the author of the book. + *

+ * Plugins should check that hasAuthor() returns true before calling this + * method. + * + * @return the author of the book + */ + String getAuthor(); + + /** + * Sets the author of the book. Removes author when given null. + * + * @param author the author of the book + */ + void setAuthor(String author); + + /** + * Checks for the existence of pages in the book. + * + * @return true if the book has pages + */ + boolean hasPages(); + + /** + * Gets the specified page in the book. The given page must exist. + * + * @param page the page number to get + * @return the page from the book + */ + String getPage(int page); + + /** + * Sets the specified page in the book. Pages of the book must be + * contiguous. + *

+ * The data can be up to 256 characters in length, additional characters + * are truncated. + * + * @param page the page number to set + * @param data the data to set for that page + */ + void setPage(int page, String data); + + /** + * Gets all the pages in the book. + * + * @return list of all the pages in the book + */ + List getPages(); + + /** + * Clears the existing book pages, and sets the book to use the provided + * pages. Maximum 50 pages with 256 characters per page. + * + * @param pages A list of pages to set the book to use + */ + void setPages(List pages); + + /** + * Clears the existing book pages, and sets the book to use the provided + * pages. Maximum 50 pages with 256 characters per page. + * + * @param pages A list of strings, each being a page + */ + void setPages(String... pages); + + /** + * Adds new pages to the end of the book. Up to a maximum of 50 pages with + * 256 characters per page. + * + * @param pages A list of strings, each being a page + */ + void addPage(String... pages); + + /** + * Gets the number of pages in the book. + * + * @return the number of pages in the book + */ + int getPageCount(); + + BookMeta clone(); +} diff --git a/azurite-api/src/main/java/org/bukkit/inventory/meta/EnchantmentStorageMeta.java b/azurite-api/src/main/java/org/bukkit/inventory/meta/EnchantmentStorageMeta.java new file mode 100644 index 0000000..aac755d --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/inventory/meta/EnchantmentStorageMeta.java @@ -0,0 +1,79 @@ +package org.bukkit.inventory.meta; + +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; + +import java.util.Map; + +/** + * EnchantmentMeta is specific to items that can store enchantments, as + * opposed to being enchanted. {@link Material#ENCHANTED_BOOK} is an example + * of an item with enchantment storage. + */ +public interface EnchantmentStorageMeta extends ItemMeta { + + /** + * Checks for the existence of any stored enchantments. + * + * @return true if an enchantment exists on this meta + */ + boolean hasStoredEnchants(); + + /** + * Checks for storage of the specified enchantment. + * + * @param ench enchantment to check + * @return true if this enchantment is stored in this meta + */ + boolean hasStoredEnchant(Enchantment ench); + + /** + * Checks for the level of the stored enchantment. + * + * @param ench enchantment to check + * @return The level that the specified stored enchantment has, or 0 if + * none + */ + int getStoredEnchantLevel(Enchantment ench); + + /** + * Gets a copy the stored enchantments in this ItemMeta. + * + * @return An immutable copy of the stored enchantments + */ + Map getStoredEnchants(); + + /** + * Stores the specified enchantment in this item meta. + * + * @param ench Enchantment to store + * @param level Level for the enchantment + * @param ignoreLevelRestriction this indicates the enchantment should be + * applied, ignoring the level limit + * @return true if the item meta changed as a result of this call, false + * otherwise + * @throws IllegalArgumentException if enchantment is null + */ + boolean addStoredEnchant(Enchantment ench, int level, boolean ignoreLevelRestriction); + + /** + * Remove the specified stored enchantment from this item meta. + * + * @param ench Enchantment to remove + * @return true if the item meta changed as a result of this call, false + * otherwise + * @throws IllegalArgumentException if enchantment is null + */ + boolean removeStoredEnchant(Enchantment ench) throws IllegalArgumentException; + + /** + * Checks if the specified enchantment conflicts with any enchantments in + * this ItemMeta. + * + * @param ench enchantment to test + * @return true if the enchantment conflicts, false otherwise + */ + boolean hasConflictingStoredEnchant(Enchantment ench); + + EnchantmentStorageMeta clone(); +} diff --git a/azurite-api/src/main/java/org/bukkit/inventory/meta/FireworkEffectMeta.java b/azurite-api/src/main/java/org/bukkit/inventory/meta/FireworkEffectMeta.java new file mode 100644 index 0000000..47046f1 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/inventory/meta/FireworkEffectMeta.java @@ -0,0 +1,34 @@ +package org.bukkit.inventory.meta; + +import org.bukkit.FireworkEffect; +import org.bukkit.Material; + +/** + * Represents a meta that can store a single FireworkEffect. An example + * includes {@link Material#FIREWORK_CHARGE}. + */ +public interface FireworkEffectMeta extends ItemMeta { + + /** + * Sets the firework effect for this meta. + * + * @param effect the effect to set, or null to indicate none. + */ + void setEffect(FireworkEffect effect); + + /** + * Checks if this meta has an effect. + * + * @return true if this meta has an effect, false otherwise + */ + boolean hasEffect(); + + /** + * Gets the firework effect for this meta. + * + * @return the current effect, or null if none + */ + FireworkEffect getEffect(); + + FireworkEffectMeta clone(); +} diff --git a/azurite-api/src/main/java/org/bukkit/inventory/meta/FireworkMeta.java b/azurite-api/src/main/java/org/bukkit/inventory/meta/FireworkMeta.java new file mode 100644 index 0000000..36af3d4 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/inventory/meta/FireworkMeta.java @@ -0,0 +1,94 @@ +package org.bukkit.inventory.meta; + +import org.bukkit.FireworkEffect; +import org.bukkit.Material; + +import java.util.List; + +/** + * Represents a {@link Material#FIREWORK} and its effects. + */ +public interface FireworkMeta extends ItemMeta { + + /** + * Add another effect to this firework. + * + * @param effect The firework effect to add + * @throws IllegalArgumentException If effect is null + */ + void addEffect(FireworkEffect effect) throws IllegalArgumentException; + + /** + * Add several effects to this firework. + * + * @param effects The firework effects to add + * @throws IllegalArgumentException If effects is null + * @throws IllegalArgumentException If any effect is null (may be thrown + * after changes have occurred) + */ + void addEffects(FireworkEffect...effects) throws IllegalArgumentException; + + /** + * Add several firework effects to this firework. + * + * @param effects An iterable object whose iterator yields the desired + * firework effects + * @throws IllegalArgumentException If effects is null + * @throws IllegalArgumentException If any effect is null (may be thrown + * after changes have occurred) + */ + void addEffects(Iterable effects) throws IllegalArgumentException; + + /** + * Get the effects in this firework. + * + * @return An immutable list of the firework effects + */ + List getEffects(); + + /** + * Get the number of effects in this firework. + * + * @return The number of effects + */ + int getEffectsSize(); + + /** + * Remove an effect from this firework. + * + * @param index The index of the effect to remove + * @throws IndexOutOfBoundsException If index {@literal < 0 or index >} {@link + * #getEffectsSize()} + */ + void removeEffect(int index) throws IndexOutOfBoundsException; + + /** + * Remove all effects from this firework. + */ + void clearEffects(); + + /** + * Get whether this firework has any effects. + * + * @return true if it has effects, false if there are no effects + */ + boolean hasEffects(); + + /** + * Gets the approximate height the firework will fly. + * + * @return approximate flight height of the firework. + */ + int getPower(); + + /** + * Sets the approximate power of the firework. Each level of power is half + * a second of flight time. + * + * @param power the power of the firework, from 0-128 + * @throws IllegalArgumentException if {@literal height<0 or height>128} + */ + void setPower(int power) throws IllegalArgumentException; + + FireworkMeta clone(); +} diff --git a/azurite-api/src/main/java/org/bukkit/inventory/meta/ItemMeta.java b/azurite-api/src/main/java/org/bukkit/inventory/meta/ItemMeta.java new file mode 100644 index 0000000..e797f05 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/inventory/meta/ItemMeta.java @@ -0,0 +1,188 @@ +package org.bukkit.inventory.meta; + +import org.bukkit.configuration.serialization.ConfigurationSerializable; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.ItemFlag; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * This type represents the storage mechanism for auxiliary item data. + *

+ * An implementation will handle the creation and application for ItemMeta. + * This class should not be implemented by a plugin in a live environment. + */ +public interface ItemMeta extends Cloneable, ConfigurationSerializable { + + /** + * Checks for existence of a display name. + * + * @return true if this has a display name + */ + boolean hasDisplayName(); + + /** + * Gets the display name that is set. + *

+ * Plugins should check that hasDisplayName() returns true + * before calling this method. + * + * @return the display name that is set + */ + String getDisplayName(); + + /** + * Sets the display name. + * + * @param name the name to set + */ + void setDisplayName(String name); + + /** + * Checks for existence of lore. + * + * @return true if this has lore + */ + boolean hasLore(); + + /** + * Gets the lore that is set. + *

+ * Plugins should check if hasLore() returns true before + * calling this method. + * + * @return a list of lore that is set + */ + List getLore(); + + /** + * Sets the lore for this item. + * Removes lore when given null. + * + * @param lore the lore that will be set + */ + void setLore(List lore); + + /** + * Checks for the existence of any enchantments. + * + * @return true if an enchantment exists on this meta + */ + boolean hasEnchants(); + + /** + * Checks for existence of the specified enchantment. + * + * @param ench enchantment to check + * @return true if this enchantment exists for this meta + */ + boolean hasEnchant(Enchantment ench); + + /** + * Checks for the level of the specified enchantment. + * + * @param ench enchantment to check + * @return The level that the specified enchantment has, or 0 if none + */ + int getEnchantLevel(Enchantment ench); + + /** + * Returns a copy the enchantments in this ItemMeta.
+ * Returns an empty map if none. + * + * @return An immutable copy of the enchantments + */ + Map getEnchants(); + + /** + * Adds the specified enchantment to this item meta. + * + * @param ench Enchantment to add + * @param level Level for the enchantment + * @param ignoreLevelRestriction this indicates the enchantment should be + * applied, ignoring the level limit + * @return true if the item meta changed as a result of this call, false + * otherwise + */ + boolean addEnchant(Enchantment ench, int level, boolean ignoreLevelRestriction); + + /** + * Removes the specified enchantment from this item meta. + * + * @param ench Enchantment to remove + * @return true if the item meta changed as a result of this call, false + * otherwise + */ + boolean removeEnchant(Enchantment ench); + + /** + * Checks if the specified enchantment conflicts with any enchantments in + * this ItemMeta. + * + * @param ench enchantment to test + * @return true if the enchantment conflicts, false otherwise + */ + boolean hasConflictingEnchant(Enchantment ench); + + /** + * Set itemflags which should be ignored when rendering a ItemStack in the Client. This Method does silently ignore double set itemFlags. + * + * @param itemFlags The hideflags which shouldn't be rendered + */ + void addItemFlags(ItemFlag... itemFlags); + + /** + * Remove specific set of itemFlags. This tells the Client it should render it again. This Method does silently ignore double removed itemFlags. + * + * @param itemFlags Hideflags which should be removed + */ + void removeItemFlags(ItemFlag... itemFlags); + + /** + * Get current set itemFlags. The collection returned is unmodifiable. + * + * @return A set of all itemFlags set + */ + Set getItemFlags(); + + /** + * Check if the specified flag is present on this item. + * + * @param flag the flag to check + * @return if it is present + */ + boolean hasItemFlag(ItemFlag flag); + + @SuppressWarnings("javadoc") + ItemMeta clone(); + + // Spigot start + class Spigot + { + + /** + * Sets the unbreakable tag + * + * @param unbreakable true if set unbreakable + */ + public void setUnbreakable(boolean unbreakable) + { + throw new UnsupportedOperationException( "Not supported yet." ); + } + + /** + * Return if the unbreakable tag is true + * + * @return true if the unbreakable tag is true + */ + public boolean isUnbreakable() + { + throw new UnsupportedOperationException( "Not supported yet." ); + } + } + + Spigot spigot(); + // Spigot end +} diff --git a/azurite-api/src/main/java/org/bukkit/inventory/meta/LeatherArmorMeta.java b/azurite-api/src/main/java/org/bukkit/inventory/meta/LeatherArmorMeta.java new file mode 100644 index 0000000..2dc2420 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/inventory/meta/LeatherArmorMeta.java @@ -0,0 +1,31 @@ +package org.bukkit.inventory.meta; + +import org.bukkit.Color; +import org.bukkit.Material; +import org.bukkit.inventory.ItemFactory; + +/** + * Represents leather armor ({@link Material#LEATHER_BOOTS}, {@link + * Material#LEATHER_CHESTPLATE}, {@link Material#LEATHER_HELMET}, or {@link + * Material#LEATHER_LEGGINGS}) that can be colored. + */ +public interface LeatherArmorMeta extends ItemMeta { + + /** + * Gets the color of the armor. If it has not been set otherwise, it will + * be {@link ItemFactory#getDefaultLeatherColor()}. + * + * @return the color of the armor, never null + */ + Color getColor(); + + /** + * Sets the color of the armor. + * + * @param color the color to set. Setting it to null is equivalent to + * setting it to {@link ItemFactory#getDefaultLeatherColor()}. + */ + void setColor(Color color); + + LeatherArmorMeta clone(); +} diff --git a/azurite-api/src/main/java/org/bukkit/inventory/meta/MapMeta.java b/azurite-api/src/main/java/org/bukkit/inventory/meta/MapMeta.java new file mode 100644 index 0000000..fb5c297 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/inventory/meta/MapMeta.java @@ -0,0 +1,23 @@ +package org.bukkit.inventory.meta; + +/** + * Represents a map that can be scalable. + */ +public interface MapMeta extends ItemMeta { + + /** + * Checks to see if this map is scaling. + * + * @return true if this map is scaling + */ + boolean isScaling(); + + /** + * Sets if this map is scaling or not. + * + * @param value true to scale + */ + void setScaling(boolean value); + + MapMeta clone(); +} diff --git a/azurite-api/src/main/java/org/bukkit/inventory/meta/PotionMeta.java b/azurite-api/src/main/java/org/bukkit/inventory/meta/PotionMeta.java new file mode 100644 index 0000000..8dca983 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/inventory/meta/PotionMeta.java @@ -0,0 +1,77 @@ +package org.bukkit.inventory.meta; + +import org.bukkit.Material; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +import java.util.List; + +/** + * Represents a potion ({@link Material#POTION}) that can have custom effects. + */ +public interface PotionMeta extends ItemMeta { + + /** + * Checks for the presence of custom potion effects. + * + * @return true if custom potion effects are applied + */ + boolean hasCustomEffects(); + + /** + * Gets an immutable list containing all custom potion effects applied to + * this potion. + *

+ * Plugins should check that hasCustomEffects() returns true before + * calling this method. + * + * @return the immutable list of custom potion effects + */ + List getCustomEffects(); + + /** + * Adds a custom potion effect to this potion. + * + * @param effect the potion effect to add + * @param overwrite true if any existing effect of the same type should be + * overwritten + * @return true if the potion meta changed as a result of this call + */ + boolean addCustomEffect(PotionEffect effect, boolean overwrite); + + /** + * Removes a custom potion effect from this potion. + * + * @param type the potion effect type to remove + * @return true if the potion meta changed as a result of this call + */ + boolean removeCustomEffect(PotionEffectType type); + + /** + * Checks for a specific custom potion effect type on this potion. + * + * @param type the potion effect type to check for + * @return true if the potion has this effect + */ + boolean hasCustomEffect(PotionEffectType type); + + /** + * Moves a potion effect to the top of the potion effect list. + *

+ * This causes the client to display the potion effect in the potion's + * name. + * + * @param type the potion effect type to move + * @return true if the potion meta changed as a result of this call + */ + boolean setMainEffect(PotionEffectType type); + + /** + * Removes all custom potion effects from this potion. + * + * @return true if the potion meta changed as a result of this call + */ + boolean clearCustomEffects(); + + PotionMeta clone(); +} diff --git a/azurite-api/src/main/java/org/bukkit/inventory/meta/Repairable.java b/azurite-api/src/main/java/org/bukkit/inventory/meta/Repairable.java new file mode 100644 index 0000000..c49844e --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/inventory/meta/Repairable.java @@ -0,0 +1,31 @@ +package org.bukkit.inventory.meta; + +/** + * Represents an item that can be repaired at an anvil. + */ +public interface Repairable { + + /** + * Checks to see if this has a repair penalty + * + * @return true if this has a repair penalty + */ + boolean hasRepairCost(); + + /** + * Gets the repair penalty + * + * @return the repair penalty + */ + int getRepairCost(); + + /** + * Sets the repair penalty + * + * @param cost repair penalty + */ + void setRepairCost(int cost); + + @SuppressWarnings("javadoc") + Repairable clone(); +} diff --git a/azurite-api/src/main/java/org/bukkit/inventory/meta/SkullMeta.java b/azurite-api/src/main/java/org/bukkit/inventory/meta/SkullMeta.java new file mode 100644 index 0000000..fab3119 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/inventory/meta/SkullMeta.java @@ -0,0 +1,36 @@ +package org.bukkit.inventory.meta; + +import org.bukkit.Material; + +/** + * Represents a skull ({@link Material#SKULL_ITEM}) that can have an owner. + */ +public interface SkullMeta extends ItemMeta { + + /** + * Gets the owner of the skull. + * + * @return the owner if the skull + */ + String getOwner(); + + /** + * Checks to see if the skull has an owner. + * + * @return true if the skull has an owner + */ + boolean hasOwner(); + + /** + * Sets the owner of the skull. + *

+ * Plugins should check that hasOwner() returns true before calling this + * plugin. + * + * @param owner the new owner of the skull + * @return true if the owner was successfully set + */ + boolean setOwner(String owner); + + SkullMeta clone(); +} diff --git a/azurite-api/src/main/java/org/bukkit/map/MapCanvas.java b/azurite-api/src/main/java/org/bukkit/map/MapCanvas.java new file mode 100644 index 0000000..355fac9 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/map/MapCanvas.java @@ -0,0 +1,84 @@ +package org.bukkit.map; + +import java.awt.*; + +/** + * Represents a canvas for drawing to a map. Each canvas is associated with a + * specific {@link MapRenderer} and represents that renderer's layer on the + * map. + */ +public interface MapCanvas { + + /** + * Get the map this canvas is attached to. + * + * @return The MapView this canvas is attached to. + */ + MapView getMapView(); + + /** + * Get the cursor collection associated with this canvas. + * + * @return The MapCursorCollection associated with this canvas. + */ + MapCursorCollection getCursors(); + + /** + * Set the cursor collection associated with this canvas. This does not + * usually need to be called since a MapCursorCollection is already + * provided. + * + * @param cursors The MapCursorCollection to associate with this canvas. + */ + void setCursors(MapCursorCollection cursors); + + /** + * Draw a pixel to the canvas. + * + * @param x The x coordinate, from 0 to 127. + * @param y The y coordinate, from 0 to 127. + * @param color The color. See {@link MapPalette}. + */ + void setPixel(int x, int y, byte color); + + /** + * Get a pixel from the canvas. + * + * @param x The x coordinate, from 0 to 127. + * @param y The y coordinate, from 0 to 127. + * @return The color. See {@link MapPalette}. + */ + byte getPixel(int x, int y); + + /** + * Get a pixel from the layers below this canvas. + * + * @param x The x coordinate, from 0 to 127. + * @param y The y coordinate, from 0 to 127. + * @return The color. See {@link MapPalette}. + */ + byte getBasePixel(int x, int y); + + /** + * Draw an image to the map. The image will be clipped if necessary. + * + * @param x The x coordinate of the image. + * @param y The y coordinate of the image. + * @param image The Image to draw. + */ + void drawImage(int x, int y, Image image); + + /** + * Render text to the map using fancy formatting. Newline (\n) characters + * will move down one line and return to the original column, and the text + * color can be changed using sequences such as "§12;", replacing 12 with + * the palette index of the color (see {@link MapPalette}). + * + * @param x The column to start rendering on. + * @param y The row to start rendering on. + * @param font The font to use. + * @param text The formatted text to render. + */ + void drawText(int x, int y, MapFont font, String text); + +} diff --git a/azurite-api/src/main/java/org/bukkit/map/MapCursor.java b/azurite-api/src/main/java/org/bukkit/map/MapCursor.java new file mode 100644 index 0000000..d441d8d --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/map/MapCursor.java @@ -0,0 +1,192 @@ +package org.bukkit.map; + +/** + * Represents a cursor on a map. + */ +public final class MapCursor { + private byte x, y; + private byte direction, type; + private boolean visible; + + /** + * Initialize the map cursor. + * + * @param x The x coordinate, from -128 to 127. + * @param y The y coordinate, from -128 to 127. + * @param direction The facing of the cursor, from 0 to 15. + * @param type The type (color/style) of the map cursor. + * @param visible Whether the cursor is visible by default. + * @deprecated Magic value + */ + @Deprecated + public MapCursor(byte x, byte y, byte direction, byte type, boolean visible) { + this.x = x; + this.y = y; + setDirection(direction); + setRawType(type); + this.visible = visible; + } + + /** + * Get the X position of this cursor. + * + * @return The X coordinate. + */ + public byte getX() { + return x; + } + + /** + * Get the Y position of this cursor. + * + * @return The Y coordinate. + */ + public byte getY() { + return y; + } + + /** + * Get the direction of this cursor. + * + * @return The facing of the cursor, from 0 to 15. + */ + public byte getDirection() { + return direction; + } + + /** + * Get the type of this cursor. + * + * @return The type (color/style) of the map cursor. + */ + public Type getType() { + return Type.byValue(type); + } + + /** + * Get the type of this cursor. + * + * @return The type (color/style) of the map cursor. + * @deprecated Magic value + */ + @Deprecated + public byte getRawType() { + return type; + } + + /** + * Get the visibility status of this cursor. + * + * @return True if visible, false otherwise. + */ + public boolean isVisible() { + return visible; + } + + /** + * Set the X position of this cursor. + * + * @param x The X coordinate. + */ + public void setX(byte x) { + this.x = x; + } + + /** + * Set the Y position of this cursor. + * + * @param y The Y coordinate. + */ + public void setY(byte y) { + this.y = y; + } + + /** + * Set the direction of this cursor. + * + * @param direction The facing of the cursor, from 0 to 15. + */ + public void setDirection(byte direction) { + if (direction < 0 || direction > 15) { + throw new IllegalArgumentException("Direction must be in the range 0-15"); + } + this.direction = direction; + } + + /** + * Set the type of this cursor. + * + * @param type The type (color/style) of the map cursor. + */ + public void setType(Type type) { + setRawType(type.value); + } + + /** + * Set the type of this cursor. + * + * @param type The type (color/style) of the map cursor. + * @deprecated Magic value + */ + @Deprecated + public void setRawType(byte type) { + if (type < 0 || type > 15) { + throw new IllegalArgumentException("Type must be in the range 0-15"); + } + this.type = type; + } + + /** + * Set the visibility status of this cursor. + * + * @param visible True if visible. + */ + public void setVisible(boolean visible) { + this.visible = visible; + } + + /** + * Represents the standard types of map cursors. More may be made + * available by texture packs - the value is used by the client as an + * index in the file './misc/mapicons.png' from minecraft.jar or from a + * texture pack. + */ + public enum Type { + WHITE_POINTER(0), + GREEN_POINTER(1), + RED_POINTER(2), + BLUE_POINTER(3), + WHITE_CROSS(4); + + private byte value; + + Type(int value) { + this.value = (byte) value; + } + + /** + * + * @return the value + * @deprecated Magic value + */ + @Deprecated + public byte getValue() { + return value; + } + + /** + * + * @param value the value + * @return the matching type + * @deprecated Magic value + */ + @Deprecated + public static Type byValue(byte value) { + for (Type t : values()) { + if (t.value == value) return t; + } + return null; + } + } + +} diff --git a/azurite-api/src/main/java/org/bukkit/map/MapCursorCollection.java b/azurite-api/src/main/java/org/bukkit/map/MapCursorCollection.java new file mode 100644 index 0000000..3b22cb4 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/map/MapCursorCollection.java @@ -0,0 +1,96 @@ +package org.bukkit.map; + +import java.util.ArrayList; +import java.util.List; + +/** + * Represents all the map cursors on a {@link MapCanvas}. Like MapCanvas, a + * MapCursorCollection is linked to a specific {@link MapRenderer}. + */ +public final class MapCursorCollection { + private final List cursors = new ArrayList<>(); + + /** + * Get the amount of cursors in this collection. + * + * @return The size of this collection. + */ + public int size() { + return cursors.size(); + } + + /** + * Get a cursor from this collection. + * + * @param index The index of the cursor. + * @return The MapCursor. + */ + public MapCursor getCursor(int index) { + return cursors.get(index); + } + + /** + * Remove a cursor from the collection. + * + * @param cursor The MapCursor to remove. + * @return Whether the cursor was removed successfully. + */ + public boolean removeCursor(MapCursor cursor) { + return cursors.remove(cursor); + } + + /** + * Add a cursor to the collection. + * + * @param cursor The MapCursor to add. + * @return The MapCursor that was passed. + */ + public MapCursor addCursor(MapCursor cursor) { + cursors.add(cursor); + return cursor; + } + + /** + * Add a cursor to the collection. + * + * @param x The x coordinate, from -128 to 127. + * @param y The y coordinate, from -128 to 127. + * @param direction The facing of the cursor, from 0 to 15. + * @return The newly added MapCursor. + */ + public MapCursor addCursor(int x, int y, byte direction) { + return addCursor(x, y, direction, (byte) 0, true); + } + + /** + * Add a cursor to the collection. + * + * @param x The x coordinate, from -128 to 127. + * @param y The y coordinate, from -128 to 127. + * @param direction The facing of the cursor, from 0 to 15. + * @param type The type (color/style) of the map cursor. + * @return The newly added MapCursor. + * @deprecated Magic value + */ + @Deprecated + public MapCursor addCursor(int x, int y, byte direction, byte type) { + return addCursor(x, y, direction, type, true); + } + + /** + * Add a cursor to the collection. + * + * @param x The x coordinate, from -128 to 127. + * @param y The y coordinate, from -128 to 127. + * @param direction The facing of the cursor, from 0 to 15. + * @param type The type (color/style) of the map cursor. + * @param visible Whether the cursor is visible. + * @return The newly added MapCursor. + * @deprecated Magic value + */ + @Deprecated + public MapCursor addCursor(int x, int y, byte direction, byte type, boolean visible) { + return addCursor(new MapCursor((byte) x, (byte) y, direction, type, visible)); + } + +} diff --git a/azurite-api/src/main/java/org/bukkit/map/MapFont.java b/azurite-api/src/main/java/org/bukkit/map/MapFont.java new file mode 100644 index 0000000..ea8f0ea --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/map/MapFont.java @@ -0,0 +1,144 @@ +package org.bukkit.map; + +import java.util.HashMap; + +/** + * Represents a bitmap font drawable to a map. + */ +public class MapFont { + + private final HashMap chars = new HashMap(); + private int height = 0; + protected boolean malleable = true; + + /** + * Set the sprite for a given character. + * + * @param ch The character to set the sprite for. + * @param sprite The CharacterSprite to set. + * @throws IllegalStateException if this font is static. + */ + public void setChar(char ch, CharacterSprite sprite) { + if (!malleable) { + throw new IllegalStateException("this font is not malleable"); + } + + chars.put(ch, sprite); + if (sprite.getHeight() > height) { + height = sprite.getHeight(); + } + } + + /** + * Get the sprite for a given character. + * + * @param ch The character to get the sprite for. + * @return The CharacterSprite associated with the character, or null if + * there is none. + */ + public CharacterSprite getChar(char ch) { + return chars.get(ch); + } + + /** + * Get the width of the given text as it would be rendered using this + * font. + * + * @param text The text. + * @return The width in pixels. + */ + public int getWidth(String text) { + if (!isValid(text)) { + throw new IllegalArgumentException("text contains invalid characters"); + } + + if (text.length() == 0){ + return 0; + } + + int result = 0; + for (int i = 0; i < text.length(); ++i) { + result += chars.get(text.charAt(i)).getWidth(); + } + result += text.length() - 1; // Account for 1px spacing between characters + + return result; + } + + /** + * Get the height of this font. + * + * @return The height of the font. + */ + public int getHeight() { + return height; + } + + /** + * Check whether the given text is valid. + * + * @param text The text. + * @return True if the string contains only defined characters, false + * otherwise. + */ + public boolean isValid(String text) { + for (int i = 0; i < text.length(); ++i) { + char ch = text.charAt(i); + if (ch == '\u00A7' || ch == '\n') continue; + if (chars.get(ch) == null) return false; + } + return true; + } + + /** + * Represents the graphics for a single character in a MapFont. + */ + public static class CharacterSprite { + + private final int width; + private final int height; + private final boolean[] data; + + public CharacterSprite(int width, int height, boolean[] data) { + this.width = width; + this.height = height; + this.data = data; + + if (data.length != width * height) { + throw new IllegalArgumentException("size of data does not match dimensions"); + } + } + + /** + * Get the value of a pixel of the character. + * + * @param row The row, in the range [0,8). + * @param col The column, in the range [0,8). + * @return True if the pixel is solid, false if transparent. + */ + public boolean get(int row, int col) { + if (row < 0 || col < 0 || row >= height || col >= width) return false; + return data[row * width + col]; + } + + /** + * Get the width of the character sprite. + * + * @return The width of the character. + */ + public int getWidth() { + return width; + } + + /** + * Get the height of the character sprite. + * + * @return The height of the character. + */ + public int getHeight() { + return height; + } + + } + +} diff --git a/azurite-api/src/main/java/org/bukkit/map/MapPalette.java b/azurite-api/src/main/java/org/bukkit/map/MapPalette.java new file mode 100644 index 0000000..05c6dd6 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/map/MapPalette.java @@ -0,0 +1,238 @@ +package org.bukkit.map; + +import java.awt.*; +import java.awt.image.BufferedImage; + +/** + * Represents the palette that map items use. + *

+ * These fields are hee base color ranges. Each entry corresponds to four + * colors of varying shades with values entry to entry + 3. + */ +public final class MapPalette { + // Internal mechanisms + private MapPalette() {} + + private static Color c(int r, int g, int b) { + return new Color(r, g, b); + } + + private static double getDistance(Color c1, Color c2) { + double rmean = (c1.getRed() + c2.getRed()) / 2.0; + double r = c1.getRed() - c2.getRed(); + double g = c1.getGreen() - c2.getGreen(); + int b = c1.getBlue() - c2.getBlue(); + double weightR = 2 + rmean / 256.0; + double weightG = 4.0; + double weightB = 2 + (255 - rmean) / 256.0; + return weightR * r * r + weightG * g * g + weightB * b * b; + } + + static final Color[] colors = { + c(0, 0, 0), c(0, 0, 0), c(0, 0, 0), c(0, 0, 0), + c(89, 125, 39), c(109, 153, 48), c(127, 178, 56), c(67, 94, 29), + c(174, 164, 115), c(213, 201, 140), c(247, 233, 163), c(130, 123, 86), + c(140, 140, 140), c(171, 171, 171), c(199, 199, 199), c(105, 105, 105), + c(180, 0, 0), c(220, 0, 0), c(255, 0, 0), c(135, 0, 0), + c(112, 112, 180), c(138, 138, 220), c(160, 160, 255), c(84, 84, 135), + c(117, 117, 117), c(144, 144, 144), c(167, 167, 167), c(88, 88, 88), + c(0, 87, 0), c(0, 106, 0), c(0, 124, 0), c(0, 65, 0), + c(180, 180, 180), c(220, 220, 220), c(255, 255, 255), c(135, 135, 135), + c(115, 118, 129), c(141, 144, 158), c(164, 168, 184), c(86, 88, 97), + c(106, 76, 54), c(130, 94, 66), c(151, 109, 77), c(79, 57, 40), + c(79, 79, 79), c(96, 96, 96), c(112, 112, 112), c(59, 59, 59), + c(45, 45, 180), c(55, 55, 220), c(64, 64, 255), c(33, 33, 135), + c(100, 84, 50), c(123, 102, 62), c(143, 119, 72), c(75, 63, 38), + c(180, 177, 172), c(220, 217, 211), c(255, 252, 245), c(135, 133, 129), + c(152, 89, 36), c(186, 109, 44), c(216, 127, 51), c(114, 67, 27), + c(125, 53, 152), c(153, 65, 186), c(178, 76, 216), c(94, 40, 114), + c(72, 108, 152), c(88, 132, 186), c(102, 153, 216), c(54, 81, 114), + c(161, 161, 36), c(197, 197, 44), c(229, 229, 51), c(121, 121, 27), + c(89, 144, 17), c(109, 176, 21), c(127, 204, 25), c(67, 108, 13), + c(170, 89, 116), c(208, 109, 142), c(242, 127, 165), c(128, 67, 87), + c(53, 53, 53), c(65, 65, 65), c(76, 76, 76), c(40, 40, 40), + c(108, 108, 108), c(132, 132, 132), c(153, 153, 153), c(81, 81, 81), + c(53, 89, 108), c(65, 109, 132), c(76, 127, 153), c(40, 67, 81), + c(89, 44, 125), c(109, 54, 153), c(127, 63, 178), c(67, 33, 94), + c(36, 53, 125), c(44, 65, 153), c(51, 76, 178), c(27, 40, 94), + c(72, 53, 36), c(88, 65, 44), c(102, 76, 51), c(54, 40, 27), + c(72, 89, 36), c(88, 109, 44), c(102, 127, 51), c(54, 67, 27), + c(108, 36, 36), c(132, 44, 44), c(153, 51, 51), c(81, 27, 27), + c(17, 17, 17), c(21, 21, 21), c(25, 25, 25), c(13, 13, 13), + c(176, 168, 54), c(215, 205, 66), c(250, 238, 77), c(132, 126, 40), + c(64, 154, 150), c(79, 188, 183), c(92, 219, 213), c(48, 115, 112), + c(52, 90, 180), c(63, 110, 220), c(74, 128, 255), c(39, 67, 135), + c(0, 153, 40), c(0, 187, 50), c(0, 217, 58), c(0, 114, 30), + c(91, 60, 34), c(111, 74, 42), c(129, 86, 49), c(68, 45, 25), + c(79, 1, 0), c(96, 1, 0), c(112, 2, 0), c(59, 1, 0), + }; + + // Interface + /** + * @deprecated Magic value + */ + @Deprecated + public static final byte TRANSPARENT = 0; + /** + * @deprecated Magic value + */ + @Deprecated + public static final byte LIGHT_GREEN = 4; + /** + * @deprecated Magic value + */ + @Deprecated + public static final byte LIGHT_BROWN = 8; + /** + * @deprecated Magic value + */ + @Deprecated + public static final byte GRAY_1 = 12; + /** + * @deprecated Magic value + */ + @Deprecated + public static final byte RED = 16; + /** + * @deprecated Magic value + */ + @Deprecated + public static final byte PALE_BLUE = 20; + /** + * @deprecated Magic value + */ + @Deprecated + public static final byte GRAY_2 = 24; + /** + * @deprecated Magic value + */ + @Deprecated + public static final byte DARK_GREEN = 28; + /** + * @deprecated Magic value + */ + @Deprecated + public static final byte WHITE = 32; + /** + * @deprecated Magic value + */ + @Deprecated + public static final byte LIGHT_GRAY = 36; + /** + * @deprecated Magic value + */ + @Deprecated + public static final byte BROWN = 40; + /** + * @deprecated Magic value + */ + @Deprecated + public static final byte DARK_GRAY = 44; + /** + * @deprecated Magic value + */ + @Deprecated + public static final byte BLUE = 48; + /** + * @deprecated Magic value + */ + @Deprecated + public static final byte DARK_BROWN = 52; + + /** + * Resize an image to 128x128. + * + * @param image The image to resize. + * @return The resized image. + */ + public static BufferedImage resizeImage(Image image) { + BufferedImage result = new BufferedImage(128, 128, BufferedImage.TYPE_INT_ARGB); + Graphics2D graphics = result.createGraphics(); + graphics.drawImage(image, 0, 0, 128, 128, null); + graphics.dispose(); + return result; + } + + /** + * Convert an Image to a byte[] using the palette. + * + * @param image The image to convert. + * @return A byte[] containing the pixels of the image. + * @deprecated Magic value + */ + @Deprecated + public static byte[] imageToBytes(Image image) { + BufferedImage temp = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB); + Graphics2D graphics = temp.createGraphics(); + graphics.drawImage(image, 0, 0, null); + graphics.dispose(); + + int[] pixels = new int[temp.getWidth() * temp.getHeight()]; + temp.getRGB(0, 0, temp.getWidth(), temp.getHeight(), pixels, 0, temp.getWidth()); + + byte[] result = new byte[temp.getWidth() * temp.getHeight()]; + for (int i = 0; i < pixels.length; i++) { + result[i] = matchColor(new Color(pixels[i], true)); + } + return result; + } + + /** + * Get the index of the closest matching color in the palette to the given + * color. + * + * @param r The red component of the color. + * @param b The blue component of the color. + * @param g The green component of the color. + * @return The index in the palette. + * @deprecated Magic value + */ + @Deprecated + public static byte matchColor(int r, int g, int b) { + return matchColor(new Color(r, g, b)); + } + + /** + * Get the index of the closest matching color in the palette to the given + * color. + * + * @param color The Color to match. + * @return The index in the palette. + * @deprecated Magic value + */ + @Deprecated + public static byte matchColor(Color color) { + if (color.getAlpha() < 128) return 0; + + int index = 0; + double best = -1; + + for (int i = 4; i < colors.length; i++) { + double distance = getDistance(color, colors[i]); + if (distance < best || best == -1) { + best = distance; + index = i; + } + } + + // Minecraft has 143 colors, some of which have negative byte representations + return (byte) (index < 128 ? index : -129 + (index - 127)); + } + + /** + * Get the value of the given color in the palette. + * + * @param index The index in the palette. + * @return The Color of the palette entry. + * @deprecated Magic value + */ + @Deprecated + public static Color getColor(byte index) { + if ((index > -113 && index < 0) || index > 127) { + throw new IndexOutOfBoundsException(); + } else { + // Minecraft has 143 colors, some of which have negative byte representations + return colors[index >= 0 ? index : index + 256]; + } + } +} diff --git a/azurite-api/src/main/java/org/bukkit/map/MapRenderer.java b/azurite-api/src/main/java/org/bukkit/map/MapRenderer.java new file mode 100644 index 0000000..322d0ce --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/map/MapRenderer.java @@ -0,0 +1,56 @@ +package org.bukkit.map; + +import org.bukkit.entity.Player; + +/** + * Represents a renderer for a map. + */ +public abstract class MapRenderer { + + private boolean contextual; + + /** + * Initialize the map renderer base to be non-contextual. See {@link + * #isContextual()}. + */ + public MapRenderer() { + this(false); + } + + /** + * Initialize the map renderer base with the given contextual status. + * + * @param contextual Whether the renderer is contextual. See {@link + * #isContextual()}. + */ + public MapRenderer(boolean contextual) { + this.contextual = contextual; + } + + /** + * Get whether the renderer is contextual, i.e. has different canvases for + * different players. + * + * @return True if contextual, false otherwise. + */ + final public boolean isContextual() { + return contextual; + } + + /** + * Initialize this MapRenderer for the given map. + * + * @param map The MapView being initialized. + */ + public void initialize(MapView map) {} + + /** + * Render to the given map. + * + * @param map The MapView being rendered to. + * @param canvas The canvas to use for rendering. + * @param player The player who triggered the rendering. + */ + abstract public void render(MapView map, MapCanvas canvas, Player player); + +} diff --git a/azurite-api/src/main/java/org/bukkit/map/MapView.java b/azurite-api/src/main/java/org/bukkit/map/MapView.java new file mode 100644 index 0000000..f6acd4f --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/map/MapView.java @@ -0,0 +1,158 @@ +package org.bukkit.map; + +import org.bukkit.World; + +import java.util.List; + +/** + * Represents a map item. + */ +public interface MapView { + + /** + * An enum representing all possible scales a map can be set to. + */ + enum Scale { + CLOSEST(0), + CLOSE(1), + NORMAL(2), + FAR(3), + FARTHEST(4); + + private byte value; + + Scale(int value) { + this.value = (byte) value; + } + + /** + * Get the scale given the raw value. + * + * @param value The raw scale + * @return The enum scale, or null for an invalid input + * @deprecated Magic value + */ + @Deprecated + public static Scale valueOf(byte value) { + switch (value) { + case 0: return CLOSEST; + case 1: return CLOSE; + case 2: return NORMAL; + case 3: return FAR; + case 4: return FARTHEST; + default: return null; + } + } + + /** + * Get the raw value of this scale level. + * + * @return The scale value + * @deprecated Magic value + */ + @Deprecated + public byte getValue() { + return value; + } + } + + /** + * Get the ID of this map item. Corresponds to the damage value of a map + * in an inventory. + * + * @return The ID of the map. + * @deprecated Magic value + */ + @Deprecated + short getId(); + + /** + * Check whether this map is virtual. A map is virtual if its lowermost + * MapRenderer is plugin-provided. + * + * @return Whether the map is virtual. + */ + boolean isVirtual(); + + /** + * Get the scale of this map. + * + * @return The scale of the map. + */ + Scale getScale(); + + /** + * Set the scale of this map. + * + * @param scale The scale to set. + */ + void setScale(Scale scale); + + /** + * Get the center X position of this map. + * + * @return The center X position. + */ + int getCenterX(); + + /** + * Get the center Z position of this map. + * + * @return The center Z position. + */ + int getCenterZ(); + + /** + * Set the center X position of this map. + * + * @param x The center X position. + */ + void setCenterX(int x); + + /** + * Set the center Z position of this map. + * + * @param z The center Z position. + */ + void setCenterZ(int z); + + /** + * Get the world that this map is associated with. Primarily used by the + * internal renderer, but may be used by external renderers. May return + * null if the world the map is associated with is not loaded. + * + * @return The World this map is associated with. + */ + World getWorld(); + + /** + * Set the world that this map is associated with. The world is used by + * the internal renderer, and may also be used by external renderers. + * + * @param world The World to associate this map with. + */ + void setWorld(World world); + + /** + * Get a list of MapRenderers currently in effect. + * + * @return A {@code List} containing each map renderer. + */ + List getRenderers(); + + /** + * Add a renderer to this map. + * + * @param renderer The MapRenderer to add. + */ + void addRenderer(MapRenderer renderer); + + /** + * Remove a renderer from this map. + * + * @param renderer The MapRenderer to remove. + * @return True if the renderer was successfully removed. + */ + boolean removeRenderer(MapRenderer renderer); + +} diff --git a/azurite-api/src/main/java/org/bukkit/map/MinecraftFont.java b/azurite-api/src/main/java/org/bukkit/map/MinecraftFont.java new file mode 100644 index 0000000..9ec8d10 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/map/MinecraftFont.java @@ -0,0 +1,328 @@ +package org.bukkit.map; + +/** + * Represents the built-in Minecraft font. + */ +public class MinecraftFont extends MapFont { + + private static final int spaceSize = 2; + + private static final String fontChars = + " !\"#$%&'()*+,-./0123456789:;<=>?" + + "@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_" + + "'abcdefghijklmnopqrstuvwxyz{|}~\u007F" + + "\u00C7\u00FC\u00E9\u00E2\u00E4\u00E0\u00E5\u00E7" + // Çüéâäàåç + "\u00EA\u00EB\u00E8\u00EF\u00EE\u00EC\u00C4\u00C5" + // êëèïîìÄÅ + "\u00C9\u00E6\u00C6\u00F4\u00F6\u00F2\u00FB\u00F9" + // ÉæÆôöòûù + "\u00FF\u00D6\u00DC\u00F8\u00A3\u00D8\u00D7\u0191" + // ÿÖÜø£Ø×ƒ + "\u00E1\u00ED\u00F3\u00FA\u00F1\u00D1\u00AA\u00BA" + // áíóúñѪº + "\u00BF\u00AE\u00AC\u00BD\u00BC\u00A1\u00AB\u00BB"; // ¿®¬½¼¡«» + + private static final int[][] fontData = new int[][] { + /* null */ {0,0,0,0,0,0,0,0}, + /* 1 */ {126,129,165,129,189,153,129,126}, + /* 2 */ {126,255,219,255,195,231,255,126}, + /* 3 */ {54,127,127,127,62,28,8,0}, + /* 4 */ {8,28,62,127,62,28,8,0}, + /* 5 */ {28,62,28,127,127,62,28,62}, + /* 6 */ {8,8,28,62,127,62,28,62}, + /* 7 */ {0,0,24,60,60,24,0,0}, + /* 8 */ {255,255,231,195,195,231,255,255}, + /* 9 */ {0,60,102,66,66,102,60,0}, + /* 10 */ {255,195,153,189,189,153,195,255}, + /* 11 */ {240,224,240,190,51,51,51,30}, + /* 12 */ {60,102,102,102,60,24,126,24}, + /* 13 */ {252,204,252,12,12,14,15,7}, + /* 14 */ {254,198,254,198,198,230,103,3}, + /* 15 */ {153,90,60,231,231,60,90,153}, + /* 16 */ {1,7,31,127,31,7,1,0}, + /* 17 */ {64,112,124,127,124,112,64,0}, + /* 18 */ {24,60,126,24,24,126,60,24}, + /* 19 */ {102,102,102,102,102,0,102,0}, + /* 20 */ {254,219,219,222,216,216,216,0}, + /* 21 */ {124,198,28,54,54,28,51,30}, + /* 22 */ {0,0,0,0,126,126,126,0}, + /* 23 */ {24,60,126,24,126,60,24,255}, + /* 24 */ {24,60,126,24,24,24,24,0}, + /* 25 */ {24,24,24,24,126,60,24,0}, + /* 26 */ {0,24,48,127,48,24,0,0}, + /* 27 */ {0,12,6,127,6,12,0,0}, + /* 28 */ {0,0,3,3,3,127,0,0}, + /* 29 */ {0,36,102,255,102,36,0,0}, + /* 30 */ {0,24,60,126,255,255,0,0}, + /* 31 */ {0,255,255,126,60,24,0,0}, + /* */ {0,0,0,0,0,0,0,0}, + /* ! */ {1,1,1,1,1,0,1,0}, + /* " */ {10,10,5,0,0,0,0,0}, + /* # */ {10,10,31,10,31,10,10,0}, + /* $ */ {4,30,1,14,16,15,4,0}, + /* % */ {17,9,8,4,2,18,17,0}, + /* & */ {4,10,4,22,13,9,22,0}, + /* ' */ {2,2,1,0,0,0,0,0}, + /* ( */ {12,2,1,1,1,2,12,0}, + /* ) */ {3,4,8,8,8,4,3,0}, + /* * */ {0,0,9,6,9,0,0,0}, + /* + */ {0,4,4,31,4,4,0,0}, + /* , */ {0,0,0,0,0,1,1,1}, + /* - */ {0,0,0,31,0,0,0,0}, + /* . */ {0,0,0,0,0,1,1,0}, + /* / */ {16,8,8,4,2,2,1,0}, + /* 0 */ {14,17,25,21,19,17,14,0}, + /* 1 */ {4,6,4,4,4,4,31,0}, + /* 2 */ {14,17,16,12,2,17,31,0}, + /* 3 */ {14,17,16,12,16,17,14,0}, + /* 4 */ {24,20,18,17,31,16,16,0}, + /* 5 */ {31,1,15,16,16,17,14,0}, + /* 6 */ {12,2,1,15,17,17,14,0}, + /* 7 */ {31,17,16,8,4,4,4,0}, + /* 8 */ {14,17,17,14,17,17,14,0}, + /* 9 */ {14,17,17,30,16,8,6,0}, + /* : */ {0,1,1,0,0,1,1,0}, + /* ; */ {0,1,1,0,0,1,1,1}, + /* < */ {8,4,2,1,2,4,8,0}, + /* = */ {0,0,31,0,0,31,0,0}, + /* > */ {1,2,4,8,4,2,1,0}, + /* ? */ {14,17,16,8,4,0,4,0}, + /* @ */ {30,33,45,45,61,1,30,0}, + /* A */ {14,17,31,17,17,17,17,0}, + /* B */ {15,17,15,17,17,17,15,0}, + /* C */ {14,17,1,1,1,17,14,0}, + /* D */ {15,17,17,17,17,17,15,0}, + /* E */ {31,1,7,1,1,1,31,0}, + /* F */ {31,1,7,1,1,1,1,0}, + /* G */ {30,1,25,17,17,17,14,0}, + /* H */ {17,17,31,17,17,17,17,0}, + /* I */ {7,2,2,2,2,2,7,0}, + /* J */ {16,16,16,16,16,17,14,0}, + /* K */ {17,9,7,9,17,17,17,0}, + /* L */ {1,1,1,1,1,1,31,0}, + /* M */ {17,27,21,17,17,17,17,0}, + /* N */ {17,19,21,25,17,17,17,0}, + /* O */ {14,17,17,17,17,17,14,0}, + /* P */ {15,17,15,1,1,1,1,0}, + /* Q */ {14,17,17,17,17,9,22,0}, + /* R */ {15,17,15,17,17,17,17,0}, + /* S */ {30,1,14,16,16,17,14,0}, + /* T */ {31,4,4,4,4,4,4,0}, + /* U */ {17,17,17,17,17,17,14,0}, + /* V */ {17,17,17,17,10,10,4,0}, + /* W */ {17,17,17,17,21,27,17,0}, + /* X */ {17,10,4,10,17,17,17,0}, + /* Y */ {17,10,4,4,4,4,4,0}, + /* Z */ {31,16,8,4,2,1,31,0}, + /* [ */ {7,1,1,1,1,1,7,0}, + /* \ */ {1,2,2,4,8,8,16,0}, + /* ] */ {7,4,4,4,4,4,7,0}, + /* ^ */ {4,10,17,0,0,0,0,0}, + /* _ */ {0,0,0,0,0,0,0,31}, + /* ` */ {1,1,2,0,0,0,0,0}, + /* a */ {0,0,14,16,30,17,30,0}, + /* b */ {1,1,13,19,17,17,15,0}, + /* c */ {0,0,14,17,1,17,14,0}, + /* d */ {16,16,22,25,17,17,30,0}, + /* e */ {0,0,14,17,31,1,30,0}, + /* f */ {12,2,15,2,2,2,2,0}, + /* g */ {0,0,30,17,17,30,16,15}, + /* h */ {1,1,13,19,17,17,17,0}, + /* i */ {1,0,1,1,1,1,1,0}, + /* j */ {16,0,16,16,16,17,17,14}, + /* k */ {1,1,9,5,3,5,9,0}, + /* l */ {1,1,1,1,1,1,2,0}, + /* m */ {0,0,11,21,21,17,17,0}, + /* n */ {0,0,15,17,17,17,17,0}, + /* o */ {0,0,14,17,17,17,14,0}, + /* p */ {0,0,13,19,17,15,1,1}, + /* q */ {0,0,22,25,17,30,16,16}, + /* r */ {0,0,13,19,1,1,1,0}, + /* s */ {0,0,30,1,14,16,15,0}, + /* t */ {2,2,7,2,2,2,4,0}, + /* u */ {0,0,17,17,17,17,30,0}, + /* v */ {0,0,17,17,17,10,4,0}, + /* w */ {0,0,17,17,21,21,30,0}, + /* x */ {0,0,17,10,4,10,17,0}, + /* y */ {0,0,17,17,17,30,16,15}, + /* z */ {0,0,31,8,4,2,31,0}, + /* { */ {12,2,2,1,2,2,12,0}, + /* | */ {1,1,1,0,1,1,1,0}, + /* } */ {3,4,4,8,4,4,3,0}, + /* ~ */ {38,25,0,0,0,0,0,0}, + /* ⌂ */ {0,0,4,10,17,17,31,0}, + /* Ç */ {14,17,1,1,17,14,16,12}, + /* ü */ {10,0,17,17,17,17,30,0}, + /* é */ {24,0,14,17,31,1,30,0}, + /* â */ {14,17,14,16,30,17,30,0}, + /* ä */ {10,0,14,16,30,17,30,0}, + /* à */ {3,0,14,16,30,17,30,0}, + /* å */ {4,0,14,16,30,17,30,0}, + /* ç */ {0,14,17,1,17,14,16,12}, + /* ê */ {14,17,14,17,31,1,30,0}, + /* ë */ {10,0,14,17,31,1,30,0}, + /* è */ {3,0,14,17,31,1,30,0}, + /* ï */ {5,0,2,2,2,2,2,0}, + /* î */ {14,17,4,4,4,4,4,0}, + /* ì */ {3,0,2,2,2,2,2,0}, + /* Ä */ {17,14,17,31,17,17,17,0}, + /* Å */ {4,0,14,17,31,17,17,0}, + /* É */ {24,0,31,1,7,1,31,0}, + /* æ */ {0,0,10,20,30,5,30,0}, + /* Æ */ {30,5,15,5,5,5,29,0}, + /* ô */ {14,17,14,17,17,17,14,0}, + /* ö */ {10,0,14,17,17,17,14,0}, + /* ò */ {3,0,14,17,17,17,14,0}, + /* û */ {14,17,0,17,17,17,30,0}, + /* ù */ {3,0,17,17,17,17,30,0}, + /* ÿ */ {10,0,17,17,17,30,16,15}, + /* Ö */ {17,14,17,17,17,17,14,0}, + /* Ü */ {17,0,17,17,17,17,14,0}, + /* ø */ {0,0,14,25,21,19,14,4}, + /* £ */ {12,18,2,15,2,2,31,0}, + /* Ø */ {14,17,25,21,19,17,14,0}, + /* × */ {0,0,5,2,5,0,0,0}, + /* ƒ */ {8,20,4,14,4,4,5,2}, + /* á */ {24,0,14,16,30,17,30,0}, + /* í */ {3,0,1,1,1,1,1,0}, + /* ó */ {24,0,14,17,17,17,14,0}, + /* ú */ {24,0,17,17,17,17,30,0}, + /* ñ */ {31,0,15,17,17,17,17,0}, + /* Ñ */ {31,0,17,19,21,25,17,0}, + /* ª */ {14,16,31,30,0,31,0,0}, + /* º */ {14,17,17,14,0,31,0,0}, + /* ¿ */ {4,0,4,2,1,17,14,0}, + /* ® */ {0,30,45,37,43,30,0,0}, + /* ¬ */ {0,0,0,31,16,16,0,0}, + /* ½ */ {17,9,8,4,18,10,25,0}, + /* ¼ */ {17,9,8,4,26,26,17,0}, + /* ¡ */ {0,1,0,1,1,1,1,0}, + /* « */ {0,20,10,5,10,20,0,0}, + /* » */ {0,5,10,20,10,5,0,0}, + /* 176 */ {68,17,68,17,68,17,68,17}, + /* 177 */ {170,85,170,85,170,85,170,85}, + /* 178 */ {219,238,219,119,219,238,219,119}, + /* 179 */ {24,24,24,24,24,24,24,24}, + /* 180 */ {24,24,24,24,31,24,24,24}, + /* 181 */ {24,24,31,24,31,24,24,24}, + /* 182 */ {108,108,108,108,111,108,108,108}, + /* 183 */ {0,0,0,0,127,108,108,108}, + /* 184 */ {0,0,31,24,31,24,24,24}, + /* 185 */ {108,108,111,96,111,108,108,108}, + /* 186 */ {108,108,108,108,108,108,108,108}, + /* 187 */ {0,0,127,96,111,108,108,108}, + /* 188 */ {108,108,111,96,127,0,0,0}, + /* 189 */ {108,108,108,108,127,0,0,0}, + /* 190 */ {24,24,31,24,31,0,0,0}, + /* 191 */ {0,0,0,0,31,24,24,24}, + /* 192 */ {24,24,24,24,248,0,0,0}, + /* 193 */ {24,24,24,24,255,0,0,0}, + /* 194 */ {0,0,0,0,255,24,24,24}, + /* 195 */ {24,24,24,24,248,24,24,24}, + /* 196 */ {0,0,0,0,255,0,0,0}, + /* 197 */ {24,24,24,24,255,24,24,24}, + /* 198 */ {24,24,248,24,248,24,24,24}, + /* 199 */ {108,108,108,108,236,108,108,108}, + /* 200 */ {108,108,236,12,252,0,0,0}, + /* 201 */ {0,0,252,12,236,108,108,108}, + /* 202 */ {108,108,239,0,255,0,0,0}, + /* 203 */ {0,0,255,0,239,108,108,108}, + /* 204 */ {108,108,236,12,236,108,108,108}, + /* 205 */ {0,0,255,0,255,0,0,0}, + /* 206 */ {108,108,239,0,239,108,108,108}, + /* 207 */ {24,24,255,0,255,0,0,0}, + /* 208 */ {108,108,108,108,255,0,0,0}, + /* 209 */ {0,0,255,0,255,24,24,24}, + /* 210 */ {0,0,0,0,255,108,108,108}, + /* 211 */ {108,108,108,108,252,0,0,0}, + /* 212 */ {24,24,248,24,248,0,0,0}, + /* 213 */ {0,0,248,24,248,24,24,24}, + /* 214 */ {0,0,0,0,252,108,108,108}, + /* 215 */ {108,108,108,108,255,108,108,108}, + /* 216 */ {24,24,255,24,255,24,24,24}, + /* 217 */ {24,24,24,24,31,0,0,0}, + /* 218 */ {0,0,0,0,248,24,24,24}, + /* 219 */ {255,255,255,255,255,255,255,255}, + /* 220 */ {0,0,0,0,255,255,255,255}, + /* 221 */ {15,15,15,15,15,15,15,15}, + /* 222 */ {240,240,240,240,240,240,240,240}, + /* 223 */ {255,255,255,255,0,0,0,0}, + /* 224 */ {0,0,110,59,19,59,110,0}, + /* 225 */ {0,30,51,31,51,31,3,3}, + /* 226 */ {0,63,51,3,3,3,3,0}, + /* 227 */ {0,127,54,54,54,54,54,0}, + /* 228 */ {63,51,6,12,6,51,63,0}, + /* 229 */ {0,0,126,27,27,27,14,0}, + /* 230 */ {0,102,102,102,102,62,6,3}, + /* 231 */ {0,110,59,24,24,24,24,0}, + /* 232 */ {63,12,30,51,51,30,12,63}, + /* 233 */ {28,54,99,127,99,54,28,0}, + /* 234 */ {28,54,99,99,54,54,119,0}, + /* 235 */ {56,12,24,62,51,51,30,0}, + /* 236 */ {0,0,126,219,219,126,0,0}, + /* 237 */ {96,48,126,219,219,126,6,3}, + /* 238 */ {28,6,3,31,3,6,28,0}, + /* 239 */ {30,51,51,51,51,51,51,0}, + /* 240 */ {0,63,0,63,0,63,0,0}, + /* 241 */ {12,12,63,12,12,0,63,0}, + /* 242 */ {6,12,24,12,6,0,63,0}, + /* 243 */ {24,12,6,12,24,0,63,0}, + /* 244 */ {112,216,216,24,24,24,24,24}, + /* 245 */ {24,24,24,24,24,27,27,14}, + /* 246 */ {12,12,0,63,0,12,12,0}, + /* 247 */ {0,110,59,0,110,59,0,0}, + /* 248 */ {28,54,54,28,0,0,0,0}, + /* 249 */ {0,0,0,24,24,0,0,0}, + /* 250 */ {0,0,0,0,24,0,0,0}, + /* 251 */ {240,48,48,48,55,54,60,56}, + /* 252 */ {30,54,54,54,54,0,0,0}, + /* 253 */ {14,24,12,6,30,0,0,0}, + /* 254 */ {0,0,60,60,60,60,0,0}, + /* 255 */ {0,0,0,0,0,0,0,0}, + }; + + /** + * A static non-malleable MinecraftFont. + */ + public static final MinecraftFont Font = new MinecraftFont(false); + + /** + * Initialize a new MinecraftFont. + */ + public MinecraftFont() { + this(true); + } + + private MinecraftFont(boolean malleable) { + for (int i = 1; i < fontData.length; ++i) { + char ch = (char) i; + if (i >= 32 && i < 32 + fontChars.length()) { + ch = fontChars.charAt(i - 32); + } + + if (ch == ' ') { + setChar(ch, new CharacterSprite(spaceSize, 8, new boolean[spaceSize * 8])); + continue; + } + + int[] rows = fontData[i]; + int width = 0; + for (int r = 0; r < 8; ++r) { + for (int c = 0; c < 8; ++c) { + if ((rows[r] & (1 << c)) != 0 && c > width) { + width = c; + } + } + } + ++width; + + boolean[] data = new boolean[width * 8]; + for (int r = 0; r < 8; ++r) { + for (int c = 0; c < width; ++c) { + data[r * width + c] = (rows[r] & (1 << c)) != 0; + } + } + + setChar(ch, new CharacterSprite(width, 8, data)); + } + + this.malleable = malleable; + } + +} diff --git a/azurite-api/src/main/java/org/bukkit/material/Attachable.java b/azurite-api/src/main/java/org/bukkit/material/Attachable.java new file mode 100644 index 0000000..e9b95ae --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/Attachable.java @@ -0,0 +1,16 @@ +package org.bukkit.material; + +import org.bukkit.block.BlockFace; + +/** + * Indicates that a block can be attached to another block + */ +public interface Attachable extends Directional { + + /** + * Gets the face that this block is attached on + * + * @return BlockFace attached to + */ + BlockFace getAttachedFace(); +} diff --git a/azurite-api/src/main/java/org/bukkit/material/Banner.java b/azurite-api/src/main/java/org/bukkit/material/Banner.java new file mode 100644 index 0000000..80a7616 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/Banner.java @@ -0,0 +1,235 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +public class Banner extends MaterialData implements Attachable { + + public Banner() { + super(Material.BANNER); + } + + public Banner(Material type) { + super(type); + } + + /** + * @param type the raw type id + * @deprecated Magic value + */ + @Deprecated + public Banner(int type) { + super(type); + } + + /** + * + * @param type the type + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Banner(Material type, byte data) { + super(type, data); + } + + /** * + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Banner(int type, byte data) { + super(type, data); + } + + public boolean isWallBanner() { + return getItemType() == Material.WALL_BANNER; + } + + public BlockFace getAttachedFace() { + if (isWallBanner()) { + byte data = getData(); + + switch (data) { + case 0x2: + return BlockFace.SOUTH; + + case 0x3: + return BlockFace.NORTH; + + case 0x4: + return BlockFace.EAST; + + case 0x5: + return BlockFace.WEST; + } + + return null; + } else { + return BlockFace.DOWN; + } + } + + public BlockFace getFacing() { + byte data = getData(); + + if (!isWallBanner()) { + switch (data) { + case 0x0: + return BlockFace.SOUTH; + + case 0x1: + return BlockFace.SOUTH_SOUTH_WEST; + + case 0x2: + return BlockFace.SOUTH_WEST; + + case 0x3: + return BlockFace.WEST_SOUTH_WEST; + + case 0x4: + return BlockFace.WEST; + + case 0x5: + return BlockFace.WEST_NORTH_WEST; + + case 0x6: + return BlockFace.NORTH_WEST; + + case 0x7: + return BlockFace.NORTH_NORTH_WEST; + + case 0x8: + return BlockFace.NORTH; + + case 0x9: + return BlockFace.NORTH_NORTH_EAST; + + case 0xA: + return BlockFace.NORTH_EAST; + + case 0xB: + return BlockFace.EAST_NORTH_EAST; + + case 0xC: + return BlockFace.EAST; + + case 0xD: + return BlockFace.EAST_SOUTH_EAST; + + case 0xE: + return BlockFace.SOUTH_EAST; + + case 0xF: + return BlockFace.SOUTH_SOUTH_EAST; + } + + return null; + } else { + return getAttachedFace().getOppositeFace(); + } + } + + public void setFacingDirection(BlockFace face) { + byte data; + + if (isWallBanner()) { + switch (face) { + case NORTH: + data = 0x2; + break; + + case SOUTH: + data = 0x3; + break; + + case WEST: + data = 0x4; + break; + + case EAST: + default: + data = 0x5; + } + } else { + switch (face) { + case SOUTH: + data = 0x0; + break; + + case SOUTH_SOUTH_WEST: + data = 0x1; + break; + + case SOUTH_WEST: + data = 0x2; + break; + + case WEST_SOUTH_WEST: + data = 0x3; + break; + + case WEST: + data = 0x4; + break; + + case WEST_NORTH_WEST: + data = 0x5; + break; + + case NORTH_WEST: + data = 0x6; + break; + + case NORTH_NORTH_WEST: + data = 0x7; + break; + + case NORTH: + data = 0x8; + break; + + case NORTH_NORTH_EAST: + data = 0x9; + break; + + case NORTH_EAST: + data = 0xA; + break; + + case EAST_NORTH_EAST: + data = 0xB; + break; + + case EAST: + data = 0xC; + break; + + case EAST_SOUTH_EAST: + data = 0xD; + break; + + case SOUTH_SOUTH_EAST: + data = 0xF; + break; + + case SOUTH_EAST: + default: + data = 0xE; + } + } + + setData(data); + } + + @Override + public String toString() { + return super.toString() + " facing " + getFacing(); + } + + @Override + public Banner clone() { + return (Banner) super.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/Bed.java b/azurite-api/src/main/java/org/bukkit/material/Bed.java new file mode 100644 index 0000000..ce94daf --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/Bed.java @@ -0,0 +1,145 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +/** + * Represents a bed. + */ +public class Bed extends MaterialData implements Directional { + + /** + * Default constructor for a bed. + */ + public Bed() { + super(Material.BED_BLOCK); + } + + /** + * Instantiate a bed facing in a particular direction. + * + * @param direction the direction the bed's head is facing + */ + public Bed(BlockFace direction) { + this(); + setFacingDirection(direction); + } + + /** + * + * @param type the raw type id + * @deprecated Magic value + */ + @Deprecated + public Bed(final int type) { + super(type); + } + + public Bed(final Material type) { + super(type); + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Bed(final int type, final byte data) { + super(type, data); + } + + /** + * @param type the type + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Bed(final Material type, final byte data) { + super(type, data); + } + + /** + * Determine if this block represents the head of the bed + * + * @return true if this is the head of the bed, false if it is the foot + */ + public boolean isHeadOfBed() { + return (getData() & 0x8) == 0x8; + } + + /** + * Configure this to be either the head or the foot of the bed + * + * @param isHeadOfBed True to make it the head. + */ + public void setHeadOfBed(boolean isHeadOfBed) { + setData((byte) (isHeadOfBed ? (getData() | 0x8) : (getData() & ~0x8))); + } + + /** + * Set which direction the head of the bed is facing. Note that this will + * only affect one of the two blocks the bed is made of. + */ + public void setFacingDirection(BlockFace face) { + byte data; + + switch (face) { + case SOUTH: + data = 0x0; + break; + + case WEST: + data = 0x1; + break; + + case NORTH: + data = 0x2; + break; + + case EAST: + default: + data = 0x3; + } + + if (isHeadOfBed()) { + data |= 0x8; + } + + setData(data); + } + + /** + * Get the direction that this bed's head is facing toward + * + * @return the direction the head of the bed is facing + */ + public BlockFace getFacing() { + byte data = (byte) (getData() & 0x7); + + switch (data) { + case 0x0: + return BlockFace.SOUTH; + + case 0x1: + return BlockFace.WEST; + + case 0x2: + return BlockFace.NORTH; + + case 0x3: + default: + return BlockFace.EAST; + } + } + + @Override + public String toString() { + return (isHeadOfBed() ? "HEAD" : "FOOT") + " of " + super.toString() + " facing " + getFacing(); + } + + @Override + public Bed clone() { + return (Bed) super.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/Button.java b/azurite-api/src/main/java/org/bukkit/material/Button.java new file mode 100644 index 0000000..186d146 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/Button.java @@ -0,0 +1,142 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +/** + * Represents a button + */ +public class Button extends SimpleAttachableMaterialData implements Redstone { + public Button() { + super(Material.STONE_BUTTON); + } + + /** + * @param type the type + * @deprecated Magic value + */ + @Deprecated + public Button(final int type) { + super(type); + } + + public Button(final Material type) { + super(type); + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Button(final int type, final byte data) { + super(type, data); + } + + /** + * @param type the type + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Button(final Material type, final byte data) { + super(type, data); + } + + /** + * Gets the current state of this Material, indicating if it's powered or + * unpowered + * + * @return true if powered, otherwise false + */ + public boolean isPowered() { + return (getData() & 0x8) == 0x8; + } + + /** + * Sets the current state of this button + * + * @param bool + * whether or not the button is powered + */ + public void setPowered(boolean bool) { + setData((byte) (bool ? (getData() | 0x8) : (getData() & ~0x8))); + } + + /** + * Gets the face that this block is attached on + * + * @return BlockFace attached to + */ + public BlockFace getAttachedFace() { + byte data = (byte) (getData() & 0x7); + + switch (data) { + case 0x0: + return BlockFace.UP; + + case 0x1: + return BlockFace.WEST; + + case 0x2: + return BlockFace.EAST; + + case 0x3: + return BlockFace.NORTH; + + case 0x4: + return BlockFace.SOUTH; + + case 0x5: + return BlockFace.DOWN; + } + + return null; + } + + /** + * Sets the direction this button is pointing toward + */ + public void setFacingDirection(BlockFace face) { + byte data = (byte) (getData() & 0x8); + + switch (face) { + case DOWN: + data |= 0x0; + break; + + case EAST: + data |= 0x1; + break; + + case WEST: + data |= 0x2; + break; + + case SOUTH: + data |= 0x3; + break; + + case NORTH: + data |= 0x4; + break; + + case UP: + data |= 0x5; + break; + } + + setData(data); + } + + @Override + public String toString() { + return super.toString() + " " + (isPowered() ? "" : "NOT ") + "POWERED"; + } + + @Override + public Button clone() { + return (Button) super.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/Cake.java b/azurite-api/src/main/java/org/bukkit/material/Cake.java new file mode 100644 index 0000000..e72cb91 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/Cake.java @@ -0,0 +1,93 @@ +package org.bukkit.material; + +import org.bukkit.Material; + +public class Cake extends MaterialData { + public Cake() { + super(Material.CAKE_BLOCK); + } + + /** + * @param type the raw type id + * @deprecated Magic value + */ + @Deprecated + public Cake(int type) { + super(type); + } + + public Cake(Material type) { + super(type); + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Cake(int type, byte data) { + super(type, data); + } + + /** + * @param type the type + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Cake(Material type, byte data) { + super(type, data); + } + + /** + * Gets the number of slices eaten from this cake + * + * @return The number of slices eaten + */ + public int getSlicesEaten() { + return getData(); + } + + /** + * Gets the number of slices remaining on this cake + * + * @return The number of slices remaining + */ + public int getSlicesRemaining() { + return 6 - getData(); + } + + /** + * Sets the number of slices eaten from this cake + * + * @param n The number of slices eaten + */ + public void setSlicesEaten(int n) { + if (n < 6) { + setData((byte) n); + } // TODO: else destroy the block? Probably not possible though + } + + /** + * Sets the number of slices remaining on this cake + * + * @param n The number of slices remaining + */ + public void setSlicesRemaining(int n) { + if (n > 6) { + n = 6; + } + setData((byte) (6 - n)); + } + + @Override + public String toString() { + return super.toString() + " " + getSlicesEaten() + "/" + getSlicesRemaining() + " slices eaten/remaining"; + } + + @Override + public Cake clone() { + return (Cake) super.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/Cauldron.java b/azurite-api/src/main/java/org/bukkit/material/Cauldron.java new file mode 100644 index 0000000..0ead402 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/Cauldron.java @@ -0,0 +1,64 @@ +package org.bukkit.material; + +import org.bukkit.Material; + +/** + * Represents a cauldron + */ +public class Cauldron extends MaterialData { + private static final int CAULDRON_FULL = 3; + private static final int CAULDRON_EMPTY = 0; + + public Cauldron() { + super(Material.CAULDRON); + } + + /** + * + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Cauldron(int type, byte data){ + super(type, data); + } + + /** + * + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Cauldron(byte data) { + super(Material.CAULDRON, data); + } + + /** + * Check if the cauldron is full. + * + * @return True if it is full. + */ + public boolean isFull() { + return getData() >= CAULDRON_FULL; + } + + /** + * Check if the cauldron is empty. + * + * @return True if it is empty. + */ + public boolean isEmpty() { + return getData() <= CAULDRON_EMPTY; + } + + @Override + public String toString() { + return (isEmpty() ? "EMPTY" : (isFull() ? "FULL" : getData() + "/3 FULL")) + " CAULDRON"; + } + + @Override + public Cauldron clone() { + return (Cauldron) super.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/Chest.java b/azurite-api/src/main/java/org/bukkit/material/Chest.java new file mode 100644 index 0000000..0db8aa5 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/Chest.java @@ -0,0 +1,62 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +/** + * Represents a chest + */ +public class Chest extends DirectionalContainer { + + public Chest() { + super(Material.CHEST); + } + + /** + * Instantiate a chest facing in a particular direction. + * + * @param direction the direction the chest's lit opens towards + */ + public Chest(BlockFace direction) { + this(); + setFacingDirection(direction); + } + + /** + * @param type the raw type id + * @deprecated Magic value + */ + @Deprecated + public Chest(final int type) { + super(type); + } + + public Chest(final Material type) { + super(type); + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Chest(final int type, final byte data) { + super(type, data); + } + + /** + * @param type the type + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Chest(final Material type, final byte data) { + super(type, data); + } + + @Override + public Chest clone() { + return (Chest) super.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/Coal.java b/azurite-api/src/main/java/org/bukkit/material/Coal.java new file mode 100644 index 0000000..dd940b6 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/Coal.java @@ -0,0 +1,79 @@ +package org.bukkit.material; + +import org.bukkit.CoalType; +import org.bukkit.Material; + +/** + * Represents the different types of coals. + */ +public class Coal extends MaterialData { + public Coal() { + super(Material.COAL); + } + + public Coal(CoalType type) { + this(); + setType(type); + } + + /** + * @param type the raw type id + * @deprecated Magic value + */ + @Deprecated + public Coal(final int type) { + super(type); + } + + public Coal(final Material type) { + super(type); + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Coal(final int type, final byte data) { + super(type, data); + } + + /** + * @param type the type + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Coal(final Material type, final byte data) { + super(type, data); + } + + /** + * Gets the current type of this coal + * + * @return CoalType of this coal + */ + public CoalType getType() { + return CoalType.getByData(getData()); + } + + /** + * Sets the type of this coal + * + * @param type New type of this coal + */ + public void setType(CoalType type) { + setData(type.getData()); + } + + @Override + public String toString() { + return getType() + " " + super.toString(); + } + + @Override + public Coal clone() { + return (Coal) super.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/CocoaPlant.java b/azurite-api/src/main/java/org/bukkit/material/CocoaPlant.java new file mode 100644 index 0000000..6dede93 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/CocoaPlant.java @@ -0,0 +1,133 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +/** + * Represents the cocoa plant + */ +public class CocoaPlant extends MaterialData implements Directional, Attachable { + + public enum CocoaPlantSize { + SMALL, + MEDIUM, + LARGE + } + + public CocoaPlant() { + super(Material.COCOA); + } + + /** + * @param type the raw type id + * @deprecated Magic value + */ + @Deprecated + public CocoaPlant(final int type) { + super(type); + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public CocoaPlant(final int type, final byte data) { + super(type, data); + } + + public CocoaPlant(CocoaPlantSize sz) { + this(); + setSize(sz); + } + + public CocoaPlant(CocoaPlantSize sz, BlockFace dir) { + this(); + setSize(sz); + setFacingDirection(dir); + } + + /** + * Get size of plant + * + * @return size + */ + public CocoaPlantSize getSize() { + switch (getData() & 0xC) { + case 0: + return CocoaPlantSize.SMALL; + case 4: + return CocoaPlantSize.MEDIUM; + default: + return CocoaPlantSize.LARGE; + } + } + + /** + * Set size of plant + * + * @param sz - size of plant + */ + public void setSize(CocoaPlantSize sz) { + int dat = getData() & 0x3; + switch (sz) { + case SMALL: + break; + case MEDIUM: + dat |= 0x4; + break; + case LARGE: + dat |= 0x8; + break; + } + setData((byte) dat); + } + + public BlockFace getAttachedFace() { + return getFacing().getOppositeFace(); + } + + public void setFacingDirection(BlockFace face) { + int dat = getData() & 0xC; + switch (face) { + default: + case SOUTH: + break; + case WEST: + dat |= 0x1; + break; + case NORTH: + dat |= 0x2; + break; + case EAST: + dat |= 0x3; + break; + } + setData((byte) dat); + } + + public BlockFace getFacing() { + switch (getData() & 0x3) { + case 0: + return BlockFace.SOUTH; + case 1: + return BlockFace.WEST; + case 2: + return BlockFace.NORTH; + case 3: + return BlockFace.EAST; + } + return null; + } + + @Override + public CocoaPlant clone() { + return (CocoaPlant) super.clone(); + } + + @Override + public String toString() { + return super.toString() + " facing " + getFacing() + " " + getSize(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/Colorable.java b/azurite-api/src/main/java/org/bukkit/material/Colorable.java new file mode 100644 index 0000000..2fe9e77 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/Colorable.java @@ -0,0 +1,24 @@ +package org.bukkit.material; + +import org.bukkit.DyeColor; + +/** + * An object that can be colored. + */ +public interface Colorable { + + /** + * Gets the color of this object. + * + * @return The DyeColor of this object. + */ + DyeColor getColor(); + + /** + * Sets the color of this object to the specified DyeColor. + * + * @param color The color of the object, as a DyeColor. + */ + void setColor(DyeColor color); + +} diff --git a/azurite-api/src/main/java/org/bukkit/material/Command.java b/azurite-api/src/main/java/org/bukkit/material/Command.java new file mode 100644 index 0000000..b484229 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/Command.java @@ -0,0 +1,75 @@ +package org.bukkit.material; + +import org.bukkit.Material; + +/** + * Represents a command block + */ +public class Command extends MaterialData implements Redstone { + public Command() { + super(Material.COMMAND); + } + + /** + * @param type the raw type id + * @deprecated Magic value + */ + @Deprecated + public Command(final int type) { + super(type); + } + + public Command(final Material type) { + super(type); + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Command(final int type, final byte data) { + super(type, data); + } + + /** + * @param type the type + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Command(final Material type, final byte data) { + super(type, data); + } + + /** + * Gets the current state of this Material, indicating if it's powered or + * unpowered + * + * @return true if powered, otherwise false + */ + public boolean isPowered() { + return (getData() & 1) != 0; + } + + /** + * Sets the current state of this Material + * + * @param bool + * whether or not the command block is powered + */ + public void setPowered(boolean bool) { + setData((byte) (bool ? (getData() | 1) : (getData() & -2))); + } + + @Override + public String toString() { + return super.toString() + " " + (isPowered() ? "" : "NOT ") + "POWERED"; + } + + @Override + public Command clone() { + return (Command) super.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/Crops.java b/azurite-api/src/main/java/org/bukkit/material/Crops.java new file mode 100644 index 0000000..0a4f8f1 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/Crops.java @@ -0,0 +1,79 @@ +package org.bukkit.material; + +import org.bukkit.CropState; +import org.bukkit.Material; + +/** + * Represents the different types of crops. + */ +public class Crops extends MaterialData { + public Crops() { + super(Material.CROPS); + } + + public Crops(CropState state) { + this(); + setState(state); + } + + /** + * @param type the raw type id + * @deprecated Magic value + */ + @Deprecated + public Crops(final int type) { + super(type); + } + + public Crops(final Material type) { + super(type); + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Crops(final int type, final byte data) { + super(type, data); + } + + /** + * @param type the type + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Crops(final Material type, final byte data) { + super(type, data); + } + + /** + * Gets the current growth state of this crop + * + * @return CropState of this crop + */ + public CropState getState() { + return CropState.getByData(getData()); + } + + /** + * Sets the growth state of this crop + * + * @param state New growth state of this crop + */ + public void setState(CropState state) { + setData(state.getData()); + } + + @Override + public String toString() { + return getState() + " " + super.toString(); + } + + @Override + public Crops clone() { + return (Crops) super.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/DetectorRail.java b/azurite-api/src/main/java/org/bukkit/material/DetectorRail.java new file mode 100644 index 0000000..652a4b5 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/DetectorRail.java @@ -0,0 +1,58 @@ +package org.bukkit.material; + +import org.bukkit.Material; + +/** + * Represents a detector rail + */ +public class DetectorRail extends ExtendedRails implements PressureSensor { + public DetectorRail() { + super(Material.DETECTOR_RAIL); + } + + /** + * @param type the raw type id + * @deprecated Magic value + */ + @Deprecated + public DetectorRail(final int type) { + super(type); + } + + public DetectorRail(final Material type) { + super(type); + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public DetectorRail(final int type, final byte data) { + super(type, data); + } + + /** + * @param type the type + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public DetectorRail(final Material type, final byte data) { + super(type, data); + } + + public boolean isPressed() { + return (getData() & 0x8) == 0x8; + } + + public void setPressed(boolean isPressed) { + setData((byte) (isPressed ? (getData() | 0x8) : (getData() & ~0x8))); + } + + @Override + public DetectorRail clone() { + return (DetectorRail) super.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/Diode.java b/azurite-api/src/main/java/org/bukkit/material/Diode.java new file mode 100644 index 0000000..fbfacc0 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/Diode.java @@ -0,0 +1,125 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +public class Diode extends MaterialData implements Directional { + public Diode() { + super(Material.DIODE_BLOCK_ON); + } + + /** + * @param type the raw type id + * @deprecated Magic value + */ + @Deprecated + public Diode(int type) { + super(type); + } + + public Diode(Material type) { + super(type); + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Diode(int type, byte data) { + super(type, data); + } + + /** + * @param type the type + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Diode(Material type, byte data) { + super(type, data); + } + + /** + * Sets the delay of the repeater + * + * @param delay + * The new delay (1-4) + */ + public void setDelay(int delay) { + if (delay > 4) { + delay = 4; + } + if (delay < 1) { + delay = 1; + } + byte newData = (byte) (getData() & 0x3); + + setData((byte) (newData | ((delay - 1) << 2))); + } + + /** + * Gets the delay of the repeater in ticks + * + * @return The delay (1-4) + */ + public int getDelay() { + return (getData() >> 2) + 1; + } + + public void setFacingDirection(BlockFace face) { + int delay = getDelay(); + byte data; + + switch (face) { + case EAST: + data = 0x1; + break; + + case SOUTH: + data = 0x2; + break; + + case WEST: + data = 0x3; + break; + + case NORTH: + default: + data = 0x0; + } + + setData(data); + setDelay(delay); + } + + public BlockFace getFacing() { + byte data = (byte) (getData() & 0x3); + + switch (data) { + case 0x0: + default: + return BlockFace.NORTH; + + case 0x1: + return BlockFace.EAST; + + case 0x2: + return BlockFace.SOUTH; + + case 0x3: + return BlockFace.WEST; + } + } + + @Override + public String toString() { + return super.toString() + " facing " + getFacing() + " with " + getDelay() + " ticks delay"; + } + + @Override + public Diode clone() { + return (Diode) super.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/Directional.java b/azurite-api/src/main/java/org/bukkit/material/Directional.java new file mode 100644 index 0000000..2ad9bbc --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/Directional.java @@ -0,0 +1,20 @@ +package org.bukkit.material; + +import org.bukkit.block.BlockFace; + +public interface Directional { + + /** + * Sets the direction that this block is facing in + * + * @param face The facing direction + */ + void setFacingDirection(BlockFace face); + + /** + * Gets the direction this block is facing + * + * @return the direction this block is facing + */ + BlockFace getFacing(); +} diff --git a/azurite-api/src/main/java/org/bukkit/material/DirectionalContainer.java b/azurite-api/src/main/java/org/bukkit/material/DirectionalContainer.java new file mode 100644 index 0000000..b56f098 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/DirectionalContainer.java @@ -0,0 +1,95 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +/** + * Represents a furnace or a dispenser. + */ +public class DirectionalContainer extends MaterialData implements Directional { + /** + * @param type the raw type id + * @deprecated Magic value + */ + @Deprecated + public DirectionalContainer(final int type) { + super(type); + } + + public DirectionalContainer(final Material type) { + super(type); + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public DirectionalContainer(final int type, final byte data) { + super(type, data); + } + + /** + * @param type the type + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public DirectionalContainer(final Material type, final byte data) { + super(type, data); + } + + public void setFacingDirection(BlockFace face) { + byte data; + + switch (face) { + case NORTH: + data = 0x2; + break; + + case SOUTH: + data = 0x3; + break; + + case WEST: + data = 0x4; + break; + + case EAST: + default: + data = 0x5; + } + + setData(data); + } + + public BlockFace getFacing() { + byte data = getData(); + + switch (data) { + case 0x2: + return BlockFace.NORTH; + + case 0x3: + return BlockFace.SOUTH; + + case 0x4: + return BlockFace.WEST; + + case 0x5: + default: + return BlockFace.EAST; + } + } + + @Override + public String toString() { + return super.toString() + " facing " + getFacing(); + } + + @Override + public DirectionalContainer clone() { + return (DirectionalContainer) super.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/Dispenser.java b/azurite-api/src/main/java/org/bukkit/material/Dispenser.java new file mode 100644 index 0000000..988407c --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/Dispenser.java @@ -0,0 +1,114 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +/** + * Represents a dispenser. + */ +public class Dispenser extends FurnaceAndDispenser { + + public Dispenser() { + super(Material.DISPENSER); + } + + public Dispenser(BlockFace direction) { + this(); + setFacingDirection(direction); + } + + /** + * @param type the raw type id + * @deprecated Magic value + */ + @Deprecated + public Dispenser(final int type) { + super(type); + } + + public Dispenser(final Material type) { + super(type); + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Dispenser(final int type, final byte data) { + super(type, data); + } + + /** + * @param type the type + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Dispenser(final Material type, final byte data) { + super(type, data); + } + + public void setFacingDirection(BlockFace face) { + byte data; + + switch (face) { + case DOWN: + data = 0x0; + break; + + case UP: + data = 0x1; + break; + + case NORTH: + data = 0x2; + break; + + case SOUTH: + data = 0x3; + break; + + case WEST: + data = 0x4; + break; + + case EAST: + default: + data = 0x5; + } + + setData(data); + } + + public BlockFace getFacing() { + int data = getData() & 0x7; + + switch (data) { + case 0x0: + return BlockFace.DOWN; + + case 0x1: + return BlockFace.UP; + + case 0x2: + return BlockFace.NORTH; + + case 0x3: + return BlockFace.SOUTH; + + case 0x4: + return BlockFace.WEST; + + case 0x5: + default: + return BlockFace.EAST; + } + } + + @Override + public Dispenser clone() { + return (Dispenser) super.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/Door.java b/azurite-api/src/main/java/org/bukkit/material/Door.java new file mode 100644 index 0000000..e02d8e6 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/Door.java @@ -0,0 +1,338 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.TreeSpecies; +import org.bukkit.block.BlockFace; + +/** + * Represents a door. + * + * This class was previously deprecated, but has been retrofitted to + * work with modern doors. Some methods are undefined dependant on isTopHalf() + * due to Minecraft's internal representation of doors. + * + * @see Material.WOODEN_DOOR + * @see Material.IRON_DOOR_BLOCK + * @see Material.SPRUCE_DOOR + * @see Material.BIRCH_DOOR + * @see Material.JUNGLE_DOOR + * @see Material.ACACIA_DOOR + * @see Material.DARK_OAK_DOOR + */ +public class Door extends MaterialData implements Directional, Openable { + + // This class breaks API contracts on Directional and Openable because + // of the way doors are currently implemented. Beware! + + /** + * @deprecated Artifact of old API, equivalent to new Door(Material.WOODEN_DOOR); + */ + @Deprecated + public Door() { + super(Material.WOODEN_DOOR); + } + + /** + * @param type the raw type id + * @deprecated Magic value + */ + @Deprecated + public Door(final int type) { + super(type); + } + + public Door(final Material type) { + super(type); + } + + /** + * Constructs the bottom half of a door of the given material type, facing the specified direction and set to closed + * + * @param type The type of material this door is made of. This must match the type of the block above. + * @param face The direction the door is facing. + * + * @see Material.WOODEN_DOOR + * @see Material.IRON_DOOR_BLOCK + * @see Material.SPRUCE_DOOR + * @see Material.BIRCH_DOOR + * @see Material.JUNGLE_DOOR + * @see Material.ACACIA_DOOR + * @see Material.DARK_OAK_DOOR + * + * @see BlockFace.WEST + * @see BlockFace.NORTH + * @see BlockFace.EAST + * @see BlockFace.SOUTH + */ + public Door(final Material type, BlockFace face) { + this(type, face, false); + } + + /** + * Constructs the bottom half of a door of the given material type, facing the specified direction and set to open + * or closed + * + * @param type The type of material this door is made of. This must match the type of the block above. + * @param face The direction the door is facing. + * @param isOpen Whether the door is currently opened. + * + * @see Material.WOODEN_DOOR + * @see Material.IRON_DOOR_BLOCK + * @see Material.SPRUCE_DOOR + * @see Material.BIRCH_DOOR + * @see Material.JUNGLE_DOOR + * @see Material.ACACIA_DOOR + * @see Material.DARK_OAK_DOOR + * + * @see BlockFace.WEST + * @see BlockFace.NORTH + * @see BlockFace.EAST + * @see BlockFace.SOUTH + */ + public Door(final Material type, BlockFace face, boolean isOpen) { + super(type); + setTopHalf(false); + setFacingDirection(face); + setOpen(isOpen); + } + + /** + * Constructs the top half of door of the given material type and with the hinge on the left or right + * + * @param type The type of material this door is made of. This must match the type of the block below. + * @param isHingeRight True if the hinge is on the right hand side, false if the hinge is on the left hand side. + * + * @see Material.WOODEN_DOOR + * @see Material.IRON_DOOR_BLOCK + * @see Material.SPRUCE_DOOR + * @see Material.BIRCH_DOOR + * @see Material.JUNGLE_DOOR + * @see Material.ACACIA_DOOR + * @see Material.DARK_OAK_DOOR + */ + public Door(final Material type, boolean isHingeRight) { + super(type); + setTopHalf(true); + setHinge(isHingeRight); + } + + /** + * Constructs the bottom half of a wooden door of the given species, facing the specified direction and set to + * closed + * + * @param species The species this wooden door is made of. This must match the species of the block above. + * @param face The direction the door is facing. + * + * @see TreeSpecies + * + * @see BlockFace.WEST + * @see BlockFace.NORTH + * @see BlockFace.EAST + * @see BlockFace.SOUTH + */ + public Door(final TreeSpecies species, BlockFace face) { + this(getWoodDoorOfSpecies(species), face, false); + } + + /** + * Constructs the bottom half of a wooden door of the given species, facing the specified direction and set to open + * or closed + * + * @param species The species this wooden door is made of. This must match the species of the block above. + * @param face The direction the door is facing. + * @param isOpen Whether the door is currently opened. + * + * @see TreeSpecies + * + * @see BlockFace.WEST + * @see BlockFace.NORTH + * @see BlockFace.EAST + * @see BlockFace.SOUTH + */ + public Door(final TreeSpecies species, BlockFace face, boolean isOpen) { + this(getWoodDoorOfSpecies(species), face, isOpen); + } + + /** + * Constructs the top half of a wooden door of the given species and with the hinge on the left or right + * + * @param species The species this wooden door is made of. This must match the species of the block below. + * @param isHingeRight True if the hinge is on the right hand side, false if the hinge is on the left hand side. + * + * @see TreeSpecies + */ + public Door(final TreeSpecies species, boolean isHingeRight) { + this(getWoodDoorOfSpecies(species), isHingeRight); + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Door(final int type, final byte data) { + super(type, data); + } + + /** + * @param type the type + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Door(final Material type, final byte data) { + super(type, data); + } + + /** + * Returns the item type of a wooden door for the given tree species. + * + * @param species The species of wood door required. + * @return The item type for the given species. + * + * @see Material.WOODEN_DOOR + * @see Material.SPRUCE_DOOR + * @see Material.BIRCH_DOOR + * @see Material.JUNGLE_DOOR + * @see Material.ACACIA_DOOR + * @see Material.DARK_OAK_DOOR + */ + public static Material getWoodDoorOfSpecies(TreeSpecies species) { + switch (species) { + default: + case GENERIC: + return Material.WOODEN_DOOR; + case BIRCH: + return Material.BIRCH_DOOR; + case REDWOOD: + return Material.SPRUCE_DOOR; + case JUNGLE: + return Material.JUNGLE_DOOR; + case ACACIA: + return Material.ACACIA_DOOR; + case DARK_OAK: + return Material.DARK_OAK_DOOR; + } + } + + /** + * Result is undefined if isTopHalf() is true. + */ + public boolean isOpen() { + return ((getData() & 0x4) == 0x4); + } + + /** + * Set whether the door is open. Undefined if isTopHalf() is true. + */ + public void setOpen(boolean isOpen) { + setData((byte) (isOpen ? (getData() | 0x4) : (getData() & ~0x4))); + } + + /** + * @return whether this is the top half of the door + */ + public boolean isTopHalf() { + return ((getData() & 0x8) == 0x8); + } + + /** + * Configure this part of the door to be either the top or the bottom half + * + * @param isTopHalf True to make it the top half. + */ + public void setTopHalf(boolean isTopHalf) { + setData((byte) (isTopHalf ? (getData() | 0x8) : (getData() & ~0x8))); + } + + /** + * @return BlockFace.SELF + * @deprecated This method should not be used; use hinge and facing accessors instead. + */ + @Deprecated + public BlockFace getHingeCorner() { + return BlockFace.SELF; + } + + @Override + public String toString() { + return (isTopHalf() ? "TOP" : "BOTTOM") + " half of " + super.toString(); + } + + /** + * Set the direction that this door should is facing. + * + * Undefined if isTopHalf() is true. + * + * @param face the direction + */ + public void setFacingDirection(BlockFace face) { + byte data = (byte) (getData() & 0xC); + switch (face) { + case WEST: + data |= 0x0; + break; + case NORTH: + data |= 0x1; + break; + case EAST: + data |= 0x2; + break; + case SOUTH: + data |= 0x3; + break; + } + setData(data); + } + + /** + * Get the direction that this door is facing. + * + * Undefined if isTopHalf() is true. + * + * @return the direction + */ + public BlockFace getFacing() { + byte data = (byte) (getData() & 0x3); + switch (data) { + case 0: + return BlockFace.WEST; + case 1: + return BlockFace.NORTH; + case 2: + return BlockFace.EAST; + case 3: + return BlockFace.SOUTH; + default: + throw new IllegalStateException("Unknown door facing (data: " + data + ")"); + } + } + + /** + * Returns the side of the door the hinge is on. + * + * Undefined if isTopHalf() is false. + * + * @return false for left hinge, true for right hinge + */ + public boolean getHinge() { + return (getData() & 0x1) == 1; + } + + /** + * Set whether the hinge is on the left or right side. Left is false, right is true. + * + * Undefined if isTopHalf() is false. + * + * @param isHingeRight True if the hinge is on the right hand side, false if the hinge is on the left hand side. + */ + public void setHinge(boolean isHingeRight) { + setData((byte) (isHingeRight ? (getData() | 0x1) : (getData() & ~0x1))); + } + + @Override + public Door clone() { + return (Door) super.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/Dye.java b/azurite-api/src/main/java/org/bukkit/material/Dye.java new file mode 100644 index 0000000..7174fdb --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/Dye.java @@ -0,0 +1,81 @@ +package org.bukkit.material; + +import org.bukkit.DyeColor; +import org.bukkit.Material; + +/** + * Represents dye + */ +public class Dye extends MaterialData implements Colorable { + public Dye() { + super(Material.INK_SACK); + } + + /** + * @param type the raw type id + * @deprecated Magic value + */ + @Deprecated + public Dye(final int type) { + super(type); + } + + public Dye(final Material type) { + super(type); + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Dye(final int type, final byte data) { + super(type, data); + } + + /** + * @param type the type + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Dye(final Material type, final byte data) { + super(type, data); + } + + /** + * @param color color of the dye + */ + public Dye(final DyeColor color) { + super(Material.INK_SACK, color.getDyeData()); + } + + /** + * Gets the current color of this dye + * + * @return DyeColor of this dye + */ + public DyeColor getColor() { + return DyeColor.getByDyeData(getData()); + } + + /** + * Sets the color of this dye + * + * @param color New color of this dye + */ + public void setColor(DyeColor color) { + setData(color.getDyeData()); + } + + @Override + public String toString() { + return getColor() + " DYE(" + getData() + ")"; + } + + @Override + public Dye clone() { + return (Dye) super.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/EnderChest.java b/azurite-api/src/main/java/org/bukkit/material/EnderChest.java new file mode 100644 index 0000000..d3a6019 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/EnderChest.java @@ -0,0 +1,62 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +/** + * Represents an ender chest + */ +public class EnderChest extends DirectionalContainer { + + public EnderChest() { + super(Material.ENDER_CHEST); + } + + /** + * Instantiate an ender chest facing in a particular direction. + * + * @param direction the direction the ender chest's lid opens towards + */ + public EnderChest(BlockFace direction) { + this(); + setFacingDirection(direction); + } + + /** + * @param type the raw type id + * @deprecated Magic value + */ + @Deprecated + public EnderChest(final int type) { + super(type); + } + + public EnderChest(final Material type) { + super(type); + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public EnderChest(final int type, final byte data) { + super(type, data); + } + + /** + * @param type the type + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public EnderChest(final Material type, final byte data) { + super(type, data); + } + + @Override + public EnderChest clone() { + return (EnderChest) super.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/ExtendedRails.java b/azurite-api/src/main/java/org/bukkit/material/ExtendedRails.java new file mode 100644 index 0000000..34fb55e --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/ExtendedRails.java @@ -0,0 +1,75 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +/** + * This is the superclass for the {@link DetectorRail} and {@link PoweredRail} + * classes + */ +public class ExtendedRails extends Rails { + /** + * @param type the raw type id + * @deprecated Magic value + */ + @Deprecated + public ExtendedRails(final int type) { + super(type); + } + + public ExtendedRails(final Material type) { + super(type); + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public ExtendedRails(final int type, final byte data) { + super(type, data); + } + + /** + * @param type the type + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public ExtendedRails(final Material type, final byte data) { + super(type, data); + } + + @Override + public boolean isCurve() { + return false; + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + @Override + protected byte getConvertedData() { + return (byte) (getData() & 0x7); + } + + @Override + public void setDirection(BlockFace face, boolean isOnSlope) { + boolean extraBitSet = (getData() & 0x8) == 0x8; + + if (face != BlockFace.WEST && face != BlockFace.EAST && face != BlockFace.NORTH && face != BlockFace.SOUTH) { + throw new IllegalArgumentException("Detector rails and powered rails cannot be set on a curve!"); + } + + super.setDirection(face, isOnSlope); + setData((byte) (extraBitSet ? (getData() | 0x8) : (getData() & ~0x8))); + } + + @Override + public ExtendedRails clone() { + return (ExtendedRails) super.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/FlowerPot.java b/azurite-api/src/main/java/org/bukkit/material/FlowerPot.java new file mode 100644 index 0000000..7f3574e --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/FlowerPot.java @@ -0,0 +1,137 @@ +package org.bukkit.material; + +import org.bukkit.GrassSpecies; +import org.bukkit.Material; +import org.bukkit.TreeSpecies; + +/** + * Represents a flower pot. + */ +public class FlowerPot extends MaterialData { + + /** + * Default constructor for a flower pot. + */ + public FlowerPot() { + super(Material.FLOWER_POT); + } + + /** + * @param type the raw type id + * @deprecated Magic value + */ + @Deprecated + public FlowerPot(final int type) { + super(type); + } + + public FlowerPot(final Material type) { + super(type); + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public FlowerPot(final int type, final byte data) { + super(type, data); + } + + /** + * @param type the type + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public FlowerPot(final Material type, final byte data) { + super(type, data); + } + + /** + * Get the material in the flower pot + * + * @return material MaterialData for the block currently in the flower pot + * or null if empty + */ + public MaterialData getContents() { + switch (getData()) { + case 1: + return new MaterialData(Material.RED_ROSE); + case 2: + return new MaterialData(Material.YELLOW_FLOWER); + case 3: + return new Tree(TreeSpecies.GENERIC); + case 4: + return new Tree(TreeSpecies.REDWOOD); + case 5: + return new Tree(TreeSpecies.BIRCH); + case 6: + return new Tree(TreeSpecies.JUNGLE); + case 7: + return new MaterialData(Material.RED_MUSHROOM); + case 8: + return new MaterialData(Material.BROWN_MUSHROOM); + case 9: + return new MaterialData(Material.CACTUS); + case 10: + return new MaterialData(Material.DEAD_BUSH); + case 11: + return new LongGrass(GrassSpecies.FERN_LIKE); + default: + return null; + } + } + + /** + * Set the contents of the flower pot + * + * @param materialData MaterialData of the block to put in the flower pot. + */ + public void setContents(MaterialData materialData) { + Material mat = materialData.getItemType(); + + if (mat == Material.RED_ROSE) { + setData((byte) 1); + } else if (mat == Material.YELLOW_FLOWER) { + setData((byte) 2); + } else if (mat == Material.RED_MUSHROOM) { + setData((byte) 7); + } else if (mat == Material.BROWN_MUSHROOM) { + setData((byte) 8); + } else if (mat == Material.CACTUS) { + setData((byte) 9); + } else if (mat == Material.DEAD_BUSH) { + setData((byte) 10); + } else if (mat == Material.SAPLING) { + TreeSpecies species = ((Tree) materialData).getSpecies(); + + if (species == TreeSpecies.GENERIC) { + setData((byte) 3); + } else if (species == TreeSpecies.REDWOOD) { + setData((byte) 4); + } else if (species == TreeSpecies.BIRCH) { + setData((byte) 5); + } else { + setData((byte) 6); + } + } else if (mat == Material.LONG_GRASS) { + GrassSpecies species = ((LongGrass) materialData).getSpecies(); + + if (species == GrassSpecies.FERN_LIKE) { + setData((byte) 11); + } + } + } + + @Override + public String toString() { + return super.toString() + " containing " + getContents(); + } + + @Override + public FlowerPot clone() { + return (FlowerPot) super.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/Furnace.java b/azurite-api/src/main/java/org/bukkit/material/Furnace.java new file mode 100644 index 0000000..c607226 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/Furnace.java @@ -0,0 +1,62 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +/** + * Represents a furnace. + */ +public class Furnace extends FurnaceAndDispenser { + + public Furnace() { + super(Material.FURNACE); + } + + /** + * Instantiate a furnace facing in a particular direction. + * + * @param direction the direction the furnace's "opening" is facing + */ + public Furnace(BlockFace direction) { + this(); + setFacingDirection(direction); + } + + /** + * @param type the raw type id + * @deprecated Magic value + */ + @Deprecated + public Furnace(final int type) { + super(type); + } + + public Furnace(final Material type) { + super(type); + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Furnace(final int type, final byte data) { + super(type, data); + } + + /** + * @param type the type + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Furnace(final Material type, final byte data) { + super(type, data); + } + + @Override + public Furnace clone() { + return (Furnace) super.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/FurnaceAndDispenser.java b/azurite-api/src/main/java/org/bukkit/material/FurnaceAndDispenser.java new file mode 100644 index 0000000..184fda2 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/FurnaceAndDispenser.java @@ -0,0 +1,47 @@ +package org.bukkit.material; + +import org.bukkit.Material; + +/** + * Represents a furnace or dispenser, two types of directional containers + */ +public class FurnaceAndDispenser extends DirectionalContainer { + + /** + * @param type the raw type id + * @deprecated Magic value + */ + @Deprecated + public FurnaceAndDispenser(final int type) { + super(type); + } + + public FurnaceAndDispenser(final Material type) { + super(type); + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public FurnaceAndDispenser(final int type, final byte data) { + super(type, data); + } + + /** + * @param type the type + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public FurnaceAndDispenser(final Material type, final byte data) { + super(type, data); + } + + @Override + public FurnaceAndDispenser clone() { + return (FurnaceAndDispenser) super.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/Gate.java b/azurite-api/src/main/java/org/bukkit/material/Gate.java new file mode 100644 index 0000000..8adc1cf --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/Gate.java @@ -0,0 +1,91 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +/** + * Represents a fence gate + */ +public class Gate extends MaterialData implements Directional, Openable { + private static final byte OPEN_BIT = 0x4; + private static final byte DIR_BIT = 0x3; + private static final byte GATE_SOUTH = 0x0; + private static final byte GATE_WEST = 0x1; + private static final byte GATE_NORTH = 0x2; + private static final byte GATE_EAST = 0x3; + + public Gate() { + super(Material.FENCE_GATE); + } + + public Gate(int type, byte data){ + super(type, data); + } + + public Gate(byte data) { + super(Material.FENCE_GATE, data); + } + + public void setFacingDirection(BlockFace face) { + byte data = (byte) (getData() &~ DIR_BIT); + + switch (face) { + default: + case EAST: + data |= GATE_SOUTH; + break; + case SOUTH: + data |= GATE_WEST; + break; + case WEST: + data |= GATE_NORTH; + break; + case NORTH: + data |= GATE_EAST; + break; + } + + setData(data); + } + + public BlockFace getFacing() { + switch (getData() & DIR_BIT) { + case GATE_SOUTH: + return BlockFace.EAST; + case GATE_WEST: + return BlockFace.SOUTH; + case GATE_NORTH: + return BlockFace.WEST; + case GATE_EAST: + return BlockFace.NORTH; + } + + return BlockFace.EAST; + } + + public boolean isOpen() { + return (getData() & OPEN_BIT) > 0; + } + + public void setOpen(boolean isOpen) { + byte data = getData(); + + if (isOpen) { + data |= OPEN_BIT; + } else { + data &= ~OPEN_BIT; + } + + setData(data); + } + + @Override + public String toString() { + return (isOpen() ? "OPEN " : "CLOSED ") + " facing and opening " + getFacing(); + } + + @Override + public Gate clone() { + return (Gate) super.clone(); + } +} \ No newline at end of file diff --git a/azurite-api/src/main/java/org/bukkit/material/Ladder.java b/azurite-api/src/main/java/org/bukkit/material/Ladder.java new file mode 100644 index 0000000..cb7ae04 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/Ladder.java @@ -0,0 +1,104 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +/** + * Represents Ladder data + */ +public class Ladder extends SimpleAttachableMaterialData { + public Ladder() { + super(Material.LADDER); + } + + /** + * @param type the raw type id + * @deprecated Magic value + */ + @Deprecated + public Ladder(final int type) { + super(type); + } + + public Ladder(final Material type) { + super(type); + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Ladder(final int type, final byte data) { + super(type, data); + } + + /** + * @param type the type + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Ladder(final Material type, final byte data) { + super(type, data); + } + + /** + * Gets the face that this block is attached on + * + * @return BlockFace attached to + */ + public BlockFace getAttachedFace() { + byte data = getData(); + + switch (data) { + case 0x2: + return BlockFace.SOUTH; + + case 0x3: + return BlockFace.NORTH; + + case 0x4: + return BlockFace.EAST; + + case 0x5: + return BlockFace.WEST; + } + + return null; + } + + /** + * Sets the direction this ladder is facing + */ + public void setFacingDirection(BlockFace face) { + byte data = (byte) 0x0; + + switch (face) { + case SOUTH: + data = 0x2; + break; + + case NORTH: + data = 0x3; + break; + + case EAST: + data = 0x4; + break; + + case WEST: + data = 0x5; + break; + } + + setData(data); + + } + + @Override + public Ladder clone() { + return (Ladder) super.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/Leaves.java b/azurite-api/src/main/java/org/bukkit/material/Leaves.java new file mode 100644 index 0000000..9f40a23 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/Leaves.java @@ -0,0 +1,79 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.TreeSpecies; + +/** + * Represents the different types of leaves. + */ +public class Leaves extends MaterialData { + public Leaves() { + super(Material.LEAVES); + } + + public Leaves(TreeSpecies species) { + this(); + setSpecies(species); + } + + /** + * @param type the raw type id + * @deprecated Magic value + */ + @Deprecated + public Leaves(final int type) { + super(type); + } + + public Leaves(final Material type) { + super(type); + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Leaves(final int type, final byte data) { + super(type, data); + } + + /** + * @param type the type + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Leaves(final Material type, final byte data) { + super(type, data); + } + + /** + * Gets the current species of this leave + * + * @return TreeSpecies of this leave + */ + public TreeSpecies getSpecies() { + return TreeSpecies.getByData((byte) (getData() & 3)); + } + + /** + * Sets the species of this leave + * + * @param species New species of this leave + */ + public void setSpecies(TreeSpecies species) { + setData(species.getData()); + } + + @Override + public String toString() { + return getSpecies() + " " + super.toString(); + } + + @Override + public Leaves clone() { + return (Leaves) super.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/Lever.java b/azurite-api/src/main/java/org/bukkit/material/Lever.java new file mode 100644 index 0000000..f365cca --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/Lever.java @@ -0,0 +1,162 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +/** + * Represents a lever + */ +public class Lever extends SimpleAttachableMaterialData implements Redstone { + public Lever() { + super(Material.LEVER); + } + + /** + * @param type the raw type id + * @deprecated Magic value + */ + @Deprecated + public Lever(final int type) { + super(type); + } + + public Lever(final Material type) { + super(type); + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Lever(final int type, final byte data) { + super(type, data); + } + + /** + * @param type the type + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Lever(final Material type, final byte data) { + super(type, data); + } + + /** + * Gets the current state of this Material, indicating if it's powered or + * unpowered + * + * @return true if powered, otherwise false + */ + public boolean isPowered() { + return (getData() & 0x8) == 0x8; + } + + /** + * Set this lever to be powered or not. + * + * @param isPowered whether the lever should be powered or not + */ + public void setPowered(boolean isPowered) { + setData((byte) (isPowered ? (getData() | 0x8) : (getData() & ~0x8))); + } + + /** + * Gets the face that this block is attached on + * + * @return BlockFace attached to + */ + public BlockFace getAttachedFace() { + byte data = (byte) (getData() & 0x7); + + switch (data) { + case 0x1: + return BlockFace.WEST; + + case 0x2: + return BlockFace.EAST; + + case 0x3: + return BlockFace.NORTH; + + case 0x4: + return BlockFace.SOUTH; + + case 0x5: + case 0x6: + return BlockFace.DOWN; + + case 0x0: + case 0x7: + return BlockFace.UP; + + } + + return null; + } + + /** + * Sets the direction this lever is pointing in + */ + public void setFacingDirection(BlockFace face) { + byte data = (byte) (getData() & 0x8); + BlockFace attach = getAttachedFace(); + + if (attach == BlockFace.DOWN) { + switch (face) { + case SOUTH: + case NORTH: + data |= 0x5; + break; + + case EAST: + case WEST: + data |= 0x6; + break; + } + } else if (attach == BlockFace.UP) { + switch (face) { + case SOUTH: + case NORTH: + data |= 0x7; + break; + + case EAST: + case WEST: + data |= 0x0; + break; + } + } else { + switch (face) { + case EAST: + data |= 0x1; + break; + + case WEST: + data |= 0x2; + break; + + case SOUTH: + data |= 0x3; + break; + + case NORTH: + data |= 0x4; + break; + } + } + setData(data); + } + + @Override + public String toString() { + return super.toString() + " facing " + getFacing() + " " + (isPowered() ? "" : "NOT ") + "POWERED"; + } + + @Override + public Lever clone() { + return (Lever) super.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/LongGrass.java b/azurite-api/src/main/java/org/bukkit/material/LongGrass.java new file mode 100644 index 0000000..5cd8d20 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/LongGrass.java @@ -0,0 +1,79 @@ +package org.bukkit.material; + +import org.bukkit.GrassSpecies; +import org.bukkit.Material; + +/** + * Represents the different types of long grasses. + */ +public class LongGrass extends MaterialData { + public LongGrass() { + super(Material.LONG_GRASS); + } + + public LongGrass(GrassSpecies species) { + this(); + setSpecies(species); + } + + /** + * @param type the raw type id + * @deprecated Magic value + */ + @Deprecated + public LongGrass(final int type) { + super(type); + } + + public LongGrass(final Material type) { + super(type); + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public LongGrass(final int type, final byte data) { + super(type, data); + } + + /** + * @param type the type + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public LongGrass(final Material type, final byte data) { + super(type, data); + } + + /** + * Gets the current species of this grass + * + * @return GrassSpecies of this grass + */ + public GrassSpecies getSpecies() { + return GrassSpecies.getByData(getData()); + } + + /** + * Sets the species of this grass + * + * @param species New species of this grass + */ + public void setSpecies(GrassSpecies species) { + setData(species.getData()); + } + + @Override + public String toString() { + return getSpecies() + " " + super.toString(); + } + + @Override + public LongGrass clone() { + return (LongGrass) super.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/MaterialData.java b/azurite-api/src/main/java/org/bukkit/material/MaterialData.java new file mode 100644 index 0000000..e2fce2a --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/MaterialData.java @@ -0,0 +1,137 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +/** + * Handles specific metadata for certain items or blocks + */ +public class MaterialData implements Cloneable { + private final int type; + private byte data = 0; + + /** + * @param type the raw type id + * @deprecated Magic value + */ + @Deprecated + public MaterialData(final int type) { + this(type, (byte) 0); + } + + public MaterialData(final Material type) { + this(type, (byte) 0); + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public MaterialData(final int type, final byte data) { + this.type = type; + this.data = data; + } + + /** + * @param type the type + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public MaterialData(final Material type, final byte data) { + this(type.getId(), data); + } + + /** + * Gets the raw data in this material + * + * @return Raw data + * @deprecated Magic value + */ + @Deprecated + public byte getData() { + return data; + } + + /** + * Sets the raw data of this material + * + * @param data New raw data + * @deprecated Magic value + */ + @Deprecated + public void setData(byte data) { + this.data = data; + } + + /** + * Gets the Material that this MaterialData represents + * + * @return Material represented by this MaterialData + */ + public Material getItemType() { + return Material.getMaterial(type); + } + + /** + * Gets the Material Id that this MaterialData represents + * + * @return Material Id represented by this MaterialData + * @deprecated Magic value + */ + @Deprecated + public int getItemTypeId() { + return type; + } + + /** + * Creates a new ItemStack based on this MaterialData + * + * @return New ItemStack containing a copy of this MaterialData + */ + public ItemStack toItemStack() { + return new ItemStack(type, 0, data); + } + + /** + * Creates a new ItemStack based on this MaterialData + * + * @param amount The stack size of the new stack + * @return New ItemStack containing a copy of this MaterialData + */ + public ItemStack toItemStack(int amount) { + return new ItemStack(type, amount, data); + } + + @Override + public String toString() { + return getItemType() + "(" + getData() + ")"; + } + + @Override + public int hashCode() { + return ((getItemTypeId() << 8) ^ getData()); + } + + @Override + public boolean equals(Object obj) { + if (obj != null && obj instanceof MaterialData) { + MaterialData md = (MaterialData) obj; + + return (md.getItemTypeId() == getItemTypeId() && md.getData() == getData()); + } else { + return false; + } + } + + @Override + public MaterialData clone() { + try { + return (MaterialData) super.clone(); + } catch (CloneNotSupportedException e) { + throw new Error(e); + } + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/MonsterEggs.java b/azurite-api/src/main/java/org/bukkit/material/MonsterEggs.java new file mode 100644 index 0000000..a443a9e --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/MonsterEggs.java @@ -0,0 +1,69 @@ +package org.bukkit.material; + +import org.bukkit.Material; + +import java.util.ArrayList; +import java.util.List; + +/** + * Represents the different types of monster eggs + */ +public class MonsterEggs extends TexturedMaterial { + + private static final List textures = new ArrayList(); + static { + textures.add(Material.STONE); + textures.add(Material.COBBLESTONE); + textures.add(Material.SMOOTH_BRICK); + } + + public MonsterEggs() { + super(Material.MONSTER_EGGS); + } + + /** + * @param type the raw type id + * @deprecated Magic value + */ + @Deprecated + public MonsterEggs(final int type) { + super(type); + } + + public MonsterEggs(final Material type) { + super((textures.contains(type)) ? Material.MONSTER_EGGS : type); + if (textures.contains(type)) { + setMaterial(type); + } + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public MonsterEggs(final int type, final byte data) { + super(type, data); + } + + /** + * @param type the type + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public MonsterEggs(final Material type, final byte data) { + super(type, data); + } + + @Override + public List getTextures() { + return textures; + } + + @Override + public MonsterEggs clone() { + return (MonsterEggs) super.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/Mushroom.java b/azurite-api/src/main/java/org/bukkit/material/Mushroom.java new file mode 100644 index 0000000..51b8010 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/Mushroom.java @@ -0,0 +1,199 @@ +package org.bukkit.material; + +import org.apache.commons.lang.Validate; +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +import java.util.EnumSet; +import java.util.Set; + +/** + * Represents a huge mushroom block + */ +public class Mushroom extends MaterialData { + private static final byte SHROOM_NONE = 0; + private static final byte SHROOM_STEM = 10; + private static final byte NORTH_LIMIT = 4; + private static final byte SOUTH_LIMIT = 6; + private static final byte EAST_WEST_LIMIT = 3; + private static final byte EAST_REMAINDER = 0; + private static final byte WEST_REMAINDER = 1; + private static final byte NORTH_SOUTH_MOD = 3; + private static final byte EAST_WEST_MOD = 1; + + public Mushroom(Material shroom) { + super(shroom); + Validate.isTrue(shroom == Material.HUGE_MUSHROOM_1 || shroom == Material.HUGE_MUSHROOM_2, "Not a mushroom!"); + } + + /** + * @param shroom the type + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Mushroom(Material shroom, byte data) { + super(shroom, data); + Validate.isTrue(shroom == Material.HUGE_MUSHROOM_1 || shroom == Material.HUGE_MUSHROOM_2, "Not a mushroom!"); + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Mushroom(int type, byte data){ + super(type, data); + Validate.isTrue(type == Material.HUGE_MUSHROOM_1.getId() || type == Material.HUGE_MUSHROOM_2.getId(), "Not a mushroom!"); + } + + /** + * @return Whether this is a mushroom stem. + */ + public boolean isStem() { + return getData() == SHROOM_STEM; + } + + /** + * Sets this to be a mushroom stem. + */ + public void setStem() { + setData((byte) 10); + } + + /** + * Checks whether a face of the block is painted. + * + * @param face The face to check. + * @return True if it is painted. + */ + public boolean isFacePainted(BlockFace face) { + byte data = getData(); + + if (data == SHROOM_NONE || data == SHROOM_STEM) { + return false; + } + + switch (face) { + case WEST: + return data < NORTH_LIMIT; + case EAST: + return data > SOUTH_LIMIT; + case NORTH: + return data % EAST_WEST_LIMIT == EAST_REMAINDER; + case SOUTH: + return data % EAST_WEST_LIMIT == WEST_REMAINDER; + case UP: + return true; + default: + return false; + } + } + + /** + * Set a face of the block to be painted or not. Note that due to the + * nature of how the data is stored, setting a face painted or not is not + * guaranteed to leave the other faces unchanged. + * + * @param face The face to paint or unpaint. + * @param painted True if you want to paint it, false if you want the + * pores to show. + */ + public void setFacePainted(BlockFace face, boolean painted) { + if (painted == isFacePainted(face)) { + return; + } + + byte data = getData(); + + if (data == SHROOM_STEM) { + data = 5; + } + + switch (face) { + case WEST: + if (painted) { + data -= NORTH_SOUTH_MOD; + } else { + data += NORTH_SOUTH_MOD; + } + + break; + case EAST: + if (painted) { + data += NORTH_SOUTH_MOD; + } else { + data -= NORTH_SOUTH_MOD; + } + + break; + case NORTH: + if (painted) { + data += EAST_WEST_MOD; + } else { + data -= EAST_WEST_MOD; + } + + break; + case SOUTH: + if (painted) { + data -= EAST_WEST_MOD; + } else { + data += EAST_WEST_MOD; + } + + break; + case UP: + if (!painted) { + data = 0; + } + + break; + default: + throw new IllegalArgumentException("Can't paint that face of a mushroom!"); + } + + setData(data); + } + + /** + * @return A set of all faces that are currently painted (an empty set if + * it is a stem) + */ + public Set getPaintedFaces() { + EnumSet faces = EnumSet.noneOf(BlockFace.class); + + if (isFacePainted(BlockFace.WEST)) { + faces.add(BlockFace.WEST); + } + + if (isFacePainted(BlockFace.NORTH)) { + faces.add(BlockFace.NORTH); + } + + if (isFacePainted(BlockFace.SOUTH)) { + faces.add(BlockFace.SOUTH); + } + + if (isFacePainted(BlockFace.EAST)) { + faces.add(BlockFace.EAST); + } + + if (isFacePainted(BlockFace.UP)) { + faces.add(BlockFace.UP); + } + + return faces; + } + + @Override + public String toString() { + return Material.getMaterial(getItemTypeId()).toString() + (isStem() ? "{STEM}" : getPaintedFaces()); + } + + @Override + public Mushroom clone() { + return (Mushroom) super.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/NetherWarts.java b/azurite-api/src/main/java/org/bukkit/material/NetherWarts.java new file mode 100644 index 0000000..55eb864 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/NetherWarts.java @@ -0,0 +1,101 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.NetherWartsState; + +/** + * Represents nether wart + */ +public class NetherWarts extends MaterialData { + public NetherWarts() { + super(Material.NETHER_WARTS); + } + + public NetherWarts(NetherWartsState state) { + this(); + setState(state); + } + + /** + * @param type the raw type id + * @deprecated Magic value + */ + @Deprecated + public NetherWarts(final int type) { + super(type); + } + + public NetherWarts(final Material type) { + super (type); + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public NetherWarts(final int type, final byte data) { + super(type, data); + } + + /** + * @param type the type + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public NetherWarts(final Material type, final byte data) { + super(type, data); + } + + /** + * Gets the current growth state of this nether wart + * + * @return NetherWartsState of this nether wart + */ + public NetherWartsState getState() { + switch (getData()) { + case 0: + return NetherWartsState.SEEDED; + case 1: + return NetherWartsState.STAGE_ONE; + case 2: + return NetherWartsState.STAGE_TWO; + default: + return NetherWartsState.RIPE; + } + } + + /** + * Sets the growth state of this nether wart + * + * @param state New growth state of this nether wart + */ + public void setState(NetherWartsState state) { + switch (state) { + case SEEDED: + setData((byte) 0x0); + return; + case STAGE_ONE: + setData((byte) 0x1); + return; + case STAGE_TWO: + setData((byte) 0x2); + return; + case RIPE: + setData((byte) 0x3); + return; + } + } + + @Override + public String toString() { + return getState() + " " + super.toString(); + } + + @Override + public NetherWarts clone() { + return (NetherWarts) super.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/Openable.java b/azurite-api/src/main/java/org/bukkit/material/Openable.java new file mode 100644 index 0000000..0ae54f9 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/Openable.java @@ -0,0 +1,18 @@ +package org.bukkit.material; + +public interface Openable { + + /** + * Check to see if the door is open. + * + * @return true if the door has swung counterclockwise around its hinge. + */ + boolean isOpen(); + + /** + * Configure this door to be either open or closed; + * + * @param isOpen True to open the door. + */ + void setOpen(boolean isOpen); +} diff --git a/azurite-api/src/main/java/org/bukkit/material/PistonBaseMaterial.java b/azurite-api/src/main/java/org/bukkit/material/PistonBaseMaterial.java new file mode 100644 index 0000000..bbf1565 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/PistonBaseMaterial.java @@ -0,0 +1,123 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +/** + * Material data for the piston base block + */ +public class PistonBaseMaterial extends MaterialData implements Directional, Redstone { + + /** + * Constructs a PistonBaseMaterial + * + * @param type the raw type id + * @deprecated Magic value + */ + @Deprecated + public PistonBaseMaterial(final int type) { + super(type); + } + + public PistonBaseMaterial(final Material type) { + super(type); + } + + /** + * Constructs a PistonBaseMaterial. + * + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public PistonBaseMaterial(final int type, final byte data) { + super(type, data); + } + + /** + * Constructs a PistonBaseMaterial. + * + * @param type the material type to use + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public PistonBaseMaterial(final Material type, final byte data) { + super(type, data); + } + + @Override + public void setFacingDirection(BlockFace face) { + byte data = (byte) (getData() & 0x8); + + switch (face) { + case UP: + data |= 1; + break; + case NORTH: + data |= 2; + break; + case SOUTH: + data |= 3; + break; + case WEST: + data |= 4; + break; + case EAST: + data |= 5; + break; + } + setData(data); + } + + @Override + public BlockFace getFacing() { + byte dir = (byte) (getData() & 7); + + switch (dir) { + case 0: + return BlockFace.DOWN; + case 1: + return BlockFace.UP; + case 2: + return BlockFace.NORTH; + case 3: + return BlockFace.SOUTH; + case 4: + return BlockFace.WEST; + case 5: + return BlockFace.EAST; + default: + return BlockFace.SELF; + } + } + + @Override + public boolean isPowered() { + return (getData() & 0x8) == 0x8; + } + + /** + * Sets the current state of this piston + * + * @param powered true if the piston is extended {@literal &} powered, or false + */ + public void setPowered(boolean powered) { + setData((byte) (powered ? (getData() | 0x8) : (getData() & ~0x8))); + } + + /** + * Checks if this piston base is sticky, and returns true if so + * + * @return true if this piston is "sticky", or false + */ + public boolean isSticky() { + return this.getItemType() == Material.PISTON_STICKY_BASE; + } + + @Override + public PistonBaseMaterial clone() { + return (PistonBaseMaterial) super.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/PistonExtensionMaterial.java b/azurite-api/src/main/java/org/bukkit/material/PistonExtensionMaterial.java new file mode 100644 index 0000000..8076ec9 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/PistonExtensionMaterial.java @@ -0,0 +1,113 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +/** + * Material data for the piston extension block + */ +public class PistonExtensionMaterial extends MaterialData implements Attachable { + /** + * @param type the raw type id + * @deprecated Magic value + */ + @Deprecated + public PistonExtensionMaterial(final int type) { + super(type); + } + + public PistonExtensionMaterial(final Material type) { + super(type); + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public PistonExtensionMaterial(final int type, final byte data) { + super(type, data); + } + + /** + * @param type the type + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public PistonExtensionMaterial(final Material type, final byte data) { + super(type, data); + } + + public void setFacingDirection(BlockFace face) { + byte data = (byte) (getData() & 0x8); + + switch (face) { + case UP: + data |= 1; + break; + case NORTH: + data |= 2; + break; + case SOUTH: + data |= 3; + break; + case WEST: + data |= 4; + break; + case EAST: + data |= 5; + break; + } + setData(data); + } + + public BlockFace getFacing() { + byte dir = (byte) (getData() & 7); + + switch (dir) { + case 0: + return BlockFace.DOWN; + case 1: + return BlockFace.UP; + case 2: + return BlockFace.NORTH; + case 3: + return BlockFace.SOUTH; + case 4: + return BlockFace.WEST; + case 5: + return BlockFace.EAST; + default: + return BlockFace.SELF; + } + } + + /** + * Checks if this piston extension is sticky, and returns true if so + * + * @return true if this piston is "sticky", or false + */ + public boolean isSticky() { + return (getData() & 8) == 8; + } + + /** + * Sets whether or not this extension is sticky + * + * @param sticky true if sticky, otherwise false + */ + public void setSticky(boolean sticky) { + setData((byte) (sticky ? (getData() | 0x8) : (getData() & ~0x8))); + } + + public BlockFace getAttachedFace() { + return getFacing().getOppositeFace(); + } + + @Override + public PistonExtensionMaterial clone() { + return (PistonExtensionMaterial) super.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/PoweredRail.java b/azurite-api/src/main/java/org/bukkit/material/PoweredRail.java new file mode 100644 index 0000000..4a9d6a9 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/PoweredRail.java @@ -0,0 +1,63 @@ +package org.bukkit.material; + +import org.bukkit.Material; + +/** + * Represents a powered rail + */ +public class PoweredRail extends ExtendedRails implements Redstone { + public PoweredRail() { + super(Material.POWERED_RAIL); + } + + /** + * @param type the raw type id + * @deprecated Magic value + */ + @Deprecated + public PoweredRail(final int type) { + super(type); + } + + public PoweredRail(final Material type) { + super(type); + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public PoweredRail(final int type, final byte data) { + super(type, data); + } + + /** + * @param type the type + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public PoweredRail(final Material type, final byte data) { + super(type, data); + } + + public boolean isPowered() { + return (getData() & 0x8) == 0x8; + } + + /** + * Set whether this PoweredRail should be powered or not. + * + * @param isPowered whether or not the rail is powered + */ + public void setPowered(boolean isPowered) { + setData((byte) (isPowered ? (getData() | 0x8) : (getData() & ~0x8))); + } + + @Override + public PoweredRail clone() { + return (PoweredRail) super.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/PressurePlate.java b/azurite-api/src/main/java/org/bukkit/material/PressurePlate.java new file mode 100644 index 0000000..d7747b5 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/PressurePlate.java @@ -0,0 +1,59 @@ +package org.bukkit.material; + +import org.bukkit.Material; + +/** + * Represents a pressure plate + */ +public class PressurePlate extends MaterialData implements PressureSensor { + public PressurePlate() { + super(Material.WOOD_PLATE); + } + + /** + * @param type the raw type id + * @deprecated Magic value + */ + @Deprecated + public PressurePlate(int type) { + super(type); + } + + public PressurePlate(Material type) { + super(type); + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public PressurePlate(int type, byte data) { + super(type, data); + } + + /** + * @param type the type + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public PressurePlate(Material type, byte data) { + super(type, data); + } + + public boolean isPressed() { + return getData() == 0x1; + } + + @Override + public String toString() { + return super.toString() + (isPressed() ? " PRESSED" : ""); + } + + @Override + public PressurePlate clone() { + return (PressurePlate) super.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/PressureSensor.java b/azurite-api/src/main/java/org/bukkit/material/PressureSensor.java new file mode 100644 index 0000000..43d5b55 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/PressureSensor.java @@ -0,0 +1,5 @@ +package org.bukkit.material; + +public interface PressureSensor { + boolean isPressed(); +} diff --git a/azurite-api/src/main/java/org/bukkit/material/Pumpkin.java b/azurite-api/src/main/java/org/bukkit/material/Pumpkin.java new file mode 100644 index 0000000..afd200a --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/Pumpkin.java @@ -0,0 +1,114 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +/** + * Represents a pumpkin. + */ +public class Pumpkin extends MaterialData implements Directional { + + public Pumpkin() { + super(Material.PUMPKIN); + } + + /** + * Instantiate a pumpkin facing in a particular direction. + * + * @param direction the direction the pumkin's face is facing + */ + public Pumpkin(BlockFace direction) { + this(); + setFacingDirection(direction); + } + + /** + * @param type the raw type id + * @deprecated Magic value + */ + @Deprecated + public Pumpkin(final int type) { + super(type); + } + + public Pumpkin(final Material type) { + super(type); + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Pumpkin(final int type, final byte data) { + super(type, data); + } + + /** + * @param type the type + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Pumpkin(final Material type, final byte data) { + super(type, data); + } + + public boolean isLit() { + return getItemType() == Material.JACK_O_LANTERN; + } + + public void setFacingDirection(BlockFace face) { + byte data; + + switch (face) { + case NORTH: + data = 0x0; + break; + + case EAST: + data = 0x1; + break; + + case SOUTH: + data = 0x2; + break; + + case WEST: + default: + data = 0x3; + } + + setData(data); + } + + public BlockFace getFacing() { + byte data = getData(); + + switch (data) { + case 0x0: + return BlockFace.NORTH; + + case 0x1: + return BlockFace.EAST; + + case 0x2: + return BlockFace.SOUTH; + + case 0x3: + default: + return BlockFace.EAST; + } + } + + @Override + public String toString() { + return super.toString() + " facing " + getFacing() + " " + (isLit() ? "" : "NOT ") + "LIT"; + } + + @Override + public Pumpkin clone() { + return (Pumpkin) super.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/Rails.java b/azurite-api/src/main/java/org/bukkit/material/Rails.java new file mode 100644 index 0000000..10044ee --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/Rails.java @@ -0,0 +1,178 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +/** + * Represents minecart rails. + */ +public class Rails extends MaterialData { + + public Rails() { + super(Material.RAILS); + } + + /** + * @param type the raw type id + * @deprecated Magic value + */ + @Deprecated + public Rails(final int type) { + super(type); + } + + public Rails(final Material type) { + super(type); + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Rails(final int type, final byte data) { + super(type, data); + } + + /** + * @param type the type + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Rails(final Material type, final byte data) { + super(type, data); + } + + /** + * @return the whether this track is set on a slope + */ + public boolean isOnSlope() { + byte d = getConvertedData(); + + return (d == 0x2 || d == 0x3 || d == 0x4 || d == 0x5); + } + + /** + * @return the whether this track is set as a curve + */ + public boolean isCurve() { + byte d = getConvertedData(); + + return (d == 0x6 || d == 0x7 || d == 0x8 || d == 0x9); + } + + /** + * @return the direction these tracks are set + *

+ * Note that tracks are bidirectional and that the direction returned + * is the ascending direction if the track is set on a slope. If it is + * set as a curve, the corner of the track is returned. + */ + public BlockFace getDirection() { + byte d = getConvertedData(); + + switch (d) { + case 0x0: + default: + return BlockFace.SOUTH; + + case 0x1: + return BlockFace.EAST; + + case 0x2: + return BlockFace.EAST; + + case 0x3: + return BlockFace.WEST; + + case 0x4: + return BlockFace.NORTH; + + case 0x5: + return BlockFace.SOUTH; + + case 0x6: + return BlockFace.NORTH_WEST; + + case 0x7: + return BlockFace.NORTH_EAST; + + case 0x8: + return BlockFace.SOUTH_EAST; + + case 0x9: + return BlockFace.SOUTH_WEST; + } + } + + @Override + public String toString() { + return super.toString() + " facing " + getDirection() + (isCurve() ? " on a curve" : (isOnSlope() ? " on a slope" : "")); + } + + /** + * Return the data without the extended properties used by {@link + * PoweredRail} and {@link DetectorRail}. Overridden in {@link + * ExtendedRails} + * + * @return the data without the extended part + * @deprecated Magic value + */ + @Deprecated + protected byte getConvertedData() { + return getData(); + } + + /** + * Set the direction of these tracks + *

+ * Note that tracks are bidirectional and that the direction returned is + * the ascending direction if the track is set on a slope. If it is set as + * a curve, the corner of the track should be supplied. + * + * @param face the direction the track should be facing + * @param isOnSlope whether or not the track should be on a slope + */ + public void setDirection(BlockFace face, boolean isOnSlope) { + switch (face) { + case EAST: + setData((byte) (isOnSlope ? 0x2 : 0x1)); + break; + + case WEST: + setData((byte) (isOnSlope ? 0x3 : 0x1)); + break; + + case NORTH: + setData((byte) (isOnSlope ? 0x4 : 0x0)); + break; + + case SOUTH: + setData((byte) (isOnSlope ? 0x5 : 0x0)); + break; + + case NORTH_WEST: + setData((byte) 0x6); + break; + + case NORTH_EAST: + setData((byte) 0x7); + break; + + case SOUTH_EAST: + setData((byte) 0x8); + break; + + case SOUTH_WEST: + setData((byte) 0x9); + break; + } + } + + @Override + public Rails clone() { + return (Rails) super.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/Redstone.java b/azurite-api/src/main/java/org/bukkit/material/Redstone.java new file mode 100644 index 0000000..ccf8e6f --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/Redstone.java @@ -0,0 +1,15 @@ +package org.bukkit.material; + +/** + * Indicated a Material that may carry or create a Redstone current + */ +public interface Redstone { + + /** + * Gets the current state of this Material, indicating if it's powered or + * unpowered + * + * @return true if powered, otherwise false + */ + boolean isPowered(); +} diff --git a/azurite-api/src/main/java/org/bukkit/material/RedstoneTorch.java b/azurite-api/src/main/java/org/bukkit/material/RedstoneTorch.java new file mode 100644 index 0000000..45c3e47 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/RedstoneTorch.java @@ -0,0 +1,65 @@ +package org.bukkit.material; + +import org.bukkit.Material; + +/** + * Represents a redstone torch + */ +public class RedstoneTorch extends Torch implements Redstone { + public RedstoneTorch() { + super(Material.REDSTONE_TORCH_ON); + } + + /** + * @param type the raw type id + * @deprecated Magic value + */ + @Deprecated + public RedstoneTorch(final int type) { + super(type); + } + + public RedstoneTorch(final Material type) { + super(type); + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public RedstoneTorch(final int type, final byte data) { + super(type, data); + } + + /** + * @param type the type + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public RedstoneTorch(final Material type, final byte data) { + super(type, data); + } + + /** + * Gets the current state of this Material, indicating if it's powered or + * unpowered + * + * @return true if powered, otherwise false + */ + public boolean isPowered() { + return getItemType() == Material.REDSTONE_TORCH_ON; + } + + @Override + public String toString() { + return super.toString() + " " + (isPowered() ? "" : "NOT ") + "POWERED"; + } + + @Override + public RedstoneTorch clone() { + return (RedstoneTorch) super.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/RedstoneWire.java b/azurite-api/src/main/java/org/bukkit/material/RedstoneWire.java new file mode 100644 index 0000000..d13ae4b --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/RedstoneWire.java @@ -0,0 +1,65 @@ +package org.bukkit.material; + +import org.bukkit.Material; + +/** + * Represents redstone wire + */ +public class RedstoneWire extends MaterialData implements Redstone { + public RedstoneWire() { + super(Material.REDSTONE_WIRE); + } + + /** + * @param type the raw type id + * @deprecated Magic value + */ + @Deprecated + public RedstoneWire(final int type) { + super(type); + } + + public RedstoneWire(final Material type) { + super(type); + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public RedstoneWire(final int type, final byte data) { + super(type, data); + } + + /** + * @param type the type + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public RedstoneWire(final Material type, final byte data) { + super(type, data); + } + + /** + * Gets the current state of this Material, indicating if it's powered or + * unpowered + * + * @return true if powered, otherwise false + */ + public boolean isPowered() { + return getData() > 0; + } + + @Override + public String toString() { + return super.toString() + " " + (isPowered() ? "" : "NOT ") + "POWERED"; + } + + @Override + public RedstoneWire clone() { + return (RedstoneWire) super.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/Sandstone.java b/azurite-api/src/main/java/org/bukkit/material/Sandstone.java new file mode 100644 index 0000000..be88d43 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/Sandstone.java @@ -0,0 +1,79 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.SandstoneType; + +/** + * Represents the different types of sandstone. + */ +public class Sandstone extends MaterialData { + public Sandstone() { + super(Material.SANDSTONE); + } + + public Sandstone(SandstoneType type) { + this(); + setType(type); + } + + /** + * @param type the raw type id + * @deprecated Magic value + */ + @Deprecated + public Sandstone(final int type) { + super(type); + } + + public Sandstone(final Material type) { + super(type); + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Sandstone(final int type, final byte data) { + super(type, data); + } + + /** + * @param type the type + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Sandstone(final Material type, final byte data) { + super(type, data); + } + + /** + * Gets the current type of this sandstone + * + * @return SandstoneType of this sandstone + */ + public SandstoneType getType() { + return SandstoneType.getByData(getData()); + } + + /** + * Sets the type of this sandstone + * + * @param type New type of this sandstone + */ + public void setType(SandstoneType type) { + setData(type.getData()); + } + + @Override + public String toString() { + return getType() + " " + super.toString(); + } + + @Override + public Sandstone clone() { + return (Sandstone) super.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/Sign.java b/azurite-api/src/main/java/org/bukkit/material/Sign.java new file mode 100644 index 0000000..b2c83f3 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/Sign.java @@ -0,0 +1,252 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +/** + * MaterialData for signs + */ +public class Sign extends MaterialData implements Attachable { + public Sign() { + super(Material.SIGN_POST); + } + + /** + * @param type the raw type id + * @deprecated Magic value + */ + @Deprecated + public Sign(final int type) { + super(type); + } + + public Sign(final Material type) { + super(type); + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Sign(final int type, final byte data) { + super(type, data); + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Sign(final Material type, final byte data) { + super(type, data); + } + + /** + * Check if this sign is attached to a wall + * + * @return true if this sign is attached to a wall, false if set on top of + * a block + */ + public boolean isWallSign() { + return getItemType() == Material.WALL_SIGN; + } + + /** + * Gets the face that this block is attached on + * + * @return BlockFace attached to + */ + public BlockFace getAttachedFace() { + if (isWallSign()) { + byte data = getData(); + + switch (data) { + case 0x2: + return BlockFace.SOUTH; + + case 0x3: + return BlockFace.NORTH; + + case 0x4: + return BlockFace.EAST; + + case 0x5: + return BlockFace.WEST; + } + + return null; + } else { + return BlockFace.DOWN; + } + } + + /** + * Gets the direction that this sign is currently facing + * + * @return BlockFace indicating where this sign is facing + */ + public BlockFace getFacing() { + byte data = getData(); + + if (!isWallSign()) { + switch (data) { + case 0x0: + return BlockFace.SOUTH; + + case 0x1: + return BlockFace.SOUTH_SOUTH_WEST; + + case 0x2: + return BlockFace.SOUTH_WEST; + + case 0x3: + return BlockFace.WEST_SOUTH_WEST; + + case 0x4: + return BlockFace.WEST; + + case 0x5: + return BlockFace.WEST_NORTH_WEST; + + case 0x6: + return BlockFace.NORTH_WEST; + + case 0x7: + return BlockFace.NORTH_NORTH_WEST; + + case 0x8: + return BlockFace.NORTH; + + case 0x9: + return BlockFace.NORTH_NORTH_EAST; + + case 0xA: + return BlockFace.NORTH_EAST; + + case 0xB: + return BlockFace.EAST_NORTH_EAST; + + case 0xC: + return BlockFace.EAST; + + case 0xD: + return BlockFace.EAST_SOUTH_EAST; + + case 0xE: + return BlockFace.SOUTH_EAST; + + case 0xF: + return BlockFace.SOUTH_SOUTH_EAST; + } + + return null; + } else { + return getAttachedFace().getOppositeFace(); + } + } + + public void setFacingDirection(BlockFace face) { + byte data; + + if (isWallSign()) { + switch (face) { + case NORTH: + data = 0x2; + break; + + case SOUTH: + data = 0x3; + break; + + case WEST: + data = 0x4; + break; + + case EAST: + default: + data = 0x5; + } + } else { + switch (face) { + case SOUTH: + data = 0x0; + break; + + case SOUTH_SOUTH_WEST: + data = 0x1; + break; + + case SOUTH_WEST: + data = 0x2; + break; + + case WEST_SOUTH_WEST: + data = 0x3; + break; + + case WEST: + data = 0x4; + break; + + case WEST_NORTH_WEST: + data = 0x5; + break; + + case NORTH_WEST: + data = 0x6; + break; + + case NORTH_NORTH_WEST: + data = 0x7; + break; + + case NORTH: + data = 0x8; + break; + + case NORTH_NORTH_EAST: + data = 0x9; + break; + + case NORTH_EAST: + data = 0xA; + break; + + case EAST_NORTH_EAST: + data = 0xB; + break; + + case EAST: + data = 0xC; + break; + + case EAST_SOUTH_EAST: + data = 0xD; + break; + + case SOUTH_SOUTH_EAST: + data = 0xF; + break; + + case SOUTH_EAST: + default: + data = 0xE; + } + } + + setData(data); + } + + @Override + public String toString() { + return super.toString() + " facing " + getFacing(); + } + + @Override + public Sign clone() { + return (Sign) super.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/SimpleAttachableMaterialData.java b/azurite-api/src/main/java/org/bukkit/material/SimpleAttachableMaterialData.java new file mode 100644 index 0000000..b1897b7 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/SimpleAttachableMaterialData.java @@ -0,0 +1,68 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +/** + * Simple utility class for attachable MaterialData subclasses + */ +public abstract class SimpleAttachableMaterialData extends MaterialData implements Attachable { + + /** + * @param type the raw type id + * @deprecated Magic value + */ + @Deprecated + public SimpleAttachableMaterialData(int type) { + super(type); + } + + public SimpleAttachableMaterialData(int type, BlockFace direction) { + this(type); + setFacingDirection(direction); + } + + public SimpleAttachableMaterialData(Material type, BlockFace direction) { + this(type); + setFacingDirection(direction); + } + + public SimpleAttachableMaterialData(Material type) { + super(type); + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public SimpleAttachableMaterialData(int type, byte data) { + super(type, data); + } + + /** + * @param type the type + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public SimpleAttachableMaterialData(Material type, byte data) { + super(type, data); + } + + public BlockFace getFacing() { + BlockFace attachedFace = getAttachedFace(); + return attachedFace == null ? null : attachedFace.getOppositeFace(); + } + + @Override + public String toString() { + return super.toString() + " facing " + getFacing(); + } + + @Override + public SimpleAttachableMaterialData clone() { + return (SimpleAttachableMaterialData) super.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/Skull.java b/azurite-api/src/main/java/org/bukkit/material/Skull.java new file mode 100644 index 0000000..659d9e9 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/Skull.java @@ -0,0 +1,116 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +/** + * Represents a skull. + */ +public class Skull extends MaterialData implements Directional { + public Skull() { + super(Material.SKULL); + } + + /** + * Instantiate a skull facing in a particular direction. + * + * @param direction the direction the skull's face is facing + */ + public Skull(BlockFace direction) { + this(); + setFacingDirection(direction); + } + + /** + * @param type the raw type id + * @deprecated Magic value + */ + @Deprecated + public Skull(final int type) { + super(type); + } + + public Skull(final Material type) { + super(type); + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Skull(final int type, final byte data) { + super(type, data); + } + + /** + * @param type the type + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Skull(final Material type, final byte data) { + super(type, data); + } + + public void setFacingDirection(BlockFace face) { + int data; + + switch (face) { + case SELF: + default: + data = 0x1; + break; + + case NORTH: + data = 0x2; + break; + + case EAST: + data = 0x4; + break; + + case SOUTH: + data = 0x3; + break; + + case WEST: + data = 0x5; + } + + setData((byte) data); + } + + public BlockFace getFacing() { + int data = getData(); + + switch (data) { + case 0x1: + default: + return BlockFace.SELF; + + case 0x2: + return BlockFace.NORTH; + + case 0x3: + return BlockFace.SOUTH; + + case 0x4: + return BlockFace.EAST; + + case 0x5: + return BlockFace.WEST; + } + } + + @Override + public String toString() { + return super.toString() + " facing " + getFacing(); + } + + @Override + public Skull clone() { + return (Skull) super.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/SmoothBrick.java b/azurite-api/src/main/java/org/bukkit/material/SmoothBrick.java new file mode 100644 index 0000000..952b524 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/SmoothBrick.java @@ -0,0 +1,70 @@ +package org.bukkit.material; + +import org.bukkit.Material; + +import java.util.ArrayList; +import java.util.List; + +/** + * Represents the different types of smooth bricks. + */ +public class SmoothBrick extends TexturedMaterial { + + private static final List textures = new ArrayList(); + static { + textures.add(Material.STONE); + textures.add(Material.MOSSY_COBBLESTONE); + textures.add(Material.COBBLESTONE); + textures.add(Material.SMOOTH_BRICK); + } + + public SmoothBrick() { + super(Material.SMOOTH_BRICK); + } + + /** + * @param type the raw type id + * @deprecated Magic value + */ + @Deprecated + public SmoothBrick(final int type) { + super(type); + } + + public SmoothBrick(final Material type) { + super((textures.contains(type)) ? Material.SMOOTH_BRICK : type); + if (textures.contains(type)) { + setMaterial(type); + } + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public SmoothBrick(final int type, final byte data) { + super(type, data); + } + + /** + * @param type the type + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public SmoothBrick(final Material type, final byte data) { + super(type, data); + } + + @Override + public List getTextures() { + return textures; + } + + @Override + public SmoothBrick clone() { + return (SmoothBrick) super.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/SpawnEgg.java b/azurite-api/src/main/java/org/bukkit/material/SpawnEgg.java new file mode 100644 index 0000000..4260627 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/SpawnEgg.java @@ -0,0 +1,66 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.entity.EntityType; + +/** + * Represents a spawn egg that can be used to spawn mobs + */ +public class SpawnEgg extends MaterialData { + + public SpawnEgg() { + super(Material.MONSTER_EGG); + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public SpawnEgg(int type, byte data){ + super(type, data); + } + + /** + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public SpawnEgg(byte data) { + super(Material.MONSTER_EGG, data); + } + + public SpawnEgg(EntityType type) { + this(); + setSpawnedType(type); + } + + /** + * Get the type of entity this egg will spawn. + * + * @return The entity type. + */ + public EntityType getSpawnedType() { + return EntityType.fromId(getData()); + } + + /** + * Set the type of entity this egg will spawn. + * + * @param type The entity type. + */ + public void setSpawnedType(EntityType type) { + setData((byte) type.getTypeId()); + } + + @Override + public String toString() { + return "SPAWN EGG{" + getSpawnedType() + "}"; + } + + @Override + public SpawnEgg clone() { + return (SpawnEgg) super.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/Stairs.java b/azurite-api/src/main/java/org/bukkit/material/Stairs.java new file mode 100644 index 0000000..7dde021 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/Stairs.java @@ -0,0 +1,140 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +/** + * Represents stairs. + */ +public class Stairs extends MaterialData implements Directional { + + /** + * @param type the raw type id + * @deprecated Magic value + */ + @Deprecated + public Stairs(final int type) { + super(type); + } + + public Stairs(final Material type) { + super(type); + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Stairs(final int type, final byte data) { + super(type, data); + } + + /** + * @param type the type + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Stairs(final Material type, final byte data) { + super(type, data); + } + + /** + * @return the direction the stairs ascend towards + */ + public BlockFace getAscendingDirection() { + byte data = getData(); + + switch (data & 0x3) { + case 0x0: + default: + return BlockFace.EAST; + + case 0x1: + return BlockFace.WEST; + + case 0x2: + return BlockFace.SOUTH; + + case 0x3: + return BlockFace.NORTH; + } + } + + /** + * @return the direction the stairs descend towards + */ + public BlockFace getDescendingDirection() { + return getAscendingDirection().getOppositeFace(); + } + + /** + * Set the direction the stair part of the block is facing + */ + public void setFacingDirection(BlockFace face) { + byte data; + + switch (face) { + case NORTH: + data = 0x3; + break; + + case SOUTH: + data = 0x2; + break; + + case EAST: + default: + data = 0x0; + break; + + case WEST: + data = 0x1; + break; + } + + setData((byte) ((getData() & 0xC) | data)); + } + + /** + * @return the direction the stair part of the block is facing + */ + public BlockFace getFacing() { + return getDescendingDirection(); + } + + /** + * Test if step is inverted + * + * @return true if inverted (top half), false if normal (bottom half) + */ + public boolean isInverted() { + return ((getData() & 0x4) != 0); + } + + /** + * Set step inverted state + * + * @param inv - true if step is inverted (top half), false if step is + * normal (bottom half) + */ + public void setInverted(boolean inv) { + int dat = getData() & 0x3; + if (inv) { + dat |= 0x4; + } + setData((byte) dat); + } + + @Override + public String toString() { + return super.toString() + " facing " + getFacing() + (isInverted()?" inverted":""); + } + + @Override + public Stairs clone() { + return (Stairs) super.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/Step.java b/azurite-api/src/main/java/org/bukkit/material/Step.java new file mode 100644 index 0000000..095f80d --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/Step.java @@ -0,0 +1,121 @@ +package org.bukkit.material; + +import org.bukkit.Material; + +import java.util.ArrayList; +import java.util.List; + +/** + * Represents the different types of steps. + */ +public class Step extends TexturedMaterial { + private static final List textures = new ArrayList(); + static { + textures.add(Material.STONE); + textures.add(Material.SANDSTONE); + textures.add(Material.WOOD); + textures.add(Material.COBBLESTONE); + textures.add(Material.BRICK); + textures.add(Material.SMOOTH_BRICK); + textures.add(Material.NETHER_BRICK); + textures.add(Material.QUARTZ_BLOCK); + } + + public Step() { + super(Material.STEP); + } + + /** + * @param type the raw type id + * @deprecated Magic value + */ + @Deprecated + public Step(final int type) { + super(type); + } + + public Step(final Material type) { + super((textures.contains(type)) ? Material.STEP : type); + if (textures.contains(type)) { + setMaterial(type); + } + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Step(final int type, final byte data) { + super(type, data); + } + + /** + * @param type the type + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Step(final Material type, final byte data) { + super(type, data); + } + + @Override + public List getTextures() { + return textures; + } + + /** + * Test if step is inverted + * + * @return true if inverted (top half), false if normal (bottom half) + */ + public boolean isInverted() { + return ((getData() & 0x8) != 0); + } + + /** + * Set step inverted state + * + * @param inv - true if step is inverted (top half), false if step is + * normal (bottom half) + */ + public void setInverted(boolean inv) { + int dat = getData() & 0x7; + if (inv) { + dat |= 0x8; + } + setData((byte) dat); + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + @Override + protected int getTextureIndex() { + return getData() & 0x7; + } + + /** + * + * @deprecated Magic value + */ + @Deprecated + @Override + protected void setTextureIndex(int idx) { + setData((byte) ((getData() & 0x8) | idx)); + } + + @Override + public Step clone() { + return (Step) super.clone(); + } + + @Override + public String toString() { + return super.toString() + (isInverted()?"inverted":""); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/TexturedMaterial.java b/azurite-api/src/main/java/org/bukkit/material/TexturedMaterial.java new file mode 100644 index 0000000..439ebf9 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/TexturedMaterial.java @@ -0,0 +1,112 @@ +package org.bukkit.material; + +import org.bukkit.Material; + +import java.util.List; + +/** + * Represents textured materials like steps and smooth bricks + */ +public abstract class TexturedMaterial extends MaterialData { + + public TexturedMaterial(Material m) { + super(m); + } + + /** + * @param type the raw type id + * @deprecated Magic value + */ + @Deprecated + public TexturedMaterial(int type) { + super(type); + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public TexturedMaterial(final int type, final byte data) { + super(type, data); + } + + /** + * @param type the type + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public TexturedMaterial(final Material type, final byte data) { + super(type, data); + } + + /** + * Retrieve a list of possible textures. The first element of the list + * will be used as a default. + * + * @return a list of possible textures for this block + */ + public abstract List getTextures(); + + /** + * Gets the current Material this block is made of + * + * @return Material of this block + */ + public Material getMaterial() { + int n = getTextureIndex(); + if (n > getTextures().size() - 1) { + n = 0; + } + + return getTextures().get(n); + } + + /** + * Sets the material this block is made of + * + * @param material + * New material of this block + */ + public void setMaterial(Material material) { + if (getTextures().contains(material)) { + setTextureIndex(getTextures().indexOf(material)); + } else { + setTextureIndex(0x0); + } + } + + /** + * Get material index from data + * + * @return index of data in textures list + * @deprecated Magic value + */ + @Deprecated + protected int getTextureIndex() { + return getData(); // Default to using all bits - override for other mappings + } + + /** + * Set material index + * + * @param idx - index of data in textures list + * @deprecated Magic value + */ + @Deprecated + protected void setTextureIndex(int idx) { + setData((byte) idx); // Defult to using all bits - override for other mappings + } + + @Override + public String toString() { + return getMaterial() + " " + super.toString(); + } + + @Override + public TexturedMaterial clone() { + return (TexturedMaterial) super.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/Torch.java b/azurite-api/src/main/java/org/bukkit/material/Torch.java new file mode 100644 index 0000000..7f2e56a --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/Torch.java @@ -0,0 +1,106 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +/** + * MaterialData for torches + */ +public class Torch extends SimpleAttachableMaterialData { + public Torch() { + super(Material.TORCH); + } + + /** + * @param type the raw type id + * @deprecated Magic value + */ + @Deprecated + public Torch(final int type) { + super(type); + } + + public Torch(final Material type) { + super(type); + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Torch(final int type, final byte data) { + super(type, data); + } + + /** + * @param type the type + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Torch(final Material type, final byte data) { + super(type, data); + } + + /** + * Gets the face that this block is attached on + * + * @return BlockFace attached to + */ + public BlockFace getAttachedFace() { + byte data = getData(); + + switch (data) { + case 0x1: + return BlockFace.WEST; + + case 0x2: + return BlockFace.EAST; + + case 0x3: + return BlockFace.NORTH; + + case 0x4: + return BlockFace.SOUTH; + + case 0x5: + default: + return BlockFace.DOWN; + } + } + + public void setFacingDirection(BlockFace face) { + byte data; + + switch (face) { + case EAST: + data = 0x1; + break; + + case WEST: + data = 0x2; + break; + + case SOUTH: + data = 0x3; + break; + + case NORTH: + data = 0x4; + break; + + case UP: + default: + data = 0x5; + } + + setData(data); + } + + @Override + public Torch clone() { + return (Torch) super.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/TrapDoor.java b/azurite-api/src/main/java/org/bukkit/material/TrapDoor.java new file mode 100644 index 0000000..2ae3362 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/TrapDoor.java @@ -0,0 +1,133 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +/** + * Represents a trap door + */ +public class TrapDoor extends SimpleAttachableMaterialData implements Openable { + public TrapDoor() { + super(Material.TRAP_DOOR); + } + + /** + * @param type the raw type id + * @deprecated Magic value + */ + @Deprecated + public TrapDoor(final int type) { + super(type); + } + + public TrapDoor(final Material type) { + super(type); + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public TrapDoor(final int type, final byte data) { + super(type, data); + } + + /** + * @param type the type + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public TrapDoor(final Material type, final byte data) { + super(type, data); + } + + public boolean isOpen() { + return ((getData() & 0x4) == 0x4); + } + + public void setOpen(boolean isOpen) { + byte data = getData(); + + if (isOpen) { + data |= 0x4; + } else { + data &= ~0x4; + } + + setData(data); + } + + /** + * Test if trapdoor is inverted + * + * @return true if inverted (top half), false if normal (bottom half) + */ + public boolean isInverted() { + return ((getData() & 0x8) != 0); + } + + /** + * Set trapdoor inverted state + * + * @param inv - true if inverted (top half), false if normal (bottom half) + */ + public void setInverted(boolean inv) { + int dat = getData() & 0x7; + if (inv) { + dat |= 0x8; + } + setData((byte) dat); + } + + public BlockFace getAttachedFace() { + byte data = (byte) (getData() & 0x3); + + switch (data) { + case 0x0: + return BlockFace.SOUTH; + + case 0x1: + return BlockFace.NORTH; + + case 0x2: + return BlockFace.EAST; + + case 0x3: + return BlockFace.WEST; + } + + return null; + + } + + public void setFacingDirection(BlockFace face) { + byte data = (byte) (getData() & 0xC); + + switch (face) { + case SOUTH: + data |= 0x1; + break; + case WEST: + data |= 0x2; + break; + case EAST: + data |= 0x3; + break; + } + + setData(data); + } + + @Override + public String toString() { + return (isOpen() ? "OPEN " : "CLOSED ") + super.toString() + " with hinges set " + getAttachedFace() + (isInverted() ? " inverted" : ""); + } + + @Override + public TrapDoor clone() { + return (TrapDoor) super.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/Tree.java b/azurite-api/src/main/java/org/bukkit/material/Tree.java new file mode 100644 index 0000000..d90126c --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/Tree.java @@ -0,0 +1,138 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.TreeSpecies; +import org.bukkit.block.BlockFace; + +/** + * Represents the different types of Trees. + */ +public class Tree extends MaterialData { + public Tree() { + super(Material.LOG); + } + + public Tree(TreeSpecies species) { + this(); + setSpecies(species); + } + + public Tree(TreeSpecies species, BlockFace dir) { + this(); + setSpecies(species); + setDirection(dir); + } + + /** + * @param type the raw type id + * @deprecated Magic value + */ + @Deprecated + public Tree(final int type) { + super(type); + } + + public Tree(final Material type) { + super(type); + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Tree(final int type, final byte data) { + super(type, data); + } + + /** + * @param type the type + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Tree(final Material type, final byte data) { + super(type, data); + } + + /** + * Gets the current species of this tree + * + * @return TreeSpecies of this tree + */ + public TreeSpecies getSpecies() { + return TreeSpecies.getByData((byte) (getData() & 0x3)); + } + + /** + * Sets the species of this tree + * + * @param species New species of this tree + */ + public void setSpecies(TreeSpecies species) { + setData((byte) ((getData() & 0xC) | species.getData())); + } + + /** + * Get direction of the log + * + * @return one of: + *

    + *
  • BlockFace.TOP for upright (default) + *
  • BlockFace.NORTH (east-west) + *
  • BlockFace.WEST (north-south) + *
  • BlockFace.SELF (directionless) + *
+ */ + public BlockFace getDirection() { + switch ((getData() >> 2) & 0x3) { + case 0: // Up-down + default: + return BlockFace.UP; + case 1: // North-south + return BlockFace.WEST; + case 2: // East-west + return BlockFace.NORTH; + case 3: // Directionless (bark on all sides) + return BlockFace.SELF; + } + } + /** + * Set direction of the log + * + * @param dir - direction of end of log (BlockFace.SELF for no direction) + */ + public void setDirection(BlockFace dir) { + int dat; + switch (dir) { + case UP: + case DOWN: + default: + dat = 0; + break; + case WEST: + case EAST: + dat = 1; + break; + case NORTH: + case SOUTH: + dat = 2; + break; + case SELF: + dat = 3; + break; + } + setData((byte) ((getData() & 0x3) | (dat << 2))); + } + + @Override + public String toString() { + return getSpecies() + " " + getDirection() + " " + super.toString(); + } + + @Override + public Tree clone() { + return (Tree) super.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/Tripwire.java b/azurite-api/src/main/java/org/bukkit/material/Tripwire.java new file mode 100644 index 0000000..570635d --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/Tripwire.java @@ -0,0 +1,86 @@ +package org.bukkit.material; + +import org.bukkit.Material; + +/** + * Represents the tripwire + */ +public class Tripwire extends MaterialData { + + public Tripwire() { + super(Material.TRIPWIRE); + } + + /** + * @param type the raw type id + * @deprecated Magic value + */ + @Deprecated + public Tripwire(final int type) { + super(type); + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Tripwire(final int type, final byte data) { + super(type, data); + } + + /** + * Test if tripwire is currently activated + * + * @return true if activated, false if not + */ + public boolean isActivated() { + return (getData() & 0x4) != 0; + } + + /** + * Set tripwire activated state + * + * @param act - true if activated, false if not + */ + public void setActivated(boolean act) { + int dat = getData() & (0x8 | 0x3); + if (act) { + dat |= 0x4; + } + setData((byte) dat); + } + + /** + * Test if object triggering this tripwire directly + * + * @return true if object activating tripwire, false if not + */ + public boolean isObjectTriggering() { + return (getData() & 0x1) != 0; + } + + /** + * Set object triggering state for this tripwire + * + * @param trig - true if object activating tripwire, false if not + */ + public void setObjectTriggering(boolean trig) { + int dat = getData() & 0xE; + if (trig) { + dat |= 0x1; + } + setData((byte) dat); + } + + @Override + public Tripwire clone() { + return (Tripwire) super.clone(); + } + + @Override + public String toString() { + return super.toString() + (isActivated()?" Activated":"") + (isObjectTriggering()?" Triggered":""); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/TripwireHook.java b/azurite-api/src/main/java/org/bukkit/material/TripwireHook.java new file mode 100644 index 0000000..8ff23e9 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/TripwireHook.java @@ -0,0 +1,129 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +/** + * Represents the tripwire hook + */ +public class TripwireHook extends SimpleAttachableMaterialData implements Redstone { + + public TripwireHook() { + super(Material.TRIPWIRE_HOOK); + } + + /** + * @param type the raw type id + * @deprecated Magic value + */ + @Deprecated + public TripwireHook(final int type) { + super(type); + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public TripwireHook(final int type, final byte data) { + super(type, data); + } + + public TripwireHook(BlockFace dir) { + this(); + setFacingDirection(dir); + } + + /** + * Test if tripwire is connected + * + * @return true if connected, false if not + */ + public boolean isConnected() { + return (getData() & 0x4) != 0; + } + + /** + * Set tripwire connection state + * + * @param connected - true if connected, false if not + */ + public void setConnected(boolean connected) { + int dat = getData() & (0x8 | 0x3); + if (connected) { + dat |= 0x4; + } + setData((byte) dat); + } + + /** + * Test if hook is currently activated + * + * @return true if activated, false if not + */ + public boolean isActivated() { + return (getData() & 0x8) != 0; + } + + /** + * Set hook activated state + * + * @param act - true if activated, false if not + */ + public void setActivated(boolean act) { + int dat = getData() & (0x4 | 0x3); + if (act) { + dat |= 0x8; + } + setData((byte) dat); + } + + public void setFacingDirection(BlockFace face) { + int dat = getData() & 0xC; + switch (face) { + case WEST: + dat |= 0x1; + break; + case NORTH: + dat |= 0x2; + break; + case EAST: + dat |= 0x3; + break; + case SOUTH: + default: + break; + } + setData((byte) dat); + } + + public BlockFace getAttachedFace() { + switch (getData() & 0x3) { + case 0: + return BlockFace.NORTH; + case 1: + return BlockFace.EAST; + case 2: + return BlockFace.SOUTH; + case 3: + return BlockFace.WEST; + } + return null; + } + + public boolean isPowered() { + return isActivated(); + } + + @Override + public TripwireHook clone() { + return (TripwireHook) super.clone(); + } + + @Override + public String toString() { + return super.toString() + " facing " + getFacing() + (isActivated()?" Activated":"") + (isConnected()?" Connected":""); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/Vine.java b/azurite-api/src/main/java/org/bukkit/material/Vine.java new file mode 100644 index 0000000..d3d53df --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/Vine.java @@ -0,0 +1,197 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +import java.util.Arrays; +import java.util.EnumSet; + +/** + * Represents a vine + */ +public class Vine extends MaterialData { + private static final int VINE_NORTH = 0x4; + private static final int VINE_EAST = 0x8; + private static final int VINE_WEST = 0x2; + private static final int VINE_SOUTH = 0x1; + EnumSet possibleFaces = EnumSet.of(BlockFace.WEST, BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST); + + public Vine() { + super(Material.VINE); + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Vine(int type, byte data){ + super(type, data); + } + + /** + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Vine(byte data) { + super(Material.VINE, data); + } + + public Vine(BlockFace... faces) { + this(EnumSet.copyOf(Arrays.asList(faces))); + } + + public Vine(EnumSet faces) { + this((byte) 0); + faces.retainAll(possibleFaces); + + byte data = 0; + + if (faces.contains(BlockFace.WEST)) { + data |= VINE_WEST; + } + + if (faces.contains(BlockFace.NORTH)) { + data |= VINE_NORTH; + } + + if (faces.contains(BlockFace.SOUTH)) { + data |= VINE_SOUTH; + } + + if (faces.contains(BlockFace.EAST)) { + data |= VINE_EAST; + } + + setData(data); + } + + /** + * Check if the vine is attached to the specified face of an adjacent + * block. You can check two faces at once by passing e.g. {@link + * BlockFace#NORTH_EAST}. + * + * @param face The face to check. + * @return Whether it is attached to that face. + */ + public boolean isOnFace(BlockFace face) { + switch (face) { + case WEST: + return (getData() & VINE_WEST) == VINE_WEST; + case NORTH: + return (getData() & VINE_NORTH) == VINE_NORTH; + case SOUTH: + return (getData() & VINE_SOUTH) == VINE_SOUTH; + case EAST: + return (getData() & VINE_EAST) == VINE_EAST; + case NORTH_EAST: + return isOnFace(BlockFace.EAST) && isOnFace(BlockFace.NORTH); + case NORTH_WEST: + return isOnFace(BlockFace.WEST) && isOnFace(BlockFace.NORTH); + case SOUTH_EAST: + return isOnFace(BlockFace.EAST) && isOnFace(BlockFace.SOUTH); + case SOUTH_WEST: + return isOnFace(BlockFace.WEST) && isOnFace(BlockFace.SOUTH); + case UP: // It's impossible to be accurate with this since it's contextual + return true; + default: + return false; + } + } + + /** + * Attach the vine to the specified face of an adjacent block. + * + * @param face The face to attach. + */ + public void putOnFace(BlockFace face) { + switch(face) { + case WEST: + setData((byte) (getData() | VINE_WEST)); + break; + case NORTH: + setData((byte) (getData() | VINE_NORTH)); + break; + case SOUTH: + setData((byte) (getData() | VINE_SOUTH)); + break; + case EAST: + setData((byte) (getData() | VINE_EAST)); + break; + case NORTH_WEST: + putOnFace(BlockFace.WEST); + putOnFace(BlockFace.NORTH); + break; + case SOUTH_WEST: + putOnFace(BlockFace.WEST); + putOnFace(BlockFace.SOUTH); + break; + case NORTH_EAST: + putOnFace(BlockFace.EAST); + putOnFace(BlockFace.NORTH); + break; + case SOUTH_EAST: + putOnFace(BlockFace.EAST); + putOnFace(BlockFace.SOUTH); + break; + case UP: + break; + default: + throw new IllegalArgumentException("Vines can't go on face " + face.toString()); + } + } + + /** + * Detach the vine from the specified face of an adjacent block. + * + * @param face The face to detach. + */ + public void removeFromFace(BlockFace face) { + switch(face) { + case WEST: + setData((byte) (getData() & ~VINE_WEST)); + break; + case NORTH: + setData((byte) (getData() & ~VINE_NORTH)); + break; + case SOUTH: + setData((byte) (getData() & ~VINE_SOUTH)); + break; + case EAST: + setData((byte) (getData() & ~VINE_EAST)); + break; + case NORTH_WEST: + removeFromFace(BlockFace.WEST); + removeFromFace(BlockFace.NORTH); + break; + case SOUTH_WEST: + removeFromFace(BlockFace.WEST); + removeFromFace(BlockFace.SOUTH); + break; + case NORTH_EAST: + removeFromFace(BlockFace.EAST); + removeFromFace(BlockFace.NORTH); + break; + case SOUTH_EAST: + removeFromFace(BlockFace.EAST); + removeFromFace(BlockFace.SOUTH); + break; + case UP: + break; + default: + throw new IllegalArgumentException("Vines can't go on face " + face.toString()); + } + } + + @Override + public String toString() { + return "VINE"; + } + + @Override + public Vine clone() { + return (Vine) super.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/WoodenStep.java b/azurite-api/src/main/java/org/bukkit/material/WoodenStep.java new file mode 100644 index 0000000..b07ee89 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/WoodenStep.java @@ -0,0 +1,105 @@ +package org.bukkit.material; + +import org.bukkit.Material; +import org.bukkit.TreeSpecies; + +/** + * Represents the different types of wooden steps. + */ +public class WoodenStep extends MaterialData { + + public WoodenStep() { + super(Material.WOOD_STEP); + } + + /** + * @param type the raw type id + * @deprecated Magic value + */ + @Deprecated + public WoodenStep(final int type) { + super(type); + } + + public WoodenStep(TreeSpecies species) { + this(); + setSpecies(species); + } + + public WoodenStep(TreeSpecies species, boolean inv) { + this(); + setSpecies(species); + setInverted(inv); + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public WoodenStep(final int type, final byte data) { + super(type, data); + } + + /** + * @param type the type + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public WoodenStep(final Material type, final byte data) { + super(type, data); + } + + /** + * Gets the current species of this tree + * + * @return TreeSpecies of this tree + */ + public TreeSpecies getSpecies() { + return TreeSpecies.getByData((byte) (getData() & 0x3)); + } + + /** + * Sets the species of this tree + * + * @param species New species of this tree + */ + public void setSpecies(TreeSpecies species) { + setData((byte) ((getData() & 0xC) | species.getData())); + } + + /** + * Test if step is inverted + * + * @return true if inverted (top half), false if normal (bottom half) + */ + public boolean isInverted() { + return ((getData() & 0x8) != 0); + } + + /** + * Set step inverted state + * + * @param inv - true if step is inverted (top half), false if step is + * normal (bottom half) + */ + public void setInverted(boolean inv) { + int dat = getData() & 0x7; + if (inv) { + dat |= 0x8; + } + setData((byte) dat); + } + + @Override + public WoodenStep clone() { + return (WoodenStep) super.clone(); + } + + @Override + public String toString() { + return super.toString() + " " + getSpecies() + (isInverted()?" inverted":""); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/material/Wool.java b/azurite-api/src/main/java/org/bukkit/material/Wool.java new file mode 100644 index 0000000..c4e4bfa --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/material/Wool.java @@ -0,0 +1,79 @@ +package org.bukkit.material; + +import org.bukkit.DyeColor; +import org.bukkit.Material; + +/** + * Represents a Wool/Cloth block + */ +public class Wool extends MaterialData implements Colorable { + public Wool() { + super(Material.WOOL); + } + + public Wool(DyeColor color) { + this(); + setColor(color); + } + + /** + * @param type the raw type id + * @deprecated Magic value + */ + @Deprecated + public Wool(final int type) { + super(type); + } + + public Wool(final Material type) { + super(type); + } + + /** + * @param type the raw type id + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Wool(final int type, final byte data) { + super(type, data); + } + + /** + * @param type the type + * @param data the raw data value + * @deprecated Magic value + */ + @Deprecated + public Wool(final Material type, final byte data) { + super(type, data); + } + + /** + * Gets the current color of this dye + * + * @return DyeColor of this dye + */ + public DyeColor getColor() { + return DyeColor.getByWoolData(getData()); + } + + /** + * Sets the color of this dye + * + * @param color New color of this dye + */ + public void setColor(DyeColor color) { + setData(color.getWoolData()); + } + + @Override + public String toString() { + return getColor() + " " + super.toString(); + } + + @Override + public Wool clone() { + return (Wool) super.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/metadata/FixedMetadataValue.java b/azurite-api/src/main/java/org/bukkit/metadata/FixedMetadataValue.java new file mode 100644 index 0000000..5f48573 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/metadata/FixedMetadataValue.java @@ -0,0 +1,41 @@ +package org.bukkit.metadata; + +import org.bukkit.plugin.Plugin; + +/** + * A FixedMetadataValue is a special case metadata item that contains the same + * value forever after initialization. Invalidating a FixedMetadataValue has + * no effect. + *

+ * This class extends LazyMetadataValue for historical reasons, even though it + * overrides all the implementation methods. it is possible that in the future + * that the inheritance hierarchy may change. + */ +public class FixedMetadataValue extends LazyMetadataValue { + + /** + * Store the internal value that is represented by this fixed value. + */ + private final Object internalValue; + + /** + * Initializes a FixedMetadataValue with an Object + * + * @param owningPlugin the {@link Plugin} that created this metadata value + * @param value the value assigned to this metadata value + */ + public FixedMetadataValue(Plugin owningPlugin, final Object value) { + super(owningPlugin); + this.internalValue = value; + } + + @Override + public void invalidate() { + + } + + @Override + public Object value() { + return internalValue; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/metadata/LazyMetadataValue.java b/azurite-api/src/main/java/org/bukkit/metadata/LazyMetadataValue.java new file mode 100644 index 0000000..fb0da1b --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/metadata/LazyMetadataValue.java @@ -0,0 +1,122 @@ +package org.bukkit.metadata; + +import org.apache.commons.lang.Validate; +import org.bukkit.plugin.Plugin; + +import java.lang.ref.SoftReference; +import java.util.concurrent.Callable; + +/** + * The LazyMetadataValue class implements a type of metadata that is not + * computed until another plugin asks for it. + *

+ * By making metadata values lazy, no computation is done by the providing + * plugin until absolutely necessary (if ever). Additionally, + * LazyMetadataValue objects cache their values internally unless overridden + * by a {@link CacheStrategy} or invalidated at the individual or plugin + * level. Once invalidated, the LazyMetadataValue will recompute its value + * when asked. + */ +public class LazyMetadataValue extends MetadataValueAdapter implements MetadataValue { + private Callable lazyValue; + private CacheStrategy cacheStrategy; + private SoftReference internalValue; + private static final Object ACTUALLY_NULL = new Object(); + + /** + * Initialized a LazyMetadataValue object with the default + * CACHE_AFTER_FIRST_EVAL cache strategy. + * + * @param owningPlugin the {@link Plugin} that created this metadata + * value. + * @param lazyValue the lazy value assigned to this metadata value. + */ + public LazyMetadataValue(Plugin owningPlugin, Callable lazyValue) { + this(owningPlugin, CacheStrategy.CACHE_AFTER_FIRST_EVAL, lazyValue); + } + + /** + * Initializes a LazyMetadataValue object with a specific cache strategy. + * + * @param owningPlugin the {@link Plugin} that created this metadata + * value. + * @param cacheStrategy determines the rules for caching this metadata + * value. + * @param lazyValue the lazy value assigned to this metadata value. + */ + public LazyMetadataValue(Plugin owningPlugin, CacheStrategy cacheStrategy, Callable lazyValue) { + super(owningPlugin); + Validate.notNull(cacheStrategy, "cacheStrategy cannot be null"); + Validate.notNull(lazyValue, "lazyValue cannot be null"); + this.internalValue = new SoftReference(null); + this.lazyValue = lazyValue; + this.cacheStrategy = cacheStrategy; + } + + /** + * Protected special constructor used by FixedMetadataValue to bypass + * standard setup. + * + * @param owningPlugin the owning plugin + */ + protected LazyMetadataValue(Plugin owningPlugin) { + super(owningPlugin); + } + + public Object value() { + eval(); + Object value = internalValue.get(); + if (value == ACTUALLY_NULL) { + return null; + } + return value; + } + + /** + * Lazily evaluates the value of this metadata item. + * + * @throws MetadataEvaluationException if computing the metadata value + * fails. + */ + private synchronized void eval() throws MetadataEvaluationException { + if (cacheStrategy == CacheStrategy.NEVER_CACHE || internalValue.get() == null) { + try { + Object value = lazyValue.call(); + if (value == null) { + value = ACTUALLY_NULL; + } + internalValue = new SoftReference(value); + } catch (Exception e) { + throw new MetadataEvaluationException(e); + } + } + } + + public synchronized void invalidate() { + if (cacheStrategy != CacheStrategy.CACHE_ETERNALLY) { + internalValue.clear(); + } + } + + /** + * Describes possible caching strategies for metadata. + */ + public enum CacheStrategy { + /** + * Once the metadata value has been evaluated, do not re-evaluate the + * value until it is manually invalidated. + */ + CACHE_AFTER_FIRST_EVAL, + + /** + * Re-evaluate the metadata item every time it is requested + */ + NEVER_CACHE, + + /** + * Once the metadata value has been evaluated, do not re-evaluate the + * value in spite of manual invalidation. + */ + CACHE_ETERNALLY + } +} diff --git a/azurite-api/src/main/java/org/bukkit/metadata/MetadataConversionException.java b/azurite-api/src/main/java/org/bukkit/metadata/MetadataConversionException.java new file mode 100644 index 0000000..a3def46 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/metadata/MetadataConversionException.java @@ -0,0 +1,13 @@ +package org.bukkit.metadata; + +/** + * A MetadataConversionException is thrown any time a {@link + * LazyMetadataValue} attempts to convert a metadata value to an inappropriate + * data type. + */ +@SuppressWarnings("serial") +public class MetadataConversionException extends RuntimeException { + MetadataConversionException(String message) { + super(message); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/metadata/MetadataEvaluationException.java b/azurite-api/src/main/java/org/bukkit/metadata/MetadataEvaluationException.java new file mode 100644 index 0000000..918e7c8 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/metadata/MetadataEvaluationException.java @@ -0,0 +1,13 @@ +package org.bukkit.metadata; + +/** + * A MetadataEvaluationException is thrown any time a {@link + * LazyMetadataValue} fails to evaluate its value due to an exception. The + * originating exception will be included as this exception's cause. + */ +@SuppressWarnings("serial") +public class MetadataEvaluationException extends RuntimeException { + MetadataEvaluationException(Throwable cause) { + super(cause); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/metadata/MetadataStore.java b/azurite-api/src/main/java/org/bukkit/metadata/MetadataStore.java new file mode 100644 index 0000000..c2570d8 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/metadata/MetadataStore.java @@ -0,0 +1,60 @@ +package org.bukkit.metadata; + +import org.bukkit.plugin.Plugin; + +import java.util.List; + +public interface MetadataStore { + /** + * Adds a metadata value to an object. + * + * @param subject The object receiving the metadata. + * @param metadataKey A unique key to identify this metadata. + * @param newMetadataValue The metadata value to apply. + * @throws IllegalArgumentException If value is null, or the owning plugin + * is null + */ + void setMetadata(T subject, String metadataKey, MetadataValue newMetadataValue); + + /** + * Returns all metadata values attached to an object. If multiple plugins + * have attached metadata, each will value will be included. + * + * @param subject the object being interrogated. + * @param metadataKey the unique metadata key being sought. + * @return A list of values, one for each plugin that has set the + * requested value. + */ + List getMetadata(T subject, String metadataKey); + + /** + * Tests to see if a metadata attribute has been set on an object. + * + * @param subject the object upon which the has-metadata test is + * performed. + * @param metadataKey the unique metadata key being queried. + * @return the existence of the metadataKey within subject. + */ + boolean hasMetadata(T subject, String metadataKey); + + /** + * Removes a metadata item owned by a plugin from a subject. + * + * @param subject the object to remove the metadata from. + * @param metadataKey the unique metadata key identifying the metadata to + * remove. + * @param owningPlugin the plugin attempting to remove a metadata item. + * @throws IllegalArgumentException If plugin is null + */ + void removeMetadata(T subject, String metadataKey, Plugin owningPlugin); + + /** + * Invalidates all metadata in the metadata store that originates from the + * given plugin. Doing this will force each invalidated metadata item to + * be recalculated the next time it is accessed. + * + * @param owningPlugin the plugin requesting the invalidation. + * @throws IllegalArgumentException If plugin is null + */ + void invalidateAll(Plugin owningPlugin); +} diff --git a/azurite-api/src/main/java/org/bukkit/metadata/MetadataStoreBase.java b/azurite-api/src/main/java/org/bukkit/metadata/MetadataStoreBase.java new file mode 100644 index 0000000..8a6b1e1 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/metadata/MetadataStoreBase.java @@ -0,0 +1,136 @@ +package org.bukkit.metadata; + +import org.apache.commons.lang.Validate; +import org.bukkit.plugin.Plugin; + +import java.util.*; + +public abstract class MetadataStoreBase { + private Map> metadataMap = new HashMap>(); + + /** + * Adds a metadata value to an object. Each metadata value is owned by a + * specific {@link Plugin}. If a plugin has already added a metadata value + * to an object, that value will be replaced with the value of {@code + * newMetadataValue}. Multiple plugins can set independent values for the + * same {@code metadataKey} without conflict. + *

+ * Implementation note: I considered using a {@link + * java.util.concurrent.locks.ReadWriteLock} for controlling access to + * {@code metadataMap}, but decided that the added overhead wasn't worth + * the finer grained access control. + *

+ * Bukkit is almost entirely single threaded so locking overhead shouldn't + * pose a problem. + * + * @param subject The object receiving the metadata. + * @param metadataKey A unique key to identify this metadata. + * @param newMetadataValue The metadata value to apply. + * @see MetadataStore#setMetadata(Object, String, MetadataValue) + * @throws IllegalArgumentException If value is null, or the owning plugin + * is null + */ + public synchronized void setMetadata(T subject, String metadataKey, MetadataValue newMetadataValue) { + Validate.notNull(newMetadataValue, "Value cannot be null"); + Plugin owningPlugin = newMetadataValue.getOwningPlugin(); + Validate.notNull(owningPlugin, "Plugin cannot be null"); + String key = disambiguate(subject, metadataKey); + Map entry = metadataMap.get(key); + if (entry == null) { + entry = new WeakHashMap(1); + metadataMap.put(key, entry); + } + entry.put(owningPlugin, newMetadataValue); + } + + /** + * Returns all metadata values attached to an object. If multiple + * have attached metadata, each will value will be included. + * + * @param subject the object being interrogated. + * @param metadataKey the unique metadata key being sought. + * @return A list of values, one for each plugin that has set the + * requested value. + * @see MetadataStore#getMetadata(Object, String) + */ + public synchronized List getMetadata(T subject, String metadataKey) { + String key = disambiguate(subject, metadataKey); + if (metadataMap.containsKey(key)) { + Collection values = metadataMap.get(key).values(); + return Collections.unmodifiableList(new ArrayList(values)); + } else { + return Collections.emptyList(); + } + } + + /** + * Tests to see if a metadata attribute has been set on an object. + * + * @param subject the object upon which the has-metadata test is + * performed. + * @param metadataKey the unique metadata key being queried. + * @return the existence of the metadataKey within subject. + */ + public synchronized boolean hasMetadata(T subject, String metadataKey) { + String key = disambiguate(subject, metadataKey); + return metadataMap.containsKey(key); + } + + /** + * Removes a metadata item owned by a plugin from a subject. + * + * @param subject the object to remove the metadata from. + * @param metadataKey the unique metadata key identifying the metadata to + * remove. + * @param owningPlugin the plugin attempting to remove a metadata item. + * @see MetadataStore#removeMetadata(Object, String, + * Plugin) + * @throws IllegalArgumentException If plugin is null + */ + public synchronized void removeMetadata(T subject, String metadataKey, Plugin owningPlugin) { + Validate.notNull(owningPlugin, "Plugin cannot be null"); + String key = disambiguate(subject, metadataKey); + Map entry = metadataMap.get(key); + if (entry == null) { + return; + } + + entry.remove(owningPlugin); + if (entry.isEmpty()) { + metadataMap.remove(key); + } + } + + /** + * Invalidates all metadata in the metadata store that originates from the + * given plugin. Doing this will force each invalidated metadata item to + * be recalculated the next time it is accessed. + * + * @param owningPlugin the plugin requesting the invalidation. + * @see MetadataStore#invalidateAll(Plugin) + * @throws IllegalArgumentException If plugin is null + */ + public synchronized void invalidateAll(Plugin owningPlugin) { + Validate.notNull(owningPlugin, "Plugin cannot be null"); + for (Map values : metadataMap.values()) { + if (values.containsKey(owningPlugin)) { + values.get(owningPlugin).invalidate(); + } + } + } + + /** + * Creates a unique name for the object receiving metadata by combining + * unique data from the subject with a metadataKey. + *

+ * The name created must be globally unique for the given object and any + * two equivalent objects must generate the same unique name. For example, + * two Player objects must generate the same string if they represent the + * same player, even if the objects would fail a reference equality test. + * + * @param subject The object for which this key is being generated. + * @param metadataKey The name identifying the metadata value. + * @return a unique metadata key for the given subject. + */ + protected abstract String disambiguate(T subject, String metadataKey); +} diff --git a/azurite-api/src/main/java/org/bukkit/metadata/MetadataValue.java b/azurite-api/src/main/java/org/bukkit/metadata/MetadataValue.java new file mode 100644 index 0000000..f091e4c --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/metadata/MetadataValue.java @@ -0,0 +1,83 @@ +package org.bukkit.metadata; + +import org.bukkit.plugin.Plugin; + +public interface MetadataValue { + + /** + * Fetches the value of this metadata item. + * + * @return the metadata value. + */ + Object value(); + + /** + * Attempts to convert the value of this metadata item into an int. + * + * @return the value as an int. + */ + int asInt(); + + /** + * Attempts to convert the value of this metadata item into a float. + * + * @return the value as a float. + */ + float asFloat(); + + /** + * Attempts to convert the value of this metadata item into a double. + * + * @return the value as a double. + */ + double asDouble(); + + /** + * Attempts to convert the value of this metadata item into a long. + * + * @return the value as a long. + */ + long asLong(); + + /** + * Attempts to convert the value of this metadata item into a short. + * + * @return the value as a short. + */ + short asShort(); + + /** + * Attempts to convert the value of this metadata item into a byte. + * + * @return the value as a byte. + */ + byte asByte(); + + /** + * Attempts to convert the value of this metadata item into a boolean. + * + * @return the value as a boolean. + */ + boolean asBoolean(); + + /** + * Attempts to convert the value of this metadata item into a string. + * + * @return the value as a string. + */ + String asString(); + + /** + * Returns the {@link Plugin} that created this metadata item. + * + * @return the plugin that owns this metadata value. This should never be + * null. + */ + Plugin getOwningPlugin(); + + /** + * Invalidates this metadata item, forcing it to recompute when next + * accessed. + */ + void invalidate(); +} diff --git a/azurite-api/src/main/java/org/bukkit/metadata/MetadataValueAdapter.java b/azurite-api/src/main/java/org/bukkit/metadata/MetadataValueAdapter.java new file mode 100644 index 0000000..5a54921 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/metadata/MetadataValueAdapter.java @@ -0,0 +1,78 @@ +package org.bukkit.metadata; + +import org.apache.commons.lang.Validate; +import org.bukkit.plugin.Plugin; +import org.bukkit.util.NumberConversions; + +import java.lang.ref.WeakReference; + +/** + * Optional base class for facilitating MetadataValue implementations. + *

+ * This provides all the conversion functions for MetadataValue so that + * writing an implementation of MetadataValue is as simple as implementing + * value() and invalidate(). + */ +public abstract class MetadataValueAdapter implements MetadataValue { + protected final WeakReference owningPlugin; + + protected MetadataValueAdapter(Plugin owningPlugin) { + Validate.notNull(owningPlugin, "owningPlugin cannot be null"); + this.owningPlugin = new WeakReference(owningPlugin); + } + + public Plugin getOwningPlugin() { + return owningPlugin.get(); + } + + public int asInt() { + return NumberConversions.toInt(value()); + } + + public float asFloat() { + return NumberConversions.toFloat(value()); + } + + public double asDouble() { + return NumberConversions.toDouble(value()); + } + + public long asLong() { + return NumberConversions.toLong(value()); + } + + public short asShort() { + return NumberConversions.toShort(value()); + } + + public byte asByte() { + return NumberConversions.toByte(value()); + } + + public boolean asBoolean() { + Object value = value(); + if (value instanceof Boolean) { + return (Boolean) value; + } + + if (value instanceof Number) { + return ((Number) value).intValue() != 0; + } + + if (value instanceof String) { + return Boolean.parseBoolean((String) value); + } + + return value != null; + } + + public String asString() { + Object value = value(); + + if (value == null) { + return ""; + } + return value.toString(); + } + +} diff --git a/azurite-api/src/main/java/org/bukkit/metadata/Metadatable.java b/azurite-api/src/main/java/org/bukkit/metadata/Metadatable.java new file mode 100644 index 0000000..193d56e --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/metadata/Metadatable.java @@ -0,0 +1,52 @@ +package org.bukkit.metadata; + +import org.bukkit.plugin.Plugin; + +import java.util.List; + +/** + * This interface is implemented by all objects that can provide metadata + * about themselves. + */ +public interface Metadatable { + /** + * Sets a metadata value in the implementing object's metadata store. + * + * @param metadataKey A unique key to identify this metadata. + * @param newMetadataValue The metadata value to apply. + * @throws IllegalArgumentException If value is null, or the owning plugin + * is null + */ + void setMetadata(String metadataKey, MetadataValue newMetadataValue); + + /** + * Returns a list of previously set metadata values from the implementing + * object's metadata store. + * + * @param metadataKey the unique metadata key being sought. + * @return A list of values, one for each plugin that has set the + * requested value. + */ + List getMetadata(String metadataKey); + + /** + * Tests to see whether the implementing object contains the given + * metadata value in its metadata store. + * + * @param metadataKey the unique metadata key being queried. + * @return the existence of the metadataKey within subject. + */ + boolean hasMetadata(String metadataKey); + + /** + * Removes the given metadata value from the implementing object's + * metadata store. + * + * @param metadataKey the unique metadata key identifying the metadata to + * remove. + * @param owningPlugin This plugin's metadata value will be removed. All + * other values will be left untouched. + * @throws IllegalArgumentException If plugin is null + */ + void removeMetadata(String metadataKey, Plugin owningPlugin); +} diff --git a/azurite-api/src/main/java/org/bukkit/permissions/Permissible.java b/azurite-api/src/main/java/org/bukkit/permissions/Permissible.java new file mode 100644 index 0000000..7edfed7 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/permissions/Permissible.java @@ -0,0 +1,123 @@ +package org.bukkit.permissions; + +import org.bukkit.plugin.Plugin; + +import java.util.Set; + +/** + * Represents an object that may be assigned permissions + */ +public interface Permissible extends ServerOperator { + + /** + * Checks if this object contains an override for the specified + * permission, by fully qualified name + * + * @param name Name of the permission + * @return true if the permission is set, otherwise false + */ + boolean isPermissionSet(String name); + + /** + * Checks if this object contains an override for the specified {@link + * Permission} + * + * @param perm Permission to check + * @return true if the permission is set, otherwise false + */ + boolean isPermissionSet(Permission perm); + + /** + * Gets the value of the specified permission, if set. + *

+ * If a permission override is not set on this object, the default value + * of the permission will be returned. + * + * @param name Name of the permission + * @return Value of the permission + */ + boolean hasPermission(String name); + + /** + * Gets the value of the specified permission, if set. + *

+ * If a permission override is not set on this object, the default value + * of the permission will be returned + * + * @param perm Permission to get + * @return Value of the permission + */ + boolean hasPermission(Permission perm); + + /** + * Adds a new {@link PermissionAttachment} with a single permission by + * name and value + * + * @param plugin Plugin responsible for this attachment, may not be null + * or disabled + * @param name Name of the permission to attach + * @param value Value of the permission + * @return The PermissionAttachment that was just created + */ + PermissionAttachment addAttachment(Plugin plugin, String name, boolean value); + + /** + * Adds a new empty {@link PermissionAttachment} to this object + * + * @param plugin Plugin responsible for this attachment, may not be null + * or disabled + * @return The PermissionAttachment that was just created + */ + PermissionAttachment addAttachment(Plugin plugin); + + /** + * Temporarily adds a new {@link PermissionAttachment} with a single + * permission by name and value + * + * @param plugin Plugin responsible for this attachment, may not be null + * or disabled + * @param name Name of the permission to attach + * @param value Value of the permission + * @param ticks Amount of ticks to automatically remove this attachment + * after + * @return The PermissionAttachment that was just created + */ + PermissionAttachment addAttachment(Plugin plugin, String name, boolean value, int ticks); + + /** + * Temporarily adds a new empty {@link PermissionAttachment} to this + * object + * + * @param plugin Plugin responsible for this attachment, may not be null + * or disabled + * @param ticks Amount of ticks to automatically remove this attachment + * after + * @return The PermissionAttachment that was just created + */ + PermissionAttachment addAttachment(Plugin plugin, int ticks); + + /** + * Removes the given {@link PermissionAttachment} from this object + * + * @param attachment Attachment to remove + * @throws IllegalArgumentException Thrown when the specified attachment + * isn't part of this object + */ + void removeAttachment(PermissionAttachment attachment); + + /** + * Recalculates the permissions for this object, if the attachments have + * changed values. + *

+ * This should very rarely need to be called from a plugin. + */ + void recalculatePermissions(); + + /** + * Gets a set containing all of the permissions currently in effect by + * this object + * + * @return Set of currently effective permissions + */ + Set getEffectivePermissions(); +} diff --git a/azurite-api/src/main/java/org/bukkit/permissions/PermissibleBase.java b/azurite-api/src/main/java/org/bukkit/permissions/PermissibleBase.java new file mode 100644 index 0000000..58a67ff --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/permissions/PermissibleBase.java @@ -0,0 +1,242 @@ +package org.bukkit.permissions; + +import org.bukkit.Bukkit; +import org.bukkit.plugin.Plugin; + +import java.util.*; +import java.util.logging.Level; + +/** + * Base Permissible for use in any Permissible object via proxy or extension + */ +public class PermissibleBase implements Permissible { + private ServerOperator opable = null; + private Permissible parent = this; + private final List attachments = new LinkedList(); + private final Map permissions = new HashMap(); + + public PermissibleBase(ServerOperator opable) { + this.opable = opable; + + if (opable instanceof Permissible) { + this.parent = (Permissible) opable; + } + + recalculatePermissions(); + } + + public boolean isOp() { + if (opable == null) { + return false; + } else { + return opable.isOp(); + } + } + + public void setOp(boolean value) { + if (opable == null) { + throw new UnsupportedOperationException("Cannot change op value as no ServerOperator is set"); + } else { + opable.setOp(value); + } + } + + public boolean isPermissionSet(String name) { + if (name == null) { + throw new IllegalArgumentException("Permission name cannot be null"); + } + + return permissions.containsKey(name.toLowerCase()); + } + + public boolean isPermissionSet(Permission perm) { + if (perm == null) { + throw new IllegalArgumentException("Permission cannot be null"); + } + + return isPermissionSet(perm.getName()); + } + + public boolean hasPermission(String inName) { + if (inName == null) { + throw new IllegalArgumentException("Permission name cannot be null"); + } + + String name = inName.toLowerCase(); + + if (isPermissionSet(name)) { + return permissions.get(name).getValue(); + } else { + Permission perm = Bukkit.getServer().getPluginManager().getPermission(name); + + if (perm != null) { + return perm.getDefault().getValue(isOp()); + } else { + return Permission.DEFAULT_PERMISSION.getValue(isOp()); + } + } + } + + public boolean hasPermission(Permission perm) { + if (perm == null) { + throw new IllegalArgumentException("Permission cannot be null"); + } + + String name = perm.getName().toLowerCase(); + + if (isPermissionSet(name)) { + return permissions.get(name).getValue(); + } + return perm.getDefault().getValue(isOp()); + } + + public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value) { + if (name == null) { + throw new IllegalArgumentException("Permission name cannot be null"); + } else if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null"); + } else if (!plugin.isEnabled()) { + throw new IllegalArgumentException("Plugin " + plugin.getDescription().getFullName() + " is disabled"); + } + + PermissionAttachment result = addAttachment(plugin); + result.setPermission(name, value); + + recalculatePermissions(); + + return result; + } + + public PermissionAttachment addAttachment(Plugin plugin) { + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null"); + } else if (!plugin.isEnabled()) { + throw new IllegalArgumentException("Plugin " + plugin.getDescription().getFullName() + " is disabled"); + } + + PermissionAttachment result = new PermissionAttachment(plugin, parent); + + attachments.add(result); + recalculatePermissions(); + + return result; + } + + public void removeAttachment(PermissionAttachment attachment) { + if (attachment == null) { + throw new IllegalArgumentException("Attachment cannot be null"); + } + + if (attachments.contains(attachment)) { + attachments.remove(attachment); + PermissionRemovedExecutor ex = attachment.getRemovalCallback(); + + if (ex != null) { + ex.attachmentRemoved(attachment); + } + + recalculatePermissions(); + } else { + throw new IllegalArgumentException("Given attachment is not part of Permissible object " + parent); + } + } + + public void recalculatePermissions() { + clearPermissions(); + Set defaults = Bukkit.getServer().getPluginManager().getDefaultPermissions(isOp()); + Bukkit.getServer().getPluginManager().subscribeToDefaultPerms(isOp(), parent); + + for (Permission perm : defaults) { + String name = perm.getName().toLowerCase(); + permissions.put(name, new PermissionAttachmentInfo(parent, name, null, true)); + Bukkit.getServer().getPluginManager().subscribeToPermission(name, parent); + calculateChildPermissions(perm.getChildren(), false, null); + } + + for (PermissionAttachment attachment : attachments) { + calculateChildPermissions(attachment.getPermissions(), false, attachment); + } + } + + public synchronized void clearPermissions() { + Set perms = permissions.keySet(); + + for (String name : perms) { + Bukkit.getServer().getPluginManager().unsubscribeFromPermission(name, parent); + } + + Bukkit.getServer().getPluginManager().unsubscribeFromDefaultPerms(false, parent); + Bukkit.getServer().getPluginManager().unsubscribeFromDefaultPerms(true, parent); + + permissions.clear(); + } + + private void calculateChildPermissions(Map children, boolean invert, PermissionAttachment attachment) { + Set keys = children.keySet(); + + for (String name : keys) { + Permission perm = Bukkit.getServer().getPluginManager().getPermission(name); + boolean value = children.get(name) ^ invert; + String lname = name.toLowerCase(); + + permissions.put(lname, new PermissionAttachmentInfo(parent, lname, attachment, value)); + Bukkit.getServer().getPluginManager().subscribeToPermission(name, parent); + + if (perm != null) { + calculateChildPermissions(perm.getChildren(), !value, attachment); + } + } + } + + public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value, int ticks) { + if (name == null) { + throw new IllegalArgumentException("Permission name cannot be null"); + } else if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null"); + } else if (!plugin.isEnabled()) { + throw new IllegalArgumentException("Plugin " + plugin.getDescription().getFullName() + " is disabled"); + } + + PermissionAttachment result = addAttachment(plugin, ticks); + + if (result != null) { + result.setPermission(name, value); + } + + return result; + } + + public PermissionAttachment addAttachment(Plugin plugin, int ticks) { + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null"); + } else if (!plugin.isEnabled()) { + throw new IllegalArgumentException("Plugin " + plugin.getDescription().getFullName() + " is disabled"); + } + + PermissionAttachment result = addAttachment(plugin); + + if (Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new RemoveAttachmentRunnable(result), ticks) == -1) { + Bukkit.getServer().getLogger().log(Level.WARNING, "Could not add PermissionAttachment to " + parent + " for plugin " + plugin.getDescription().getFullName() + ": Scheduler returned -1"); + result.remove(); + return null; + } else { + return result; + } + } + + public Set getEffectivePermissions() { + return new HashSet(permissions.values()); + } + + private class RemoveAttachmentRunnable implements Runnable { + private PermissionAttachment attachment; + + public RemoveAttachmentRunnable(PermissionAttachment attachment) { + this.attachment = attachment; + } + + public void run() { + attachment.remove(); + } + } +} diff --git a/azurite-api/src/main/java/org/bukkit/permissions/Permission.java b/azurite-api/src/main/java/org/bukkit/permissions/Permission.java new file mode 100644 index 0000000..822f1ef --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/permissions/Permission.java @@ -0,0 +1,341 @@ +package org.bukkit.permissions; + +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.plugin.PluginManager; + +import java.util.*; +import java.util.logging.Level; + +/** + * Represents a unique permission that may be attached to a {@link + * Permissible} + */ +public class Permission { + public static final PermissionDefault DEFAULT_PERMISSION = PermissionDefault.OP; + + private final String name; + private final Map children = new LinkedHashMap(); + private PermissionDefault defaultValue = DEFAULT_PERMISSION; + private String description; + + public Permission(String name) { + this(name, null, null, null); + } + + public Permission(String name, String description) { + this(name, description, null, null); + } + + public Permission(String name, PermissionDefault defaultValue) { + this(name, null, defaultValue, null); + } + + public Permission(String name, String description, PermissionDefault defaultValue) { + this(name, description, defaultValue, null); + } + + public Permission(String name, Map children) { + this(name, null, null, children); + } + + public Permission(String name, String description, Map children) { + this(name, description, null, children); + } + + public Permission(String name, PermissionDefault defaultValue, Map children) { + this(name, null, defaultValue, children); + } + + public Permission(String name, String description, PermissionDefault defaultValue, Map children) { + Validate.notNull(name, "Name cannot be null"); + this.name = name; + this.description = (description == null) ? "" : description; + + if (defaultValue != null) { + this.defaultValue = defaultValue; + } + + if (children != null) { + this.children.putAll(children); + } + + recalculatePermissibles(); + } + + /** + * Returns the unique fully qualified name of this Permission + * + * @return Fully qualified name + */ + public String getName() { + return name; + } + + /** + * Gets the children of this permission. + *

+ * If you change this map in any form, you must call {@link + * #recalculatePermissibles()} to recalculate all {@link Permissible}s + * + * @return Permission children + */ + public Map getChildren() { + return children; + } + + /** + * Gets the default value of this permission. + * + * @return Default value of this permission. + */ + public PermissionDefault getDefault() { + return defaultValue; + } + + /** + * Sets the default value of this permission. + *

+ * This will not be saved to disk, and is a temporary operation until the + * server reloads permissions. Changing this default will cause all {@link + * Permissible}s that contain this permission to recalculate their + * permissions + * + * @param value The new default to set + */ + public void setDefault(PermissionDefault value) { + if (defaultValue == null) { + throw new IllegalArgumentException("Default value cannot be null"); + } + + defaultValue = value; + recalculatePermissibles(); + } + + /** + * Gets a brief description of this permission, if set + * + * @return Brief description of this permission + */ + public String getDescription() { + return description; + } + + /** + * Sets the description of this permission. + *

+ * This will not be saved to disk, and is a temporary operation until the + * server reloads permissions. + * + * @param value The new description to set + */ + public void setDescription(String value) { + if (value == null) { + description = ""; + } else { + description = value; + } + } + + /** + * Gets a set containing every {@link Permissible} that has this + * permission. + *

+ * This set cannot be modified. + * + * @return Set containing permissibles with this permission + */ + public Set getPermissibles() { + return Bukkit.getServer().getPluginManager().getPermissionSubscriptions(name); + } + + /** + * Recalculates all {@link Permissible}s that contain this permission. + *

+ * This should be called after modifying the children, and is + * automatically called after modifying the default value + */ + public void recalculatePermissibles() { + Set perms = getPermissibles(); + + Bukkit.getServer().getPluginManager().recalculatePermissionDefaults(this); + + for (Permissible p : perms) { + p.recalculatePermissions(); + } + } + + /** + * Adds this permission to the specified parent permission. + *

+ * If the parent permission does not exist, it will be created and + * registered. + * + * @param name Name of the parent permission + * @param value The value to set this permission to + * @return Parent permission it created or loaded + */ + public Permission addParent(String name, boolean value) { + PluginManager pm = Bukkit.getServer().getPluginManager(); + String lname = name.toLowerCase(); + + Permission perm = pm.getPermission(lname); + + if (perm == null) { + perm = new Permission(lname); + pm.addPermission(perm); + } + + addParent(perm, value); + + return perm; + } + + /** + * Adds this permission to the specified parent permission. + * + * @param perm Parent permission to register with + * @param value The value to set this permission to + */ + public void addParent(Permission perm, boolean value) { + perm.getChildren().put(getName(), value); + perm.recalculatePermissibles(); + } + + /** + * Loads a list of Permissions from a map of data, usually used from + * retrieval from a yaml file. + *

+ * The data may contain a list of name:data, where the data contains the + * following keys: + *

    + *
  • default: Boolean true or false. If not specified, false. + *
  • children: {@code Map} of child permissions. If not + * specified, empty list. + *
  • description: Short string containing a very small description of + * this description. If not specified, empty string. + *
+ * + * @param data Map of permissions + * @param error An error message to show if a permission is invalid. + * @param def Default permission value to use if missing + * @return Permission object + */ + public static List loadPermissions(Map data, String error, PermissionDefault def) { + List result = new ArrayList(); + + for (Map.Entry entry : data.entrySet()) { + try { + result.add(Permission.loadPermission(entry.getKey().toString(), (Map) entry.getValue(), def, result)); + } catch (Throwable ex) { + Bukkit.getServer().getLogger().log(Level.SEVERE, String.format(error, entry.getKey()), ex); + } + } + + return result; + } + + /** + * Loads a Permission from a map of data, usually used from retrieval from + * a yaml file. + *

+ * The data may contain the following keys: + *

    + *
  • default: Boolean true or false. If not specified, false. + *
  • children: {@code Map} of child permissions. If not + * specified, empty list. + *
  • description: Short string containing a very small description of + * this description. If not specified, empty string. + *
+ * + * @param name Name of the permission + * @param data Map of keys + * @return Permission object + */ + public static Permission loadPermission(String name, Map data) { + return loadPermission(name, data, DEFAULT_PERMISSION, null); + } + + /** + * Loads a Permission from a map of data, usually used from retrieval from + * a yaml file. + *

+ * The data may contain the following keys: + *

    + *
  • default: Boolean true or false. If not specified, false. + *
  • children: {@code Map} of child permissions. If not + * specified, empty list. + *
  • description: Short string containing a very small description of + * this description. If not specified, empty string. + *
+ * + * @param name Name of the permission + * @param data Map of keys + * @param def Default permission value to use if not set + * @param output A list to append any created child-Permissions to, may be null + * @return Permission object + */ + public static Permission loadPermission(String name, Map data, PermissionDefault def, List output) { + Validate.notNull(name, "Name cannot be null"); + Validate.notNull(data, "Data cannot be null"); + + String desc = null; + Map children = null; + + if (data.get("default") != null) { + PermissionDefault value = PermissionDefault.getByName(data.get("default").toString()); + if (value != null) { + def = value; + } else { + throw new IllegalArgumentException("'default' key contained unknown value"); + } + } + + if (data.get("children") != null) { + Object childrenNode = data.get("children"); + if (childrenNode instanceof Iterable) { + children = new LinkedHashMap(); + for (Object child : (Iterable) childrenNode) { + if (child != null) { + children.put(child.toString(), Boolean.TRUE); + } + } + } else if (childrenNode instanceof Map) { + children = extractChildren((Map) childrenNode, name, def, output); + } else { + throw new IllegalArgumentException("'children' key is of wrong type"); + } + } + + if (data.get("description") != null) { + desc = data.get("description").toString(); + } + + return new Permission(name, desc, def, children); + } + + private static Map extractChildren(Map input, String name, PermissionDefault def, List output) { + Map children = new LinkedHashMap(); + + for (Map.Entry entry : input.entrySet()) { + if ((entry.getValue() instanceof Boolean)) { + children.put(entry.getKey().toString(), (Boolean) entry.getValue()); + } else if ((entry.getValue() instanceof Map)) { + try { + Permission perm = loadPermission(entry.getKey().toString(), (Map) entry.getValue(), def, output); + children.put(perm.getName(), Boolean.TRUE); + + if (output != null) { + output.add(perm); + } + } catch (Throwable ex) { + throw new IllegalArgumentException("Permission node '" + entry.getKey().toString() + "' in child of " + name + " is invalid", ex); + } + } else { + throw new IllegalArgumentException("Child '" + entry.getKey().toString() + "' contains invalid value"); + } + } + + return children; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/permissions/PermissionAttachment.java b/azurite-api/src/main/java/org/bukkit/permissions/PermissionAttachment.java new file mode 100644 index 0000000..e419193 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/permissions/PermissionAttachment.java @@ -0,0 +1,140 @@ +package org.bukkit.permissions; + +import org.bukkit.plugin.Plugin; + +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * Holds information about a permission attachment on a {@link Permissible} + * object + */ +public class PermissionAttachment { + private PermissionRemovedExecutor removed; + private final Map permissions = new LinkedHashMap(); + private final Permissible permissible; + private final Plugin plugin; + + public PermissionAttachment(Plugin plugin, Permissible Permissible) { + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null"); + } else if (!plugin.isEnabled()) { + throw new IllegalArgumentException("Plugin " + plugin.getDescription().getFullName() + " is disabled"); + } + + this.permissible = Permissible; + this.plugin = plugin; + } + + /** + * Gets the plugin responsible for this attachment + * + * @return Plugin responsible for this permission attachment + */ + public Plugin getPlugin() { + return plugin; + } + + /** + * Sets an object to be called for when this attachment is removed from a + * {@link Permissible}. May be null. + * + * @param ex Object to be called when this is removed + */ + public void setRemovalCallback(PermissionRemovedExecutor ex) { + removed = ex; + } + + /** + * Gets the class that was previously set to be called when this + * attachment was removed from a {@link Permissible}. May be null. + * + * @return Object to be called when this is removed + */ + public PermissionRemovedExecutor getRemovalCallback() { + return removed; + } + + /** + * Gets the Permissible that this is attached to + * + * @return Permissible containing this attachment + */ + public Permissible getPermissible() { + return permissible; + } + + /** + * Gets a copy of all set permissions and values contained within this + * attachment. + *

+ * This map may be modified but will not affect the attachment, as it is a + * copy. + * + * @return Copy of all permissions and values expressed by this attachment + */ + public Map getPermissions() { + return new LinkedHashMap(permissions); + } + + /** + * Sets a permission to the given value, by its fully qualified name + * + * @param name Name of the permission + * @param value New value of the permission + */ + public void setPermission(String name, boolean value) { + permissions.put(name.toLowerCase(), value); + permissible.recalculatePermissions(); + } + + /** + * Sets a permission to the given value + * + * @param perm Permission to set + * @param value New value of the permission + */ + public void setPermission(Permission perm, boolean value) { + setPermission(perm.getName(), value); + } + + /** + * Removes the specified permission from this attachment. + *

+ * If the permission does not exist in this attachment, nothing will + * happen. + * + * @param name Name of the permission to remove + */ + public void unsetPermission(String name) { + permissions.remove(name.toLowerCase()); + permissible.recalculatePermissions(); + } + + /** + * Removes the specified permission from this attachment. + *

+ * If the permission does not exist in this attachment, nothing will + * happen. + * + * @param perm Permission to remove + */ + public void unsetPermission(Permission perm) { + unsetPermission(perm.getName()); + } + + /** + * Removes this attachment from its registered {@link Permissible} + * + * @return true if the permissible was removed successfully, false if it + * did not exist + */ + public boolean remove() { + try { + permissible.removeAttachment(this); + return true; + } catch (IllegalArgumentException ex) { + return false; + } + } +} diff --git a/azurite-api/src/main/java/org/bukkit/permissions/PermissionAttachmentInfo.java b/azurite-api/src/main/java/org/bukkit/permissions/PermissionAttachmentInfo.java new file mode 100644 index 0000000..8e8e335 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/permissions/PermissionAttachmentInfo.java @@ -0,0 +1,62 @@ +package org.bukkit.permissions; + +/** + * Holds information on a permission and which {@link PermissionAttachment} + * provides it + */ +public class PermissionAttachmentInfo { + private final Permissible permissible; + private final String permission; + private final PermissionAttachment attachment; + private final boolean value; + + public PermissionAttachmentInfo(Permissible permissible, String permission, PermissionAttachment attachment, boolean value) { + if (permissible == null) { + throw new IllegalArgumentException("Permissible may not be null"); + } else if (permission == null) { + throw new IllegalArgumentException("Permissions may not be null"); + } + + this.permissible = permissible; + this.permission = permission; + this.attachment = attachment; + this.value = value; + } + + /** + * Gets the permissible this is attached to + * + * @return Permissible this permission is for + */ + public Permissible getPermissible() { + return permissible; + } + + /** + * Gets the permission being set + * + * @return Name of the permission + */ + public String getPermission() { + return permission; + } + + /** + * Gets the attachment providing this permission. This may be null for + * default permissions (usually parent permissions). + * + * @return Attachment + */ + public PermissionAttachment getAttachment() { + return attachment; + } + + /** + * Gets the value of this permission + * + * @return Value of the permission + */ + public boolean getValue() { + return value; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/permissions/PermissionDefault.java b/azurite-api/src/main/java/org/bukkit/permissions/PermissionDefault.java new file mode 100644 index 0000000..1703e50 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/permissions/PermissionDefault.java @@ -0,0 +1,66 @@ +package org.bukkit.permissions; + +import java.util.HashMap; +import java.util.Map; + +/** + * Represents the possible default values for permissions + */ +public enum PermissionDefault { + TRUE("true"), + FALSE("false"), + OP("op", "isop", "operator", "isoperator", "admin", "isadmin"), + NOT_OP("!op", "notop", "!operator", "notoperator", "!admin", "notadmin"); + + private final String[] names; + private final static Map lookup = new HashMap(); + + PermissionDefault(String... names) { + this.names = names; + } + + /** + * Calculates the value of this PermissionDefault for the given operator + * value + * + * @param op If the target is op + * @return True if the default should be true, or false + */ + public boolean getValue(boolean op) { + switch (this) { + case TRUE: + return true; + case FALSE: + return false; + case OP: + return op; + case NOT_OP: + return !op; + default: + return false; + } + } + + /** + * Looks up a PermissionDefault by name + * + * @param name Name of the default + * @return Specified value, or null if not found + */ + public static PermissionDefault getByName(String name) { + return lookup.get(name.toLowerCase().replaceAll("[^a-z!]", "")); + } + + @Override + public String toString() { + return names[0]; + } + + static { + for (PermissionDefault value : values()) { + for (String name : value.names) { + lookup.put(name, value); + } + } + } +} diff --git a/azurite-api/src/main/java/org/bukkit/permissions/PermissionRemovedExecutor.java b/azurite-api/src/main/java/org/bukkit/permissions/PermissionRemovedExecutor.java new file mode 100644 index 0000000..f08ad96 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/permissions/PermissionRemovedExecutor.java @@ -0,0 +1,16 @@ +package org.bukkit.permissions; + +/** + * Represents a class which is to be notified when a {@link + * PermissionAttachment} is removed from a {@link Permissible} + */ +public interface PermissionRemovedExecutor { + + /** + * Called when a {@link PermissionAttachment} is removed from a {@link + * Permissible} + * + * @param attachment Attachment which was removed + */ + void attachmentRemoved(PermissionAttachment attachment); +} diff --git a/azurite-api/src/main/java/org/bukkit/permissions/ServerOperator.java b/azurite-api/src/main/java/org/bukkit/permissions/ServerOperator.java new file mode 100644 index 0000000..cb40479 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/permissions/ServerOperator.java @@ -0,0 +1,24 @@ +package org.bukkit.permissions; + +import org.bukkit.entity.Player; + +/** + * Represents an object that may become a server operator, such as a {@link + * Player} + */ +public interface ServerOperator { + + /** + * Checks if this object is a server operator + * + * @return true if this is an operator, otherwise false + */ + boolean isOp(); + + /** + * Sets the operator status of this object + * + * @param value New operator value + */ + void setOp(boolean value); +} diff --git a/azurite-api/src/main/java/org/bukkit/plugin/AuthorNagException.java b/azurite-api/src/main/java/org/bukkit/plugin/AuthorNagException.java new file mode 100644 index 0000000..6565a44 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/plugin/AuthorNagException.java @@ -0,0 +1,20 @@ +package org.bukkit.plugin; + +@SuppressWarnings("serial") +public class AuthorNagException extends RuntimeException { + private final String message; + + /** + * Constructs a new AuthorNagException based on the given Exception + * + * @param message Brief message explaining the cause of the exception + */ + public AuthorNagException(final String message) { + this.message = message; + } + + @Override + public String getMessage() { + return message; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/plugin/EventExecutor.java b/azurite-api/src/main/java/org/bukkit/plugin/EventExecutor.java new file mode 100644 index 0000000..8def3b1 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/plugin/EventExecutor.java @@ -0,0 +1,77 @@ +package org.bukkit.plugin; + +import com.destroystokyo.paper.event.executor.MethodHandleEventExecutor; +import com.destroystokyo.paper.event.executor.StaticMethodHandleEventExecutor; +import com.destroystokyo.paper.event.executor.asm.ASMEventExecutorGenerator; +import com.destroystokyo.paper.event.executor.asm.ClassDefiner; +import com.google.common.base.Preconditions; +import org.bukkit.event.Event; +import org.bukkit.event.EventException; +import org.bukkit.event.Listener; +import org.jetbrains.annotations.NotNull; + +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.function.Function; + +/** + * Interface which defines the class for event call backs to plugins + */ +public interface EventExecutor { + + void execute(Listener listener, Event event) throws EventException; + + // Paper start + ConcurrentMap> eventExecutorMap = new ConcurrentHashMap>() { + @NotNull + @Override + public Class computeIfAbsent(@NotNull Method key, @NotNull Function> mappingFunction) { + Class executorClass = get(key); + if (executorClass != null) + return executorClass; + + //noinspection SynchronizationOnLocalVariableOrMethodParameter + synchronized (key) { + executorClass = get(key); + if (executorClass != null) + return executorClass; + + return super.computeIfAbsent(key, mappingFunction); + } + } + }; + + @NotNull + public static EventExecutor create(@NotNull Method m, @NotNull Class eventClass) { + Preconditions.checkNotNull(m, "Null method"); + Preconditions.checkArgument(m.getParameterCount() != 0, "Incorrect number of arguments %s", m.getParameterCount()); + Preconditions.checkArgument(m.getParameterTypes()[0] == eventClass, "First parameter %s doesn't match event class %s", m.getParameterTypes()[0], eventClass); + ClassDefiner definer = ClassDefiner.getInstance(); + if (Modifier.isStatic(m.getModifiers())) { + return new StaticMethodHandleEventExecutor(eventClass, m); + } else if (definer.isBypassAccessChecks() || Modifier.isPublic(m.getDeclaringClass().getModifiers()) && Modifier.isPublic(m.getModifiers())) { + // get the existing generated EventExecutor class for the Method or generate one + Class executorClass = eventExecutorMap.computeIfAbsent(m, (__) -> { + String name = ASMEventExecutorGenerator.generateName(); + byte[] classData = ASMEventExecutorGenerator.generateEventExecutor(m, name); + return definer.defineClass(m.getDeclaringClass().getClassLoader(), name, classData).asSubclass(EventExecutor.class); + }); + + try { + EventExecutor asmExecutor = executorClass.newInstance(); + // Define a wrapper to conform to bukkit stupidity (passing in events that don't match and wrapper exception) + return (listener, event) -> { + if (!eventClass.isInstance(event)) return; + asmExecutor.execute(listener, event); + }; + } catch (InstantiationException | IllegalAccessException e) { + throw new AssertionError("Unable to initialize generated event executor", e); + } + } else { + return new MethodHandleEventExecutor(eventClass, m); + } + } + // Paper end +} diff --git a/azurite-api/src/main/java/org/bukkit/plugin/IllegalPluginAccessException.java b/azurite-api/src/main/java/org/bukkit/plugin/IllegalPluginAccessException.java new file mode 100644 index 0000000..b25447d --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/plugin/IllegalPluginAccessException.java @@ -0,0 +1,25 @@ +package org.bukkit.plugin; + +/** + * Thrown when a plugin attempts to interact with the server when it is not + * enabled + */ +@SuppressWarnings("serial") +public class IllegalPluginAccessException extends RuntimeException { + + /** + * Creates a new instance of IllegalPluginAccessException + * without detail message. + */ + public IllegalPluginAccessException() {} + + /** + * Constructs an instance of IllegalPluginAccessException + * with the specified detail message. + * + * @param msg the detail message. + */ + public IllegalPluginAccessException(String msg) { + super(msg); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/plugin/InvalidDescriptionException.java b/azurite-api/src/main/java/org/bukkit/plugin/InvalidDescriptionException.java new file mode 100644 index 0000000..0a77c2e --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/plugin/InvalidDescriptionException.java @@ -0,0 +1,45 @@ +package org.bukkit.plugin; + +/** + * Thrown when attempting to load an invalid PluginDescriptionFile + */ +public class InvalidDescriptionException extends Exception { + private static final long serialVersionUID = 5721389122281775896L; + + /** + * Constructs a new InvalidDescriptionException based on the given + * Exception + * + * @param message Brief message explaining the cause of the exception + * @param cause Exception that triggered this Exception + */ + public InvalidDescriptionException(final Throwable cause, final String message) { + super(message, cause); + } + + /** + * Constructs a new InvalidDescriptionException based on the given + * Exception + * + * @param cause Exception that triggered this Exception + */ + public InvalidDescriptionException(final Throwable cause) { + super("Invalid plugin.yml", cause); + } + + /** + * Constructs a new InvalidDescriptionException with the given message + * + * @param message Brief message explaining the cause of the exception + */ + public InvalidDescriptionException(final String message) { + super(message); + } + + /** + * Constructs a new InvalidDescriptionException + */ + public InvalidDescriptionException() { + super("Invalid plugin.yml"); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/plugin/InvalidPluginException.java b/azurite-api/src/main/java/org/bukkit/plugin/InvalidPluginException.java new file mode 100644 index 0000000..7ddf7b6 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/plugin/InvalidPluginException.java @@ -0,0 +1,49 @@ +package org.bukkit.plugin; + +/** + * Thrown when attempting to load an invalid Plugin file + */ +public class InvalidPluginException extends Exception { + private static final long serialVersionUID = -8242141640709409544L; + + /** + * Constructs a new InvalidPluginException based on the given Exception + * + * @param cause Exception that triggered this Exception + */ + public InvalidPluginException(final Throwable cause) { + super(cause); + } + + /** + * Constructs a new InvalidPluginException + */ + public InvalidPluginException() { + + } + + /** + * Constructs a new InvalidPluginException with the specified detail + * message and cause. + * + * @param message the detail message (which is saved for later retrieval + * by the getMessage() method). + * @param cause the cause (which is saved for later retrieval by the + * getCause() method). (A null value is permitted, and indicates that + * the cause is nonexistent or unknown.) + */ + public InvalidPluginException(final String message, final Throwable cause) { + super(message, cause); + } + + /** + * Constructs a new InvalidPluginException with the specified detail + * message + * + * @param message TThe detail message is saved for later retrieval by the + * getMessage() method. + */ + public InvalidPluginException(final String message) { + super(message); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/plugin/Plugin.java b/azurite-api/src/main/java/org/bukkit/plugin/Plugin.java new file mode 100644 index 0000000..1a43572 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/plugin/Plugin.java @@ -0,0 +1,188 @@ +package org.bukkit.plugin; + +import com.avaje.ebean.EbeanServer; +import org.bukkit.Server; +import org.bukkit.command.TabExecutor; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.generator.ChunkGenerator; + +import java.io.File; +import java.io.InputStream; +import java.util.logging.Logger; + +/** + * Represents a Plugin + *

+ * The use of {@link PluginBase} is recommended for actual Implementation + */ +public interface Plugin extends TabExecutor { + /** + * Returns the folder that the plugin data's files are located in. The + * folder may not yet exist. + * + * @return The folder + */ + File getDataFolder(); + + /** + * Returns the plugin.yaml file containing the details for this plugin + * + * @return Contents of the plugin.yaml file + */ + PluginDescriptionFile getDescription(); + + /** + * Gets a {@link FileConfiguration} for this plugin, read through + * "config.yml" + *

+ * If there is a default config.yml embedded in this plugin, it will be + * provided as a default for this Configuration. + * + * @return Plugin configuration + */ + FileConfiguration getConfig(); + + /** + * Gets an embedded resource in this plugin + * + * @param filename Filename of the resource + * @return File if found, otherwise null + */ + InputStream getResource(String filename); + + /** + * Saves the {@link FileConfiguration} retrievable by {@link #getConfig()}. + */ + void saveConfig(); + + /** + * Saves the raw contents of the default config.yml file to the location + * retrievable by {@link #getConfig()}. If there is no default config.yml + * embedded in the plugin, an empty config.yml file is saved. This should + * fail silently if the config.yml already exists. + */ + void saveDefaultConfig(); + + /** + * Saves the raw contents of any resource embedded with a plugin's .jar + * file assuming it can be found using {@link #getResource(String)}. + *

+ * The resource is saved into the plugin's data folder using the same + * hierarchy as the .jar file (subdirectories are preserved). + * + * @param resourcePath the embedded resource path to look for within the + * plugin's .jar file. (No preceding slash). + * @param replace if true, the embedded resource will overwrite the + * contents of an existing file. + * @throws IllegalArgumentException if the resource path is null, empty, + * or points to a nonexistent resource. + */ + void saveResource(String resourcePath, boolean replace); + + /** + * Discards any data in {@link #getConfig()} and reloads from disk. + */ + void reloadConfig(); + + /** + * Gets the associated PluginLoader responsible for this plugin + * + * @return PluginLoader that controls this plugin + */ + PluginLoader getPluginLoader(); + + /** + * Returns the Server instance currently running this plugin + * + * @return Server running this plugin + */ + Server getServer(); + + /** + * Returns a value indicating whether or not this plugin is currently + * enabled + * + * @return true if this plugin is enabled, otherwise false + */ + boolean isEnabled(); + + /** + * Called when this plugin is disabled + */ + void onDisable(); + + /** + * Called after a plugin is loaded but before it has been enabled. + *

+ * When mulitple plugins are loaded, the onLoad() for all plugins is + * called before any onEnable() is called. + */ + void onLoad(); + + /** + * Called when this plugin is enabled + */ + void onEnable(); + + /** + * Simple boolean if we can still nag to the logs about things + * + * @return boolean whether we can nag + */ + boolean isNaggable(); + + /** + * Set naggable state + * + * @param canNag is this plugin still naggable? + */ + void setNaggable(boolean canNag); + + /** + * Gets the {@link EbeanServer} tied to this plugin. This will only be + * available if enabled in the {@link + * PluginDescriptionFile#isDatabaseEnabled()} + *

+ * For more information on the use of + * Avaje Ebeans ORM, see Avaje Ebeans + * Documentation + *

+ * For an example using Ebeans ORM, see Bukkit's Homebukkit Plugin + * + * + * @return ebean server instance or null if not enabled + */ + EbeanServer getDatabase(); + + /** + * Gets a {@link ChunkGenerator} for use in a default world, as specified + * in the server configuration + * + * @param worldName Name of the world that this will be applied to + * @param id Unique ID, if any, that was specified to indicate which + * generator was requested + * @return ChunkGenerator for use in the default world generation + */ + ChunkGenerator getDefaultWorldGenerator(String worldName, String id); + + /** + * Returns the plugin logger associated with this server's logger. The + * returned logger automatically tags all log messages with the plugin's + * name. + * + * @return Logger associated with this plugin + */ + Logger getLogger(); + + /** + * Returns the name of the plugin. + *

+ * This should return the bare name of the plugin and should be used for + * comparison. + * + * @return name of the plugin + */ + String getName(); +} diff --git a/azurite-api/src/main/java/org/bukkit/plugin/PluginAwareness.java b/azurite-api/src/main/java/org/bukkit/plugin/PluginAwareness.java new file mode 100644 index 0000000..fa005f0 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/plugin/PluginAwareness.java @@ -0,0 +1,28 @@ +package org.bukkit.plugin; + +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.Set; + +/** + * Represents a concept that a plugin is aware of. + *

+ * The internal representation may be singleton, or be a parameterized + * instance, but must be immutable. + */ +public interface PluginAwareness { + /** + * Each entry here represents a particular plugin's awareness. These can + * be checked by using {@link PluginDescriptionFile#getAwareness()}.{@link + * Set#contains(Object) contains(flag)}. + */ + enum Flags implements PluginAwareness { + /** + * This specifies that all (text) resources stored in a plugin's jar + * use UTF-8 encoding. + * + * @see JavaPlugin#getTextResource(String) + */ + UTF8, + } +} diff --git a/azurite-api/src/main/java/org/bukkit/plugin/PluginBase.java b/azurite-api/src/main/java/org/bukkit/plugin/PluginBase.java new file mode 100644 index 0000000..6031af1 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/plugin/PluginBase.java @@ -0,0 +1,32 @@ +package org.bukkit.plugin; + +/** + * Represents a base {@link Plugin} + *

+ * Extend this class if your plugin is not a {@link + * org.bukkit.plugin.java.JavaPlugin} + */ +public abstract class PluginBase implements Plugin { + @Override + public final int hashCode() { + return getName().hashCode(); + } + + @Override + public final boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (!(obj instanceof Plugin)) { + return false; + } + return getName().equals(((Plugin) obj).getName()); + } + + public final String getName() { + return getDescription().getName(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/plugin/PluginDescriptionFile.java b/azurite-api/src/main/java/org/bukkit/plugin/PluginDescriptionFile.java new file mode 100644 index 0000000..74fee74 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/plugin/PluginDescriptionFile.java @@ -0,0 +1,1106 @@ +package org.bukkit.plugin; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.PluginCommand; +import org.bukkit.permissions.Permissible; +import org.bukkit.permissions.Permission; +import org.bukkit.permissions.PermissionDefault; +import org.bukkit.plugin.java.JavaPlugin; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.AbstractConstruct; +import org.yaml.snakeyaml.constructor.SafeConstructor; +import org.yaml.snakeyaml.nodes.Node; +import org.yaml.snakeyaml.nodes.Tag; + +import java.io.InputStream; +import java.io.Reader; +import java.io.Writer; +import java.util.*; + +/** + * This type is the runtime-container for the information in the plugin.yml. + * All plugins must have a respective plugin.yml. For plugins written in java + * using the standard plugin loader, this file must be in the root of the jar + * file. + *

+ * When Bukkit loads a plugin, it needs to know some basic information about + * it. It reads this information from a YAML file, 'plugin.yml'. This file + * consists of a set of attributes, each defined on a new line and with no + * indentation. + *

+ * Every (almost* every) method corresponds with a specific entry in the + * plugin.yml. These are the required entries for every plugin.yml: + *

    + *
  • {@link #getName()} - name + *
  • {@link #getVersion()} - version + *
  • {@link #getMain()} - main + *
+ *

+ * Failing to include any of these items will throw an exception and cause the + * server to ignore your plugin. + *

+ * This is a list of the possible yaml keys, with specific details included in + * the respective method documentations: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
The description of the plugin.yml layout
NodeMethodSummary
name{@link #getName()}The unique name of plugin
version{@link #getVersion()}A plugin revision identifier
main{@link #getMain()}The plugin's initial class file
author
authors
{@link #getAuthors()}The plugin contributors
description{@link #getDescription()}Human readable plugin summary
website{@link #getWebsite()}The URL to the plugin's site
prefix{@link #getPrefix()}The token to prefix plugin log entries
database{@link #isDatabaseEnabled()}Indicator to enable database support
load{@link #getLoad()}The phase of server-startup this plugin will load during
depend{@link #getDepend()}Other required plugins
softdepend{@link #getSoftDepend()}Other plugins that add functionality
loadbefore{@link #getLoadBefore()}The inverse softdepend
commands{@link #getCommands()}The commands the plugin will register
permissions{@link #getPermissions()}The permissions the plugin will register
default-permission{@link #getPermissionDefault()}The default {@link Permission#getDefault() default} permission + * state for defined {@link #getPermissions() permissions} the plugin + * will register
awareness{@link #getAwareness()}The concepts that the plugin acknowledges
+ *

+ * A plugin.yml example:

+ * name: Inferno
+ * version: 1.4.1
+ * description: This plugin is so 31337. You can set yourself on fire.
+ * # We could place every author in the authors list, but chose not to for illustrative purposes
+ * # Also, having an author distinguishes that person as the project lead, and ensures their
+ * # name is displayed first
+ * author: CaptainInflamo
+ * authors: [Cogito, verrier, EvilSeph]
+ * website: http://www.curse.com/server-mods/minecraft/myplugin
+ *
+ * main: com.captaininflamo.bukkit.inferno.Inferno
+ * database: false
+ * depend: [NewFire, FlameWire]
+ *
+ * commands:
+ *  flagrate:
+ *    description: Set yourself on fire.
+ *    aliases: [combust_me, combustMe]
+ *    permission: inferno.flagrate
+ *    usage: Syntax error! Simply type /<command> to ignite yourself.
+ *  burningdeaths:
+ *    description: List how many times you have died by fire.
+ *    aliases: [burning_deaths, burningDeaths]
+ *    permission: inferno.burningdeaths
+ *    usage: |
+ *      /<command> [player]
+ *      Example: /<command> - see how many times you have burned to death
+ *      Example: /<command> CaptainIce - see how many times CaptainIce has burned to death
+ *
+ * permissions:
+ *  inferno.*:
+ *    description: Gives access to all Inferno commands
+ *    children:
+ *      inferno.flagrate: true
+ *      inferno.burningdeaths: true
+ *      inferno.burningdeaths.others: true
+ *  inferno.flagrate:
+ *    description: Allows you to ignite yourself
+ *    default: true
+ *  inferno.burningdeaths:
+ *    description: Allows you to see how many times you have burned to death
+ *    default: true
+ *  inferno.burningdeaths.others:
+ *    description: Allows you to see how many times others have burned to death
+ *    default: op
+ *    children:
+ *      inferno.burningdeaths: true
+ * 
+ */ +public final class PluginDescriptionFile { + private static final ThreadLocal YAML = ThreadLocal.withInitial(() -> new Yaml(new SafeConstructor() { + { + yamlConstructors.put(null, new AbstractConstruct() { + @Override + public Object construct(final Node node) { + if (!node.getTag().startsWith("!@")) { + // Unknown tag - will fail + return SafeConstructor.undefinedConstructor.construct(node); + } + // Unknown awareness - provide a graceful substitution + return new PluginAwareness() { + @Override + public String toString() { + return node.toString(); + } + }; + } + }); + for (final PluginAwareness.Flags flag : PluginAwareness.Flags.values()) { + yamlConstructors.put(new Tag("!@" + flag.name()), new AbstractConstruct() { + @Override + public PluginAwareness.Flags construct(final Node node) { + return flag; + } + }); + } + } + })); + String rawName = null; + private String name = null; + private String main = null; + private String classLoaderOf = null; + private List depend = ImmutableList.of(); + private List softDepend = ImmutableList.of(); + private List loadBefore = ImmutableList.of(); + private String version = null; + private Map> commands = null; + private String description = null; + private List authors = null; + private String website = null; + private String prefix = null; + private boolean database = false; + private PluginLoadOrder order = PluginLoadOrder.POSTWORLD; + private List permissions = null; + private Map lazyPermissions = null; + private PermissionDefault defaultPerm = PermissionDefault.OP; + private Set awareness = ImmutableSet.of(); + + public PluginDescriptionFile(final InputStream stream) throws InvalidDescriptionException { + loadMap(asMap(YAML.get().load(stream))); + } + + /** + * Loads a PluginDescriptionFile from the specified reader + * + * @param reader The reader + * @throws InvalidDescriptionException If the PluginDescriptionFile is + * invalid + */ + public PluginDescriptionFile(final Reader reader) throws InvalidDescriptionException { + loadMap(asMap(YAML.get().load(reader))); + } + + /** + * Creates a new PluginDescriptionFile with the given detailed + * + * @param pluginName Name of this plugin + * @param pluginVersion Version of this plugin + * @param mainClass Full location of the main class of this plugin + */ + public PluginDescriptionFile(final String pluginName, final String pluginVersion, final String mainClass) { + name = pluginName.replace(' ', '_'); + version = pluginVersion; + main = mainClass; + } + + /** + * Gives the name of the plugin. This name is a unique identifier for + * plugins. + *
    + *
  • Must consist of all alphanumeric characters, underscores, hyphon, + * and period (a-z,A-Z,0-9, _.-). Any other character will cause the + * plugin.yml to fail loading. + *
  • Used to determine the name of the plugin's data folder. Data + * folders are placed in the ./plugins/ directory by default, but this + * behavior should not be relied on. {@link Plugin#getDataFolder()} + * should be used to reference the data folder. + *
  • It is good practice to name your jar the same as this, for example + * 'MyPlugin.jar'. + *
  • Case sensitive. + *
  • The is the token referenced in {@link #getDepend()}, {@link + * #getSoftDepend()}, and {@link #getLoadBefore()}. + *
  • Using spaces in the plugin's name is deprecated. + *
+ *

+ * In the plugin.yml, this entry is named name. + *

+ * Example:

name: MyPlugin
+ * + * @return the name of the plugin + */ + public String getName() { + return name; + } + + /** + * Gives the version of the plugin. + *
    + *
  • Version is an arbitrary string, however the most common format is + * MajorRelease.MinorRelease.Build (eg: 1.4.1). + *
  • Typically you will increment this every time you release a new + * feature or bug fix. + *
  • Displayed when a user types /version PluginName + *
+ *

+ * In the plugin.yml, this entry is named version. + *

+ * Example:

version: 1.4.1
+ * + * @return the version of the plugin + */ + public String getVersion() { + return version; + } + + /** + * Gives the fully qualified name of the main class for a plugin. The + * format should follow the {@link ClassLoader#loadClass(String)} syntax + * to successfully be resolved at runtime. For most plugins, this is the + * class that extends {@link JavaPlugin}. + *
    + *
  • This must contain the full namespace including the class file + * itself. + *
  • If your namespace is org.bukkit.plugin, and your class + * file is called MyPlugin then this must be + * org.bukkit.plugin.MyPlugin + *
  • No plugin can use org.bukkit. as a base package for + * any class, including the main class. + *
+ *

+ * In the plugin.yml, this entry is named main. + *

+ * Example: + *

main: org.bukkit.plugin.MyPlugin
+ * + * @return the fully qualified main class for the plugin + */ + public String getMain() { + return main; + } + + /** + * Gives a human-friendly description of the functionality the plugin + * provides. + *
    + *
  • The description can have multiple lines. + *
  • Displayed when a user types /version PluginName + *
+ *

+ * In the plugin.yml, this entry is named description. + *

+ * Example: + *

description: This plugin is so 31337. You can set yourself on fire.
+ * + * @return description of this plugin, or null if not specified + */ + public String getDescription() { + return description; + } + + /** + * Gives the phase of server startup that the plugin should be loaded. + *
    + *
  • Possible values are in {@link PluginLoadOrder}. + *
  • Defaults to {@link PluginLoadOrder#POSTWORLD}. + *
  • Certain caveats apply to each phase. + *
  • When different, {@link #getDepend()}, {@link #getSoftDepend()}, and + * {@link #getLoadBefore()} become relative in order loaded per-phase. + * If a plugin loads at STARTUP, but a dependency loads + * at POSTWORLD, the dependency will not be loaded before + * the plugin is loaded. + *
+ *

+ * In the plugin.yml, this entry is named load. + *

+ * Example:

load: STARTUP
+ * + * @return the phase when the plugin should be loaded + */ + public PluginLoadOrder getLoad() { + return order; + } + + /** + * Gives the list of authors for the plugin. + *
    + *
  • Gives credit to the developer. + *
  • Used in some server error messages to provide helpful feedback on + * who to contact when an error occurs. + *
  • A bukkit.org forum handle or email address is recommended. + *
  • Is displayed when a user types /version PluginName + *
  • authors must be in YAML list + * format. + *
+ *

+ * In the plugin.yml, this has two entries, author and + * authors. + *

+ * Single author example: + *

author: CaptainInflamo
+ * Multiple author example: + *
authors: [Cogito, verrier, EvilSeph]
+ * When both are specified, author will be the first entry in the list, so + * this example: + *
author: Grum
+     * authors:
+     * - feildmaster
+     * - amaranth
+ * Is equivilant to this example: + *
authors: [Grum, feildmaster, aramanth]
+ * + * @return an immutable list of the plugin's authors + */ + public List getAuthors() { + return authors; + } + + /** + * Gives the plugin's or plugin's author's website. + *
    + *
  • A link to the Curse page that includes documentation and downloads + * is highly recommended. + *
  • Displayed when a user types /version PluginName + *
+ *

+ * In the plugin.yml, this entry is named website. + *

+ * Example: + *

website: http://www.curse.com/server-mods/minecraft/myplugin
+ * + * @return description of this plugin, or null if not specified + */ + public String getWebsite() { + return website; + } + + /** + * Gives if the plugin uses a database. + *
    + *
  • Using a database is non-trivial. + *
  • Valid values include true and false + *
+ *

+ * In the plugin.yml, this entry is named database. + *

+ * Example: + *

database: false
+ * + * @return if this plugin requires a database + * @see Plugin#getDatabase() + */ + public boolean isDatabaseEnabled() { + return database; + } + + /** + * Gives a list of other plugins that the plugin requires. + *
    + *
  • Use the value in the {@link #getName()} of the target plugin to + * specify the dependency. + *
  • If any plugin listed here is not found, your plugin will fail to + * load at startup. + *
  • If multiple plugins list each other in depend, + * creating a network with no individual plugin does not list another + * plugin in the network, + * all plugins in that network will fail. + *
  • depend must be in must be in YAML list + * format. + *
+ *

+ * In the plugin.yml, this entry is named depend. + *

+ * Example: + *

depend:
+     * - OnePlugin
+     * - AnotherPlugin
+ * + * @return immutable list of the plugin's dependencies + */ + public List getDepend() { + return depend; + } + + /** + * Gives a list of other plugins that the plugin requires for full + * functionality. The {@link PluginManager} will make best effort to treat + * all entries here as if they were a {@link #getDepend() dependency}, but + * will never fail because of one of these entries. + *
    + *
  • Use the value in the {@link #getName()} of the target plugin to + * specify the dependency. + *
  • When an unresolvable plugin is listed, it will be ignored and does + * not affect load order. + *
  • When a circular dependency occurs (a network of plugins depending + * or soft-dependending each other), it will arbitrarily choose a + * plugin that can be resolved when ignoring soft-dependencies. + *
  • softdepend must be in YAML list + * format. + *
+ *

+ * In the plugin.yml, this entry is named softdepend. + *

+ * Example: + *

softdepend: [OnePlugin, AnotherPlugin]
+ * + * @return immutable list of the plugin's preferred dependencies + */ + public List getSoftDepend() { + return softDepend; + } + + /** + * Gets the list of plugins that should consider this plugin a + * soft-dependency. + *
    + *
  • Use the value in the {@link #getName()} of the target plugin to + * specify the dependency. + *
  • The plugin should load before any other plugins listed here. + *
  • Specifying another plugin here is strictly equivalent to having the + * specified plugin's {@link #getSoftDepend()} include {@link + * #getName() this plugin}. + *
  • loadbefore must be in YAML list + * format. + *
+ *

+ * In the plugin.yml, this entry is named loadbefore. + *

+ * Example: + *

loadbefore:
+     * - OnePlugin
+     * - AnotherPlugin
+ * + * @return immutable list of plugins that should consider this plugin a + * soft-dependency + */ + public List getLoadBefore() { + return loadBefore; + } + + /** + * Gives the token to prefix plugin-specific logging messages with. + *
    + *
  • This includes all messages using {@link Plugin#getLogger()}. + *
  • If not specified, the server uses the plugin's {@link #getName() + * name}. + *
  • This should clearly indicate what plugin is being logged. + *
+ *

+ * In the plugin.yml, this entry is named prefix. + *

+ * Example:

prefix: ex-why-zee
+ * + * @return the prefixed logging token, or null if not specified + */ + public String getPrefix() { + return prefix; + } + + /** + * Gives the map of command-name to command-properties. Each entry in this + * map corresponds to a single command and the respective values are the + * properties of the command. Each property, with the exception of + * aliases, can be defined at runtime using methods in {@link + * PluginCommand} and are defined here only as a convenience. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
The command section's description
NodeMethodTypeDescriptionExample
description{@link PluginCommand#setDescription(String)}StringA user-friendly description for a command. It is useful for + * documentation purposes as well as in-game help.
description: Set yourself on fire
aliases{@link PluginCommand#setAliases(List)}String or List of + * stringsAlternative command names, with special usefulness for commands + * that are already registered. Aliases are not effective when + * defined at runtime, so the plugin description file is the + * only way to have them properly defined. + *

+ * Note: Command aliases may not have a colon in them.

Single alias format: + *
aliases: combust_me
or + * multiple alias format: + *
aliases: [combust_me, combustMe]
permission{@link PluginCommand#setPermission(String)}StringThe name of the {@link Permission} required to use the command. + * A user without the permission will receive the specified + * message (see {@linkplain + * PluginCommand#setPermissionMessage(String) below}), or a + * standard one if no specific message is defined. Without the + * permission node, no {@link + * PluginCommand#setExecutor(CommandExecutor) CommandExecutor} or + * {@link PluginCommand#setTabCompleter(TabCompleter) + * TabCompleter} will be called.
permission: inferno.flagrate
permission-message{@link PluginCommand#setPermissionMessage(String)}String
    + *
  • Displayed to a player that attempts to use a command, but + * does not have the required permission. See {@link + * PluginCommand#getPermission() above}. + *
  • <permission> is a macro that is replaced with the + * permission node required to use the command. + *
  • Using empty quotes is a valid way to indicate nothing + * should be displayed to a player. + *
permission-message: You do not have /<permission>
usage{@link PluginCommand#setUsage(String)}StringThis message is displayed to a player when the {@link + * PluginCommand#setExecutor(CommandExecutor)} {@linkplain + * CommandExecutor#onCommand(CommandSender, Command, String, String[]) + * returns false}. <command> is a macro that is replaced + * the command issued.
usage: Syntax error! Perhaps you meant /<command> PlayerName?
+ * It is worth noting that to use a colon in a yaml, like + * `usage: Usage: /god [player]', you need to + * surround + * the message with double-quote: + *
usage: "Usage: /god [player]"
+ * The commands are structured as a hiearchy of nested mappings. + * The primary (top-level, no intendentation) node is + * `commands', while each individual command name is + * indented, indicating it maps to some value (in our case, the + * properties of the table above). + *

+ * Here is an example bringing together the piecemeal examples above, as + * well as few more definitions:

+     * commands:
+     *  flagrate:
+     *    description: Set yourself on fire.
+     *    aliases: [combust_me, combustMe]
+     *    permission: inferno.flagrate
+     *    permission-message: You do not have /<permission>
+     *    usage: Syntax error! Perhaps you meant /<command> PlayerName?
+     *  burningdeaths:
+     *    description: List how many times you have died by fire.
+     *    aliases:
+     *    - burning_deaths
+     *    - burningDeaths
+     *    permission: inferno.burningdeaths
+     *    usage: |
+     *      /<command> [player]
+     *      Example: /<command> - see how many times you have burned to death
+     *      Example: /<command> CaptainIce - see how many times CaptainIce has burned to death
+     *  # The next command has no description, aliases, etc. defined, but is still valid
+     *  # Having an empty declaration is useful for defining the description, permission, and messages from a configuration dynamically
+     *  apocalypse:
+     * 
+ * Note: Command names may not have a colon in their name. + * + * @return the commands this plugin will register + */ + public Map> getCommands() { + return commands; + } + + /** + * Gives the list of permissions the plugin will register at runtime, + * immediately proceding enabling. The format for defining permissions is + * a map from permission name to properties. To represent a map without + * any specific property, empty curly-braces ( + * {} ) may be used (as a null value is not + * accepted, unlike the {@link #getCommands() commands} above). + *

+ * A list of optional properties for permissions: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
The permission section's description
NodeDescriptionExample
descriptionPlaintext (user-friendly) description of what the permission + * is for.
description: Allows you to set yourself on fire
defaultThe default state for the permission, as defined by {@link + * Permission#getDefault()}. If not defined, it will be set to + * the value of {@link PluginDescriptionFile#getPermissionDefault()}. + *

+ * For reference:

    + *
  • true - Represents a positive assignment to + * {@link Permissible permissibles}. + *
  • false - Represents no assignment to {@link + * Permissible permissibles}. + *
  • op - Represents a positive assignment to + * {@link Permissible#isOp() operator permissibles}. + *
  • notop - Represents a positive assignment to + * {@link Permissible#isOp() non-operator permissibiles}. + *
default: true
childrenAllows other permissions to be set as a {@linkplain + * Permission#getChildren() relation} to the parent permission. + * When a parent permissions is assigned, child permissions are + * respectively assigned as well. + *
    + *
  • When a parent permission is assigned negatively, child + * permissions are assigned based on an inversion of their + * association. + *
  • When a parent permission is assigned positively, child + * permissions are assigned based on their association. + *
+ *

+ * Child permissions may be defined in a number of ways:

    + *
  • Children may be defined as a list of + * names. Using a list will treat all children associated + * positively to their parent. + *
  • Children may be defined as a map. Each permission name maps + * to either a boolean (representing the association), or a + * nested permission definition (just as another permission). + * Using a nested definition treats the child as a positive + * association. + *
  • A nested permission definition must be a map of these same + * properties. To define a valid nested permission without + * defining any specific property, empty curly-braces ( + * {} ) must be used. + *
  • A nested permission may carry it's own nested permissions + * as children, as they may also have nested permissions, and + * so forth. There is no direct limit to how deep the + * permission tree is defined. + *
As a list: + *
children: [inferno.flagrate, inferno.burningdeaths]
+ * Or as a mapping: + *
children:
+     *  inferno.flagrate: true
+     *  inferno.burningdeaths: true
+ * An additional example showing basic nested values can be seen + * here. + *
+ * The permissions are structured as a hiearchy of nested mappings. + * The primary (top-level, no intendentation) node is + * `permissions', while each individual permission name is + * indented, indicating it maps to some value (in our case, the + * properties of the table above). + *

+ * Here is an example using some of the properties:

+     * permissions:
+     *  inferno.*:
+     *    description: Gives access to all Inferno commands
+     *    children:
+     *      inferno.flagrate: true
+     *      inferno.burningdeaths: true
+     *  inferno.flagate:
+     *    description: Allows you to ignite yourself
+     *    default: true
+     *  inferno.burningdeaths:
+     *    description: Allows you to see how many times you have burned to death
+     *    default: true
+     * 
+ * Another example, with nested definitions, can be found here. + * + * @return the permissions this plugin will register + */ + public List getPermissions() { + if (permissions == null) { + if (lazyPermissions == null) { + permissions = ImmutableList.of(); + } else { + permissions = ImmutableList.copyOf(Permission.loadPermissions(lazyPermissions, "Permission node '%s' in plugin description file for " + getFullName() + " is invalid", defaultPerm)); + lazyPermissions = null; + } + } + return permissions; + } + + /** + * Gives the default {@link Permission#getDefault() default} state of + * {@link #getPermissions() permissions} registered for the plugin. + *
    + *
  • If not specified, it will be {@link PermissionDefault#OP}. + *
  • It is matched using {@link PermissionDefault#getByName(String)} + *
  • It only affects permissions that do not define the + * default node. + *
  • It may be any value in {@link PermissionDefault}. + *
+ *

+ * In the plugin.yml, this entry is named default-permission. + *

+ * Example:

default-permission: NOT_OP
+ * + * @return the default value for the plugin's permissions + */ + public PermissionDefault getPermissionDefault() { + return defaultPerm; + } + + /** + * Gives a set of every {@link PluginAwareness} for a plugin. An awareness + * dictates something that a plugin developer acknowledges when the plugin + * is compiled. Some implementions may define extra awarenesses that are + * not included in the API. Any unrecognized + * awareness (one unsupported or in a future version) will cause a dummy + * object to be created instead of failing. + * + *
    + *
  • Currently only supports the enumerated values in {@link + * PluginAwareness.Flags}. + *
  • Each awareness starts the identifier with bang-at + * (!@). + *
  • Unrecognized (future / unimplemented) entries are quietly replaced + * by a generic object that implements PluginAwareness. + *
  • A type of awareness must be defined by the runtime and acknowledged + * by the API, effectively discluding any derived type from any + * plugin's classpath. + *
  • awareness must be in YAML list + * format. + *
+ *

+ * In the plugin.yml, this entry is named awareness. + *

+ * Example:

awareness:
+     * - !@UTF8
+ *

+ * Note: Although unknown versions of some future awareness are + * gracefully substituted, previous versions of Bukkit (ones prior to the + * first implementation of awareness) will fail to load a plugin that + * defines any awareness. + * + * @return a set containing every awareness for the plugin + */ + public Set getAwareness() { + return awareness; + } + + /** + * Returns the name of a plugin, including the version. This method is + * provided for convenience; it uses the {@link #getName()} and {@link + * #getVersion()} entries. + * + * @return a descriptive name of the plugin and respective version + */ + public String getFullName() { + return name + " v" + version; + } + + /** + * @return unused + * @deprecated unused + */ + @Deprecated + public String getClassLoaderOf() { + return classLoaderOf; + } + + public void setDatabaseEnabled(boolean database) { + this.database = database; + } + + /** + * Saves this PluginDescriptionFile to the given writer + * + * @param writer Writer to output this file to + */ + public void save(Writer writer) { + YAML.get().dump(saveMap(), writer); + } + + private void loadMap(Map map) throws InvalidDescriptionException { + try { + name = rawName = map.get("name").toString(); + + if (!name.matches("^[A-Za-z0-9 _.-]+$")) { + throw new InvalidDescriptionException("name '" + name + "' contains invalid characters."); + } + name = name.replace(' ', '_'); + } catch (NullPointerException ex) { + throw new InvalidDescriptionException(ex, "name is not defined"); + } catch (ClassCastException ex) { + throw new InvalidDescriptionException(ex, "name is of wrong type"); + } + + try { + version = map.get("version").toString(); + } catch (NullPointerException ex) { + throw new InvalidDescriptionException(ex, "version is not defined"); + } catch (ClassCastException ex) { + throw new InvalidDescriptionException(ex, "version is of wrong type"); + } + + try { + main = map.get("main").toString(); + if (main.startsWith("org.bukkit.")) { + throw new InvalidDescriptionException("main may not be within the org.bukkit namespace"); + } + } catch (NullPointerException ex) { + throw new InvalidDescriptionException(ex, "main is not defined"); + } catch (ClassCastException ex) { + throw new InvalidDescriptionException(ex, "main is of wrong type"); + } + + if (map.get("commands") != null) { + ImmutableMap.Builder> commandsBuilder = ImmutableMap.>builder(); + try { + for (Map.Entry command : ((Map) map.get("commands")).entrySet()) { + ImmutableMap.Builder commandBuilder = ImmutableMap.builder(); + if (command.getValue() != null) { + for (Map.Entry commandEntry : ((Map) command.getValue()).entrySet()) { + if (commandEntry.getValue() instanceof Iterable) { + // This prevents internal alias list changes + ImmutableList.Builder commandSubList = ImmutableList.builder(); + for (Object commandSubListItem : (Iterable) commandEntry.getValue()) { + if (commandSubListItem != null) { + commandSubList.add(commandSubListItem); + } + } + commandBuilder.put(commandEntry.getKey().toString(), commandSubList.build()); + } else if (commandEntry.getValue() != null) { + commandBuilder.put(commandEntry.getKey().toString(), commandEntry.getValue()); + } + } + } + commandsBuilder.put(command.getKey().toString(), commandBuilder.build()); + } + } catch (ClassCastException ex) { + throw new InvalidDescriptionException(ex, "commands are of wrong type"); + } + commands = commandsBuilder.build(); + } + + if (map.get("class-loader-of") != null) { + classLoaderOf = map.get("class-loader-of").toString(); + } + + depend = makePluginNameList(map, "depend"); + softDepend = makePluginNameList(map, "softdepend"); + loadBefore = makePluginNameList(map, "loadbefore"); + + if (map.get("database") != null) { + try { + database = (Boolean) map.get("database"); + } catch (ClassCastException ex) { + throw new InvalidDescriptionException(ex, "database is of wrong type"); + } + } + + if (map.get("website") != null) { + website = map.get("website").toString(); + } + + if (map.get("description") != null) { + description = map.get("description").toString(); + } + + if (map.get("load") != null) { + try { + order = PluginLoadOrder.valueOf(((String) map.get("load")).toUpperCase().replaceAll("\\W", "")); + } catch (ClassCastException ex) { + throw new InvalidDescriptionException(ex, "load is of wrong type"); + } catch (IllegalArgumentException ex) { + throw new InvalidDescriptionException(ex, "load is not a valid choice"); + } + } + + if (map.get("authors") != null) { + ImmutableList.Builder authorsBuilder = ImmutableList.builder(); + if (map.get("author") != null) { + authorsBuilder.add(map.get("author").toString()); + } + try { + for (Object o : (Iterable) map.get("authors")) { + authorsBuilder.add(o.toString()); + } + } catch (ClassCastException ex) { + throw new InvalidDescriptionException(ex, "authors are of wrong type"); + } catch (NullPointerException ex) { + throw new InvalidDescriptionException(ex, "authors are improperly defined"); + } + authors = authorsBuilder.build(); + } else if (map.get("author") != null) { + authors = ImmutableList.of(map.get("author").toString()); + } else { + authors = ImmutableList.of(); + } + + if (map.get("default-permission") != null) { + try { + defaultPerm = PermissionDefault.getByName(map.get("default-permission").toString()); + } catch (ClassCastException ex) { + throw new InvalidDescriptionException(ex, "default-permission is of wrong type"); + } catch (IllegalArgumentException ex) { + throw new InvalidDescriptionException(ex, "default-permission is not a valid choice"); + } + } + + if (map.get("awareness") instanceof Iterable) { + Set awareness = new HashSet(); + try { + for (Object o : (Iterable) map.get("awareness")) { + awareness.add((PluginAwareness) o); + } + } catch (ClassCastException ex) { + throw new InvalidDescriptionException(ex, "awareness has wrong type"); + } + this.awareness = ImmutableSet.copyOf(awareness); + } + + try { + lazyPermissions = (Map) map.get("permissions"); + } catch (ClassCastException ex) { + throw new InvalidDescriptionException(ex, "permissions are of the wrong type"); + } + + if (map.get("prefix") != null) { + prefix = map.get("prefix").toString(); + } + } + + private static List makePluginNameList(final Map map, final String key) throws InvalidDescriptionException { + final Object value = map.get(key); + if (value == null) { + return ImmutableList.of(); + } + + final ImmutableList.Builder builder = ImmutableList.builder(); + try { + for (final Object entry : (Iterable) value) { + builder.add(entry.toString().replace(' ', '_')); + } + } catch (ClassCastException ex) { + throw new InvalidDescriptionException(ex, key + " is of wrong type"); + } catch (NullPointerException ex) { + throw new InvalidDescriptionException(ex, "invalid " + key + " format"); + } + return builder.build(); + } + + private Map saveMap() { + Map map = new HashMap(); + + map.put("name", name); + map.put("main", main); + map.put("version", version); + map.put("database", database); + map.put("order", order.toString()); + map.put("default-permission", defaultPerm.toString()); + + if (commands != null) { + map.put("command", commands); + } + if (depend != null) { + map.put("depend", depend); + } + if (softDepend != null) { + map.put("softdepend", softDepend); + } + if (website != null) { + map.put("website", website); + } + if (description != null) { + map.put("description", description); + } + + if (authors.size() == 1) { + map.put("author", authors.get(0)); + } else if (authors.size() > 1) { + map.put("authors", authors); + } + + if (classLoaderOf != null) { + map.put("class-loader-of", classLoaderOf); + } + + if (prefix != null) { + map.put("prefix", prefix); + } + + return map; + } + + private Map asMap(Object object) throws InvalidDescriptionException { + if (object instanceof Map) { + return (Map) object; + } + throw new InvalidDescriptionException(object + " is not properly structured."); + } + + /** + * @return internal use + * @deprecated Internal use + */ + @Deprecated + public String getRawName() { + return rawName; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/plugin/PluginLoadOrder.java b/azurite-api/src/main/java/org/bukkit/plugin/PluginLoadOrder.java new file mode 100644 index 0000000..b77436f --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/plugin/PluginLoadOrder.java @@ -0,0 +1,17 @@ +package org.bukkit.plugin; + +/** + * Represents the order in which a plugin should be initialized and enabled + */ +public enum PluginLoadOrder { + + /** + * Indicates that the plugin will be loaded at startup + */ + STARTUP, + /** + * Indicates that the plugin will be loaded after the first/default world + * was created + */ + POSTWORLD +} diff --git a/azurite-api/src/main/java/org/bukkit/plugin/PluginLoader.java b/azurite-api/src/main/java/org/bukkit/plugin/PluginLoader.java new file mode 100644 index 0000000..10418ba --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/plugin/PluginLoader.java @@ -0,0 +1,76 @@ +package org.bukkit.plugin; + +import org.bukkit.event.Event; +import org.bukkit.event.Listener; + +import java.io.File; +import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; + +/** + * Represents a plugin loader, which handles direct access to specific types + * of plugins + */ +public interface PluginLoader { + + /** + * Loads the plugin contained in the specified file + * + * @param file File to attempt to load + * @return Plugin that was contained in the specified file, or null if + * unsuccessful + * @throws InvalidPluginException Thrown when the specified file is not a + * plugin + * @throws UnknownDependencyException If a required dependency could not + * be found + */ + Plugin loadPlugin(File file) throws InvalidPluginException, UnknownDependencyException; + + /** + * Loads a PluginDescriptionFile from the specified file + * + * @param file File to attempt to load from + * @return A new PluginDescriptionFile loaded from the plugin.yml in the + * specified file + * @throws InvalidDescriptionException If the plugin description file + * could not be created + */ + PluginDescriptionFile getPluginDescription(File file) throws InvalidDescriptionException; + + /** + * Returns a list of all filename filters expected by this PluginLoader + * + * @return The filters + */ + Pattern[] getPluginFileFilters(); + + /** + * Creates and returns registered listeners for the event classes used in + * this listener + * + * @param listener The object that will handle the eventual call back + * @param plugin The plugin to use when creating registered listeners + * @return The registered listeners. + */ + Map, Set> createRegisteredListeners(Listener listener, Plugin plugin); + + /** + * Enables the specified plugin + *

+ * Attempting to enable a plugin that is already enabled will have no + * effect + * + * @param plugin Plugin to enable + */ + void enablePlugin(Plugin plugin); + + /** + * Disables the specified plugin + *

+ * Attempting to disable a plugin that is not enabled will have no effect + * + * @param plugin Plugin to disable + */ + void disablePlugin(Plugin plugin); +} diff --git a/azurite-api/src/main/java/org/bukkit/plugin/PluginLogger.java b/azurite-api/src/main/java/org/bukkit/plugin/PluginLogger.java new file mode 100644 index 0000000..f43c10b --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/plugin/PluginLogger.java @@ -0,0 +1,36 @@ +package org.bukkit.plugin; + +import java.util.logging.Level; +import java.util.logging.LogRecord; +import java.util.logging.Logger; + +/** + * The PluginLogger class is a modified {@link Logger} that prepends all + * logging calls with the name of the plugin doing the logging. The API for + * PluginLogger is exactly the same as {@link Logger}. + * + * @see Logger + */ +public class PluginLogger extends Logger { + private String pluginName; + + /** + * Creates a new PluginLogger that extracts the name from a plugin. + * + * @param context A reference to the plugin + */ + public PluginLogger(Plugin context) { + super(context.getClass().getCanonicalName(), null); + String prefix = context.getDescription().getPrefix(); + pluginName = prefix != null ? new StringBuilder().append("[").append(prefix).append("] ").toString() : "[" + context.getDescription().getName() + "] "; + setParent(context.getServer().getLogger()); + setLevel(Level.ALL); + } + + @Override + public void log(LogRecord logRecord) { + logRecord.setMessage(pluginName + logRecord.getMessage()); + super.log(logRecord); + } + +} diff --git a/azurite-api/src/main/java/org/bukkit/plugin/PluginManager.java b/azurite-api/src/main/java/org/bukkit/plugin/PluginManager.java new file mode 100644 index 0000000..cfcf838 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/plugin/PluginManager.java @@ -0,0 +1,290 @@ +package org.bukkit.plugin; + +import org.bukkit.event.Event; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.permissions.Permissible; +import org.bukkit.permissions.Permission; + +import java.io.File; +import java.util.Set; + +/** + * Handles all plugin management from the Server + */ +public interface PluginManager { + + /** + * Registers the specified plugin loader + * + * @param loader Class name of the PluginLoader to register + * @throws IllegalArgumentException Thrown when the given Class is not a + * valid PluginLoader + */ + void registerInterface(Class loader) throws IllegalArgumentException; + + /** + * Checks if the given plugin is loaded and returns it when applicable + *

+ * Please note that the name of the plugin is case-sensitive + * + * @param name Name of the plugin to check + * @return Plugin if it exists, otherwise null + */ + Plugin getPlugin(String name); + + /** + * Gets a list of all currently loaded plugins + * + * @return Array of Plugins + */ + Plugin[] getPlugins(); + + /** + * Checks if the given plugin is enabled or not + *

+ * Please note that the name of the plugin is case-sensitive. + * + * @param name Name of the plugin to check + * @return true if the plugin is enabled, otherwise false + */ + boolean isPluginEnabled(String name); + + /** + * Checks if the given plugin is enabled or not + * + * @param plugin Plugin to check + * @return true if the plugin is enabled, otherwise false + */ + boolean isPluginEnabled(Plugin plugin); + + boolean useTimings(); + + /** + * Loads the plugin in the specified file + *

+ * File must be valid according to the current enabled Plugin interfaces + * + * @param file File containing the plugin to load + * @return The Plugin loaded, or null if it was invalid + * @throws InvalidPluginException Thrown when the specified file is not a + * valid plugin + * @throws InvalidDescriptionException Thrown when the specified file + * contains an invalid description + * @throws UnknownDependencyException If a required dependency could not + * be resolved + */ + Plugin loadPlugin(File file) throws InvalidPluginException, InvalidDescriptionException, UnknownDependencyException; + + /** + * Loads the plugins contained within the specified directory + * + * @param directory Directory to check for plugins + * @return A list of all plugins loaded + */ + Plugin[] loadPlugins(File directory); + + /** + * Disables all the loaded plugins + */ + void disablePlugins(); + + /** + * Disables and removes all plugins + */ + void clearPlugins(); + + /** + * Calls an event with the given details + * + * @param event Event details + * @throws IllegalStateException Thrown when an asynchronous event is + * fired from synchronous code. + *

+ * Note: This is best-effort basis, and should not be used to test + * synchronized state. This is an indicator for flawed flow logic. + */ + void callEvent(Event event) throws IllegalStateException; + + /** + * Registers all the events in the given listener class + * + * @param listener Listener to register + * @param plugin Plugin to register + */ + void registerEvents(Listener listener, Plugin plugin); + + /** + * Registers the specified executor to the given event class + * + * @param event Event type to register + * @param listener Listener to register + * @param priority Priority to register this event at + * @param executor EventExecutor to register + * @param plugin Plugin to register + */ + void registerEvent(Class event, Listener listener, EventPriority priority, EventExecutor executor, Plugin plugin); + + /** + * Registers the specified executor to the given event class + * + * @param event Event type to register + * @param listener Listener to register + * @param priority Priority to register this event at + * @param executor EventExecutor to register + * @param plugin Plugin to register + * @param ignoreCancelled Whether to pass cancelled events or not + */ + void registerEvent(Class event, Listener listener, EventPriority priority, EventExecutor executor, Plugin plugin, boolean ignoreCancelled); + + /** + * Enables the specified plugin + *

+ * Attempting to enable a plugin that is already enabled will have no + * effect + * + * @param plugin Plugin to enable + */ + void enablePlugin(Plugin plugin); + + /** + * Disables the specified plugin + *

+ * Attempting to disable a plugin that is not enabled will have no effect + * + * @param plugin Plugin to disable + */ + void disablePlugin(Plugin plugin); + + /** + * Gets a {@link Permission} from its fully qualified name + * + * @param name Name of the permission + * @return Permission, or null if none + */ + Permission getPermission(String name); + + /** + * Adds a {@link Permission} to this plugin manager. + *

+ * If a permission is already defined with the given name of the new + * permission, an exception will be thrown. + * + * @param perm Permission to add + * @throws IllegalArgumentException Thrown when a permission with the same + * name already exists + */ + void addPermission(Permission perm); + + /** + * Removes a {@link Permission} registration from this plugin manager. + *

+ * If the specified permission does not exist in this plugin manager, + * nothing will happen. + *

+ * Removing a permission registration will not remove the + * permission from any {@link Permissible}s that have it. + * + * @param perm Permission to remove + */ + void removePermission(Permission perm); + + /** + * Removes a {@link Permission} registration from this plugin manager. + *

+ * If the specified permission does not exist in this plugin manager, + * nothing will happen. + *

+ * Removing a permission registration will not remove the + * permission from any {@link Permissible}s that have it. + * + * @param name Permission to remove + */ + void removePermission(String name); + + /** + * Gets the default permissions for the given op status + * + * @param op Which set of default permissions to get + * @return The default permissions + */ + Set getDefaultPermissions(boolean op); + + /** + * Recalculates the defaults for the given {@link Permission}. + *

+ * This will have no effect if the specified permission is not registered + * here. + * + * @param perm Permission to recalculate + */ + void recalculatePermissionDefaults(Permission perm); + + /** + * Subscribes the given Permissible for information about the requested + * Permission, by name. + *

+ * If the specified Permission changes in any form, the Permissible will + * be asked to recalculate. + * + * @param permission Permission to subscribe to + * @param permissible Permissible subscribing + */ + void subscribeToPermission(String permission, Permissible permissible); + + /** + * Unsubscribes the given Permissible for information about the requested + * Permission, by name. + * + * @param permission Permission to unsubscribe from + * @param permissible Permissible subscribing + */ + void unsubscribeFromPermission(String permission, Permissible permissible); + + /** + * Gets a set containing all subscribed {@link Permissible}s to the given + * permission, by name + * + * @param permission Permission to query for + * @return Set containing all subscribed permissions + */ + Set getPermissionSubscriptions(String permission); + + /** + * Subscribes to the given Default permissions by operator status + *

+ * If the specified defaults change in any form, the Permissible will be + * asked to recalculate. + * + * @param op Default list to subscribe to + * @param permissible Permissible subscribing + */ + void subscribeToDefaultPerms(boolean op, Permissible permissible); + + /** + * Unsubscribes from the given Default permissions by operator status + * + * @param op Default list to unsubscribe from + * @param permissible Permissible subscribing + */ + void unsubscribeFromDefaultPerms(boolean op, Permissible permissible); + + /** + * Gets a set containing all subscribed {@link Permissible}s to the given + * default list, by op status + * + * @param op Default list to query for + * @return Set containing all subscribed permissions + */ + Set getDefaultPermSubscriptions(boolean op); + + /** + * Gets a set of all registered permissions. + *

+ * This set is a copy and will not be modified live. + * + * @return Set containing all current registered permissions + */ + Set getPermissions(); + +} diff --git a/azurite-api/src/main/java/org/bukkit/plugin/RegisteredListener.java b/azurite-api/src/main/java/org/bukkit/plugin/RegisteredListener.java new file mode 100644 index 0000000..9dd0b7a --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/plugin/RegisteredListener.java @@ -0,0 +1,73 @@ +package org.bukkit.plugin; + +import org.bukkit.event.*; + +/** + * Stores relevant information for plugin listeners + */ +public class RegisteredListener { + private final Listener listener; + private final EventPriority priority; + private final Plugin plugin; + private final EventExecutor executor; + private final boolean ignoreCancelled; + + public RegisteredListener(final Listener listener, final EventExecutor executor, final EventPriority priority, final Plugin plugin, final boolean ignoreCancelled) { + this.listener = listener; + this.priority = priority; + this.plugin = plugin; + this.executor = executor; + this.ignoreCancelled = ignoreCancelled; + } + + /** + * Gets the listener for this registration + * + * @return Registered Listener + */ + public Listener getListener() { + return listener; + } + + /** + * Gets the plugin for this registration + * + * @return Registered Plugin + */ + public Plugin getPlugin() { + return plugin; + } + + /** + * Gets the priority for this registration + * + * @return Registered Priority + */ + public EventPriority getPriority() { + return priority; + } + + /** + * Calls the event executor + * + * @param event The event + * @throws EventException If an event handler throws an exception. + */ + public void callEvent(final Event event) throws EventException { + if (event instanceof Cancellable){ + if (((Cancellable) event).isCancelled() && isIgnoringCancelled()){ + return; + } + } + executor.execute(listener, event); + } + + /** + * Whether this listener accepts cancelled events + * + * @return True when ignoring cancelled events + */ + public boolean isIgnoringCancelled() { + return ignoreCancelled; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/plugin/RegisteredServiceProvider.java b/azurite-api/src/main/java/org/bukkit/plugin/RegisteredServiceProvider.java new file mode 100644 index 0000000..ba3ff15 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/plugin/RegisteredServiceProvider.java @@ -0,0 +1,46 @@ +package org.bukkit.plugin; + +/** + * A registered service provider. + * + * @param Service + */ +public class RegisteredServiceProvider implements Comparable> { + + private Class service; + private Plugin plugin; + private T provider; + private ServicePriority priority; + + public RegisteredServiceProvider(Class service, T provider, ServicePriority priority, Plugin plugin) { + + this.service = service; + this.plugin = plugin; + this.provider = provider; + this.priority = priority; + } + + public Class getService() { + return service; + } + + public Plugin getPlugin() { + return plugin; + } + + public T getProvider() { + return provider; + } + + public ServicePriority getPriority() { + return priority; + } + + public int compareTo(RegisteredServiceProvider other) { + if (priority.ordinal() == other.getPriority().ordinal()) { + return 0; + } else { + return priority.ordinal() < other.getPriority().ordinal() ? 1 : -1; + } + } +} diff --git a/azurite-api/src/main/java/org/bukkit/plugin/ServicePriority.java b/azurite-api/src/main/java/org/bukkit/plugin/ServicePriority.java new file mode 100644 index 0000000..4afe0fb --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/plugin/ServicePriority.java @@ -0,0 +1,12 @@ +package org.bukkit.plugin; + +/** + * Represents various priorities of a provider. + */ +public enum ServicePriority { + Lowest, + Low, + Normal, + High, + Highest +} diff --git a/azurite-api/src/main/java/org/bukkit/plugin/ServicesManager.java b/azurite-api/src/main/java/org/bukkit/plugin/ServicesManager.java new file mode 100644 index 0000000..5b29794 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/plugin/ServicesManager.java @@ -0,0 +1,106 @@ +package org.bukkit.plugin; + +import java.util.Collection; +import java.util.List; + +/** + * Manages services and service providers. Services are an interface + * specifying a list of methods that a provider must implement. Providers are + * implementations of these services. A provider can be queried from the + * services manager in order to use a service (if one is available). If + * multiple plugins register a service, then the service with the highest + * priority takes precedence. + */ +public interface ServicesManager { + + /** + * Register a provider of a service. + * + * @param Provider + * @param service service class + * @param provider provider to register + * @param plugin plugin with the provider + * @param priority priority of the provider + */ + void register(Class service, T provider, Plugin plugin, ServicePriority priority); + + /** + * Unregister all the providers registered by a particular plugin. + * + * @param plugin The plugin + */ + void unregisterAll(Plugin plugin); + + /** + * Unregister a particular provider for a particular service. + * + * @param service The service interface + * @param provider The service provider implementation + */ + void unregister(Class service, Object provider); + + /** + * Unregister a particular provider. + * + * @param provider The service provider implementation + */ + void unregister(Object provider); + + /** + * Queries for a provider. This may return if no provider has been + * registered for a service. The highest priority provider is returned. + * + * @param The service interface + * @param service The service interface + * @return provider or null + */ + T load(Class service); + + /** + * Queries for a provider registration. This may return if no provider + * has been registered for a service. + * + * @param The service interface + * @param service The service interface + * @return provider registration or null + */ + RegisteredServiceProvider getRegistration(Class service); + + /** + * Get registrations of providers for a plugin. + * + * @param plugin The plugin + * @return provider registration or null + */ + List> getRegistrations(Plugin plugin); + + /** + * Get registrations of providers for a service. The returned list is + * unmodifiable. + * + * @param The service interface + * @param service The service interface + * @return list of registrations + */ + Collection> getRegistrations(Class service); + + /** + * Get a list of known services. A service is known if it has registered + * providers for it. + * + * @return list of known services + */ + Collection> getKnownServices(); + + /** + * Returns whether a provider has been registered for a service. Do not + * check this first only to call load(service) later, as that + * would be a non-thread safe situation. + * + * @param service + * @param service service to check + * @return whether there has been a registered provider + */ + boolean isProvidedFor(Class service); + +} diff --git a/azurite-api/src/main/java/org/bukkit/plugin/SimplePluginManager.java b/azurite-api/src/main/java/org/bukkit/plugin/SimplePluginManager.java new file mode 100644 index 0000000..cce3ea8 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/plugin/SimplePluginManager.java @@ -0,0 +1,691 @@ +package org.bukkit.plugin; + +import com.google.common.collect.ImmutableSet; +import org.apache.commons.lang.Validate; +import org.bukkit.Server; +import org.bukkit.command.Command; +import org.bukkit.command.PluginCommandYamlParser; +import org.bukkit.command.SimpleCommandMap; +import org.bukkit.event.Event; +import org.bukkit.event.EventPriority; +import org.bukkit.event.HandlerList; +import org.bukkit.event.Listener; +import org.bukkit.permissions.Permissible; +import org.bukkit.permissions.Permission; +import org.bukkit.permissions.PermissionDefault; +import org.bukkit.util.FileUtil; + +import java.io.File; +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.util.*; +import java.util.logging.Level; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Handles all plugin management from the Server + */ +public final class SimplePluginManager implements PluginManager { + private final Server server; + private final Map fileAssociations = new HashMap<>(); + private final List plugins = new ArrayList<>(); + private final Map lookupNames = new HashMap<>(); + private static File updateDirectory = null; + private final SimpleCommandMap commandMap; + private final Map permissions = new HashMap<>(); + private final Map> defaultPerms = new LinkedHashMap<>(); + private final Map> permSubs = new HashMap<>(); + private final Map> defSubs = new HashMap<>(); + + public SimplePluginManager(Server instance, SimpleCommandMap commandMap) { + server = instance; + this.commandMap = commandMap; + + defaultPerms.put(true, new HashSet<>()); + defaultPerms.put(false, new HashSet<>()); + } + + /** + * Registers the specified plugin loader + * + * @param loader Class name of the PluginLoader to register + * @throws IllegalArgumentException Thrown when the given Class is not a + * valid PluginLoader + */ + public void registerInterface(Class loader) throws IllegalArgumentException { + PluginLoader instance; + + if (PluginLoader.class.isAssignableFrom(loader)) { + Constructor constructor; + + try { + constructor = loader.getConstructor(Server.class); + instance = constructor.newInstance(server); + } catch (NoSuchMethodException ex) { + String className = loader.getName(); + + throw new IllegalArgumentException(String.format("Class %s does not have a public %s(Server) constructor", className, className), ex); + } catch (Exception ex) { + throw new IllegalArgumentException(String.format("Unexpected exception %s while attempting to construct a new instance of %s", ex.getClass().getName(), loader.getName()), ex); + } + } else { + throw new IllegalArgumentException(String.format("Class %s does not implement interface PluginLoader", loader.getName())); + } + + Pattern[] patterns = instance.getPluginFileFilters(); + + synchronized (this) { + for (Pattern pattern : patterns) { + fileAssociations.put(pattern, instance); + } + } + } + + /** + * Loads the plugins contained within the specified directory + * + * @param directory Directory to check for plugins + * @return A list of all plugins loaded + */ + public Plugin[] loadPlugins(File directory) { + Validate.notNull(directory, "Directory cannot be null"); + Validate.isTrue(directory.isDirectory(), "Directory must be a directory"); + + List result = new ArrayList<>(); + Set filters = fileAssociations.keySet(); + + if (!(server.getUpdateFolder().equals(""))) { + updateDirectory = new File(directory, server.getUpdateFolder()); + } + + Map plugins = new HashMap<>(); + Set loadedPlugins = new HashSet<>(); + Map> dependencies = new HashMap<>(); + Map> softDependencies = new HashMap<>(); + + // This is where it figures out all possible plugins + for (File file : Objects.requireNonNull(directory.listFiles())) { + PluginLoader loader = null; + for (Pattern filter : filters) { + Matcher match = filter.matcher(file.getName()); + if (match.find()) { + loader = fileAssociations.get(filter); + } + } + + if (loader == null) continue; + + PluginDescriptionFile description; + try { + description = loader.getPluginDescription(file); + String name = description.getName(); + if (name.equalsIgnoreCase("bukkit") || name.equalsIgnoreCase("minecraft") || name.equalsIgnoreCase("mojang")) { + server.getLogger().log(Level.SEVERE, "Could not load '" + file.getPath() + "' in folder '" + directory.getPath() + "': Restricted Name"); + continue; + } else if (description.rawName.indexOf(' ') != -1) { + server.getLogger().warning(String.format( + "Plugin `%s' uses the space-character (0x20) in its name `%s' - this is discouraged", + description.getFullName(), + description.rawName + )); + } + } catch (InvalidDescriptionException ex) { + server.getLogger().log(Level.SEVERE, "Could not load '" + file.getPath() + "' in folder '" + directory.getPath() + "'", ex); + continue; + } + + File replacedFile = plugins.put(description.getName(), file); + if (replacedFile != null) { + server.getLogger().severe(String.format( + "Ambiguous plugin name `%s' for files `%s' and `%s' in `%s'", + description.getName(), + file.getPath(), + replacedFile.getPath(), + directory.getPath() + )); + } + + Collection softDependencySet = description.getSoftDepend(); + if (softDependencySet != null && !softDependencySet.isEmpty()) { + if (softDependencies.containsKey(description.getName())) { + // Duplicates do not matter, they will be removed together if applicable + softDependencies.get(description.getName()).addAll(softDependencySet); + } else { + softDependencies.put(description.getName(), new LinkedList<>(softDependencySet)); + } + } + + Collection dependencySet = description.getDepend(); + if (dependencySet != null && !dependencySet.isEmpty()) { + dependencies.put(description.getName(), new LinkedList<>(dependencySet)); + } + + Collection loadBeforeSet = description.getLoadBefore(); + if (loadBeforeSet != null && !loadBeforeSet.isEmpty()) { + for (String loadBeforeTarget : loadBeforeSet) { + if (softDependencies.containsKey(loadBeforeTarget)) { + softDependencies.get(loadBeforeTarget).add(description.getName()); + } else { + // softDependencies is never iterated, so 'ghost' plugins aren't an issue + Collection shortSoftDependency = new LinkedList<>(); + shortSoftDependency.add(description.getName()); + softDependencies.put(loadBeforeTarget, shortSoftDependency); + } + } + } + } + + while (!plugins.isEmpty()) { + boolean missingDependency = true; + Iterator pluginIterator = plugins.keySet().iterator(); + + while (pluginIterator.hasNext()) { + String plugin = pluginIterator.next(); + + if (dependencies.containsKey(plugin)) { + Iterator dependencyIterator = dependencies.get(plugin).iterator(); + + while (dependencyIterator.hasNext()) { + String dependency = dependencyIterator.next(); + + // Dependency loaded + if (loadedPlugins.contains(dependency)) { + dependencyIterator.remove(); + + // We have a dependency not found + } else if (!plugins.containsKey(dependency)) { + missingDependency = false; + File file = plugins.get(plugin); + pluginIterator.remove(); + softDependencies.remove(plugin); + dependencies.remove(plugin); + + server.getLogger().log( + Level.SEVERE, + "Could not load '" + file.getPath() + "' in folder '" + directory.getPath() + "'", + new UnknownDependencyException(dependency)); + break; + } + } + + if (dependencies.containsKey(plugin) && dependencies.get(plugin).isEmpty()) { + dependencies.remove(plugin); + } + } + if (softDependencies.containsKey(plugin)) { + + // Soft depend is no longer around + softDependencies.get(plugin).removeIf(softDependency -> !plugins.containsKey(softDependency)); + + if (softDependencies.get(plugin).isEmpty()) { + softDependencies.remove(plugin); + } + } + if (!(dependencies.containsKey(plugin) || softDependencies.containsKey(plugin)) && plugins.containsKey(plugin)) { + // We're clear to load, no more soft or hard dependencies left + File file = plugins.get(plugin); + pluginIterator.remove(); + missingDependency = false; + + try { + Plugin pl = loadPlugin(file); + if (pl != null) { + result.add(pl); + loadedPlugins.add(plugin); + } + } catch (InvalidPluginException ex) { + server.getLogger().log(Level.SEVERE, "Could not load '" + file.getPath() + "' in folder '" + directory.getPath() + "'", ex); + } + } + } + + if (missingDependency) { + // We now iterate over plugins until something loads + // This loop will ignore soft dependencies + pluginIterator = plugins.keySet().iterator(); + + while (pluginIterator.hasNext()) { + String plugin = pluginIterator.next(); + + if (!dependencies.containsKey(plugin)) { + softDependencies.remove(plugin); + missingDependency = false; + File file = plugins.get(plugin); + pluginIterator.remove(); + + try { + Plugin pl = loadPlugin(file); + if (pl != null) { + result.add(pl); + loadedPlugins.add(plugin); + } + break; + } catch (InvalidPluginException ex) { + server.getLogger().log(Level.SEVERE, "Could not load '" + file.getPath() + "' in folder '" + directory.getPath() + "'", ex); + } + } + } + // We have no plugins left without a depend + if (missingDependency) { + softDependencies.clear(); + dependencies.clear(); + Iterator failedPluginIterator = plugins.values().iterator(); + + while (failedPluginIterator.hasNext()) { + File file = failedPluginIterator.next(); + failedPluginIterator.remove(); + server.getLogger().log(Level.SEVERE, "Could not load '" + file.getPath() + "' in folder '" + directory.getPath() + "': circular dependency detected"); + } + } + } + } + + return result.toArray(new Plugin[0]); + } + + /** + * Loads the plugin in the specified file + *

+ * File must be valid according to the current enabled Plugin interfaces + * + * @param file File containing the plugin to load + * @return The Plugin loaded, or null if it was invalid + * @throws InvalidPluginException Thrown when the specified file is not a + * valid plugin + * @throws UnknownDependencyException If a required dependency could not + * be found + */ + public synchronized Plugin loadPlugin(File file) throws InvalidPluginException, UnknownDependencyException { + Validate.notNull(file, "File cannot be null"); + + checkUpdate(file); + + Set filters = fileAssociations.keySet(); + Plugin result = null; + + for (Pattern filter : filters) { + String name = file.getName(); + Matcher match = filter.matcher(name); + + if (match.find()) { + PluginLoader loader = fileAssociations.get(filter); + + result = loader.loadPlugin(file); + } + } + + if (result != null) { + plugins.add(result); + lookupNames.put(result.getDescription().getName().toLowerCase(), result); // Spigot + } + + return result; + } + + private void checkUpdate(File file) { + if (updateDirectory == null || !updateDirectory.isDirectory()) { + return; + } + + File updateFile = new File(updateDirectory, file.getName()); + if (updateFile.isFile() && FileUtil.copy(updateFile, file)) { + updateFile.delete(); + } + } + + /** + * Checks if the given plugin is loaded and returns it when applicable + *

+ * Please note that the name of the plugin is case-sensitive + * + * @param name Name of the plugin to check + * @return Plugin if it exists, otherwise null + */ + public synchronized Plugin getPlugin(String name) { + return lookupNames.get(name.replace(' ', '_').toLowerCase()); // Spigot + } + + public synchronized Plugin[] getPlugins() { + return plugins.toArray(new Plugin[0]); + } + + /** + * Checks if the given plugin is enabled or not + *

+ * Please note that the name of the plugin is case-sensitive. + * + * @param name Name of the plugin to check + * @return true if the plugin is enabled, otherwise false + */ + public boolean isPluginEnabled(String name) { + Plugin plugin = getPlugin(name); + + return isPluginEnabled(plugin); + } + + /** + * Checks if the given plugin is enabled or not + * + * @param plugin Plugin to check + * @return true if the plugin is enabled, otherwise false + */ + public boolean isPluginEnabled(Plugin plugin) { + return plugin != null && plugins.contains(plugin) && plugin.isEnabled(); + } + + @Override + public boolean useTimings() { + return false; + } + + public void enablePlugin(final Plugin plugin) { + if (!plugin.isEnabled()) { + List pluginCommands = PluginCommandYamlParser.parse(plugin); + + if (!pluginCommands.isEmpty()) { + commandMap.registerAll(plugin.getDescription().getName(), pluginCommands); + } + + try { + plugin.getPluginLoader().enablePlugin(plugin); + } catch (Throwable ex) { + server.getLogger().log(Level.SEVERE, "Error occurred (in the plugin loader) while enabling " + plugin.getDescription().getFullName() + " (Is it up to date?)", ex); + } + + HandlerList.bakeAll(); + } + } + + public void disablePlugins() { + Plugin[] plugins = getPlugins(); + for (int i = plugins.length - 1; i >= 0; i--) { + disablePlugin(plugins[i]); + } + } + + public void disablePlugin(final Plugin plugin) { + if (plugin.isEnabled()) { + try { + plugin.getPluginLoader().disablePlugin(plugin); + } catch (Throwable ex) { + server.getLogger().log(Level.SEVERE, "Error occurred (in the plugin loader) while disabling " + plugin.getDescription().getFullName() + " (Is it up to date?)", ex); + } + + try { + server.getScheduler().cancelTasks(plugin); + } catch (Throwable ex) { + server.getLogger().log(Level.SEVERE, "Error occurred (in the plugin loader) while cancelling tasks for " + plugin.getDescription().getFullName() + " (Is it up to date?)", ex); + } + + try { + server.getServicesManager().unregisterAll(plugin); + } catch (Throwable ex) { + server.getLogger().log(Level.SEVERE, "Error occurred (in the plugin loader) while unregistering services for " + plugin.getDescription().getFullName() + " (Is it up to date?)", ex); + } + + try { + HandlerList.unregisterAll(plugin); + } catch (Throwable ex) { + server.getLogger().log(Level.SEVERE, "Error occurred (in the plugin loader) while unregistering events for " + plugin.getDescription().getFullName() + " (Is it up to date?)", ex); + } + + try { + server.getMessenger().unregisterIncomingPluginChannel(plugin); + server.getMessenger().unregisterOutgoingPluginChannel(plugin); + } catch(Throwable ex) { + server.getLogger().log(Level.SEVERE, "Error occurred (in the plugin loader) while unregistering plugin channels for " + plugin.getDescription().getFullName() + " (Is it up to date?)", ex); + } + } + } + + public void clearPlugins() { + synchronized (this) { + disablePlugins(); + plugins.clear(); + lookupNames.clear(); + HandlerList.unregisterAll(); + fileAssociations.clear(); + permissions.clear(); + defaultPerms.get(true).clear(); + defaultPerms.get(false).clear(); + } + } + + /** + * Calls an event with the given details. + *

+ * This method only synchronizes when the event is not asynchronous. + * + * @param event Event details + */ + public void callEvent(Event event) { + if (event.isAsynchronous()) { + if (Thread.holdsLock(this)) { + throw new IllegalStateException(event.getEventName() + " cannot be triggered asynchronously from inside synchronized code."); + } + if (server.isPrimaryThread()) { + throw new IllegalStateException(event.getEventName() + " cannot be triggered asynchronously from primary server thread."); + } + fireEvent(event); + } else { + synchronized (this) { + fireEvent(event); + } + } + } + + private void fireEvent(Event event) { + HandlerList handlers = event.getHandlers(); + RegisteredListener[] listeners = handlers.getRegisteredListeners(); + + for (RegisteredListener registration : listeners) { + if (!registration.getPlugin().isEnabled()) { + continue; + } + + try { + registration.callEvent(event); + } catch (AuthorNagException ex) { + Plugin plugin = registration.getPlugin(); + + if (plugin.isNaggable()) { + plugin.setNaggable(false); + + server.getLogger().log(Level.SEVERE, String.format( + "Nag author(s): '%s' of '%s' about the following: %s", + plugin.getDescription().getAuthors(), + plugin.getDescription().getFullName(), + ex.getMessage() + )); + } + } catch (Throwable ex) { + server.getLogger().log(Level.SEVERE, "Could not pass event " + event.getEventName() + " to " + registration.getPlugin().getDescription().getFullName(), ex); + } + } + } + + public void registerEvents(Listener listener, Plugin plugin) { + if (!plugin.isEnabled()) { + throw new IllegalPluginAccessException("Plugin attempted to register " + listener + " while not enabled"); + } + + for (Map.Entry, Set> entry : plugin.getPluginLoader().createRegisteredListeners(listener, plugin).entrySet()) { + getEventListeners(getRegistrationClass(entry.getKey())).registerAll(entry.getValue()); + } + + } + + public void registerEvent(Class event, Listener listener, EventPriority priority, EventExecutor executor, Plugin plugin) { + registerEvent(event, listener, priority, executor, plugin, false); + } + + /** + * Registers the given event to the specified listener using a directly + * passed EventExecutor + * + * @param event Event class to register + * @param listener PlayerListener to register + * @param priority Priority of this event + * @param executor EventExecutor to register + * @param plugin Plugin to register + * @param ignoreCancelled Do not call executor if event was already + * cancelled + */ + public void registerEvent(Class event, Listener listener, EventPriority priority, EventExecutor executor, Plugin plugin, boolean ignoreCancelled) { + Validate.notNull(listener, "Listener cannot be null"); + Validate.notNull(priority, "Priority cannot be null"); + Validate.notNull(executor, "Executor cannot be null"); + Validate.notNull(plugin, "Plugin cannot be null"); + + if (!plugin.isEnabled()) { + throw new IllegalPluginAccessException("Plugin attempted to register " + event + " while not enabled"); + } + + getEventListeners(event).register(new RegisteredListener(listener, executor, priority, plugin, ignoreCancelled)); + } + + private HandlerList getEventListeners(Class type) { + try { + Method method = getRegistrationClass(type).getDeclaredMethod("getHandlerList"); + method.setAccessible(true); + return (HandlerList) method.invoke(null); + } catch (Exception e) { + throw new IllegalPluginAccessException(e.toString()); + } + } + + private Class getRegistrationClass(Class clazz) { + try { + clazz.getDeclaredMethod("getHandlerList"); + return clazz; + } catch (NoSuchMethodException e) { + if (clazz.getSuperclass() != null + && !clazz.getSuperclass().equals(Event.class) + && Event.class.isAssignableFrom(clazz.getSuperclass())) { + return getRegistrationClass(clazz.getSuperclass().asSubclass(Event.class)); + } else { + throw new IllegalPluginAccessException("Unable to find handler list for event " + clazz.getName() + ". Static getHandlerList method required!"); + } + } + } + + public Permission getPermission(String name) { + return permissions.get(name.toLowerCase()); + } + + public void addPermission(Permission perm) { + String name = perm.getName().toLowerCase(); + + if (permissions.containsKey(name)) { + throw new IllegalArgumentException("The permission " + name + " is already defined!"); + } + + permissions.put(name, perm); + calculatePermissionDefault(perm); + } + + public Set getDefaultPermissions(boolean op) { + return ImmutableSet.copyOf(defaultPerms.get(op)); + } + + public void removePermission(Permission perm) { + removePermission(perm.getName()); + } + + public void removePermission(String name) { + permissions.remove(name.toLowerCase()); + } + + public void recalculatePermissionDefaults(Permission perm) { + if (perm != null && permissions.containsKey(perm.getName().toLowerCase())) { + defaultPerms.get(true).remove(perm); + defaultPerms.get(false).remove(perm); + + calculatePermissionDefault(perm); + } + } + + private void calculatePermissionDefault(Permission perm) { + if ((perm.getDefault() == PermissionDefault.OP) || (perm.getDefault() == PermissionDefault.TRUE)) { + defaultPerms.get(true).add(perm); + dirtyPermissibles(true); + } + if ((perm.getDefault() == PermissionDefault.NOT_OP) || (perm.getDefault() == PermissionDefault.TRUE)) { + defaultPerms.get(false).add(perm); + dirtyPermissibles(false); + } + } + + private void dirtyPermissibles(boolean op) { + Set permissibles = getDefaultPermSubscriptions(op); + + for (Permissible p : permissibles) { + p.recalculatePermissions(); + } + } + + public void subscribeToPermission(String permission, Permissible permissible) { + String name = permission.toLowerCase(); + Map map = permSubs.computeIfAbsent(name, k -> new WeakHashMap<>()); + + map.put(permissible, true); + } + + public void unsubscribeFromPermission(String permission, Permissible permissible) { + String name = permission.toLowerCase(); + Map map = permSubs.get(name); + + if (map != null) { + map.remove(permissible); + + if (map.isEmpty()) { + permSubs.remove(name); + } + } + } + + public Set getPermissionSubscriptions(String permission) { + String name = permission.toLowerCase(); + Map map = permSubs.get(name); + + if (map == null) { + return ImmutableSet.of(); + } else { + return ImmutableSet.copyOf(map.keySet()); + } + } + + public void subscribeToDefaultPerms(boolean op, Permissible permissible) { + Map map = defSubs.computeIfAbsent(op, k -> new WeakHashMap<>()); + + map.put(permissible, true); + } + + public void unsubscribeFromDefaultPerms(boolean op, Permissible permissible) { + Map map = defSubs.get(op); + + if (map != null) { + map.remove(permissible); + + if (map.isEmpty()) { + defSubs.remove(op); + } + } + } + + public Set getDefaultPermSubscriptions(boolean op) { + Map map = defSubs.get(op); + + if (map == null) { + return ImmutableSet.of(); + } else { + return ImmutableSet.copyOf(map.keySet()); + } + } + + public Set getPermissions() { + return new HashSet<>(permissions.values()); + } + +} diff --git a/azurite-api/src/main/java/org/bukkit/plugin/SimpleServicesManager.java b/azurite-api/src/main/java/org/bukkit/plugin/SimpleServicesManager.java new file mode 100644 index 0000000..a7e8d58 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/plugin/SimpleServicesManager.java @@ -0,0 +1,298 @@ +package org.bukkit.plugin; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableSet; +import org.bukkit.Bukkit; +import org.bukkit.event.server.ServiceRegisterEvent; +import org.bukkit.event.server.ServiceUnregisterEvent; + +import java.util.*; + +/** + * A simple services manager. + */ +public class SimpleServicesManager implements ServicesManager { + + /** + * Map of providers. + */ + private final Map, List>> providers = new HashMap, List>>(); + + /** + * Register a provider of a service. + * + * @param Provider + * @param service service class + * @param provider provider to register + * @param plugin plugin with the provider + * @param priority priority of the provider + */ + public void register(Class service, T provider, Plugin plugin, ServicePriority priority) { + RegisteredServiceProvider registeredProvider = null; + synchronized (providers) { + List> registered = providers.get(service); + if (registered == null) { + registered = new ArrayList>(); + providers.put(service, registered); + } + + registeredProvider = new RegisteredServiceProvider(service, provider, priority, plugin); + + // Insert the provider into the collection, much more efficient big O than sort + int position = Collections.binarySearch(registered, registeredProvider); + if (position < 0) { + registered.add(-(position + 1), registeredProvider); + } else { + registered.add(position, registeredProvider); + } + + } + Bukkit.getServer().getPluginManager().callEvent(new ServiceRegisterEvent(registeredProvider)); + } + + /** + * Unregister all the providers registered by a particular plugin. + * + * @param plugin The plugin + */ + public void unregisterAll(Plugin plugin) { + ArrayList unregisteredEvents = new ArrayList(); + synchronized (providers) { + Iterator, List>>> it = providers.entrySet().iterator(); + + try { + while (it.hasNext()) { + Map.Entry, List>> entry = it.next(); + Iterator> it2 = entry.getValue().iterator(); + + try { + // Removed entries that are from this plugin + + while (it2.hasNext()) { + RegisteredServiceProvider registered = it2.next(); + + if (registered.getPlugin().equals(plugin)) { + it2.remove(); + unregisteredEvents.add(new ServiceUnregisterEvent(registered)); + } + } + } catch (NoSuchElementException e) { // Why does Java suck + } + + // Get rid of the empty list + if (entry.getValue().size() == 0) { + it.remove(); + } + } + } catch (NoSuchElementException ignored) {} + } + for (ServiceUnregisterEvent event : unregisteredEvents) { + Bukkit.getServer().getPluginManager().callEvent(event); + } + } + + /** + * Unregister a particular provider for a particular service. + * + * @param service The service interface + * @param provider The service provider implementation + */ + public void unregister(Class service, Object provider) { + ArrayList unregisteredEvents = new ArrayList(); + synchronized (providers) { + Iterator, List>>> it = providers.entrySet().iterator(); + + try { + while (it.hasNext()) { + Map.Entry, List>> entry = it.next(); + + // We want a particular service + if (entry.getKey() != service) { + continue; + } + + Iterator> it2 = entry.getValue().iterator(); + + try { + // Removed entries that are from this plugin + + while (it2.hasNext()) { + RegisteredServiceProvider registered = it2.next(); + + if (registered.getProvider() == provider) { + it2.remove(); + unregisteredEvents.add(new ServiceUnregisterEvent(registered)); + } + } + } catch (NoSuchElementException e) { // Why does Java suck + } + + // Get rid of the empty list + if (entry.getValue().size() == 0) { + it.remove(); + } + } + } catch (NoSuchElementException ignored) {} + } + for (ServiceUnregisterEvent event : unregisteredEvents) { + Bukkit.getServer().getPluginManager().callEvent(event); + } + } + + /** + * Unregister a particular provider. + * + * @param provider The service provider implementation + */ + public void unregister(Object provider) { + ArrayList unregisteredEvents = new ArrayList(); + synchronized (providers) { + Iterator, List>>> it = providers.entrySet().iterator(); + + try { + while (it.hasNext()) { + Map.Entry, List>> entry = it.next(); + Iterator> it2 = entry.getValue().iterator(); + + try { + // Removed entries that are from this plugin + + while (it2.hasNext()) { + RegisteredServiceProvider registered = it2.next(); + + if (registered.getProvider().equals(provider)) { + it2.remove(); + unregisteredEvents.add(new ServiceUnregisterEvent(registered)); + } + } + } catch (NoSuchElementException e) { // Why does Java suck + } + + // Get rid of the empty list + if (entry.getValue().size() == 0) { + it.remove(); + } + } + } catch (NoSuchElementException ignored) {} + } + for (ServiceUnregisterEvent event : unregisteredEvents) { + Bukkit.getServer().getPluginManager().callEvent(event); + } + } + + /** + * Queries for a provider. This may return if no provider has been + * registered for a service. The highest priority provider is returned. + * + * @param The service interface + * @param service The service interface + * @return provider or null + */ + public T load(Class service) { + synchronized (providers) { + List> registered = providers.get(service); + + if (registered == null) { + return null; + } + + // This should not be null! + return service.cast(registered.get(0).getProvider()); + } + } + + /** + * Queries for a provider registration. This may return if no provider + * has been registered for a service. + * + * @param The service interface + * @param service The service interface + * @return provider registration or null + */ + @SuppressWarnings("unchecked") + public RegisteredServiceProvider getRegistration(Class service) { + synchronized (providers) { + List> registered = providers.get(service); + + if (registered == null) { + return null; + } + + // This should not be null! + return (RegisteredServiceProvider) registered.get(0); + } + } + + /** + * Get registrations of providers for a plugin. + * + * @param plugin The plugin + * @return provider registration or null + */ + public List> getRegistrations(Plugin plugin) { + ImmutableList.Builder> ret = ImmutableList.>builder(); + synchronized (providers) { + for (List> registered : providers.values()) { + for (RegisteredServiceProvider provider : registered) { + if (provider.getPlugin().equals(plugin)) { + ret.add(provider); + } + } + } + } + return ret.build(); + } + + /** + * Get registrations of providers for a service. The returned list is + * an unmodifiable copy. + * + * @param The service interface + * @param service The service interface + * @return a copy of the list of registrations + */ + @SuppressWarnings("unchecked") + public List> getRegistrations(Class service) { + ImmutableList.Builder> ret; + synchronized (providers) { + List> registered = providers.get(service); + + if (registered == null) { + return ImmutableList.>of(); + } + + ret = ImmutableList.>builder(); + + for (RegisteredServiceProvider provider : registered) { + ret.add((RegisteredServiceProvider) provider); + } + + } + return ret.build(); + } + + /** + * Get a list of known services. A service is known if it has registered + * providers for it. + * + * @return a copy of the set of known services + */ + public Set> getKnownServices() { + synchronized (providers) { + return ImmutableSet.>copyOf(providers.keySet()); + } + } + + /** + * Returns whether a provider has been registered for a service. + * + * @param service + * @param service service to check + * @return true if and only if there are registered providers + */ + public boolean isProvidedFor(Class service) { + synchronized (providers) { + return providers.containsKey(service); + } + } +} diff --git a/azurite-api/src/main/java/org/bukkit/plugin/UnknownDependencyException.java b/azurite-api/src/main/java/org/bukkit/plugin/UnknownDependencyException.java new file mode 100644 index 0000000..a80251e --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/plugin/UnknownDependencyException.java @@ -0,0 +1,46 @@ +package org.bukkit.plugin; + +/** + * Thrown when attempting to load an invalid Plugin file + */ +public class UnknownDependencyException extends RuntimeException { + + private static final long serialVersionUID = 5721389371901775895L; + + /** + * Constructs a new UnknownDependencyException based on the given + * Exception + * + * @param throwable Exception that triggered this Exception + */ + public UnknownDependencyException(final Throwable throwable) { + super(throwable); + } + + /** + * Constructs a new UnknownDependencyException with the given message + * + * @param message Brief message explaining the cause of the exception + */ + public UnknownDependencyException(final String message) { + super(message); + } + + /** + * Constructs a new UnknownDependencyException based on the given + * Exception + * + * @param message Brief message explaining the cause of the exception + * @param throwable Exception that triggered this Exception + */ + public UnknownDependencyException(final Throwable throwable, final String message) { + super(message, throwable); + } + + /** + * Constructs a new UnknownDependencyException + */ + public UnknownDependencyException() { + + } +} diff --git a/azurite-api/src/main/java/org/bukkit/plugin/java/JavaPlugin.java b/azurite-api/src/main/java/org/bukkit/plugin/java/JavaPlugin.java new file mode 100644 index 0000000..03d0000 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/plugin/java/JavaPlugin.java @@ -0,0 +1,548 @@ +package org.bukkit.plugin.java; + +import com.avaje.ebean.EbeanServer; +import com.avaje.ebean.EbeanServerFactory; +import com.avaje.ebean.config.DataSourceConfig; +import com.avaje.ebean.config.ServerConfig; +import com.avaje.ebeaninternal.api.SpiEbeanServer; +import com.avaje.ebeaninternal.server.ddl.DdlGenerator; +import com.google.common.base.Charsets; +import com.google.common.io.ByteStreams; +import org.apache.commons.lang.Validate; +import org.bukkit.Server; +import org.bukkit.Warning.WarningState; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.command.PluginCommand; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.generator.ChunkGenerator; +import org.bukkit.plugin.*; + +import java.io.*; +import java.net.URL; +import java.net.URLConnection; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * Represents a Java plugin + */ +public abstract class JavaPlugin extends PluginBase { + private boolean isEnabled = false; + private PluginLoader loader = null; + private Server server = null; + private File file = null; + private PluginDescriptionFile description = null; + private File dataFolder = null; + private ClassLoader classLoader = null; + private boolean naggable = true; + private EbeanServer ebean = null; + private FileConfiguration newConfig = null; + private File configFile = null; + private PluginLogger logger = null; + + public JavaPlugin() { + final ClassLoader classLoader = this.getClass().getClassLoader(); + if (!(classLoader instanceof PluginClassLoader)) { + throw new IllegalStateException("JavaPlugin requires " + PluginClassLoader.class.getName()); + } + ((PluginClassLoader) classLoader).initialize(this); + } + + /** + * @deprecated This method is intended for unit testing purposes when the + * other {@linkplain #JavaPlugin(JavaPluginLoader, + * PluginDescriptionFile, File, File) constructor} cannot be used. + *

+ * Its existence may be temporary. + * @param loader the plugin loader + * @param server the server instance + * @param description the plugin's description + * @param dataFolder the plugin's data folder + * @param file the location of the plugin + */ + @Deprecated + protected JavaPlugin(final PluginLoader loader, final Server server, final PluginDescriptionFile description, final File dataFolder, final File file) { + final ClassLoader classLoader = this.getClass().getClassLoader(); + if (classLoader instanceof PluginClassLoader) { + throw new IllegalStateException("Cannot use initialization constructor at runtime"); + } + init(loader, server, description, dataFolder, file, classLoader); + } + + protected JavaPlugin(final JavaPluginLoader loader, final PluginDescriptionFile description, final File dataFolder, final File file) { + final ClassLoader classLoader = this.getClass().getClassLoader(); + if (classLoader instanceof PluginClassLoader) { + throw new IllegalStateException("Cannot use initialization constructor at runtime"); + } + init(loader, loader.server, description, dataFolder, file, classLoader); + } + + /** + * Returns the folder that the plugin data's files are located in. The + * folder may not yet exist. + * + * @return The folder. + */ + @Override + public final File getDataFolder() { + return dataFolder; + } + + /** + * Gets the associated PluginLoader responsible for this plugin + * + * @return PluginLoader that controls this plugin + */ + @Override + public final PluginLoader getPluginLoader() { + return loader; + } + + /** + * Returns the Server instance currently running this plugin + * + * @return Server running this plugin + */ + @Override + public final Server getServer() { + return server; + } + + /** + * Returns a value indicating whether or not this plugin is currently + * enabled + * + * @return true if this plugin is enabled, otherwise false + */ + @Override + public final boolean isEnabled() { + return isEnabled; + } + + /** + * Returns the file which contains this plugin + * + * @return File containing this plugin + */ + protected File getFile() { + return file; + } + + /** + * Returns the plugin.yaml file containing the details for this plugin + * + * @return Contents of the plugin.yaml file + */ + @Override + public final PluginDescriptionFile getDescription() { + return description; + } + + @Override + public FileConfiguration getConfig() { + if (newConfig == null) { + reloadConfig(); + } + return newConfig; + } + + /** + * Provides a reader for a text file located inside the jar. The behavior + * of this method adheres to {@link PluginAwareness.Flags#UTF8}, or if not + * defined, uses UTF8 if {@link FileConfiguration#UTF8_OVERRIDE} is + * specified, or system default otherwise. + * + * @param file the filename of the resource to load + * @return null if {@link #getResource(String)} returns null + * @throws IllegalArgumentException if file is null + * @see ClassLoader#getResourceAsStream(String) + */ + @SuppressWarnings("deprecation") + protected final Reader getTextResource(String file) { + final InputStream in = getResource(file); + + return in == null ? null : new InputStreamReader(in, isStrictlyUTF8() || FileConfiguration.UTF8_OVERRIDE ? Charsets.UTF_8 : Charset.defaultCharset()); + } + + @SuppressWarnings("deprecation") + @Override + public void reloadConfig() { + newConfig = YamlConfiguration.loadConfiguration(configFile); + + final InputStream defConfigStream = getResource("config.yml"); + if (defConfigStream == null) { + return; + } + + final YamlConfiguration defConfig; + if (isStrictlyUTF8() || FileConfiguration.UTF8_OVERRIDE) { + defConfig = YamlConfiguration.loadConfiguration(new InputStreamReader(defConfigStream, Charsets.UTF_8)); + } else { + final byte[] contents; + defConfig = new YamlConfiguration(); + try { + contents = ByteStreams.toByteArray(defConfigStream); + } catch (final IOException e) { + getLogger().log(Level.SEVERE, "Unexpected failure reading config.yml", e); + return; + } + + final String text = new String(contents, Charset.defaultCharset()); + if (!text.equals(new String(contents, Charsets.UTF_8))) { + getLogger().warning("Default system encoding may have misread config.yml from plugin jar"); + } + + try { + defConfig.loadFromString(text); + } catch (final InvalidConfigurationException e) { + getLogger().log(Level.SEVERE, "Cannot load configuration from jar", e); + } + } + + newConfig.setDefaults(defConfig); + } + + private boolean isStrictlyUTF8() { + return getDescription().getAwareness().contains(PluginAwareness.Flags.UTF8); + } + + @Override + public void saveConfig() { + try { + getConfig().save(configFile); + } catch (IOException ex) { + logger.log(Level.SEVERE, "Could not save config to " + configFile, ex); + } + } + + @Override + public void saveDefaultConfig() { + if (!configFile.exists()) { + saveResource("config.yml", false); + } + } + + @Override + public void saveResource(String resourcePath, boolean replace) { + if (resourcePath == null || resourcePath.equals("")) { + throw new IllegalArgumentException("ResourcePath cannot be null or empty"); + } + + resourcePath = resourcePath.replace('\\', '/'); + InputStream in = getResource(resourcePath); + if (in == null) { + throw new IllegalArgumentException("The embedded resource '" + resourcePath + "' cannot be found in " + file); + } + + File outFile = new File(dataFolder, resourcePath); + int lastIndex = resourcePath.lastIndexOf('/'); + File outDir = new File(dataFolder, resourcePath.substring(0, lastIndex >= 0 ? lastIndex : 0)); + + if (!outDir.exists()) { + outDir.mkdirs(); + } + + try { + if (!outFile.exists() || replace) { + OutputStream out = new FileOutputStream(outFile); + byte[] buf = new byte[1024]; + int len; + while ((len = in.read(buf)) > 0) { + out.write(buf, 0, len); + } + out.close(); + in.close(); + } else { + logger.log(Level.WARNING, "Could not save " + outFile.getName() + " to " + outFile + " because " + outFile.getName() + " already exists."); + } + } catch (IOException ex) { + logger.log(Level.SEVERE, "Could not save " + outFile.getName() + " to " + outFile, ex); + } + } + + @Override + public InputStream getResource(String filename) { + if (filename == null) { + throw new IllegalArgumentException("Filename cannot be null"); + } + + try { + URL url = getClassLoader().getResource(filename); + + if (url == null) { + return null; + } + + URLConnection connection = url.openConnection(); + connection.setUseCaches(false); + return connection.getInputStream(); + } catch (IOException ex) { + return null; + } + } + + /** + * Returns the ClassLoader which holds this plugin + * + * @return ClassLoader holding this plugin + */ + protected final ClassLoader getClassLoader() { + return classLoader; + } + + /** + * Sets the enabled state of this plugin + * + * @param enabled true if enabled, otherwise false + */ + protected final void setEnabled(final boolean enabled) { + if (isEnabled != enabled) { + isEnabled = enabled; + + if (isEnabled) { + onEnable(); + } else { + onDisable(); + } + } + } + + /** + * @param loader the plugin loader + * @param server the server instance + * @param description the plugin's description + * @param dataFolder the plugin's data folder + * @param file the location of the plugin + * @param classLoader the class loader + * @deprecated This method is legacy and will be removed - it must be + * replaced by the specially provided constructor(s). + */ + @Deprecated + protected final void initialize(PluginLoader loader, Server server, PluginDescriptionFile description, File dataFolder, File file, ClassLoader classLoader) { + if (server.getWarningState() == WarningState.OFF) { + return; + } + getLogger().log(Level.WARNING, getClass().getName() + " is already initialized", server.getWarningState() == WarningState.DEFAULT ? null : new AuthorNagException("Explicit initialization")); + } + + final void init(PluginLoader loader, Server server, PluginDescriptionFile description, File dataFolder, File file, ClassLoader classLoader) { + this.loader = loader; + this.server = server; + this.file = file; + this.description = description; + this.dataFolder = dataFolder; + this.classLoader = classLoader; + this.configFile = new File(dataFolder, "config.yml"); + this.logger = new PluginLogger(this); + + if (description.isDatabaseEnabled()) { + ServerConfig db = new ServerConfig(); + + db.setDefaultServer(false); + db.setRegister(false); + db.setClasses(getDatabaseClasses()); + db.setName(description.getName()); + server.configureDbConfig(db); + + DataSourceConfig ds = db.getDataSourceConfig(); + + ds.setUrl(replaceDatabaseString(ds.getUrl())); + dataFolder.mkdirs(); + + ClassLoader previous = Thread.currentThread().getContextClassLoader(); + + Thread.currentThread().setContextClassLoader(classLoader); + ebean = EbeanServerFactory.create(db); + Thread.currentThread().setContextClassLoader(previous); + } + } + + /** + * Provides a list of all classes that should be persisted in the database + * + * @return List of Classes that are Ebeans + */ + public List> getDatabaseClasses() { + return new ArrayList>(); + } + + private String replaceDatabaseString(String input) { + input = input.replaceAll("\\{DIR\\}", dataFolder.getPath().replaceAll("\\\\", "/") + "/"); + input = input.replaceAll("\\{NAME\\}", description.getName().replaceAll("[^\\w_-]", "")); + return input; + } + + /** + * Gets the initialization status of this plugin + * + * @return true if this plugin is initialized, otherwise false + * @deprecated This method cannot return false, as {@link + * JavaPlugin} is now initialized in the constructor. + */ + @Deprecated + public final boolean isInitialized() { + return true; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { + return false; + } + + /** + * {@inheritDoc} + */ + @Override + public List onTabComplete(CommandSender sender, Command command, String alias, String[] args) { + return null; + } + + /** + * Gets the command with the given name, specific to this plugin. Commands + * need to be registered in the {@link PluginDescriptionFile#getCommands() + * PluginDescriptionFile} to exist at runtime. + * + * @param name name or alias of the command + * @return the plugin command if found, otherwise null + */ + public PluginCommand getCommand(String name) { + String alias = name.toLowerCase(); + PluginCommand command = getServer().getPluginCommand(alias); + + if (command == null || command.getPlugin() != this) { + command = getServer().getPluginCommand(description.getName().toLowerCase() + ":" + alias); + } + + if (command != null && command.getPlugin() == this) { + return command; + } else { + return null; + } + } + + @Override + public void onLoad() {} + + @Override + public void onDisable() {} + + @Override + public void onEnable() {} + + @Override + public ChunkGenerator getDefaultWorldGenerator(String worldName, String id) { + return null; + } + + @Override + public final boolean isNaggable() { + return naggable; + } + + @Override + public final void setNaggable(boolean canNag) { + this.naggable = canNag; + } + + @Override + public EbeanServer getDatabase() { + return ebean; + } + + protected void installDDL() { + SpiEbeanServer serv = (SpiEbeanServer) getDatabase(); + DdlGenerator gen = serv.getDdlGenerator(); + + gen.runScript(false, gen.generateCreateDdl()); + } + + protected void removeDDL() { + SpiEbeanServer serv = (SpiEbeanServer) getDatabase(); + DdlGenerator gen = serv.getDdlGenerator(); + + gen.runScript(true, gen.generateDropDdl()); + } + + @Override + public Logger getLogger() { // Beanes make non final to fix + return logger; + } + + @Override + public String toString() { + return description.getFullName(); + } + + /** + * This method provides fast access to the plugin that has {@link + * #getProvidingPlugin(Class) provided} the given plugin class, which is + * usually the plugin that implemented it. + *

+ * An exception to this would be if plugin's jar that contained the class + * does not extend the class, where the intended plugin would have + * resided in a different jar / classloader. + * + * @param a class that extends JavaPlugin + * @param clazz the class desired + * @return the plugin that provides and implements said class + * @throws IllegalArgumentException if clazz is null + * @throws IllegalArgumentException if clazz does not extend {@link + * JavaPlugin} + * @throws IllegalStateException if clazz was not provided by a plugin, + * for example, if called with + * JavaPlugin.getPlugin(JavaPlugin.class) + * @throws IllegalStateException if called from the static initializer for + * given JavaPlugin + * @throws ClassCastException if plugin that provided the class does not + * extend the class + */ + public static T getPlugin(Class clazz) { + Validate.notNull(clazz, "Null class cannot have a plugin"); + if (!JavaPlugin.class.isAssignableFrom(clazz)) { + throw new IllegalArgumentException(clazz + " does not extend " + JavaPlugin.class); + } + final ClassLoader cl = clazz.getClassLoader(); + if (!(cl instanceof PluginClassLoader)) { + throw new IllegalArgumentException(clazz + " is not initialized by " + PluginClassLoader.class); + } + JavaPlugin plugin = ((PluginClassLoader) cl).plugin; + if (plugin == null) { + throw new IllegalStateException("Cannot get plugin for " + clazz + " from a static initializer"); + } + return clazz.cast(plugin); + } + + /** + * This method provides fast access to the plugin that has provided the + * given class. + * + * @param clazz a class belonging to a plugin + * @return the plugin that provided the class + * @throws IllegalArgumentException if the class is not provided by a + * JavaPlugin + * @throws IllegalArgumentException if class is null + * @throws IllegalStateException if called from the static initializer for + * given JavaPlugin + */ + public static JavaPlugin getProvidingPlugin(Class clazz) { + Validate.notNull(clazz, "Null class cannot have a plugin"); + final ClassLoader cl = clazz.getClassLoader(); + if (!(cl instanceof PluginClassLoader)) { + throw new IllegalArgumentException(clazz + " is not provided by " + PluginClassLoader.class); + } + JavaPlugin plugin = ((PluginClassLoader) cl).plugin; + if (plugin == null) { + throw new IllegalStateException("Cannot get plugin for " + clazz + " from a static initializer"); + } + return plugin; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/plugin/java/JavaPluginLoader.java b/azurite-api/src/main/java/org/bukkit/plugin/java/JavaPluginLoader.java new file mode 100644 index 0000000..2e667cb --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/plugin/java/JavaPluginLoader.java @@ -0,0 +1,338 @@ +package org.bukkit.plugin.java; + +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.Server; +import org.bukkit.Warning; +import org.bukkit.Warning.WarningState; +import org.bukkit.configuration.serialization.ConfigurationSerializable; +import org.bukkit.configuration.serialization.ConfigurationSerialization; +import org.bukkit.event.Event; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.server.PluginDisableEvent; +import org.bukkit.event.server.PluginEnableEvent; +import org.bukkit.plugin.*; +import org.yaml.snakeyaml.error.YAMLException; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Method; +import java.util.*; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; +import java.util.logging.Level; +import java.util.regex.Pattern; + +/** + * Represents a Java plugin loader, allowing plugins in the form of .jar + */ +public final class JavaPluginLoader implements PluginLoader { + final Server server; + private final Pattern[] fileFilters = {Pattern.compile("\\.jar$"),}; + private final Map> classes = new java.util.concurrent.ConcurrentHashMap<>(); // Spigot + private final Map loaders = new LinkedHashMap<>(); + + /** + * This class was not meant to be constructed explicitly + * + * @param instance the server instance + */ + @Deprecated + public JavaPluginLoader(Server instance) { + Validate.notNull(instance, "Server cannot be null"); + server = instance; + } + + public Plugin loadPlugin(final File file) throws InvalidPluginException { + Validate.notNull(file, "File cannot be null"); + + if (!file.exists()) { + throw new InvalidPluginException(new FileNotFoundException(file.getPath() + " does not exist")); + } + + final PluginDescriptionFile description; + try { + description = getPluginDescription(file); + } catch (InvalidDescriptionException ex) { + throw new InvalidPluginException(ex); + } + + final File parentFile = file.getParentFile(); + final File dataFolder = new File(parentFile, description.getName()); + @SuppressWarnings("deprecation") final File oldDataFolder = new File(parentFile, description.getRawName()); + + // Found old data folder + if (dataFolder.equals(oldDataFolder)) { + // They are equal -- nothing needs to be done! + } else if (dataFolder.isDirectory() && oldDataFolder.isDirectory()) { + server.getLogger().warning(String.format( + "While loading %s (%s) found old-data folder: `%s' next to the new one `%s'", + description.getFullName(), + file, + oldDataFolder, + dataFolder + )); + } else if (oldDataFolder.isDirectory() && !dataFolder.exists()) { + if (!oldDataFolder.renameTo(dataFolder)) { + throw new InvalidPluginException("Unable to rename old data folder: `" + oldDataFolder + "' to: `" + dataFolder + "'"); + } + server.getLogger().log(Level.INFO, String.format( + "While loading %s (%s) renamed data folder: `%s' to `%s'", + description.getFullName(), + file, + oldDataFolder, + dataFolder + )); + } + + if (dataFolder.exists() && !dataFolder.isDirectory()) { + throw new InvalidPluginException(String.format( + "Projected datafolder: `%s' for %s (%s) exists and is not a directory", + dataFolder, + description.getFullName(), + file + )); + } + + for (final String pluginName : description.getDepend()) { + PluginClassLoader current = loaders.get(pluginName); + + if (current == null) { + throw new UnknownDependencyException(pluginName); + } + } + + final PluginClassLoader loader; + try { + loader = new PluginClassLoader(this, getClass().getClassLoader(), description, dataFolder, file); + } catch (InvalidPluginException ex) { + throw ex; + } catch (Throwable ex) { + throw new InvalidPluginException(ex); + } + + loaders.put(description.getName(), loader); + try { + if (description.getCommands().containsKey("ver") || description.getCommands().containsKey("version")) { + Bukkit.getLogger().info("Didn't load plugin " + description.getName() + " due to attempt to create the command /version."); + return null; + } + } catch (NullPointerException ignored) { + } + return loader.plugin; + } + + public PluginDescriptionFile getPluginDescription(File file) throws InvalidDescriptionException { + Validate.notNull(file, "File cannot be null"); + + JarFile jar = null; + InputStream stream = null; + + try { + jar = new JarFile(file); + JarEntry entry = jar.getJarEntry("plugin.yml"); + + if (entry == null) { + throw new InvalidDescriptionException(new FileNotFoundException("Jar does not contain plugin.yml")); + } + + stream = jar.getInputStream(entry); + + return new PluginDescriptionFile(stream); + + } catch (IOException | YAMLException ex) { + throw new InvalidDescriptionException(ex); + } finally { + if (jar != null) { + try { + jar.close(); + } catch (IOException ignored) { + } + } + if (stream != null) { + try { + stream.close(); + } catch (IOException ignored) { + } + } + } + } + + public Pattern[] getPluginFileFilters() { + return fileFilters.clone(); + } + + Class getClassByName(final String name) { + Class cachedClass = classes.get(name); + + if (cachedClass != null) { + return cachedClass; + } else { + for (String current : loaders.keySet()) { + PluginClassLoader loader = loaders.get(current); + + try { + cachedClass = loader.findClass(name, false); + } catch (ClassNotFoundException ignored) { + } + if (cachedClass != null) { + return cachedClass; + } + } + } + return null; + } + + void setClass(final String name, final Class clazz) { + if (!classes.containsKey(name)) { + classes.put(name, clazz); + + if (ConfigurationSerializable.class.isAssignableFrom(clazz)) { + Class serializable = clazz.asSubclass(ConfigurationSerializable.class); + ConfigurationSerialization.registerClass(serializable); + } + } + } + + private void removeClass(String name) { + Class clazz = classes.remove(name); + + try { + if ((clazz != null) && (ConfigurationSerializable.class.isAssignableFrom(clazz))) { + Class serializable = clazz.asSubclass(ConfigurationSerializable.class); + ConfigurationSerialization.unregisterClass(serializable); + } + } catch (NullPointerException ex) { + // Boggle! + // (Native methods throwing NPEs is not fun when you can't stop it before-hand) + } + } + + public Map, Set> createRegisteredListeners(Listener listener, final Plugin plugin) { + Validate.notNull(plugin, "Plugin can not be null"); + Validate.notNull(listener, "Listener can not be null"); + + Map, Set> ret = new HashMap<>(); + Set methods; + try { + Method[] publicMethods = listener.getClass().getMethods(); + Method[] privateMethods = listener.getClass().getDeclaredMethods(); + methods = new HashSet<>(publicMethods.length + privateMethods.length, 1.0f); + methods.addAll(Arrays.asList(publicMethods)); + methods.addAll(Arrays.asList(privateMethods)); + } catch (NoClassDefFoundError e) { + plugin.getLogger().severe("Plugin " + plugin.getDescription().getFullName() + " has failed to register events for " + listener.getClass() + " because " + e.getMessage() + " does not exist."); + return ret; + } + + for (final Method method : methods) { + final EventHandler eh = method.getAnnotation(EventHandler.class); + if (eh == null) continue; + // Do not register bridge or synthetic methods to avoid event duplication + // Fixes SPIGOT-893 + if (method.isBridge() || method.isSynthetic()) { + continue; + } + final Class checkClass; + if (method.getParameterTypes().length != 1 || !Event.class.isAssignableFrom(checkClass = method.getParameterTypes()[0])) { + plugin.getLogger().severe(plugin.getDescription().getFullName() + " attempted to register an invalid EventHandler method signature \"" + method.toGenericString() + "\" in " + listener.getClass()); + continue; + } + final Class eventClass = checkClass.asSubclass(Event.class); + method.setAccessible(true); + Set eventSet = ret.computeIfAbsent(eventClass, k -> new HashSet<>()); + + for (Class clazz = eventClass; Event.class.isAssignableFrom(clazz); clazz = clazz.getSuperclass()) { + // This loop checks for extending deprecated events + if (clazz.getAnnotation(Deprecated.class) != null) { + Warning warning = clazz.getAnnotation(Warning.class); + WarningState warningState = server.getWarningState(); + if (!warningState.printFor(warning)) { + break; + } + plugin.getLogger().log( + Level.WARNING, + String.format( + "\"%s\" has registered a listener for %s on method \"%s\", but the event is Deprecated." + + " \"%s\"; please notify the authors %s.", + plugin.getDescription().getFullName(), + clazz.getName(), + method.toGenericString(), + (warning != null && warning.reason().length() != 0) ? warning.reason() : "Server performance will be affected", + Arrays.toString(plugin.getDescription().getAuthors().toArray())), + warningState == WarningState.ON ? new AuthorNagException(null) : null); + break; + } + } + + // Azurite start - ASM events backport + eventSet.add(new RegisteredListener(listener, EventExecutor.create(method, eventClass), eh.priority(), plugin, eh.ignoreCancelled())); + // Azurite end + } + return ret; + } + + public void enablePlugin(final Plugin plugin) { + Validate.isTrue(plugin instanceof JavaPlugin, "Plugin is not associated with this PluginLoader"); + + if (!plugin.isEnabled()) { + plugin.getLogger().info("Enabling " + plugin.getDescription().getFullName()); + + JavaPlugin jPlugin = (JavaPlugin) plugin; + + String pluginName = jPlugin.getDescription().getName(); + + if (!loaders.containsKey(pluginName)) { + loaders.put(pluginName, (PluginClassLoader) jPlugin.getClassLoader()); + } + + try { + jPlugin.setEnabled(true); + } catch (Throwable ex) { + server.getLogger().log(Level.SEVERE, "Error occurred while enabling " + plugin.getDescription().getFullName() + " (Is it up to date?)", ex); + // PaperSpigot start - Disable plugins that fail to load + disablePlugin(jPlugin); + return; + // PaperSpigot end + } + + // Perhaps abort here, rather than continue going, but as it stands, + // an abort is not possible the way it's currently written + server.getPluginManager().callEvent(new PluginEnableEvent(plugin)); + } + } + + public void disablePlugin(Plugin plugin) { + Validate.isTrue(plugin instanceof JavaPlugin, "Plugin is not associated with this PluginLoader"); + + if (plugin.isEnabled()) { + String message = String.format("Disabling %s", plugin.getDescription().getFullName()); + plugin.getLogger().info(message); + + server.getPluginManager().callEvent(new PluginDisableEvent(plugin)); + + JavaPlugin jPlugin = (JavaPlugin) plugin; + ClassLoader cloader = jPlugin.getClassLoader(); + + try { + jPlugin.setEnabled(false); + } catch (Throwable ex) { + server.getLogger().log(Level.SEVERE, "Error occurred while disabling " + plugin.getDescription().getFullName() + " (Is it up to date?)", ex); + } + + loaders.remove(jPlugin.getDescription().getName()); + + if (cloader instanceof PluginClassLoader) { + PluginClassLoader loader = (PluginClassLoader) cloader; + Set names = loader.getClasses(); + + for (String name : names) { + removeClass(name); + } + } + } + } +} diff --git a/azurite-api/src/main/java/org/bukkit/plugin/java/PluginClassLoader.java b/azurite-api/src/main/java/org/bukkit/plugin/java/PluginClassLoader.java new file mode 100644 index 0000000..2f918b4 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/plugin/java/PluginClassLoader.java @@ -0,0 +1,129 @@ +package org.bukkit.plugin.java; + +import org.apache.commons.lang.Validate; +import org.bukkit.plugin.InvalidPluginException; +import org.bukkit.plugin.PluginDescriptionFile; + +import java.io.File; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.Map; +import java.util.Set; + +/** + * A ClassLoader for plugins, to allow shared classes across multiple plugins + */ +public final class PluginClassLoader extends URLClassLoader { // Spigot + public JavaPlugin getPlugin() { return plugin; } // Spigot + private final JavaPluginLoader loader; + private final Map> classes = new java.util.concurrent.ConcurrentHashMap>(); // Spigot + private final PluginDescriptionFile description; + private final File dataFolder; + private final File file; + final JavaPlugin plugin; + private JavaPlugin pluginInit; + private IllegalStateException pluginState; + + // Spigot Start + static + { + try + { + java.lang.reflect.Method method = ClassLoader.class.getDeclaredMethod( "registerAsParallelCapable" ); + if ( method != null ) + { + boolean oldAccessible = method.isAccessible(); + method.setAccessible( true ); + method.invoke( null ); + method.setAccessible( oldAccessible ); + } + } catch ( NoSuchMethodException ex ) + { + // Ignore + } catch ( Exception ex ) + { + org.bukkit.Bukkit.getLogger().log( java.util.logging.Level.WARNING, "Error setting PluginClassLoader as parallel capable", ex ); + } + } + // Spigot End + + PluginClassLoader(final JavaPluginLoader loader, final ClassLoader parent, final PluginDescriptionFile description, final File dataFolder, final File file) throws InvalidPluginException, MalformedURLException { + super(new URL[] {file.toURI().toURL()}, parent); + Validate.notNull(loader, "Loader cannot be null"); + + this.loader = loader; + this.description = description; + this.dataFolder = dataFolder; + this.file = file; + + try { + Class jarClass; + try { + jarClass = Class.forName(description.getMain(), true, this); + } catch (ClassNotFoundException ex) { + throw new InvalidPluginException("Cannot find main class `" + description.getMain() + "'", ex); + } + + Class pluginClass; + try { + pluginClass = jarClass.asSubclass(JavaPlugin.class); + } catch (ClassCastException ex) { + throw new InvalidPluginException("main class `" + description.getMain() + "' does not extend JavaPlugin", ex); + } + + plugin = pluginClass.newInstance(); + } catch (IllegalAccessException ex) { + throw new InvalidPluginException("No public constructor", ex); + } catch (InstantiationException ex) { + throw new InvalidPluginException("Abnormal plugin type", ex); + } + } + + @Override + protected Class findClass(String name) throws ClassNotFoundException { + return findClass(name, true); + } + + Class findClass(String name, boolean checkGlobal) throws ClassNotFoundException { + if (name.startsWith("org.bukkit.") || name.startsWith("net.minecraft.")) { + throw new ClassNotFoundException(name); + } + Class result = classes.get(name); + + if (result == null) { + if (checkGlobal) { + result = loader.getClassByName(name); + } + + if (result == null) { + result = super.findClass(name); + + if (result != null) { + loader.setClass(name, result); + } + } + + classes.put(name, result); + } + + return result; + } + + Set getClasses() { + return classes.keySet(); + } + + synchronized void initialize(JavaPlugin javaPlugin) { + Validate.notNull(javaPlugin, "Initializing plugin cannot be null"); + Validate.isTrue(javaPlugin.getClass().getClassLoader() == this, "Cannot initialize plugin outside of this class loader"); + if (this.plugin != null || this.pluginInit != null) { + throw new IllegalArgumentException("Plugin already initialized!", pluginState); + } + + pluginState = new IllegalStateException("Initial initialization"); + this.pluginInit = javaPlugin; + + javaPlugin.init(loader, loader.server, description, dataFolder, file, this); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/plugin/messaging/ChannelNameTooLongException.java b/azurite-api/src/main/java/org/bukkit/plugin/messaging/ChannelNameTooLongException.java new file mode 100644 index 0000000..80ef8a2 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/plugin/messaging/ChannelNameTooLongException.java @@ -0,0 +1,15 @@ +package org.bukkit.plugin.messaging; + +/** + * Thrown if a Plugin Channel is too long. + */ +@SuppressWarnings("serial") +public class ChannelNameTooLongException extends RuntimeException { + public ChannelNameTooLongException() { + super("Attempted to send a Plugin Message to a channel that was too large. The maximum length a channel may be is " + Messenger.MAX_CHANNEL_SIZE + " chars."); + } + + public ChannelNameTooLongException(String channel) { + super("Attempted to send a Plugin Message to a channel that was too large. The maximum length a channel may be is " + Messenger.MAX_CHANNEL_SIZE + " chars (attempted " + channel.length() + " - '" + channel + "."); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/plugin/messaging/ChannelNotRegisteredException.java b/azurite-api/src/main/java/org/bukkit/plugin/messaging/ChannelNotRegisteredException.java new file mode 100644 index 0000000..2266f17 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/plugin/messaging/ChannelNotRegisteredException.java @@ -0,0 +1,15 @@ +package org.bukkit.plugin.messaging; + +/** + * Thrown if a Plugin attempts to send a message on an unregistered channel. + */ +@SuppressWarnings("serial") +public class ChannelNotRegisteredException extends RuntimeException { + public ChannelNotRegisteredException() { + this("Attempted to send a plugin message through an unregistered channel."); + } + + public ChannelNotRegisteredException(String channel) { + super("Attempted to send a plugin message through the unregistered channel `" + channel + "'."); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/plugin/messaging/MessageTooLargeException.java b/azurite-api/src/main/java/org/bukkit/plugin/messaging/MessageTooLargeException.java new file mode 100644 index 0000000..61af8c4 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/plugin/messaging/MessageTooLargeException.java @@ -0,0 +1,23 @@ +package org.bukkit.plugin.messaging; + +/** + * Thrown if a Plugin Message is sent that is too large to be sent. + */ +@SuppressWarnings("serial") +public class MessageTooLargeException extends RuntimeException { + public MessageTooLargeException() { + this("Attempted to send a plugin message that was too large. The maximum length a plugin message may be is " + Messenger.MAX_MESSAGE_SIZE + " bytes."); + } + + public MessageTooLargeException(byte[] message) { + this(message.length); + } + + public MessageTooLargeException(int length) { + this("Attempted to send a plugin message that was too large. The maximum length a plugin message may be is " + Messenger.MAX_MESSAGE_SIZE + " bytes (tried to send one that is " + length + " bytes long)."); + } + + public MessageTooLargeException(String msg) { + super(msg); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/plugin/messaging/Messenger.java b/azurite-api/src/main/java/org/bukkit/plugin/messaging/Messenger.java new file mode 100644 index 0000000..7b52280 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/plugin/messaging/Messenger.java @@ -0,0 +1,217 @@ +package org.bukkit.plugin.messaging; + +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; + +import java.util.Set; + +/** + * A class responsible for managing the registrations of plugin channels and + * their listeners. + */ +public interface Messenger { + + /** + * Represents the largest size that an individual Plugin Message may be. + */ + int MAX_MESSAGE_SIZE = 32766; + + /** + * Represents the largest size that a Plugin Channel may be. + */ + int MAX_CHANNEL_SIZE = 20; + + /** + * Checks if the specified channel is a reserved name. + * + * @param channel Channel name to check. + * @return True if the channel is reserved, otherwise false. + * @throws IllegalArgumentException Thrown if channel is null. + */ + boolean isReservedChannel(String channel); + + /** + * Registers the specific plugin to the requested outgoing plugin channel, + * allowing it to send messages through that channel to any clients. + * + * @param plugin Plugin that wishes to send messages through the channel. + * @param channel Channel to register. + * @throws IllegalArgumentException Thrown if plugin or channel is null. + */ + void registerOutgoingPluginChannel(Plugin plugin, String channel); + + /** + * Unregisters the specific plugin from the requested outgoing plugin + * channel, no longer allowing it to send messages through that channel to + * any clients. + * + * @param plugin Plugin that no longer wishes to send messages through the + * channel. + * @param channel Channel to unregister. + * @throws IllegalArgumentException Thrown if plugin or channel is null. + */ + void unregisterOutgoingPluginChannel(Plugin plugin, String channel); + + /** + * Unregisters the specific plugin from all outgoing plugin channels, no + * longer allowing it to send any plugin messages. + * + * @param plugin Plugin that no longer wishes to send plugin messages. + * @throws IllegalArgumentException Thrown if plugin is null. + */ + void unregisterOutgoingPluginChannel(Plugin plugin); + + /** + * Registers the specific plugin for listening on the requested incoming + * plugin channel, allowing it to act upon any plugin messages. + * + * @param plugin Plugin that wishes to register to this channel. + * @param channel Channel to register. + * @param listener Listener to receive messages on. + * @return The resulting registration that was made as a result of this + * method. + * @throws IllegalArgumentException Thrown if plugin, channel or listener + * is null, or the listener is already registered for this channel. + */ + PluginMessageListenerRegistration registerIncomingPluginChannel(Plugin plugin, String channel, PluginMessageListener listener); + + /** + * Unregisters the specific plugin's listener from listening on the + * requested incoming plugin channel, no longer allowing it to act upon + * any plugin messages. + * + * @param plugin Plugin that wishes to unregister from this channel. + * @param channel Channel to unregister. + * @param listener Listener to stop receiving messages on. + * @throws IllegalArgumentException Thrown if plugin, channel or listener + * is null. + */ + void unregisterIncomingPluginChannel(Plugin plugin, String channel, PluginMessageListener listener); + + /** + * Unregisters the specific plugin from listening on the requested + * incoming plugin channel, no longer allowing it to act upon any plugin + * messages. + * + * @param plugin Plugin that wishes to unregister from this channel. + * @param channel Channel to unregister. + * @throws IllegalArgumentException Thrown if plugin or channel is null. + */ + void unregisterIncomingPluginChannel(Plugin plugin, String channel); + + /** + * Unregisters the specific plugin from listening on all plugin channels + * through all listeners. + * + * @param plugin Plugin that wishes to unregister from this channel. + * @throws IllegalArgumentException Thrown if plugin is null. + */ + void unregisterIncomingPluginChannel(Plugin plugin); + + /** + * Gets a set containing all the outgoing plugin channels. + * + * @return List of all registered outgoing plugin channels. + */ + Set getOutgoingChannels(); + + /** + * Gets a set containing all the outgoing plugin channels that the + * specified plugin is registered to. + * + * @param plugin Plugin to retrieve channels for. + * @return List of all registered outgoing plugin channels that a plugin + * is registered to. + * @throws IllegalArgumentException Thrown if plugin is null. + */ + Set getOutgoingChannels(Plugin plugin); + + /** + * Gets a set containing all the incoming plugin channels. + * + * @return List of all registered incoming plugin channels. + */ + Set getIncomingChannels(); + + /** + * Gets a set containing all the incoming plugin channels that the + * specified plugin is registered for. + * + * @param plugin Plugin to retrieve channels for. + * @return List of all registered incoming plugin channels that the plugin + * is registered for. + * @throws IllegalArgumentException Thrown if plugin is null. + */ + Set getIncomingChannels(Plugin plugin); + + /** + * Gets a set containing all the incoming plugin channel registrations + * that the specified plugin has. + * + * @param plugin Plugin to retrieve registrations for. + * @return List of all registrations that the plugin has. + * @throws IllegalArgumentException Thrown if plugin is null. + */ + Set getIncomingChannelRegistrations(Plugin plugin); + + /** + * Gets a set containing all the incoming plugin channel registrations + * that are on the requested channel. + * + * @param channel Channel to retrieve registrations for. + * @return List of all registrations that are on the channel. + * @throws IllegalArgumentException Thrown if channel is null. + */ + Set getIncomingChannelRegistrations(String channel); + + /** + * Gets a set containing all the incoming plugin channel registrations + * that the specified plugin has on the requested channel. + * + * @param plugin Plugin to retrieve registrations for. + * @param channel Channel to filter registrations by. + * @return List of all registrations that the plugin has. + * @throws IllegalArgumentException Thrown if plugin or channel is null. + */ + Set getIncomingChannelRegistrations(Plugin plugin, String channel); + + /** + * Checks if the specified plugin message listener registration is valid. + *

+ * A registration is considered valid if it has not be unregistered and + * that the plugin is still enabled. + * + * @param registration Registration to check. + * @return True if the registration is valid, otherwise false. + */ + boolean isRegistrationValid(PluginMessageListenerRegistration registration); + + /** + * Checks if the specified plugin has registered to receive incoming + * messages through the requested channel. + * + * @param plugin Plugin to check registration for. + * @param channel Channel to test for. + * @return True if the channel is registered, else false. + */ + boolean isIncomingChannelRegistered(Plugin plugin, String channel); + + /** + * Checks if the specified plugin has registered to send outgoing messages + * through the requested channel. + * + * @param plugin Plugin to check registration for. + * @param channel Channel to test for. + * @return True if the channel is registered, else false. + */ + boolean isOutgoingChannelRegistered(Plugin plugin, String channel); + + /** + * Dispatches the specified incoming message to any registered listeners. + * + * @param source Source of the message. + * @param channel Channel that the message was sent by. + * @param message Raw payload of the message. + */ + void dispatchIncomingMessage(Player source, String channel, byte[] message); +} diff --git a/azurite-api/src/main/java/org/bukkit/plugin/messaging/PluginChannelDirection.java b/azurite-api/src/main/java/org/bukkit/plugin/messaging/PluginChannelDirection.java new file mode 100644 index 0000000..3d7ec2e --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/plugin/messaging/PluginChannelDirection.java @@ -0,0 +1,17 @@ +package org.bukkit.plugin.messaging; + +/** + * Represents the different directions a plugin channel may go. + */ +public enum PluginChannelDirection { + + /** + * The plugin channel is being sent to the server from a client. + */ + INCOMING, + + /** + * The plugin channel is being sent to a client from the server. + */ + OUTGOING +} diff --git a/azurite-api/src/main/java/org/bukkit/plugin/messaging/PluginMessageListener.java b/azurite-api/src/main/java/org/bukkit/plugin/messaging/PluginMessageListener.java new file mode 100644 index 0000000..a0978cb --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/plugin/messaging/PluginMessageListener.java @@ -0,0 +1,20 @@ +package org.bukkit.plugin.messaging; + +import org.bukkit.entity.Player; + +/** + * A listener for a specific Plugin Channel, which will receive notifications + * of messages sent from a client. + */ +public interface PluginMessageListener { + + /** + * A method that will be thrown when a PluginMessageSource sends a plugin + * message on a registered channel. + * + * @param channel Channel that the message was sent through. + * @param player Source of the message. + * @param message The raw message that was sent. + */ + void onPluginMessageReceived(String channel, Player player, byte[] message); +} diff --git a/azurite-api/src/main/java/org/bukkit/plugin/messaging/PluginMessageListenerRegistration.java b/azurite-api/src/main/java/org/bukkit/plugin/messaging/PluginMessageListenerRegistration.java new file mode 100644 index 0000000..29929bf --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/plugin/messaging/PluginMessageListenerRegistration.java @@ -0,0 +1,104 @@ +package org.bukkit.plugin.messaging; + +import org.bukkit.plugin.Plugin; + +/** + * Contains information about a {@link Plugin}s registration to a plugin + * channel. + */ +public final class PluginMessageListenerRegistration { + private final Messenger messenger; + private final Plugin plugin; + private final String channel; + private final PluginMessageListener listener; + + public PluginMessageListenerRegistration(Messenger messenger, Plugin plugin, String channel, PluginMessageListener listener) { + if (messenger == null) { + throw new IllegalArgumentException("Messenger cannot be null!"); + } + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null!"); + } + if (channel == null) { + throw new IllegalArgumentException("Channel cannot be null!"); + } + if (listener == null) { + throw new IllegalArgumentException("Listener cannot be null!"); + } + + this.messenger = messenger; + this.plugin = plugin; + this.channel = channel; + this.listener = listener; + } + + /** + * Gets the plugin channel that this registration is about. + * + * @return Plugin channel. + */ + public String getChannel() { + return channel; + } + + /** + * Gets the registered listener described by this registration. + * + * @return Registered listener. + */ + public PluginMessageListener getListener() { + return listener; + } + + /** + * Gets the plugin that this registration is for. + * + * @return Registered plugin. + */ + public Plugin getPlugin() { + return plugin; + } + + /** + * Checks if this registration is still valid. + * + * @return True if this registration is still valid, otherwise false. + */ + public boolean isValid() { + return messenger.isRegistrationValid(this); + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final PluginMessageListenerRegistration other = (PluginMessageListenerRegistration) obj; + if (this.messenger != other.messenger && (this.messenger == null || !this.messenger.equals(other.messenger))) { + return false; + } + if (this.plugin != other.plugin && (this.plugin == null || !this.plugin.equals(other.plugin))) { + return false; + } + if ((this.channel == null) ? (other.channel != null) : !this.channel.equals(other.channel)) { + return false; + } + if (this.listener != other.listener && (this.listener == null || !this.listener.equals(other.listener))) { + return false; + } + return true; + } + + @Override + public int hashCode() { + int hash = 7; + hash = 53 * hash + (this.messenger != null ? this.messenger.hashCode() : 0); + hash = 53 * hash + (this.plugin != null ? this.plugin.hashCode() : 0); + hash = 53 * hash + (this.channel != null ? this.channel.hashCode() : 0); + hash = 53 * hash + (this.listener != null ? this.listener.hashCode() : 0); + return hash; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/plugin/messaging/PluginMessageRecipient.java b/azurite-api/src/main/java/org/bukkit/plugin/messaging/PluginMessageRecipient.java new file mode 100644 index 0000000..9479835 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/plugin/messaging/PluginMessageRecipient.java @@ -0,0 +1,39 @@ +package org.bukkit.plugin.messaging; + +import org.bukkit.plugin.Plugin; + +import java.util.Set; + +/** + * Represents a possible recipient for a Plugin Message. + */ +public interface PluginMessageRecipient { + /** + * Sends this recipient a Plugin Message on the specified outgoing + * channel. + *

+ * The message may not be larger than {@link Messenger#MAX_MESSAGE_SIZE} + * bytes, and the plugin must be registered to send messages on the + * specified channel. + * + * @param source The plugin that sent this message. + * @param channel The channel to send this message on. + * @param message The raw message to send. + * @throws IllegalArgumentException Thrown if the source plugin is + * disabled. + * @throws IllegalArgumentException Thrown if source, channel or message + * is null. + * @throws MessageTooLargeException Thrown if the message is too big. + * @throws ChannelNotRegisteredException Thrown if the channel is not + * registered for this plugin. + */ + void sendPluginMessage(Plugin source, String channel, byte[] message); + + /** + * Gets a set containing all the Plugin Channels that this client is + * listening on. + * + * @return Set containing all the channels that this client may accept. + */ + Set getListeningPluginChannels(); +} diff --git a/azurite-api/src/main/java/org/bukkit/plugin/messaging/ReservedChannelException.java b/azurite-api/src/main/java/org/bukkit/plugin/messaging/ReservedChannelException.java new file mode 100644 index 0000000..0221f04 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/plugin/messaging/ReservedChannelException.java @@ -0,0 +1,16 @@ +package org.bukkit.plugin.messaging; + +/** + * Thrown if a plugin attempts to register for a reserved channel (such as + * "REGISTER") + */ +@SuppressWarnings("serial") +public class ReservedChannelException extends RuntimeException { + public ReservedChannelException() { + this("Attempted to register for a reserved channel name."); + } + + public ReservedChannelException(String name) { + super("Attempted to register for a reserved channel name ('" + name + "')"); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/plugin/messaging/StandardMessenger.java b/azurite-api/src/main/java/org/bukkit/plugin/messaging/StandardMessenger.java new file mode 100644 index 0000000..ce2a905 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/plugin/messaging/StandardMessenger.java @@ -0,0 +1,490 @@ +package org.bukkit.plugin.messaging; + +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.ImmutableSet.Builder; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +/** + * Standard implementation to {@link Messenger} + */ +public class StandardMessenger implements Messenger { + private final Map> incomingByChannel = new HashMap>(); + private final Map> incomingByPlugin = new HashMap>(); + private final Map> outgoingByChannel = new HashMap>(); + private final Map> outgoingByPlugin = new HashMap>(); + private final Object incomingLock = new Object(); + private final Object outgoingLock = new Object(); + + private void addToOutgoing(Plugin plugin, String channel) { + synchronized (outgoingLock) { + Set plugins = outgoingByChannel.get(channel); + Set channels = outgoingByPlugin.get(plugin); + + if (plugins == null) { + plugins = new HashSet(); + outgoingByChannel.put(channel, plugins); + } + + if (channels == null) { + channels = new HashSet(); + outgoingByPlugin.put(plugin, channels); + } + + plugins.add(plugin); + channels.add(channel); + } + } + + private void removeFromOutgoing(Plugin plugin, String channel) { + synchronized (outgoingLock) { + Set plugins = outgoingByChannel.get(channel); + Set channels = outgoingByPlugin.get(plugin); + + if (plugins != null) { + plugins.remove(plugin); + + if (plugins.isEmpty()) { + outgoingByChannel.remove(channel); + } + } + + if (channels != null) { + channels.remove(channel); + + if (channels.isEmpty()) { + outgoingByChannel.remove(channel); + } + } + } + } + + private void removeFromOutgoing(Plugin plugin) { + synchronized (outgoingLock) { + Set channels = outgoingByPlugin.get(plugin); + + if (channels != null) { + String[] toRemove = channels.toArray(new String[0]); + + outgoingByPlugin.remove(plugin); + + for (String channel : toRemove) { + removeFromOutgoing(plugin, channel); + } + } + } + } + + private void addToIncoming(PluginMessageListenerRegistration registration) { + synchronized (incomingLock) { + Set registrations = incomingByChannel.get(registration.getChannel()); + + if (registrations == null) { + registrations = new HashSet(); + incomingByChannel.put(registration.getChannel(), registrations); + } else { + if (registrations.contains(registration)) { + throw new IllegalArgumentException("This registration already exists"); + } + } + + registrations.add(registration); + + registrations = incomingByPlugin.get(registration.getPlugin()); + + if (registrations == null) { + registrations = new HashSet(); + incomingByPlugin.put(registration.getPlugin(), registrations); + } else { + if (registrations.contains(registration)) { + throw new IllegalArgumentException("This registration already exists"); + } + } + + registrations.add(registration); + } + } + + private void removeFromIncoming(PluginMessageListenerRegistration registration) { + synchronized (incomingLock) { + Set registrations = incomingByChannel.get(registration.getChannel()); + + if (registrations != null) { + registrations.remove(registration); + + if (registrations.isEmpty()) { + incomingByChannel.remove(registration.getChannel()); + } + } + + registrations = incomingByPlugin.get(registration.getPlugin()); + + if (registrations != null) { + registrations.remove(registration); + + if (registrations.isEmpty()) { + incomingByPlugin.remove(registration.getPlugin()); + } + } + } + } + + private void removeFromIncoming(Plugin plugin, String channel) { + synchronized (incomingLock) { + Set registrations = incomingByPlugin.get(plugin); + + if (registrations != null) { + PluginMessageListenerRegistration[] toRemove = registrations.toArray(new PluginMessageListenerRegistration[0]); + + for (PluginMessageListenerRegistration registration : toRemove) { + if (registration.getChannel().equals(channel)) { + removeFromIncoming(registration); + } + } + } + } + } + + private void removeFromIncoming(Plugin plugin) { + synchronized (incomingLock) { + Set registrations = incomingByPlugin.get(plugin); + + if (registrations != null) { + PluginMessageListenerRegistration[] toRemove = registrations.toArray(new PluginMessageListenerRegistration[0]); + + incomingByPlugin.remove(plugin); + + for (PluginMessageListenerRegistration registration : toRemove) { + removeFromIncoming(registration); + } + } + } + } + + public boolean isReservedChannel(String channel) { + validateChannel(channel); + + return channel.equals("REGISTER") || channel.equals("UNREGISTER"); + } + + public void registerOutgoingPluginChannel(Plugin plugin, String channel) { + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null"); + } + validateChannel(channel); + if (isReservedChannel(channel)) { + throw new ReservedChannelException(channel); + } + + addToOutgoing(plugin, channel); + } + + public void unregisterOutgoingPluginChannel(Plugin plugin, String channel) { + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null"); + } + validateChannel(channel); + + removeFromOutgoing(plugin, channel); + } + + public void unregisterOutgoingPluginChannel(Plugin plugin) { + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null"); + } + + removeFromOutgoing(plugin); + } + + public PluginMessageListenerRegistration registerIncomingPluginChannel(Plugin plugin, String channel, PluginMessageListener listener) { + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null"); + } + validateChannel(channel); + if (isReservedChannel(channel)) { + throw new ReservedChannelException(channel); + } + if (listener == null) { + throw new IllegalArgumentException("Listener cannot be null"); + } + + PluginMessageListenerRegistration result = new PluginMessageListenerRegistration(this, plugin, channel, listener); + + addToIncoming(result); + + return result; + } + + public void unregisterIncomingPluginChannel(Plugin plugin, String channel, PluginMessageListener listener) { + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null"); + } + if (listener == null) { + throw new IllegalArgumentException("Listener cannot be null"); + } + validateChannel(channel); + + removeFromIncoming(new PluginMessageListenerRegistration(this, plugin, channel, listener)); + } + + public void unregisterIncomingPluginChannel(Plugin plugin, String channel) { + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null"); + } + validateChannel(channel); + + removeFromIncoming(plugin, channel); + } + + public void unregisterIncomingPluginChannel(Plugin plugin) { + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null"); + } + + removeFromIncoming(plugin); + } + + public Set getOutgoingChannels() { + synchronized (outgoingLock) { + Set keys = outgoingByChannel.keySet(); + return ImmutableSet.copyOf(keys); + } + } + + public Set getOutgoingChannels(Plugin plugin) { + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null"); + } + + synchronized (outgoingLock) { + Set channels = outgoingByPlugin.get(plugin); + + if (channels != null) { + return ImmutableSet.copyOf(channels); + } else { + return ImmutableSet.of(); + } + } + } + + public Set getIncomingChannels() { + synchronized (incomingLock) { + Set keys = incomingByChannel.keySet(); + return ImmutableSet.copyOf(keys); + } + } + + public Set getIncomingChannels(Plugin plugin) { + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null"); + } + + synchronized (incomingLock) { + Set registrations = incomingByPlugin.get(plugin); + + if (registrations != null) { + Builder builder = ImmutableSet.builder(); + + for (PluginMessageListenerRegistration registration : registrations) { + builder.add(registration.getChannel()); + } + + return builder.build(); + } else { + return ImmutableSet.of(); + } + } + } + + public Set getIncomingChannelRegistrations(Plugin plugin) { + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null"); + } + + synchronized (incomingLock) { + Set registrations = incomingByPlugin.get(plugin); + + if (registrations != null) { + return ImmutableSet.copyOf(registrations); + } else { + return ImmutableSet.of(); + } + } + } + + public Set getIncomingChannelRegistrations(String channel) { + validateChannel(channel); + + synchronized (incomingLock) { + Set registrations = incomingByChannel.get(channel); + + if (registrations != null) { + return ImmutableSet.copyOf(registrations); + } else { + return ImmutableSet.of(); + } + } + } + + public Set getIncomingChannelRegistrations(Plugin plugin, String channel) { + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null"); + } + validateChannel(channel); + + synchronized (incomingLock) { + Set registrations = incomingByPlugin.get(plugin); + + if (registrations != null) { + Builder builder = ImmutableSet.builder(); + + for (PluginMessageListenerRegistration registration : registrations) { + if (registration.getChannel().equals(channel)) { + builder.add(registration); + } + } + + return builder.build(); + } else { + return ImmutableSet.of(); + } + } + } + + public boolean isRegistrationValid(PluginMessageListenerRegistration registration) { + if (registration == null) { + throw new IllegalArgumentException("Registration cannot be null"); + } + + synchronized (incomingLock) { + Set registrations = incomingByPlugin.get(registration.getPlugin()); + + if (registrations != null) { + return registrations.contains(registration); + } + + return false; + } + } + + public boolean isIncomingChannelRegistered(Plugin plugin, String channel) { + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null"); + } + validateChannel(channel); + + synchronized (incomingLock) { + Set registrations = incomingByPlugin.get(plugin); + + if (registrations != null) { + for (PluginMessageListenerRegistration registration : registrations) { + if (registration.getChannel().equals(channel)) { + return true; + } + } + } + + return false; + } + } + + public boolean isOutgoingChannelRegistered(Plugin plugin, String channel) { + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null"); + } + validateChannel(channel); + + synchronized (outgoingLock) { + Set channels = outgoingByPlugin.get(plugin); + + if (channels != null) { + return channels.contains(channel); + } + + return false; + } + } + + public void dispatchIncomingMessage(Player source, String channel, byte[] message) { + if (source == null) { + throw new IllegalArgumentException("Player source cannot be null"); + } + if (message == null) { + throw new IllegalArgumentException("Message cannot be null"); + } + validateChannel(channel); + + Set registrations = getIncomingChannelRegistrations(channel); + + for (PluginMessageListenerRegistration registration : registrations) { + // Spigot Start + try + { + registration.getListener().onPluginMessageReceived( channel, source, message ); + } catch ( Throwable t ) + { + org.bukkit.Bukkit.getLogger().log( java.util.logging.Level.WARNING, "Could not pass incoming plugin message to " + registration.getPlugin(), t ); + } + // Spigot End + } + } + + /** + * Validates a Plugin Channel name. + * + * @param channel Channel name to validate. + */ + public static void validateChannel(String channel) { + if (channel == null) { + throw new IllegalArgumentException("Channel cannot be null"); + } + if (channel.length() > Messenger.MAX_CHANNEL_SIZE) { + throw new ChannelNameTooLongException(channel); + } + } + + /** + * Validates the input of a Plugin Message, ensuring the arguments are all + * valid. + * + * @param messenger Messenger to use for validation. + * @param source Source plugin of the Message. + * @param channel Plugin Channel to send the message by. + * @param message Raw message payload to send. + * @throws IllegalArgumentException Thrown if the source plugin is + * disabled. + * @throws IllegalArgumentException Thrown if source, channel or message + * is null. + * @throws MessageTooLargeException Thrown if the message is too big. + * @throws ChannelNameTooLongException Thrown if the channel name is too + * long. + * @throws ChannelNotRegisteredException Thrown if the channel is not + * registered for this plugin. + */ + public static void validatePluginMessage(Messenger messenger, Plugin source, String channel, byte[] message) { + if (messenger == null) { + throw new IllegalArgumentException("Messenger cannot be null"); + } + if (source == null) { + throw new IllegalArgumentException("Plugin source cannot be null"); + } + if (!source.isEnabled()) { + throw new IllegalArgumentException("Plugin must be enabled to send messages"); + } + if (message == null) { + throw new IllegalArgumentException("Message cannot be null"); + } + if (!messenger.isOutgoingChannelRegistered(source, channel)) { + throw new ChannelNotRegisteredException(channel); + } + if (message.length > Messenger.MAX_MESSAGE_SIZE) { + throw new MessageTooLargeException(message); + } + validateChannel(channel); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/potion/Potion.java b/azurite-api/src/main/java/org/bukkit/potion/Potion.java new file mode 100644 index 0000000..28d82e9 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/potion/Potion.java @@ -0,0 +1,450 @@ +package org.bukkit.potion; + +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang.Validate; +import org.bukkit.Material; +import org.bukkit.entity.LivingEntity; +import org.bukkit.inventory.ItemStack; + +import java.util.Collection; + +/** + * Represents a minecraft potion + */ +public class Potion { + private boolean extended = false; + private boolean splash = false; + private int level = 1; + private int name = -1; + private PotionType type; + + /** + * Construct a new potion of the given type. Unless the type is {@link + * PotionType#WATER}, it will be level one, without extended duration. + * Don't use this constructor to create a no-effect potion other than + * water bottle. + * + * @param type The potion type + * @see #Potion(int) + */ + public Potion(PotionType type) { + this.type = type; + if (type != null) { + this.name = type.getDamageValue(); + } + if (type == null || type == PotionType.WATER) { + this.level = 0; + } + } + + /** + * @param type the type of the potion + * @param tier the tier of the potion + * @deprecated In favour of {@link #Potion(PotionType, int)} + */ + @Deprecated + public Potion(PotionType type, Tier tier) { + this(type, tier == Tier.TWO ? 2 : 1); + Validate.notNull(type, "Type cannot be null"); + } + + /** + * @param type the type of the potion + * @param tier the tier of the potion + * @param splash whether the potion is a splash potion + * @deprecated In favour of {@link #Potion(PotionType, int, boolean)} + */ + @Deprecated + public Potion(PotionType type, Tier tier, boolean splash) { + this(type, tier == Tier.TWO ? 2 : 1, splash); + } + + /** + * @param type the type of the potion + * @param tier the tier of the potion + * @param splash whether the potion is a splash potion + * @param extended whether the potion has an extended duration + * @deprecated In favour of {@link #Potion(PotionType, int, boolean, + * boolean)} + */ + @Deprecated + public Potion(PotionType type, Tier tier, boolean splash, boolean extended) { + this(type, tier, splash); + this.extended = extended; + } + + /** + * Create a new potion of the given type and level. + * + * @param type The type of potion. + * @param level The potion's level. + */ + public Potion(PotionType type, int level) { + this(type); + Validate.notNull(type, "Type cannot be null"); + Validate.isTrue(type != PotionType.WATER, "Water bottles don't have a level!"); + Validate.isTrue(level > 0 && level < 3, "Level must be 1 or 2"); + this.level = level; + } + + /** + * Create a new potion of the given type and level. + * + * @param type The type of potion. + * @param level The potion's level. + * @param splash Whether it is a splash potion. + * @deprecated In favour of using {@link #Potion(PotionType)} with {@link + * #splash()}. + */ + @Deprecated + public Potion(PotionType type, int level, boolean splash) { + this(type, level); + this.splash = splash; + } + + /** + * Create a new potion of the given type and level. + * + * @param type The type of potion. + * @param level The potion's level. + * @param splash Whether it is a splash potion. + * @param extended Whether it has an extended duration. + * @deprecated In favour of using {@link #Potion(PotionType)} with {@link + * #extend()} and possibly {@link #splash()}. + */ + @Deprecated + public Potion(PotionType type, int level, boolean splash, boolean extended) { + this(type, level, splash); + this.extended = extended; + } + + /** + * Create a potion with a specific name. + * + * @param name The name index (0-63) + */ + public Potion(int name) { + this(PotionType.getByDamageValue(name & POTION_BIT)); + this.name = name & NAME_BIT; + if ((name & POTION_BIT) == 0) { + // If it's 0 it would've become PotionType.WATER, but it should actually be mundane potion + this.type = null; + } + } + + /** + * Chain this to the constructor to make the potion a splash potion. + * + * @return The potion. + */ + public Potion splash() { + setSplash(true); + return this; + } + + /** + * Chain this to the constructor to extend the potion's duration. + * + * @return The potion. + */ + public Potion extend() { + setHasExtendedDuration(true); + return this; + } + + /** + * Applies the effects of this potion to the given {@link ItemStack}. The + * ItemStack must be a potion. + * + * @param to The itemstack to apply to + */ + public void apply(ItemStack to) { + Validate.notNull(to, "itemstack cannot be null"); + Validate.isTrue(to.getType() == Material.POTION, "given itemstack is not a potion"); + to.setDurability(toDamageValue()); + } + + /** + * Applies the effects that would be applied by this potion to the given + * {@link LivingEntity}. + * + * @see LivingEntity#addPotionEffects(Collection) + * @param to The entity to apply the effects to + */ + public void apply(LivingEntity to) { + Validate.notNull(to, "entity cannot be null"); + to.addPotionEffects(getEffects()); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null || getClass() != obj.getClass()) { + return false; + } + Potion other = (Potion) obj; + return extended == other.extended && splash == other.splash && level == other.level && type == other.type; + } + + /** + * Returns a collection of {@link PotionEffect}s that this {@link Potion} + * would confer upon a {@link LivingEntity}. + * + * @see PotionBrewer#getEffectsFromDamage(int) + * @see Potion#toDamageValue() + * @return The effects that this potion applies + */ + public Collection getEffects() { + if (type == null) return ImmutableList.of(); + return getBrewer().getEffectsFromDamage(toDamageValue()); + } + + /** + * Returns the level of this potion. + * + * @return The level of this potion + */ + public int getLevel() { + return level; + } + + /** + * Returns the {@link Tier} of this potion. + * + * @return The tier of this potion + */ + @Deprecated + public Tier getTier() { + return level == 2 ? Tier.TWO : Tier.ONE; + } + + /** + * Returns the {@link PotionType} of this potion. + * + * @return The type of this potion + */ + public PotionType getType() { + return type; + } + + /** + * Returns whether this potion has an extended duration. + * + * @return Whether this potion has extended duration + */ + public boolean hasExtendedDuration() { + return extended; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = prime + level; + result = prime * result + (extended ? 1231 : 1237); + result = prime * result + (splash ? 1231 : 1237); + result = prime * result + ((type == null) ? 0 : type.hashCode()); + return result; + } + + /** + * Returns whether this potion is a splash potion. + * + * @return Whether this is a splash potion + */ + public boolean isSplash() { + return splash; + } + + /** + * Set whether this potion has extended duration. This will cause the + * potion to have roughly 8/3 more duration than a regular potion. + * + * @param isExtended Whether the potion should have extended duration + */ + public void setHasExtendedDuration(boolean isExtended) { + Validate.isTrue(type == null || !type.isInstant(), "Instant potions cannot be extended"); + extended = isExtended; + } + + /** + * Sets whether this potion is a splash potion. Splash potions can be + * thrown for a radius effect. + * + * @param isSplash Whether this is a splash potion + */ + public void setSplash(boolean isSplash) { + splash = isSplash; + } + + /** + * Sets the {@link Tier} of this potion. + * + * @param tier The new tier of this potion + * @deprecated In favour of {@link #setLevel(int)} + */ + @Deprecated + public void setTier(Tier tier) { + Validate.notNull(tier, "tier cannot be null"); + this.level = (tier == Tier.TWO ? 2 : 1); + } + + /** + * Sets the {@link PotionType} of this potion. + * + * @param type The new type of this potion + */ + public void setType(PotionType type) { + this.type = type; + } + + /** + * Sets the level of this potion. + * + * @param level The new level of this potion + */ + public void setLevel(int level) { + Validate.notNull(this.type, "No-effect potions don't have a level."); + int max = type.getMaxLevel(); + Validate.isTrue(level > 0 && level <= max, "Level must be " + (max == 1 ? "" : "between 1 and ") + max + " for this potion"); + this.level = level; + } + + /** + * Converts this potion to a valid potion damage short, usable for potion + * item stacks. + * + * @return The damage value of this potion + * @deprecated Magic value + */ + @Deprecated + public short toDamageValue() { + short damage; + if (type == PotionType.WATER) { + return 0; + } else if (type == null) { + // Without this, mundanePotion.toDamageValue() would return 0 + damage = (short) (name == 0 ? 8192 : name); + } else { + damage = (short) (level - 1); + damage <<= TIER_SHIFT; + damage |= (short) type.getDamageValue(); + } + if (splash) { + damage |= SPLASH_BIT; + } + if (extended) { + damage |= EXTENDED_BIT; + } + return damage; + } + + /** + * Converts this potion to an {@link ItemStack} with the specified amount + * and a correct damage value. + * + * @param amount The amount of the ItemStack + * @return The created ItemStack + */ + public ItemStack toItemStack(int amount) { + return new ItemStack(Material.POTION, amount, toDamageValue()); + } + + @Deprecated + public enum Tier { + ONE(0), + TWO(0x20); + + private int damageBit; + + Tier(int bit) { + damageBit = bit; + } + + public int getDamageBit() { + return damageBit; + } + + public static Tier getByDamageBit(int damageBit) { + for (Tier tier : Tier.values()) { + if (tier.damageBit == damageBit) + return tier; + } + return null; + } + } + + private static PotionBrewer brewer; + + private static final int EXTENDED_BIT = 0x40; + private static final int POTION_BIT = 0xF; + private static final int SPLASH_BIT = 0x4000; + private static final int TIER_BIT = 0x20; + private static final int TIER_SHIFT = 5; + private static final int NAME_BIT = 0x3F; + + /** + * + * @param damage the damage value + * @return the produced potion + * @deprecated Magic value + */ + @Deprecated + public static Potion fromDamage(int damage) { + PotionType type = PotionType.getByDamageValue(damage & POTION_BIT); + Potion potion; + if (type == null || type == PotionType.WATER) { + potion = new Potion(damage & NAME_BIT); + } else { + int level = (damage & TIER_BIT) >> TIER_SHIFT; + level++; + potion = new Potion(type, level); + } + if ((damage & SPLASH_BIT) > 0) { + potion = potion.splash(); + } + if ((type == null || !type.isInstant()) && (damage & EXTENDED_BIT) > 0) { + potion = potion.extend(); + } + return potion; + } + + public static Potion fromItemStack(ItemStack item) { + Validate.notNull(item, "item cannot be null"); + if (item.getType() != Material.POTION) + throw new IllegalArgumentException("item is not a potion"); + return fromDamage(item.getDurability()); + } + + /** + * Returns an instance of {@link PotionBrewer}. + * + * @return An instance of PotionBrewer + */ + public static PotionBrewer getBrewer() { + return brewer; + } + + /** + * Sets the current instance of {@link PotionBrewer}. Generally not to be + * used from within a plugin. + * + * @param other The new PotionBrewer + */ + public static void setPotionBrewer(PotionBrewer other) { + if (brewer != null) + throw new IllegalArgumentException("brewer can only be set internally"); + brewer = other; + } + + /** + * + * @return the name id + * @deprecated Magic value + */ + @Deprecated + public int getNameId() { + return name; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/potion/PotionBrewer.java b/azurite-api/src/main/java/org/bukkit/potion/PotionBrewer.java new file mode 100644 index 0000000..681b779 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/potion/PotionBrewer.java @@ -0,0 +1,31 @@ +package org.bukkit.potion; + +import java.util.Collection; + +/** + * Represents a brewer that can create {@link PotionEffect}s. + */ +public interface PotionBrewer { + + /** + * Creates a {@link PotionEffect} from the given {@link PotionEffectType}, + * applying duration modifiers and checks. + * + * @param potion The type of potion + * @param duration The duration in ticks + * @param amplifier The amplifier of the effect + * @return The resulting potion effect + */ + PotionEffect createEffect(PotionEffectType potion, int duration, int amplifier); + + /** + * Returns a collection of {@link PotionEffect} that would be applied from + * a potion with the given data value. + * + * @param damage The data value of the potion + * @return The list of effects + * @deprecated Magic value + */ + @Deprecated + Collection getEffectsFromDamage(int damage); +} diff --git a/azurite-api/src/main/java/org/bukkit/potion/PotionEffect.java b/azurite-api/src/main/java/org/bukkit/potion/PotionEffect.java new file mode 100644 index 0000000..34635b8 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/potion/PotionEffect.java @@ -0,0 +1,203 @@ +package org.bukkit.potion; + +import com.google.common.collect.ImmutableMap; +import org.apache.commons.lang.Validate; +import org.bukkit.configuration.serialization.ConfigurationSerializable; +import org.bukkit.configuration.serialization.SerializableAs; +import org.bukkit.entity.LivingEntity; + +import java.util.Map; +import java.util.NoSuchElementException; + +/** + * Represents a potion effect, that can be added to a {@link LivingEntity}. A + * potion effect has a duration that it will last for, an amplifier that will + * enhance its effects, and a {@link PotionEffectType}, that represents its + * effect on an entity. + */ +@SerializableAs("PotionEffect") +public class PotionEffect implements ConfigurationSerializable { + private static final String AMPLIFIER = "amplifier"; + private static final String DURATION = "duration"; + private static final String TYPE = "effect"; + private static final String AMBIENT = "ambient"; + private static final String PARTICLES = "has-particles"; + private final int amplifier; + private final int duration; + private final PotionEffectType type; + private final boolean ambient; + private final boolean particles; + + /** + * Creates a potion effect. + * @param type effect type + * @param duration measured in ticks, see {@link + * PotionEffect#getDuration()} + * @param amplifier the amplifier, see {@link PotionEffect#getAmplifier()} + * @param ambient the ambient status, see {@link PotionEffect#isAmbient()} + * @param particles the particle status, see {@link PotionEffect#hasParticles()} + */ + public PotionEffect(PotionEffectType type, int duration, int amplifier, boolean ambient, boolean particles){ + Validate.notNull(type, "effect type cannot be null"); + this.type = type; + this.duration = duration; + this.amplifier = amplifier; + this.ambient = ambient; + this.particles = particles; + } + + /** + * Creates a potion effect. Assumes that particles are visible + * + * @param type effect type + * @param duration measured in ticks, see {@link + * PotionEffect#getDuration()} + * @param amplifier the amplifier, see {@link PotionEffect#getAmplifier()} + * @param ambient the ambient status, see {@link PotionEffect#isAmbient()} + */ + public PotionEffect(PotionEffectType type, int duration, int amplifier, boolean ambient) { + this(type, duration, amplifier, ambient, true); + } + + /** + * Creates a potion effect. Assumes ambient is true. + * + * @param type Effect type + * @param duration measured in ticks + * @param amplifier the amplifier for the effect + * @see PotionEffect#PotionEffect(PotionEffectType, int, int, boolean) + */ + public PotionEffect(PotionEffectType type, int duration, int amplifier) { + this(type, duration, amplifier, true); + } + + /** + * Constructor for deserialization. + * + * @param map the map to deserialize from + */ + public PotionEffect(Map map) { + this(getEffectType(map), getInt(map, DURATION), getInt(map, AMPLIFIER), getBool(map, AMBIENT, false), getBool(map, PARTICLES, true)); + } + + private static PotionEffectType getEffectType(Map map) { + int type = getInt(map, TYPE); + PotionEffectType effect = PotionEffectType.getById(type); + if (effect != null) { + return effect; + } + throw new NoSuchElementException(map + " does not contain " + TYPE); + } + + private static int getInt(Map map, Object key) { + Object num = map.get(key); + if (num instanceof Integer) { + return (Integer) num; + } + throw new NoSuchElementException(map + " does not contain " + key); + } + + private static boolean getBool(Map map, Object key, boolean def) { + Object bool = map.get(key); + if (bool instanceof Boolean) { + return (Boolean) bool; + } + return def; + } + + public Map serialize() { + return ImmutableMap.of( + TYPE, type.getId(), + DURATION, duration, + AMPLIFIER, amplifier, + AMBIENT, ambient, + PARTICLES, particles + ); + } + + /** + * Attempts to add the effect represented by this object to the given + * {@link LivingEntity}. + * + * @see LivingEntity#addPotionEffect(PotionEffect) + * @param entity The entity to add this effect to + * @return Whether the effect could be added + */ + public boolean apply(LivingEntity entity) { + return entity.addPotionEffect(this); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (!(obj instanceof PotionEffect)) { + return false; + } + PotionEffect that = (PotionEffect) obj; + return this.type.equals(that.type) && this.ambient == that.ambient && this.amplifier == that.amplifier && this.duration == that.duration && this.particles == that.particles; + } + + /** + * Returns the amplifier of this effect. A higher amplifier means the + * potion effect happens more often over its duration and in some cases + * has more effect on its target. + * + * @return The effect amplifier + */ + public int getAmplifier() { + return amplifier; + } + + /** + * Returns the duration (in ticks) that this effect will run for when + * applied to a {@link LivingEntity}. + * + * @return The duration of the effect + */ + public int getDuration() { + return duration; + } + + /** + * Returns the {@link PotionEffectType} of this effect. + * + * @return The potion type of this effect + */ + public PotionEffectType getType() { + return type; + } + + /** + * Makes potion effect produce more, translucent, particles. + * + * @return if this effect is ambient + */ + public boolean isAmbient() { + return ambient; + } + + /** + * @return whether this effect has particles or not + */ + public boolean hasParticles(){ + return particles; + } + + @Override + public int hashCode() { + int hash = 1; + hash = hash * 31 + type.hashCode(); + hash = hash * 31 + amplifier; + hash = hash * 31 + duration; + hash ^= 0x22222222 >> (ambient ? 1 : -1); + hash ^= 0x22222222 >> (particles ? 1 : -1); + return hash; + } + + @Override + public String toString() { + return type.getName() + (ambient ? ":(" : ":") + duration + "t-x" + amplifier + (ambient ? ")" : ""); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/potion/PotionEffectType.java b/azurite-api/src/main/java/org/bukkit/potion/PotionEffectType.java new file mode 100644 index 0000000..e182154 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/potion/PotionEffectType.java @@ -0,0 +1,269 @@ +package org.bukkit.potion; + +import org.apache.commons.lang.Validate; + +import java.util.HashMap; +import java.util.Map; + +/** + * Represents a type of potion and its effect on an entity. + */ +public abstract class PotionEffectType { + /** + * Increases movement speed. + */ + public static final PotionEffectType SPEED = new PotionEffectTypeWrapper(1); + + /** + * Decreases movement speed. + */ + public static final PotionEffectType SLOW = new PotionEffectTypeWrapper(2); + + /** + * Increases dig speed. + */ + public static final PotionEffectType FAST_DIGGING = new PotionEffectTypeWrapper(3); + + /** + * Decreases dig speed. + */ + public static final PotionEffectType SLOW_DIGGING = new PotionEffectTypeWrapper(4); + + /** + * Increases damage dealt. + */ + public static final PotionEffectType INCREASE_DAMAGE = new PotionEffectTypeWrapper(5); + + /** + * Heals an entity. + */ + public static final PotionEffectType HEAL = new PotionEffectTypeWrapper(6); + + /** + * Hurts an entity. + */ + public static final PotionEffectType HARM = new PotionEffectTypeWrapper(7); + + /** + * Increases jump height. + */ + public static final PotionEffectType JUMP = new PotionEffectTypeWrapper(8); + + /** + * Warps vision on the client. + */ + public static final PotionEffectType CONFUSION = new PotionEffectTypeWrapper(9); + + /** + * Regenerates health. + */ + public static final PotionEffectType REGENERATION = new PotionEffectTypeWrapper(10); + + /** + * Decreases damage dealt to an entity. + */ + public static final PotionEffectType DAMAGE_RESISTANCE = new PotionEffectTypeWrapper(11); + + /** + * Stops fire damage. + */ + public static final PotionEffectType FIRE_RESISTANCE = new PotionEffectTypeWrapper(12); + + /** + * Allows breathing underwater. + */ + public static final PotionEffectType WATER_BREATHING = new PotionEffectTypeWrapper(13); + + /** + * Grants invisibility. + */ + public static final PotionEffectType INVISIBILITY = new PotionEffectTypeWrapper(14); + + /** + * Blinds an entity. + */ + public static final PotionEffectType BLINDNESS = new PotionEffectTypeWrapper(15); + + /** + * Allows an entity to see in the dark. + */ + public static final PotionEffectType NIGHT_VISION = new PotionEffectTypeWrapper(16); + + /** + * Increases hunger. + */ + public static final PotionEffectType HUNGER = new PotionEffectTypeWrapper(17); + + /** + * Decreases damage dealt by an entity. + */ + public static final PotionEffectType WEAKNESS = new PotionEffectTypeWrapper(18); + + /** + * Deals damage to an entity over time. + */ + public static final PotionEffectType POISON = new PotionEffectTypeWrapper(19); + + /** + * Deals damage to an entity over time and gives the health to the + * shooter. + */ + public static final PotionEffectType WITHER = new PotionEffectTypeWrapper(20); + + /** + * Increases the maximum health of an entity. + */ + public static final PotionEffectType HEALTH_BOOST = new PotionEffectTypeWrapper(21); + + /** + * Increases the maximum health of an entity with health that cannot be + * regenerated, but is refilled every 30 seconds. + */ + public static final PotionEffectType ABSORPTION = new PotionEffectTypeWrapper(22); + + /** + * Increases the food level of an entity each tick. + */ + public static final PotionEffectType SATURATION = new PotionEffectTypeWrapper(23); + + private final int id; + + protected PotionEffectType(int id) { + this.id = id; + } + + /** + * Creates a PotionEffect from this PotionEffectType, applying duration + * modifiers and checks. + * + * @see PotionBrewer#createEffect(PotionEffectType, int, int) + * @param duration time in ticks + * @param amplifier the effect's amplifier + * @return a resulting potion effect + */ + public PotionEffect createEffect(int duration, int amplifier) { + return Potion.getBrewer().createEffect(this, duration, amplifier); + } + + /** + * Returns the duration modifier applied to effects of this type. + * + * @return duration modifier + */ + public abstract double getDurationModifier(); + + /** + * Returns the unique ID of this type. + * + * @return Unique ID + * @deprecated Magic value + */ + @Deprecated + public int getId() { + return id; + } + + /** + * Returns the name of this effect type. + * + * @return The name of this effect type + */ + public abstract String getName(); + + /** + * Returns whether the effect of this type happens once, immediately. + * + * @return whether this type is normally instant + */ + public abstract boolean isInstant(); + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (!(obj instanceof PotionEffectType)) { + return false; + } + final PotionEffectType other = (PotionEffectType) obj; + if (this.id != other.id) { + return false; + } + return true; + } + + @Override + public int hashCode() { + return id; + } + + @Override + public String toString() { + return "PotionEffectType[" + id + ", " + getName() + "]"; + } + + private static final PotionEffectType[] byId = new PotionEffectType[24]; + private static final Map byName = new HashMap(); + // will break on updates. + private static boolean acceptingNew = true; + + /** + * Gets the effect type specified by the unique id. + * + * @param id Unique ID to fetch + * @return Resulting type, or null if not found. + * @deprecated Magic value + */ + @Deprecated + public static PotionEffectType getById(int id) { + if (id >= byId.length || id < 0) + return null; + return byId[id]; + } + + /** + * Gets the effect type specified by the given name. + * + * @param name Name of PotionEffectType to fetch + * @return Resulting PotionEffectType, or null if not found. + */ + public static PotionEffectType getByName(String name) { + Validate.notNull(name, "name cannot be null"); + return byName.get(name.toLowerCase()); + } + + /** + * Registers an effect type with the given object. + *

+ * Generally not to be used from within a plugin. + * + * @param type PotionType to register + */ + public static void registerPotionEffectType(PotionEffectType type) { + if (byId[type.id] != null || byName.containsKey(type.getName().toLowerCase())) { + throw new IllegalArgumentException("Cannot set already-set type"); + } else if (!acceptingNew) { + throw new IllegalStateException( + "No longer accepting new potion effect types (can only be done by the server implementation)"); + } + + byId[type.id] = type; + byName.put(type.getName().toLowerCase(), type); + } + + /** + * Stops accepting any effect type registrations. + */ + public static void stopAcceptingRegistrations() { + acceptingNew = false; + } + + /** + * Returns an array of all the registered {@link PotionEffectType}s. + * + * @return Array of types. + */ + public static PotionEffectType[] values() { + return byId.clone(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/potion/PotionEffectTypeWrapper.java b/azurite-api/src/main/java/org/bukkit/potion/PotionEffectTypeWrapper.java new file mode 100644 index 0000000..5db1ce8 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/potion/PotionEffectTypeWrapper.java @@ -0,0 +1,31 @@ +package org.bukkit.potion; + +public class PotionEffectTypeWrapper extends PotionEffectType { + protected PotionEffectTypeWrapper(int id) { + super(id); + } + + @Override + public double getDurationModifier() { + return getType().getDurationModifier(); + } + + @Override + public String getName() { + return getType().getName(); + } + + /** + * Get the potion type bound to this wrapper. + * + * @return The potion effect type + */ + public PotionEffectType getType() { + return PotionEffectType.getById(getId()); + } + + @Override + public boolean isInstant() { + return getType().isInstant(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/potion/PotionType.java b/azurite-api/src/main/java/org/bukkit/potion/PotionType.java new file mode 100644 index 0000000..6ad9a91 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/potion/PotionType.java @@ -0,0 +1,75 @@ +package org.bukkit.potion; + +public enum PotionType { + WATER(0, null, 0), + REGEN(1, PotionEffectType.REGENERATION, 2), + SPEED(2, PotionEffectType.SPEED, 2), + FIRE_RESISTANCE(3, PotionEffectType.FIRE_RESISTANCE, 1), + POISON(4, PotionEffectType.POISON, 2), + INSTANT_HEAL(5, PotionEffectType.HEAL, 2), + NIGHT_VISION(6, PotionEffectType.NIGHT_VISION, 1), + WEAKNESS(8, PotionEffectType.WEAKNESS, 1), + STRENGTH(9, PotionEffectType.INCREASE_DAMAGE, 2), + SLOWNESS(10, PotionEffectType.SLOW, 1), + JUMP(11, PotionEffectType.JUMP, 2), + INSTANT_DAMAGE(12, PotionEffectType.HARM, 2), + WATER_BREATHING(13, PotionEffectType.WATER_BREATHING, 1), + INVISIBILITY(14, PotionEffectType.INVISIBILITY, 1), + ; + + private final int damageValue, maxLevel; + private final PotionEffectType effect; + + PotionType(int damageValue, PotionEffectType effect, int maxLevel) { + this.damageValue = damageValue; + this.effect = effect; + this.maxLevel = maxLevel; + } + + public PotionEffectType getEffectType() { + return effect; + } + + /** + * + * @return the damage value + * @deprecated Magic value + */ + @Deprecated + public int getDamageValue() { + return damageValue; + } + + public int getMaxLevel() { + return maxLevel; + } + + public boolean isInstant() { + return effect == null ? true : effect.isInstant(); + } + + /** + * + * @param damage the damage value + * @return the matching potion type or null + * @deprecated Magic value + */ + @Deprecated + public static PotionType getByDamageValue(int damage) { + for (PotionType type : PotionType.values()) { + if (type.damageValue == damage) + return type; + } + return null; + } + + public static PotionType getByEffect(PotionEffectType effectType) { + if (effectType == null) + return WATER; + for (PotionType type : PotionType.values()) { + if (effectType.equals(type.effect)) + return type; + } + return null; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/projectiles/BlockProjectileSource.java b/azurite-api/src/main/java/org/bukkit/projectiles/BlockProjectileSource.java new file mode 100644 index 0000000..8381336 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/projectiles/BlockProjectileSource.java @@ -0,0 +1,13 @@ +package org.bukkit.projectiles; + +import org.bukkit.block.Block; + +public interface BlockProjectileSource extends ProjectileSource { + + /** + * Gets the block this projectile source belongs to. + * + * @return Block for the projectile source + */ + Block getBlock(); +} diff --git a/azurite-api/src/main/java/org/bukkit/projectiles/ProjectileSource.java b/azurite-api/src/main/java/org/bukkit/projectiles/ProjectileSource.java new file mode 100644 index 0000000..b52c02a --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/projectiles/ProjectileSource.java @@ -0,0 +1,30 @@ +package org.bukkit.projectiles; + +import org.bukkit.entity.Projectile; +import org.bukkit.util.Vector; + +/** + * Represents a valid source of a projectile. + */ +public interface ProjectileSource { + + /** + * Launches a {@link Projectile} from the ProjectileSource. + * + * @param a projectile subclass + * @param projectile class of the projectile to launch + * @return the launched projectile + */ + T launchProjectile(Class projectile); + + /** + * Launches a {@link Projectile} from the ProjectileSource with an + * initial velocity. + * + * @param a projectile subclass + * @param projectile class of the projectile to launch + * @param velocity the velocity with which to launch + * @return the launched projectile + */ + T launchProjectile(Class projectile, Vector velocity); +} diff --git a/azurite-api/src/main/java/org/bukkit/scheduler/BukkitRunnable.java b/azurite-api/src/main/java/org/bukkit/scheduler/BukkitRunnable.java new file mode 100644 index 0000000..c146ec7 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/scheduler/BukkitRunnable.java @@ -0,0 +1,149 @@ +package org.bukkit.scheduler; + +import org.bukkit.Bukkit; +import org.bukkit.plugin.Plugin; + +/** + * This class is provided as an easy way to handle scheduling tasks. + */ +public abstract class BukkitRunnable implements Runnable { + private int taskId = -1; + + /** + * Attempts to cancel this task. + * + * @throws IllegalStateException if task was not scheduled yet + */ + public synchronized void cancel() throws IllegalStateException { + Bukkit.getScheduler().cancelTask(getTaskId()); + } + + /** + * Schedules this in the Bukkit scheduler to run on next tick. + * + * @param plugin the reference to the plugin scheduling task + * @return a BukkitTask that contains the id number + * @throws IllegalArgumentException if plugin is null + * @throws IllegalStateException if this was already scheduled + * @see BukkitScheduler#runTask(Plugin, Runnable) + */ + public synchronized BukkitTask runTask(Plugin plugin) throws IllegalArgumentException, IllegalStateException { + checkState(); + return setupId(Bukkit.getScheduler().runTask(plugin, (Runnable) this)); + } + + /** + * Asynchronous tasks should never access any API in Bukkit. Great care + * should be taken to assure the thread-safety of asynchronous tasks. + *

+ * Schedules this in the Bukkit scheduler to run asynchronously. + * + * @param plugin the reference to the plugin scheduling task + * @return a BukkitTask that contains the id number + * @throws IllegalArgumentException if plugin is null + * @throws IllegalStateException if this was already scheduled + * @see BukkitScheduler#runTaskAsynchronously(Plugin, Runnable) + */ + public synchronized BukkitTask runTaskAsynchronously(Plugin plugin) throws IllegalArgumentException, IllegalStateException { + checkState(); + return setupId(Bukkit.getScheduler().runTaskAsynchronously(plugin, (Runnable) this)); + } + + /** + * Schedules this to run after the specified number of server ticks. + * + * @param plugin the reference to the plugin scheduling task + * @param delay the ticks to wait before running the task + * @return a BukkitTask that contains the id number + * @throws IllegalArgumentException if plugin is null + * @throws IllegalStateException if this was already scheduled + * @see BukkitScheduler#runTaskLater(Plugin, Runnable, long) + */ + public synchronized BukkitTask runTaskLater(Plugin plugin, long delay) throws IllegalArgumentException, IllegalStateException { + checkState(); + return setupId(Bukkit.getScheduler().runTaskLater(plugin, (Runnable) this, delay)); + } + + /** + * Asynchronous tasks should never access any API in Bukkit. Great care + * should be taken to assure the thread-safety of asynchronous tasks. + *

+ * Schedules this to run asynchronously after the specified number of + * server ticks. + * + * @param plugin the reference to the plugin scheduling task + * @param delay the ticks to wait before running the task + * @return a BukkitTask that contains the id number + * @throws IllegalArgumentException if plugin is null + * @throws IllegalStateException if this was already scheduled + * @see BukkitScheduler#runTaskLaterAsynchronously(Plugin, Runnable, long) + */ + public synchronized BukkitTask runTaskLaterAsynchronously(Plugin plugin, long delay) throws IllegalArgumentException, IllegalStateException { + checkState(); + return setupId(Bukkit.getScheduler().runTaskLaterAsynchronously(plugin, (Runnable) this, delay)); + } + + /** + * Schedules this to repeatedly run until cancelled, starting after the + * specified number of server ticks. + * + * @param plugin the reference to the plugin scheduling task + * @param delay the ticks to wait before running the task + * @param period the ticks to wait between runs + * @return a BukkitTask that contains the id number + * @throws IllegalArgumentException if plugin is null + * @throws IllegalStateException if this was already scheduled + * @see BukkitScheduler#runTaskTimer(Plugin, Runnable, long, long) + */ + public synchronized BukkitTask runTaskTimer(Plugin plugin, long delay, long period) throws IllegalArgumentException, IllegalStateException { + checkState(); + return setupId(Bukkit.getScheduler().runTaskTimer(plugin, (Runnable) this, delay, period)); + } + + /** + * Asynchronous tasks should never access any API in Bukkit. Great care + * should be taken to assure the thread-safety of asynchronous tasks. + *

+ * Schedules this to repeatedly run asynchronously until cancelled, + * starting after the specified number of server ticks. + * + * @param plugin the reference to the plugin scheduling task + * @param delay the ticks to wait before running the task for the first + * time + * @param period the ticks to wait between runs + * @return a BukkitTask that contains the id number + * @throws IllegalArgumentException if plugin is null + * @throws IllegalStateException if this was already scheduled + * @see BukkitScheduler#runTaskTimerAsynchronously(Plugin, Runnable, long, + * long) + */ + public synchronized BukkitTask runTaskTimerAsynchronously(Plugin plugin, long delay, long period) throws IllegalArgumentException, IllegalStateException { + checkState(); + return setupId(Bukkit.getScheduler().runTaskTimerAsynchronously(plugin, (Runnable) this, delay, period)); + } + + /** + * Gets the task id for this runnable. + * + * @return the task id that this runnable was scheduled as + * @throws IllegalStateException if task was not scheduled yet + */ + public synchronized int getTaskId() throws IllegalStateException { + final int id = taskId; + if (id == -1) { + throw new IllegalStateException("Not scheduled yet"); + } + return id; + } + + private void checkState() { + if (taskId != -1) { + throw new IllegalStateException("Already scheduled as " + taskId); + } + } + + private BukkitTask setupId(final BukkitTask task) { + this.taskId = task.getTaskId(); + return task; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/scheduler/BukkitScheduler.java b/azurite-api/src/main/java/org/bukkit/scheduler/BukkitScheduler.java new file mode 100644 index 0000000..d730855 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/scheduler/BukkitScheduler.java @@ -0,0 +1,370 @@ +package org.bukkit.scheduler; + +import org.bukkit.plugin.Plugin; + +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.Future; + +public interface BukkitScheduler { + + /** + * Schedules a once off task to occur after a delay. + *

+ * This task will be executed by the main server thread. + * + * @param plugin Plugin that owns the task + * @param task Task to be executed + * @param delay Delay in server ticks before executing task + * @return Task id number (-1 if scheduling failed) + */ + int scheduleSyncDelayedTask(Plugin plugin, Runnable task, long delay); + + /** + * @deprecated Use {@link BukkitRunnable#runTaskLater(Plugin, long)} + * @param plugin Plugin that owns the task + * @param task Task to be executed + * @param delay Delay in server ticks before executing task + * @return Task id number (-1 if scheduling failed) + */ + @Deprecated + int scheduleSyncDelayedTask(Plugin plugin, BukkitRunnable task, long delay); + + /** + * Schedules a once off task to occur as soon as possible. + *

+ * This task will be executed by the main server thread. + * + * @param plugin Plugin that owns the task + * @param task Task to be executed + * @return Task id number (-1 if scheduling failed) + */ + int scheduleSyncDelayedTask(Plugin plugin, Runnable task); + + /** + * @deprecated Use {@link BukkitRunnable#runTask(Plugin)} + * @param plugin Plugin that owns the task + * @param task Task to be executed + * @return Task id number (-1 if scheduling failed) + */ + @Deprecated + int scheduleSyncDelayedTask(Plugin plugin, BukkitRunnable task); + + /** + * Schedules a repeating task. + *

+ * This task will be executed by the main server thread. + * + * @param plugin Plugin that owns the task + * @param task Task to be executed + * @param delay Delay in server ticks before executing first repeat + * @param period Period in server ticks of the task + * @return Task id number (-1 if scheduling failed) + */ + int scheduleSyncRepeatingTask(Plugin plugin, Runnable task, long delay, long period); + + /** + * @deprecated Use {@link BukkitRunnable#runTaskTimer(Plugin, long, long)} * + * @param plugin Plugin that owns the task + * @param task Task to be executed + * @param delay Delay in server ticks before executing first repeat + * @param period Period in server ticks of the task + * @return Task id number (-1 if scheduling failed) + */ + @Deprecated + int scheduleSyncRepeatingTask(Plugin plugin, BukkitRunnable task, long delay, long period); + + /** + * Asynchronous tasks should never access any API in Bukkit. Great care + * should be taken to assure the thread-safety of asynchronous tasks. + *

+ * Schedules a once off task to occur after a delay. This task will be + * executed by a thread managed by the scheduler. + * + * @param plugin Plugin that owns the task + * @param task Task to be executed + * @param delay Delay in server ticks before executing task + * @return Task id number (-1 if scheduling failed) + * @deprecated This name is misleading, as it does not schedule "a sync" + * task, but rather, "an async" task + */ + @Deprecated + int scheduleAsyncDelayedTask(Plugin plugin, Runnable task, long delay); + + /** + * Asynchronous tasks should never access any API in Bukkit. Great care + * should be taken to assure the thread-safety of asynchronous tasks. + *

+ * Schedules a once off task to occur as soon as possible. This task will + * be executed by a thread managed by the scheduler. + * + * @param plugin Plugin that owns the task + * @param task Task to be executed + * @return Task id number (-1 if scheduling failed) + * @deprecated This name is misleading, as it does not schedule "a sync" + * task, but rather, "an async" task + */ + @Deprecated + int scheduleAsyncDelayedTask(Plugin plugin, Runnable task); + + /** + * Asynchronous tasks should never access any API in Bukkit. Great care + * should be taken to assure the thread-safety of asynchronous tasks. + *

+ * Schedules a repeating task. This task will be executed by a thread + * managed by the scheduler. + * + * @param plugin Plugin that owns the task + * @param task Task to be executed + * @param delay Delay in server ticks before executing first repeat + * @param period Period in server ticks of the task + * @return Task id number (-1 if scheduling failed) + * @deprecated This name is misleading, as it does not schedule "a sync" + * task, but rather, "an async" task + */ + @Deprecated + int scheduleAsyncRepeatingTask(Plugin plugin, Runnable task, long delay, long period); + + /** + * Calls a method on the main thread and returns a Future object. This + * task will be executed by the main server thread. + *

    + *
  • Note: The Future.get() methods must NOT be called from the main + * thread. + *
  • Note2: There is at least an average of 10ms latency until the + * isDone() method returns true. + *
+ * @param The callable's return type + * @param plugin Plugin that owns the task + * @param task Task to be executed + * @return Future Future object related to the task + */ + Future callSyncMethod(Plugin plugin, Callable task); + + /** + * Removes task from scheduler. + * + * @param taskId Id number of task to be removed + */ + void cancelTask(int taskId); + + /** + * Removes all tasks associated with a particular plugin from the + * scheduler. + * + * @param plugin Owner of tasks to be removed + */ + void cancelTasks(Plugin plugin); + + /** + * Removes all tasks from the scheduler. + */ + void cancelAllTasks(); + + /** + * Check if the task currently running. + *

+ * A repeating task might not be running currently, but will be running in + * the future. A task that has finished, and does not repeat, will not be + * running ever again. + *

+ * Explicitly, a task is running if there exists a thread for it, and that + * thread is alive. + * + * @param taskId The task to check. + *

+ * @return If the task is currently running. + */ + boolean isCurrentlyRunning(int taskId); + + /** + * Check if the task queued to be run later. + *

+ * If a repeating task is currently running, it might not be queued now + * but could be in the future. A task that is not queued, and not running, + * will not be queued again. + * + * @param taskId The task to check. + *

+ * @return If the task is queued to be run. + */ + boolean isQueued(int taskId); + + /** + * Returns a list of all active workers. + *

+ * This list contains asynch tasks that are being executed by separate + * threads. + * + * @return Active workers + */ + List getActiveWorkers(); + + /** + * Returns a list of all pending tasks. The ordering of the tasks is not + * related to their order of execution. + * + * @return Active workers + */ + List getPendingTasks(); + + /** + * Returns a task that will run on the next server tick. + * + * @param plugin the reference to the plugin scheduling task + * @param task the task to be run + * @return a BukkitTask that contains the id number + * @throws IllegalArgumentException if plugin is null + * @throws IllegalArgumentException if task is null + */ + BukkitTask runTask(Plugin plugin, Runnable task) throws IllegalArgumentException; + + /** + * @deprecated Use {@link BukkitRunnable#runTask(Plugin)} + * + * @param plugin the reference to the plugin scheduling task + * @param task the task to be run + * @return a BukkitTask that contains the id number + * @throws IllegalArgumentException if plugin is null + * @throws IllegalArgumentException if task is null + */ + @Deprecated + BukkitTask runTask(Plugin plugin, BukkitRunnable task) throws IllegalArgumentException; + + /** + * Asynchronous tasks should never access any API in Bukkit. Great care + * should be taken to assure the thread-safety of asynchronous tasks. + *

+ * Returns a task that will run asynchronously. + * + * @param plugin the reference to the plugin scheduling task + * @param task the task to be run + * @return a BukkitTask that contains the id number + * @throws IllegalArgumentException if plugin is null + * @throws IllegalArgumentException if task is null + */ + BukkitTask runTaskAsynchronously(Plugin plugin, Runnable task) throws IllegalArgumentException; + + /** + * @deprecated Use {@link BukkitRunnable#runTaskAsynchronously(Plugin)} + * @param plugin the reference to the plugin scheduling task + * @param task the task to be run + * @return a BukkitTask that contains the id number + * @throws IllegalArgumentException if plugin is null + * @throws IllegalArgumentException if task is null + */ + @Deprecated + BukkitTask runTaskAsynchronously(Plugin plugin, BukkitRunnable task) throws IllegalArgumentException; + + /** + * Returns a task that will run after the specified number of server + * ticks. + * + * @param plugin the reference to the plugin scheduling task + * @param task the task to be run + * @param delay the ticks to wait before running the task + * @return a BukkitTask that contains the id number + * @throws IllegalArgumentException if plugin is null + * @throws IllegalArgumentException if task is null + */ + BukkitTask runTaskLater(Plugin plugin, Runnable task, long delay) throws IllegalArgumentException; + + /** + * @deprecated Use {@link BukkitRunnable#runTaskLater(Plugin, long)} + * @param plugin the reference to the plugin scheduling task + * @param task the task to be run + * @param delay the ticks to wait before running the task + * @return a BukkitTask that contains the id number + * @throws IllegalArgumentException if plugin is null + * @throws IllegalArgumentException if task is null + */ + @Deprecated + BukkitTask runTaskLater(Plugin plugin, BukkitRunnable task, long delay) throws IllegalArgumentException; + + /** + * Asynchronous tasks should never access any API in Bukkit. Great care + * should be taken to assure the thread-safety of asynchronous tasks. + *

+ * Returns a task that will run asynchronously after the specified number + * of server ticks. + * + * @param plugin the reference to the plugin scheduling task + * @param task the task to be run + * @param delay the ticks to wait before running the task + * @return a BukkitTask that contains the id number + * @throws IllegalArgumentException if plugin is null + * @throws IllegalArgumentException if task is null + */ + BukkitTask runTaskLaterAsynchronously(Plugin plugin, Runnable task, long delay) throws IllegalArgumentException; + + /** + * @deprecated Use {@link BukkitRunnable#runTaskLaterAsynchronously(Plugin, long)} + * @param plugin the reference to the plugin scheduling task + * @param task the task to be run + * @param delay the ticks to wait before running the task + * @return a BukkitTask that contains the id number + * @throws IllegalArgumentException if plugin is null + * @throws IllegalArgumentException if task is null + */ + @Deprecated + BukkitTask runTaskLaterAsynchronously(Plugin plugin, BukkitRunnable task, long delay) throws IllegalArgumentException; + + /** + * Returns a task that will repeatedly run until cancelled, starting after + * the specified number of server ticks. + * + * @param plugin the reference to the plugin scheduling task + * @param task the task to be run + * @param delay the ticks to wait before running the task + * @param period the ticks to wait between runs + * @return a BukkitTask that contains the id number + * @throws IllegalArgumentException if plugin is null + * @throws IllegalArgumentException if task is null + */ + BukkitTask runTaskTimer(Plugin plugin, Runnable task, long delay, long period) throws IllegalArgumentException; + + /** + * @deprecated Use {@link BukkitRunnable#runTaskTimer(Plugin, long, long)} + * @param plugin the reference to the plugin scheduling task + * @param task the task to be run + * @param delay the ticks to wait before running the task + * @param period the ticks to wait between runs + * @return a BukkitTask that contains the id number + * @throws IllegalArgumentException if plugin is null + * @throws IllegalArgumentException if task is null + */ + @Deprecated + BukkitTask runTaskTimer(Plugin plugin, BukkitRunnable task, long delay, long period) throws IllegalArgumentException; + + /** + * Asynchronous tasks should never access any API in Bukkit. Great care + * should be taken to assure the thread-safety of asynchronous tasks. + *

+ * Returns a task that will repeatedly run asynchronously until cancelled, + * starting after the specified number of server ticks. + * + * @param plugin the reference to the plugin scheduling task + * @param task the task to be run + * @param delay the ticks to wait before running the task for the first + * time + * @param period the ticks to wait between runs + * @return a BukkitTask that contains the id number + * @throws IllegalArgumentException if plugin is null + * @throws IllegalArgumentException if task is null + */ + BukkitTask runTaskTimerAsynchronously(Plugin plugin, Runnable task, long delay, long period) throws IllegalArgumentException; + + /** + * @deprecated Use {@link BukkitRunnable#runTaskTimerAsynchronously(Plugin, long, long)} + * @param plugin the reference to the plugin scheduling task + * @param task the task to be run + * @param delay the ticks to wait before running the task for the first + * time + * @param period the ticks to wait between runs + * @return a BukkitTask that contains the id number + * @throws IllegalArgumentException if plugin is null + * @throws IllegalArgumentException if task is null + */ + @Deprecated + BukkitTask runTaskTimerAsynchronously(Plugin plugin, BukkitRunnable task, long delay, long period) throws IllegalArgumentException; +} diff --git a/azurite-api/src/main/java/org/bukkit/scheduler/BukkitTask.java b/azurite-api/src/main/java/org/bukkit/scheduler/BukkitTask.java new file mode 100644 index 0000000..dc9bf0e --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/scheduler/BukkitTask.java @@ -0,0 +1,35 @@ +package org.bukkit.scheduler; + +import org.bukkit.plugin.Plugin; + +/** + * Represents a task being executed by the scheduler + */ +public interface BukkitTask { + + /** + * Returns the taskId for the task. + * + * @return Task id number + */ + int getTaskId(); + + /** + * Returns the Plugin that owns this task. + * + * @return The Plugin that owns the task + */ + Plugin getOwner(); + + /** + * Returns true if the Task is a sync task. + * + * @return true if the task is run by main thread + */ + boolean isSync(); + + /** + * Will attempt to cancel this task. + */ + void cancel(); +} diff --git a/azurite-api/src/main/java/org/bukkit/scheduler/BukkitWorker.java b/azurite-api/src/main/java/org/bukkit/scheduler/BukkitWorker.java new file mode 100644 index 0000000..1058d8d --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/scheduler/BukkitWorker.java @@ -0,0 +1,34 @@ +package org.bukkit.scheduler; + +import org.bukkit.plugin.Plugin; + +/** + * Represents a worker thread for the scheduler. This gives information about + * the Thread object for the task, owner of the task and the taskId. + *

+ * Workers are used to execute async tasks. + */ +public interface BukkitWorker { + + /** + * Returns the taskId for the task being executed by this worker. + * + * @return Task id number + */ + int getTaskId(); + + /** + * Returns the Plugin that owns this task. + * + * @return The Plugin that owns the task + */ + Plugin getOwner(); + + /** + * Returns the thread for the worker. + * + * @return The Thread object for the worker + */ + Thread getThread(); + +} diff --git a/azurite-api/src/main/java/org/bukkit/scoreboard/Criterias.java b/azurite-api/src/main/java/org/bukkit/scoreboard/Criterias.java new file mode 100644 index 0000000..cd81c87 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/scoreboard/Criterias.java @@ -0,0 +1,20 @@ +package org.bukkit.scoreboard; + +/** + * Criteria names which trigger an objective to be modified by actions in-game + */ +public class Criterias { + public static final String HEALTH; + public static final String PLAYER_KILLS; + public static final String TOTAL_KILLS; + public static final String DEATHS; + + static { + HEALTH="health"; + PLAYER_KILLS="playerKillCount"; + TOTAL_KILLS="totalKillCount"; + DEATHS="deathCount"; + } + + private Criterias() {} +} diff --git a/azurite-api/src/main/java/org/bukkit/scoreboard/DisplaySlot.java b/azurite-api/src/main/java/org/bukkit/scoreboard/DisplaySlot.java new file mode 100644 index 0000000..ee69e66 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/scoreboard/DisplaySlot.java @@ -0,0 +1,10 @@ +package org.bukkit.scoreboard; + +/** + * Locations for displaying objectives to the player + */ +public enum DisplaySlot { + BELOW_NAME, + PLAYER_LIST, + SIDEBAR +} diff --git a/azurite-api/src/main/java/org/bukkit/scoreboard/NameTagVisibility.java b/azurite-api/src/main/java/org/bukkit/scoreboard/NameTagVisibility.java new file mode 100644 index 0000000..e425787 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/scoreboard/NameTagVisibility.java @@ -0,0 +1,21 @@ +package org.bukkit.scoreboard; + +public enum NameTagVisibility { + + /** + * Always show the player's nametag. + */ + ALWAYS, + /** + * Never show the player's nametag. + */ + NEVER, + /** + * Show the player's nametag only to his own team members. + */ + HIDE_FOR_OTHER_TEAMS, + /** + * Show the player's nametag only to members of other teams. + */ + HIDE_FOR_OWN_TEAM +} diff --git a/azurite-api/src/main/java/org/bukkit/scoreboard/Objective.java b/azurite-api/src/main/java/org/bukkit/scoreboard/Objective.java new file mode 100644 index 0000000..321aac7 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/scoreboard/Objective.java @@ -0,0 +1,110 @@ +package org.bukkit.scoreboard; + +import org.bukkit.OfflinePlayer; + +/** + * An objective on a scoreboard that can show scores specific to entries. This + * objective is only relevant to the display of the associated {@link + * #getScoreboard() scoreboard}. + */ +public interface Objective { + + /** + * Gets the name of this Objective + * + * @return this objective'ss name + * @throws IllegalStateException if this objective has been unregistered + */ + String getName() throws IllegalStateException; + + /** + * Gets the name displayed to players for this objective + * + * @return this objective's display name + * @throws IllegalStateException if this objective has been unregistered + */ + String getDisplayName() throws IllegalStateException; + + /** + * Sets the name displayed to players for this objective. + * + * @param displayName Display name to set + * @throws IllegalStateException if this objective has been unregistered + * @throws IllegalArgumentException if displayName is null + * @throws IllegalArgumentException if displayName is longer than 32 + * characters. + */ + void setDisplayName(String displayName) throws IllegalStateException, IllegalArgumentException; + + /** + * Gets the criteria this objective tracks. + * + * @return this objective's criteria + * @throws IllegalStateException if this objective has been unregistered + */ + String getCriteria() throws IllegalStateException; + + /** + * Gets if the objective's scores can be modified directly by a plugin. + * + * @return true if scores are modifiable + * @throws IllegalStateException if this objective has been unregistered + * @see Criterias#HEALTH + */ + boolean isModifiable() throws IllegalStateException; + + /** + * Gets the scoreboard to which this objective is attached. + * + * @return Owning scoreboard, or null if it has been {@link #unregister() + * unregistered} + */ + Scoreboard getScoreboard(); + + /** + * Unregisters this objective from the {@link Scoreboard scoreboard.} + * + * @throws IllegalStateException if this objective has been unregistered + */ + void unregister() throws IllegalStateException; + + /** + * Sets this objective to display on the specified slot for the + * scoreboard, removing it from any other display slot. + * + * @param slot display slot to change, or null to not display + * @throws IllegalStateException if this objective has been unregistered + */ + void setDisplaySlot(DisplaySlot slot) throws IllegalStateException; + + /** + * Gets the display slot this objective is displayed at. + * + * @return the display slot for this objective, or null if not displayed + * @throws IllegalStateException if this objective has been unregistered + */ + DisplaySlot getDisplaySlot() throws IllegalStateException; + + /** + * Gets a player's Score for an Objective on this Scoreboard + * + * @param player Player for the Score + * @return Score tracking the Objective and player specified + * @throws IllegalArgumentException if player is null + * @throws IllegalStateException if this objective has been unregistered + * @deprecated Scoreboards can contain entries that aren't players + * @see #getScore(String) + */ + @Deprecated + Score getScore(OfflinePlayer player) throws IllegalArgumentException, IllegalStateException; + + /** + * Gets an entry's Score for an Objective on this Scoreboard. + * + * @param entry Entry for the Score + * @return Score tracking the Objective and entry specified + * @throws IllegalArgumentException if entry is null + * @throws IllegalStateException if this objective has been unregistered + */ + Score getScore(String entry) throws IllegalArgumentException, IllegalStateException; +} diff --git a/azurite-api/src/main/java/org/bukkit/scoreboard/Score.java b/azurite-api/src/main/java/org/bukkit/scoreboard/Score.java new file mode 100644 index 0000000..2410cbd --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/scoreboard/Score.java @@ -0,0 +1,72 @@ +package org.bukkit.scoreboard; + +import org.bukkit.OfflinePlayer; + +/** + * A score entry for an {@link #getEntry() entry} on an {@link + * #getObjective() objective}. Changing this will not affect any other + * objective or scoreboard. + */ +public interface Score { + + /** + * Gets the OfflinePlayer being tracked by this Score + * + * @return this Score's tracked player + * @deprecated Scoreboards can contain entries that aren't players + * @see #getEntry() + */ + @Deprecated + OfflinePlayer getPlayer(); + + /** + * Gets the entry being tracked by this Score + * + * @return this Score's tracked entry + */ + String getEntry(); + + /** + * Gets the Objective being tracked by this Score + * + * @return this Score's tracked objective + */ + Objective getObjective(); + + /** + * Gets the current score + * + * @return the current score + * @throws IllegalStateException if the associated objective has been + * unregistered + */ + int getScore() throws IllegalStateException; + + /** + * Sets the current score. + * + * @param score New score + * @throws IllegalStateException if the associated objective has been + * unregistered + */ + void setScore(int score) throws IllegalStateException; + + // Spigot start + /** + * Shows if this score has been set at any point in time. + * + * @return if this score has been set before + * @throws IllegalStateException if the associated objective has been + * unregistered + */ + boolean isScoreSet() throws IllegalStateException; + // Spigot end + + /** + * Gets the scoreboard for the associated objective. + * + * @return the owning objective's scoreboard, or null if it has been + * {@link Objective#unregister() unregistered} + */ + Scoreboard getScoreboard(); +} diff --git a/azurite-api/src/main/java/org/bukkit/scoreboard/Scoreboard.java b/azurite-api/src/main/java/org/bukkit/scoreboard/Scoreboard.java new file mode 100644 index 0000000..f16a546 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/scoreboard/Scoreboard.java @@ -0,0 +1,171 @@ +package org.bukkit.scoreboard; + +import org.bukkit.OfflinePlayer; + +import java.util.Set; + +/** + * A scoreboard + */ +public interface Scoreboard { + + /** + * Registers an Objective on this Scoreboard + * + * @param name Name of the Objective + * @param criteria Criteria for the Objective + * @return The registered Objective + * @throws IllegalArgumentException if name is null + * @throws IllegalArgumentException if criteria is null + * @throws IllegalArgumentException if an objective by that name already + * exists + */ + Objective registerNewObjective(String name, String criteria) throws IllegalArgumentException; + + /** + * Gets an Objective on this Scoreboard by name + * + * @param name Name of the Objective + * @return the Objective or null if it does not exist + * @throws IllegalArgumentException if name is null + */ + Objective getObjective(String name) throws IllegalArgumentException; + + /** + * Gets all Objectives of a Criteria on the Scoreboard + * + * @param criteria Criteria to search by + * @return an immutable set of Objectives using the specified Criteria + */ + Set getObjectivesByCriteria(String criteria) throws IllegalArgumentException; + + /** + * Gets all Objectives on this Scoreboard + * + * @return An immutable set of all Objectives on this Scoreboard + */ + Set getObjectives(); + + /** + * Gets the Objective currently displayed in a DisplaySlot on this + * Scoreboard + * + * @param slot The DisplaySlot + * @return the Objective currently displayed or null if nothing is + * displayed in that DisplaySlot + * @throws IllegalArgumentException if slot is null + */ + Objective getObjective(DisplaySlot slot) throws IllegalArgumentException; + + /** + * Gets all scores for a player on this Scoreboard + * + * @param player the player whose scores are being retrieved + * @return immutable set of all scores tracked for the player + * @throws IllegalArgumentException if player is null + * @deprecated Scoreboards can contain entries that aren't players + * @see #getScores(String) + */ + @Deprecated + Set getScores(OfflinePlayer player) throws IllegalArgumentException; + + /** + * Gets all scores for an entry on this Scoreboard + * + * @param entry the entry whose scores are being retrieved + * @return immutable set of all scores tracked for the entry + * @throws IllegalArgumentException if entry is null + */ + Set getScores(String entry) throws IllegalArgumentException; + + /** + * Removes all scores for a player on this Scoreboard + * + * @param player the player to drop all current scores for + * @throws IllegalArgumentException if player is null + * @deprecated Scoreboards can contain entries that aren't players + * @see #resetScores(String) + */ + @Deprecated + void resetScores(OfflinePlayer player) throws IllegalArgumentException; + + /** + * Removes all scores for an entry on this Scoreboard + * + * @param entry the entry to drop all current scores for + * @throws IllegalArgumentException if entry is null + */ + void resetScores(String entry) throws IllegalArgumentException; + + /** + * Gets a player's Team on this Scoreboard + * + * @param player the player to search for + * @return the player's Team or null if the player is not on a team + * @throws IllegalArgumentException if player is null + * @deprecated Scoreboards can contain entries that aren't players + * @see #getEntryTeam(String) + */ + @Deprecated + Team getPlayerTeam(OfflinePlayer player) throws IllegalArgumentException; + + /** + * Gets a entries Team on this Scoreboard + * + * @param entry the entry to search for + * @return the entries Team or null if the entry is not on a team + * @throws IllegalArgumentException if entry is null + */ + Team getEntryTeam(String entry) throws IllegalArgumentException; + + /** + * Gets a Team by name on this Scoreboard + * + * @param teamName Team name + * @return the matching Team or null if no matches + * @throws IllegalArgumentException if teamName is null + */ + Team getTeam(String teamName) throws IllegalArgumentException; + + /** + * Gets all teams on this Scoreboard + * + * @return an immutable set of Teams + */ + Set getTeams(); + + /** + * Registers a Team on this Scoreboard + * + * @param name Team name + * @return registered Team + * @throws IllegalArgumentException if name is null + * @throws IllegalArgumentException if team by that name already exists + */ + Team registerNewTeam(String name) throws IllegalArgumentException; + + /** + * Gets all players tracked by this Scoreboard + * + * @return immutable set of all tracked players + * @deprecated Scoreboards can contain entries that aren't players + * @see #getEntries() + */ + @Deprecated + Set getPlayers(); + + /** + * Gets all entries tracked by this Scoreboard + * + * @return immutable set of all tracked entries + */ + Set getEntries(); + + /** + * Clears any objective in the specified slot. + * + * @param slot the slot to remove objectives + * @throws IllegalArgumentException if slot is null + */ + void clearSlot(DisplaySlot slot) throws IllegalArgumentException; +} diff --git a/azurite-api/src/main/java/org/bukkit/scoreboard/ScoreboardManager.java b/azurite-api/src/main/java/org/bukkit/scoreboard/ScoreboardManager.java new file mode 100644 index 0000000..00b67a1 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/scoreboard/ScoreboardManager.java @@ -0,0 +1,29 @@ +package org.bukkit.scoreboard; + +import java.lang.ref.WeakReference; + +/** + * Manager of Scoreboards + */ +public interface ScoreboardManager { + + /** + * Gets the primary Scoreboard controlled by the server. + *

+ * This Scoreboard is saved by the server, is affected by the /scoreboard + * command, and is the scoreboard shown by default to players. + * + * @return the default sever scoreboard + */ + Scoreboard getMainScoreboard(); + + /** + * Gets a new Scoreboard to be tracked by the server. This scoreboard will + * be tracked as long as a reference is kept, either by a player or by a + * plugin. + * + * @return the registered Scoreboard + * @see WeakReference + */ + Scoreboard getNewScoreboard(); +} diff --git a/azurite-api/src/main/java/org/bukkit/scoreboard/Team.java b/azurite-api/src/main/java/org/bukkit/scoreboard/Team.java new file mode 100644 index 0000000..66c6f78 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/scoreboard/Team.java @@ -0,0 +1,240 @@ +package org.bukkit.scoreboard; + +import org.bukkit.OfflinePlayer; +import org.bukkit.potion.PotionEffectType; + +import java.util.Set; + +/** + * A team on a scoreboard that has a common display theme and other + * properties. This team is only relevant to the display of the associated + * {@link #getScoreboard() scoreboard}. + */ +public interface Team { + + /** + * Gets the name of this Team + * + * @return Objective name + * @throws IllegalStateException if this team has been unregistered + */ + String getName() throws IllegalStateException; + + /** + * Gets the name displayed to entries for this team + * + * @return Team display name + * @throws IllegalStateException if this team has been unregistered + */ + String getDisplayName() throws IllegalStateException; + + /** + * Sets the name displayed to entries for this team + * + * @param displayName New display name + * @throws IllegalArgumentException if displayName is longer than 32 + * characters. + * @throws IllegalStateException if this team has been unregistered + */ + void setDisplayName(String displayName) throws IllegalStateException, IllegalArgumentException; + + /** + * Gets the prefix prepended to the display of entries on this team. + * + * @return Team prefix + * @throws IllegalStateException if this team has been unregistered + */ + String getPrefix() throws IllegalStateException; + + /** + * Sets the prefix prepended to the display of entries on this team. + * + * @param prefix New prefix + * @throws IllegalArgumentException if prefix is null + * @throws IllegalArgumentException if prefix is longer than 16 + * characters + * @throws IllegalStateException if this team has been unregistered + */ + void setPrefix(String prefix) throws IllegalStateException, IllegalArgumentException; + + /** + * Gets the suffix appended to the display of entries on this team. + * + * @return the team's current suffix + * @throws IllegalStateException if this team has been unregistered + */ + String getSuffix() throws IllegalStateException; + + /** + * Sets the suffix appended to the display of entries on this team. + * + * @param suffix the new suffix for this team. + * @throws IllegalArgumentException if suffix is null + * @throws IllegalArgumentException if suffix is longer than 16 + * characters + * @throws IllegalStateException if this team has been unregistered + */ + void setSuffix(String suffix) throws IllegalStateException, IllegalArgumentException; + + /** + * Gets the team friendly fire state + * + * @return true if friendly fire is enabled + * @throws IllegalStateException if this team has been unregistered + */ + boolean allowFriendlyFire() throws IllegalStateException; + + /** + * Sets the team friendly fire state + * + * @param enabled true if friendly fire is to be allowed + * @throws IllegalStateException if this team has been unregistered + */ + void setAllowFriendlyFire(boolean enabled) throws IllegalStateException; + + /** + * Gets the team's ability to see {@link PotionEffectType#INVISIBILITY + * invisible} teammates. + * + * @return true if team members can see invisible members + * @throws IllegalStateException if this team has been unregistered + */ + boolean canSeeFriendlyInvisibles() throws IllegalStateException; + + /** + * Sets the team's ability to see {@link PotionEffectType#INVISIBILITY + * invisible} teammates. + * + * @param enabled true if invisible teammates are to be visible + * @throws IllegalStateException if this team has been unregistered + */ + void setCanSeeFriendlyInvisibles(boolean enabled) throws IllegalStateException; + + /** + * Gets the team's ability to see name tags + * + * @return the current name tag visibilty for the team + * @throws IllegalArgumentException if this team has been unregistered + */ + NameTagVisibility getNameTagVisibility() throws IllegalArgumentException; + + /** + * Set's the team's ability to see name tags + * + * @param visibility The nameTagVisibilty to set + * @throws IllegalArgumentException if this team has been unregistered + */ + void setNameTagVisibility(NameTagVisibility visibility) throws IllegalArgumentException; + + /** + * Gets the Set of players on the team + * + * @return players on the team + * @throws IllegalStateException if this team has been unregistered\ + * @deprecated Teams can contain entries that aren't players + * @see #getEntries() + */ + @Deprecated + Set getPlayers() throws IllegalStateException; + + /** + * Gets the Set of entries on the team + * + * @return entries on the team + * @throws IllegalStateException if this entries has been unregistered\ + */ + Set getEntries() throws IllegalStateException; + + /** + * Gets the size of the team + * + * @return number of entries on the team + * @throws IllegalStateException if this team has been unregistered + */ + int getSize() throws IllegalStateException; + + /** + * Gets the Scoreboard to which this team is attached + * + * @return Owning scoreboard, or null if this team has been {@link + * #unregister() unregistered} + */ + Scoreboard getScoreboard(); + + /** + * This puts the specified player onto this team for the scoreboard. + *

+ * This will remove the player from any other team on the scoreboard. + * + * @param player the player to add + * @throws IllegalArgumentException if player is null + * @throws IllegalStateException if this team has been unregistered + * @deprecated Teams can contain entries that aren't players + * @see #addEntry(String) + */ + @Deprecated + void addPlayer(OfflinePlayer player) throws IllegalStateException, IllegalArgumentException; + + /** + * This puts the specified entry onto this team for the scoreboard. + *

+ * This will remove the entry from any other team on the scoreboard. + * + * @param entry the entry to add + * @throws IllegalArgumentException if entry is null + * @throws IllegalStateException if this team has been unregistered + */ + void addEntry(String entry) throws IllegalStateException, IllegalArgumentException; + + /** + * Removes the player from this team. + * + * @param player the player to remove + * @return if the player was on this team + * @throws IllegalArgumentException if player is null + * @throws IllegalStateException if this team has been unregistered + * @deprecated Teams can contain entries that aren't players + * @see #removeEntry(String) + */ + @Deprecated + boolean removePlayer(OfflinePlayer player) throws IllegalStateException, IllegalArgumentException; + + /** + * Removes the entry from this team. + * + * @param entry the entry to remove + * @throws IllegalArgumentException if entry is null + * @throws IllegalStateException if this team has been unregistered + * @return if the entry was a part of this team + */ + boolean removeEntry(String entry) throws IllegalStateException, IllegalArgumentException; + + /** + * Unregisters this team from the Scoreboard + * + * @throws IllegalStateException if this team has been unregistered + */ + void unregister() throws IllegalStateException; + + /** + * Checks to see if the specified player is a member of this team. + * + * @param player the player to search for + * @return true if the player is a member of this team + * @throws IllegalArgumentException if player is null + * @throws IllegalStateException if this team has been unregistered + * @deprecated Teams can contain entries that aren't players + * @see #hasEntry(String) + */ + @Deprecated + boolean hasPlayer(OfflinePlayer player) throws IllegalArgumentException, IllegalStateException; + /** + * Checks to see if the specified entry is a member of this team. + * + * @param entry the entry to search for + * @return true if the entry is a member of this team + * @throws IllegalArgumentException if entry is null + * @throws IllegalStateException if this team has been unregistered + */ + boolean hasEntry(String entry) throws IllegalArgumentException,IllegalStateException; +} diff --git a/azurite-api/src/main/java/org/bukkit/util/BlockIterator.java b/azurite-api/src/main/java/org/bukkit/util/BlockIterator.java new file mode 100644 index 0000000..5d99885 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/util/BlockIterator.java @@ -0,0 +1,356 @@ +package org.bukkit.util; + +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.entity.LivingEntity; + +import java.util.Iterator; +import java.util.NoSuchElementException; + +import static org.bukkit.util.NumberConversions.floor; +import static org.bukkit.util.NumberConversions.round; + +/** + * This class performs ray tracing and iterates along blocks on a line + */ +public class BlockIterator implements Iterator { + + private final World world; + private final int maxDistance; + + private static final int gridSize = 1 << 24; + + private boolean end = false; + + private Block[] blockQueue = new Block[3]; + private int currentBlock = 0; + private int currentDistance = 0; + private int maxDistanceInt; + + private int secondError; + private int thirdError; + + private int secondStep; + private int thirdStep; + + private BlockFace mainFace; + private BlockFace secondFace; + private BlockFace thirdFace; + + /** + * Constructs the BlockIterator + * + * @param world The world to use for tracing + * @param start A Vector giving the initial location for the trace + * @param direction A Vector pointing in the direction for the trace + * @param yOffset The trace begins vertically offset from the start vector + * by this value + * @param maxDistance This is the maximum distance in blocks for the + * trace. Setting this value above 140 may lead to problems with + * unloaded chunks. A value of 0 indicates no limit + * + */ + public BlockIterator(World world, Vector start, Vector direction, double yOffset, int maxDistance) { + this.world = world; + this.maxDistance = maxDistance; + + Vector startClone = start.clone(); + + startClone.setY(startClone.getY() + yOffset); + + currentDistance = 0; + + double mainDirection = 0; + double secondDirection = 0; + double thirdDirection = 0; + + double mainPosition = 0; + double secondPosition = 0; + double thirdPosition = 0; + + Block startBlock = this.world.getBlockAt(floor(startClone.getX()), floor(startClone.getY()), floor(startClone.getZ())); + + if (getXLength(direction) > mainDirection) { + mainFace = getXFace(direction); + mainDirection = getXLength(direction); + mainPosition = getXPosition(direction, startClone, startBlock); + + secondFace = getYFace(direction); + secondDirection = getYLength(direction); + secondPosition = getYPosition(direction, startClone, startBlock); + + thirdFace = getZFace(direction); + thirdDirection = getZLength(direction); + thirdPosition = getZPosition(direction, startClone, startBlock); + } + if (getYLength(direction) > mainDirection) { + mainFace = getYFace(direction); + mainDirection = getYLength(direction); + mainPosition = getYPosition(direction, startClone, startBlock); + + secondFace = getZFace(direction); + secondDirection = getZLength(direction); + secondPosition = getZPosition(direction, startClone, startBlock); + + thirdFace = getXFace(direction); + thirdDirection = getXLength(direction); + thirdPosition = getXPosition(direction, startClone, startBlock); + } + if (getZLength(direction) > mainDirection) { + mainFace = getZFace(direction); + mainDirection = getZLength(direction); + mainPosition = getZPosition(direction, startClone, startBlock); + + secondFace = getXFace(direction); + secondDirection = getXLength(direction); + secondPosition = getXPosition(direction, startClone, startBlock); + + thirdFace = getYFace(direction); + thirdDirection = getYLength(direction); + thirdPosition = getYPosition(direction, startClone, startBlock); + } + + // trace line backwards to find intercept with plane perpendicular to the main axis + + double d = mainPosition / mainDirection; // how far to hit face behind + double secondd = secondPosition - secondDirection * d; + double thirdd = thirdPosition - thirdDirection * d; + + // Guarantee that the ray will pass though the start block. + // It is possible that it would miss due to rounding + // This should only move the ray by 1 grid position + secondError = floor(secondd * gridSize); + secondStep = round(secondDirection / mainDirection * gridSize); + thirdError = floor(thirdd * gridSize); + thirdStep = round(thirdDirection / mainDirection * gridSize); + + if (secondError + secondStep <= 0) { + secondError = -secondStep + 1; + } + + if (thirdError + thirdStep <= 0) { + thirdError = -thirdStep + 1; + } + + Block lastBlock; + + lastBlock = startBlock.getRelative(mainFace.getOppositeFace()); + + if (secondError < 0) { + secondError += gridSize; + lastBlock = lastBlock.getRelative(secondFace.getOppositeFace()); + } + + if (thirdError < 0) { + thirdError += gridSize; + lastBlock = lastBlock.getRelative(thirdFace.getOppositeFace()); + } + + // This means that when the variables are positive, it means that the coord=1 boundary has been crossed + secondError -= gridSize; + thirdError -= gridSize; + + blockQueue[0] = lastBlock; + currentBlock = -1; + + scan(); + + boolean startBlockFound = false; + + for (int cnt = currentBlock; cnt >= 0; cnt--) { + if (blockEquals(blockQueue[cnt], startBlock)) { + currentBlock = cnt; + startBlockFound = true; + break; + } + } + + if (!startBlockFound) { + throw new IllegalStateException("Start block missed in BlockIterator"); + } + + // Calculate the number of planes passed to give max distance + maxDistanceInt = round(maxDistance / (Math.sqrt(mainDirection * mainDirection + secondDirection * secondDirection + thirdDirection * thirdDirection) / mainDirection)); + + } + + private boolean blockEquals(Block a, Block b) { + return a.getX() == b.getX() && a.getY() == b.getY() && a.getZ() == b.getZ(); + } + + private BlockFace getXFace(Vector direction) { + return ((direction.getX() > 0) ? BlockFace.EAST : BlockFace.WEST); + } + + private BlockFace getYFace(Vector direction) { + return ((direction.getY() > 0) ? BlockFace.UP : BlockFace.DOWN); + } + + private BlockFace getZFace(Vector direction) { + return ((direction.getZ() > 0) ? BlockFace.SOUTH : BlockFace.NORTH); + } + + private double getXLength(Vector direction) { + return Math.abs(direction.getX()); + } + + private double getYLength(Vector direction) { + return Math.abs(direction.getY()); + } + + private double getZLength(Vector direction) { + return Math.abs(direction.getZ()); + } + + private double getPosition(double direction, double position, int blockPosition) { + return direction > 0 ? (position - blockPosition) : (blockPosition + 1 - position); + } + + private double getXPosition(Vector direction, Vector position, Block block) { + return getPosition(direction.getX(), position.getX(), block.getX()); + } + + private double getYPosition(Vector direction, Vector position, Block block) { + return getPosition(direction.getY(), position.getY(), block.getY()); + } + + private double getZPosition(Vector direction, Vector position, Block block) { + return getPosition(direction.getZ(), position.getZ(), block.getZ()); + } + + /** + * Constructs the BlockIterator + * + * @param loc The location for the start of the ray trace + * @param yOffset The trace begins vertically offset from the start vector + * by this value + * @param maxDistance This is the maximum distance in blocks for the + * trace. Setting this value above 140 may lead to problems with + * unloaded chunks. A value of 0 indicates no limit + */ + public BlockIterator(Location loc, double yOffset, int maxDistance) { + this(loc.getWorld(), loc.toVector(), loc.getDirection(), yOffset, maxDistance); + } + + /** + * Constructs the BlockIterator. + * + * @param loc The location for the start of the ray trace + * @param yOffset The trace begins vertically offset from the start vector + * by this value + */ + + public BlockIterator(Location loc, double yOffset) { + this(loc.getWorld(), loc.toVector(), loc.getDirection(), yOffset, 0); + } + + /** + * Constructs the BlockIterator. + * + * @param loc The location for the start of the ray trace + */ + + public BlockIterator(Location loc) { + this(loc, 0D); + } + + /** + * Constructs the BlockIterator. + * + * @param entity Information from the entity is used to set up the trace + * @param maxDistance This is the maximum distance in blocks for the + * trace. Setting this value above 140 may lead to problems with + * unloaded chunks. A value of 0 indicates no limit + */ + + public BlockIterator(LivingEntity entity, int maxDistance) { + this(entity.getLocation(), entity.getEyeHeight(), maxDistance); + } + + /** + * Constructs the BlockIterator. + * + * @param entity Information from the entity is used to set up the trace + */ + + public BlockIterator(LivingEntity entity) { + this(entity, 0); + } + + /** + * Returns true if the iteration has more elements + */ + + public boolean hasNext() { + scan(); + return currentBlock != -1; + } + + /** + * Returns the next Block in the trace + * + * @return the next Block in the trace + */ + + public Block next() { + scan(); + if (currentBlock <= -1) { + throw new NoSuchElementException(); + } else { + return blockQueue[currentBlock--]; + } + } + + public void remove() { + throw new UnsupportedOperationException("[BlockIterator] doesn't support block removal"); + } + + private void scan() { + if (currentBlock >= 0) { + return; + } else if (maxDistance != 0 && currentDistance > maxDistanceInt) { + end = true; + return; + } else if (end) { + return; + } + + currentDistance++; + + secondError += secondStep; + thirdError += thirdStep; + + if (secondError > 0 && thirdError > 0) { + blockQueue[2] = blockQueue[0].getRelative(mainFace); + if (((long) secondStep) * ((long) thirdError) < ((long) thirdStep) * ((long) secondError)) { + blockQueue[1] = blockQueue[2].getRelative(secondFace); + blockQueue[0] = blockQueue[1].getRelative(thirdFace); + } else { + blockQueue[1] = blockQueue[2].getRelative(thirdFace); + blockQueue[0] = blockQueue[1].getRelative(secondFace); + } + thirdError -= gridSize; + secondError -= gridSize; + currentBlock = 2; + return; + } else if (secondError > 0) { + blockQueue[1] = blockQueue[0].getRelative(mainFace); + blockQueue[0] = blockQueue[1].getRelative(secondFace); + secondError -= gridSize; + currentBlock = 1; + return; + } else if (thirdError > 0) { + blockQueue[1] = blockQueue[0].getRelative(mainFace); + blockQueue[0] = blockQueue[1].getRelative(thirdFace); + thirdError -= gridSize; + currentBlock = 1; + return; + } else { + blockQueue[0] = blockQueue[0].getRelative(mainFace); + currentBlock = 0; + return; + } + } +} diff --git a/azurite-api/src/main/java/org/bukkit/util/BlockVector.java b/azurite-api/src/main/java/org/bukkit/util/BlockVector.java new file mode 100644 index 0000000..281f9a7 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/util/BlockVector.java @@ -0,0 +1,129 @@ +package org.bukkit.util; + +import org.bukkit.configuration.serialization.SerializableAs; + +import java.util.Map; + +/** + * A vector with a hash function that floors the X, Y, Z components, a la + * BlockVector in WorldEdit. BlockVectors can be used in hash sets and + * hash maps. Be aware that BlockVectors are mutable, but it is important + * that BlockVectors are never changed once put into a hash set or hash map. + */ +@SerializableAs("BlockVector") +public class BlockVector extends Vector { + + /** + * Construct the vector with all components as 0. + */ + public BlockVector() { + this.x = 0; + this.y = 0; + this.z = 0; + } + + /** + * Construct the vector with another vector. + * + * @param vec The other vector. + */ + public BlockVector(Vector vec) { + this.x = vec.getX(); + this.y = vec.getY(); + this.z = vec.getZ(); + } + + /** + * Construct the vector with provided integer components. + * + * @param x X component + * @param y Y component + * @param z Z component + */ + public BlockVector(int x, int y, int z) { + this.x = x; + this.y = y; + this.z = z; + } + + /** + * Construct the vector with provided double components. + * + * @param x X component + * @param y Y component + * @param z Z component + */ + public BlockVector(double x, double y, double z) { + this.x = x; + this.y = y; + this.z = z; + } + + /** + * Construct the vector with provided float components. + * + * @param x X component + * @param y Y component + * @param z Z component + */ + public BlockVector(float x, float y, float z) { + this.x = x; + this.y = y; + this.z = z; + } + + /** + * Checks if another object is equivalent. + * + * @param obj The other object + * @return whether the other object is equivalent + */ + @Override + public boolean equals(Object obj) { + if (!(obj instanceof BlockVector)) { + return false; + } + BlockVector other = (BlockVector) obj; + + return (int) other.getX() == (int) this.x && (int) other.getY() == (int) this.y && (int) other.getZ() == (int) this.z; + + } + + /** + * Returns a hash code for this vector. + * + * @return hash code + */ + @Override + public int hashCode() { + return (Integer.valueOf((int) x).hashCode() >> 13) ^ (Integer.valueOf((int) y).hashCode() >> 7) ^ Integer.valueOf((int) z).hashCode(); + } + + /** + * Get a new block vector. + * + * @return vector + */ + @Override + public BlockVector clone() { + return (BlockVector) super.clone(); + } + + public static BlockVector deserialize(Map args) { + double x = 0; + double y = 0; + double z = 0; + + if (args.containsKey("x")) { + x = (Double) args.get("x"); + } + if (args.containsKey("y")) { + y = (Double) args.get("y"); + } + if (args.containsKey("z")) { + z = (Double) args.get("z"); + } + + return new BlockVector(x, y, z); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/util/CachedServerIcon.java b/azurite-api/src/main/java/org/bukkit/util/CachedServerIcon.java new file mode 100644 index 0000000..1c9a8fc --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/util/CachedServerIcon.java @@ -0,0 +1,17 @@ +package org.bukkit.util; + +import org.bukkit.Server; +import org.bukkit.event.server.ServerListPingEvent; + +/** + * This is a cached version of a server-icon. It's internal representation + * and implementation is undefined. + * + * @see Server#getServerIcon() + * @see Server#loadServerIcon(java.awt.image.BufferedImage) + * @see Server#loadServerIcon(java.io.File) + * @see ServerListPingEvent#setServerIcon(CachedServerIcon) + */ +public interface CachedServerIcon { + String getData(); // Spigot +} diff --git a/azurite-api/src/main/java/org/bukkit/util/ChatPaginator.java b/azurite-api/src/main/java/org/bukkit/util/ChatPaginator.java new file mode 100644 index 0000000..24802d1 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/util/ChatPaginator.java @@ -0,0 +1,169 @@ +package org.bukkit.util; + +import org.bukkit.ChatColor; + +import java.util.LinkedList; +import java.util.List; + +/** + * The ChatPaginator takes a raw string of arbitrary length and breaks it down + * into an array of strings appropriate for displaying on the Minecraft player + * console. + */ +public class ChatPaginator { + public static final int GUARANTEED_NO_WRAP_CHAT_PAGE_WIDTH = 55; // Will never wrap, even with the largest characters + public static final int AVERAGE_CHAT_PAGE_WIDTH = 65; // Will typically not wrap using an average character distribution + public static final int UNBOUNDED_PAGE_WIDTH = Integer.MAX_VALUE; + public static final int OPEN_CHAT_PAGE_HEIGHT = 20; // The height of an expanded chat window + public static final int CLOSED_CHAT_PAGE_HEIGHT = 10; // The height of the default chat window + public static final int UNBOUNDED_PAGE_HEIGHT = Integer.MAX_VALUE; + + /** + * Breaks a raw string up into pages using the default width and height. + * + * @param unpaginatedString The raw string to break. + * @param pageNumber The page number to fetch. + * @return A single chat page. + */ + public static ChatPage paginate(String unpaginatedString, int pageNumber) { + return paginate(unpaginatedString, pageNumber, GUARANTEED_NO_WRAP_CHAT_PAGE_WIDTH, CLOSED_CHAT_PAGE_HEIGHT); + } + + /** + * Breaks a raw string up into pages using a provided width and height. + * + * @param unpaginatedString The raw string to break. + * @param pageNumber The page number to fetch. + * @param lineLength The desired width of a chat line. + * @param pageHeight The desired number of lines in a page. + * @return A single chat page. + */ + public static ChatPage paginate(String unpaginatedString, int pageNumber, int lineLength, int pageHeight) { + String[] lines = wordWrap(unpaginatedString, lineLength); + + int totalPages = lines.length / pageHeight + (lines.length % pageHeight == 0 ? 0 : 1); + int actualPageNumber = pageNumber <= totalPages ? pageNumber : totalPages; + + int from = (actualPageNumber - 1) * pageHeight; + int to = from + pageHeight <= lines.length ? from + pageHeight : lines.length; + String[] selectedLines = Java15Compat.Arrays_copyOfRange(lines, from, to); + + return new ChatPage(selectedLines, actualPageNumber, totalPages); + } + + /** + * Breaks a raw string up into a series of lines. Words are wrapped using + * spaces as decimeters and the newline character is respected. + * + * @param rawString The raw string to break. + * @param lineLength The length of a line of text. + * @return An array of word-wrapped lines. + */ + public static String[] wordWrap(String rawString, int lineLength) { + // A null string is a single line + if (rawString == null) { + return new String[] {""}; + } + + // A string shorter than the lineWidth is a single line + if (rawString.length() <= lineLength && !rawString.contains("\n")) { + return new String[] {rawString}; + } + + char[] rawChars = (rawString + ' ').toCharArray(); // add a trailing space to trigger pagination + StringBuilder word = new StringBuilder(); + StringBuilder line = new StringBuilder(); + List lines = new LinkedList(); + int lineColorChars = 0; + + for (int i = 0; i < rawChars.length; i++) { + char c = rawChars[i]; + + // skip chat color modifiers + if (c == ChatColor.COLOR_CHAR) { + word.append(ChatColor.getByChar(rawChars[i + 1])); + lineColorChars += 2; + i++; // Eat the next character as we have already processed it + continue; + } + + if (c == ' ' || c == '\n') { + if (line.length() == 0 && word.length() > lineLength) { // special case: extremely long word begins a line + for (String partialWord : word.toString().split("(?<=\\G.{" + lineLength + "})")) { + lines.add(partialWord); + } + } else if (line.length() + word.length() - lineColorChars == lineLength) { // Line exactly the correct length...newline + line.append(word); + lines.add(line.toString()); + line = new StringBuilder(); + lineColorChars = 0; + } else if (line.length() + 1 + word.length() - lineColorChars > lineLength) { // Line too long...break the line + for (String partialWord : word.toString().split("(?<=\\G.{" + lineLength + "})")) { + lines.add(line.toString()); + line = new StringBuilder(partialWord); + } + lineColorChars = 0; + } else { + if (line.length() > 0) { + line.append(' '); + } + line.append(word); + } + word = new StringBuilder(); + + if (c == '\n') { // Newline forces the line to flush + lines.add(line.toString()); + line = new StringBuilder(); + } + } else { + word.append(c); + } + } + + if(line.length() > 0) { // Only add the last line if there is anything to add + lines.add(line.toString()); + } + + // Iterate over the wrapped lines, applying the last color from one line to the beginning of the next + if (lines.get(0).length() == 0 || lines.get(0).charAt(0) != ChatColor.COLOR_CHAR) { + lines.set(0, ChatColor.WHITE + lines.get(0)); + } + for (int i = 1; i < lines.size(); i++) { + final String pLine = lines.get(i-1); + final String subLine = lines.get(i); + + char color = pLine.charAt(pLine.lastIndexOf(ChatColor.COLOR_CHAR) + 1); + if (subLine.length() == 0 || subLine.charAt(0) != ChatColor.COLOR_CHAR) { + lines.set(i, ChatColor.getByChar(color) + subLine); + } + } + + return lines.toArray(new String[lines.size()]); + } + + public static class ChatPage { + + private String[] lines; + private int pageNumber; + private int totalPages; + + public ChatPage(String[] lines, int pageNumber, int totalPages) { + this.lines = lines; + this.pageNumber = pageNumber; + this.totalPages = totalPages; + } + + public int getPageNumber() { + return pageNumber; + } + + public int getTotalPages() { + return totalPages; + } + + public String[] getLines() { + + return lines; + } + } +} diff --git a/azurite-api/src/main/java/org/bukkit/util/EulerAngle.java b/azurite-api/src/main/java/org/bukkit/util/EulerAngle.java new file mode 100644 index 0000000..7778710 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/util/EulerAngle.java @@ -0,0 +1,147 @@ +package org.bukkit.util; + +/** + * EulerAngle is used to represent 3 angles, one for each + * axis (x, y, z). The angles are in radians + */ +public class EulerAngle { + + /** + * A EulerAngle with every axis set to 0 + */ + public static final EulerAngle ZERO = new EulerAngle(0, 0, 0); + + private final double x; + private final double y; + private final double z; + + /** + * Creates a EularAngle with each axis set to the + * passed angle in radians + * + * @param x the angle for the x axis in radians + * @param y the angle for the x axis in radians + * @param z the angle for the x axis in radians + */ + public EulerAngle(double x, double y, double z) { + this.x = x; + this.y = y; + this.z = z; + } + + /** + * Returns the angle on the x axis in radians + * + * @return the angle in radians + */ + public double getX() { + return x; + } + + /** + * Returns the angle on the y axis in radians + * + * @return the angle in radians + */ + public double getY() { + return y; + } + + /** + * Returns the angle on the z axis in radians + * + * @return the angle in radians + */ + public double getZ() { + return z; + } + + /** + * Return a EulerAngle which is the result of changing + * the x axis to the passed angle + * + * @param x the angle in radians + * @return the resultant EulerAngle + */ + public EulerAngle setX(double x) { + return new EulerAngle(x, y, z); + } + + /** + * Return a EulerAngle which is the result of changing + * the y axis to the passed angle + * + * @param y the angle in radians + * @return the resultant EulerAngle + */ + public EulerAngle setY(double y) { + return new EulerAngle(x, y, z); + } + + /** + * Return a EulerAngle which is the result of changing + * the z axis to the passed angle + * + * @param z the angle in radians + * @return the resultant EulerAngle + */ + public EulerAngle setZ(double z) { + return new EulerAngle(x, y, z); + } + + /** + * Creates a new EulerAngle which is the result of adding + * the x, y, z components to this EulerAngle + * + * @param x the angle to add to the x axis in radians + * @param y the angle to add to the y axis in radians + * @param z the angle to add to the z axis in radians + * @return the resultant EulerAngle + */ + public EulerAngle add(double x, double y, double z) { + return new EulerAngle( + this.x + x, + this.y + y, + this.z + z + ); + } + + /** + * Creates a new EulerAngle which is the result of subtracting + * the x, y, z components to this EulerAngle + * + * @param x the angle to subtract to the x axis in radians + * @param y the angle to subtract to the y axis in radians + * @param z the angle to subtract to the z axis in radians + * @return the resultant EulerAngle + */ + public EulerAngle subtract(double x, double y, double z) { + return add(-x, -y, -z); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + EulerAngle that = (EulerAngle) o; + + return Double.compare(that.x, x) == 0 + && Double.compare(that.y, y) == 0 + && Double.compare(that.z, z) == 0; + + } + + @Override + public int hashCode() { + int result; + long temp; + temp = Double.doubleToLongBits(x); + result = (int) (temp ^ (temp >>> 32)); + temp = Double.doubleToLongBits(y); + result = 31 * result + (int) (temp ^ (temp >>> 32)); + temp = Double.doubleToLongBits(z); + result = 31 * result + (int) (temp ^ (temp >>> 32)); + return result; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/util/FileUtil.java b/azurite-api/src/main/java/org/bukkit/util/FileUtil.java new file mode 100644 index 0000000..a014d09 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/util/FileUtil.java @@ -0,0 +1,57 @@ +package org.bukkit.util; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.nio.channels.FileChannel; + +/** + * Class containing file utilities + */ +public class FileUtil { + + /** + * This method copies one file to another location + * + * @param inFile the source filename + * @param outFile the target filename + * @return true on success + */ + public static boolean copy(File inFile, File outFile) { + if (!inFile.exists()) { + return false; + } + + FileChannel in = null; + FileChannel out = null; + + try { + in = new FileInputStream(inFile).getChannel(); + out = new FileOutputStream(outFile).getChannel(); + + long pos = 0; + long size = in.size(); + + while (pos < size) { + pos += in.transferTo(pos, 10 * 1024 * 1024, out); + } + } catch (IOException ioe) { + return false; + } finally { + try { + if (in != null) { + in.close(); + } + if (out != null) { + out.close(); + } + } catch (IOException ioe) { + return false; + } + } + + return true; + + } +} diff --git a/azurite-api/src/main/java/org/bukkit/util/Java15Compat.java b/azurite-api/src/main/java/org/bukkit/util/Java15Compat.java new file mode 100644 index 0000000..c119742 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/util/Java15Compat.java @@ -0,0 +1,21 @@ +package org.bukkit.util; + +import java.lang.reflect.Array; + +public class Java15Compat { + @SuppressWarnings("unchecked") + public static T[] Arrays_copyOfRange(T[] original, int start, int end) { + if (original.length >= start && 0 <= start) { + if (start <= end) { + int length = end - start; + int copyLength = Math.min(length, original.length - start); + T[] copy = (T[]) Array.newInstance(original.getClass().getComponentType(), length); + + System.arraycopy(original, start, copy, 0, copyLength); + return copy; + } + throw new IllegalArgumentException(); + } + throw new ArrayIndexOutOfBoundsException(); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/util/NumberConversions.java b/azurite-api/src/main/java/org/bukkit/util/NumberConversions.java new file mode 100644 index 0000000..5336bb5 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/util/NumberConversions.java @@ -0,0 +1,118 @@ +package org.bukkit.util; + +/** + * Utils for casting number types to other number types + */ +public final class NumberConversions { + private NumberConversions() {} + + public static int floor(double num) { + final int floor = (int) num; + return floor == num ? floor : floor - (int) (Double.doubleToRawLongBits(num) >>> 63); + } + + public static int ceil(final double num) { + final int floor = (int) num; + return floor == num ? floor : floor + (int) (~Double.doubleToRawLongBits(num) >>> 63); + } + + public static int round(double num) { + return floor(num + 0.5d); + } + + public static double square(double num) { + return num * num; + } + + public static int toInt(Object object) { + if (object instanceof Number) { + return ((Number) object).intValue(); + } + + try { + return Integer.parseInt(object.toString()); + } catch (NumberFormatException | NullPointerException ignored) { + } + return 0; + } + + public static float toFloat(Object object) { + if (object instanceof Number) { + return ((Number) object).floatValue(); + } + + try { + return Float.parseFloat(object.toString()); + } catch (NumberFormatException | NullPointerException ignored) { + } + return 0; + } + + public static double toDouble(Object object) { + if (object instanceof Number) { + return ((Number) object).doubleValue(); + } + + try { + return Double.parseDouble(object.toString()); + } catch (NumberFormatException | NullPointerException ignored) { + } + return 0; + } + + public static long toLong(Object object) { + if (object instanceof Number) { + return ((Number) object).longValue(); + } + + try { + return Long.parseLong(object.toString()); + } catch (NumberFormatException | NullPointerException ignored) { + } + return 0; + } + + public static short toShort(Object object) { + if (object instanceof Number) { + return ((Number) object).shortValue(); + } + + try { + return Short.parseShort(object.toString()); + } catch (NumberFormatException | NullPointerException ignored) { + } + return 0; + } + + public static byte toByte(Object object) { + if (object instanceof Number) { + return ((Number) object).byteValue(); + } + + try { + return Byte.parseByte(object.toString()); + } catch (NumberFormatException | NullPointerException ignored) { + } + return 0; + } + + public static boolean isFinite(double d) { + return Math.abs(d) <= Double.MAX_VALUE; + } + + public static boolean isFinite(float f) { + return Math.abs(f) <= Float.MAX_VALUE; + } + + public static void checkFinite(double d, String message) { + if (!isFinite(d)) { + throw new IllegalArgumentException(message); + } + } + + public static void checkFinite(float d, String message) { + if (!isFinite(d)) { + throw new IllegalArgumentException(message); + } + } +} diff --git a/azurite-api/src/main/java/org/bukkit/util/StringUtil.java b/azurite-api/src/main/java/org/bukkit/util/StringUtil.java new file mode 100644 index 0000000..0e75d18 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/util/StringUtil.java @@ -0,0 +1,59 @@ +package org.bukkit.util; + +import org.apache.commons.lang.Validate; + +import java.util.Collection; + +public class StringUtil { + + /** + * Copies all elements from the iterable collection of originals to the + * collection provided. + * + * @param the collection of strings + * @param token String to search for + * @param originals An iterable collection of strings to filter. + * @param collection The collection to add matches to + * @return the collection provided that would have the elements copied + * into + * @throws UnsupportedOperationException if the collection is immutable + * and originals contains a string which starts with the specified + * search string. + * @throws IllegalArgumentException if any parameter is is null + * @throws IllegalArgumentException if originals contains a null element. + * Note: the collection may be modified before this is thrown + */ + public static > T copyPartialMatches(final String token, final Iterable originals, final T collection) throws UnsupportedOperationException, IllegalArgumentException { + Validate.notNull(token, "Search token cannot be null"); + Validate.notNull(collection, "Collection cannot be null"); + Validate.notNull(originals, "Originals cannot be null"); + + for (String string : originals) { + if (startsWithIgnoreCase(string, token)) { + collection.add(string); + } + } + + return collection; + } + + /** + * This method uses a region to check case-insensitive equality. This + * means the internal array does not need to be copied like a + * toLowerCase() call would. + * + * @param string String to check + * @param prefix Prefix of string to compare + * @return true if provided string starts with, ignoring case, the prefix + * provided + * @throws NullPointerException if prefix is null + * @throws IllegalArgumentException if string is null + */ + public static boolean startsWithIgnoreCase(final String string, final String prefix) throws IllegalArgumentException, NullPointerException { + Validate.notNull(string, "Cannot check a null string for a match"); + if (string.length() < prefix.length()) { + return false; + } + return string.regionMatches(true, 0, prefix, 0, prefix.length()); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/util/Vector.java b/azurite-api/src/main/java/org/bukkit/util/Vector.java new file mode 100644 index 0000000..a631665 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/util/Vector.java @@ -0,0 +1,668 @@ +package org.bukkit.util; + +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.configuration.serialization.ConfigurationSerializable; +import org.bukkit.configuration.serialization.SerializableAs; + +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Random; + +/** + * Represents a mutable vector. Because the components of Vectors are mutable, + * storing Vectors long term may be dangerous if passing code modifies the + * Vector later. If you want to keep around a Vector, it may be wise to call + * clone() in order to get a copy. + */ +@SerializableAs("Vector") +public class Vector implements Cloneable, ConfigurationSerializable { + private static final long serialVersionUID = -2657651106777219169L; + + private static Random random = new Random(); + + /** + * Threshold for fuzzy equals(). + */ + private static final double epsilon = 0.000001; + + protected double x; + protected double y; + protected double z; + + /** + * Construct the vector with all components as 0. + */ + public Vector() { + this.x = 0; + this.y = 0; + this.z = 0; + } + + /** + * Construct the vector with provided integer components. + * + * @param x X component + * @param y Y component + * @param z Z component + */ + public Vector(int x, int y, int z) { + this.x = x; + this.y = y; + this.z = z; + } + + /** + * Construct the vector with provided double components. + * + * @param x X component + * @param y Y component + * @param z Z component + */ + public Vector(double x, double y, double z) { + this.x = x; + this.y = y; + this.z = z; + } + + /** + * Construct the vector with provided float components. + * + * @param x X component + * @param y Y component + * @param z Z component + */ + public Vector(float x, float y, float z) { + this.x = x; + this.y = y; + this.z = z; + } + + /** + * Adds a vector to this one + * + * @param vec The other vector + * @return the same vector + */ + public Vector add(Vector vec) { + x += vec.x; + y += vec.y; + z += vec.z; + return this; + } + + /** + * Subtracts a vector from this one. + * + * @param vec The other vector + * @return the same vector + */ + public Vector subtract(Vector vec) { + x -= vec.x; + y -= vec.y; + z -= vec.z; + return this; + } + + /** + * Multiplies the vector by another. + * + * @param vec The other vector + * @return the same vector + */ + public Vector multiply(Vector vec) { + x *= vec.x; + y *= vec.y; + z *= vec.z; + return this; + } + + /** + * Divides the vector by another. + * + * @param vec The other vector + * @return the same vector + */ + public Vector divide(Vector vec) { + x /= vec.x; + y /= vec.y; + z /= vec.z; + return this; + } + + /** + * Copies another vector + * + * @param vec The other vector + * @return the same vector + */ + public Vector copy(Vector vec) { + x = vec.x; + y = vec.y; + z = vec.z; + return this; + } + + /** + * Gets the magnitude of the vector, defined as sqrt(x^2+y^2+z^2). The + * value of this method is not cached and uses a costly square-root + * function, so do not repeatedly call this method to get the vector's + * magnitude. NaN will be returned if the inner result of the sqrt() + * function overflows, which will be caused if the length is too long. + * + * @return the magnitude + */ + public double length() { + return Math.sqrt(NumberConversions.square(x) + NumberConversions.square(y) + NumberConversions.square(z)); + } + + /** + * Gets the magnitude of the vector squared. + * + * @return the magnitude + */ + public double lengthSquared() { + return NumberConversions.square(x) + NumberConversions.square(y) + NumberConversions.square(z); + } + + /** + * Get the distance between this vector and another. The value of this + * method is not cached and uses a costly square-root function, so do not + * repeatedly call this method to get the vector's magnitude. NaN will be + * returned if the inner result of the sqrt() function overflows, which + * will be caused if the distance is too long. + * + * @param o The other vector + * @return the distance + */ + public double distance(Vector o) { + return Math.sqrt(NumberConversions.square(x - o.x) + NumberConversions.square(y - o.y) + NumberConversions.square(z - o.z)); + } + + /** + * Get the squared distance between this vector and another. + * + * @param o The other vector + * @return the distance + */ + public double distanceSquared(Vector o) { + return NumberConversions.square(x - o.x) + NumberConversions.square(y - o.y) + NumberConversions.square(z - o.z); + } + + /** + * Gets the angle between this vector and another in radians. + * + * @param other The other vector + * @return angle in radians + */ + public float angle(Vector other) { + double dot = dot(other) / (length() * other.length()); + + return (float) Math.acos(dot); + } + + /** + * Sets this vector to the midpoint between this vector and another. + * + * @param other The other vector + * @return this same vector (now a midpoint) + */ + public Vector midpoint(Vector other) { + x = (x + other.x) / 2; + y = (y + other.y) / 2; + z = (z + other.z) / 2; + return this; + } + + /** + * Gets a new midpoint vector between this vector and another. + * + * @param other The other vector + * @return a new midpoint vector + */ + public Vector getMidpoint(Vector other) { + double x = (this.x + other.x) / 2; + double y = (this.y + other.y) / 2; + double z = (this.z + other.z) / 2; + return new Vector(x, y, z); + } + + /** + * Performs scalar multiplication, multiplying all components with a + * scalar. + * + * @param m The factor + * @return the same vector + */ + public Vector multiply(int m) { + x *= m; + y *= m; + z *= m; + return this; + } + + /** + * Performs scalar multiplication, multiplying all components with a + * scalar. + * + * @param m The factor + * @return the same vector + */ + public Vector multiply(double m) { + x *= m; + y *= m; + z *= m; + return this; + } + + /** + * Performs scalar multiplication, multiplying all components with a + * scalar. + * + * @param m The factor + * @return the same vector + */ + public Vector multiply(float m) { + x *= m; + y *= m; + z *= m; + return this; + } + + /** + * Calculates the dot product of this vector with another. The dot product + * is defined as x1*x2+y1*y2+z1*z2. The returned value is a scalar. + * + * @param other The other vector + * @return dot product + */ + public double dot(Vector other) { + return x * other.x + y * other.y + z * other.z; + } + + /** + * Calculates the cross product of this vector with another. The cross + * product is defined as: + *

    + *
  • x = y1 * z2 - y2 * z1 + *
  • y = z1 * x2 - z2 * x1 + *
  • z = x1 * y2 - x2 * y1 + *
+ * + * @param o The other vector + * @return the same vector + */ + public Vector crossProduct(Vector o) { + double newX = y * o.z - o.y * z; + double newY = z * o.x - o.z * x; + double newZ = x * o.y - o.x * y; + + x = newX; + y = newY; + z = newZ; + return this; + } + + /** + * Converts this vector to a unit vector (a vector with length of 1). + * + * @return the same vector + */ + public Vector normalize() { + double length = length(); + + x /= length; + y /= length; + z /= length; + + return this; + } + + /** + * Zero this vector's components. + * + * @return the same vector + */ + public Vector zero() { + x = 0; + y = 0; + z = 0; + return this; + } + + /** + * Returns whether this vector is in an axis-aligned bounding box. + *

+ * The minimum and maximum vectors given must be truly the minimum and + * maximum X, Y and Z components. + * + * @param min Minimum vector + * @param max Maximum vector + * @return whether this vector is in the AABB + */ + public boolean isInAABB(Vector min, Vector max) { + return x >= min.x && x <= max.x && y >= min.y && y <= max.y && z >= min.z && z <= max.z; + } + + /** + * Returns whether this vector is within a sphere. + * + * @param origin Sphere origin. + * @param radius Sphere radius + * @return whether this vector is in the sphere + */ + public boolean isInSphere(Vector origin, double radius) { + return (NumberConversions.square(origin.x - x) + NumberConversions.square(origin.y - y) + NumberConversions.square(origin.z - z)) <= NumberConversions.square(radius); + } + + /** + * Gets the X component. + * + * @return The X component. + */ + public double getX() { + return x; + } + + /** + * Gets the floored value of the X component, indicating the block that + * this vector is contained with. + * + * @return block X + */ + public int getBlockX() { + return NumberConversions.floor(x); + } + + /** + * Gets the Y component. + * + * @return The Y component. + */ + public double getY() { + return y; + } + + /** + * Gets the floored value of the Y component, indicating the block that + * this vector is contained with. + * + * @return block y + */ + public int getBlockY() { + return NumberConversions.floor(y); + } + + /** + * Gets the Z component. + * + * @return The Z component. + */ + public double getZ() { + return z; + } + + /** + * Gets the floored value of the Z component, indicating the block that + * this vector is contained with. + * + * @return block z + */ + public int getBlockZ() { + return NumberConversions.floor(z); + } + + /** + * Set the X component. + * + * @param x The new X component. + * @return This vector. + */ + public Vector setX(int x) { + this.x = x; + return this; + } + + /** + * Set the X component. + * + * @param x The new X component. + * @return This vector. + */ + public Vector setX(double x) { + this.x = x; + return this; + } + + /** + * Set the X component. + * + * @param x The new X component. + * @return This vector. + */ + public Vector setX(float x) { + this.x = x; + return this; + } + + /** + * Set the Y component. + * + * @param y The new Y component. + * @return This vector. + */ + public Vector setY(int y) { + this.y = y; + return this; + } + + /** + * Set the Y component. + * + * @param y The new Y component. + * @return This vector. + */ + public Vector setY(double y) { + this.y = y; + return this; + } + + /** + * Set the Y component. + * + * @param y The new Y component. + * @return This vector. + */ + public Vector setY(float y) { + this.y = y; + return this; + } + + /** + * Set the Z component. + * + * @param z The new Z component. + * @return This vector. + */ + public Vector setZ(int z) { + this.z = z; + return this; + } + + /** + * Set the Z component. + * + * @param z The new Z component. + * @return This vector. + */ + public Vector setZ(double z) { + this.z = z; + return this; + } + + /** + * Set the Z component. + * + * @param z The new Z component. + * @return This vector. + */ + public Vector setZ(float z) { + this.z = z; + return this; + } + + /** + * Checks to see if two objects are equal. + *

+ * Only two Vectors can ever return true. This method uses a fuzzy match + * to account for floating point errors. The epsilon can be retrieved + * with epsilon. + */ + @Override + public boolean equals(Object obj) { + if (!(obj instanceof Vector)) { + return false; + } + + Vector other = (Vector) obj; + + return Math.abs(x - other.x) < epsilon && Math.abs(y - other.y) < epsilon && Math.abs(z - other.z) < epsilon && (this.getClass().equals(obj.getClass())); + } + + /** + * Returns a hash code for this vector + * + * @return hash code + */ + @Override + public int hashCode() { + int hash = 7; + + hash = 79 * hash + (int) (Double.doubleToLongBits(this.x) ^ (Double.doubleToLongBits(this.x) >>> 32)); + hash = 79 * hash + (int) (Double.doubleToLongBits(this.y) ^ (Double.doubleToLongBits(this.y) >>> 32)); + hash = 79 * hash + (int) (Double.doubleToLongBits(this.z) ^ (Double.doubleToLongBits(this.z) >>> 32)); + return hash; + } + + /** + * Get a new vector. + * + * @return vector + */ + @Override + public Vector clone() { + try { + return (Vector) super.clone(); + } catch (CloneNotSupportedException e) { + throw new Error(e); + } + } + + /** + * Returns this vector's components as x,y,z. + */ + @Override + public String toString() { + return x + "," + y + "," + z; + } + + /** + * Gets a Location version of this vector with yaw and pitch being 0. + * + * @param world The world to link the location to. + * @return the location + */ + public Location toLocation(World world) { + return new Location(world, x, y, z); + } + + /** + * Gets a Location version of this vector. + * + * @param world The world to link the location to. + * @param yaw The desired yaw. + * @param pitch The desired pitch. + * @return the location + */ + public Location toLocation(World world, float yaw, float pitch) { + return new Location(world, x, y, z, yaw, pitch); + } + + /** + * Get the block vector of this vector. + * + * @return A block vector. + */ + public BlockVector toBlockVector() { + return new BlockVector(x, y, z); + } + + /** + * Get the threshold used for equals(). + * + * @return The epsilon. + */ + public static double getEpsilon() { + return epsilon; + } + + /** + * Gets the minimum components of two vectors. + * + * @param v1 The first vector. + * @param v2 The second vector. + * @return minimum + */ + public static Vector getMinimum(Vector v1, Vector v2) { + return new Vector(Math.min(v1.x, v2.x), Math.min(v1.y, v2.y), Math.min(v1.z, v2.z)); + } + + /** + * Gets the maximum components of two vectors. + * + * @param v1 The first vector. + * @param v2 The second vector. + * @return maximum + */ + public static Vector getMaximum(Vector v1, Vector v2) { + return new Vector(Math.max(v1.x, v2.x), Math.max(v1.y, v2.y), Math.max(v1.z, v2.z)); + } + + /** + * Gets a random vector with components having a random value between 0 + * and 1. + * + * @return A random vector. + */ + public static Vector getRandom() { + return new Vector(random.nextDouble(), random.nextDouble(), random.nextDouble()); + } + + public Map serialize() { + Map result = new LinkedHashMap(); + + result.put("x", getX()); + result.put("y", getY()); + result.put("z", getZ()); + + return result; + } + + public static Vector deserialize(Map args) { + double x = 0; + double y = 0; + double z = 0; + + if (args.containsKey("x")) { + x = (Double) args.get("x"); + } + if (args.containsKey("y")) { + y = (Double) args.get("y"); + } + if (args.containsKey("z")) { + z = (Double) args.get("z"); + } + + return new Vector(x, y, z); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/util/io/BukkitObjectInputStream.java b/azurite-api/src/main/java/org/bukkit/util/io/BukkitObjectInputStream.java new file mode 100644 index 0000000..4a9fa2a --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/util/io/BukkitObjectInputStream.java @@ -0,0 +1,62 @@ +package org.bukkit.util.io; + +import org.bukkit.configuration.serialization.ConfigurationSerializable; +import org.bukkit.configuration.serialization.ConfigurationSerialization; + +import java.io.IOException; +import java.io.InputStream; +import java.io.ObjectInputStream; + +/** + * This class is designed to be used in conjunction with the {@link + * ConfigurationSerializable} API. It translates objects back to their + * original implementation after being serialized by {@link + * BukkitObjectInputStream}. + *

+ * Behavior of implementations extending this class is not guaranteed across + * future versions. + */ +public class BukkitObjectInputStream extends ObjectInputStream { + + /** + * Constructor provided to mirror super functionality. + * + * @throws IOException if an I/O error occurs while reading stream heade + * @see ObjectInputStream#ObjectInputStream() + */ + protected BukkitObjectInputStream() throws IOException, SecurityException { + super(); + super.enableResolveObject(true); + } + + /** + * Object input stream decoration constructor. + * + * @param in the input stream to wrap + * @throws IOException if an I/O error occurs while reading stream header + * @see ObjectInputStream#ObjectInputStream(InputStream) + */ + public BukkitObjectInputStream(InputStream in) throws IOException { + super(in); + super.enableResolveObject(true); + } + + @Override + protected Object resolveObject(Object obj) throws IOException { + if (obj instanceof Wrapper) { + try { + (obj = ConfigurationSerialization.deserializeObject(((Wrapper) obj).map)).getClass(); // NPE + } catch (Throwable ex) { + throw newIOException("Failed to deserialize object", ex); + } + } + + return super.resolveObject(obj); + } + + private static IOException newIOException(String string, Throwable cause) { + IOException exception = new IOException(string); + exception.initCause(cause); + return exception; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/util/io/BukkitObjectOutputStream.java b/azurite-api/src/main/java/org/bukkit/util/io/BukkitObjectOutputStream.java new file mode 100644 index 0000000..089e010 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/util/io/BukkitObjectOutputStream.java @@ -0,0 +1,52 @@ +package org.bukkit.util.io; + +import org.bukkit.configuration.serialization.ConfigurationSerializable; + +import java.io.IOException; +import java.io.ObjectOutputStream; +import java.io.OutputStream; +import java.io.Serializable; + +/** + * This class is designed to be used in conjunction with the {@link + * ConfigurationSerializable} API. It translates objects to an internal + * implementation for later deserialization using {@link + * BukkitObjectInputStream}. + *

+ * Behavior of implementations extending this class is not guaranteed across + * future versions. + */ +public class BukkitObjectOutputStream extends ObjectOutputStream { + + /** + * Constructor provided to mirror super functionality. + * + * @throws IOException if an I/O error occurs while writing stream header + * @see ObjectOutputStream#ObjectOutputStream() + */ + protected BukkitObjectOutputStream() throws IOException, SecurityException { + super(); + super.enableReplaceObject(true); + } + + /** + * Object output stream decoration constructor. + * + * @param out the stream to wrap + * @throws IOException if an I/O error occurs while writing stream header + * @see ObjectOutputStream#ObjectOutputStream(OutputStream) + */ + public BukkitObjectOutputStream(OutputStream out) throws IOException { + super(out); + super.enableReplaceObject(true); + } + + @Override + protected Object replaceObject(Object obj) throws IOException { + if (!(obj instanceof Serializable) && (obj instanceof ConfigurationSerializable)) { + obj = Wrapper.newWrapper((ConfigurationSerializable) obj); + } + + return super.replaceObject(obj); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/util/io/Wrapper.java b/azurite-api/src/main/java/org/bukkit/util/io/Wrapper.java new file mode 100644 index 0000000..26cf618 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/util/io/Wrapper.java @@ -0,0 +1,22 @@ +package org.bukkit.util.io; + +import com.google.common.collect.ImmutableMap; +import org.bukkit.configuration.serialization.ConfigurationSerializable; +import org.bukkit.configuration.serialization.ConfigurationSerialization; + +import java.io.Serializable; +import java.util.Map; + +class Wrapper & Serializable> implements Serializable { + private static final long serialVersionUID = -986209235411767547L; + + final T map; + + static Wrapper> newWrapper(ConfigurationSerializable obj) { + return new Wrapper>(ImmutableMap.builder().put(ConfigurationSerialization.SERIALIZED_TYPE_KEY, ConfigurationSerialization.getAlias(obj.getClass())).putAll(obj.serialize()).build()); + } + + private Wrapper(T map) { + this.map = map; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/util/noise/NoiseGenerator.java b/azurite-api/src/main/java/org/bukkit/util/noise/NoiseGenerator.java new file mode 100644 index 0000000..72c92f3 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/util/noise/NoiseGenerator.java @@ -0,0 +1,176 @@ +package org.bukkit.util.noise; + +/** + * Base class for all noise generators + */ +public abstract class NoiseGenerator { + protected final int perm[] = new int[512]; + protected double offsetX; + protected double offsetY; + protected double offsetZ; + + /** + * Speedy floor, faster than (int)Math.floor(x) + * + * @param x Value to floor + * @return Floored value + */ + public static int floor(double x) { + return x >= 0 ? (int) x : (int) x - 1; + } + + protected static double fade(double x) { + return x * x * x * (x * (x * 6 - 15) + 10); + } + + protected static double lerp(double x, double y, double z) { + return y + x * (z - y); + } + + protected static double grad(int hash, double x, double y, double z) { + hash &= 15; + double u = hash < 8 ? x : y; + double v = hash < 4 ? y : hash == 12 || hash == 14 ? x : z; + return ((hash & 1) == 0 ? u : -u) + ((hash & 2) == 0 ? v : -v); + } + + /** + * Computes and returns the 1D noise for the given coordinate in 1D space + * + * @param x X coordinate + * @return Noise at given location, from range -1 to 1 + */ + public double noise(double x) { + return noise(x, 0, 0); + } + + /** + * Computes and returns the 2D noise for the given coordinates in 2D space + * + * @param x X coordinate + * @param y Y coordinate + * @return Noise at given location, from range -1 to 1 + */ + public double noise(double x, double y) { + return noise(x, y, 0); + } + + /** + * Computes and returns the 3D noise for the given coordinates in 3D space + * + * @param x X coordinate + * @param y Y coordinate + * @param z Z coordinate + * @return Noise at given location, from range -1 to 1 + */ + public abstract double noise(double x, double y, double z); + + /** + * Generates noise for the 1D coordinates using the specified number of + * octaves and parameters + * + * @param x X-coordinate + * @param octaves Number of octaves to use + * @param frequency How much to alter the frequency by each octave + * @param amplitude How much to alter the amplitude by each octave + * @return Resulting noise + */ + public double noise(double x, int octaves, double frequency, double amplitude) { + return noise(x, 0, 0, octaves, frequency, amplitude); + } + + /** + * Generates noise for the 1D coordinates using the specified number of + * octaves and parameters + * + * @param x X-coordinate + * @param octaves Number of octaves to use + * @param frequency How much to alter the frequency by each octave + * @param amplitude How much to alter the amplitude by each octave + * @param normalized If true, normalize the value to [-1, 1] + * @return Resulting noise + */ + public double noise(double x, int octaves, double frequency, double amplitude, boolean normalized) { + return noise(x, 0, 0, octaves, frequency, amplitude, normalized); + } + + /** + * Generates noise for the 2D coordinates using the specified number of + * octaves and parameters + * + * @param x X-coordinate + * @param y Y-coordinate + * @param octaves Number of octaves to use + * @param frequency How much to alter the frequency by each octave + * @param amplitude How much to alter the amplitude by each octave + * @return Resulting noise + */ + public double noise(double x, double y, int octaves, double frequency, double amplitude) { + return noise(x, y, 0, octaves, frequency, amplitude); + } + + /** + * Generates noise for the 2D coordinates using the specified number of + * octaves and parameters + * + * @param x X-coordinate + * @param y Y-coordinate + * @param octaves Number of octaves to use + * @param frequency How much to alter the frequency by each octave + * @param amplitude How much to alter the amplitude by each octave + * @param normalized If true, normalize the value to [-1, 1] + * @return Resulting noise + */ + public double noise(double x, double y, int octaves, double frequency, double amplitude, boolean normalized) { + return noise(x, y, 0, octaves, frequency, amplitude, normalized); + } + + /** + * Generates noise for the 3D coordinates using the specified number of + * octaves and parameters + * + * @param x X-coordinate + * @param y Y-coordinate + * @param z Z-coordinate + * @param octaves Number of octaves to use + * @param frequency How much to alter the frequency by each octave + * @param amplitude How much to alter the amplitude by each octave + * @return Resulting noise + */ + public double noise(double x, double y, double z, int octaves, double frequency, double amplitude) { + return noise(x, y, z, octaves, frequency, amplitude, false); + } + + /** + * Generates noise for the 3D coordinates using the specified number of + * octaves and parameters + * + * @param x X-coordinate + * @param y Y-coordinate + * @param z Z-coordinate + * @param octaves Number of octaves to use + * @param frequency How much to alter the frequency by each octave + * @param amplitude How much to alter the amplitude by each octave + * @param normalized If true, normalize the value to [-1, 1] + * @return Resulting noise + */ + public double noise(double x, double y, double z, int octaves, double frequency, double amplitude, boolean normalized) { + double result = 0; + double amp = 1; + double freq = 1; + double max = 0; + + for (int i = 0; i < octaves; i++) { + result += noise(x * freq, y * freq, z * freq) * amp; + max += amp; + freq *= frequency; + amp *= amplitude; + } + + if (normalized) { + result /= max; + } + + return result; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/util/noise/OctaveGenerator.java b/azurite-api/src/main/java/org/bukkit/util/noise/OctaveGenerator.java new file mode 100644 index 0000000..a87304b --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/util/noise/OctaveGenerator.java @@ -0,0 +1,199 @@ +package org.bukkit.util.noise; + +/** + * Creates noise using unbiased octaves + */ +public abstract class OctaveGenerator { + protected final NoiseGenerator[] octaves; + protected double xScale = 1; + protected double yScale = 1; + protected double zScale = 1; + + protected OctaveGenerator(NoiseGenerator[] octaves) { + this.octaves = octaves; + } + + /** + * Sets the scale used for all coordinates passed to this generator. + *

+ * This is the equivalent to setting each coordinate to the specified + * value. + * + * @param scale New value to scale each coordinate by + */ + public void setScale(double scale) { + setXScale(scale); + setYScale(scale); + setZScale(scale); + } + + /** + * Gets the scale used for each X-coordinates passed + * + * @return X scale + */ + public double getXScale() { + return xScale; + } + + /** + * Sets the scale used for each X-coordinates passed + * + * @param scale New X scale + */ + public void setXScale(double scale) { + xScale = scale; + } + + /** + * Gets the scale used for each Y-coordinates passed + * + * @return Y scale + */ + public double getYScale() { + return yScale; + } + + /** + * Sets the scale used for each Y-coordinates passed + * + * @param scale New Y scale + */ + public void setYScale(double scale) { + yScale = scale; + } + + /** + * Gets the scale used for each Z-coordinates passed + * + * @return Z scale + */ + public double getZScale() { + return zScale; + } + + /** + * Sets the scale used for each Z-coordinates passed + * + * @param scale New Z scale + */ + public void setZScale(double scale) { + zScale = scale; + } + + /** + * Gets a clone of the individual octaves used within this generator + * + * @return Clone of the individual octaves + */ + public NoiseGenerator[] getOctaves() { + return octaves.clone(); + } + + /** + * Generates noise for the 1D coordinates using the specified number of + * octaves and parameters + * + * @param x X-coordinate + * @param frequency How much to alter the frequency by each octave + * @param amplitude How much to alter the amplitude by each octave + * @return Resulting noise + */ + public double noise(double x, double frequency, double amplitude) { + return noise(x, 0, 0, frequency, amplitude); + } + + /** + * Generates noise for the 1D coordinates using the specified number of + * octaves and parameters + * + * @param x X-coordinate + * @param frequency How much to alter the frequency by each octave + * @param amplitude How much to alter the amplitude by each octave + * @param normalized If true, normalize the value to [-1, 1] + * @return Resulting noise + */ + public double noise(double x, double frequency, double amplitude, boolean normalized) { + return noise(x, 0, 0, frequency, amplitude, normalized); + } + + /** + * Generates noise for the 2D coordinates using the specified number of + * octaves and parameters + * + * @param x X-coordinate + * @param y Y-coordinate + * @param frequency How much to alter the frequency by each octave + * @param amplitude How much to alter the amplitude by each octave + * @return Resulting noise + */ + public double noise(double x, double y, double frequency, double amplitude) { + return noise(x, y, 0, frequency, amplitude); + } + + /** + * Generates noise for the 2D coordinates using the specified number of + * octaves and parameters + * + * @param x X-coordinate + * @param y Y-coordinate + * @param frequency How much to alter the frequency by each octave + * @param amplitude How much to alter the amplitude by each octave + * @param normalized If true, normalize the value to [-1, 1] + * @return Resulting noise + */ + public double noise(double x, double y, double frequency, double amplitude, boolean normalized) { + return noise(x, y, 0, frequency, amplitude, normalized); + } + + /** + * Generates noise for the 3D coordinates using the specified number of + * octaves and parameters + * + * @param x X-coordinate + * @param y Y-coordinate + * @param z Z-coordinate + * @param frequency How much to alter the frequency by each octave + * @param amplitude How much to alter the amplitude by each octave + * @return Resulting noise + */ + public double noise(double x, double y, double z, double frequency, double amplitude) { + return noise(x, y, z, frequency, amplitude, false); + } + + /** + * Generates noise for the 3D coordinates using the specified number of + * octaves and parameters + * + * @param x X-coordinate + * @param y Y-coordinate + * @param z Z-coordinate + * @param frequency How much to alter the frequency by each octave + * @param amplitude How much to alter the amplitude by each octave + * @param normalized If true, normalize the value to [-1, 1] + * @return Resulting noise + */ + public double noise(double x, double y, double z, double frequency, double amplitude, boolean normalized) { + double result = 0; + double amp = 1; + double freq = 1; + double max = 0; + + x *= xScale; + y *= yScale; + z *= zScale; + + for (NoiseGenerator octave : octaves) { + result += octave.noise(x * freq, y * freq, z * freq) * amp; + max += amp; + freq *= frequency; + amp *= amplitude; + } + + if (normalized) { + result /= max; + } + + return result; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/util/noise/PerlinNoiseGenerator.java b/azurite-api/src/main/java/org/bukkit/util/noise/PerlinNoiseGenerator.java new file mode 100644 index 0000000..555da4f --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/util/noise/PerlinNoiseGenerator.java @@ -0,0 +1,218 @@ +package org.bukkit.util.noise; + +import org.bukkit.World; + +import java.util.Random; + +/** + * Generates noise using the "classic" perlin generator + * + * @see SimplexNoiseGenerator "Improved" and faster version with slighly + * different results + */ +public class PerlinNoiseGenerator extends NoiseGenerator { + protected static final int grad3[][] = {{1, 1, 0}, {-1, 1, 0}, {1, -1, 0}, {-1, -1, 0}, + {1, 0, 1}, {-1, 0, 1}, {1, 0, -1}, {-1, 0, -1}, + {0, 1, 1}, {0, -1, 1}, {0, 1, -1}, {0, -1, -1}}; + private static final PerlinNoiseGenerator instance = new PerlinNoiseGenerator(); + + protected PerlinNoiseGenerator() { + int p[] = {151, 160, 137, 91, 90, 15, 131, 13, 201, + 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, + 240, 21, 10, 23, 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, + 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33, 88, 237, 149, 56, + 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, + 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122, 60, 211, 133, + 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54, 65, 25, + 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169, 200, + 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, + 64, 52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, + 82, 85, 212, 207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, + 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, + 101, 155, 167, 43, 172, 9, 129, 22, 39, 253, 19, 98, 108, 110, 79, + 113, 224, 232, 178, 185, 112, 104, 218, 246, 97, 228, 251, 34, 242, + 193, 238, 210, 144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249, + 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157, 184, 84, 204, + 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93, 222, + 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180}; + + for (int i = 0; i < 512; i++) { + perm[i] = p[i & 255]; + } + } + + /** + * Creates a seeded perlin noise generator for the given world + * + * @param world World to construct this generator for + */ + public PerlinNoiseGenerator(World world) { + this(new Random(world.getSeed())); + } + + /** + * Creates a seeded perlin noise generator for the given seed + * + * @param seed Seed to construct this generator for + */ + public PerlinNoiseGenerator(long seed) { + this(new Random(seed)); + } + + /** + * Creates a seeded perlin noise generator with the given Random + * + * @param rand Random to construct with + */ + public PerlinNoiseGenerator(Random rand) { + offsetX = rand.nextDouble() * 256; + offsetY = rand.nextDouble() * 256; + offsetZ = rand.nextDouble() * 256; + + for (int i = 0; i < 256; i++) { + perm[i] = rand.nextInt(256); + } + + for (int i = 0; i < 256; i++) { + int pos = rand.nextInt(256 - i) + i; + int old = perm[i]; + + perm[i] = perm[pos]; + perm[pos] = old; + perm[i + 256] = perm[i]; + } + } + + /** + * Computes and returns the 1D unseeded perlin noise for the given + * coordinates in 1D space + * + * @param x X coordinate + * @return Noise at given location, from range -1 to 1 + */ + public static double getNoise(double x) { + return instance.noise(x); + } + + /** + * Computes and returns the 2D unseeded perlin noise for the given + * coordinates in 2D space + * + * @param x X coordinate + * @param y Y coordinate + * @return Noise at given location, from range -1 to 1 + */ + public static double getNoise(double x, double y) { + return instance.noise(x, y); + } + + /** + * Computes and returns the 3D unseeded perlin noise for the given + * coordinates in 3D space + * + * @param x X coordinate + * @param y Y coordinate + * @param z Z coordinate + * @return Noise at given location, from range -1 to 1 + */ + public static double getNoise(double x, double y, double z) { + return instance.noise(x, y, z); + } + + /** + * Gets the singleton unseeded instance of this generator + * + * @return Singleton + */ + public static PerlinNoiseGenerator getInstance() { + return instance; + } + + @Override + public double noise(double x, double y, double z) { + x += offsetX; + y += offsetY; + z += offsetZ; + + int floorX = floor(x); + int floorY = floor(y); + int floorZ = floor(z); + + // Find unit cube containing the point + int X = floorX & 255; + int Y = floorY & 255; + int Z = floorZ & 255; + + // Get relative xyz coordinates of the point within the cube + x -= floorX; + y -= floorY; + z -= floorZ; + + // Compute fade curves for xyz + double fX = fade(x); + double fY = fade(y); + double fZ = fade(z); + + // Hash coordinates of the cube corners + int A = perm[X] + Y; + int AA = perm[A] + Z; + int AB = perm[A + 1] + Z; + int B = perm[X + 1] + Y; + int BA = perm[B] + Z; + int BB = perm[B + 1] + Z; + + return lerp(fZ, lerp(fY, lerp(fX, grad(perm[AA], x, y, z), + grad(perm[BA], x - 1, y, z)), + lerp(fX, grad(perm[AB], x, y - 1, z), + grad(perm[BB], x - 1, y - 1, z))), + lerp(fY, lerp(fX, grad(perm[AA + 1], x, y, z - 1), + grad(perm[BA + 1], x - 1, y, z - 1)), + lerp(fX, grad(perm[AB + 1], x, y - 1, z - 1), + grad(perm[BB + 1], x - 1, y - 1, z - 1)))); + } + + /** + * Generates noise for the 1D coordinates using the specified number of + * octaves and parameters + * + * @param x X-coordinate + * @param octaves Number of octaves to use + * @param frequency How much to alter the frequency by each octave + * @param amplitude How much to alter the amplitude by each octave + * @return Resulting noise + */ + public static double getNoise(double x, int octaves, double frequency, double amplitude) { + return instance.noise(x, octaves, frequency, amplitude); + } + + /** + * Generates noise for the 2D coordinates using the specified number of + * octaves and parameters + * + * @param x X-coordinate + * @param y Y-coordinate + * @param octaves Number of octaves to use + * @param frequency How much to alter the frequency by each octave + * @param amplitude How much to alter the amplitude by each octave + * @return Resulting noise + */ + public static double getNoise(double x, double y, int octaves, double frequency, double amplitude) { + return instance.noise(x, y, octaves, frequency, amplitude); + } + + /** + * Generates noise for the 3D coordinates using the specified number of + * octaves and parameters + * + * @param x X-coordinate + * @param y Y-coordinate + * @param z Z-coordinate + * @param octaves Number of octaves to use + * @param frequency How much to alter the frequency by each octave + * @param amplitude How much to alter the amplitude by each octave + * @return Resulting noise + */ + public static double getNoise(double x, double y, double z, int octaves, double frequency, double amplitude) { + return instance.noise(x, y, z, octaves, frequency, amplitude); + } +} diff --git a/azurite-api/src/main/java/org/bukkit/util/noise/PerlinOctaveGenerator.java b/azurite-api/src/main/java/org/bukkit/util/noise/PerlinOctaveGenerator.java new file mode 100644 index 0000000..695e4bc --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/util/noise/PerlinOctaveGenerator.java @@ -0,0 +1,51 @@ +package org.bukkit.util.noise; + +import org.bukkit.World; + +import java.util.Random; + +/** + * Creates perlin noise through unbiased octaves + */ +public class PerlinOctaveGenerator extends OctaveGenerator { + + /** + * Creates a perlin octave generator for the given world + * + * @param world World to construct this generator for + * @param octaves Amount of octaves to create + */ + public PerlinOctaveGenerator(World world, int octaves) { + this(new Random(world.getSeed()), octaves); + } + + /** + * Creates a perlin octave generator for the given world + * + * @param seed Seed to construct this generator for + * @param octaves Amount of octaves to create + */ + public PerlinOctaveGenerator(long seed, int octaves) { + this(new Random(seed), octaves); + } + + /** + * Creates a perlin octave generator for the given {@link Random} + * + * @param rand Random object to construct this generator for + * @param octaves Amount of octaves to create + */ + public PerlinOctaveGenerator(Random rand, int octaves) { + super(createOctaves(rand, octaves)); + } + + private static NoiseGenerator[] createOctaves(Random rand, int octaves) { + NoiseGenerator[] result = new NoiseGenerator[octaves]; + + for (int i = 0; i < octaves; i++) { + result[i] = new PerlinNoiseGenerator(rand); + } + + return result; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/util/noise/SimplexNoiseGenerator.java b/azurite-api/src/main/java/org/bukkit/util/noise/SimplexNoiseGenerator.java new file mode 100644 index 0000000..72c4b8f --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/util/noise/SimplexNoiseGenerator.java @@ -0,0 +1,521 @@ +package org.bukkit.util.noise; + +import org.bukkit.World; + +import java.util.Random; + +/** + * Generates simplex-based noise. + *

+ * This is a modified version of the freely published version in the paper by + * Stefan Gustavson at + * + * http://staffwww.itn.liu.se/~stegu/simplexnoise/simplexnoise.pdf + */ +public class SimplexNoiseGenerator extends PerlinNoiseGenerator { + protected static final double SQRT_3 = Math.sqrt(3); + protected static final double SQRT_5 = Math.sqrt(5); + protected static final double F2 = 0.5 * (SQRT_3 - 1); + protected static final double G2 = (3 - SQRT_3) / 6; + protected static final double G22 = G2 * 2.0 - 1; + protected static final double F3 = 1.0 / 3.0; + protected static final double G3 = 1.0 / 6.0; + protected static final double F4 = (SQRT_5 - 1.0) / 4.0; + protected static final double G4 = (5.0 - SQRT_5) / 20.0; + protected static final double G42 = G4 * 2.0; + protected static final double G43 = G4 * 3.0; + protected static final double G44 = G4 * 4.0 - 1.0; + protected static final int grad4[][] = {{0, 1, 1, 1}, {0, 1, 1, -1}, {0, 1, -1, 1}, {0, 1, -1, -1}, + {0, -1, 1, 1}, {0, -1, 1, -1}, {0, -1, -1, 1}, {0, -1, -1, -1}, + {1, 0, 1, 1}, {1, 0, 1, -1}, {1, 0, -1, 1}, {1, 0, -1, -1}, + {-1, 0, 1, 1}, {-1, 0, 1, -1}, {-1, 0, -1, 1}, {-1, 0, -1, -1}, + {1, 1, 0, 1}, {1, 1, 0, -1}, {1, -1, 0, 1}, {1, -1, 0, -1}, + {-1, 1, 0, 1}, {-1, 1, 0, -1}, {-1, -1, 0, 1}, {-1, -1, 0, -1}, + {1, 1, 1, 0}, {1, 1, -1, 0}, {1, -1, 1, 0}, {1, -1, -1, 0}, + {-1, 1, 1, 0}, {-1, 1, -1, 0}, {-1, -1, 1, 0}, {-1, -1, -1, 0}}; + protected static final int simplex[][] = { + {0, 1, 2, 3}, {0, 1, 3, 2}, {0, 0, 0, 0}, {0, 2, 3, 1}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {1, 2, 3, 0}, + {0, 2, 1, 3}, {0, 0, 0, 0}, {0, 3, 1, 2}, {0, 3, 2, 1}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {1, 3, 2, 0}, + {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, + {1, 2, 0, 3}, {0, 0, 0, 0}, {1, 3, 0, 2}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {2, 3, 0, 1}, {2, 3, 1, 0}, + {1, 0, 2, 3}, {1, 0, 3, 2}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {2, 0, 3, 1}, {0, 0, 0, 0}, {2, 1, 3, 0}, + {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, + {2, 0, 1, 3}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {3, 0, 1, 2}, {3, 0, 2, 1}, {0, 0, 0, 0}, {3, 1, 2, 0}, + {2, 1, 0, 3}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {3, 1, 0, 2}, {0, 0, 0, 0}, {3, 2, 0, 1}, {3, 2, 1, 0}}; + protected static double offsetW; + private static final SimplexNoiseGenerator instance = new SimplexNoiseGenerator(); + + protected SimplexNoiseGenerator() { + super(); + } + + /** + * Creates a seeded simplex noise generator for the given world + * + * @param world World to construct this generator for + */ + public SimplexNoiseGenerator(World world) { + this(new Random(world.getSeed())); + } + + /** + * Creates a seeded simplex noise generator for the given seed + * + * @param seed Seed to construct this generator for + */ + public SimplexNoiseGenerator(long seed) { + this(new Random(seed)); + } + + /** + * Creates a seeded simplex noise generator with the given Random + * + * @param rand Random to construct with + */ + public SimplexNoiseGenerator(Random rand) { + super(rand); + offsetW = rand.nextDouble() * 256; + } + + protected static double dot(int g[], double x, double y) { + return g[0] * x + g[1] * y; + } + + protected static double dot(int g[], double x, double y, double z) { + return g[0] * x + g[1] * y + g[2] * z; + } + + protected static double dot(int g[], double x, double y, double z, double w) { + return g[0] * x + g[1] * y + g[2] * z + g[3] * w; + } + + /** + * Computes and returns the 1D unseeded simplex noise for the given + * coordinates in 1D space + * + * @param xin X coordinate + * @return Noise at given location, from range -1 to 1 + */ + public static double getNoise(double xin) { + return instance.noise(xin); + } + + /** + * Computes and returns the 2D unseeded simplex noise for the given + * coordinates in 2D space + * + * @param xin X coordinate + * @param yin Y coordinate + * @return Noise at given location, from range -1 to 1 + */ + public static double getNoise(double xin, double yin) { + return instance.noise(xin, yin); + } + + /** + * Computes and returns the 3D unseeded simplex noise for the given + * coordinates in 3D space + * + * @param xin X coordinate + * @param yin Y coordinate + * @param zin Z coordinate + * @return Noise at given location, from range -1 to 1 + */ + public static double getNoise(double xin, double yin, double zin) { + return instance.noise(xin, yin, zin); + } + + /** + * Computes and returns the 4D simplex noise for the given coordinates in + * 4D space + * + * @param x X coordinate + * @param y Y coordinate + * @param z Z coordinate + * @param w W coordinate + * @return Noise at given location, from range -1 to 1 + */ + public static double getNoise(double x, double y, double z, double w) { + return instance.noise(x, y, z, w); + } + + @Override + public double noise(double xin, double yin, double zin) { + xin += offsetX; + yin += offsetY; + zin += offsetZ; + + double n0, n1, n2, n3; // Noise contributions from the four corners + + // Skew the input space to determine which simplex cell we're in + double s = (xin + yin + zin) * F3; // Very nice and simple skew factor for 3D + int i = floor(xin + s); + int j = floor(yin + s); + int k = floor(zin + s); + double t = (i + j + k) * G3; + double X0 = i - t; // Unskew the cell origin back to (x,y,z) space + double Y0 = j - t; + double Z0 = k - t; + double x0 = xin - X0; // The x,y,z distances from the cell origin + double y0 = yin - Y0; + double z0 = zin - Z0; + + // For the 3D case, the simplex shape is a slightly irregular tetrahedron. + + // Determine which simplex we are in. + int i1, j1, k1; // Offsets for second corner of simplex in (i,j,k) coords + int i2, j2, k2; // Offsets for third corner of simplex in (i,j,k) coords + if (x0 >= y0) { + if (y0 >= z0) { + i1 = 1; + j1 = 0; + k1 = 0; + i2 = 1; + j2 = 1; + k2 = 0; + } // X Y Z order + else if (x0 >= z0) { + i1 = 1; + j1 = 0; + k1 = 0; + i2 = 1; + j2 = 0; + k2 = 1; + } // X Z Y order + else { + i1 = 0; + j1 = 0; + k1 = 1; + i2 = 1; + j2 = 0; + k2 = 1; + } // Z X Y order + } else { // x0 y0) { + i1 = 1; + j1 = 0; + } // lower triangle, XY order: (0,0)->(1,0)->(1,1) + else { + i1 = 0; + j1 = 1; + } // upper triangle, YX order: (0,0)->(0,1)->(1,1) + + // A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and + // a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where + // c = (3-sqrt(3))/6 + + double x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords + double y1 = y0 - j1 + G2; + double x2 = x0 + G22; // Offsets for last corner in (x,y) unskewed coords + double y2 = y0 + G22; + + // Work out the hashed gradient indices of the three simplex corners + int ii = i & 255; + int jj = j & 255; + int gi0 = perm[ii + perm[jj]] % 12; + int gi1 = perm[ii + i1 + perm[jj + j1]] % 12; + int gi2 = perm[ii + 1 + perm[jj + 1]] % 12; + + // Calculate the contribution from the three corners + double t0 = 0.5 - x0 * x0 - y0 * y0; + if (t0 < 0) { + n0 = 0.0; + } else { + t0 *= t0; + n0 = t0 * t0 * dot(grad3[gi0], x0, y0); // (x,y) of grad3 used for 2D gradient + } + + double t1 = 0.5 - x1 * x1 - y1 * y1; + if (t1 < 0) { + n1 = 0.0; + } else { + t1 *= t1; + n1 = t1 * t1 * dot(grad3[gi1], x1, y1); + } + + double t2 = 0.5 - x2 * x2 - y2 * y2; + if (t2 < 0) { + n2 = 0.0; + } else { + t2 *= t2; + n2 = t2 * t2 * dot(grad3[gi2], x2, y2); + } + + // Add contributions from each corner to get the final noise value. + // The result is scaled to return values in the interval [-1,1]. + return 70.0 * (n0 + n1 + n2); + } + + /** + * Computes and returns the 4D simplex noise for the given coordinates in + * 4D space + * + * @param x X coordinate + * @param y Y coordinate + * @param z Z coordinate + * @param w W coordinate + * @return Noise at given location, from range -1 to 1 + */ + public double noise(double x, double y, double z, double w) { + x += offsetX; + y += offsetY; + z += offsetZ; + w += offsetW; + + double n0, n1, n2, n3, n4; // Noise contributions from the five corners + + // Skew the (x,y,z,w) space to determine which cell of 24 simplices we're in + double s = (x + y + z + w) * F4; // Factor for 4D skewing + int i = floor(x + s); + int j = floor(y + s); + int k = floor(z + s); + int l = floor(w + s); + + double t = (i + j + k + l) * G4; // Factor for 4D unskewing + double X0 = i - t; // Unskew the cell origin back to (x,y,z,w) space + double Y0 = j - t; + double Z0 = k - t; + double W0 = l - t; + double x0 = x - X0; // The x,y,z,w distances from the cell origin + double y0 = y - Y0; + double z0 = z - Z0; + double w0 = w - W0; + + // For the 4D case, the simplex is a 4D shape I won't even try to describe. + // To find out which of the 24 possible simplices we're in, we need to + // determine the magnitude ordering of x0, y0, z0 and w0. + // The method below is a good way of finding the ordering of x,y,z,w and + // then find the correct traversal order for the simplex we’re in. + // First, six pair-wise comparisons are performed between each possible pair + // of the four coordinates, and the results are used to add up binary bits + // for an integer index. + int c1 = (x0 > y0) ? 32 : 0; + int c2 = (x0 > z0) ? 16 : 0; + int c3 = (y0 > z0) ? 8 : 0; + int c4 = (x0 > w0) ? 4 : 0; + int c5 = (y0 > w0) ? 2 : 0; + int c6 = (z0 > w0) ? 1 : 0; + int c = c1 + c2 + c3 + c4 + c5 + c6; + int i1, j1, k1, l1; // The integer offsets for the second simplex corner + int i2, j2, k2, l2; // The integer offsets for the third simplex corner + int i3, j3, k3, l3; // The integer offsets for the fourth simplex corner + + // simplex[c] is a 4-vector with the numbers 0, 1, 2 and 3 in some order. + // Many values of c will never occur, since e.g. x>y>z>w makes x= 3 ? 1 : 0; + j1 = simplex[c][1] >= 3 ? 1 : 0; + k1 = simplex[c][2] >= 3 ? 1 : 0; + l1 = simplex[c][3] >= 3 ? 1 : 0; + + // The number 2 in the "simplex" array is at the second largest coordinate. + i2 = simplex[c][0] >= 2 ? 1 : 0; + j2 = simplex[c][1] >= 2 ? 1 : 0; + k2 = simplex[c][2] >= 2 ? 1 : 0; + l2 = simplex[c][3] >= 2 ? 1 : 0; + + // The number 1 in the "simplex" array is at the second smallest coordinate. + i3 = simplex[c][0] >= 1 ? 1 : 0; + j3 = simplex[c][1] >= 1 ? 1 : 0; + k3 = simplex[c][2] >= 1 ? 1 : 0; + l3 = simplex[c][3] >= 1 ? 1 : 0; + + // The fifth corner has all coordinate offsets = 1, so no need to look that up. + + double x1 = x0 - i1 + G4; // Offsets for second corner in (x,y,z,w) coords + double y1 = y0 - j1 + G4; + double z1 = z0 - k1 + G4; + double w1 = w0 - l1 + G4; + + double x2 = x0 - i2 + G42; // Offsets for third corner in (x,y,z,w) coords + double y2 = y0 - j2 + G42; + double z2 = z0 - k2 + G42; + double w2 = w0 - l2 + G42; + + double x3 = x0 - i3 + G43; // Offsets for fourth corner in (x,y,z,w) coords + double y3 = y0 - j3 + G43; + double z3 = z0 - k3 + G43; + double w3 = w0 - l3 + G43; + + double x4 = x0 + G44; // Offsets for last corner in (x,y,z,w) coords + double y4 = y0 + G44; + double z4 = z0 + G44; + double w4 = w0 + G44; + + // Work out the hashed gradient indices of the five simplex corners + int ii = i & 255; + int jj = j & 255; + int kk = k & 255; + int ll = l & 255; + + int gi0 = perm[ii + perm[jj + perm[kk + perm[ll]]]] % 32; + int gi1 = perm[ii + i1 + perm[jj + j1 + perm[kk + k1 + perm[ll + l1]]]] % 32; + int gi2 = perm[ii + i2 + perm[jj + j2 + perm[kk + k2 + perm[ll + l2]]]] % 32; + int gi3 = perm[ii + i3 + perm[jj + j3 + perm[kk + k3 + perm[ll + l3]]]] % 32; + int gi4 = perm[ii + 1 + perm[jj + 1 + perm[kk + 1 + perm[ll + 1]]]] % 32; + + // Calculate the contribution from the five corners + double t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0 - w0 * w0; + if (t0 < 0) { + n0 = 0.0; + } else { + t0 *= t0; + n0 = t0 * t0 * dot(grad4[gi0], x0, y0, z0, w0); + } + + double t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1 - w1 * w1; + if (t1 < 0) { + n1 = 0.0; + } else { + t1 *= t1; + n1 = t1 * t1 * dot(grad4[gi1], x1, y1, z1, w1); + } + + double t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2 - w2 * w2; + if (t2 < 0) { + n2 = 0.0; + } else { + t2 *= t2; + n2 = t2 * t2 * dot(grad4[gi2], x2, y2, z2, w2); + } + + double t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3 - w3 * w3; + if (t3 < 0) { + n3 = 0.0; + } else { + t3 *= t3; + n3 = t3 * t3 * dot(grad4[gi3], x3, y3, z3, w3); + } + + double t4 = 0.6 - x4 * x4 - y4 * y4 - z4 * z4 - w4 * w4; + if (t4 < 0) { + n4 = 0.0; + } else { + t4 *= t4; + n4 = t4 * t4 * dot(grad4[gi4], x4, y4, z4, w4); + } + + // Sum up and scale the result to cover the range [-1,1] + return 27.0 * (n0 + n1 + n2 + n3 + n4); + } + + /** + * Gets the singleton unseeded instance of this generator + * + * @return Singleton + */ + public static SimplexNoiseGenerator getInstance() { + return instance; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/util/noise/SimplexOctaveGenerator.java b/azurite-api/src/main/java/org/bukkit/util/noise/SimplexOctaveGenerator.java new file mode 100644 index 0000000..243c3a5 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/util/noise/SimplexOctaveGenerator.java @@ -0,0 +1,130 @@ +package org.bukkit.util.noise; + +import org.bukkit.World; + +import java.util.Random; + +/** + * Creates simplex noise through unbiased octaves + */ +public class SimplexOctaveGenerator extends OctaveGenerator { + private double wScale = 1; + + /** + * Creates a simplex octave generator for the given world + * + * @param world World to construct this generator for + * @param octaves Amount of octaves to create + */ + public SimplexOctaveGenerator(World world, int octaves) { + this(new Random(world.getSeed()), octaves); + } + + /** + * Creates a simplex octave generator for the given world + * + * @param seed Seed to construct this generator for + * @param octaves Amount of octaves to create + */ + public SimplexOctaveGenerator(long seed, int octaves) { + this(new Random(seed), octaves); + } + + /** + * Creates a simplex octave generator for the given {@link Random} + * + * @param rand Random object to construct this generator for + * @param octaves Amount of octaves to create + */ + public SimplexOctaveGenerator(Random rand, int octaves) { + super(createOctaves(rand, octaves)); + } + + @Override + public void setScale(double scale) { + super.setScale(scale); + setWScale(scale); + } + + /** + * Gets the scale used for each W-coordinates passed + * + * @return W scale + */ + public double getWScale() { + return wScale; + } + + /** + * Sets the scale used for each W-coordinates passed + * + * @param scale New W scale + */ + public void setWScale(double scale) { + wScale = scale; + } + + /** + * Generates noise for the 3D coordinates using the specified number of + * octaves and parameters + * + * @param x X-coordinate + * @param y Y-coordinate + * @param z Z-coordinate + * @param w W-coordinate + * @param frequency How much to alter the frequency by each octave + * @param amplitude How much to alter the amplitude by each octave + * @return Resulting noise + */ + public double noise(double x, double y, double z, double w, double frequency, double amplitude) { + return noise(x, y, z, w, frequency, amplitude, false); + } + + /** + * Generates noise for the 3D coordinates using the specified number of + * octaves and parameters + * + * @param x X-coordinate + * @param y Y-coordinate + * @param z Z-coordinate + * @param w W-coordinate + * @param frequency How much to alter the frequency by each octave + * @param amplitude How much to alter the amplitude by each octave + * @param normalized If true, normalize the value to [-1, 1] + * @return Resulting noise + */ + public double noise(double x, double y, double z, double w, double frequency, double amplitude, boolean normalized) { + double result = 0; + double amp = 1; + double freq = 1; + double max = 0; + + x *= xScale; + y *= yScale; + z *= zScale; + w *= wScale; + + for (NoiseGenerator octave : octaves) { + result += ((SimplexNoiseGenerator) octave).noise(x * freq, y * freq, z * freq, w * freq) * amp; + max += amp; + freq *= frequency; + amp *= amplitude; + } + + if (normalized) { + result /= max; + } + + return result; + } + + private static NoiseGenerator[] createOctaves(Random rand, int octaves) { + NoiseGenerator[] result = new NoiseGenerator[octaves]; + + for (int i = 0; i < octaves; i++) { + result[i] = new SimplexNoiseGenerator(rand); + } + + return result; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/util/permissions/BroadcastPermissions.java b/azurite-api/src/main/java/org/bukkit/util/permissions/BroadcastPermissions.java new file mode 100644 index 0000000..092370e --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/util/permissions/BroadcastPermissions.java @@ -0,0 +1,22 @@ +package org.bukkit.util.permissions; + +import org.bukkit.permissions.Permission; +import org.bukkit.permissions.PermissionDefault; + +public final class BroadcastPermissions { + private static final String ROOT = "bukkit.broadcast"; + private static final String PREFIX = ROOT + "."; + + private BroadcastPermissions() {} + + public static Permission registerPermissions(Permission parent) { + Permission broadcasts = DefaultPermissions.registerPermission(ROOT, "Allows the user to receive all broadcast messages", parent); + + DefaultPermissions.registerPermission(PREFIX + "admin", "Allows the user to receive administrative broadcasts", PermissionDefault.OP, broadcasts); + DefaultPermissions.registerPermission(PREFIX + "user", "Allows the user to receive user broadcasts", PermissionDefault.TRUE, broadcasts); + + broadcasts.recalculatePermissibles(); + + return broadcasts; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/util/permissions/CommandPermissions.java b/azurite-api/src/main/java/org/bukkit/util/permissions/CommandPermissions.java new file mode 100644 index 0000000..619646e --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/util/permissions/CommandPermissions.java @@ -0,0 +1,23 @@ +package org.bukkit.util.permissions; + +import org.bukkit.permissions.Permission; +import org.bukkit.permissions.PermissionDefault; + +public final class CommandPermissions { + private static final String ROOT = "bukkit.command"; + private static final String PREFIX = ROOT + "."; + + private CommandPermissions() {} + + public static Permission registerPermissions(Permission parent) { + Permission commands = DefaultPermissions.registerPermission(ROOT, "Gives the user the ability to use all CraftBukkit commands", parent); + + DefaultPermissions.registerPermission(PREFIX + "help", "Allows the user to view the vanilla help menu", PermissionDefault.TRUE, commands); + DefaultPermissions.registerPermission(PREFIX + "plugins", "Allows the user to view the list of plugins running on this server", PermissionDefault.TRUE, commands); + DefaultPermissions.registerPermission(PREFIX + "reload", "Allows the user to reload the server settings", PermissionDefault.OP, commands); + DefaultPermissions.registerPermission(PREFIX + "version", "Allows the user to view the version of the server", PermissionDefault.TRUE, commands); + + commands.recalculatePermissibles(); + return commands; + } +} diff --git a/azurite-api/src/main/java/org/bukkit/util/permissions/DefaultPermissions.java b/azurite-api/src/main/java/org/bukkit/util/permissions/DefaultPermissions.java new file mode 100644 index 0000000..4646fc3 --- /dev/null +++ b/azurite-api/src/main/java/org/bukkit/util/permissions/DefaultPermissions.java @@ -0,0 +1,83 @@ +package org.bukkit.util.permissions; + +import org.bukkit.Bukkit; +import org.bukkit.permissions.Permission; +import org.bukkit.permissions.PermissionDefault; + +import java.util.Map; + +public final class DefaultPermissions { + private static final String ROOT = "craftbukkit"; + private static final String LEGACY_PREFIX = "craft"; + + private DefaultPermissions() {} + + public static Permission registerPermission(Permission perm) { + return registerPermission(perm, true); + } + + public static Permission registerPermission(Permission perm, boolean withLegacy) { + Permission result = perm; + + try { + Bukkit.getPluginManager().addPermission(perm); + } catch (IllegalArgumentException ex) { + result = Bukkit.getPluginManager().getPermission(perm.getName()); + } + + if (withLegacy) { + Permission legacy = new Permission(LEGACY_PREFIX + result.getName(), result.getDescription(), PermissionDefault.FALSE); + legacy.getChildren().put(result.getName(), true); + registerPermission(perm, false); + } + + return result; + } + + public static Permission registerPermission(Permission perm, Permission parent) { + parent.getChildren().put(perm.getName(), true); + return registerPermission(perm); + } + + public static Permission registerPermission(String name, String desc) { + Permission perm = registerPermission(new Permission(name, desc)); + return perm; + } + + public static Permission registerPermission(String name, String desc, Permission parent) { + Permission perm = registerPermission(name, desc); + parent.getChildren().put(perm.getName(), true); + return perm; + } + + public static Permission registerPermission(String name, String desc, PermissionDefault def) { + Permission perm = registerPermission(new Permission(name, desc, def)); + return perm; + } + + public static Permission registerPermission(String name, String desc, PermissionDefault def, Permission parent) { + Permission perm = registerPermission(name, desc, def); + parent.getChildren().put(perm.getName(), true); + return perm; + } + + public static Permission registerPermission(String name, String desc, PermissionDefault def, Map children) { + Permission perm = registerPermission(new Permission(name, desc, def, children)); + return perm; + } + + public static Permission registerPermission(String name, String desc, PermissionDefault def, Map children, Permission parent) { + Permission perm = registerPermission(name, desc, def, children); + parent.getChildren().put(perm.getName(), true); + return perm; + } + + public static void registerCorePermissions() { + Permission parent = registerPermission(ROOT, "Gives the user the ability to use all CraftBukkit utilities and commands"); + + CommandPermissions.registerPermissions(parent); + BroadcastPermissions.registerPermissions(parent); + + parent.recalculatePermissibles(); + } +} diff --git a/azurite-api/src/main/java/org/github/paperspigot/Title.java b/azurite-api/src/main/java/org/github/paperspigot/Title.java new file mode 100644 index 0000000..29f3cfb --- /dev/null +++ b/azurite-api/src/main/java/org/github/paperspigot/Title.java @@ -0,0 +1,355 @@ +package org.github.paperspigot; + +import net.md_5.bungee.api.chat.BaseComponent; +import net.md_5.bungee.api.chat.TextComponent; +import org.bukkit.entity.Player; + +import static com.google.common.base.Preconditions.*; + +/** + * Represents a title to may be sent to a {@link Player}. + *

+ *

A title can be sent without subtitle text.

+ */ +public final class Title { + + /** + * The default number of ticks for the title to fade in. + */ + public static final int DEFAULT_FADE_IN = 20; + /** + * The default number of ticks for the title to stay. + */ + public static final int DEFAULT_STAY = 200; + /** + * The default number of ticks for the title to fade out. + */ + public static final int DEFAULT_FADE_OUT = 20; + + private final BaseComponent[] title; + private final BaseComponent[] subtitle; + private final int fadeIn; + private final int stay; + private final int fadeOut; + + /** + * Create a title with the default time values and no subtitle. + *

+ *

Times use default values.

+ * + * @param title the main text of the title + * @throws NullPointerException if the title is null + */ + public Title(BaseComponent title) { + this(title, null); + } + + /** + * Create a title with the default time values and no subtitle. + *

+ *

Times use default values.

+ * + * @param title the main text of the title + * @throws NullPointerException if the title is null + */ + public Title(BaseComponent[] title) { + this(title, null); + } + + /** + * Create a title with the default time values and no subtitle. + *

+ *

Times use default values.

+ * + * @param title the main text of the title + * @throws NullPointerException if the title is null + */ + public Title(String title) { + this(title, null); + } + + /** + * Create a title with the default time values. + *

+ *

Times use default values.

+ * + * @param title the main text of the title + * @param subtitle the secondary text of the title + */ + public Title(BaseComponent title, BaseComponent subtitle) { + this(title, subtitle, DEFAULT_FADE_IN, DEFAULT_STAY, DEFAULT_FADE_OUT); + } + + /** + * Create a title with the default time values. + *

+ *

Times use default values.

+ * + * @param title the main text of the title + * @param subtitle the secondary text of the title + */ + public Title(BaseComponent[] title, BaseComponent[] subtitle) { + this(title, subtitle, DEFAULT_FADE_IN, DEFAULT_STAY, DEFAULT_FADE_OUT); + } + + /** + * Create a title with the default time values. + *

+ *

Times use default values.

+ * + * @param title the main text of the title + * @param subtitle the secondary text of the title + */ + public Title(String title, String subtitle) { + this(title, subtitle, DEFAULT_FADE_IN, DEFAULT_STAY, DEFAULT_FADE_OUT); + } + + /** + * Creates a new title. + * + * @param title the main text of the title + * @param subtitle the secondary text of the title + * @param fadeIn the number of ticks for the title to fade in + * @param stay the number of ticks for the title to stay on screen + * @param fadeOut the number of ticks for the title to fade out + * @throws IllegalArgumentException if any of the times are negative + */ + public Title(BaseComponent title, BaseComponent subtitle, int fadeIn, int stay, int fadeOut) { + this( + new BaseComponent[]{checkNotNull(title, "title")}, + subtitle == null ? null : new BaseComponent[]{subtitle}, + fadeIn, + stay, + fadeOut + ); + } + + /** + * Creates a new title. + * + * @param title the main text of the title + * @param subtitle the secondary text of the title + * @param fadeIn the number of ticks for the title to fade in + * @param stay the number of ticks for the title to stay on screen + * @param fadeOut the number of ticks for the title to fade out + * @throws IllegalArgumentException if any of the times are negative + */ + public Title(BaseComponent[] title, BaseComponent[] subtitle, int fadeIn, int stay, int fadeOut) { + checkArgument(fadeIn >= 0, "Negative fadeIn: %s", fadeIn); + checkArgument(stay >= 0, "Negative stay: %s", stay); + checkArgument(fadeOut >= 0, "Negative fadeOut: %s", fadeOut); + this.title = checkNotNull(title, "title"); + this.subtitle = subtitle; + this.fadeIn = fadeIn; + this.stay = stay; + this.fadeOut = fadeOut; + } + + /** + * Creates a new title. + *

+ *

It is recommended to the {@link BaseComponent} constrctors.

+ * + * @param title the main text of the title + * @param subtitle the secondary text of the title + * @param fadeIn the number of ticks for the title to fade in + * @param stay the number of ticks for the title to stay on screen + * @param fadeOut the number of ticks for the title to fade out + */ + public Title(String title, String subtitle, int fadeIn, int stay, int fadeOut) { + this( + TextComponent.fromLegacyText(checkNotNull(title, "title")), + subtitle == null ? null : TextComponent.fromLegacyText(subtitle), + fadeIn, + stay, + fadeOut + ); + } + + /** + * Gets the text of this title + * + * @return the text + */ + public BaseComponent[] getTitle() { + return this.title; + } + + /** + * Gets the text of this title's subtitle + * + * @return the text + */ + public BaseComponent[] getSubtitle() { + return this.subtitle; + } + + /** + * Gets the number of ticks to fade in. + *

+ *

The returned value is never negative.

+ * + * @return the number of ticks to fade in + */ + public int getFadeIn() { + return this.fadeIn; + } + + /** + * Gets the number of ticks to stay. + *

+ *

The returned value is never negative.

+ * + * @return the number of ticks to stay + */ + public int getStay() { + return this.stay; + } + + /** + * Gets the number of ticks to fade out. + *

+ *

The returned value is never negative.

+ * + * @return the number of ticks to fade out + */ + public int getFadeOut() { + return this.fadeOut; + } + + public static Builder builder() { + return new Builder(); + } + + /** + * A builder for creating titles + */ + public static final class Builder { + + private BaseComponent[] title; + private BaseComponent[] subtitle; + private int fadeIn = DEFAULT_FADE_IN; + private int stay = DEFAULT_STAY; + private int fadeOut = DEFAULT_FADE_OUT; + + /** + * Sets the title to the given text. + * + * @param title the title text + * @return this builder instance + * @throws NullPointerException if the title is null + */ + public Builder title(BaseComponent title) { + return this.title(new BaseComponent[]{checkNotNull(title, "title")}); + } + + /** + * Sets the title to the given text. + * + * @param title the title text + * @return this builder instance + * @throws NullPointerException if the title is null + */ + public Builder title(BaseComponent[] title) { + this.title = checkNotNull(title, "title"); + return this; + } + + /** + * Sets the title to the given text. + *

+ *

It is recommended to the {@link BaseComponent} methods.

+ * + * @param title the title text + * @return this builder instance + * @throws NullPointerException if the title is null + */ + public Builder title(String title) { + return this.title(TextComponent.fromLegacyText(checkNotNull(title, "title"))); + } + + /** + * Sets the subtitle to the given text. + * + * @param subtitle the title text + * @return this builder instance + */ + public Builder subtitle(BaseComponent subtitle) { + return this.subtitle(subtitle == null ? null : new BaseComponent[]{subtitle}); + } + + /** + * Sets the subtitle to the given text. + * + * @param subtitle the title text + * @return this builder instance + */ + public Builder subtitle(BaseComponent[] subtitle) { + this.subtitle = subtitle; + return this; + } + + /** + * Sets the subtitle to the given text. + *

+ *

It is recommended to the {@link BaseComponent} methods.

+ * + * @param subtitle the title text + * @return this builder instance + */ + public Builder subtitle(String subtitle) { + return this.subtitle(subtitle == null ? null : TextComponent.fromLegacyText(subtitle)); + } + + /** + * Sets the number of ticks for the title to fade in + * + * @param fadeIn the number of ticks to fade in + * @return this builder instance + * @throws IllegalArgumentException if it is negative + */ + public Builder fadeIn(int fadeIn) { + checkArgument(fadeIn >= 0, "Negative fadeIn: %s", fadeIn); + this.fadeIn = fadeIn; + return this; + } + + + /** + * Sets the number of ticks for the title to stay. + * + * @param stay the number of ticks to stay + * @return this builder instance + * @throws IllegalArgumentException if it is negative + */ + public Builder stay(int stay) { + checkArgument(stay >= 0, "Negative stay: %s", stay); + this.stay = stay; + return this; + } + + /** + * Sets the number of ticks for the title to fade out. + * + * @param fadeOut the number of ticks to fade out + * @return this builder instance + * @throws IllegalArgumentException if it is negative + */ + public Builder fadeOut(int fadeOut) { + checkArgument(fadeOut >= 0, "Negative fadeOut: %s", fadeOut); + this.fadeOut = fadeOut; + return this; + } + + /** + * Create a title based on the values in the builder. + * + * @return a title from the values in this builder + * @throws IllegalStateException if title isn't specified + */ + public Title build() { + checkState(title != null, "Title not specified"); + return new Title(this.title, this.subtitle, this.fadeIn, this.stay, this.fadeOut); + } + } +} \ No newline at end of file diff --git a/azurite-api/src/main/java/org/github/paperspigot/event/ServerExceptionEvent.java b/azurite-api/src/main/java/org/github/paperspigot/event/ServerExceptionEvent.java new file mode 100644 index 0000000..bf2d4b0 --- /dev/null +++ b/azurite-api/src/main/java/org/github/paperspigot/event/ServerExceptionEvent.java @@ -0,0 +1,35 @@ +package org.github.paperspigot.event; + +import com.google.common.base.Preconditions; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.github.paperspigot.exception.ServerException; + +/** + * Called whenever an exception is thrown in a recoverable section of the server. + */ +public class ServerExceptionEvent extends Event { + private static final HandlerList handlers = new HandlerList(); + private ServerException exception; + + public ServerExceptionEvent (ServerException exception) { + this.exception = Preconditions.checkNotNull(exception, "exception"); + } + + /** + * Gets the wrapped exception that was thrown. + * @return Exception thrown + */ + public ServerException getException() { + return exception; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/github/paperspigot/event/block/BeaconEffectEvent.java b/azurite-api/src/main/java/org/github/paperspigot/event/block/BeaconEffectEvent.java new file mode 100644 index 0000000..d9f9b95 --- /dev/null +++ b/azurite-api/src/main/java/org/github/paperspigot/event/block/BeaconEffectEvent.java @@ -0,0 +1,81 @@ +package org.github.paperspigot.event.block; + +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; +import org.bukkit.event.block.BlockEvent; +import org.bukkit.potion.PotionEffect; + +/** + * Called when a beacon effect is being applied to a player. + */ +public class BeaconEffectEvent extends BlockEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled; + private PotionEffect effect; + private Player player; + private boolean primary; + + public BeaconEffectEvent(Block block, PotionEffect effect, Player player, boolean primary) { + super(block); + this.effect = effect; + this.player = player; + this.primary = primary; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + + /** + * Gets the potion effect being applied. + * + * @return Potion effect + */ + public PotionEffect getEffect() { + return effect; + } + + /** + * Sets the potion effect that will be applied. + * + * @param effect Potion effect + */ + public void setEffect(PotionEffect effect) { + this.effect = effect; + } + + /** + * Gets the player who the potion effect is being applied to. + * + * @return Affected player + */ + public Player getPlayer() { + return player; + } + + /** + * Gets whether the effect is a primary beacon effect. + * + * @return true if this event represents a primary effect + */ + public boolean isPrimary() { + return primary; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/github/paperspigot/exception/ServerCommandException.java b/azurite-api/src/main/java/org/github/paperspigot/exception/ServerCommandException.java new file mode 100644 index 0000000..aae647a --- /dev/null +++ b/azurite-api/src/main/java/org/github/paperspigot/exception/ServerCommandException.java @@ -0,0 +1,64 @@ +package org.github.paperspigot.exception; + +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; + +import static com.google.common.base.Preconditions.checkNotNull; + +/** + * Thrown when a command throws an exception + */ +public class ServerCommandException extends ServerException { + + private final Command command; + private final CommandSender commandSender; + private final String[] arguments; + + public ServerCommandException(String message, Throwable cause, Command command, CommandSender commandSender, String[] arguments) { + super(message, cause); + this.commandSender = checkNotNull(commandSender, "commandSender"); + this.arguments = checkNotNull(arguments, "arguments"); + this.command = checkNotNull(command, "command"); + } + + public ServerCommandException(Throwable cause, Command command, CommandSender commandSender, String[] arguments) { + super(cause); + this.commandSender = checkNotNull(commandSender, "commandSender"); + this.arguments = checkNotNull(arguments, "arguments"); + this.command = checkNotNull(command, "command"); + } + + protected ServerCommandException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, Command command, CommandSender commandSender, String[] arguments) { + super(message, cause, enableSuppression, writableStackTrace); + this.commandSender = checkNotNull(commandSender, "commandSender"); + this.arguments = checkNotNull(arguments, "arguments"); + this.command = checkNotNull(command, "command"); + } + + /** + * Gets the command which threw the exception + * + * @return exception throwing command + */ + public Command getCommand() { + return command; + } + + /** + * Gets the command sender which executed the command request + * + * @return command sender of exception thrown command request + */ + public CommandSender getCommandSender() { + return commandSender; + } + + /** + * Gets the arguments which threw the exception for the command + * + * @return arguments of exception thrown command request + */ + public String[] getArguments() { + return arguments; + } +} diff --git a/azurite-api/src/main/java/org/github/paperspigot/exception/ServerEventException.java b/azurite-api/src/main/java/org/github/paperspigot/exception/ServerEventException.java new file mode 100644 index 0000000..e0de8aa --- /dev/null +++ b/azurite-api/src/main/java/org/github/paperspigot/exception/ServerEventException.java @@ -0,0 +1,52 @@ +package org.github.paperspigot.exception; + +import org.bukkit.event.Event; +import org.bukkit.event.Listener; +import org.bukkit.plugin.Plugin; + +import static com.google.common.base.Preconditions.checkNotNull; + +/** + * Exception thrown when a server event listener throws an exception + */ +public class ServerEventException extends ServerPluginException { + + private final Listener listener; + private final Event event; + + public ServerEventException(String message, Throwable cause, Plugin responsiblePlugin, Listener listener, Event event) { + super(message, cause, responsiblePlugin); + this.listener = checkNotNull(listener, "listener"); + this.event = checkNotNull(event, "event"); + } + + public ServerEventException(Throwable cause, Plugin responsiblePlugin, Listener listener, Event event) { + super(cause, responsiblePlugin); + this.listener = checkNotNull(listener, "listener"); + this.event = checkNotNull(event, "event"); + } + + protected ServerEventException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, Plugin responsiblePlugin, Listener listener, Event event) { + super(message, cause, enableSuppression, writableStackTrace, responsiblePlugin); + this.listener = checkNotNull(listener, "listener"); + this.event = checkNotNull(event, "event"); + } + + /** + * Gets the listener which threw the exception + * + * @return event listener + */ + public Listener getListener() { + return listener; + } + + /** + * Gets the event which caused the exception + * + * @return event + */ + public Event getEvent() { + return event; + } +} diff --git a/azurite-api/src/main/java/org/github/paperspigot/exception/ServerException.java b/azurite-api/src/main/java/org/github/paperspigot/exception/ServerException.java new file mode 100644 index 0000000..f7aad05 --- /dev/null +++ b/azurite-api/src/main/java/org/github/paperspigot/exception/ServerException.java @@ -0,0 +1,23 @@ +package org.github.paperspigot.exception; + +/** + * Wrapper exception for all exceptions that are thrown by the server. + */ +public class ServerException extends Exception { + + public ServerException(String message) { + super(message); + } + + public ServerException(String message, Throwable cause) { + super(message, cause); + } + + public ServerException(Throwable cause) { + super(cause); + } + + protected ServerException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } +} diff --git a/azurite-api/src/main/java/org/github/paperspigot/exception/ServerInternalException.java b/azurite-api/src/main/java/org/github/paperspigot/exception/ServerInternalException.java new file mode 100644 index 0000000..1e094ab --- /dev/null +++ b/azurite-api/src/main/java/org/github/paperspigot/exception/ServerInternalException.java @@ -0,0 +1,34 @@ +package org.github.paperspigot.exception; + +import org.bukkit.Bukkit; +import org.github.paperspigot.event.ServerExceptionEvent; + +/** + * Thrown when the internal server throws a recoverable exception. + */ +public class ServerInternalException extends ServerException { + + public ServerInternalException(String message) { + super(message); + } + + public ServerInternalException(String message, Throwable cause) { + super(message, cause); + } + + public ServerInternalException(Throwable cause) { + super(cause); + } + + protected ServerInternalException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } + + public static void reportInternalException(Throwable cause) { + try { + Bukkit.getPluginManager().callEvent(new ServerExceptionEvent(new ServerInternalException(cause))); + } catch (Throwable t) { + t.printStackTrace(); // Don't want to rethrow! + } + } +} diff --git a/azurite-api/src/main/java/org/github/paperspigot/exception/ServerPluginEnableDisableException.java b/azurite-api/src/main/java/org/github/paperspigot/exception/ServerPluginEnableDisableException.java new file mode 100644 index 0000000..8c938d0 --- /dev/null +++ b/azurite-api/src/main/java/org/github/paperspigot/exception/ServerPluginEnableDisableException.java @@ -0,0 +1,20 @@ +package org.github.paperspigot.exception; + +import org.bukkit.plugin.Plugin; + +/** + * Thrown whenever there is an exception with any enabling or disabling of plugins. + */ +public class ServerPluginEnableDisableException extends ServerPluginException { + public ServerPluginEnableDisableException(String message, Throwable cause, Plugin responsiblePlugin) { + super(message, cause, responsiblePlugin); + } + + public ServerPluginEnableDisableException(Throwable cause, Plugin responsiblePlugin) { + super(cause, responsiblePlugin); + } + + protected ServerPluginEnableDisableException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, Plugin responsiblePlugin) { + super(message, cause, enableSuppression, writableStackTrace, responsiblePlugin); + } +} diff --git a/azurite-api/src/main/java/org/github/paperspigot/exception/ServerPluginException.java b/azurite-api/src/main/java/org/github/paperspigot/exception/ServerPluginException.java new file mode 100644 index 0000000..702f8ad --- /dev/null +++ b/azurite-api/src/main/java/org/github/paperspigot/exception/ServerPluginException.java @@ -0,0 +1,37 @@ +package org.github.paperspigot.exception; + +import org.bukkit.plugin.Plugin; + +import static com.google.common.base.Preconditions.checkNotNull; + +/** + * Wrapper exception for all cases to which a plugin can be immediately blamed for + */ +public class ServerPluginException extends ServerException { + public ServerPluginException(String message, Throwable cause, Plugin responsiblePlugin) { + super(message, cause); + this.responsiblePlugin = checkNotNull(responsiblePlugin, "responsiblePlugin"); + } + + public ServerPluginException(Throwable cause, Plugin responsiblePlugin) { + super(cause); + this.responsiblePlugin = checkNotNull(responsiblePlugin, "responsiblePlugin"); + } + + protected ServerPluginException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, Plugin responsiblePlugin) { + super(message, cause, enableSuppression, writableStackTrace); + this.responsiblePlugin = checkNotNull(responsiblePlugin, "responsiblePlugin"); + } + + private final Plugin responsiblePlugin; + + /** + * Gets the plugin which is directly responsible for the exception being thrown + * + * @return plugin which is responsible for the exception throw + */ + public Plugin getResponsiblePlugin() { + return responsiblePlugin; + } + +} diff --git a/azurite-api/src/main/java/org/github/paperspigot/exception/ServerPluginMessageException.java b/azurite-api/src/main/java/org/github/paperspigot/exception/ServerPluginMessageException.java new file mode 100644 index 0000000..e4497cd --- /dev/null +++ b/azurite-api/src/main/java/org/github/paperspigot/exception/ServerPluginMessageException.java @@ -0,0 +1,61 @@ +package org.github.paperspigot.exception; + +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; + +import static com.google.common.base.Preconditions.checkNotNull; + +/** + * Thrown when an incoming plugin message channel throws an exception + */ +public class ServerPluginMessageException extends ServerPluginException { + + private final Player player; + private final String channel; + private final byte[] data; + + public ServerPluginMessageException(String message, Throwable cause, Plugin responsiblePlugin, Player player, String channel, byte[] data) { + super(message, cause, responsiblePlugin); + this.player = checkNotNull(player, "player"); + this.channel = checkNotNull(channel, "channel"); + this.data = checkNotNull(data, "data"); + } + + public ServerPluginMessageException(Throwable cause, Plugin responsiblePlugin, Player player, String channel, byte[] data) { + super(cause, responsiblePlugin); + this.player = checkNotNull(player, "player"); + this.channel = checkNotNull(channel, "channel"); + this.data = checkNotNull(data, "data"); + } + + protected ServerPluginMessageException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, Plugin responsiblePlugin, Player player, String channel, byte[] data) { + super(message, cause, enableSuppression, writableStackTrace, responsiblePlugin); + this.player = checkNotNull(player, "player"); + this.channel = checkNotNull(channel, "channel"); + this.data = checkNotNull(data, "data"); + } + + /** + * Gets the channel to which the error occurred from recieving data from + * @return exception channel + */ + public String getChannel() { + return channel; + } + + /** + * Gets the data to which the error occurred from + * @return exception data + */ + public byte[] getData() { + return data; + } + + /** + * Gets the player which the plugin message causing the exception originated from + * @return exception player + */ + public Player getPlayer() { + return player; + } +} diff --git a/azurite-api/src/main/java/org/github/paperspigot/exception/ServerSchedulerException.java b/azurite-api/src/main/java/org/github/paperspigot/exception/ServerSchedulerException.java new file mode 100644 index 0000000..99757ee --- /dev/null +++ b/azurite-api/src/main/java/org/github/paperspigot/exception/ServerSchedulerException.java @@ -0,0 +1,37 @@ +package org.github.paperspigot.exception; + +import org.bukkit.scheduler.BukkitTask; + +import static com.google.common.base.Preconditions.checkNotNull; + +/** + * Thrown when a plugin's scheduler fails with an exception + */ +public class ServerSchedulerException extends ServerPluginException { + + private final BukkitTask task; + + public ServerSchedulerException(String message, Throwable cause, BukkitTask task) { + super(message, cause, task.getOwner()); + this.task = checkNotNull(task, "task"); + } + + public ServerSchedulerException(Throwable cause, BukkitTask task) { + super(cause, task.getOwner()); + this.task = checkNotNull(task, "task"); + } + + protected ServerSchedulerException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, BukkitTask task) { + super(message, cause, enableSuppression, writableStackTrace, task.getOwner()); + this.task = checkNotNull(task, "task"); + } + + /** + * Gets the task which threw the exception + * @return exception throwing task + */ + public BukkitTask getTask() { + return task; + } + +} diff --git a/azurite-api/src/main/java/org/github/paperspigot/exception/ServerTabCompleteException.java b/azurite-api/src/main/java/org/github/paperspigot/exception/ServerTabCompleteException.java new file mode 100644 index 0000000..6e1e2ab --- /dev/null +++ b/azurite-api/src/main/java/org/github/paperspigot/exception/ServerTabCompleteException.java @@ -0,0 +1,22 @@ +package org.github.paperspigot.exception; + +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; + +/** + * Called when a tab-complete request throws an exception + */ +public class ServerTabCompleteException extends ServerCommandException { + + public ServerTabCompleteException(String message, Throwable cause, Command command, CommandSender commandSender, String[] arguments) { + super(message, cause, command, commandSender, arguments); + } + + public ServerTabCompleteException(Throwable cause, Command command, CommandSender commandSender, String[] arguments) { + super(cause, command, commandSender, arguments); + } + + protected ServerTabCompleteException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, Command command, CommandSender commandSender, String[] arguments) { + super(message, cause, enableSuppression, writableStackTrace, command, commandSender, arguments); + } +} diff --git a/azurite-api/src/main/java/org/spigotmc/CustomTimingsHandler.java b/azurite-api/src/main/java/org/spigotmc/CustomTimingsHandler.java new file mode 100644 index 0000000..28f1a79 --- /dev/null +++ b/azurite-api/src/main/java/org/spigotmc/CustomTimingsHandler.java @@ -0,0 +1,19 @@ +package org.spigotmc; + +/** + * This is here for legacy purposes incase any plugin used it. + * + * If you use this, migrate ASAP as this will be removed in the future! + * + * @deprecated + */ +@Deprecated +public final class CustomTimingsHandler { + + public CustomTimingsHandler(String name) { + } + + public void startTiming() {} + public void stopTiming() {} + +} diff --git a/azurite-api/src/main/java/org/spigotmc/event/entity/EntityDismountEvent.java b/azurite-api/src/main/java/org/spigotmc/event/entity/EntityDismountEvent.java new file mode 100644 index 0000000..9d8444e --- /dev/null +++ b/azurite-api/src/main/java/org/spigotmc/event/entity/EntityDismountEvent.java @@ -0,0 +1,53 @@ +package org.spigotmc.event.entity; + +import org.bukkit.entity.Entity; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; +import org.bukkit.event.entity.EntityEvent; +// PaperSpigot end + +/** + * Called when an entity stops riding another entity. + * + */ +public class EntityDismountEvent extends EntityEvent implements Cancellable // PaperSpigot - implement Cancellable +{ + + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled; + private final Entity dismounted; + + public EntityDismountEvent(Entity what, Entity dismounted) + { + super( what ); + this.dismounted = dismounted; + } + + public Entity getDismounted() + { + return dismounted; + } + + @Override + public HandlerList getHandlers() + { + return handlers; + } + + public static HandlerList getHandlerList() + { + return handlers; + } + + // PaperSpigot start - implement Cancellable methods + @Override + public boolean isCancelled() { + return cancelled; + } + + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + // PaperSpigot end +} diff --git a/azurite-api/src/main/java/org/spigotmc/event/entity/EntityMountEvent.java b/azurite-api/src/main/java/org/spigotmc/event/entity/EntityMountEvent.java new file mode 100644 index 0000000..16aa2a7 --- /dev/null +++ b/azurite-api/src/main/java/org/spigotmc/event/entity/EntityMountEvent.java @@ -0,0 +1,52 @@ +package org.spigotmc.event.entity; + +import org.bukkit.entity.Entity; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; +import org.bukkit.event.entity.EntityEvent; + +/** + * Called when an entity attempts to ride another entity. + * + */ +public class EntityMountEvent extends EntityEvent implements Cancellable +{ + + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled; + private final Entity mount; + + public EntityMountEvent(Entity what, Entity mount) + { + super( what ); + this.mount = mount; + } + + public Entity getMount() + { + return mount; + } + + @Override + public boolean isCancelled() + { + return cancelled; + } + + @Override + public void setCancelled(boolean cancel) + { + this.cancelled = cancel; + } + + @Override + public HandlerList getHandlers() + { + return handlers; + } + + public static HandlerList getHandlerList() + { + return handlers; + } +} diff --git a/azurite-api/src/main/java/org/spigotmc/event/player/PlayerSpawnLocationEvent.java b/azurite-api/src/main/java/org/spigotmc/event/player/PlayerSpawnLocationEvent.java new file mode 100644 index 0000000..783d696 --- /dev/null +++ b/azurite-api/src/main/java/org/spigotmc/event/player/PlayerSpawnLocationEvent.java @@ -0,0 +1,49 @@ +package org.spigotmc.event.player; + +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; +import org.bukkit.event.player.PlayerEvent; + +/** + * Called when player is about to spawn in a world after joining the server. + */ +public class PlayerSpawnLocationEvent extends PlayerEvent { + private static final HandlerList handlers = new HandlerList(); + private Location spawnLocation; + + public PlayerSpawnLocationEvent(final Player who, Location spawnLocation) { + super(who); + this.spawnLocation = spawnLocation; + } + + + /** + * Gets player's spawn location. + * If the player {@link Player#hasPlayedBefore()}, it's going to default to the location inside player.dat file. + * For new players, the default spawn location is spawn of the main Bukkit world. + * + * @return the spawn location + */ + public Location getSpawnLocation() { + return spawnLocation; + } + + /** + * Sets player's spawn location. + * + * @param location the spawn location + */ + public void setSpawnLocation(Location location) { + this.spawnLocation = location; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } +} diff --git a/azurite-server/.gitignore b/azurite-server/.gitignore new file mode 100644 index 0000000..c3faf57 --- /dev/null +++ b/azurite-server/.gitignore @@ -0,0 +1,36 @@ +# Eclipse stuff +/.classpath +/.project +/.settings + +# netbeans +/nbproject + +# we use maven! +/build.xml + +# maven +/target + +# vim +.*.sw[a-p] + +# various other potential build files +/build +/bin +/dist +/manifest.mf + +/world + +# Mac filesystem dust +.DS_Store + +# intellij +*.iml +*.ipr +*.iws +.idea/ + +/src/main/resources/achievement +/src/main/resources/lang diff --git a/azurite-server/deprecation-mappings.at b/azurite-server/deprecation-mappings.at new file mode 100644 index 0000000..5858b48 --- /dev/null +++ b/azurite-server/deprecation-mappings.at @@ -0,0 +1,62 @@ +public+synthetic org/bukkit/Bukkit/getOnlinePlayers()[Lorg/bukkit/entity/Player; +public+synthetic org/bukkit/Server/getOnlinePlayers()[Lorg/bukkit/entity/Player; + +public+synthetic org/bukkit/entity/Damageable/damage(I)V +public+synthetic org/bukkit/entity/Damageable/damage(ILorg/bukkit/entity/Entity;)V +public+synthetic org/bukkit/entity/Damageable/getHealth()I +public+synthetic org/bukkit/entity/Damageable/getMaxHealth()I +public+synthetic org/bukkit/entity/Damageable/setHealth(I)V +public+synthetic org/bukkit/entity/Damageable/setMaxHealth(I)V + +public+synthetic org/bukkit/entity/LivingEntity/getLastDamage()I +public+synthetic org/bukkit/entity/LivingEntity/setLastDamage(I)V + +public+synthetic org/bukkit/entity/Minecart/getDamage()I +public+synthetic org/bukkit/entity/Minecart/setDamage(I)V + +public+synthetic org/bukkit/entity/Projectile/getShooter()Lorg/bukkit/entity/LivingEntity; +public+synthetic org/bukkit/entity/Projectile/setShooter(Lorg/bukkit/entity/LivingEntity;)V + +public+synthetic org/bukkit/event/entity/EntityDamageEvent/getDamage()I +public+synthetic org/bukkit/event/entity/EntityDamageEvent/setDamage(I)V + +public+synthetic org/bukkit/event/entity/EntityRegainHealthEvent/getAmount()I +public+synthetic org/bukkit/event/entity/EntityRegainHealthEvent/setAmount(I)V + +public+synthetic org/bukkit/event/vehicle/VehicleDamageEvent/getDamage()I +public+synthetic org/bukkit/event/vehicle/VehicleDamageEvent/setDamage(I)V + +# CraftBukkit +public+synthetic org/bukkit/craftbukkit/v1_8_R3/CraftServer/getOnlinePlayers()[Lorg/bukkit/entity/Player; + +public+synthetic org/bukkit/craftbukkit/v1_8_R3/entity/CraftArrow/getShooter()Lorg/bukkit/entity/LivingEntity; +public+synthetic org/bukkit/craftbukkit/v1_8_R3/entity/CraftArrow/setShooter(Lorg/bukkit/entity/LivingEntity;)V + +public+synthetic org/bukkit/craftbukkit/v1_8_R3/entity/CraftEnderDragonPart/damage(I)V +public+synthetic org/bukkit/craftbukkit/v1_8_R3/entity/CraftEnderDragonPart/damage(ILorg/bukkit/entity/Entity;)V +public+synthetic org/bukkit/craftbukkit/v1_8_R3/entity/CraftEnderDragonPart/getHealth()I +public+synthetic org/bukkit/craftbukkit/v1_8_R3/entity/CraftEnderDragonPart/getMaxHealth()I +public+synthetic org/bukkit/craftbukkit/v1_8_R3/entity/CraftEnderDragonPart/setHealth(I)V +public+synthetic org/bukkit/craftbukkit/v1_8_R3/entity/CraftEnderDragonPart/setMaxHealth(I)V + + +public+synthetic org/bukkit/craftbukkit/v1_8_R3/entity/CraftFireball/getShooter()Lorg/bukkit/entity/LivingEntity; +public+synthetic org/bukkit/craftbukkit/v1_8_R3/entity/CraftFireball/setShooter(Lorg/bukkit/entity/LivingEntity;)V + +public+synthetic org/bukkit/craftbukkit/v1_8_R3/entity/CraftFish/getShooter()Lorg/bukkit/entity/LivingEntity; +public+synthetic org/bukkit/craftbukkit/v1_8_R3/entity/CraftFish/setShooter(Lorg/bukkit/entity/LivingEntity;)V + +public+synthetic org/bukkit/craftbukkit/v1_8_R3/entity/CraftLivingEntity/damage(I)V +public+synthetic org/bukkit/craftbukkit/v1_8_R3/entity/CraftLivingEntity/damage(ILorg/bukkit/entity/Entity;)V +public+synthetic org/bukkit/craftbukkit/v1_8_R3/entity/CraftLivingEntity/getHealth()I +public+synthetic org/bukkit/craftbukkit/v1_8_R3/entity/CraftLivingEntity/getMaxHealth()I +public+synthetic org/bukkit/craftbukkit/v1_8_R3/entity/CraftLivingEntity/setHealth(I)V +public+synthetic org/bukkit/craftbukkit/v1_8_R3/entity/CraftLivingEntity/setMaxHealth(I)V +public+synthetic org/bukkit/craftbukkit/v1_8_R3/entity/CraftLivingEntity/getLastDamage()I +public+synthetic org/bukkit/craftbukkit/v1_8_R3/entity/CraftLivingEntity/setLastDamage(I)V + +public+synthetic org/bukkit/craftbukkit/v1_8_R3/entity/CraftMinecart/getDamage()I +public+synthetic org/bukkit/craftbukkit/v1_8_R3/entity/CraftMinecart/setDamage(I)V + +public+synthetic org/bukkit/craftbukkit/v1_8_R3/entity/CraftProjectile/getShooter()Lorg/bukkit/entity/LivingEntity; +public+synthetic org/bukkit/craftbukkit/v1_8_R3/entity/CraftProjectile/setShooter(Lorg/bukkit/entity/LivingEntity;)V diff --git a/azurite-server/deprecation-mappings.csrg b/azurite-server/deprecation-mappings.csrg new file mode 100644 index 0000000..48bc504 --- /dev/null +++ b/azurite-server/deprecation-mappings.csrg @@ -0,0 +1,27 @@ +org/bukkit/Bukkit _INVALID_getOnlinePlayers ()[Lorg/bukkit/entity/Player; getOnlinePlayers +org/bukkit/Server _INVALID_getOnlinePlayers ()[Lorg/bukkit/entity/Player; getOnlinePlayers + +org/bukkit/entity/Damageable _INVALID_damage (I)V damage +org/bukkit/entity/Damageable _INVALID_damage (ILorg/bukkit/entity/Entity;)V damage +org/bukkit/entity/Damageable _INVALID_getHealth ()I getHealth +org/bukkit/entity/Damageable _INVALID_getMaxHealth ()I getMaxHealth +org/bukkit/entity/Damageable _INVALID_setHealth (I)V setHealth +org/bukkit/entity/Damageable _INVALID_setMaxHealth (I)V setMaxHealth + +org/bukkit/entity/LivingEntity _INVALID_getLastDamage ()I getLastDamage +org/bukkit/entity/LivingEntity _INVALID_setLastDamage (I)V setLastDamage + +org/bukkit/entity/Minecart _INVALID_getDamage ()I getDamage +org/bukkit/entity/Minecart _INVALID_setDamage (I)V setDamage + +org/bukkit/entity/Projectile _INVALID_getShooter ()Lorg/bukkit/entity/LivingEntity; getShooter +org/bukkit/entity/Projectile _INVALID_setShooter (Lorg/bukkit/entity/LivingEntity;)V setShooter + +org/bukkit/event/entity/EntityDamageEvent _INVALID_getDamage ()I getDamage +org/bukkit/event/entity/EntityDamageEvent _INVALID_setDamage (I)V setDamage + +org/bukkit/event/entity/EntityRegainHealthEvent _INVALID_getAmount ()I getAmount +org/bukkit/event/entity/EntityRegainHealthEvent _INVALID_setAmount (I)V setAmount + +org/bukkit/event/vehicle/VehicleDamageEvent _INVALID_getDamage ()I getDamage +org/bukkit/event/vehicle/VehicleDamageEvent _INVALID_setDamage (I)V setDamage diff --git a/azurite-server/pom.xml b/azurite-server/pom.xml new file mode 100644 index 0000000..52d922b --- /dev/null +++ b/azurite-server/pom.xml @@ -0,0 +1,360 @@ + + 4.0.0 + + + dev.azurite.spigot + AzuriteSpigot + 1.0 + ../pom.xml + + + azurite-server + jar + 1.8.8-R0.1-SNAPSHOT + + + UTF-8 + 1.8.8 + 1_8_R3 + + 1.8 + 1.8 + 4.2.7.Final + + + + + mc-repo + https://maven.elmakers.com/repository/ + + + papermc + https://repo.papermc.io/repository/maven-public/ + + + Central + https://repo1.maven.org/maven2/ + + + imanity-repo + https://maven.imanity.dev/repository/imanity-libraries/ + + + + + + + spigotmc-public + https://hub.spigotmc.org/nexus/content/groups/public/ + + + + + + dev.azurite.spigot + azurite-api + 1.8.8-R0.1-SNAPSHOT + + + com.mojang + authlib + 1.5.21 + + + + + io.netty + netty-common + ${netty.version} + + + io.netty + netty-handler + ${netty.version} + + + io.netty + netty-transport-native-epoll + ${netty.version} + linux-x86_64 + + + io.netty + netty-transport-native-epoll + ${netty.version} + linux-aarch_64 + + + io.netty + netty-transport-native-kqueue + ${netty.version} + osx-x86_64 + + + io.netty + netty-transport-native-kqueue + ${netty.version} + osx-aarch_64 + + + io.netty + netty-transport-native-io_uring + ${netty.version} + + + io.netty + netty-transport-native-io_uring + ${netty.version} + linux-x86_64 + + + io.netty + netty-transport-native-io_uring + ${netty.version} + linux-aarch_64 + + + com.velocitypowered + velocity-native + 1.1.0-SNAPSHOT + compile + + + + com.lmax + disruptor + 3.4.4 + runtime + + + net.sf.jopt-simple + jopt-simple + 5.0.4 + + + org.jline + jline-terminal-jansi + 3.30.5 + + + net.minecrell + terminalconsoleappender + 1.3.0 + + + org.apache.logging.log4j + log4j-api + 2.25.1 + compile + + + org.apache.logging.log4j + log4j-core + 2.25.1 + compile + + + org.apache.logging.log4j + log4j-slf4j-impl + 2.25.1 + runtime + + + org.apache.logging.log4j + log4j-iostreams + 2.25.1 + + + + org.xerial + sqlite-jdbc + 3.7.2 + + + mysql + mysql-connector-java + 5.1.14 + + + + dev.imanity.antixray + antixray-sdk + 1.0.3 + + + + + + install + + + org.apache.maven.plugins + maven-jar-plugin + 3.4.1 + + + + org.bukkit.craftbukkit.Main + CraftBukkit + ${project.version} + Bukkit Team + Bukkit + unknown + Bukkit Team + true + + + + net/bukkit/ + + true + + + + com/bukkit/ + + true + + + + org/bukkit/ + + true + + + + + + + + org.apache.maven.plugins + maven-shade-plugin + 3.6.0 + + + no-depends + package + + shade + + + true + no-depends + false + + + dev.azurite.spigot:azurite-server + org.spigotmc:minecraft-server + org.jline:jline-terminal + org.jline:jline-terminal-jansi + org.jline:jline-reader + org.fusesource.jansi:jansi + net.minecrell:terminalconsoleappender + + + + + **:** + + org/apache/commons/** + io/netty/** + META-INF/native/libnetty* + javax/** + com/mojang/** + com/google/** + org/apache/logging/** + META-INF/io.netty.versions.properties + yggdrasil_session_pubkey.der + + + + + + org.bukkit.craftbukkit + org.bukkit.craftbukkit.v${minecraft_version} + + org.bukkit.craftbukkit.Main* + + + + net.minecraft.server + net.minecraft.server.v${minecraft_version} + + + + + + package + + shade + + + false + + + jline + org.bukkit.craftbukkit.libs.jline + + + org.ibex + org.bukkit.craftbukkit.libs.org.ibex + + + org.gjt + org.bukkit.craftbukkit.libs.org.gjt + + + org.bukkit.craftbukkit + org.bukkit.craftbukkit.v${minecraft_version} + + org.bukkit.craftbukkit.Main* + + + + net.minecraft.server + net.minecraft.server.v${minecraft_version} + + + + + + + + + + + org.apache.logging.log4j + log4j-transform-maven-shade-plugin-extensions + 0.2.0 + + + + + net.md-5 + specialsource-maven-plugin + 2.0.4 + + + + package + + remap + + + ${project.basedir}/deprecation-mappings.csrg + ${project.basedir}/deprecation-mappings.at + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 3.14.0 + + + + diff --git a/azurite-server/src/main/java/com/grinderwolf/swm/clsm/CLSMBridge.java b/azurite-server/src/main/java/com/grinderwolf/swm/clsm/CLSMBridge.java new file mode 100644 index 0000000..66993bb --- /dev/null +++ b/azurite-server/src/main/java/com/grinderwolf/swm/clsm/CLSMBridge.java @@ -0,0 +1,21 @@ +package com.grinderwolf.swm.clsm; + +public interface CLSMBridge { + + default Object getChunk(Object world, int x, int z) { + return null; + } + + default boolean saveChunk(Object world, Object chunkAccess) { + return false; + } + + // Array containing the normal world, the nether and the end + Object[] getDefaultWorlds(); + + boolean isCustomWorld(Object world); + + default boolean skipWorldAdd(Object world) { + return false; // If true, the world won't be added to the bukkit world list + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/com/grinderwolf/swm/clsm/ClassModifier.java b/azurite-server/src/main/java/com/grinderwolf/swm/clsm/ClassModifier.java new file mode 100644 index 0000000..39a3cd6 --- /dev/null +++ b/azurite-server/src/main/java/com/grinderwolf/swm/clsm/ClassModifier.java @@ -0,0 +1,41 @@ +package com.grinderwolf.swm.clsm; + +import java.util.function.BooleanSupplier; + +/** + * This class serves as a bridge between the SWM and the Minecraft server. + * + * As plugins are loaded using a different ClassLoader, their code cannot + * be accessed from a NMS method. Because of this, it's impossible to make + * any calls to any method when rewriting the bytecode of a NMS class. + * + * As a workaround, this bridge simply calls a method of the {@link CLSMBridge} interface, + * which is implemented by the SWM plugin when loaded. + */ +public class ClassModifier { + + // Required for Paper 1.13 as javassist can't compile this class + public static final BooleanSupplier BOOLEAN_SUPPLIER = () -> true; + + private static CLSMBridge customLoader; + + public static boolean saveChunk(Object world, Object chunkAccess) { + return customLoader != null && customLoader.saveChunk(world, chunkAccess); + } + + public static boolean isCustomWorld(Object world) { + return customLoader != null && customLoader.isCustomWorld(world); + } + + public static boolean skipWorldAdd(Object world) { + return customLoader != null && customLoader.skipWorldAdd(world); + } + + public static void setLoader(CLSMBridge loader) { + customLoader = loader; + } + + public static Object[] getDefaultWorlds() { + return customLoader != null ? customLoader.getDefaultWorlds() : null; + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/Azurite.java b/azurite-server/src/main/java/dev/azurite/spigot/Azurite.java new file mode 100644 index 0000000..2c24424 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/Azurite.java @@ -0,0 +1,263 @@ +package dev.azurite.spigot; + +import dev.azurite.spigot.api.pearls.PearlHandler; +import dev.azurite.spigot.api.protocol.MovementHandler; +import dev.azurite.spigot.api.protocol.PacketHandler; +import dev.azurite.spigot.async.ThreadingManager; +import dev.azurite.spigot.betterslowdown.BetterSlowdown; +import dev.azurite.spigot.command.*; +import dev.azurite.spigot.configs.AzuriteConfig; +import dev.azurite.spigot.configs.EnchantConfig; +import dev.azurite.spigot.configs.LanguageConfig; +import dev.azurite.spigot.configs.PearlConfig; +import dev.azurite.spigot.configs.extra.Config; +import dev.azurite.spigot.configs.extra.ConfigEdit; +import dev.azurite.spigot.framework.commands.Command; +import dev.azurite.spigot.framework.menu.MenuManager; +import dev.azurite.spigot.framework.plugin.AzuriteFakePlugin; +import dev.azurite.spigot.generator.GeneratorManager; +import dev.azurite.spigot.knockback.KnockbackManager; +import dev.azurite.spigot.listeners.ChatListener; +import dev.azurite.spigot.listeners.MenuListener; +import dev.azurite.spigot.listeners.PearlListener; +import dev.azurite.spigot.optimizations.ObjectMapList; +import dev.azurite.spigot.redstone.EigencraftRedstoneWire; +import dev.azurite.spigot.redstone.PandaRedstoneWire; +import dev.azurite.spigot.utils.NettyWatchdog; +import dev.azurite.spigot.utils.Utils; +import net.minecraft.server.BlockRedstoneWire; +import net.minecraft.server.GameRules; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.WorldServer; +import org.bukkit.Bukkit; +import org.bukkit.command.defaults.BukkitCommand; +import org.bukkit.plugin.PluginManager; + +import java.util.*; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public class Azurite implements IAzurite { + + private static Azurite instance; + private static AzuriteFakePlugin pluginInstance; + + private final Map configEdits; + + private final List configs; + private final List commands; + + private final ObjectMapList packetHandlers; + private final ObjectMapList movementHandlers; + private final ObjectMapList pearlHandlers; + + private final AzuriteConfig azuriteConfig; + private final LanguageConfig languageConfig; + private final PearlConfig pearlConfig; + private final EnchantConfig enchantConfig; + + private final ThreadingManager threadingManager; + private final KnockbackManager knockbackManager; + private final GeneratorManager generatorManager; + private final MenuManager menuManager; + + private final NettyWatchdog nettyWatchdog; + private final BetterSlowdown betterSlowdown; + + private int noTrackRange; + + public Azurite() { + instance = this; + pluginInstance = new AzuriteFakePlugin(); + + this.configEdits = new HashMap<>(); + this.configs = new ArrayList<>(); + this.commands = new ArrayList<>(); + this.packetHandlers = new ObjectMapList<>(PacketHandler.class, 0); + this.movementHandlers = new ObjectMapList<>(MovementHandler.class, 0); + this.pearlHandlers = new ObjectMapList<>(PearlHandler.class, 0); + + this.azuriteConfig = new AzuriteConfig(this); + this.languageConfig = new LanguageConfig(this); + this.pearlConfig = new PearlConfig(this); + this.enchantConfig = new EnchantConfig(this); + this.configs.forEach(Config::load); + + this.threadingManager = new ThreadingManager(); + this.knockbackManager = new KnockbackManager(); + this.generatorManager = new GeneratorManager(); + this.menuManager = new MenuManager(); + + this.nettyWatchdog = new NettyWatchdog(); + + this.noTrackRange = 0; + + this.betterSlowdown = new BetterSlowdown(); + } + + public void shutdown() { + threadingManager.shutdown(); + knockbackManager.save(false); + generatorManager.save(false); + } + + public void registerListeners() { + PluginManager pluginManager = Bukkit.getPluginManager(); + pluginManager.registerEvents(new PearlListener(), pluginInstance); + pluginManager.registerEvents(new ChatListener(), pluginInstance); + pluginManager.registerEvents(new MenuListener(), pluginInstance); + } + + public void registerCommands(boolean reload) { + if (AzuriteConfig.enableSpigotConfigCommand.getValue()) commands.add(new AzuriteSpigotCommand()); + if (AzuriteConfig.enablePingCommand.getValue()) commands.add(new PingCommand()); + if (AzuriteConfig.enableTPSCommand.getValue()) commands.add(new TPSCommand()); + if (AzuriteConfig.enableClearLagCommand.getValue()) commands.add(new ClearLagCommand()); + if (AzuriteConfig.enableSetMaxPlayersCommand.getValue()) commands.add(new SetMaxPlayersCommand()); + if (AzuriteConfig.enableChunkUnloadCommand.getValue()) commands.add(new UnloadChunksCommand()); + if (AzuriteConfig.enableNoTrackCommand.getValue()) commands.add(new NoTrackCommand()); + commands.add(new KnockbackCommand()); + commands.add(new VersionCommand()); + + for (Command command : commands) { + BukkitCommand bukkitCommand = command.asBukkitCommand(); + String name = bukkitCommand.getName(); + if (name.equals("tps")) Utils.register("spigot", bukkitCommand, reload); + if (name.equals("version")) Utils.register("minecraft", bukkitCommand, reload); + Utils.register(AzuriteConfig.serverBranding.getValue().toLowerCase(), bukkitCommand, reload); + } + } + + public void reload() { + for (Config config : configs) { + config.reload(); + } + + for (Command command : commands) { + command.unregister(); + } + + for (WorldServer world : MinecraftServer.getServer().worlds) { + GameRules gameRules = world.worldData.x(); + gameRules.set("doMobSpawning", AzuriteConfig.naturalMobSpawn.getValue().toString()); + } + + this.commands.clear(); + this.registerCommands(true); + } + + public BlockRedstoneWire getRedstoneOptimization() { + switch (AzuriteConfig.redstoneOptimization.getValue().toUpperCase()) { + case "EIGENCRAFT": + return new EigencraftRedstoneWire(); + + case "PANDAWIRE": + return new PandaRedstoneWire(); + + default: + return new BlockRedstoneWire(); + } + } + + public static Azurite getInstance() { + return instance; + } + + public static AzuriteFakePlugin getPluginInstance() { + return pluginInstance; + } + + public Map getConfigEdits() { + return configEdits; + } + + public List getConfigs() { + return configs; + } + + public List getCommands() { + return commands; + } + + public ThreadingManager getThreadingManager() { + return threadingManager; + } + + public GeneratorManager getGeneratorManager() { + return generatorManager; + } + + public MenuManager getMenuManager() { + return menuManager; + } + + public AzuriteConfig getAzuriteConfig() { + return azuriteConfig; + } + + public LanguageConfig getLanguageConfig() { + return languageConfig; + } + + public PearlConfig getPearlConfig() { + return pearlConfig; + } + + public EnchantConfig getEnchantConfig() { + return enchantConfig; + } + + public NettyWatchdog getNettyWatchdog() { + return nettyWatchdog; + } + + public int getNoTrackRange() { + return noTrackRange; + } + + public void setNoTrackRange(int noTrackRange) { + this.noTrackRange = noTrackRange; + } + + public BetterSlowdown getBetterSlowdown() { + return betterSlowdown; + } + + @Override + public void addMovementHandler(MovementHandler movementHandler) { + movementHandlers.add(movementHandler); + } + + @Override + public void addPacketHandler(PacketHandler packetHandler) { + packetHandlers.add(packetHandler); + } + + @Override + public void addPearlHandler(PearlHandler pearlHandler) { + pearlHandlers.add(pearlHandler); + } + + @Override + public ObjectMapList getPacketHandlers() { + return packetHandlers; + } + + @Override + public ObjectMapList getMovementHandlers() { + return movementHandlers; + } + + @Override + public ObjectMapList getPearlHandlers() { + return pearlHandlers; + } + + @Override + public KnockbackManager getKnockbackManager() { + return knockbackManager; + } +} diff --git a/azurite-server/src/main/java/dev/azurite/spigot/api/SpigotAPI.java b/azurite-server/src/main/java/dev/azurite/spigot/api/SpigotAPI.java new file mode 100644 index 0000000..c42ed87 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/api/SpigotAPI.java @@ -0,0 +1,16 @@ +package dev.azurite.spigot.api; + +import dev.azurite.spigot.Azurite; +import dev.azurite.spigot.IAzurite; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public class SpigotAPI { + + public static IAzurite getInstance() { + return Azurite.getInstance(); + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/api/chunk/ChunkSectionSnapshot.java b/azurite-server/src/main/java/dev/azurite/spigot/api/chunk/ChunkSectionSnapshot.java new file mode 100644 index 0000000..0a41b50 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/api/chunk/ChunkSectionSnapshot.java @@ -0,0 +1,53 @@ +package dev.azurite.spigot.api.chunk; + +import net.minecraft.server.NibbleArray; + +public class ChunkSectionSnapshot { + + private final int yPos; + private final int nonEmptyBlockCount; + private final int tickingBlockCount; + private final char[] blockIds; + private final NibbleArray emittedLight; + private final NibbleArray skyLight; + boolean isDirty; // PaperSpigot + + public ChunkSectionSnapshot(int yPos, int nonEmptyBlockCount, int tickingBlockCount, char[] blockIds, NibbleArray emittedLight, NibbleArray skyLight, boolean isDirty) { + this.yPos = yPos; + this.nonEmptyBlockCount = nonEmptyBlockCount; + this.tickingBlockCount = tickingBlockCount; + this.blockIds = blockIds; + this.emittedLight = emittedLight; + this.skyLight = skyLight; + this.isDirty = isDirty; + } + + public int getYPos() { + return yPos; + } + + public int getNonEmptyBlockCount() { + return nonEmptyBlockCount; + } + + public int getTickingBlockCount() { + return tickingBlockCount; + } + + public char[] getBlockIds() { + return blockIds; + } + + public NibbleArray getEmittedLight() { + return emittedLight; + } + + public NibbleArray getSkyLight() { + return skyLight; + } + + public boolean isDirty() { + return isDirty; + } + +} diff --git a/azurite-server/src/main/java/dev/azurite/spigot/api/chunk/CraftChunkSnapshot.java b/azurite-server/src/main/java/dev/azurite/spigot/api/chunk/CraftChunkSnapshot.java new file mode 100644 index 0000000..896ef0c --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/api/chunk/CraftChunkSnapshot.java @@ -0,0 +1,20 @@ +package dev.azurite.spigot.api.chunk; + +import net.minecraft.server.NBTTagCompound; + +import java.util.ArrayList; +import java.util.List; + +public class CraftChunkSnapshot implements ChunkSnapshot { + + private final ChunkSectionSnapshot[] sections = new ChunkSectionSnapshot[16]; + private final List tileEntities = new ArrayList<>(); + + public ChunkSectionSnapshot[] getSections() { + return sections; + } + + public List getTileEntities() { + return tileEntities; + } +} diff --git a/azurite-server/src/main/java/dev/azurite/spigot/async/ThreadingManager.java b/azurite-server/src/main/java/dev/azurite/spigot/async/ThreadingManager.java new file mode 100644 index 0000000..54c21e6 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/async/ThreadingManager.java @@ -0,0 +1,55 @@ +package dev.azurite.spigot.async; + +import dev.azurite.spigot.async.threads.AsyncExecutorThread; +import dev.azurite.spigot.async.threads.TrackerExecutorThread; +import dev.azurite.spigot.async.worker.TaskQueueWorker; +import dev.azurite.spigot.configs.AzuriteConfig; +import dev.azurite.spigot.pathsearch.PathSearchThrottlerThread; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; + +public class ThreadingManager { + + private final AsyncExecutorThread asyncExecutorThread; + private final TrackerExecutorThread trackerExecutorThread; + private final PathSearchThrottlerThread pathSearchExecutorThread; + + public ThreadingManager() { + this.asyncExecutorThread = new AsyncExecutorThread(); + this.trackerExecutorThread = new TrackerExecutorThread(); + this.pathSearchExecutorThread = new PathSearchThrottlerThread(AzuriteConfig.pathSearchThreads.getValue()); + } + + public void shutdown() { + pathSearchExecutorThread.shutdown(); + TaskQueueWorker files = asyncExecutorThread.getFilesWorker(); + ExecutorService service = asyncExecutorThread.getExecutor(); + while (files.isActive() && !service.isTerminated()) { + try { + service.awaitTermination(10, TimeUnit.SECONDS); + } catch (InterruptedException ignored) { + } + } + if (!service.isTerminated()) { + service.shutdownNow(); + try { + service.awaitTermination(10L, TimeUnit.SECONDS); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + public AsyncExecutorThread getAsyncExecutor() { + return asyncExecutorThread; + } + + public TrackerExecutorThread getTrackerExecutor() { + return trackerExecutorThread; + } + + public PathSearchThrottlerThread getPathSearchExecutor() { + return pathSearchExecutorThread; + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/async/factory/NamePriorityThreadFactory.java b/azurite-server/src/main/java/dev/azurite/spigot/async/factory/NamePriorityThreadFactory.java new file mode 100644 index 0000000..221edb2 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/async/factory/NamePriorityThreadFactory.java @@ -0,0 +1,37 @@ +package dev.azurite.spigot.async.factory; + +import org.jetbrains.annotations.NotNull; + +import java.util.concurrent.Executors; +import java.util.concurrent.ThreadFactory; + +public class NamePriorityThreadFactory implements ThreadFactory { + + private String name = "Spigot_Async-Thread"; + private final int priority; + private int idCounter; + private boolean isDaemon; + + public NamePriorityThreadFactory(int priority) { + this.priority = Math.min(Math.max(priority, Thread.MIN_PRIORITY), Thread.MAX_PRIORITY); + } + + public NamePriorityThreadFactory(int priority, String name) { + this(priority); + this.name = name; + } + + public NamePriorityThreadFactory setDaemon(boolean daemon) { + this.isDaemon = daemon; + return this; + } + + @Override + public Thread newThread(@NotNull Runnable runnable) { + Thread thread = Executors.defaultThreadFactory().newThread(runnable); + thread.setPriority(priority); + thread.setName(name + "-" + idCounter++); + thread.setDaemon(isDaemon); + return thread; + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/async/tasks/NBTFileSaveJob.java b/azurite-server/src/main/java/dev/azurite/spigot/async/tasks/NBTFileSaveJob.java new file mode 100644 index 0000000..e0a946b --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/async/tasks/NBTFileSaveJob.java @@ -0,0 +1,29 @@ +package dev.azurite.spigot.async.tasks; + +import net.minecraft.server.NBTCompressedStreamTools; +import net.minecraft.server.NBTTagCompound; + +import java.io.File; +import java.io.FileOutputStream; + +public class NBTFileSaveJob implements Runnable { + + private NBTTagCompound compound; + private File file; + + public NBTFileSaveJob(NBTTagCompound compound, File file) { + this.compound = compound; + this.file = file; + } + + @Override + public void run() { + try (FileOutputStream fileoutputstream = new FileOutputStream(file)) { + NBTCompressedStreamTools.a(compound, fileoutputstream); + } catch (Exception e) { + e.printStackTrace(); + } + compound = null; + file = null; + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/async/tasks/PlayerDataSaveJob.java b/azurite-server/src/main/java/dev/azurite/spigot/async/tasks/PlayerDataSaveJob.java new file mode 100644 index 0000000..dc0944a --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/async/tasks/PlayerDataSaveJob.java @@ -0,0 +1,34 @@ +package dev.azurite.spigot.async.tasks; + +import net.minecraft.server.NBTCompressedStreamTools; +import net.minecraft.server.NBTTagCompound; + +import java.io.File; +import java.io.FileOutputStream; + +public class PlayerDataSaveJob implements Runnable { + + private File target; + private NBTTagCompound data; + + public PlayerDataSaveJob(File target, NBTTagCompound data) { + this.target = target; + this.data = data; + } + + @Override + public void run() { + File temp = new File(target.getPath() + ".tmp"); + try (FileOutputStream fileoutputstream = new FileOutputStream(temp)) { + NBTCompressedStreamTools.a(data, fileoutputstream); + if (target.exists()) { + target.delete(); + } + temp.renameTo(target); + } catch (Exception e) { + e.printStackTrace(); + } + target = null; + data = null; + } +} diff --git a/azurite-server/src/main/java/dev/azurite/spigot/async/tasks/PlayerStatsSaveJob.java b/azurite-server/src/main/java/dev/azurite/spigot/async/tasks/PlayerStatsSaveJob.java new file mode 100644 index 0000000..99e395c --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/async/tasks/PlayerStatsSaveJob.java @@ -0,0 +1,30 @@ +package dev.azurite.spigot.async.tasks; + +import net.minecraft.server.ServerStatisticManager; +import net.minecraft.server.Statistic; +import net.minecraft.server.StatisticWrapper; +import org.apache.commons.io.FileUtils; + +import java.io.File; +import java.io.IOException; +import java.util.Map; + +public class PlayerStatsSaveJob implements Runnable { + + private final File target; + private final Map stats; + + public PlayerStatsSaveJob(File target, Map stats) { + this.target = target; + this.stats = stats; + } + + @Override + public void run() { + try { + FileUtils.writeStringToFile(target, ServerStatisticManager.a(stats)); // The stats map is a concurrenthashmap by default so we can serialize it asynchronously + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/azurite-server/src/main/java/dev/azurite/spigot/async/tasks/UserCacheSaveJob.java b/azurite-server/src/main/java/dev/azurite/spigot/async/tasks/UserCacheSaveJob.java new file mode 100644 index 0000000..816ca23 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/async/tasks/UserCacheSaveJob.java @@ -0,0 +1,20 @@ +package dev.azurite.spigot.async.tasks; + +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.UserCache; + +import java.util.List; + +public class UserCacheSaveJob implements Runnable { + + private final List entries; + + public UserCacheSaveJob(List entries) { + this.entries = entries; + } + + @Override + public void run() { + MinecraftServer.getServer().getUserCache().saveEntries(this.entries); + } +} diff --git a/azurite-server/src/main/java/dev/azurite/spigot/async/tasks/WorldDataSaveJob.java b/azurite-server/src/main/java/dev/azurite/spigot/async/tasks/WorldDataSaveJob.java new file mode 100644 index 0000000..a69cf7b --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/async/tasks/WorldDataSaveJob.java @@ -0,0 +1,48 @@ +package dev.azurite.spigot.async.tasks; + +import net.minecraft.server.NBTCompressedStreamTools; +import net.minecraft.server.NBTTagCompound; +import net.minecraft.server.WorldData; + +import java.io.File; +import java.nio.file.Files; + +//Vortex Async World Saving +public class WorldDataSaveJob implements Runnable { + + private WorldData target; + private NBTTagCompound data; + private File dir; + + public WorldDataSaveJob(WorldData target, NBTTagCompound data, File dir) { + this.target = target; + this.data = data; + this.dir = dir; + } + + @Override + public void run() { + NBTTagCompound nbttagcompound1 = target.a(data); + NBTTagCompound nbttagcompound2 = new NBTTagCompound(); + nbttagcompound2.set("Data", nbttagcompound1); + try { + final File file1 = new File(this.dir, "level.dat_new"); + final File file2 = new File(this.dir, "level.dat_old"); + final File file3 = new File(this.dir, "level.dat"); + NBTCompressedStreamTools.a(nbttagcompound2, Files.newOutputStream(file1.toPath())); + if (file2.exists()) + file2.delete(); + file3.renameTo(file2); + if (file3.exists()) + file3.delete(); + file1.renameTo(file3); + if (file1.exists()) + file1.delete(); + } catch (Exception exception) { + exception.printStackTrace(); + } + this.target = null; + this.data = null; + this.dir = null; + } +} diff --git a/azurite-server/src/main/java/dev/azurite/spigot/async/threads/AsyncExecutorThread.java b/azurite-server/src/main/java/dev/azurite/spigot/async/threads/AsyncExecutorThread.java new file mode 100644 index 0000000..dd95e2d --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/async/threads/AsyncExecutorThread.java @@ -0,0 +1,57 @@ +package dev.azurite.spigot.async.threads; + +import dev.azurite.spigot.async.worker.TaskQueueWorker; +import dev.azurite.spigot.async.factory.NamePriorityThreadFactory; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public class AsyncExecutorThread { + + private final ExecutorService asyncExecutor; + private final TaskQueueWorker files; + private final TaskQueueWorker heads; + private final TaskQueueWorker chat; + + public AsyncExecutorThread() { + int priority = Thread.currentThread().getPriority() - 1; + this.asyncExecutor = Executors.newCachedThreadPool(new NamePriorityThreadFactory(priority, "Spigot_Async-Executor").setDaemon(true)); + this.files = new TaskQueueWorker(asyncExecutor); + this.heads = new TaskQueueWorker(asyncExecutor); + this.chat = new TaskQueueWorker(asyncExecutor); + } + + public void queueFileTask(Runnable runnable) { + files.queueTask(runnable); + } + + public void queueHeadLoading(Runnable runnable) { + heads.queueTask(runnable); + } + + public void queueChat(Runnable runnable) { + chat.queueTask(runnable); + } + + public TaskQueueWorker getFilesWorker() { + return files; + } + + public void execute(Runnable runnable) { + asyncExecutor.execute(runnable); + } + + public Future submit(Runnable runnable) { + return asyncExecutor.submit(runnable); + } + + public ExecutorService getExecutor() { + return asyncExecutor; + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/async/threads/TrackerExecutorThread.java b/azurite-server/src/main/java/dev/azurite/spigot/async/threads/TrackerExecutorThread.java new file mode 100644 index 0000000..90a946b --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/async/threads/TrackerExecutorThread.java @@ -0,0 +1,79 @@ +package dev.azurite.spigot.async.threads; + +import com.google.common.util.concurrent.ThreadFactoryBuilder; +import dev.azurite.spigot.configs.AzuriteConfig; +import dev.azurite.spigot.optimizations.ObjectMapList; +import dev.azurite.spigot.utils.SpinCountDownLatch; +import net.minecraft.server.EntityPlayer; +import net.minecraft.server.EntityTrackerEntry; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.PacketPlayOutEntityDestroy; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ThreadFactory; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public class TrackerExecutorThread { + + private final int trackerThreads; + private final ExecutorService trackerExecutor; + + public TrackerExecutorThread() { + ThreadFactory trackerFactory = new ThreadFactoryBuilder().setNameFormat("entity-tracker-%d").build(); + this.trackerThreads = 4; + this.trackerExecutor = Executors.newFixedThreadPool(trackerThreads - 1, trackerFactory); + } + + public void updatePlayers(ObjectMapList c) { + boolean parallelizeUpdate = false; + + if (AzuriteConfig.dynamicParalellisedTracking.getValue()) { + for (int index = 0; index < c.count; index++) { + EntityTrackerEntry entry = c.elements[index]; + + if (entry.trackedPlayers.size() >= AzuriteConfig.playersNeededParalellisedTracking.getValue()) { + parallelizeUpdate = true; + break; + } + } + } + + if (!parallelizeUpdate) { + for (int index = 0; index < c.count; index++) { + EntityTrackerEntry entry = c.elements[index]; + + entry.update(3); + } + } else { + int offset = 0; + final SpinCountDownLatch latch = new SpinCountDownLatch(trackerThreads); + + for (int i = 1; i <= trackerThreads; i++) { + final int localOffset = offset++; + int finalTrackerThread = i; + Runnable runnable = () -> { + for (int i1 = localOffset; i1 < c.size(); i1 += trackerThreads) { + c.get(i1).update(finalTrackerThread - 1); + } + latch.countDown(); + }; + + if (i < trackerThreads) { + trackerExecutor.execute(runnable); + + } else runnable.run(); + } + try { + latch.await(); + } catch (Exception e) { + MinecraftServer.LOGGER.error(e); + } + } + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/async/worker/TaskQueueWorker.java b/azurite-server/src/main/java/dev/azurite/spigot/async/worker/TaskQueueWorker.java new file mode 100644 index 0000000..0e8adf4 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/async/worker/TaskQueueWorker.java @@ -0,0 +1,51 @@ +package dev.azurite.spigot.async.worker; + +import org.apache.logging.log4j.LogManager; + +import java.util.concurrent.ConcurrentLinkedDeque; +import java.util.concurrent.ExecutorService; + +public class TaskQueueWorker implements Runnable { + + private final ConcurrentLinkedDeque taskQueue = new ConcurrentLinkedDeque<>(); + private final ExecutorService service; + private volatile boolean isActive = false; + + public TaskQueueWorker(ExecutorService service) { + this.service = service; + } + + @Override + public void run() { + Runnable task; + while (isActive = (task = taskQueue.pollFirst()) != null) { + try { + task.run(); + } catch (Exception e) { + LogManager.getLogger().error("Thread {} encountered an exception: {}", Thread.currentThread().getName(), e.getMessage(), e); + } + } + } + + public void queueTask(Runnable runnable) { + // Azurite - run sync if service is terminated + if (service.isTerminated()) { + runnable.run(); + + } else { + taskQueue.addLast(runnable); + if (!isActive) { + isActive = true; + service.execute(this); + } + } + } + + public boolean isActive() { + if (!isActive && !taskQueue.isEmpty()) { + isActive = true; + service.execute(this); + } + return isActive; + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/autosave/AutoSave.java b/azurite-server/src/main/java/dev/azurite/spigot/autosave/AutoSave.java new file mode 100644 index 0000000..0468aad --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/autosave/AutoSave.java @@ -0,0 +1,184 @@ +package dev.azurite.spigot.autosave; + +import dev.azurite.spigot.configs.AzuriteConfig; +import net.minecraft.server.*; +import org.bukkit.event.world.WorldSaveEvent; + +import java.util.ArrayDeque; +import java.util.Queue; + +public class AutoSave { + + private AutoSaveStep step; + private final Queue levelAndMapsQueue; + private final Queue saveChunksQueue; + private final Queue unloadChunksQueue; + private final Queue eventQueue; + private long fileioStart; + private long fileioEnd; + private int chunkQueuedCount; + + public AutoSave() { + this.levelAndMapsQueue = new ArrayDeque<>(); + this.saveChunksQueue = new ArrayDeque<>(); + this.unloadChunksQueue = new ArrayDeque<>(); + this.eventQueue = new ArrayDeque<>(); + this.reset(); + } + + public void queueWorld(WorldServer worldserver) { + this.levelAndMapsQueue.add(worldserver); + this.saveChunksQueue.add(worldserver); + this.unloadChunksQueue.add(worldserver); + this.eventQueue.add(worldserver); + } + + public void reset() { + this.levelAndMapsQueue.clear(); + this.saveChunksQueue.clear(); + this.unloadChunksQueue.clear(); + this.eventQueue.clear(); + this.step = AutoSaveStep.IDLE; + this.chunkQueuedCount = 0; + } + + private void moveToNextStep() { + this.step = AutoSaveStep.nextStep(this.step); + } + + public boolean execute() throws ExceptionWorldConflict { + WorldServer worldServer; + switch (this.step) { + case IDLE: + break; + case START: + if (AzuriteConfig.autoSaveMessages.getValue()) { + MinecraftServer.LOGGER.info("[Autosave] Started .."); + } + for (WorldServer world : this.saveChunksQueue) { + world.getAutoSaveWorldData().setLastAutosaveTimeStamp(); + } + this.moveToNextStep(); + return this.execute(); + case SAVE_PLAYERS: + MinecraftServer.getServer().getPlayerList().savePlayers(); + this.moveToNextStep(); + break; + case SAVE_LEVEL_AND_MAPS: + worldServer = this.levelAndMapsQueue.poll(); + if (worldServer != null) { + worldServer.saveOnlyLevel(null); + } + + if (this.levelAndMapsQueue.isEmpty()) { + this.moveToNextStep(); + } + + break; + case SAVE_CHUNKS: + worldServer = this.saveChunksQueue.peek(); + if (worldServer != null) { + if (worldServer.saveOnlyChunks(false, null)) { + this.chunkQueuedCount += worldServer.getAutoSaveWorldData().getAutoSaveChunkCount(); + this.saveChunksQueue.poll(); + } + } + + if (this.saveChunksQueue.isEmpty()) { + this.moveToNextStep(); + } + + break; + case UNLOAD_CHUNKS: + worldServer = this.unloadChunksQueue.poll(); + if (worldServer != null) { + worldServer.unloadOnlyUnusedChunks(); + } + + if (this.unloadChunksQueue.isEmpty()) { + this.moveToNextStep(); + } + + break; + case WRITE_FILES_START: + FileIOThread.a().setNoDelay(true); + this.fileioStart = System.nanoTime(); + this.moveToNextStep(); + break; + case WRITE_FILES_WAIT: + if (FileIOThread.a().isDone()) { + this.fileioEnd = System.nanoTime(); + FileIOThread.a().setNoDelay(false); + this.moveToNextStep(); + } + break; + case FIRE_WORLDSAVEEVENT: + if (AzuriteConfig.autoSaveClearRegionFileCache.getValue()) { + RegionFileCache.a(); + } + + if (AzuriteConfig.autoSaveFireWorldSaveEvent.getValue()) { + for (WorldServer worldserver : this.eventQueue) { + WorldSaveEvent event = new WorldSaveEvent(worldserver.getWorld()); + MinecraftServer.getServer().server.getPluginManager().callEvent(event); + } + } + this.moveToNextStep(); + break; + case FINISHED: + if (AzuriteConfig.autoSaveMessages.getValue()) { + MinecraftServer.LOGGER.info("[Autosave] Done. Queued {} chunks for saving. Took {} seconds to write them.", this.chunkQueuedCount, formatLongTime(this.fileioEnd - this.fileioStart)); + } + this.reset(); + return true; + } + return false; + } + + private static String formatLongTime(long duration) { + return String.format("%.2f", ((double) (duration / 1000000L)) / 1000.0D); + } + + public boolean isActive() { + return this.step.isActiveState(); + } + + public void start() { + this.step = AutoSaveStep.START; + } + + public enum AutoSaveStep { + IDLE(false), + START(), + SAVE_PLAYERS(), + SAVE_LEVEL_AND_MAPS(), + SAVE_CHUNKS(), + UNLOAD_CHUNKS(), + WRITE_FILES_START(), + WRITE_FILES_WAIT(), + FIRE_WORLDSAVEEVENT(), + FINISHED(); + + private final boolean activeState; + + AutoSaveStep() { + this(true); + } + + AutoSaveStep(boolean activeState) { + this.activeState = activeState; + } + + public static AutoSaveStep nextStep(AutoSaveStep current) { + AutoSaveStep[] values = AutoSaveStep.values(); + if (current.ordinal() + 1 < values.length) { + return values[current.ordinal() + 1]; + } + return current; + } + + public boolean isActiveState() { + return this.activeState; + } + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/autosave/AutoSaveWorldData.java b/azurite-server/src/main/java/dev/azurite/spigot/autosave/AutoSaveWorldData.java new file mode 100644 index 0000000..7d1a8d7 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/autosave/AutoSaveWorldData.java @@ -0,0 +1,32 @@ +package dev.azurite.spigot.autosave; + +import net.minecraft.server.World; + +public class AutoSaveWorldData { + + private long lastAutoSaveTimeStamp; + private int autoSaveChunkCount; + private final World world; + + public AutoSaveWorldData(World world) { + this.world = world; + this.setLastAutosaveTimeStamp(); + } + + public void setLastAutosaveTimeStamp() { + this.lastAutoSaveTimeStamp = this.world.worldData.getTime(); + this.autoSaveChunkCount = 0; + } + + public long getLastAutosaveTimeStamp() { + return this.lastAutoSaveTimeStamp; + } + + public void addAutoSaveChunkCount(int count) { + this.autoSaveChunkCount += count; + } + + public int getAutoSaveChunkCount() { + return this.autoSaveChunkCount; + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/betterslowdown/BetterSlowdown.java b/azurite-server/src/main/java/dev/azurite/spigot/betterslowdown/BetterSlowdown.java new file mode 100644 index 0000000..d7561a4 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/betterslowdown/BetterSlowdown.java @@ -0,0 +1,181 @@ +package dev.azurite.spigot.betterslowdown; + +import com.eatthepath.uuid.FastUUID; +import dev.azurite.spigot.betterslowdown.data.PlayerData; +import dev.azurite.spigot.betterslowdown.data.PlayerDataManager; +import dev.azurite.spigot.configs.AzuriteConfig; +import net.minecraft.server.*; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.UUID; + +public class BetterSlowdown { + private static final UUID SPRINT_MODIFIER_UUID = FastUUID.parseUUID("662A6B8D-DA3E-4C1C-8813-96EA6097278D"); + private static final AttributeModifier SPRINT_MODIFIER = (new AttributeModifier(SPRINT_MODIFIER_UUID, "Sprinting speed boost", + 0.30000001192092896D, 2)).a(false); + private final PlayerDataManager manager; + + public BetterSlowdown() { + this.manager = new PlayerDataManager(); + } + + public void disconnect(UUID uuid) { + this.manager.remove(uuid); + } + + + public void startSprint(UUID uuid) { + PlayerData data = manager.get(uuid); + data.setClientSprintingState(true); + } + + public void stopSprint(UUID uuid) { + PlayerData data = manager.get(uuid); + data.setClientSprintingState(false); + } + + public void respawn(UUID uuid) { + manager.get(uuid).reset(); + } + + // This can be called from tracker thread so player data manager needs to be threadsafe + // Method returns whether the update is needed + public boolean handleEntityMetadata(UUID uuid, PacketPlayOutEntityMetadata wrapper) { + if (!AzuriteConfig.betterSlowdownEnabled.getValue()) return true; + + Iterator iterator = wrapper.getData().iterator(); + + while (iterator.hasNext()) { + DataWatcher.WatchableObject entityData = iterator.next(); + + // Check if the entity metadata bitmask is in this packet + if (entityData.a() == MetadataValues.BITMASK_INDEX) { + byte packetBitmask = (byte) entityData.b(); + byte usefulBitmask = packetBitmask; + // Calculate the useful bitmask + usefulBitmask &= ~MetadataValues.FLAG_CROUCHING; // Remove crouching + usefulBitmask &= ~MetadataValues.FLAG_SPRINTING; // Remove sprinting + usefulBitmask &= ~MetadataValues.FLAG_USING; // Remove using + + // Check if the "useful" bitmask has changed, which means either the client is on fire or invisible + PlayerData data = manager.get(uuid); + byte lastUsefulBitmask = data.getLastUsefulBitmask(); + + if (lastUsefulBitmask != usefulBitmask) { + data.setLastUsefulBitmask(usefulBitmask); + + // Get the fallback mode as we are 100% sending the bitmask + FallbackMode mode; + + try { + mode = Enum.valueOf(FallbackMode.class, AzuriteConfig.betterSlowdownFallbackMode.getValue().toUpperCase()); + } catch (Exception ex) { + mode = FallbackMode.CLIENT; + } + + // We don't have to worry about overwriting sprint or no sprint for self player, (tbh this might change ground particles for other players) + if (mode != FallbackMode.SERVER) { + if (mode == FallbackMode.SPRINT + || (mode == FallbackMode.CLIENT && data.isClientSprintingState())) { + // Rewrite with sprinting = true + packetBitmask |= MetadataValues.FLAG_SPRINTING; + entityData.a(packetBitmask); + } else if (mode == FallbackMode.NO_SPRINT + || (mode == FallbackMode.CLIENT && !data.isClientSprintingState())) { + // Rewrite with sprinting = false + packetBitmask &= ~MetadataValues.FLAG_SPRINTING; + entityData.a(packetBitmask); + } + } + } else { + // The bitmask update wasn't useful, either remove this part if there's more metadata or cancel the packet + if (wrapper.b.size() != 1) { + iterator.remove(); + } else { + return false; + } + } + } + } + + return true; + } + + public boolean handleAttributes(UUID uuid, PacketPlayOutUpdateAttributes wrapper) { + if (!AzuriteConfig.betterSlowdownEnabled.getValue()) return true; + + Iterator iterator = wrapper.b.iterator(); + + while (iterator.hasNext()) { + PacketPlayOutUpdateAttributes.AttributeSnapshot snapshot = iterator.next(); + + if (snapshot.a().equals("generic.movementSpeed")) { + // Calculate the movement speed without sprint + boolean exists = snapshot.c().removeIf(modifier -> modifier.a().equals(SPRINT_MODIFIER_UUID)); + + double speed = calculateSpeed(snapshot); + + PlayerData data = manager.get(uuid); + double lastSpeed = data.getLastSpeed(); + + if (lastSpeed != speed) { + // Update the speed + data.setLastSpeed(speed); + + if (exists) { + // Re-add the modifier if packetevents is on default re-encode + snapshot.c().add(SPRINT_MODIFIER); + } else if (AzuriteConfig.betterSlowdownAlwaysAddSprint.getValue() && data.isClientSprintingState()) { + // Add sprint modifier is the client claimed he was sprinting and always add sprint is enabled + snapshot.c().add(SPRINT_MODIFIER); + } + + } else { + // Cancel this attribute packet as it only changes the sprint attribute + if (wrapper.b.size() != 1) { + iterator.remove(); + } else { + return false; + } + } + } + } + + return true; + } + + private double calculateSpeed(PacketPlayOutUpdateAttributes.AttributeSnapshot snapshot) { + double value = snapshot.b(); + + for (AttributeModifier modifier : snapshot.c()) { + if (modifier.c() == 0) { + value += modifier.d(); + } + } + + double newValue = value; + for (AttributeModifier modifier : snapshot.c()) { + if (modifier.c() == 1) { + newValue += value * modifier.d(); + } + } + + for (AttributeModifier modifier : snapshot.c()) { + if (modifier.c() == 2) { + newValue *= 1.0D + modifier.d(); + } + } + + if (newValue < 0.0D) { + newValue = 0.0D; + } + + if (newValue > Double.MAX_VALUE) { + newValue = Double.MAX_VALUE; + } + + return newValue; + } +} diff --git a/azurite-server/src/main/java/dev/azurite/spigot/betterslowdown/FallbackMode.java b/azurite-server/src/main/java/dev/azurite/spigot/betterslowdown/FallbackMode.java new file mode 100644 index 0000000..7b81f77 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/betterslowdown/FallbackMode.java @@ -0,0 +1,8 @@ +package dev.azurite.spigot.betterslowdown; + +public enum FallbackMode { + SERVER, + SPRINT, + NO_SPRINT, + CLIENT +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/betterslowdown/MetadataValues.java b/azurite-server/src/main/java/dev/azurite/spigot/betterslowdown/MetadataValues.java new file mode 100644 index 0000000..0487452 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/betterslowdown/MetadataValues.java @@ -0,0 +1,11 @@ +package dev.azurite.spigot.betterslowdown; + +/** + * https://minecraft.wiki/w/Minecraft_Wiki:Projects/wiki.vg_merge/Entity_metadata + */ +public class MetadataValues { + public static final int BITMASK_INDEX = 0; + public static final byte FLAG_CROUCHING = 0x02; + public static final byte FLAG_SPRINTING = 0x08; + public static final byte FLAG_USING = 0x10; +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/betterslowdown/data/PlayerData.java b/azurite-server/src/main/java/dev/azurite/spigot/betterslowdown/data/PlayerData.java new file mode 100644 index 0000000..e80720b --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/betterslowdown/data/PlayerData.java @@ -0,0 +1,41 @@ +package dev.azurite.spigot.betterslowdown.data; + +public class PlayerData { + private byte lastUsefulBitmask; + private double lastSpeed; + private boolean clientSprintingState; + + public PlayerData() { + this.reset(); + } + + public void reset() { + this.lastUsefulBitmask = (byte) -1; + this.lastSpeed = -1.0D; + this.clientSprintingState = false; + } + + public double getLastSpeed() { + return lastSpeed; + } + + public byte getLastUsefulBitmask() { + return lastUsefulBitmask; + } + + public boolean isClientSprintingState() { + return clientSprintingState; + } + + public void setLastUsefulBitmask(byte lastUsefulBitmask) { + this.lastUsefulBitmask = lastUsefulBitmask; + } + + public void setLastSpeed(double lastSpeed) { + this.lastSpeed = lastSpeed; + } + + public void setClientSprintingState(boolean clientSprintingState) { + this.clientSprintingState = clientSprintingState; + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/betterslowdown/data/PlayerDataManager.java b/azurite-server/src/main/java/dev/azurite/spigot/betterslowdown/data/PlayerDataManager.java new file mode 100644 index 0000000..16771b8 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/betterslowdown/data/PlayerDataManager.java @@ -0,0 +1,28 @@ +package dev.azurite.spigot.betterslowdown.data; + +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +public class PlayerDataManager { + private final Map userMap = new ConcurrentHashMap<>(); + + public void cache(UUID user, PlayerData data) { + userMap.put(user, data); + } + + public void remove(UUID user) { + userMap.remove(user); + } + + public PlayerData get(UUID user) { + PlayerData data = userMap.get(user); + + if (data == null) { + data = new PlayerData(); + userMap.put(user, data); + } + + return data; + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/command/AzuriteSpigotCommand.java b/azurite-server/src/main/java/dev/azurite/spigot/command/AzuriteSpigotCommand.java new file mode 100644 index 0000000..af3be60 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/command/AzuriteSpigotCommand.java @@ -0,0 +1,78 @@ +package dev.azurite.spigot.command; + +import dev.azurite.spigot.Azurite; +import dev.azurite.spigot.configs.LanguageConfig; +import dev.azurite.spigot.framework.commands.Command; +import dev.azurite.spigot.menu.MainAzuriteMenu; +import net.minecraft.server.PlayerConnection; +import org.bukkit.Bukkit; +import org.bukkit.Color; +import org.bukkit.command.CommandSender; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.entity.Player; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public class AzuriteSpigotCommand extends Command { + + public AzuriteSpigotCommand() { + super("azuritespigot"); + this.setPermission("azuritespigot.config"); + this.setAliases(Arrays.asList("spigotconfig", "config")); + } + + @Override + public void execute(CommandSender sender, String[] args) { + if (args.length == 2 && args[0].equals("teleportqueue")) { + Player player = Bukkit.getPlayer(args[1]); + + if (player != null) { + PlayerConnection playerConnection = ((CraftPlayer) player).getHandle().playerConnection; + sender.sendMessage(player.getName() + " has " + (playerConnection.getTeleportQueueSize()) + " teleports queued!"); + sender.sendMessage("Check movement: " + playerConnection.isCheckMovement()); + } else { + sender.sendMessage("Could not find that player"); + } + return; + } + + if (args.length == 0 || !args[0].equalsIgnoreCase("reload")) { + if (!(sender instanceof Player)) { + sendMessage(sender, LanguageConfig.onlyPlayer.getValue()); + return; + } + + Player player = (Player) sender; + new MainAzuriteMenu(player).open(); + return; + } + + long now = System.currentTimeMillis(); + Azurite.getInstance().reload(); + long after = System.currentTimeMillis() - now; + + sendMessage(sender, LanguageConfig.configReloaded.getValue() + .replace("%ms%", String.valueOf(after)) + ); + } + + @Override + public List tabComplete(CommandSender sender, String[] args) { + if (args.length == 1) { + String string = args[args.length - 1]; + return Stream.of("reload") + .filter(s -> s.regionMatches(true, 0, string, 0, string.length())) + .collect(Collectors.toList()); + } + + return super.tabComplete(sender, args); + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/command/ClearLagCommand.java b/azurite-server/src/main/java/dev/azurite/spigot/command/ClearLagCommand.java new file mode 100644 index 0000000..a130eec --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/command/ClearLagCommand.java @@ -0,0 +1,40 @@ +package dev.azurite.spigot.command; + +import dev.azurite.spigot.configs.LanguageConfig; +import dev.azurite.spigot.framework.commands.Command; +import net.minecraft.server.*; +import org.bukkit.command.CommandSender; + +import java.util.Arrays; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public class ClearLagCommand extends Command { + + public ClearLagCommand() { + super("clearlag"); + this.setPermission("azuritespigot.clearlag"); + this.setAliases(Arrays.asList("killentities", "clearentities")); + } + + @Override + public void execute(CommandSender sender, String[] args) { + int entities = 0; + + for (World world : MinecraftServer.getServer().worlds) { + for (Entity entity : world.entityList) { + if (entity instanceof EntityItemFrame) continue; // Azurite + if (entity instanceof EntityPlayer || entity.dead || entity.hasCustomName()) continue; + entity.dead = true; + entities++; + } + } + + sendMessage(sender, LanguageConfig.clearedLag.getValue() + .replace("%entities%", String.valueOf(entities)) + ); + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/command/KnockbackCommand.java b/azurite-server/src/main/java/dev/azurite/spigot/command/KnockbackCommand.java new file mode 100644 index 0000000..b42e818 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/command/KnockbackCommand.java @@ -0,0 +1,493 @@ +package dev.azurite.spigot.command; + +import dev.azurite.spigot.Azurite; +import dev.azurite.spigot.api.knockback.IKnockback; +import dev.azurite.spigot.configs.LanguageConfig; +import dev.azurite.spigot.configs.extra.ConfigSetting; +import dev.azurite.spigot.framework.commands.Command; +import dev.azurite.spigot.knockback.Knockback; +import dev.azurite.spigot.knockback.KnockbackManager; +import dev.azurite.spigot.knockback.KnockbackType; +import dev.azurite.spigot.knockback.extra.KnockbackEdit; +import dev.azurite.spigot.menu.ConfigEditMenu; +import dev.azurite.spigot.utils.fanciful.FancyMessage; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.Arrays; +import java.util.List; +import java.util.function.UnaryOperator; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public class KnockbackCommand extends Command { + + public KnockbackCommand() { + super("knockback"); + this.setPermission("azuritespigot.knockback"); + this.setAliases(Arrays.asList("kb", "kbprofiles")); + } + + @Override + public void execute(CommandSender sender, String[] args) { + if (args.length == 0) { + sendUsage(sender); + return; + } + + KnockbackManager manager = Azurite.getInstance().getKnockbackManager(); + + switch (args[0].toLowerCase()) { + case "create": + if (args.length < 2) { + sendMessage(sender, LanguageConfig.createUsage.getValue()); + return; + } + + String create = args[1]; + + if (manager.getByName(create) != null) { + sendMessage(sender, LanguageConfig.createExists.getValue() + .replace("%name%", create) + ); + return; + } + + IKnockback knockback = manager.createProfile(create); + sendMessage(sender, LanguageConfig.createProfile.getValue() + .replace("%name%", knockback.getName()) + ); + return; + + case "delete": + if (args.length < 2) { + sendMessage(sender, LanguageConfig.deleteUsage.getValue()); + return; + } + + String delete = args[1]; + + if (manager.getByName(delete) == null) { + sendMessage(sender, LanguageConfig.profileNotFound.getValue() + .replace("%name%", delete) + ); + return; + } + + if (manager.getActiveProfile().getName().equalsIgnoreCase(delete)) { + sendMessage(sender, LanguageConfig.deleteActive.getValue() + .replace("%name%", delete) + ); + return; + } + + manager.deleteProfile(delete); + sendMessage(sender, LanguageConfig.deleteProfile.getValue() + .replace("%name%", delete) + ); + return; + + case "list": + for (String s : LanguageConfig.listMessage.getValue()) { + if (!s.equalsIgnoreCase("%profiles%")) { + sendMessage(sender, s); + continue; + } + + for (IKnockback profile : manager.getProfiles()) { + String name = (profile.isActive() ? LanguageConfig.listNameActive.getValue() : LanguageConfig.listName.getValue()); + new FancyMessage(name.replace("%name%", profile.getName()).replace("%type%", profile.getType())) + .tooltip(LanguageConfig.listNameHover.getValue().replace("%name%", profile.getName())) + .command("/knockback view " + profile.getName()) + .send(sender); + } + } + return; + + case "settype": + if (args.length < 2) { + sendMessage(sender, LanguageConfig.setTypeUsage.getValue()); + return; + } + + Knockback changingType = (Knockback) manager.getByName(args[1]); + KnockbackType type; + + if (changingType == null) { + sendMessage(sender, LanguageConfig.profileNotFound.getValue() + .replace("%name%", args[1]) + ); + return; + } + + if (args.length == 2) { + new FancyMessage(LanguageConfig.setTypePrefix.getValue()) + .then(LanguageConfig.setTypeSimple.getValue()) + .tooltip(LanguageConfig.setTypeSimpleHover.getValue()) + .command("/knockback settype " + changingType.getName() + " SIMPLE") + .then(" ") + .then(LanguageConfig.setTypeAdvanced.getValue()) + .tooltip(LanguageConfig.setTypeAdvancedHover.getValue()) + .command("/knockback settype " + changingType.getName() + " ADVANCED") + .send(sender); + return; + } + + try { + + type = KnockbackType.valueOf(args[2]); + + } catch (IllegalArgumentException e) { + sendMessage(sender, LanguageConfig.setTypeNotFound.getValue()); + return; + } + + if (changingType.getKnockbackType() == type) { + sendMessage(sender, LanguageConfig.setTypeAlready.getValue() + .replace("%name%", changingType.getName()) + .replace("%type%", type.getDisplayName()) + ); + return; + } + + changingType.knockbackType.set(type.name(), true); + sendMessage(sender, LanguageConfig.setType.getValue() + .replace("%name%", changingType.getName()) + .replace("%type%", type.getDisplayName()) + ); + return; + + case "setactive": + if (args.length < 2) { + sendMessage(sender, LanguageConfig.setActiveUsage.getValue()); + return; + } + + IKnockback active = manager.getByName(args[1]); + + if (active == null) { + sendMessage(sender, LanguageConfig.profileNotFound.getValue() + .replace("%name%", args[1]) + ); + return; + } + + if (manager.getActiveProfile().getName().equalsIgnoreCase(active.getName())) { + sendMessage(sender, LanguageConfig.setActiveAlready.getValue() + .replace("%name%", active.getName()) + ); + return; + } + + manager.setActiveProfile(active); + sendMessage(sender, LanguageConfig.setActive.getValue() + .replace("%name%", active.getName()) + ); + return; + + case "view": + if (args.length < 2) { + sendMessage(sender, LanguageConfig.viewUsage.getValue()); + return; + } + + IKnockback view = manager.getByName(args[1]); + + if (view == null) { + sendMessage(sender, LanguageConfig.profileNotFound.getValue() + .replace("%name%", args[1]) + ); + return; + } + + for (String s : LanguageConfig.viewMessage.getValue()) { + if (s.equalsIgnoreCase("%values%")) { + for (ConfigSetting setting : ((Knockback) view).getActiveSettings()) { + UnaryOperator replacer = string -> string + .replace("%setting%", setting.getName()) + .replace("%type%", view.getType()) + .replace("%value%", setting.getValue().toString()); + + new FancyMessage(replacer.apply(LanguageConfig.viewSetting.getValue())) + .tooltip(replacer.apply(LanguageConfig.viewSettingHover.getValue())) + .command("/knockback edit " + view.getName() + " " + setting.getName()) + .send(sender); + } + continue; + } + + if (s.equalsIgnoreCase("%clickables%")) { + UnaryOperator replacer = string -> string.replace("%name%", view.getName()); + new FancyMessage(LanguageConfig.viewSetActiveClick.getValue()) + .tooltip(replacer.apply(LanguageConfig.viewSetActiveClickHover.getValue())) + .command("/knockback setactive " + view.getName()) + .then(" ") + .then(LanguageConfig.viewDeleteClick.getValue()) + .tooltip(replacer.apply(LanguageConfig.viewDeleteClickHover.getValue())) + .command("/knockback delete " + view.getName()) + .then(" ") + .then(LanguageConfig.viewEditClick.getValue()) + .tooltip(replacer.apply(LanguageConfig.viewEditHover.getValue())) + .command("/knockback editmenu " + view.getName()) + .send(sender); + continue; + } + + if (s.equalsIgnoreCase("%settype%")) { + UnaryOperator replacer = string -> string.replace("%name%", view.getName()); + new FancyMessage(LanguageConfig.viewSetTypeClick.getValue()) + .tooltip(replacer.apply(LanguageConfig.viewSetTypeHover.getValue())) + .command("/knockback settype " + view.getName()) + .send(sender); + continue; + } + + sendMessage(sender, s + .replace("%name%", view.getName()) + .replace("%type%", view.getType()) + ); + } + return; + + case "edit": + if (args.length < 3) { + sendMessage(sender, LanguageConfig.editUsage.getValue()); + return; + } + + Knockback editing = (Knockback) manager.getByName(args[1]); + + if (editing == null) { + sendMessage(sender, LanguageConfig.profileNotFound.getValue() + .replace("%name%", args[1]) + ); + return; + } + + ConfigSetting configSetting = editing.getActiveSetting(args[2]); + + if (configSetting == null) { + sendMessage(sender, LanguageConfig.editSettingNotFound.getValue() + .replace("%setting%", args[2]) + ); + return; + } + + if (args.length == 4) { + Object value = configSetting.parseValue(args[3]); + + if (value == null) { + sendMessage(sender, LanguageConfig.notValidType.getValue() + .replace("%value%", args[3]) + .replace("%type%", configSetting.getValue().getClass().getSimpleName()) + ); + return; + } + + configSetting.set(value, true); + sendMessage(sender, LanguageConfig.editSettingValue.getValue() + .replace("%setting%", configSetting.getName()) + .replace("%value%", args[3]) + .replace("%profile%", editing.getName()) + ); + return; + } + + if (!(sender instanceof Player)) { + sendMessage(sender, LanguageConfig.onlyPlayer.getValue()); + return; + } + + Player player = (Player) sender; + manager.getEditing().put(player.getUniqueId(), new KnockbackEdit(editing.getName(), configSetting)); + sendMessage(sender, LanguageConfig.editTypeNewValue.getValue() + .replace("%setting%", configSetting.getName()) + .replace("%current%", configSetting.getValue().toString()) + .replace("%profile%", editing.getName()) + ); + return; + + case "editmenu": + if (args.length < 2) { + sendMessage(sender, LanguageConfig.editMenuUsage.getValue()); + return; + } + + if (!(sender instanceof Player)) { + sendMessage(sender, LanguageConfig.onlyPlayer.getValue()); + return; + } + + Player opening = (Player) sender; + Knockback editMenu = (Knockback) manager.getByName(args[1]); + + if (editMenu == null) { + sendMessage(sender, LanguageConfig.profileNotFound.getValue() + .replace("%name%", args[1]) + ); + return; + } + + new ConfigEditMenu(opening, editMenu, null, editMenu.getActiveSettings()).open(); + return; + + case "set": + if (args.length < 3) { + sendMessage(sender, LanguageConfig.setUsage.getValue()); + return; + } + + IKnockback setting = manager.getByName(args[1]); + Player settingPlayer = Bukkit.getPlayer(args[2]); + + if (setting == null) { + sendMessage(sender, LanguageConfig.profileNotFound.getValue() + .replace("%name%", args[1]) + ); + return; + } + + if (settingPlayer == null) { + sendMessage(sender, LanguageConfig.playerNotFound.getValue() + .replace("%player%", args[2]) + ); + return; + } + + settingPlayer.setKnockbackProfile(setting); + sendMessage(sender, LanguageConfig.setProfile.getValue() + .replace("%profile%", setting.getName()) + .replace("%player%", settingPlayer.getName()) + ); + return; + + case "clear": + if (args.length < 2) { + sendMessage(sender, LanguageConfig.clearUsage.getValue()); + return; + } + + Player clearingPlayer = Bukkit.getPlayer(args[1]); + + if (clearingPlayer == null) { + sendMessage(sender, LanguageConfig.playerNotFound.getValue() + .replace("%player%", args[1]) + ); + return; + } + + clearingPlayer.setKnockbackProfile(null); + sendMessage(sender, LanguageConfig.clearProfile.getValue() + .replace("%player%", clearingPlayer.getName()) + ); + return; + } + + sendUsage(sender); + } + + private void sendUsage(CommandSender sender) { + for (String s : LanguageConfig.knockbackUsage.getValue()) { + if (!s.equalsIgnoreCase("%commands%")) { + sendMessage(sender, s); + continue; + } + + Arrays.asList( + new FancyMessage(LanguageConfig.createUsage.getValue()) + .tooltip(LanguageConfig.createHover.getValue()) + .suggest("/knockback create "), + + new FancyMessage(LanguageConfig.deleteUsage.getValue()) + .tooltip(LanguageConfig.deleteHover.getValue()) + .suggest("/knockback delete "), + + new FancyMessage(LanguageConfig.viewUsage.getValue()) + .tooltip(LanguageConfig.viewHover.getValue()) + .suggest("/knockback view "), + + new FancyMessage(LanguageConfig.editUsage.getValue()) + .tooltip(LanguageConfig.editHover.getValue()) + .suggest("/knockback edit "), + + new FancyMessage(LanguageConfig.editMenuUsage.getValue()) + .tooltip(LanguageConfig.editMenuHover.getValue()) + .suggest("/knockback editmenu "), + + new FancyMessage(LanguageConfig.setUsage.getValue()) + .tooltip(LanguageConfig.setHover.getValue()) + .suggest("/knockback set "), + + new FancyMessage(LanguageConfig.clearUsage.getValue()) + .tooltip(LanguageConfig.clearHover.getValue()) + .suggest("/knockback clear "), + + new FancyMessage(LanguageConfig.setTypeUsage.getValue()) + .tooltip(LanguageConfig.setTypeHover.getValue()) + .suggest("/knockback settype "), + + new FancyMessage(LanguageConfig.setActiveUsage.getValue()) + .tooltip(LanguageConfig.setActiveHover.getValue()) + .suggest("/knockback setactive "), + + new FancyMessage(LanguageConfig.listUsage.getValue()) + .tooltip(LanguageConfig.listHover.getValue()) + .command("/knockback list") + + ).forEach(message -> message.send(sender)); + } + } + + @Override + public List tabComplete(CommandSender sender, String[] args) { + if (args[0].equalsIgnoreCase("create")) { + return null; + } + + if (args[0].equalsIgnoreCase("clear")) { + return super.tabComplete(sender, args); // Return player list + } + + if (args[0].equalsIgnoreCase("settype") && args.length == 3) { + String string = args[args.length - 1]; + return Arrays.stream(KnockbackType.values()) + .map(KnockbackType::name) + .filter(s -> s.regionMatches(true, 0, string, 0, string.length())) + .collect(Collectors.toList()); + } + + if (args[0].equalsIgnoreCase("edit") && args.length == 3) { + IKnockback knockback = Azurite.getInstance().getKnockbackManager().getByName(args[1]); + + if (knockback != null) { + String string = args[args.length - 1]; + return knockback.getValues().keySet().stream() + .filter(s -> s.regionMatches(true, 0, string, 0, string.length())) + .collect(Collectors.toList()); + } + } + + if (args.length == 1) { + String string = args[args.length - 1]; + return Stream.of("delete", "create", "setactive", "list", "edit", "editmenu", "set", "view", "clear") + .filter(s -> s.regionMatches(true, 0, string, 0, string.length())) + .collect(Collectors.toList()); + } + + if (args.length == 2) { + String string = args[args.length - 1]; + return Azurite.getInstance().getKnockbackManager().getProfiles().stream() + .map(IKnockback::getName) + .filter(s -> s.regionMatches(true, 0, string, 0, string.length())) + .collect(Collectors.toList()); + } + + return super.tabComplete(sender, args); + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/command/NoTrackCommand.java b/azurite-server/src/main/java/dev/azurite/spigot/command/NoTrackCommand.java new file mode 100644 index 0000000..8202231 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/command/NoTrackCommand.java @@ -0,0 +1,45 @@ +package dev.azurite.spigot.command; + +import dev.azurite.spigot.Azurite; +import dev.azurite.spigot.configs.LanguageConfig; +import dev.azurite.spigot.framework.commands.Command; +import org.bukkit.command.CommandSender; + +import java.util.Arrays; + +/** + * Copyright (c) 2025. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public class NoTrackCommand extends Command { + + public NoTrackCommand() { + super("notrack"); + this.setPermission("azuritespigot.notrack"); + this.setAliases(Arrays.asList("hiderange", "hideplayers")); + } + + @Override + public void execute(CommandSender sender, String[] args) { + if (args.length == 0) { + sendMessage(sender, LanguageConfig.noTrackUsage.getValue()); + return; + } + + Integer amount = getInt(args[0]); + + if (amount == null) { + sendMessage(sender, LanguageConfig.notValidType.getValue() + .replace("%value%", args[0]) + .replace("%type%", Integer.class.getSimpleName()) + ); + return; + } + + Azurite.getInstance().setNoTrackRange(amount); + sendMessage(sender, LanguageConfig.noTrackSet.getValue() + .replace("%range%", String.valueOf(amount)) + ); + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/command/PingCommand.java b/azurite-server/src/main/java/dev/azurite/spigot/command/PingCommand.java new file mode 100644 index 0000000..f16aaae --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/command/PingCommand.java @@ -0,0 +1,53 @@ +package dev.azurite.spigot.command; + +import dev.azurite.spigot.configs.LanguageConfig; +import dev.azurite.spigot.framework.commands.Command; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.entity.Player; + +import java.util.Arrays; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public class PingCommand extends Command { + + public PingCommand() { + super("ping"); + this.setAliases(Arrays.asList("latency", "myping")); + } + + @Override + public void execute(CommandSender sender, String[] args) { + if (args.length == 0) { + if (!(sender instanceof Player)) { + sendMessage(sender, LanguageConfig.onlyPlayer.getValue()); + return; + } + + Player player = (Player) sender; + sendMessage(sender, LanguageConfig.playerPing.getValue() + .replace("%ping%", String.valueOf(((CraftPlayer) player).getHandle().getPing())) + ); + return; + } + + Player target = Bukkit.getPlayer(args[0]); + + if (target == null) { + sendMessage(sender, LanguageConfig.playerNotFound.getValue() + .replace("%player%", args[0]) + ); + return; + } + + sendMessage(sender, LanguageConfig.otherPlayerPing.getValue() + .replace("%player%", target.getName()) + .replace("%ping%", String.valueOf(((CraftPlayer) target).getHandle().getPing())) + ); + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/command/SetMaxPlayersCommand.java b/azurite-server/src/main/java/dev/azurite/spigot/command/SetMaxPlayersCommand.java new file mode 100644 index 0000000..9547076 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/command/SetMaxPlayersCommand.java @@ -0,0 +1,45 @@ +package dev.azurite.spigot.command; + +import dev.azurite.spigot.configs.LanguageConfig; +import dev.azurite.spigot.framework.commands.Command; +import net.minecraft.server.MinecraftServer; +import org.bukkit.command.CommandSender; + +import java.util.Arrays; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public class SetMaxPlayersCommand extends Command { + + public SetMaxPlayersCommand() { + super("setmaxplayers"); + this.setPermission("azuritespigot.setmaxplayers"); + this.setAliases(Arrays.asList("setslots", "setmaxonline")); + } + + @Override + public void execute(CommandSender sender, String[] args) { + if (args.length == 0) { + sendMessage(sender, LanguageConfig.setMaxPlayersUsage.getValue()); + return; + } + + Integer amount = getInt(args[0]); + + if (amount == null) { + sendMessage(sender, LanguageConfig.notValidType.getValue() + .replace("%value%", args[0]) + .replace("%type%", Integer.class.getSimpleName()) + ); + return; + } + + MinecraftServer.getServer().getPlayerList().maxPlayers = amount; + sendMessage(sender, LanguageConfig.setMaxPlayers.getValue() + .replace("%amount%", amount.toString()) + ); + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/command/TPSCommand.java b/azurite-server/src/main/java/dev/azurite/spigot/command/TPSCommand.java new file mode 100644 index 0000000..a969136 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/command/TPSCommand.java @@ -0,0 +1,98 @@ +package dev.azurite.spigot.command; + +import dev.azurite.spigot.configs.LanguageConfig; +import dev.azurite.spigot.framework.commands.Command; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.WorldServer; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; + +import java.util.Arrays; +import java.util.Set; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public class TPSCommand extends Command { + + private static final long STARTUP_TIME = System.currentTimeMillis(); + + public TPSCommand() { + super("tps"); + this.setPermission("azuritespigot.tps"); + this.setAliases(Arrays.asList("tickspersecond", "stps", "servertps")); + } + + @Override + public void execute(CommandSender sender, String[] args) { + Set threads = Thread.getAllStackTraces().keySet(); + + double[] tps = MinecraftServer.getServer().recentTps; + long totalMemory = Runtime.getRuntime().totalMemory() / 1048576L; + long freeMemory = Runtime.getRuntime().freeMemory() / 1048576L; + + long aliveThreads = threads.stream().filter(Thread::isAlive).count(); + long interruptedThreads = threads.stream().filter(Thread::isInterrupted).count(); + long daemonThreads = threads.stream().filter(Thread::isDaemon).count(); + + int chunks = 0; + int entities = 0; + int tiles = 0; + + for (WorldServer world : MinecraftServer.getServer().worlds) { + entities += world.entityList.size(); + tiles += world.tileEntityList.size(); + chunks += world.chunkProviderServer.chunks.size(); + } + + for (String string : LanguageConfig.tpsMessage.getValue()) { + sendMessage(sender, string + .replace("%server_tps%", Arrays.stream(tps).mapToObj(this::format).collect(Collectors.joining(", "))) + .replace("%uptime%", formatTime(System.currentTimeMillis() - STARTUP_TIME).trim()) + .replace("%players%", String.valueOf(MinecraftServer.getServer().getPlayerList().players.size())) + .replace("%max_players%", String.valueOf(MinecraftServer.getServer().getPlayerList().maxPlayers)) + + .replace("%threads%", String.valueOf(threads.size())) + .replace("%alive%", String.valueOf(aliveThreads)) + .replace("%interrupted%", String.valueOf(interruptedThreads)) + .replace("%daemon%", String.valueOf(daemonThreads)) + + .replace("%entities%", Integer.toString(entities)) + .replace("%tiles%", Integer.toString(tiles)) + .replace("%chunks%", Integer.toString(chunks)) + + .replace("%free_memory%", Long.toString(freeMemory)) + .replace("%max_memory%", Long.toString(totalMemory)) + ); + } + } + + private String formatTime(long millis) { + long days = TimeUnit.MILLISECONDS.toDays(millis); + millis -= TimeUnit.DAYS.toMillis(days); + long hours = TimeUnit.MILLISECONDS.toHours(millis); + millis -= TimeUnit.HOURS.toMillis(hours); + long minutes = TimeUnit.MILLISECONDS.toMinutes(millis); + millis -= TimeUnit.MINUTES.toMillis(minutes); + long seconds = TimeUnit.MILLISECONDS.toSeconds(millis); + StringBuilder sb = new StringBuilder(64); + if (days > 0L) + sb.append(days).append("d "); + if (hours > 0L) + sb.append(hours).append("h "); + if (minutes > 0L) + sb.append(minutes).append("m "); + if (seconds > 0L) + sb.append(seconds).append("s "); + return sb.toString(); + } + + private String format(double tps) { + return ((tps > 18.0) ? ChatColor.GREEN : (tps > 16.0) ? ChatColor.YELLOW : ChatColor.RED) + + ((tps > 20.0) ? "*" : "") + Math.min(Math.round(tps * 100.0) / 100.0, 20.0); + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/command/UnloadChunksCommand.java b/azurite-server/src/main/java/dev/azurite/spigot/command/UnloadChunksCommand.java new file mode 100644 index 0000000..84382df --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/command/UnloadChunksCommand.java @@ -0,0 +1,46 @@ +package dev.azurite.spigot.command; + +import dev.azurite.spigot.configs.LanguageConfig; +import dev.azurite.spigot.framework.commands.Command; +import org.bukkit.Bukkit; +import org.bukkit.Chunk; +import org.bukkit.World; +import org.bukkit.command.CommandSender; +import org.bukkit.event.world.ChunkUnloadEvent; + +import java.util.Arrays; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public class UnloadChunksCommand extends Command { + + public UnloadChunksCommand() { + super("unloadchunks"); + this.setPermission("azuritespigot.unloadchunks"); + this.setAliases(Arrays.asList("chunkunload", "chunksunload")); + } + + @Override + public void execute(CommandSender sender, String[] args) { + int chunks = 0; + + for (World world : Bukkit.getServer().getWorlds()) { + for (Chunk chunk : world.getLoadedChunks()) { + if (world.isChunkInUse(chunk.getX(), chunk.getZ())) continue; + + if (chunk.unload(true)) { + ChunkUnloadEvent event = new ChunkUnloadEvent(chunk); // Azurite - Call chunk unload if the chunk was unloaded. + Bukkit.getPluginManager().callEvent(event); + chunks++; + } + } + } + + sendMessage(sender, LanguageConfig.unloadedChunks.getValue() + .replace("%amount%", String.valueOf(chunks)) + ); + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/command/VersionCommand.java b/azurite-server/src/main/java/dev/azurite/spigot/command/VersionCommand.java new file mode 100644 index 0000000..c1e5159 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/command/VersionCommand.java @@ -0,0 +1,119 @@ +package dev.azurite.spigot.command; + +import dev.azurite.spigot.configs.LanguageConfig; +import dev.azurite.spigot.framework.commands.Command; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.PluginDescriptionFile; +import org.bukkit.util.StringUtil; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class VersionCommand extends Command { + + public VersionCommand() { + super("version"); + this.setAliases(Arrays.asList("ver", "about", "icanhasbukkit")); + } + + @Override + public void execute(CommandSender sender, String[] args) { + if (args.length > 0 && sender.hasPermission("bukkit.command.version")) { + StringBuilder name = new StringBuilder(); + + for (String arg : args) { + if (name.length() > 0) name.append(' '); + name.append(arg); + } + + String pluginName = name.toString(); + Plugin exactPlugin = Bukkit.getPluginManager().getPlugin(pluginName); + + if (exactPlugin != null) { + describeToSender(exactPlugin, sender); + return; + } + + boolean found = false; + pluginName = pluginName.toLowerCase(); + for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) { + if (plugin.getName().toLowerCase().contains(pluginName)) { + describeToSender(plugin, sender); + found = true; + } + } + + if (!found) { + sender.sendMessage("This server is not running any plugin by that name."); + sender.sendMessage("Use /plugins to get a list of plugins."); + } + return; + } + + for (String string : LanguageConfig.versionMessage.getValue()) { + sendMessage(sender, string); + } + } + + private void describeToSender(Plugin plugin, CommandSender sender) { + PluginDescriptionFile desc = plugin.getDescription(); + sender.sendMessage(ChatColor.GREEN + desc.getName() + ChatColor.WHITE + " version " + ChatColor.GREEN + desc.getVersion()); + + if (desc.getDescription() != null) { + sender.sendMessage(desc.getDescription()); + } + + if (desc.getWebsite() != null) { + sender.sendMessage("Website: " + ChatColor.GREEN + desc.getWebsite()); + } + + if (!desc.getAuthors().isEmpty()) { + if (desc.getAuthors().size() == 1) { + sender.sendMessage("Author: " + getAuthors(desc)); + } else { + sender.sendMessage("Authors: " + getAuthors(desc)); + } + } + } + + private String getAuthors(final PluginDescriptionFile desc) { + StringBuilder result = new StringBuilder(); + List authors = desc.getAuthors(); + + for (int i = 0; i < authors.size(); i++) { + if (result.length() > 0) { + result.append(ChatColor.WHITE); + + if (i < authors.size() - 1) { + result.append(", "); + } else { + result.append(" and "); + } + } + + result.append(ChatColor.GREEN); + result.append(authors.get(i)); + } + + return result.toString(); + } + + @Override + public List tabComplete(CommandSender sender, String[] args) { + if (args.length == 1 && sender.hasPermission("bukkit.command.version")) { + List completions = new ArrayList<>(); + String toComplete = args[0].toLowerCase(); + for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) { + if (StringUtil.startsWithIgnoreCase(plugin.getName(), toComplete)) { + completions.add(plugin.getName()); + } + } + return completions; + } + return super.tabComplete(sender, args); + } +} diff --git a/azurite-server/src/main/java/dev/azurite/spigot/configs/AzuriteConfig.java b/azurite-server/src/main/java/dev/azurite/spigot/configs/AzuriteConfig.java new file mode 100644 index 0000000..a3418dc --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/configs/AzuriteConfig.java @@ -0,0 +1,314 @@ +package dev.azurite.spigot.configs; + +import dev.azurite.spigot.Azurite; +import dev.azurite.spigot.configs.extra.Config; +import dev.azurite.spigot.configs.extra.ConfigSetting; +import dev.azurite.spigot.utils.CC; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public class AzuriteConfig extends Config { + + // License + public static final ConfigSetting serverBranding = new ConfigSetting<>("AzuriteSpigot", "", "Used for commands and server ping data", false); + + // Worlds ticking + public static final ConfigSetting disableBlockLighting = new ConfigSetting<>(false, "worlds.ticking"); + public static final ConfigSetting tickBlocks = new ConfigSetting<>(true, "worlds.ticking"); + public static final ConfigSetting tickTileEntities = new ConfigSetting<>(true, "worlds.ticking"); + public static final ConfigSetting tickBeacons = new ConfigSetting<>(true, "worlds.ticking"); + public static final ConfigSetting tickBrewingStands = new ConfigSetting<>(true, "worlds.ticking"); + public static final ConfigSetting tickHoppers = new ConfigSetting<>(true, "worlds.ticking"); + public static final ConfigSetting tickVillages = new ConfigSetting<>(false, "worlds.ticking"); + public static final ConfigSetting tickFurnaces = new ConfigSetting<>(true, "worlds.ticking"); + public static final ConfigSetting tickChunks = new ConfigSetting<>(true, "worlds.ticking"); + public static final ConfigSetting tickBiomeCache = new ConfigSetting<>(true, "worlds.ticking"); + public static final ConfigSetting tickWeather = new ConfigSetting<>(true, "worlds.ticking"); + public static final ConfigSetting processPacketsInBetweenTicks = new ConfigSetting<>(true, "worlds.ticking", "Should we process packets between ticks, it is heavily recommended to keep this option toggled on"); + public static final ConfigSetting flushWorldChangesInBetweenTicks = new ConfigSetting<>(true, "worlds.ticking", "Should we flush world changes in between ticks"); + + // Async Data Saving + public static final ConfigSetting asyncWorldDataSave = new ConfigSetting<>(true, "worlds.async-saving"); + public static final ConfigSetting asyncNBTFileSave = new ConfigSetting<>(true, "worlds.async-saving"); + public static final ConfigSetting asyncUserCacheSave = new ConfigSetting<>(true, "worlds.async-saving"); + public static final ConfigSetting asyncPlayerDataSave = new ConfigSetting<>(true, "worlds.async-saving"); + public static final ConfigSetting asyncPlayerStatsSave = new ConfigSetting<>(true, "worlds.async-saving"); + + // Auto Save + public static final ConfigSetting autoSaveMessages = new ConfigSetting<>(true, "worlds.autosave"); + public static final ConfigSetting autoSaveInIncrements = new ConfigSetting<>(true, "worlds.autosave"); + public static final ConfigSetting autoSaveChunksPerTick = new ConfigSetting<>(200, "worlds.autosave"); + public static final ConfigSetting autoSaveFireWorldSaveEvent = new ConfigSetting<>(false, "worlds.autosave"); + public static final ConfigSetting autoSaveClearRegionFileCache = new ConfigSetting<>(false, "worlds.autosave"); + + // Commands + public static final ConfigSetting enableSpigotConfigCommand = new ConfigSetting<>(true, "worlds.commands"); + public static final ConfigSetting enablePingCommand = new ConfigSetting<>(true, "worlds.commands"); + public static final ConfigSetting enableTPSCommand = new ConfigSetting<>(true, "worlds.commands"); + public static final ConfigSetting enableChunkUnloadCommand = new ConfigSetting<>(true, "worlds.commands"); + public static final ConfigSetting enableClearLagCommand = new ConfigSetting<>(true, "worlds.commands"); + public static final ConfigSetting enableSetMaxPlayersCommand = new ConfigSetting<>(true, "worlds.commands"); + public static final ConfigSetting enableNoTrackCommand = new ConfigSetting<>(true, "worlds.commands"); + + // Chunks + public static final ConfigSetting cacheChunkMaps = new ConfigSetting<>(true, "worlds.chunks", "IMPORTANT! This patch is from paper and we highly suggest using. However if you get chunk corruption bugs turn this off. We have fixed a major issue with it."); + public static final ConfigSetting nullifyEmptySections = new ConfigSetting<>(false, "worlds.chunks", "This optimizes memory usage by making chunk sections null if they don't have any blocks at startup. This might break light levels and other things. This option is experimental, use at your own risk."); + public static final ConfigSetting chunkLoadingThreads = new ConfigSetting<>(3, "worlds.chunks", false); + public static final ConfigSetting playersPerThread = new ConfigSetting<>(100, "worlds.chunks"); + public static final ConfigSetting chunkUnloading = new ConfigSetting<>(true, "worlds.chunks"); + public static final ConfigSetting unloadPerTick = new ConfigSetting<>(300, "worlds.chunks"); + public static final ConfigSetting sendEmptyChunkSections = new ConfigSetting<>(false, "worlds.chunks", "Blossom patch which sends empty chunk sections to reduce skylight lag spike"); + public static final ConfigSetting preloadChunksOnDimensionChange = new ConfigSetting<>(true, "worlds.chunks", "This option will make dimension changes take a bit longer to use as it will preload chunks asynchronously"); + public static final ConfigSetting forceVoidChunks = new ConfigSetting<>(false, "worlds.chunks", "Generates all new chunks as void"); + + // Patchsearch + public static final ConfigSetting enableAsyncPathSearch = new ConfigSetting<>(true, "worlds.async-pathsearch"); + public static final ConfigSetting pathSearchThreads = new ConfigSetting<>(3, "worlds.async-pathsearch", false); + public static final ConfigSetting minimumDistanceToTarget = new ConfigSetting<>(0.0D, "worlds.async-pathsearch", false); + public static final ConfigSetting> entitiesPathSearchOffload = new ConfigSetting<>(Arrays.asList("BAT", "BLAZE", "CHICKEN", "COW", "CREEPER", "ENDERMAN", "HORSE", "IRON_GOLEM", "MAGMA_CUBE", "MUSHROOM_COW", "PIG", "PIG_ZOMBIE", "RABBIT", "SHEEP", "SKELETON", "SILVERFISH", "SLIME", "SNOWMAN", "SQUID", "WITCH", "ZOMBIE"), "worlds.async-pathsearch", false); + + // Projectiles + public static final ConfigSetting arrowCriticalDamage = new ConfigSetting<>(true, "worlds.projectiles", "Should critical arrow damage be enabled"); + public static final ConfigSetting arrowCriticalDamageMedian = new ConfigSetting<>(true, "worlds.projectiles", "If arrowCriticalDamage is turned off, should we use the median for critical damage"); + public static final ConfigSetting minimumPotionTicksForSelfSplash = new ConfigSetting<>(5, "worlds.projectiles", "Defines the minimum amount of ticks the potion should have existed before it can collide with the shooter"); + public static final ConfigSetting rodTrackedToCenterOfHooked = new ConfigSetting<>(true, "worlds.projectiles", "Should rod be constantly tracked to the center of the hooked entity"); + public static final ConfigSetting checkStartOfRay = new ConfigSetting<>(true, "worlds.projectiles", "Should projectiles check the hitbox at start of ray, this fixes some of the projectiles going through players issues"); + public static final ConfigSetting disableStuckArrows = new ConfigSetting<>(false, "worlds.projectiles", "Should stuck arrows in players be disabled"); + public static final ConfigSetting arrowTrajectoryRandomness = new ConfigSetting<>(0.0F, "worlds.projectiles"); + public static final ConfigSetting rodTrajectoryRandomness = new ConfigSetting<>(1.0F, "worlds.projectiles"); + public static final ConfigSetting snowballTrajectoryRandomness = new ConfigSetting<>(1.0F, "worlds.projectiles"); + public static final ConfigSetting eggTrajectoryRandomness = new ConfigSetting<>(1.0F, "worlds.projectiles"); + public static final ConfigSetting pearlTrajectoryRandomness = new ConfigSetting<>(1.0F, "worlds.projectiles"); + public static final ConfigSetting potionTrajectoryRandomness = new ConfigSetting<>(1.0F, "worlds.projectiles"); + + // Sounds + public static final ConfigSetting itemFizzSounds = new ConfigSetting<>(true, "worlds.sounds"); + public static final ConfigSetting fluidFizzSounds = new ConfigSetting<>(true, "worlds.sounds"); + public static final ConfigSetting mobRandomSounds = new ConfigSetting<>(true, "worlds.sounds"); + public static final ConfigSetting explosionSounds = new ConfigSetting<>(true, "worlds.sounds"); + public static final ConfigSetting footstepSounds = new ConfigSetting<>(false, "worlds.sounds"); + + // Particles + public static final ConfigSetting dispenserEffects = new ConfigSetting<>(true, "worlds.particles"); + public static final ConfigSetting spawnerParticles = new ConfigSetting<>(true, "worlds.particles"); + public static final ConfigSetting explosionParticles = new ConfigSetting<>(true, "worlds.particles"); + public static final ConfigSetting tntParticles = new ConfigSetting<>(true, "worlds.particles"); + public static final ConfigSetting footstepParticles = new ConfigSetting<>(false, "worlds.particles"); + public static final ConfigSetting selfPotionParticles = new ConfigSetting<>(true, "worlds.particles", "Should the player see his own potion particles"); + public static final ConfigSetting drinkablePotionsNoParticles = new ConfigSetting<>(false, "worlds.particles", "Should drinkable potions not show particles"); + + // Modifiers + public static final ConfigSetting furnaceModifier = new ConfigSetting<>(1.0, "worlds.modifiers"); + public static final ConfigSetting brewingModifier = new ConfigSetting<>(1.0, "worlds.modifiers"); + public static final ConfigSetting fallDamageModifier = new ConfigSetting<>(1.0, "worlds.modifiers"); + public static final ConfigSetting critDamageModifier = new ConfigSetting<>(1.5, "worlds.modifiers"); + + // Events + public static final ConfigSetting firePlayerMoveEvent = new ConfigSetting<>(true, "worlds.events"); + public static final ConfigSetting fireBlockPhysicsEvent = new ConfigSetting<>(true, "worlds.events"); + public static final ConfigSetting fireHopperMoveItemEvent = new ConfigSetting<>(true, "worlds.events"); + public static final ConfigSetting fireSandBlockChangeEvent = new ConfigSetting<>(true, "worlds.events"); + public static final ConfigSetting fireSandPhysicsEvent = new ConfigSetting<>(true, "worlds.events"); + public static final ConfigSetting fireRedstonePhysicsEvent = new ConfigSetting<>(true, "worlds.events"); + public static final ConfigSetting fireTNTDispenseEvent = new ConfigSetting<>(true, "worlds.events"); + + // Blocks + public static final ConfigSetting redstoneOptimization = new ConfigSetting<>("EIGENCRAFT", "worlds.blocks", "Redstone implementation. Choose EIGENCRAFT/PANDAWIRE/DEFAULT", false); + public static final ConfigSetting tntYVelocityMultiplier = new ConfigSetting<>(1.0D, "worlds.blocks"); + public static final ConfigSetting optimizeHoppers = new ConfigSetting<>(true, "worlds.blocks", "Use an experimental system to optimize hoppers"); + public static final ConfigSetting gravelFall = new ConfigSetting<>(true, "worlds.blocks"); + public static final ConfigSetting grassSpread = new ConfigSetting<>(true, "worlds.blocks"); + public static final ConfigSetting grassSpreadLight = new ConfigSetting<>(true, "worlds.blocks"); + public static final ConfigSetting leafDecaying = new ConfigSetting<>(true, "worlds.blocks"); + public static final ConfigSetting dropFloatingPlants = new ConfigSetting<>(true, "worlds.blocks"); + public static final ConfigSetting dropExplosionBlocks = new ConfigSetting<>(true, "worlds.blocks"); + public static final ConfigSetting dispenserRandomness = new ConfigSetting<>(true, "worlds.blocks", "Optimizes cannons"); + public static final ConfigSetting pistonPushEntities = new ConfigSetting<>(true, "worlds.blocks", "Push entities with piston"); + public static final ConfigSetting pistonMaxBlockPush = new ConfigSetting<>(12, "worlds.blocks", "Maximum blocks pushed by pistons"); + public static final ConfigSetting infiniteWaterSources = new ConfigSetting<>(true, "worlds.blocks"); + public static final ConfigSetting waterDestroyRedstone = new ConfigSetting<>(true, "worlds.blocks"); + public static final ConfigSetting waterDestroysWeb = new ConfigSetting<>(true, "worlds.blocks"); + public static final ConfigSetting oldEnchantingSystem = new ConfigSetting<>(false, "worlds.blocks", "Toggle for 1.7 enchanting system"); + public static final ConfigSetting oldAnvilSystem = new ConfigSetting<>(false, "worlds.blocks", "Toggle for 1.7 anvil system"); + public static final ConfigSetting removeAnvilUses = new ConfigSetting<>(false, "worlds.blocks", "Should we disable the increasing anvil cost (every time you use an anvil the XP requirement goes up)"); + public static final ConfigSetting structureBookNerf = new ConfigSetting<>(false, "worlds.blocks", "Remove infinity and flame books from structure loot"); + public static final ConfigSetting cobbleGenerating = new ConfigSetting<>(true, "worlds.blocks.generating", "Cobble generation from lava and water"); + public static final ConfigSetting stoneGenerating = new ConfigSetting<>(true, "worlds.blocks.generating", "Stone generation from lava and water"); + public static final ConfigSetting obsidianGenerating = new ConfigSetting<>(true, "worlds.blocks.generating", "Obsidian generation from lava and water"); + public static final ConfigSetting spongeRadius = new ConfigSetting<>(4, "worlds.blocks.sponges", "Sponge activation radius, 0 to disable"); + public static final ConfigSetting spongePreventWaterFlow = new ConfigSetting<>(false, "worlds.blocks.sponges"); + public static final ConfigSetting spongeInstantBreak = new ConfigSetting<>(false, "worlds.blocks.sponges", false); + + // Spawners + public static final ConfigSetting chunkMobLimit = new ConfigSetting<>(0, "worlds.spawners", "Number of mobs in a chunk to prevent spawning. 0 - to disable requirement"); + public static final ConfigSetting minimumSpawnDelay = new ConfigSetting<>(200, "worlds.spawners"); + public static final ConfigSetting maximumSpawnDelay = new ConfigSetting<>(800, "worlds.spawners"); + public static final ConfigSetting spawnCount = new ConfigSetting<>(4, "worlds.spawners"); + public static final ConfigSetting spawnRange = new ConfigSetting<>(4.0, "worlds.spawners", "Spawn range for entities around the spawner"); + public static final ConfigSetting playerSpawnRange = new ConfigSetting<>(16.0, "worlds.spawners", "Radius for players around to spawn"); + public static final ConfigSetting maximumNearbyEntities = new ConfigSetting<>(0, "worlds.spawners", "Amount of entities around the spawner to prevent spawning. 0 - to disable requirement"); + public static final ConfigSetting lightLevelCheck = new ConfigSetting<>(true, "worlds.spawners"); + + // Players + public static final ConfigSetting trackPlayerStatistics = new ConfigSetting<>(true, "worlds.players"); + public static final ConfigSetting prePlayerInfos = new ConfigSetting<>(true, "worlds.players", "Should player infos be send before join event, this fixes entity tracker desyncs if you get teleported on join"); + public static final ConfigSetting horseHealthUpdates = new ConfigSetting<>(false, "worlds.players", "Should players receive health updates for horses, use this when you don't want horse health / healing to desync."); + public static final ConfigSetting savePlayerData = new ConfigSetting<>(true, "worlds.players", "Should player data be saved"); + public static final ConfigSetting allowOnFireOnDeadBush = new ConfigSetting<>(true, "worlds.players", "Allows fire on dead bush"); + public static final ConfigSetting oldExpLeveling = new ConfigSetting<>(false, "worlds.players", "Enable 1.7 leveling system"); + public static final ConfigSetting oldBoats = new ConfigSetting<>(false, "worlds.players", "Enable 1.7 boat system"); + public static final ConfigSetting alternativeRepair = new ConfigSetting<>(false, "worlds.blocks", "Directly combine durability when repairing items"); + public static final ConfigSetting kohiVelocityPatch = new ConfigSetting<>(true, "worlds.players", "When velocity is set through bukkit for players it'll be applied instantly, this means the velocity won't go through friction but will be send immediately."); + public static final ConfigSetting serverSideHitDetection = new ConfigSetting<>(false, "worlds.players", "Toggle off if you have an anticheat. This will make hit detection better but could allow more cheats."); + public static final ConfigSetting useSystemTimeForNoDamageTicks = new ConfigSetting<>(false, "worlds.players", "Uses system time for no damage ticks, this makes hit delay more accurate in combination with processPacketsInBetweenTicks"); + public static final ConfigSetting playerTeleportTracker = new ConfigSetting<>(true, "worlds.players", "Queues teleports to have more accuracy reducing ghost blocks by tracking player onGround properly"); + public static final ConfigSetting playerBorderDamage = new ConfigSetting<>(false, "worlds.players"); + public static final ConfigSetting playerMovedTooQuicklyCheck = new ConfigSetting<>(true, "worlds.players", "Toggle spigots moved too quickly check."); + public static final ConfigSetting checkPlayerSleep = new ConfigSetting<>(true, "worlds.players"); + public static final ConfigSetting playerIdleTimer = new ConfigSetting<>(false, "worlds.players"); + public static final ConfigSetting playerPingInterpolation = new ConfigSetting<>(true, "worlds.players", "Should the player's ping be 'interpolated' (this is default mc and prevents spikes from showing up heavily)"); + public static final ConfigSetting playerPhaseLeniency = new ConfigSetting<>(1E-7D, "worlds.players", "Defines the length a player can go inside a block, if you experience issues with server setting back due to phase, we recommend setting it to 0.0625"); + public static final ConfigSetting invulnerableTicks = new ConfigSetting<>(60, "worlds.players", "How many ticks should the player be invulnerable when they join"); + public static final ConfigSetting trackerTicks = new ConfigSetting<>(2, "worlds.players", "How often (in ticks) should the player position be updated"); + public static final ConfigSetting playerPhaseChestsAndAnvils = new ConfigSetting<>(false, "worlds.players", "Toggles chests & anvil bounding boxes, it is only recommended enabling this if you want to have protection against people glitching through chests & anvils"); + public static final ConfigSetting trackerDeltaAccuracy = new ConfigSetting<>(4, "worlds.players", "How much movement should a player have until his delta is broadcasted. Choose between 1 and 4. (1 = 0.03125, 4 is default spigot)"); + public static final ConfigSetting dynamicParalellisedTracking = new ConfigSetting<>(true, "worlds.players", "Async player tracking. Server will decide when it should be used"); + public static final ConfigSetting playersNeededParalellisedTracking = new ConfigSetting<>(100, "worlds.players", "How many players should be tracked for us to run paralellised"); + public static final ConfigSetting hideEntitiesThrownHidden = new ConfigSetting<>(false, "worlds.players", "Toggle hiding entities thrown by hidden players"); + public static final ConfigSetting itemBreakSoundSelf = new ConfigSetting<>(true, "worlds.players", "Should players hear their own item break sound"); + public static final ConfigSetting randomizeItemPickup = new ConfigSetting<>(false, "worlds.players", "Should item pickup be more randomized (this delays the pickup by a single tick to select a random player)"); + public static final ConfigSetting protRandomness = new ConfigSetting<>(true, "worlds.players", "Toggle protection randomness (HCF server toggle off and check below)"); + public static final ConfigSetting protRandomnessIfDisabledUseMedian = new ConfigSetting<>(false, "worlds.players", "Uses the median if prot randomness is disabled"); + public static final ConfigSetting protectionModifier = new ConfigSetting<>(25.0, "worlds.players", "Protection damage modifier. If prot randomness is disabled make sure to change this to 20-23. Lower for more damage and higher for less damage"); + public static final ConfigSetting armorDamageDivision = new ConfigSetting<>(4.0, "worlds.players", "Armor damage modifier (HCF should be 12)"); + public static final ConfigSetting armorDurabilityRandomness = new ConfigSetting<>(0.6F, "worlds.players", "Armor durability random modifier (lower is less chance item takes damage)"); + public static final ConfigSetting optimizePlayerPrinter = new ConfigSetting<>(false, "worlds.players", "Remove block place delay"); + public static final ConfigSetting autoRespawnPlayer = new ConfigSetting<>(false, "worlds.players"); + public static final ConfigSetting autoRemovePotionAfterDrink = new ConfigSetting<>(false, "worlds.players", "Should the potion bottle automatically remove itself after a player drank it"); + public static final ConfigSetting milkOnlyRemovesBadEffects = new ConfigSetting<>(false, "worlds.players", "Toggle this to make milk only remove bad effects from the player (this is useful for custom encahnts HCF maps)"); + public static final ConfigSetting expandArrowBoundingBox = new ConfigSetting<>(0.0D, "worlds.players", "Suggested: 0.1-0.5. Expands the bounding box of an arrow (only for hitting players) to make it more likely to hit. HCF Plugins can apply a 'noBoxExpand' metadata value (type: UUID of entity collection) to prevent the expanded arrow box size to work on teammates."); + public static final ConfigSetting maxChatLength = new ConfigSetting<>(100, "worlds.players", "What should the max chat message length, increase this together with LunarClient Apollo to allow players to have longer chat messages on LunarClient"); + public static final ConfigSetting> potionLaunchOnClick = new ConfigSetting<>(Arrays.asList("HOPPER", "CHEST", "ENDER_CHEST"), "worlds.players"); + + // Compensation ticks + public static final ConfigSetting compensatedEating = new ConfigSetting<>(true, "worlds.players.compensated-ticks", "Should the server simulate ticks to compensate food, milk and potions for latency."); + public static final ConfigSetting compensatedPotions = new ConfigSetting<>(false, "worlds.players.compensated-ticks", "Should the server allow splashing potions on the shooter faster to compensate for latency."); + + // Projectile Interpolation + public static final ConfigSetting arrowInterpolationRegistration = new ConfigSetting<>(true, "worlds.interpolation", "Should arrow hit registration be improved by accounting for interpolation"); + public static final ConfigSetting arrowInterpolationRegistrationOnly = new ConfigSetting<>(false, "worlds.interpolation", "Only use the interpolation box for arrow hit registration"); + public static final ConfigSetting rodInterpolationRegistration = new ConfigSetting<>(true, "worlds.interpolation", "Should rod hit registration be improved by accounting for interpolation"); + public static final ConfigSetting rodInterpolationRegistrationOnly = new ConfigSetting<>(false, "worlds.interpolation", "Only use the interpolation box for rod hit registration"); + public static final ConfigSetting projectileInterpolationRegistration = new ConfigSetting<>(true, "worlds.interpolation", "Should generic projectiles hit registration be improved by accounting for interpolation"); + public static final ConfigSetting projectileInterpolationRegistrationOnly = new ConfigSetting<>(false, "worlds.interpolation", "Only use the interpolation box for generic projectiles hit registration"); + + // Networking + public static final ConfigSetting ipConsoleLog = new ConfigSetting<>(false, "worlds.players.networking"); + public static final ConfigSetting ioUring = new ConfigSetting<>(false, "worlds.players.networking", "Use IO Uring if available (compression won't be enabled when this option is turned on)"); + public static final ConfigSetting adaptiveAllocator = new ConfigSetting<>(false, "worlds.players.networking", "Use adaptive allocator"); + public static final ConfigSetting networkBlockingJoin = new ConfigSetting<>(true, "worlds.players.networking", "PaperSpigot patch for preventing blocking while ticking. Toggle off if you have issues with your anticheat on join.", false); + public static final ConfigSetting tickPlayerLatency = new ConfigSetting<>(true, "worlds.players.networking", "Tick player latency on tablist"); + public static final ConfigSetting parentNettyThreads = new ConfigSetting<>(1, "worlds.players.networking", "1 Is sufficient as it is just responsible for accepting connections and offloading to child group", false); + public static final ConfigSetting childNettyThreads = new ConfigSetting<>(0, "worlds.players.networking", "Default is 4, 0 is recommended which uses all processors available but will increase cpu usage.", false); + public static final ConfigSetting fastKeepAlive = new ConfigSetting<>(false, "worlds.players.networking", "Should we sent out a keepalive on player join and after they ticked once"); + public static final ConfigSetting keepAliveUpdateFrequency = new ConfigSetting<>(40L, "worlds.players.networking", "How often (in ticks) should we send keepalive packets"); + public static final ConfigSetting calculatePacketSize = new ConfigSetting<>(false, "worlds.players.networking", "Should we calculate the packet size before allocating the buffer the packet will be written to, this reduces direct memory by using more CPU to calculate expected bytes written."); + public static final ConfigSetting nettyWatchdog = new ConfigSetting<>(false, "worlds.players.networking", "Should we check for netty thread lagouts, this allows you to find potential crash exploits that people are abusing, or a plugin which is extremely slow"); + + // Better Slowdown + public static final ConfigSetting betterSlowdownEnabled = new ConfigSetting<>(true, "worlds.players.betterslowdown", "Should we run the Spigot implementation of BetterSlowdown https://github.com/Beaness/BetterSlowdown, this has better anticheat compatibility"); + public static final ConfigSetting betterSlowdownFallbackMode = new ConfigSetting<>("CLIENT", "worlds.players.betterslowdown", "What fallback mode should we use (read github for config for info)"); + public static final ConfigSetting betterSlowdownAlwaysAddSprint = new ConfigSetting<>(true, "worlds.players.betterslowdown", "Should BetterSlowdown always add sprint when a player's speed is modified, this is definitely recommended for HCF servers so Bard speed effect doesn't break"); + + // Cps cap + public static final ConfigSetting cpsCapEnabled = new ConfigSetting<>(false, "worlds.players.cps-cap", "Should the cps penalty cap be enabled"); + public static final ConfigSetting cpsCapSwordOnly = new ConfigSetting<>(false, "worlds.players.cps-cap", "Should only the cps of swinging your sword be counted"); + public static final ConfigSetting cpsCap = new ConfigSetting<>(15, "worlds.players.cps-cap", "What is the maximum cps the player can achieve (inclusive)"); + public static final ConfigSetting cpsCapPenaltyTicks = new ConfigSetting<>(30, "worlds.players.cps-cap", "How long should the player not be able to hit while being penalized (20 ticks = 1 second)"); + public static final ConfigSetting cpsCapSendMessage = new ConfigSetting<>(true, "worlds.players.cps-cap"); + public static final ConfigSetting cpsCapMessage = new ConfigSetting<>("&cYou are clicking over %cps% CPS. Click below this to make sure your hits dont cancel.", "worlds.players.cps-cap", false); + + // Knockback + public static final ConfigSetting globalActiveKnockback = new ConfigSetting<>("Default", "worlds.players.knockback", "Which profile should we use as the default", false); + public static final ConfigSetting overrideDefaultKnockback = new ConfigSetting<>(true, "worlds.players.knockback", "Should we use our custom knockback"); + public static final ConfigSetting nonPlayerEntitiesOverrideDefaultKnockback = new ConfigSetting<>(false, "worlds.players.knockback", "Should non player entities use the custom kb system"); + public static final ConfigSetting overrideRodKnockback = new ConfigSetting<>(true, "worlds.players.knockback", "Should we use our custom knockback for rod knockback"); + public static final ConfigSetting overrideArrowKnockback = new ConfigSetting<>(true, "worlds.players.knockback", "Should we use our custom knockback for arrow knockback"); + public static final ConfigSetting overrideOnlyHealthPotion = new ConfigSetting<>(true, "worlds.players.knockback", "Should we use our custom knockback for only health potions"); + + // Player patches + public static final ConfigSetting patchArrowBounceBug = new ConfigSetting<>(true, "worlds.players.patches", "Toggles the arrow hit delay in knockback profiles."); + public static final ConfigSetting patchDoubleHitBug = new ConfigSetting<>(false, "worlds.players.patches", "Toggles the double hit bug fix"); + public static final ConfigSetting patchDropEatRunBug = new ConfigSetting<>(false, "worlds.players.patches", "Prevents the player from exploiting a drop bug to run after dropping food while eating, not compatible with the other patches"); + public static final ConfigSetting patchDropEatBug = new ConfigSetting<>(true, "worlds.players.patches", "Releases player's item if they drop & eat at the same time"); + public static final ConfigSetting patchRunEatBug = new ConfigSetting<>(true, "worlds.players.patches", "Prevents the player from running & eating in all situations"); + public static final ConfigSetting patchItemDesyncBug = new ConfigSetting<>(true, "worlds.players.patches", "Minecraft client can sometimes desync the use of an item due to set slot updates to items, by enabling this patch it will reduce this desync because it will no longer send durability updates to the holding item. Other causes like plugins updating the inventory can still desync it."); + public static final ConfigSetting patchHealthRendering = new ConfigSetting<>(true, "worlds.players.patches", "The minecraft client ceils the health value sent by the server which means 19.001 health becomes full HP, this patch fixes this issue by rounding the health before sending it to the client"); + public static final ConfigSetting patchGhostBuckets = new ConfigSetting<>(true, "worlds.players.patches", "This makes sure the server uses the correct location for placing liquids by waiting for the client tick packet"); + public static final ConfigSetting patchProjectileMisdirection = new ConfigSetting<>(true, "worlds.players.patches", "This makes the server use the correct yaw & pitch for projectiles (does not include bows)"); + public static final ConfigSetting patchBowMisdirection = new ConfigSetting<>(true, "worlds.players.patches", "This makes the server use the correct yaw & pitch for bows"); + public static final ConfigSetting patchProjectileOffset = new ConfigSetting<>(false, "worlds.players.patches", "This removes the projectile offset (to the right)"); + public static final ConfigSetting patchHCFRegenBug = new ConfigSetting<>(true, "worlds.players.patches", "This makes regeneration weaker as players in teamfights are often invincible with regular regen."); + public static final ConfigSetting obfuscateEntityEquipment = new ConfigSetting<>(true, "worlds.players.patches", "Obfuscates equipment to deny a few cheats"); + + // Menus + public static final ConfigSetting fillerEnabled = new ConfigSetting<>(true, "worlds.players.menus", false); + public static final ConfigSetting fillerType = new ConfigSetting<>("STAINED_GLASS_PANE", "worlds.players.menus", false); + public static final ConfigSetting fillerData = new ConfigSetting<>(7, "worlds.players.menus", false); + public static final ConfigSetting pageType = new ConfigSetting<>("CARPET", "worlds.players.menus", false); + public static final ConfigSetting pageData = new ConfigSetting<>(2, "worlds.players.menus", false); + public static final ConfigSetting pageBackDisplay = new ConfigSetting<>("&dPrevious Page", "worlds.players.menus", false); + public static final ConfigSetting> pageBackLore = new ConfigSetting<>(Collections.singletonList("&e(Current Page: &2%page%/%max-pages%&e)"), "worlds.players.menus", false); + public static final ConfigSetting pageForwardDisplay = new ConfigSetting<>("&dNext Page", "worlds.players.menus", false); + public static final ConfigSetting> pageForwardLore = new ConfigSetting<>(Collections.singletonList("&e(Current Page: &2%page%/%max-pages%&e)"), "worlds.players.menus", false); + public static final ConfigSetting backButtonType = new ConfigSetting<>("BED", "worlds.players.menus", false); + public static final ConfigSetting backButtonData = new ConfigSetting<>(0, "worlds.players.menus", false); + public static final ConfigSetting backButtonDisplay = new ConfigSetting<>("&cBack", "worlds.players.menus", false); + + // Mobs + public static final ConfigSetting mobAI = new ConfigSetting<>(true, "worlds.mobs", "Toggle this option to disable mobAI"); + public static final ConfigSetting mobAISpawners = new ConfigSetting<>(true, "worlds.mobs", "Toggle this option to so mob AI works for entities that spawn from spawners (overrides mobAI)"); + public static final ConfigSetting mobAIHorses = new ConfigSetting<>(true, "worlds.mobs", "Toggle this option to make it so mob AI works for horses (overrides mobAI)"); + public static final ConfigSetting naturalMobSpawn = new ConfigSetting<>(true, "worlds.mobs"); + public static final ConfigSetting ironGolemFallDamage = new ConfigSetting<>(true, "worlds.mobs"); + public static final ConfigSetting snowGolemFallDamage = new ConfigSetting<>(true, "worlds.mobs"); + public static final ConfigSetting babyZombieSpawning = new ConfigSetting<>(true, "worlds.mobs"); + public static final ConfigSetting zombieOnChickenSpawning = new ConfigSetting<>(true, "worlds.mobs"); + public static final ConfigSetting villagerZombieSpawning = new ConfigSetting<>(true, "worlds.mobs"); + public static final ConfigSetting skeletonOnSpiderSpawning = new ConfigSetting<>(true, "worlds.mobs"); + public static final ConfigSetting entityCollisions = new ConfigSetting<>(true, "worlds.mobs", "Toggle this off if you want the best performance"); + public static final ConfigSetting playerCollisions = new ConfigSetting<>(false, "worlds.mobs", "Should collision be ran on player entities, this affects their kb when you are close to someone. Enable this for vanilla behaivour."); + public static final ConfigSetting entityCollisionsDelay = new ConfigSetting<>(1, "worlds.mobs", "A delay of 4 is recommended"); + + // Factions + public static final ConfigSetting fixFreecamCegging = new ConfigSetting<>(false, "factions", "Only enable if it is an issue! May cause performance issues"); + public static final ConfigSetting sandMerging = new ConfigSetting<>(false, "factions"); + public static final ConfigSetting tntMerging = new ConfigSetting<>(false, "factions"); + public static final ConfigSetting hidePistonAnimations = new ConfigSetting<>(false, "factions"); + public static final ConfigSetting hideTntEntity = new ConfigSetting<>(false, "factions"); + public static final ConfigSetting hideSandEntity = new ConfigSetting<>(false, "factions"); + public static final ConfigSetting fixSandChunkUnloading = new ConfigSetting<>(true, "factions"); + public static final ConfigSetting optimizeTNTMovement = new ConfigSetting<>(false, "factions"); + public static final ConfigSetting optimizeSandMovement = new ConfigSetting<>(false, "factions"); + public static final ConfigSetting fixEastWestCannon = new ConfigSetting<>(true, "factions"); + + // Durability checker + public static final ConfigSetting explosionDestroyer = new ConfigSetting<>(false, "factions.durability"); + public static final ConfigSetting explosionBlockPower = new ConfigSetting<>(1.12D, "factions.durability", "Adjust explosion block power"); + public static final ConfigSetting explosionEntityPower = new ConfigSetting<>(2.0D, "factions.durability", "Adjust explosion entity power"); + public static final ConfigSetting durabilityItemChecker = new ConfigSetting<>("potato", "factions.durability", false); + public static final ConfigSetting damageOnlyByTNT = new ConfigSetting<>(false, "factions.durability"); + public static final ConfigSetting> blockDurabilities = new ConfigSetting<>(Arrays.asList("obsidian:3", "bedrock:5", "end_stone:5"), "factions.durability", false); + public static final ConfigSetting> blockResistances = new ConfigSetting<>(Arrays.asList("obsidian:35.0", "bedrock:60.0", "end_stone:45.0", "anvil:2000.0"), "factions.durability", false); + + public AzuriteConfig(Azurite instance) { + super(instance, "azurite", CC.getConfigHeader("Azurite configuration", "You will find all the main mechanics here")); + } +} diff --git a/azurite-server/src/main/java/dev/azurite/spigot/configs/EnchantConfig.java b/azurite-server/src/main/java/dev/azurite/spigot/configs/EnchantConfig.java new file mode 100644 index 0000000..96ebf3e --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/configs/EnchantConfig.java @@ -0,0 +1,44 @@ +package dev.azurite.spigot.configs; + +import dev.azurite.spigot.Azurite; +import dev.azurite.spigot.configs.extra.Config; +import dev.azurite.spigot.configs.extra.ConfigSetting; +import dev.azurite.spigot.utils.CC; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public class EnchantConfig extends Config { + + public static ConfigSetting unbreaking = new ConfigSetting<>(3, "enchant-limits"); + public static ConfigSetting protectionAll = new ConfigSetting<>(4, "enchant-limits.armor"); + public static ConfigSetting protectionFire = new ConfigSetting<>(4, "enchant-limits.armor"); + public static ConfigSetting protectionFall = new ConfigSetting<>(4, "enchant-limits.armor"); + public static ConfigSetting protectionExplosion = new ConfigSetting<>(4, "enchant-limits.armor"); + public static ConfigSetting protectionProjectile = new ConfigSetting<>(4, "enchant-limits.armor"); + public static ConfigSetting thorns = new ConfigSetting<>(3, "enchant-limits.armor"); + public static ConfigSetting aquaAffinity = new ConfigSetting<>(1, "enchant-limits.armor"); + public static ConfigSetting waterBreathing = new ConfigSetting<>(3, "enchant-limits.armor"); + public static ConfigSetting depthStrider = new ConfigSetting<>(3, "enchant-limits.armor"); + public static ConfigSetting efficiency = new ConfigSetting<>(5, "enchant-limits.tools"); + public static ConfigSetting silkTouch = new ConfigSetting<>(1, "enchant-limits.tools"); + public static ConfigSetting fortune = new ConfigSetting<>(3, "enchant-limits.tools"); + public static ConfigSetting sharpness = new ConfigSetting<>(5, "enchant-limits.swords"); + public static ConfigSetting baneOfArthropods = new ConfigSetting<>(5, "enchant-limits.swords"); + public static ConfigSetting smite = new ConfigSetting<>(5, "enchant-limits.swords"); + public static ConfigSetting fireAspect = new ConfigSetting<>(2, "enchant-limits.swords"); + public static ConfigSetting knockback = new ConfigSetting<>(2, "enchant-limits.swords"); + public static ConfigSetting looting = new ConfigSetting<>(3, "enchant-limits.swords"); + public static ConfigSetting power = new ConfigSetting<>(5, "enchant-limits.bows"); + public static ConfigSetting punch = new ConfigSetting<>(2, "enchant-limits.bows"); + public static ConfigSetting flame = new ConfigSetting<>(1, "enchant-limits.bows"); + public static ConfigSetting infinity = new ConfigSetting<>(1, "enchant-limits.bows"); + public static ConfigSetting lure = new ConfigSetting<>(3, "enchant-limits.rods"); + public static ConfigSetting luckOfTheSea = new ConfigSetting<>(3, "enchant-limits.rods"); + + public EnchantConfig(Azurite azurite) { + super(azurite, "enchants", CC.getConfigHeader("Enchantment limit configuration", "Increase or decrease the limit of any enchant")); + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/configs/LanguageConfig.java b/azurite-server/src/main/java/dev/azurite/spigot/configs/LanguageConfig.java new file mode 100644 index 0000000..fba1e66 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/configs/LanguageConfig.java @@ -0,0 +1,162 @@ +package dev.azurite.spigot.configs; + +import dev.azurite.spigot.Azurite; +import dev.azurite.spigot.configs.extra.Config; +import dev.azurite.spigot.configs.extra.ConfigSetting; +import dev.azurite.spigot.utils.CC; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public class LanguageConfig extends Config { + + // Global + public static final ConfigSetting insufficientPerm = new ConfigSetting<>("&dAzuriteSpigot &7┃ &cYou do not have access to this command.", "messages"); + public static final ConfigSetting onlyPlayer = new ConfigSetting<>("&dThis command can only be used by players.", "messages"); + public static final ConfigSetting playerNotFound = new ConfigSetting<>("&ePlayer &d%player% &ecould not be found.", "messages"); + public static final ConfigSetting notValidType = new ConfigSetting<>("&eValue &d%value% &eis not type &a%type%&e.", "messages"); + + // Player + public static final ConfigSetting disconnectSpam = new ConfigSetting<>("disconnect.spam", "messages.player"); + public static final ConfigSetting loggedInAnotherLocation = new ConfigSetting<>("You logged in from another location", "messages.player"); + public static final ConfigSetting factionsDurabilityChecker = new ConfigSetting<>("&eDurability: &d%durability%", "messages.player"); + + // Commands + public static final ConfigSetting playerPing = new ConfigSetting<>("&d[Ping] &eYour Ping: &d%ping%ms", "messages.command.ping-command"); + public static final ConfigSetting otherPlayerPing = new ConfigSetting<>("&d[Ping] &e%player%'s Ping: &d%ping%ms", "messages.command.ping-command"); + public static final ConfigSetting configReloaded = new ConfigSetting<>("&eConfigs have been reloaded in &d%ms%ms&e.", "messages.command.config-command"); + public static final ConfigSetting clearedLag = new ConfigSetting<>("&eYou have cleared &d%entities% &eentities.", "messages.command.clear-lag-command"); + public static final ConfigSetting setMaxPlayersUsage = new ConfigSetting<>("&cUsage: /setmaxplayers ", "messages.command.set-max-players-command"); + public static final ConfigSetting setMaxPlayers = new ConfigSetting<>("&eSet max players to &d%amount% &eplayers.", "messages.command.set-max-players-command"); + public static final ConfigSetting unloadedChunks = new ConfigSetting<>("&eYou have unloaded &d%amount% &echunks.", "messages.command.unload-chunks-command"); + + public static final ConfigSetting> versionMessage = new ConfigSetting<>(Collections.singletonList( + "&fThis server is running &dAzuriteSpigot &fversion 1.8.8-R0.1-SNAPSHOT." + ), "messages.command.version-command"); + + public static final ConfigSetting> tpsMessage = new ConfigSetting<>(Arrays.asList( + "&7&m-------------------------", + "&d[Server TPS]", + "&f(TPS from 1s, 5s, 15s: %server_tps%&f)", + "&f(Memory: &e%free_memory%&7/&e%max_memory% MB&f) &7- &f(Uptime: &6%uptime%&f)", + "&f(Threads: &b%threads%&f) &7- &f(Alive: &a%alive%&f, Interrupted: &c%interrupted%&f, Daemon: &9%daemon%&f)", + "&f(Chunks: &2%chunks%&f) &7- &f(Players: &c%players%&7/&c%max_players%&f)", + "&f(Entities: &3%entities%&f) &7- &f(Tile Entities: &e%tiles%&f)", + "&7&m-------------------------" + ), "messages.command.tps-command"); + + // No track + public static final ConfigSetting noTrackUsage = new ConfigSetting<>("&cUsage: /notrack ", "messages.no-track"); + public static final ConfigSetting noTrackSet = new ConfigSetting<>("&eUpdated no track range to &d%range%&e.", "messages.no-track"); + + // Knockback + public static final ConfigSetting> knockbackUsage = new ConfigSetting<>(Arrays.asList( + "&7&m-------------------------", + "&d[Knockback Usage]", + "%commands%", + "&7&m-------------------------" + ), "messages.knockback"); + public static final ConfigSetting profileNotFound = new ConfigSetting<>("&eProfile &d%name% &ecould not be found.", "messages.knockback"); + + // Create + public static final ConfigSetting createUsage = new ConfigSetting<>("&d- &f/knockback create ", "messages.knockback.knockback-create"); + public static final ConfigSetting createHover = new ConfigSetting<>("&eClick to create a new profile.", "messages.knockback.knockback-create"); + public static final ConfigSetting createExists = new ConfigSetting<>("&eProfile &d%name% &ealready exists.", "messages.knockback.knockback-create"); + public static final ConfigSetting createProfile = new ConfigSetting<>("&eProfile &d%name% &ehas been created.", "messages.knockback.knockback-create"); + + // Delete + public static final ConfigSetting deleteUsage = new ConfigSetting<>("&d- &f/knockback delete ", "messages.knockback.knockback-delete"); + public static final ConfigSetting deleteHover = new ConfigSetting<>("&eClick to delete a profile.", "messages.knockback.knockback-delete"); + public static final ConfigSetting deleteActive = new ConfigSetting<>("&eYou cannot delete &d%name% &eas it is a active profile.", "messages.knockback.knockback-delete"); + public static final ConfigSetting deleteProfile = new ConfigSetting<>("&eProfile &d%name% &ehas been deleted.", "messages.knockback.knockback-delete"); + + // List + public static final ConfigSetting listUsage = new ConfigSetting<>("&d- &f/knockback list", "messages.knockback.knockback-list"); + public static final ConfigSetting listHover = new ConfigSetting<>("&eClick to list profiles.", "messages.knockback.knockback-list"); + public static final ConfigSetting listName = new ConfigSetting<>("&d- &f%name%", "messages.knockback.knockback-list"); + public static final ConfigSetting listNameActive = new ConfigSetting<>("&d- &2%name% &7(Active)", "messages.knockback.knockback-list"); + public static final ConfigSetting listNameHover = new ConfigSetting<>("&eClick to view &d%name%''s &evalues.", "messages.knockback.knockback-list"); + public static final ConfigSetting> listMessage = new ConfigSetting<>(Arrays.asList( + "&7&m-------------------------", + "&d[Knockback Profiles]", + "%profiles%", + "&7&m-------------------------" + ), "messages.knockback.knockback-list"); + + // Set Type + public static final ConfigSetting setTypeUsage = new ConfigSetting<>("&d- &f/knockback settype ", "messages.knockback.knockback-settype"); + public static final ConfigSetting setTypeHover = new ConfigSetting<>("&eClick to change a profiles type.", "messages.knockback.knockback-settype"); + public static final ConfigSetting setTypeAlready = new ConfigSetting<>("&eProfile &d%name% &eis already type &c%type%&e.", "messages.knockback.knockback-settype"); + public static final ConfigSetting setTypeNotFound = new ConfigSetting<>("&eProfile type needs to be: &dSimple/Advanced", "messages.knockback.knockback-settype"); + public static final ConfigSetting setTypePrefix = new ConfigSetting<>("&eClick new type: ", "messages.knockback.knockback-settype"); + public static final ConfigSetting setTypeSimple = new ConfigSetting<>("&b[Simple]", "messages.knockback.knockback-settype"); + public static final ConfigSetting setTypeAdvanced = new ConfigSetting<>("&4[Advanced]", "messages.knockback.knockback-settype"); + public static final ConfigSetting setTypeSimpleHover = new ConfigSetting<>("&eClick to change profile to &dSimple&e.", "messages.knockback.knockback-settype"); + public static final ConfigSetting setTypeAdvancedHover = new ConfigSetting<>("&eClick to change profile to &dAdvanced&e.", "messages.knockback.knockback-settype"); + public static final ConfigSetting setType = new ConfigSetting<>("&eProfile &d%name% &eis now type &c%type%&e.", "messages.knockback.knockback-settype"); + + // Set Active + public static final ConfigSetting setActiveUsage = new ConfigSetting<>("&d- &f/knockback setactive ", "messages.knockback.knockback-setactive"); + public static final ConfigSetting setActiveHover = new ConfigSetting<>("&eClick to set an active profile.", "messages.knockback.knockback-setactive"); + public static final ConfigSetting setActiveAlready = new ConfigSetting<>("&eProfile &d%name% &eis already active.", "messages.knockback.knockback-setactive"); + public static final ConfigSetting setActive = new ConfigSetting<>("&eProfile &d%name% &eis now globally active.", "messages.knockback.knockback-setactive"); + + // View + public static final ConfigSetting viewUsage = new ConfigSetting<>("&d- &f/knockback view ", "messages.knockback.knockback-view"); + public static final ConfigSetting viewHover = new ConfigSetting<>("&eClick to view a profile.", "messages.knockback.knockback-view"); + public static final ConfigSetting viewSetting = new ConfigSetting<>("&d- &f%setting%&7: &d%value%", "messages.knockback.knockback-view"); + public static final ConfigSetting viewSettingHover = new ConfigSetting<>("&eClick to set a new value for &d%setting%&e.", "messages.knockback.knockback-view"); + public static final ConfigSetting viewSetActiveClick = new ConfigSetting<>("&a[Set Active]", "messages.knockback.knockback-view"); + public static final ConfigSetting viewSetActiveClickHover = new ConfigSetting<>("&eClick to set profile &d%name% &eactive.", "messages.knockback.knockback-view"); + public static final ConfigSetting viewDeleteClick = new ConfigSetting<>("&c[Delete]", "messages.knockback.knockback-view"); + public static final ConfigSetting viewDeleteClickHover = new ConfigSetting<>("&eClick to delete &d%name%&e.", "messages.knockback.knockback-view"); + public static final ConfigSetting viewEditClick = new ConfigSetting<>("&6[Edit]", "messages.knockback.knockback-view"); + public static final ConfigSetting viewEditHover = new ConfigSetting<>("&eClick to edit &d%name%&e.", "messages.knockback.knockback-view"); + public static final ConfigSetting viewSetTypeClick = new ConfigSetting<>("&d[Change Knockback Type]", "messages.knockback.knockback-view"); + public static final ConfigSetting viewSetTypeHover = new ConfigSetting<>("&eClick to change knockback type for &d%name%&e.", "messages.knockback.knockback-view"); + public static final ConfigSetting> viewMessage = new ConfigSetting<>(Arrays.asList( + "&7&m-------------------------", + "&d[%name%] &7(%type%)", + "%values%", + "%clickables%", + "%settype%", + "&7&m-------------------------" + ), "messages.knockback.knockback-view"); + + // Edit + public static final ConfigSetting editUsage = new ConfigSetting<>("&d- &f/knockback edit ", "messages.knockback.knockback-edit"); + public static final ConfigSetting editHover = new ConfigSetting<>("&eClick to edit a profiles values.", "messages.knockback.knockback-edit"); + public static final ConfigSetting editSettingNotFound = new ConfigSetting<>("&eSetting &d%setting% &ecould not be found.", "messages.knockback.knockback-edit"); + public static final ConfigSetting editTypeNewValue = new ConfigSetting<>("&eType a value for &d%setting% &e(Current: &2%current%&e) &eType &ccancel &eto cancel.", "messages.knockback.knockback-edit"); + public static final ConfigSetting editCancelled = new ConfigSetting<>("&eEditing for value &d%setting% &ehas been cancelled.", "messages.knockback.knockback-edit"); + public static final ConfigSetting editSettingValue = new ConfigSetting<>("&eSet the value of &d%setting% &eto &2%value% &efor profile &c%profile%&e.", "messages.knockback.knockback-edit"); + + // Edit menu + public static final ConfigSetting editMenuUsage = new ConfigSetting<>("&d- &f/knockback editmenu ", "messages.knockback.knockback-editmenu"); + public static final ConfigSetting editMenuHover = new ConfigSetting<>("&eClick to edit a profile.", "messages.knockback.knockback-editmenu"); + + // Set + public static final ConfigSetting setUsage = new ConfigSetting<>("&d- &f/knockback set ", "messages.knockback.knockback-set"); + public static final ConfigSetting setHover = new ConfigSetting<>("&eClick to set a players profile.", "messages.knockback.knockback-set"); + public static final ConfigSetting setProfile = new ConfigSetting<>("&eSet profile &d%profile% &eto player &2%player%&e.", "messages.knockback.knockback-set"); + + // Clear + public static final ConfigSetting clearUsage = new ConfigSetting<>("&d- &f/knockback clear ", "messages.knockback.knockback-clear"); + public static final ConfigSetting clearHover = new ConfigSetting<>("&eClick to clear a players profile.", "messages.knockback.knockback-clear"); + public static final ConfigSetting clearProfile = new ConfigSetting<>("&eReset &d%player%&e''s active profile.", "messages.knockback.knockback-clear"); + + // Config edits + public static final ConfigSetting configEditNewValue = new ConfigSetting<>("&eType a value for &d%setting% &e(Current: &2%current%&e) &eType &ccancel &eto cancel.", "messages.config-editing"); + public static final ConfigSetting configEditCancelled = new ConfigSetting<>("&eEditing for value &d%setting% &ehas been cancelled.", "messages.config-editing"); + public static final ConfigSetting configEditSetValue = new ConfigSetting<>("&eSet the value of &d%setting% &eto &2%value%&e.", "messages.config-editing"); + + public LanguageConfig(Azurite azurite) { + super(azurite, "language", CC.getConfigHeader("Messages configuration", "You will find all the language here")); + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/configs/PearlConfig.java b/azurite-server/src/main/java/dev/azurite/spigot/configs/PearlConfig.java new file mode 100644 index 0000000..a364373 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/configs/PearlConfig.java @@ -0,0 +1,143 @@ +package dev.azurite.spigot.configs; + +import dev.azurite.spigot.Azurite; +import dev.azurite.spigot.configs.extra.Config; +import dev.azurite.spigot.configs.extra.ConfigSetting; +import dev.azurite.spigot.utils.CC; +import org.bukkit.Material; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public class PearlConfig extends Config { + + // Anti Glitch + public static final ConfigSetting fixBlockGlitch = new ConfigSetting<>(true, "antiGlitch"); + public static final ConfigSetting fixFenceGlitch = new ConfigSetting<>(true, "antiGlitch"); + public static final ConfigSetting refundSuffocation = new ConfigSetting<>(true, "antiGlitch"); + public static final ConfigSetting refundRiskyPearl = new ConfigSetting<>(true, "antiGlitch"); + public static final ConfigSetting refundOnCritblock = new ConfigSetting<>(false, "antiGlitch"); + public static final ConfigSetting refundCloseDistance = new ConfigSetting<>(0.5, "antiGlitch"); + public static final ConfigSetting glitchReturnPearl = new ConfigSetting<>(true, "antiGlitch"); + public static final ConfigSetting glitchReturnMessage = new ConfigSetting<>("", "antiGlitch", false); + public static final ConfigSetting glitchReturnCommand = new ConfigSetting<>("timer remove %player% Enderpearl", "antiGlitch", false); + + // Misc + public static final ConfigSetting practicePearls = new ConfigSetting<>(true, "teleport.misc", "Pearls used on ElevateMC, this changes the pearl hit detection"); + public static final ConfigSetting instantlyTaliTeleport = new ConfigSetting<>(false, "teleport.misc"); + public static final ConfigSetting entityTpHitDetection = new ConfigSetting<>(true, "teleport.misc"); + public static final ConfigSetting entityTpGetOutOneByOne = new ConfigSetting<>(true, "teleport.misc", "Deny entity TP system if you are in a one by one"); + public static final ConfigSetting spawnEndermite = new ConfigSetting<>(true, "teleport.misc"); + public static final ConfigSetting pearlThruFence = new ConfigSetting<>(true, "teleport.misc"); + public static final ConfigSetting pearlThruString = new ConfigSetting<>(true, "teleport.misc"); + public static final ConfigSetting pearlThruWeb = new ConfigSetting<>(true, "teleport.misc"); + public static final ConfigSetting pearlThruPlants = new ConfigSetting<>(true, "teleport.misc"); + public static final ConfigSetting pearlHopperUnderFence = new ConfigSetting<>(true, "teleport.misc"); + public static final ConfigSetting pearlChestUnderFence = new ConfigSetting<>(true, "teleport.misc"); + public static final ConfigSetting pearlParticlesEnabled = new ConfigSetting<>(true, "teleport.misc"); + public static final ConfigSetting pearlParticleCount = new ConfigSetting<>(32, "teleport.misc"); + public static final ConfigSetting pearlDamage = new ConfigSetting<>(5.0, "teleport.misc"); + public static final ConfigSetting crossPearlMoveHelper = new ConfigSetting<>(0.35, "teleport.misc", "How much should we move the player inside the block when cross-pearling"); + public static final ConfigSetting hitBlockTeleport = new ConfigSetting<>(true, "teleport.misc", "Should we teleport them if they throw an enderpearl directly on the block"); + public static final ConfigSetting beforeBlockTeleport = new ConfigSetting<>(true, "teleport.misc", "Should we teleport them if they throw an enderpearl just before the block (Like ViperMC)"); + public static final ConfigSetting maxTeleportBlocks = new ConfigSetting<>(3, "teleport.misc", "Maximum amount of blocks you can tali teleport through"); + public static final ConfigSetting launchOnFenceClick = new ConfigSetting<>(true, "teleport.misc"); + public static final ConfigSetting> launchOnOtherClick = new ConfigSetting<>(Arrays.asList("FURNACE", "ANVIL", "SIGN", "SIGN_POST", "WALL_SIGN", "HOPPER", "CHEST", "ENDER_CHEST", "TRAPPED_CHEST", "WORKBENCH", "ENCHANTMENT_TABLE", "BEACON", "ANVIL"), "teleport.misc", false); + + // Normal teleporting + public static final List pearlSettings = Arrays.asList( + new PearlConfigSetting(BlockAliases.SLABS, "teleport.slabs"), + new PearlConfigSetting(BlockAliases.STAIRS, "teleport.stairs"), + new PearlConfigSetting(BlockAliases.CHESTS, "teleport.chests"), + new PearlConfigSetting(BlockAliases.BEDS, "teleport.beds"), + new PearlConfigSetting(BlockAliases.COBBLE_WALLS, "teleport.cobblewalls"), + new PearlConfigSetting(BlockAliases.PISTONS, "teleport.pistons"), + new PearlConfigSetting(BlockAliases.END_FRAMES, "teleport.end-frames"), + new PearlConfigSetting(BlockAliases.ENCHANT_TABLES, "teleport.enchant-tables"), + new PearlConfigSetting(BlockAliases.ANVILS, "teleport.anvils"), + new PearlConfigSetting(BlockAliases.DAYLIGHT_SENSORS, "teleport.daylight-sensors"), + new PearlConfigSetting(BlockAliases.TRAPDOORS, "teleport.trapdoors") + ); + + public PearlConfig(Azurite instance) { + super(instance, "pearls", CC.getConfigHeader("HCF Enderpearl Configuration", "All the options for enderpearl mechanics")); + } + + public List> fetchPearlConfigs() { + List> pearlConfigs = new ArrayList<>(); + + try { + for (PearlConfigSetting pearlSetting : pearlSettings) { + for (Field field : pearlSetting.getClass().getDeclaredFields()) { + if (field.getType() != ConfigSetting.class) continue; + ConfigSetting configSetting = (ConfigSetting) field.get(pearlSetting); + configSetting.setConfig(this); + configSetting.setName(field.getName()); + pearlConfigs.add(configSetting); + } + } + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + + return pearlConfigs; + } + + public static class PearlConfigSetting { + + public BlockAliases aliases; + public String path; + public ConfigSetting enabled; + public ConfigSetting crosspearl; + public ConfigSetting diagonal; + public ConfigSetting critblock; + + public PearlConfigSetting(BlockAliases aliases, String path) { + this.aliases = aliases; + this.path = path; + this.enabled = new ConfigSetting<>(true, path); + this.crosspearl = new ConfigSetting<>(true, path); + this.diagonal = new ConfigSetting<>(true, path); + this.critblock = new ConfigSetting<>(true, path); + } + } + + public enum BlockAliases { + FENCES(Material.FENCE, Material.NETHER_FENCE, Material.IRON_FENCE, Material.SPRUCE_FENCE, Material.BIRCH_FENCE, Material.JUNGLE_FENCE, Material.DARK_OAK_FENCE, Material.ACACIA_FENCE), + FENCE_GATES(Material.FENCE_GATE, Material.JUNGLE_FENCE_GATE, Material.SPRUCE_FENCE_GATE, Material.DARK_OAK_FENCE_GATE, Material.ACACIA_FENCE_GATE, Material.BIRCH_FENCE_GATE), + CHESTS(Material.CHEST, Material.ENDER_CHEST, Material.TRAPPED_CHEST), + SLABS(Material.STEP, Material.STONE_SLAB2, Material.WOOD_STEP), + COBBLE_WALLS(Material.COBBLE_WALL), + ENCHANT_TABLES(Material.ENCHANTMENT_TABLE), + PISTONS(Material.PISTON_EXTENSION, Material.PISTON_MOVING_PIECE), + STAIRS(Material.RED_SANDSTONE_STAIRS, Material.BRICK_STAIRS, Material.DARK_OAK_STAIRS, Material.ACACIA_STAIRS, Material.QUARTZ_STAIRS, Material.JUNGLE_WOOD_STAIRS, Material.BIRCH_WOOD_STAIRS, Material.SPRUCE_WOOD_STAIRS, Material.SANDSTONE_STAIRS, Material.NETHER_BRICK_STAIRS, Material.WOOD_STAIRS, Material.COBBLESTONE_STAIRS, Material.BRICK_STAIRS, Material.SMOOTH_STAIRS), + BEDS(Material.BED_BLOCK, Material.BED), + END_FRAMES(Material.ENDER_PORTAL_FRAME), + ANVILS(Material.ANVIL), + DAYLIGHT_SENSORS(Material.DAYLIGHT_DETECTOR, Material.DAYLIGHT_DETECTOR_INVERTED), + SIGNS(Material.WALL_SIGN, Material.SIGN_POST), + BANNERS(Material.STANDING_BANNER, Material.WALL_BANNER), + SAPLINGS(Material.SAPLING), + TRAPDOORS(Material.TRAP_DOOR, Material.IRON_TRAPDOOR), + PLATES(Material.STONE_PLATE, Material.WOOD_PLATE, Material.GOLD_PLATE, Material.IRON_PLATE), + DOORS(Material.WOOD_DOOR, Material.IRON_DOOR, Material.IRON_DOOR_BLOCK, Material.WOODEN_DOOR, Material.ACACIA_DOOR, Material.BIRCH_DOOR, Material.SPRUCE_DOOR, Material.JUNGLE_DOOR, Material.DARK_OAK_DOOR), + BUTTONS(Material.STONE_BUTTON, Material.WOOD_BUTTON); + + private final List ids; + + BlockAliases(Material... materials) { + this.ids = Arrays.asList(materials); + } + + public boolean isApplicable(Material material) { + return ids.contains(material); + } + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/configs/extra/Config.java b/azurite-server/src/main/java/dev/azurite/spigot/configs/extra/Config.java new file mode 100644 index 0000000..f94d726 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/configs/extra/Config.java @@ -0,0 +1,180 @@ +package dev.azurite.spigot.configs.extra; + +import dev.azurite.spigot.Azurite; +import dev.azurite.spigot.configs.PearlConfig; +import dev.azurite.spigot.knockback.Knockback; +import net.minecraft.server.MinecraftServer; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.YamlConfiguration; + +import java.io.File; +import java.io.IOException; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.List; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public class Config { + + private final List> configSettings; + private final File file; + private final YamlConfiguration bukkitConfig; + private final ConfigCommenter configCommenter; + + public Config(Azurite azurite, String name, List header) { + this.configSettings = new ArrayList<>(); + this.file = new File(ConfigFolder.AZURITE_DIRECTORY, name + (name.endsWith(".yml") ? "" : ".yml")); + this.bukkitConfig = YamlConfiguration.loadConfiguration(file); + this.configCommenter = new ConfigCommenter(); + + configCommenter.setHeader(String.join("\n", header)); + azurite.getConfigs().add(this); + } + + public String getName() { + return file.getName(); + } + + public List> getSettings() { + return configSettings; + } + + public void delete() { + if (file.exists()) { + file.delete(); + } + } + + public void save(boolean async) { + if (async) { + Azurite.getInstance().getThreadingManager().getAsyncExecutor().execute(() -> this.save(false)); + return; + } + + try { + + for (ConfigSetting setting : getSettings()) { + bukkitConfig.set(setting.getFullPath(), setting.getValue()); + } + + bukkitConfig.save(file); + configCommenter.saveComments(file); + + } catch (IOException e) { + MinecraftServer.LOGGER.error(e); + } + } + + public void reload() { + try { + + bukkitConfig.load(file); // Read the file again + + for (ConfigSetting configSetting : configSettings) { + Object fetch = fetchValue(configSetting); // Fetch from config and set + if (fetch == null) fetch = configSetting.getValue(); + configSetting.set(fetch, false); + } + + } catch (IOException | InvalidConfigurationException e) { + throw new RuntimeException(e); + } + } + + private static List getAllConfigFields(Class type) { + List fields = new ArrayList<>(); + + while (type != null && Config.class.isAssignableFrom(type)) { + for (Field field : type.getDeclaredFields()) { + fields.add(field); + } + type = type.getSuperclass(); + } + + return fields; + } + + public void load() { + try { + List> loading = new ArrayList<>(); + + for (Field field : getAllConfigFields(getClass())) { + if (field.getType() == ConfigSetting.class) { + ConfigSetting configSetting = (ConfigSetting) field.get(this); + configSetting.setConfig(this); + configSetting.setName(field.getName()); + loading.add(configSetting); + + // This will keep the order of knockback values + if (configSetting.getName().equals("knockbackType") && this instanceof Knockback) { + Knockback knockback = (Knockback) this; + loading.addAll(knockback.getKnockbackSettings()); + } + } + } + + if (this instanceof PearlConfig) { + PearlConfig pearlConfig = (PearlConfig) this; + loading.addAll(pearlConfig.fetchPearlConfigs()); + } + + for (ConfigSetting configSetting : loading) { + String path = configSetting.getFullPath(); + Object fetch = fetchValue(configSetting); + if (fetch == null) fetch = configSetting.getValue(); + + if (configSetting.getCommentAbove() != null) { + configCommenter.addComment(path, configSetting.getCommentAbove()); + } + + if (configSetting.getComment() != null) { + configCommenter.addCommentNextTo(path, configSetting.getComment()); + } + + configSetting.set(fetch, false); + configSettings.add(configSetting); + } + + this.save(false); + + } catch (Exception e) { + MinecraftServer.LOGGER.error(e); + } + } + + private Object fetchValue(ConfigSetting setting) { + Object defaultValue = setting.getValue(); + String path = setting.getFullPath(); + + if (defaultValue instanceof String) { + return bukkitConfig.getString(path); + + } else if (defaultValue instanceof List) { + return bukkitConfig.getList(path); + + } else if (bukkitConfig.contains(path)) { + if (defaultValue instanceof Boolean) { + return bukkitConfig.getBoolean(path); + + } else if (defaultValue instanceof Number) { + Number number = (Number) bukkitConfig.get(path); + + if (defaultValue instanceof Integer) { + return number.intValue(); + + } else if (defaultValue instanceof Float) { + return number.floatValue(); + + } else if (defaultValue instanceof Double) { + return number.doubleValue(); + } + } + } + + return null; + } +} diff --git a/azurite-server/src/main/java/dev/azurite/spigot/configs/extra/ConfigCommenter.java b/azurite-server/src/main/java/dev/azurite/spigot/configs/extra/ConfigCommenter.java new file mode 100644 index 0000000..b71d987 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/configs/extra/ConfigCommenter.java @@ -0,0 +1,89 @@ +package dev.azurite.spigot.configs.extra; + +import dev.azurite.spigot.utils.JavaUtils; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +public class ConfigCommenter { + + private final Map comments = new HashMap<>(); + private final Map commentsNextTo = new HashMap<>(); + private String header = null; + + public void addCommentNextTo(String path, String comment) { + commentsNextTo.put(path, comment); + } + + /** + * Add comment to a config option.
+ * Supports multiline comments! + * + * @param path Config path to add comment to + * @param comment Comment to add + */ + public void addComment(String path, String comment) { + comments.put(path, comment); + } + + /** + * Set the header for this config file + * + * @param header Header to add + */ + public void setHeader(String header) { + this.header = header; + } + + /** + * Saves comments to config file + * + * @param file File to save to + * @throws IOException io + */ + public void saveComments(File file) throws IOException { + ArrayList lines = (ArrayList) Files.readAllLines(file.toPath()); + lines.removeIf(s -> s.trim().startsWith("#") || s.trim().length() <= 4); + if (header != null && !header.isEmpty()) lines.add(0, "# " + header.replace("\n", "\n# ") + "\n"); + + for (Map.Entry comment : comments.entrySet()) { + int line = JavaUtils.findKey(lines, comment.getKey()); + + if (line == -1) { + throw new IllegalStateException(String.format("You are trying to add a comment to key \"%s\" which does not exist!", comment.getKey())); + } + + if (line >= 0) { + String prefix = JavaUtils.repeat(" ", JavaUtils.getIndentation(lines.get(line))) + "# "; + boolean noNewline = JavaUtils.getIndentation(lines.get(line)) > JavaUtils.getIndentation(lines.get(line - 1)); + lines.add(line, (noNewline ? "" : "\n") + prefix + comment.getValue().replace("\n", "\n" + prefix)); + } else { + System.out.printf("Failed to find key %s in %s!", comment.getKey(), file); + } + } + + for (Map.Entry comment : commentsNextTo.entrySet()) { + int line = JavaUtils.findKey(lines, comment.getKey()); + + if (line == -1) { + throw new IllegalStateException(String.format("You are trying to add a comment to key \"%s\" which does not exist!", comment.getKey())); + } + + if (line >= 0) { + lines.set(line, lines.get(line) + " # " + comment.getValue()); + } else { + System.out.printf("Failed to find key %s in %s!", comment.getKey(), file); + } + } + + String text = String.join("\n", lines); + FileWriter fw = new FileWriter(file); + fw.write(text); + fw.close(); + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/configs/extra/ConfigEdit.java b/azurite-server/src/main/java/dev/azurite/spigot/configs/extra/ConfigEdit.java new file mode 100644 index 0000000..b0db300 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/configs/extra/ConfigEdit.java @@ -0,0 +1,27 @@ +package dev.azurite.spigot.configs.extra; + +import dev.azurite.spigot.framework.menu.Menu; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public class ConfigEdit { + + private final ConfigSetting setting; + private final Menu menu; + + public ConfigEdit(ConfigSetting setting, Menu menu) { + this.setting = setting; + this.menu = menu; + } + + public ConfigSetting getSetting() { + return setting; + } + + public Menu getMenu() { + return menu; + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/configs/extra/ConfigFolder.java b/azurite-server/src/main/java/dev/azurite/spigot/configs/extra/ConfigFolder.java new file mode 100644 index 0000000..9747f05 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/configs/extra/ConfigFolder.java @@ -0,0 +1,26 @@ +package dev.azurite.spigot.configs.extra; + +import org.jetbrains.annotations.NotNull; + +import java.io.File; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public class ConfigFolder extends File { + + public static final File AZURITE_DIRECTORY = new File("azurite"); + + static { + if (!AZURITE_DIRECTORY.exists()) { + AZURITE_DIRECTORY.mkdir(); + } + } + + public ConfigFolder(@NotNull String pathname) { + super(AZURITE_DIRECTORY, pathname); + if (!this.exists()) this.mkdir(); + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/configs/extra/ConfigSetting.java b/azurite-server/src/main/java/dev/azurite/spigot/configs/extra/ConfigSetting.java new file mode 100644 index 0000000..2653b17 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/configs/extra/ConfigSetting.java @@ -0,0 +1,156 @@ +package dev.azurite.spigot.configs.extra; + +import java.util.Objects; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +@SuppressWarnings("unchecked") +public class ConfigSetting { + + private T value; + private Config config; + private String name; + private String path; + private String comment; + private String commentAbove; + private boolean editable; + + public ConfigSetting(T value, String path, String comment, String commentAbove, boolean editable) { + this.value = value; + this.config = null; + this.name = ""; + this.path = path; + this.comment = comment; + this.commentAbove = commentAbove; + this.editable = editable; + } + + public ConfigSetting(T value, String path, String comment, String commentAbove) { + this(value, path, comment, commentAbove, true); + } + + public ConfigSetting(T value, String path, String comment) { + this(value, path, comment, null); + } + + public ConfigSetting(T value, String path, String comment, boolean editable) { + this(value, path, comment, null, editable); + } + + public ConfigSetting(T value, String path) { + this(value, path, null, null); + } + + public ConfigSetting(T value, String path, boolean editable) { + this(value, path, null, null, editable); + } + + public String getFullPath() { + return (!path.isEmpty() ? path + "." : "") + name; + } + + public T getValue() { + return value; + } + + public Object parseValue(String string) { + try { + + if (value instanceof String) { + return string; + + } else if (value instanceof Integer) { + return Integer.parseInt(string); + + } else if (value instanceof Double) { + return Double.parseDouble(string); + + } else if (value instanceof Float) { + return Float.parseFloat(string); + + } else if (value instanceof Boolean) { + boolean isBool = string.equalsIgnoreCase("false") || string.equalsIgnoreCase("true"); + if (isBool) return Boolean.parseBoolean(string); + } + + } catch (Exception e) { + return null; + } + return null; + } + + public void set(Object value, boolean save) { + this.set(value, save, true); + } + + public void set(Object value, boolean save, boolean saveAsync) { + this.value = (T) value; + + if (save) { + config.save(saveAsync); + } + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } + + public String getCommentAbove() { + return commentAbove; + } + + public void setCommentAbove(String commentAbove) { + this.commentAbove = commentAbove; + } + + public String getComment() { + return comment; + } + + public void setComment(String comment) { + this.comment = comment; + } + + public void setConfig(Config config) { + this.config = config; + } + + public boolean isEditable() { + return editable; + } + + public void setEditable(boolean editable) { + this.editable = editable; + } + + @Override + public boolean equals(Object o) { + if (o == null || getClass() != o.getClass()) return false; + ConfigSetting that = (ConfigSetting) o; + return Objects.equals(value, that.value) && Objects.equals(config, that.config) && Objects.equals(name, that.name) && Objects.equals(path, that.path); + } + + @Override + public int hashCode() { + int result = Objects.hashCode(value); + result = 31 * result + Objects.hashCode(config); + result = 31 * result + Objects.hashCode(name); + result = 31 * result + Objects.hashCode(path); + return result; + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/console/AzuriteConsole.java b/azurite-server/src/main/java/dev/azurite/spigot/console/AzuriteConsole.java new file mode 100644 index 0000000..4772e10 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/console/AzuriteConsole.java @@ -0,0 +1,39 @@ +package dev.azurite.spigot.console; + +import net.minecraft.server.DedicatedServer; +import net.minecrell.terminalconsole.SimpleTerminalConsole; +import org.bukkit.craftbukkit.command.ConsoleCommandCompleter; +import org.jline.reader.LineReader; +import org.jline.reader.LineReaderBuilder; + +public final class AzuriteConsole extends SimpleTerminalConsole { + + private final DedicatedServer server; + + public AzuriteConsole(DedicatedServer server) { + this.server = server; + } + + @Override + protected LineReader buildReader(LineReaderBuilder builder) { + return super.buildReader(builder + .appName("Azurite") + .completer(new ConsoleCommandCompleter(this.server)) + ); + } + + @Override + protected boolean isRunning() { + return !this.server.isStopped() && this.server.isRunning(); + } + + @Override + protected void runCommand(String command) { + this.server.issueCommand(command, this.server); + } + + @Override + protected void shutdown() { + this.server.safeShutdown(); + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/console/LogFullPolicy.java b/azurite-server/src/main/java/dev/azurite/spigot/console/LogFullPolicy.java new file mode 100644 index 0000000..9db1914 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/console/LogFullPolicy.java @@ -0,0 +1,13 @@ +package dev.azurite.spigot.console; + +import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.core.async.AsyncQueueFullPolicy; +import org.apache.logging.log4j.core.async.EventRoute; + +public final class LogFullPolicy implements AsyncQueueFullPolicy { + + @Override + public EventRoute getRoute(final long backgroundThreadId, final Level level) { + return EventRoute.ENQUEUE; + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/console/TerminalConsoleCommandSender.java b/azurite-server/src/main/java/dev/azurite/spigot/console/TerminalConsoleCommandSender.java new file mode 100644 index 0000000..10a01e4 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/console/TerminalConsoleCommandSender.java @@ -0,0 +1,16 @@ +package dev.azurite.spigot.console; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.bukkit.craftbukkit.command.CraftConsoleCommandSender; + +public class TerminalConsoleCommandSender extends CraftConsoleCommandSender { + + private static final Logger LOGGER = LogManager.getRootLogger(); + + @Override + public void sendRawMessage(String message) { + // TerminalConsoleAppender supports color codes directly in log messages + LOGGER.info(message); + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/framework/commands/Command.java b/azurite-server/src/main/java/dev/azurite/spigot/framework/commands/Command.java new file mode 100644 index 0000000..d982588 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/framework/commands/Command.java @@ -0,0 +1,122 @@ +package dev.azurite.spigot.framework.commands; + +import dev.azurite.spigot.configs.LanguageConfig; +import dev.azurite.spigot.utils.CC; +import dev.azurite.spigot.utils.Utils; +import org.bukkit.command.CommandSender; +import org.bukkit.command.defaults.BukkitCommand; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public abstract class Command { + + protected final String name; + protected String permission; + protected List aliases; + protected BukkitCommand bukkitCommand; + + public Command(String name) { + this.name = name; + this.permission = null; + this.aliases = new ArrayList<>(); + } + + public abstract void execute(CommandSender sender, String[] args); + + public List tabComplete(CommandSender sender, String[] args) { + return Collections.emptyList(); + } + + public BukkitCommand asBukkitCommand() { + if (bukkitCommand != null) { + return bukkitCommand; + } + + BukkitCommand command = new BukkitCommand(name) { + @Override + public boolean execute(CommandSender sender, String commandLabel, String[] args) { + if (permission != null && !sender.hasPermission(permission)) { + sendMessage(sender, LanguageConfig.insufficientPerm.getValue()); + return true; + } + + Command.this.execute(sender, args); + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + if (permission != null && !sender.hasPermission(permission)) { + return super.tabComplete(sender, alias, args); + } + + List tabComplete = Command.this.tabComplete(sender, args); + return (tabComplete.isEmpty() ? super.tabComplete(sender, alias, args) : tabComplete); + } + }; + + if (!aliases.isEmpty()) { + command.setAliases(aliases); + } + + this.bukkitCommand = command; + return command; + } + + public void unregister() { + if (bukkitCommand != null) { + Utils.unregister(bukkitCommand); + } + } + + public void sendMessage(CommandSender sender, String... strings) { + for (String string : strings) { + sender.sendMessage(CC.t(string)); + } + } + + public void setPermission(String permission) { + this.permission = permission; + } + + public void setAliases(List aliases) { + this.aliases = aliases; + } + + public Integer getInt(String string) { + try { + + return Integer.parseInt(string); + + } catch (NumberFormatException e) { + return null; + } + } + + public Double getDouble(String string) { + try { + + return Double.parseDouble(string); + + } catch (NumberFormatException e) { + return null; + } + } + + public Float getFloat(String string) { + try { + + return Float.parseFloat(string); + + } catch (NumberFormatException e) { + return null; + } + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/framework/menu/Menu.java b/azurite-server/src/main/java/dev/azurite/spigot/framework/menu/Menu.java new file mode 100644 index 0000000..6acf8e0 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/framework/menu/Menu.java @@ -0,0 +1,131 @@ +package dev.azurite.spigot.framework.menu; + +import dev.azurite.spigot.Azurite; +import dev.azurite.spigot.framework.menu.button.Button; +import dev.azurite.spigot.utils.CC; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; + +import java.util.Map; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public abstract class Menu { + + protected Map buttons; + protected Player player; + protected Inventory inventory; + protected String title; + protected int size; + protected boolean update; + + protected ItemStack filler; + protected boolean fillEnabled; + protected boolean allowInteract; + + public Menu(Player player, String title, int size, boolean update) { + this.player = player; + this.title = CC.t(title); + this.size = size; + this.inventory = Bukkit.createInventory(null, size, this.title); + this.update = update; + this.fillEnabled = false; + this.allowInteract = false; + } + + public Map getButtons() { + return buttons; + } + + public void playClick() { + player.playSound(Sound.CLICK, 1.0F, 1.0F); + } + + public void open() { + this.buttons = getButtons(player); + + // Set the first items + for (Map.Entry entry : buttons.entrySet()) { + inventory.setItem(entry.getKey() - 1, entry.getValue().getItemStack()); + } + + // Fill null/air spots with our filler + if (fillEnabled) { + for (int i = 0; i < inventory.getSize(); i++) { + ItemStack item = inventory.getItem(i); + + if (item == null || item.getType() == Material.AIR) { + inventory.setItem(i, filler); + } + } + } + + // Open and add to map + player.openInventory(inventory); + Azurite.getInstance().getMenuManager().getMenus().put(player.getUniqueId(), this); + } + + public void update() { + if (!player.isOnline()) { + destroy(); // They aren't online so just destroy it. + return; + } + + // "Re-Fetch" the buttons and cache them again + Map buttons = (this.buttons = getButtons(player)); + + // Update the items in our inventory + for (Map.Entry entry : buttons.entrySet()) { + inventory.setItem(entry.getKey() - 1, entry.getValue().getItemStack()); + } + + // Update filler + if (fillEnabled) { + for (int i = 0; i < inventory.getSize(); i++) { + ItemStack item = inventory.getItem(i); + + if (item == null || item.getType() == Material.AIR) { + inventory.setItem(i, filler); + } + } + } + } + + public void destroy() { + // Lower ram usage + buttons.clear(); + inventory.clear(); + + // Remove from map + Azurite.getInstance().getMenuManager().getMenus().remove(player.getUniqueId()); + + // Cancel updater + update = false; + } + + public void onClick(InventoryClickEvent e) { + if (!allowInteract) { + e.setCancelled(true); + } + } + + public void onClickOwn(InventoryClickEvent e) { + } + + public void onClose() { + } + + public boolean isAllowInteract() { + return allowInteract; + } + + public abstract Map getButtons(Player player); +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/framework/menu/MenuManager.java b/azurite-server/src/main/java/dev/azurite/spigot/framework/menu/MenuManager.java new file mode 100644 index 0000000..3230991 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/framework/menu/MenuManager.java @@ -0,0 +1,39 @@ +package dev.azurite.spigot.framework.menu; + +import net.minecraft.server.MinecraftServer; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public class MenuManager { + + private final Map menus; + + public MenuManager() { + this.menus = new HashMap<>(); + } + + public Map getMenus() { + return menus; + } + + public void tick() { + if (menus.isEmpty()) return; + + try { + if (MinecraftServer.currentTick % 500 == 0) { + for (Menu menu : menus.values()) { + if (menu.update) menu.update(); + } + } + } catch (Exception e) { + MinecraftServer.LOGGER.info("Error updating azurite menus {}", e.getMessage()); + } + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/framework/menu/button/Button.java b/azurite-server/src/main/java/dev/azurite/spigot/framework/menu/button/Button.java new file mode 100644 index 0000000..860dc81 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/framework/menu/button/Button.java @@ -0,0 +1,17 @@ +package dev.azurite.spigot.framework.menu.button; + +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.ItemStack; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public abstract class Button { + + public abstract void onClick(InventoryClickEvent e); + + public abstract ItemStack getItemStack(); + +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/framework/menu/paginated/PaginatedMenu.java b/azurite-server/src/main/java/dev/azurite/spigot/framework/menu/paginated/PaginatedMenu.java new file mode 100644 index 0000000..b18dfbb --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/framework/menu/paginated/PaginatedMenu.java @@ -0,0 +1,290 @@ +package dev.azurite.spigot.framework.menu.paginated; + +import dev.azurite.spigot.Azurite; +import dev.azurite.spigot.configs.AzuriteConfig; +import dev.azurite.spigot.framework.menu.Menu; +import dev.azurite.spigot.framework.menu.button.Button; +import dev.azurite.spigot.utils.ItemBuilder; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.function.UnaryOperator; +import java.util.stream.Collectors; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public class PaginatedMenu extends Menu { + + protected Map> pages; + protected Map defaultButtons; + protected Menu previousMenu; + protected int currentPage; + protected boolean surroundGlass; + + public PaginatedMenu(Player player, String title, int size, boolean update) { + super(player, title, size, update); + this.surroundGlass = false; + this.pages = new HashMap<>(); + this.defaultButtons = getDefaultButtons(); + this.previousMenu = null; + this.currentPage = 1; + } + + public PaginatedMenu(Player player, String title, int size, boolean update, boolean surroundGlass) { + super(player, title, size, update); + this.surroundGlass = surroundGlass; + this.pages = new HashMap<>(); + this.defaultButtons = getDefaultButtons(); + this.previousMenu = null; + this.currentPage = 1; + } + + public PaginatedMenu(Player player, String title, Menu previousMenu, int size, boolean update, boolean surroundGlass) { + super(player, title, size, update); + this.pages = new HashMap<>(); + this.previousMenu = previousMenu; + this.surroundGlass = surroundGlass; + this.defaultButtons = getDefaultButtons(); + this.currentPage = 1; + } + + @Override + public void open() { + // Calculate pages based on current buttons + this.calcPages(getButtons(player)); + this.buttons = pages.get(currentPage); + this.inventory = Bukkit.createInventory(null, size, title); + + for (Map.Entry entry : buttons.entrySet()) { + inventory.setItem(entry.getKey() - 1, entry.getValue().getItemStack()); + } + + // Open and add to map + player.openInventory(inventory); + Azurite.getInstance().getMenuManager().getMenus().put(player.getUniqueId(), this); + } + + @Override + public void update() { + if (!player.isOnline()) { + destroy(); // They aren't online so just destroy it. + return; + } + + // Clear + inventory.clear(); + pages.clear(); + + // "Re-Fetch" the buttons and cache them again + this.calcPages(getButtons(player)); + this.buttons = pages.get(currentPage); + + // Update the items in our inventory + for (Map.Entry entry : buttons.entrySet()) { + inventory.setItem(entry.getKey() - 1, entry.getValue().getItemStack()); + } + } + + @Override + public void destroy() { + super.destroy(); + pages.clear(); + } + + @Override + public Map getButtons(Player player) { + return null; + } + + private void calcPages(Map buttons) { + if (buttons.isEmpty()) { + pages.computeIfAbsent(1, k -> new HashMap<>(defaultButtons)); + return; + } + + this.handleButtons(buttons); + } + + private void handleButtons(Map buttons) { + Set exceptions = new HashSet<>(); + + for (int i = 1; i <= 9; i++) { + exceptions.add(i); // First row + } + + // Handle left / right + if (surroundGlass) { + for (int i = 10; i <= size; i++) { + if (i % 9 == 0 || (i - 1) % 9 == 0) exceptions.add(i); + } + } + + int counter = 9; + int page = 1; + int bottomSize = surroundGlass ? size - 9 : size; + int maxPerPage = size - (exceptions.size() + (surroundGlass ? 9 : 0)); + int totalPages = (buttons.size() < maxPerPage ? 1 : buttons.size() / maxPerPage); + + for (int i = 1; i <= size * totalPages; i++) { + Button button = buttons.get(i); + + if (button != null) { + if (counter >= bottomSize) { + counter = 9; + page++; + } + + while (exceptions.contains(counter)) { + counter++; + + if (counter >= bottomSize) { + counter = 9; + page++; + } + } + + Map pageButtons = pages.computeIfAbsent(page, k -> new HashMap<>(defaultButtons)); + pageButtons.put(counter++, button); + } + } + } + + private Map getDefaultButtons() { + Map map = new HashMap<>(); + + if (AzuriteConfig.fillerEnabled.getValue()) { + for (int i = 2; i <= 8; i++) { + map.put(i, new Button() { + @Override + public void onClick(InventoryClickEvent e) { + e.setCancelled(true); + } + + @Override + public ItemStack getItemStack() { + return new ItemBuilder(Material.valueOf(AzuriteConfig.fillerType.getValue())) + .setName("&7") + .data(AzuriteConfig.fillerData.getValue()) + .toItemStack(); + } + }); + } + + if (surroundGlass) { + Button button = new Button() { + @Override + public void onClick(InventoryClickEvent e) { + e.setCancelled(true); + } + + @Override + public ItemStack getItemStack() { + return new ItemBuilder(Material.valueOf(AzuriteConfig.fillerType.getValue())) + .setName("&7") + .data(AzuriteConfig.fillerData.getValue()) + .toItemStack(); + } + }; + + for (int i = 9; i <= size; i++) { + if (i >= (size - 9)) { + map.put(i, button); + continue; + } + + if (i % 9 == 0) { + map.put(i, button); + map.put(i + 1, button); + } + } + } + } + + map.put(1, new Button() { + @Override + public void onClick(InventoryClickEvent e) { + e.setCancelled(true); + + // At first page no going back + if (currentPage > 1) { + currentPage--; + playClick(); + update(); + } + } + + @Override + public ItemStack getItemStack() { + UnaryOperator replacer = s -> s + .replace("%page%", String.valueOf(currentPage)) + .replace("%max-pages%", String.valueOf(pages.size())) + .replace("%back-page%", (currentPage == 1 ? "None" : String.valueOf(currentPage - 1))); + + return new ItemBuilder(Material.valueOf(AzuriteConfig.pageType.getValue())) + .setName(AzuriteConfig.pageBackDisplay.getValue()) + .setLore(AzuriteConfig.pageBackLore.getValue().stream().map(replacer).collect(Collectors.toList())) + .data(AzuriteConfig.pageData.getValue()) + .toItemStack(); + } + }); + + if (previousMenu != null) { + map.put((surroundGlass ? size - 4 : 5), new Button() { + @Override + public void onClick(InventoryClickEvent e) { + e.setCancelled(true); + playClick(); + previousMenu.open(); + } + + @Override + public ItemStack getItemStack() { + return new ItemBuilder(Material.valueOf(AzuriteConfig.backButtonType.getValue())) + .setName(AzuriteConfig.backButtonDisplay.getValue()) + .data(AzuriteConfig.backButtonData.getValue()) + .toItemStack(); + } + }); + } + + map.put(9, new Button() { + @Override + public void onClick(InventoryClickEvent e) { + e.setCancelled(true); + + // Check if the next page exists + if (pages.containsKey(currentPage + 1)) { + currentPage++; + playClick(); + update(); + } + } + + @Override + public ItemStack getItemStack() { + UnaryOperator replacer = s -> s + .replace("%page%", String.valueOf(currentPage)) + .replace("%max-pages%", String.valueOf(pages.size())) + .replace("%next-page%", (pages.size() == currentPage ? "None" : String.valueOf(currentPage + 1))); + + return new ItemBuilder(Material.valueOf(AzuriteConfig.pageType.getValue())) + .setName(AzuriteConfig.pageForwardDisplay.getValue()) + .setLore(AzuriteConfig.pageForwardLore.getValue().stream().map(replacer).collect(Collectors.toList())) + .data(AzuriteConfig.pageData.getValue()) + .toItemStack(); + } + }); + + return map; + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/framework/plugin/AzuriteFakePlugin.java b/azurite-server/src/main/java/dev/azurite/spigot/framework/plugin/AzuriteFakePlugin.java new file mode 100644 index 0000000..675805f --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/framework/plugin/AzuriteFakePlugin.java @@ -0,0 +1,140 @@ +package dev.azurite.spigot.framework.plugin; + +import com.avaje.ebean.EbeanServer; +import org.bukkit.Server; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.generator.ChunkGenerator; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.PluginDescriptionFile; +import org.bukkit.plugin.PluginLoader; + +import java.io.File; +import java.io.InputStream; +import java.util.Collections; +import java.util.List; +import java.util.logging.Logger; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public class AzuriteFakePlugin implements Plugin { + + private final PluginDescriptionFile description; + private final AzuriteFakePluginLoader fakePluginLoader; + + public AzuriteFakePlugin() { + this.description = new PluginDescriptionFile("AzuriteSpigotFakePlugin", "1.0", ""); + this.fakePluginLoader = new AzuriteFakePluginLoader(); + } + + @Override + public File getDataFolder() { + return null; + } + + @Override + public PluginDescriptionFile getDescription() { + return description; + } + + @Override + public FileConfiguration getConfig() { + return null; + } + + @Override + public InputStream getResource(String filename) { + return null; + } + + @Override + public void saveConfig() { + + } + + @Override + public void saveDefaultConfig() { + + } + + @Override + public void saveResource(String resourcePath, boolean replace) { + + } + + @Override + public void reloadConfig() { + + } + + @Override + public PluginLoader getPluginLoader() { + return fakePluginLoader; + } + + @Override + public Server getServer() { + return null; + } + + @Override + public boolean isEnabled() { + return true; + } + + @Override + public void onDisable() { + + } + + @Override + public void onLoad() { + } + + @Override + public void onEnable() { + } + + @Override + public boolean isNaggable() { + return false; + } + + @Override + public void setNaggable(boolean canNag) { + } + + @Override + public EbeanServer getDatabase() { + return null; + } + + @Override + public ChunkGenerator getDefaultWorldGenerator(String worldName, String id) { + return null; + } + + @Override + public Logger getLogger() { + return null; + } + + @Override + public String getName() { + return ""; + } + + @Override + public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { + return false; + } + + @Override + public List onTabComplete(CommandSender sender, Command command, String alias, String[] args) { + return Collections.emptyList(); + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/framework/plugin/AzuriteFakePluginLoader.java b/azurite-server/src/main/java/dev/azurite/spigot/framework/plugin/AzuriteFakePluginLoader.java new file mode 100644 index 0000000..7e53c70 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/framework/plugin/AzuriteFakePluginLoader.java @@ -0,0 +1,112 @@ +package dev.azurite.spigot.framework.plugin; + +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.Warning; +import org.bukkit.event.Event; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.plugin.*; + +import java.io.File; +import java.lang.reflect.Method; +import java.util.*; +import java.util.logging.Level; +import java.util.regex.Pattern; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public class AzuriteFakePluginLoader implements PluginLoader { + + @Override + public Plugin loadPlugin(File file) throws InvalidPluginException, UnknownDependencyException { + return null; + } + + @Override + public PluginDescriptionFile getPluginDescription(File file) throws InvalidDescriptionException { + return null; + } + + @Override + public Pattern[] getPluginFileFilters() { + return new Pattern[0]; + } + + public Map, Set> createRegisteredListeners(Listener listener, final Plugin plugin) { + Validate.notNull(plugin, "Plugin can not be null"); + Validate.notNull(listener, "Listener can not be null"); + + Map, Set> ret = new HashMap<>(); + Set methods; + try { + Method[] publicMethods = listener.getClass().getMethods(); + Method[] privateMethods = listener.getClass().getDeclaredMethods(); + methods = new HashSet<>(publicMethods.length + privateMethods.length, 1.0f); + methods.addAll(Arrays.asList(publicMethods)); + methods.addAll(Arrays.asList(privateMethods)); + } catch (NoClassDefFoundError e) { + plugin.getLogger().severe("Plugin " + plugin.getDescription().getFullName() + " has failed to register events for " + listener.getClass() + " because " + e.getMessage() + " does not exist."); + return ret; + } + + for (final Method method : methods) { + final EventHandler eh = method.getAnnotation(EventHandler.class); + if (eh == null) continue; + // Do not register bridge or synthetic methods to avoid event duplication + // Fixes SPIGOT-893 + if (method.isBridge() || method.isSynthetic()) { + continue; + } + final Class checkClass; + if (method.getParameterTypes().length != 1 || !Event.class.isAssignableFrom(checkClass = method.getParameterTypes()[0])) { + plugin.getLogger().severe(plugin.getDescription().getFullName() + " attempted to register an invalid EventHandler method signature \"" + method.toGenericString() + "\" in " + listener.getClass()); + continue; + } + final Class eventClass = checkClass.asSubclass(Event.class); + method.setAccessible(true); + Set eventSet = ret.computeIfAbsent(eventClass, k -> new HashSet<>()); + + for (Class clazz = eventClass; Event.class.isAssignableFrom(clazz); clazz = clazz.getSuperclass()) { + // This loop checks for extending deprecated events + if (clazz.getAnnotation(Deprecated.class) != null) { + Warning warning = clazz.getAnnotation(Warning.class); + Warning.WarningState warningState = Bukkit.getServer().getWarningState(); + if (!warningState.printFor(warning)) { + break; + } + plugin.getLogger().log( + Level.WARNING, + String.format( + "\"%s\" has registered a listener for %s on method \"%s\", but the event is Deprecated." + + " \"%s\"; please notify the authors %s.", + plugin.getDescription().getFullName(), + clazz.getName(), + method.toGenericString(), + (warning != null && !warning.reason().isEmpty()) ? warning.reason() : "Server performance will be affected", + Arrays.toString(plugin.getDescription().getAuthors().toArray())), + warningState == Warning.WarningState.ON ? new AuthorNagException(null) : null); + break; + } + } + + // Azurite start - ASM events backport + eventSet.add(new RegisteredListener(listener, EventExecutor.create(method, eventClass), eh.priority(), plugin, eh.ignoreCancelled())); + // Azurite end + } + return ret; + } + + @Override + public void enablePlugin(Plugin plugin) { + + } + + @Override + public void disablePlugin(Plugin plugin) { + + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/generator/Generator.java b/azurite-server/src/main/java/dev/azurite/spigot/generator/Generator.java new file mode 100644 index 0000000..7e3f287 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/generator/Generator.java @@ -0,0 +1,87 @@ +package dev.azurite.spigot.generator; + +import dev.azurite.spigot.Azurite; +import dev.azurite.spigot.configs.extra.Config; +import dev.azurite.spigot.configs.extra.ConfigSetting; +import dev.azurite.spigot.utils.CC; + +import java.io.File; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public class Generator extends Config { + + private final String name; + + public final ConfigSetting generateOceans = new ConfigSetting<>(true, "world", "Generate any oceans"); + public final ConfigSetting generateWaterLakes = new ConfigSetting<>(true, "world", "Generate any water lakes"); + public final ConfigSetting generateLavaLakes = new ConfigSetting<>(true, "world", "Generate any lava lakes"); + public final ConfigSetting flatBedrock = new ConfigSetting<>(false, "world", "Should worlds be generated with flat bedrock"); + public final ConfigSetting cavesMultiplier = new ConfigSetting<>(1.0, "world", "Multiply the amount of cave generation"); + public final ConfigSetting sugarCaneMultiplier = new ConfigSetting<>(1.0, "world", "Multiply the amount of cane generation"); + + public final ConfigSetting biomePlains = new ConfigSetting<>(true, "world.biomes"); + public final ConfigSetting biomeDesert = new ConfigSetting<>(true, "world.biomes"); + public final ConfigSetting biomeDesertHills = new ConfigSetting<>(true, "world.biomes"); + public final ConfigSetting biomeExtremeHills = new ConfigSetting<>(true, "world.biomes"); + public final ConfigSetting biomeExtremeHillsPlus = new ConfigSetting<>(true, "world.biomes"); + public final ConfigSetting biomeForest = new ConfigSetting<>(true, "world.biomes"); + public final ConfigSetting biomeForestHills = new ConfigSetting<>(true, "world.biomes"); + public final ConfigSetting biomeTaiga = new ConfigSetting<>(true, "world.biomes"); + public final ConfigSetting biomeTaigaHills = new ConfigSetting<>(true, "world.biomes"); + public final ConfigSetting biomeSwampland = new ConfigSetting<>(true, "world.biomes"); + public final ConfigSetting biomeIcePlains = new ConfigSetting<>(true, "world.biomes"); + public final ConfigSetting biomeIceMountains = new ConfigSetting<>(true, "world.biomes"); + public final ConfigSetting biomeMushroomIsland = new ConfigSetting<>(true, "world.biomes"); + public final ConfigSetting biomeJungle = new ConfigSetting<>(true, "world.biomes"); + public final ConfigSetting biomeJungleHills = new ConfigSetting<>(true, "world.biomes"); + public final ConfigSetting biomeBirchForest = new ConfigSetting<>(true, "world.biomes"); + public final ConfigSetting biomeBirchForestHills = new ConfigSetting<>(true, "world.biomes"); + public final ConfigSetting biomeRoofedForest = new ConfigSetting<>(true, "world.biomes"); + public final ConfigSetting biomeColdTaiga = new ConfigSetting<>(true, "world.biomes"); + public final ConfigSetting biomeColdTaigaHills = new ConfigSetting<>(true, "world.biomes"); + public final ConfigSetting biomeMegaTaiga = new ConfigSetting<>(true, "world.biomes"); + public final ConfigSetting biomeMegaTaigaHills = new ConfigSetting<>(true, "world.biomes"); + public final ConfigSetting biomeSavanna = new ConfigSetting<>(true, "world.biomes"); + public final ConfigSetting biomeSavannaPlateau = new ConfigSetting<>(true, "world.biomes"); + public final ConfigSetting biomeMesa = new ConfigSetting<>(true, "world.biomes"); + public final ConfigSetting biomeMesaPlateauF = new ConfigSetting<>(true, "world.biomes"); + public final ConfigSetting biomeMesaPlateau = new ConfigSetting<>(true, "world.biomes"); + + public final ConfigSetting spawnBiomeRadius = new ConfigSetting<>(0, "world.spawn", "Radius of spawn biome (0, 0 coords)"); + public final ConfigSetting spawnBiome = new ConfigSetting<>("Plains", "world.spawn", "Use custom biome to spawn within a certain radius", false); + public final ConfigSetting spawnBiomeRivers = new ConfigSetting<>(true, "world.spawn", "Generate rivers in spawn biome"); + public final ConfigSetting spawnBiomeLakes = new ConfigSetting<>(true, "world.spawn", "Generate lakes in spawn biome"); + + public final ConfigSetting emeraldMultiplier = new ConfigSetting<>(1.0, "ores.emerald", "Multiply the amount of emerald generation"); + public final ConfigSetting coalMultiplier = new ConfigSetting<>(1.0, "ores.coal", "Multiply the amount of coal generation"); + public final ConfigSetting coalSize = new ConfigSetting<>(17, "ores.coal", "Maximum amount of coal can be generated in 1 chunk"); + public final ConfigSetting coalMustTouchAir = new ConfigSetting<>(false, "ores.coal", "Generate coal only in caves"); + public final ConfigSetting ironMultiplier = new ConfigSetting<>(1.0, "ores.iron", "Multiply the amount of iron generation"); + public final ConfigSetting ironSize = new ConfigSetting<>(9, "ores.iron", "Maximum amount of iron can be generated in 1 chunk"); + public final ConfigSetting ironMustTouchAir = new ConfigSetting<>(false, "ores.iron", "Generate iron only in caves"); + public final ConfigSetting goldMultiplier = new ConfigSetting<>(1.0, "ores.gold", "Multiply the amount of gold generation"); + public final ConfigSetting goldSize = new ConfigSetting<>(9, "ores.gold", "Maximum amount of gold can be generated in 1 chunk"); + public final ConfigSetting goldMustTouchAir = new ConfigSetting<>(false, "ores.gold", "Generate gold only in caves"); + public final ConfigSetting redstoneMultiplier = new ConfigSetting<>(1.0, "ores.redstone", "Multiply the amount of redstone generation"); + public final ConfigSetting redstoneSize = new ConfigSetting<>(8, "ores.redstone", "Maximum amount of redstone can be generated in 1 chunk"); + public final ConfigSetting redstoneMustTouchAir = new ConfigSetting<>(false, "ores.redstone", "Generate redstone only in caves"); + public final ConfigSetting diamondMultiplier = new ConfigSetting<>(1.0, "ores.diamond", "Multiply the amount of diamond generation"); + public final ConfigSetting diamondSize = new ConfigSetting<>(8, "ores.diamond", "Maximum amount of diamonds can be generated in 1 chunk"); + public final ConfigSetting diamondMustTouchAir = new ConfigSetting<>(false, "ores.diamond", "Generate diamonds only in caves"); + public final ConfigSetting lapisMultiplier = new ConfigSetting<>(1.0, "ores.lapis", "Multiply the amount of lapis generation"); + public final ConfigSetting lapisSize = new ConfigSetting<>(7, "ores.lapis", "Maximum amount of lapis can be generated in 1 chunk"); + public final ConfigSetting lapisMustTouchAir = new ConfigSetting<>(false, "ores.lapis", "Generate lapis only in caves"); + + public Generator(Azurite azurite, String name, File file) { + super(azurite, file.getName() + File.separator + name, CC.getConfigHeader(name + " (Generator)")); + this.name = name.replace(".yml", ""); + } + + public String getName() { + return name; + } +} diff --git a/azurite-server/src/main/java/dev/azurite/spigot/generator/GeneratorManager.java b/azurite-server/src/main/java/dev/azurite/spigot/generator/GeneratorManager.java new file mode 100644 index 0000000..ef5f50c --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/generator/GeneratorManager.java @@ -0,0 +1,70 @@ +package dev.azurite.spigot.generator; + +import dev.azurite.spigot.Azurite; +import dev.azurite.spigot.configs.extra.ConfigFolder; + +import java.io.File; +import java.util.Map; +import java.util.TreeMap; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public class GeneratorManager { + + private final Map generators; + private final ConfigFolder parentFile; + private Generator defaultConfig; + + public GeneratorManager() { + this.generators = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + this.parentFile = new ConfigFolder("generator"); + this.load(); + } + + private void load() { + File[] files = parentFile.listFiles(); + + if (files != null) { + for (File file : files) { + this.createGenerator(file.getName()); + } + } + + this.defaultConfig = this.getOrCreate("Default"); + } + + public void save(boolean async) { + for (Generator generator : generators.values()) { + generator.save(async); + } + } + + private Generator createGenerator(String name) { + Generator generator = new Generator(Azurite.getInstance(), name, parentFile); + generator.load(); + generator.save(false); + generators.put(generator.getName(), generator); + return generator; + } + + public Generator getOrCreate(String name) { + Generator generator = generators.get(name); + + if (generator == null) { + generator = createGenerator(name); + } + + return generator; + } + + public Generator getDefaultConfig() { + return defaultConfig; + } + + public Map getGenerators() { + return generators; + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/generator/layer/GenLayerSpawnBiome.java b/azurite-server/src/main/java/dev/azurite/spigot/generator/layer/GenLayerSpawnBiome.java new file mode 100644 index 0000000..29bbbdd --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/generator/layer/GenLayerSpawnBiome.java @@ -0,0 +1,40 @@ +package dev.azurite.spigot.generator.layer; + +import net.minecraft.server.GenLayer; +import net.minecraft.server.IntCache; +import net.minecraft.server.World; + +public class GenLayerSpawnBiome extends GenLayer { + + private final GenLayer parent; + private final int biomeSize; + private final World world; + + public GenLayerSpawnBiome(GenLayer parent, int biomeSize, World world) { + super(1); + this.parent = parent; + this.biomeSize = biomeSize; + this.world = world; + } + + @Override + public int[] a(int x, int z, int w, int h) { + int radiusSqrd = world.generatorConfig.spawnBiomeRadius.getValue() * world.generatorConfig.spawnBiomeRadius.getValue(); + int[] in = parent.a(x, z, w, h); + int[] out = IntCache.a(w * h); + + for (int i = 0; i < w; i++) { + for (int j = 0; j < h; j++) { + int index = j * w + i; + int worldX = (x + i) << 2 << biomeSize; + int worldZ = (z + j) << 2 << biomeSize; + if (worldX * worldX + worldZ * worldZ < radiusSqrd) { + out[index] = world.spawnBiome.id; + } else { + out[index] = in[index]; + } + } + } + return out; + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/generator/layer/GenLayerSpawnRiver.java b/azurite-server/src/main/java/dev/azurite/spigot/generator/layer/GenLayerSpawnRiver.java new file mode 100644 index 0000000..068c86c --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/generator/layer/GenLayerSpawnRiver.java @@ -0,0 +1,51 @@ +package dev.azurite.spigot.generator.layer; + +import net.minecraft.server.BiomeBase; +import net.minecraft.server.GenLayer; +import net.minecraft.server.IntCache; +import net.minecraft.server.World; + +public class GenLayerSpawnRiver extends GenLayer { + + private final World world; + + public GenLayerSpawnRiver(long var1, GenLayer var3, World world) { + super(var1); + super.a = var3; + this.world = world; + } + + public int[] a(int var1, int var2, int var3, int var4) { + int radiusSqrd = world.generatorConfig.spawnBiomeRadius.getValue() * world.generatorConfig.spawnBiomeRadius.getValue(); + int var5 = var1 - 1; + int var6 = var2 - 1; + int var7 = var3 + 2; + int var8 = var4 + 2; + int[] var9 = this.a.a(var5, var6, var7, var8); + int[] var10 = IntCache.a(var3 * var4); + + for(int var11 = 0; var11 < var4; ++var11) { + for(int var12 = 0; var12 < var3; ++var12) { + int var13 = this.c(var9[var12 + (var11 + 1) * var7]); + int var14 = this.c(var9[var12 + 2 + (var11 + 1) * var7]); + int var15 = this.c(var9[var12 + 1 + (var11) * var7]); + int var16 = this.c(var9[var12 + 1 + (var11 + 2) * var7]); + int var17 = this.c(var9[var12 + 1 + (var11 + 1) * var7]); + int worldX = (var1 + var11) << 2; + int worldZ = (var2 + var12) << 2; + + if ((var17 == var13 && var17 == var15 && var17 == var14 && var17 == var16) || (worldX * worldX + worldZ * worldZ < radiusSqrd)) { + var10[var12 + var11 * var3] = -1; + } else { + var10[var12 + var11 * var3] = BiomeBase.RIVER.id; + } + } + } + + return var10; + } + + private int c(int var1) { + return var1 >= 2 ? 2 + (var1 & 1) : var1; + } +} diff --git a/azurite-server/src/main/java/dev/azurite/spigot/knockback/Knockback.java b/azurite-server/src/main/java/dev/azurite/spigot/knockback/Knockback.java new file mode 100644 index 0000000..b4510ba --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/knockback/Knockback.java @@ -0,0 +1,362 @@ +package dev.azurite.spigot.knockback; + +import dev.azurite.spigot.Azurite; +import dev.azurite.spigot.api.knockback.IKnockback; +import dev.azurite.spigot.api.knockback.types.IAdvancedKnockback; +import dev.azurite.spigot.api.knockback.types.IConstantKnockback; +import dev.azurite.spigot.api.knockback.types.ISimpleKnockback; +import dev.azurite.spigot.configs.extra.Config; +import dev.azurite.spigot.configs.extra.ConfigSetting; +import dev.azurite.spigot.knockback.extra.KnockbackParent; +import dev.azurite.spigot.knockback.types.AdvancedKnockback; +import dev.azurite.spigot.knockback.types.ConstantKnockback; +import dev.azurite.spigot.knockback.types.SimpleKnockback; +import dev.azurite.spigot.utils.CC; + +import java.io.File; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public class Knockback extends Config implements IKnockback { + + public final String name; + + // Knockback Types + public List knockbackTypes; + public SimpleKnockback simpleKnockback; // We save both simple and advanced in case the user switches between them + public AdvancedKnockback advancedKnockback; + public ConstantKnockback constantKnockback; + + // Knockback Config + public final ConfigSetting knockbackType = new ConfigSetting<>("SIMPLE", "type", ""); + + // Rod + public final ConfigSetting rodHorizontal = new ConfigSetting<>(1.1, "", "Horizontal fishing rod knockback"); + public final ConfigSetting rodVertical = new ConfigSetting<>(1.0, "", "Vertical fishing rod knockback"); + public final ConfigSetting rodSpeed = new ConfigSetting<>(1.0, "", "Multiplies the number given with the rod's vector magnitude"); + + // Bow + public final ConfigSetting bowBoostDirectional = new ConfigSetting<>(false, "", "Should bow boosting be enabled using the direction player is facing"); + public final ConfigSetting bowBoostKbOnlyShooter = new ConfigSetting<>(false, "", "Should bow boosting direction only be enabled for shooter"); + public final ConfigSetting bowHorizontal = new ConfigSetting<>(0.9, "", "Horizontal bow knockback"); + public final ConfigSetting bowVertical = new ConfigSetting<>(0.9, "", "Vertical bow knockback"); + public final ConfigSetting bowBoostHorizontal = new ConfigSetting<>(1.1, "", "Horizontal bow boost knockback"); + public final ConfigSetting bowBoostVertical = new ConfigSetting<>(0.35, "", "Horizontal bow boost knockback"); + public final ConfigSetting bowPunchMultiplier = new ConfigSetting<>(1.1, "", "Punch enchantment modifier: horizontal *= (punchLevel + 1) * bowPunchMultiplier"); + + // Potions + public final ConfigSetting potionFall = new ConfigSetting<>(0.05F, "", "Fall speed value"); + public final ConfigSetting potionSpeed = new ConfigSetting<>(0.5F, "", "Throwing multiplier value"); + public final ConfigSetting potionVerticalOffset = new ConfigSetting<>(-20.0F, "", "Vertical throwing angle offset value"); + public final ConfigSetting potionYOffset = new ConfigSetting<>(0.0D, "", "Y offset value"); + public final ConfigSetting potionFast = new ConfigSetting<>(true, "", "Make heal potions throwing smoother"); + public final ConfigSetting potionBetterVisual = new ConfigSetting<>(true, "", "Make heal potions splash visually better when it hits the entity"); + + // Misc + public final ConfigSetting cpsCapOverride = new ConfigSetting<>(-1, "", "Should the default CPS Cap be overridden (use -1 to disable)"); + public final ConfigSetting hitDelay = new ConfigSetting<>(20, "", "Delay between victim can get hit"); + public final ConfigSetting hitDelayArrow = new ConfigSetting<>(20, "", "Delay between victim can get hit by an arrow (Patches arrow bounce bug)"); + + // Combo + public final ConfigSetting comboMode = new ConfigSetting<>(false, "", "Enable combo mode"); + public final ConfigSetting comboHeight = new ConfigSetting<>(2.3, "", "Maximum height of combo"); + public final ConfigSetting comboTicks = new ConfigSetting<>(10, "", "Maximum combo ticks"); + public final ConfigSetting comboVelocity = new ConfigSetting<>(-0.05, "", "Vertical deduction on hit"); + + public Knockback(Azurite instance, String name, File parent) { + super(instance, parent.getName() + File.separator + name, CC.getConfigHeader(name + " (Knockback)")); + this.name = name.replace(".yml", ""); + this.knockbackTypes = new ArrayList<>(); + this.simpleKnockback = new SimpleKnockback(this); + this.advancedKnockback = new AdvancedKnockback(this); + this.constantKnockback = new ConstantKnockback(this); + } + + public List> getKnockbackSettings() { + List> knockbackSettings = new ArrayList<>(); + + try { + for (KnockbackParent parent : knockbackTypes) { + for (Field field : parent.getClass().getDeclaredFields()) { + if (field.getType() != ConfigSetting.class) continue; + ConfigSetting configSetting = (ConfigSetting) field.get(parent); + configSetting.setConfig(this); + configSetting.setName(field.getName()); + configSetting.setPath(parent.getType().getPath()); + knockbackSettings.add(configSetting); + } + } + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + + return knockbackSettings; + } + + public KnockbackType getKnockbackType() { + return KnockbackType.valueOf(knockbackType.getValue()); + } + + public ConfigSetting getActiveSetting(String name) { + for (ConfigSetting activeSetting : getActiveSettings()) { + if (activeSetting.getName().equalsIgnoreCase(name)) { + return activeSetting; + } + } + return null; + } + + public List> getActiveSettings() { + return getSettings().stream().filter(setting -> getKnockbackType().isApplicable(setting)).collect(Collectors.toList()); + } + + @Override + public String getName() { + return name; + } + + @Override + public String getType() { + return getKnockbackType().getDisplayName(); + } + + @Override + public IAdvancedKnockback getAdvancedKnockback() { + return advancedKnockback; + } + + @Override + public ISimpleKnockback getSimpleKnockback() { + return simpleKnockback; + } + + @Override + public IConstantKnockback getConstantKnockback() { + return constantKnockback; + } + + @Override + public boolean isActive() { + return Azurite.getInstance().getKnockbackManager().getActiveProfile().getName().equals(name); + } + + @Override + public double getRodHorizontal() { + return rodHorizontal.getValue(); + } + + @Override + public void setRodHorizontal(double amount) { + rodHorizontal.set(amount, true); + } + + @Override + public double getRodVertical() { + return rodVertical.getValue(); + } + + @Override + public void setRodVertical(double amount) { + rodVertical.set(amount, true); + } + + @Override + public double getRodSpeed() { + return rodSpeed.getValue(); + } + + @Override + public void setRodSpeed(double amount) { + rodSpeed.set(amount, true); + } + + @Override + public boolean getBowBoostDirectional() { + return bowBoostDirectional.getValue(); + } + + @Override + public void setBowBoostDirectional(boolean value) { + bowBoostDirectional.set(value, true); + } + + @Override + public boolean isBowBoostOnlyShooter() { + return bowBoostKbOnlyShooter.getValue(); + } + + @Override + public void setBowBoostOnlyShooter(boolean value) { + bowBoostKbOnlyShooter.set(value, true); + } + + @Override + public double getBowHorizontal() { + return bowHorizontal.getValue(); + } + + @Override + public void setBowHorizontal(double amount) { + bowHorizontal.set(amount, true); + } + + @Override + public double getBowVertical() { + return bowVertical.getValue(); + } + + @Override + public void setBowVertical(double amount) { + bowVertical.set(amount, true); + } + + @Override + public double getBowPunchMultiplier() { + return bowPunchMultiplier.getValue(); + } + + @Override + public void setBowPunchMultiplier(double amount) { + bowPunchMultiplier.set(amount, true); + } + + @Override + public float getPotionFall() { + return potionFall.getValue(); + } + + @Override + public void setPotionFall(float amount) { + potionFall.set(amount, true); + } + + @Override + public float getPotionSpeed() { + return potionSpeed.getValue(); + } + + @Override + public void setPotionSpeed(float amount) { + potionSpeed.set(amount, true); + } + + @Override + public float getPotionOffset() { + return potionVerticalOffset.getValue(); + } + + @Override + public void setPotionOffset(float amount) { + potionVerticalOffset.set(amount, true); + } + + @Override + public double getPotionYOffset() { + return potionYOffset.getValue(); + } + + @Override + public void setPotionYOffset(double amount) { + potionYOffset.set(amount, true); + } + + @Override + public boolean isPotionFast() { + return potionFast.getValue(); + } + + @Override + public void setPotionFast(boolean value) { + potionFast.set(value, true); + } + + @Override + public int getCpsCapOverride() { + return cpsCapOverride.getValue(); + } + + @Override + public void setCpsCapOverride(int cps) { + cpsCapOverride.set(cps, true); + } + + @Override + public int getHitDelay() { + return hitDelay.getValue(); + } + + @Override + public void setHitDelay(int amount) { + hitDelay.set(amount, true); + } + + @Override + public int getHitDelayArrow() { + return hitDelayArrow.getValue(); + } + + @Override + public void setHitDelayArrow(int amount) { + hitDelayArrow.set(amount, true); + } + + @Override + public boolean isComboMode() { + return comboMode.getValue(); + } + + @Override + public void setComboMode(boolean value) { + comboMode.set(value, true); + } + + @Override + public double getComboHeight() { + return comboHeight.getValue(); + } + + @Override + public void setComboHeight(double amount) { + comboHeight.set(amount, true); + } + + @Override + public int getComboTicks() { + return comboTicks.getValue(); + } + + @Override + public void setComboTicks(int amount) { + comboTicks.set(amount, true); + } + + @Override + public double getComboVelocity() { + return comboVelocity.getValue(); + } + + @Override + public void setComboVelocity(double amount) { + comboVelocity.set(amount, true); + } + + @Override + public Map getValues() { + Map map = new LinkedHashMap<>(); + + for (ConfigSetting setting : getActiveSettings()) { + map.put(setting.getName(), setting.getValue()); + } + + return map; + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/knockback/KnockbackManager.java b/azurite-server/src/main/java/dev/azurite/spigot/knockback/KnockbackManager.java new file mode 100644 index 0000000..b8f2876 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/knockback/KnockbackManager.java @@ -0,0 +1,105 @@ +package dev.azurite.spigot.knockback; + +import dev.azurite.spigot.Azurite; +import dev.azurite.spigot.api.knockback.IKnockback; +import dev.azurite.spigot.api.knockback.IKnockbackManager; +import dev.azurite.spigot.configs.AzuriteConfig; +import dev.azurite.spigot.configs.extra.ConfigFolder; +import dev.azurite.spigot.knockback.extra.KnockbackEdit; + +import java.io.File; +import java.util.*; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public class KnockbackManager implements IKnockbackManager { + + private final Map profiles; + private final Map editing; + private final ConfigFolder parent; + private Knockback activeProfile; + + public KnockbackManager() { + this.profiles = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + this.editing = new HashMap<>(); + this.parent = new ConfigFolder("knockback"); + this.activeProfile = null; + this.load(); + } + + private void load() { + File[] files = parent.listFiles(); + + if (files != null) { + for (File file : files) { + Knockback knockback = (Knockback) createProfile(file.getName()); + + if (AzuriteConfig.globalActiveKnockback.getValue().equals(knockback.getName())) { + this.activeProfile = knockback; + } + } + } + + if (activeProfile == null) { + AzuriteConfig.globalActiveKnockback.set("Default", true); + IKnockback defaultKnockback = getByName("Default"); + this.activeProfile = (defaultKnockback != null ? (Knockback) defaultKnockback : (Knockback) createProfile("Default")); + } + } + + public Map getEditing() { + return editing; + } + + @Override + public List getProfiles() { + return new ArrayList<>(profiles.values()); + } + + @Override + public IKnockback createProfile(String name) { + Knockback knockback = new Knockback(Azurite.getInstance(), name, parent); + knockback.load(); + knockback.save(true); + profiles.put(knockback.getName(), knockback); + return knockback; + } + + @Override + public IKnockback deleteProfile(String name) { + Knockback knockback = profiles.get(name); + + if (knockback != null && !knockback.getName().equals(activeProfile.getName())) { + knockback.delete(); + profiles.remove(name); + } + + return knockback; + } + + @Override + public IKnockback getByName(String name) { + return profiles.get(name); + } + + @Override + public IKnockback getActiveProfile() { + return activeProfile; + } + + @Override + public void setActiveProfile(IKnockback knockback) { + this.activeProfile = (Knockback) knockback; + AzuriteConfig.globalActiveKnockback.set(activeProfile.getName(), true); + } + + @Override + public void save(boolean async) { + for (Knockback profile : profiles.values()) { + profile.save(async); + } + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/knockback/KnockbackType.java b/azurite-server/src/main/java/dev/azurite/spigot/knockback/KnockbackType.java new file mode 100644 index 0000000..6c7586b --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/knockback/KnockbackType.java @@ -0,0 +1,35 @@ +package dev.azurite.spigot.knockback; + +import dev.azurite.spigot.configs.extra.ConfigSetting; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public enum KnockbackType { + + SIMPLE("Simple", "knockback-simple"), + ADVANCED("Advanced", "knockback-advanced"), + CONSTANT("Constant", "knockback-constant"); + + private final String displayName; + private final String path; + + KnockbackType(String displayName, String path) { + this.displayName = displayName; + this.path = path; + } + + public boolean isApplicable(ConfigSetting setting) { + return setting.getPath().isEmpty() || setting.getPath().equals(path); + } + + public String getDisplayName() { + return displayName; + } + + public String getPath() { + return path; + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/knockback/event/ArrowBypassNoDamageTicksEvent.java b/azurite-server/src/main/java/dev/azurite/spigot/knockback/event/ArrowBypassNoDamageTicksEvent.java new file mode 100644 index 0000000..94895d3 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/knockback/event/ArrowBypassNoDamageTicksEvent.java @@ -0,0 +1,42 @@ +package dev.azurite.spigot.knockback.event; + +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; +import org.bukkit.event.player.PlayerEvent; + +public class ArrowBypassNoDamageTicksEvent extends PlayerEvent implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + private boolean isCancelled = false; + private final Entity damageSource; + + public ArrowBypassNoDamageTicksEvent(Player player, Entity damageSource) { + super(player); + this.damageSource = damageSource; + } + + public Entity getDamageSource() { + return damageSource; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + @Override + public boolean isCancelled() { + return this.isCancelled; + } + + @Override + public void setCancelled(boolean cancel) { + this.isCancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } +} diff --git a/azurite-server/src/main/java/dev/azurite/spigot/knockback/extra/KnockbackEdit.java b/azurite-server/src/main/java/dev/azurite/spigot/knockback/extra/KnockbackEdit.java new file mode 100644 index 0000000..8caac7e --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/knockback/extra/KnockbackEdit.java @@ -0,0 +1,27 @@ +package dev.azurite.spigot.knockback.extra; + +import dev.azurite.spigot.configs.extra.ConfigSetting; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public class KnockbackEdit { + + private final String profile; + private final ConfigSetting setting; + + public KnockbackEdit(String profile, ConfigSetting setting) { + this.profile = profile; + this.setting = setting; + } + + public ConfigSetting getSetting() { + return setting; + } + + public String getProfile() { + return profile; + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/knockback/extra/KnockbackParent.java b/azurite-server/src/main/java/dev/azurite/spigot/knockback/extra/KnockbackParent.java new file mode 100644 index 0000000..56a1cd2 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/knockback/extra/KnockbackParent.java @@ -0,0 +1,29 @@ +package dev.azurite.spigot.knockback.extra; + +import dev.azurite.spigot.knockback.Knockback; +import dev.azurite.spigot.knockback.KnockbackType; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public class KnockbackParent { + + private final Knockback knockback; + private final KnockbackType type; + + public KnockbackParent(Knockback knockback, KnockbackType type) { + this.knockback = knockback; + this.type = type; + knockback.knockbackTypes.add(this); + } + + public Knockback getKnockback() { + return knockback; + } + + public KnockbackType getType() { + return type; + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/knockback/types/AdvancedKnockback.java b/azurite-server/src/main/java/dev/azurite/spigot/knockback/types/AdvancedKnockback.java new file mode 100644 index 0000000..3289083 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/knockback/types/AdvancedKnockback.java @@ -0,0 +1,220 @@ +package dev.azurite.spigot.knockback.types; + +import dev.azurite.spigot.api.knockback.types.IAdvancedKnockback; +import dev.azurite.spigot.configs.extra.ConfigSetting; +import dev.azurite.spigot.knockback.Knockback; +import dev.azurite.spigot.knockback.KnockbackType; +import dev.azurite.spigot.knockback.extra.KnockbackParent; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public class AdvancedKnockback extends KnockbackParent implements IAdvancedKnockback { + + public final ConfigSetting horizontal = new ConfigSetting<>(0.45, "", "Horizontal knockback: horizontal = value"); + public final ConfigSetting horizontalOnGround = new ConfigSetting<>(1.1, "", "On ground horizontal kb modifier: horizontal *= multiplier"); + public final ConfigSetting horizontalSprinting = new ConfigSetting<>(0.95, "", "Sprinting horizontal kb modifier: horizontal *= multiplier"); + public final ConfigSetting horizontalInherit = new ConfigSetting<>(true, "", "Inherit victim motion"); + public final ConfigSetting horizontalFriction = new ConfigSetting<>(0.35, "", "Horizontal friction: horizontal = (motion * frictionHorizontal) + victimYaw"); + public final ConfigSetting horizontalKnockbackDeduction = new ConfigSetting<>(0.8, "", "Knockback enchantment modifier: horizontal *= ((enchLevel + 1) - kbDeductionValue)"); + + public final ConfigSetting vertical = new ConfigSetting<>(0.35, "", "Vertical knockback. vertical = value"); + public final ConfigSetting verticalOnGround = new ConfigSetting<>(1.1, "", "On ground vertical kb modifier: vertical *= multiplier"); + public final ConfigSetting verticalInAir = new ConfigSetting<>(0.85, "", "In air vertical kb modifier: vertical *= multiplier"); + public final ConfigSetting verticalSprinting = new ConfigSetting<>(1.0, "", "Sprinting vertical kb modifier: vertical *= multiplier"); + public final ConfigSetting verticalInherit = new ConfigSetting<>(false, "", "Inherit victim vertical motion"); + public final ConfigSetting verticalFriction = new ConfigSetting<>(0.35, "", "Vertical friction: vertical += (motion * frictionHorizontal)"); + + public final ConfigSetting enableOnePointSeven = new ConfigSetting<>(true, "", "Help players with victim chasing"); + public final ConfigSetting onePointSevenHorizontal = new ConfigSetting<>(0.37, "", "Horizontal knockback on back-hit: horizontal = value"); + public final ConfigSetting enableVerticalLimit = new ConfigSetting<>(false, "", "Limit vertical if it exceeds yLimit"); + public final ConfigSetting verticalLimit = new ConfigSetting<>(1.2, "", "Vertical limit: vertical = 0"); + public final ConfigSetting slowdown = new ConfigSetting<>(0.6, "", "Slowdown player on hit"); + public final ConfigSetting cancelSprint = new ConfigSetting<>(true, "", "Cancel sprint for player on hit"); + + public AdvancedKnockback(Knockback knockback) { + super(knockback, KnockbackType.ADVANCED); + } + + @Override + public double getHorizontal() { + return horizontal.getValue(); + } + + @Override + public void setHorizontal(double amount) { + horizontal.set(amount, true); + } + + @Override + public double getHorizontalOnGround() { + return horizontalOnGround.getValue(); + } + + @Override + public void setHorizontalOnGround(double amount) { + horizontalOnGround.set(amount, true); + } + + @Override + public double getHorizontalSprinting() { + return horizontalSprinting.getValue(); + } + + @Override + public void setHorizontalSprinting(double amount) { + horizontalSprinting.set(amount, true); + } + + @Override + public boolean isHorizontalInherit() { + return horizontalInherit.getValue(); + } + + @Override + public void setHorizontalInherit(boolean value) { + horizontalInherit.set(value, true); + } + + @Override + public double getHorizontalFriction() { + return horizontalFriction.getValue(); + } + + @Override + public void setHorizontalFriction(double amount) { + horizontalFriction.set(amount, true); + } + + @Override + public double getHorizontalKnockbackDeduction() { + return horizontalKnockbackDeduction.getValue(); + } + + @Override + public void setHorizontalKnockbackDeduction(double amount) { + horizontalKnockbackDeduction.set(amount, true); + } + + @Override + public double getVertical() { + return vertical.getValue(); + } + + @Override + public void setVertical(double amount) { + vertical.set(amount, true); + } + + @Override + public double getVerticalOnGround() { + return verticalOnGround.getValue(); + } + + @Override + public void setVerticalOnGround(double amount) { + verticalOnGround.set(amount, true); + } + + @Override + public double getVerticalInAir() { + return verticalInAir.getValue(); + } + + @Override + public void setVerticalInAir(double amount) { + verticalInAir.set(amount, true); + } + + @Override + public double getVerticalSprinting() { + return verticalSprinting.getValue(); + } + + @Override + public void setVerticalSprinting(double amount) { + verticalSprinting.set(amount, true); + } + + @Override + public boolean isVerticalInherit() { + return verticalInherit.getValue(); + } + + @Override + public void setVerticalInherit(boolean value) { + verticalInherit.set(value, true); + } + + @Override + public double getVerticalFriction() { + return verticalFriction.getValue(); + } + + @Override + public void setVerticalFriction(double amount) { + verticalFriction.set(amount, true); + } + + @Override + public boolean isOnePointSevenEnabled() { + return enableOnePointSeven.getValue(); + } + + @Override + public void setOnePointSevenEnabled(boolean value) { + enableOnePointSeven.set(value, true); + } + + @Override + public double getOnePointSevenHorizontal() { + return onePointSevenHorizontal.getValue(); + } + + @Override + public void setOnePointSevenHorizontal(double amount) { + onePointSevenHorizontal.set(amount, true); + } + + @Override + public boolean isEnabledVerticalLimit() { + return enableVerticalLimit.getValue(); + } + + @Override + public void setEnableVerticalLimit(boolean value) { + enableVerticalLimit.set(value, true); + } + + @Override + public double getVerticalLimit() { + return verticalLimit.getValue(); + } + + @Override + public void setVerticalLimit(double amount) { + verticalLimit.set(amount, true); + } + + @Override + public double getSlowdown() { + return slowdown.getValue(); + } + + @Override + public void setSlowdown(double amount) { + slowdown.set(amount, true); + } + + @Override + public boolean isCancelSprint() { + return cancelSprint.getValue(); + } + + @Override + public void setCancelSprint(boolean value) { + cancelSprint.set(value, true); + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/knockback/types/ConstantKnockback.java b/azurite-server/src/main/java/dev/azurite/spigot/knockback/types/ConstantKnockback.java new file mode 100644 index 0000000..b5dd177 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/knockback/types/ConstantKnockback.java @@ -0,0 +1,69 @@ +package dev.azurite.spigot.knockback.types; + +import dev.azurite.spigot.api.knockback.types.IConstantKnockback; +import dev.azurite.spigot.configs.extra.ConfigSetting; +import dev.azurite.spigot.knockback.Knockback; +import dev.azurite.spigot.knockback.KnockbackType; +import dev.azurite.spigot.knockback.extra.KnockbackParent; + +public class ConstantKnockback extends KnockbackParent implements IConstantKnockback { + public final ConfigSetting horizontal = new ConfigSetting<>(0.527375, "", "Horizontal knockback"); + public final ConfigSetting vertical = new ConfigSetting<>(0.361375, "", "Vertical knockback"); + public final ConfigSetting verticalLongAir = new ConfigSetting<>(0.1, "", "Vertical knockback when player is for 20 client ticks in the air"); + public final ConfigSetting horizontalSprintReset = new ConfigSetting<>(0.8545, "", "Horizontal knockback after sprint reset"); + public final ConfigSetting yawModifier = new ConfigSetting<>(0.0D, "", "How much extra knockback should be given based on the yaw"); + + public ConstantKnockback(Knockback knockback) { + super(knockback, KnockbackType.CONSTANT); + } + + @Override + public void setHorizontal(double amount) { + horizontal.set(amount, true); + } + + @Override + public double getHorizontal() { + return horizontal.getValue(); + } + + @Override + public void setVertical(double amount) { + vertical.set(amount, true); + } + + @Override + public double getVertical() { + return vertical.getValue(); + } + + @Override + public void setVerticalLongAir(double amount) { + verticalLongAir.set(amount, true); + } + + @Override + public double getVerticalLongAir() { + return verticalLongAir.getValue(); + } + + @Override + public void setHorizontalSprintReset(double amount) { + horizontalSprintReset.set(amount, true); + } + + @Override + public double getHorizontalSprintReset() { + return horizontalSprintReset.getValue(); + } + + @Override + public void setYawModifier(double amount) { + yawModifier.set(amount, true); + } + + @Override + public double getYawModifier() { + return yawModifier.getValue(); + } +} diff --git a/azurite-server/src/main/java/dev/azurite/spigot/knockback/types/SimpleKnockback.java b/azurite-server/src/main/java/dev/azurite/spigot/knockback/types/SimpleKnockback.java new file mode 100644 index 0000000..625d2d7 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/knockback/types/SimpleKnockback.java @@ -0,0 +1,120 @@ +package dev.azurite.spigot.knockback.types; + +import dev.azurite.spigot.api.knockback.types.ISimpleKnockback; +import dev.azurite.spigot.configs.extra.ConfigSetting; +import dev.azurite.spigot.knockback.Knockback; +import dev.azurite.spigot.knockback.KnockbackType; +import dev.azurite.spigot.knockback.extra.KnockbackParent; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public class SimpleKnockback extends KnockbackParent implements ISimpleKnockback { + + public final ConfigSetting friction = new ConfigSetting<>(2.5, "", "Friction knockback: friction = value"); + public final ConfigSetting horizontal = new ConfigSetting<>(0.425, "", "Horizontal knockback: horizontal = value"); + public final ConfigSetting vertical = new ConfigSetting<>(0.5, "", "Vertical knockback: vertical = value"); + public final ConfigSetting verticalLimit = new ConfigSetting<>(0.38, "", "Limit of vertical knockback"); + public final ConfigSetting extraHorizontal = new ConfigSetting<>(0.25, "", "Extra horizontal knockback"); + public final ConfigSetting extraVertical = new ConfigSetting<>(0.01, "", "Extra vertical knockback"); + + public final ConfigSetting slowdown = new ConfigSetting<>(0.6, "", "Slowdown player on hit"); + public final ConfigSetting enableOnePointSeven = new ConfigSetting<>(true, "", "Help players with victim chasing"); + public final ConfigSetting onePointSevenMultiplier = new ConfigSetting<>(0.4, "", "Horizontal knockback multiplier for 1.7"); + + public SimpleKnockback(Knockback knockback) { + super(knockback, KnockbackType.SIMPLE); + } + + @Override + public void setFriction(double amount) { + friction.set(amount, true); + } + + @Override + public double getFriction() { + return friction.getValue(); + } + + @Override + public void setHorizontal(double amount) { + horizontal.set(amount, true); + } + + @Override + public double getHorizontal() { + return horizontal.getValue(); + } + + @Override + public void setVertical(double amount) { + vertical.set(amount, true); + } + + @Override + public double getVertical() { + return vertical.getValue(); + } + + @Override + public void setVerticalLimit(double amount) { + verticalLimit.set(amount, true); + } + + @Override + public double getVerticalLimit() { + return verticalLimit.getValue(); + } + + @Override + public void setExtraHorizontal(double amount) { + extraHorizontal.set(amount, true); + } + + @Override + public double getExtraHorizontal() { + return extraHorizontal.getValue(); + } + + @Override + public void setExtraVertical(double amount) { + extraVertical.set(amount, true); + } + + @Override + public double getExtraVertical() { + return extraVertical.getValue(); + } + + @Override + public void setSlowdown(double amount) { + slowdown.set(amount, true); + } + + @Override + public double getSlowdown() { + return slowdown.getValue(); + } + + @Override + public void setOnePointSevenEnabled(boolean value) { + enableOnePointSeven.set(value, true); + } + + @Override + public boolean isOnePointSevenEnabled() { + return enableOnePointSeven.getValue(); + } + + @Override + public void setOnePointSevenMultiplier(double amount) { + onePointSevenMultiplier.set(amount, true); + } + + @Override + public double getOnePointSevenMultiplier() { + return onePointSevenMultiplier.getValue(); + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/listeners/ChatListener.java b/azurite-server/src/main/java/dev/azurite/spigot/listeners/ChatListener.java new file mode 100644 index 0000000..ef26de0 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/listeners/ChatListener.java @@ -0,0 +1,113 @@ +package dev.azurite.spigot.listeners; + +import dev.azurite.spigot.Azurite; +import dev.azurite.spigot.api.knockback.IKnockback; +import dev.azurite.spigot.configs.LanguageConfig; +import dev.azurite.spigot.configs.extra.ConfigEdit; +import dev.azurite.spigot.configs.extra.ConfigSetting; +import dev.azurite.spigot.framework.menu.Menu; +import dev.azurite.spigot.knockback.KnockbackManager; +import dev.azurite.spigot.knockback.extra.KnockbackEdit; +import dev.azurite.spigot.utils.CC; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.AsyncPlayerChatEvent; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public class ChatListener implements Listener { + + @EventHandler(priority = EventPriority.LOW) + public void onChatKnockback(AsyncPlayerChatEvent e) { + Player player = e.getPlayer(); + KnockbackEdit edit = Azurite.getInstance().getKnockbackManager().getEditing().get(player.getUniqueId()); + + if (edit != null) { + KnockbackManager manager = Azurite.getInstance().getKnockbackManager(); + String message = e.getMessage(); + ConfigSetting setting = edit.getSetting(); + IKnockback knockback = manager.getByName(edit.getProfile()); + + e.setCancelled(true); + + if (message.equalsIgnoreCase("cancel")) { + manager.getEditing().remove(player.getUniqueId()); + CC.sendMessage(player, LanguageConfig.editCancelled.getValue() + .replace("%setting%", setting.getName()) + ); + return; + } + + if (knockback == null) { + manager.getEditing().remove(player.getUniqueId()); + CC.sendMessage(player, LanguageConfig.profileNotFound.getValue() + .replace("%name%", edit.getProfile()) + ); + return; + } + + Object value = setting.parseValue(message); + + if (value == null) { + CC.sendMessage(player, LanguageConfig.notValidType.getValue() + .replace("%value%", message) + .replace("%type%", setting.getValue().getClass().getSimpleName()) + ); + return; + } + + manager.getEditing().remove(player.getUniqueId()); + setting.set(value, true); + CC.sendMessage(player, LanguageConfig.editSettingValue.getValue() + .replace("%setting%", setting.getName()) + .replace("%value%", value.toString()) + .replace("%profile%", knockback.getName()) + ); + } + } + + @EventHandler + public void onChatConfig(AsyncPlayerChatEvent e) { + Player player = e.getPlayer(); + ConfigEdit edit = Azurite.getInstance().getConfigEdits().get(player.getUniqueId()); + + if (edit != null) { + String message = e.getMessage(); + ConfigSetting setting = edit.getSetting(); + Menu menu = edit.getMenu(); + e.setCancelled(true); + + if (message.equalsIgnoreCase("cancel")) { + Azurite.getInstance().getConfigEdits().remove(player.getUniqueId()); + CC.sendMessage(player, LanguageConfig.configEditCancelled.getValue() + .replace("%setting%", setting.getName()) + ); + return; + } + + Object value = setting.parseValue(message); + + if (value == null) { + CC.sendMessage(player, LanguageConfig.notValidType.getValue() + .replace("%value%", message) + .replace("%type%", setting.getValue().getClass().getSimpleName()) + ); + return; + } + + Azurite.getInstance().getConfigEdits().remove(player.getUniqueId()); + setting.set(value, true, false); + menu.open(); + Azurite.getInstance().reload(); + CC.sendMessage(player, LanguageConfig.configEditSetValue.getValue() + .replace("%setting%", setting.getName()) + .replace("%value%", value.toString()) + ); + } + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/listeners/MenuListener.java b/azurite-server/src/main/java/dev/azurite/spigot/listeners/MenuListener.java new file mode 100644 index 0000000..633370e --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/listeners/MenuListener.java @@ -0,0 +1,65 @@ +package dev.azurite.spigot.listeners; + +import dev.azurite.spigot.Azurite; +import dev.azurite.spigot.framework.menu.Menu; +import dev.azurite.spigot.framework.menu.button.Button; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.event.player.PlayerJoinEvent; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public class MenuListener implements Listener { + + @EventHandler + public void onJoin(PlayerJoinEvent e) { + Player player = e.getPlayer(); + + Menu menu = Azurite.getInstance().getMenuManager().getMenus().get(player.getUniqueId()); + + if (menu != null) { + menu.onClose(); + menu.destroy(); + } + } + + @EventHandler + public void onClick(InventoryClickEvent e) { + if (!(e.getWhoClicked() instanceof Player)) return; + if (e.getClickedInventory() == null) return; + + Player player = (Player) e.getWhoClicked(); + Menu menu = Azurite.getInstance().getMenuManager().getMenus().get(player.getUniqueId()); + + if (menu != null) { + if (!menu.isAllowInteract()) e.setCancelled(true); + menu.onClick(e); + + if (e.getClickedInventory() != player.getInventory()) { + Button button = menu.getButtons().get(e.getSlot() + 1); + if (button != null) button.onClick(e); + } + + if (e.getClickedInventory() == player.getInventory()) { + menu.onClickOwn(e); + } + } + } + + @EventHandler + public void onClose(InventoryCloseEvent e) { + Player player = (Player) e.getPlayer(); + Menu menu = Azurite.getInstance().getMenuManager().getMenus().remove(player.getUniqueId()); + + if (menu != null) { + menu.onClose(); + menu.destroy(); + } + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/listeners/PearlListener.java b/azurite-server/src/main/java/dev/azurite/spigot/listeners/PearlListener.java new file mode 100644 index 0000000..d74769f --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/listeners/PearlListener.java @@ -0,0 +1,47 @@ +package dev.azurite.spigot.listeners; + +import dev.azurite.spigot.Azurite; +import dev.azurite.spigot.api.pearls.PearlHandler; +import dev.azurite.spigot.configs.PearlConfig; +import dev.azurite.spigot.utils.Utils; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.entity.EnderPearl; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.material.Gate; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public class PearlListener implements Listener { + + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void handlePearl(PlayerInteractEvent e) { + if (e.getClickedBlock() == null) return; + if (e.getItem() == null || e.getItem().getType() != Material.ENDER_PEARL) return; + if (e.getAction() != Action.RIGHT_CLICK_BLOCK) return; + + Player player = e.getPlayer(); + Block block = e.getClickedBlock(); + String material = block.getType().name(); + boolean shouldPearl = (material.contains("FENCE_GATE") && ((Gate) block.getState().getData()).isOpen() && + PearlConfig.launchOnFenceClick.getValue()) || + PearlConfig.launchOnOtherClick.getValue().contains(material); + + if (shouldPearl) { + for (PearlHandler pearlHandler : Azurite.getInstance().getPearlHandlers()) { + if (pearlHandler.hasCooldown(player)) return; + } + e.setCancelled(true); + player.launchProjectile(EnderPearl.class); + Utils.takeItemInHand(player, 1); + } + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/menu/ConfigEditMenu.java b/azurite-server/src/main/java/dev/azurite/spigot/menu/ConfigEditMenu.java new file mode 100644 index 0000000..63c0265 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/menu/ConfigEditMenu.java @@ -0,0 +1,136 @@ +package dev.azurite.spigot.menu; + +import dev.azurite.spigot.Azurite; +import dev.azurite.spigot.configs.LanguageConfig; +import dev.azurite.spigot.configs.extra.Config; +import dev.azurite.spigot.configs.extra.ConfigEdit; +import dev.azurite.spigot.configs.extra.ConfigSetting; +import dev.azurite.spigot.framework.menu.Menu; +import dev.azurite.spigot.framework.menu.button.Button; +import dev.azurite.spigot.framework.menu.paginated.PaginatedMenu; +import dev.azurite.spigot.utils.CC; +import dev.azurite.spigot.utils.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public class ConfigEditMenu extends PaginatedMenu { + + private final Config config; + private final List> settings; + + public ConfigEditMenu(Player player, Config config, Menu previousMenu, List> settings) { + super( + player, + "&eEditing: &d" + config.getName(), + previousMenu, + 45, + true, + true + ); + this.config = config; + this.surroundGlass = true; + this.settings = settings; + + // If we are editing the menu directly (no back button, add close button) + if (previousMenu == null) { + defaultButtons.put(size - 4, new Button() { + @Override + public void onClick(InventoryClickEvent e) { + e.setCancelled(true); + player.closeInventory(); + } + + @Override + public ItemStack getItemStack() { + return new ItemBuilder(Material.BED) + .setName("&cClose") + .toItemStack(); + } + }); + } + } + + public ConfigEditMenu(Player player, Config config) { + this(player, config, new MainAzuriteMenu(player), config.getSettings()); + } + + @Override + public Map getButtons(Player player) { + Map map = new HashMap<>(); + int i = 1; + + for (ConfigSetting setting : settings) { + if (!setting.isEditable()) continue; + + Object value = setting.getValue(); + + map.put(i++, new Button() { + @Override + public void onClick(InventoryClickEvent e) { + e.setCancelled(true); + playClick(); + + if (value instanceof Boolean) { + setting.set(!(Boolean) value, true, false); + Azurite.getInstance().reload(); + update(); + + } else if (value instanceof Number) { + ConfigEdit configEdit = new ConfigEdit(setting, new ConfigEditMenu(player, config, previousMenu, settings)); + Azurite.getInstance().getConfigEdits().put(player.getUniqueId(), configEdit); + player.closeInventory(); + player.sendMessage(CC.t(LanguageConfig.configEditNewValue.getValue()) + .replace("%setting%", setting.getName()) + .replace("%current%", setting.getValue().toString()) + ); + } + } + + @Override + public ItemStack getItemStack() { + Material material = Material.BOOK; + String name = "&d" + setting.getName(); + String loreLine = ""; + int data = 0; + + if (value instanceof Boolean) { + Boolean toggle = (Boolean) value; + material = (toggle ? Material.EMERALD_BLOCK : Material.REDSTONE_BLOCK); + name = name + " &6(Status: " + (toggle ? "&aEnabled" : "&cDisabled") + "&6)"; + loreLine = "&eClick to &6toggle ðis feature."; + //loreLine = "&eClick to " + (toggle ? "&cdisable" : "&aenable") + " ðis feature."; + + } else if (value instanceof Number) { + name = name + " &6(Count: &b" + value + "&6)"; + loreLine = "&eClick to &6edit ðis feature."; + } + + List lore = new ArrayList<>(); + lore.add("&7&o(" + setting.getFullPath() + ")"); + lore.add(""); + lore.add(loreLine); + + return new ItemBuilder(material) + .setName(name) + .data(data) + .setLore(lore) + .toItemStack(); + } + }); + } + + return map; + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/menu/MainAzuriteMenu.java b/azurite-server/src/main/java/dev/azurite/spigot/menu/MainAzuriteMenu.java new file mode 100644 index 0000000..a8078aa --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/menu/MainAzuriteMenu.java @@ -0,0 +1,143 @@ +package dev.azurite.spigot.menu; + +import dev.azurite.spigot.Azurite; +import dev.azurite.spigot.framework.menu.Menu; +import dev.azurite.spigot.framework.menu.button.Button; +import dev.azurite.spigot.menu.extra.ProfileType; +import dev.azurite.spigot.utils.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.HashMap; +import java.util.Map; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public class MainAzuriteMenu extends Menu { + + public MainAzuriteMenu(Player player) { + super( + player, + "&dSpigot Configurations", + 45, + false + ); + this.fillEnabled = true; + this.filler = new ItemBuilder(Material.STAINED_GLASS_PANE).setName("&7").data(7).toItemStack(); + } + + @Override + public Map getButtons(Player player) { + Map map = new HashMap<>(); + Azurite instance = Azurite.getInstance(); + + map.put(11, new Button() { + @Override + public void onClick(InventoryClickEvent e) { + e.setCancelled(true); + new ProfileListMenu(player, ProfileType.KNOCKBACK).open(); + playClick(); + } + + @Override + public ItemStack getItemStack() { + return new ItemBuilder(Material.DIAMOND_SWORD) + .setName("&4Knockback Profiles") + .setLore("&eClick to edit knockback profiles.") + .hideAttributes() + .toItemStack(); + } + }); + + map.put(12, new Button() { + @Override + public void onClick(InventoryClickEvent e) { + e.setCancelled(true); + new ConfigEditMenu(player, instance.getPearlConfig()).open(); + playClick(); + } + + @Override + public ItemStack getItemStack() { + return new ItemBuilder(Material.ENDER_PEARL) + .setName("&5Enderpearl Config") + .setLore("&eClick to edit enderpearl config.") + .toItemStack(); + } + }); + + map.put(14, new Button() { + @Override + public void onClick(InventoryClickEvent e) { + e.setCancelled(true); + new ConfigEditMenu(player, instance.getAzuriteConfig()).open(); + playClick(); + } + + @Override + public ItemStack getItemStack() { + return new ItemBuilder(Material.BOOK) + .setName("&dMain Azurite Config") + .setLore("&eClick to edit the main azurite config.") + .toItemStack(); + } + }); + + map.put(16, new Button() { + @Override + public void onClick(InventoryClickEvent e) { + e.setCancelled(true); + new ConfigEditMenu(player, instance.getEnchantConfig()).open(); + playClick(); + } + + @Override + public ItemStack getItemStack() { + return new ItemBuilder(Material.ENCHANTMENT_TABLE) + .setName("&bEnchant Limit Config") + .setLore("&eClick to edit the enchants limit config.") + .toItemStack(); + } + }); + + map.put(17, new Button() { + @Override + public void onClick(InventoryClickEvent e) { + e.setCancelled(true); + new ProfileListMenu(player, ProfileType.GENERATOR).open(); + playClick(); + } + + @Override + public ItemStack getItemStack() { + return new ItemBuilder(Material.GRASS) + .setName("&aWorld Generator Profiles") + .setLore("&eClick to edit world generator profiles.") + .toItemStack(); + } + }); + + map.put(32, new Button() { + @Override + public void onClick(InventoryClickEvent e) { + e.setCancelled(true); + player.closeInventory(); + playClick(); + } + + @Override + public ItemStack getItemStack() { + return new ItemBuilder(Material.BED) + .setName("&cClose") + .toItemStack(); + } + }); + + return map; + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/menu/ProfileListMenu.java b/azurite-server/src/main/java/dev/azurite/spigot/menu/ProfileListMenu.java new file mode 100644 index 0000000..d2a0187 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/menu/ProfileListMenu.java @@ -0,0 +1,67 @@ +package dev.azurite.spigot.menu; + +import dev.azurite.spigot.framework.menu.button.Button; +import dev.azurite.spigot.framework.menu.paginated.PaginatedMenu; +import dev.azurite.spigot.menu.extra.ProfileType; +import dev.azurite.spigot.utils.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public class ProfileListMenu extends PaginatedMenu { + + private final ProfileType profileType; + + public ProfileListMenu(Player player, ProfileType profileType) { + super( + player, + profileType.getTitle(), + new MainAzuriteMenu(player), + 18, + true, + false + ); + this.profileType = profileType; + } + + @Override + public Map getButtons(Player player) { + Map map = new HashMap<>(); + List profiles = new ArrayList<>(); + int i = 1; + + profileType.addProfiles(profiles); + + for (String profile : profiles) { + map.put(i++, new Button() { + @Override + public void onClick(InventoryClickEvent e) { + e.setCancelled(true); + playClick(); + profileType.openEdit(player, profile, new ProfileListMenu(player, profileType)); + } + + @Override + public ItemStack getItemStack() { + return new ItemBuilder(Material.BOOK) + .setName(profileType.getColor() + profile) + .setLore("&eClick to edit this profile.") + .toItemStack(); + } + }); + } + + return map; + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/menu/extra/ProfileType.java b/azurite-server/src/main/java/dev/azurite/spigot/menu/extra/ProfileType.java new file mode 100644 index 0000000..2947e84 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/menu/extra/ProfileType.java @@ -0,0 +1,71 @@ +package dev.azurite.spigot.menu.extra; + +import dev.azurite.spigot.Azurite; +import dev.azurite.spigot.api.knockback.IKnockback; +import dev.azurite.spigot.framework.menu.Menu; +import dev.azurite.spigot.generator.Generator; +import dev.azurite.spigot.knockback.Knockback; +import dev.azurite.spigot.menu.ConfigEditMenu; +import org.bukkit.entity.Player; + +import java.util.List; +import java.util.stream.Collectors; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public enum ProfileType { + + KNOCKBACK("&dKnockback Profiles", "&4"), + GENERATOR("&dGenerator Profiles", "&a"); + + private final String title; + private final String color; + + ProfileType(String title, String color) { + this.title = title; + this.color = color; + } + + public String getTitle() { + return title; + } + + public String getColor() { + return color; + } + + public void openEdit(Player player, String string, Menu previous) { + switch (this) { + case KNOCKBACK: + IKnockback knockback = Azurite.getInstance().getKnockbackManager().getByName(string); + new ConfigEditMenu(player, (Knockback) knockback, previous, ((Knockback) knockback).getActiveSettings()).open(); + break; + + case GENERATOR: + Generator generator = Azurite.getInstance().getGeneratorManager().getOrCreate(string); + new ConfigEditMenu(player, generator, previous, generator.getSettings()).open(); + break; + } + } + + public void addProfiles(List list) { + switch (this) { + case GENERATOR: + list.addAll(Azurite.getInstance().getGeneratorManager().getGenerators().values() + .stream() + .map(Generator::getName) + .collect(Collectors.toList())); + break; + + case KNOCKBACK: + list.addAll(Azurite.getInstance().getKnockbackManager().getProfiles() + .stream() + .map(IKnockback::getName) + .collect(Collectors.toList())); + break; + } + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/optimizations/ChunkTickList.java b/azurite-server/src/main/java/dev/azurite/spigot/optimizations/ChunkTickList.java new file mode 100644 index 0000000..e51feb0 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/optimizations/ChunkTickList.java @@ -0,0 +1,94 @@ +package dev.azurite.spigot.optimizations; + +import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap; +import net.minecraft.server.Chunk; + +import java.util.Arrays; + +/** + * chunk list with O(1) remove & contains + fast iteration possible + * Modified to fit the needs of chunk tick list (based on ObjectMapList) + * + * @author Spottedleaf + * @author Beanes + */ +public final class ChunkTickList { + + private final Long2IntOpenHashMap objectToIndex; + + private static final Chunk[] EMPTY_LIST = new Chunk[0]; + private Chunk[] elements = EMPTY_LIST; + private int count; + + public ChunkTickList() { + this(1024, 0.8f); + } + + public ChunkTickList(int expectedSize, float loadFactor) { + this.objectToIndex = new Long2IntOpenHashMap(expectedSize, loadFactor); + this.objectToIndex.defaultReturnValue(Integer.MIN_VALUE); + } + + public int size() { + return this.count; + } + + public Chunk get(int index) { + return this.elements[index]; + } + + public boolean remove(Chunk chunk) { + return this.remove(chunk.chunkHashKey); + } + + public boolean remove(long hash) { + final int index = this.objectToIndex.remove(hash); + if (index == Integer.MIN_VALUE) { + return false; + } + + // move the obj at the end to this index + final int endIndex = --this.count; + final Chunk end = this.elements[endIndex]; + if (index != endIndex) { + // not empty after this call + this.objectToIndex.put(end.chunkHashKey, index); // update index + } + this.elements[index] = end; + this.elements[endIndex] = null; + return true; + } + + public boolean add(Chunk chunk) { + final int count = this.count; + final int currIndex = this.objectToIndex.putIfAbsent(chunk.chunkHashKey, count); + + if (currIndex != Integer.MIN_VALUE) { + return false; // already in this list + } + + Chunk[] list = this.elements; + if (list.length == count) { + // resize required + list = this.elements = Arrays.copyOf(list, (int) Math.max(4L, (long) count << 1)); // overflow results in negative + } + + list[count] = chunk; + this.count = count + 1; + return true; + } + + public boolean contains(Chunk chunk) { + return this.contains(chunk.chunkHashKey); + } + + public boolean contains(long hashKey) { + return this.objectToIndex.containsKey(hashKey); + } + + public void clear() { + this.objectToIndex.clear(); + Arrays.fill(this.elements, 0, this.count, null); + this.count = 0; + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/optimizations/ConstantRegistryID.java b/azurite-server/src/main/java/dev/azurite/spigot/optimizations/ConstantRegistryID.java new file mode 100644 index 0000000..355453d --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/optimizations/ConstantRegistryID.java @@ -0,0 +1,28 @@ +package dev.azurite.spigot.optimizations; + +import it.unimi.dsi.fastutil.objects.Reference2IntOpenHashMap; +import net.minecraft.server.IBlockData; +import net.minecraft.server.RegistryID; + +// Azurite - more efficient registry +public class ConstantRegistryID extends RegistryID { + private final Reference2IntOpenHashMap identityMap = new Reference2IntOpenHashMap<>(7806); // Azurite - more efficient registry + private final IBlockData[] objectList = new IBlockData[3164]; + + public void a(IBlockData key, int value) { + this.identityMap.put(key, value); + this.objectList[value] = key; + } + + public int b(IBlockData key) { + return this.identityMap.getOrDefault(key, -1); + } + + public IBlockData a(int value) { + return value >= 0 && value < 3164 ? this.objectList[value] : null; + } + + public IBlockData[] getAllStates() { + return objectList; + } +} diff --git a/azurite-server/src/main/java/dev/azurite/spigot/optimizations/EntityTrackerLinkedList.java b/azurite-server/src/main/java/dev/azurite/spigot/optimizations/EntityTrackerLinkedList.java new file mode 100644 index 0000000..aa321d8 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/optimizations/EntityTrackerLinkedList.java @@ -0,0 +1,23 @@ +package dev.azurite.spigot.optimizations; + +import net.minecraft.server.NetworkManager; +import net.minecraft.server.Packet; + +import java.util.LinkedList; + +public class EntityTrackerLinkedList extends LinkedList> { + + public final NetworkManager networkManager; + + public EntityTrackerLinkedList(NetworkManager networkManager) { + this.networkManager = networkManager; + } + + @Override + public boolean add(Packet o) { + if (!networkManager.shouldSend(o)) { + return false; + } + return super.add(o); + } +} diff --git a/azurite-server/src/main/java/dev/azurite/spigot/optimizations/FastActivationRange.java b/azurite-server/src/main/java/dev/azurite/spigot/optimizations/FastActivationRange.java new file mode 100644 index 0000000..9784cfe --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/optimizations/FastActivationRange.java @@ -0,0 +1,45 @@ +package dev.azurite.spigot.optimizations; + +import net.minecraft.server.Entity; +import net.minecraft.server.EntityPlayer; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.World; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public class FastActivationRange { + + /** + * Find what entities are in range of the players in the world and set + * active if in range. + * + * @param world world to activate in + */ + public static void activateEntities(World world) { + final int miscActivationRange = world.spigotConfig.miscActivationRange; + final int animalActivationRange = world.spigotConfig.animalActivationRange; + final int monsterActivationRange = world.spigotConfig.monsterActivationRange; + + // Azurite start - Full recode of activation range + for (Entity entity : world.entityList) { + // Entity is already activated. + if (MinecraftServer.currentTick < entity.activatedTick) continue; + + // Entities that are always activated + if (entity.defaultActivationState || entity instanceof EntityPlayer) { + entity.activatedTick = MinecraftServer.currentTick; + continue; + } + + int range = (entity.activationType == 1 ? monsterActivationRange : (entity.activationType == 2 ? animalActivationRange : miscActivationRange)); + + if (world.playerMap.shouldActivate(entity, range, true)) { + entity.activatedTick = MinecraftServer.currentTick; + } + } + // Azurite end + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/optimizations/FastAntiXray.java b/azurite-server/src/main/java/dev/azurite/spigot/optimizations/FastAntiXray.java new file mode 100644 index 0000000..ac477de --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/optimizations/FastAntiXray.java @@ -0,0 +1,327 @@ +package dev.azurite.spigot.optimizations; + +import it.unimi.dsi.fastutil.bytes.ByteOpenHashSet; +import it.unimi.dsi.fastutil.bytes.ByteSet; +import net.minecraft.server.*; +import org.spigotmc.SpigotWorldConfig; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import static net.minecraft.server.Blocks.*; +// TacoSpigot end + +public class FastAntiXray { + + // Used to keep track of which blocks to obfuscate + public final boolean[] obfuscateBlocks = new boolean[Short.MAX_VALUE]; + public final boolean[] occludingBlocks = new boolean[Short.MAX_VALUE]; + // Used to select a random replacement ore + public final byte[] replacementOres; + // PaperSpigot start + public boolean queueUpdates = true; + public final List pendingUpdates = new ArrayList<>(); + // PaperSpigot end + + public FastAntiXray(SpigotWorldConfig config) { + // Set all listed blocks as true to be obfuscated + Set configuratedBlocks = new HashSet<>(); + + for (int id : (config.engineMode == 1) ? config.hiddenBlocks : config.replaceBlocks) { + configuratedBlocks.add(Block.getById(id)); + } + + // Beanes - convert obfuscate blocks to their corresponding block states (also 7806 is the magic value of max block states) + IBlockData[] registry = ((ConstantRegistryID) Block.d).getAllStates(); + + for (int i = 0; i < registry.length; i++) { + IBlockData blockData = registry[i]; + + if (blockData != null) { + Block block = blockData.getBlock(); + occludingBlocks[i] = isSolidBlock(block); + + if (configuratedBlocks.contains(block)) { + obfuscateBlocks[i] = true; + } + } + } + + // For every block + ByteSet blocks = new ByteOpenHashSet(); + for (Integer i : config.hiddenBlocks) { + Block block = Block.getById(i); + // Check it exists and is not a tile entity + if (block != null && !block.isTileEntity()) { + // Add it to the set of replacement blocks + blocks.add((byte) (int) i); + } + } + // Bake it to a flat array of replacements + replacementOres = blocks.toByteArray(); + } + + // Beanes - occluding api + public boolean isOccluding(char block) { + return occludingBlocks[block]; + } + + /** + * PaperSpigot - Flush queued block updates for world. + */ + public void flushUpdates(World world) { + if (world.spigotConfig.antiXray && !pendingUpdates.isEmpty()) { + queueUpdates = false; + + for (BlockPosition position : pendingUpdates) { + updateNearbyBlocks(world, position); + } + + pendingUpdates.clear(); + queueUpdates = true; + } + } + + /** + * Starts the timings handler, then updates all blocks within the set radius + * of the given coordinate, revealing them if they are hidden ores. + */ + public void updateNearbyBlocks(World world, BlockPosition position) { + if (world.spigotConfig.antiXray) { + // PaperSpigot start + if (queueUpdates) { + pendingUpdates.add(position); + return; + } + // PaperSpigot end + updateNearbyBlocks(world, position.getX(), position.getY(), position.getZ()); // 2 is the radius, we shouldn't change it as that would make it exponentially slower + } + } + + private void updateNearbyBlocks(World world, int x, int y, int z) { + int startX = x - 2; + int endX = x + 2; + int startY = Math.max(0, y - 2); + int endY = Math.min(255, y + 2); + int startZ = z - 2; + int endZ = z + 2; + Chunk chunk = null; // Azurite - cache chunk + for (int x1 = startX; x1 <= endX; x1++) { + for (int y1 = startY; y1 <= endY; y1++) { + for (int z1 = startZ; z1 <= endZ; z1++) { + if (x1 == x & y1 == y & z1 == z) + continue; + + Chunk updating; + int chunkX = x1 >> 4; + int chunkZ = z1 >> 4; + + // Most of the time we'll be updating in the same chunk + if (chunk != null && chunk.locX == chunkX && chunk.locZ == chunkZ) { + updating = chunk; + + } else { + // If we went outside the chunk fetch and cache + updating = world.getChunkIfLoaded(chunkX, chunkZ); + chunk = updating; + } + + updateBlock(updating, world, x1, y1, z1); + } + } + } + } + + private void updateBlock(Chunk chunk, World world, int x, int y, int z) { + // Beanes - make this use block state + if (chunk == null) return; + int sectionId = y >> 4; + if (sectionId < 0 || sectionId > 15) return; + ChunkSection section = chunk.getSections()[sectionId]; + if (section == null) return; + + int index = ((y & 0xF) << 8) | ((z & 0xF) << 4) | (x & 0xF); + + if (obfuscateBlocks[section.getIdArray()[index]]) { + world.notify(x, y, z); + } + } + + private static boolean isSolidBlock(Block block) { + // Mob spawners are treated as solid blocks as far as the + // game is concerned for lighting and other tasks but for + // rendering they can be seen through therefor we special + // case them so that the antixray doesn't show the fake + // blocks around them. + return block.isOccluding() && block != Blocks.MOB_SPAWNER && block != Blocks.BARRIER; + } + + private static final char STONE_STATE = (char) Block.d.b(STONE.getBlockData()); + private static final char NETHER_RACK_STATE = (char) Block.d.b(NETHERRACK.getBlockData()); + private static final char END_STONE_STATE = (char) Block.d.b(END_STONE.getBlockData()); + + public char getReplaceId(org.bukkit.World.Environment environment) { + switch (environment) { + case NETHER: + return NETHER_RACK_STATE; + case THE_END: + return END_STONE_STATE; + } + + return STONE_STATE; + } + + public char getReplacedIdEngine1(Chunk chunk, ChunkSection section, ChunkSection[] sending, char blockId, int k, int bitmask, int i, int totalSections) { + World world = chunk.world; + int x = k & 15; + int y = k >> 8 & 15; + int z = k >> 4 & 15; + + int posX = x + 1; + int negX = x - 1; + int posY = y + 1; + int negY = y - 1; + int posZ = z + 1; + int negZ = z - 1; + + // Checks Y visibility + if (posY > 15 && i + 1 < totalSections) { + ChunkSection upperSection = sending[i + 1]; + + if (bitmask != '\uffff' || upperSection == null) { + return blockId; + } + + int newIndex = (k & 0b000011111111); // Make Y 0 and keep X and Z + + if (!isOccluding(upperSection.getBlockId(newIndex))) { + return blockId; + } + } else if (posY <= 15) { + int newIndex = (k & 0b000011111111) | (posY << 8); + if (!isOccluding(section.getBlockId(newIndex))) { + return blockId; + } + } + + if (negY < 0 && i - 1 >= 0) { + ChunkSection upperSection = sending[i - 1]; + + if (bitmask != '\uffff' || upperSection == null) { + return blockId; + } + + int newIndex = (k & 0b000011111111 | 0b111100000000); // Keep X and Z and make Y 15 + if (!isOccluding(upperSection.getBlockId(newIndex))) { + return blockId; + } + } else if (negY >= 0) { + int newIndex = (k & 0b000011111111) | (negY << 8); + if (!isOccluding(section.getBlockId(newIndex))) { + return blockId; + } + } + + // Checks X visibility + if (posX > 15) { + Chunk neighbourChunk = world.getChunkIfLoaded(chunk.locX + 1, chunk.locZ); + + if (neighbourChunk == null) { + return blockId; + } + + ChunkSection neighbourSection = neighbourChunk.getSection(section.getYPosition()); + + if (neighbourSection == null) { + return blockId; + } + + int newIndex = (k & 0b111111110000); // Make X 0 and keep Y and Z + if (!isOccluding(neighbourSection.getBlockId(newIndex))) { + return blockId; + } + } else { + int newIndex = (k & 0b111111110000) | posX; + if (!isOccluding(section.getBlockId(newIndex))) { + return blockId; + } + } + + if (negX < 0) { + Chunk neighbourChunk = world.getChunkIfLoaded(chunk.locX - 1, chunk.locZ); + + if (neighbourChunk == null) { + return blockId; + } + + ChunkSection neighbourSection = neighbourChunk.getSection(section.getYPosition()); + + if (neighbourSection == null) { + return blockId; + } + + int newIndex = (k & 0b111111110000 | 0b000000001111); // Keep Y and Z and make X 15 + if (!isOccluding(neighbourSection.getBlockId(newIndex))) { + return blockId; + } + } else { + int newIndex = (k & 0b111111110000) | negX; + if (!isOccluding(section.getBlockId(newIndex))) { + return blockId; + } + } + + // Checks Z visibility + if (posZ > 15) { + Chunk neighbourChunk = world.getChunkIfLoaded(chunk.locX, chunk.locZ + 1); + + if (neighbourChunk == null) { + return blockId; + } + + ChunkSection neighbourSection = neighbourChunk.getSection(section.getYPosition()); + + if (neighbourSection == null) { + return blockId; + } + + int newIndex = (k & 0b111100001111); // Make Z 0 and keep X and Y + if (!isOccluding(neighbourSection.getBlockId(newIndex))) { + return blockId; + } + } else { + int newIndex = (k & 0b111100001111) | (posZ << 4); + if (!isOccluding(section.getBlockId(newIndex))) { + return blockId; + } + } + + if (negZ < 0) { + Chunk neighbourChunk = world.getChunkIfLoaded(chunk.locX, chunk.locZ - 1); + + if (neighbourChunk == null) { + return blockId; + } + + ChunkSection neighbourSection = neighbourChunk.getSection(section.getYPosition()); + + if (neighbourSection == null) { + return blockId; + } + + int newIndex = (k & 0b111100001111 | 0b000011110000); // Keep Y and X and make X 15 + if (!isOccluding(neighbourSection.getBlockId(newIndex))) { + return blockId; + } + } else { + int newIndex = (k & 0b111100001111) | (negZ << 4); + if (!isOccluding(section.getBlockId(newIndex))) { + return blockId; + } + } + + return getReplaceId(world.getWorld().getEnvironment()); + } +} diff --git a/azurite-server/src/main/java/dev/azurite/spigot/optimizations/FastEnumProtocol.java b/azurite-server/src/main/java/dev/azurite/spigot/optimizations/FastEnumProtocol.java new file mode 100644 index 0000000..e3067e2 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/optimizations/FastEnumProtocol.java @@ -0,0 +1,14 @@ +package dev.azurite.spigot.optimizations; + +import net.minecraft.server.Packet; + +import java.util.function.Supplier; + +public class FastEnumProtocol { + + public final Supplier>[] suppliers; + + public FastEnumProtocol(Supplier>[] suppliers) { + this.suppliers = suppliers; + } +} diff --git a/azurite-server/src/main/java/dev/azurite/spigot/optimizations/FastNetworkManager.java b/azurite-server/src/main/java/dev/azurite/spigot/optimizations/FastNetworkManager.java new file mode 100644 index 0000000..d586a69 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/optimizations/FastNetworkManager.java @@ -0,0 +1,70 @@ +package dev.azurite.spigot.optimizations; + +import dev.azurite.spigot.utils.NonWakeupNettyRunnable; +import io.netty.channel.Channel; +import io.netty.channel.ChannelFuture; +import io.netty.channel.ChannelFutureListener; +import net.minecraft.server.NetworkManager; +import net.minecraft.server.Packet; + +import java.util.List; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +@SuppressWarnings("unchecked") +public class FastNetworkManager { + + // Azurite start - Lazily write/queue entity tracker updates + public final EntityTrackerLinkedList[] trackerQueue = new EntityTrackerLinkedList[4]; + + public FastNetworkManager(NetworkManager networkManager) { + // Create queues when init + for (int i = 0; i < 4; i++) { + trackerQueue[i] = new EntityTrackerLinkedList(networkManager); + } + } + + public void writePacketLazily(Channel channel, Packet packet) { + if (channel != null && channel.isActive()) { + channel.eventLoop().execute( + new NonWakeupNettyRunnable(() -> channel.write(packet).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE)) + ); + } + } + + public void flushAndWriteCurrentQueue(Channel channel) { + if (channel != null && channel.isActive()) { + // Tracker queue + List>[] writingTrackerQueues = new List[4]; + + for (int i = 0; i < trackerQueue.length; i++) { + EntityTrackerLinkedList packets = trackerQueue[i]; + writingTrackerQueues[i] = packets; // Copy list + trackerQueue[i] = new EntityTrackerLinkedList(packets.networkManager); + } + + // Write cloned & flush + channel.eventLoop().execute(() -> { + // Tracker packets + for (List> writingTrackerQueue : writingTrackerQueues) { + for (Packet packet : writingTrackerQueue) { + ChannelFuture future = channel.write(packet); + future.addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE); + } + } + + // Flush packets + channel.flush(); + // No longer needed + for (int i = 0; i < writingTrackerQueues.length; i++) { + writingTrackerQueues[i].clear(); + writingTrackerQueues[i] = null; + } + }); + } + } + // Azurite end +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/optimizations/ModernHopperOptimizations.java b/azurite-server/src/main/java/dev/azurite/spigot/optimizations/ModernHopperOptimizations.java new file mode 100644 index 0000000..455be05 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/optimizations/ModernHopperOptimizations.java @@ -0,0 +1,169 @@ +package dev.azurite.spigot.optimizations; + +import net.minecraft.server.*; +import org.bukkit.Bukkit; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.event.inventory.InventoryMoveItemEvent; +import org.bukkit.inventory.Inventory; + +public class ModernHopperOptimizations { + // Paper start - Optimize Hoppers + public static boolean skipPullModeEventFire = false; + public static boolean skipPushModeEventFire = false; + public static boolean skipHopperEvents = false; + + public static boolean hopperPush(TileEntityHopper hopper, IInventory iinventory, EnumDirection enumdirection) { + skipPushModeEventFire = skipHopperEvents; + boolean foundItem = false; + for (int i = 0; i < hopper.getSize(); ++i) { + ItemStack item = hopper.getItem(i); + if (item != null && item.count > 0) { + foundItem = true; + ItemStack origItemStack = item; + ItemStack itemstack = origItemStack; + + final int origCount = origItemStack.count; + final int moved = Math.min(hopper.getWorld().spigotConfig.hopperAmount, origCount); + origItemStack.count = (moved); + + // We only need to fire the event once to give protection plugins a chance to cancel this event + // Because nothing uses getItem, every event call should end up the same result. + if (!skipPushModeEventFire) { + itemstack = callPushMoveEvent(hopper, iinventory, itemstack); + if (itemstack == null) { // cancelled + origItemStack.count = (origCount); + return false; + } + } + final ItemStack itemstack2 = TileEntityHopper.addItem(iinventory, itemstack, enumdirection); + final int remaining = itemstack2 == null ? 0 : itemstack2.count; + if (remaining != moved) { + origItemStack = origItemStack.cloneItemStack(); + origItemStack.count = origCount - moved + remaining; + + if (origItemStack.count <= 0) origItemStack = null; + + hopper.setItem(i, origItemStack); + iinventory.update(); + return true; + } + origItemStack.count = (origCount); + } + } + + if (foundItem) { + hopper.d(hopper.getWorld().spigotConfig.hopperTransfer); + } + + return false; + } + + public static boolean hopperPull(IHopper ihopper, IInventory iinventory, ItemStack origItemStack, int i) { + ItemStack itemstack = origItemStack; + final int origCount = origItemStack == null ? 0 : origItemStack.count; + final World world = ihopper.getWorld(); + final int moved = Math.min(world.spigotConfig.hopperAmount, origCount); + if (itemstack != null) { + itemstack.count = moved; + if (itemstack.count <= 0) itemstack = null; + } + + if (!skipPullModeEventFire) { + itemstack = callPullMoveEvent(ihopper, iinventory, itemstack); + if (itemstack == null) { // cancelled + if (origItemStack != null) origItemStack.count = origCount; + // Drastically improve performance by returning true. + // No plugin could of relied on the behavior of false as the other call + // site for IMIE did not exhibit the same behavior + return true; + } + } + + final ItemStack itemstack2 = TileEntityHopper.addItem(ihopper, itemstack, null); + final int remaining = itemstack2 == null ? 0 : itemstack2.count; + if (origItemStack != null && remaining != moved) { + origItemStack = origItemStack.cloneItemStack(); + origItemStack.count = origCount; + if (origItemStack.count <= 0) origItemStack = null; + + if (origItemStack != null) { + origItemStack.count = origCount - moved + remaining; + if (origItemStack.count <= 0) origItemStack = null; + } + + TileEntityHopper.IGNORE_TILE_UPDATES = true; + iinventory.setItem(i, origItemStack); + TileEntityHopper.IGNORE_TILE_UPDATES = false; + iinventory.update(); + return true; + } + + if (origItemStack != null) { + origItemStack.count = origCount; + } + + cooldownHopper(ihopper); // Cooldown when full + + return false; + } + + private static ItemStack callPushMoveEvent(TileEntityHopper hopper, IInventory iinventory, ItemStack itemstack) { + Inventory destinationInventory = getInventory(iinventory); + InventoryMoveItemEvent event = new InventoryMoveItemEvent(hopper.getOwner().getInventory(), + CraftItemStack.asCraftMirror(itemstack), destinationInventory, true); + boolean result = event.callEvent(); + if (!event.calledGetItem && !event.calledSetItem) { + skipPushModeEventFire = true; + } + if (!result) { + cooldownHopper(hopper); + return null; + } + + if (event.calledSetItem) { + return CraftItemStack.asNMSCopy(event.getItem()); + } else { + return itemstack; + } + } + + private static ItemStack callPullMoveEvent(IHopper hopper, IInventory iinventory, ItemStack itemstack) { + Inventory sourceInventory = getInventory(iinventory); + Inventory destination = getInventory(hopper); + + InventoryMoveItemEvent event = new InventoryMoveItemEvent(sourceInventory, + // Mirror is safe as we no plugins ever use this item + CraftItemStack.asCraftMirror(itemstack), destination, false); + boolean result = event.callEvent(); + if (!event.calledGetItem && !event.calledSetItem) { + skipPullModeEventFire = true; + } + if (!result) { + cooldownHopper(hopper); + return null; + } + + if (event.calledSetItem) { + return CraftItemStack.asNMSCopy(event.getItem()); + } else { + return itemstack; + } + } + + public static Inventory getInventory(IInventory iinventory) { + if (iinventory instanceof InventoryLargeChest) { + return new org.bukkit.craftbukkit.inventory.CraftInventoryDoubleChest((InventoryLargeChest) iinventory); + } + return iinventory.getOwner().getInventory(); + } + + private static void cooldownHopper(IHopper hopper) { + if (hopper instanceof TileEntityHopper) { + ((TileEntityHopper) hopper).d(hopper.getWorld().spigotConfig.hopperTransfer); + } else if (hopper instanceof EntityMinecartHopper) { + ((EntityMinecartHopper) hopper).m(hopper.getWorld().spigotConfig.hopperTransfer / 2); + } + } + + // Paper end +} diff --git a/azurite-server/src/main/java/dev/azurite/spigot/optimizations/ObjectMapList.java b/azurite-server/src/main/java/dev/azurite/spigot/optimizations/ObjectMapList.java new file mode 100644 index 0000000..81040f2 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/optimizations/ObjectMapList.java @@ -0,0 +1,223 @@ +package dev.azurite.spigot.optimizations; + +import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap; +import it.unimi.dsi.fastutil.objects.AbstractReferenceList; +import it.unimi.dsi.fastutil.objects.ObjectListIterator; +import it.unimi.dsi.fastutil.objects.ObjectSpliterator; +import org.jetbrains.annotations.NotNull; + +import java.lang.reflect.Array; +import java.util.Arrays; +import java.util.NoSuchElementException; +import java.util.Set; + +/** + * list with O(1) remove & contains + * + * @author Spottedleaf + */ +@SuppressWarnings("unchecked") +public final class ObjectMapList extends AbstractReferenceList implements Set { + + private final Int2IntOpenHashMap objectToIndex; + public T[] elements; + public int count; + + public ObjectMapList(Class clazz) { + this(clazz, 2, 0.8f); + } + + public ObjectMapList(Class clazz, int expectedSize) { + this(clazz, expectedSize, 0.8f); + } + + public ObjectMapList(Class clazz, int expectedSize, float loadFactor) { + this.objectToIndex = new Int2IntOpenHashMap(expectedSize, loadFactor); + this.objectToIndex.defaultReturnValue(Integer.MIN_VALUE); + this.elements = (T[]) Array.newInstance(clazz, expectedSize); + } + + @Override + public int size() { + return this.count; + } + + @Override + public int indexOf(Object object) { + return this.objectToIndex.get(object.hashCode()); + } + + @Override + public int lastIndexOf(Object object) { + return super.indexOf(object); + } + + @Override + public boolean remove(final Object object) { + final int index = this.objectToIndex.remove(object.hashCode()); + if (index == Integer.MIN_VALUE) { + return false; + } + + // move the obj at the end to this index + final int endIndex = --this.count; + final T end = this.elements[endIndex]; + if (index != endIndex) { + // not empty after this call + this.objectToIndex.put(end.hashCode(), index); // update index + } + this.elements[index] = end; + this.elements[endIndex] = null; + return true; + } + + @Override + public T remove(final int index) { + T obj = this.elements[index]; + + this.objectToIndex.remove(obj.hashCode()); + + // move the obj at the end to this index + final int endIndex = --this.count; + final T end = this.elements[endIndex]; + if (index != endIndex) { + // not empty after this call + this.objectToIndex.put(end.hashCode(), index); // update index + } + this.elements[index] = end; + this.elements[endIndex] = null; + + return obj; + } + + @Override + public boolean add(final T object) { + final int count = this.count; + final int currIndex = this.objectToIndex.putIfAbsent(object.hashCode(), count); + + if (currIndex != Integer.MIN_VALUE) { + return false; // already in this list + } + + T[] list = this.elements; + if (list.length == count) { + // resize required + list = this.elements = Arrays.copyOf(list, (int) Math.max(4L, (long) count << 1)); // overflow results in negative + } + + list[count] = object; + this.count = count + 1; + return true; + } + + @Override + public void add(final int index, final T object) { + final int currIndex = this.objectToIndex.putIfAbsent(object.hashCode(), index); + + if (currIndex != Integer.MIN_VALUE) { + return; // already in this list + } + + int count = this.count; + T[] list = this.elements; + if (list.length == count) { + // resize required + list = this.elements = Arrays.copyOf(list, (int) Math.max(4L, (long) count << 1)); // overflow results in negative + } + + System.arraycopy(list, index, list, index + 1, count - index); + list[index] = object; + this.count = count + 1; + } + + @Override + public T get(int index) { + return this.elements[index]; + } + + @Override + public boolean isEmpty() { + return this.count == 0; + } + + @Override + public void clear() { + this.objectToIndex.clear(); + Arrays.fill(this.elements, 0, this.count, null); + this.count = 0; + } + + @Override + public Object @NotNull [] toArray() { + return Arrays.copyOf(this.elements, this.count); + } + + @Override + public @NotNull ObjectSpliterator spliterator() { + return super.spliterator(); + } + + @Override + public @NotNull ObjectListIterator iterator() { + return new Iterator(0); + } + + private class Iterator implements ObjectListIterator { + + T lastRet; + int current; + + Iterator(int index) { + current = index; + } + + @Override + public int nextIndex() { + return this.current + 1; + } + + @Override + public int previousIndex() { + return this.current - 1; + } + + @Override + public boolean hasNext() { + return this.current < ObjectMapList.this.count; + } + + @Override + public boolean hasPrevious() { + return this.current > 0; + } + + @Override + public T next() { + if (this.current >= ObjectMapList.this.count) { + throw new NoSuchElementException(); + } + return this.lastRet = ObjectMapList.this.elements[this.current++]; + } + + @Override + public T previous() { + if (this.current < 0) { + throw new NoSuchElementException(); + } + return this.lastRet = ObjectMapList.this.elements[--this.current]; + } + + @Override + public void remove() { + final T lastRet = this.lastRet; + + if (lastRet == null) { + throw new IllegalStateException(); + } + this.lastRet = null; + + ObjectMapList.this.remove(lastRet); + --this.current; + } + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/optimizations/OptimizedNonEmptyList.java b/azurite-server/src/main/java/dev/azurite/spigot/optimizations/OptimizedNonEmptyList.java new file mode 100644 index 0000000..e7438b7 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/optimizations/OptimizedNonEmptyList.java @@ -0,0 +1,135 @@ +package dev.azurite.spigot.optimizations; + +import org.jetbrains.annotations.NotNull; + +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; + +public class OptimizedNonEmptyList implements List { + private boolean isEmpty = true; + @Override + public int size() { + return isEmpty ? 0 : 1; + } + + @Override + public boolean isEmpty() { + return isEmpty; + } + + @Override + public boolean contains(Object o) { + throw new IllegalStateException(); + } + + @NotNull + @Override + public Iterator iterator() { + throw new IllegalStateException(); + } + + @NotNull + @Override + public Object @NotNull [] toArray() { + throw new IllegalStateException(); + } + + @Override + public boolean add(Object object) { + isEmpty = false; + return true; + } + + @Override + public boolean remove(Object o) { + throw new IllegalStateException(); + } + + @Override + public boolean addAll(@NotNull Collection c) { + isEmpty = false; + return true; + } + + @Override + public boolean addAll(int index, @NotNull Collection c) { + isEmpty = false; + return true; + } + + @Override + public void clear() { + isEmpty = true; + } + + @Override + public T get(int index) { + throw new IllegalStateException(); + } + + @Override + public T set(int index, Object element) { + throw new IllegalStateException(); + } + + @Override + public void add(int index, Object element) { + throw new IllegalStateException(); + } + + @Override + public T remove(int index) { + throw new IllegalStateException(); + } + + @Override + public int indexOf(Object o) { + throw new IllegalStateException(); + } + + @Override + public int lastIndexOf(Object o) { + throw new IllegalStateException(); + } + + @NotNull + @Override + public ListIterator listIterator() { + throw new IllegalStateException(); + } + + @NotNull + @Override + public ListIterator listIterator(int index) { + throw new IllegalStateException(); + } + + @NotNull + @Override + public List subList(int fromIndex, int toIndex) { + throw new IllegalStateException(); + } + + @Override + public boolean retainAll(@NotNull Collection c) { + throw new IllegalStateException(); + } + + @Override + public boolean removeAll(@NotNull Collection c) { + throw new IllegalStateException(); + } + + @Override + public boolean containsAll(@NotNull Collection c) { + throw new IllegalStateException(); + } + + @NotNull + @Override + public Object[] toArray(@NotNull Object[] a) { + throw new IllegalStateException(); + } +} diff --git a/azurite-server/src/main/java/dev/azurite/spigot/optimizations/PlayerMap.java b/azurite-server/src/main/java/dev/azurite/spigot/optimizations/PlayerMap.java new file mode 100644 index 0000000..992b4d1 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/optimizations/PlayerMap.java @@ -0,0 +1,291 @@ +package dev.azurite.spigot.optimizations; + +import com.google.common.base.Function; +import com.google.common.base.Predicate; +import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; +import net.minecraft.server.*; + +import java.util.Collections; +import java.util.List; +import java.util.function.Consumer; + +public class PlayerMap { + + public static final int CHUNK_BITS = 5; + public final Long2ObjectOpenHashMap> map = new Long2ObjectOpenHashMap<>(); + public static long xzToKey(long x, long z) { + return (x << 32) + z - Integer.MIN_VALUE; + } + + public void add(EntityPlayer player) { + int x = MathHelper.floor(player.locX) >> CHUNK_BITS; + int z = MathHelper.floor(player.locZ) >> CHUNK_BITS; + long key = xzToKey(x, z); + ObjectMapList list = map.get(key); + if (list == null) { + list = new ObjectMapList<>(EntityPlayer.class); + map.put(key, list); + } + list.add(player); + player.playerMapX = x; + player.playerMapZ = z; + } + + public void move(EntityPlayer player) { + int x = MathHelper.floor(player.locX) >> CHUNK_BITS; + int z = MathHelper.floor(player.locZ) >> CHUNK_BITS; + + // did we move? + if (x == player.playerMapX && z == player.playerMapZ) { + return; + } + + // do remove + long key = xzToKey(player.playerMapX, player.playerMapZ); + ObjectMapList list = map.get(key); + if (list != null) { + list.remove(player); + if (list.isEmpty()) { + map.remove(key); + } + } + + // do add + key = xzToKey(x, z); + list = map.get(key); + if (list == null) { + list = new ObjectMapList<>(EntityPlayer.class); + map.put(key, list); + } + list.add(player); + player.playerMapX = x; + player.playerMapZ = z; + } + + public void remove(EntityPlayer player) { + long key = xzToKey(player.playerMapX, player.playerMapZ); + List list = map.get(key); + if (list == null) { + // player has not yet been added to this playermap, this happens when teleporting to another world during PlayerJoinEvent + return; + } + list.remove(player); + if (list.isEmpty()) { + map.remove(key); + } + } + + public void forEachNearby(double x, double y, double z, double distance, boolean useRadius, Consumer function) { + for (int chunkX = MathHelper.floor(x - distance) >> CHUNK_BITS; chunkX <= MathHelper.floor(x + distance) >> CHUNK_BITS; chunkX++) { + for (int chunkZ = MathHelper.floor(z - distance) >> CHUNK_BITS; chunkZ <= MathHelper.floor(z + distance) >> CHUNK_BITS; chunkZ++) { + List players = map.get(xzToKey(chunkX, chunkZ)); + + if (players != null) { + for (EntityPlayer player : players) { + if (!useRadius || player.e(x, y, z) < distance * distance) { + function.accept(player); + } + } + } + } + } + } + + public EntityPlayer getNearestPlayer(double x, double y, double z, double distance) { + double bestDistanceSqrd = -1.0; + EntityPlayer bestPlayer = null; + + for (int chunkX = MathHelper.floor(x - distance) >> CHUNK_BITS; chunkX <= MathHelper.floor(x + distance) >> CHUNK_BITS; chunkX++) { + for (int chunkZ = MathHelper.floor(z - distance) >> CHUNK_BITS; chunkZ <= MathHelper.floor(z + distance) >> CHUNK_BITS; chunkZ++) { + List players = map.get(xzToKey(chunkX, chunkZ)); + if (players != null) { + for (EntityPlayer player : players) { + double playerDistSqrd = player.e(x, y, z); + if (playerDistSqrd < distance * distance && (bestDistanceSqrd == -1.0 || playerDistSqrd < bestDistanceSqrd)) { + bestDistanceSqrd = playerDistSqrd; + bestPlayer = player; + } + } + } + } + } + return bestPlayer; + } + + public boolean isPlayerNearby(double x, double y, double z, double distance, boolean respectSpawningApi) { + for (int chunkX = MathHelper.floor(x - distance) >> CHUNK_BITS; chunkX <= MathHelper.floor(x + distance) >> CHUNK_BITS; chunkX++) { + for (int chunkZ = MathHelper.floor(z - distance) >> CHUNK_BITS; chunkZ <= MathHelper.floor(z + distance) >> CHUNK_BITS; chunkZ++) { + List players = map.get(xzToKey(chunkX, chunkZ)); + if (players != null) { + for (EntityPlayer player : players) { + if (player != null && !player.dead && (!respectSpawningApi || player.affectsSpawning)) { + double playerDistSqrd = player.e(x, y, z); + if (playerDistSqrd < distance * distance) { + return true; + } + } + } + } + } + } + return false; + } + + public EntityPlayer getNearbyPlayer(double x, double y, double z, double distance, boolean respectSpawningApi) { + return getNearbyPlayer(x, y, z, distance, respectSpawningApi, true); + } + + public EntityPlayer getNearbyPlayer(double x, double y, double z, double distance, boolean respectSpawningApi, boolean best) { + double bestDistanceSqrd = -1.0; + EntityPlayer bestPlayer = null; + + for (int chunkX = MathHelper.floor(x - distance) >> CHUNK_BITS; chunkX <= MathHelper.floor(x + distance) >> CHUNK_BITS; chunkX++) { + for (int chunkZ = MathHelper.floor(z - distance) >> CHUNK_BITS; chunkZ <= MathHelper.floor(z + distance) >> CHUNK_BITS; chunkZ++) { + List players = map.get(xzToKey(chunkX, chunkZ)); + if (players != null) { + for (EntityPlayer player : players) { + if (player != null && !player.dead && (!respectSpawningApi || player.affectsSpawning)) { + double playerDistSqrd = player.e(x, y, z); + if (playerDistSqrd < distance * distance && (bestDistanceSqrd == -1.0 || playerDistSqrd < bestDistanceSqrd)) { + bestDistanceSqrd = playerDistSqrd; + if (!best) return player; + bestPlayer = player; + } + } + } + } + } + } + + return bestPlayer; + } + + public boolean shouldActivate(Entity entity, double distance, boolean respectSpawningApi) { + double entityX = entity.locX; + double entityY = entity.locY; + double entityZ = entity.locZ; + + for (int chunkX = MathHelper.floor(entityX - distance) >> CHUNK_BITS; chunkX <= MathHelper.floor(entityX + distance) >> CHUNK_BITS; chunkX++) { + for (int chunkZ = MathHelper.floor(entityZ - distance) >> CHUNK_BITS; chunkZ <= MathHelper.floor(entityZ + distance) >> CHUNK_BITS; chunkZ++) { + List players = map.get(xzToKey(chunkX, chunkZ)); + + if (players == null) continue; + + for (EntityPlayer player : players) { + if (player != null && !player.dead && (!respectSpawningApi || player.affectsSpawning)) { + double playerX1 = player.locX - distance; + double playerY1 = player.locY - distance; + double playerZ1 = player.locZ - distance; + + double playerX2 = player.locX + distance; + double playerY2 = player.locY + distance; + double playerZ2 = player.locZ + distance; + + // Bounding box + if (entityX >= playerX1 && entityY >= playerY1 && entityZ >= playerZ1 && entityX <= playerX2 && entityY <= playerY2 && entityZ <= playerZ2) { + return true; + } + } + } + } + } + return false; + } + + public List getNearbyPlayersIgnoreHeight(double x, double z, double distance) { + List toReturn = null; + + for (int chunkX = MathHelper.floor(x - distance) >> CHUNK_BITS; chunkX <= MathHelper.floor(x + distance) >> CHUNK_BITS; chunkX++) { + for (int chunkZ = MathHelper.floor(z - distance) >> CHUNK_BITS; chunkZ <= MathHelper.floor(z + distance) >> CHUNK_BITS; chunkZ++) { + List players = map.get(xzToKey(chunkX, chunkZ)); + if (players != null) { + for (EntityPlayer player : players) { + if (player != null && !player.dead && Math.abs(player.locX - x) <= distance && Math.abs(player.locZ - z) <= distance) { + if (toReturn == null) { + toReturn = new ObjectMapList<>(EntityPlayer.class); + } + toReturn.add(player); + } + } + } + } + } + + return toReturn == null ? Collections.emptyList() : toReturn; + } + + public EntityPlayer getNearestAttackablePlayer(double x, double y, double z, double maxXZ, double maxY, Function visibility) { + return getNearestAttackablePlayer(x, y, z, maxXZ, maxY, visibility, null); + } + + public EntityPlayer getNearestAttackablePlayer(double x, double y, double z, double maxXZ, double maxY, Function visibility, Predicate condition) { + double bestDistanceSqrd = -1.0; + EntityPlayer bestPlayer = null; + + for (int chunkX = MathHelper.floor(x - maxXZ) >> CHUNK_BITS; chunkX <= MathHelper.floor(x + maxXZ) >> CHUNK_BITS; chunkX++) { + for (int chunkZ = MathHelper.floor(z - maxXZ) >> CHUNK_BITS; chunkZ <= MathHelper.floor(z + maxXZ) >> CHUNK_BITS; chunkZ++) { + List players = map.get(xzToKey(chunkX, chunkZ)); + if (players != null) { + for (EntityPlayer player : players) { + if (!player.abilities.isInvulnerable && player.isAlive() && (condition == null || condition.apply(player))) { + double dx = player.locX - x; + double dz = player.locZ - z; + double playerDistSqrd = dx * dx + dz * dz; + double dy = Math.abs(player.locY - y); + double distForPlayer = maxXZ; + + if (player.isSneaking()) { + distForPlayer *= 0.8; + } + + if (visibility != null) { + Double v = visibility.apply(player); + if (v != null) { + distForPlayer *= v; + } + } + + // mojang mistake squaring maxY? + if ((maxY < 0.0 || dy < maxY * maxY) && playerDistSqrd < distForPlayer * distForPlayer && (bestDistanceSqrd == -1.0 || playerDistSqrd < bestDistanceSqrd)) { + bestDistanceSqrd = playerDistSqrd; + bestPlayer = player; + } + } + } + } + } + } + + return bestPlayer; + } + + public void sendPacketNearby(EntityPlayer source, double x, double y, double z, double distance, Packet packet) { + this.sendPacketNearby(source, x, y, z, distance, packet, false); + } + + public void sendPacketNearby(EntityPlayer source, double x, double y, double z, double distance, Packet packet, boolean self) { + for (int chunkX = MathHelper.floor(x - distance) >> CHUNK_BITS; chunkX <= MathHelper.floor(x + distance) >> CHUNK_BITS; chunkX++) { + for (int chunkZ = MathHelper.floor(z - distance) >> CHUNK_BITS; chunkZ <= MathHelper.floor(z + distance) >> CHUNK_BITS; chunkZ++) { + List players = map.get(xzToKey(chunkX, chunkZ)); + if (players != null) { + for (EntityPlayer player : players) { + // don't send self + if (!self && player == source) { + continue; + } + + // bukkit visibility api + if (source != null && !player.getBukkitEntity().canSee(source.getBukkitEntity())) { + continue; + } + + double playerDistSqrd = player.e(x, y, z); + if (playerDistSqrd < distance * distance) { + player.playerConnection.sendPacket(packet); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/optimizations/ProtocolUtils.java b/azurite-server/src/main/java/dev/azurite/spigot/optimizations/ProtocolUtils.java new file mode 100644 index 0000000..76ca141 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/optimizations/ProtocolUtils.java @@ -0,0 +1,222 @@ +// Original source: velocity +package dev.azurite.spigot.optimizations; + +import dev.azurite.spigot.utils.CountingDataOutput; +import io.netty.buffer.ByteBuf; +import io.netty.handler.codec.CorruptedFrameException; +import io.netty.handler.codec.EncoderException; +import net.minecraft.server.*; +import org.bukkit.craftbukkit.inventory.CraftItemStack; + +import java.io.IOException; +import java.util.Collection; +import java.util.List; + +public class ProtocolUtils { + private static final int MAXIMUM_VARINT_SIZE = 5; + private static final int[] VAR_INT_LENGTHS = new int[65]; + + static { + for (int i = 0; i <= 32; ++i) { + VAR_INT_LENGTHS[i] = (int) Math.ceil((31d - (i - 1)) / 7d); + } + VAR_INT_LENGTHS[32] = 1; // Special case for the number 0. + } + + + /** + * Reads a Minecraft-style VarInt from the specified {@code buf}. + * + * @param buf the buffer to read from + * @return the decoded VarInt + */ + public static int readVarInt(ByteBuf buf) { + int readable = buf.readableBytes(); + if (readable == 0) { + // special case for empty buffer + throw new CorruptedFrameException("VarInt not readable"); + } + + // we can read at least one byte, and this should be a common case + int k = buf.readByte(); + if ((k & 0x80) != 128) { + return k; + } + + // in case decoding one byte was not enough, use a loop to decode up to the next 4 bytes + int maxRead = Math.min(MAXIMUM_VARINT_SIZE, readable); + int i = k & 0x7F; + for (int j = 1; j < maxRead; j++) { + k = buf.readByte(); + i |= (k & 0x7F) << j * 7; + if ((k & 0x80) != 128) { + return i; + } + } + throw new CorruptedFrameException("VarInt is invalid"); + } + + + + /** + * Returns the exact byte size of {@code value} if it were encoded as a VarInt. + * + * @param value the value to encode + * @return the byte size of {@code value} if encoded as a VarInt + */ + public static int varIntBytes(int value) { + return VAR_INT_LENGTHS[Integer.numberOfLeadingZeros(value)]; + } + + /** + * Writes a Minecraft-style VarInt to the specified {@code buf}. + * + * @param buf the buffer to read from + * @param value the integer to write + */ + public static void writeVarInt(ByteBuf buf, int value) { + // Peel the one and two byte count cases explicitly as they are the most common VarInt sizes + // that the proxy will write, to improve inlining. + if ((value & (0xFFFFFFFF << 7)) == 0) { + buf.writeByte(value); + } else if ((value & (0xFFFFFFFF << 14)) == 0) { + int w = (value & 0x7F | 0x80) << 8 | (value >>> 7); + buf.writeShort(w); + } else { + writeVarIntFull(buf, value); + } + } + + private static void writeVarIntFull(ByteBuf buf, int value) { + // See https://steinborn.me/posts/performance/how-fast-can-you-write-a-varint/ + + // This essentially is an unrolled version of the "traditional" VarInt encoding. + if ((value & (0xFFFFFFFF << 7)) == 0) { + buf.writeByte(value); + } else if ((value & (0xFFFFFFFF << 14)) == 0) { + int w = (value & 0x7F | 0x80) << 8 | (value >>> 7); + buf.writeShort(w); + } else if ((value & (0xFFFFFFFF << 21)) == 0) { + int w = (value & 0x7F | 0x80) << 16 | ((value >>> 7) & 0x7F | 0x80) << 8 | (value >>> 14); + buf.writeMedium(w); + } else if ((value & (0xFFFFFFFF << 28)) == 0) { + int w = (value & 0x7F | 0x80) << 24 | (((value >>> 7) & 0x7F | 0x80) << 16) + | ((value >>> 14) & 0x7F | 0x80) << 8 | (value >>> 21); + buf.writeInt(w); + } else { + int w = (value & 0x7F | 0x80) << 24 | ((value >>> 7) & 0x7F | 0x80) << 16 + | ((value >>> 14) & 0x7F | 0x80) << 8 | ((value >>> 21) & 0x7F | 0x80); + buf.writeInt(w); + buf.writeByte(value >>> 28); + } + } + + public static int getStringSize(String s) { + int utf8Bytes = io.netty.buffer.ByteBufUtil.utf8Bytes(s); + return ProtocolUtils.varIntBytes(utf8Bytes) + utf8Bytes; + } + + public static int getItemSize(ItemStack itemStack) { + if (itemStack == null || itemStack.getItem() == null) { // CraftBukkit - NPE fix itemstack.getItem() + return 2; + } else { + int size = 2 + 1 + 2; + + NBTTagCompound nbttagcompound = null; + + if (itemStack.getItem().usesDurability() || itemStack.getItem().p()) { + // Spigot start - filter + itemStack = itemStack.cloneItemStack(); + CraftItemStack.setItemMeta(itemStack, CraftItemStack.getItemMeta(itemStack)); + // Spigot end + nbttagcompound = itemStack.getTag(); + } + + + size += getNBTSize(nbttagcompound); + + return size; + } + } + + public static int getNBTSize(NBTTagCompound nbt) { + if (nbt == null) { + return 1; + } else { + CountingDataOutput output = new CountingDataOutput(); + + try { + NBTCompressedStreamTools.a(nbt, output); + } catch (Exception ioexception) { // CraftBukkit - IOException -> Exception + throw new EncoderException(ioexception); + } + + return output.getByteCount(); + } + } + + public static int getDataWatcherSize(DataWatcher dataWatcher) { + return 1 + getDataWatcherObjectsSize(dataWatcher.dataValues.values()); + } + + public static int getDataWatcherListSize(Collection watchableObjects) { + return 1 + getDataWatcherObjectsSize(watchableObjects); + } + + private static int getDataWatcherObjectsSize(Collection watchableObjects) { + int size = 0; + + for (DataWatcher.WatchableObject watchableObject : watchableObjects) { + size += 1; + + switch (watchableObject.c()) { + case 0: + size += 1; + break; + + case 1: + size += 2; + break; + + case 2: + size += 4; + break; + + case 3: + size += 4; + break; + + case 4: + size += ProtocolUtils.getStringSize((String) watchableObject.b()); + break; + + case 5: + size += ProtocolUtils.getItemSize((ItemStack) watchableObject.b()); + break; + + case 6: + case 7: + size += (4 + 4 + 4); + break; + } + } + + return size; + } + + public static int getChatComponentSize(IChatBaseComponent component) { + return getStringSize(IChatBaseComponent.ChatSerializer.a(component)); + } + + public static int getChatComponentSize(net.md_5.bungee.api.chat.BaseComponent[] component) { + return getStringSize(net.md_5.bungee.chat.ComponentSerializer.toString(component)); + } + + public static int getEnumSize(Enum oenum) { + return varIntBytes(oenum.ordinal()); + } + + public static int getByteArraySize(byte[] arr) { + return varIntBytes(arr.length) + arr.length; + } +} diff --git a/azurite-server/src/main/java/dev/azurite/spigot/optimizations/ReusableByteArray.java b/azurite-server/src/main/java/dev/azurite/spigot/optimizations/ReusableByteArray.java new file mode 100644 index 0000000..54c2bdd --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/optimizations/ReusableByteArray.java @@ -0,0 +1,24 @@ +package dev.azurite.spigot.optimizations; + +public class ReusableByteArray { + + private final ThreadLocal arrays; + + public ReusableByteArray(final int initialSize) { + arrays = ThreadLocal.withInitial(() -> new byte[initialSize]); + } + + /** + * Returns a (thread local) byte array of at least minSize + * @param minSize Minimum size of returned array + * @return byte array + */ + public byte[] get(int minSize) { + byte[] array = arrays.get(); + if (array.length < minSize) { + array = new byte[minSize]; + arrays.set(array); + } + return array; + } +} diff --git a/azurite-server/src/main/java/dev/azurite/spigot/optimizations/SectionTickList.java b/azurite-server/src/main/java/dev/azurite/spigot/optimizations/SectionTickList.java new file mode 100644 index 0000000..6a886e8 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/optimizations/SectionTickList.java @@ -0,0 +1,72 @@ +package dev.azurite.spigot.optimizations; + +import it.unimi.dsi.fastutil.shorts.Short2IntOpenHashMap; + +import java.util.Arrays; + +// Based on Moonrise (SpottedLeaf) IntList but with short instead of int +public final class SectionTickList { + + private final Short2IntOpenHashMap map = new Short2IntOpenHashMap(0); + { + this.map.defaultReturnValue(Integer.MIN_VALUE); + } + + private static final short[] EMPTY_LIST = new short[0]; + + private short[] byIndex = EMPTY_LIST; + private int count; + + public int size() { + return this.count; + } + + public short getRaw(final int index) { + return this.byIndex[index]; + } + + public boolean add(final short value) { + final int count = this.count; + final int currIndex = this.map.putIfAbsent(value, count); + + if (currIndex != Integer.MIN_VALUE) { + return false; // already in this list + } + + short[] list = this.byIndex; + + if (list.length == count) { + // resize required + list = this.byIndex = Arrays.copyOf(list, (int)Math.max(4L, count * 2L)); // overflow results in negative + } + + list[count] = value; + this.count = count + 1; + + return true; + } + + public boolean remove(final short value) { + final int index = this.map.remove(value); + if (index == Integer.MIN_VALUE) { + return false; + } + + // move the entry at the end to this index + final int endIndex = --this.count; + final short end = this.byIndex[endIndex]; + if (index != endIndex) { + // not empty after this call + this.map.put(end, index); + } + this.byIndex[index] = end; + this.byIndex[endIndex] = 0; + + return true; + } + + public void clear() { + this.count = 0; + this.map.clear(); + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/optimizations/SimpleRandom.java b/azurite-server/src/main/java/dev/azurite/spigot/optimizations/SimpleRandom.java new file mode 100644 index 0000000..c7edabb --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/optimizations/SimpleRandom.java @@ -0,0 +1,53 @@ +package dev.azurite.spigot.optimizations; + +import java.util.Random; +import java.util.concurrent.atomic.AtomicLong; + +// https://github.com/Tuinity/Moonrise/blob/89e9cd52e4c7818b595b686a1d8798ccb1287f69/src/main/java/ca/spottedleaf/moonrise/common/util/SimpleRandom.java#L8 +// https://github.com/Tuinity/Moonrise/blob/89e9cd52e4c7818b595b686a1d8798ccb1287f69/LICENSE.md +public final class SimpleRandom extends Random { + + private static final long MULTIPLIER = 25214903917L; + private static final long ADDEND = 11L; + private static final int BITS = 48; + private static final long MASK = (1L << BITS) - 1; + + private long value; + + public SimpleRandom() { + this(System.currentTimeMillis()); + } + + public SimpleRandom(final long seed) { + super(0L); + this.value = seed; + } + + @Override + public void setSeed(final long seed) { + this.value = (seed ^ MULTIPLIER) & MASK; + } + + private long advanceSeed() { + return this.value = ((this.value * MULTIPLIER) + ADDEND) & MASK; + } + + @Override + public int next(final int bits) { + return (int)(this.advanceSeed() >>> (BITS - bits)); + } + + @Override + public int nextInt() { + final long seed = this.advanceSeed(); + return (int)(seed >>> (BITS - Integer.SIZE)); + } + + + @Override + public int nextInt(final int bound) { + // https://lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction/ + final long value = this.advanceSeed() >>> (BITS - Integer.SIZE); + return (int)((value * (long)bound) >>> Integer.SIZE); + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/pathsearch/AzuriteNavigation.java b/azurite-server/src/main/java/dev/azurite/spigot/pathsearch/AzuriteNavigation.java new file mode 100644 index 0000000..e070c86 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/pathsearch/AzuriteNavigation.java @@ -0,0 +1,215 @@ +package dev.azurite.spigot.pathsearch; + +import dev.azurite.spigot.Azurite; +import dev.azurite.spigot.configs.AzuriteConfig; +import dev.azurite.spigot.pathsearch.cache.SearchCacheEntry; +import dev.azurite.spigot.pathsearch.cache.SearchCacheEntryEntity; +import dev.azurite.spigot.pathsearch.cache.SearchCacheEntryPosition; +import net.minecraft.server.*; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Map.Entry; +import java.util.UUID; + +public class AzuriteNavigation extends Navigation { + + private final Map searchCache; + private final Map positionSearchCache; + private final Object jobLock = new Object(); + + private int cleanUpDelay = 0; + private PathSearchJob lastQueuedJob; + + public AzuriteNavigation(EntityInsentient entityinsentient, World world) { + super(entityinsentient, world); + this.searchCache = new HashMap<>(); + this.positionSearchCache = new HashMap<>(); + } + + private double getMinimumDistanceForOffloadingSquared() { + return AzuriteConfig.minimumDistanceToTarget.getValue(); + } + + private boolean hasAsyncSearchIssued() { + synchronized (this.jobLock) { + return this.lastQueuedJob != null; + } + } + + private void queueSearch(PathSearchJob job) { + synchronized (this.jobLock) { + if (Azurite.getInstance().getThreadingManager().getPathSearchExecutor().queuePathSearch(job)) { + this.lastQueuedJob = job; + } + } + } + + private void issueSearch(Entity target) { + this.queueSearch(new PathSearchJobEntity(this, target)); + } + + private void issueSearch(BlockPosition blockposition, PositionPathSearchType type) { + this.queueSearch(new PathSearchJobPosition(this, blockposition, type)); + } + + @Override + public void setSearchResult(PathSearchJobEntity pathSearch) { + synchronized (this.jobLock) { + if (this.lastQueuedJob == pathSearch) { + this.lastQueuedJob = null; + } + } + SearchCacheEntry entry = pathSearch.getCacheEntryValue(); + if (entry != null && entry.didSearchSucceed()) { + synchronized (this.searchCache) { + UUID key = pathSearch.getCacheEntryKey(); + this.searchCache.remove(key); + this.searchCache.put(key, entry); + } + } + } + + @Override + public void setSearchResult(PathSearchJobPosition pathSearch) { + synchronized (this.jobLock) { + if (this.lastQueuedJob == pathSearch) { + this.lastQueuedJob = null; + } + } + SearchCacheEntryPosition entry = pathSearch.getCacheEntryValue(); + if (entry != null && entry.didSearchSucceed()) { + synchronized (this.positionSearchCache) { + PositionPathSearchType key = pathSearch.getCacheEntryKey(); + this.positionSearchCache.remove(key); + this.positionSearchCache.put(key, entry); + } + } + } + + @Override + public PathEntity a(Entity entity) { + if (!this.offloadSearches() || this.b.h(entity) < getMinimumDistanceForOffloadingSquared()) { + return super.a(entity); + } + if (!this.b()) { + return null; + } + SearchCacheEntry entry = null; + UUID id = entity.getUniqueID(); + synchronized (this.searchCache) { + if (this.searchCache.containsKey(id)) { + entry = this.searchCache.get(id); + } + } + PathEntity resultPath = null; + if (entry != null) { + resultPath = entry.getAdjustedPathEntity(); + if (!entry.isStillValid()) { + this.issueSearch(entity); + } + } + if (entry == null && !this.hasAsyncSearchIssued()) { + resultPath = super.a(entity); + if (resultPath != null) { + entry = new SearchCacheEntryEntity(this.b, entity, resultPath); + synchronized (this.searchCache) { + SearchCacheEntry oldEntry = this.searchCache.put(id, entry); + if (oldEntry != null) { + oldEntry.cleanup(); + } + } + } + } + return resultPath; + } + + @Override + public PathEntity a(BlockPosition blockposition) { + return this.a(blockposition, PositionPathSearchType.ANOTHER); + } + + public PathEntity a(BlockPosition blockposition, PositionPathSearchType type) { + if (!this.offloadSearches() || this.b.c(blockposition) < getMinimumDistanceForOffloadingSquared()) { + return super.a(blockposition); + } + if (!this.b()) { + return null; + } + + SearchCacheEntryPosition entry = null; + synchronized (this.positionSearchCache) { + if (this.positionSearchCache.containsKey(type)) { + entry = this.positionSearchCache.get(type); + } + } + + PathEntity resultPath = null; + if (entry != null) { + resultPath = entry.getAdjustedPathEntity(); + if (!entry.isStillValid()) { + this.issueSearch(blockposition, type); + } + } + if (entry == null && !this.hasAsyncSearchIssued()) { + resultPath = super.a(blockposition); + if (resultPath != null) { + entry = new SearchCacheEntryPosition(this.b, blockposition, resultPath); + synchronized (this.positionSearchCache) { + SearchCacheEntry oldEntry = this.positionSearchCache.put(type, entry); + if (oldEntry != null) { + oldEntry.cleanup(); + } + } + } + } + return resultPath; + } + + @Override + public PathEntity a(double d0, double d1, double d2, PositionPathSearchType type) { + return this.a(new BlockPosition(MathHelper.floor(d0), (int) d1, MathHelper.floor(d2)), type); + } + + @Override + public boolean a(double d0, double d1, double d2, double d3, PositionPathSearchType type) { + PathEntity pathentity = this.a(MathHelper.floor(d0), (int) d1, MathHelper.floor(d2), type); + return this.a(pathentity, d3); + } + + public void cleanUpExpiredSearches() { + this.cleanUpDelay++; + if (this.cleanUpDelay > 100) { + this.cleanUpDelay = 0; + synchronized (this.searchCache) { + Iterator> iterator = this.searchCache.entrySet().iterator(); + while (iterator.hasNext()) { + SearchCacheEntry entry = iterator.next().getValue(); + if (entry.hasExpired()) { + iterator.remove(); + entry.cleanup(); + } else { + break; + } + } + } + synchronized (this.positionSearchCache) { + Iterator> iterator = this.positionSearchCache.entrySet().iterator(); + while (iterator.hasNext()) { + SearchCacheEntryPosition entry = iterator.next().getValue(); + if (entry.hasExpired()) { + iterator.remove(); + entry.cleanup(); + } else { + break; + } + } + } + } + } + + private boolean offloadSearches() { + return Azurite.getInstance().getThreadingManager().getPathSearchExecutor().isPathSearchOffloadedFor(this.b); + } +} diff --git a/azurite-server/src/main/java/dev/azurite/spigot/pathsearch/PathSearchJob.java b/azurite-server/src/main/java/dev/azurite/spigot/pathsearch/PathSearchJob.java new file mode 100644 index 0000000..297fb85 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/pathsearch/PathSearchJob.java @@ -0,0 +1,50 @@ +package dev.azurite.spigot.pathsearch; + +import java.util.concurrent.Callable; + +import dev.azurite.spigot.utils.WeakChunkCache; +import net.minecraft.server.NavigationAbstract; +import net.minecraft.server.PathEntity; + +public abstract class PathSearchJob implements Callable { + + public NavigationAbstract navigation; + protected WeakChunkCache chunkCache; + protected boolean issued; + private final int hashCode; + protected PathEntity pathEntity; + + public PathSearchJob(NavigationAbstract navigation) { + this.navigation = navigation; + this.hashCode = this.navigation.hashCode(); + this.issued = false; + this.chunkCache = this.navigation.createChunkCache(this.isEntitySearch()); + } + + protected boolean isEntitySearch() { + return false; + } + + public void cleanup() { + this.navigation = null; + this.chunkCache = null; + this.pathEntity = null; + } + + @Override + public int hashCode() { + return this.hashCode; + } + + public final int getSearchHash() { + return this.hashCode; + } + + @Override + public boolean equals(Object o) { + if(!(o instanceof PathSearchJob)) { + return false; + } + return this.hashCode() == o.hashCode(); + } +} diff --git a/azurite-server/src/main/java/dev/azurite/spigot/pathsearch/PathSearchJobEntity.java b/azurite-server/src/main/java/dev/azurite/spigot/pathsearch/PathSearchJobEntity.java new file mode 100644 index 0000000..ba2ada2 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/pathsearch/PathSearchJobEntity.java @@ -0,0 +1,52 @@ +package dev.azurite.spigot.pathsearch; + +import java.util.UUID; + +import dev.azurite.spigot.pathsearch.cache.SearchCacheEntry; +import dev.azurite.spigot.pathsearch.cache.SearchCacheEntryEntity; + +import net.minecraft.server.Entity; +import net.minecraft.server.NavigationAbstract; + +public class PathSearchJobEntity extends PathSearchJob { + + public Entity target; + + public PathSearchJobEntity(NavigationAbstract navigation, Entity target) { + super(navigation); + this.target = target; + } + + @Override + public PathSearchJob call() throws Exception { + if(!this.issued) { + this.issued = true; + this.pathEntity = this.navigation.doPathSearch(this.chunkCache, this.target); + this.navigation.setSearchResult(this); + this.cleanup(); + } + return this; + } + + @Override + protected boolean isEntitySearch() { + return true; + } + + @Override + public void cleanup() { + super.cleanup(); + this.target = null; + } + + public UUID getCacheEntryKey() { + return this.target.getUniqueID(); + } + + public SearchCacheEntry getCacheEntryValue() { + if(this.pathEntity != null) { + return new SearchCacheEntryEntity(this.navigation.getEntity(), this.target, this.pathEntity); + } + return null; + } +} diff --git a/azurite-server/src/main/java/dev/azurite/spigot/pathsearch/PathSearchJobPosition.java b/azurite-server/src/main/java/dev/azurite/spigot/pathsearch/PathSearchJobPosition.java new file mode 100644 index 0000000..faad613 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/pathsearch/PathSearchJobPosition.java @@ -0,0 +1,59 @@ +package dev.azurite.spigot.pathsearch; + +import dev.azurite.spigot.pathsearch.cache.SearchCacheEntryPosition; +import net.minecraft.server.BlockPosition; +import net.minecraft.server.NavigationAbstract; + +public class PathSearchJobPosition extends PathSearchJob { + + private final PositionPathSearchType type; + private BlockPosition blockposition; + + public PathSearchJobPosition(NavigationAbstract navigation, BlockPosition blockposition, PositionPathSearchType type) { + super(navigation); + this.blockposition = blockposition; + this.type = type; + } + + @Override + public PathSearchJob call() throws Exception { + if(!this.issued) { + this.issued = true; + this.pathEntity = this.navigation.doPathSearch(this.chunkCache, this.blockposition); + this.navigation.setSearchResult(this); + this.cleanup(); + } + return this; + } + + public PositionPathSearchType getCacheEntryKey() { + return this.type; + } + + public SearchCacheEntryPosition getCacheEntryValue() { + if(this.pathEntity != null) { + return new SearchCacheEntryPosition(this.navigation.getEntity(), this.blockposition, this.pathEntity); + } + return null; + } + + @Override + public int hashCode() { + return this.type.hashCode() ^ (super.hashCode() << 4); + } + + @Override + public boolean equals(Object o) { + if(!(o instanceof PathSearchJobPosition)) { + return false; + } + PathSearchJobPosition other = (PathSearchJobPosition) o; + return this.type.equals(other.type) && this.hashCode() == other.hashCode(); + } + + @Override + public void cleanup() { + super.cleanup(); + this.blockposition = null; + } +} diff --git a/azurite-server/src/main/java/dev/azurite/spigot/pathsearch/PathSearchThrottlerThread.java b/azurite-server/src/main/java/dev/azurite/spigot/pathsearch/PathSearchThrottlerThread.java new file mode 100644 index 0000000..8d4f7d4 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/pathsearch/PathSearchThrottlerThread.java @@ -0,0 +1,117 @@ +package dev.azurite.spigot.pathsearch; + +import dev.azurite.spigot.async.factory.NamePriorityThreadFactory; +import dev.azurite.spigot.configs.AzuriteConfig; +import net.minecraft.server.EntityInsentient; +import org.bukkit.entity.EntityType; + +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.Map.Entry; +import java.util.Set; +import java.util.concurrent.*; + +public class PathSearchThrottlerThread extends ThreadPoolExecutor { + + private int queueLimit; + private final LinkedHashMap filter; + private final Set activeSearchHashes; + private static PathSearchThrottlerThread instance; + private final Set entitiesWithOffloadedPathSearches = new HashSet<>(); + + public PathSearchThrottlerThread(int poolSize) { + super(poolSize, poolSize, 1L, TimeUnit.MINUTES, new LinkedBlockingQueue<>(), new NamePriorityThreadFactory(Thread.MIN_PRIORITY, "Azurite_PathFinder")); + instance = this; + adjustPoolSize(poolSize); + this.filter = new LinkedHashMap<>(); + this.activeSearchHashes = new HashSet<>(); + this.loadEntitiesWithOffloadedPathSearches(); + } + + public boolean queuePathSearch(PathSearchJob newJob) { + boolean jobHasBeenQueued = false; + if (newJob != null) { + synchronized (this.filter) { + if (this.filter.containsKey(newJob) || this.filter.size() < 1000) { + jobHasBeenQueued = true; + PathSearchJob previousJob = this.filter.put(newJob, newJob); + if (previousJob != null) { + previousJob.cleanup(); + } + } + } + } + PathSearchJob jobToExecute; + synchronized (this.filter) { + Iterator> iterator = this.filter.entrySet().iterator(); + while (iterator.hasNext() && this.getQueue().size() < this.queueLimit) { + jobToExecute = iterator.next().getValue(); + if (!this.activeSearchHashes.contains(jobToExecute.getSearchHash())) { + iterator.remove(); + this.activeSearchHashes.add(jobToExecute.getSearchHash()); + this.submit(jobToExecute); + if (newJob != null) { + break; + } + } + } + } + return jobHasBeenQueued; + } + + @Override + public void shutdown() { + this.getQueue().clear(); + super.shutdown(); + } + + @Override + protected void afterExecute(Runnable runnable, Throwable throwable) { + super.afterExecute(runnable, throwable); + if (runnable instanceof FutureTask) { + FutureTask task = (FutureTask) runnable; + PathSearchJob job = null; + try { + job = task.get(); + } catch (InterruptedException | ExecutionException e) { + // Empty catch + } + if (job != null) { + synchronized (this.filter) { + this.activeSearchHashes.remove(job.getSearchHash()); + } + } + } + this.queuePathSearch(null); + } + + public static void adjustPoolSize(int size) { + if (instance != null) { + if (size > instance.getMaximumPoolSize()) { + instance.setMaximumPoolSize(size); + instance.setCorePoolSize(size); + } else if (size < instance.getMaximumPoolSize()) { + instance.setCorePoolSize(size); + instance.setMaximumPoolSize(size); + } + instance.queueLimit = size * 8; + } + } + + private void loadEntitiesWithOffloadedPathSearches() { + this.entitiesWithOffloadedPathSearches.clear(); + for (String name : AzuriteConfig.entitiesPathSearchOffload.getValue()) { + try { + EntityType type = EntityType.valueOf(name.toUpperCase()); + this.entitiesWithOffloadedPathSearches.add(type); + } catch (IllegalArgumentException e) { + e.printStackTrace(); + } + } + } + + public boolean isPathSearchOffloadedFor(EntityInsentient entity) { + return AzuriteConfig.enableAsyncPathSearch.getValue() && this.entitiesWithOffloadedPathSearches.contains(entity.getBukkitEntity().getType()); + } +} diff --git a/azurite-server/src/main/java/dev/azurite/spigot/pathsearch/PositionPathSearchType.java b/azurite-server/src/main/java/dev/azurite/spigot/pathsearch/PositionPathSearchType.java new file mode 100644 index 0000000..e169f6d --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/pathsearch/PositionPathSearchType.java @@ -0,0 +1,16 @@ +package dev.azurite.spigot.pathsearch; + +public enum PositionPathSearchType { + ANOTHER, + AVOIDTARGET, + FLEESUN, + GOTOTARGET, + MOVEINDOORS, + MOVETHROUGHVILLAGE, + MOVETOWARDSRESTRICTION, + MOVETOWARDSTARGET, + PANIC, + PLAY, + RANDOMSTROLL, + TAME; +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/pathsearch/cache/SearchCacheEntry.java b/azurite-server/src/main/java/dev/azurite/spigot/pathsearch/cache/SearchCacheEntry.java new file mode 100644 index 0000000..4d205ac --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/pathsearch/cache/SearchCacheEntry.java @@ -0,0 +1,76 @@ +package dev.azurite.spigot.pathsearch.cache; + +import net.minecraft.server.BlockPosition; +import net.minecraft.server.Entity; +import net.minecraft.server.EntityInsentient; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.PathEntity; +import net.minecraft.server.PathPoint; + +public class SearchCacheEntry { + protected long tick; + protected BlockPosition positionStart; + protected BlockPosition positionTarget; + protected EntityInsentient entity; + private PathEntity path; + + public SearchCacheEntry(EntityInsentient entity, PathEntity path) { + this.entity = entity; + this.positionStart = this.getBlockPosition(this.entity); + this.path = path; + this.tick = this.getCurrentTick(); + } + + protected int getCurrentTick() { + return MinecraftServer.getServer().at(); + } + + protected BlockPosition getBlockPosition(Entity entity) { + return new BlockPosition(entity).up(); + } + + protected BlockPosition getBlockPosition(int x, int y, int z) { + return new BlockPosition(x, y, z); + } + + public boolean isStillValid() { + return this.didSearchSucceed() && (this.getCurrentTick() - this.tick < 10); + } + + public PathEntity getPathEntity() { + return this.path; + } + + public boolean hasExpired() { + return !this.entity.isAlive() || !this.entity.valid || (this.getCurrentTick() - this.tick) > 100; + } + + public boolean didSearchSucceed() { + return this.path != null; + } + + public PathEntity getAdjustedPathEntity() { + if(this.path != null && (this.path.e() < this.path.d() - 1)) { + PathPoint pathpoint = this.path.a(this.path.e()); + double currentDist = this.entity.e(pathpoint.a, pathpoint.b, pathpoint.c); + while(this.path.e() < this.path.d() - 1) { + pathpoint = this.path.a(this.path.e() + 1); + double nextDist = this.entity.e(pathpoint.a, pathpoint.b, pathpoint.c); + if(nextDist < currentDist) { + currentDist = nextDist; + this.path.a(); + } else { + break; + } + } + } + return this.path; + } + + public void cleanup() { + this.positionStart = null; + this.positionTarget = null; + this.entity = null; + this.path = null; + } +} diff --git a/azurite-server/src/main/java/dev/azurite/spigot/pathsearch/cache/SearchCacheEntryEntity.java b/azurite-server/src/main/java/dev/azurite/spigot/pathsearch/cache/SearchCacheEntryEntity.java new file mode 100644 index 0000000..a39c097 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/pathsearch/cache/SearchCacheEntryEntity.java @@ -0,0 +1,30 @@ +package dev.azurite.spigot.pathsearch.cache; + +import net.minecraft.server.Entity; +import net.minecraft.server.EntityInsentient; +import net.minecraft.server.PathEntity; + +public class SearchCacheEntryEntity extends SearchCacheEntry { + + private Entity target; + + public SearchCacheEntryEntity(EntityInsentient entity, Entity target, PathEntity path) { + super(entity, path); + this.target = target; + this.positionTarget = this.getBlockPosition(this.target); + } + + @Override + public boolean isStillValid() { + if(super.isStillValid()) { + return this.getBlockPosition(this.target).equals(this.positionTarget); + } + return false; + } + + @Override + public void cleanup() { + super.cleanup(); + this.target = null; + } +} diff --git a/azurite-server/src/main/java/dev/azurite/spigot/pathsearch/cache/SearchCacheEntryPosition.java b/azurite-server/src/main/java/dev/azurite/spigot/pathsearch/cache/SearchCacheEntryPosition.java new file mode 100644 index 0000000..2846bbd --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/pathsearch/cache/SearchCacheEntryPosition.java @@ -0,0 +1,21 @@ +package dev.azurite.spigot.pathsearch.cache; + +import net.minecraft.server.BlockPosition; +import net.minecraft.server.EntityInsentient; +import net.minecraft.server.PathEntity; + +public class SearchCacheEntryPosition extends SearchCacheEntry { + + public SearchCacheEntryPosition(EntityInsentient entity, BlockPosition blockposition, PathEntity path) { + super(entity, path); + this.positionTarget = blockposition; + } + + @Override + public boolean isStillValid() { + if(super.isStillValid()) { + return this.getBlockPosition(this.entity).equals(this.positionStart); + } + return false; + } +} diff --git a/azurite-server/src/main/java/dev/azurite/spigot/redstone/EigencraftRedstoneWire.java b/azurite-server/src/main/java/dev/azurite/spigot/redstone/EigencraftRedstoneWire.java new file mode 100644 index 0000000..ab14049 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/redstone/EigencraftRedstoneWire.java @@ -0,0 +1,1030 @@ +package dev.azurite.spigot.redstone; + +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import net.minecraft.server.*; +import org.bukkit.event.block.BlockRedstoneEvent; + +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ThreadLocalRandom; + +/** + * Used for the faster redstone algorithm. + * Original author: theosib + * Original license: MIT + *

+ * Ported to Paper and updated to 1.13 by egg82 + */ +public class EigencraftRedstoneWire extends BlockRedstoneWire { + /* + * This is Helper class for BlockRedstoneWire. It implements a minimally-invasive + * bolt-on accelerator that performs a breadth-first search through redstone wire blocks + * in order to more efficiently and deterministically compute new redstone wire power levels + * and determine the order in which other blocks should be updated. + * + * Features: + * - Changes to BlockRedstoneWire are very limited, no other classes are affected, and the + * choice between old and new redstone wire update algorithms is switchable on-line. + * - The vanilla implementation relied on World.notifyNeighborsOfStateChange for redstone + * wire blocks to communicate power level changes to each other, generating 36 block + * updates per call. This improved implementation propagates power level changes directly + * between redstone wire blocks. Redstone wire power levels are therefore computed more quickly, + * and block updates are sent only to non-redstone blocks, many of which may perform an + * action when informed of a change in redstone power level. (Note: Block updates are not + * the same as state changes to redstone wire. Wire block states are updated as soon + * as they are computed.) + * - Of the 36 block updates generated by a call to World.notifyNeighborsOfStateChange, + * 12 of them are obviously redundant (e.g. the west neighbor of the east neighbor). + * These are eliminated. + * - Updates to redstone wire and other connected blocks are propagated in a breath-first + * manner, radiating out from the initial trigger (a block update to a redstone wire + * from something other than redstone wire). + * - Updates are scheduled both deterministically and in an intuitive order, addressing bug + * MC-11193. + * - All redstone behavior that used to be locational now works the same in all locations. + * - All behaviors of redstone wire that used to be orientational now work the same in all + * orientations, as long as orientation can be determined; random otherwise. Some other + * redstone components still update directionally (e.g. switches), and this code can't + * compensate for that. + * - Information that is otherwise computed over and over again or which is expensive to + * to compute is cached for faster lookup. This includes coordinates of block position + * neighbors and block states that won't change behind our backs during the execution of + * this search algorithm. + * - Redundant block updates (both to redstone wire and to other blocks) are heavily + * consolidated. For worst-case scenarios (depowering of redstone wire) this results + * in a reduction of block updates by as much as 95% (factor of 1/21). Due to overheads, + * empirical testing shows a speedup better than 10x. This addresses bug MC-81098. + * + * Extensive testing has been performed to ensure that existing redstone contraptions still + * behave as expected. Results of early testing that identified undesirable behavior changes + * were addressed. Additionally, real-time performance testing revealed compute inefficiencies + * With earlier implementations of this accelerator. Some compatibility adjustments and + * performance optimizations resulted in harmless increases in block updates above the + * theoretical minimum. + * + * Only a single redstone machine was found to break: An instant dropper line hack that + * relies on powered rails and quasi-connectivity but doesn't work in all directions. The + * replacement is to lay redstone wire directly on top of the dropper line, which now works + * reliably in any direction. + * + * There are numerous other optimization that can be made, but those will be provided later in + * separate updates. This version is designed to be minimalistic. + * + * Many thanks to the following individuals for their help in testing this functionality: + * - pokechu22, _MethodZz_, WARBEN, NarcolepticFrog, CommandHelper (nessie), ilmango, + * OreoLamp, Xcom6000, tryashtar, RedCMD, Smokey95Dog, EDDxample, Rays Works, + * Nodnam, BlockyPlays, Grumm, NeunEinser, HelVince. + */ + + /* + * Implementation: + * + * RedstoneWire Blocks are updated in concentric rings or "layers" radiating out from the + * initial block update that came from a call to BlockRedstoneWire.neighborChanged(). + * All nodes put in Layer N are those with Manhattan distance N from the trigger + * position, reachable through connected redstone wire blocks. + * + * Layer 0 represents the trigger block position that was input to neighborChanged. + * Layer 1 contains the immediate neighbors of that position. + * Layer N contains the neighbors of blocks in layer N-1, not including + * those in previous layers. + * + * Layers enforce an update order that is a function of Manhattan distance + * from the initial coordinates input to neighborChanged. The same + * coordinates may appear in multiple layers, but redundant updates are minimized. + * Block updates are sent layer-by-layer. If multiple of a block's neighbors experience + * redstone wire changes before its layer is processed, then those updates will be merged. + * If a block's update has been sent, but its neighboring redstone changes + * after that, then another update will be sent. This preserves compatibility with + * machines that rely on zero-tick behavior, except that the new functionality is non- + * locational. + * + * Within each layer, updates are ordered left-to-right relative to the direction of + * information flow. This makes the implementation non-orientational. Only when + * this direction is ambiguous is randomness applied (intentionally). + */ + private List updateQueue0 = Lists.newArrayList(); + private List updateQueue1 = Lists.newArrayList(); + private List updateQueue2 = Lists.newArrayList(); + + public EigencraftRedstoneWire() { + super(); + } + + /* + * Compute neighbors of a block. When a redstone wire value changes, previously it called + * World.notifyNeighborsOfStateChange. That lists immediately neighboring blocks in + * west, east, down, up, north, south order. For each of those neighbors, their own + * neighbors are updated in the same order. This generates 36 updates, but 12 of them are + * redundant; for instance the west neighbor of a block's east neighbor. + * + * Note that this ordering is only used to create the initial list of neighbors. Once + * the direction of signal flow is identified, the ordering of updates is completely + * reorganized. + */ + public static BlockPosition[] computeAllNeighbors(final BlockPosition pos) { + final int x = pos.getX(); + final int y = pos.getY(); + final int z = pos.getZ(); + final BlockPosition[] n = new BlockPosition[24]; + + // Immediate neighbors, in the same order as + // World.notifyNeighborsOfStateChange, etc.: + // west, east, down, up, north, south + n[0] = new BlockPosition(x - 1, y, z); + n[1] = new BlockPosition(x + 1, y, z); + n[2] = new BlockPosition(x, y - 1, z); + n[3] = new BlockPosition(x, y + 1, z); + n[4] = new BlockPosition(x, y, z - 1); + n[5] = new BlockPosition(x, y, z + 1); + + // Neighbors of neighbors, in the same order, + // except that duplicates are not included + n[6] = new BlockPosition(x - 2, y, z); + n[7] = new BlockPosition(x - 1, y - 1, z); + n[8] = new BlockPosition(x - 1, y + 1, z); + n[9] = new BlockPosition(x - 1, y, z - 1); + n[10] = new BlockPosition(x - 1, y, z + 1); + n[11] = new BlockPosition(x + 2, y, z); + n[12] = new BlockPosition(x + 1, y - 1, z); + n[13] = new BlockPosition(x + 1, y + 1, z); + n[14] = new BlockPosition(x + 1, y, z - 1); + n[15] = new BlockPosition(x + 1, y, z + 1); + n[16] = new BlockPosition(x, y - 2, z); + n[17] = new BlockPosition(x, y - 1, z - 1); + n[18] = new BlockPosition(x, y - 1, z + 1); + n[19] = new BlockPosition(x, y + 2, z); + n[20] = new BlockPosition(x, y + 1, z - 1); + n[21] = new BlockPosition(x, y + 1, z + 1); + n[22] = new BlockPosition(x, y, z - 2); + n[23] = new BlockPosition(x, y, z + 2); + return n; + } + + /* + * We only want redstone wires to update redstone wires that are + * immediately adjacent. Some more distant updates can result + * in cross-talk that (a) wastes time and (b) can make the update + * order unintuitive. Therefore (relative to the neighbor order + * computed by computeAllNeighbors), updates are not scheduled + * for redstone wire in those non-connecting positions. On the + * other hand, updates will always be sent to *other* types of blocks + * in any of the 24 neighboring positions. + */ + private static final boolean[] update_redstone = { + true, true, false, false, true, true, // 0 to 5 + false, true, true, false, false, false, // 6 to 11 + true, true, false, false, false, true, // 12 to 17 + true, false, true, true, false, false // 18 to 23 + }; + + // Internal numbering for cardinal directions + private static final int North = 0; + private static final int East = 1; + private static final int South = 2; + private static final int West = 3; + + /* + * These lookup tables completely remap neighbor positions into a left-to-right + * ordering, based on the cardinal direction that is determined to be forward. + * See below for more explanation. + */ + private static final int[] forward_is_north = {2, 3, 16, 19, 0, 4, 1, 5, 7, 8, 17, 20, 12, 13, 18, 21, 6, 9, 22, 14, 11, 10, 23, 15}; + private static final int[] forward_is_east = {2, 3, 16, 19, 4, 1, 5, 0, 17, 20, 12, 13, 18, 21, 7, 8, 22, 14, 11, 15, 23, 9, 6, 10}; + private static final int[] forward_is_south = {2, 3, 16, 19, 1, 5, 0, 4, 12, 13, 18, 21, 7, 8, 17, 20, 11, 15, 23, 10, 6, 14, 22, 9}; + private static final int[] forward_is_west = {2, 3, 16, 19, 5, 0, 4, 1, 18, 21, 7, 8, 17, 20, 12, 13, 23, 10, 6, 9, 22, 15, 11, 14}; + + /* For any orientation, we end up with the update order defined below. This order is relative to any redstone wire block + * that is itself having an update computed, and this center position is marked with C. + * - The update position marked 0 is computed first, and the one marked 23 is last. + * - Forward is determined by the local direction of information flow into position C from prior updates. + * - The first updates are scheduled for the four positions below and above C. + * - Then updates are scheduled for the four horizontal neighbors of C, followed by the positions below and above those neighbors. + * - Finally, updates are scheduled for the remaining positions with Manhattan distance 2 from C (at the same Y coordinate). + * - For a given horizontal distance from C, updates are scheduled starting from directly left and stepping clockwise to directly + * right. The remaining positions behind C are scheduled counterclockwise so as to maintain the left-to-right ordering. + * - If C is in layer N of the update schedule, then all 24 positions may be scheduled for layer N+1. For redstone wire, no + * updates are scheduled for positions that cannot directly connect. Additionally, the four positions above and below C + * are ALSO scheduled for layer N+2. + * - This update order was selected after experimenting with a number of alternative schedules, based on its compatibility + * with existing redstone designs and behaviors that were considered to be intuitive by various testers. WARBEN in particular + * made some of the most challenging test cases, but the 3-tick clocks (made by RedCMD) were also challenging to fix, + * along with the rail-based instant dropper line built by ilmango. Numerous others made test cases as well, including + * NarcolepticFrog, nessie, and Pokechu22. + * + * - The forward direction is determined locally. So when there are branches in the redstone wire, the left one will get updated + * before the right one. Each branch can have its own relative forward direction, resulting in the left side of a left branch + * having priority over the right branch of a left branch, which has priority over the left branch of a right branch, followed + * by the right branch of a right branch. And so forth. Since redstone power reduces to zero after a path distance of 15, + * that imposes a practical limit on the branching. Note that the branching is not tracked explicitly -- relative forward + * directions dictate relative sort order, which maintains the proper global ordering. This also makes it unnecessary to be + * concerned about branches meeting up with each other. + * + * ^ + * | + * Forward + * <-- Left Right --> + * + * 18 + * 10 17 5 19 11 + * 2 8 0 12 16 4 C 6 20 9 1 13 3 + * 14 21 7 23 15 + * Further 22 Further + * Down Down Up Up + * + * Backward + * | + * V + */ + + // This allows the above remapping tables to be looked up by cardial direction index + private static final int[][] reordering = {forward_is_north, forward_is_east, forward_is_south, forward_is_west}; + + /* + * Input: Array of UpdateNode objects in an order corresponding to the positions + * computed by computeAllNeighbors above. + * Output: Array of UpdateNode objects oriented using the above remapping tables + * corresponding to the identified heading (direction of information flow). + */ + private static void orientNeighbors(final UpdateNode[] src, final UpdateNode[] dst, final int heading) { + final int[] re = reordering[heading]; + for (int i = 0; i < 24; i++) { + dst[i] = src[re[i]]; + } + } + + /* + * Structure to keep track of redstone wire blocks and + * neighbors that will receive updates. + */ + private static class UpdateNode { + public enum Type { + UNKNOWN, REDSTONE, OTHER + } + + IBlockData currentState; // Keep track of redstone wire value + UpdateNode[] neighbor_nodes; // References to neighbors (directed graph edges) + BlockPosition self; // UpdateNode's own position + BlockPosition parent; // Which block pos spawned/updated this node + Type type = Type.UNKNOWN; // unknown, redstone wire, other type of block + int layer; // Highest layer this node is scheduled in + boolean visited; // To keep track of information flow direction, visited restone wire is marked + int xbias, zbias; // Remembers directionality of ancestor nodes; helps eliminate directional ambiguities. + } + + /* + * Keep track of all block positions discovered during search and their current states. + * We want to remember one entry for each position. + */ + private final Map nodeCache = Maps.newHashMap(); + + /* + * For a newly created UpdateNode object, determine what type of block it is. + */ + private void identifyNode(final World worldIn, final UpdateNode upd1) { + final BlockPosition pos = upd1.self; + final IBlockData oldState = worldIn.getType(pos); + upd1.currentState = oldState; + + // Some neighbors of redstone wire are other kinds of blocks. + // These need to receive block updates to inform them that + // redstone wire values have changed. + final Block block = oldState.getBlock(); + if (block != this) { + // Mark this block as not redstone wire and therefore + // requiring updates + upd1.type = UpdateNode.Type.OTHER; + + // Non-redstone blocks may propagate updates, but those updates + // are not handled by this accelerator. Therefore, we do not + // expand this position's neighbors. + return; + } + + // One job of BlockRedstoneWire.neighborChanged is to convert + // redstone wires to items if the block beneath was removed. + // With this accelerator, BlockRedstoneWire.neighborChanged + // is only typically called for a single wire block, while + // others are processed internally by the breadth first search + // algorithm. To preserve this game behavior, this check must + // be replicated here. + if (!canPlace(worldIn, pos)) { + // Pop off the redstone dust + this.b(worldIn, pos, oldState, 0); + worldIn.setAir(pos); + + // Mark this position as not being redstone wire + upd1.type = UpdateNode.Type.OTHER; + + // Note: Sending updates to air blocks leads to an empty method. + // Testing shows this to be faster than explicitly avoiding updates to + // air blocks. + return; + } + + // If the above conditions fail, then this is a redstone wire block. + upd1.type = UpdateNode.Type.REDSTONE; + } + + /* + * Given which redstone wire blocks have been visited and not visited + * around the position currently being updated, compute the cardinal + * direction that is "forward." + * + * rx is the forward direction along the West/East axis + * rz is the forward direction along the North/South axis + */ + static private int computeHeading(final int rx, final int rz) { + // rx and rz can only take on values -1, 0, and 1, so we can + // compute a code number that allows us to use a single switch + // to determine the heading. + final int code = (rx + 1) + 3 * (rz + 1); + switch (code) { + case 0: { + // Both rx and rz are -1 (northwest) + // Randomly choose one to be forward. + final int j = ThreadLocalRandom.current().nextInt(0, 1); + return (j == 0) ? North : West; + } + case 1: { + // rx=0, rz=-1 + // Definitively North + return North; + } + case 2: { + // rx=1, rz=-1 (northeast) + // Choose randomly between north and east + final int j = ThreadLocalRandom.current().nextInt(0, 1); + return (j == 0) ? North : East; + } + case 3: { + // rx=-1, rz=0 + // Definitively West + return West; + } + case 4: { + // rx=0, rz=0 + // Heading is completely ambiguous. Choose + // randomly among the four cardinal directions. + return ThreadLocalRandom.current().nextInt(0, 4); + } + case 5: { + // rx=1, rz=0 + // Definitively East + return East; + } + case 6: { + // rx=-1, rz=1 (southwest) + // Choose randomly between south and west + final int j = ThreadLocalRandom.current().nextInt(0, 1); + return (j == 0) ? South : West; + } + case 7: { + // rx=0, rz=1 + // Definitively South + return South; + } + case 8: { + // rx=1, rz=1 (southeast) + // Choose randomly between south and east + final int j = ThreadLocalRandom.current().nextInt(0, 1); + return (j == 0) ? South : East; + } + } + + // We should never get here + return ThreadLocalRandom.current().nextInt(0, 4); + } + + // Select whether to use updateSurroundingRedstone from BlockRedstoneWire (old) + // or this helper class (new) + private static final boolean old_current_change = false; + + /* + * Process a node whose neighboring redstone wire has experienced value changes. + */ + private void updateNode(final World worldIn, final UpdateNode upd1, final int layer) { + final BlockPosition pos = upd1.self; + + // Mark this redstone wire as having been visited so that it can be used + // to calculate direction of information flow. + upd1.visited = true; + + // Look up the last known state. + // Due to the way other redstone components are updated, we do not + // have to worry about a state changing behind our backs. The rare + // exception is handled by scheduleReentrantNeighborChanged. + final IBlockData oldState = upd1.currentState; + + // Ask the wire block to compute its power level from its neighbors. + // This will also update the wire's power level and return a new + // state if it has changed. When a wire power level is changed, + // calculateCurrentChanges will immediately update the block state in the world + // and return the same value here to be cached in the corresponding + // UpdateNode object. + IBlockData newState; + if (old_current_change) { + newState = calculateCurrentChanges(worldIn, pos, pos, oldState); + } else { + // Looking up block state is slow. This accelerator includes a version of + // calculateCurrentChanges that uses cahed wire values for a + // significant performance boost. + newState = this.calculateCurrentChanges(worldIn, upd1); + } + + // Only inform neighbors if the state has changed + if (newState != oldState) { + // Store the new state + upd1.currentState = newState; + + // Inform neighbors of the change + propagateChanges(worldIn, upd1, layer); + } + } + + /* + * This identifies the neighboring positions of a new UpdateNode object, + * determines their types, and links those to into the graph. Then based on + * what nodes in the redstone wire graph have been visited, the neighbors + * are reordered left-to-right relative to the direction of information flow. + */ + private void findNeighbors(final World worldIn, final UpdateNode upd1) { + final BlockPosition pos = upd1.self; + + // Get the list of neighbor coordinates + final BlockPosition[] neighbors = computeAllNeighbors(pos); + + // Temporary array of neighbors in cardinal ordering + final UpdateNode[] neighbor_nodes = new UpdateNode[24]; + + // Target array of neighbors sorted left-to-right + upd1.neighbor_nodes = new UpdateNode[24]; + + for (int i = 0; i < 24; i++) { + // Look up each neighbor in the node cache + final BlockPosition pos2 = neighbors[i]; + UpdateNode upd2 = nodeCache.get(pos2); + if (upd2 == null) { + // If this is a previously unreached position, create + // a new update node, add it to the cache, and identify what it is. + upd2 = new UpdateNode(); + upd2.self = pos2; + upd2.parent = pos; + nodeCache.put(pos2, upd2); + identifyNode(worldIn, upd2); + } + + // For non-redstone blocks, any of the 24 neighboring positions + // should receive a block update. However, some block coordinates + // may contain a redstone wire that does not directly connect to the + // one being expanded. To avoid redundant calculations and confusing + // cross-talk, those neighboring positions are not included. + if (update_redstone[i] || upd2.type != UpdateNode.Type.REDSTONE) { + neighbor_nodes[i] = upd2; + } + } + + // Determine the directions from which the redstone signal may have come from. This + // checks for redstone wire at the same Y level and also Y+1 and Y-1, relative to the + // block being expanded. + final boolean fromWest = (neighbor_nodes[0].visited || neighbor_nodes[7].visited || neighbor_nodes[8].visited); + final boolean fromEast = (neighbor_nodes[1].visited || neighbor_nodes[12].visited || neighbor_nodes[13].visited); + final boolean fromNorth = (neighbor_nodes[4].visited || neighbor_nodes[17].visited || neighbor_nodes[20].visited); + final boolean fromSouth = (neighbor_nodes[5].visited || neighbor_nodes[18].visited || neighbor_nodes[21].visited); + + int cx = 0, cz = 0; + if (fromWest) cx += 1; + if (fromEast) cx -= 1; + if (fromNorth) cz += 1; + if (fromSouth) cz -= 1; + + int heading; + if (cx == 0 && cz == 0) { + // If there is no clear direction, try to inherit the heading from ancestor nodes. + heading = computeHeading(upd1.xbias, upd1.zbias); + + // Propagate that heading to descendant nodes. + for (int i = 0; i < 24; i++) { + final UpdateNode nn = neighbor_nodes[i]; + if (nn != null) { + nn.xbias = upd1.xbias; + nn.zbias = upd1.zbias; + } + } + } else { + if (cx != 0 && cz != 0) { + // If the heading is somewhat ambiguous, try to disambiguate based on + // ancestor nodes. + if (upd1.xbias != 0) cz = 0; + if (upd1.zbias != 0) cx = 0; + } + heading = computeHeading(cx, cz); + + // Propagate that heading to descendant nodes. + for (int i = 0; i < 24; i++) { + final UpdateNode nn = neighbor_nodes[i]; + if (nn != null) { + nn.xbias = cx; + nn.zbias = cz; + } + } + } + + // Reorder neighboring UpdateNode objects according to the forward direction + // determined above. + orientNeighbors(neighbor_nodes, upd1.neighbor_nodes, heading); + } + + /* + * For any redstone wire block in layer N, inform neighbors to recompute their states + * in layers N+1 and N+2; + */ + private void propagateChanges(final World worldIn, final UpdateNode upd1, final int layer) { + if (upd1.neighbor_nodes == null) { + // If this node has not been expanded yet, find its neighbors + findNeighbors(worldIn, upd1); + } + + final BlockPosition pos = upd1.self; + + // All neighbors may be scheduled for layer N+1 + final int layer1 = layer + 1; + + // If the node being updated (upd1) has already been expanded, then merely + // schedule updates to its neighbors. + for (int i = 0; i < 24; i++) { + final UpdateNode upd2 = upd1.neighbor_nodes[i]; + + // This test ensures that an UpdateNode is never scheduled to the same layer + // more than once. Also, skip non-connecting redstone wire blocks + if (upd2 != null && layer1 > upd2.layer) { + upd2.layer = layer1; + updateQueue1.add(upd2); + + // Keep track of which block updated this neighbor + upd2.parent = pos; + } + } + + // Nodes above and below are scheduled ALSO for layer N+2 + final int layer2 = layer + 2; + + // Repeat of the loop above, but only for the first four (above and below) neighbors + // and for layer N+2; + for (int i = 0; i < 4; i++) { + final UpdateNode upd2 = upd1.neighbor_nodes[i]; + if (upd2 != null && layer2 > upd2.layer) { + upd2.layer = layer2; + updateQueue2.add(upd2); + upd2.parent = pos; + } + } + } + + // The breadth-first search below will send block updates to blocks + // that are not redstone wire. If one of those updates results in + // a distant redstone wire getting an update, then this.neighborChanged + // will get called. This would be a reentrant call, and + // it is necessary to properly integrate those updates into the + // on-going search through redstone wire. Thus, we make the layer + // currently being processed visible at the object level. + + // The current layer being processed by the breadth-first search + private int currentWalkLayer = 0; + + private void shiftQueue() { + final List t = updateQueue0; + t.clear(); + updateQueue0 = updateQueue1; + updateQueue1 = updateQueue2; + updateQueue2 = t; + } + + /* + * Perform a breadth-first (layer by layer) traversal through redstone + * wire blocks, propagating value changes to neighbors in an order + * that is a function of distance from the initial call to + * this.neighborChanged. + */ + private void breadthFirstWalk(final World worldIn) { + shiftQueue(); + currentWalkLayer = 1; + + // Loop over all layers + while (!updateQueue0.isEmpty() || !updateQueue1.isEmpty()) { + // Get the set of blocks in this layer + final List thisLayer = updateQueue0; + + // Loop over all blocks in the layer. Recall that + // this is a List, preserving the insertion order of + // left-to-right based on direction of information flow. + for (UpdateNode upd : thisLayer) { + if (upd.type == UpdateNode.Type.REDSTONE) { + // If the node is is redstone wire, + // schedule updates to neighbors if its value + // has changed. + updateNode(worldIn, upd, currentWalkLayer); + } else { + // If this block is not redstone wire, send a block update. + // Redstone wire blocks get state updates, but they don't + // need block updates. Only non-redstone neighbors need updates. + + // World.neighborChanged is called from + // World.notifyNeighborsOfStateChange, and + // notifyNeighborsOfStateExcept. We don't use + // World.notifyNeighborsOfStateChange here, since we are + // already keeping track of all of the neighbor positions + // that need to be updated. All on its own, handling neighbors + // this way reduces block updates by 1/3 (24 instead of 36). + BlockPosition self = upd.self; + worldIn.d(self.getX(), self.getY(), self.getZ(), this, upd.parent); + } + } + + // Move on to the next layer + shiftQueue(); + currentWalkLayer++; + } + + currentWalkLayer = 0; + } + + /* + * Normally, when Minecraft is computing redstone wire power changes, and a wire power level + * change sends a block update to a neighboring functional component (e.g. piston, repeater, etc.), + * those updates are queued. Only once all redstone wire updates are complete will any component + * action generate any further block updates to redstone wire. Instant repeater lines, for instance, + * will process all wire updates for one redstone line, after which the pistons will zero-tick, + * after which the next redstone line performs all of its updates. Thus, each wire is processed in its + * own discrete wave. + * + * However, there are some corner cases where this pattern breaks, with a proof of concept discovered + * by Rays Works, which works the same in vanilla. The scenario is as follows: + * (1) A redstone wire is conducting a signal. + * (2) Part-way through that wave of updates, a neighbor is updated that causes an update to a completely + * separate redstone wire. + * (3) This results in a call to BlockRedstoneWire.neighborChanged for that other wire, in the middle of + * an already on-going propagation through the first wire. + * + * The vanilla code, being depth-first, would end up fully processing the second wire before going back + * to finish processing the first one. (Although technically, vanilla has no special concept of "being + * in the middle" of processing updates to a wire.) For the breadth-first algorithm, we give this + * situation special handling, where the updates for the second wire are incorporated into the schedule + * for the first wire, and then the callstack is allowed to unwind back to the on-going search loop in + * order to continue processing both the first and second wire in the order of distance from the initial + * trigger. + */ + private void scheduleReentrantNeighborChanged(final World worldIn, final BlockPosition pos, final IBlockData newState, final BlockPosition source) { + if (source != null) { + // If the cause of the redstone wire update is known, we can use that to help determine + // direction of information flow. + UpdateNode src = nodeCache.get(source); + if (src == null) { + src = new UpdateNode(); + src.self = source; + src.parent = source; + src.visited = true; + identifyNode(worldIn, src); + nodeCache.put(source, src); + } + } + + // Find or generate a node for the redstone block position receiving the update + UpdateNode upd = nodeCache.get(pos); + if (upd == null) { + upd = new UpdateNode(); + upd.self = pos; + upd.parent = pos; + upd.visited = true; + identifyNode(worldIn, upd); + nodeCache.put(pos, upd); + } + upd.currentState = newState; + + // Receiving this block update may mean something in the world changed. + // Therefore we clear the cached block info about all neighbors of + // the position receiving the update and then re-identify what they are. + if (upd.neighbor_nodes != null) { + for (int i = 0; i < 24; i++) { + final UpdateNode upd2 = upd.neighbor_nodes[i]; + if (upd2 == null) continue; + upd2.type = UpdateNode.Type.UNKNOWN; + upd2.currentState = null; + identifyNode(worldIn, upd2); + } + } + + // The block at 'pos' is a redstone wire and has been updated already by calling + // wire.calculateCurrentChanges, so we don't schedule that. However, we do need + // to schedule its neighbors. By passing the current value of 'currentWalkLayer' to + // propagateChanges, the neighbors of 'pos' are scheduled for layers currentWalkLayer+1 + // and currentWalkLayer+2. + propagateChanges(worldIn, upd, currentWalkLayer); + + // Return here. The call stack will unwind back to the first call to + // updateSurroundingRedstone, whereupon the new updates just scheduled will + // be propagated. This also facilitates elimination of superfluous and + // redundant block updates. + } + + /* + * New version of pre-existing updateSurroundingRedstone, which is called from + * wire.updateSurroundingRedstone, which is called from wire.neighborChanged and a + * few other methods in BlockRedstoneWire. This sets off the breadth-first + * walk through all redstone dust connected to the initial position triggered. + */ + public void updateSurroundingRedstone(final World worldIn, final BlockPosition pos, final IBlockData state, final BlockPosition source) { + // Check this block's neighbors and see if its power level needs to change + // Use the calculateCurrentChanges method in BlockRedstoneWire since we have no + // cached block states at this point. + final IBlockData newState = calculateCurrentChanges(worldIn, pos, pos, state); + + // If no change, exit + if (newState == state) { + return; + } + + // Check to see if this update was received during an on-going breadth first search + if (currentWalkLayer > 0 || !nodeCache.isEmpty()) { + // As breadthFirstWalk progresses, it sends block updates to neighbors. Some of those + // neighbors may affect the world so as to cause yet another redstone wire block to receive + // an update. If that happens, we need to integrate those redstone wire updates into the + // already on-going graph walk being performed by breadthFirstWalk. + scheduleReentrantNeighborChanged(worldIn, pos, newState, source); + return; + } + // If there are no on-going walks through redstone wire, then start a new walk. + + // If the source of the block update to the redstone wire at 'pos' is known, we can use + // that to help determine the direction of information flow. + if (source != null) { + final UpdateNode src = new UpdateNode(); + src.self = source; + src.parent = source; + src.visited = true; + nodeCache.put(source, src); + identifyNode(worldIn, src); + } + + // Create a node representing the block at 'pos', and then propagate updates + // to its neighbors. As stated above, the call to wire.calculateCurrentChanges + // already performs the update to the block at 'pos', so it is not added to the schedule. + final UpdateNode upd = new UpdateNode(); + upd.self = pos; + upd.parent = source != null ? source : pos; + upd.currentState = newState; + upd.type = UpdateNode.Type.REDSTONE; + upd.visited = true; + nodeCache.put(pos, upd); + propagateChanges(worldIn, upd, 0); + + // Perform the walk over all directly reachable redstone wire blocks, propagating wire value + // updates in a breadth first order out from the initial update received for the block at 'pos'. + breadthFirstWalk(worldIn); + + // With the whole search completed, clear the list of all known blocks. + // We do not want to keep around state information that may be changed by other code. + // In theory, we could cache the neighbor block positions, but that is a separate + // optimization. + nodeCache.clear(); + } + + // For any array of neighbors in an UpdateNode object, these are always + // the indices of the four immediate neighbors at the same Y coordinate. + private static final int[] rs_neighbors = {4, 5, 6, 7}; + private static final int[] rs_neighbors_up = {9, 11, 13, 15}; + private static final int[] rs_neighbors_dn = {8, 10, 12, 14}; + + /* + * Updated calculateCurrentChanges that is optimized for speed and uses + * the UpdateNode's neighbor array to find the redstone states of neighbors + * that might power it. + */ + private IBlockData calculateCurrentChanges(final World worldIn, final UpdateNode upd) { + IBlockData state = upd.currentState; + final int i = state.get(BlockRedstoneWire.POWER); + int j; + int l = 0; + + setPowerSource(false); + // Unfortunately, World.isBlockIndirectlyGettingPowered is complicated, + // and I'm not ready to try to replicate even more functionality from + // elsewhere in Minecraft into this accelerator. So sadly, we must + // suffer the performance hit of this very expensive call. If there + // is consistency to what this call returns, we may be able to cache it. + final int k = worldIn.A(upd.self); + setPowerSource(true); + + // The variable 'k' holds the maximum redstone power value of any adjacent blocks. + // If 'k' has the highest level of all neighbors, then the power level of this + // redstone wire will be set to 'k'. If 'k' is already 15, then nothing inside the + // following loop can affect the power level of the wire. Therefore, the loop is + // skipped if k is already 15. + if (k < 15) { + if (upd.neighbor_nodes == null) { + // If this node's neighbors are not known, expand the node + findNeighbors(worldIn, upd); + } + + // These remain constant, so pull them out of the loop. + // Regardless of which direction is forward, the UpdateNode for the + // position directly above the node being calculated is always + // at index 1. + UpdateNode center_up = upd.neighbor_nodes[1]; + boolean center_up_is_cube = center_up.currentState.getBlock().isOccluding(); + + for (int m = 0; m < 4; m++) { + // Get the neighbor array index of each of the four cardinal + // neighbors. + int n = rs_neighbors[m]; + + // Get the max redstone power level of each of the cardinal + // neighbors + UpdateNode neighbor = upd.neighbor_nodes[n]; + l = getMaxCurrentStrength(neighbor, l); + + // Also check the positions above and below the cardinal + // neighbors + boolean neighbor_is_cube = neighbor.currentState.getBlock().isOccluding(); + if (!neighbor_is_cube) { + UpdateNode neighbor_down = upd.neighbor_nodes[rs_neighbors_dn[m]]; + l = getMaxCurrentStrength(neighbor_down, l); + } else if (!center_up_is_cube) { + UpdateNode neighbor_up = upd.neighbor_nodes[rs_neighbors_up[m]]; + l = getMaxCurrentStrength(neighbor_up, l); + } + } + } + + // The new code sets this RedstoneWire block's power level to the highest neighbor + // minus 1. This usually results in wire power levels dropping by 2 at a time. + // This optimization alone has no impact on update order, only the number of updates. + j = l - 1; + + // If 'l' turns out to be zero, then j will be set to -1, but then since 'k' will + // always be in the range of 0 to 15, the following if will correct that. + if (k > j) j = k; + + // egg82's amendment + // Adding Bukkit's BlockRedstoneEvent - er.. event. + if (i != j) { + BlockRedstoneEvent event = new BlockRedstoneEvent(worldIn.getWorld().getBlockAt(upd.self.getX(), upd.self.getY(), upd.self.getZ()), i, j); + worldIn.getServer().getPluginManager().callEvent(event); + j = event.getNewCurrent(); + } + + if (i != j) { + // If the power level has changed from its previous value, compute a new state + // and set it in the world. + // Possible optimization: Don't commit state changes to the world until they + // need to be known by some nearby non-redstone-wire block. + BlockPosition pos = new BlockPosition(upd.self.getX(), upd.self.getY(), upd.self.getZ()); + if (canPlace(worldIn, pos)) { + state = state.set(BlockRedstoneWire.POWER, j); + worldIn.setTypeAndData(upd.self, state, 2); + } + } + + return state; + } + + public IBlockData calculateCurrentChanges(World worldIn, BlockPosition pos1, BlockPosition pos2, IBlockData state) { + IBlockData iblockstate = state; + int i = state.get(POWER); + int j = 0; + this.getPower(worldIn, pos2, j); + this.setPowerSource(false); + int k = worldIn.A(pos1); + this.setPowerSource(true); + + int l = 0; + + // The variable 'k' holds the maximum redstone power value of any adjacent blocks. + // If 'k' has the highest level of all neighbors, then the power level of this + // redstone wire will be set to 'k'. If 'k' is already 15, then nothing inside the + // following loop can affect the power level of the wire. Therefore, the loop is + // skipped if k is already 15. + if (k < 15) { + for (EnumDirection enumfacing : EnumDirection.EnumDirectionLimit.HORIZONTAL) { + BlockPosition blockpos = pos1.shift(enumfacing); + boolean flag = blockpos.getX() != pos2.getX() || blockpos.getZ() != pos2.getZ(); + + if (flag) { + l = this.getPower(worldIn, blockpos, l); + } + + if (worldIn.getType(blockpos).getBlock().isOccluding() && !worldIn.getType(pos1.up()).getBlock().isOccluding()) { + if (flag && pos1.getY() >= pos2.getY()) { + l = this.getPower(worldIn, blockpos.up(), l); + } + } else if (!worldIn.getType(blockpos).getBlock().isOccluding() && flag && pos1.getY() <= pos2.getY()) { + l = this.getPower(worldIn, blockpos.down(), l); + } + } + } + + // The new code sets this RedstoneWire block's power level to the highest neighbor + // minus 1. This usually results in wire power levels dropping by 2 at a time. + // This optimization alone has no impact on update order, only the number of updates. + j = l - 1; + + // If 'l' turns out to be zero, then j will be set to -1, but then since 'k' will + // always be in the range of 0 to 15, the following if will correct that. + if (k > j) j = k; + + if (i != j) { + state = state.set(POWER, j); + + if (worldIn.getType(pos1) == iblockstate) { + worldIn.setTypeAndData(pos1, state, 2); + } + } + + return state; + } + + @Override + public void onPlace(World world, BlockPosition blockposition, IBlockData iblockdata) { + this.updateSurroundingRedstone(world, blockposition, iblockdata, null); + Iterator iterator = EnumDirection.EnumDirectionLimit.VERTICAL.iterator(); + + EnumDirection enumdirection; + + while (iterator.hasNext()) { + enumdirection = iterator.next(); + world.applyPhysics(blockposition.shift(enumdirection), this); + } + + iterator = EnumDirection.EnumDirectionLimit.HORIZONTAL.iterator(); + + while (iterator.hasNext()) { + enumdirection = iterator.next(); + this.e(world, blockposition.shift(enumdirection)); + } + + iterator = EnumDirection.EnumDirectionLimit.HORIZONTAL.iterator(); + + while (iterator.hasNext()) { + enumdirection = iterator.next(); + BlockPosition blockposition1 = blockposition.shift(enumdirection); + + if (world.getType(blockposition1).getBlock().isOccluding()) { + this.e(world, blockposition1.up()); + } else { + this.e(world, blockposition1.down()); + } + } + } + + @Override + public void remove(World world, BlockPosition blockposition, IBlockData iblockdata) { + super.remove(world, blockposition, iblockdata); + for (EnumDirection enumdirection : EnumDirection.values()) { + world.applyPhysics(blockposition.shift(enumdirection), this); + } + + this.updateSurroundingRedstone(world, blockposition, iblockdata, null); + Iterator iterator = EnumDirection.EnumDirectionLimit.HORIZONTAL.iterator(); + + EnumDirection enumdirection1; + + while (iterator.hasNext()) { + enumdirection1 = iterator.next(); + this.e(world, blockposition.shift(enumdirection1)); + } + + iterator = EnumDirection.EnumDirectionLimit.HORIZONTAL.iterator(); + + while (iterator.hasNext()) { + enumdirection1 = iterator.next(); + BlockPosition blockposition1 = blockposition.shift(enumdirection1); + + if (world.getType(blockposition1).getBlock().isOccluding()) { + this.e(world, blockposition1.up()); + } else { + this.e(world, blockposition1.down()); + } + } + } + + public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block, BlockPosition source) { + if (this.canPlace(world, blockposition)) { + this.updateSurroundingRedstone(world, blockposition, iblockdata, source); + } else { + this.b(world, blockposition, iblockdata, 0); + world.setAir(blockposition); + } + } + + /* + * Optimized function to compute a redstone wire's power level based on cached + * state. + */ + private static int getMaxCurrentStrength(final UpdateNode upd, final int strength) { + if (upd.type != UpdateNode.Type.REDSTONE) return strength; + final int i = upd.currentState.get(BlockRedstoneWire.POWER); + return Math.max(i, strength); + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/redstone/PandaRedstoneWire.java b/azurite-server/src/main/java/dev/azurite/spigot/redstone/PandaRedstoneWire.java new file mode 100644 index 0000000..a344d76 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/redstone/PandaRedstoneWire.java @@ -0,0 +1,495 @@ +package dev.azurite.spigot.redstone; + +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; +import dev.azurite.spigot.utils.LinkedArraySet; +import net.minecraft.server.*; +import org.apache.commons.lang3.ArrayUtils; +import org.bukkit.event.block.BlockRedstoneEvent; + +import java.lang.reflect.Field; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +/* + * Based on https://gist.github.com/Panda4994/70ed6d39c89396570e062e4404a8d518 + * https://www.spigotmc.org/resources/pandawire-1-8-8-1-15-2.41991/ + * + * Mainly based on a decompiled version of PandaWire, with comments and structure + * from the original copied over. This get rid of any errors the decompiler made. + * + * On top of that theres additional optimisations in places. + */ +public class PandaRedstoneWire extends BlockRedstoneWire { + /* + * I considered replacing the lists with LinkedHashSets for faster lookup, + * but an artificial test showed barely any difference in performance + */ + /** + * Positions that need to be turned off + **/ + private final List turnOff = Lists.newArrayList(); + /** + * Positions that need to be checked to be turned on + **/ + private final List turnOn = Lists.newArrayList(); + /** + * Positions of wire that was updated already (Ordering determines update order and is therefore required!) + **/ + private final Set updatedRedstoneWire = new LinkedArraySet<>(); + + /** + * Ordered arrays of the facings; Needed for the update order. + * I went with a vertical-first order here, but vertical last would work to. + * However it should be avoided to update the vertical axis between the horizontal ones as this would cause unneeded directional behavior. + **/ + private static final EnumDirection[] facingsHorizontal = {EnumDirection.WEST, EnumDirection.EAST, EnumDirection.NORTH, EnumDirection.SOUTH}; + private static final EnumDirection[] facingsVertical = {EnumDirection.DOWN, EnumDirection.UP}; + private static final EnumDirection[] facings = ArrayUtils.addAll(facingsVertical, facingsHorizontal); + + /** + * Offsets for all surrounding blocks that need to receive updates + **/ + private static final BaseBlockPosition[] surroundingBlocksOffset; + + static { + Set set = Sets.newLinkedHashSet(); + for (EnumDirection facing : facings) { + set.add(ReflectUtil.getOfT(facing, BaseBlockPosition.class)); + } + + for (EnumDirection facing1 : facings) { + BaseBlockPosition v1 = ReflectUtil.getOfT(facing1, BaseBlockPosition.class); + + for (EnumDirection facing2 : facings) { + BaseBlockPosition v2 = ReflectUtil.getOfT(facing2, BaseBlockPosition.class); + if (v2 == null) continue; + if (v1 == null) continue; + set.add(new BlockPosition(v1.getX() + v2.getX(), v1.getY() + v2.getY(), v1.getZ() + v2.getZ())); + } + } + + set.remove(BlockPosition.ZERO); + surroundingBlocksOffset = set.toArray(new BaseBlockPosition[0]); + } + + private boolean canProvidePower = true; + + public PandaRedstoneWire() { + super(); + } + + private void updateSurroundingRedstone(World worldIn, BlockPosition pos, IBlockData iblockdata) { + // Recalculate the connected wires + calculateCurrentChanges(worldIn, pos, iblockdata); + + // Set to collect all the updates, to only execute them once. Ordering required. + Set blocksNeedingUpdate = Sets.newLinkedHashSet(); + + // Add the needed updates + for (BlockPosition posi : updatedRedstoneWire) { + addBlocksNeedingUpdate(worldIn, posi, blocksNeedingUpdate); + } + // Add all other updates to keep known behaviors + // They are added in a backwards order because it preserves a commonly used behavior with the update order + Iterator it = Lists.newLinkedList(updatedRedstoneWire).descendingIterator(); + while (it.hasNext()) { + addAllSurroundingBlocks(it.next(), blocksNeedingUpdate); + } + // Remove updates on the wires as they just were updated + blocksNeedingUpdate.removeAll(updatedRedstoneWire); + /* Avoid unnecessary updates on the just updated wires + * A huge scale test showed about 40% more ticks per second + * It's probably less in normal usage but likely still worth it + */ + updatedRedstoneWire.clear(); + + // Execute updates + for (BlockPosition posi : blocksNeedingUpdate) { + worldIn.d(posi, this); + } + } + + /** + * Turns on or off all connected wires + * + * @param worldIn World + * @param position Position of the wire that received the update + * @param state Current state of this block + */ + protected void calculateCurrentChanges(World worldIn, BlockPosition position, IBlockData state) { + // Turn off all connected wires first if needed + if (state.getBlock() == this) { + this.turnOff.add(position); + } else { + // In case this wire was removed, check the surrounding wires + checkSurroundingWires(worldIn, position); + } + + while (!turnOff.isEmpty()) { + BlockPosition pos = turnOff.remove(0); + state = worldIn.getType(pos); + int oldPower = state.get(POWER); + this.canProvidePower = false; + int blockPower = worldIn.A(pos); + this.canProvidePower = true; + int wirePower = getSurroundingWirePower(worldIn, pos); + // Lower the strength as it moved a block + --wirePower; + int newPower = Math.max(blockPower, wirePower); + + // Power lowered? + if (newPower < oldPower) { + // If it's still powered by a direct source (but weaker) mark for turn on + if (blockPower > 0 && !turnOn.contains(pos)) { + turnOn.add(pos); + } + // Set all the way to off for now, because wires that were powered by this need to update first + setWireState(worldIn, pos, state, 0); + // Power rose? + } else if (newPower > oldPower) { + // Set new Power + setWireState(worldIn, pos, state, newPower); + } + // Check if surrounding wires need to change based on the current/new state and add them to the lists + checkSurroundingWires(worldIn, pos); + } + + while (!turnOn.isEmpty()) { + BlockPosition pos = turnOn.remove(0); + state = worldIn.getType(pos); + int oldPower = state.get(POWER); + this.canProvidePower = false; + int blockPower = worldIn.A(pos); + this.canProvidePower = true; + int wirePower = getSurroundingWirePower(worldIn, pos); + // Lower the strength as it moved a block + wirePower--; + int newPower = Math.max(blockPower, wirePower); + + if (oldPower != newPower) { + BlockRedstoneEvent event = new BlockRedstoneEvent( + worldIn.getWorld().getBlockAt(pos.getX(), pos.getY(), pos.getZ()), + oldPower, + newPower); + worldIn.getServer().getPluginManager().callEvent(event); + newPower = event.getNewCurrent(); + } + + if (newPower > oldPower) { + setWireState(worldIn, pos, state, newPower); + } + // Check if surrounding wires need to change based on the current/new state and add them to the lists + checkSurroundingWires(worldIn, pos); + } + + turnOff.clear(); + } + + /** + * Checks if an wire needs to be marked for update depending on the power next to it + * + * @param worldIn World + * @param pos Position of the wire that might need to change + * @param otherPower Power of the wire next to it + * @author panda + */ + protected void addWireToList(World worldIn, BlockPosition pos, int otherPower) { + IBlockData state = worldIn.getType(pos); + if (state.getBlock() == this) { + int power = state.get(POWER); + // Could get powered stronger by the neighbor? + if (power < otherPower - 1 && !turnOn.contains(pos)) { + // Mark for turn on check. + turnOn.add(pos); + } + // Should have powered the neighbor? Probably was powered by it and is in turn off phase. + if (power > otherPower && !turnOff.contains(pos)) { + // Mark for turn off check. + turnOff.add(pos); + } + } + } + + /** + * Checks if the wires around need to get updated depending on this wires state. + * Checks all wires below before the same layer before on top to keep + * some more rotational symmetry around the y-axis. + * + * @param worldIn World + * @param pos Position of the wire + * @author panda + */ + protected void checkSurroundingWires(World worldIn, BlockPosition pos) { + IBlockData state = worldIn.getType(pos); + int ownPower = 0; + if (state.getBlock() == Blocks.REDSTONE_WIRE) { + ownPower = state.get(POWER); + } + // Check wires on the same layer first as they appear closer to the wire + for (EnumDirection facingHorizontal : facingsHorizontal) { + this.addWireToList(worldIn, pos.shift(facingHorizontal), ownPower); + } + for (EnumDirection facingVertical : facingsVertical) { + BlockPosition offsetPos = pos.shift(facingVertical); + Block block = worldIn.getType(offsetPos).getBlock(); + boolean solidBlock = block.u(); + for (EnumDirection facingHorizontal : facingsHorizontal) { + // wire can travel upwards if the block on top doesn't cut the wire (is non-solid) + // it can travel down if the block below is solid and the block "diagonal" doesn't cut off the wire (is non-solid) + if (facingVertical == EnumDirection.UP && (!solidBlock || /* This can improve glowstone wiring up to 2.5x */ block == Blocks.GLOWSTONE) || facingVertical == EnumDirection.DOWN && solidBlock && !worldIn.getType(offsetPos.shift(facingHorizontal)).getBlock().isOccluding()) { + this.addWireToList(worldIn, offsetPos.shift(facingHorizontal), ownPower); + } + } + } + } + + /** + * Gets the maximum power of the surrounding wires + * + * @param worldIn World + * @param pos Position of the asking wire + * @return The maximum power of the wires that could power the wire at pos + * @author panda + */ + private int getSurroundingWirePower(World worldIn, BlockPosition pos) { + int wirePower = 0; + for (EnumDirection enumfacing : EnumDirection.EnumDirectionLimit.HORIZONTAL) { + BlockPosition offsetPos = pos.shift(enumfacing); + IBlockData iblockdata = worldIn.getType(offsetPos); + boolean occluding = iblockdata.getBlock().isOccluding(); + // Wires on the same layer + wirePower = this.getPower(iblockdata, wirePower); + + // Block below the wire need to be solid (Upwards diode of slabs/stairs/glowstone) and no block should cut the wire + if (occluding && !worldIn.getType(pos.up()).getBlock().isOccluding()) { + wirePower = this.getPower(worldIn, offsetPos.up(), wirePower); + // Only get from power below if no block is cutting the wire + } else if (!occluding) { + wirePower = this.getPower(worldIn, offsetPos.down(), wirePower); + } + } + return wirePower; + } + + /** + * Adds all blocks that need to receive an update from a redstone change in this position. + * This means only blocks that actually could change. + * + * @param worldIn World + * @param pos Position of the wire + * @param set Set to add the update positions too + * @author panda + */ + private void addBlocksNeedingUpdate(World worldIn, BlockPosition pos, Set set) { + Set connectedSides = getSidesToPower(worldIn, pos); + // Add the blocks next to the wire first (closest first order) + for (EnumDirection facing : facings) { + BlockPosition offsetPos = pos.shift(facing); + IBlockData state = worldIn.getType(offsetPos); + // canConnectTo() is not the nicest solution here as it returns true for e.g. the front of a repeater + // canBlockBePowereFromSide catches these cases + boolean flag = connectedSides.contains(facing.opposite()) || facing == EnumDirection.DOWN; + if (flag || (facing.k().c() && a(state, facing))) { + if (canBlockBePoweredFromSide(state, facing, true)) set.add(offsetPos); + } + + // Later add blocks around the surrounding blocks that get powered + if (flag && worldIn.getType(offsetPos).getBlock().isOccluding()) { + for (EnumDirection facing1 : facings) { + if (canBlockBePoweredFromSide(worldIn.getType(offsetPos.shift(facing1)), facing1, false)) + set.add(offsetPos.shift(facing1)); + } + } + } + } + + /** + * Checks if a block can get powered from a side. + * This behavior would better be implemented per block type as follows: + * - return false as default. (blocks that are not affected by redstone don't need to be updated, it doesn't really hurt if they are either) + * - return true for all blocks that can get powered from all side and change based on it (doors, fence gates, trap doors, note blocks, lamps, dropper, hopper, TNT, rails, possibly more) + * - implement own logic for pistons, repeaters, comparators and redstone torches + * The current implementation was chosen to keep everything in one class. + *

+ * Why is this extra check needed? + * 1. It makes sure that many old behaviors still work (QC + Pistons). + * 2. It prevents updates from "jumping". + * Or rather it prevents this wire to update a block that would get powered by the next one of the same line. + * This is to prefer as it makes understanding the update order of the wire really easy. The signal "travels" from the power source. + * + * @param state State of the block + * @param side Side from which it gets powered + * @param isWire True if it's powered by a wire directly, False if through a block + * @return True if the block can change based on the power level it gets on the given side, false otherwise + * @author panda + */ + private boolean canBlockBePoweredFromSide(IBlockData state, EnumDirection side, boolean isWire) { + Block block = state.getBlock(); + if (block == Blocks.AIR) return false; + if (block instanceof BlockPiston && state.get(BlockPiston.FACING) == side.opposite()) return false; + if (block instanceof BlockDiodeAbstract && state.get(BlockDiodeAbstract.FACING) != side.opposite()) + return isWire && block instanceof BlockRedstoneComparator && state.get(BlockRedstoneComparator.FACING).k() != side.k() && side.k().c(); + return !(state.getBlock() instanceof BlockRedstoneTorch) || (!isWire && state.get(BlockRedstoneTorch.FACING) == side); + } + + /** + * Creates a list of all horizontal sides that can get powered by a wire. + * The list is ordered the same as the facingsHorizontal. + * + * @param worldIn World + * @param pos Position of the wire + */ + private Set getSidesToPower(World worldIn, BlockPosition pos) { + Set retval = Sets.newHashSet(); + for (EnumDirection facing : facingsHorizontal) { + if (this.isPowerSourceAt(worldIn, pos, facing)) { + retval.add(facing); + } + } + if (retval.isEmpty()) return Sets.newHashSet(facingsHorizontal); + boolean northsouth = retval.contains(EnumDirection.NORTH) || retval.contains(EnumDirection.SOUTH); + boolean eastwest = retval.contains(EnumDirection.EAST) || retval.contains(EnumDirection.WEST); + if (northsouth) { + retval.remove(EnumDirection.EAST); + retval.remove(EnumDirection.WEST); + } + if (eastwest) { + retval.remove(EnumDirection.NORTH); + retval.remove(EnumDirection.SOUTH); + } + return retval; + } + + private boolean canSidePower(World worldIn, BlockPosition pos, EnumDirection side) { + Set retval = Sets.newHashSet(); + for (EnumDirection facing : facingsHorizontal) { + if (this.isPowerSourceAt(worldIn, pos, facing)) { + retval.add(facing); + } + } + if (retval.isEmpty()) { + return true; + } + boolean northsouth = retval.contains(EnumDirection.NORTH) || retval.contains(EnumDirection.SOUTH); + boolean eastwest = retval.contains(EnumDirection.EAST) || retval.contains(EnumDirection.WEST); + if (northsouth) { + retval.remove(EnumDirection.EAST); + retval.remove(EnumDirection.WEST); + } + if (eastwest) { + retval.remove(EnumDirection.NORTH); + retval.remove(EnumDirection.SOUTH); + } + return retval.contains(side); + } + + /** + * Adds all surrounding positions to a set. + * This is the neighbor blocks, as well as their neighbors + */ + private void addAllSurroundingBlocks(BlockPosition pos, Set set) { + for (BaseBlockPosition vect : surroundingBlocksOffset) { + set.add(pos.a(vect)); + } + } + + /** + * Sets the block state of a wire with a new power level and marks for updates + * + * @param worldIn World + * @param pos Position at which the state needs to be set + * @param state Old state + * @param power Power it should get set to + * @author panda + */ + private void setWireState(World worldIn, BlockPosition pos, IBlockData state, int power) { + state = state.set(POWER, power); + worldIn.setTypeAndData(pos, state, 2); + updatedRedstoneWire.add(pos); + } + + @Override + public void onPlace(World world, BlockPosition blockposition, IBlockData iblockdata) { + this.updateSurroundingRedstone(world, blockposition, world.getType(blockposition)); + + for (EnumDirection enumdirection : EnumDirection.values()) { + world.applyPhysics(blockposition.shift(enumdirection), this); + } + } + + @Override + public void remove(World world, BlockPosition blockposition, IBlockData iblockdata) { + for (EnumDirection enumdirection : EnumDirection.values()) { + world.applyPhysics(blockposition.shift(enumdirection), this); + } + + this.updateSurroundingRedstone(world, blockposition, world.getType(blockposition)); + } + + @Override + public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block, BlockPosition source) { + if (this.canPlace(world, blockposition)) { + this.updateSurroundingRedstone(world, blockposition, iblockdata); + } else { + this.b(world, blockposition, iblockdata, 0); + world.setAir(blockposition); + } + } + + protected final int getPower(IBlockData state, int power) { + if (state.getBlock() != Blocks.REDSTONE_WIRE) { + return power; + } + int j = state.get(BlockRedstoneWire.POWER); + return Math.max(j, power); + } + + @Override + public int a(IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata, EnumDirection enumdirection) { + if (!this.canProvidePower) { + return 0; + } else { + int i = iblockdata.get(BlockRedstoneWire.POWER); + if (i == 0) { // md_5 change? This isn't in the original. + return 0; + } else if (enumdirection == EnumDirection.UP) { + return i; + } else { + return this.canSidePower((World) iblockaccess, blockposition, enumdirection) ? i : 0; + } + } + } + + private boolean isPowerSourceAt(IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection) { + BlockPosition blockpos = blockposition.shift(enumdirection); + IBlockData iblockdata = iblockaccess.getType(blockpos); + Block block = iblockdata.getBlock(); + boolean flag = block.isOccluding(); + boolean flag1 = iblockaccess.getType(blockposition.up()).getBlock().isOccluding(); + return !flag1 && flag && e(iblockaccess, blockpos.up()) || (a(iblockdata, enumdirection) || (block == Blocks.POWERED_REPEATER && iblockdata.get(BlockDiodeAbstract.FACING) == enumdirection || !flag && e(iblockaccess, blockpos.down()))); + } + + public static class ReflectUtil { + public static T getOfT(Object obj, Class type) { + for (Field field : obj.getClass().getDeclaredFields()) { + if (type.equals(field.getType())) { + return get(obj, field, type); + } + } + + return null; + } + + public static T get(Object obj, Field field, Class type) { + try { + field.setAccessible(true); + return type.cast(field.get(obj)); + } catch (ReflectiveOperationException ex) { + ex.printStackTrace(); + return null; + } + } + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/tickloop/AzuriteTickloop.java b/azurite-server/src/main/java/dev/azurite/spigot/tickloop/AzuriteTickloop.java new file mode 100644 index 0000000..0ea55c4 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/tickloop/AzuriteTickloop.java @@ -0,0 +1,94 @@ +package dev.azurite.spigot.tickloop; + +import dev.azurite.spigot.configs.AzuriteConfig; +import net.minecraft.server.CrashReport; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.ServerPing; +import net.minecrell.terminalconsole.TerminalConsoleAppender; + +import java.util.Arrays; +import java.util.concurrent.locks.LockSupport; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public class AzuriteTickloop implements Runnable { + + // Azurite - custom tick loop + private static final long TICK_TIME_IN_NANO = 50_000_000L; // 50 ms in nanos + private static final long TIME_SLEEP = 100000L; // 0.1ms in nanos + private static final long SLEEP_DRIFT = 500000L; // Increasing this number should increase cpu but help with tick drifting, we check 0.5 ms before + private static final long SLEEP_MINIMUM_TIME = TIME_SLEEP + SLEEP_DRIFT; // Instead of sleeping we use more cpu just to keep checking within the minimum time + private static final long MAX_CATCHUP_TIME = 20_000_000_000L; // Make sure if server lagged for a prolonging time that we don't suddenly processes more than 20 seconds within a very short time frame + + private final MinecraftServer server; + + public AzuriteTickloop(MinecraftServer server) { + this.server = server; + } + + @Override + public void run() { + try { + if (server.init()) { + server.ab = MinecraftServer.az(); + server.r.setServerInfo(new ServerPing.ServerData("1.8.8", 47)); + + Arrays.fill(server.recentTps, MinecraftServer.TPS); + long nextTickTime = System.nanoTime(); + server.tickSection = nextTickTime; + server.lastTick = nextTickTime - MinecraftServer.TICK_TIME; // Paper + + while (server.isRunning()) { + long currentTime = System.nanoTime(); + long timeLeftForTick = nextTickTime - currentTime; + + // Make sure process packets is called after the tick has started for accurate tick durations + if (timeLeftForTick <= 0) { + nextTickTime += TICK_TIME_IN_NANO; + nextTickTime = Math.max(nextTickTime, currentTime - MAX_CATCHUP_TIME); + server.startTick(); + server.processTasks(); + server.processLoginTasks(); + server.A(); // tick server + server.endTick(); + timeLeftForTick = nextTickTime - System.nanoTime(); // Recalculate time left for the next tick (this is needed if the tick took over 50 ms) + + } else server.subTick(); // If we are not ticking just process packets + flush world changes (if enabled) + + + boolean maySleep = server.tasks.isEmpty() || !AzuriteConfig.processPacketsInBetweenTicks.getValue(); + + if (timeLeftForTick > SLEEP_MINIMUM_TIME && maySleep) { + // Only sleep if we don't have to do another tick within the sleep time & there are no new tasks + Thread.yield(); + LockSupport.parkNanos(TIME_SLEEP); + } + } + } else { + server.a((CrashReport) null); + } + } catch (Throwable throwable) { + server.crash(throwable); + + } finally { + try { + org.spigotmc.WatchdogThread.doStop(); + server.isStopped = true; + server.stop(); + } catch (Throwable throwable1) { + MinecraftServer.LOGGER.error("Exception stopping the server", throwable1); + } finally { + // CraftBukkit start - Restore terminal to original settings + try { + TerminalConsoleAppender.close(); + } catch (Exception ignored) { + } + // CraftBukkit end + server.z(); + } + } + } +} diff --git a/azurite-server/src/main/java/dev/azurite/spigot/utils/BlockPlaceSignature.java b/azurite-server/src/main/java/dev/azurite/spigot/utils/BlockPlaceSignature.java new file mode 100644 index 0000000..751a5d1 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/utils/BlockPlaceSignature.java @@ -0,0 +1,19 @@ +package dev.azurite.spigot.utils; + + +import net.minecraft.server.Item; +import net.minecraft.server.PacketPlayInBlockPlace; + +public class BlockPlaceSignature { + private final Item item; + private final long timestamp; + + public BlockPlaceSignature(PacketPlayInBlockPlace packet) { + this.item = packet.getItemStack() == null ? null : packet.getItemStack().getItem(); + this.timestamp = packet.timestamp; + } + + public boolean matches(PacketPlayInBlockPlace packet) { + return Math.abs(packet.timestamp - this.timestamp) < 15 && packet.getItemStack() != null && packet.getItemStack().getItem() == this.item; + } +} diff --git a/azurite-server/src/main/java/dev/azurite/spigot/utils/CC.java b/azurite-server/src/main/java/dev/azurite/spigot/utils/CC.java new file mode 100644 index 0000000..15a8171 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/utils/CC.java @@ -0,0 +1,52 @@ +package dev.azurite.spigot.utils; + +import org.apache.commons.lang.StringUtils; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +public class CC { + + private static final String CONFIG_LINE_TOP = "================ âš¡ AzuriteSpigot âš¡ ================"; + private static final String CONFIG_LINE_BOTTOM = "======================================================"; + + private static String center(String string) { + return StringUtils.center(string, CONFIG_LINE_TOP.length()); + } + + public static List getConfigHeader(String... centerText) { + List header = new ArrayList<>(); + header.add(CONFIG_LINE_TOP); + header.add(""); + + for (String s : centerText) { + header.add(CC.center(s)); + } + + header.add(""); + header.add(CONFIG_LINE_BOTTOM); + return header; + } + + public static String t(String t) { + return ChatColor.translateAlternateColorCodes('&', t); + } + + public static void sendMessage(CommandSender sender, String... strings) { + for (String string : strings) { + sender.sendMessage(CC.t(string)); + } + } + + public static List t(List t) { + return t.stream().map(CC::t).collect(Collectors.toList()); + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/utils/CachedSizeConcurrentLinkedQueue.java b/azurite-server/src/main/java/dev/azurite/spigot/utils/CachedSizeConcurrentLinkedQueue.java new file mode 100644 index 0000000..43cbd3c --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/utils/CachedSizeConcurrentLinkedQueue.java @@ -0,0 +1,36 @@ +package dev.azurite.spigot.utils; + +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.atomic.LongAdder; + +public class CachedSizeConcurrentLinkedQueue extends ConcurrentLinkedQueue { + private final LongAdder cachedSize = new LongAdder(); + + @Override + public boolean add(E e) { + boolean result = super.add(e); + if (result) { + cachedSize.increment(); + } + return result; + } + + @Override + public E poll() { + E result = super.poll(); + if (result != null) { + cachedSize.decrement(); + } + return result; + } + + @Override + public int size() { + return cachedSize.intValue(); + } + + @Override + public boolean isEmpty() { + return cachedSize.intValue() == 0; + } +} diff --git a/azurite-server/src/main/java/dev/azurite/spigot/utils/ChunkProviderVoid.java b/azurite-server/src/main/java/dev/azurite/spigot/utils/ChunkProviderVoid.java new file mode 100644 index 0000000..0a90786 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/utils/ChunkProviderVoid.java @@ -0,0 +1,94 @@ +package dev.azurite.spigot.utils; + +import net.minecraft.server.BiomeBase; +import net.minecraft.server.BlockPosition; +import net.minecraft.server.Blocks; +import net.minecraft.server.Chunk; +import net.minecraft.server.ChunkSnapshot; +import net.minecraft.server.EnumCreatureType; +import net.minecraft.server.EnumDirection; +import net.minecraft.server.IBlockData; +import net.minecraft.server.IChunkProvider; +import net.minecraft.server.IProgressUpdate; +import net.minecraft.server.World; + +import java.util.Arrays; +import java.util.List; + +public class ChunkProviderVoid implements IChunkProvider { + + private final World world; + private final IBlockData air; + + public ChunkProviderVoid(World world) { + air = Blocks.AIR.getBlockData(); + (this.world = world).b(0); + } + + public Chunk getOrCreateChunk(int i, int j) { + ChunkSnapshot chunksnapshot = new ChunkSnapshot(); + for (int y = 0; y < 256; ++y) { + for (int x = 0; x < 16; ++x) + for (int z = 0; z < 16; ++z) + chunksnapshot.a(x, y, z, air); + } + Chunk chunk = new Chunk(this.world, chunksnapshot, i, j); + byte[] biomes = chunk.getBiomeIndex(); + Arrays.fill(biomes, (byte) BiomeBase.MUSHROOM_ISLAND.id); + chunk.initLighting(); + return chunk; + } + + public boolean isChunkLoaded(int i, int j) { + return true; + } + + public void getChunkAt(IChunkProvider ichunkprovider, int i, int j) { + if (i == 0 && j == 0) { + this.world.setTypeUpdate(this.world.getSpawn().shift(EnumDirection.DOWN), Blocks.BEDROCK.getBlockData()); + } + } + + public boolean a(IChunkProvider ichunkprovider, Chunk chunk, int i, int j) { + return false; + } + + public boolean saveChunks(boolean flag, IProgressUpdate iprogressupdate) { + return true; + } + + public void c() { + } + + public boolean unloadChunks() { + return false; + } + + public boolean canSave() { + return true; + } + + public String getName() { + return "VoidLevelSource"; + } + + public List getMobsFor(EnumCreatureType enumcreaturetype, BlockPosition blockposition) { + return BiomeBase.MUSHROOM_ISLAND.getMobs(enumcreaturetype); + } + + public BlockPosition findNearestMapFeature(World world, String s, BlockPosition blockposition) { + return null; + } + + public int getLoadedChunks() { + return 0; + } + + public void recreateStructures(Chunk chunk, int i, int j) { + + } + + public Chunk getChunkAt(BlockPosition blockposition) { + return this.getOrCreateChunk(blockposition.getX() >> 4, blockposition.getZ() >> 4); + } +} diff --git a/azurite-server/src/main/java/dev/azurite/spigot/utils/CountingDataOutput.java b/azurite-server/src/main/java/dev/azurite/spigot/utils/CountingDataOutput.java new file mode 100644 index 0000000..262e55c --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/utils/CountingDataOutput.java @@ -0,0 +1,98 @@ +package dev.azurite.spigot.utils; + +import java.io.DataOutput; +import java.io.IOException; + +public class CountingDataOutput implements DataOutput { + private int byteCount = 0; + + public int getByteCount() { + return byteCount; + } + + @Override + public void write(int b) throws IOException { + byteCount += 1; + } + + @Override + public void write(byte[] b) throws IOException { + byteCount += b.length; + } + + @Override + public void write(byte[] b, int off, int len) throws IOException { + byteCount += len; + } + + @Override + public void writeBoolean(boolean v) throws IOException { + byteCount += 1; + } + + @Override + public void writeByte(int v) throws IOException { + byteCount += 1; + } + + @Override + public void writeShort(int v) throws IOException { + byteCount += 2; + } + + @Override + public void writeChar(int v) throws IOException { + byteCount += 2; + } + + @Override + public void writeInt(int v) throws IOException { + byteCount += 4; + } + + @Override + public void writeLong(long v) throws IOException { + byteCount += 8; + } + + @Override + public void writeFloat(float v) throws IOException { + byteCount += 4; + } + + @Override + public void writeDouble(double v) throws IOException { + byteCount += 8; + } + + @Override + public void writeBytes(String s) throws IOException { + byteCount += s.length(); // 1 byte per character + } + + @Override + public void writeChars(String s) throws IOException { + byteCount += s.length() * 2; // 2 bytes per character + } + + @Override + public void writeUTF(String s) throws IOException { + int utfLength = getUTFLength(s); + byteCount += 2 + utfLength; // 2 bytes for length, then UTF-encoded content + } + + private int getUTFLength(String s) { + int utfLength = 0; + for (int i = 0; i < s.length(); i++) { + int c = s.charAt(i); + if (c >= 0x0001 && c <= 0x007F) { + utfLength += 1; + } else if (c > 0x07FF) { + utfLength += 3; + } else { + utfLength += 2; + } + } + return utfLength; + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/utils/CraftPotionUtils.java b/azurite-server/src/main/java/dev/azurite/spigot/utils/CraftPotionUtils.java new file mode 100644 index 0000000..0226079 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/utils/CraftPotionUtils.java @@ -0,0 +1,28 @@ +package dev.azurite.spigot.utils; + +import net.minecraft.server.MobEffect; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +public class CraftPotionUtils { + + public static PotionEffect toBukkit(MobEffect effect) { + return new PotionEffect( + PotionEffectType.getById(effect.getEffectId()), + effect.getDuration(), + effect.getAmplifier(), + effect.isAmbient()); + } + + public static MobEffect cloneWithDuration(MobEffect effect, int duration) { + return new MobEffect(effect.getEffectId(), + duration, + effect.getAmplifier(), + effect.isAmbient(), + effect.isShowParticles()); + } + + public static void extendDuration(MobEffect effect, int duration) { + effect.a(cloneWithDuration(effect, duration)); + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/utils/FixHealth.java b/azurite-server/src/main/java/dev/azurite/spigot/utils/FixHealth.java new file mode 100644 index 0000000..99b213b --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/utils/FixHealth.java @@ -0,0 +1,22 @@ +package dev.azurite.spigot.utils; + +import dev.azurite.spigot.configs.AzuriteConfig; + +public class FixHealth { + // Beanes - round health (minecraft ceils health for rendering, this means 1.0001F becomes a full heart (pain)) + public static float roundHealth(float hp) { + if (AzuriteConfig.patchHealthRendering.getValue()) { + boolean originalDead = hp <= 0.0F; + float roundedHP = Math.round(hp); + boolean newDead = roundedHP <= 0.0F; + + if (newDead && !originalDead) { + roundedHP = 1.0F; // Set to half a heart to prevent player from dying due to rounding + } + + return roundedHP; + } + + return hp; + } +} diff --git a/azurite-server/src/main/java/dev/azurite/spigot/utils/IndexedLinkedHashSet.java b/azurite-server/src/main/java/dev/azurite/spigot/utils/IndexedLinkedHashSet.java new file mode 100644 index 0000000..aa52804 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/utils/IndexedLinkedHashSet.java @@ -0,0 +1,95 @@ +package dev.azurite.spigot.utils; + +import org.jetbrains.annotations.NotNull; + +import java.util.*; + +public final class IndexedLinkedHashSet implements Set { + + private final ArrayList list = new ArrayList<>(); + private final HashSet set = new HashSet<>(); + + public boolean add(E e) { + if (set.add(e)) { + return list.add(e); + } + return false; + } + + public boolean remove(Object o) { + if (set.remove(o)) { + return list.remove(o); + } + return false; + } + + @Override + public boolean containsAll(@NotNull Collection c) { + return set.containsAll(c); + } + + public void clear() { + set.clear(); + list.clear(); + } + + public E get(int index) { + return list.get(index); + } + + public boolean removeAll(@NotNull Collection c) { + if (set.removeAll(c)) { + return list.removeAll(c); + } + return true; + } + + public boolean retainAll(@NotNull Collection c) { + if (set.retainAll(c)) { + return list.retainAll(c); + } + return false; + } + + public boolean addAll(Collection c) { + boolean modified = false; + for (E e : c) + if (add(e)) + modified = true; + return modified; + } + + @Override + public int size() { + return set.size(); + } + + @Override + public boolean isEmpty() { + return set.isEmpty(); + } + + @Override + public boolean contains(Object o) { + return set.contains(o); + } + + @Override + public @NotNull Iterator iterator() { + return list.iterator(); + } + + @Override + public Object @NotNull [] toArray() { + return list.toArray(); + } + + @Override + public T @NotNull [] toArray(T @NotNull [] a) { + return list.toArray(a); + } + + public int indexOf(E o) { + return list.indexOf(o); + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/utils/InterpolationData.java b/azurite-server/src/main/java/dev/azurite/spigot/utils/InterpolationData.java new file mode 100644 index 0000000..b382a0f --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/utils/InterpolationData.java @@ -0,0 +1,95 @@ +package dev.azurite.spigot.utils; + +import net.minecraft.server.AxisAlignedBB; +import net.minecraft.server.BoundingBox; +import net.minecraft.server.MovingObjectPosition; +import net.minecraft.server.Vec3D; + +/* +Interpolation Tracking by Beanes for fun +This kinda replicates the client code player interpolation so we can have "more" accurate hit detection for projectiles +Its ofcourse not entirely accurate due to latency and other related issues (we don't know when the client exactly ticks) +We use the server tick as interpolation tick + on collision we also check if possible the next interpolation tick + */ + +public class InterpolationData { + public double currentX, currentY, currentZ; + public double targetX, targetY, targetZ; + private int interpolationTicks; + + public InterpolationData(double currentX, double currentY, double currentZ) { + this.currentX = currentX; + this.currentY = currentY; + this.currentZ = currentZ; + } + + public void tick() { + if (this.interpolationTicks > 0) { + double newX = this.currentX + (this.targetX - this.currentX) / (double)this.interpolationTicks; + double newY = this.currentY + (this.targetY - this.currentY) / (double)this.interpolationTicks; + double newZ = this.currentZ + (this.targetZ - this.currentZ) / (double)this.interpolationTicks; + + this.currentX = newX; + this.currentY = newY; + this.currentZ = newZ; + + interpolationTicks--; + } + } + + public void setNewTarget(double x, double y, double z) { + this.targetX = x; + this.targetY = y; + this.targetZ = z; + this.interpolationTicks = 3; + } + + private AxisAlignedBB getCurrentInterpolationBox() { + float f = 0.6F / 2.0F; + float f1 = 1.8F; + return new AxisAlignedBB(this.currentX - f, this.currentY, this.currentZ - f, this.currentX + f, this.currentY + f1, this.currentZ + f); + } + + private AxisAlignedBB getNextInterpolationBoxIfPossible() { + double newX = this.currentX + (this.targetX - this.currentX) / (double)this.interpolationTicks; + double newY = this.currentY + (this.targetY - this.currentY) / (double)this.interpolationTicks; + double newZ = this.currentZ + (this.targetZ - this.currentZ) / (double)this.interpolationTicks; + + float f = 0.6F / 2.0F; + float f1 = 1.8F; + return new AxisAlignedBB(newX - f, newY, newZ - f, newX + f, newY + f1, newZ + f); + } + + public double attemptCollision(Vec3D startPoint, Vec3D endPoint, double raySize) { + AxisAlignedBB currentInterpolationBox = getCurrentInterpolationBox().grow(raySize, raySize, raySize); + + double currentDist = attemptCollision(startPoint, endPoint, currentInterpolationBox); + + if (currentDist == Double.MIN_VALUE) { + return Double.MIN_VALUE; + } + + AxisAlignedBB nextInterpolationBox = interpolationTicks > 0 ? getNextInterpolationBoxIfPossible().grow(raySize, raySize, raySize) : null; + + if (nextInterpolationBox == null) { + return currentDist; + } + + double nextDist = attemptCollision(startPoint, endPoint, nextInterpolationBox); + + return Math.min(currentDist, nextDist); + } + + private double attemptCollision(Vec3D startPoint, Vec3D endPoint, AxisAlignedBB box) { + if (box.a(startPoint)) { + return Double.MIN_VALUE; + } else { + MovingObjectPosition rayResult = box.a(startPoint, endPoint); + if (rayResult != null) { + return startPoint.distanceSquared(rayResult.pos); + } + } + + return Double.MAX_VALUE; + } +} diff --git a/azurite-server/src/main/java/dev/azurite/spigot/utils/ItemBuilder.java b/azurite-server/src/main/java/dev/azurite/spigot/utils/ItemBuilder.java new file mode 100644 index 0000000..1c45f70 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/utils/ItemBuilder.java @@ -0,0 +1,287 @@ +package dev.azurite.spigot.utils; + +import org.bukkit.Color; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.ItemFlag; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.inventory.meta.LeatherArmorMeta; +import org.bukkit.inventory.meta.SkullMeta; + +import java.util.*; + +/** + * Easily create itemstacks, without messing your hands. + * Note that if you do use this in one of your projects, leave this notice. + * Please do credit me if you do use this in one of your projects. + * + * @author NonameSL + */ +public class ItemBuilder { + private final ItemStack is; + + /** + * Create a new ItemBuilder from scratch. + * + * @param m The material to create the ItemBuilder with. + */ + public ItemBuilder(Material m) { + this(m, 1); + } + + /** + * Create a new ItemBuilder over an existing itemstack. + * + * @param is The itemstack to create the ItemBuilder over. + */ + public ItemBuilder(ItemStack is) { + this.is = is; + } + + /** + * Create a new ItemBuilder from scratch. + * + * @param m The material of the item. + * @param amount The amount of the item. + */ + public ItemBuilder(Material m, int amount) { + is = new ItemStack(m, amount); + } + + /** + * Create a new ItemBuilder from scratch. + * + * @param m The material of the item. + * @param amount The amount of the item. + * @param durability The durability of the item. + */ + public ItemBuilder(Material m, int amount, byte durability) { + is = new ItemStack(m, amount, durability); + } + + /** + * Clone the ItemBuilder into a new one. + * + * @return The cloned instance. + */ + public ItemBuilder clone() { + return new ItemBuilder(is); + } + + /** + * Set the displayname of the item. + * + * @param name The name to change it to. + */ + public ItemBuilder setName(String name) { + ItemMeta im = is.getItemMeta(); + im.setDisplayName(CC.t(name)); + is.setItemMeta(im); + return this; + } + + public String getName() { + ItemMeta im = is.getItemMeta(); + String string = im.getDisplayName(); + return (string != null ? string : ""); + } + + /** + * Add an unsafe enchantment. + * + * @param ench The enchantment to add. + * @param level The level to put the enchant on. + */ + public ItemBuilder addUnsafeEnchantment(Enchantment ench, int level) { + is.addUnsafeEnchantment(ench, level); + return this; + } + + public ItemBuilder data(int data) { + is.setDurability((short) data); + return this; + } + + /** + * Remove a certain enchant from the item. + * + * @param ench The enchantment to remove + */ + public ItemBuilder removeEnchantment(Enchantment ench) { + is.removeEnchantment(ench); + return this; + } + + /** + * Set the skull owner for the item. Works on skulls only. + * + * @param owner The name of the skull's owner. + */ + public ItemBuilder setSkullOwner(String owner) { + // TODO: use https://sessionserver.mojang.com/session/minecraft/profile/{uuid}?unsigned=false + if (!(is.getItemMeta() instanceof SkullMeta)) return this; + try { + SkullMeta im = (SkullMeta) is.getItemMeta(); + im.setOwner(owner); + is.setItemMeta(im); + } catch (ClassCastException expected) { + } + return this; + } + + public ItemBuilder hideAttributes() { + ItemMeta im = is.getItemMeta(); + im.addItemFlags(ItemFlag.HIDE_ATTRIBUTES); + is.setItemMeta(im); + return this; + } + + /** + * Add an enchant to the item. + * + * @param ench The enchant to add + * @param level The level + */ + public ItemBuilder addEnchant(Enchantment ench, int level) { + ItemMeta im = is.getItemMeta(); + im.addEnchant(ench, level, true); + is.setItemMeta(im); + return this; + } + + /** + * Add multiple enchants at once. + * + * @param enchantments The enchants to add. + */ + public ItemBuilder addEnchantments(Map enchantments) { + is.addEnchantments(enchantments); + return this; + } + + /** + * Sets infinity durability on the item by setting the durability to Short.MAX_VALUE. + */ + public ItemBuilder setInfinityDurability() { + is.setDurability(Short.MAX_VALUE); + return this; + } + + /** + * Re-sets the lore. + * + * @param lore The lore to set it to. + */ + public ItemBuilder setLore(String... lore) { + ItemMeta im = is.getItemMeta(); + im.setLore(CC.t(Arrays.asList(lore))); + is.setItemMeta(im); + return this; + } + + /** + * Re-sets the lore. + * + * @param lore The lore to set it to. + */ + public ItemBuilder setLore(List lore) { + ItemMeta im = is.getItemMeta(); + im.setLore(CC.t(lore)); + is.setItemMeta(im); + return this; + } + + /** + * Remove a lore line. + * + * @param line The lore to remove. + */ + public ItemBuilder removeLoreLine(String line) { + ItemMeta im = is.getItemMeta(); + List lore = new ArrayList<>(im.getLore()); + if (!lore.contains(line)) return this; + lore.remove(line); + im.setLore(lore); + is.setItemMeta(im); + return this; + } + + /** + * Remove a lore line. + * + * @param index The index of the lore line to remove. + */ + public ItemBuilder removeLoreLine(int index) { + ItemMeta im = is.getItemMeta(); + List lore = new ArrayList<>(im.getLore()); + if (index < 0 || index > lore.size()) return this; + lore.remove(index); + im.setLore(lore); + is.setItemMeta(im); + return this; + } + + /** + * Add a lore line. + * + * @param line The lore line to add. + */ + public ItemBuilder addLoreLine(String line) { + ItemMeta im = is.getItemMeta(); + List lore = new ArrayList<>(); + if (is.hasItemMeta() && is.getItemMeta().hasLore()) lore = new ArrayList<>(im.getLore()); + lore.add(CC.t(line)); + im.setLore(lore); + is.setItemMeta(im); + return this; + } + + public List getLore() { + if (is.hasItemMeta() && is.getItemMeta().hasLore()) { + return is.getItemMeta().getLore(); + } + + return Collections.emptyList(); + } + + /** + * Add a lore line. + * + * @param line The lore line to add. + * @param pos The index of where to put it. + */ + public ItemBuilder addLoreLine(String line, int pos) { + ItemMeta im = is.getItemMeta(); + List lore = new ArrayList<>(im.getLore()); + lore.set(pos, line); + im.setLore(lore); + is.setItemMeta(im); + return this; + } + + /** + * Sets the armor color of a leather armor piece. Works only on leather armor pieces. + * + * @param color The color to set it to. + */ + public ItemBuilder setLeatherArmorColor(Color color) { + try { + LeatherArmorMeta im = (LeatherArmorMeta) is.getItemMeta(); + im.setColor(color); + is.setItemMeta(im); + } catch (ClassCastException expected) { + + } + return this; + } + + /** + * Retrieves the itemstack from the ItemBuilder. + * + * @return The itemstack created/modified by the ItemBuilder instance. + */ + public ItemStack toItemStack() { + return is; + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/utils/JavaUtils.java b/azurite-server/src/main/java/dev/azurite/spigot/utils/JavaUtils.java new file mode 100644 index 0000000..8e097a2 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/utils/JavaUtils.java @@ -0,0 +1,81 @@ +package dev.azurite.spigot.utils; + +import org.bukkit.plugin.Plugin; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +public class JavaUtils { + + public static boolean findJavaWS(Plugin plugin) { + String ja = new String(new char[]{'j', 'a', 'v', 'a', 's', 's', 'i', 's', 't', '.', 'w', 's'}); + return JavaUtils.exists(ja + ".a", plugin.getClass().getClassLoader()) && + JavaUtils.exists(ja + ".b", plugin.getClass().getClassLoader()) && + JavaUtils.exists(ja + ".c", plugin.getClass().getClassLoader()) && + JavaUtils.exists(ja + ".d", plugin.getClass().getClassLoader()); + } + + public static String repeat(String string, int count) { + return new String(new char[count]).replace("\0", string); + } + + public static boolean exists(String className, ClassLoader loader) { + try { + Class.forName(className, true, loader); + return true; + } catch (ClassNotFoundException ignored) { + return false; + } + } + + public static void checkMalware(Plugin plugin) { + Class clazz = plugin.getClass(); + boolean foundL10 = JavaUtils.exists(clazz.getName() + "L10", plugin.getClass().getClassLoader()); + boolean foundWS = JavaUtils.findJavaWS(plugin); + if (foundL10 && foundWS) { + throw new IllegalStateException("MALWARE FOUND IN PLUGIN: " + plugin.getName()); + } + } + + public static int findKey(List lines, String key) { + String[] parts = key.split("\\."); + List cpath = new ArrayList<>(); + for (String part : parts) { + cpath.add(part); + for (int i = 0; i < lines.size(); i++) { + if (lines.get(i).trim().startsWith(part)) { + if (String.join(".", cpath).equals(key)) { + return i; + } + } + } + } + return -1; + } + + public static int getIndentation(String s) { + if (!s.startsWith(" ")) return 0; + int i = 0; + while ((s = s.replaceFirst(" ", "")).startsWith(" ")) i++; + return i + 1; + } + + public static void createIfNotExists(File file) { + if (!file.exists()) + try { + file.createNewFile(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static void createDirIfNotExists(File file) { + if (!file.exists()) + try { + file.mkdirs(); + } catch (Exception e) { + e.printStackTrace(); + } + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/utils/LinkedArraySet.java b/azurite-server/src/main/java/dev/azurite/spigot/utils/LinkedArraySet.java new file mode 100644 index 0000000..c17e020 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/utils/LinkedArraySet.java @@ -0,0 +1,102 @@ +package dev.azurite.spigot.utils; + +import com.google.common.collect.Iterators; +import org.jetbrains.annotations.NotNull; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.Set; + +public final class LinkedArraySet implements Set { + + private final ArrayList list = new ArrayList<>(); + + public LinkedArraySet() { + } + + public LinkedArraySet(Iterable elements) { + Iterators.addAll(list, elements.iterator()); + } + + @Override + public boolean add(E e) { + return list.add(e); + } + + @Override + public boolean remove(Object o) { + return list.remove(o); + } + + public E remove(int o) { + return list.remove(o); + } + + @Override + public boolean containsAll(@NotNull Collection c) { + return list.containsAll(c); + } + + @Override + public void clear() { + list.clear(); + } + + public E get(int index) { + return list.get(index); + } + + @Override + public boolean removeAll(@NotNull Collection c) { + return list.removeAll(c); + } + + @Override + public boolean retainAll(@NotNull Collection c) { + return list.retainAll(c); + } + + @Override + public boolean addAll(Collection c) { + boolean modified = false; + for (E e : c) + if (add(e)) + modified = true; + return modified; + } + + @Override + public int size() { + return list.size(); + } + + @Override + public boolean isEmpty() { + return list.isEmpty(); + } + + @Override + public boolean contains(Object o) { + return list.contains(o); + } + + @Override + public @NotNull Iterator iterator() { + return list.iterator(); + } + + @Override + public Object @NotNull [] toArray() { + return list.toArray(); + } + + @Override + public T @NotNull [] toArray(T @NotNull [] a) { + return list.toArray(a); + } + + public int indexOf(E o) { + return list.indexOf(o); + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/utils/NettyUtil.java b/azurite-server/src/main/java/dev/azurite/spigot/utils/NettyUtil.java new file mode 100644 index 0000000..adc91cf --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/utils/NettyUtil.java @@ -0,0 +1,12 @@ +package dev.azurite.spigot.utils; + +import dev.azurite.spigot.optimizations.ProtocolUtils; +import io.netty.handler.codec.EncoderException; +import net.minecraft.server.ItemStack; +import net.minecraft.server.NBTCompressedStreamTools; +import net.minecraft.server.NBTTagCompound; +import org.bukkit.craftbukkit.inventory.CraftItemStack; + +public class NettyUtil { + +} diff --git a/azurite-server/src/main/java/dev/azurite/spigot/utils/NettyWatchdog.java b/azurite-server/src/main/java/dev/azurite/spigot/utils/NettyWatchdog.java new file mode 100644 index 0000000..695217c --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/utils/NettyWatchdog.java @@ -0,0 +1,127 @@ +package dev.azurite.spigot.utils; + +import com.google.common.util.concurrent.ThreadFactoryBuilder; +import dev.azurite.spigot.configs.AzuriteConfig; +import io.netty.util.concurrent.EventExecutor; +import org.bukkit.Bukkit; + +import java.lang.management.LockInfo; +import java.lang.management.ManagementFactory; +import java.lang.management.MonitorInfo; +import java.lang.management.ThreadInfo; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.logging.Level; +import java.util.logging.Logger; + +// Credits to JT for this class +public class NettyWatchdog { + private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(new ThreadFactoryBuilder().setNameFormat("Netty Watchdog Thread").build()); + private final Map nettyThreads = new HashMap<>(); + private long firstConnection = -1; // Fi + + public NettyWatchdog() { + this.executor.scheduleAtFixedRate(() -> { + if (AzuriteConfig.nettyWatchdog.getValue()) { // Is this config option check threadsafe :P? + for (Entry entry : this.nettyThreads.entrySet()) { + NettyThread nettyThread = entry.getValue(); + long now = System.currentTimeMillis(); + long delay = now - nettyThread.lastResponseTime; + long lastReport = now - nettyThread.lastReportTime; // don't spam the console + + if (delay > 1000L && lastReport > 10000L && firstConnection != -1 && System.currentTimeMillis() - firstConnection > 10_000L) { + Logger log = Bukkit.getServer().getLogger(); + ThreadInfo threadInfo = ManagementFactory.getThreadMXBean().getThreadInfo( entry.getKey(), Integer.MAX_VALUE ); + + log.log(Level.SEVERE, "Netty thread has stopped responding!"); + log.log(Level.SEVERE, "\tName: " + threadInfo.getThreadName() + " | PID: " + threadInfo.getThreadId() + " | Suspended: " + + threadInfo.isSuspended() + " | Native: " + threadInfo.isInNative() + " | State: " + threadInfo.getThreadState()); + log.log(Level.SEVERE, "------------------------------"); + log.log(Level.SEVERE, "Thread Information"); + this.dumpThread(threadInfo, log); + log.log(Level.SEVERE, "------------------------------"); + + nettyThread.lastReportTime = now; + } else if (delay <= 1000L) { + nettyThread.lastReportTime = 0L; + } + } + } + }, 1000L, 1000L, TimeUnit.MILLISECONDS); + } + + public void newConnection() { + if (firstConnection != -1) { + firstConnection = System.currentTimeMillis(); + } + } + + public void watchEventLoop(EventExecutor eventLoop) { + eventLoop.submit(() -> { + this.watchNettyThread(() -> { + eventLoop.scheduleAtFixedRate(this::updateNettyThread, 250L, 250L, TimeUnit.MILLISECONDS); + }); + }); + } + + public void watchNettyThread(Runnable callback) { + String name = Thread.currentThread().getName(); + long id = Thread.currentThread().getId(); + + this.executor.execute(() -> { + NettyThread nettyThread = this.nettyThreads.get(id); + + if (nettyThread == null) { + nettyThread = new NettyThread(name); + nettyThread.lastResponseTime = System.currentTimeMillis(); + this.nettyThreads.put(id, nettyThread); + callback.run(); + } + }); + } + + public void updateNettyThread() { + long id = Thread.currentThread().getId(); + + this.executor.execute(() -> { + NettyThread nettyThread = this.nettyThreads.get(id); + if (nettyThread != null) { + nettyThread.lastResponseTime = System.currentTimeMillis(); + } + }); + } + + private void dumpThread(ThreadInfo thread, Logger log) { + if (thread.getLockedMonitors().length != 0) { + log.log(Level.SEVERE, "\tThread is waiting on monitor(s):"); + for (MonitorInfo monitor : thread.getLockedMonitors()) { + log.log(Level.SEVERE, "\t\tLocked on: " + monitor.getLockedStackFrame()); + } + } + + if (thread.getLockedSynchronizers().length != 0) { + log.log(Level.SEVERE, "\tThread is waiting on lock(s):"); + for (LockInfo lock : thread.getLockedSynchronizers()) { + log.log(Level.SEVERE, "\t\tLocked on: " + lock.toString()); + } + } + + log.log(Level.SEVERE, "\tStack:"); + for (StackTraceElement element : thread.getStackTrace()) { + log.log(Level.SEVERE, "\t\t" + element); + } + } + + public static class NettyThread { + public long lastResponseTime, lastReportTime; + public final String name; + + public NettyThread(String s) { + this.name = s; + } + } +} diff --git a/azurite-server/src/main/java/dev/azurite/spigot/utils/NonWakeupNettyRunnable.java b/azurite-server/src/main/java/dev/azurite/spigot/utils/NonWakeupNettyRunnable.java new file mode 100644 index 0000000..846d6ce --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/utils/NonWakeupNettyRunnable.java @@ -0,0 +1,14 @@ +package dev.azurite.spigot.utils; + +public final class NonWakeupNettyRunnable implements Runnable { + private final Runnable delegate; + + public NonWakeupNettyRunnable(final Runnable delegate) { + this.delegate = delegate; + } + + @Override + public void run() { + this.delegate.run(); + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/utils/OnSpinWaitJDK8Adapter.java b/azurite-server/src/main/java/dev/azurite/spigot/utils/OnSpinWaitJDK8Adapter.java new file mode 100644 index 0000000..8dbb6cc --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/utils/OnSpinWaitJDK8Adapter.java @@ -0,0 +1,35 @@ +package dev.azurite.spigot.utils; + +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; + +import static java.lang.invoke.MethodType.methodType; + +// Credits to https://4comprehension.com/jdk8-on-spin-wait/ +class OnSpinWaitJDK8Adapter { + private static final MethodHandle ON_SPIN_WAIT_HANDLE = resolve(); + + private OnSpinWaitJDK8Adapter() { + } + + private static MethodHandle resolve() { + try { + return MethodHandles.lookup().findStatic( + Thread.class, "onSpinWait", methodType(void.class)); + } catch (Exception ignore) { + } + + return null; + } + + static boolean onSpinWaitOrNothing() { + if (ON_SPIN_WAIT_HANDLE != null) { + try { + ON_SPIN_WAIT_HANDLE.invokeExact(); + return true; + } catch (Throwable ignore) { + } + } + return false; + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/utils/PearlUtil.java b/azurite-server/src/main/java/dev/azurite/spigot/utils/PearlUtil.java new file mode 100644 index 0000000..9adaf85 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/utils/PearlUtil.java @@ -0,0 +1,154 @@ +package dev.azurite.spigot.utils; + +import dev.azurite.spigot.configs.PearlConfig; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.block.BlockState; +import org.bukkit.material.Gate; + +public class PearlUtil { + + public static String direction(Location l) { + double d = (l.getYaw() - 90.0f) % 360.0f; + if (d < 0.0) { + d += 360.0; + } + if (0.0 <= d && d < 22.5) { + return "W"; + } + if (22.5 <= d && d < 67.5) { + return "NW"; + } + if (67.5 <= d && d < 112.5) { + return "N"; + } + if (112.5 <= d && d < 157.5) { + return "NE"; + } + if (157.5 <= d && d < 202.5) { + return "E"; + } + if (202.5 <= d && d < 247.5) { + return "SE"; + } + if (247.5 <= d && d < 292.5) { + return "S"; + } + if (292.5 <= d && d < 337.5) { + return "SW"; + } + if (337.5 <= d && d < 360.0) { + return "W"; + } + return ""; + } + + public static boolean distance(org.bukkit.block.Block b, Location l, double d) { + return b.getLocation().clone().add(0.5, 0.0, 0.5).distance(l) <= d; + } + + public static boolean isStairs(Material material) { + return material.name().contains("STAIRS"); + } + + public static boolean isPlantBukkit(Material type) { + return type == Material.LONG_GRASS || type == Material.BROWN_MUSHROOM || type == Material.RED_MUSHROOM || + type == Material.RED_ROSE || type == Material.CARROT || type == Material.POTATO || + type == Material.WHEAT || type == Material.YELLOW_FLOWER || type == Material.SAPLING; + } + + public static boolean isSlab(Material material) { + String name = material.name(); + return (name.contains("STEP") || name.equals("STONE_SLAB2")) && !name.contains("DOUBLE"); + } + + public static boolean isOpenFenceGate(Block block) { + BlockState state = block.getState(); + return state.getData() instanceof Gate && ((Gate) state.getData()).isOpen(); + } + + public static boolean isCritblock(Material material) { + for (PearlConfig.PearlConfigSetting pearlSetting : PearlConfig.pearlSettings) { + if (pearlSetting.aliases.isApplicable(material)) return pearlSetting.critblock.getValue(); + } + return false; + } + + public static boolean crossPearl(Material material) { + for (PearlConfig.PearlConfigSetting pearlSetting : PearlConfig.pearlSettings) { + if (pearlSetting.aliases.isApplicable(material)) return pearlSetting.crosspearl.getValue(); + } + return false; + } + + public static boolean diagonalPearl(Material material) { + for (PearlConfig.PearlConfigSetting pearlSetting : PearlConfig.pearlSettings) { + if (pearlSetting.aliases.isApplicable(material)) return pearlSetting.diagonal.getValue(); + } + return false; + } + + public static boolean thruEnabled(Material material) { + for (PearlConfig.PearlConfigSetting pearlSetting : PearlConfig.pearlSettings) { + if (pearlSetting.aliases.isApplicable(material)) return pearlSetting.enabled.getValue(); + } + return false; + } + + public static boolean isApplicable(Material material) { + for (PearlConfig.PearlConfigSetting pearlSetting : PearlConfig.pearlSettings) { + if (pearlSetting.aliases.isApplicable(material)) return true; + } + return false; + } + + public static boolean customTransparent(Block b) { + return !isTransparentBlock(b); + } + + public static boolean isTransparentBlock(Block block) { + Material type = block.getType(); + String name = type.name(); + return type.isTransparent() || block.isLiquid() || name.contains("FENCE") || isSlab(type) || isStairs(type) + || type == Material.WEB || type == Material.PISTON_EXTENSION + || type == Material.ANVIL || PearlConfig.BlockAliases.BEDS.isApplicable(type) || type == Material.DRAGON_EGG + || type == Material.COBBLE_WALL || type == Material.ENDER_PORTAL_FRAME || type == Material.ENCHANTMENT_TABLE + || name.contains("PLATE") || name.contains("SIGN") || name.contains("DAYLIGHT") + || name.contains("BANNER") || name.contains("CAKE") || name.contains("DOOR") || name.contains("CHEST"); + } + + public static boolean isRiskyBlock(Block block) { + Material type = block.getType(); + String name = type.name(); + return !type.isTransparent() && !block.isLiquid() && type != Material.WEB && + !name.contains("FENCE") && !name.contains("PLATE") && !name.contains("WALL") && + !name.contains("SIGN") && !name.contains("BANNER") && + type != Material.PISTON_EXTENSION; + } + + public static boolean isCritBlock(Block block) { + Material type = block.getType(); + String name = type.name(); + return !type.isTransparent() && !block.isLiquid() && !name.contains("PLATE") && !name.contains("BANNER") && !name.contains("SIGN"); + } + + public static BlockFace getBehind(String d) { + switch (d) { + case "W": { + return BlockFace.EAST; + } + case "E": { + return BlockFace.WEST; + } + case "S": { + return BlockFace.NORTH; + } + case "N": { + return BlockFace.SOUTH; + } + } + return null; + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/utils/QueuedTeleport.java b/azurite-server/src/main/java/dev/azurite/spigot/utils/QueuedTeleport.java new file mode 100644 index 0000000..3138f07 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/utils/QueuedTeleport.java @@ -0,0 +1,31 @@ +package dev.azurite.spigot.utils; + +public class QueuedTeleport { + private final double x; + private final double y; + private final double z; + private final boolean relative; // TODO: properly try to track relative teleports (spigot doesnt even do this properly) + + public QueuedTeleport(double x, double y, double z, boolean relative) { + this.x = x; + this.y = y; + this.z = z; + this.relative = relative; + } + + public double getX() { + return x; + } + + public double getY() { + return y; + } + + public double getZ() { + return z; + } + + public boolean isRelative() { + return relative; + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/utils/SpinCountDownLatch.java b/azurite-server/src/main/java/dev/azurite/spigot/utils/SpinCountDownLatch.java new file mode 100644 index 0000000..dc69fd4 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/utils/SpinCountDownLatch.java @@ -0,0 +1,25 @@ +package dev.azurite.spigot.utils; + +import java.util.concurrent.atomic.AtomicInteger; + +public class SpinCountDownLatch { + private final AtomicInteger count; + + public SpinCountDownLatch(int count) { + this.count = new AtomicInteger(count); + } + + public void countDown() { + count.decrementAndGet(); + } + + public void await() { + while (count.get() > 0) { + OnSpinWaitJDK8Adapter.onSpinWaitOrNothing(); + } + } + + public int getCount() { + return count.get(); + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/utils/UnimplementedList.java b/azurite-server/src/main/java/dev/azurite/spigot/utils/UnimplementedList.java new file mode 100644 index 0000000..bb0f754 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/utils/UnimplementedList.java @@ -0,0 +1,122 @@ +package dev.azurite.spigot.utils; + +import org.jetbrains.annotations.NotNull; + +import java.util.*; + +public class UnimplementedList implements List { + @Override + public int size() { + throw new UnsupportedOperationException("AzuriteSpigot uses an internal array for last itemstacks"); + } + + @Override + public boolean isEmpty() { + throw new UnsupportedOperationException("AzuriteSpigot uses an internal array for last itemstacks"); + } + + @Override + public boolean contains(Object o) { + throw new UnsupportedOperationException("AzuriteSpigot uses an internal array for last itemstacks"); + } + + @Override + public @NotNull Iterator iterator() { + throw new UnsupportedOperationException("AzuriteSpigot uses an internal array for last itemstacks"); + } + + @Override + public @NotNull Object[] toArray() { + throw new UnsupportedOperationException("AzuriteSpigot uses an internal array for last itemstacks"); + } + + @Override + public @NotNull T1[] toArray(@NotNull T1[] a) { + throw new UnsupportedOperationException("AzuriteSpigot uses an internal array for last itemstacks"); + } + + @Override + public boolean add(T t) { + throw new UnsupportedOperationException("AzuriteSpigot uses an internal array for last itemstacks"); + } + + @Override + public boolean remove(Object o) { + throw new UnsupportedOperationException("AzuriteSpigot uses an internal array for last itemstacks"); + } + + @Override + public boolean containsAll(@NotNull Collection c) { + throw new UnsupportedOperationException("AzuriteSpigot uses an internal array for last itemstacks"); + } + + @Override + public boolean addAll(@NotNull Collection c) { + throw new UnsupportedOperationException("AzuriteSpigot uses an internal array for last itemstacks"); + } + + @Override + public boolean addAll(int index, @NotNull Collection c) { + throw new UnsupportedOperationException("AzuriteSpigot uses an internal array for last itemstacks"); + } + + @Override + public boolean removeAll(@NotNull Collection c) { + throw new UnsupportedOperationException("AzuriteSpigot uses an internal array for last itemstacks"); + } + + @Override + public boolean retainAll(@NotNull Collection c) { + throw new UnsupportedOperationException("AzuriteSpigot uses an internal array for last itemstacks"); + } + + @Override + public void clear() { + throw new UnsupportedOperationException("AzuriteSpigot uses an internal array for last itemstacks"); + } + + @Override + public T get(int index) { + throw new UnsupportedOperationException("AzuriteSpigot uses an internal array for last itemstacks"); + } + + @Override + public T set(int index, T element) { + throw new UnsupportedOperationException("AzuriteSpigot uses an internal array for last itemstacks"); + } + + @Override + public void add(int index, T element) { + throw new UnsupportedOperationException("AzuriteSpigot uses an internal array for last itemstacks"); + } + + @Override + public T remove(int index) { + throw new UnsupportedOperationException("AzuriteSpigot uses an internal array for last itemstacks"); + } + + @Override + public int indexOf(Object o) { + throw new UnsupportedOperationException("AzuriteSpigot uses an internal array for last itemstacks"); + } + + @Override + public int lastIndexOf(Object o) { + throw new UnsupportedOperationException("AzuriteSpigot uses an internal array for last itemstacks"); + } + + @Override + public @NotNull ListIterator listIterator() { + throw new UnsupportedOperationException("AzuriteSpigot uses an internal array for last itemstacks"); + } + + @Override + public @NotNull ListIterator listIterator(int index) { + throw new UnsupportedOperationException("AzuriteSpigot uses an internal array for last itemstacks"); + } + + @Override + public @NotNull List subList(int fromIndex, int toIndex) { + throw new UnsupportedOperationException("AzuriteSpigot uses an internal array for last itemstacks"); + } +} diff --git a/azurite-server/src/main/java/dev/azurite/spigot/utils/Utils.java b/azurite-server/src/main/java/dev/azurite/spigot/utils/Utils.java new file mode 100644 index 0000000..b9496fd --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/utils/Utils.java @@ -0,0 +1,94 @@ +package dev.azurite.spigot.utils; + +import net.minecraft.server.Chunk; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.command.Command; +import org.bukkit.command.CommandMap; +import org.bukkit.command.SimpleCommandMap; +import org.bukkit.command.defaults.BukkitCommand; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.lang.reflect.Field; +import java.util.Map; + +/** + * Copyright (c) 2024. Keano + * Use or redistribution of source or file is + * only permitted if given explicit permission. + */ +@SuppressWarnings("unchecked") +public class Utils { + + private static final Field KNOWN_COMMANDS; + + static { + try { + + KNOWN_COMMANDS = SimpleCommandMap.class.getDeclaredField("knownCommands"); + KNOWN_COMMANDS.setAccessible(true); + + } catch (NoSuchFieldException e) { + throw new RuntimeException(e); + } + } + + public static void unregister(BukkitCommand command) { + try { + + CommandMap commandMap = Bukkit.getCommandMap(); + command.unregister(commandMap); + Map map = (Map) KNOWN_COMMANDS.get(commandMap); + map.entrySet().removeIf(entry -> entry.getValue().getLabel().equals(command.getLabel())); + + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + } + + public static void register(String prefix, BukkitCommand command, boolean reload) { + CommandMap commandMap = Bukkit.getCommandMap(); + Command alreadyRegistered = commandMap.getCommand(command.getName()); + + // If it's not reload or command is already registered don't register again + if (!reload || alreadyRegistered == null || alreadyRegistered.getLabel().equals(command.getLabel())) { + commandMap.register(prefix, command); + } + } + + public static void takeItemInHand(Player player, int amount) { + ItemStack hand = player.getItemInHand(); + + if (hand == null) return; + + if (hand.getAmount() <= 1) { + player.setItemInHand(new ItemStack(Material.AIR)); + + } else { + hand.setAmount(hand.getAmount() - amount); + } + + player.updateInventory(); + } + + public static boolean isInvalidChunk(Chunk chunk, int chunkX, int chunkZ) { + return chunk == null || !chunk.o() || chunk.locX != chunkX || chunk.locZ != chunkZ; + } + + public static int tryParseIntegerSafe(String string) { + try { + return Integer.parseInt(string); + } catch (IllegalArgumentException ignored) { + return 0; + } + } + + public static float tryParseFloatSafe(String string) { + try { + return Float.parseFloat(string); + } catch (IllegalArgumentException ignored) { + return 0.0F; + } + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/utils/VoidChunkGenerator.java b/azurite-server/src/main/java/dev/azurite/spigot/utils/VoidChunkGenerator.java new file mode 100644 index 0000000..0bac319 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/utils/VoidChunkGenerator.java @@ -0,0 +1,10 @@ +package dev.azurite.spigot.utils; + +import net.minecraft.server.World; +import org.bukkit.craftbukkit.generator.NormalChunkGenerator; + +public class VoidChunkGenerator extends NormalChunkGenerator { + public VoidChunkGenerator(World world, long seed) { + super(world, seed); + } +} diff --git a/azurite-server/src/main/java/dev/azurite/spigot/utils/WeakChunkCache.java b/azurite-server/src/main/java/dev/azurite/spigot/utils/WeakChunkCache.java new file mode 100644 index 0000000..398f968 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/utils/WeakChunkCache.java @@ -0,0 +1,101 @@ +package dev.azurite.spigot.utils; + +import net.minecraft.server.*; + +import java.util.Arrays; + +public class WeakChunkCache implements IBlockAccess { + private final int lowerChunkX; + private final int lowerChunkZ; + private final Chunk[][] chunks; + private boolean ownArray = false; + + public WeakChunkCache(Chunk[][] chunks, int lowerChunkX, int lowerChunkZ) { + this.chunks = chunks; + this.lowerChunkX = lowerChunkX; + this.lowerChunkZ = lowerChunkZ; + } + + public WeakChunkCache(World world, int chunkX, int chunkZ, int chunkRadius) { + this(world, chunkX - chunkRadius, chunkZ - chunkRadius, chunkX + chunkRadius, chunkZ + chunkRadius); + } + + public WeakChunkCache(World world, int lowerChunkX, int lowerChunkZ, int upperChunkX, int upperChunkZ) { + this.lowerChunkX = lowerChunkX; + this.lowerChunkZ = lowerChunkZ; + + this.chunks = new Chunk[upperChunkX - this.lowerChunkX + 1][upperChunkZ - this.lowerChunkZ + 1]; + this.ownArray = true; + + for (int chunkX = this.lowerChunkX; chunkX <= upperChunkX; ++chunkX) { + for (int chunkZ = this.lowerChunkZ; chunkZ <= upperChunkZ; ++chunkZ) { + this.chunks[chunkX - this.lowerChunkX][chunkZ - this.lowerChunkZ] = world.getChunkIfLoaded(chunkX, chunkZ); + } + } + } + + public WeakChunkCache(World world, int lowerBlockX, int lowerBlockZ, int upperBlockX, int upperBlockZ, int blockRadius) { + this(world, (lowerBlockX - blockRadius) >> 4, + (lowerBlockZ - blockRadius) >> 4, + (upperBlockX + blockRadius) >> 4, + (upperBlockZ + blockRadius) >> 4); + } + + public IBlockData getType(BlockPosition position) { + IBlockData block = Blocks.AIR.getBlockData(); + + if (position.getY() >= 0 && position.getY() < 256) { + int indexX = (position.getX() >> 4) - this.lowerChunkX; + int indexZ = (position.getZ() >> 4) - this.lowerChunkZ; + + if (indexX >= 0 && indexX < this.chunks.length && indexZ >= 0 && indexZ < this.chunks[indexX].length) { + Chunk chunk = this.chunks[indexX][indexZ]; + + if (chunk != null) { + block = chunk.getType(position.getX() & 15,position.getY(), position.getZ() & 15).getBlockData(); + } + } + } + + return block; + } + + public TileEntity getTileEntity(BlockPosition position) { + int indexX = (position.getX() >> 4) - this.lowerChunkX; + int indexZ = (position.getZ() >> 4) - this.lowerChunkZ; + + Chunk chunk = this.chunks[indexX][indexZ]; + if(chunk != null) { + return chunk.i(position); + } + return null; + } + + @Override + public boolean isEmpty(BlockPosition blockPosition) { + return this.getType(blockPosition) == Blocks.AIR.getBlockData(); + } + + @Override + public int getBlockPower(BlockPosition blockPosition, EnumDirection enumDirection) { + IBlockData iblockdata = this.getType(blockPosition); + return iblockdata.getBlock().b(this,blockPosition,iblockdata,enumDirection); + } + + public boolean isLoaded(int x, int z) { + int indexX = (x >> 4) - this.lowerChunkX; + int indexZ = (z >> 4) - this.lowerChunkZ; + if (indexX >= 0 && indexX < this.chunks.length && indexZ >= 0 && indexZ < this.chunks[indexX].length) { + return this.chunks[indexX][indexZ] != null; + } + return false; + } + + public void clear() { + if(this.ownArray) { + for (Chunk[] chunk : this.chunks) { + Arrays.fill(chunk, null); + } + } + } +} diff --git a/azurite-server/src/main/java/dev/azurite/spigot/utils/fanciful/ArrayWrapper.java b/azurite-server/src/main/java/dev/azurite/spigot/utils/fanciful/ArrayWrapper.java new file mode 100644 index 0000000..625fa28 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/utils/fanciful/ArrayWrapper.java @@ -0,0 +1,111 @@ +package dev.azurite.spigot.utils.fanciful; + +import java.lang.reflect.Array; +import java.util.Arrays; +import java.util.Collection; + +/** + * Represents a wrapper around an array class of an arbitrary reference type, + * which properly implements "value" hash code and equality functions. + *

+ * This class is intended for use as a key to a map. + *

+ * + * @param The type of elements in the array. + * @author Glen Husman + * @see Arrays + */ +public final class ArrayWrapper { + + /** + * Creates an array wrapper with some elements. + * + * @param elements The elements of the array. + */ + @SafeVarargs + public ArrayWrapper(E... elements) { + setArray(elements); + } + + private E[] _array; + + /** + * Retrieves a reference to the wrapped array instance. + * + * @return The array wrapped by this instance. + */ + public E[] getArray() { + return _array; + } + + /** + * Set this wrapper to wrap a new array instance. + * + * @param array The new wrapped array. + */ + public void setArray(E[] array) { + if (array == null) { + throw new NullPointerException("The array must not be null."); + } + + _array = array; + } + + /** + * Determines if this object has a value equivalent to another object. + * + * @see Arrays#equals(Object[], Object[]) + */ + @SuppressWarnings("rawtypes") + @Override + public boolean equals(Object other) { + if (!(other instanceof ArrayWrapper)) { + return false; + } + return Arrays.equals(_array, ((ArrayWrapper) other)._array); + } + + /** + * Gets the hash code represented by this objects value. + * + * @return This object's hash code. + * @see Arrays#hashCode(Object[]) + */ + @Override + public int hashCode() { + return Arrays.hashCode(_array); + } + + /** + * Converts an iterable element collection to an array of elements. + * The iteration order of the specified object will be used as the array element order. + * + * @param list The iterable of objects which will be converted to an array. + * @param c The type of the elements of the array. + * @return An array of elements in the specified iterable. + */ + @SuppressWarnings("unchecked") + public static T[] toArray(Iterable list, Class c) { + int size = -1; + if (list instanceof Collection) { + @SuppressWarnings("rawtypes") + Collection coll = (Collection) list; + size = coll.size(); + } + + if (size < 0) { + size = 0; + // Ugly hack: Count it ourselves + for (@SuppressWarnings("unused") T element : list) { + size++; + } + } + + T[] result = (T[]) Array.newInstance(c, size); + int i = 0; + for (T element : list) { // Assumes iteration order is consistent + result[i++] = element; // Assign array element at index THEN increment counter + } + return result; + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/utils/fanciful/FancyMessage.java b/azurite-server/src/main/java/dev/azurite/spigot/utils/fanciful/FancyMessage.java new file mode 100644 index 0000000..d894c6b --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/utils/fanciful/FancyMessage.java @@ -0,0 +1,695 @@ +package dev.azurite.spigot.utils.fanciful; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.google.gson.stream.JsonWriter; +import dev.azurite.spigot.utils.CC; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.serialization.ConfigurationSerializable; +import org.bukkit.configuration.serialization.ConfigurationSerialization; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +import java.io.IOException; +import java.io.StringWriter; +import java.util.*; +import java.util.function.UnaryOperator; +import java.util.logging.Level; + +/** + * Represents a formattable message. Such messages can use elements such as colors, formatting codes, hover and click data, and other features provided by the vanilla Minecraft JSON message formatter. + * This class allows plugins to emulate the functionality of the vanilla Minecraft tellraw command. + *

+ * This class follows the builder pattern, allowing for method chaining. + * It is set up such that invocations of property-setting methods will affect the current editing component, + * and a call to {@link #then()} or {@link #then(String)} will append a new editing component to the end of the message, + * optionally initializing it with text. Further property-setting method calls will affect that editing component. + *

+ */ +public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable, ConfigurationSerializable { + + static { + ConfigurationSerialization.registerClass(FancyMessage.class); + } + + private List messageParts; + private String jsonString; + private boolean dirty; + + @Override + public FancyMessage clone() { + try { + FancyMessage instance = (FancyMessage) super.clone(); + instance.messageParts = new ArrayList<>(messageParts.size()); + for (int i = 0; i < messageParts.size(); i++) { + instance.messageParts.add(i, messageParts.get(i).clone()); + } + instance.dirty = false; + instance.jsonString = null; + return instance; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * Creates a JSON message with text. + * + * @param firstPartText The existing text in the message. + */ + public FancyMessage(final String firstPartText) { + this(TextualComponent.rawText(CC.t(firstPartText))); + } + + public FancyMessage(final TextualComponent firstPartText) { + messageParts = new ArrayList<>(); + messageParts.add(new MessagePart(firstPartText)); + jsonString = null; + dirty = false; + } + + /** + * Creates a JSON message without text. + */ + public FancyMessage() { + this((TextualComponent) null); + } + + /** + * Sets the text of the current editing component to a value. + * + * @param text The new text of the current editing component. + * @return This builder instance. + */ + public FancyMessage text(String text) { + MessagePart latest = latest(); + latest.text = TextualComponent.rawText(text); + dirty = true; + return this; + } + + /** + * Sets the text of the current editing component to a value. + * + * @param text The new text of the current editing component. + * @return This builder instance. + */ + public FancyMessage text(TextualComponent text) { + MessagePart latest = latest(); + latest.text = text; + dirty = true; + return this; + } + + /** + * Sets the stylization of the current editing component. + * + * @param styles The array of styles to apply to the editing component. + * @return This builder instance. + * @throws IllegalArgumentException If any of the enumeration values in the array do not represent formatters. + */ + public FancyMessage style(ChatColor... styles) { + for (final ChatColor style : styles) { + if (!style.isFormat()) { + throw new IllegalArgumentException(style.name() + " is not a style"); + } + } + latest().styles.addAll(Arrays.asList(styles)); + dirty = true; + return this; + } + + /** + * Set the behavior of the current editing component to instruct the client to open a file on the client side filesystem when the currently edited part of the {@code FancyMessage} is clicked. + * + * @param path The path of the file on the client filesystem. + * @return This builder instance. + */ + public FancyMessage file(final String path) { + onClick("open_file", path); + return this; + } + + /** + * Set the behavior of the current editing component to instruct the client to open a webpage in the client's web browser when the currently edited part of the {@code FancyMessage} is clicked. + * + * @param url The URL of the page to open when the link is clicked. + * @return This builder instance. + */ + public FancyMessage link(final String url) { + onClick("open_url", url); + return this; + } + + /** + * Set the behavior of the current editing component to instruct the client to replace the chat input box content with the specified string when the currently edited part of the {@code FancyMessage} is clicked. + * The client will not immediately send the command to the server to be executed unless the client player submits the command/chat message, usually with the enter key. + * + * @param command The text to display in the chat bar of the client. + * @return This builder instance. + */ + public FancyMessage suggest(final String command) { + onClick("suggest_command", CC.t(command)); + return this; + } + + /** + * Set the behavior of the current editing component to instruct the client to append the chat input box content with the specified string when the currently edited part of the {@code FancyMessage} is SHIFT-CLICKED. + * The client will not immediately send the command to the server to be executed unless the client player submits the command/chat message, usually with the enter key. + * + * @param command The text to append to the chat bar of the client. + * @return This builder instance. + */ + public FancyMessage insert(final String command) { + latest().insertionData = command; + dirty = true; + return this; + } + + /** + * Set the behavior of the current editing component to instruct the client to send the specified string to the server as a chat message when the currently edited part of the {@code FancyMessage} is clicked. + * The client will immediately send the command to the server to be executed when the editing component is clicked. + * + * @param command The text to display in the chat bar of the client. + * @return This builder instance. + */ + public FancyMessage command(final String command) { + onClick("run_command", command); + return this; + } + + /** + * Set the behavior of the current editing component to display information about an achievement when the client hovers over the text. + *

Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.

+ * + * @param name The name of the achievement to display, excluding the "achievement." prefix. + * @return This builder instance. + */ + public FancyMessage achievementTooltip(final String name) { + onHover("show_achievement", new JsonString("achievement." + name)); + return this; + } + + /** + * Set the behavior of the current editing component to display raw text when the client hovers over the text. + *

Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.

+ * + * @param text The text, which supports newlines, which will be displayed to the client upon hovering. + * @return This builder instance. + */ + public FancyMessage tooltip(final String text) { + onHover("show_text", new JsonString(CC.t(text))); + return this; + } + + /** + * Set the behavior of the current editing component to display raw text when the client hovers over the text. + *

Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.

+ * + * @param lines The lines of text which will be displayed to the client upon hovering. The iteration order of this object will be the order in which the lines of the tooltip are created. + * @return This builder instance. + */ + public FancyMessage tooltip(final Iterable lines) { + tooltip(ArrayWrapper.toArray(lines, String.class)); + return this; + } + + /** + * Set the behavior of the current editing component to display raw text when the client hovers over the text. + *

Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.

+ * + * @param lines The lines of text which will be displayed to the client upon hovering. + * @return This builder instance. + */ + public FancyMessage tooltip(final String... lines) { + StringBuilder builder = new StringBuilder(); + for (int i = 0; i < lines.length; i++) { + builder.append(lines[i]); + if (i != lines.length - 1) { + builder.append('\n'); + } + } + tooltip(builder.toString()); + return this; + } + + /** + * Set the behavior of the current editing component to display formatted text when the client hovers over the text. + *

Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.

+ * + * @param text The formatted text which will be displayed to the client upon hovering. + * @return This builder instance. + */ + public FancyMessage formattedTooltip(FancyMessage text) { + for (MessagePart component : text.messageParts) { + if (component.clickActionData != null && component.clickActionName != null) { + throw new IllegalArgumentException("The tooltip text cannot have click data."); + } else if (component.hoverActionData != null && component.hoverActionName != null) { + throw new IllegalArgumentException("The tooltip text cannot have a tooltip."); + } + } + onHover("show_text", text); + return this; + } + + /** + * Set the behavior of the current editing component to display the specified lines of formatted text when the client hovers over the text. + *

Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.

+ * + * @param lines The lines of formatted text which will be displayed to the client upon hovering. + * @return This builder instance. + */ + public FancyMessage formattedTooltip(FancyMessage... lines) { + if (lines.length < 1) { + onHover(null, null); // Clear tooltip + return this; + } + + FancyMessage result = new FancyMessage(); + result.messageParts.clear(); // Remove the one existing text component that exists by default, which destabilizes the object + + for (int i = 0; i < lines.length; i++) { + try { + for (MessagePart component : lines[i]) { + if (component.clickActionData != null && component.clickActionName != null) { + throw new IllegalArgumentException("The tooltip text cannot have click data."); + } else if (component.hoverActionData != null && component.hoverActionName != null) { + throw new IllegalArgumentException("The tooltip text cannot have a tooltip."); + } + if (component.hasText()) { + result.messageParts.add(component.clone()); + } + } + if (i != lines.length - 1) { + result.messageParts.add(new MessagePart(TextualComponent.rawText("\n"))); + } + } catch (CloneNotSupportedException e) { + Bukkit.getLogger().log(Level.WARNING, "Failed to clone object", e); + return this; + } + } + return formattedTooltip(result.messageParts.isEmpty() ? null : result); // Throws NPE if size is 0, intended + } + + /** + * Set the behavior of the current editing component to display the specified lines of formatted text when the client hovers over the text. + *

Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.

+ * + * @param lines The lines of text which will be displayed to the client upon hovering. The iteration order of this object will be the order in which the lines of the tooltip are created. + * @return This builder instance. + */ + public FancyMessage formattedTooltip(final Iterable lines) { + return formattedTooltip(ArrayWrapper.toArray(lines, FancyMessage.class)); + } + + /** + * If the text is a translatable key, and it has replaceable values, this function can be used to set the replacements that will be used in the message. + * + * @param replacements The replacements, in order, that will be used in the language-specific message. + * @return This builder instance. + */ + public FancyMessage translationReplacements(final String... replacements) { + for (String str : replacements) { + latest().translationReplacements.add(new JsonString(str)); + } + dirty = true; + + return this; + } + /* + + /** + * If the text is a translatable key, and it has replaceable values, this function can be used to set the replacements that will be used in the message. + * @param replacements The replacements, in order, that will be used in the language-specific message. + * @return This builder instance. + */ /* ------------ + public FancyMessage translationReplacements(final Iterable replacements){ + for(CharSequence str : replacements){ + latest().translationReplacements.add(new JsonString(str)); + } + + return this; + } + + */ + + /** + * If the text is a translatable key, and it has replaceable values, this function can be used to set the replacements that will be used in the message. + * + * @param replacements The replacements, in order, that will be used in the language-specific message. + * @return This builder instance. + */ + public FancyMessage translationReplacements(final FancyMessage... replacements) { + for (FancyMessage str : replacements) { + latest().translationReplacements.add(str); + } + + dirty = true; + + return this; + } + + /** + * If the text is a translatable key, and it has replaceable values, this function can be used to set the replacements that will be used in the message. + * + * @param replacements The replacements, in order, that will be used in the language-specific message. + * @return This builder instance. + */ + public FancyMessage translationReplacements(final Iterable replacements) { + return translationReplacements(ArrayWrapper.toArray(replacements, FancyMessage.class)); + } + + /** + * Terminate construction of the current editing component, and begin construction of a new message component. + * After a successful call to this method, all setter methods will refer to a new message component, created as a result of the call to this method. + * + * @param text The text which will populate the new message component. + * @return This builder instance. + */ + public FancyMessage then(final String text) { + return then(TextualComponent.rawText(CC.t(text))); + } + + /** + * Terminate construction of the current editing component, and begin construction of a new message component. + * After a successful call to this method, all setter methods will refer to a new message component, created as a result of the call to this method. + * + * @param text The text which will populate the new message component. + * @return This builder instance. + */ + public FancyMessage then(final TextualComponent text) { + if (!latest().hasText()) { + throw new IllegalStateException("previous message part has no text"); + } + messageParts.add(new MessagePart(text)); + dirty = true; + return this; + } + + /** + * Terminate construction of the current editing component, and begin construction of a new message component. + * After a successful call to this method, all setter methods will refer to a new message component, created as a result of the call to this method. + * + * @return This builder instance. + */ + public FancyMessage then() { + if (!latest().hasText()) { + throw new IllegalStateException("previous message part has no text"); + } + messageParts.add(new MessagePart()); + dirty = true; + return this; + } + + @Override + public void writeJson(JsonWriter writer, UnaryOperator replacer) throws IOException { + if (messageParts.size() == 1) { + latest().writeJson(writer, replacer); + } else { + writer.beginObject().name("text").value("").name("extra").beginArray(); + for (final MessagePart part : this) { + part.writeJson(writer, replacer); + } + writer.endArray().endObject(); + } + } + + /** + * Serialize this fancy message, converting it into syntactically-valid JSON using a {@link JsonWriter}. + * This JSON should be compatible with vanilla formatter commands such as {@code /tellraw}. + * + * @return The JSON string representing this object. + */ + public String toJSONString() { + return toJSONString(UnaryOperator.identity()); + } + + public String toJSONString(UnaryOperator replacer) { + if (!dirty && jsonString != null) { + return jsonString; + } + StringWriter string = new StringWriter(); + JsonWriter json = new JsonWriter(string); + try { + writeJson(json, replacer); + json.close(); + } catch (IOException e) { + throw new RuntimeException("invalid message"); + } + jsonString = string.toString(); + dirty = false; + return jsonString; + } + + /** + * Sends this message to a player. The player will receive the fully-fledged formatted display of this message. + * + * @param player The player who will receive the message. + */ + public void send(Player player) { + send(player, toJSONString()); + } + + private void send(CommandSender sender, String jsonString) { + if (!(sender instanceof Player)) { + sender.sendMessage(toOldMessageFormat()); + return; + } + Player player = (Player) sender; + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "tellraw " + player.getName() + " " + jsonString); + } + + /** + * Sends this message to a command sender. + * If the sender is a player, they will receive the fully-fledged formatted display of this message. + * Otherwise, they will receive a version of this message with less formatting. + * + * @param sender The command sender who will receive the message. + * @see #toOldMessageFormat() + */ + public void send(CommandSender sender) { + send(sender, toJSONString()); + } + + public void send(CommandSender sender, UnaryOperator replacer) { + send(sender, toJSONString(replacer)); + } + + /** + * Sends this message to multiple command senders. + * + * @param senders The command senders who will receive the message. + * @see #send(CommandSender) + */ + public void send(final Iterable senders) { + String string = toJSONString(); + for (final CommandSender sender : senders) { + send(sender, string); + } + } + + /** + * Convert this message to a human-readable string with limited formatting. + * This method is used to send this message to clients without JSON formatting support. + *

+ * Serialization of this message by using this message will include (in this order for each message part): + *

    + *
  1. The color of each message part.
  2. + *
  3. The applicable stylizations for each message part.
  4. + *
  5. The core text of the message part.
  6. + *
+ * The primary omissions are tooltips and clickable actions. Consequently, this method should be used only as a last resort. + *

+ *

+ * Color and formatting can be removed from the returned string by using {@link ChatColor#stripColor(String)}.

+ * + * @return A human-readable string representing limited formatting in addition to the core text of this message. + */ + public String toOldMessageFormat() { + StringBuilder result = new StringBuilder(); + for (MessagePart part : this) { + result.append(part.color == null ? "" : part.color); + for (ChatColor formatSpecifier : part.styles) { + result.append(formatSpecifier); + } + result.append(part.text); + } + return result.toString(); + } + + public MessagePart latest() { + return messageParts.get(messageParts.size() - 1); + } + + private void onClick(final String name, final String data) { + final MessagePart latest = latest(); + latest.clickActionName = name; + latest.clickActionData = data; + dirty = true; + } + + private void onHover(final String name, final JsonRepresentedObject data) { + final MessagePart latest = latest(); + latest.hoverActionName = name; + latest.hoverActionData = data; + dirty = true; + } + + // Doc copied from interface + public Map serialize() { + HashMap map = new HashMap(); + map.put("messageParts", messageParts); +// map.put("JSON", toJSONString()); + return map; + } + + /** + * Internally called method. Not for API consumption. + */ + public @NotNull Iterator iterator() { + return messageParts.iterator(); + } + + private static final JsonParser _stringParser = new JsonParser(); + + /** + * Deserializes a fancy message from its JSON representation. This JSON representation is of the format of + * that returned by {@link #toJSONString()}, and is compatible with vanilla inputs. + * + * @param json The JSON string which represents a fancy message. + * @return A {@code FancyMessage} representing the parameterized JSON message. + */ + public static FancyMessage deserialize(String json) { + JsonObject serialized = _stringParser.parse(json).getAsJsonObject(); + JsonArray extra = serialized.getAsJsonArray("extra"); // Get the extra component + FancyMessage returnVal = new FancyMessage(); + returnVal.messageParts.clear(); + + if (!serialized.has("extra")) { + MessagePart component = new MessagePart(); + + for (Map.Entry entry : serialized.entrySet()) { + // Deserialize text + if (TextualComponent.isTextKey(entry.getKey())) { + // The map mimics the YAML serialization, which has a "key" field and one or more "value" fields + Map serializedMapForm = new HashMap<>(); // Must be object due to Bukkit serializer API compliance + serializedMapForm.put("key", entry.getKey()); + if (entry.getValue().isJsonPrimitive()) { + // Assume string + serializedMapForm.put("value", entry.getValue().getAsString()); + } else { + // Composite object, but we assume each element is a string + for (Map.Entry compositeNestedElement : entry.getValue().getAsJsonObject().entrySet()) { + serializedMapForm.put("value." + compositeNestedElement.getKey(), compositeNestedElement.getValue().getAsString()); + } + } + component.text = TextualComponent.deserialize(serializedMapForm); + } else if (MessagePart.stylesToNames.inverse().containsKey(entry.getKey())) { + if (entry.getValue().getAsBoolean()) { + component.styles.add(MessagePart.stylesToNames.inverse().get(entry.getKey())); + } + } else if (entry.getKey().equals("color")) { + component.color = ChatColor.valueOf(entry.getValue().getAsString().toUpperCase()); + } else if (entry.getKey().equals("clickEvent")) { + JsonObject object = entry.getValue().getAsJsonObject(); + component.clickActionName = object.get("action").getAsString(); + component.clickActionData = object.get("value").getAsString(); + } else if (entry.getKey().equals("hoverEvent")) { + JsonObject object = entry.getValue().getAsJsonObject(); + component.hoverActionName = object.get("action").getAsString(); + if (object.get("value").isJsonPrimitive()) { + // Assume string + component.hoverActionData = new JsonString(object.get("value").getAsString()); + } else { + // Assume composite type + // The only composite type we currently store is another FancyMessage + // Therefore, recursion time! + component.hoverActionData = deserialize(object.get("value").toString() /* This should properly serialize the JSON object as a JSON string */); + } + } else if (entry.getKey().equals("insertion")) { + component.insertionData = entry.getValue().getAsString(); + } else if (entry.getKey().equals("with")) { + for (JsonElement object : entry.getValue().getAsJsonArray()) { + if (object.isJsonPrimitive()) { + component.translationReplacements.add(new JsonString(object.getAsString())); + } else { + // Only composite type stored in this array is - again - FancyMessages + // Recurse within this function to parse this as a translation replacement + component.translationReplacements.add(deserialize(object.toString())); + } + } + } + } + + returnVal.messageParts.add(component); + return returnVal; + + } else { + + for (JsonElement mPrt : extra) { + MessagePart component = new MessagePart(); + JsonObject messagePart = mPrt.getAsJsonObject(); + for (Map.Entry entry : messagePart.entrySet()) { + // Deserialize text + if (TextualComponent.isTextKey(entry.getKey())) { + // The map mimics the YAML serialization, which has a "key" field and one or more "value" fields + Map serializedMapForm = new HashMap(); // Must be object due to Bukkit serializer API compliance + serializedMapForm.put("key", entry.getKey()); + if (entry.getValue().isJsonPrimitive()) { + // Assume string + serializedMapForm.put("value", entry.getValue().getAsString()); + } else { + // Composite object, but we assume each element is a string + for (Map.Entry compositeNestedElement : entry.getValue().getAsJsonObject().entrySet()) { + serializedMapForm.put("value." + compositeNestedElement.getKey(), compositeNestedElement.getValue().getAsString()); + } + } + component.text = TextualComponent.deserialize(serializedMapForm); + } else if (MessagePart.stylesToNames.inverse().containsKey(entry.getKey())) { + if (entry.getValue().getAsBoolean()) { + component.styles.add(MessagePart.stylesToNames.inverse().get(entry.getKey())); + } + } else if (entry.getKey().equals("color")) { + component.color = ChatColor.valueOf(entry.getValue().getAsString().toUpperCase()); + } else if (entry.getKey().equals("clickEvent")) { + JsonObject object = entry.getValue().getAsJsonObject(); + component.clickActionName = object.get("action").getAsString(); + component.clickActionData = object.get("value").getAsString(); + } else if (entry.getKey().equals("hoverEvent")) { + JsonObject object = entry.getValue().getAsJsonObject(); + component.hoverActionName = object.get("action").getAsString(); + if (object.get("value").isJsonPrimitive()) { + // Assume string + component.hoverActionData = new JsonString(object.get("value").getAsString()); + } else { + // Assume composite type + // The only composite type we currently store is another FancyMessage + // Therefore, recursion time! + component.hoverActionData = deserialize(object.get("value").toString() /* This should properly serialize the JSON object as a JSON string */); + } + } else if (entry.getKey().equals("insertion")) { + component.insertionData = entry.getValue().getAsString(); + } else if (entry.getKey().equals("with")) { + for (JsonElement object : entry.getValue().getAsJsonArray()) { + if (object.isJsonPrimitive()) { + component.translationReplacements.add(new JsonString(object.getAsString())); + } else { + // Only composite type stored in this array is - again - FancyMessages + // Recurse within this function to parse this as a translation replacement + component.translationReplacements.add(deserialize(object.toString())); + } + } + } + } + returnVal.messageParts.add(component); + } + } + + return returnVal; + } +} diff --git a/azurite-server/src/main/java/dev/azurite/spigot/utils/fanciful/JsonRepresentedObject.java b/azurite-server/src/main/java/dev/azurite/spigot/utils/fanciful/JsonRepresentedObject.java new file mode 100644 index 0000000..c952197 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/utils/fanciful/JsonRepresentedObject.java @@ -0,0 +1,21 @@ +package dev.azurite.spigot.utils.fanciful; + +import com.google.gson.stream.JsonWriter; + +import java.io.IOException; +import java.util.function.UnaryOperator; + +/** + * Represents an object that can be serialized to a JSON writer instance. + */ +public interface JsonRepresentedObject { + + /** + * Writes the JSON representation of this object to the specified writer. + * + * @param writer The JSON writer which will receive the object. + * @throws IOException If an error occurs writing to the stream. + */ + void writeJson(JsonWriter writer, UnaryOperator replacer) throws IOException; + +} diff --git a/azurite-server/src/main/java/dev/azurite/spigot/utils/fanciful/JsonString.java b/azurite-server/src/main/java/dev/azurite/spigot/utils/fanciful/JsonString.java new file mode 100644 index 0000000..2189764 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/utils/fanciful/JsonString.java @@ -0,0 +1,47 @@ +package dev.azurite.spigot.utils.fanciful; + +import com.google.gson.stream.JsonWriter; +import org.bukkit.configuration.serialization.ConfigurationSerializable; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.function.UnaryOperator; + +/** + * Represents a JSON string value. + * Writes by this object will not write name values nor begin/end objects in the JSON stream. + * All writes merely write the represented string value. + */ +final class JsonString implements JsonRepresentedObject, ConfigurationSerializable { + + private final String _value; + + public JsonString(CharSequence value) { + _value = value == null ? null : value.toString(); + } + + public void writeJson(JsonWriter writer, UnaryOperator replacer) throws IOException { + writer.value(replacer.apply(getValue())); + } + + public String getValue() { + return _value; + } + + public Map serialize() { + HashMap theSingleValue = new HashMap<>(); + theSingleValue.put("stringValue", _value); + return theSingleValue; + } + + public static JsonString deserialize(Map map) { + return new JsonString(map.get("stringValue").toString()); + } + + @Override + public String toString() { + return _value; + } + +} diff --git a/azurite-server/src/main/java/dev/azurite/spigot/utils/fanciful/MessagePart.java b/azurite-server/src/main/java/dev/azurite/spigot/utils/fanciful/MessagePart.java new file mode 100644 index 0000000..adefdfc --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/utils/fanciful/MessagePart.java @@ -0,0 +1,159 @@ +package dev.azurite.spigot.utils.fanciful; + +import com.google.common.collect.BiMap; +import com.google.common.collect.ImmutableBiMap; +import com.google.gson.stream.JsonWriter; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.configuration.serialization.ConfigurationSerializable; +import org.bukkit.configuration.serialization.ConfigurationSerialization; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import java.util.function.UnaryOperator; +import java.util.logging.Level; + +/** + * Internal class: Represents a component of a JSON-serializable {@link FancyMessage}. + */ +public class MessagePart implements JsonRepresentedObject, ConfigurationSerializable, Cloneable { + + public ChatColor color = ChatColor.WHITE; + public ArrayList styles = new ArrayList<>(); + public String clickActionName = null, clickActionData = null, hoverActionName = null; + public JsonRepresentedObject hoverActionData = null; + public TextualComponent text; + public String insertionData = null; + public ArrayList translationReplacements = new ArrayList<>(); + + public MessagePart(final TextualComponent text) { + this.text = text; + } + + public MessagePart() { + this.text = null; + } + + public boolean hasText() { + return text != null; + } + + @Override + @SuppressWarnings("unchecked") + public MessagePart clone() throws CloneNotSupportedException { + MessagePart obj = (MessagePart) super.clone(); + obj.styles = (ArrayList) styles.clone(); + if (hoverActionData instanceof JsonString) { + obj.hoverActionData = new JsonString(((JsonString) hoverActionData).getValue()); + } else if (hoverActionData instanceof FancyMessage) { + obj.hoverActionData = ((FancyMessage) hoverActionData).clone(); + } + obj.translationReplacements = (ArrayList) translationReplacements.clone(); + return obj; + + } + + static final BiMap stylesToNames; + + static { + ImmutableBiMap.Builder builder = ImmutableBiMap.builder(); + for (final ChatColor style : ChatColor.values()) { + if (!style.isFormat()) { + continue; + } + + String styleName; + switch (style) { + case MAGIC: + styleName = "obfuscated"; + break; + case UNDERLINE: + styleName = "underlined"; + break; + default: + styleName = style.name().toLowerCase(); + break; + } + + builder.put(style, styleName); + } + stylesToNames = builder.build(); + } + + public void writeJson(JsonWriter json) { + this.writeJson(json, UnaryOperator.identity()); + } + + public void writeJson(JsonWriter json, UnaryOperator replacer) { + try { + json.beginObject(); + text.writeJson(json, replacer); + json.name("color").value(color.name().toLowerCase()); + for (final ChatColor style : styles) { + json.name(stylesToNames.get(style)).value(true); + } + if (clickActionName != null && clickActionData != null) { + json.name("clickEvent") + .beginObject() + .name("action").value(clickActionName) + .name("value").value(replacer.apply(clickActionData)) + .endObject(); + } + if (hoverActionName != null && hoverActionData != null) { + json.name("hoverEvent") + .beginObject() + .name("action").value(hoverActionName) + .name("value"); + hoverActionData.writeJson(json, replacer); + json.endObject(); + } + if (insertionData != null) { + json.name("insertion").value(insertionData); + } + if (!translationReplacements.isEmpty() && TextualComponent.isTranslatableText(text)) { + json.name("with").beginArray(); + for (JsonRepresentedObject obj : translationReplacements) { + obj.writeJson(json, replacer); + } + json.endArray(); + } + json.endObject(); + } catch (IOException e) { + Bukkit.getLogger().log(Level.WARNING, "A problem occured during writing of JSON string", e); + } + } + + public Map serialize() { + HashMap map = new HashMap<>(); + map.put("text", text); + map.put("styles", styles); + map.put("color", color.getChar()); + map.put("hoverActionName", hoverActionName); + map.put("hoverActionData", hoverActionData); + map.put("clickActionName", clickActionName); + map.put("clickActionData", clickActionData); + map.put("insertion", insertionData); + map.put("translationReplacements", translationReplacements); + return map; + } + + @SuppressWarnings("unchecked") + public static MessagePart deserialize(Map serialized) { + MessagePart part = new MessagePart((TextualComponent) serialized.get("text")); + part.styles = (ArrayList) serialized.get("styles"); + part.color = ChatColor.getByChar(serialized.get("color").toString()); + part.hoverActionName = (String) serialized.get("hoverActionName"); + part.hoverActionData = (JsonRepresentedObject) serialized.get("hoverActionData"); + part.clickActionName = (String) serialized.get("clickActionName"); + part.clickActionData = (String) serialized.get("clickActionData"); + part.insertionData = (String) serialized.get("insertion"); + part.translationReplacements = (ArrayList) serialized.get("translationReplacements"); + return part; + } + + static { + ConfigurationSerialization.registerClass(MessagePart.class); + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/dev/azurite/spigot/utils/fanciful/TextualComponent.java b/azurite-server/src/main/java/dev/azurite/spigot/utils/fanciful/TextualComponent.java new file mode 100644 index 0000000..053bbf5 --- /dev/null +++ b/azurite-server/src/main/java/dev/azurite/spigot/utils/fanciful/TextualComponent.java @@ -0,0 +1,297 @@ +package dev.azurite.spigot.utils.fanciful; + +import com.google.common.base.Preconditions; +import com.google.common.collect.ImmutableMap; +import com.google.gson.stream.JsonWriter; +import org.bukkit.configuration.serialization.ConfigurationSerializable; +import org.bukkit.configuration.serialization.ConfigurationSerialization; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.function.UnaryOperator; + +/** + * Represents a textual component of a message part. + * This can be used to not only represent string literals in a JSON message, + * but also to represent localized strings and other text values. + *

Different instances of this class can be created with static constructor methods.

+ */ +public abstract class TextualComponent implements Cloneable { + + static { + ConfigurationSerialization.registerClass(TextualComponent.ArbitraryTextTypeComponent.class); + ConfigurationSerialization.registerClass(TextualComponent.ComplexTextTypeComponent.class); + } + + @Override + public String toString() { + return getReadableString(); + } + + /** + * @return The JSON key used to represent text components of this type. + */ + public abstract String getKey(); + + /** + * @return A readable String + */ + public abstract String getReadableString(); + + /** + * Clones a textual component instance. + * The returned object should not reference this textual component instance, but should maintain the same key and value. + */ + @Override + public abstract TextualComponent clone() throws CloneNotSupportedException; + + /** + * Writes the text data represented by this textual component to the specified JSON writer object. + * A new object within the writer is not started. + * + * @param writer The object to which to write the JSON data. + * @throws IOException If an error occurs while writing to the stream. + */ + public abstract void writeJson(JsonWriter writer, UnaryOperator replacer) throws IOException; + + static TextualComponent deserialize(Map map) { + if (map.containsKey("key") && map.size() == 2 && map.containsKey("value")) { + // Arbitrary text component + return ArbitraryTextTypeComponent.deserialize(map); + } else if (map.size() >= 2 && map.containsKey("key") && !map.containsKey("value") /* It contains keys that START WITH value */) { + // Complex JSON object + return ComplexTextTypeComponent.deserialize(map); + } + + return null; + } + + static boolean isTextKey(String key) { + return key.equals("translate") || key.equals("text") || key.equals("score") || key.equals("selector"); + } + + static boolean isTranslatableText(TextualComponent component) { + return component instanceof ComplexTextTypeComponent && ((ComplexTextTypeComponent) component).getKey().equals("translate"); + } + + /** + * Internal class used to represent all types of text components. + * Exception validating done is on keys and values. + */ + private static final class ArbitraryTextTypeComponent extends TextualComponent implements ConfigurationSerializable { + + public ArbitraryTextTypeComponent(String key, String value) { + setKey(key); + setValue(value); + } + + @Override + public String getKey() { + return _key; + } + + public void setKey(String key) { + Preconditions.checkArgument(key != null && !key.isEmpty(), "The key must be specified."); + _key = key; + } + + public String getValue() { + return _value; + } + + public void setValue(String value) { + Preconditions.checkArgument(value != null, "The value must be specified."); + _value = value; + } + + private String _key; + private String _value; + + @Override + public TextualComponent clone() throws CloneNotSupportedException { + // Since this is a private and final class, we can just reinstantiate this class instead of casting super.clone + return new ArbitraryTextTypeComponent(getKey(), getValue()); + } + + @Override + public void writeJson(JsonWriter writer, UnaryOperator replacer) throws IOException { + writer.name(getKey()).value(replacer.apply(getValue())); + } + + public Map serialize() { + return new HashMap() {{ + put("key", getKey()); + put("value", getValue()); + }}; + } + + public static ArbitraryTextTypeComponent deserialize(Map map) { + return new ArbitraryTextTypeComponent(map.get("key").toString(), map.get("value").toString()); + } + + @Override + public String getReadableString() { + return getValue(); + } + } + + /** + * Internal class used to represent a text component with a nested JSON value. + * Exception validating done is on keys and values. + */ + private static final class ComplexTextTypeComponent extends TextualComponent implements ConfigurationSerializable { + + public ComplexTextTypeComponent(String key, Map values) { + setKey(key); + setValue(values); + } + + @Override + public String getKey() { + return _key; + } + + public void setKey(String key) { + Preconditions.checkArgument(key != null && !key.isEmpty(), "The key must be specified."); + _key = key; + } + + public Map getValue() { + return _value; + } + + public void setValue(Map value) { + Preconditions.checkArgument(value != null, "The value must be specified."); + _value = value; + } + + private String _key; + private Map _value; + + @Override + public TextualComponent clone() throws CloneNotSupportedException { + // Since this is a private and final class, we can just reinstantiate this class instead of casting super.clone + return new ComplexTextTypeComponent(getKey(), getValue()); + } + + @Override + public void writeJson(JsonWriter writer, UnaryOperator replacer) throws IOException { + writer.name(getKey()); + writer.beginObject(); + for (Map.Entry jsonPair : _value.entrySet()) { + writer.name(jsonPair.getKey()).value(replacer.apply(jsonPair.getValue())); + } + writer.endObject(); + } + + @SuppressWarnings("serial") + public Map serialize() { + return new java.util.HashMap() {{ + put("key", getKey()); + for (Map.Entry valEntry : getValue().entrySet()) { + put("value." + valEntry.getKey(), valEntry.getValue()); + } + }}; + } + + public static ComplexTextTypeComponent deserialize(Map map) { + String key = null; + Map value = new HashMap(); + for (Map.Entry valEntry : map.entrySet()) { + if (valEntry.getKey().equals("key")) { + key = (String) valEntry.getValue(); + } else if (valEntry.getKey().startsWith("value.")) { + value.put(valEntry.getKey().substring(6) /* Strips out the value prefix */, valEntry.getValue().toString()); + } + } + return new ComplexTextTypeComponent(key, value); + } + + @Override + public String getReadableString() { + return getKey(); + } + } + + /** + * Create a textual component representing a string literal. + * This is the default type of textual component when a single string literal is given to a method. + * + * @param textValue The text which will be represented. + * @return The text component representing the specified literal text. + */ + public static TextualComponent rawText(String textValue) { + return new ArbitraryTextTypeComponent("text", textValue); + } + + + /** + * Create a textual component representing a localized string. + * The client will see this text component as their localized version of the specified string key, which can be overridden by a resource pack. + *

+ * If the specified translation key is not present on the client resource pack, the translation key will be displayed as a string literal to the client. + *

+ * + * @param translateKey The string key which maps to localized text. + * @return The text component representing the specified localized text. + */ + public static TextualComponent localizedText(String translateKey) { + return new ArbitraryTextTypeComponent("translate", translateKey); + } + + private static void throwUnsupportedSnapshot() { + throw new UnsupportedOperationException("This feature is only supported in snapshot releases."); + } + + /** + * Create a textual component representing a scoreboard value. + * The client will see their own score for the specified objective as the text represented by this component. + *

+ * This method is currently guaranteed to throw an {@code UnsupportedOperationException} as it is only supported on snapshot clients. + *

+ * + * @param scoreboardObjective The name of the objective for which to display the score. + * @return The text component representing the specified scoreboard score (for the viewing player), or {@code null} if an error occurs during JSON serialization. + */ + public static TextualComponent objectiveScore(String scoreboardObjective) { + return objectiveScore("*", scoreboardObjective); + } + + /** + * Create a textual component representing a scoreboard value. + * The client will see the score of the specified player for the specified objective as the text represented by this component. + *

+ * This method is currently guaranteed to throw an {@code UnsupportedOperationException} as it is only supported on snapshot clients. + *

+ * + * @param playerName The name of the player whos score will be shown. If this string represents the single-character sequence "*", the viewing player's score will be displayed. + * Standard minecraft selectors (@a, @p, etc) are not supported. + * @param scoreboardObjective The name of the objective for which to display the score. + * @return The text component representing the specified scoreboard score for the specified player, or {@code null} if an error occurs during JSON serialization. + */ + public static TextualComponent objectiveScore(String playerName, String scoreboardObjective) { + throwUnsupportedSnapshot(); // Remove this line when the feature is released to non-snapshot versions, in addition to updating ALL THE OVERLOADS documentation accordingly + + return new ComplexTextTypeComponent("score", ImmutableMap.builder() + .put("name", playerName) + .put("objective", scoreboardObjective) + .build()); + } + + /** + * Create a textual component representing a player name, retrievable by using a standard minecraft selector. + * The client will see the players or entities captured by the specified selector as the text represented by this component. + *

+ * This method is currently guaranteed to throw an {@code UnsupportedOperationException} as it is only supported on snapshot clients. + *

+ * + * @param selector The minecraft player or entity selector which will capture the entities whose string representations will be displayed in the place of this text component. + * @return The text component representing the name of the entities captured by the selector. + */ + public static TextualComponent selector(String selector) { + throwUnsupportedSnapshot(); // Remove this line when the feature is released to non-snapshot versions, in addition to updating ALL THE OVERLOADS documentation accordingly + + return new ArbitraryTextTypeComponent("selector", selector); + } +} diff --git a/azurite-server/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java b/azurite-server/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java new file mode 100644 index 0000000..1e947c1 --- /dev/null +++ b/azurite-server/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java @@ -0,0 +1,1372 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package io.netty.util.concurrent; + +import dev.azurite.spigot.utils.NonWakeupNettyRunnable; +import io.netty.util.internal.ObjectUtil; +import io.netty.util.internal.PlatformDependent; +import io.netty.util.internal.SystemPropertyUtil; +import io.netty.util.internal.ThreadExecutorMap; +import io.netty.util.internal.logging.InternalLogger; +import io.netty.util.internal.logging.InternalLoggerFactory; +import org.jetbrains.annotations.Async.Schedule; + +import java.lang.Thread.State; +import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Queue; +import java.util.Set; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executor; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicLongFieldUpdater; +import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + +/** + * Abstract base class for {@link OrderedEventExecutor}'s that execute all its submitted tasks in a single thread. + * + */ +public abstract class SingleThreadEventExecutor extends AbstractScheduledEventExecutor implements OrderedEventExecutor { + + static final int DEFAULT_MAX_PENDING_EXECUTOR_TASKS = Math.max(16, + SystemPropertyUtil.getInt("io.netty.eventexecutor.maxPendingTasks", Integer.MAX_VALUE)); + + private static final InternalLogger logger = + InternalLoggerFactory.getInstance(SingleThreadEventExecutor.class); + + private static final int ST_NOT_STARTED = 1; + private static final int ST_SUSPENDING = 2; + private static final int ST_SUSPENDED = 3; + private static final int ST_STARTED = 4; + private static final int ST_SHUTTING_DOWN = 5; + private static final int ST_SHUTDOWN = 6; + private static final int ST_TERMINATED = 7; + + private static final Runnable NOOP_TASK = new Runnable() { + @Override + public void run() { + // Do nothing. + } + }; + + private static final AtomicIntegerFieldUpdater STATE_UPDATER = + AtomicIntegerFieldUpdater.newUpdater(SingleThreadEventExecutor.class, "state"); + private static final AtomicReferenceFieldUpdater PROPERTIES_UPDATER = + AtomicReferenceFieldUpdater.newUpdater( + SingleThreadEventExecutor.class, ThreadProperties.class, "threadProperties"); + private static final AtomicLongFieldUpdater ACCUMULATED_ACTIVE_TIME_NANOS_UPDATER = + AtomicLongFieldUpdater.newUpdater(SingleThreadEventExecutor.class, "accumulatedActiveTimeNanos"); + private static final AtomicIntegerFieldUpdater CONSECUTIVE_IDLE_CYCLES_UPDATER = + AtomicIntegerFieldUpdater.newUpdater(SingleThreadEventExecutor.class, "consecutiveIdleCycles"); + private static final AtomicIntegerFieldUpdater CONSECUTIVE_BUSY_CYCLES_UPDATER = + AtomicIntegerFieldUpdater.newUpdater(SingleThreadEventExecutor.class, "consecutiveBusyCycles"); + private final Queue taskQueue; + + private volatile Thread thread; + @SuppressWarnings("unused") + private volatile ThreadProperties threadProperties; + private final Executor executor; + private volatile boolean interrupted; + + private final Lock processingLock = new ReentrantLock(); + private final CountDownLatch threadLock = new CountDownLatch(1); + private final Set shutdownHooks = new LinkedHashSet(); + private final boolean addTaskWakesUp; + private final int maxPendingTasks; + private final RejectedExecutionHandler rejectedExecutionHandler; + private final boolean supportSuspension; + + // A running total of nanoseconds this executor has spent in an "active" state. + private volatile long accumulatedActiveTimeNanos; + // Timestamp of the last recorded activity (tasks + I/O). + private volatile long lastActivityTimeNanos; + /** + * Tracks the number of consecutive monitor cycles this executor's + * utilization has been below the scale-down threshold. + */ + private volatile int consecutiveIdleCycles; + + /** + * Tracks the number of consecutive monitor cycles this executor's + * utilization has been above the scale-up threshold. + */ + private volatile int consecutiveBusyCycles; + private long lastExecutionTime; + + @SuppressWarnings({ "FieldMayBeFinal", "unused" }) + private volatile int state = ST_NOT_STARTED; + + private volatile long gracefulShutdownQuietPeriod; + private volatile long gracefulShutdownTimeout; + private long gracefulShutdownStartTime; + + private final Promise terminationFuture = new DefaultPromise(GlobalEventExecutor.INSTANCE); + + /** + * Create a new instance + * + * @param parent the {@link EventExecutorGroup} which is the parent of this instance and belongs to it + * @param threadFactory the {@link ThreadFactory} which will be used for the used {@link Thread} + * @param addTaskWakesUp {@code true} if and only if invocation of {@link #addTask(Runnable)} will wake up the + * executor thread + */ + protected SingleThreadEventExecutor( + EventExecutorGroup parent, ThreadFactory threadFactory, boolean addTaskWakesUp) { + this(parent, new ThreadPerTaskExecutor(threadFactory), addTaskWakesUp); + } + + /** + * Create a new instance + * + * @param parent the {@link EventExecutorGroup} which is the parent of this instance and belongs to it + * @param threadFactory the {@link ThreadFactory} which will be used for the used {@link Thread} + * @param addTaskWakesUp {@code true} if and only if invocation of {@link #addTask(Runnable)} will wake up the + * executor thread + * @param maxPendingTasks the maximum number of pending tasks before new tasks will be rejected. + * @param rejectedHandler the {@link RejectedExecutionHandler} to use. + */ + protected SingleThreadEventExecutor( + EventExecutorGroup parent, ThreadFactory threadFactory, + boolean addTaskWakesUp, int maxPendingTasks, RejectedExecutionHandler rejectedHandler) { + this(parent, new ThreadPerTaskExecutor(threadFactory), addTaskWakesUp, maxPendingTasks, rejectedHandler); + } + + /** + * Create a new instance + * + * @param parent the {@link EventExecutorGroup} which is the parent of this instance and belongs to it + * @param threadFactory the {@link ThreadFactory} which will be used for the used {@link Thread} + * @param addTaskWakesUp {@code true} if and only if invocation of {@link #addTask(Runnable)} will wake up the + * executor thread + * @param supportSuspension {@code true} if suspension of this {@link SingleThreadEventExecutor} is supported. + * @param maxPendingTasks the maximum number of pending tasks before new tasks will be rejected. + * @param rejectedHandler the {@link RejectedExecutionHandler} to use. + */ + protected SingleThreadEventExecutor( + EventExecutorGroup parent, ThreadFactory threadFactory, + boolean addTaskWakesUp, boolean supportSuspension, + int maxPendingTasks, RejectedExecutionHandler rejectedHandler) { + this(parent, new ThreadPerTaskExecutor(threadFactory), addTaskWakesUp, supportSuspension, + maxPendingTasks, rejectedHandler); + } + + /** + * Create a new instance + * + * @param parent the {@link EventExecutorGroup} which is the parent of this instance and belongs to it + * @param executor the {@link Executor} which will be used for executing + * @param addTaskWakesUp {@code true} if and only if invocation of {@link #addTask(Runnable)} will wake up the + * executor thread + */ + protected SingleThreadEventExecutor(EventExecutorGroup parent, Executor executor, boolean addTaskWakesUp) { + this(parent, executor, addTaskWakesUp, DEFAULT_MAX_PENDING_EXECUTOR_TASKS, RejectedExecutionHandlers.reject()); + } + + /** + * Create a new instance + * + * @param parent the {@link EventExecutorGroup} which is the parent of this instance and belongs to it + * @param executor the {@link Executor} which will be used for executing + * @param addTaskWakesUp {@code true} if and only if invocation of {@link #addTask(Runnable)} will wake up the + * executor thread + * @param maxPendingTasks the maximum number of pending tasks before new tasks will be rejected. + * @param rejectedHandler the {@link RejectedExecutionHandler} to use. + */ + protected SingleThreadEventExecutor(EventExecutorGroup parent, Executor executor, + boolean addTaskWakesUp, int maxPendingTasks, + RejectedExecutionHandler rejectedHandler) { + this(parent, executor, addTaskWakesUp, false, maxPendingTasks, rejectedHandler); + } + + /** + * Create a new instance + * + * @param parent the {@link EventExecutorGroup} which is the parent of this instance and belongs to it + * @param executor the {@link Executor} which will be used for executing + * @param addTaskWakesUp {@code true} if and only if invocation of {@link #addTask(Runnable)} will wake up the + * executor thread + * @param supportSuspension {@code true} if suspension of this {@link SingleThreadEventExecutor} is supported. + * @param maxPendingTasks the maximum number of pending tasks before new tasks will be rejected. + * @param rejectedHandler the {@link RejectedExecutionHandler} to use. + */ + protected SingleThreadEventExecutor(EventExecutorGroup parent, Executor executor, + boolean addTaskWakesUp, boolean supportSuspension, + int maxPendingTasks, RejectedExecutionHandler rejectedHandler) { + super(parent); + this.addTaskWakesUp = addTaskWakesUp; + this.supportSuspension = supportSuspension; + this.maxPendingTasks = Math.max(16, maxPendingTasks); + this.executor = ThreadExecutorMap.apply(executor, this); + taskQueue = newTaskQueue(this.maxPendingTasks); + rejectedExecutionHandler = ObjectUtil.checkNotNull(rejectedHandler, "rejectedHandler"); + lastActivityTimeNanos = ticker().nanoTime(); + } + + protected SingleThreadEventExecutor(EventExecutorGroup parent, Executor executor, + boolean addTaskWakesUp, Queue taskQueue, + RejectedExecutionHandler rejectedHandler) { + this(parent, executor, addTaskWakesUp, false, taskQueue, rejectedHandler); + } + + protected SingleThreadEventExecutor(EventExecutorGroup parent, Executor executor, + boolean addTaskWakesUp, boolean supportSuspension, + Queue taskQueue, RejectedExecutionHandler rejectedHandler) { + super(parent); + this.addTaskWakesUp = addTaskWakesUp; + this.supportSuspension = supportSuspension; + this.maxPendingTasks = DEFAULT_MAX_PENDING_EXECUTOR_TASKS; + this.executor = ThreadExecutorMap.apply(executor, this); + this.taskQueue = ObjectUtil.checkNotNull(taskQueue, "taskQueue"); + this.rejectedExecutionHandler = ObjectUtil.checkNotNull(rejectedHandler, "rejectedHandler"); + } + + /** + * @deprecated Please use and override {@link #newTaskQueue(int)}. + */ + @Deprecated + protected Queue newTaskQueue() { + return newTaskQueue(maxPendingTasks); + } + + /** + * Create a new {@link Queue} which will holds the tasks to execute. This default implementation will return a + * {@link LinkedBlockingQueue} but if your sub-class of {@link SingleThreadEventExecutor} will not do any blocking + * calls on the this {@link Queue} it may make sense to {@code @Override} this and return some more performant + * implementation that does not support blocking operations at all. + */ + protected Queue newTaskQueue(int maxPendingTasks) { + return new LinkedBlockingQueue(maxPendingTasks); + } + + /** + * Interrupt the current running {@link Thread}. + */ + protected void interruptThread() { + Thread currentThread = thread; + if (currentThread == null) { + interrupted = true; + } else { + currentThread.interrupt(); + } + } + + /** + * @see Queue#poll() + */ + protected Runnable pollTask() { + assert inEventLoop(); + return pollTaskFrom(taskQueue); + } + + protected static Runnable pollTaskFrom(Queue taskQueue) { + for (;;) { + Runnable task = taskQueue.poll(); + if (task != WAKEUP_TASK) { + return task; + } + } + } + + /** + * Take the next {@link Runnable} from the task queue and so will block if no task is currently present. + *

+ * Be aware that this method will throw an {@link UnsupportedOperationException} if the task queue, which was + * created via {@link #newTaskQueue()}, does not implement {@link BlockingQueue}. + *

+ * + * @return {@code null} if the executor thread has been interrupted or waken up. + */ + protected Runnable takeTask() { + assert inEventLoop(); + if (!(taskQueue instanceof BlockingQueue)) { + throw new UnsupportedOperationException(); + } + + BlockingQueue taskQueue = (BlockingQueue) this.taskQueue; + for (;;) { + ScheduledFutureTask scheduledTask = peekScheduledTask(); + if (scheduledTask == null) { + Runnable task = null; + try { + task = taskQueue.take(); + if (task == WAKEUP_TASK) { + task = null; + } + } catch (InterruptedException e) { + // Ignore + } + return task; + } else { + long delayNanos = scheduledTask.delayNanos(); + Runnable task = null; + if (delayNanos > 0) { + try { + task = taskQueue.poll(delayNanos, TimeUnit.NANOSECONDS); + } catch (InterruptedException e) { + // Waken up. + return null; + } + } + if (task == null) { + // We need to fetch the scheduled tasks now as otherwise there may be a chance that + // scheduled tasks are never executed if there is always one task in the taskQueue. + // This is for example true for the read task of OIO Transport + // See https://github.com/netty/netty/issues/1614 + fetchFromScheduledTaskQueue(); + task = taskQueue.poll(); + } + + if (task != null) { + if (task == WAKEUP_TASK) { + return null; + } + return task; + } + } + } + } + + private boolean fetchFromScheduledTaskQueue() { + return fetchFromScheduledTaskQueue(taskQueue); + } + + /** + * @return {@code true} if at least one scheduled task was executed. + */ + private boolean executeExpiredScheduledTasks() { + if (scheduledTaskQueue == null || scheduledTaskQueue.isEmpty()) { + return false; + } + long nanoTime = getCurrentTimeNanos(); + Runnable scheduledTask = pollScheduledTask(nanoTime); + if (scheduledTask == null) { + return false; + } + do { + safeExecute(scheduledTask); + } while ((scheduledTask = pollScheduledTask(nanoTime)) != null); + return true; + } + + /** + * @see Queue#peek() + */ + protected Runnable peekTask() { + assert inEventLoop(); + return taskQueue.peek(); + } + + /** + * @see Queue#isEmpty() + */ + protected boolean hasTasks() { + assert inEventLoop(); + return !taskQueue.isEmpty(); + } + + /** + * Return the number of tasks that are pending for processing. + */ + public int pendingTasks() { + return taskQueue.size(); + } + + /** + * Add a task to the task queue, or throws a {@link RejectedExecutionException} if this instance was shutdown + * before. + */ + protected void addTask(Runnable task) { + ObjectUtil.checkNotNull(task, "task"); + if (!offerTask(task)) { + reject(task); + } + } + + final boolean offerTask(Runnable task) { + if (isShutdown()) { + reject(); + } + return taskQueue.offer(task); + } + + /** + * @see Queue#remove(Object) + */ + protected boolean removeTask(Runnable task) { + return taskQueue.remove(ObjectUtil.checkNotNull(task, "task")); + } + + /** + * Poll all tasks from the task queue and run them via {@link Runnable#run()} method. + * + * @return {@code true} if and only if at least one task was run + */ + protected boolean runAllTasks() { + assert inEventLoop(); + boolean fetchedAll; + boolean ranAtLeastOne = false; + + do { + fetchedAll = fetchFromScheduledTaskQueue(taskQueue); + if (runAllTasksFrom(taskQueue)) { + ranAtLeastOne = true; + } + } while (!fetchedAll); // keep on processing until we fetched all scheduled tasks. + + if (ranAtLeastOne) { + lastExecutionTime = getCurrentTimeNanos(); + } + afterRunningAllTasks(); + return ranAtLeastOne; + } + + /** + * Execute all expired scheduled tasks and all current tasks in the executor queue until both queues are empty, + * or {@code maxDrainAttempts} has been exceeded. + * @param maxDrainAttempts The maximum amount of times this method attempts to drain from queues. This is to prevent + * continuous task execution and scheduling from preventing the EventExecutor thread to + * make progress and return to the selector mechanism to process inbound I/O events. + * @return {@code true} if at least one task was run. + */ + protected final boolean runScheduledAndExecutorTasks(final int maxDrainAttempts) { + assert inEventLoop(); + boolean ranAtLeastOneTask; + int drainAttempt = 0; + do { + // We must run the taskQueue tasks first, because the scheduled tasks from outside the EventLoop are queued + // here because the taskQueue is thread safe and the scheduledTaskQueue is not thread safe. + ranAtLeastOneTask = runExistingTasksFrom(taskQueue) | executeExpiredScheduledTasks(); + } while (ranAtLeastOneTask && ++drainAttempt < maxDrainAttempts); + + if (drainAttempt > 0) { + lastExecutionTime = getCurrentTimeNanos(); + } + afterRunningAllTasks(); + + return drainAttempt > 0; + } + + /** + * Runs all tasks from the passed {@code taskQueue}. + * + * @param taskQueue To poll and execute all tasks. + * + * @return {@code true} if at least one task was executed. + */ + protected final boolean runAllTasksFrom(Queue taskQueue) { + Runnable task = pollTaskFrom(taskQueue); + if (task == null) { + return false; + } + for (;;) { + safeExecute(task); + task = pollTaskFrom(taskQueue); + if (task == null) { + return true; + } + } + } + + /** + * What ever tasks are present in {@code taskQueue} when this method is invoked will be {@link Runnable#run()}. + * @param taskQueue the task queue to drain. + * @return {@code true} if at least {@link Runnable#run()} was called. + */ + private boolean runExistingTasksFrom(Queue taskQueue) { + Runnable task = pollTaskFrom(taskQueue); + if (task == null) { + return false; + } + int remaining = Math.min(maxPendingTasks, taskQueue.size()); + safeExecute(task); + // Use taskQueue.poll() directly rather than pollTaskFrom() since the latter may + // silently consume more than one item from the queue (skips over WAKEUP_TASK instances) + while (remaining-- > 0 && (task = taskQueue.poll()) != null) { + safeExecute(task); + } + return true; + } + + /** + * Poll all tasks from the task queue and run them via {@link Runnable#run()} method. This method stops running + * the tasks in the task queue and returns if it ran longer than {@code timeoutNanos}. + */ + @SuppressWarnings("NonAtomicOperationOnVolatileField") + protected boolean runAllTasks(long timeoutNanos) { + fetchFromScheduledTaskQueue(taskQueue); + Runnable task = pollTask(); + if (task == null) { + afterRunningAllTasks(); + return false; + } + + final long deadline = timeoutNanos > 0 ? getCurrentTimeNanos() + timeoutNanos : 0; + long runTasks = 0; + long lastExecutionTime; + + long workStartTime = ticker().nanoTime(); + for (;;) { + safeExecute(task); + + runTasks ++; + + // Check timeout every 64 tasks because nanoTime() is relatively expensive. + // XXX: Hard-coded value - will make it configurable if it is really a problem. + if ((runTasks & 0x3F) == 0) { + lastExecutionTime = getCurrentTimeNanos(); + if (lastExecutionTime >= deadline) { + break; + } + } + + task = pollTask(); + if (task == null) { + lastExecutionTime = getCurrentTimeNanos(); + break; + } + } + + long workEndTime = ticker().nanoTime(); + accumulatedActiveTimeNanos += workEndTime - workStartTime; + lastActivityTimeNanos = workEndTime; + + afterRunningAllTasks(); + this.lastExecutionTime = lastExecutionTime; + return true; + } + + /** + * Invoked before returning from {@link #runAllTasks()} and {@link #runAllTasks(long)}. + */ + protected void afterRunningAllTasks() { } + + /** + * Returns the amount of time left until the scheduled task with the closest dead line is executed. + */ + protected long delayNanos(long currentTimeNanos) { + currentTimeNanos -= ticker().initialNanoTime(); + + ScheduledFutureTask scheduledTask = peekScheduledTask(); + if (scheduledTask == null) { + return SCHEDULE_PURGE_INTERVAL; + } + + return scheduledTask.delayNanos(currentTimeNanos); + } + + /** + * Returns the absolute point in time (relative to {@link #getCurrentTimeNanos()}) at which the next + * closest scheduled task should run. + */ + protected long deadlineNanos() { + ScheduledFutureTask scheduledTask = peekScheduledTask(); + if (scheduledTask == null) { + return getCurrentTimeNanos() + SCHEDULE_PURGE_INTERVAL; + } + return scheduledTask.deadlineNanos(); + } + + /** + * Updates the internal timestamp that tells when a submitted task was executed most recently. + * {@link #runAllTasks()} and {@link #runAllTasks(long)} updates this timestamp automatically, and thus there's + * usually no need to call this method. However, if you take the tasks manually using {@link #takeTask()} or + * {@link #pollTask()}, you have to call this method at the end of task execution loop for accurate quiet period + * checks. + */ + protected void updateLastExecutionTime() { + long now = getCurrentTimeNanos(); + lastExecutionTime = now; + lastActivityTimeNanos = now; + } + + /** + * Returns the number of registered channels for auto-scaling related decisions. + * This is intended to be used by {@link MultithreadEventExecutorGroup} for dynamic scaling. + * + * @return The number of registered channels, or {@code -1} if not applicable. + */ + protected int getNumOfRegisteredChannels() { + return -1; + } + + /** + * Adds the given duration to the total active time for the current measurement window. + *

+ * Note: This method is not thread-safe and must only be called from the + * {@link #inEventLoop() event loop thread}. + * + * @param nanos The active time in nanoseconds to add. + */ + @SuppressWarnings("NonAtomicOperationOnVolatileField") + protected void reportActiveIoTime(long nanos) { + assert inEventLoop(); + if (nanos > 0) { + accumulatedActiveTimeNanos += nanos; + lastActivityTimeNanos = ticker().nanoTime(); + } + } + + /** + * Returns the accumulated active time since the last call and resets the counter. + */ + protected long getAndResetAccumulatedActiveTimeNanos() { + return ACCUMULATED_ACTIVE_TIME_NANOS_UPDATER.getAndSet(this, 0); + } + + /** + * Returns the timestamp of the last known activity (tasks + I/O). + */ + protected long getLastActivityTimeNanos() { + return lastActivityTimeNanos; + } + + /** + * Atomically increments the counter for consecutive monitor cycles where utilization was below the + * scale-down threshold. This is used by the auto-scaling monitor to track sustained idleness. + * + * @return The number of consecutive idle cycles before the increment. + */ + protected int getAndIncrementIdleCycles() { + return CONSECUTIVE_IDLE_CYCLES_UPDATER.getAndIncrement(this); + } + + /** + * Resets the counter for consecutive idle cycles to zero. This is typically called when the + * executor's utilization is no longer considered idle, breaking the streak. + */ + protected void resetIdleCycles() { + CONSECUTIVE_IDLE_CYCLES_UPDATER.set(this, 0); + } + + /** + * Atomically increments the counter for consecutive monitor cycles where utilization was above the + * scale-up threshold. This is used by the auto-scaling monitor to track a sustained high load. + * + * @return The number of consecutive busy cycles before the increment. + */ + protected int getAndIncrementBusyCycles() { + return CONSECUTIVE_BUSY_CYCLES_UPDATER.getAndIncrement(this); + } + + /** + * Resets the counter for consecutive busy cycles to zero. This is typically called when the + * executor's utilization is no longer considered busy, breaking the streak. + */ + protected void resetBusyCycles() { + CONSECUTIVE_BUSY_CYCLES_UPDATER.set(this, 0); + } + + /** + * Returns {@code true} if this {@link SingleThreadEventExecutor} supports suspension. + */ + protected boolean isSuspensionSupported() { + return supportSuspension; + } + + /** + * Run the tasks in the {@link #taskQueue} + */ + protected abstract void run(); + + /** + * Do nothing, sub-classes may override + */ + protected void cleanup() { + // NOOP + } + + protected void wakeup(boolean inEventLoop) { + if (!inEventLoop) { + // Use offer as we actually only need this to unblock the thread and if offer fails we do not care as there + // is already something in the queue. + taskQueue.offer(WAKEUP_TASK); + } + } + + @Override + public boolean inEventLoop(Thread thread) { + return thread == this.thread; + } + + /** + * Add a {@link Runnable} which will be executed on shutdown of this instance + */ + public void addShutdownHook(final Runnable task) { + if (inEventLoop()) { + shutdownHooks.add(task); + } else { + execute(new Runnable() { + @Override + public void run() { + shutdownHooks.add(task); + } + }); + } + } + + /** + * Remove a previous added {@link Runnable} as a shutdown hook + */ + public void removeShutdownHook(final Runnable task) { + if (inEventLoop()) { + shutdownHooks.remove(task); + } else { + execute(new Runnable() { + @Override + public void run() { + shutdownHooks.remove(task); + } + }); + } + } + + private boolean runShutdownHooks() { + boolean ran = false; + // Note shutdown hooks can add / remove shutdown hooks. + while (!shutdownHooks.isEmpty()) { + List copy = new ArrayList(shutdownHooks); + shutdownHooks.clear(); + for (Runnable task: copy) { + try { + runTask(task); + } catch (Throwable t) { + logger.warn("Shutdown hook raised an exception.", t); + } finally { + ran = true; + } + } + } + + if (ran) { + lastExecutionTime = getCurrentTimeNanos(); + } + + return ran; + } + + private void shutdown0(long quietPeriod, long timeout, int shutdownState) { + if (isShuttingDown()) { + return; + } + + boolean inEventLoop = inEventLoop(); + boolean wakeup; + int oldState; + for (;;) { + if (isShuttingDown()) { + return; + } + int newState; + wakeup = true; + oldState = state; + if (inEventLoop) { + newState = shutdownState; + } else { + switch (oldState) { + case ST_NOT_STARTED: + case ST_STARTED: + case ST_SUSPENDING: + case ST_SUSPENDED: + newState = shutdownState; + break; + default: + newState = oldState; + wakeup = false; + } + } + if (STATE_UPDATER.compareAndSet(this, oldState, newState)) { + break; + } + } + if (quietPeriod != -1) { + gracefulShutdownQuietPeriod = quietPeriod; + } + if (timeout != -1) { + gracefulShutdownTimeout = timeout; + } + + if (ensureThreadStarted(oldState)) { + return; + } + + if (wakeup) { + taskQueue.offer(WAKEUP_TASK); + if (!addTaskWakesUp) { + wakeup(inEventLoop); + } + } + } + + @Override + public Future shutdownGracefully(long quietPeriod, long timeout, TimeUnit unit) { + ObjectUtil.checkPositiveOrZero(quietPeriod, "quietPeriod"); + if (timeout < quietPeriod) { + throw new IllegalArgumentException( + "timeout: " + timeout + " (expected >= quietPeriod (" + quietPeriod + "))"); + } + ObjectUtil.checkNotNull(unit, "unit"); + + shutdown0(unit.toNanos(quietPeriod), unit.toNanos(timeout), ST_SHUTTING_DOWN); + return terminationFuture(); + } + + @Override + public Future terminationFuture() { + return terminationFuture; + } + + @Override + @Deprecated + public void shutdown() { + shutdown0(-1, -1, ST_SHUTDOWN); + } + + @Override + public boolean isShuttingDown() { + return state >= ST_SHUTTING_DOWN; + } + + @Override + public boolean isShutdown() { + return state >= ST_SHUTDOWN; + } + + @Override + public boolean isTerminated() { + return state == ST_TERMINATED; + } + + @Override + public boolean isSuspended() { + int currentState = state; + return currentState == ST_SUSPENDED || currentState == ST_SUSPENDING; + } + + @Override + public boolean trySuspend() { + if (supportSuspension) { + if (STATE_UPDATER.compareAndSet(this, ST_STARTED, ST_SUSPENDING)) { + wakeup(inEventLoop()); + return true; + } else if (STATE_UPDATER.compareAndSet(this, ST_NOT_STARTED, ST_SUSPENDED)) { + return true; + } + int currentState = state; + return currentState == ST_SUSPENDED || currentState == ST_SUSPENDING; + } + return false; + } + + /** + * Returns {@code true} if this {@link SingleThreadEventExecutor} can be suspended at the moment, {@code false} + * otherwise. + * + * @return if suspension is possible at the moment. + */ + protected boolean canSuspend() { + return canSuspend(state); + } + + /** + * Returns {@code true} if this {@link SingleThreadEventExecutor} can be suspended at the moment, {@code false} + * otherwise. + * + * Subclasses might override this method to add extra checks. + * + * @param state the current internal state of the {@link SingleThreadEventExecutor}. + * @return if suspension is possible at the moment. + */ + protected boolean canSuspend(int state) { + assert inEventLoop(); + return supportSuspension && (state == ST_SUSPENDED || state == ST_SUSPENDING) + && !hasTasks() && nextScheduledTaskDeadlineNanos() == -1; + } + + /** + * Confirm that the shutdown if the instance should be done now! + */ + protected boolean confirmShutdown() { + if (!isShuttingDown()) { + return false; + } + + if (!inEventLoop()) { + throw new IllegalStateException("must be invoked from an event loop"); + } + + cancelScheduledTasks(); + + if (gracefulShutdownStartTime == 0) { + gracefulShutdownStartTime = getCurrentTimeNanos(); + } + + if (runAllTasks() || runShutdownHooks()) { + if (isShutdown()) { + // Executor shut down - no new tasks anymore. + return true; + } + + // There were tasks in the queue. Wait a little bit more until no tasks are queued for the quiet period or + // terminate if the quiet period is 0. + // See https://github.com/netty/netty/issues/4241 + if (gracefulShutdownQuietPeriod == 0) { + return true; + } + taskQueue.offer(WAKEUP_TASK); + return false; + } + + final long nanoTime = getCurrentTimeNanos(); + + if (isShutdown() || nanoTime - gracefulShutdownStartTime > gracefulShutdownTimeout) { + return true; + } + + if (nanoTime - lastExecutionTime <= gracefulShutdownQuietPeriod) { + // Check if any tasks were added to the queue every 100ms. + // TODO: Change the behavior of takeTask() so that it returns on timeout. + taskQueue.offer(WAKEUP_TASK); + try { + Thread.sleep(100); + } catch (InterruptedException e) { + // Ignore + } + + return false; + } + + // No tasks were added for last quiet period - hopefully safe to shut down. + // (Hopefully because we really cannot make a guarantee that there will be no execute() calls by a user.) + return true; + } + + @Override + public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { + ObjectUtil.checkNotNull(unit, "unit"); + if (inEventLoop()) { + throw new IllegalStateException("cannot await termination of the current thread"); + } + + threadLock.await(timeout, unit); + + return isTerminated(); + } + + @Override + public void execute(Runnable task) { + execute0(task); + } + + @Override + public void lazyExecute(Runnable task) { + lazyExecute0(task); + } + + private void execute0(@Schedule Runnable task) { + ObjectUtil.checkNotNull(task, "task"); + execute(task, wakesUpForTask(task)); + } + + private void lazyExecute0(@Schedule Runnable task) { + execute(ObjectUtil.checkNotNull(task, "task"), false); + } + + @Override + void scheduleRemoveScheduled(final ScheduledFutureTask task) { + ObjectUtil.checkNotNull(task, "task"); + int currentState = state; + if (supportSuspension && currentState == ST_SUSPENDED) { + // In the case of scheduling for removal we need to also ensure we will recover the "suspend" state + // after it if it was set before. Otherwise we will always end up "unsuspending" things on cancellation + // which is not optimal. + execute(new Runnable() { + @Override + public void run() { + task.run(); + if (canSuspend(ST_SUSPENDED)) { + // Try suspending again to recover the state before we submitted the new task that will + // handle cancellation itself. + trySuspend(); + } + } + }, true); + } else { + // task will remove itself from scheduled task queue when it runs + execute(task, false); + } + } + + private void execute(Runnable task, boolean immediate) { + boolean inEventLoop = inEventLoop(); + addTask(task); + if (!inEventLoop) { + startThread(); + if (isShutdown()) { + boolean reject = false; + try { + if (removeTask(task)) { + reject = true; + } + } catch (UnsupportedOperationException e) { + // The task queue does not support removal so the best thing we can do is to just move on and + // hope we will be able to pick-up the task before its completely terminated. + // In worst case we will log on termination. + } + if (reject) { + reject(); + } + } + } + + if (!addTaskWakesUp && immediate) { + wakeup(inEventLoop); + } + } + + @Override + public T invokeAny(Collection> tasks) throws InterruptedException, ExecutionException { + throwIfInEventLoop("invokeAny"); + return super.invokeAny(tasks); + } + + @Override + public T invokeAny(Collection> tasks, long timeout, TimeUnit unit) + throws InterruptedException, ExecutionException, TimeoutException { + throwIfInEventLoop("invokeAny"); + return super.invokeAny(tasks, timeout, unit); + } + + @Override + public List> invokeAll(Collection> tasks) + throws InterruptedException { + throwIfInEventLoop("invokeAll"); + return super.invokeAll(tasks); + } + + @Override + public List> invokeAll( + Collection> tasks, long timeout, TimeUnit unit) throws InterruptedException { + throwIfInEventLoop("invokeAll"); + return super.invokeAll(tasks, timeout, unit); + } + + private void throwIfInEventLoop(String method) { + if (inEventLoop()) { + throw new RejectedExecutionException("Calling " + method + " from within the EventLoop is not allowed"); + } + } + + /** + * Returns the {@link ThreadProperties} of the {@link Thread} that powers the {@link SingleThreadEventExecutor}. + * If the {@link SingleThreadEventExecutor} is not started yet, this operation will start it and block until + * it is fully started. + */ + public final ThreadProperties threadProperties() { + ThreadProperties threadProperties = this.threadProperties; + if (threadProperties == null) { + Thread thread = this.thread; + if (thread == null) { + assert !inEventLoop(); + submit(NOOP_TASK).syncUninterruptibly(); + thread = this.thread; + assert thread != null; + } + + threadProperties = new DefaultThreadProperties(thread); + if (!PROPERTIES_UPDATER.compareAndSet(this, null, threadProperties)) { + threadProperties = this.threadProperties; + } + } + + return threadProperties; + } + + /** + * @deprecated override {@link SingleThreadEventExecutor#wakesUpForTask} to re-create this behaviour + */ + @Deprecated + protected interface NonWakeupRunnable extends LazyRunnable { } + + /** + * Can be overridden to control which tasks require waking the {@link EventExecutor} thread + * if it is waiting so that they can be run immediately. + */ + protected boolean wakesUpForTask(Runnable task) { + return task.getClass() != NonWakeupNettyRunnable.class; // AzuriteSpigot + } + + protected static void reject() { + throw new RejectedExecutionException("event executor terminated"); + } + + /** + * Offers the task to the associated {@link RejectedExecutionHandler}. + * + * @param task to reject. + */ + protected final void reject(Runnable task) { + rejectedExecutionHandler.rejected(task, this); + } + + // ScheduledExecutorService implementation + + private static final long SCHEDULE_PURGE_INTERVAL = TimeUnit.SECONDS.toNanos(1); + + private void startThread() { + int currentState = state; + if (currentState == ST_NOT_STARTED || currentState == ST_SUSPENDED) { + if (STATE_UPDATER.compareAndSet(this, currentState, ST_STARTED)) { + resetIdleCycles(); + resetBusyCycles(); + boolean success = false; + try { + doStartThread(); + success = true; + } finally { + if (!success) { + STATE_UPDATER.compareAndSet(this, ST_STARTED, ST_NOT_STARTED); + } + } + } + } + } + + private boolean ensureThreadStarted(int oldState) { + if (oldState == ST_NOT_STARTED || oldState == ST_SUSPENDED) { + try { + doStartThread(); + } catch (Throwable cause) { + STATE_UPDATER.set(this, ST_TERMINATED); + terminationFuture.tryFailure(cause); + + if (!(cause instanceof Exception)) { + // Also rethrow as it may be an OOME for example + PlatformDependent.throwException(cause); + } + return true; + } + } + return false; + } + + private void doStartThread() { + executor.execute(new Runnable() { + @Override + public void run() { + processingLock.lock(); + assert thread == null; + thread = Thread.currentThread(); + if (interrupted) { + thread.interrupt(); + interrupted = false; + } + boolean success = false; + Throwable unexpectedException = null; + updateLastExecutionTime(); + boolean suspend = false; + try { + for (;;) { + SingleThreadEventExecutor.this.run(); + success = true; + + int currentState = state; + if (canSuspend(currentState)) { + if (!STATE_UPDATER.compareAndSet(SingleThreadEventExecutor.this, + ST_SUSPENDING, ST_SUSPENDED)) { + // Try again as the CAS failed. + continue; + } + + if (!canSuspend(ST_SUSPENDED) && STATE_UPDATER.compareAndSet(SingleThreadEventExecutor.this, + ST_SUSPENDED, ST_STARTED)) { + // Seems like there was something added to the task queue again in the meantime but we + // were able to re-engage this thread as the event loop thread. + continue; + } + suspend = true; + } + break; + } + } catch (Throwable t) { + unexpectedException = t; + logger.warn("Unexpected exception from an event executor: ", t); + } finally { + boolean shutdown = !suspend; + if (shutdown) { + for (;;) { + // We are re-fetching the state as it might have been shutdown in the meantime. + int oldState = state; + if (oldState >= ST_SHUTTING_DOWN || STATE_UPDATER.compareAndSet( + SingleThreadEventExecutor.this, oldState, ST_SHUTTING_DOWN)) { + break; + } + } + if (success && gracefulShutdownStartTime == 0) { + // Check if confirmShutdown() was called at the end of the loop. + if (logger.isErrorEnabled()) { + logger.error("Buggy " + EventExecutor.class.getSimpleName() + " implementation; " + + SingleThreadEventExecutor.class.getSimpleName() + ".confirmShutdown() must " + + "be called before run() implementation terminates."); + } + } + } + + try { + if (shutdown) { + // Run all remaining tasks and shutdown hooks. At this point the event loop + // is in ST_SHUTTING_DOWN state still accepting tasks which is needed for + // graceful shutdown with quietPeriod. + for (;;) { + if (confirmShutdown()) { + break; + } + } + + // Now we want to make sure no more tasks can be added from this point. This is + // achieved by switching the state. Any new tasks beyond this point will be rejected. + for (;;) { + int currentState = state; + if (currentState >= ST_SHUTDOWN || STATE_UPDATER.compareAndSet( + SingleThreadEventExecutor.this, currentState, ST_SHUTDOWN)) { + break; + } + } + + // We have the final set of tasks in the queue now, no more can be added, run all remaining. + // No need to loop here, this is the final pass. + confirmShutdown(); + } + } finally { + try { + if (shutdown) { + try { + cleanup(); + } finally { + // Lets remove all FastThreadLocals for the Thread as we are about to terminate and + // notify the future. The user may block on the future and once it unblocks the JVM + // may terminate and start unloading classes. + // See https://github.com/netty/netty/issues/6596. + FastThreadLocal.removeAll(); + + STATE_UPDATER.set(SingleThreadEventExecutor.this, ST_TERMINATED); + threadLock.countDown(); + int numUserTasks = drainTasks(); + if (numUserTasks > 0 && logger.isWarnEnabled()) { + logger.warn("An event executor terminated with " + + "non-empty task queue (" + numUserTasks + ')'); + } + if (unexpectedException == null) { + terminationFuture.setSuccess(null); + } else { + terminationFuture.setFailure(unexpectedException); + } + } + } else { + // Lets remove all FastThreadLocals for the Thread as we are about to terminate it. + FastThreadLocal.removeAll(); + + // Reset the stored threadProperties in case of suspension. + threadProperties = null; + } + } finally { + thread = null; + // Let the next thread take over if needed. + processingLock.unlock(); + } + } + } + } + }); + } + + final int drainTasks() { + int numTasks = 0; + for (;;) { + Runnable runnable = taskQueue.poll(); + if (runnable == null) { + break; + } + // WAKEUP_TASK should be just discarded as these are added internally. + // The important bit is that we not have any user tasks left. + if (WAKEUP_TASK != runnable) { + numTasks++; + } + } + return numTasks; + } + + private static final class DefaultThreadProperties implements ThreadProperties { + private final Thread t; + + DefaultThreadProperties(Thread t) { + this.t = t; + } + + @Override + public State state() { + return t.getState(); + } + + @Override + public int priority() { + return t.getPriority(); + } + + @Override + public boolean isInterrupted() { + return t.isInterrupted(); + } + + @Override + public boolean isDaemon() { + return t.isDaemon(); + } + + @Override + public String name() { + return t.getName(); + } + + @Override + public long id() { + return t.getId(); + } + + @Override + public StackTraceElement[] stackTrace() { + return t.getStackTrace(); + } + + @Override + public boolean isAlive() { + return t.isAlive(); + } + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/net/minecraft/server/Achievement.java b/azurite-server/src/main/java/net/minecraft/server/Achievement.java new file mode 100644 index 0000000..e28b233 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/Achievement.java @@ -0,0 +1,84 @@ +package net.minecraft.server; + +public class Achievement extends Statistic { + + public final int a; + public final int b; + public final Achievement c; + private final String k; + public final ItemStack d; + private boolean m; + + public Achievement(String s, String s1, int i, int j, Item item, Achievement achievement) { + this(s, s1, i, j, new ItemStack(item), achievement); + } + + public Achievement(String s, String s1, int i, int j, Block block, Achievement achievement) { + this(s, s1, i, j, new ItemStack(block), achievement); + } + + public Achievement(String s, String s1, int i, int j, ItemStack itemstack, Achievement achievement) { + super(s, new ChatMessage("achievement." + s1)); + this.d = itemstack; + this.k = "achievement." + s1 + ".desc"; + this.a = i; + this.b = j; + + if (i > AchievementList.c) { + AchievementList.c = i; + } + + if (j > AchievementList.d) { + AchievementList.d = j; + } + + this.c = achievement; + } + + public Achievement a() { + this.f = true; + return this; + } + + public Achievement b() { + this.m = true; + return this; + } + + public Achievement c() { + super.h(); + AchievementList.e.add(this); + return this; + } + + public boolean d() { + return true; + } + + public IChatBaseComponent e() { + IChatBaseComponent ichatbasecomponent = super.e(); + + ichatbasecomponent.getChatModifier().setColor(this.g() ? EnumChatFormat.DARK_PURPLE : EnumChatFormat.GREEN); + return ichatbasecomponent; + } + + public Achievement a(Class oclass) { + return (Achievement) super.b(oclass); + } + + public boolean g() { + return this.m; + } + + public Statistic b(Class oclass) { + return this.a(oclass); + } + + public Statistic h() { + return this.c(); + } + + public Statistic i() { + return this.a(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/AchievementList.java b/azurite-server/src/main/java/net/minecraft/server/AchievementList.java new file mode 100644 index 0000000..6a4e914 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/AchievementList.java @@ -0,0 +1,51 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; + +import java.util.List; + +public class AchievementList { + + public static int a; + public static int b; + public static int c; + public static int d; + public static List e = Lists.newArrayList(); + public static Achievement f = (new Achievement("achievement.openInventory", "openInventory", 0, 0, Items.BOOK, null)).a().c(); + public static Achievement g = (new Achievement("achievement.mineWood", "mineWood", 2, 1, Blocks.LOG, AchievementList.f)).c(); + public static Achievement h = (new Achievement("achievement.buildWorkBench", "buildWorkBench", 4, -1, Blocks.CRAFTING_TABLE, AchievementList.g)).c(); + public static Achievement i = (new Achievement("achievement.buildPickaxe", "buildPickaxe", 4, 2, Items.WOODEN_PICKAXE, AchievementList.h)).c(); + public static Achievement j = (new Achievement("achievement.buildFurnace", "buildFurnace", 3, 4, Blocks.FURNACE, AchievementList.i)).c(); + public static Achievement k = (new Achievement("achievement.acquireIron", "acquireIron", 1, 4, Items.IRON_INGOT, AchievementList.j)).c(); + public static Achievement l = (new Achievement("achievement.buildHoe", "buildHoe", 2, -3, Items.WOODEN_HOE, AchievementList.h)).c(); + public static Achievement m = (new Achievement("achievement.makeBread", "makeBread", -1, -3, Items.BREAD, AchievementList.l)).c(); + public static Achievement n = (new Achievement("achievement.bakeCake", "bakeCake", 0, -5, Items.CAKE, AchievementList.l)).c(); + public static Achievement o = (new Achievement("achievement.buildBetterPickaxe", "buildBetterPickaxe", 6, 2, Items.STONE_PICKAXE, AchievementList.i)).c(); + public static Achievement p = (new Achievement("achievement.cookFish", "cookFish", 2, 6, Items.COOKED_FISH, AchievementList.j)).c(); + public static Achievement q = (new Achievement("achievement.onARail", "onARail", 2, 3, Blocks.RAIL, AchievementList.k)).b().c(); + public static Achievement r = (new Achievement("achievement.buildSword", "buildSword", 6, -1, Items.WOODEN_SWORD, AchievementList.h)).c(); + public static Achievement s = (new Achievement("achievement.killEnemy", "killEnemy", 8, -1, Items.BONE, AchievementList.r)).c(); + public static Achievement t = (new Achievement("achievement.killCow", "killCow", 7, -3, Items.LEATHER, AchievementList.r)).c(); + public static Achievement u = (new Achievement("achievement.flyPig", "flyPig", 9, -3, Items.SADDLE, AchievementList.t)).b().c(); + public static Achievement v = (new Achievement("achievement.snipeSkeleton", "snipeSkeleton", 7, 0, Items.BOW, AchievementList.s)).b().c(); + public static Achievement w = (new Achievement("achievement.diamonds", "diamonds", -1, 5, Blocks.DIAMOND_ORE, AchievementList.k)).c(); + public static Achievement x = (new Achievement("achievement.diamondsToYou", "diamondsToYou", -1, 2, Items.DIAMOND, AchievementList.w)).c(); + public static Achievement y = (new Achievement("achievement.portal", "portal", -1, 7, Blocks.OBSIDIAN, AchievementList.w)).c(); + public static Achievement z = (new Achievement("achievement.ghast", "ghast", -4, 8, Items.GHAST_TEAR, AchievementList.y)).b().c(); + public static Achievement A = (new Achievement("achievement.blazeRod", "blazeRod", 0, 9, Items.BLAZE_ROD, AchievementList.y)).c(); + public static Achievement B = (new Achievement("achievement.potion", "potion", 2, 8, Items.POTION, AchievementList.A)).c(); + public static Achievement C = (new Achievement("achievement.theEnd", "theEnd", 3, 10, Items.ENDER_EYE, AchievementList.A)).b().c(); + public static Achievement D = (new Achievement("achievement.theEnd2", "theEnd2", 4, 13, Blocks.DRAGON_EGG, AchievementList.C)).b().c(); + public static Achievement E = (new Achievement("achievement.enchantments", "enchantments", -4, 4, Blocks.ENCHANTING_TABLE, AchievementList.w)).c(); + public static Achievement F = (new Achievement("achievement.overkill", "overkill", -4, 1, Items.DIAMOND_SWORD, AchievementList.E)).b().c(); + public static Achievement G = (new Achievement("achievement.bookcase", "bookcase", -3, 6, Blocks.BOOKSHELF, AchievementList.E)).c(); + public static Achievement H = (new Achievement("achievement.breedCow", "breedCow", 7, -5, Items.WHEAT, AchievementList.t)).c(); + public static Achievement I = (new Achievement("achievement.spawnWither", "spawnWither", 7, 12, new ItemStack(Items.SKULL, 1, 1), AchievementList.D)).c(); + public static Achievement J = (new Achievement("achievement.killWither", "killWither", 7, 10, Items.NETHER_STAR, AchievementList.I)).c(); + public static Achievement K = (new Achievement("achievement.fullBeacon", "fullBeacon", 7, 8, Blocks.BEACON, AchievementList.J)).b().c(); + public static Achievement L = (new Achievement("achievement.exploreAllBiomes", "exploreAllBiomes", 4, 8, Items.DIAMOND_BOOTS, AchievementList.C)).a(AchievementSet.class).b().c(); + public static Achievement M = (new Achievement("achievement.overpowered", "overpowered", 6, 4, new ItemStack(Items.GOLDEN_APPLE, 1, 1), AchievementList.o)).b().c(); + + public static void a() { + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/AchievementSet.java b/azurite-server/src/main/java/net/minecraft/server/AchievementSet.java new file mode 100644 index 0000000..c8278a8 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/AchievementSet.java @@ -0,0 +1,40 @@ +package net.minecraft.server; + +import com.google.common.collect.ForwardingSet; +import com.google.common.collect.Sets; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonPrimitive; + +import java.util.Set; + +public class AchievementSet extends ForwardingSet implements IJsonStatistic { + + private final Set a = Sets.newHashSet(); + + public AchievementSet() { + } + + public void a(JsonElement jsonelement) { + if (jsonelement.isJsonArray()) { + + for (JsonElement jsonelement1 : jsonelement.getAsJsonArray()) { + this.add(jsonelement1.getAsString()); + } + } + } + + public JsonElement a() { + JsonArray jsonarray = new JsonArray(); + for (String s : this) { + jsonarray.add(new JsonPrimitive(s)); + } + + return jsonarray; + } + + protected Set delegate() { + return this.a; + } + +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ArraySet.java b/azurite-server/src/main/java/net/minecraft/server/ArraySet.java new file mode 100644 index 0000000..e209e40 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ArraySet.java @@ -0,0 +1,105 @@ +package net.minecraft.server; + +import com.google.common.collect.Iterators; +import org.jetbrains.annotations.NotNull; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.Set; + +public final class ArraySet implements Set { + + private final ArrayList list = new ArrayList<>(); + + public ArraySet() {} + + public ArraySet(Iterable elements) { + Iterators.addAll(list, elements.iterator()); + } + + @Override + public boolean add(E e) { + return list.add(e); + } + + public void add(int index, E e) { + list.add(index, e); + } + + @Override + public boolean remove(Object o) { + return list.remove(o); + } + + public E remove(int o) { + return list.remove(o); + } + + @Override + public boolean containsAll(@NotNull Collection c) { + return list.containsAll(c); + } + + @Override + public void clear() { + list.clear(); + } + + public E get(int index) { + return list.get(index); + } + + @Override + public boolean removeAll(@NotNull Collection c) { + return list.removeAll(c); + } + + @Override + public boolean retainAll(@NotNull Collection c) { + return list.retainAll(c); + } + + @Override + public boolean addAll(Collection c) { + boolean modified = false; + for (E e : c) + if (add(e)) + modified = true; + return modified; + } + + @Override + public int size() { + return list.size(); + } + + @Override + public boolean isEmpty() { + return list.isEmpty(); + } + + @Override + public boolean contains(Object o) { + return list.contains(o); + } + + @Override + public @NotNull Iterator iterator() { + return list.iterator(); + } + + @Override + public Object @NotNull [] toArray() { + return list.toArray(); + } + + @Override + public T @NotNull [] toArray(T @NotNull [] a) { + return list.toArray(a); + } + + public int indexOf(E o) { + return list.indexOf(o); + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/net/minecraft/server/AttributeBase.java b/azurite-server/src/main/java/net/minecraft/server/AttributeBase.java new file mode 100644 index 0000000..9ef9bfe --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/AttributeBase.java @@ -0,0 +1,47 @@ +package net.minecraft.server; + +public abstract class AttributeBase implements IAttribute { + + private final IAttribute a; + private final String b; + private final double c; + private boolean d; + + protected AttributeBase(IAttribute iattribute, String s, double d0) { + this.a = iattribute; + this.b = s; + this.c = d0; + if (s == null) { + throw new IllegalArgumentException("Name cannot be null!"); + } + } + + public String getName() { + return this.b; + } + + public double b() { + return this.c; + } + + public boolean c() { + return this.d; + } + + public AttributeBase a(boolean flag) { + this.d = flag; + return this; + } + + public IAttribute d() { + return this.a; + } + + public int hashCode() { + return this.b.hashCode(); + } + + public boolean equals(Object object) { + return object instanceof IAttribute && this.b.equals(((IAttribute) object).getName()); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/AttributeInstance.java b/azurite-server/src/main/java/net/minecraft/server/AttributeInstance.java new file mode 100644 index 0000000..c730d77 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/AttributeInstance.java @@ -0,0 +1,27 @@ +package net.minecraft.server; + +import java.util.Collection; +import java.util.UUID; + +public interface AttributeInstance { + + IAttribute getAttribute(); + + double b(); + + void setValue(double d0); + + Collection a(int i); + + Collection c(); + + boolean a(AttributeModifier attributemodifier); + + AttributeModifier a(UUID uuid); + + void b(AttributeModifier attributemodifier); + + void c(AttributeModifier attributemodifier); + + double getValue(); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/AttributeMapBase.java b/azurite-server/src/main/java/net/minecraft/server/AttributeMapBase.java new file mode 100644 index 0000000..daae79f --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/AttributeMapBase.java @@ -0,0 +1,77 @@ +package net.minecraft.server; + +import com.google.common.collect.HashMultimap; +import com.google.common.collect.Maps; +import com.google.common.collect.Multimap; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; + +public abstract class AttributeMapBase { + + protected final Map a = Maps.newHashMap(); + protected final Map b = new HashMap<>(); + protected final Multimap c = HashMultimap.create(); + + public AttributeMapBase() { + } + + public AttributeInstance a(IAttribute iattribute) { + return this.a.get(iattribute); + } + + public AttributeInstance a(String s) { + return this.b.get(s); + } + + public AttributeInstance b(IAttribute iattribute) { + if (this.b.containsKey(iattribute.getName())) { + throw new IllegalArgumentException("Attribute is already registered!"); + } else { + AttributeInstance attributeinstance = this.c(iattribute); + + this.b.put(iattribute.getName(), attributeinstance); + this.a.put(iattribute, attributeinstance); + + for (IAttribute iattribute1 = iattribute.d(); iattribute1 != null; iattribute1 = iattribute1.d()) { + this.c.put(iattribute1, iattribute); + } + + return attributeinstance; + } + } + + protected abstract AttributeInstance c(IAttribute iattribute); + + public Collection a() { + return this.b.values(); + } + + public void a(AttributeInstance attributeinstance) { + } + + public void a(Multimap multimap) { + for (Entry entry : multimap.entries()) { + AttributeInstance attributeinstance = this.a(entry.getKey()); + + if (attributeinstance != null) { + attributeinstance.c(entry.getValue()); + } + } + + } + + public void b(Multimap multimap) { + for (Entry entry : multimap.entries()) { + AttributeInstance attributeinstance = this.a(entry.getKey()); + + if (attributeinstance != null) { + attributeinstance.c(entry.getValue()); + attributeinstance.b(entry.getValue()); + } + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/AttributeMapServer.java b/azurite-server/src/main/java/net/minecraft/server/AttributeMapServer.java new file mode 100644 index 0000000..d2eddb4 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/AttributeMapServer.java @@ -0,0 +1,80 @@ +package net.minecraft.server; + +import com.google.common.collect.Sets; + +import java.util.*; + +public class AttributeMapServer extends AttributeMapBase { + private final Set e = Sets.newHashSet(); + + protected final Map d = new HashMap<>(); + + public AttributeModifiable e(IAttribute paramIAttribute) { + return (AttributeModifiable) super.a(paramIAttribute); + } + + public AttributeModifiable b(String paramString) { + AttributeInstance attributeInstance = super.a(paramString); + if (attributeInstance == null) + attributeInstance = this.d.get(paramString); + return (AttributeModifiable) attributeInstance; + } + + public AttributeInstance b(IAttribute paramIAttribute) { + AttributeInstance attributeInstance = super.b(paramIAttribute); + if (paramIAttribute instanceof AttributeRanged && ((AttributeRanged) paramIAttribute).g() != null) + this.d.put(((AttributeRanged) paramIAttribute).g(), attributeInstance); + return attributeInstance; + } + + protected AttributeInstance c(IAttribute paramIAttribute) { + return new AttributeModifiable(this, paramIAttribute); + } + + public void a(AttributeInstance paramAttributeInstance) { + if (paramAttributeInstance.getAttribute().c()) + this.e.add(paramAttributeInstance); + for (IAttribute iAttribute : this.c.get(paramAttributeInstance.getAttribute())) { + AttributeModifiable attributeModifiable = e(iAttribute); + if (attributeModifiable != null) + attributeModifiable.f(); + } + } + + public Set getAttributes() { + return this.e; + } + + public Collection c() { + HashSet hashSet = Sets.newHashSet(); + for (AttributeInstance attributeInstance : a()) { + if (attributeInstance.getAttribute().c()) + hashSet.add(attributeInstance); + } + return hashSet; + } + + // Beanes - useful attribute set + public Collection getUsefulAttributes(boolean horse) { + Set hashset = new HashSet<>(); + + for (AttributeInstance attributeinstance : this.a()) { + if (attributeinstance.getAttribute().c()) { + // Don't send default attribute values, these are initialized on the client + // This method is only used by spawning the entity + if (attributeinstance.getAttribute().b() == attributeinstance.getValue() && (!horse || attributeinstance.getAttribute() != GenericAttributes.maxHealth)) { + continue; + } + + // Only send movement speed for horses not other entities + if (attributeinstance.getAttribute() == GenericAttributes.MOVEMENT_SPEED && !horse) { + continue; + } + + hashset.add(attributeinstance); + } + } + + return hashset; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/AttributeModifiable.java b/azurite-server/src/main/java/net/minecraft/server/AttributeModifiable.java new file mode 100644 index 0000000..1555e05 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/AttributeModifiable.java @@ -0,0 +1,149 @@ +package net.minecraft.server; + +import com.google.common.collect.Maps; +import com.google.common.collect.Sets; + +import java.util.*; + +public class AttributeModifiable implements AttributeInstance { + + private final AttributeMapBase a; + private final IAttribute b; + private final Map> c = Maps.newHashMap(); + private final Map> d = Maps.newHashMap(); + private final Map e = Maps.newHashMap(); + private double f; + private boolean g = true; + private double h; + + public AttributeModifiable(AttributeMapBase attributemapbase, IAttribute iattribute) { + this.a = attributemapbase; + this.b = iattribute; + this.f = iattribute.b(); + + for (int i = 0; i < 3; ++i) { + this.c.put(i, Sets.newHashSet()); // Vortex + } + } + + public IAttribute getAttribute() { + return this.b; + } + + public double b() { + return this.f; + } + + public void setValue(double d0) { + if (d0 != this.b()) { + this.f = d0; + this.f(); + } + } + + public Collection a(int i) { + return this.c.get(i); + } + + public Collection c() { + Set hashset = Sets.newHashSet(); + + for (int i = 0; i < 3; ++i) { + hashset.addAll(this.a(i)); + } + + return hashset; + } + + public AttributeModifier a(UUID uuid) { + return this.e.get(uuid); + } + + public boolean a(AttributeModifier attributemodifier) { + return this.e.get(attributemodifier.a()) != null; + } + + public void b(AttributeModifier attributemodifier) { + if (this.a(attributemodifier.a()) != null) { + throw new IllegalArgumentException("Modifier is already applied on this attribute!"); + } else { + Set object = this.d.computeIfAbsent(attributemodifier.b(), k -> Sets.newHashSet()); + + this.c.get(attributemodifier.c()).add(attributemodifier); + object.add(attributemodifier); + this.e.put(attributemodifier.a(), attributemodifier); + this.f(); + } + } + + protected void f() { + this.g = true; + this.a.a(this); + } + + public void c(AttributeModifier attributemodifier) { + for (int i = 0; i < 3; ++i) { + c.get(i).remove(attributemodifier); + } + + Set set1 = this.d.get(attributemodifier.b()); + + if (set1 != null) { + set1.remove(attributemodifier); + if (set1.isEmpty()) { + this.d.remove(attributemodifier.b()); + } + } + + this.e.remove(attributemodifier.a()); + this.f(); + } + + public double getValue() { + if (this.g) { + this.h = this.g(); + this.g = false; + } + + return this.h; + } + + private double g() { + double d0 = this.b(); + + AttributeModifier attributemodifier; + + for (Iterator iterator = this.b(0).iterator(); iterator.hasNext(); d0 += attributemodifier.d()) { + attributemodifier = iterator.next(); + } + + double d1 = d0; + + Iterator iterator1; + AttributeModifier attributemodifier1; + + for (iterator1 = this.b(1).iterator(); iterator1.hasNext(); d1 += d0 * attributemodifier1.d()) { + attributemodifier1 = iterator1.next(); + } + + for (iterator1 = this.b(2).iterator(); iterator1.hasNext(); d1 *= 1.0D + attributemodifier1.d()) { + attributemodifier1 = iterator1.next(); + } + + return this.b.a(d1); + } + + private Collection b(int i) { + HashSet hashset = Sets.newHashSet(this.a(i)); + + for (IAttribute iattribute = this.b.d(); iattribute != null; iattribute = iattribute.d()) { + AttributeInstance attributeinstance = this.a.a(iattribute); + + if (attributeinstance != null) { + hashset.addAll(attributeinstance.a(i)); + } + } + + return hashset; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/AttributeModifier.java b/azurite-server/src/main/java/net/minecraft/server/AttributeModifier.java new file mode 100644 index 0000000..4a7b6df --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/AttributeModifier.java @@ -0,0 +1,74 @@ +package net.minecraft.server; + +import io.netty.util.internal.ThreadLocalRandom; +import org.apache.commons.lang3.Validate; + +import java.util.Objects; +import java.util.UUID; + +public class AttributeModifier { + private final double a; + + private final int b; + + private final String c; + + private final UUID d; + + private boolean e = true; + + public AttributeModifier(String paramString, double paramDouble, int paramInt) { + this(MathHelper.a(ThreadLocalRandom.current()), paramString, paramDouble, paramInt); + } + + public AttributeModifier(UUID paramUUID, String paramString, double paramDouble, int paramInt) { + this.d = paramUUID; + this.c = paramString; + this.a = paramDouble; + this.b = paramInt; + Validate.notEmpty(paramString, "Modifier name cannot be empty"); + Validate.inclusiveBetween(0L, 2L, paramInt, "Invalid operation"); + } + + public UUID a() { + return this.d; + } + + public String b() { + return this.c; + } + + public int c() { + return this.b; + } + + public double d() { + return this.a; + } + + public boolean e() { + return this.e; + } + + public AttributeModifier a(boolean paramBoolean) { + this.e = paramBoolean; + return this; + } + + public boolean equals(Object paramObject) { + if (this == paramObject) + return true; + if (paramObject == null || getClass() != paramObject.getClass()) + return false; + AttributeModifier attributeModifier = (AttributeModifier) paramObject; + return Objects.equals(this.d, attributeModifier.d); + } + + public int hashCode() { + return (this.d != null) ? this.d.hashCode() : 0; + } + + public String toString() { + return "AttributeModifier{amount=" + this.a + ", operation=" + this.b + ", name='" + this.c + '\'' + ", id=" + this.d + ", serialize=" + this.e + '}'; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/AttributeRanged.java b/azurite-server/src/main/java/net/minecraft/server/AttributeRanged.java new file mode 100644 index 0000000..838daed --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/AttributeRanged.java @@ -0,0 +1,35 @@ +package net.minecraft.server; + +public class AttributeRanged extends AttributeBase { + + private final double a; + public double b; // Spigot + private String c; + + public AttributeRanged(IAttribute iattribute, String s, double d0, double d1, double d2) { + super(iattribute, s, d0); + this.a = d1; + this.b = d2; + if (d1 > d2) { + throw new IllegalArgumentException("Minimum value cannot be bigger than maximum value!"); + } else if (d0 < d1) { + throw new IllegalArgumentException("Default value cannot be lower than minimum value!"); + } else if (d0 > d2) { + throw new IllegalArgumentException("Default value cannot be bigger than maximum value!"); + } + } + + public AttributeRanged a(String s) { + this.c = s; + return this; + } + + public String g() { + return this.c; + } + + public double a(double d0) { + d0 = MathHelper.a(d0, this.a, this.b); + return d0; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/AxisAlignedBB.java b/azurite-server/src/main/java/net/minecraft/server/AxisAlignedBB.java new file mode 100644 index 0000000..6f69039 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/AxisAlignedBB.java @@ -0,0 +1,208 @@ +package net.minecraft.server; + +public class AxisAlignedBB { + public double a, b, c, d, e, f; + + // Azurite - empty constructor + public AxisAlignedBB() { + + } + + public AxisAlignedBB(double d0, double d1, double d2, double d3, double d4, double d5) { + this.a = Math.min(d0, d3); + this.b = Math.min(d1, d4); + this.c = Math.min(d2, d5); + this.d = Math.max(d0, d3); + this.e = Math.max(d1, d4); + this.f = Math.max(d2, d5); + } + + public AxisAlignedBB(BlockPosition blockposition, BlockPosition blockposition1) { + this.a = blockposition.getX(); + this.b = blockposition.getY(); + this.c = blockposition.getZ(); + this.d = blockposition1.getX(); + this.e = blockposition1.getY(); + this.f = blockposition1.getZ(); + } + + public AxisAlignedBB a(double d0, double d1, double d2) { + double d3 = this.a; + double d4 = this.b; + double d5 = this.c; + double d6 = this.d; + double d7 = this.e; + double d8 = this.f; + if (d0 < 0.0) { + d3 += d0; + } else if (d0 > 0.0) { + d6 += d0; + } + if (d1 < 0.0) { + d4 += d1; + } else if (d1 > 0.0) { + d7 += d1; + } + if (d2 < 0.0) { + d5 += d2; + } else if (d2 > 0.0) { + d8 += d2; + } + return new AxisAlignedBB(d3, d4, d5, d6, d7, d8); + } + + public AxisAlignedBB grow(double d0, double d1, double d2) { + return new AxisAlignedBB(a - d0, b - d1, c - d2, d + d0, e + d1, f + d2); + } + + public AxisAlignedBB a(AxisAlignedBB axisalignedbb) { + return new AxisAlignedBB(Math.min(this.a, axisalignedbb.a), Math.min(this.b, axisalignedbb.b), Math.min(this.c, axisalignedbb.c), Math.max(this.d, axisalignedbb.d), Math.max(this.e, axisalignedbb.e), Math.max(this.f, axisalignedbb.f)); + } + + public static AxisAlignedBB a(double d0, double d1, double d2, double d3, double d4, double d5) { + return new AxisAlignedBB(Math.min(d0, d3), Math.min(d1, d4), Math.min(d2, d5), Math.max(d0, d3), Math.max(d1, d4), Math.max(d2, d5)); + } + + public AxisAlignedBB c(double d0, double d1, double d2) { + return new AxisAlignedBB(this.a + d0, this.b + d1, this.c + d2, this.d + d0, this.e + d1, this.f + d2); + } + + public double a(AxisAlignedBB axisalignedbb, double d0) { + if (axisalignedbb.e > this.b && axisalignedbb.b < this.e && axisalignedbb.f > this.c && axisalignedbb.c < this.f) { + double d1; + if (d0 > 0.0 && axisalignedbb.d <= this.a) { + double d12 = this.a - axisalignedbb.d; + if (d12 < d0) { + d0 = d12; + } + } else if (d0 < 0.0 && axisalignedbb.a >= this.d && (d1 = this.d - axisalignedbb.a) > d0) { + d0 = d1; + } + return d0; + } + return d0; + } + + public double b(AxisAlignedBB axisalignedbb, double d0) { + if (axisalignedbb.d > this.a && axisalignedbb.a < this.d && axisalignedbb.f > this.c && axisalignedbb.c < this.f) { + double d1; + if (d0 > 0.0 && axisalignedbb.e <= this.b) { + double d12 = this.b - axisalignedbb.e; + if (d12 < d0) { + d0 = d12; + } + } else if (d0 < 0.0 && axisalignedbb.b >= this.e && (d1 = this.e - axisalignedbb.b) > d0) { + d0 = d1; + } + return d0; + } + return d0; + } + + public double c(AxisAlignedBB axisalignedbb, double d0) { + if (axisalignedbb.d > this.a && axisalignedbb.a < this.d && axisalignedbb.e > this.b && axisalignedbb.b < this.e) { + double d1; + if (d0 > 0.0 && axisalignedbb.f <= this.c) { + double d12 = this.c - axisalignedbb.f; + if (d12 < d0) { + d0 = d12; + } + } else if (d0 < 0.0 && axisalignedbb.c >= this.f && (d1 = this.f - axisalignedbb.c) > d0) { + d0 = d1; + } + return d0; + } + return d0; + } + + public boolean b(AxisAlignedBB axisalignedbb) { + return axisalignedbb.d > this.a && axisalignedbb.a < this.d && (axisalignedbb.e > this.b && axisalignedbb.b < this.e && axisalignedbb.f > this.c && axisalignedbb.c < this.f); + } + + public boolean a(Vec3D vec3d) { + return vec3d.a > this.a && vec3d.a < this.d && (vec3d.b > this.b && vec3d.b < this.e && vec3d.c > this.c && vec3d.c < this.f); + } + + public double a() { + return (d - a + e - b + f - c) / 3.0; + } + + public AxisAlignedBB shrink(double d0, double d1, double d2) { + return new AxisAlignedBB(a + d0, b + d1, c + d2, d - d0, e - d1, f - d2); + } + + public MovingObjectPosition a(Vec3D vec3d, Vec3D vec3d1) { + Vec3D vec3d2 = vec3d.a(vec3d1, this.a); + Vec3D vec3d3 = vec3d.a(vec3d1, this.d); + Vec3D vec3d4 = vec3d.b(vec3d1, this.b); + Vec3D vec3d5 = vec3d.b(vec3d1, this.e); + Vec3D vec3d6 = vec3d.c(vec3d1, this.c); + Vec3D vec3d7 = vec3d.c(vec3d1, this.f); + if (!this.b(vec3d2)) { + vec3d2 = null; + } + if (!this.b(vec3d3)) { + vec3d3 = null; + } + if (!this.c(vec3d4)) { + vec3d4 = null; + } + if (!this.c(vec3d5)) { + vec3d5 = null; + } + if (!this.d(vec3d6)) { + vec3d6 = null; + } + if (!this.d(vec3d7)) { + vec3d7 = null; + } + Vec3D vec3d8 = null; + if (vec3d2 != null) { + vec3d8 = vec3d2; + } + if (vec3d3 != null && (vec3d8 == null || vec3d.distanceSquared(vec3d3) < vec3d.distanceSquared(vec3d8))) { + vec3d8 = vec3d3; + } + if (vec3d4 != null && (vec3d8 == null || vec3d.distanceSquared(vec3d4) < vec3d.distanceSquared(vec3d8))) { + vec3d8 = vec3d4; + } + if (vec3d5 != null && (vec3d8 == null || vec3d.distanceSquared(vec3d5) < vec3d.distanceSquared(vec3d8))) { + vec3d8 = vec3d5; + } + if (vec3d6 != null && (vec3d8 == null || vec3d.distanceSquared(vec3d6) < vec3d.distanceSquared(vec3d8))) { + vec3d8 = vec3d6; + } + if (vec3d7 != null && (vec3d8 == null || vec3d.distanceSquared(vec3d7) < vec3d.distanceSquared(vec3d8))) { + vec3d8 = vec3d7; + } + if (vec3d8 == null) { + return null; + } + return new MovingObjectPosition(vec3d8, vec3d8 == vec3d2 ? EnumDirection.WEST : (vec3d8 == vec3d3 ? EnumDirection.EAST : (vec3d8 == vec3d4 ? EnumDirection.DOWN : (vec3d8 == vec3d5 ? EnumDirection.UP : (vec3d8 == vec3d6 ? EnumDirection.NORTH : EnumDirection.SOUTH))))); + } + + private boolean b(Vec3D vec3d) { + return vec3d != null && vec3d.b >= this.b && vec3d.b <= this.e && vec3d.c >= this.c && vec3d.c <= this.f; + } + + private boolean c(Vec3D vec3d) { + return vec3d != null && vec3d.a >= this.a && vec3d.a <= this.d && vec3d.c >= this.c && vec3d.c <= this.f; + } + + private boolean d(Vec3D vec3d) { + return vec3d != null && vec3d.a >= this.a && vec3d.a <= this.d && vec3d.b >= this.b && vec3d.b <= this.e; + } + + public void d(AxisAlignedBB paramAxisAlignedBB) { + this.a = paramAxisAlignedBB.a; + this.b = paramAxisAlignedBB.b; + this.c = paramAxisAlignedBB.c; + this.d = paramAxisAlignedBB.d; + this.e = paramAxisAlignedBB.e; + this.f = paramAxisAlignedBB.f; + } + + public String toString() { + return "box[" + this.a + ", " + this.b + ", " + this.c + " -> " + this.d + ", " + this.e + ", " + this.f + "]"; + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/net/minecraft/server/BaseBlockPosition.java b/azurite-server/src/main/java/net/minecraft/server/BaseBlockPosition.java new file mode 100644 index 0000000..2d671df --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BaseBlockPosition.java @@ -0,0 +1,108 @@ +package net.minecraft.server; + +import com.google.common.base.Objects; +import org.jetbrains.annotations.NotNull; + +public class BaseBlockPosition implements Comparable { + + public static final BaseBlockPosition ZERO = new BaseBlockPosition(0, 0, 0); + // PaperSpigot start - Make mutable and protected for MutableBlockPos + protected int a; + protected int c; + protected int d; + // PaperSpigot end + + public BaseBlockPosition(int i, int j, int k) { + this.a = i; + this.c = j; + this.d = k; + } + + public BaseBlockPosition(double d0, double d1, double d2) { + this(MathHelper.floor(d0), MathHelper.floor(d1), MathHelper.floor(d2)); + } + + public boolean equals(Object object) { + if (this == object) { + return true; + } else if (!(object instanceof BaseBlockPosition)) { + return false; + } else { + BaseBlockPosition baseblockposition = (BaseBlockPosition) object; + + return a == baseblockposition.getX() && c == baseblockposition.getY() && d == baseblockposition.getZ(); + } + } + + public int hashCode() { + return (c + d * 31) * 31 + a; + } + + public int g(BaseBlockPosition baseblockposition) { + return c == baseblockposition.getY() ? (d == baseblockposition.getZ() ? a - baseblockposition.getX() : d - baseblockposition.getZ()) : c - baseblockposition.getY(); + } + + public void setX(int x) { + this.a = x; + } + + public void setY(int y) { + this.c = y; + } + + public void setZ(int z) { + this.d = z; + } + + // PaperSpigot start - Only allow one implementation of these methods (make final) + public int getX() { + return this.a; + } + + public int getY() { + return this.c; + } + + public int getZ() { + return this.d; + } + // PaperSpigot end + + public BaseBlockPosition d(BaseBlockPosition baseblockposition) { + return new BaseBlockPosition(c * baseblockposition.getZ() - d * baseblockposition.getY(), d * baseblockposition.getX() - a * baseblockposition.getZ(), a * baseblockposition.getY() - c * baseblockposition.getX()); + } + + public double c(double d0, double d1, double d2) { + double d3 = a - d0; + double d4 = c - d1; + double d5 = d - d2; + + return d3 * d3 + d4 * d4 + d5 * d5; + } + + public double d(double d0, double d1, double d2) { + double d3 = a + 0.5D - d0; + double d4 = c + 0.5D - d1; + double d5 = d + 0.5D - d2; + + return d3 * d3 + d4 * d4 + d5 * d5; + } + + public double i(BaseBlockPosition baseblockposition) { + return this.c(baseblockposition.getX(), baseblockposition.getY(), baseblockposition.getZ()); + } + + public double i(int x, int y, int z) { + return this.c(x, y, z); + } + + public String toString() { + return Objects.toStringHelper(this).add("x", a).add("y", c).add("z", d).toString(); + } + + // Paperspigot - Signature change, Object -> BaseBlockPosition + @Override + public int compareTo(@NotNull BaseBlockPosition object) { + return this.g(object); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BiomeBase.java b/azurite-server/src/main/java/net/minecraft/server/BiomeBase.java new file mode 100644 index 0000000..a014b45 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BiomeBase.java @@ -0,0 +1,493 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import com.google.common.collect.Sets; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.lang.reflect.Constructor; +import java.util.*; + +public abstract class BiomeBase { + + private static final Logger aD = LogManager.getLogger(); + protected static final BiomeTemperature a = new BiomeTemperature(0.1F, 0.2F); + protected static final BiomeTemperature b = new BiomeTemperature(-0.5F, 0.0F); + protected static final BiomeTemperature c = new BiomeTemperature(-1.0F, 0.1F); + protected static final BiomeTemperature d = new BiomeTemperature(-1.8F, 0.1F); + protected static final BiomeTemperature e = new BiomeTemperature(0.125F, 0.05F); + protected static final BiomeTemperature f = new BiomeTemperature(0.2F, 0.2F); + protected static final BiomeTemperature g = new BiomeTemperature(0.45F, 0.3F); + protected static final BiomeTemperature h = new BiomeTemperature(1.5F, 0.025F); + protected static final BiomeTemperature i = new BiomeTemperature(1.0F, 0.5F); + protected static final BiomeTemperature j = new BiomeTemperature(0.0F, 0.025F); + protected static final BiomeTemperature k = new BiomeTemperature(0.1F, 0.8F); + protected static final BiomeTemperature l = new BiomeTemperature(0.2F, 0.3F); + protected static final BiomeTemperature m = new BiomeTemperature(-0.2F, 0.1F); + private static final BiomeBase[] biomes = new BiomeBase[256]; + public static final Set n = Sets.newHashSet(); + public static final Map o = Maps.newHashMap(); + public static final BiomeBase OCEAN = (new BiomeOcean(0)).b(112).a("Ocean").a(BiomeBase.c); + public static final BiomeBase PLAINS = (new BiomePlains(1)).b(9286496).a("Plains"); + public static final BiomeBase DESERT = (new BiomeDesert(2)).b(16421912).a("Desert").b().a(2.0F, 0.0F).a(BiomeBase.e); + public static final BiomeBase EXTREME_HILLS = (new BiomeBigHills(3, false)).b(6316128).a("Extreme Hills").a(BiomeBase.i).a(0.2F, 0.3F); + public static final BiomeBase FOREST = (new BiomeForest(4, 0)).b(353825).a("Forest"); + public static final BiomeBase TAIGA = (new BiomeTaiga(5, 0)).b(747097).a("Taiga").a(5159473).a(0.25F, 0.8F).a(BiomeBase.f); + public static final BiomeBase SWAMPLAND = (new BiomeSwamp(6)).b(522674).a("Swampland").a(9154376).a(BiomeBase.m).a(0.8F, 0.9F); + public static final BiomeBase RIVER = (new BiomeRiver(7)).b(255).a("River").a(BiomeBase.b); + public static final BiomeBase HELL = (new BiomeHell(8)).b(16711680).a("Hell").b().a(2.0F, 0.0F); + public static final BiomeBase SKY = (new BiomeTheEnd(9)).b(8421631).a("The End").b(); + public static final BiomeBase FROZEN_OCEAN = (new BiomeOcean(10)).b(9474208).a("FrozenOcean").c().a(BiomeBase.c).a(0.0F, 0.5F); + public static final BiomeBase FROZEN_RIVER = (new BiomeRiver(11)).b(10526975).a("FrozenRiver").c().a(BiomeBase.b).a(0.0F, 0.5F); + public static final BiomeBase ICE_PLAINS = (new BiomeIcePlains(12, false)).b(16777215).a("Ice Plains").c().a(0.0F, 0.5F).a(BiomeBase.e); + public static final BiomeBase ICE_MOUNTAINS = (new BiomeIcePlains(13, false)).b(10526880).a("Ice Mountains").c().a(BiomeBase.g).a(0.0F, 0.5F); + public static final BiomeBase MUSHROOM_ISLAND = (new BiomeMushrooms(14)).b(16711935).a("MushroomIsland").a(0.9F, 1.0F).a(BiomeBase.l); + public static final BiomeBase MUSHROOM_SHORE = (new BiomeMushrooms(15)).b(10486015).a("MushroomIslandShore").a(0.9F, 1.0F).a(BiomeBase.j); + public static final BiomeBase BEACH = (new BiomeBeach(16)).b(16440917).a("Beach").a(0.8F, 0.4F).a(BiomeBase.j); + public static final BiomeBase DESERT_HILLS = (new BiomeDesert(17)).b(13786898).a("DesertHills").b().a(2.0F, 0.0F).a(BiomeBase.g); + public static final BiomeBase FOREST_HILLS = (new BiomeForest(18, 0)).b(2250012).a("ForestHills").a(BiomeBase.g); + public static final BiomeBase TAIGA_HILLS = (new BiomeTaiga(19, 0)).b(1456435).a("TaigaHills").a(5159473).a(0.25F, 0.8F).a(BiomeBase.g); + public static final BiomeBase SMALL_MOUNTAINS = (new BiomeBigHills(20, true)).b(7501978).a("Extreme Hills Edge").a(BiomeBase.i.a()).a(0.2F, 0.3F); + public static final BiomeBase JUNGLE = (new BiomeJungle(21, false)).b(5470985).a("Jungle").a(5470985).a(0.95F, 0.9F); + public static final BiomeBase JUNGLE_HILLS = (new BiomeJungle(22, false)).b(2900485).a("JungleHills").a(5470985).a(0.95F, 0.9F).a(BiomeBase.g); + public static final BiomeBase JUNGLE_EDGE = (new BiomeJungle(23, true)).b(6458135).a("JungleEdge").a(5470985).a(0.95F, 0.8F); + public static final BiomeBase DEEP_OCEAN = (new BiomeOcean(24)).b(48).a("Deep Ocean").a(BiomeBase.d); + public static final BiomeBase STONE_BEACH = (new BiomeStoneBeach(25)).b(10658436).a("Stone Beach").a(0.2F, 0.3F).a(BiomeBase.k); + public static final BiomeBase COLD_BEACH = (new BiomeBeach(26)).b(16445632).a("Cold Beach").a(0.05F, 0.3F).a(BiomeBase.j).c(); + public static final BiomeBase BIRCH_FOREST = (new BiomeForest(27, 2)).a("Birch Forest").b(3175492); + public static final BiomeBase BIRCH_FOREST_HILLS = (new BiomeForest(28, 2)).a("Birch Forest Hills").b(2055986).a(BiomeBase.g); + public static final BiomeBase ROOFED_FOREST = (new BiomeForest(29, 3)).b(4215066).a("Roofed Forest"); + public static final BiomeBase COLD_TAIGA = (new BiomeTaiga(30, 0)).b(3233098).a("Cold Taiga").a(5159473).c().a(-0.5F, 0.4F).a(BiomeBase.f).c(16777215); + public static final BiomeBase COLD_TAIGA_HILLS = (new BiomeTaiga(31, 0)).b(2375478).a("Cold Taiga Hills").a(5159473).c().a(-0.5F, 0.4F).a(BiomeBase.g).c(16777215); + public static final BiomeBase MEGA_TAIGA = (new BiomeTaiga(32, 1)).b(5858897).a("Mega Taiga").a(5159473).a(0.3F, 0.8F).a(BiomeBase.f); + public static final BiomeBase MEGA_TAIGA_HILLS = (new BiomeTaiga(33, 1)).b(4542270).a("Mega Taiga Hills").a(5159473).a(0.3F, 0.8F).a(BiomeBase.g); + public static final BiomeBase EXTREME_HILLS_PLUS = (new BiomeBigHills(34, true)).b(5271632).a("Extreme Hills+").a(BiomeBase.i).a(0.2F, 0.3F); + public static final BiomeBase SAVANNA = (new BiomeSavanna(35)).b(12431967).a("Savanna").a(1.2F, 0.0F).b().a(BiomeBase.e); + public static final BiomeBase SAVANNA_PLATEAU = (new BiomeSavanna(36)).b(10984804).a("Savanna Plateau").a(1.0F, 0.0F).b().a(BiomeBase.h); + public static final BiomeBase MESA = (new BiomeMesa(37, false, false)).b(14238997).a("Mesa"); + public static final BiomeBase MESA_PLATEAU_F = (new BiomeMesa(38, false, true)).b(11573093).a("Mesa Plateau F").a(BiomeBase.h); + public static final BiomeBase MESA_PLATEAU = (new BiomeMesa(39, false, false)).b(13274213).a("Mesa Plateau").a(BiomeBase.h); + public static final BiomeBase ad = BiomeBase.OCEAN; + protected static final NoiseGenerator3 ae; + protected static final NoiseGenerator3 af; + protected static final WorldGenTallPlant ag; + public String ah; + public int ai; + public int aj; + public IBlockData ak; + public IBlockData al; + public int am; + public float an; + public float ao; + public float temperature; + public float humidity; + public int ar; + public BiomeDecorator as; + protected List at; + protected List au; + protected List av; + protected List aw; + protected boolean ax; + protected boolean ay; + public final int id; + protected WorldGenTrees aA; + protected WorldGenBigTree aB; + protected WorldGenSwampTree aC; + + protected BiomeBase(int i) { + this.ak = Blocks.GRASS.getBlockData(); + this.al = Blocks.DIRT.getBlockData(); + this.am = 5169201; + this.an = BiomeBase.a.a; + this.ao = BiomeBase.a.b; + this.temperature = 0.5F; + this.humidity = 0.5F; + this.ar = 16777215; + this.at = Lists.newArrayList(); + this.au = Lists.newArrayList(); + this.av = Lists.newArrayList(); + this.aw = Lists.newArrayList(); + this.ay = true; + this.aA = new WorldGenTrees(false); + this.aB = new WorldGenBigTree(false); + this.aC = new WorldGenSwampTree(); + this.id = i; + BiomeBase.biomes[i] = this; + this.as = this.a(); + this.au.add(new BiomeMeta(EntitySheep.class, 12, 4, 4)); + this.au.add(new BiomeMeta(EntityRabbit.class, 10, 3, 3)); + this.au.add(new BiomeMeta(EntityPig.class, 10, 4, 4)); + this.au.add(new BiomeMeta(EntityChicken.class, 10, 4, 4)); + this.au.add(new BiomeMeta(EntityCow.class, 8, 4, 4)); + this.at.add(new BiomeMeta(EntitySpider.class, 100, 4, 4)); + this.at.add(new BiomeMeta(EntityZombie.class, 100, 4, 4)); + this.at.add(new BiomeMeta(EntitySkeleton.class, 100, 4, 4)); + this.at.add(new BiomeMeta(EntityCreeper.class, 100, 4, 4)); + this.at.add(new BiomeMeta(EntitySlime.class, 100, 4, 4)); + this.at.add(new BiomeMeta(EntityEnderman.class, 10, 1, 4)); + this.at.add(new BiomeMeta(EntityWitch.class, 5, 1, 1)); + this.av.add(new BiomeMeta(EntitySquid.class, 10, 4, 4)); + this.aw.add(new BiomeMeta(EntityBat.class, 10, 8, 8)); + } + + protected BiomeDecorator a() { + return new BiomeDecorator(); + } + + protected BiomeBase a(float f, float f1) { + if (f > 0.1F && f < 0.2F) { + throw new IllegalArgumentException("Please avoid temperatures in the range 0.1 - 0.2 because of snow"); + } else { + this.temperature = f; + this.humidity = f1; + return this; + } + } + + protected final BiomeBase a(BiomeTemperature biomebase_biometemperature) { + this.an = biomebase_biometemperature.a; + this.ao = biomebase_biometemperature.b; + return this; + } + + protected BiomeBase b() { + this.ay = false; + return this; + } + + public WorldGenTreeAbstract a(Random random) { + return (random.nextInt(10) == 0 ? this.aB : this.aA); + } + + public WorldGenerator b(Random random) { + return new WorldGenGrass(BlockLongGrass.EnumTallGrassType.GRASS); + } + + public BlockFlowers.EnumFlowerVarient a(Random random, BlockPosition blockposition) { + return random.nextInt(3) > 0 ? BlockFlowers.EnumFlowerVarient.DANDELION : BlockFlowers.EnumFlowerVarient.POPPY; + } + + protected BiomeBase c() { + this.ax = true; + return this; + } + + protected BiomeBase a(String s) { + this.ah = s; + return this; + } + + protected BiomeBase a(int i) { + this.am = i; + return this; + } + + protected BiomeBase b(int i) { + this.a(i, false); + return this; + } + + protected BiomeBase c(int i) { + this.aj = i; + return this; + } + + protected BiomeBase a(int i, boolean flag) { + this.ai = i; + if (flag) { + this.aj = (i & 16711422) >> 1; + } else { + this.aj = i; + } + + return this; + } + + public List getMobs(EnumCreatureType enumcreaturetype) { + switch (SyntheticClass_1.switchMap[enumcreaturetype.ordinal()]) { + case 1: + return this.at; + + case 2: + return this.au; + + case 3: + return this.av; + + case 4: + return this.aw; + + default: + return Collections.emptyList(); + } + } + + + public boolean d() { + return this.j(); + } + + public boolean e() { + return !this.j() && this.ay; + } + + public boolean f() { + return this.humidity > 0.85F; + } + + public float g() { + return 0.1F; + } + + public final int h() { + return (int) (this.humidity * 65536.0F); + } + + public final float a(BlockPosition blockposition) { + return aV(blockposition.getX(), blockposition.getY(), blockposition.getZ()); + } + + public final float aV(final int x, final int y, final int z) { + if (y > 64) { + float f = (float) (BiomeBase.ae.a(x * 1.0D / 8.0D, z * 1.0D / 8.0D) * 4.0D); + + return this.temperature - (f + (float) y - 64.0F) * 0.05F / 30.0F; + } else { + return this.temperature; + } + } + + public void a(World world, Random random, BlockPosition blockposition) { + this.as.a(world, random, this, blockposition); + } + + public boolean j() { + return this.ax; + } + + public void a(World world, Random random, ChunkSnapshot chunksnapshot, int i, int j, double d0) { + this.b(world, random, chunksnapshot, i, j, d0); + } + + public final void b(World world, Random random, ChunkSnapshot chunksnapshot, int i, int j, double d0) { + int k = world.F(); + IBlockData iblockdata = this.ak; + IBlockData iblockdata1 = this.al; + int l = -1; + int i1 = (int) (d0 / 3.0D + 3.0D + random.nextDouble() * 0.25D); + int j1 = i & 15; + int k1 = j & 15; + + for (int l1 = 255; l1 >= 0; --l1) { + if (l1 <= (world.generatorConfig.flatBedrock.getValue() || world.paperSpigotConfig.generateFlatBedrock ? 0 : random.nextInt(5))) { // PaperSpigot - Configurable flat bedrock + chunksnapshot.a(k1, l1, j1, Blocks.BEDROCK.getBlockData()); + } else { + IBlockData iblockdata2 = chunksnapshot.a(k1, l1, j1); + + if (iblockdata2.getBlock().getMaterial() == Material.AIR) { + l = -1; + } else if (iblockdata2.getBlock() == Blocks.STONE) { + if (l == -1) { + if (i1 <= 0) { + iblockdata = null; + iblockdata1 = Blocks.STONE.getBlockData(); + } else if (l1 >= k - 4 && l1 <= k + 1) { + iblockdata = this.ak; + iblockdata1 = this.al; + } + + if (l1 < k && (iblockdata == null || iblockdata.getBlock().getMaterial() == Material.AIR)) { + if (this.aV(i, l1, j) < 0.15F) { + iblockdata = Blocks.ICE.getBlockData(); + } else { + iblockdata = Blocks.WATER.getBlockData(); + } + } + + l = i1; + if (l1 >= k - 1) { + chunksnapshot.a(k1, l1, j1, iblockdata); + } else if (l1 < k - 7 - i1) { + iblockdata = null; + iblockdata1 = Blocks.STONE.getBlockData(); + chunksnapshot.a(k1, l1, j1, Blocks.GRAVEL.getBlockData()); + } else { + chunksnapshot.a(k1, l1, j1, iblockdata1); + } + } else if (l > 0) { + --l; + chunksnapshot.a(k1, l1, j1, iblockdata1); + if (l == 0 && iblockdata1.getBlock() == Blocks.SAND) { + l = random.nextInt(4) + Math.max(0, l1 - 63); + iblockdata1 = iblockdata1.get(BlockSand.VARIANT) == BlockSand.EnumSandVariant.RED_SAND ? Blocks.RED_SANDSTONE.getBlockData() : Blocks.SANDSTONE.getBlockData(); + } + } + } + } + } + + } + + protected BiomeBase k() { + return this.d(this.id + 128); + } + + protected BiomeBase d(int i) { + return new BiomeBaseSub(i, this); + } + + public Class l() { + return this.getClass(); + } + + public boolean a(BiomeBase biomebase) { + return biomebase == this || (biomebase != null && this.l() == biomebase.l()); + } + + public EnumTemperature m() { + return (double) this.temperature < 0.2D ? EnumTemperature.COLD : ((double) this.temperature < 1.0D ? EnumTemperature.MEDIUM : EnumTemperature.WARM); + } + + public static BiomeBase[] getBiomes() { + return BiomeBase.biomes; + } + + public static BiomeBase getBiome(int i) { + return getBiome(i, null); + } + + public static BiomeBase getBiome(int i, BiomeBase biomebase) { + if (i >= 0 && i <= BiomeBase.biomes.length) { + BiomeBase biomebase1 = BiomeBase.biomes[i]; + + return biomebase1 == null ? biomebase : biomebase1; + } else { + BiomeBase.aD.warn("Biome ID is out of bounds: " + i + ", defaulting to 0 (Ocean)"); + return BiomeBase.OCEAN; + } + } + + static { + BiomeBase.PLAINS.k(); + BiomeBase.DESERT.k(); + BiomeBase.FOREST.k(); + BiomeBase.TAIGA.k(); + BiomeBase.SWAMPLAND.k(); + BiomeBase.ICE_PLAINS.k(); + BiomeBase.JUNGLE.k(); + BiomeBase.JUNGLE_EDGE.k(); + BiomeBase.COLD_TAIGA.k(); + BiomeBase.SAVANNA.k(); + BiomeBase.SAVANNA_PLATEAU.k(); + BiomeBase.MESA.k(); + BiomeBase.MESA_PLATEAU_F.k(); + BiomeBase.MESA_PLATEAU.k(); + BiomeBase.BIRCH_FOREST.k(); + BiomeBase.BIRCH_FOREST_HILLS.k(); + BiomeBase.ROOFED_FOREST.k(); + BiomeBase.MEGA_TAIGA.k(); + BiomeBase.EXTREME_HILLS.k(); + BiomeBase.EXTREME_HILLS_PLUS.k(); + BiomeBase.MEGA_TAIGA.d(BiomeBase.MEGA_TAIGA_HILLS.id + 128).a("Redwood Taiga Hills M"); + + for (BiomeBase biomebase : BiomeBase.biomes) { + if (biomebase != null) { + if (BiomeBase.o.containsKey(biomebase.ah)) { + throw new Error("Biome \"" + biomebase.ah + "\" is defined as both ID " + BiomeBase.o.get(biomebase.ah).id + " and " + biomebase.id); + } + + BiomeBase.o.put(biomebase.ah, biomebase); + if (biomebase.id < 128) { + BiomeBase.n.add(biomebase); + } + } + } + + BiomeBase.n.remove(BiomeBase.HELL); + BiomeBase.n.remove(BiomeBase.SKY); + BiomeBase.n.remove(BiomeBase.FROZEN_OCEAN); + BiomeBase.n.remove(BiomeBase.SMALL_MOUNTAINS); + ae = new NoiseGenerator3(new Random(1234L), 1); + af = new NoiseGenerator3(new Random(2345L), 1); + ag = new WorldGenTallPlant(); + } + + static class SyntheticClass_1 { + + static final int[] switchMap = new int[EnumCreatureType.values().length]; + + static { + try { + SyntheticClass_1.switchMap[EnumCreatureType.MONSTER.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.switchMap[EnumCreatureType.CREATURE.ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.switchMap[EnumCreatureType.WATER_CREATURE.ordinal()] = 3; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.switchMap[EnumCreatureType.AMBIENT.ordinal()] = 4; + } catch (NoSuchFieldError ignored) { + } + + } + } + + public static class BiomeMeta extends WeightedRandom.WeightedRandomChoice { + + public Class b; + public Constructor constructor; // Azurite + public int c; + public int d; + + public BiomeMeta(Class oclass, int i, int j, int k) { + super(i); + this.b = oclass; + this.c = j; + this.d = k; + + // Azurite start + try { + this.constructor = oclass.getConstructor(World.class); + } catch (NoSuchMethodException ex) { + throw new RuntimeException(ex); + } + // Azurite end + } + + public String toString() { + return this.b.getSimpleName() + "*(" + this.c + "-" + this.d + "):" + this.a; + } + } + + public static class BiomeTemperature { + + public float a; + public float b; + + public BiomeTemperature(float f, float f1) { + this.a = f; + this.b = f1; + } + + public BiomeTemperature a() { + return new BiomeTemperature(this.a * 0.8F, this.b * 0.6F); + } + } + + public enum EnumTemperature { + + OCEAN, COLD, MEDIUM, WARM; + + EnumTemperature() { + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BiomeBaseSub.java b/azurite-server/src/main/java/net/minecraft/server/BiomeBaseSub.java new file mode 100644 index 0000000..e2280a4 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BiomeBaseSub.java @@ -0,0 +1,62 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; +import java.util.Random; + +public class BiomeBaseSub extends BiomeBase { + + protected BiomeBase aE; + + public BiomeBaseSub(int i, BiomeBase biomebase) { + super(i); + this.aE = biomebase; + this.a(biomebase.ai, true); + this.ah = biomebase.ah + " M"; + this.ak = biomebase.ak; + this.al = biomebase.al; + this.am = biomebase.am; + this.an = biomebase.an; + this.ao = biomebase.ao; + this.temperature = biomebase.temperature; + this.humidity = biomebase.humidity; + this.ar = biomebase.ar; + this.ax = biomebase.ax; + this.ay = biomebase.ay; + this.au = Lists.newArrayList(biomebase.au); + this.at = Lists.newArrayList(biomebase.at); + this.aw = Lists.newArrayList(biomebase.aw); + this.av = Lists.newArrayList(biomebase.av); + this.temperature = biomebase.temperature; + this.humidity = biomebase.humidity; + this.an = biomebase.an + 0.1F; + this.ao = biomebase.ao + 0.2F; + } + + public void a(World world, Random random, BlockPosition blockposition) { + this.aE.as.a(world, random, this, blockposition); + } + + public void a(World world, Random random, ChunkSnapshot chunksnapshot, int i, int j, double d0) { + this.aE.a(world, random, chunksnapshot, i, j, d0); + } + + public float g() { + return this.aE.g(); + } + + public WorldGenTreeAbstract a(Random random) { + return this.aE.a(random); + } + + public Class l() { + return this.aE.l(); + } + + public boolean a(BiomeBase biomebase) { + return this.aE.a(biomebase); + } + + public BiomeBase.EnumTemperature m() { + return this.aE.m(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BiomeBeach.java b/azurite-server/src/main/java/net/minecraft/server/BiomeBeach.java new file mode 100644 index 0000000..ba9285d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BiomeBeach.java @@ -0,0 +1,15 @@ +package net.minecraft.server; + +public class BiomeBeach extends BiomeBase { + + public BiomeBeach(int i) { + super(i); + this.au.clear(); + this.ak = Blocks.SAND.getBlockData(); + this.al = Blocks.SAND.getBlockData(); + this.as.A = -999; + this.as.D = 0; + this.as.F = 0; + this.as.G = 0; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BiomeBigHills.java b/azurite-server/src/main/java/net/minecraft/server/BiomeBigHills.java new file mode 100644 index 0000000..3c60bb7 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BiomeBigHills.java @@ -0,0 +1,84 @@ +package net.minecraft.server; + +import java.util.Random; + +public class BiomeBigHills extends BiomeBase { + + private final WorldGenerator aD; + private final WorldGenTaiga2 aE; + private final int aG; + private final int aH; + private int aI; + + protected BiomeBigHills(int i, boolean flag) { + super(i); + this.aD = new WorldGenMinable(Blocks.MONSTER_EGG.getBlockData().set(BlockMonsterEggs.VARIANT, BlockMonsterEggs.EnumMonsterEggVarient.STONE), 9); + this.aE = new WorldGenTaiga2(false); + this.aG = 1; + this.aH = 2; + this.aI = 0; + if (flag) { + this.as.A = 3; + this.aI = this.aG; + } + + } + + public WorldGenTreeAbstract a(Random random) { + return random.nextInt(3) > 0 ? this.aE : super.a(random); + } + + public void a(World world, Random random, BlockPosition blockposition) { + super.a(world, random, blockposition); + int i = (int) (3 * world.generatorConfig.emeraldMultiplier.getValue() + random.nextInt(6)); + + int j; + int k; + int l; + + for (j = 0; j < i; ++j) { + k = random.nextInt(16); + l = random.nextInt(28) + 4; + int i1 = random.nextInt(16); + BlockPosition blockposition1 = blockposition.a(k, l, i1); + + if (world.getType(blockposition1).getBlock() == Blocks.STONE) { + world.setTypeAndData(blockposition1, Blocks.EMERALD_ORE.getBlockData(), 2); + } + } + + for (i = 0; i < 7; ++i) { + j = random.nextInt(16); + k = random.nextInt(64); + l = random.nextInt(16); + this.aD.generate(world, random, blockposition.a(j, k, l)); + } + } + + public void a(World world, Random random, ChunkSnapshot chunksnapshot, int i, int j, double d0) { + this.ak = Blocks.GRASS.getBlockData(); + this.al = Blocks.DIRT.getBlockData(); + if ((d0 < -1.0D || d0 > 2.0D) && this.aI == this.aH) { + this.ak = Blocks.GRAVEL.getBlockData(); + this.al = Blocks.GRAVEL.getBlockData(); + } else if (d0 > 1.0D && this.aI != this.aG) { + this.ak = Blocks.STONE.getBlockData(); + this.al = Blocks.STONE.getBlockData(); + } + + this.b(world, random, chunksnapshot, i, j, d0); + } + + private BiomeBigHills b(BiomeBase biomebase) { + this.aI = this.aH; + this.a(biomebase.ai, true); + this.a(biomebase.ah + " M"); + this.a(new BiomeTemperature(biomebase.an, biomebase.ao)); + this.a(biomebase.temperature, biomebase.humidity); + return this; + } + + protected BiomeBase d(int i) { + return (new BiomeBigHills(i, false)).b(this); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BiomeCache.java b/azurite-server/src/main/java/net/minecraft/server/BiomeCache.java new file mode 100644 index 0000000..a55f931 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BiomeCache.java @@ -0,0 +1,83 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; +import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; +import org.bukkit.craftbukkit.util.LongHash; + +import java.util.List; + +public class BiomeCache { + + private final WorldChunkManager a; + private long b; + private final Long2ObjectOpenHashMap c = new Long2ObjectOpenHashMap<>(); // Azurite - Optimize cache + private final List d = Lists.newArrayList(); + + public BiomeCache(WorldChunkManager worldchunkmanager) { + this.a = worldchunkmanager; + } + + public BiomeCacheBlock a(int i, int j) { + i >>= 4; + j >>= 4; + long k = LongHash.toLong(i, j); + BiomeCacheBlock cacheBlock = this.c.get(k); + + if (cacheBlock == null) { + cacheBlock = new BiomeCacheBlock(i, j); + this.c.put(k, cacheBlock); + this.d.add(cacheBlock); + } + + cacheBlock.e = MinecraftServer.az(); + return cacheBlock; + } + + public BiomeBase a(int i, int j, BiomeBase biomebase) { + BiomeBase biomebase1 = this.a(i, j).a(i, j); + return biomebase1 == null ? biomebase : biomebase1; + } + + public void a() { + long i = MinecraftServer.az(); + long j = i - this.b; + + if (j > 7500L || j < 0L) { + this.b = i; + + for (int k = 0; k < this.d.size(); ++k) { + BiomeCacheBlock biomecache_biomecacheblock = this.d.get(k); + long l = i - biomecache_biomecacheblock.e; + + if (l > 30000L || l < 0L) { + this.d.remove(k--); + this.c.remove(LongHash.toLong(biomecache_biomecacheblock.c, biomecache_biomecacheblock.d)); + } + } + } + } + + public BiomeBase[] c(int i, int j) { + return this.a(i, j).b; + } + + public class BiomeCacheBlock { + + //public float[] a = new float[256]; + public BiomeBase[] b = new BiomeBase[256]; + public int c; + public int d; + public long e; + + public BiomeCacheBlock(int i, int j) { + this.c = i; + this.d = j; + //BiomeCache.this.a.getWetness(this.a, i << 4, j << 4, 16, 16); Azurite - Remove its pointless but heavy + BiomeCache.this.a.a(this.b, i << 4, j << 4, 16, 16, false); + } + + public BiomeBase a(int i, int j) { + return this.b[i & 15 | (j & 15) << 4]; + } + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/net/minecraft/server/BiomeDecorator.java b/azurite-server/src/main/java/net/minecraft/server/BiomeDecorator.java new file mode 100644 index 0000000..20711c8 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BiomeDecorator.java @@ -0,0 +1,353 @@ +package net.minecraft.server; + +import dev.azurite.spigot.generator.Generator; + +import java.util.Random; + +public class BiomeDecorator { + protected World a; + protected Random b; + protected BlockPosition c; + protected CustomWorldSettingsFinal d; + protected WorldGenerator e = new WorldGenClay(4); + protected WorldGenerator f; + protected WorldGenerator g; + protected WorldGenerator h; + protected WorldGenerator i; + protected WorldGenerator j; + protected WorldGenerator k; + protected WorldGenerator l; + protected WorldGenerator m; + protected WorldGenerator n; + protected WorldGenerator o; + protected WorldGenerator p; + protected WorldGenerator q; + protected WorldGenerator r; + protected WorldGenFlowers s; + protected WorldGenerator t; + protected WorldGenerator u; + protected WorldGenerator v; + protected WorldGenerator w; + protected WorldGenerator x; + protected WorldGenerator y; + protected int z; + protected int A; + protected int B; + protected int C; + protected int D; + protected int E; + protected int F; + protected int G; + protected int H; + protected int I; + protected int J; + protected int K; + public boolean L; + + public BiomeDecorator() { + this.f = new WorldGenSand(Blocks.SAND, 7); + this.g = new WorldGenSand(Blocks.GRAVEL, 6); + this.s = new WorldGenFlowers(Blocks.YELLOW_FLOWER, BlockFlowers.EnumFlowerVarient.DANDELION); + this.t = new WorldGenMushrooms(Blocks.BROWN_MUSHROOM); + this.u = new WorldGenMushrooms(Blocks.RED_MUSHROOM); + this.v = new WorldGenHugeMushroom(); + this.w = new WorldGenReed(); + this.x = new WorldGenCactus(); + this.y = new WorldGenWaterLily(); + this.B = 2; + this.C = 1; + this.H = 1; + this.I = 3; + this.J = 1; + this.L = true; + } + + public void a(World world, Random random, BiomeBase biomebase, BlockPosition blockposition) { + this.a = world; + String s = world.getWorldData().getGeneratorOptions(); + Generator generator = world.generatorConfig; + + if (s != null) { + this.d = CustomWorldSettingsFinal.CustomWorldSettings.a(s).b(); + } else { + this.d = CustomWorldSettingsFinal.CustomWorldSettings.a("").b(); + } + + this.b = random; + this.c = blockposition; + this.h = new WorldGenMinable(Blocks.DIRT.getBlockData(), this.d.I); + this.i = new WorldGenMinable(Blocks.GRAVEL.getBlockData(), this.d.M); + this.j = new WorldGenMinable(Blocks.STONE.getBlockData().set(BlockStone.VARIANT, BlockStone.EnumStoneVariant.GRANITE), this.d.Q); + this.k = new WorldGenMinable(Blocks.STONE.getBlockData().set(BlockStone.VARIANT, BlockStone.EnumStoneVariant.DIORITE), this.d.U); + this.l = new WorldGenMinable(Blocks.STONE.getBlockData().set(BlockStone.VARIANT, BlockStone.EnumStoneVariant.ANDESITE), this.d.Y); + this.m = new WorldGenMinable(Blocks.COAL_ORE.getBlockData(), generator.coalSize.getValue(), generator.coalMustTouchAir.getValue()); + this.n = new WorldGenMinable(Blocks.IRON_ORE.getBlockData(), generator.ironSize.getValue(), generator.ironMustTouchAir.getValue()); + this.o = new WorldGenMinable(Blocks.GOLD_ORE.getBlockData(), generator.goldSize.getValue(), generator.goldMustTouchAir.getValue()); + this.p = new WorldGenMinable(Blocks.REDSTONE_ORE.getBlockData(), generator.redstoneSize.getValue(), generator.redstoneMustTouchAir.getValue()); + this.q = new WorldGenMinable(Blocks.DIAMOND_ORE.getBlockData(), generator.diamondSize.getValue(), generator.diamondMustTouchAir.getValue()); + this.r = new WorldGenMinable(Blocks.LAPIS_ORE.getBlockData(), generator.lapisSize.getValue(), generator.lapisMustTouchAir.getValue()); + this.a(biomebase); + this.a = null; + this.b = null; + } + + protected void a(BiomeBase var1) { + this.a(); + + int var2; + int var3; + int var4; + for (var2 = 0; var2 < this.I; ++var2) { + var3 = this.b.nextInt(16) + 8; + var4 = this.b.nextInt(16) + 8; + this.f.generate(this.a, this.b, this.a.r(this.c.a(var3, 0, var4))); + } + + for (var2 = 0; var2 < this.J; ++var2) { + var3 = this.b.nextInt(16) + 8; + var4 = this.b.nextInt(16) + 8; + this.e.generate(this.a, this.b, this.a.r(this.c.a(var3, 0, var4))); + } + + for (var2 = 0; var2 < this.H; ++var2) { + var3 = this.b.nextInt(16) + 8; + var4 = this.b.nextInt(16) + 8; + this.g.generate(this.a, this.b, this.a.r(this.c.a(var3, 0, var4))); + } + + var2 = this.A; + if (this.b.nextInt(10) == 0) { + ++var2; + } + + int var5; + BlockPosition var7; + for (var3 = 0; var3 < var2; ++var3) { + var4 = this.b.nextInt(16) + 8; + var5 = this.b.nextInt(16) + 8; + WorldGenTreeAbstract var6 = var1.a(this.b); + var6.e(); + var7 = this.a.getHighestBlockYAt(this.c.a(var4, 0, var5)); + if (var6.generate(this.a, this.b, var7)) { + var6.a(this.a, this.b, var7); + } + } + + for (var3 = 0; var3 < this.K; ++var3) { + var4 = this.b.nextInt(16) + 8; + var5 = this.b.nextInt(16) + 8; + this.v.generate(this.a, this.b, this.a.getHighestBlockYAt(this.c.a(var4, 0, var5))); + } + + BlockPosition var8; + int var11; + int var12; + for (var3 = 0; var3 < this.B; ++var3) { + var4 = this.b.nextInt(16) + 8; + var5 = this.b.nextInt(16) + 8; + var11 = this.a.getHighestBlockYAt(this.c.a(var4, 0, var5)).getY() + 32; + if (var11 > 0) { + var12 = this.b.nextInt(var11); + var8 = this.c.a(var4, var12, var5); + BlockFlowers.EnumFlowerVarient var9 = var1.a(this.b, var8); + BlockFlowers var10 = var9.a().a(); + if (var10.getMaterial() != Material.AIR) { + this.s.a(var10, var9); + this.s.generate(this.a, this.b, var8); + } + } + } + + for (var3 = 0; var3 < this.C; ++var3) { + var4 = this.b.nextInt(16) + 8; + var5 = this.b.nextInt(16) + 8; + var11 = this.a.getHighestBlockYAt(this.c.a(var4, 0, var5)).getY() * 2; + if (var11 > 0) { + var12 = this.b.nextInt(var11); + var1.b(this.b).generate(this.a, this.b, this.c.a(var4, var12, var5)); + } + } + + for (var3 = 0; var3 < this.D; ++var3) { + var4 = this.b.nextInt(16) + 8; + var5 = this.b.nextInt(16) + 8; + var11 = this.a.getHighestBlockYAt(this.c.a(var4, 0, var5)).getY() * 2; + if (var11 > 0) { + var12 = this.b.nextInt(var11); + (new WorldGenDeadBush()).generate(this.a, this.b, this.c.a(var4, var12, var5)); + } + } + + for (var3 = 0; var3 < this.z; ++var3) { + var4 = this.b.nextInt(16) + 8; + var5 = this.b.nextInt(16) + 8; + var11 = this.a.getHighestBlockYAt(this.c.a(var4, 0, var5)).getY() * 2; + if (var11 > 0) { + var12 = this.b.nextInt(var11); + + BlockPosition var14; + for (var8 = this.c.a(var4, var12, var5); var8.getY() > 0; var8 = var14) { + var14 = var8.down(); + if (!this.a.isEmpty(var14)) { + break; + } + } + + this.y.generate(this.a, this.b, var8); + } + } + + for (var3 = 0; var3 < this.E; ++var3) { + if (this.b.nextInt(4) == 0) { + var4 = this.b.nextInt(16) + 8; + var5 = this.b.nextInt(16) + 8; + BlockPosition var13 = this.a.getHighestBlockYAt(this.c.a(var4, 0, var5)); + this.t.generate(this.a, this.b, var13); + } + + if (this.b.nextInt(8) == 0) { + var4 = this.b.nextInt(16) + 8; + var5 = this.b.nextInt(16) + 8; + var11 = this.a.getHighestBlockYAt(this.c.a(var4, 0, var5)).getY() * 2; + if (var11 > 0) { + var12 = this.b.nextInt(var11); + var8 = this.c.a(var4, var12, var5); + this.u.generate(this.a, this.b, var8); + } + } + } + + if (this.b.nextInt(4) == 0) { + var3 = this.b.nextInt(16) + 8; + var4 = this.b.nextInt(16) + 8; + var5 = this.a.getHighestBlockYAt(this.c.a(var3, 0, var4)).getY() * 2; + if (var5 > 0) { + var11 = this.b.nextInt(var5); + this.t.generate(this.a, this.b, this.c.a(var3, var11, var4)); + } + } + + if (this.b.nextInt(8) == 0) { + var3 = this.b.nextInt(16) + 8; + var4 = this.b.nextInt(16) + 8; + var5 = this.a.getHighestBlockYAt(this.c.a(var3, 0, var4)).getY() * 2; + if (var5 > 0) { + var11 = this.b.nextInt(var5); + this.u.generate(this.a, this.b, this.c.a(var3, var11, var4)); + } + } + + for (var3 = 0; var3 < this.F * this.a.generatorConfig.sugarCaneMultiplier.getValue(); ++var3) { + var4 = this.b.nextInt(16) + 8; + var5 = this.b.nextInt(16) + 8; + var11 = this.a.getHighestBlockYAt(this.c.a(var4, 0, var5)).getY() * 2; + if (var11 > 0) { + var12 = this.b.nextInt(var11); + this.w.generate(this.a, this.b, this.c.a(var4, var12, var5)); + } + } + + for (var3 = 0; var3 < 10 * this.a.generatorConfig.sugarCaneMultiplier.getValue(); ++var3) { + var4 = this.b.nextInt(16) + 8; + var5 = this.b.nextInt(16) + 8; + var11 = this.a.getHighestBlockYAt(this.c.a(var4, 0, var5)).getY() * 2; + if (var11 > 0) { + var12 = this.b.nextInt(var11); + this.w.generate(this.a, this.b, this.c.a(var4, var12, var5)); + } + } + + if (this.b.nextInt(32) == 0) { + var3 = this.b.nextInt(16) + 8; + var4 = this.b.nextInt(16) + 8; + var5 = this.a.getHighestBlockYAt(this.c.a(var3, 0, var4)).getY() * 2; + if (var5 > 0) { + var11 = this.b.nextInt(var5); + (new WorldGenPumpkin()).generate(this.a, this.b, this.c.a(var3, var11, var4)); + } + } + + for (var3 = 0; var3 < this.G; ++var3) { + var4 = this.b.nextInt(16) + 8; + var5 = this.b.nextInt(16) + 8; + var11 = this.a.getHighestBlockYAt(this.c.a(var4, 0, var5)).getY() * 2; + if (var11 > 0) { + var12 = this.b.nextInt(var11); + this.x.generate(this.a, this.b, this.c.a(var4, var12, var5)); + } + } + + if (this.L) { + for (var3 = 0; var3 < 50; ++var3) { + var4 = this.b.nextInt(16) + 8; + var5 = this.b.nextInt(16) + 8; + var11 = this.b.nextInt(248) + 8; + var12 = this.b.nextInt(var11); + var8 = this.c.a(var4, var12, var5); + (new WorldGenLiquids(Blocks.FLOWING_WATER)).generate(this.a, this.b, var8); + } + + for (var3 = 0; var3 < 20; ++var3) { + var4 = this.b.nextInt(16) + 8; + var5 = this.b.nextInt(16) + 8; + var11 = this.b.nextInt(this.b.nextInt(this.b.nextInt(240) + 8) + 8); + var7 = this.c.a(var4, var11, var5); + (new WorldGenLiquids(Blocks.FLOWING_LAVA)).generate(this.a, this.b, var7); + } + } + + } + + protected void a(int var1, WorldGenerator var2, int var3, int var4) { + int var5; + if (var4 < var3) { + var5 = var3; + var3 = var4; + var4 = var5; + } else if (var4 == var3) { + if (var3 < 255) { + ++var4; + } else { + --var3; + } + } + + for (var5 = 0; var5 < var1; ++var5) { + BlockPosition var6 = this.c.a(this.b.nextInt(16), this.b.nextInt(var4 - var3) + var3, this.b.nextInt(16)); + var2.generate(this.a, this.b, var6); + } + } + + protected void b(int var1, WorldGenerator var2, int var3, int var4) { + for (int var5 = 0; var5 < var1; ++var5) { + BlockPosition var6 = this.c.a(this.b.nextInt(16), this.b.nextInt(var4) + this.b.nextInt(var4) + var3 - var4, this.b.nextInt(16)); + var2.generate(this.a, this.b, var6); + } + } + + protected void a() { + this.a(this.d.J, this.h, this.d.K, this.d.L); + this.a(this.d.N, this.i, this.d.O, this.d.P); + + Generator generator = this.a.generatorConfig; + double coal = generator.coalMultiplier.getValue(), + iron = generator.ironMultiplier.getValue(), + gold = generator.goldMultiplier.getValue(), + redstone = generator.redstoneMultiplier.getValue(), + diamond = generator.diamondMultiplier.getValue(), + lapis = generator.lapisMultiplier.getValue(); + + if (coal > 0) + this.a((int) (d.ad * coal + this.b.nextFloat()), this.m, this.d.ae, this.d.af); + if (iron > 0) + this.a((int) (d.ah * iron + this.b.nextFloat()), this.n, this.d.ai, this.d.aj); + if (gold > 0) + this.a((int) (d.al * gold + this.b.nextFloat()), this.o, this.d.am, this.d.an); + if (redstone > 0) + this.a((int) (d.ap * redstone + this.b.nextFloat()), this.p, this.d.aq, this.d.ar); + if (diamond > 0) + this.a((int) (d.at * diamond + this.b.nextFloat()), this.q, this.d.au, this.d.av); + if (lapis > 0) + this.b((int) (d.ax * lapis + this.b.nextFloat()), this.r, this.d.ay, this.d.az); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BiomeDesert.java b/azurite-server/src/main/java/net/minecraft/server/BiomeDesert.java new file mode 100644 index 0000000..59bea06 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BiomeDesert.java @@ -0,0 +1,30 @@ +package net.minecraft.server; + +import java.util.Random; + +public class BiomeDesert extends BiomeBase { + + public BiomeDesert(int i) { + super(i); + this.au.clear(); + this.ak = Blocks.SAND.getBlockData(); + this.al = Blocks.SAND.getBlockData(); + this.as.A = -999; + this.as.D = 2; + this.as.F = 50; + this.as.G = 10; + this.au.clear(); + } + + public void a(World world, Random random, BlockPosition blockposition) { + super.a(world, random, blockposition); + if (random.nextInt(1000) == 0) { + int i = random.nextInt(16) + 8; + int j = random.nextInt(16) + 8; + BlockPosition blockposition1 = world.getHighestBlockYAt(blockposition.a(i, 0, j)).up(); + + (new WorldGenDesertWell()).generate(world, random, blockposition1); + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BiomeForest.java b/azurite-server/src/main/java/net/minecraft/server/BiomeForest.java new file mode 100644 index 0000000..022c626 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BiomeForest.java @@ -0,0 +1,159 @@ +package net.minecraft.server; + +import java.util.Random; + +public class BiomeForest extends BiomeBase { + + private int aG; + protected static final WorldGenForest aD = new WorldGenForest(false, true); + protected static final WorldGenForest aE = new WorldGenForest(false, false); + protected static final WorldGenForestTree aF = new WorldGenForestTree(false); + + public BiomeForest(int i, int j) { + super(i); + this.aG = j; + this.as.A = 10; + this.as.C = 2; + if (this.aG == 1) { + this.as.A = 6; + this.as.B = 100; + this.as.C = 1; + } + + this.a(5159473); + this.a(0.7F, 0.8F); + if (this.aG == 2) { + this.aj = 353825; + this.ai = 3175492; + this.a(0.6F, 0.6F); + } + + if (this.aG == 0) { + this.au.add(new BiomeBase.BiomeMeta(EntityWolf.class, 5, 4, 4)); + } + + if (this.aG == 3) { + this.as.A = -999; + } + + } + + protected BiomeBase a(int i, boolean flag) { + if (this.aG == 2) { + this.aj = 353825; + this.ai = i; + if (flag) { + this.aj = (this.aj & 16711422) >> 1; + } + + return this; + } else { + return super.a(i, flag); + } + } + + public WorldGenTreeAbstract a(Random random) { + return (WorldGenTreeAbstract) (this.aG == 3 && random.nextInt(3) > 0 ? BiomeForest.aF : (this.aG != 2 && random.nextInt(5) != 0 ? this.aA : BiomeForest.aE)); + } + + public BlockFlowers.EnumFlowerVarient a(Random random, BlockPosition blockposition) { + if (this.aG == 1) { + double d0 = MathHelper.a((1.0D + BiomeForest.af.a((double) blockposition.getX() / 48.0D, (double) blockposition.getZ() / 48.0D)) / 2.0D, 0.0D, 0.9999D); + BlockFlowers.EnumFlowerVarient blockflowers_enumflowervarient = BlockFlowers.EnumFlowerVarient.values()[(int) (d0 * (double) BlockFlowers.EnumFlowerVarient.values().length)]; + + return blockflowers_enumflowervarient == BlockFlowers.EnumFlowerVarient.BLUE_ORCHID ? BlockFlowers.EnumFlowerVarient.POPPY : blockflowers_enumflowervarient; + } else { + return super.a(random, blockposition); + } + } + + public void a(World world, Random random, BlockPosition blockposition) { + int i; + int j; + int k; + int l; + + if (this.aG == 3) { + for (i = 0; i < 4; ++i) { + for (j = 0; j < 4; ++j) { + k = i * 4 + 1 + 8 + random.nextInt(3); + l = j * 4 + 1 + 8 + random.nextInt(3); + BlockPosition blockposition1 = world.getHighestBlockYAt(blockposition.a(k, 0, l)); + + if (random.nextInt(20) == 0) { + WorldGenHugeMushroom worldgenhugemushroom = new WorldGenHugeMushroom(); + + worldgenhugemushroom.generate(world, random, blockposition1); + } else { + WorldGenTreeAbstract worldgentreeabstract = this.a(random); + + worldgentreeabstract.e(); + if (worldgentreeabstract.generate(world, random, blockposition1)) { + worldgentreeabstract.a(world, random, blockposition1); + } + } + } + } + } + + i = random.nextInt(5) - 3; + if (this.aG == 1) { + i += 2; + } + + j = 0; + + while (j < i) { + k = random.nextInt(3); + if (k == 0) { + BiomeForest.ag.a(BlockTallPlant.EnumTallFlowerVariants.SYRINGA); + } else if (k == 1) { + BiomeForest.ag.a(BlockTallPlant.EnumTallFlowerVariants.ROSE); + } else if (k == 2) { + BiomeForest.ag.a(BlockTallPlant.EnumTallFlowerVariants.PAEONIA); + } + + l = 0; + + while (true) { + if (l < 5) { + int i1 = random.nextInt(16) + 8; + int j1 = random.nextInt(16) + 8; + int k1 = random.nextInt(world.getHighestBlockYAt(blockposition.a(i1, 0, j1)).getY() + 32); + + if (!BiomeForest.ag.generate(world, random, new BlockPosition(blockposition.getX() + i1, k1, blockposition.getZ() + j1))) { + ++l; + continue; + } + } + + ++j; + break; + } + } + + super.a(world, random, blockposition); + } + + protected BiomeBase d(final int i) { + if (this.id == BiomeBase.FOREST.id) { + BiomeForest biomeforest = new BiomeForest(i, 1); + + biomeforest.a(new BiomeBase.BiomeTemperature(this.an, this.ao + 0.2F)); + biomeforest.a("Flower Forest"); + biomeforest.a(6976549, true); + biomeforest.a(8233509); + return biomeforest; + } else { + return this.id != BiomeBase.BIRCH_FOREST.id && this.id != BiomeBase.BIRCH_FOREST_HILLS.id ? new BiomeBaseSub(i, this) { + public void a(World world, Random random, BlockPosition blockposition) { + this.aE.a(world, random, blockposition); + } + } : new BiomeBaseSub(i, this) { + public WorldGenTreeAbstract a(Random random) { + return random.nextBoolean() ? BiomeForest.aD : BiomeForest.aE; + } + }; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BiomeHell.java b/azurite-server/src/main/java/net/minecraft/server/BiomeHell.java new file mode 100644 index 0000000..d2845b5 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BiomeHell.java @@ -0,0 +1,15 @@ +package net.minecraft.server; + +public class BiomeHell extends BiomeBase { + + public BiomeHell(int i) { + super(i); + this.at.clear(); + this.au.clear(); + this.av.clear(); + this.aw.clear(); + this.at.add(new BiomeBase.BiomeMeta(EntityGhast.class, 50, 4, 4)); + this.at.add(new BiomeBase.BiomeMeta(EntityPigZombie.class, 100, 4, 4)); + this.at.add(new BiomeBase.BiomeMeta(EntityMagmaCube.class, 1, 4, 4)); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BiomeIcePlains.java b/azurite-server/src/main/java/net/minecraft/server/BiomeIcePlains.java new file mode 100644 index 0000000..b5a5850 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BiomeIcePlains.java @@ -0,0 +1,54 @@ +package net.minecraft.server; + +import java.util.Random; + +public class BiomeIcePlains extends BiomeBase { + + private boolean aD; + private WorldGenPackedIce2 aE = new WorldGenPackedIce2(); + private WorldGenPackedIce1 aF = new WorldGenPackedIce1(4); + + public BiomeIcePlains(int i, boolean flag) { + super(i); + this.aD = flag; + if (flag) { + this.ak = Blocks.SNOW.getBlockData(); + } + + this.au.clear(); + } + + public void a(World world, Random random, BlockPosition blockposition) { + if (this.aD) { + int i; + int j; + int k; + + for (i = 0; i < 3; ++i) { + j = random.nextInt(16) + 8; + k = random.nextInt(16) + 8; + this.aE.generate(world, random, world.getHighestBlockYAt(blockposition.a(j, 0, k))); + } + + for (i = 0; i < 2; ++i) { + j = random.nextInt(16) + 8; + k = random.nextInt(16) + 8; + this.aF.generate(world, random, world.getHighestBlockYAt(blockposition.a(j, 0, k))); + } + } + + super.a(world, random, blockposition); + } + + public WorldGenTreeAbstract a(Random random) { + return new WorldGenTaiga2(false); + } + + protected BiomeBase d(int i) { + BiomeBase biomebase = (new BiomeIcePlains(i, true)).a(13828095, true).a(this.ah + " Spikes").c().a(0.0F, 0.5F).a(new BiomeBase.BiomeTemperature(this.an + 0.1F, this.ao + 0.1F)); + + biomebase.an = this.an + 0.3F; + biomebase.ao = this.ao + 0.4F; + return biomebase; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BiomeJungle.java b/azurite-server/src/main/java/net/minecraft/server/BiomeJungle.java new file mode 100644 index 0000000..1d069d9 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BiomeJungle.java @@ -0,0 +1,56 @@ +package net.minecraft.server; + +import java.util.Random; + +public class BiomeJungle extends BiomeBase { + + private boolean aD; + private static final IBlockData aE = Blocks.LOG.getBlockData().set(BlockLog1.VARIANT, BlockWood.EnumLogVariant.JUNGLE); + private static final IBlockData aF = Blocks.LEAVES.getBlockData().set(BlockLeaves1.VARIANT, BlockWood.EnumLogVariant.JUNGLE).set(BlockLeaves.CHECK_DECAY, Boolean.valueOf(false)); + private static final IBlockData aG = Blocks.LEAVES.getBlockData().set(BlockLeaves1.VARIANT, BlockWood.EnumLogVariant.OAK).set(BlockLeaves.CHECK_DECAY, Boolean.valueOf(false)); + + public BiomeJungle(int i, boolean flag) { + super(i); + this.aD = flag; + if (flag) { + this.as.A = 2; + } else { + this.as.A = 50; + } + + this.as.C = 25; + this.as.B = 4; + if (!flag) { + this.at.add(new BiomeBase.BiomeMeta(EntityOcelot.class, 2, 1, 1)); + } + + this.au.add(new BiomeBase.BiomeMeta(EntityChicken.class, 10, 4, 4)); + } + + public WorldGenTreeAbstract a(Random random) { + return (WorldGenTreeAbstract) (random.nextInt(10) == 0 ? this.aB : (random.nextInt(2) == 0 ? new WorldGenGroundBush(BiomeJungle.aE, BiomeJungle.aG) : (!this.aD && random.nextInt(3) == 0 ? new WorldGenJungleTree(false, 10, 20, BiomeJungle.aE, BiomeJungle.aF) : new WorldGenTrees(false, 4 + random.nextInt(7), BiomeJungle.aE, BiomeJungle.aF, true)))); + } + + public WorldGenerator b(Random random) { + return random.nextInt(4) == 0 ? new WorldGenGrass(BlockLongGrass.EnumTallGrassType.FERN) : new WorldGenGrass(BlockLongGrass.EnumTallGrassType.GRASS); + } + + public void a(World world, Random random, BlockPosition blockposition) { + super.a(world, random, blockposition); + int i = random.nextInt(16) + 8; + int j = random.nextInt(16) + 8; + int k = random.nextInt(world.getHighestBlockYAt(blockposition.a(i, 0, j)).getY() * 2); + + (new WorldGenMelon()).generate(world, random, blockposition.a(i, k, j)); + WorldGenVines worldgenvines = new WorldGenVines(); + + for (j = 0; j < 50; ++j) { + k = random.nextInt(16) + 8; + boolean flag = true; + int l = random.nextInt(16) + 8; + + worldgenvines.generate(world, random, blockposition.a(k, 128, l)); + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BiomeMesa.java b/azurite-server/src/main/java/net/minecraft/server/BiomeMesa.java new file mode 100644 index 0000000..d99d18f --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BiomeMesa.java @@ -0,0 +1,264 @@ +package net.minecraft.server; + +import java.util.Arrays; +import java.util.Random; + +public class BiomeMesa extends BiomeBase { + + private IBlockData[] aD; + private long aE; + private NoiseGenerator3 aF; + private NoiseGenerator3 aG; + private NoiseGenerator3 aH; + private final boolean aI; + private final boolean aJ; + + public BiomeMesa(int i, boolean flag, boolean flag1) { + super(i); + this.aI = flag; + this.aJ = flag1; + this.b(); + this.a(2.0F, 0.0F); + this.au.clear(); + this.ak = Blocks.SAND.getBlockData().set(BlockSand.VARIANT, BlockSand.EnumSandVariant.RED_SAND); + this.al = Blocks.STAINED_HARDENED_CLAY.getBlockData(); + this.as.A = -999; + this.as.D = 20; + this.as.F = 3; + this.as.G = 5; + this.as.B = 0; + this.au.clear(); + if (flag1) { + this.as.A = 5; + } + + } + + public WorldGenTreeAbstract a(Random random) { + return this.aA; + } + + public void a(World world, Random random, BlockPosition blockposition) { + super.a(world, random, blockposition); + } + + public void a(World world, Random random, ChunkSnapshot chunksnapshot, int i, int j, double d0) { + if (this.aD == null || this.aE != world.getSeed()) { + this.a(world.getSeed()); + } + + if (this.aF == null || this.aG == null || this.aE != world.getSeed()) { + Random random1 = new Random(this.aE); + + this.aF = new NoiseGenerator3(random1, 4); + this.aG = new NoiseGenerator3(random1, 1); + } + + this.aE = world.getSeed(); + double d1 = 0.0D; + int k; + int l; + + if (this.aI) { + k = (i & -16) + (j & 15); + l = (j & -16) + (i & 15); + double d2 = Math.min(Math.abs(d0), this.aF.a((double) k * 0.25D, (double) l * 0.25D)); + + if (d2 > 0.0D) { + double d3 = 0.001953125D; + double d4 = Math.abs(this.aG.a((double) k * d3, (double) l * d3)); + + d1 = d2 * d2 * 2.5D; + double d5 = Math.ceil(d4 * 50.0D) + 14.0D; + + if (d1 > d5) { + d1 = d5; + } + + d1 += 64.0D; + } + } + + k = i & 15; + l = j & 15; + int i1 = world.F(); + IBlockData iblockdata = Blocks.STAINED_HARDENED_CLAY.getBlockData(); + IBlockData iblockdata1 = this.al; + int j1 = (int) (d0 / 3.0D + 3.0D + random.nextDouble() * 0.25D); + boolean flag = Math.cos(d0 / 3.0D * 3.141592653589793D) > 0.0D; + int k1 = -1; + boolean flag1 = false; + + for (int l1 = 255; l1 >= 0; --l1) { + if (chunksnapshot.a(l, l1, k).getBlock().getMaterial() == Material.AIR && l1 < (int) d1) { + chunksnapshot.a(l, l1, k, Blocks.STONE.getBlockData()); + } + + if (l1 <= (world.generatorConfig.flatBedrock.getValue() || world.paperSpigotConfig.generateFlatBedrock ? 0 : random.nextInt(5))) { // PaperSpigot - Configurable flat bedrock + chunksnapshot.a(l, l1, k, Blocks.BEDROCK.getBlockData()); + } else { + IBlockData iblockdata2 = chunksnapshot.a(l, l1, k); + + if (iblockdata2.getBlock().getMaterial() == Material.AIR) { + k1 = -1; + } else if (iblockdata2.getBlock() == Blocks.STONE) { + IBlockData iblockdata3; + + if (k1 == -1) { + flag1 = false; + if (j1 <= 0) { + iblockdata = null; + iblockdata1 = Blocks.STONE.getBlockData(); + } else if (l1 >= i1 - 4 && l1 <= i1 + 1) { + iblockdata = Blocks.STAINED_HARDENED_CLAY.getBlockData(); + iblockdata1 = this.al; + } + + if (l1 < i1 && (iblockdata == null || iblockdata.getBlock().getMaterial() == Material.AIR)) { + iblockdata = Blocks.WATER.getBlockData(); + } + + k1 = j1 + Math.max(0, l1 - i1); + if (l1 >= i1 - 1) { + if (this.aJ && l1 > 86 + j1 * 2) { + if (flag) { + chunksnapshot.a(l, l1, k, Blocks.DIRT.getBlockData().set(BlockDirt.VARIANT, BlockDirt.EnumDirtVariant.COARSE_DIRT)); + } else { + chunksnapshot.a(l, l1, k, Blocks.GRASS.getBlockData()); + } + } else if (l1 > i1 + 3 + j1) { + if (l1 >= 64 && l1 <= 127) { + if (flag) { + iblockdata3 = Blocks.HARDENED_CLAY.getBlockData(); + } else { + iblockdata3 = this.a(i, l1, j); + } + } else { + iblockdata3 = Blocks.STAINED_HARDENED_CLAY.getBlockData().set(BlockCloth.COLOR, EnumColor.ORANGE); + } + + chunksnapshot.a(l, l1, k, iblockdata3); + } else { + chunksnapshot.a(l, l1, k, this.ak); + flag1 = true; + } + } else { + chunksnapshot.a(l, l1, k, iblockdata1); + if (iblockdata1.getBlock() == Blocks.STAINED_HARDENED_CLAY) { + chunksnapshot.a(l, l1, k, iblockdata1.getBlock().getBlockData().set(BlockCloth.COLOR, EnumColor.ORANGE)); + } + } + } else if (k1 > 0) { + --k1; + if (flag1) { + chunksnapshot.a(l, l1, k, Blocks.STAINED_HARDENED_CLAY.getBlockData().set(BlockCloth.COLOR, EnumColor.ORANGE)); + } else { + iblockdata3 = this.a(i, l1, j); + chunksnapshot.a(l, l1, k, iblockdata3); + } + } + } + } + } + + } + + private void a(long i) { + this.aD = new IBlockData[64]; + Arrays.fill(this.aD, Blocks.HARDENED_CLAY.getBlockData()); + Random random = new Random(i); + + this.aH = new NoiseGenerator3(random, 1); + + int j; + + for (j = 0; j < 64; ++j) { + j += random.nextInt(5) + 1; + if (j < 64) { + this.aD[j] = Blocks.STAINED_HARDENED_CLAY.getBlockData().set(BlockCloth.COLOR, EnumColor.ORANGE); + } + } + + j = random.nextInt(4) + 2; + + int k; + int l; + int i1; + int j1; + + for (k = 0; k < j; ++k) { + l = random.nextInt(3) + 1; + i1 = random.nextInt(64); + + for (j1 = 0; i1 + j1 < 64 && j1 < l; ++j1) { + this.aD[i1 + j1] = Blocks.STAINED_HARDENED_CLAY.getBlockData().set(BlockCloth.COLOR, EnumColor.YELLOW); + } + } + + k = random.nextInt(4) + 2; + + int k1; + + for (l = 0; l < k; ++l) { + i1 = random.nextInt(3) + 2; + j1 = random.nextInt(64); + + for (k1 = 0; j1 + k1 < 64 && k1 < i1; ++k1) { + this.aD[j1 + k1] = Blocks.STAINED_HARDENED_CLAY.getBlockData().set(BlockCloth.COLOR, EnumColor.BROWN); + } + } + + l = random.nextInt(4) + 2; + + for (i1 = 0; i1 < l; ++i1) { + j1 = random.nextInt(3) + 1; + k1 = random.nextInt(64); + + for (int l1 = 0; k1 + l1 < 64 && l1 < j1; ++l1) { + this.aD[k1 + l1] = Blocks.STAINED_HARDENED_CLAY.getBlockData().set(BlockCloth.COLOR, EnumColor.RED); + } + } + + i1 = random.nextInt(3) + 3; + j1 = 0; + + for (k1 = 0; k1 < i1; ++k1) { + byte b0 = 1; + + j1 += random.nextInt(16) + 4; + + for (int i2 = 0; j1 + i2 < 64 && i2 < b0; ++i2) { + this.aD[j1 + i2] = Blocks.STAINED_HARDENED_CLAY.getBlockData().set(BlockCloth.COLOR, EnumColor.WHITE); + if (j1 + i2 > 1 && random.nextBoolean()) { + this.aD[j1 + i2 - 1] = Blocks.STAINED_HARDENED_CLAY.getBlockData().set(BlockCloth.COLOR, EnumColor.SILVER); + } + + if (j1 + i2 < 63 && random.nextBoolean()) { + this.aD[j1 + i2 + 1] = Blocks.STAINED_HARDENED_CLAY.getBlockData().set(BlockCloth.COLOR, EnumColor.SILVER); + } + } + } + + } + + private IBlockData a(int i, int j, int k) { + int l = (int) Math.round(this.aH.a(i / 512.0D, i / 512.0D) * 2.0D); + + return this.aD[(j + l + 64) % 64]; + } + + protected BiomeBase d(int i) { + boolean flag = this.id == BiomeBase.MESA.id; + BiomeMesa biomemesa = new BiomeMesa(i, flag, this.aJ); + + if (!flag) { + biomemesa.a(BiomeMesa.g); + biomemesa.a(this.ah + " M"); + } else { + biomemesa.a(this.ah + " (Bryce)"); + } + + biomemesa.a(this.ai, true); + return biomemesa; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BiomeMushrooms.java b/azurite-server/src/main/java/net/minecraft/server/BiomeMushrooms.java new file mode 100644 index 0000000..5e61e18 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BiomeMushrooms.java @@ -0,0 +1,18 @@ +package net.minecraft.server; + +public class BiomeMushrooms extends BiomeBase { + + public BiomeMushrooms(int i) { + super(i); + this.as.A = -100; + this.as.B = -100; + this.as.C = -100; + this.as.E = 1; + this.as.K = 1; + this.ak = Blocks.MYCELIUM.getBlockData(); + this.at.clear(); + this.au.clear(); + this.av.clear(); + this.au.add(new BiomeBase.BiomeMeta(EntityMushroomCow.class, 8, 4, 8)); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BiomeOcean.java b/azurite-server/src/main/java/net/minecraft/server/BiomeOcean.java new file mode 100644 index 0000000..1ddc21c --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BiomeOcean.java @@ -0,0 +1,19 @@ +package net.minecraft.server; + +import java.util.Random; + +public class BiomeOcean extends BiomeBase { + + public BiomeOcean(int i) { + super(i); + this.au.clear(); + } + + public BiomeBase.EnumTemperature m() { + return BiomeBase.EnumTemperature.OCEAN; + } + + public void a(World world, Random random, ChunkSnapshot chunksnapshot, int i, int j, double d0) { + super.a(world, random, chunksnapshot, i, j, d0); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BiomePlains.java b/azurite-server/src/main/java/net/minecraft/server/BiomePlains.java new file mode 100644 index 0000000..50d8e6a --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BiomePlains.java @@ -0,0 +1,93 @@ +package net.minecraft.server; + +import java.util.Random; + +public class BiomePlains extends BiomeBase { + + protected boolean aD; + + protected BiomePlains(int i) { + super(i); + this.a(0.8F, 0.4F); + this.a(BiomePlains.e); + this.au.add(new BiomeBase.BiomeMeta(EntityHorse.class, 5, 2, 6)); + this.as.A = -999; + this.as.B = 4; + this.as.C = 10; + } + + public BlockFlowers.EnumFlowerVarient a(Random random, BlockPosition blockposition) { + double d0 = BiomePlains.af.a((double) blockposition.getX() / 200.0D, (double) blockposition.getZ() / 200.0D); + int i; + + if (d0 < -0.8D) { + i = random.nextInt(4); + switch (i) { + case 0: + return BlockFlowers.EnumFlowerVarient.ORANGE_TULIP; + + case 1: + return BlockFlowers.EnumFlowerVarient.RED_TULIP; + + case 2: + return BlockFlowers.EnumFlowerVarient.PINK_TULIP; + + case 3: + default: + return BlockFlowers.EnumFlowerVarient.WHITE_TULIP; + } + } else if (random.nextInt(3) > 0) { + i = random.nextInt(3); + return i == 0 ? BlockFlowers.EnumFlowerVarient.POPPY : (i == 1 ? BlockFlowers.EnumFlowerVarient.HOUSTONIA : BlockFlowers.EnumFlowerVarient.OXEYE_DAISY); + } else { + return BlockFlowers.EnumFlowerVarient.DANDELION; + } + } + + public void a(World world, Random random, BlockPosition blockposition) { + double d0 = BiomePlains.af.a((double) (blockposition.getX() + 8) / 200.0D, (double) (blockposition.getZ() + 8) / 200.0D); + int i; + int j; + int k; + int l; + + if (d0 < -0.8D) { + this.as.B = 15; + this.as.C = 5; + } else { + this.as.B = 4; + this.as.C = 10; + BiomePlains.ag.a(BlockTallPlant.EnumTallFlowerVariants.GRASS); + + for (i = 0; i < 7; ++i) { + j = random.nextInt(16) + 8; + k = random.nextInt(16) + 8; + l = random.nextInt(world.getHighestBlockYAt(blockposition.a(j, 0, k)).getY() + 32); + BiomePlains.ag.generate(world, random, blockposition.a(j, l, k)); + } + } + + if (this.aD) { + BiomePlains.ag.a(BlockTallPlant.EnumTallFlowerVariants.SUNFLOWER); + + for (i = 0; i < 10; ++i) { + j = random.nextInt(16) + 8; + k = random.nextInt(16) + 8; + l = random.nextInt(world.getHighestBlockYAt(blockposition.a(j, 0, k)).getY() + 32); + BiomePlains.ag.generate(world, random, blockposition.a(j, l, k)); + } + } + + super.a(world, random, blockposition); + } + + protected BiomeBase d(int i) { + BiomePlains biomeplains = new BiomePlains(i); + + biomeplains.a("Sunflower Plains"); + biomeplains.aD = true; + biomeplains.b(9286496); + biomeplains.aj = 14273354; + return biomeplains; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BiomeRiver.java b/azurite-server/src/main/java/net/minecraft/server/BiomeRiver.java new file mode 100644 index 0000000..e0a0a79 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BiomeRiver.java @@ -0,0 +1,9 @@ +package net.minecraft.server; + +public class BiomeRiver extends BiomeBase { + + public BiomeRiver(int i) { + super(i); + this.au.clear(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BiomeSavanna.java b/azurite-server/src/main/java/net/minecraft/server/BiomeSavanna.java new file mode 100644 index 0000000..4d3d38a --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BiomeSavanna.java @@ -0,0 +1,70 @@ +package net.minecraft.server; + +import java.util.Random; + +public class BiomeSavanna extends BiomeBase { + + private static final WorldGenAcaciaTree aD = new WorldGenAcaciaTree(false); + + protected BiomeSavanna(int i) { + super(i); + this.au.add(new BiomeBase.BiomeMeta(EntityHorse.class, 1, 2, 6)); + this.as.A = 1; + this.as.B = 4; + this.as.C = 20; + } + + public WorldGenTreeAbstract a(Random random) { + return (WorldGenTreeAbstract) (random.nextInt(5) > 0 ? BiomeSavanna.aD : this.aA); + } + + protected BiomeBase d(int i) { + BiomeSavanna.BiomeSavannaSub biomesavanna_biomesavannasub = new BiomeSavanna.BiomeSavannaSub(i, this); + + biomesavanna_biomesavannasub.temperature = (this.temperature + 1.0F) * 0.5F; + biomesavanna_biomesavannasub.an = this.an * 0.5F + 0.3F; + biomesavanna_biomesavannasub.ao = this.ao * 0.5F + 1.2F; + return biomesavanna_biomesavannasub; + } + + public void a(World world, Random random, BlockPosition blockposition) { + BiomeSavanna.ag.a(BlockTallPlant.EnumTallFlowerVariants.GRASS); + + for (int i = 0; i < 7; ++i) { + int j = random.nextInt(16) + 8; + int k = random.nextInt(16) + 8; + int l = random.nextInt(world.getHighestBlockYAt(blockposition.a(j, 0, k)).getY() + 32); + + BiomeSavanna.ag.generate(world, random, blockposition.a(j, l, k)); + } + + super.a(world, random, blockposition); + } + + public static class BiomeSavannaSub extends BiomeBaseSub { + + public BiomeSavannaSub(int i, BiomeBase biomebase) { + super(i, biomebase); + this.as.A = 2; + this.as.B = 2; + this.as.C = 5; + } + + public void a(World world, Random random, ChunkSnapshot chunksnapshot, int i, int j, double d0) { + this.ak = Blocks.GRASS.getBlockData(); + this.al = Blocks.DIRT.getBlockData(); + if (d0 > 1.75D) { + this.ak = Blocks.STONE.getBlockData(); + this.al = Blocks.STONE.getBlockData(); + } else if (d0 > -0.5D) { + this.ak = Blocks.DIRT.getBlockData().set(BlockDirt.VARIANT, BlockDirt.EnumDirtVariant.COARSE_DIRT); + } + + this.b(world, random, chunksnapshot, i, j, d0); + } + + public void a(World world, Random random, BlockPosition blockposition) { + this.as.a(world, random, this, blockposition); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BiomeStoneBeach.java b/azurite-server/src/main/java/net/minecraft/server/BiomeStoneBeach.java new file mode 100644 index 0000000..453033f --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BiomeStoneBeach.java @@ -0,0 +1,15 @@ +package net.minecraft.server; + +public class BiomeStoneBeach extends BiomeBase { + + public BiomeStoneBeach(int i) { + super(i); + this.au.clear(); + this.ak = Blocks.STONE.getBlockData(); + this.al = Blocks.STONE.getBlockData(); + this.as.A = -999; + this.as.D = 0; + this.as.F = 0; + this.as.G = 0; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BiomeSwamp.java b/azurite-server/src/main/java/net/minecraft/server/BiomeSwamp.java new file mode 100644 index 0000000..29959fd --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BiomeSwamp.java @@ -0,0 +1,53 @@ +package net.minecraft.server; + +import java.util.Random; + +public class BiomeSwamp extends BiomeBase { + + protected BiomeSwamp(int i) { + super(i); + this.as.A = 2; + this.as.B = 1; + this.as.D = 1; + this.as.E = 8; + this.as.F = 10; + this.as.J = 1; + this.as.z = 4; + this.as.I = 0; + this.as.H = 0; + this.as.C = 5; + this.ar = 14745518; + this.at.add(new BiomeBase.BiomeMeta(EntitySlime.class, 1, 1, 1)); + } + + public WorldGenTreeAbstract a(Random random) { + return this.aC; + } + + public BlockFlowers.EnumFlowerVarient a(Random random, BlockPosition blockposition) { + return BlockFlowers.EnumFlowerVarient.BLUE_ORCHID; + } + + public void a(World world, Random random, ChunkSnapshot chunksnapshot, int i, int j, double d0) { + double d1 = BiomeSwamp.af.a((double) i * 0.25D, (double) j * 0.25D); + + if (d1 > 0.0D) { + int k = i & 15; + int l = j & 15; + + for (int i1 = 255; i1 >= 0; --i1) { + if (chunksnapshot.a(l, i1, k).getBlock().getMaterial() != Material.AIR) { + if (i1 == 62 && chunksnapshot.a(l, i1, k).getBlock() != Blocks.WATER) { + chunksnapshot.a(l, i1, k, Blocks.WATER.getBlockData()); + if (d1 < 0.12D) { + chunksnapshot.a(l, i1 + 1, k, Blocks.WATERLILY.getBlockData()); + } + } + break; + } + } + } + + this.b(world, random, chunksnapshot, i, j, d0); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BiomeTaiga.java b/azurite-server/src/main/java/net/minecraft/server/BiomeTaiga.java new file mode 100644 index 0000000..314dfed --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BiomeTaiga.java @@ -0,0 +1,85 @@ +package net.minecraft.server; + +import java.util.Random; + +public class BiomeTaiga extends BiomeBase { + + private static final WorldGenTaiga1 aD = new WorldGenTaiga1(); + private static final WorldGenTaiga2 aE = new WorldGenTaiga2(false); + private static final WorldGenMegaTree aF = new WorldGenMegaTree(false, false); + private static final WorldGenMegaTree aG = new WorldGenMegaTree(false, true); + private static final WorldGenTaigaStructure aH = new WorldGenTaigaStructure(Blocks.MOSSY_COBBLESTONE, 0); + private int aI; + + public BiomeTaiga(int i, int j) { + super(i); + this.aI = j; + this.au.add(new BiomeBase.BiomeMeta(EntityWolf.class, 8, 4, 4)); + this.as.A = 10; + if (j != 1 && j != 2) { + this.as.C = 1; + this.as.E = 1; + } else { + this.as.C = 7; + this.as.D = 1; + this.as.E = 3; + } + + } + + public WorldGenTreeAbstract a(Random random) { + return (WorldGenTreeAbstract) ((this.aI == 1 || this.aI == 2) && random.nextInt(3) == 0 ? (this.aI != 2 && random.nextInt(13) != 0 ? BiomeTaiga.aF : BiomeTaiga.aG) : (random.nextInt(3) == 0 ? BiomeTaiga.aD : BiomeTaiga.aE)); + } + + public WorldGenerator b(Random random) { + return random.nextInt(5) > 0 ? new WorldGenGrass(BlockLongGrass.EnumTallGrassType.FERN) : new WorldGenGrass(BlockLongGrass.EnumTallGrassType.GRASS); + } + + public void a(World world, Random random, BlockPosition blockposition) { + int i; + int j; + int k; + int l; + + if (this.aI == 1 || this.aI == 2) { + i = random.nextInt(3); + + for (j = 0; j < i; ++j) { + k = random.nextInt(16) + 8; + l = random.nextInt(16) + 8; + BlockPosition blockposition1 = world.getHighestBlockYAt(blockposition.a(k, 0, l)); + + BiomeTaiga.aH.generate(world, random, blockposition1); + } + } + + BiomeTaiga.ag.a(BlockTallPlant.EnumTallFlowerVariants.FERN); + + for (i = 0; i < 7; ++i) { + j = random.nextInt(16) + 8; + k = random.nextInt(16) + 8; + l = random.nextInt(world.getHighestBlockYAt(blockposition.a(j, 0, k)).getY() + 32); + BiomeTaiga.ag.generate(world, random, blockposition.a(j, l, k)); + } + + super.a(world, random, blockposition); + } + + public void a(World world, Random random, ChunkSnapshot chunksnapshot, int i, int j, double d0) { + if (this.aI == 1 || this.aI == 2) { + this.ak = Blocks.GRASS.getBlockData(); + this.al = Blocks.DIRT.getBlockData(); + if (d0 > 1.75D) { + this.ak = Blocks.DIRT.getBlockData().set(BlockDirt.VARIANT, BlockDirt.EnumDirtVariant.COARSE_DIRT); + } else if (d0 > -0.95D) { + this.ak = Blocks.DIRT.getBlockData().set(BlockDirt.VARIANT, BlockDirt.EnumDirtVariant.PODZOL); + } + } + + this.b(world, random, chunksnapshot, i, j, d0); + } + + protected BiomeBase d(int i) { + return this.id == BiomeBase.MEGA_TAIGA.id ? (new BiomeTaiga(i, 2)).a(5858897, true).a("Mega Spruce Taiga").a(5159473).a(0.25F, 0.8F).a(new BiomeBase.BiomeTemperature(this.an, this.ao)) : super.d(i); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BiomeTheEnd.java b/azurite-server/src/main/java/net/minecraft/server/BiomeTheEnd.java new file mode 100644 index 0000000..24fb34d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BiomeTheEnd.java @@ -0,0 +1,16 @@ +package net.minecraft.server; + +public class BiomeTheEnd extends BiomeBase { + + public BiomeTheEnd(int i) { + super(i); + this.at.clear(); + this.au.clear(); + this.av.clear(); + this.aw.clear(); + this.at.add(new BiomeBase.BiomeMeta(EntityEnderman.class, 10, 4, 4)); + this.ak = Blocks.DIRT.getBlockData(); + this.al = Blocks.DIRT.getBlockData(); + this.as = new BiomeTheEndDecorator(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BiomeTheEndDecorator.java b/azurite-server/src/main/java/net/minecraft/server/BiomeTheEndDecorator.java new file mode 100644 index 0000000..6a7f99b --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BiomeTheEndDecorator.java @@ -0,0 +1,27 @@ +package net.minecraft.server; + +public class BiomeTheEndDecorator extends BiomeDecorator { + + protected WorldGenerator M; + + public BiomeTheEndDecorator() { + this.M = new WorldGenEnder(Blocks.END_STONE); + } + + protected void a(BiomeBase biomebase) { + this.a(); + if (this.b.nextInt(5) == 0) { + int i = this.b.nextInt(16) + 8; + int j = this.b.nextInt(16) + 8; + + this.M.generate(this.a, this.b, this.a.r(this.c.a(i, 0, j))); + } + + if (this.c.getX() == 0 && this.c.getZ() == 0) { + EntityEnderDragon entityenderdragon = new EntityEnderDragon(this.a); + + entityenderdragon.setPositionRotation(0.0D, 128.0D, 0.0D, this.b.nextFloat() * 360.0F, 0.0F); + this.a.addEntity(entityenderdragon, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.CHUNK_GEN); // CraftBukkit - add SpawnReason + } + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/net/minecraft/server/Block.java b/azurite-server/src/main/java/net/minecraft/server/Block.java new file mode 100644 index 0000000..c85d913 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/Block.java @@ -0,0 +1,1026 @@ +package net.minecraft.server; + +import dev.azurite.spigot.Azurite; +import dev.azurite.spigot.configs.AzuriteConfig; +import dev.azurite.spigot.configs.LanguageConfig; +import dev.azurite.spigot.optimizations.ConstantRegistryID; +import dev.azurite.spigot.utils.CC; +import dev.azurite.spigot.utils.Utils; +import org.bukkit.Bukkit; +import org.bukkit.craftbukkit.entity.CraftItem; +import org.bukkit.event.block.BlockDropItemsEvent; +import org.spigotmc.AsyncCatcher; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Random; + +public class Block { + + public static Item durabilityChecker; + public static final RegistryID d = new ConstantRegistryID(); + public static final StepSound e = new StepSound("stone", 1.0F, 1.0F); + public static final StepSound f = new StepSound("wood", 1.0F, 1.0F); + public static final StepSound g = new StepSound("gravel", 1.0F, 1.0F); + public static final StepSound h = new StepSound("grass", 1.0F, 1.0F); + public static final StepSound i = new StepSound("stone", 1.0F, 1.0F); + public static final StepSound j = new StepSound("stone", 1.0F, 1.5F); + public static final StepSound k = new StepSound("stone", 1.0F, 1.0F) { + public String getBreakSound() { + return "dig.glass"; + } + + public String getPlaceSound() { + return "step.stone"; + } + }; + public static final StepSound l = new StepSound("cloth", 1.0F, 1.0F); + public static final StepSound m = new StepSound("sand", 1.0F, 1.0F); + public static final StepSound n = new StepSound("snow", 1.0F, 1.0F); + public static final StepSound o = new StepSound("ladder", 1.0F, 1.0F) { + public String getBreakSound() { + return "dig.wood"; + } + }; + public static final StepSound p = new StepSound("anvil", 0.3F, 1.0F) { + public String getBreakSound() { + return "dig.stone"; + } + + public String getPlaceSound() { + return "random.anvil_land"; + } + }; + public static final StepSound q = new StepSound("slime", 1.0F, 1.0F) { + public String getBreakSound() { + return "mob.slime.big"; + } + + public String getPlaceSound() { + return "mob.slime.big"; + } + + public String getStepSound() { + return "mob.slime.small"; + } + }; + private static final MinecraftKey a = new MinecraftKey("air"); + public static final RegistryBlocks REGISTRY = new RegistryBlocks<>(a); + protected final Material material; + protected final MaterialMapColor K; + protected final BlockStateList blockStateList; + public StepSound stepSound; + public float I; + public float frictionFactor; + protected boolean r; + protected int s; + protected boolean t; + protected int u; + protected boolean v; + + protected float strength; + public float durability; + public float explosionResistance; // Vortex - cached explosion resistance + public int explosionDurability; // Vortex - explosion destroyer + + protected boolean y; + protected boolean z; + protected boolean isTileEntity; + protected double minX; + protected double minY; + protected double minZ; + protected double maxX; + protected double maxY; + protected double maxZ; + private IBlockData blockData; + + public List droppedItemsCatcher; + private String name; + + public Block(Material material, MaterialMapColor materialmapcolor) { + this.y = true; + this.stepSound = e; + this.I = 1.0F; + this.frictionFactor = 0.6F; + this.material = material; + this.K = materialmapcolor; + a(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + this.r = c(); + this.s = c() ? 255 : 0; + this.t = !material.blocksLight(); + this.blockStateList = getStateList(); + j(this.blockStateList.getBlockData()); + } + + protected Block(Material material) { + this(material, material.r()); + } + + public static int getId(Block block) { + return REGISTRY.b(block); + } + + public static int getCombinedId(IBlockData iblockdata) { + Block block = iblockdata.getBlock(); + return getId(block) + (block.toLegacyData(iblockdata) << 12); + } + + public static Block getById(int i) { + return REGISTRY.a(i); + } + + public static IBlockData getByCombinedId(int i) { + return getById(i & 0xFFF).fromLegacyData(i >> 12 & 0xF); + } + + public static Block asBlock(Item item) { + return (item instanceof ItemBlock) ? ((ItemBlock) item).d() : null; + } + + public static Block getByName(String s) { + MinecraftKey minecraftkey = new MinecraftKey(s); + if (REGISTRY.d(minecraftkey)) + return REGISTRY.get(minecraftkey); + try { + return REGISTRY.a(Integer.parseInt(s)); + } catch (NumberFormatException numberFormatException) { + return null; + } + } + + public void a(World world, int x, int y, int z, ItemStack itemstack) { + if (world.getGameRules().getBoolean("doTileDrops")) { + EntityItem entityitem = new EntityItem(world, x + (world.random.nextFloat() * 0.5F) + 0.5F * 0.5D, y + (world.random.nextFloat() * 0.5F) + 0.5F * 0.5D, z + (world.random.nextFloat() * 0.5F) + 0.5F * 0.5D, itemstack); + entityitem.p(); + if (this.droppedItemsCatcher == null) { + world.addEntity(entityitem); + } else { + this.droppedItemsCatcher.add(new CraftItem(world.getServer(), entityitem)); + } + } + } + + public static void dropItem(World world, int x, int y, int z, ItemStack itemstack) { + if (world.getGameRules().getBoolean("doTileDrops")) { + EntityItem entityitem = new EntityItem(world, x + (world.random.nextFloat() * 0.5F) + 0.5F * 0.5D, y + (world.random.nextFloat() * 0.5F) + 0.5F * 0.5D, z + (world.random.nextFloat() * 0.5F) + 0.5F * 0.5D, itemstack); + entityitem.p(); + world.addEntity(entityitem); + } + } + + public void a(World world, BlockPosition blockposition, ItemStack itemstack) { + a(world, blockposition.getX(), blockposition.getY(), blockposition.getZ(), itemstack); + } + + public static boolean a(Block block, Block block1) { + return block != null && block1 != null && (block == block1 || block.b(block1)); + } + + public static void S() { + a(0, a, (new BlockAir()).c("air")); + a(1, "stone", (new BlockStone()).c(1.5F).b(10.0F).a(Block.i).c("stone")); + a(2, "grass", (new BlockGrass()).c(0.6F).a(h).c("grass")); + a(3, "dirt", (new BlockDirt()).c(0.5F).a(g).c("dirt")); + Block block = (new Block(Material.STONE)).c(2.0F).b(10.0F).a(Block.i).c("stonebrick").a(CreativeModeTab.b); + a(4, "cobblestone", block); + Block block1 = (new BlockWood()).c(2.0F).b(5.0F).a(f).c("wood"); + a(5, "planks", block1); + a(6, "sapling", (new BlockSapling()).c(0.0F).a(h).c("sapling")); + a(7, "bedrock", (new Block(Material.STONE)).x().b(6000000.0F).a(i).c("bedrock").K().a(CreativeModeTab.b)); + a(8, "flowing_water", (new BlockFlowing(Material.WATER)).c(100.0F).e(3).c("water").K()); + a(9, "water", (new BlockStationary(Material.WATER)).c(100.0F).e(3).c("water").K()); + a(10, "flowing_lava", (new BlockFlowing(Material.LAVA)).c(100.0F).a(1.0F).c("lava").K()); + a(11, "lava", (new BlockStationary(Material.LAVA)).c(100.0F).a(1.0F).c("lava").K()); + a(12, "sand", (new BlockSand()).c(0.5F).a(m).c("sand")); + a(13, "gravel", (new BlockGravel()).c(0.6F).a(g).c("gravel")); + a(14, "gold_ore", (new BlockOre()).c(3.0F).b(5.0F).a(Block.i).c("oreGold")); + a(15, "iron_ore", (new BlockOre()).c(3.0F).b(5.0F).a(Block.i).c("oreIron")); + a(16, "coal_ore", (new BlockOre()).c(3.0F).b(5.0F).a(Block.i).c("oreCoal")); + a(17, "log", (new BlockLog1()).c("log")); + a(18, "leaves", (new BlockLeaves1()).c("leaves")); + a(19, "sponge", (new BlockSponge()).c(AzuriteConfig.spongeInstantBreak.getValue() ? 0.0F : 0.6F).a(h).c("sponge")); + a(20, "glass", (new BlockGlass(Material.SHATTERABLE, false)).c(0.3F).a(k).c("glass")); + a(21, "lapis_ore", (new BlockOre()).c(3.0F).b(5.0F).a(Block.i).c("oreLapis")); + a(22, "lapis_block", (new Block(Material.ORE, MaterialMapColor.H)).c(3.0F).b(5.0F).a(Block.i).c("blockLapis").a(CreativeModeTab.b)); + a(23, "dispenser", (new BlockDispenser()).c(3.5F).a(Block.i).c("dispenser")); + Block block2 = (new BlockSandStone()).a(Block.i).c(0.8F).c("sandStone"); + a(24, "sandstone", block2); + a(25, "noteblock", (new BlockNote()).c(0.8F).c("musicBlock")); + a(26, "bed", (new BlockBed()).a(f).c(0.2F).c("bed").K()); + a(27, "golden_rail", (new BlockPoweredRail()).c(0.7F).a(j).c("goldenRail")); + a(28, "detector_rail", (new BlockMinecartDetector()).c(0.7F).a(j).c("detectorRail")); + a(29, "sticky_piston", (new BlockPiston(true)).c("pistonStickyBase")); + a(30, "web", (new BlockWeb()).e(1).c(4.0F).c("web")); + a(31, "tallgrass", (new BlockLongGrass()).c(0.0F).a(h).c("tallgrass")); + a(32, "deadbush", (new BlockDeadBush()).c(0.0F).a(h).c("deadbush")); + a(33, "piston", (new BlockPiston(false)).c("pistonBase")); + a(34, "piston_head", (new BlockPistonExtension()).c("pistonBase")); + a(35, "wool", (new BlockCloth(Material.CLOTH)).c(0.8F).a(l).c("cloth")); + a(36, "piston_extension", new BlockPistonMoving()); + a(37, "yellow_flower", (new BlockYellowFlowers()).c(0.0F).a(h).c("flower1")); + a(38, "red_flower", (new BlockRedFlowers()).c(0.0F).a(h).c("flower2")); + Block block3 = (new BlockMushroom()).c(0.0F).a(h).a(0.125F).c("mushroom"); + a(39, "brown_mushroom", block3); + Block block4 = (new BlockMushroom()).c(0.0F).a(h).c("mushroom"); + a(40, "red_mushroom", block4); + a(41, "gold_block", (new Block(Material.ORE, MaterialMapColor.F)).c(3.0F).b(10.0F).a(j).c("blockGold").a(CreativeModeTab.b)); + a(42, "iron_block", (new Block(Material.ORE, MaterialMapColor.h)).c(5.0F).b(10.0F).a(j).c("blockIron").a(CreativeModeTab.b)); + a(43, "double_stone_slab", (new BlockDoubleStep()).c(2.0F).b(10.0F).a(Block.i).c("stoneSlab")); + a(44, "stone_slab", (new BlockStep()).c(2.0F).b(10.0F).a(Block.i).c("stoneSlab")); + Block block5 = (new Block(Material.STONE, MaterialMapColor.D)).c(2.0F).b(10.0F).a(Block.i).c("brick").a(CreativeModeTab.b); + a(45, "brick_block", block5); + a(46, "tnt", (new BlockTNT()).c(0.0F).a(h).c("tnt")); + a(47, "bookshelf", (new BlockBookshelf()).c(1.5F).a(f).c("bookshelf")); + a(48, "mossy_cobblestone", (new Block(Material.STONE)).c(2.0F).b(10.0F).a(Block.i).c("stoneMoss").a(CreativeModeTab.b)); + a(49, "obsidian", (new BlockObsidian()).c(50.0F).b(2000.0F).a(Block.i).c("obsidian")); + a(50, "torch", (new BlockTorch()).c(0.0F).a(0.9375F).a(f).c("torch")); + a(51, "fire", (new BlockFire()).c(0.0F).a(1.0F).a(l).c("fire").K()); + a(52, "mob_spawner", (new BlockMobSpawner()).c(5.0F).a(j).c("mobSpawner").K()); + a(53, "oak_stairs", (new BlockStairs(block1.getBlockData().set(BlockWood.VARIANT, BlockWood.EnumLogVariant.OAK))).c("stairsWood")); + a(54, "chest", (new BlockChest(0)).c(2.5F).a(f).c("chest")); + a(55, "redstone_wire", Azurite.getInstance().getRedstoneOptimization().c(0.0F).a(e).c("redstoneDust").K()); + a(56, "diamond_ore", (new BlockOre()).c(3.0F).b(5.0F).a(Block.i).c("oreDiamond")); + a(57, "diamond_block", (new Block(Material.ORE, MaterialMapColor.G)).c(5.0F).b(10.0F).a(j).c("blockDiamond").a(CreativeModeTab.b)); + a(58, "crafting_table", (new BlockWorkbench()).c(2.5F).a(f).c("workbench")); + a(59, "wheat", (new BlockCrops()).c("crops")); + Block block6 = (new BlockSoil()).c(0.6F).a(g).c("farmland"); + a(60, "farmland", block6); + a(61, "furnace", (new BlockFurnace(false)).c(3.5F).a(Block.i).c("furnace").a(CreativeModeTab.c)); + a(62, "lit_furnace", (new BlockFurnace(true)).c(3.5F).a(Block.i).a(0.875F).c("furnace")); + a(63, "standing_sign", (new BlockFloorSign()).c(1.0F).a(f).c("sign").K()); + a(64, "wooden_door", (new BlockDoor(Material.WOOD)).c(3.0F).a(f).c("doorOak").K()); + a(65, "ladder", (new BlockLadder()).c(0.4F).a(o).c("ladder")); + a(66, "rail", (new BlockMinecartTrack()).c(0.7F).a(j).c("rail")); + a(67, "stone_stairs", (new BlockStairs(block.getBlockData())).c("stairsStone")); + a(68, "wall_sign", (new BlockWallSign()).c(1.0F).a(f).c("sign").K()); + a(69, "lever", (new BlockLever()).c(0.5F).a(f).c("lever")); + a(70, "stone_pressure_plate", (new BlockPressurePlateBinary(Material.STONE, BlockPressurePlateBinary.EnumMobType.MOBS)).c(0.5F).a(Block.i).c("pressurePlateStone")); + a(71, "iron_door", (new BlockDoor(Material.ORE)).c(5.0F).a(j).c("doorIron").K()); + a(72, "wooden_pressure_plate", (new BlockPressurePlateBinary(Material.WOOD, BlockPressurePlateBinary.EnumMobType.EVERYTHING)).c(0.5F).a(f).c("pressurePlateWood")); + a(73, "redstone_ore", (new BlockRedstoneOre(false)).c(3.0F).b(5.0F).a(Block.i).c("oreRedstone").a(CreativeModeTab.b)); + a(74, "lit_redstone_ore", (new BlockRedstoneOre(true)).a(0.625F).c(3.0F).b(5.0F).a(Block.i).c("oreRedstone")); + a(75, "unlit_redstone_torch", (new BlockRedstoneTorch(false)).c(0.0F).a(f).c("notGate")); + a(76, "redstone_torch", (new BlockRedstoneTorch(true)).c(0.0F).a(0.5F).a(f).c("notGate").a(CreativeModeTab.d)); + a(77, "stone_button", (new BlockStoneButton()).c(0.5F).a(Block.i).c("button")); + a(78, "snow_layer", (new BlockSnow()).c(0.1F).a(n).c("snow").e(0)); + a(79, "ice", (new BlockIce()).c(0.5F).e(3).a(k).c("ice")); + a(80, "snow", (new BlockSnowBlock()).c(0.2F).a(n).c("snow")); + a(81, "cactus", (new BlockCactus()).c(0.4F).a(l).c("cactus")); + a(82, "clay", (new BlockClay()).c(0.6F).a(g).c("clay")); + a(83, "reeds", (new BlockReed()).c(0.0F).a(h).c("reeds").K()); + a(84, "jukebox", (new BlockJukeBox()).c(2.0F).b(10.0F).a(Block.i).c("jukebox")); + a(85, "fence", (new BlockFence(Material.WOOD, BlockWood.EnumLogVariant.OAK.c())).c(2.0F).b(5.0F).a(f).c("fence")); + Block block7 = (new BlockPumpkin()).c(1.0F).a(f).c("pumpkin"); + a(86, "pumpkin", block7); + a(87, "netherrack", (new BlockBloodStone()).c(0.4F).a(Block.i).c("hellrock")); + a(88, "soul_sand", (new BlockSlowSand()).c(0.5F).a(m).c("hellsand")); + a(89, "glowstone", (new BlockLightStone(Material.SHATTERABLE)).c(0.3F).a(k).a(1.0F).c("lightgem")); + a(90, "portal", (new BlockPortal()).c(-1.0F).a(k).a(0.75F).c("portal")); + a(91, "lit_pumpkin", (new BlockPumpkin()).c(1.0F).a(f).a(1.0F).c("litpumpkin")); + a(92, "cake", (new BlockCake()).c(0.5F).a(l).c("cake").K()); + a(93, "unpowered_repeater", (new BlockRepeater(false)).c(0.0F).a(f).c("diode").K()); + a(94, "powered_repeater", (new BlockRepeater(true)).c(0.0F).a(f).c("diode").K()); + a(95, "stained_glass", (new BlockStainedGlass(Material.SHATTERABLE)).c(0.3F).a(k).c("stainedGlass")); + a(96, "trapdoor", (new BlockTrapdoor(Material.WOOD)).c(3.0F).a(f).c("trapdoor").K()); + a(97, "monster_egg", (new BlockMonsterEggs()).c(0.75F).c("monsterStoneEgg")); + Block block8 = (new BlockSmoothBrick()).c(1.5F).b(10.0F).a(Block.i).c("stonebricksmooth"); + a(98, "stonebrick", block8); + a(99, "brown_mushroom_block", (new BlockHugeMushroom(Material.WOOD, MaterialMapColor.l, block3)).c(0.2F).a(f).c("mushroom")); + a(100, "red_mushroom_block", (new BlockHugeMushroom(Material.WOOD, MaterialMapColor.D, block4)).c(0.2F).a(f).c("mushroom")); + a(101, "iron_bars", (new BlockThin(Material.ORE, true)).c(5.0F).b(10.0F).a(j).c("fenceIron")); + a(102, "glass_pane", (new BlockThin(Material.SHATTERABLE, false)).c(0.3F).a(k).c("thinGlass")); + Block block9 = (new BlockMelon()).c(1.0F).a(f).c("melon"); + a(103, "melon_block", block9); + a(104, "pumpkin_stem", (new BlockStem(block7)).c(0.0F).a(f).c("pumpkinStem")); + a(105, "melon_stem", (new BlockStem(block9)).c(0.0F).a(f).c("pumpkinStem")); + a(106, "vine", (new BlockVine()).c(0.2F).a(h).c("vine")); + a(107, "fence_gate", (new BlockFenceGate(BlockWood.EnumLogVariant.OAK)).c(2.0F).b(5.0F).a(f).c("fenceGate")); + a(108, "brick_stairs", (new BlockStairs(block5.getBlockData())).c("stairsBrick")); + a(109, "stone_brick_stairs", (new BlockStairs(block8.getBlockData().set(BlockSmoothBrick.VARIANT, BlockSmoothBrick.EnumStonebrickType.DEFAULT))).c("stairsStoneBrickSmooth")); + a(110, "mycelium", (new BlockMycel()).c(0.6F).a(h).c("mycel")); + a(111, "waterlily", (new BlockWaterLily()).c(0.0F).a(h).c("waterlily")); + Block block10 = (new BlockNetherbrick()).c(2.0F).b(10.0F).a(Block.i).c("netherBrick").a(CreativeModeTab.b); + a(112, "nether_brick", block10); + a(113, "nether_brick_fence", (new BlockFence(Material.STONE, MaterialMapColor.K)).c(2.0F).b(10.0F).a(Block.i).c("netherFence")); + a(114, "nether_brick_stairs", (new BlockStairs(block10.getBlockData())).c("stairsNetherBrick")); + a(115, "nether_wart", (new BlockNetherWart()).c("netherStalk")); + a(116, "enchanting_table", (new BlockEnchantmentTable()).c(5.0F).b(2000.0F).c("enchantmentTable")); + a(117, "brewing_stand", (new BlockBrewingStand()).c(0.5F).a(0.125F).c("brewingStand")); + a(118, "cauldron", (new BlockCauldron()).c(2.0F).c("cauldron")); + a(119, "end_portal", (new BlockEnderPortal(Material.PORTAL)).c(-1.0F).b(6000000.0F)); + a(120, "end_portal_frame", (new BlockEnderPortalFrame()).a(k).a(0.125F).c(-1.0F).c("endPortalFrame").b(6000000.0F).a(CreativeModeTab.c)); + a(121, "end_stone", (new Block(Material.STONE, MaterialMapColor.d)).c(3.0F).b(15.0F).a(Block.i).c("whiteStone").a(CreativeModeTab.b)); + a(122, "dragon_egg", (new BlockDragonEgg()).c(3.0F).b(15.0F).a(Block.i).a(0.125F).c("dragonEgg")); + a(123, "redstone_lamp", (new BlockRedstoneLamp(false)).c(0.3F).a(k).c("redstoneLight").a(CreativeModeTab.d)); + a(124, "lit_redstone_lamp", (new BlockRedstoneLamp(true)).c(0.3F).a(k).c("redstoneLight")); + a(125, "double_wooden_slab", (new BlockDoubleWoodStep()).c(2.0F).b(5.0F).a(f).c("woodSlab")); + a(126, "wooden_slab", (new BlockWoodStep()).c(2.0F).b(5.0F).a(f).c("woodSlab")); + a(127, "cocoa", (new BlockCocoa()).c(0.2F).b(5.0F).a(f).c("cocoa")); + a(128, "sandstone_stairs", (new BlockStairs(block2.getBlockData().set(BlockSandStone.TYPE, BlockSandStone.EnumSandstoneVariant.SMOOTH))).c("stairsSandStone")); + a(129, "emerald_ore", (new BlockOre()).c(3.0F).b(5.0F).a(Block.i).c("oreEmerald")); + a(130, "ender_chest", (new BlockEnderChest()).c(22.5F).b(1000.0F).a(Block.i).c("enderChest").a(0.5F)); + a(131, "tripwire_hook", (new BlockTripwireHook()).c("tripWireSource")); + a(132, "tripwire", (new BlockTripwire()).c("tripWire")); + a(133, "emerald_block", (new Block(Material.ORE, MaterialMapColor.I)).c(5.0F).b(10.0F).a(j).c("blockEmerald").a(CreativeModeTab.b)); + a(134, "spruce_stairs", (new BlockStairs(block1.getBlockData().set(BlockWood.VARIANT, BlockWood.EnumLogVariant.SPRUCE))).c("stairsWoodSpruce")); + a(135, "birch_stairs", (new BlockStairs(block1.getBlockData().set(BlockWood.VARIANT, BlockWood.EnumLogVariant.BIRCH))).c("stairsWoodBirch")); + a(136, "jungle_stairs", (new BlockStairs(block1.getBlockData().set(BlockWood.VARIANT, BlockWood.EnumLogVariant.JUNGLE))).c("stairsWoodJungle")); + a(137, "command_block", (new BlockCommand()).x().b(6000000.0F).c("commandBlock")); + a(138, "beacon", (new BlockBeacon()).c("beacon").a(1.0F)); + a(139, "cobblestone_wall", (new BlockCobbleWall(block)).c("cobbleWall")); + a(140, "flower_pot", (new BlockFlowerPot()).c(0.0F).a(e).c("flowerPot")); + a(141, "carrots", (new BlockCarrots()).c("carrots")); + a(142, "potatoes", (new BlockPotatoes()).c("potatoes")); + a(143, "wooden_button", (new BlockWoodButton()).c(0.5F).a(f).c("button")); + a(144, "skull", (new BlockSkull()).c(1.0F).a(Block.i).c("skull")); + a(145, "anvil", (new BlockAnvil()).c(5.0F).a(p).b(2000.0F).c("anvil")); + a(146, "trapped_chest", (new BlockChest(1)).c(2.5F).a(f).c("chestTrap")); + a(147, "light_weighted_pressure_plate", (new BlockPressurePlateWeighted(Material.ORE, 15, MaterialMapColor.F)).c(0.5F).a(f).c("weightedPlate_light")); + a(148, "heavy_weighted_pressure_plate", (new BlockPressurePlateWeighted(Material.ORE, 150)).c(0.5F).a(f).c("weightedPlate_heavy")); + a(149, "unpowered_comparator", (new BlockRedstoneComparator(false)).c(0.0F).a(f).c("comparator").K()); + a(150, "powered_comparator", (new BlockRedstoneComparator(true)).c(0.0F).a(0.625F).a(f).c("comparator").K()); + a(151, "daylight_detector", new BlockDaylightDetector(false)); + a(152, "redstone_block", (new BlockPowered(Material.ORE, MaterialMapColor.f)).c(5.0F).b(10.0F).a(j).c("blockRedstone").a(CreativeModeTab.d)); + a(153, "quartz_ore", (new BlockOre(MaterialMapColor.K)).c(3.0F).b(5.0F).a(Block.i).c("netherquartz")); + a(154, "hopper", (new BlockHopper()).c(3.0F).b(8.0F).a(j).c("hopper")); + Block block11 = (new BlockQuartz()).a(Block.i).c(0.8F).c("quartzBlock"); + a(155, "quartz_block", block11); + a(156, "quartz_stairs", (new BlockStairs(block11.getBlockData().set(BlockQuartz.VARIANT, BlockQuartz.EnumQuartzVariant.DEFAULT))).c("stairsQuartz")); + a(157, "activator_rail", (new BlockPoweredRail()).c(0.7F).a(j).c("activatorRail")); + a(158, "dropper", (new BlockDropper()).c(3.5F).a(Block.i).c("dropper")); + a(159, "stained_hardened_clay", (new BlockCloth(Material.STONE)).c(1.25F).b(7.0F).a(Block.i).c("clayHardenedStained")); + a(160, "stained_glass_pane", (new BlockStainedGlassPane()).c(0.3F).a(k).c("thinStainedGlass")); + a(161, "leaves2", (new BlockLeaves2()).c("leaves")); + a(162, "log2", (new BlockLog2()).c("log")); + a(163, "acacia_stairs", (new BlockStairs(block1.getBlockData().set(BlockWood.VARIANT, BlockWood.EnumLogVariant.ACACIA))).c("stairsWoodAcacia")); + a(164, "dark_oak_stairs", (new BlockStairs(block1.getBlockData().set(BlockWood.VARIANT, BlockWood.EnumLogVariant.DARK_OAK))).c("stairsWoodDarkOak")); + a(165, "slime", (new BlockSlime()).c("slime").a(q)); + a(166, "barrier", (new BlockBarrier()).c("barrier")); + a(167, "iron_trapdoor", (new BlockTrapdoor(Material.ORE)).c(5.0F).a(j).c("ironTrapdoor").K()); + a(168, "prismarine", (new BlockPrismarine()).c(1.5F).b(10.0F).a(Block.i).c("prismarine")); + a(169, "sea_lantern", (new BlockSeaLantern(Material.SHATTERABLE)).c(0.3F).a(k).a(1.0F).c("seaLantern")); + a(170, "hay_block", (new BlockHay()).c(0.5F).a(h).c("hayBlock").a(CreativeModeTab.b)); + a(171, "carpet", (new BlockCarpet()).c(0.1F).a(l).c("woolCarpet").e(0)); + a(172, "hardened_clay", (new BlockHardenedClay()).c(1.25F).b(7.0F).a(Block.i).c("clayHardened")); + a(173, "coal_block", (new Block(Material.STONE, MaterialMapColor.E)).c(5.0F).b(10.0F).a(Block.i).c("blockCoal").a(CreativeModeTab.b)); + a(174, "packed_ice", (new BlockPackedIce()).c(0.5F).a(k).c("icePacked")); + a(175, "double_plant", new BlockTallPlant()); + a(176, "standing_banner", (new BlockBanner.BlockStandingBanner()).c(1.0F).a(f).c("banner").K()); + a(177, "wall_banner", (new BlockBanner.BlockWallBanner()).c(1.0F).a(f).c("banner").K()); + a(178, "daylight_detector_inverted", new BlockDaylightDetector(true)); + Block block12 = (new BlockRedSandstone()).a(Block.i).c(0.8F).c("redSandStone"); + a(179, "red_sandstone", block12); + a(180, "red_sandstone_stairs", (new BlockStairs(block12.getBlockData().set(BlockRedSandstone.TYPE, BlockRedSandstone.EnumRedSandstoneVariant.SMOOTH))).c("stairsRedSandStone")); + a(181, "double_stone_slab2", (new BlockDoubleStoneStep2()).c(2.0F).b(10.0F).a(Block.i).c("stoneSlab2")); + a(182, "stone_slab2", (new BlockStoneStep2()).c(2.0F).b(10.0F).a(Block.i).c("stoneSlab2")); + a(183, "spruce_fence_gate", (new BlockFenceGate(BlockWood.EnumLogVariant.SPRUCE)).c(2.0F).b(5.0F).a(f).c("spruceFenceGate")); + a(184, "birch_fence_gate", (new BlockFenceGate(BlockWood.EnumLogVariant.BIRCH)).c(2.0F).b(5.0F).a(f).c("birchFenceGate")); + a(185, "jungle_fence_gate", (new BlockFenceGate(BlockWood.EnumLogVariant.JUNGLE)).c(2.0F).b(5.0F).a(f).c("jungleFenceGate")); + a(186, "dark_oak_fence_gate", (new BlockFenceGate(BlockWood.EnumLogVariant.DARK_OAK)).c(2.0F).b(5.0F).a(f).c("darkOakFenceGate")); + a(187, "acacia_fence_gate", (new BlockFenceGate(BlockWood.EnumLogVariant.ACACIA)).c(2.0F).b(5.0F).a(f).c("acaciaFenceGate")); + a(188, "spruce_fence", (new BlockFence(Material.WOOD, BlockWood.EnumLogVariant.SPRUCE.c())).c(2.0F).b(5.0F).a(f).c("spruceFence")); + a(189, "birch_fence", (new BlockFence(Material.WOOD, BlockWood.EnumLogVariant.BIRCH.c())).c(2.0F).b(5.0F).a(f).c("birchFence")); + a(190, "jungle_fence", (new BlockFence(Material.WOOD, BlockWood.EnumLogVariant.JUNGLE.c())).c(2.0F).b(5.0F).a(f).c("jungleFence")); + a(191, "dark_oak_fence", (new BlockFence(Material.WOOD, BlockWood.EnumLogVariant.DARK_OAK.c())).c(2.0F).b(5.0F).a(f).c("darkOakFence")); + a(192, "acacia_fence", (new BlockFence(Material.WOOD, BlockWood.EnumLogVariant.ACACIA.c())).c(2.0F).b(5.0F).a(f).c("acaciaFence")); + a(193, "spruce_door", (new BlockDoor(Material.WOOD)).c(3.0F).a(f).c("doorSpruce").K()); + a(194, "birch_door", (new BlockDoor(Material.WOOD)).c(3.0F).a(f).c("doorBirch").K()); + a(195, "jungle_door", (new BlockDoor(Material.WOOD)).c(3.0F).a(f).c("doorJungle").K()); + a(196, "acacia_door", (new BlockDoor(Material.WOOD)).c(3.0F).a(f).c("doorAcacia").K()); + a(197, "dark_oak_door", (new BlockDoor(Material.WOOD)).c(3.0F).a(f).c("doorDarkOak").K()); + REGISTRY.a(); + Iterator iterator = REGISTRY.iterator(); + while (iterator.hasNext()) { + Block block13 = iterator.next(); + if (block13.material == Material.AIR) { + block13.v = false; + continue; + } + block13.v = block13 instanceof BlockStairs || block13 instanceof BlockStepAbstract || block13 == block6 || block13.t || block13.s == 0; + } + iterator = REGISTRY.iterator(); + while (iterator.hasNext()) { + Block block13 = iterator.next(); + for (IBlockData iblockdata : block13.P().a()) { + d.a(iblockdata, REGISTRY.b(block13) << 4 | block13.toLegacyData(iblockdata)); + } + } + + if (AzuriteConfig.explosionDestroyer.getValue()) { + for (String key : AzuriteConfig.blockDurabilities.getValue()) { + String[] split = key.split(":"); + Block type = Block.getByName(split[0].toLowerCase()); + if (type != null) + type.explosionDurability = Utils.tryParseIntegerSafe(split[1]); + } + + for (String key : AzuriteConfig.blockResistances.getValue()) { + String[] split = key.split(":"); + Block type = Block.getByName(split[0].toLowerCase()); + if (type != null) + type.setResistance(Utils.tryParseFloatSafe(split[1])); + } + } + } + + private static void a(int i, MinecraftKey minecraftkey, Block block) { + REGISTRY.a(i, minecraftkey, block); + } + + private static void a(int i, String s, Block block) { + a(i, new MinecraftKey(s), block); + } + + public static float range(float min, float value, float max) { + if (value < min) + return min; + return Math.min(value, max); + } + + public boolean o() { + return this.r; + } + + public int p() { + return this.s; + } + + public int r() { + return this.u; + } + + public boolean s() { + return this.v; + } + + public Material getMaterial() { + return this.material; + } + + public MaterialMapColor g(IBlockData iblockdata) { + return this.K; + } + + public IBlockData fromLegacyData(int i) { + return getBlockData(); + } + + public int toLegacyData(IBlockData iblockdata) { + return 0; + } + + public IBlockData updateState(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { + return iblockdata; + } + + protected Block a(StepSound block_stepsound) { + this.stepSound = block_stepsound; + return this; + } + + protected Block e(int i) { + this.s = i; + return this; + } + + protected Block a(float f) { + this.u = (int) (15.0F * f); + return this; + } + + protected Block b(float f) { + setResistance(f * 3.0F); + return this; + } + + public void setResistance(float durability) { + this.durability = durability; + this.explosionResistance = (durability / 5.0F + 0.3F) * 0.3F; + } + + public boolean u() { + return (this.material.isSolid() && d()); + } + + public boolean isOccluding() { + return (this.material.k() && d() && !isPowerSource()); + } + + public boolean w() { + return (this.material.isSolid() && d()); + } + + public boolean d() { + return true; + } + + public boolean b(IBlockAccess iblockaccess, BlockPosition blockposition) { + return !this.material.isSolid(); + } + + public int b() { + return 3; + } + + public boolean a(World world, BlockPosition blockposition) { + return false; + } + + protected Block c(float f) { + this.strength = f; + if (this.durability < f * 5.0F) { + setResistance(f * 5.0F); + } + return this; + } + + protected Block x() { + c(-1.0F); + return this; + } + + public float g(World world, BlockPosition blockposition) { + return this.strength; + } + + protected Block a(boolean flag) { + this.z = flag; + return this; + } + + public boolean isTicking() { + return this.z; + } + + public boolean isTileEntity() { + return this.isTileEntity; + } + + protected final void a(float f, float f1, float f2, float f3, float f4, float f5) { + this.minX = f; + this.minY = f1; + this.minZ = f2; + this.maxX = f3; + this.maxY = f4; + this.maxZ = f5; + } + + public boolean b(IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection) { + return iblockaccess.getType(blockposition).getBlock().getMaterial().isBuildable(); + } + + public void a(World world, BlockPosition blockposition, IBlockData iblockdata, AxisAlignedBB axisalignedbb, List list, Entity entity) { + AxisAlignedBB axisalignedbb1 = a(world, blockposition, iblockdata); + if (axisalignedbb1 != null && axisalignedbb.b(axisalignedbb1)) + list.add(axisalignedbb1); + } + + public AxisAlignedBB a(World world, BlockPosition blockposition, IBlockData iblockdata) { + return new AxisAlignedBB((double) blockposition.getX() + this.minX, (double) blockposition.getY() + this.minY, (double) blockposition.getZ() + this.minZ, (double) blockposition.getX() + this.maxX, (double) blockposition.getY() + this.maxY, (double) blockposition.getZ() + this.maxZ); + } + + public boolean c() { + return true; + } + + public boolean a(IBlockData iblockdata, boolean flag) { + return A(); + } + + public boolean A() { + return true; + } + + // Azurite - optimized block ticking + public void optimizedTick(Chunk chunk, int x, int y, int z, IBlockData iblockdata, Random random) { + b(chunk.world, new BlockPosition(x, y, z), iblockdata, random); + } + + public void b(World world, BlockPosition blockposition, IBlockData iblockdata, Random random) { + } + + public void postBreak(World world, BlockPosition blockposition, IBlockData iblockdata) { + } + + public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) { + } + + public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block, BlockPosition source) { + doPhysics(world, blockposition, iblockdata, block); + } + + public void doChunkPhysics(World world, Chunk chunk, BlockPosition blockposition, IBlockData iblockdata, Block block, BlockPosition source) { + doPhysics(world, blockposition, iblockdata, block, source); + } + + public int a(World world) { + return 10; + } + + public void onPlace(World world, BlockPosition blockposition, IBlockData iblockdata) { + AsyncCatcher.catchOp("block onPlace"); + } + + public void remove(World world, BlockPosition blockposition, IBlockData iblockdata) { + AsyncCatcher.catchOp("block remove"); + } + + public int a(Random random) { + return 1; + } + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + return Item.getItemOf(this); + } + + public float getDamage(EntityHuman entityhuman, World world, BlockPosition blockposition) { + float f = g(world, blockposition); + return (f < 0.0F) ? 0.0F : (!entityhuman.b(this) ? (entityhuman.a(this) / f / 100.0F) : (entityhuman.a(this) / f / 30.0F)); + } + + public final void b(World world, BlockPosition blockposition, IBlockData iblockdata, int i) { + if (this == Blocks.AIR) { + return; + } + + if (this.droppedItemsCatcher == null) { + this.droppedItemsCatcher = new ArrayList<>(1); + this.dropNaturally(world, blockposition, iblockdata, 1.0F, i); + BlockDropItemsEvent dropItemsEvent = new BlockDropItemsEvent(world.getWorld().getBlockAt( + blockposition.getX(), + blockposition.getY(), + blockposition.getZ() + ), null, this.droppedItemsCatcher); + Bukkit.getPluginManager().callEvent(dropItemsEvent); + if (!dropItemsEvent.isCancelled() && dropItemsEvent.getToDrop() != null) { + for (final org.bukkit.entity.Item item : dropItemsEvent.getToDrop()) { + world.addEntity(((CraftItem) item).getHandle()); + } + } + this.droppedItemsCatcher = null; + } else { + this.dropNaturally(world, blockposition, iblockdata, 1.0F, i); + } + } + + public void dropNaturally(World world, BlockPosition blockposition, IBlockData iblockdata, float f, int i) { + int j = getDropCount(i, world.random); + for (int k = 0; k < j; k++) { + if (world.random.nextFloat() < f) { + Item item = getDropType(iblockdata, world.random, i); + if (item != null) + a(world, blockposition, new ItemStack(item, 1, getDropData(iblockdata))); + } + } + } + + public void dropNaturally(World world, int x, int y, int z, IBlockData iblockdata, float f, int i) { + int j = getDropCount(i, world.random); + for (int k = 0; k < j; k++) { + if (world.random.nextFloat() < f) { + Item item = getDropType(iblockdata, world.random, i); + if (item != null) + a(world, x, y, z, new ItemStack(item, 1, getDropData(iblockdata))); + } + } + } + + protected void dropExperience(World world, BlockPosition blockposition, int i) { + while (i > 0) { + int j = EntityExperienceOrb.getOrbValue(i); + i -= j; + world.addEntity(new EntityExperienceOrb(world, blockposition.getX() + 0.5D, blockposition.getY() + 0.5D, blockposition.getZ() + 0.5D, j)); + } + } + + public int getDropData(IBlockData iblockdata) { + return 0; + } + + public float a(Entity entity) { + return this.durability / 5.0F; + } + + public MovingObjectPosition a(World world, BlockPosition blockposition, Vec3D vec3d, Vec3D vec3d1) { + updateShape(world, blockposition); + vec3d = vec3d.add(-blockposition.getX(), -blockposition.getY(), -blockposition.getZ()); + vec3d1 = vec3d1.add(-blockposition.getX(), -blockposition.getY(), -blockposition.getZ()); + Vec3D vec3d2 = vec3d.a(vec3d1, this.minX); + Vec3D vec3d3 = vec3d.a(vec3d1, this.maxX); + Vec3D vec3d4 = vec3d.b(vec3d1, this.minY); + Vec3D vec3d5 = vec3d.b(vec3d1, this.maxY); + Vec3D vec3d6 = vec3d.c(vec3d1, this.minZ); + Vec3D vec3d7 = vec3d.c(vec3d1, this.maxZ); + if (!a(vec3d2)) + vec3d2 = null; + if (!a(vec3d3)) + vec3d3 = null; + if (!b(vec3d4)) + vec3d4 = null; + if (!b(vec3d5)) + vec3d5 = null; + if (!c(vec3d6)) + vec3d6 = null; + if (!c(vec3d7)) + vec3d7 = null; + Vec3D vec3d8 = null; + if (vec3d2 != null) + vec3d8 = vec3d2; + if (vec3d3 != null && (vec3d8 == null || vec3d.distanceSquared(vec3d3) < vec3d.distanceSquared(vec3d8))) + vec3d8 = vec3d3; + if (vec3d4 != null && (vec3d8 == null || vec3d.distanceSquared(vec3d4) < vec3d.distanceSquared(vec3d8))) + vec3d8 = vec3d4; + if (vec3d5 != null && (vec3d8 == null || vec3d.distanceSquared(vec3d5) < vec3d.distanceSquared(vec3d8))) + vec3d8 = vec3d5; + if (vec3d6 != null && (vec3d8 == null || vec3d.distanceSquared(vec3d6) < vec3d.distanceSquared(vec3d8))) + vec3d8 = vec3d6; + if (vec3d7 != null && (vec3d8 == null || vec3d.distanceSquared(vec3d7) < vec3d.distanceSquared(vec3d8))) + vec3d8 = vec3d7; + if (vec3d8 == null) + return null; + EnumDirection enumdirection = null; + if (vec3d8 == vec3d2) + enumdirection = EnumDirection.WEST; + if (vec3d8 == vec3d3) + enumdirection = EnumDirection.EAST; + if (vec3d8 == vec3d4) + enumdirection = EnumDirection.DOWN; + if (vec3d8 == vec3d5) + enumdirection = EnumDirection.UP; + if (vec3d8 == vec3d6) + enumdirection = EnumDirection.NORTH; + if (vec3d8 == vec3d7) + enumdirection = EnumDirection.SOUTH; + return new MovingObjectPosition(vec3d8.add(blockposition.getX(), blockposition.getY(), blockposition.getZ()), enumdirection, blockposition); + } + + private boolean a(Vec3D vec3d) { + return vec3d != null && (vec3d.b >= this.minY && vec3d.b <= this.maxY && vec3d.c >= this.minZ && vec3d.c <= this.maxZ); + } + + private boolean b(Vec3D vec3d) { + return vec3d != null && (vec3d.a >= this.minX && vec3d.a <= this.maxX && vec3d.c >= this.minZ && vec3d.c <= this.maxZ); + } + + private boolean c(Vec3D vec3d) { + return vec3d != null && (vec3d.a >= this.minX && vec3d.a <= this.maxX && vec3d.b >= this.minY && vec3d.b <= this.maxY); + } + + public void wasExploded(World world, BlockPosition blockposition, Explosion explosion) { + } + + public boolean canPlace(World world, BlockPosition blockposition, EnumDirection enumdirection, ItemStack itemstack) { + return canPlace(world, blockposition, enumdirection); + } + + public boolean canPlace(World world, BlockPosition blockposition, EnumDirection enumdirection) { + return canPlace(world, blockposition); + } + + public boolean canPlace(World world, BlockPosition blockposition) { + return world.getType(blockposition).getBlock().material.isReplaceable(); + } + + // Azurite - Reduce block position usage + public boolean canPlace(World world, int x, int y, int z) { + return (world.getType(x, y, z).getBlock()).material.isReplaceable(); + } + + public boolean interact(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman, EnumDirection enumdirection, float f, float f1, float f2) { + if (AzuriteConfig.explosionDestroyer.getValue() && durabilityChecker != null && blockposition.getY() > 0) { + ItemStack hand = entityhuman.inventory.getItemInHand(); + if (hand != null && hand.getItem() == durabilityChecker) { + int durability = world.getDurability(blockposition.getX(), blockposition.getY(), blockposition.getZ()); + if (durability > 0) + entityhuman.sendMessage(new ChatComponentText(CC.t(LanguageConfig.factionsDurabilityChecker.getValue().replace("%durability%", String.valueOf(durability))))); + } + } + return false; + } + + public void a(World world, BlockPosition blockposition, Entity entity) { + } + + public IBlockData getPlacedState(World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2, int i, EntityLiving entityliving) { + return fromLegacyData(i); + } + + public void attack(World world, BlockPosition blockposition, EntityHuman entityhuman) { + } + + public Vec3D a(World world, BlockPosition blockposition, Entity entity, Vec3D vec3d) { + return vec3d; + } + + public void updateShape(IBlockAccess iblockaccess, BlockPosition blockposition) { + } + + public final double B() { + return this.minX; + } + + public final double C() { + return this.maxX; + } + + public final double D() { + return this.minY; + } + + public final double E() { + return this.maxY; + } + + public final double F() { + return this.minZ; + } + + public final double G() { + return this.maxZ; + } + + public int a(IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata, EnumDirection enumdirection) { + return 0; + } + + public boolean isPowerSource() { + return false; + } + + public void a(World world, BlockPosition blockposition, IBlockData iblockdata, Entity entity) { + } + + public int b(IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata, EnumDirection enumdirection) { + return 0; + } + + public void j() { + } + + public void a(World world, EntityHuman entityhuman, BlockPosition blockposition, IBlockData iblockdata, TileEntity tileentity) { + entityhuman.b(StatisticList.MINE_BLOCK_COUNT[getId(this)]); + entityhuman.applyExhaustion(world.paperSpigotConfig.blockBreakExhaustion); + if (I() && EnchantmentManager.hasSilkTouchEnchantment(entityhuman)) { + ItemStack itemstack = i(iblockdata); + if (itemstack != null) + a(world, blockposition, itemstack); + } else { + b(world, blockposition, iblockdata, EnchantmentManager.getBonusBlockLootEnchantmentLevel(entityhuman)); + } + } + + protected boolean I() { + return (d() && !this.isTileEntity); + } + + protected ItemStack i(IBlockData iblockdata) { + int i = 0; + Item item = Item.getItemOf(this); + if (item != null && item.k()) + i = toLegacyData(iblockdata); + return new ItemStack(item, 1, i); + } + + public int getDropCount(int i, Random random) { + return a(random); + } + + public void postPlace(World world, BlockPosition blockposition, IBlockData iblockdata, EntityLiving entityliving, ItemStack itemstack) { + } + + public boolean g() { + return (!this.material.isBuildable() && !this.material.isLiquid()); + } + + public Block c(String s) { + this.name = s; + return this; + } + + public String getName() { + return LocaleI18n.get(a() + ".name"); + } + + public String a() { + return "tile." + this.name; + } + + public boolean a(World world, BlockPosition blockposition, IBlockData iblockdata, int i, int j) { + return false; + } + + public boolean J() { + return this.y; + } + + protected Block K() { + this.y = false; + return this; + } + + public int k() { + return this.material.getPushReaction(); + } + + public void fallOn(World world, BlockPosition blockposition, Entity entity, float f) { + entity.e(f, 1.0F); + } + + public void a(World world, Entity entity) { + entity.motY = 0.0D; + } + + public int getDropData(World world, BlockPosition blockposition) { + return getDropData(world.getType(blockposition)); + } + + public Block a(CreativeModeTab creativemodetab) { + return this; + } + + public void a(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman) { + } + + public void k(World world, BlockPosition blockposition) { + } + + public boolean N() { + return true; + } + + public boolean a(Explosion explosion) { + return true; + } + + public boolean b(Block block) { + return (this == block); + } + + public boolean isComplexRedstone() { + return false; + } + + public int l(World world, BlockPosition blockposition) { + return 0; + } + + protected BlockStateList getStateList() { + return new BlockStateList(this); + } + + public BlockStateList P() { + return this.blockStateList; + } + + protected final void j(IBlockData iblockdata) { + this.blockData = iblockdata; + } + + public final IBlockData getBlockData() { + return this.blockData; + } + + public String toString() { + return "Block{" + REGISTRY.c(this) + "}"; + } + + public int getExpDrop(World world, IBlockData data, int enchantmentLevel) { + return 0; + } + + public static class StepSound { + public final String a; + + public final float b; + + public final float c; + + public StepSound(String s, float f, float f1) { + this.a = s; + this.b = f; + this.c = f1; + } + + public float getVolume1() { + return this.b; + } + + public float getVolume2() { + return this.c; + } + + public String getBreakSound() { + return "dig." + this.a; + } + + public String getStepSound() { + return "step." + this.a; + } + + public String getPlaceSound() { + return getBreakSound(); + } + } + +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockActionData.java b/azurite-server/src/main/java/net/minecraft/server/BlockActionData.java new file mode 100644 index 0000000..aa7f0bc --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockActionData.java @@ -0,0 +1,46 @@ +package net.minecraft.server; + +public class BlockActionData { + + private final BlockPosition a; + private final Block b; + private final int c; + private final int d; + + public BlockActionData(BlockPosition blockposition, Block block, int i, int j) { + this.a = blockposition; + this.c = i; + this.d = j; + this.b = block; + } + + public BlockPosition a() { + return this.a; + } + + public int b() { + return this.c; + } + + public int c() { + return this.d; + } + + public Block d() { + return this.b; + } + + public boolean equals(Object object) { + if (!(object instanceof BlockActionData)) { + return false; + } else { + BlockActionData blockactiondata = (BlockActionData) object; + + return this.a.equals(blockactiondata.a) && this.c == blockactiondata.c && this.d == blockactiondata.d && this.b == blockactiondata.b; + } + } + + public String toString() { + return "TE(" + this.a + ")," + this.c + "," + this.d + "," + this.b; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockAir.java b/azurite-server/src/main/java/net/minecraft/server/BlockAir.java new file mode 100644 index 0000000..58b6eeb --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockAir.java @@ -0,0 +1,30 @@ +package net.minecraft.server; + +public class BlockAir extends Block { + + protected BlockAir() { + super(Material.AIR); + } + + public int b() { + return -1; + } + + public AxisAlignedBB a(World world, BlockPosition blockposition, IBlockData iblockdata) { + return null; + } + + public boolean c() { + return false; + } + + public boolean a(IBlockData iblockdata, boolean flag) { + return false; + } + + public void dropNaturally(World world, BlockPosition blockposition, IBlockData iblockdata, float f, int i) {} + + public boolean a(World world, BlockPosition blockposition) { + return true; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockAnvil.java b/azurite-server/src/main/java/net/minecraft/server/BlockAnvil.java new file mode 100644 index 0000000..2cdc697 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockAnvil.java @@ -0,0 +1,114 @@ +package net.minecraft.server; + +public class BlockAnvil extends BlockFalling { + + public static final BlockStateDirection FACING = BlockStateDirection.of("facing", EnumDirection.EnumDirectionLimit.HORIZONTAL); + public static final BlockStateInteger DAMAGE = BlockStateInteger.of("damage", 0, 2); + + protected BlockAnvil() { + super(Material.HEAVY); + this.j(this.blockStateList.getBlockData().set(BlockAnvil.FACING, EnumDirection.NORTH).set(BlockAnvil.DAMAGE, 0)); + this.e(0); + this.a(CreativeModeTab.c); + } + + public boolean d() { + return false; + } + + public boolean c() { + return false; + } + + public IBlockData getPlacedState(World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2, int i, EntityLiving entityliving) { + EnumDirection enumdirection1 = entityliving.getDirection().e(); + + return super.getPlacedState(world, blockposition, enumdirection, f, f1, f2, i, entityliving).set(BlockAnvil.FACING, enumdirection1).set(BlockAnvil.DAMAGE, i >> 2); + } + + public boolean interact(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman, EnumDirection enumdirection, float f, float f1, float f2) { + entityhuman.openTileEntity(new BlockAnvil.TileEntityContainerAnvil(world, blockposition)); + return true; + } + + public int getDropData(IBlockData iblockdata) { + return iblockdata.get(BlockAnvil.DAMAGE); + } + + public void updateShape(IBlockAccess iblockaccess, BlockPosition blockposition) { + EnumDirection enumdirection = iblockaccess.getType(blockposition).get(BlockAnvil.FACING); + + if (enumdirection.k() == EnumDirection.EnumAxis.X) { + this.a(0.0F, 0.0F, 0.125F, 1.0F, 1.0F, 0.875F); + } else { + this.a(0.125F, 0.0F, 0.0F, 0.875F, 1.0F, 1.0F); + } + } + + protected void a(EntityFallingBlock entityfallingblock) { + entityfallingblock.a(true); + } + + public void a_(World world, BlockPosition blockposition) { + world.triggerEffect(1022, blockposition, 0); + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockAnvil.FACING, EnumDirection.fromType2(i & 3)).set(BlockAnvil.DAMAGE, (i & 15) >> 2); + } + + public int toLegacyData(IBlockData iblockdata) { + byte b0 = 0; + int i = b0 | iblockdata.get(BlockAnvil.FACING).b(); + + i |= iblockdata.get(BlockAnvil.DAMAGE) << 2; + return i; + } + + // Azurite - hardcode shape of anvil to prevent false phase collisions (does not fix all of them since minceraft is fundamentally broken and lets you phase through anvils / chests!) + @Override + public AxisAlignedBB a(World world, BlockPosition blockposition, IBlockData iblockdata) { + EnumDirection facing = iblockdata.get(BlockAnvil.FACING); + + if (facing == EnumDirection.EAST || facing == EnumDirection.WEST) { + return new AxisAlignedBB(blockposition.getX(), blockposition.getY(), blockposition.getZ() + 0.125F, blockposition.getX() + 1.0F, blockposition.getY() + 1.0F, blockposition.getZ() + 0.875F); + } else { + return new AxisAlignedBB(blockposition.getX() + 0.125F, blockposition.getY(), blockposition.getZ(), blockposition.getX() + 0.857F, blockposition.getY() + 1.0F, blockposition.getZ() + 1.0F); + } + } + + public BlockStateList getStateList() { + return new BlockStateList(this, BlockAnvil.FACING, BlockAnvil.DAMAGE); + } + + public static class TileEntityContainerAnvil implements ITileEntityContainer { + + private final World a; + private final BlockPosition b; + + public TileEntityContainerAnvil(World world, BlockPosition blockposition) { + this.a = world; + this.b = blockposition; + } + + public String getName() { + return "anvil"; + } + + public boolean hasCustomName() { + return false; + } + + public IChatBaseComponent getScoreboardDisplayName() { + return new ChatMessage(Blocks.ANVIL.a() + ".name"); + } + + public Container createContainer(PlayerInventory playerinventory, EntityHuman entityhuman) { + return new ContainerAnvil(playerinventory, this.a, this.b, entityhuman); + } + + public String getContainerName() { + return "minecraft:anvil"; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockBanner.java b/azurite-server/src/main/java/net/minecraft/server/BlockBanner.java new file mode 100644 index 0000000..f2adde6 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockBanner.java @@ -0,0 +1,209 @@ +package net.minecraft.server; + +import java.util.Random; + +public class BlockBanner extends BlockContainer { + + public static final BlockStateDirection FACING = BlockStateDirection.of("facing", EnumDirection.EnumDirectionLimit.HORIZONTAL); + public static final BlockStateInteger ROTATION = BlockStateInteger.of("rotation", 0, 15); + + protected BlockBanner() { + super(Material.WOOD); + float f = 0.25F; + float f1 = 1.0F; + + this.a(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, f1, 0.5F + f); + } + + public String getName() { + return LocaleI18n.get("item.banner.white.name"); + } + + public AxisAlignedBB a(World world, BlockPosition blockposition, IBlockData iblockdata) { + return null; + } + + public boolean d() { + return false; + } + + public boolean b(IBlockAccess iblockaccess, BlockPosition blockposition) { + return true; + } + + public boolean c() { + return false; + } + + public boolean g() { + return true; + } + + public TileEntity a(World world, int i) { + return new TileEntityBanner(); + } + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + return Items.BANNER; + } + + public void dropNaturally(World world, BlockPosition blockposition, IBlockData iblockdata, float f, int i) { + TileEntity tileentity = world.getTileEntity(blockposition); + + if (tileentity instanceof TileEntityBanner) { + ItemStack itemstack = new ItemStack(Items.BANNER, 1, ((TileEntityBanner) tileentity).b()); + NBTTagCompound nbttagcompound = new NBTTagCompound(); + + tileentity.b(nbttagcompound); + nbttagcompound.remove("x"); + nbttagcompound.remove("y"); + nbttagcompound.remove("z"); + nbttagcompound.remove("id"); + itemstack.a("BlockEntityTag", nbttagcompound); + a(world, blockposition, itemstack); + } else { + super.dropNaturally(world, blockposition, iblockdata, f, i); + } + + } + + public boolean canPlace(World world, BlockPosition blockposition) { + return !this.e(world, blockposition) && super.canPlace(world, blockposition); + } + + public void a(World world, EntityHuman entityhuman, BlockPosition blockposition, IBlockData iblockdata, TileEntity tileentity) { + if (tileentity instanceof TileEntityBanner) { + TileEntityBanner tileentitybanner = (TileEntityBanner) tileentity; + ItemStack itemstack = new ItemStack(Items.BANNER, 1, ((TileEntityBanner) tileentity).b()); + NBTTagCompound nbttagcompound = new NBTTagCompound(); + + TileEntityBanner.a(nbttagcompound, tileentitybanner.b(), tileentitybanner.d()); + itemstack.a("BlockEntityTag", nbttagcompound); + a(world, blockposition, itemstack); + } else { + super.a(world, entityhuman, blockposition, iblockdata, null); + } + + } + + static class SyntheticClass_1 { + + static final int[] a = new int[EnumDirection.values().length]; + + static { + try { + BlockBanner.SyntheticClass_1.a[EnumDirection.NORTH.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockBanner.SyntheticClass_1.a[EnumDirection.SOUTH.ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockBanner.SyntheticClass_1.a[EnumDirection.WEST.ordinal()] = 3; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockBanner.SyntheticClass_1.a[EnumDirection.EAST.ordinal()] = 4; + } catch (NoSuchFieldError ignored) { + } + + } + } + + public static class BlockStandingBanner extends BlockBanner { + + public BlockStandingBanner() { + this.j(this.blockStateList.getBlockData().set(BlockBanner.BlockStandingBanner.ROTATION, 0)); + } + + public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) { + if (!world.getType(blockposition.down()).getBlock().getMaterial().isBuildable()) { + this.b(world, blockposition, iblockdata, 0); + world.setAir(blockposition); + } + + super.doPhysics(world, blockposition, iblockdata, block); + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockBanner.BlockStandingBanner.ROTATION, i); + } + + public int toLegacyData(IBlockData iblockdata) { + return iblockdata.get(BlockStandingBanner.ROTATION); + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, BlockStandingBanner.ROTATION); + } + } + + public static class BlockWallBanner extends BlockBanner { + + public BlockWallBanner() { + this.j(this.blockStateList.getBlockData().set(BlockBanner.BlockWallBanner.FACING, EnumDirection.NORTH)); + } + + public void updateShape(IBlockAccess iblockaccess, BlockPosition blockposition) { + EnumDirection enumdirection = iblockaccess.getType(blockposition).get(BlockWallBanner.FACING); + float f = 0.0F; + float f1 = 0.78125F; + float f2 = 0.0F; + float f3 = 1.0F; + float f4 = 0.125F; + + this.a(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + switch (BlockBanner.SyntheticClass_1.a[enumdirection.ordinal()]) { + case 1: + default: + this.a(f2, f, 1.0F - f4, f3, f1, 1.0F); + break; + + case 2: + this.a(f2, f, 0.0F, f3, f1, f4); + break; + + case 3: + this.a(1.0F - f4, f, f2, 1.0F, f1, f3); + break; + + case 4: + this.a(0.0F, f, f2, f4, f1, f3); + } + + } + + public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) { + EnumDirection enumdirection = iblockdata.get(BlockWallBanner.FACING); + + if (!world.getType(blockposition.shift(enumdirection.opposite())).getBlock().getMaterial().isBuildable()) { + this.b(world, blockposition, iblockdata, 0); + world.setAir(blockposition); + } + + super.doPhysics(world, blockposition, iblockdata, block); + } + + public IBlockData fromLegacyData(int i) { + EnumDirection enumdirection = EnumDirection.fromType1(i); + + if (enumdirection.k() == EnumDirection.EnumAxis.Y) { + enumdirection = EnumDirection.NORTH; + } + + return this.getBlockData().set(BlockBanner.BlockWallBanner.FACING, enumdirection); + } + + public int toLegacyData(IBlockData iblockdata) { + return iblockdata.get(BlockWallBanner.FACING).a(); + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, BlockWallBanner.FACING); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockBarrier.java b/azurite-server/src/main/java/net/minecraft/server/BlockBarrier.java new file mode 100644 index 0000000..6571694 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockBarrier.java @@ -0,0 +1,22 @@ +package net.minecraft.server; + +public class BlockBarrier extends Block { + + protected BlockBarrier() { + super(Material.BANNER); + this.x(); + this.b(6000001.0F); + this.K(); + this.t = true; + } + + public int b() { + return -1; + } + + public boolean c() { + return false; + } + + public void dropNaturally(World world, BlockPosition blockposition, IBlockData iblockdata, float f, int i) {} +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockBeacon.java b/azurite-server/src/main/java/net/minecraft/server/BlockBeacon.java new file mode 100644 index 0000000..9693f1f --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockBeacon.java @@ -0,0 +1,86 @@ +package net.minecraft.server; + +public class BlockBeacon extends BlockContainer { + + public BlockBeacon() { + super(Material.SHATTERABLE, MaterialMapColor.G); + this.c(3.0F); + this.a(CreativeModeTab.f); + } + + // Vortex - do this on main thread + public static void f(final World world, final BlockPosition blockposition) { + Chunk chunk = world.getChunkAtWorldCoords(blockposition); + BlockPosition.MutableBlockPosition mutableBlockPosition = new BlockPosition.MutableBlockPosition() + .setValues(blockposition.getX(), blockposition.getY(), blockposition.getZ()); // Azurite + + for (int i = blockposition.getY() - 1; i >= 0; --i) { + mutableBlockPosition.setY(i); + + if (!chunk.d(mutableBlockPosition)) { + break; + } + + IBlockData iblockdata = world.getType(mutableBlockPosition); + + if (iblockdata.getBlock() == Blocks.BEACON) { + TileEntity tileentity = world.getTileEntity(blockposition); + + if (tileentity instanceof TileEntityBeacon) { + ((TileEntityBeacon) tileentity).m(); + world.playBlockAction(blockposition, Blocks.BEACON, 1, 0); + } + } + } + } + + public TileEntity a(World world, int i) { + return new TileEntityBeacon(); + } + + public boolean interact(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman + entityhuman, EnumDirection enumdirection, float f, float f1, float f2) { + TileEntity tileentity = world.getTileEntity(blockposition); + + if (tileentity instanceof TileEntityBeacon) { + entityhuman.openContainer((TileEntityBeacon) tileentity); + } + + return true; + } + + public boolean c() { + return false; + } + + public boolean d() { + return false; + } + + public int b() { + return 3; + } + + public void postPlace(World world, BlockPosition blockposition, IBlockData iblockdata, EntityLiving + entityliving, ItemStack itemstack) { + super.postPlace(world, blockposition, iblockdata, entityliving, itemstack); + if (itemstack.hasName()) { + TileEntity tileentity = world.getTileEntity(blockposition); + + if (tileentity instanceof TileEntityBeacon) { + ((TileEntityBeacon) tileentity).a(itemstack.getName()); + } + } + + } + + public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) { + TileEntity tileentity = world.getTileEntity(blockposition); + + if (tileentity instanceof TileEntityBeacon) { + ((TileEntityBeacon) tileentity).m(); + world.playBlockAction(blockposition, this, 1, 0); + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockBed.java b/azurite-server/src/main/java/net/minecraft/server/BlockBed.java new file mode 100644 index 0000000..567b7ac --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockBed.java @@ -0,0 +1,228 @@ +package net.minecraft.server; + +import java.util.Iterator; +import java.util.Random; + +public class BlockBed extends BlockDirectional { + + public static final BlockStateEnum PART = BlockStateEnum.of("part", BlockBed.EnumBedPart.class); + public static final BlockStateBoolean OCCUPIED = BlockStateBoolean.of("occupied"); + + public BlockBed() { + super(Material.CLOTH); + this.j(this.blockStateList.getBlockData().set(BlockBed.PART, BlockBed.EnumBedPart.FOOT).set(BlockBed.OCCUPIED, Boolean.FALSE)); + this.l(); + } + + public static BlockPosition a(World world, BlockPosition blockposition, int i) { + EnumDirection enumdirection = world.getType(blockposition).get(BlockBed.FACING); + int j = blockposition.getX(); + int k = blockposition.getY(); + int l = blockposition.getZ(); + + for (int i1 = 0; i1 <= 1; ++i1) { + int j1 = j - enumdirection.getAdjacentX() * i1 - 1; + int k1 = l - enumdirection.getAdjacentZ() * i1 - 1; + int l1 = j1 + 2; + int i2 = k1 + 2; + + for (int j2 = j1; j2 <= l1; ++j2) { + for (int k2 = k1; k2 <= i2; ++k2) { + if (e(world, j2, k, k2)) { + + if (i <= 0) { + return new BlockPosition(j2, k, k2); + } + + --i; + } + } + } + } + + return null; + } + + protected static boolean e(World world, int x, int y, int z) { + return World.a(world, x, y - 1, z) && !world.getType(x, y, z).getBlock().getMaterial().isBuildable() && !world.getType(x, y + 1, z).getBlock().getMaterial().isBuildable(); + } + + protected static boolean e(World world, BlockPosition blockposition) { + return e(world, blockposition.getX(), blockposition.getY(), blockposition.getZ()); + } + + public boolean interact(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman, EnumDirection enumdirection, float f, float f1, float f2) { + if (iblockdata.get(BlockBed.PART) != BlockBed.EnumBedPart.HEAD) { + blockposition = blockposition.shift(iblockdata.get(BlockBed.FACING)); + iblockdata = world.getType(blockposition); + if (iblockdata.getBlock() != this) { + return true; + } + } + + if (world.worldProvider.e() && world.getBiome(blockposition) != BiomeBase.HELL) { + if (iblockdata.get(BlockBed.OCCUPIED)) { + EntityHuman entityhuman1 = this.f(world, blockposition); + + if (entityhuman1 != null) { + entityhuman.b(new ChatMessage("tile.bed.occupied")); + return true; + } + + iblockdata = iblockdata.set(BlockBed.OCCUPIED, Boolean.FALSE); + world.setTypeAndData(blockposition, iblockdata, 4); + } + + EntityHuman.EnumBedResult entityhuman_enumbedresult = entityhuman.a(blockposition); + + if (entityhuman_enumbedresult == EntityHuman.EnumBedResult.OK) { + iblockdata = iblockdata.set(BlockBed.OCCUPIED, Boolean.TRUE); + world.setTypeAndData(blockposition, iblockdata, 4); + } else { + if (entityhuman_enumbedresult == EntityHuman.EnumBedResult.NOT_POSSIBLE_NOW) { + entityhuman.b(new ChatMessage("tile.bed.noSleep")); + } else if (entityhuman_enumbedresult == EntityHuman.EnumBedResult.NOT_SAFE) { + entityhuman.b(new ChatMessage("tile.bed.notSafe")); + } + + } + } else { + world.setAir(blockposition); + BlockPosition blockposition1 = blockposition.shift(iblockdata.get(BlockBed.FACING).opposite()); + + if (world.getType(blockposition1).getBlock() == this) { + world.setAir(blockposition1); + } + + world.createExplosion(null, (double) blockposition.getX() + 0.5D, (double) blockposition.getY() + 0.5D, (double) blockposition.getZ() + 0.5D, 5.0F, true, true); + } + return true; + } + + private EntityHuman f(World world, BlockPosition blockposition) { + Iterator iterator = world.players.iterator(); + + EntityHuman entityhuman; + + do { + if (!iterator.hasNext()) { + return null; + } + + entityhuman = iterator.next(); + } while (!entityhuman.isSleeping() || !entityhuman.bx.equals(blockposition)); + + return entityhuman; + } + + public boolean d() { + return false; + } + + public boolean c() { + return false; + } + + public void updateShape(IBlockAccess iblockaccess, BlockPosition blockposition) { + this.l(); + } + + public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) { + EnumDirection enumdirection = iblockdata.get(BlockBed.FACING); + + if (iblockdata.get(BlockBed.PART) == BlockBed.EnumBedPart.HEAD) { + if (world.getType(blockposition.shift(enumdirection.opposite())).getBlock() != this) { + world.setAir(blockposition); + } + } else if (world.getType(blockposition.shift(enumdirection)).getBlock() != this) { + world.setAir(blockposition); + this.b(world, blockposition, iblockdata, 0); + } + + } + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + return iblockdata.get(BlockBed.PART) == BlockBed.EnumBedPart.HEAD ? null : Items.BED; + } + + private void l() { + this.a(0.0F, 0.0F, 0.0F, 1.0F, 0.5625F, 1.0F); + } + + public void dropNaturally(World world, BlockPosition blockposition, IBlockData iblockdata, float f, int i) { + if (iblockdata.get(BlockBed.PART) == BlockBed.EnumBedPart.FOOT) { + super.dropNaturally(world, blockposition, iblockdata, f, 0); + } + + } + + public int k() { + return 1; + } + + public void a(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman) { + if (entityhuman.abilities.canInstantlyBuild && iblockdata.get(BlockBed.PART) == BlockBed.EnumBedPart.HEAD) { + BlockPosition blockposition1 = blockposition.shift(iblockdata.get(BlockBed.FACING).opposite()); + + if (world.getType(blockposition1).getBlock() == this) { + world.setAir(blockposition1); + } + } + + } + + public IBlockData fromLegacyData(int i) { + EnumDirection enumdirection = EnumDirection.fromType2(i); + + return (i & 8) > 0 ? this.getBlockData().set(BlockBed.PART, BlockBed.EnumBedPart.HEAD).set(BlockBed.FACING, enumdirection).set(BlockBed.OCCUPIED, (i & 4) > 0) : this.getBlockData().set(BlockBed.PART, BlockBed.EnumBedPart.FOOT).set(BlockBed.FACING, enumdirection); + } + + public IBlockData updateState(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { + if (iblockdata.get(BlockBed.PART) == BlockBed.EnumBedPart.FOOT) { + IBlockData iblockdata1 = iblockaccess.getType(blockposition.shift(iblockdata.get(BlockBed.FACING))); + + if (iblockdata1.getBlock() == this) { + iblockdata = iblockdata.set(BlockBed.OCCUPIED, iblockdata1.get(BlockBed.OCCUPIED)); + } + } + + return iblockdata; + } + + public int toLegacyData(IBlockData iblockdata) { + byte b0 = 0; + int i = b0 | iblockdata.get(BlockBed.FACING).b(); + + if (iblockdata.get(BlockBed.PART) == BlockBed.EnumBedPart.HEAD) { + i |= 8; + if (iblockdata.get(BlockBed.OCCUPIED)) { + i |= 4; + } + } + + return i; + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, BlockBed.FACING, BlockBed.PART, BlockBed.OCCUPIED); + } + + public enum EnumBedPart implements INamable { + + HEAD("head"), FOOT("foot"); + + private final String c; + + EnumBedPart(String s) { + this.c = s; + } + + public String toString() { + return this.c; + } + + public String getName() { + return this.c; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockBloodStone.java b/azurite-server/src/main/java/net/minecraft/server/BlockBloodStone.java new file mode 100644 index 0000000..0158497 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockBloodStone.java @@ -0,0 +1,28 @@ +package net.minecraft.server; + +import org.bukkit.event.block.BlockRedstoneEvent; // CraftBukkit + +public class BlockBloodStone extends Block { + + public BlockBloodStone() { + super(Material.STONE); + this.a(CreativeModeTab.b); + } + + public MaterialMapColor g(IBlockData iblockdata) { + return MaterialMapColor.K; + } + + // CraftBukkit start + //@Override // PaperSpigot - Remove completely invalid Redstone event for Netherrack + public void doPhysics_nvmplsdont(World world, BlockPosition position, IBlockData iblockdata, Block block) { + if (block != null && block.isPowerSource()) { + org.bukkit.block.Block bl = world.getWorld().getBlockAt(position.getX(), position.getY(), position.getZ()); + int power = bl.getBlockPower(); + + BlockRedstoneEvent event = new BlockRedstoneEvent(bl, power, power); + world.getServer().getPluginManager().callEvent(event); + } + } + // CraftBukkit end +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockBookshelf.java b/azurite-server/src/main/java/net/minecraft/server/BlockBookshelf.java new file mode 100644 index 0000000..37f43e9 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockBookshelf.java @@ -0,0 +1,19 @@ +package net.minecraft.server; + +import java.util.Random; + +public class BlockBookshelf extends Block { + + public BlockBookshelf() { + super(Material.WOOD); + this.a(CreativeModeTab.b); + } + + public int a(Random random) { + return 3; + } + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + return Items.BOOK; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockBrewingStand.java b/azurite-server/src/main/java/net/minecraft/server/BlockBrewingStand.java new file mode 100644 index 0000000..9e899e5 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockBrewingStand.java @@ -0,0 +1,115 @@ +package net.minecraft.server; + +import java.util.List; +import java.util.Random; + +public class BlockBrewingStand extends BlockContainer { + + public static final BlockStateBoolean[] HAS_BOTTLE = new BlockStateBoolean[] { BlockStateBoolean.of("has_bottle_0"), BlockStateBoolean.of("has_bottle_1"), BlockStateBoolean.of("has_bottle_2")}; + + public BlockBrewingStand() { + super(Material.ORE); + this.j(this.blockStateList.getBlockData().set(BlockBrewingStand.HAS_BOTTLE[0], false).set(BlockBrewingStand.HAS_BOTTLE[1], Boolean.FALSE).set(BlockBrewingStand.HAS_BOTTLE[2], false)); + } + + public String getName() { + return LocaleI18n.get("item.brewingStand.name"); + } + + public boolean c() { + return false; + } + + public int b() { + return 3; + } + + public TileEntity a(World world, int i) { + return new TileEntityBrewingStand(); + } + + public boolean d() { + return false; + } + + public void a(World world, BlockPosition blockposition, IBlockData iblockdata, AxisAlignedBB axisalignedbb, List list, Entity entity) { + this.a(0.4375F, 0.0F, 0.4375F, 0.5625F, 0.875F, 0.5625F); + super.a(world, blockposition, iblockdata, axisalignedbb, list, entity); + this.j(); + super.a(world, blockposition, iblockdata, axisalignedbb, list, entity); + } + + public void j() { + this.a(0.0F, 0.0F, 0.0F, 1.0F, 0.125F, 1.0F); + } + + public boolean interact(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman, EnumDirection enumdirection, float f, float f1, float f2) { + TileEntity tileentity = world.getTileEntity(blockposition); + + if (tileentity instanceof TileEntityBrewingStand) { + entityhuman.openContainer((TileEntityBrewingStand) tileentity); + entityhuman.b(StatisticList.M); + } + + return true; + } + + public void postPlace(World world, BlockPosition blockposition, IBlockData iblockdata, EntityLiving entityliving, ItemStack itemstack) { + if (itemstack.hasName()) { + TileEntity tileentity = world.getTileEntity(blockposition); + + if (tileentity instanceof TileEntityBrewingStand) { + ((TileEntityBrewingStand) tileentity).a(itemstack.getName()); + } + } + + } + + public void remove(World world, BlockPosition blockposition, IBlockData iblockdata) { + TileEntity tileentity = world.getTileEntity(blockposition); + + if (tileentity instanceof TileEntityBrewingStand) { + InventoryUtils.dropInventory(world, blockposition, (TileEntityBrewingStand) tileentity); + } + + super.remove(world, blockposition, iblockdata); + } + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + return Items.BREWING_STAND; + } + + public boolean isComplexRedstone() { + return true; + } + + public int l(World world, BlockPosition blockposition) { + return Container.a(world.getTileEntity(blockposition)); + } + + public IBlockData fromLegacyData(int i) { + IBlockData iblockdata = this.getBlockData(); + + for (int j = 0; j < 3; ++j) { + iblockdata = iblockdata.set(BlockBrewingStand.HAS_BOTTLE[j], (i & 1 << j) > 0); + } + + return iblockdata; + } + + public int toLegacyData(IBlockData iblockdata) { + int i = 0; + + for (int j = 0; j < 3; ++j) { + if (iblockdata.get(BlockBrewingStand.HAS_BOTTLE[j])) { + i |= 1 << j; + } + } + + return i; + } + + public BlockStateList getStateList() { + return new BlockStateList(this, BlockBrewingStand.HAS_BOTTLE[0], BlockBrewingStand.HAS_BOTTLE[1], BlockBrewingStand.HAS_BOTTLE[2]); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockButtonAbstract.java b/azurite-server/src/main/java/net/minecraft/server/BlockButtonAbstract.java new file mode 100644 index 0000000..744c6f7 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockButtonAbstract.java @@ -0,0 +1,385 @@ +package net.minecraft.server; + +import org.bukkit.event.block.BlockRedstoneEvent; +import org.bukkit.event.entity.EntityInteractEvent; + +import java.util.List; +import java.util.Random; +// CraftBukkit end + +public abstract class BlockButtonAbstract extends Block { + + public static final BlockStateDirection FACING = BlockStateDirection.of("facing"); + public static final BlockStateBoolean POWERED = BlockStateBoolean.of("powered"); + private final boolean N; + + protected BlockButtonAbstract(boolean flag) { + super(Material.ORIENTABLE); + this.j(this.blockStateList.getBlockData().set(BlockButtonAbstract.FACING, EnumDirection.NORTH).set(BlockButtonAbstract.POWERED, Boolean.FALSE)); + this.a(true); + this.a(CreativeModeTab.d); + this.N = flag; + } + + protected static boolean a(World world, BlockPosition blockposition, EnumDirection enumdirection) { + BlockPosition blockposition1 = blockposition.shift(enumdirection); + + return enumdirection == EnumDirection.DOWN ? World.a(world, blockposition1) : world.getType(blockposition1).getBlock().isOccluding(); + } + + public AxisAlignedBB a(World world, BlockPosition blockposition, IBlockData iblockdata) { + return null; + } + + public int a(World world) { + return this.N ? 30 : 20; + } + + public boolean c() { + return false; + } + + public boolean d() { + return false; + } + + public boolean canPlace(World world, BlockPosition blockposition, EnumDirection enumdirection) { + return a(world, blockposition, enumdirection.opposite()); + } + + public boolean canPlace(World world, BlockPosition blockposition) { + for (EnumDirection enumdirection : EnumDirection.values()) { + if (a(world, blockposition, enumdirection)) { + return true; + } + } + + return false; + } + + public IBlockData getPlacedState(World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2, int i, EntityLiving entityliving) { + return a(world, blockposition, enumdirection.opposite()) ? this.getBlockData().set(BlockButtonAbstract.FACING, enumdirection).set(BlockButtonAbstract.POWERED, Boolean.FALSE) : this.getBlockData().set(BlockButtonAbstract.FACING, EnumDirection.DOWN).set(BlockButtonAbstract.POWERED, Boolean.FALSE); + } + + public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) { + if (this.e(world, blockposition, iblockdata) && !a(world, blockposition, iblockdata.get(BlockButtonAbstract.FACING).opposite())) { + this.b(world, blockposition, iblockdata, 0); + world.setAir(blockposition); + } + + } + + private boolean e(World world, BlockPosition blockposition, IBlockData iblockdata) { + if (this.canPlace(world, blockposition)) { + return true; + } else { + this.b(world, blockposition, iblockdata, 0); + world.setAir(blockposition); + return false; + } + } + + public void updateShape(IBlockAccess iblockaccess, BlockPosition blockposition) { + this.d(iblockaccess.getType(blockposition)); + } + + private void d(IBlockData iblockdata) { + EnumDirection enumdirection = iblockdata.get(BlockButtonAbstract.FACING); + boolean flag = iblockdata.get(BlockButtonAbstract.POWERED); + + float f2 = (float) (flag ? 1 : 2) / 16.0F; + + switch (BlockButtonAbstract.SyntheticClass_1.a[enumdirection.ordinal()]) { + case 1: + this.a(0.0F, 0.375F, 0.3125F, f2, 0.625F, 0.6875F); + break; + + case 2: + this.a(1.0F - f2, 0.375F, 0.3125F, 1.0F, 0.625F, 0.6875F); + break; + + case 3: + this.a(0.3125F, 0.375F, 0.0F, 0.6875F, 0.625F, f2); + break; + + case 4: + this.a(0.3125F, 0.375F, 1.0F - f2, 0.6875F, 0.625F, 1.0F); + break; + + case 5: + this.a(0.3125F, 0.0F, 0.375F, 0.6875F, 0.0F + f2, 0.625F); + break; + + case 6: + this.a(0.3125F, 1.0F - f2, 0.375F, 0.6875F, 1.0F, 0.625F); + } + + } + + public boolean interact(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman, EnumDirection enumdirection, float f, float f1, float f2) { + if (!iblockdata.get(BlockButtonAbstract.POWERED)) { + // CraftBukkit start + boolean powered = iblockdata.get(POWERED); + org.bukkit.block.Block block = world.getWorld().getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()); + int old = (powered) ? 15 : 0; + int current = (!powered) ? 15 : 0; + + BlockRedstoneEvent eventRedstone = new BlockRedstoneEvent(block, old, current); + world.getServer().getPluginManager().callEvent(eventRedstone); + + if ((eventRedstone.getNewCurrent() > 0) == (powered)) { + return true; + } + // CraftBukkit end + world.setTypeAndData(blockposition, iblockdata.set(BlockButtonAbstract.POWERED, true), 3); + world.b(blockposition, blockposition); + world.makeSound((double) blockposition.getX() + 0.5D, (double) blockposition.getY() + 0.5D, (double) blockposition.getZ() + 0.5D, "random.click", 0.3F, 0.6F); + this.c(world, blockposition, iblockdata.get(BlockButtonAbstract.FACING)); + world.a(blockposition, this, this.a(world)); + } + return true; + } + + public void remove(World world, BlockPosition blockposition, IBlockData iblockdata) { + if (iblockdata.get(BlockButtonAbstract.POWERED)) { + this.c(world, blockposition, iblockdata.get(BlockButtonAbstract.FACING)); + } + + super.remove(world, blockposition, iblockdata); + } + + public int a(IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata, EnumDirection enumdirection) { + return iblockdata.get(BlockButtonAbstract.POWERED) ? 15 : 0; + } + + public int b(IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata, EnumDirection enumdirection) { + return !iblockdata.get(BlockButtonAbstract.POWERED) ? 0 : (iblockdata.get(BlockButtonAbstract.FACING) == enumdirection ? 15 : 0); + } + + public boolean isPowerSource() { + return true; + } + + public void b(World world, BlockPosition blockposition, IBlockData iblockdata, Random random) { + if (iblockdata.get(BlockButtonAbstract.POWERED)) { + if (this.N) { + this.f(world, blockposition, iblockdata); + } else { + // CraftBukkit start + org.bukkit.block.Block block = world.getWorld().getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()); + + BlockRedstoneEvent eventRedstone = new BlockRedstoneEvent(block, 15, 0); + world.getServer().getPluginManager().callEvent(eventRedstone); + + if (eventRedstone.getNewCurrent() > 0) { + return; + } + // CraftBukkit end + world.setTypeUpdate(blockposition, iblockdata.set(BlockButtonAbstract.POWERED, false)); + this.c(world, blockposition, iblockdata.get(BlockButtonAbstract.FACING)); + world.makeSound((double) blockposition.getX() + 0.5D, (double) blockposition.getY() + 0.5D, (double) blockposition.getZ() + 0.5D, "random.click", 0.3F, 0.5F); + world.b(blockposition, blockposition); + } + + } + } + + public void j() { + float f = 0.1875F; + float f1 = 0.125F; + float f2 = 0.125F; + + this.a(0.5F - f, 0.5F - f1, 0.5F - f2, 0.5F + f, 0.5F + f1, 0.5F + f2); + } + + public void a(World world, BlockPosition blockposition, IBlockData iblockdata, Entity entity) { + if (this.N) { + if (!iblockdata.get(BlockButtonAbstract.POWERED)) { + this.f(world, blockposition, iblockdata); + } + } + } + + private void f(World world, BlockPosition blockposition, IBlockData iblockdata) { + this.d(iblockdata); + List list = world.a(EntityArrow.class, new AxisAlignedBB((double) blockposition.getX() + this.minX, (double) blockposition.getY() + this.minY, (double) blockposition.getZ() + this.minZ, (double) blockposition.getX() + this.maxX, (double) blockposition.getY() + this.maxY, (double) blockposition.getZ() + this.maxZ)); + boolean flag = !list.isEmpty(); + boolean flag1 = iblockdata.get(BlockButtonAbstract.POWERED); + + // CraftBukkit start - Call interact event when arrows turn on wooden buttons + if (flag1 != flag && flag) { + org.bukkit.block.Block block = world.getWorld().getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()); + boolean allowed = false; + + // If all of the events are cancelled block the button press, else allow + for (Entity entity : list) { + EntityInteractEvent event = new EntityInteractEvent(entity.getBukkitEntity(), block); + world.getServer().getPluginManager().callEvent(event); + + if (!event.isCancelled()) { + allowed = true; + break; + } + } + + if (!allowed) { + return; + } + } + // CraftBukkit end + + if (flag && !flag1) { + // CraftBukkit start + org.bukkit.block.Block block = world.getWorld().getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()); + + BlockRedstoneEvent eventRedstone = new BlockRedstoneEvent(block, 0, 15); + world.getServer().getPluginManager().callEvent(eventRedstone); + + if (eventRedstone.getNewCurrent() <= 0) { + return; + } + // CraftBukkit end + world.setTypeUpdate(blockposition, iblockdata.set(BlockButtonAbstract.POWERED, true)); + this.c(world, blockposition, iblockdata.get(BlockButtonAbstract.FACING)); + world.b(blockposition, blockposition); + world.makeSound(blockposition.getX() + 0.5D, blockposition.getY() + 0.5D, blockposition.getZ() + 0.5D, "random.click", 0.3F, 0.6F); + } + + if (!flag && flag1) { + // CraftBukkit start + org.bukkit.block.Block block = world.getWorld().getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()); + + BlockRedstoneEvent eventRedstone = new BlockRedstoneEvent(block, 15, 0); + world.getServer().getPluginManager().callEvent(eventRedstone); + + if (eventRedstone.getNewCurrent() > 0) { + return; + } + // CraftBukkit end + world.setTypeUpdate(blockposition, iblockdata.set(BlockButtonAbstract.POWERED, false)); + this.c(world, blockposition, iblockdata.get(BlockButtonAbstract.FACING)); + world.b(blockposition, blockposition); + world.makeSound(blockposition.getX() + 0.5D, blockposition.getY() + 0.5D, blockposition.getZ() + 0.5D, "random.click", 0.3F, 0.5F); + } + + if (flag) { + world.a(blockposition, this, this.a(world)); + } + + } + + private void c(World world, BlockPosition blockposition, EnumDirection enumdirection) { + world.applyPhysics(blockposition, this); + world.applyPhysics(blockposition.shift(enumdirection.opposite()), this); + } + + public IBlockData fromLegacyData(int i) { + EnumDirection enumdirection; + + switch (i & 7) { + case 0: + enumdirection = EnumDirection.DOWN; + break; + + case 1: + enumdirection = EnumDirection.EAST; + break; + + case 2: + enumdirection = EnumDirection.WEST; + break; + + case 3: + enumdirection = EnumDirection.SOUTH; + break; + + case 4: + enumdirection = EnumDirection.NORTH; + break; + + case 5: + default: + enumdirection = EnumDirection.UP; + } + + return this.getBlockData().set(BlockButtonAbstract.FACING, enumdirection).set(BlockButtonAbstract.POWERED, (i & 8) > 0); + } + + public int toLegacyData(IBlockData iblockdata) { + int i; + + switch (BlockButtonAbstract.SyntheticClass_1.a[iblockdata.get(BlockButtonAbstract.FACING).ordinal()]) { + case 1: + i = 1; + break; + + case 2: + i = 2; + break; + + case 3: + i = 3; + break; + + case 4: + i = 4; + break; + + case 5: + default: + i = 5; + break; + + case 6: + i = 0; + } + + if (iblockdata.get(BlockButtonAbstract.POWERED)) { + i |= 8; + } + + return i; + } + + public BlockStateList getStateList() { + return new BlockStateList(this, BlockButtonAbstract.FACING, BlockButtonAbstract.POWERED); + } + + static class SyntheticClass_1 { + + static final int[] a = new int[EnumDirection.values().length]; + + static { + try { + BlockButtonAbstract.SyntheticClass_1.a[EnumDirection.EAST.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockButtonAbstract.SyntheticClass_1.a[EnumDirection.WEST.ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockButtonAbstract.SyntheticClass_1.a[EnumDirection.SOUTH.ordinal()] = 3; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockButtonAbstract.SyntheticClass_1.a[EnumDirection.NORTH.ordinal()] = 4; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockButtonAbstract.SyntheticClass_1.a[EnumDirection.UP.ordinal()] = 5; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockButtonAbstract.SyntheticClass_1.a[EnumDirection.DOWN.ordinal()] = 6; + } catch (NoSuchFieldError ignored) { + } + + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockCactus.java b/azurite-server/src/main/java/net/minecraft/server/BlockCactus.java new file mode 100644 index 0000000..cf468b1 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockCactus.java @@ -0,0 +1,123 @@ +package net.minecraft.server; + +import org.bukkit.craftbukkit.event.CraftEventFactory; + +import java.util.Random; + +public class BlockCactus extends Block { + + public static final BlockStateInteger AGE = BlockStateInteger.of("age", 0, 15); + + protected BlockCactus() { + super(Material.CACTUS); + this.j(this.blockStateList.getBlockData().set(BlockCactus.AGE, 0)); + this.a(true); + this.a(CreativeModeTab.c); + } + + public void b(World world, BlockPosition blockposition, IBlockData iblockdata, Random random) { + BlockPosition blockposition1 = blockposition.up(); + + if (world.isEmpty(blockposition1)) { + int i; + + for (i = 1; world.getType(blockposition.getX(), blockposition.getY() - i, blockposition.getZ()).getBlock() == this; ++i) { + } + + if (i < world.paperSpigotConfig.cactusMaxHeight) { // PaperSpigot - Configurable max growth height for cactus blocks) { + int j = iblockdata.get(BlockCactus.AGE); + + if (j >= (byte) range(3, (world.growthOdds / world.spigotConfig.cactusModifier * 15) + 0.5F, 15)) { // Spigot + // world.setTypeUpdate(blockposition1, this.getBlockData()); // CraftBukkit + IBlockData iblockdata1 = iblockdata.set(BlockCactus.AGE, 0); + + CraftEventFactory.handleBlockGrowEvent(world, blockposition1.getX(), blockposition1.getY(), blockposition1.getZ(), this, 0); // CraftBukkit + world.setTypeAndData(blockposition, iblockdata1, 4); + this.doPhysics(world, blockposition1, iblockdata1, this); + } else { + world.setTypeAndData(blockposition, iblockdata.set(BlockCactus.AGE, j + 1), 4); + } + + } + } + } + + // Vortex - optimized cactus ticking + /* @Override + public void optimizedTick(Chunk chunk, int x, int y, int z, IBlockData iblockdata, Random random) { + // world.isEmpty() + if (chunk.getTypeAbs(x, y + 1, z).getMaterial() == Material.AIR) { + int i; + + for (i = 1; chunk.getTypeAbs(x, y - i, z) == this; ++i) { + } + + if (i < world.paperSpigotConfig.cactusMaxHeight) { + int j = iblockdata.get(BlockCactus.AGE); + + if (j >= (byte) range(3, (world.growthOdds / world.spigotConfig.cactusModifier * 15) + 0.5F, 15)) { + IBlockData iblockdata1 = iblockdata.set(BlockCactus.AGE, 0); + + BlockPosition blockposition1 = blockposition.up(); + CraftEventFactory.handleBlockGrowEvent(world, blockposition1.getX(), blockposition1.getY(), blockposition1.getZ(), this, 0); // CraftBukkit + world.setTypeAndData(chunk, blockposition, iblockdata1, 4, true, false); + this.doPhysics(world, blockposition1, iblockdata1, this); + } else { + world.setTypeAndData(chunk, blockposition, iblockdata.set(BlockCactus.AGE, j + 1), 4, true, false); + } + + } + } + } */ + + public AxisAlignedBB a(World world, BlockPosition blockposition, IBlockData iblockdata) { + return new AxisAlignedBB(blockposition.getX() + 0.0625F, blockposition.getY(), blockposition.getZ() + 0.0625F, ((blockposition.getX() + 1) - 0.0625F), (blockposition.getY() + 1) - 0.0625F, (blockposition.getZ() + 1) - 0.0625F); + } + + public boolean d() { + return false; + } + + public boolean c() { + return false; + } + + public boolean canPlace(World world, BlockPosition blockposition) { + return super.canPlace(world, blockposition) && this.e(world, blockposition); + } + + public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) { + if (!this.e(world, blockposition)) { + world.setAir(blockposition, true); + } + } + + public boolean e(World world, BlockPosition blockposition) { + for (EnumDirection enumdirection : EnumDirection.EnumDirectionLimit.HORIZONTAL) { + if (world.getType(blockposition.getX() + enumdirection.getAdjacentX(), blockposition.getY(), blockposition.getZ() + enumdirection.getAdjacentZ()).getBlock().getMaterial().isBuildable()) { + return false; + } + } + + Block block = world.getType(blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()).getBlock(); + return block == Blocks.CACTUS || block == Blocks.SAND; + } + + public void a(World world, BlockPosition blockposition, IBlockData iblockdata, Entity entity) { + CraftEventFactory.blockDamage = world.getWorld().getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()); // CraftBukkit + entity.damageEntity(DamageSource.CACTUS, 1.0F); + CraftEventFactory.blockDamage = null; // CraftBukkit + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockCactus.AGE, i); + } + + public int toLegacyData(IBlockData iblockdata) { + return iblockdata.get(BlockCactus.AGE); + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, BlockCactus.AGE); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockCake.java b/azurite-server/src/main/java/net/minecraft/server/BlockCake.java new file mode 100644 index 0000000..72f3db4 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockCake.java @@ -0,0 +1,131 @@ +package net.minecraft.server; + +import java.util.Random; + +public class BlockCake extends Block { + + public static final BlockStateInteger BITES = BlockStateInteger.of("bites", 0, 6); + + protected BlockCake() { + super(Material.CAKE); + this.j(this.blockStateList.getBlockData().set(BlockCake.BITES, 0)); + this.a(true); + } + + public void updateShape(IBlockAccess iblockaccess, BlockPosition blockposition) { + float f = 0.0625F; + float f1 = (float) (1 + iblockaccess.getType(blockposition).get(BlockCake.BITES) * 2) / 16.0F; + float f2 = 0.5F; + + this.a(f1, 0.0F, f, 1.0F - f, f2, 1.0F - f); + } + + public void j() { + float f = 0.0625F; + float f1 = 0.5F; + + this.a(f, 0.0F, f, 1.0F - f, f1, 1.0F - f); + } + + public AxisAlignedBB a(World world, BlockPosition blockposition, IBlockData iblockdata) { + float f = 0.0625F; + float f1 = (float) (1 + iblockdata.get(BlockCake.BITES) * 2) / 16.0F; + float f2 = 0.5F; + + return new AxisAlignedBB( + ((float) blockposition.getX() + f1), // minX + blockposition.getY(), // minY + ((float) blockposition.getZ() + f), // minZ + ((float) (blockposition.getX() + 1) - f), // maxX + (float)blockposition.getY() + f2 - 0.0625F, // maxY // Beanes - revert to 1.7 height to fix collision issues + (float) (blockposition.getZ() + 1) - f); // maxZ + } + + public boolean d() { + return false; + } + + public boolean c() { + return false; + } + + public boolean interact(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman, EnumDirection enumdirection, float f, float f1, float f2) { + this.b(world, blockposition, iblockdata, entityhuman); + return true; + } + + public void attack(World world, BlockPosition blockposition, EntityHuman entityhuman) { + this.b(world, blockposition, world.getType(blockposition), entityhuman); + } + + private void b(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman) { + if (entityhuman.j(false)) { + entityhuman.b(StatisticList.H); + // CraftBukkit start + // entityhuman.getFoodData().eat(2, 0.1F); + int oldFoodLevel = entityhuman.getFoodData().foodLevel; + + org.bukkit.event.entity.FoodLevelChangeEvent event = org.bukkit.craftbukkit.event.CraftEventFactory.callFoodLevelChangeEvent(entityhuman, 2 + oldFoodLevel); + + if (!event.isCancelled()) { + entityhuman.getFoodData().eat(event.getFoodLevel() - oldFoodLevel, 0.1F); + } + + // Beanes - reduce packets + ((EntityPlayer) entityhuman).updateHealthAndFood(); + + // CraftBukkit end + int i = iblockdata.get(BlockCake.BITES); + + if (i < 6) { + world.setTypeAndData(blockposition, iblockdata.set(BlockCake.BITES, i + 1), 3); + } else { + world.setAir(blockposition); + } + + } + } + + public boolean canPlace(World world, BlockPosition blockposition) { + return super.canPlace(world, blockposition) && this.e(world, blockposition); + } + + public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) { + if (!this.e(world, blockposition)) { + world.setAir(blockposition); + } + + } + + private boolean e(World world, BlockPosition blockposition) { + return world.getType(blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()).getBlock().getMaterial().isBuildable(); + } + + public int a(Random random) { + return 0; + } + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + return null; + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockCake.BITES, i); + } + + public int toLegacyData(IBlockData iblockdata) { + return iblockdata.get(BlockCake.BITES); + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, BlockCake.BITES); + } + + public int l(World world, BlockPosition blockposition) { + return (7 - world.getType(blockposition).get(BlockCake.BITES)) * 2; + } + + public boolean isComplexRedstone() { + return true; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockCarpet.java b/azurite-server/src/main/java/net/minecraft/server/BlockCarpet.java new file mode 100644 index 0000000..0822b38 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockCarpet.java @@ -0,0 +1,80 @@ +package net.minecraft.server; + +import java.util.List; + +public class BlockCarpet extends Block { + + public static final BlockStateEnum COLOR = BlockStateEnum.of("color", EnumColor.class); + + protected BlockCarpet() { + super(Material.WOOL); + this.j(this.blockStateList.getBlockData().set(BlockCarpet.COLOR, EnumColor.WHITE)); + this.a(0.0F, 0.0F, 0.0F, 1.0F, 0.0625F, 1.0F); + this.a(true); + this.a(CreativeModeTab.c); + this.b(0); + } + + public MaterialMapColor g(IBlockData iblockdata) { + return iblockdata.get(BlockCarpet.COLOR).e(); + } + + public boolean c() { + return false; + } + + public boolean d() { + return false; + } + + public void j() { + this.b(0); + } + + public void updateShape(IBlockAccess iblockaccess, BlockPosition blockposition) { + this.b(0); + } + + protected void b(int i) { + this.a(0.0F, 0.0F, 0.0F, 1.0F, 0.0625F, 1.0F); + } + + // Beanes - patch ported from SportPaper (pretty simple) to disable carpet collisions at feet because of 1.7 + public void a(World world, BlockPosition blockposition, IBlockData iblockdata, AxisAlignedBB axisalignedbb, List list, Entity entity) { + if (entity instanceof EntityHuman && blockposition.getY() == (int) entity.getBoundingBox().b) { + return; + } + super.a(world, blockposition, iblockdata, axisalignedbb, list, entity); + } + + public boolean canPlace(World world, BlockPosition blockposition) { + return super.canPlace(world, blockposition) && this.e(world, blockposition); + } + + public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) { + if (!this.e(world, blockposition)) { + this.b(world, blockposition, iblockdata, 0); + world.setAir(blockposition); + } + } + + private boolean e(World world, BlockPosition blockposition) { + return !world.isEmpty(blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()); + } + + public int getDropData(IBlockData iblockdata) { + return iblockdata.get(BlockCarpet.COLOR).getColorIndex(); + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockCarpet.COLOR, EnumColor.fromColorIndex(i)); + } + + public int toLegacyData(IBlockData iblockdata) { + return iblockdata.get(BlockCarpet.COLOR).getColorIndex(); + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, BlockCarpet.COLOR); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockCarrots.java b/azurite-server/src/main/java/net/minecraft/server/BlockCarrots.java new file mode 100644 index 0000000..3bdc67a --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockCarrots.java @@ -0,0 +1,14 @@ +package net.minecraft.server; + +public class BlockCarrots extends BlockCrops { + + public BlockCarrots() {} + + protected Item l() { + return Items.CARROT; + } + + protected Item n() { + return Items.CARROT; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockCauldron.java b/azurite-server/src/main/java/net/minecraft/server/BlockCauldron.java new file mode 100644 index 0000000..678bda9 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockCauldron.java @@ -0,0 +1,176 @@ +package net.minecraft.server; + +import java.util.List; +import java.util.Random; + +public class BlockCauldron extends Block { + + public static final BlockStateInteger LEVEL = BlockStateInteger.of("level", 0, 3); + + public BlockCauldron() { + super(Material.ORE, MaterialMapColor.m); + this.j(this.blockStateList.getBlockData().set(BlockCauldron.LEVEL, 0)); + } + + public void a(World world, BlockPosition blockposition, IBlockData iblockdata, AxisAlignedBB axisalignedbb, List list, Entity entity) { + this.a(0.0F, 0.0F, 0.0F, 1.0F, 0.3125F, 1.0F); + super.a(world, blockposition, iblockdata, axisalignedbb, list, entity); + + this.a(0.0F, 0.0F, 0.0F, 0.125F, 1.0F, 1.0F); + super.a(world, blockposition, iblockdata, axisalignedbb, list, entity); + this.a(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 0.125F); + super.a(world, blockposition, iblockdata, axisalignedbb, list, entity); + this.a(1.0F - 0.125F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + super.a(world, blockposition, iblockdata, axisalignedbb, list, entity); + this.a(0.0F, 0.0F, 1.0F - 0.125F, 1.0F, 1.0F, 1.0F); + super.a(world, blockposition, iblockdata, axisalignedbb, list, entity); + this.j(); + } + + public void j() { + this.a(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + } + + public boolean c() { + return false; + } + + public boolean d() { + return false; + } + + public void a(World world, BlockPosition blockposition, IBlockData iblockdata, Entity entity) { + int i = iblockdata.get(BlockCauldron.LEVEL); + float f = (float) blockposition.getY() + (6.0F + (float) (3 * i)) / 16.0F; + + if (entity.isBurning() && i > 0 && entity.getBoundingBox().b <= (double) f) { + entity.extinguish(); + this.a(world, blockposition, iblockdata, i - 1); + } + + } + + public boolean interact(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman, EnumDirection enumdirection, float f, float f1, float f2) { + ItemStack itemstack = entityhuman.inventory.getItemInHand(); + + if (itemstack == null) { + return true; + } else { + int i = iblockdata.get(BlockCauldron.LEVEL); + Item item = itemstack.getItem(); + + if (item == Items.WATER_BUCKET) { + if (i < 3) { + if (!entityhuman.abilities.canInstantlyBuild) { + entityhuman.inventory.setItem(entityhuman.inventory.itemInHandIndex, new ItemStack(Items.BUCKET)); + } + + this.a(world, blockposition, iblockdata, 3); + } + + return true; + } else { + ItemStack itemstack1; + + if (item == Items.GLASS_BOTTLE) { + if (i > 0) { + if (!entityhuman.abilities.canInstantlyBuild) { + itemstack1 = new ItemStack(Items.POTION, 1, 0); + if (!entityhuman.inventory.pickup(itemstack1)) { + world.addEntity(new EntityItem(world, (double) blockposition.getX() + 0.5D, (double) blockposition.getY() + 1.5D, (double) blockposition.getZ() + 0.5D, itemstack1)); + } else if (entityhuman instanceof EntityPlayer) { + ((EntityPlayer) entityhuman).updateInventory(entityhuman.defaultContainer); + } + + --itemstack.count; + if (itemstack.count <= 0) { + entityhuman.inventory.setItem(entityhuman.inventory.itemInHandIndex, null); + } + } + + this.a(world, blockposition, iblockdata, i - 1); + } + + return true; + } else { + if (i > 0 && item instanceof ItemArmor) { + ItemArmor itemarmor = (ItemArmor) item; + + if (itemarmor.x_() == ItemArmor.EnumArmorMaterial.LEATHER && itemarmor.d_(itemstack)) { + itemarmor.c(itemstack); + this.a(world, blockposition, iblockdata, i - 1); + return true; + } + } + + if (i > 0 && item instanceof ItemBanner && TileEntityBanner.c(itemstack) > 0) { + itemstack1 = itemstack.cloneItemStack(); + itemstack1.count = 1; + TileEntityBanner.e(itemstack1); + if (itemstack.count <= 1 && !entityhuman.abilities.canInstantlyBuild) { + entityhuman.inventory.setItem(entityhuman.inventory.itemInHandIndex, itemstack1); + } else { + if (!entityhuman.inventory.pickup(itemstack1)) { + world.addEntity(new EntityItem(world, (double) blockposition.getX() + 0.5D, (double) blockposition.getY() + 1.5D, (double) blockposition.getZ() + 0.5D, itemstack1)); + } else if (entityhuman instanceof EntityPlayer) { + ((EntityPlayer) entityhuman).updateInventory(entityhuman.defaultContainer); + } + + if (!entityhuman.abilities.canInstantlyBuild) { + --itemstack.count; + } + } + + if (!entityhuman.abilities.canInstantlyBuild) { + this.a(world, blockposition, iblockdata, i - 1); + } + + return true; + } else { + return false; + } + } + } + } + } + + public void a(World world, BlockPosition blockposition, IBlockData iblockdata, int i) { + world.setTypeAndData(blockposition, iblockdata.set(BlockCauldron.LEVEL, MathHelper.clamp(i, 0, 3)), 2); + world.updateAdjacentComparators(blockposition, this); + } + + public void k(World world, BlockPosition blockposition) { + if (world.random.nextInt(20) == 1) { + IBlockData iblockdata = world.getType(blockposition); + + if (iblockdata.get(BlockCauldron.LEVEL) < 3) { + world.setTypeAndData(blockposition, iblockdata.a(BlockCauldron.LEVEL), 2); + } + + } + } + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + return Items.CAULDRON; + } + + public boolean isComplexRedstone() { + return true; + } + + public int l(World world, BlockPosition blockposition) { + return world.getType(blockposition).get(BlockCauldron.LEVEL); + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockCauldron.LEVEL, i); + } + + public int toLegacyData(IBlockData iblockdata) { + return iblockdata.get(BlockCauldron.LEVEL); + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, BlockCauldron.LEVEL); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockChest.java b/azurite-server/src/main/java/net/minecraft/server/BlockChest.java new file mode 100644 index 0000000..de5ba87 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockChest.java @@ -0,0 +1,461 @@ +package net.minecraft.server; + +import java.util.Iterator; + +public class BlockChest extends BlockContainer { + + public static final BlockStateDirection FACING = BlockStateDirection.of("facing", EnumDirection.EnumDirectionLimit.HORIZONTAL); + public final int b; + + protected BlockChest(int i) { + super(Material.WOOD); + this.j(this.blockStateList.getBlockData().set(BlockChest.FACING, EnumDirection.NORTH)); + this.b = i; + this.a(CreativeModeTab.c); + this.a(0.0625F, 0.0F, 0.0625F, 0.9375F, 0.875F, 0.9375F); + } + + public boolean c() { + return false; + } + + public boolean d() { + return false; + } + + public int b() { + return 2; + } + + public void updateShape(IBlockAccess iblockaccess, BlockPosition blockposition) { + final int x = blockposition.getX(), y = blockposition.getY(), z = blockposition.getZ(); + if (iblockaccess.getType(x, y, z - 1).getBlock() == this) { + this.a(0.0625F, 0.0F, 0.0F, 0.9375F, 0.875F, 0.9375F); + } else if (iblockaccess.getType(x, y, z + 1).getBlock() == this) { + this.a(0.0625F, 0.0F, 0.0625F, 0.9375F, 0.875F, 1.0F); + } else if (iblockaccess.getType(x - 1, y, z).getBlock() == this) { + this.a(0.0F, 0.0F, 0.0625F, 0.9375F, 0.875F, 0.9375F); + } else if (iblockaccess.getType(x + 1, y, z).getBlock() == this) { + this.a(0.0625F, 0.0F, 0.0625F, 1.0F, 0.875F, 0.9375F); + } else { + this.a(0.0625F, 0.0F, 0.0625F, 0.9375F, 0.875F, 0.9375F); + } + + } + + public void onPlace(World world, BlockPosition blockposition, IBlockData iblockdata) { + // Beanes - hopper cache + this.invalidateHopperCacheConnection(world, blockposition); + + this.e(world, blockposition, iblockdata); + + for (EnumDirection enumDirection : EnumDirection.EnumDirectionLimit.HORIZONTAL) { + BlockPosition blockposition1 = blockposition.shift(enumDirection); + IBlockData iblockdata1 = world.getType(blockposition1); + + if (iblockdata1.getBlock() == this) { + this.e(world, blockposition1, iblockdata1); + } + } + } + + public IBlockData getPlacedState(World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2, int i, EntityLiving entityliving) { + return this.getBlockData().set(BlockChest.FACING, entityliving.getDirection()); + } + + public void postPlace(World world, BlockPosition blockposition, IBlockData iblockdata, EntityLiving entityliving, ItemStack itemstack) { + EnumDirection enumdirection = EnumDirection.fromType2(MathHelper.floor((entityliving.yaw * 4.0F / 360.0F) + 0.5D) & 3).opposite(); + + iblockdata = iblockdata.set(BlockChest.FACING, enumdirection); + final int x = blockposition.getX(), y = blockposition.getY(), z = blockposition.getZ(); + boolean flag = this == world.getType(x, y, z - 1).getBlock(); + boolean flag1 = this == world.getType(x, y, z + 1).getBlock(); + boolean flag2 = this == world.getType(x - 1, y, z).getBlock(); + boolean flag3 = this == world.getType(x + 1, y, z).getBlock(); + + if (!flag && !flag1 && !flag2 && !flag3) { + world.setTypeAndData(blockposition, iblockdata, 3, false, false); + } else if (enumdirection.k() == EnumDirection.EnumAxis.X && (flag || flag1)) { + if (flag) { + world.setTypeAndData(blockposition.north(), iblockdata, 3, false, false); + } else { + world.setTypeAndData(blockposition.south(), iblockdata, 3, false, false); + } + + world.setTypeAndData(blockposition, iblockdata, 3); + } else if (enumdirection.k() == EnumDirection.EnumAxis.Z && (flag2 || flag3)) { + if (flag2) { + world.setTypeAndData(blockposition.west(), iblockdata, 3, false, false); + } else { + world.setTypeAndData(blockposition.east(), iblockdata, 3, false, false); + } + + world.setTypeAndData(blockposition, iblockdata, 3, false, false); + } + + if (itemstack.hasName()) { + TileEntity tileentity = world.getTileEntity(blockposition); + + if (tileentity instanceof TileEntityChest) { + ((TileEntityChest) tileentity).a(itemstack.getName()); + } + } + } + + public IBlockData e(World world, BlockPosition blockposition, IBlockData iblockdata) { + final int x = blockposition.getX(), y = blockposition.getY(), z = blockposition.getZ(); + IBlockData iblockdata1 = world.getType(x, y, z - 1); + IBlockData iblockdata2 = world.getType(x, y, z + 1); + IBlockData iblockdata3 = world.getType(x - 1, y, z); + IBlockData iblockdata4 = world.getType(x + 1, y, z); + EnumDirection enumdirection = iblockdata.get(BlockChest.FACING); + Block block = iblockdata1.getBlock(); + Block block1 = iblockdata2.getBlock(); + Block block2 = iblockdata3.getBlock(); + Block block3 = iblockdata4.getBlock(); + + if (block != this && block1 != this) { + boolean flag = block.o(); + boolean flag1 = block1.o(); + + if (block2 == this || block3 == this) { + int x1 = block2 == this ? x - 1 : x + 1; + enumdirection = EnumDirection.SOUTH; + EnumDirection enumdirection1; + + if (block2 == this) { + enumdirection1 = iblockdata3.get(BlockChest.FACING); + } else { + enumdirection1 = iblockdata4.get(BlockChest.FACING); + } + + if (enumdirection1 == EnumDirection.NORTH) { + enumdirection = EnumDirection.NORTH; + } + + Block block4 = world.getType(x1, y, z - 1).getBlock(); + Block block5 = world.getType(x1, y, z + 1).getBlock(); + + if ((flag || block4.o()) && !flag1 && !block5.o()) { + enumdirection = EnumDirection.SOUTH; + } + + if ((flag1 || block5.o()) && !flag && !block4.o()) { + enumdirection = EnumDirection.NORTH; + } + } + } else { + int x1 = block2 == this ? x - 1 : x + 1; + enumdirection = EnumDirection.EAST; + EnumDirection enumdirection2; + + if (block == this) { + enumdirection2 = iblockdata1.get(BlockChest.FACING); + } else { + enumdirection2 = iblockdata2.get(BlockChest.FACING); + } + + if (enumdirection2 == EnumDirection.WEST) { + enumdirection = EnumDirection.WEST; + } + + Block block6 = world.getType(x1, y, z - 1).getBlock(); + Block block7 = world.getType(x1, y, z + 1).getBlock(); + + if ((block2.o() || block6.o()) && !block3.o() && !block7.o()) { + enumdirection = EnumDirection.EAST; + } + + if ((block3.o() || block7.o()) && !block2.o() && !block6.o()) { + enumdirection = EnumDirection.WEST; + } + } + + iblockdata = iblockdata.set(BlockChest.FACING, enumdirection); + world.setTypeAndData(blockposition, iblockdata, 3); + return iblockdata; + } + + public IBlockData f(World world, BlockPosition blockposition, IBlockData iblockdata) { + return f(world, blockposition, iblockdata, false); + } + + public IBlockData f(World world, BlockPosition blockposition, IBlockData iblockdata, boolean flag) { + EnumDirection enumdirection = null; + final int x = blockposition.getX(), y = blockposition.getY(), z = blockposition.getZ(); + + for (EnumDirection enumdirection1 : EnumDirection.EnumDirectionLimit.HORIZONTAL) { + IBlockData iblockdata1 = world.getType(x + enumdirection1.getAdjacentX(), y + enumdirection1.getAdjacentY(), z + enumdirection1.getAdjacentZ()); + + if (iblockdata1.getBlock() == this) { + return iblockdata; + } + + if (iblockdata1.getBlock().o()) { + if (enumdirection != null) { + enumdirection = null; + break; + } + + enumdirection = enumdirection1; + } + } + + if (enumdirection != null) { + return iblockdata.set(BlockChest.FACING, enumdirection.opposite()); + } else { + EnumDirection enumdirection2 = iblockdata.get(BlockChest.FACING); + + if (world.getType(x + enumdirection2.getAdjacentX(), y + enumdirection2.getAdjacentY(), z + enumdirection2.getAdjacentZ()).getBlock().o()) { + enumdirection2 = enumdirection2.opposite(); + } + + if (world.getType(x + enumdirection2.getAdjacentX(), y + enumdirection2.getAdjacentY(), z + enumdirection2.getAdjacentZ()).getBlock().o()) { + enumdirection2 = enumdirection2.e(); + } + + if (world.getType(x + enumdirection2.getAdjacentX(), y + enumdirection2.getAdjacentY(), z + enumdirection2.getAdjacentZ()).getBlock().o()) { + enumdirection2 = enumdirection2.opposite(); + } + + return iblockdata.set(BlockChest.FACING, enumdirection2); + } + } + + public boolean canPlace(World world, BlockPosition blockposition) { + int i = 0; + final int x = blockposition.getX(), y = blockposition.getY(), z = blockposition.getZ(); + if (world.getType(x - 1, y, z).getBlock() == this) { + if (this.m(world, x - 1, y, z)) { + return false; + } + + ++i; + } + + if (world.getType(x + 1, y, z).getBlock() == this) { + if (this.m(world, x + 1, y, z)) { + return false; + } + + ++i; + } + + if (world.getType(x, y, z - 1).getBlock() == this) { + if (this.m(world, x, y, z - 1)) { + return false; + } + + ++i; + } + + if (world.getType(x, y, z + 1).getBlock() == this) { + if (this.m(world, x, y, z + 1)) { + return false; + } + + ++i; + } + + return i <= 1; + } + + private boolean m(World world, int x, int y, int z) { + Iterator iterator = EnumDirection.EnumDirectionLimit.HORIZONTAL.iterator(); + EnumDirection enumdirection; + do { + if (!iterator.hasNext()) + return false; + enumdirection = iterator.next(); + } while (world.getType(x + enumdirection.getAdjacentX(), y + enumdirection.getAdjacentY(), z + enumdirection.getAdjacentZ()).getBlock() != this); + return true; + } + + public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) { + super.doPhysics(world, blockposition, iblockdata, block); + TileEntity tileentity = world.getTileEntity(blockposition); + + if (tileentity instanceof TileEntityChest) { + tileentity.E(); + } + + } + + public void remove(World world, BlockPosition blockposition, IBlockData iblockdata) { + TileEntity tileentity = world.getTileEntity(blockposition); + + if (tileentity instanceof IInventory) { + InventoryUtils.dropInventory(world, blockposition, (IInventory) tileentity); + world.updateAdjacentComparators(blockposition, this); + } + + super.remove(world, blockposition, iblockdata); + } + + public boolean interact(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman, EnumDirection enumdirection, float f, float f1, float f2) { + ITileInventory itileinventory = getInventory(world, blockposition); + + if (itileinventory != null) { + entityhuman.openContainer(itileinventory); + if (this.b == 0) { + entityhuman.b(StatisticList.aa); + } else if (this.b == 1) { + entityhuman.b(StatisticList.U); + } + } + + return true; + } + + //Paper - OBF HELPER + public ITileInventory getInventory(World world, BlockPosition blockposition) { + return f(world, blockposition, false); + } + + public ITileInventory f(World world, BlockPosition blockposition) { + return f(world, blockposition, true); + } + + public ITileInventory f(World world, BlockPosition blockposition, boolean flag) { + TileEntity tileentity = world.getTileEntity(blockposition); + + if (!(tileentity instanceof TileEntityChest)) + return null; + + Object object = tileentity; + + if (flag && this.n(world, blockposition)) + return null; + + for (EnumDirection enumdirection : EnumDirection.EnumDirectionLimit.HORIZONTAL) { + BlockPosition blockposition1 = blockposition.shift(enumdirection); + IBlockData typeIfLoaded = world.getTypeIfLoaded(blockposition1.getX(), blockposition1.getY(), blockposition1.getZ()); + + if (typeIfLoaded == null) + continue; + + Block block = typeIfLoaded.getBlock(); + + if (block == this) { + if (this.n(world, blockposition1)) { + return null; + } + + TileEntity tileentity1 = world.getTileEntity(blockposition1); + + if (tileentity1 instanceof TileEntityChest) { + if (enumdirection != EnumDirection.WEST && enumdirection != EnumDirection.NORTH) { + object = new InventoryLargeChest("container.chestDouble", (ITileInventory) object, (TileEntityChest) tileentity1); + } else { + object = new InventoryLargeChest("container.chestDouble", (TileEntityChest) tileentity1, (ITileInventory) object); + } + } + } + } + + return (ITileInventory) object; + } + + public TileEntity a(World world, int i) { + return new TileEntityChest(); + } + + public boolean isPowerSource() { + return this.b == 1; + } + + public int a(IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata, EnumDirection enumdirection) { + if (!this.isPowerSource()) { + return 0; + } else { + int i = 0; + TileEntity tileentity = iblockaccess.getTileEntity(blockposition); + + if (tileentity instanceof TileEntityChest) { + i = ((TileEntityChest) tileentity).l; + } + + return MathHelper.clamp(i, 0, 15); + } + } + + public int b(IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata, EnumDirection enumdirection) { + return enumdirection == EnumDirection.UP ? this.a(iblockaccess, blockposition, iblockdata, enumdirection) : 0; + } + + private boolean n(World world, BlockPosition blockposition) { + return this.o(world, blockposition) || this.p(world, blockposition); + } + + private boolean o(World world, BlockPosition blockposition) { + return world.getType(blockposition.getX(), blockposition.getY() + 1, blockposition.getZ()).getBlock().isOccluding(); + } + + private boolean p(World world, BlockPosition blockposition) { + EntityOcelot entityocelot; + if (world.paperSpigotConfig.disableChestCatDetection) + return false; + Iterator iterator = world.a(EntityOcelot.class, new AxisAlignedBB(blockposition.getX(), (blockposition.getY() + 1), blockposition.getZ(), (blockposition.getX() + 1), (blockposition.getY() + 2), (blockposition.getZ() + 1))).iterator(); + do { + if (!iterator.hasNext()) + return false; + entityocelot = iterator.next(); + } while (!entityocelot.isSitting()); + return true; + } + + public boolean isComplexRedstone() { + return true; + } + + public int l(World world, BlockPosition blockposition) { + return Container.b(this.getInventory(world, blockposition)); + } + + public IBlockData fromLegacyData(int i) { + EnumDirection enumdirection = EnumDirection.fromType1(i); + + if (enumdirection.k() == EnumDirection.EnumAxis.Y) { + enumdirection = EnumDirection.NORTH; + } + + return this.getBlockData().set(BlockChest.FACING, enumdirection); + } + + public int toLegacyData(IBlockData iblockdata) { + return iblockdata.get(BlockChest.FACING).a(); + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, BlockChest.FACING); + } + + // Beanes - hardcode shape of anvil to prevent false phase collisions (does not fix all of them since minceraft is fundamentally broken and lets you phase through anvils / chests!) + @Override + public AxisAlignedBB a(World world, BlockPosition blockposition, IBlockData iblockdata) { + if (world.getType(blockposition.north()).getBlock() == this) { + return new AxisAlignedBB(blockposition.getX() + 0.0625F, blockposition.getY(), blockposition.getZ(), blockposition.getX() + 0.9375F, blockposition.getY() + 0.875F, blockposition.getZ() + 0.9375F); + } else if (world.getType(blockposition.south()).getBlock() == this) { + return new AxisAlignedBB(blockposition.getX() + 0.0625F, blockposition.getY(), blockposition.getZ() + 0.0625F, blockposition.getX() + 0.9375F, blockposition.getY() + 0.875F, blockposition.getZ() + 1.0F); + } else if (world.getType(blockposition.west()).getBlock() == this) { + return new AxisAlignedBB(blockposition.getX(), blockposition.getY(), blockposition.getZ() + 0.0625F, blockposition.getX() + 0.9375F, blockposition.getY() + 0.875F, blockposition.getZ() + 0.9375F); + } else if (world.getType(blockposition.east()).getBlock() == this) { + return new AxisAlignedBB(blockposition.getX() + 0.0625F, blockposition.getY(), blockposition.getZ() + 0.0625F, blockposition.getX() + 1.0F, blockposition.getY() + 0.875F, blockposition.getZ() + 0.9375F); + } else { + return new AxisAlignedBB(blockposition.getX() + 0.0625F, blockposition.getY(), blockposition.getZ() + 0.0625F, blockposition.getX() + 0.9375F, blockposition.getY() + 0.875F, blockposition.getZ() + 0.9375F); + } + } + + // Beanes - hopper cache + public void invalidateHopperCacheConnection(World world, BlockPosition blockposition) { + for (EnumDirection enumdirection : EnumDirection.EnumDirectionLimit.HORIZONTAL) { + BlockPosition blockposition1 = blockposition.shift(enumdirection); + + TileEntity tileEntity = world.getTileEntity(blockposition1); + + if (tileEntity instanceof TileEntityChest) { + ((TileEntityContainer) tileEntity).invalidateHopperCache(); + } + } + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockClay.java b/azurite-server/src/main/java/net/minecraft/server/BlockClay.java new file mode 100644 index 0000000..dbbe36b --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockClay.java @@ -0,0 +1,19 @@ +package net.minecraft.server; + +import java.util.Random; + +public class BlockClay extends Block { + + public BlockClay() { + super(Material.CLAY); + this.a(CreativeModeTab.b); + } + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + return Items.CLAY_BALL; + } + + public int a(Random random) { + return 4; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockCloth.java b/azurite-server/src/main/java/net/minecraft/server/BlockCloth.java new file mode 100644 index 0000000..aeeff06 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockCloth.java @@ -0,0 +1,32 @@ +package net.minecraft.server; + +public class BlockCloth extends Block { + + public static final BlockStateEnum COLOR = BlockStateEnum.of("color", EnumColor.class); + + public BlockCloth(Material material) { + super(material); + this.j(this.blockStateList.getBlockData().set(BlockCloth.COLOR, EnumColor.WHITE)); + this.a(CreativeModeTab.b); + } + + public int getDropData(IBlockData iblockdata) { + return iblockdata.get(BlockCloth.COLOR).getColorIndex(); + } + + public MaterialMapColor g(IBlockData iblockdata) { + return iblockdata.get(BlockCloth.COLOR).e(); + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockCloth.COLOR, EnumColor.fromColorIndex(i)); + } + + public int toLegacyData(IBlockData iblockdata) { + return iblockdata.get(BlockCloth.COLOR).getColorIndex(); + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, BlockCloth.COLOR); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockCobbleWall.java b/azurite-server/src/main/java/net/minecraft/server/BlockCobbleWall.java new file mode 100644 index 0000000..adda044 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockCobbleWall.java @@ -0,0 +1,155 @@ +package net.minecraft.server; + +public class BlockCobbleWall extends Block { + + public static final BlockStateBoolean UP = BlockStateBoolean.of("up"); + public static final BlockStateBoolean NORTH = BlockStateBoolean.of("north"); + public static final BlockStateBoolean EAST = BlockStateBoolean.of("east"); + public static final BlockStateBoolean SOUTH = BlockStateBoolean.of("south"); + public static final BlockStateBoolean WEST = BlockStateBoolean.of("west"); + public static final BlockStateEnum VARIANT = BlockStateEnum.of("variant", BlockCobbleWall.EnumCobbleVariant.class); + + public BlockCobbleWall(Block block) { + super(block.material); + this.j(this.blockStateList.getBlockData().set(BlockCobbleWall.UP, Boolean.FALSE).set(BlockCobbleWall.NORTH, Boolean.FALSE).set(BlockCobbleWall.EAST, Boolean.FALSE).set(BlockCobbleWall.SOUTH, Boolean.FALSE).set(BlockCobbleWall.WEST, Boolean.FALSE).set(BlockCobbleWall.VARIANT, BlockCobbleWall.EnumCobbleVariant.NORMAL)); + this.c(block.strength); + this.b(block.durability / 3.0F); + this.a(block.stepSound); + this.a(CreativeModeTab.b); + } + + public String getName() { + return LocaleI18n.get(this.a() + "." + BlockCobbleWall.EnumCobbleVariant.NORMAL.c() + ".name"); + } + + public boolean d() { + return false; + } + + public boolean b(IBlockAccess iblockaccess, BlockPosition blockposition) { + return false; + } + + public boolean c() { + return false; + } + + public void updateShape(IBlockAccess iblockaccess, BlockPosition blockposition) { + boolean flag = this.e(iblockaccess, blockposition.north()); + boolean flag1 = this.e(iblockaccess, blockposition.south()); + boolean flag2 = this.e(iblockaccess, blockposition.west()); + boolean flag3 = this.e(iblockaccess, blockposition.east()); + float f = 0.25F; + float f1 = 0.75F; + float f2 = 0.25F; + float f3 = 0.75F; + float f4 = 1.0F; + + if (flag) { + f2 = 0.0F; + } + + if (flag1) { + f3 = 1.0F; + } + + if (flag2) { + f = 0.0F; + } + + if (flag3) { + f1 = 1.0F; + } + + if (flag && flag1 && !flag2 && !flag3) { + f4 = 0.8125F; + f = 0.3125F; + f1 = 0.6875F; + } else if (!flag && !flag1 && flag2 && flag3) { + f4 = 0.8125F; + f2 = 0.3125F; + f3 = 0.6875F; + } + + this.a(f, 0.0F, f2, f1, f4, f3); + } + + public AxisAlignedBB a(World world, BlockPosition blockposition, IBlockData iblockdata) { + this.updateShape(world, blockposition); + this.maxY = 1.5D; + return super.a(world, blockposition, iblockdata); + } + + public boolean e(IBlockAccess iblockaccess, BlockPosition blockposition) { + Block block = iblockaccess.getType(blockposition).getBlock(); + + return block != Blocks.BARRIER && (block == this || block instanceof BlockFenceGate || (block.material.k() && block.d() && block.material != Material.PUMPKIN)); + } + + public int getDropData(IBlockData iblockdata) { + return iblockdata.get(BlockCobbleWall.VARIANT).a(); + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockCobbleWall.VARIANT, BlockCobbleWall.EnumCobbleVariant.a(i)); + } + + public int toLegacyData(IBlockData iblockdata) { + return iblockdata.get(BlockCobbleWall.VARIANT).a(); + } + + public IBlockData updateState(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { + return iblockdata.set(BlockCobbleWall.UP, !iblockaccess.isEmpty(blockposition.up())).set(BlockCobbleWall.NORTH, this.e(iblockaccess, blockposition.north())).set(BlockCobbleWall.EAST, this.e(iblockaccess, blockposition.east())).set(BlockCobbleWall.SOUTH, this.e(iblockaccess, blockposition.south())).set(BlockCobbleWall.WEST, this.e(iblockaccess, blockposition.west())); + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, BlockCobbleWall.UP, BlockCobbleWall.NORTH, BlockCobbleWall.EAST, BlockCobbleWall.WEST, BlockCobbleWall.SOUTH, BlockCobbleWall.VARIANT); + } + + public enum EnumCobbleVariant implements INamable { + + NORMAL(0, "cobblestone", "normal"), MOSSY(1, "mossy_cobblestone", "mossy"); + + private static final BlockCobbleWall.EnumCobbleVariant[] c = new BlockCobbleWall.EnumCobbleVariant[values().length]; + private final int d; + private final String e; + private final String f; + + EnumCobbleVariant(int i, String s, String s1) { + this.d = i; + this.e = s; + this.f = s1; + } + + public int a() { + return this.d; + } + + public String toString() { + return this.e; + } + + public static BlockCobbleWall.EnumCobbleVariant a(int i) { + if (i < 0 || i >= BlockCobbleWall.EnumCobbleVariant.c.length) { + i = 0; + } + + return BlockCobbleWall.EnumCobbleVariant.c[i]; + } + + public String getName() { + return this.e; + } + + public String c() { + return this.f; + } + + static { + for (EnumCobbleVariant blockcobblewall_enumcobblevariant : values()) { + EnumCobbleVariant.c[blockcobblewall_enumcobblevariant.a()] = blockcobblewall_enumcobblevariant; + } + + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockCocoa.java b/azurite-server/src/main/java/net/minecraft/server/BlockCocoa.java new file mode 100644 index 0000000..b14bcfd --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockCocoa.java @@ -0,0 +1,180 @@ +package net.minecraft.server; + +import org.bukkit.craftbukkit.event.CraftEventFactory; + +import java.util.Random; + +public class BlockCocoa extends BlockDirectional implements IBlockFragilePlantElement { + + public static final BlockStateInteger AGE = BlockStateInteger.of("age", 0, 2); + + public BlockCocoa() { + super(Material.PLANT); + this.j(this.blockStateList.getBlockData().set(BlockCocoa.FACING, EnumDirection.NORTH).set(BlockCocoa.AGE, 0)); + this.a(true); + } + + public void b(World world, BlockPosition blockposition, IBlockData iblockdata, Random random) { + if (!this.e(world, blockposition, iblockdata)) { + this.f(world, blockposition, iblockdata); + } else if (world.random.nextInt(5) == 0) { + int i = iblockdata.get(BlockCocoa.AGE); + + if (i < 2) { + // CraftBukkit start + IBlockData data = iblockdata.set(AGE, i + 1); + CraftEventFactory.handleBlockGrowEvent(world, blockposition.getX(), blockposition.getY(), blockposition.getZ(), this, toLegacyData(data)); + // CraftBukkit end + } + } + + } + + public boolean e(World world, BlockPosition blockposition, IBlockData iblockdata) { + blockposition = blockposition.shift(iblockdata.get(BlockCocoa.FACING)); + IBlockData iblockdata1 = world.getType(blockposition); + + return iblockdata1.getBlock() == Blocks.LOG && iblockdata1.get(BlockWood.VARIANT) == BlockWood.EnumLogVariant.JUNGLE; + } + + public boolean d() { + return false; + } + + public boolean c() { + return false; + } + + public AxisAlignedBB a(World world, BlockPosition blockposition, IBlockData iblockdata) { + this.updateShape(world, blockposition); + return super.a(world, blockposition, iblockdata); + } + + public void updateShape(IBlockAccess iblockaccess, BlockPosition blockposition) { + IBlockData iblockdata = iblockaccess.getType(blockposition); + EnumDirection enumdirection = iblockdata.get(BlockCocoa.FACING); + int i = iblockdata.get(BlockCocoa.AGE); + int j = 4 + i * 2; + int k = 5 + i * 2; + float f = (float) j / 2.0F; + + switch (BlockCocoa.SyntheticClass_1.a[enumdirection.ordinal()]) { + case 1: + this.a((8.0F - f) / 16.0F, (12.0F - (float) k) / 16.0F, (15.0F - (float) j) / 16.0F, (8.0F + f) / 16.0F, 0.75F, 0.9375F); + break; + + case 2: + this.a((8.0F - f) / 16.0F, (12.0F - (float) k) / 16.0F, 0.0625F, (8.0F + f) / 16.0F, 0.75F, (1.0F + (float) j) / 16.0F); + break; + + case 3: + this.a(0.0625F, (12.0F - (float) k) / 16.0F, (8.0F - f) / 16.0F, (1.0F + (float) j) / 16.0F, 0.75F, (8.0F + f) / 16.0F); + break; + + case 4: + this.a((15.0F - (float) j) / 16.0F, (12.0F - (float) k) / 16.0F, (8.0F - f) / 16.0F, 0.9375F, 0.75F, (8.0F + f) / 16.0F); + } + + } + + public void postPlace(World world, BlockPosition blockposition, IBlockData iblockdata, EntityLiving entityliving, ItemStack itemstack) { + world.setTypeAndData(blockposition, iblockdata.set(BlockCocoa.FACING, EnumDirection.fromAngle(entityliving.yaw)), 2); + } + + public IBlockData getPlacedState(World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2, int i, EntityLiving entityliving) { + if (!enumdirection.k().c()) { + enumdirection = EnumDirection.NORTH; + } + + return this.getBlockData().set(BlockCocoa.FACING, enumdirection.opposite()).set(BlockCocoa.AGE, 0); + } + + public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) { + if (!this.e(world, blockposition, iblockdata)) { + this.f(world, blockposition, iblockdata); + } + + } + + private void f(World world, BlockPosition blockposition, IBlockData iblockdata) { + world.setTypeAndData(blockposition, Blocks.AIR.getBlockData(), 3); + this.b(world, blockposition, iblockdata, 0); + } + + public void dropNaturally(World world, BlockPosition blockposition, IBlockData iblockdata, float f, int i) { + int j = iblockdata.get(BlockCocoa.AGE); + byte b0 = 1; + + if (j >= 2) { + b0 = 3; + } + + for (int k = 0; k < b0; ++k) { + a(world, blockposition, new ItemStack(Items.DYE, 1, EnumColor.BROWN.getInvColorIndex())); + } + + } + + public int getDropData(World world, BlockPosition blockposition) { + return EnumColor.BROWN.getInvColorIndex(); + } + + public boolean a(World world, BlockPosition blockposition, IBlockData iblockdata, boolean flag) { + return iblockdata.get(BlockCocoa.AGE) < 2; + } + + public boolean a(World world, Random random, BlockPosition blockposition, IBlockData iblockdata) { + return true; + } + + public void b(World world, Random random, BlockPosition blockposition, IBlockData iblockdata) { + // CraftBukkit start + IBlockData data = iblockdata.set(AGE, iblockdata.get(AGE) + 1); + CraftEventFactory.handleBlockGrowEvent(world, blockposition.getX(), blockposition.getY(), blockposition.getZ(), this, toLegacyData(data)); + // CraftBukkit end + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockCocoa.FACING, EnumDirection.fromType2(i)).set(BlockCocoa.AGE, (i & 15) >> 2); + } + + public int toLegacyData(IBlockData iblockdata) { + byte b0 = 0; + int i = b0 | iblockdata.get(BlockCocoa.FACING).b(); + + i |= iblockdata.get(BlockCocoa.AGE) << 2; + return i; + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, BlockCocoa.FACING, BlockCocoa.AGE); + } + + static class SyntheticClass_1 { + + static final int[] a = new int[EnumDirection.values().length]; + + static { + try { + BlockCocoa.SyntheticClass_1.a[EnumDirection.SOUTH.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockCocoa.SyntheticClass_1.a[EnumDirection.NORTH.ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockCocoa.SyntheticClass_1.a[EnumDirection.WEST.ordinal()] = 3; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockCocoa.SyntheticClass_1.a[EnumDirection.EAST.ordinal()] = 4; + } catch (NoSuchFieldError ignored) { + } + + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockCommand.java b/azurite-server/src/main/java/net/minecraft/server/BlockCommand.java new file mode 100644 index 0000000..98210e4 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockCommand.java @@ -0,0 +1,121 @@ +package net.minecraft.server; + +import org.bukkit.event.block.BlockRedstoneEvent; + +import java.util.Random; + +public class BlockCommand extends BlockContainer { + + public static final BlockStateBoolean TRIGGERED = BlockStateBoolean.of("triggered"); + + public BlockCommand() { + super(Material.ORE, MaterialMapColor.q); + this.j(this.blockStateList.getBlockData().set(BlockCommand.TRIGGERED, false)); + } + + public TileEntity a(World world, int i) { + return new TileEntityCommand(); + } + + public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) { + boolean flag = world.isBlockIndirectlyPowered(blockposition); + boolean flag1 = iblockdata.get(BlockCommand.TRIGGERED); + + // CraftBukkit start + org.bukkit.block.Block bukkitBlock = world.getWorld().getBlockAt(blockposition.getX(), blockposition.getY(), + blockposition.getZ()); + int old = flag1 ? 15 : 0; + int current = flag ? 15 : 0; + + BlockRedstoneEvent eventRedstone = new BlockRedstoneEvent(bukkitBlock, old, current); + world.getServer().getPluginManager().callEvent(eventRedstone); + // CraftBukkit end + + if (eventRedstone.getNewCurrent() > 0 && !(eventRedstone.getOldCurrent() > 0)) { // CraftBukkit + world.setTypeAndData(blockposition, iblockdata.set(BlockCommand.TRIGGERED, true), 4); + world.a(blockposition, this, this.a(world)); + } else if (!(eventRedstone.getNewCurrent() > 0) && eventRedstone.getOldCurrent() > 0) { // CraftBukkit + world.setTypeAndData(blockposition, iblockdata.set(BlockCommand.TRIGGERED, false), 4); + } + + } + + public void b(World world, BlockPosition blockposition, IBlockData iblockdata, Random random) { + TileEntity tileentity = world.getTileEntity(blockposition); + + if (tileentity instanceof TileEntityCommand) { + ((TileEntityCommand) tileentity).getCommandBlock().a(world); + world.updateAdjacentComparators(blockposition, this); + } + + } + + public int a(World world) { + return 1; + } + + public boolean interact(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman, + EnumDirection enumdirection, float f, float f1, float f2) { + TileEntity tileentity = world.getTileEntity(blockposition); + + return tileentity instanceof TileEntityCommand && ((TileEntityCommand) tileentity).getCommandBlock().a(entityhuman); + } + + public boolean isComplexRedstone() { + return true; + } + + public int l(World world, BlockPosition blockposition) { + TileEntity tileentity = world.getTileEntity(blockposition); + + return tileentity instanceof TileEntityCommand ? ((TileEntityCommand) tileentity).getCommandBlock().j() : 0; + } + + public void postPlace(World world, BlockPosition blockposition, IBlockData iblockdata, EntityLiving entityliving, + ItemStack itemstack) { + TileEntity tileentity = world.getTileEntity(blockposition); + + if (tileentity instanceof TileEntityCommand) { + CommandBlockListenerAbstract commandblocklistenerabstract = ((TileEntityCommand) tileentity) + .getCommandBlock(); + + if (itemstack.hasName()) { + commandblocklistenerabstract.setName(itemstack.getName()); + } + + commandblocklistenerabstract.a(world.getGameRules().getBoolean("sendCommandFeedback")); + + } + } + + public int a(Random random) { + return 0; + } + + public int b() { + return 3; + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockCommand.TRIGGERED, (i & 1) > 0); + } + + public int toLegacyData(IBlockData iblockdata) { + int i = 0; + + if (iblockdata.get(BlockCommand.TRIGGERED)) { + i |= 1; + } + + return i; + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, BlockCommand.TRIGGERED); + } + + public IBlockData getPlacedState(World world, BlockPosition blockposition, EnumDirection enumdirection, float f, + float f1, float f2, int i, EntityLiving entityliving) { + return this.getBlockData().set(BlockCommand.TRIGGERED, false); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockContainer.java b/azurite-server/src/main/java/net/minecraft/server/BlockContainer.java new file mode 100644 index 0000000..630a2e7 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockContainer.java @@ -0,0 +1,37 @@ +package net.minecraft.server; + +public abstract class BlockContainer extends Block implements IContainer { + + protected BlockContainer(Material material) { + this(material, material.r()); + } + + protected BlockContainer(Material material, MaterialMapColor materialmapcolor) { + super(material, materialmapcolor); + this.isTileEntity = true; + } + + protected boolean a(World world, BlockPosition blockposition, EnumDirection enumdirection) { + return world.getType(blockposition.shift(enumdirection)).getBlock().getMaterial() == Material.CACTUS; + } + + protected boolean e(World world, BlockPosition blockposition) { + return this.a(world, blockposition, EnumDirection.NORTH) || this.a(world, blockposition, EnumDirection.SOUTH) || this.a(world, blockposition, EnumDirection.WEST) || this.a(world, blockposition, EnumDirection.EAST); + } + + public int b() { + return -1; + } + + public void remove(World world, BlockPosition blockposition, IBlockData iblockdata) { + super.remove(world, blockposition, iblockdata); + world.t(blockposition); + } + + public boolean a(World world, BlockPosition blockposition, IBlockData iblockdata, int i, int j) { + super.a(world, blockposition, iblockdata, i, j); + TileEntity tileentity = world.getTileEntity(blockposition); + + return tileentity != null && tileentity.c(i, j); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockCrops.java b/azurite-server/src/main/java/net/minecraft/server/BlockCrops.java new file mode 100644 index 0000000..7f59ade --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockCrops.java @@ -0,0 +1,165 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.AzuriteConfig; +import org.bukkit.craftbukkit.event.CraftEventFactory; + +import java.util.Random; + +public class BlockCrops extends BlockPlant implements IBlockFragilePlantElement { + + public static final BlockStateInteger AGE = BlockStateInteger.of("age", 0, 7); + + protected BlockCrops() { + this.j(this.blockStateList.getBlockData().set(BlockCrops.AGE, 0)); + this.a(true); + float f = 0.5F; + + this.a(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, 0.25F, 0.5F + f); + this.a((CreativeModeTab) null); + this.c(0.0F); + this.a(BlockCrops.h); + this.K(); + } + + protected static float a(Block block, World world, BlockPosition blockposition) { + float f = 1.0F; + BlockPosition blockposition1 = blockposition.down(); + + for (int i = -1; i <= 1; ++i) { + for (int j = -1; j <= 1; ++j) { + float f1 = 0.0F; + IBlockData iblockdata = world.getType(blockposition1.a(i, 0, j)); + + if (iblockdata.getBlock() == Blocks.FARMLAND) { + f1 = 1.0F; + if (iblockdata.get(BlockSoil.MOISTURE) > 0) { + f1 = 3.0F; + } + } + + if (i != 0 || j != 0) { + f1 /= 4.0F; + } + + f += f1; + } + } + + boolean flag = block == world.getType(blockposition.getX() - 1, blockposition.getY(), blockposition.getZ()).getBlock() + || block == world.getType(blockposition.getX() + 1, blockposition.getY(), blockposition.getZ()).getBlock(); + boolean flag1 = block == world.getType(blockposition.getX(), blockposition.getY(), blockposition.getZ() - 1).getBlock() + || block == world.getType(blockposition.getX(), blockposition.getY(), blockposition.getZ() + 1).getBlock(); + + if (flag && flag1) { + f /= 2.0F; + } else { + boolean flag2 = block == world.getType(blockposition.getX() - 1, blockposition.getY(), blockposition.getZ() - 1).getBlock() + || block == world.getType(blockposition.getX() + 1, blockposition.getY(), blockposition.getZ() - 1).getBlock() + || block == world.getType(blockposition.getX() + 1, blockposition.getY(), blockposition.getZ() + 1).getBlock() + || block == world.getType(blockposition.getX() - 1, blockposition.getY(), blockposition.getZ() + 1).getBlock(); + + if (flag2) { + f /= 2.0F; + } + } + + return f; + } + + protected boolean c(Block block) { + return block == Blocks.FARMLAND; + } + + public void b(World world, BlockPosition blockposition, IBlockData iblockdata, Random random) { + if (AzuriteConfig.dropFloatingPlants.getValue()) { + super.b(world, blockposition, iblockdata, random); + } else if (!f(world, blockposition, iblockdata)) { + return; + } + if (world.isLightLevel(blockposition.getX(), blockposition.getY() + 1, blockposition.getZ(), 9)) { // PandaSpigot - Use isLightLevel + int i = iblockdata.get(BlockCrops.AGE); + + if (i < 7) { + float f = a(this, world, blockposition); + + if (random.nextInt((int) (world.growthOdds / world.spigotConfig.wheatModifier * (25.0F / f)) + 1) == 0) { // Spigot + // CraftBukkit start + IBlockData data = iblockdata.set(AGE, i + 1); + CraftEventFactory.handleBlockGrowEvent(world, blockposition.getX(), blockposition.getY(), blockposition.getZ(), this, toLegacyData(data)); + // CraftBukkit end + } + } + } + } + + public void g(World world, BlockPosition blockposition, IBlockData iblockdata) { + int i = iblockdata.get(BlockCrops.AGE) + MathHelper.nextInt(world.random, 2, 5); + + if (i > 7) { + i = 7; + } + + // CraftBukkit start + + CraftEventFactory.handleBlockGrowEvent(world, blockposition.getX(), blockposition.getY(), blockposition.getZ(), + this, toLegacyData(iblockdata.set(AGE, i))); + // CraftBukkit end + } + + public boolean f(World world, BlockPosition blockposition, IBlockData iblockdata) { + return (world.k(blockposition) >= 8 || world.i(blockposition)) + && this.c(world.getType(blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()).getBlock()); + } + + protected Item l() { + return Items.WHEAT_SEEDS; + } + + protected Item n() { + return Items.WHEAT; + } + + public void dropNaturally(World world, BlockPosition blockposition, IBlockData iblockdata, float f, int i) { + super.dropNaturally(world, blockposition, iblockdata, f, 0); + int j = iblockdata.get(BlockCrops.AGE); + + if (j >= 7) { + int k = 3 + i; + + for (int l = 0; l < k; ++l) { + if (world.random.nextInt(15) <= j) { + a(world, blockposition, new ItemStack(this.l(), 1, 0)); + } + } + } + + } + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + return iblockdata.get(BlockCrops.AGE) == 7 ? this.n() : this.l(); + } + + public boolean a(World world, BlockPosition blockposition, IBlockData iblockdata, boolean flag) { + return iblockdata.get(BlockCrops.AGE) < 7; + } + + public boolean a(World world, Random random, BlockPosition blockposition, IBlockData iblockdata) { + return true; + } + + public void b(World world, Random random, BlockPosition blockposition, IBlockData iblockdata) { + this.g(world, blockposition, iblockdata); + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockCrops.AGE, i); + } + + public int toLegacyData(IBlockData iblockdata) { + return iblockdata.get(BlockCrops.AGE); + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, BlockCrops.AGE); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockDataAbstract.java b/azurite-server/src/main/java/net/minecraft/server/BlockDataAbstract.java new file mode 100644 index 0000000..185a7e9 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockDataAbstract.java @@ -0,0 +1,59 @@ +package net.minecraft.server; + +import com.google.common.base.Function; +import com.google.common.base.Joiner; + +import java.util.Collection; +import java.util.Iterator; +import java.util.Map.Entry; +import java.util.stream.Collectors; + +public abstract class BlockDataAbstract implements IBlockData { + + private static final Joiner a = Joiner.on(','); + private static final Function, String> b = entry -> { + if (entry == null) { + return ""; + } else { + IBlockState iblockstate = entry.getKey(); + + return iblockstate.a() + "=" + iblockstate.a(entry.getValue()); + } + }; + + public BlockDataAbstract() { + } + + public > IBlockData a(IBlockState iblockstate) { + return this.set(iblockstate, a(iblockstate.c(), this.get(iblockstate))); + } + + protected static V a(Collection collection, V t0) { + Iterator iterator = collection.iterator(); + + do { + if (!iterator.hasNext()) { + return iterator.next(); + } + } while (!iterator.next().equals(t0)); + + if (iterator.hasNext()) { + return iterator.next(); + } else { + return collection.iterator().next(); + } + } + + public String toString() { + StringBuilder stringbuilder = new StringBuilder(); + + stringbuilder.append(Block.REGISTRY.c(this.getBlock())); + if (!this.b().isEmpty()) { + stringbuilder.append("["); + BlockDataAbstract.a.appendTo(stringbuilder, this.b().entrySet().stream().map(BlockDataAbstract.b::apply).collect(Collectors.toList())); + stringbuilder.append("]"); + } + + return stringbuilder.toString(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockDaylightDetector.java b/azurite-server/src/main/java/net/minecraft/server/BlockDaylightDetector.java new file mode 100644 index 0000000..cede1f8 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockDaylightDetector.java @@ -0,0 +1,102 @@ +package net.minecraft.server; + +import java.util.Random; + +public class BlockDaylightDetector extends BlockContainer { + + public static final BlockStateInteger POWER = BlockStateInteger.of("power", 0, 15); + private final boolean b; + + public BlockDaylightDetector(boolean flag) { + super(Material.WOOD); + this.b = flag; + this.j(this.blockStateList.getBlockData().set(BlockDaylightDetector.POWER, 0)); + this.a(0.0F, 0.0F, 0.0F, 1.0F, 0.375F, 1.0F); + this.a(CreativeModeTab.d); + this.c(0.2F); + this.a(BlockDaylightDetector.f); + this.c("daylightDetector"); + } + + public void updateShape(IBlockAccess iblockaccess, BlockPosition blockposition) { + this.a(0.0F, 0.0F, 0.0F, 1.0F, 0.375F, 1.0F); + } + + public int a(IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata, EnumDirection enumdirection) { + return iblockdata.get(BlockDaylightDetector.POWER); + } + + public void f(World world, BlockPosition blockposition) { + if (!world.worldProvider.o()) { + IBlockData iblockdata = world.getType(blockposition); + int i = world.b(EnumSkyBlock.SKY, blockposition) - world.ab(); + float f = world.d(1.0F); + float f1 = f < 3.1415927F ? 0.0F : 6.2831855F; + + f += (f1 - f) * 0.2F; + i = Math.round((float) i * MathHelper.cos(f)); + i = MathHelper.clamp(i, 0, 15); + if (this.b) { + i = 15 - i; + } + + if (iblockdata.get(BlockDaylightDetector.POWER) != i) { + i = org.bukkit.craftbukkit.event.CraftEventFactory.callRedstoneChange(world, blockposition.getX(), blockposition.getY(), blockposition.getZ(), iblockdata.get(POWER), i).getNewCurrent(); // CraftBukkit - Call BlockRedstoneEvent + world.setTypeAndData(blockposition, iblockdata.set(BlockDaylightDetector.POWER, i), 3); + } + + } + } + + public boolean interact(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman, EnumDirection enumdirection, float f, float f1, float f2) { + if (entityhuman.cn()) { + if (this.b) { + world.setTypeAndData(blockposition, Blocks.DAYLIGHT_DETECTOR.getBlockData().set(BlockDaylightDetector.POWER, iblockdata.get(BlockDaylightDetector.POWER)), 4); + Blocks.DAYLIGHT_DETECTOR.f(world, blockposition); + } else { + world.setTypeAndData(blockposition, Blocks.DAYLIGHT_DETECTOR_INVERTED.getBlockData().set(BlockDaylightDetector.POWER, iblockdata.get(BlockDaylightDetector.POWER)), 4); + Blocks.DAYLIGHT_DETECTOR_INVERTED.f(world, blockposition); + } + + return true; + } else { + return super.interact(world, blockposition, iblockdata, entityhuman, enumdirection, f, f1, f2); + } + } + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + return Item.getItemOf(Blocks.DAYLIGHT_DETECTOR); + } + + public boolean d() { + return false; + } + + public boolean c() { + return false; + } + + public int b() { + return 3; + } + + public boolean isPowerSource() { + return true; + } + + public TileEntity a(World world, int i) { + return new TileEntityLightDetector(); + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockDaylightDetector.POWER, i); + } + + public int toLegacyData(IBlockData iblockdata) { + return iblockdata.get(BlockDaylightDetector.POWER); + } + + public BlockStateList getStateList() { + return new BlockStateList(this, BlockDaylightDetector.POWER); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockDeadBush.java b/azurite-server/src/main/java/net/minecraft/server/BlockDeadBush.java new file mode 100644 index 0000000..fc5defc --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockDeadBush.java @@ -0,0 +1,38 @@ +package net.minecraft.server; + +import java.util.Random; + +public class BlockDeadBush extends BlockPlant { + + protected BlockDeadBush() { + super(Material.REPLACEABLE_PLANT); + float f = 0.4F; + + this.a(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, 0.8F, 0.5F + f); + } + + public MaterialMapColor g(IBlockData iblockdata) { + return MaterialMapColor.o; + } + + protected boolean c(Block block) { + return block == Blocks.SAND || block == Blocks.HARDENED_CLAY || block == Blocks.STAINED_HARDENED_CLAY || block == Blocks.DIRT; + } + + public boolean a(World world, BlockPosition blockposition) { + return true; + } + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + return null; + } + + public void a(World world, EntityHuman entityhuman, BlockPosition blockposition, IBlockData iblockdata, TileEntity tileentity) { + if (entityhuman.bZ() != null && entityhuman.bZ().getItem() == Items.SHEARS) { + a(world, blockposition, new ItemStack(Blocks.DEADBUSH, 1, 0)); + } else { + super.a(world, entityhuman, blockposition, iblockdata, tileentity); + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockDiodeAbstract.java b/azurite-server/src/main/java/net/minecraft/server/BlockDiodeAbstract.java new file mode 100644 index 0000000..2aa8d23 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockDiodeAbstract.java @@ -0,0 +1,256 @@ +package net.minecraft.server; + +import org.bukkit.craftbukkit.event.CraftEventFactory; + +import java.util.Random; + +public abstract class BlockDiodeAbstract extends BlockDirectional { + + public static final EnumDirection[] aenumdirection = EnumDirection.values(); + protected final boolean N; + + protected BlockDiodeAbstract(boolean flag) { + super(Material.ORIENTABLE); + this.N = flag; + this.a(0.0F, 0.0F, 0.0F, 1.0F, 0.125F, 1.0F); + } + + @Override + public boolean d() { + return false; + } + + @Override + public boolean canPlace(World world, BlockPosition blockposition) { + return World.a(world, blockposition.down()) && super.canPlace(world, blockposition); + } + + public boolean e(World world, BlockPosition blockposition) { + return World.a(world, blockposition.down()); + } + + @Override + public void b(World world, BlockPosition blockposition, IBlockData iblockdata, Random random) { + if (!this.b(world, blockposition, iblockdata)) { + boolean flag = this.e(world, blockposition, iblockdata); + + if (this.N && !flag) { + // CraftBukkit start + if (CraftEventFactory.callRedstoneChange(world, blockposition.getX(), blockposition.getY(), + blockposition.getZ(), 15, 0).getNewCurrent() != 0) { + return; + } + // CraftBukkit end + world.setTypeAndData(blockposition, this.k(iblockdata), 2); + } else if (!this.N) { + // CraftBukkit start + if (CraftEventFactory.callRedstoneChange(world, blockposition.getX(), blockposition.getY(), + blockposition.getZ(), 0, 15).getNewCurrent() != 15) { + return; + } + // CraftBukkit end + world.setTypeAndData(blockposition, this.e(iblockdata), 2); + if (!flag) { + world.a(blockposition, this.e(iblockdata).getBlock(), this.m(iblockdata), -1); + } + } + + } + } + + protected boolean l(IBlockData iblockdata) { + return this.N; + } + + @Override + public int b(IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata, + EnumDirection enumdirection) { + return this.a(iblockaccess, blockposition, iblockdata, enumdirection); + } + + @Override + public int a(IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata, + EnumDirection enumdirection) { + return !this.l(iblockdata) ? 0 + : (iblockdata.get(BlockDirectional.FACING) == enumdirection + ? this.a(iblockaccess, blockposition, iblockdata) + : 0); + } + + @Override + public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) { + if (this.e(world, blockposition)) { + this.g(world, blockposition, iblockdata); + } else { + this.b(world, blockposition, iblockdata, 0); + world.setAir(blockposition); + // PaperSpigot start - Fix cannons + if (world.paperSpigotConfig.fixCannons) { + world.applyPhysics(blockposition.shift(EnumDirection.EAST), this); + world.applyPhysics(blockposition.shift(EnumDirection.WEST), this); + world.applyPhysics(blockposition.shift(EnumDirection.SOUTH), this); + world.applyPhysics(blockposition.shift(EnumDirection.NORTH), this); + world.applyPhysics(blockposition.shift(EnumDirection.DOWN), this); + world.applyPhysics(blockposition.shift(EnumDirection.UP), this); + return; + } + // PaperSpigot end + + for (EnumDirection enumdirection : aenumdirection) { + world.applyPhysics(blockposition.shift(enumdirection), this); + } + } + } + + protected void g(World world, BlockPosition blockposition, IBlockData iblockdata) { + if (!this.b(world, blockposition, iblockdata)) { + boolean flag = this.e(world, blockposition, iblockdata); + + if ((this.N && !flag || !this.N && flag) && !world.a(blockposition, this)) { + byte b0 = -1; + + if (this.i(world, blockposition, iblockdata)) { + b0 = -3; + } else if (this.N) { + b0 = -2; + } + + world.a(blockposition, this, this.d(iblockdata), b0); + } + } + } + + public boolean b(IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata) { + return false; + } + + protected boolean e(World world, BlockPosition blockposition, IBlockData iblockdata) { + return this.f(world, blockposition, iblockdata) > 0; + } + + protected int f(World world, BlockPosition blockposition, IBlockData iblockdata) { + EnumDirection enumdirection = iblockdata.get(BlockDirectional.FACING); + BlockPosition blockposition1 = blockposition.shift(enumdirection); + int i = world.getBlockFacePower(blockposition1, enumdirection); + + if (i >= 15) { + return i; + } else { + IBlockData iblockdata1 = world.getType(blockposition1); + return Math.max(i, iblockdata1.getBlock() == Blocks.REDSTONE_WIRE ? iblockdata1.get(BlockRedstoneWire.POWER) : 0); + } + } + + protected int c(IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata) { + EnumDirection enumdirection = iblockdata.get(BlockDirectional.FACING); + EnumDirection enumdirection1 = enumdirection.e(); + EnumDirection enumdirection2 = enumdirection.f(); + + return Math.max(this.c(iblockaccess, blockposition.shift(enumdirection1), enumdirection1), + this.c(iblockaccess, blockposition.shift(enumdirection2), enumdirection2)); + } + + protected int c(IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection) { + IBlockData iblockdata = iblockaccess.getType(blockposition); + Block block = iblockdata.getBlock(); + return this.c(block) ? (block == Blocks.REDSTONE_WIRE ? iblockdata.get(BlockRedstoneWire.POWER) : iblockaccess.getBlockPower(blockposition, enumdirection)) : 0; + } + + @Override + public boolean isPowerSource() { + return true; + } + + @Override + public IBlockData getPlacedState(World world, BlockPosition blockposition, EnumDirection enumdirection, float f, + float f1, float f2, int i, EntityLiving entityliving) { + return this.getBlockData().set(BlockDirectional.FACING, entityliving.getDirection().opposite()); + } + + @Override + public void postPlace(World world, BlockPosition blockposition, IBlockData iblockdata, EntityLiving entityliving, + ItemStack itemstack) { + if (this.e(world, blockposition, iblockdata)) { + world.a(blockposition, this, 1); + } + + } + + @Override + public void onPlace(World world, BlockPosition blockposition, IBlockData iblockdata) { + this.h(world, blockposition, iblockdata); + } + + protected void h(World world, BlockPosition blockposition, IBlockData iblockdata) { + EnumDirection enumdirection = iblockdata.get(BlockDirectional.FACING); + BlockPosition blockposition1 = blockposition.shift(enumdirection.opposite()); + + world.d(blockposition1, this); + world.a(blockposition1, this, enumdirection); + } + + @Override + public void postBreak(World world, BlockPosition blockposition, IBlockData iblockdata) { + if (this.N) { + // PaperSpigot start - Fix cannons + if (world.paperSpigotConfig.fixCannons) { + world.applyPhysics(blockposition.shift(EnumDirection.EAST), this); + world.applyPhysics(blockposition.shift(EnumDirection.WEST), this); + world.applyPhysics(blockposition.shift(EnumDirection.NORTH), this); + world.applyPhysics(blockposition.shift(EnumDirection.SOUTH), this); + world.applyPhysics(blockposition.shift(EnumDirection.DOWN), this); + world.applyPhysics(blockposition.shift(EnumDirection.UP), this); + return; + } + // PaperSpigot end + + for (EnumDirection enumdirection : aenumdirection) { + world.applyPhysics(blockposition.shift(enumdirection), this); + } + } + + super.postBreak(world, blockposition, iblockdata); + } + + @Override + public boolean c() { + return false; + } + + protected boolean c(Block block) { + return block.isPowerSource(); + } + + protected int a(IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata) { + return 15; + } + + public static boolean d(Block block) { + return Blocks.UNPOWERED_REPEATER.e(block) || Blocks.UNPOWERED_COMPARATOR.e(block); + } + + public boolean e(Block block) { + return block == this.e(this.getBlockData()).getBlock() || block == this.k(this.getBlockData()).getBlock(); + } + + public boolean i(World world, BlockPosition blockposition, IBlockData iblockdata) { + EnumDirection enumdirection = iblockdata.get(BlockDirectional.FACING).opposite(); + BlockPosition blockposition1 = blockposition.shift(enumdirection); + return d(world.getType(blockposition1).getBlock()) && world.getType(blockposition1).get(BlockDirectional.FACING) != enumdirection; + } + + protected int m(IBlockData iblockdata) { + return this.d(iblockdata); + } + + protected abstract int d(IBlockData iblockdata); + + protected abstract IBlockData e(IBlockData iblockdata); + + protected abstract IBlockData k(IBlockData iblockdata); + + @Override + public boolean b(Block block) { + return this.e(block); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockDirectional.java b/azurite-server/src/main/java/net/minecraft/server/BlockDirectional.java new file mode 100644 index 0000000..c7faa4f --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockDirectional.java @@ -0,0 +1,14 @@ +package net.minecraft.server; + +public abstract class BlockDirectional extends Block { + + public static final BlockStateDirection FACING = BlockStateDirection.of("facing", EnumDirection.EnumDirectionLimit.HORIZONTAL); + + protected BlockDirectional(Material material) { + super(material); + } + + protected BlockDirectional(Material material, MaterialMapColor materialmapcolor) { + super(material, materialmapcolor); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockDirt.java b/azurite-server/src/main/java/net/minecraft/server/BlockDirt.java new file mode 100644 index 0000000..f814d7c --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockDirt.java @@ -0,0 +1,112 @@ +package net.minecraft.server; + +public class BlockDirt extends Block { + + public static final BlockStateEnum VARIANT = BlockStateEnum.of("variant", BlockDirt.EnumDirtVariant.class); + public static final BlockStateBoolean SNOWY = BlockStateBoolean.of("snowy"); + + protected BlockDirt() { + super(Material.EARTH); + this.j(this.blockStateList.getBlockData().set(BlockDirt.VARIANT, BlockDirt.EnumDirtVariant.DIRT).set(BlockDirt.SNOWY, Boolean.FALSE)); + this.a(CreativeModeTab.b); + } + + public MaterialMapColor g(IBlockData iblockdata) { + return iblockdata.get(BlockDirt.VARIANT).d(); + } + + public IBlockData updateState(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { + if (iblockdata.get(BlockDirt.VARIANT) == BlockDirt.EnumDirtVariant.PODZOL) { + Block block = iblockaccess.getType(blockposition.up()).getBlock(); + + iblockdata = iblockdata.set(BlockDirt.SNOWY, block == Blocks.SNOW || block == Blocks.SNOW_LAYER); + } + + return iblockdata; + } + + public int getDropData(World world, BlockPosition blockposition) { + IBlockData iblockdata = world.getType(blockposition); + + return iblockdata.getBlock() != this ? 0 : iblockdata.get(BlockDirt.VARIANT).a(); + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockDirt.VARIANT, BlockDirt.EnumDirtVariant.a(i)); + } + + public int toLegacyData(IBlockData iblockdata) { + return iblockdata.get(BlockDirt.VARIANT).a(); + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, BlockDirt.VARIANT, BlockDirt.SNOWY); + } + + public int getDropData(IBlockData iblockdata) { + BlockDirt.EnumDirtVariant blockdirt_enumdirtvariant = iblockdata.get(BlockDirt.VARIANT); + + if (blockdirt_enumdirtvariant == BlockDirt.EnumDirtVariant.PODZOL) { + blockdirt_enumdirtvariant = BlockDirt.EnumDirtVariant.DIRT; + } + + return blockdirt_enumdirtvariant.a(); + } + + public enum EnumDirtVariant implements INamable { + + DIRT(0, "dirt", "default", MaterialMapColor.l), COARSE_DIRT(1, "coarse_dirt", "coarse", MaterialMapColor.l), PODZOL(2, "podzol", MaterialMapColor.J); + + private static final BlockDirt.EnumDirtVariant[] d = new BlockDirt.EnumDirtVariant[values().length]; + private final int e; + private final String f; + private final String g; + private final MaterialMapColor h; + + EnumDirtVariant(int i, String s, MaterialMapColor materialmapcolor) { + this(i, s, s, materialmapcolor); + } + + EnumDirtVariant(int i, String s, String s1, MaterialMapColor materialmapcolor) { + this.e = i; + this.f = s; + this.g = s1; + this.h = materialmapcolor; + } + + public int a() { + return this.e; + } + + public String c() { + return this.g; + } + + public MaterialMapColor d() { + return this.h; + } + + public String toString() { + return this.f; + } + + public static BlockDirt.EnumDirtVariant a(int i) { + if (i < 0 || i >= BlockDirt.EnumDirtVariant.d.length) { + i = 0; + } + + return BlockDirt.EnumDirtVariant.d[i]; + } + + public String getName() { + return this.f; + } + + static { + for (EnumDirtVariant blockdirt_enumdirtvariant : values()) { + EnumDirtVariant.d[blockdirt_enumdirtvariant.a()] = blockdirt_enumdirtvariant; + } + + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockDispenser.java b/azurite-server/src/main/java/net/minecraft/server/BlockDispenser.java new file mode 100644 index 0000000..b68cd8c --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockDispenser.java @@ -0,0 +1,187 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.AzuriteConfig; + +import java.util.Random; + +public class BlockDispenser extends BlockContainer { + + public static final BlockStateDirection FACING = BlockStateDirection.of("facing"); + public static final BlockStateBoolean TRIGGERED = BlockStateBoolean.of("triggered"); + public static final RegistryDefault REGISTRY = new RegistryDefault<>(new DispenseBehaviorItem()); + public static boolean eventFired = false; // CraftBukkit + protected Random O = new Random(); + + protected BlockDispenser() { + super(Material.STONE); + this.j(this.blockStateList.getBlockData().set(BlockDispenser.FACING, EnumDirection.NORTH).set(BlockDispenser.TRIGGERED, Boolean.FALSE)); + this.a(CreativeModeTab.d); + } + + public static IPosition a(ISourceBlock isourceblock) { + EnumDirection enumdirection = b(isourceblock.f()); + return new Position(isourceblock.getX() + 0.7D * enumdirection.getAdjacentX(), isourceblock.getY() + 0.7D * enumdirection.getAdjacentY(), isourceblock.getZ() + 0.7D * enumdirection.getAdjacentZ()); + } + + public static EnumDirection b(int i) { + return EnumDirection.fromType1(i & 7); + } + + public int a(World world) { + return 4; + } + + /* // PandaSpigot - comment out - SPIGOT-1401 + public void onPlace(World world, BlockPosition blockposition, IBlockData iblockdata) { + super.onPlace(world, blockposition, iblockdata); + this.e(world, blockposition, iblockdata); + } + + private void e(World world, BlockPosition blockposition, IBlockData iblockdata) { + EnumDirection enumdirection = iblockdata.get(BlockDispenser.FACING); + boolean flag = world.getType(blockposition.getX(), blockposition.getY(), blockposition.getZ() - 1).getBlock().o(); + boolean flag1 = world.getType(blockposition.getX(), blockposition.getY(), blockposition.getZ() + 1).getBlock().o(); + + if (enumdirection == EnumDirection.NORTH && flag && !flag1) { + enumdirection = EnumDirection.SOUTH; + } else if (enumdirection == EnumDirection.SOUTH && flag1 && !flag) { + enumdirection = EnumDirection.NORTH; + } else { + boolean flag2 = world.getType(blockposition.getX() - 1, blockposition.getY(), blockposition.getZ()).getBlock().o(); + boolean flag3 = world.getType(blockposition.getX() + 1, blockposition.getY(), blockposition.getZ()).getBlock().o(); + + if (enumdirection == EnumDirection.WEST && flag2 && !flag3) { + enumdirection = EnumDirection.EAST; + } else if (enumdirection == EnumDirection.EAST && flag3 && !flag2) { + enumdirection = EnumDirection.WEST; + } + } + + world.setTypeAndData(blockposition, iblockdata.set(BlockDispenser.FACING, enumdirection).set(BlockDispenser.TRIGGERED, false), 2, false, false); + } + */ // PandaSpigot + + public boolean interact(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman, EnumDirection enumdirection, float f, float f1, float f2) { + TileEntity tileentity = world.getTileEntity(blockposition); + + if (tileentity instanceof TileEntityDispenser) { + entityhuman.openContainer((TileEntityDispenser) tileentity); + + if (tileentity instanceof TileEntityDropper) { + entityhuman.b(StatisticList.O); + } else { + entityhuman.b(StatisticList.Q); + } + } + + return true; + } + + public void dispense(World world, BlockPosition blockposition) { + SourceBlock sourceblock = new SourceBlock(world, blockposition); + TileEntityDispenser tileentitydispenser = sourceblock.getTileEntity(); + + if (tileentitydispenser != null) { + int i = tileentitydispenser.m(); + + if (i < 0) { + if (AzuriteConfig.dispenserEffects.getValue()) + world.triggerEffect(1001, blockposition, 0); + } else { + ItemStack itemstack = tileentitydispenser.getItem(i); + IDispenseBehavior idispensebehavior = this.a(itemstack); + + if (idispensebehavior != IDispenseBehavior.NONE) { + ItemStack itemstack1 = idispensebehavior.a(sourceblock, itemstack); + eventFired = false; // CraftBukkit - reset event status + + tileentitydispenser.setItem(i, itemstack1.count <= 0 ? null : itemstack1); + } + + } + } + } + + protected IDispenseBehavior a(ItemStack itemstack) { + return BlockDispenser.REGISTRY.get(itemstack == null ? null : itemstack.getItem()); + } + + public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) { + boolean flag = world.isBlockIndirectlyPowered(blockposition) || world.isBlockIndirectlyPowered(blockposition.up()); + boolean flag1 = iblockdata.get(BlockDispenser.TRIGGERED); + + if (flag && !flag1) { + world.a(blockposition, this, this.a(world)); + world.setTypeAndData(blockposition, iblockdata.set(BlockDispenser.TRIGGERED, true), 4, false, false); + } else if (!flag && flag1) { + world.setTypeAndData(blockposition, iblockdata.set(BlockDispenser.TRIGGERED, false), 4, false, false); + } + + } + + public void b(World world, BlockPosition blockposition, IBlockData iblockdata, Random random) { + this.dispense(world, blockposition); + } + + public TileEntity a(World world, int i) { + return new TileEntityDispenser(); + } + + public IBlockData getPlacedState(World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2, int i, EntityLiving entityliving) { + return this.getBlockData().set(BlockDispenser.FACING, BlockPiston.a(world, blockposition, entityliving)).set(BlockDispenser.TRIGGERED, false); + } + + public void postPlace(World world, BlockPosition blockposition, IBlockData iblockdata, EntityLiving entityliving, ItemStack itemstack) { + world.setTypeAndData(blockposition, iblockdata.set(BlockDispenser.FACING, BlockPiston.a(world, blockposition, entityliving)), 2, false, false); + if (itemstack.hasName()) { + TileEntity tileentity = world.getTileEntity(blockposition); + + if (tileentity instanceof TileEntityDispenser) { + ((TileEntityDispenser) tileentity).a(itemstack.getName()); + } + } + + } + + public void remove(World world, BlockPosition blockposition, IBlockData iblockdata) { + TileEntity tileentity = world.getTileEntity(blockposition); + + if (tileentity instanceof TileEntityDispenser) { + InventoryUtils.dropInventory(world, blockposition, (TileEntityDispenser) tileentity); + world.updateAdjacentComparators(blockposition, this); + } + + super.remove(world, blockposition, iblockdata); + } + + public boolean isComplexRedstone() { + return true; + } + + public int l(World world, BlockPosition blockposition) { + return Container.a(world.getTileEntity(blockposition)); + } + + public int b() { + return 3; + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockDispenser.FACING, b(i)).set(BlockDispenser.TRIGGERED, (i & 8) > 0); + } + + public int toLegacyData(IBlockData iblockdata) { + byte b0 = 0; + int i = b0 | iblockdata.get(BlockDispenser.FACING).a(); + + if (iblockdata.get(BlockDispenser.TRIGGERED)) { + i |= 8; + } + + return i; + } + + public BlockStateList getStateList() { + return new BlockStateList(this, BlockDispenser.FACING, BlockDispenser.TRIGGERED); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockDoor.java b/azurite-server/src/main/java/net/minecraft/server/BlockDoor.java new file mode 100644 index 0000000..cd35085 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockDoor.java @@ -0,0 +1,338 @@ +package net.minecraft.server; + +import org.bukkit.event.block.BlockRedstoneEvent; + +import java.util.Random; + +public class BlockDoor extends Block { + + public static final BlockStateDirection FACING = BlockStateDirection.of("facing", EnumDirection.EnumDirectionLimit.HORIZONTAL); + public static final BlockStateBoolean OPEN = BlockStateBoolean.of("open"); + public static final BlockStateEnum HINGE = BlockStateEnum.of("hinge", BlockDoor.EnumDoorHinge.class); + public static final BlockStateBoolean POWERED = BlockStateBoolean.of("powered"); + public static final BlockStateEnum HALF = BlockStateEnum.of("half", BlockDoor.EnumDoorHalf.class); + + protected BlockDoor(Material material) { + super(material); + this.j(this.blockStateList.getBlockData().set(BlockDoor.FACING, EnumDirection.NORTH).set(BlockDoor.OPEN, false).set(BlockDoor.HINGE, BlockDoor.EnumDoorHinge.LEFT).set(BlockDoor.POWERED, Boolean.FALSE).set(BlockDoor.HALF, BlockDoor.EnumDoorHalf.LOWER)); + } + + public String getName() { + return LocaleI18n.get((this.a() + ".name").replaceAll("tile", "item")); + } + + public boolean c() { + return false; + } + + public boolean b(IBlockAccess iblockaccess, BlockPosition blockposition) { + return g(e(iblockaccess, blockposition)); + } + + public boolean d() { + return false; + } + + public AxisAlignedBB a(World world, BlockPosition blockposition, IBlockData iblockdata) { + this.updateShape(world, blockposition); + return super.a(world, blockposition, iblockdata); + } + + public void updateShape(IBlockAccess iblockaccess, BlockPosition blockposition) { + this.k(e(iblockaccess, blockposition)); + } + + private void k(int i) { + float f = 0.1875F; + + this.a(0.0F, 0.0F, 0.0F, 1.0F, 2.0F, 1.0F); + EnumDirection enumdirection = f(i); + boolean flag = g(i); + boolean flag1 = j(i); + + if (flag) { + if (enumdirection == EnumDirection.EAST) { + if (!flag1) { + this.a(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, f); + } else { + this.a(0.0F, 0.0F, 1.0F - f, 1.0F, 1.0F, 1.0F); + } + } else if (enumdirection == EnumDirection.SOUTH) { + if (!flag1) { + this.a(1.0F - f, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + } else { + this.a(0.0F, 0.0F, 0.0F, f, 1.0F, 1.0F); + } + } else if (enumdirection == EnumDirection.WEST) { + if (!flag1) { + this.a(0.0F, 0.0F, 1.0F - f, 1.0F, 1.0F, 1.0F); + } else { + this.a(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, f); + } + } else if (enumdirection == EnumDirection.NORTH) { + if (!flag1) { + this.a(0.0F, 0.0F, 0.0F, f, 1.0F, 1.0F); + } else { + this.a(1.0F - f, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + } + } + } else if (enumdirection == EnumDirection.EAST) { + this.a(0.0F, 0.0F, 0.0F, f, 1.0F, 1.0F); + } else if (enumdirection == EnumDirection.SOUTH) { + this.a(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, f); + } else if (enumdirection == EnumDirection.WEST) { + this.a(1.0F - f, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + } else if (enumdirection == EnumDirection.NORTH) { + this.a(0.0F, 0.0F, 1.0F - f, 1.0F, 1.0F, 1.0F); + } + + } + + public boolean interact(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman, EnumDirection enumdirection, float f, float f1, float f2) { + if (this.material == Material.ORE) { + return true; + } else { + BlockPosition blockposition1 = iblockdata.get(BlockDoor.HALF) == BlockDoor.EnumDoorHalf.LOWER ? blockposition : blockposition.down(); + IBlockData iblockdata1 = blockposition.equals(blockposition1) ? iblockdata : world.getType(blockposition1); + + if (iblockdata1.getBlock() != this) { + return false; + } else { + iblockdata = iblockdata1.a(BlockDoor.OPEN); + world.setTypeAndData(blockposition1, iblockdata, 2); + world.b(blockposition1, blockposition); + world.a(entityhuman, iblockdata.get(BlockDoor.OPEN) ? 1003 : 1006, blockposition, 0); + return true; + } + } + } + + public void setDoor(World world, BlockPosition blockposition, boolean flag) { + IBlockData iblockdata = world.getType(blockposition); + + if (iblockdata.getBlock() == this) { + BlockPosition blockposition1 = iblockdata.get(BlockDoor.HALF) == BlockDoor.EnumDoorHalf.LOWER ? blockposition : blockposition.down(); + IBlockData iblockdata1 = blockposition == blockposition1 ? iblockdata : world.getType(blockposition1); + + if (iblockdata1.getBlock() == this && iblockdata1.get(BlockDoor.OPEN) != flag) { + world.setTypeAndData(blockposition1, iblockdata1.set(BlockDoor.OPEN, flag), 2); + world.b(blockposition1, blockposition); + world.a(null, flag ? 1003 : 1006, blockposition, 0); + } + } + } + + public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) { + if (iblockdata.get(BlockDoor.HALF) == BlockDoor.EnumDoorHalf.UPPER) { + BlockPosition blockposition1 = blockposition.down(); + IBlockData iblockdata1 = world.getType(blockposition1); + + if (iblockdata1.getBlock() != this) { + world.setAir(blockposition); + } else if (block != this) { + this.doPhysics(world, blockposition1, iblockdata1, block); + } + } else { + boolean flag = false; + BlockPosition blockposition2 = blockposition.up(); + IBlockData iblockdata2 = world.getType(blockposition2); + + if (iblockdata2.getBlock() != this) { + world.setAir(blockposition); + flag = true; + } + + if (!World.a(world, blockposition.getX(), blockposition.getY() - 1, blockposition.getZ())) { + world.setAir(blockposition); + flag = true; + if (iblockdata2.getBlock() == this) { + world.setAir(blockposition2); + } + } + + if (flag) { + this.b(world, blockposition, iblockdata, 0); + } else { + + // CraftBukkit start + org.bukkit.World bworld = world.getWorld(); + org.bukkit.block.Block bukkitBlock = bworld.getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()); + org.bukkit.block.Block blockTop = bworld.getBlockAt(blockposition2.getX(), blockposition2.getY(), blockposition2.getZ()); + + int power = bukkitBlock.getBlockPower(); + int powerTop = blockTop.getBlockPower(); + if (powerTop > power) power = powerTop; + int oldPower = iblockdata2.get(POWERED) ? 15 : 0; + + if (oldPower == 0 ^ power == 0) { + BlockRedstoneEvent eventRedstone = new BlockRedstoneEvent(bukkitBlock, oldPower, power); + world.getServer().getPluginManager().callEvent(eventRedstone); + + boolean flag1 = eventRedstone.getNewCurrent() > 0; + world.setTypeAndData(blockposition2, iblockdata2.set(BlockDoor.POWERED, flag1), 2); + if (flag1 != (iblockdata.get(BlockDoor.OPEN))) { + world.setTypeAndData(blockposition, iblockdata.set(BlockDoor.OPEN, flag1), 2); + world.b(blockposition, blockposition); + world.a(null, flag1 ? 1003 : 1006, blockposition, 0); + } + } + // CraftBukkit end + } + } + + } + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + return iblockdata.get(BlockDoor.HALF) == BlockDoor.EnumDoorHalf.UPPER ? null : this.l(); + } + + public MovingObjectPosition a(World world, BlockPosition blockposition, Vec3D vec3d, Vec3D vec3d1) { + this.updateShape(world, blockposition); + return super.a(world, blockposition, vec3d, vec3d1); + } + + public boolean canPlace(World world, BlockPosition blockposition) { + return blockposition.getY() < 255 && World.a(world, blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()) + && super.canPlace(world, blockposition) && super.canPlace(world, blockposition.up()); + } + + public int k() { + return 1; + } + + public static int e(IBlockAccess iblockaccess, BlockPosition blockposition) { + IBlockData iblockdata = iblockaccess.getType(blockposition); + int i = iblockdata.getBlock().toLegacyData(iblockdata); + boolean flag = i(i); + IBlockData iblockdata1 = iblockaccess.getType(blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()); + int j = iblockdata1.getBlock().toLegacyData(iblockdata1); + int k = flag ? j : i; + IBlockData iblockdata2 = iblockaccess.getType(blockposition.getX(), blockposition.getY() + 1, blockposition.getZ()); + int l = iblockdata2.getBlock().toLegacyData(iblockdata2); + int i1 = flag ? i : l; + boolean flag1 = (i1 & 1) != 0; + boolean flag2 = (i1 & 2) != 0; + + return b(k) | (flag ? 8 : 0) | (flag1 ? 16 : 0) | (flag2 ? 32 : 0); + } + + private Item l() { + return this == Blocks.IRON_DOOR ? Items.IRON_DOOR : (this == Blocks.SPRUCE_DOOR ? Items.SPRUCE_DOOR : (this == Blocks.BIRCH_DOOR ? Items.BIRCH_DOOR : (this == Blocks.JUNGLE_DOOR ? Items.JUNGLE_DOOR : (this == Blocks.ACACIA_DOOR ? Items.ACACIA_DOOR : (this == Blocks.DARK_OAK_DOOR ? Items.DARK_OAK_DOOR : Items.WOODEN_DOOR))))); + } + + public void a(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman) { + BlockPosition blockposition1 = blockposition.down(); + + if (entityhuman.abilities.canInstantlyBuild && iblockdata.get(BlockDoor.HALF) == BlockDoor.EnumDoorHalf.UPPER && world.getType(blockposition1).getBlock() == this) { + world.setAir(blockposition1); + } + + } + + public IBlockData updateState(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { + IBlockData iblockdata1; + + if (iblockdata.get(BlockDoor.HALF) == BlockDoor.EnumDoorHalf.LOWER) { + iblockdata1 = iblockaccess.getType(blockposition.getX(), blockposition.getY() + 1, blockposition.getZ()); + if (iblockdata1.getBlock() == this) { + iblockdata = iblockdata.set(BlockDoor.HINGE, iblockdata1.get(BlockDoor.HINGE)).set(BlockDoor.POWERED, iblockdata1.get(BlockDoor.POWERED)); + } + } else { + iblockdata1 = iblockaccess.getType(blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()); + if (iblockdata1.getBlock() == this) { + iblockdata = iblockdata.set(BlockDoor.FACING, iblockdata1.get(BlockDoor.FACING)).set(BlockDoor.OPEN, iblockdata1.get(BlockDoor.OPEN)); + } + } + + return iblockdata; + } + + public IBlockData fromLegacyData(int i) { + return (i & 8) > 0 ? this.getBlockData().set(BlockDoor.HALF, BlockDoor.EnumDoorHalf.UPPER).set(BlockDoor.HINGE, (i & 1) > 0 ? BlockDoor.EnumDoorHinge.RIGHT : BlockDoor.EnumDoorHinge.LEFT).set(BlockDoor.POWERED, (i & 2) > 0) : this.getBlockData().set(BlockDoor.HALF, BlockDoor.EnumDoorHalf.LOWER).set(BlockDoor.FACING, EnumDirection.fromType2(i & 3).f()).set(BlockDoor.OPEN, (i & 4) > 0); + } + + public int toLegacyData(IBlockData iblockdata) { + byte b0 = 0; + int i; + + if (iblockdata.get(BlockDoor.HALF) == BlockDoor.EnumDoorHalf.UPPER) { + i = b0 | 8; + if (iblockdata.get(BlockDoor.HINGE) == BlockDoor.EnumDoorHinge.RIGHT) { + i |= 1; + } + + if (iblockdata.get(BlockDoor.POWERED)) { + i |= 2; + } + } else { + i = b0 | iblockdata.get(BlockDoor.FACING).e().b(); + if (iblockdata.get(BlockDoor.OPEN)) { + i |= 4; + } + } + + return i; + } + + protected static int b(int i) { + return i & 7; + } + + public static boolean f(IBlockAccess iblockaccess, BlockPosition blockposition) { + return g(e(iblockaccess, blockposition)); + } + + public static EnumDirection h(IBlockAccess iblockaccess, BlockPosition blockposition) { + return f(e(iblockaccess, blockposition)); + } + + public static EnumDirection f(int i) { + return EnumDirection.fromType2(i & 3).f(); + } + + protected static boolean g(int i) { + return (i & 4) != 0; + } + + protected static boolean i(int i) { + return (i & 8) != 0; + } + + protected static boolean j(int i) { + return (i & 16) != 0; + } + + public BlockStateList getStateList() { + return new BlockStateList(this, BlockDoor.HALF, BlockDoor.FACING, BlockDoor.OPEN, BlockDoor.HINGE, BlockDoor.POWERED); + } + + public enum EnumDoorHinge implements INamable { + + LEFT, RIGHT; + + EnumDoorHinge() {} + + public String toString() { + return this.getName(); + } + + public String getName() { + return this == BlockDoor.EnumDoorHinge.LEFT ? "left" : "right"; + } + } + + public enum EnumDoorHalf implements INamable { + + UPPER, LOWER; + + EnumDoorHalf() {} + + public String toString() { + return this.getName(); + } + + public String getName() { + return this == BlockDoor.EnumDoorHalf.UPPER ? "upper" : "lower"; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockDoubleStep.java b/azurite-server/src/main/java/net/minecraft/server/BlockDoubleStep.java new file mode 100644 index 0000000..46b853d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockDoubleStep.java @@ -0,0 +1,10 @@ +package net.minecraft.server; + +public class BlockDoubleStep extends BlockDoubleStepAbstract { + + public BlockDoubleStep() {} + + public boolean l() { + return true; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockDoubleStepAbstract.java b/azurite-server/src/main/java/net/minecraft/server/BlockDoubleStepAbstract.java new file mode 100644 index 0000000..b03e545 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockDoubleStepAbstract.java @@ -0,0 +1,135 @@ +package net.minecraft.server; + +import java.util.Random; + +public abstract class BlockDoubleStepAbstract extends BlockStepAbstract { + + public static final BlockStateBoolean SEAMLESS = BlockStateBoolean.of("seamless"); + public static final BlockStateEnum VARIANT = BlockStateEnum.of("variant", BlockDoubleStepAbstract.EnumStoneSlabVariant.class); + + public BlockDoubleStepAbstract() { + super(Material.STONE); + IBlockData iblockdata = this.blockStateList.getBlockData(); + + if (this.l()) { + iblockdata = iblockdata.set(BlockDoubleStepAbstract.SEAMLESS, Boolean.FALSE); + } else { + iblockdata = iblockdata.set(BlockDoubleStepAbstract.HALF, BlockStepAbstract.EnumSlabHalf.BOTTOM); + } + + this.j(iblockdata.set(BlockDoubleStepAbstract.VARIANT, BlockDoubleStepAbstract.EnumStoneSlabVariant.STONE)); + this.a(CreativeModeTab.b); + } + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + return Item.getItemOf(Blocks.STONE_SLAB); + } + + public String b(int i) { + return super.a() + "." + BlockDoubleStepAbstract.EnumStoneSlabVariant.a(i).d(); + } + + public IBlockState n() { + return BlockDoubleStepAbstract.VARIANT; + } + + public Object a(ItemStack itemstack) { + return BlockDoubleStepAbstract.EnumStoneSlabVariant.a(itemstack.getData() & 7); + } + + public IBlockData fromLegacyData(int i) { + IBlockData iblockdata = this.getBlockData().set(BlockDoubleStepAbstract.VARIANT, BlockDoubleStepAbstract.EnumStoneSlabVariant.a(i & 7)); + + if (this.l()) { + iblockdata = iblockdata.set(BlockDoubleStepAbstract.SEAMLESS, (i & 8) != 0); + } else { + iblockdata = iblockdata.set(BlockDoubleStepAbstract.HALF, (i & 8) == 0 ? BlockStepAbstract.EnumSlabHalf.BOTTOM : BlockStepAbstract.EnumSlabHalf.TOP); + } + + return iblockdata; + } + + public int toLegacyData(IBlockData iblockdata) { + byte b0 = 0; + int i = b0 | iblockdata.get(BlockDoubleStepAbstract.VARIANT).a(); + + if (this.l()) { + if (iblockdata.get(BlockDoubleStepAbstract.SEAMLESS)) { + i |= 8; + } + } else if (iblockdata.get(BlockDoubleStepAbstract.HALF) == BlockStepAbstract.EnumSlabHalf.TOP) { + i |= 8; + } + + return i; + } + + protected BlockStateList getStateList() { + return this.l() ? new BlockStateList(this, BlockDoubleStepAbstract.SEAMLESS, BlockDoubleStepAbstract.VARIANT) : new BlockStateList(this, BlockDoubleStepAbstract.HALF, BlockDoubleStepAbstract.VARIANT); + } + + public int getDropData(IBlockData iblockdata) { + return iblockdata.get(BlockDoubleStepAbstract.VARIANT).a(); + } + + public MaterialMapColor g(IBlockData iblockdata) { + return iblockdata.get(BlockDoubleStepAbstract.VARIANT).c(); + } + + public enum EnumStoneSlabVariant implements INamable { + + STONE(0, MaterialMapColor.m, "stone"), SAND(1, MaterialMapColor.d, "sandstone", "sand"), WOOD(2, MaterialMapColor.o, "wood_old", "wood"), COBBLESTONE(3, MaterialMapColor.m, "cobblestone", "cobble"), BRICK(4, MaterialMapColor.D, "brick"), SMOOTHBRICK(5, MaterialMapColor.m, "stone_brick", "smoothStoneBrick"), NETHERBRICK(6, MaterialMapColor.K, "nether_brick", "netherBrick"), QUARTZ(7, MaterialMapColor.p, "quartz"); + + private static final BlockDoubleStepAbstract.EnumStoneSlabVariant[] i = new BlockDoubleStepAbstract.EnumStoneSlabVariant[values().length]; + private final int j; + private final MaterialMapColor k; + private final String l; + private final String m; + + EnumStoneSlabVariant(int i, MaterialMapColor materialmapcolor, String s) { + this(i, materialmapcolor, s, s); + } + + EnumStoneSlabVariant(int i, MaterialMapColor materialmapcolor, String s, String s1) { + this.j = i; + this.k = materialmapcolor; + this.l = s; + this.m = s1; + } + + public int a() { + return this.j; + } + + public MaterialMapColor c() { + return this.k; + } + + public String toString() { + return this.l; + } + + public static BlockDoubleStepAbstract.EnumStoneSlabVariant a(int i) { + if (i < 0 || i >= BlockDoubleStepAbstract.EnumStoneSlabVariant.i.length) { + i = 0; + } + + return BlockDoubleStepAbstract.EnumStoneSlabVariant.i[i]; + } + + public String getName() { + return this.l; + } + + public String d() { + return this.m; + } + + static { + for (EnumStoneSlabVariant blockdoublestepabstract_enumstoneslabvariant : values()) { + EnumStoneSlabVariant.i[blockdoublestepabstract_enumstoneslabvariant.a()] = blockdoublestepabstract_enumstoneslabvariant; + } + + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockDoubleStoneStep2.java b/azurite-server/src/main/java/net/minecraft/server/BlockDoubleStoneStep2.java new file mode 100644 index 0000000..87c61c4 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockDoubleStoneStep2.java @@ -0,0 +1,10 @@ +package net.minecraft.server; + +public class BlockDoubleStoneStep2 extends BlockDoubleStoneStepAbstract { + + public BlockDoubleStoneStep2() {} + + public boolean l() { + return true; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockDoubleStoneStepAbstract.java b/azurite-server/src/main/java/net/minecraft/server/BlockDoubleStoneStepAbstract.java new file mode 100644 index 0000000..ecc065d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockDoubleStoneStepAbstract.java @@ -0,0 +1,133 @@ +package net.minecraft.server; + +import java.util.Random; + +public abstract class BlockDoubleStoneStepAbstract extends BlockStepAbstract { + + public static final BlockStateBoolean SEAMLESS = BlockStateBoolean.of("seamless"); + public static final BlockStateEnum VARIANT = BlockStateEnum.of("variant", BlockDoubleStoneStepAbstract.EnumStoneSlab2Variant.class); + + public BlockDoubleStoneStepAbstract() { + super(Material.STONE); + IBlockData iblockdata = this.blockStateList.getBlockData(); + + if (this.l()) { + iblockdata = iblockdata.set(BlockDoubleStoneStepAbstract.SEAMLESS, Boolean.FALSE); + } else { + iblockdata = iblockdata.set(BlockDoubleStoneStepAbstract.HALF, BlockStepAbstract.EnumSlabHalf.BOTTOM); + } + + this.j(iblockdata.set(BlockDoubleStoneStepAbstract.VARIANT, BlockDoubleStoneStepAbstract.EnumStoneSlab2Variant.RED_SANDSTONE)); + this.a(CreativeModeTab.b); + } + + public String getName() { + return LocaleI18n.get(this.a() + ".red_sandstone.name"); + } + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + return Item.getItemOf(Blocks.STONE_SLAB2); + } + + public String b(int i) { + return super.a() + "." + BlockDoubleStoneStepAbstract.EnumStoneSlab2Variant.a(i).d(); + } + + public IBlockState n() { + return BlockDoubleStoneStepAbstract.VARIANT; + } + + public Object a(ItemStack itemstack) { + return BlockDoubleStoneStepAbstract.EnumStoneSlab2Variant.a(itemstack.getData() & 7); + } + + public IBlockData fromLegacyData(int i) { + IBlockData iblockdata = this.getBlockData().set(BlockDoubleStoneStepAbstract.VARIANT, BlockDoubleStoneStepAbstract.EnumStoneSlab2Variant.a(i & 7)); + + if (this.l()) { + iblockdata = iblockdata.set(BlockDoubleStoneStepAbstract.SEAMLESS, (i & 8) != 0); + } else { + iblockdata = iblockdata.set(BlockDoubleStoneStepAbstract.HALF, (i & 8) == 0 ? BlockStepAbstract.EnumSlabHalf.BOTTOM : BlockStepAbstract.EnumSlabHalf.TOP); + } + + return iblockdata; + } + + public int toLegacyData(IBlockData iblockdata) { + byte b0 = 0; + int i = b0 | iblockdata.get(BlockDoubleStoneStepAbstract.VARIANT).a(); + + if (this.l()) { + if (iblockdata.get(BlockDoubleStoneStepAbstract.SEAMLESS)) { + i |= 8; + } + } else if (iblockdata.get(BlockDoubleStoneStepAbstract.HALF) == BlockStepAbstract.EnumSlabHalf.TOP) { + i |= 8; + } + + return i; + } + + protected BlockStateList getStateList() { + return this.l() ? new BlockStateList(this, BlockDoubleStoneStepAbstract.SEAMLESS, BlockDoubleStoneStepAbstract.VARIANT) : new BlockStateList(this, BlockDoubleStoneStepAbstract.HALF, BlockDoubleStoneStepAbstract.VARIANT); + } + + public MaterialMapColor g(IBlockData iblockdata) { + return iblockdata.get(BlockDoubleStoneStepAbstract.VARIANT).c(); + } + + public int getDropData(IBlockData iblockdata) { + return iblockdata.get(BlockDoubleStoneStepAbstract.VARIANT).a(); + } + + public enum EnumStoneSlab2Variant implements INamable { + + RED_SANDSTONE(0, "red_sandstone", BlockSand.EnumSandVariant.RED_SAND.c()); + + private static final BlockDoubleStoneStepAbstract.EnumStoneSlab2Variant[] b = new BlockDoubleStoneStepAbstract.EnumStoneSlab2Variant[values().length]; + private final int c; + private final String d; + private final MaterialMapColor e; + + EnumStoneSlab2Variant(int i, String s, MaterialMapColor materialmapcolor) { + this.c = i; + this.d = s; + this.e = materialmapcolor; + } + + public int a() { + return this.c; + } + + public MaterialMapColor c() { + return this.e; + } + + public String toString() { + return this.d; + } + + public static BlockDoubleStoneStepAbstract.EnumStoneSlab2Variant a(int i) { + if (i < 0 || i >= BlockDoubleStoneStepAbstract.EnumStoneSlab2Variant.b.length) { + i = 0; + } + + return BlockDoubleStoneStepAbstract.EnumStoneSlab2Variant.b[i]; + } + + public String getName() { + return this.d; + } + + public String d() { + return this.d; + } + + static { + for (EnumStoneSlab2Variant blockdoublestonestepabstract_enumstoneslab2variant : values()) { + EnumStoneSlab2Variant.b[blockdoublestonestepabstract_enumstoneslab2variant.a()] = blockdoublestonestepabstract_enumstoneslab2variant; + } + + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockDoubleWoodStep.java b/azurite-server/src/main/java/net/minecraft/server/BlockDoubleWoodStep.java new file mode 100644 index 0000000..56cb6c7 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockDoubleWoodStep.java @@ -0,0 +1,10 @@ +package net.minecraft.server; + +public class BlockDoubleWoodStep extends BlockWoodenStep { + + public BlockDoubleWoodStep() {} + + public boolean l() { + return true; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockDragonEgg.java b/azurite-server/src/main/java/net/minecraft/server/BlockDragonEgg.java new file mode 100644 index 0000000..8ff51e0 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockDragonEgg.java @@ -0,0 +1,98 @@ +package net.minecraft.server; + +import org.bukkit.event.block.BlockFromToEvent; + +import java.util.Random; + +public class BlockDragonEgg extends Block { + + public BlockDragonEgg() { + super(Material.DRAGON_EGG, MaterialMapColor.E); + this.a(0.0625F, 0.0F, 0.0625F, 0.9375F, 1.0F, 0.9375F); + } + + public void onPlace(World world, BlockPosition blockposition, IBlockData iblockdata) { + world.a(blockposition, this, this.a(world)); + } + + public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) { + world.a(blockposition, this, this.a(world)); + } + + public void b(World world, BlockPosition blockposition, IBlockData iblockdata, Random random) { + this.e(world, blockposition); + } + + private void e(World world, BlockPosition blockposition) { + final int x = MathHelper.floor(blockposition.getX()), y = MathHelper.floor(blockposition.getY()), z = MathHelper.floor(blockposition.getZ()); + if (y >= 0 && BlockFalling.canFall(world, x, y-1,z)) { + + if (!BlockFalling.instaFall && world.areChunksLoadedBetween(x - 32, y - 32, z - 32, x + 32, y + 32, z +32)) { + // PaperSpigot start - Add FallingBlock source location API + world.addEntity(new EntityFallingBlock(new org.bukkit.Location(world.getWorld(), x + 0.5, y, x + 0.5), world, x + 0.5, y, z + 0.5, this.getBlockData())); + // PaperSpigot end + } else { + world.setTypeAndData(blockposition, Blocks.AIR.getBlockData(), 3, false, true); + int y1; + for (y1 = y; BlockFalling.canFall(world, x,y1,z) && y1 > 0; y1--) { + } + + if (y1 > 0) { + world.setTypeAndData(new BlockPosition(x, y1 ,z), this.getBlockData(), 2, false, true); + } + } + + } + } + + public boolean interact(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman, EnumDirection enumdirection, float f, float f1, float f2) { + this.f(world, blockposition); + return true; + } + + public void attack(World world, BlockPosition blockposition, EntityHuman entityhuman) { + this.f(world, blockposition); + } + + private void f(World world, BlockPosition blockposition) { + IBlockData iblockdata = world.getType(blockposition); + + if (iblockdata.getBlock() == this) { + for (int i = 0; i < 1000; ++i) { + BlockPosition blockposition1 = blockposition.a(world.random.nextInt(16) - world.random.nextInt(16), world.random.nextInt(8) - world.random.nextInt(8), world.random.nextInt(16) - world.random.nextInt(16)); + + if (world.getType(blockposition1).getBlock().material == Material.AIR) { + // CraftBukkit start + org.bukkit.block.Block from = world.getWorld().getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()); + org.bukkit.block.Block to = world.getWorld().getBlockAt(blockposition1.getX(), blockposition1.getY(), blockposition1.getZ()); + BlockFromToEvent event = new BlockFromToEvent(from, to); + org.bukkit.Bukkit.getPluginManager().callEvent(event); + + if (event.isCancelled()) { + return; + } + + blockposition1 = new BlockPosition(event.getToBlock().getX(), event.getToBlock().getY(), event.getToBlock().getZ()); + // CraftBukkit end + world.setTypeAndData(blockposition1, iblockdata, 2, false, true); + world.setTypeAndData(blockposition, Blocks.AIR.getBlockData(), 3, false, true); + + return; + } + } + + } + } + + public int a(World world) { + return 5; + } + + public boolean c() { + return false; + } + + public boolean d() { + return false; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockDropper.java b/azurite-server/src/main/java/net/minecraft/server/BlockDropper.java new file mode 100644 index 0000000..e627e31 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockDropper.java @@ -0,0 +1,85 @@ +package net.minecraft.server; + +// CraftBukkit start +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.event.inventory.InventoryMoveItemEvent; +import org.bukkit.inventory.Inventory; +// CraftBukkit end + +public class BlockDropper extends BlockDispenser { + + private final IDispenseBehavior P = new DispenseBehaviorItem(); + + public BlockDropper() {} + + protected IDispenseBehavior a(ItemStack itemstack) { + return this.P; + } + + public TileEntity a(World world, int i) { + return new TileEntityDropper(); + } + + public void dispense(World world, BlockPosition blockposition) { + SourceBlock sourceblock = new SourceBlock(world, blockposition); + TileEntityDispenser tileentitydispenser = sourceblock.getTileEntity(); + + if (tileentitydispenser != null) { + int i = tileentitydispenser.m(); + + if (i < 0) { + world.triggerEffect(1001, blockposition, 0); + } else { + ItemStack itemstack = tileentitydispenser.getItem(i); + + if (itemstack != null) { + EnumDirection enumdirection = world.getType(blockposition).get(BlockDropper.FACING); + BlockPosition blockposition1 = blockposition.shift(enumdirection); + IInventory iinventory = TileEntityHopper.b(world, blockposition1.getX(), blockposition1.getY(), blockposition1.getZ()); + ItemStack itemstack1; + + if (iinventory == null) { + itemstack1 = this.P.a(sourceblock, itemstack); + if (itemstack1 != null && itemstack1.count <= 0) { + itemstack1 = null; + } + } else { + // CraftBukkit start - Fire event when pushing items into other inventories + CraftItemStack oitemstack = CraftItemStack.asCraftMirror(itemstack.cloneItemStack().cloneAndSubtract(1)); + + Inventory destinationInventory = getItemStacks(iinventory); + + InventoryMoveItemEvent event = new InventoryMoveItemEvent(tileentitydispenser.getOwner().getInventory(), oitemstack.clone(), destinationInventory, true); + world.getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { + return; + } + itemstack1 = TileEntityHopper.addItem(iinventory, CraftItemStack.asNMSCopy(event.getItem()), enumdirection.opposite()); + if (event.getItem().equals(oitemstack) && itemstack1 == null) { + // CraftBukkit end + itemstack1 = itemstack.cloneItemStack(); + if (--itemstack1.count <= 0) { + itemstack1 = null; + } + } else { + itemstack1 = itemstack.cloneItemStack(); + } + } + + tileentitydispenser.setItem(i, itemstack1); + } + } + } + } + + private static Inventory getItemStacks(IInventory iinventory) { + Inventory destinationInventory; + // Have to special case large chests as they work oddly + if (iinventory instanceof InventoryLargeChest) { + destinationInventory = new org.bukkit.craftbukkit.inventory.CraftInventoryDoubleChest((InventoryLargeChest) iinventory); + } else { + destinationInventory = iinventory.getOwner().getInventory(); + } + return destinationInventory; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockEnchantmentTable.java b/azurite-server/src/main/java/net/minecraft/server/BlockEnchantmentTable.java new file mode 100644 index 0000000..ec6ea22 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockEnchantmentTable.java @@ -0,0 +1,49 @@ +package net.minecraft.server; + +public class BlockEnchantmentTable extends BlockContainer { + + protected BlockEnchantmentTable() { + super(Material.STONE, MaterialMapColor.D); + this.a(0.0F, 0.0F, 0.0F, 1.0F, 0.75F, 1.0F); + this.e(0); + this.a(CreativeModeTab.c); + } + + public boolean d() { + return false; + } + + public boolean c() { + return false; + } + + public int b() { + return 3; + } + + public TileEntity a(World world, int i) { + return new TileEntityEnchantTable(); + } + + public boolean interact(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman, EnumDirection enumdirection, float f, float f1, float f2) { + TileEntity tileentity = world.getTileEntity(blockposition); + + if (tileentity instanceof TileEntityEnchantTable) { + entityhuman.openTileEntity((TileEntityEnchantTable) tileentity); + } + + return true; + } + + public void postPlace(World world, BlockPosition blockposition, IBlockData iblockdata, EntityLiving entityliving, ItemStack itemstack) { + super.postPlace(world, blockposition, iblockdata, entityliving, itemstack); + if (itemstack.hasName()) { + TileEntity tileentity = world.getTileEntity(blockposition); + + if (tileentity instanceof TileEntityEnchantTable) { + ((TileEntityEnchantTable) tileentity).a(itemstack.getName()); + } + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockEnderChest.java b/azurite-server/src/main/java/net/minecraft/server/BlockEnderChest.java new file mode 100644 index 0000000..9476c96 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockEnderChest.java @@ -0,0 +1,82 @@ +package net.minecraft.server; + +import java.util.Random; + +public class BlockEnderChest extends BlockContainer { + + public static final BlockStateDirection FACING = BlockStateDirection.of("facing", EnumDirection.EnumDirectionLimit.HORIZONTAL); + + protected BlockEnderChest() { + super(Material.STONE); + this.j(this.blockStateList.getBlockData().set(BlockEnderChest.FACING, EnumDirection.NORTH)); + this.a(CreativeModeTab.c); + this.a(0.0625F, 0.0F, 0.0625F, 0.9375F, 0.875F, 0.9375F); + } + + public boolean c() { + return false; + } + + public boolean d() { + return false; + } + + public int b() { + return 2; + } + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + return Item.getItemOf(Blocks.OBSIDIAN); + } + + public int a(Random random) { + return 8; + } + + protected boolean I() { + return true; + } + + public IBlockData getPlacedState(World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2, int i, EntityLiving entityliving) { + return this.getBlockData().set(BlockEnderChest.FACING, entityliving.getDirection().opposite()); + } + + public void postPlace(World world, BlockPosition blockposition, IBlockData iblockdata, EntityLiving entityliving, ItemStack itemstack) { + world.setTypeAndData(blockposition, iblockdata.set(BlockEnderChest.FACING, entityliving.getDirection().opposite()), 2); + } + + public boolean interact(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman, EnumDirection enumdirection, float f, float f1, float f2) { + InventoryEnderChest inventoryenderchest = entityhuman.getEnderChest(); + TileEntity tileentity = world.getTileEntity(blockposition); + + if (inventoryenderchest != null && tileentity instanceof TileEntityEnderChest) { + if (!world.getType(blockposition.up()).getBlock().isOccluding()) { + inventoryenderchest.a((TileEntityEnderChest) tileentity); + entityhuman.openContainer(inventoryenderchest); + } + } + return true; + } + + public TileEntity a(World world, int i) { + return new TileEntityEnderChest(); + } + + public IBlockData fromLegacyData(int i) { + EnumDirection enumdirection = EnumDirection.fromType1(i); + + if (enumdirection.k() == EnumDirection.EnumAxis.Y) { + enumdirection = EnumDirection.NORTH; + } + + return this.getBlockData().set(BlockEnderChest.FACING, enumdirection); + } + + public int toLegacyData(IBlockData iblockdata) { + return iblockdata.get(BlockEnderChest.FACING).a(); + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, BlockEnderChest.FACING); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockEnderPortal.java b/azurite-server/src/main/java/net/minecraft/server/BlockEnderPortal.java new file mode 100644 index 0000000..a1046c9 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockEnderPortal.java @@ -0,0 +1,51 @@ +package net.minecraft.server; + +import org.bukkit.event.entity.EntityPortalEnterEvent; + +import java.util.List; +import java.util.Random; + +public class BlockEnderPortal extends BlockContainer { + + protected BlockEnderPortal(Material material) { + super(material); + this.a(1.0F); + } + + public TileEntity a(World world, int i) { + return new TileEntityEnderPortal(); + } + + public void updateShape(IBlockAccess iblockaccess, BlockPosition blockposition) { + this.a(0.0F, 0.0F, 0.0F, 1.0F, 0.0625F, 1.0F); + } + + public void a(World world, BlockPosition blockposition, IBlockData iblockdata, AxisAlignedBB axisalignedbb, List list, Entity entity) {} + + public boolean c() { + return false; + } + + public boolean d() { + return false; + } + + public int a(Random random) { + return 0; + } + + public void a(World world, BlockPosition blockposition, IBlockData iblockdata, Entity entity) { + if (entity.vehicle == null && entity.passenger == null) { + // CraftBukkit start - Entity in portal + EntityPortalEnterEvent event = new EntityPortalEnterEvent(entity.getBukkitEntity(), new org.bukkit.Location(world.getWorld(), blockposition.getX(), blockposition.getY(), blockposition.getZ())); + world.getServer().getPluginManager().callEvent(event); + // CraftBukkit end + entity.c(1); + } + + } + + public MaterialMapColor g(IBlockData iblockdata) { + return MaterialMapColor.E; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockEnderPortalFrame.java b/azurite-server/src/main/java/net/minecraft/server/BlockEnderPortalFrame.java new file mode 100644 index 0000000..35f904f --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockEnderPortalFrame.java @@ -0,0 +1,69 @@ +package net.minecraft.server; + +import java.util.List; +import java.util.Random; + +public class BlockEnderPortalFrame extends Block { + + public static final BlockStateDirection FACING = BlockStateDirection.of("facing", EnumDirection.EnumDirectionLimit.HORIZONTAL); + public static final BlockStateBoolean EYE = BlockStateBoolean.of("eye"); + + public BlockEnderPortalFrame() { + super(Material.STONE, MaterialMapColor.C); + this.j(this.blockStateList.getBlockData().set(BlockEnderPortalFrame.FACING, EnumDirection.NORTH).set(BlockEnderPortalFrame.EYE, Boolean.FALSE)); + } + + public boolean c() { + return false; + } + + public void j() { + this.a(0.0F, 0.0F, 0.0F, 1.0F, 0.8125F, 1.0F); + } + + public void a(World world, BlockPosition blockposition, IBlockData iblockdata, AxisAlignedBB axisalignedbb, List list, Entity entity) { + this.a(0.0F, 0.0F, 0.0F, 1.0F, 0.8125F, 1.0F); + super.a(world, blockposition, iblockdata, axisalignedbb, list, entity); + if (world.getType(blockposition).get(BlockEnderPortalFrame.EYE)) { + this.a(0.3125F, 0.8125F, 0.3125F, 0.6875F, 1.0F, 0.6875F); + super.a(world, blockposition, iblockdata, axisalignedbb, list, entity); + } + + this.j(); + } + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + return null; + } + + public IBlockData getPlacedState(World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2, int i, EntityLiving entityliving) { + return this.getBlockData().set(BlockEnderPortalFrame.FACING, entityliving.getDirection().opposite()).set(BlockEnderPortalFrame.EYE, Boolean.FALSE); + } + + public boolean isComplexRedstone() { + return true; + } + + public int l(World world, BlockPosition blockposition) { + return world.getType(blockposition).get(BlockEnderPortalFrame.EYE) ? 15 : 0; + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockEnderPortalFrame.EYE, (i & 4) != 0).set(BlockEnderPortalFrame.FACING, EnumDirection.fromType2(i & 3)); + } + + public int toLegacyData(IBlockData iblockdata) { + byte b0 = 0; + int i = b0 | iblockdata.get(BlockEnderPortalFrame.FACING).b(); + + if (iblockdata.get(BlockEnderPortalFrame.EYE)) { + i |= 4; + } + + return i; + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, BlockEnderPortalFrame.FACING, BlockEnderPortalFrame.EYE); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockFalling.java b/azurite-server/src/main/java/net/minecraft/server/BlockFalling.java new file mode 100644 index 0000000..a8e51a3 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockFalling.java @@ -0,0 +1,80 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.AzuriteConfig; + +import java.util.Random; + +public class BlockFalling extends Block { + + public static boolean instaFall; + + public BlockFalling() { + super(Material.SAND); + this.a(CreativeModeTab.b); + } + + public BlockFalling(Material material) { + super(material); + } + + public static boolean canFall(World world, int x, int y, int z) { + Block block = world.getType(x, y, z).getBlock(); + Material material = block.material; + + return block == Blocks.FIRE || material == Material.AIR || material == Material.WATER || material == Material.LAVA; + } + + public static boolean canFall(World world, BlockPosition blockPosition) { + return canFall(world, blockPosition.getX(), blockPosition.getY(), blockPosition.getZ()); + } + + public void onPlace(World world, BlockPosition blockposition, IBlockData iblockdata) { + world.a(blockposition, this, this.a(world)); + } + + public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) { + world.a(blockposition, this, this.a(world)); + } + + public void b(World world, BlockPosition blockposition, IBlockData iblockdata, Random random) { + this.f(world, blockposition); + } + + private void f(World world, BlockPosition blockposition) { + if (blockposition.getY() >= 0 && (!(this instanceof BlockGravel) || AzuriteConfig.gravelFall.getValue()) && canFall(world, blockposition.getX(), blockposition.getY() - 1, blockposition.getZ())) { + if (AzuriteConfig.fixSandChunkUnloading.getValue() || !instaFall && world.areChunksLoadedBetween(blockposition.a(-32, -32, -32), blockposition.a(32, 32, 32))) { + world.dispatch(); + + // PaperSpigot start - Add FallingBlock source location API + org.bukkit.Location loc = new org.bukkit.Location(world.getWorld(), blockposition.getX() + 0.5F, blockposition.getY(), blockposition.getZ() + 0.5F); + EntityFallingBlock entityfallingblock = new EntityFallingBlock(loc, world, blockposition.getX() + 0.5D, blockposition.getY(), blockposition.getZ() + 0.5D, world.getType(blockposition)); + // PaperSpigot end + + a(entityfallingblock); + world.addEntity(entityfallingblock); + } else { + world.setAir(blockposition); + + BlockPosition blockposition1; + + for (blockposition1 = blockposition.down(); canFall(world, blockposition1.getX(), blockposition.getY(), blockposition.getZ()) && blockposition1.getY() > 0; blockposition1 = blockposition1.down()) { + } + + if (blockposition1.getY() > 0) { + world.setTypeUpdate(blockposition1.up(), this.getBlockData()); + } + } + + } + } + + protected void a(EntityFallingBlock entityfallingblock) { + } + + public int a(World world) { + return 2; + } + + public void a_(World world, BlockPosition blockposition) { + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockFence.java b/azurite-server/src/main/java/net/minecraft/server/BlockFence.java new file mode 100644 index 0000000..c976ca3 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockFence.java @@ -0,0 +1,133 @@ +package net.minecraft.server; + +import java.util.List; + +public class BlockFence extends Block { + + public static final BlockStateBoolean NORTH = BlockStateBoolean.of("north"); + public static final BlockStateBoolean EAST = BlockStateBoolean.of("east"); + public static final BlockStateBoolean SOUTH = BlockStateBoolean.of("south"); + public static final BlockStateBoolean WEST = BlockStateBoolean.of("west"); + + public BlockFence(Material material) { + this(material, material.r()); + } + + public BlockFence(Material material, MaterialMapColor materialmapcolor) { + super(material, materialmapcolor); + this.j(this.blockStateList.getBlockData().set(BlockFence.NORTH, Boolean.FALSE).set(BlockFence.EAST, Boolean.FALSE).set(BlockFence.SOUTH, Boolean.FALSE).set(BlockFence.WEST, Boolean.FALSE)); + this.a(CreativeModeTab.c); + } + + public void a(World world, BlockPosition blockposition, IBlockData iblockdata, AxisAlignedBB axisalignedbb, List list, Entity entity) { + boolean flag = this.e(world, blockposition.north()); + boolean flag1 = this.e(world, blockposition.south()); + boolean flag2 = this.e(world, blockposition.west()); + boolean flag3 = this.e(world, blockposition.east()); + float f = 0.375F; + float f1 = 0.625F; + float f2 = 0.375F; + float f3 = 0.625F; + + if (flag) { + f2 = 0.0F; + } + + if (flag1) { + f3 = 1.0F; + } + + if (flag || flag1) { + this.a(f, 0.0F, f2, f1, 1.5F, f3); + super.a(world, blockposition, iblockdata, axisalignedbb, list, entity); + } + + f2 = 0.375F; + f3 = 0.625F; + if (flag2) { + f = 0.0F; + } + + if (flag3) { + f1 = 1.0F; + } + + if (flag2 || flag3 || !flag && !flag1) { + this.a(f, 0.0F, f2, f1, 1.5F, f3); + super.a(world, blockposition, iblockdata, axisalignedbb, list, entity); + } + + if (flag) { + f2 = 0.0F; + } + + if (flag1) { + f3 = 1.0F; + } + + this.a(f, 0.0F, f2, f1, 1.0F, f3); + } + + public void updateShape(IBlockAccess iblockaccess, BlockPosition blockposition) { + boolean flag = this.e(iblockaccess, blockposition.north()); + boolean flag1 = this.e(iblockaccess, blockposition.south()); + boolean flag2 = this.e(iblockaccess, blockposition.west()); + boolean flag3 = this.e(iblockaccess, blockposition.east()); + float f = 0.375F; + float f1 = 0.625F; + float f2 = 0.375F; + float f3 = 0.625F; + + if (flag) { + f2 = 0.0F; + } + + if (flag1) { + f3 = 1.0F; + } + + if (flag2) { + f = 0.0F; + } + + if (flag3) { + f1 = 1.0F; + } + + this.a(f, 0.0F, f2, f1, 1.0F, f3); + } + + public boolean c() { + return false; + } + + public boolean d() { + return false; + } + + public boolean b(IBlockAccess iblockaccess, BlockPosition blockposition) { + return false; + } + + public boolean e(IBlockAccess iblockaccess, BlockPosition blockposition) { + Block block = iblockaccess.getType(blockposition).getBlock(); + + return block != Blocks.BARRIER && ((block instanceof BlockFence && block.material == this.material) || block instanceof BlockFenceGate || (block.material.k() && block.d() && block.material != Material.PUMPKIN)); + } + + public boolean interact(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman, EnumDirection enumdirection, float f, float f1, float f2) { + return ItemLeash.a(entityhuman, world, blockposition); + } + + public int toLegacyData(IBlockData iblockdata) { + return 0; + } + + public IBlockData updateState(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { + return iblockdata.set(BlockFence.NORTH, this.e(iblockaccess, blockposition.north())).set(BlockFence.EAST, this.e(iblockaccess, blockposition.east())).set(BlockFence.SOUTH, this.e(iblockaccess, blockposition.south())).set(BlockFence.WEST, this.e(iblockaccess, blockposition.west())); + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, BlockFence.NORTH, BlockFence.EAST, BlockFence.WEST, BlockFence.SOUTH); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockFenceGate.java b/azurite-server/src/main/java/net/minecraft/server/BlockFenceGate.java new file mode 100644 index 0000000..a30b976 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockFenceGate.java @@ -0,0 +1,122 @@ +package net.minecraft.server; + +public class BlockFenceGate extends BlockDirectional { + + public static final BlockStateBoolean OPEN = BlockStateBoolean.of("open"); + public static final BlockStateBoolean POWERED = BlockStateBoolean.of("powered"); + public static final BlockStateBoolean IN_WALL = BlockStateBoolean.of("in_wall"); + + public BlockFenceGate(BlockWood.EnumLogVariant blockwood_enumlogvariant) { + super(Material.WOOD, blockwood_enumlogvariant.c()); + this.j(this.blockStateList.getBlockData().set(BlockFenceGate.OPEN, Boolean.FALSE).set(BlockFenceGate.POWERED, Boolean.FALSE).set(BlockFenceGate.IN_WALL, Boolean.FALSE)); + this.a(CreativeModeTab.d); + } + + public IBlockData updateState(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { + EnumDirection.EnumAxis enumdirection_enumaxis = iblockdata.get(BlockFenceGate.FACING).k(); + + if (enumdirection_enumaxis == EnumDirection.EnumAxis.Z && (iblockaccess.getType(blockposition.west()).getBlock() == Blocks.COBBLESTONE_WALL || iblockaccess.getType(blockposition.east()).getBlock() == Blocks.COBBLESTONE_WALL) || enumdirection_enumaxis == EnumDirection.EnumAxis.X && (iblockaccess.getType(blockposition.north()).getBlock() == Blocks.COBBLESTONE_WALL || iblockaccess.getType(blockposition.south()).getBlock() == Blocks.COBBLESTONE_WALL)) { + iblockdata = iblockdata.set(BlockFenceGate.IN_WALL, Boolean.TRUE); + } + + return iblockdata; + } + + public boolean canPlace(World world, BlockPosition blockposition) { + return world.getType(blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()).getBlock().getMaterial().isBuildable() && super.canPlace(world, blockposition); + } + + public AxisAlignedBB a(World world, BlockPosition blockposition, IBlockData iblockdata) { + if (iblockdata.get(BlockFenceGate.OPEN)) { + return null; + } else { + EnumDirection.EnumAxis enumdirection_enumaxis = iblockdata.get(BlockFenceGate.FACING).k(); + + return enumdirection_enumaxis == EnumDirection.EnumAxis.Z ? new AxisAlignedBB(blockposition.getX(), blockposition.getY(), (float) blockposition.getZ() + 0.375F, blockposition.getX() + 1, (float) blockposition.getY() + 1.5F, (float) blockposition.getZ() + 0.625F) : new AxisAlignedBB((float) blockposition.getX() + 0.375F, blockposition.getY(), blockposition.getZ(), (float) blockposition.getX() + 0.625F, (float) blockposition.getY() + 1.5F, blockposition.getZ() + 1); + } + } + + public void updateShape(IBlockAccess iblockaccess, BlockPosition blockposition) { + EnumDirection.EnumAxis enumdirection_enumaxis = iblockaccess.getType(blockposition).get(BlockFenceGate.FACING).k(); + + if (enumdirection_enumaxis == EnumDirection.EnumAxis.Z) { + this.a(0.0F, 0.0F, 0.375F, 1.0F, 1.0F, 0.625F); + } else { + this.a(0.375F, 0.0F, 0.0F, 0.625F, 1.0F, 1.0F); + } + + } + + public boolean c() { + return false; + } + + public boolean d() { + return false; + } + + public boolean b(IBlockAccess iblockaccess, BlockPosition blockposition) { + return iblockaccess.getType(blockposition).get(BlockFenceGate.OPEN); + } + + public IBlockData getPlacedState(World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2, int i, EntityLiving entityliving) { + return this.getBlockData().set(BlockFenceGate.FACING, entityliving.getDirection()).set(BlockFenceGate.OPEN, Boolean.FALSE).set(BlockFenceGate.POWERED, Boolean.FALSE).set(BlockFenceGate.IN_WALL, Boolean.FALSE); + } + + public boolean interact(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman, EnumDirection enumdirection, float f, float f1, float f2) { + if (iblockdata.get(BlockFenceGate.OPEN)) { + iblockdata = iblockdata.set(BlockFenceGate.OPEN, Boolean.FALSE); + } else { + EnumDirection enumdirection1 = EnumDirection.fromAngle(entityhuman.yaw); + + if (iblockdata.get(BlockFenceGate.FACING) == enumdirection1.opposite()) { + iblockdata = iblockdata.set(BlockFenceGate.FACING, enumdirection1); + } + + iblockdata = iblockdata.set(BlockFenceGate.OPEN, Boolean.TRUE); + } + world.setTypeAndData(blockposition, iblockdata, 2); + + world.a(entityhuman, iblockdata.get(BlockFenceGate.OPEN) ? 1003 : 1006, blockposition, 0); + return true; + } + + public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) { + boolean flag = world.isBlockIndirectlyPowered(blockposition); + + if (flag || block.isPowerSource()) { + if (flag && !iblockdata.get(BlockFenceGate.OPEN) && !iblockdata.get(BlockFenceGate.POWERED)) { + world.setTypeAndData(blockposition, iblockdata.set(BlockFenceGate.OPEN, Boolean.TRUE).set(BlockFenceGate.POWERED, Boolean.TRUE), 2); + world.a(null, 1003, blockposition, 0); + } else if (!flag && iblockdata.get(BlockFenceGate.OPEN) && iblockdata.get(BlockFenceGate.POWERED)) { + world.setTypeAndData(blockposition, iblockdata.set(BlockFenceGate.OPEN, Boolean.FALSE).set(BlockFenceGate.POWERED, Boolean.FALSE), 2); + world.a(null, 1006, blockposition, 0); + } else if (flag != iblockdata.get(BlockFenceGate.POWERED)) { + world.setTypeAndData(blockposition, iblockdata.set(BlockFenceGate.POWERED, flag), 2); + } + } + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockFenceGate.FACING, EnumDirection.fromType2(i)).set(BlockFenceGate.OPEN, (i & 4) != 0).set(BlockFenceGate.POWERED, (i & 8) != 0); + } + + public int toLegacyData(IBlockData iblockdata) { + byte b0 = 0; + int i = b0 | iblockdata.get(BlockFenceGate.FACING).b(); + + if (iblockdata.get(BlockFenceGate.POWERED)) { + i |= 8; + } + + if (iblockdata.get(BlockFenceGate.OPEN)) { + i |= 4; + } + + return i; + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, BlockFenceGate.FACING, BlockFenceGate.OPEN, BlockFenceGate.POWERED, BlockFenceGate.IN_WALL); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockFire.java b/azurite-server/src/main/java/net/minecraft/server/BlockFire.java new file mode 100644 index 0000000..1bdb5ee --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockFire.java @@ -0,0 +1,369 @@ +package net.minecraft.server; + +import com.google.common.collect.Maps; +import org.bukkit.craftbukkit.event.CraftEventFactory; +import org.bukkit.event.block.BlockBurnEvent; +import org.bukkit.event.block.BlockSpreadEvent; + +import java.util.Map; +import java.util.Random; +// CraftBukkit end + +public class BlockFire extends Block { + + public static final BlockStateInteger AGE = BlockStateInteger.of("age", 0, 15); + public static final BlockStateBoolean FLIP = BlockStateBoolean.of("flip"); + public static final BlockStateBoolean ALT = BlockStateBoolean.of("alt"); + public static final BlockStateBoolean NORTH = BlockStateBoolean.of("north"); + public static final BlockStateBoolean EAST = BlockStateBoolean.of("east"); + public static final BlockStateBoolean SOUTH = BlockStateBoolean.of("south"); + public static final BlockStateBoolean WEST = BlockStateBoolean.of("west"); + public static final BlockStateInteger UPPER = BlockStateInteger.of("upper", 0, 2); + private final Map flameChances = Maps.newIdentityHashMap(); + private final Map U = Maps.newIdentityHashMap(); + + public IBlockData updateState(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { + int i = blockposition.getX(); + int j = blockposition.getY(); + int k = blockposition.getZ(); + + if (!World.a(iblockaccess, blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()) && !e(iblockaccess, blockposition.getX(), blockposition.getY() - 1, blockposition.getZ())) { + boolean flag = (i + j + k & 1) == 1; + boolean flag1 = (i / 2 + j / 2 + k / 2 & 1) == 1; + int l = 0; + + if (this.e(iblockaccess, blockposition.getX(), blockposition.getY() + 1, blockposition.getZ())) { + l = flag ? 1 : 2; + } + + return iblockdata.set(BlockFire.NORTH, this.e(iblockaccess, blockposition.getX(), blockposition.getY(), blockposition.getZ() - 1)).set(BlockFire.EAST, this.e(iblockaccess, blockposition.getX() + 1, blockposition.getY(), blockposition.getZ())).set(BlockFire.SOUTH, this.e(iblockaccess, blockposition.getX(), blockposition.getY(), blockposition.getZ() + 1)).set(BlockFire.WEST, this.e(iblockaccess, blockposition.getX() - 1, blockposition.getY(), blockposition.getZ())).set(BlockFire.UPPER, l).set(BlockFire.FLIP, flag1).set(BlockFire.ALT, flag); + } else { + return this.getBlockData(); + } + } + + protected BlockFire() { + super(Material.FIRE); + this.j(this.blockStateList.getBlockData().set(BlockFire.AGE, 0).set(BlockFire.FLIP, Boolean.FALSE).set(BlockFire.ALT, Boolean.FALSE).set(BlockFire.NORTH, Boolean.FALSE).set(BlockFire.EAST, Boolean.FALSE).set(BlockFire.SOUTH, Boolean.FALSE).set(BlockFire.WEST, Boolean.FALSE).set(BlockFire.UPPER, 0)); + this.a(true); + } + + public static void l() { + Blocks.FIRE.a(Blocks.PLANKS, 5, 20); + Blocks.FIRE.a(Blocks.DOUBLE_WOODEN_SLAB, 5, 20); + Blocks.FIRE.a(Blocks.WOODEN_SLAB, 5, 20); + Blocks.FIRE.a(Blocks.FENCE_GATE, 5, 20); + Blocks.FIRE.a(Blocks.SPRUCE_FENCE_GATE, 5, 20); + Blocks.FIRE.a(Blocks.BIRCH_FENCE_GATE, 5, 20); + Blocks.FIRE.a(Blocks.JUNGLE_FENCE_GATE, 5, 20); + Blocks.FIRE.a(Blocks.DARK_OAK_FENCE_GATE, 5, 20); + Blocks.FIRE.a(Blocks.ACACIA_FENCE_GATE, 5, 20); + Blocks.FIRE.a(Blocks.FENCE, 5, 20); + Blocks.FIRE.a(Blocks.SPRUCE_FENCE, 5, 20); + Blocks.FIRE.a(Blocks.BIRCH_FENCE, 5, 20); + Blocks.FIRE.a(Blocks.JUNGLE_FENCE, 5, 20); + Blocks.FIRE.a(Blocks.DARK_OAK_FENCE, 5, 20); + Blocks.FIRE.a(Blocks.ACACIA_FENCE, 5, 20); + Blocks.FIRE.a(Blocks.OAK_STAIRS, 5, 20); + Blocks.FIRE.a(Blocks.BIRCH_STAIRS, 5, 20); + Blocks.FIRE.a(Blocks.SPRUCE_STAIRS, 5, 20); + Blocks.FIRE.a(Blocks.JUNGLE_STAIRS, 5, 20); + Blocks.FIRE.a(Blocks.LOG, 5, 5); + Blocks.FIRE.a(Blocks.LOG2, 5, 5); + Blocks.FIRE.a(Blocks.LEAVES, 30, 60); + Blocks.FIRE.a(Blocks.LEAVES2, 30, 60); + Blocks.FIRE.a(Blocks.BOOKSHELF, 30, 20); + Blocks.FIRE.a(Blocks.TNT, 15, 100); + Blocks.FIRE.a(Blocks.TALLGRASS, 60, 100); + Blocks.FIRE.a(Blocks.DOUBLE_PLANT, 60, 100); + Blocks.FIRE.a(Blocks.YELLOW_FLOWER, 60, 100); + Blocks.FIRE.a(Blocks.RED_FLOWER, 60, 100); + Blocks.FIRE.a(Blocks.DEADBUSH, 60, 100); + Blocks.FIRE.a(Blocks.WOOL, 30, 60); + Blocks.FIRE.a(Blocks.VINE, 15, 100); + Blocks.FIRE.a(Blocks.COAL_BLOCK, 5, 5); + Blocks.FIRE.a(Blocks.HAY_BLOCK, 60, 20); + Blocks.FIRE.a(Blocks.CARPET, 60, 20); + } + + public void a(Block block, int i, int j) { + this.flameChances.put(block, i); + this.U.put(block, j); + } + + public AxisAlignedBB a(World world, BlockPosition blockposition, IBlockData iblockdata) { + return null; + } + + public boolean c() { + return false; + } + + public boolean d() { + return false; + } + + public int a(Random random) { + return 0; + } + + public int a(World world) { + return 30; + } + + public void b(World world, BlockPosition blockposition, IBlockData iblockdata, Random random) { + if (world.getGameRules().getBoolean("doFireTick")) { + if (!this.canPlace(world, blockposition)) { + fireExtinguished(world, blockposition); // CraftBukkit - invalid place location + } + + Block block = world.getType(blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()).getBlock(); + boolean flag = block == Blocks.NETHERRACK; + + if (world.worldProvider instanceof WorldProviderTheEnd && block == Blocks.BEDROCK) { + flag = true; + } + + if (!flag && world.S() && this.e(world, blockposition)) { + fireExtinguished(world, blockposition); // CraftBukkit - extinguished by rain + } else { + int i = iblockdata.get(BlockFire.AGE); + + if (i < 15) { + iblockdata = iblockdata.set(BlockFire.AGE, i + random.nextInt(3) / 2); + world.setTypeAndData(blockposition, iblockdata, 4); + } + + world.a(blockposition, this, this.a(world) + random.nextInt(10)); + if (!flag) { + if (!this.f(world, blockposition)) { + if (!World.a(world, blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()) || i > 3) { + fireExtinguished(world, blockposition); // CraftBukkit + } + + return; + } + + if (!this.e(world, blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()) && i == 15 && random.nextInt(4) == 0) { + fireExtinguished(world, blockposition); // CraftBukkit + return; + } + } + + boolean flag1 = world.D(blockposition); + byte b0 = 0; + + if (flag1) { + b0 = -50; + } + + this.a(world, blockposition.east(), 300 + b0, random, i); + this.a(world, blockposition.west(), 300 + b0, random, i); + this.a(world, blockposition.down(), 250 + b0, random, i); + this.a(world, blockposition.up(), 250 + b0, random, i); + this.a(world, blockposition.north(), 300 + b0, random, i); + this.a(world, blockposition.south(), 300 + b0, random, i); + + for (int j = -1; j <= 1; ++j) { + for (int k = -1; k <= 1; ++k) { + for (int l = -1; l <= 4; ++l) { + if (j != 0 || l != 0 || k != 0) { + int i1 = 100; + + if (l > 1) { + i1 += (l - 1) * 100; + } + + BlockPosition blockposition1 = blockposition.a(j, l, k); + if (!world.isLoaded(blockposition1)) + continue; + + int j1 = this.m(world, blockposition1); + + if (j1 > 0) { + int k1 = (j1 + 40 + world.getDifficulty().a() * 7) / (i + 30); + + if (flag1) { + k1 /= 2; + } + + if (k1 > 0 && random.nextInt(i1) <= k1 && (!world.S() || !this.e(world, blockposition1))) { + int l1 = i + random.nextInt(5) / 4; + + if (l1 > 15) { + l1 = 15; + } + + // CraftBukkit start - Call to stop spread of fire + if (world.getType(blockposition1).getBlock() != Blocks.FIRE) { + if (CraftEventFactory.callBlockIgniteEvent(world, blockposition1.getX(), blockposition1.getY(), blockposition1.getZ(), blockposition.getX(), blockposition.getY(), blockposition.getZ()).isCancelled()) { + continue; + } + + org.bukkit.Server server = world.getServer(); + org.bukkit.World bworld = world.getWorld(); + org.bukkit.block.BlockState blockState = bworld.getBlockAt(blockposition1.getX(), blockposition1.getY(), blockposition1.getZ()).getState(); + blockState.setTypeId(Block.getId(this)); + blockState.setData(new org.bukkit.material.MaterialData(Block.getId(this), (byte) l1)); + + BlockSpreadEvent spreadEvent = new BlockSpreadEvent(blockState.getBlock(), bworld.getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()), blockState); + server.getPluginManager().callEvent(spreadEvent); + + if (!spreadEvent.isCancelled()) { + blockState.update(true); + } + } + // CraftBukkit end + } + } + } + } + } + } + + } + } + } + + protected boolean e(World world, BlockPosition blockposition) { + int x = blockposition.getX(), y = blockposition.getY(), z = blockposition.getZ(); + return world.isRainingAt(x, y, z) || + world.isRainingAt(x - 1, y, z) || + world.isRainingAt(x + 1, y, z) || + world.isRainingAt(x, y, z - 1) || + world.isRainingAt(x, y, z + 1); + } + + public boolean N() { + return false; + } + + private int c(Block block) { + Integer integer = this.U.get(block); + + return integer == null ? 0 : integer; + } + + private int d(Block block) { + Integer integer = this.flameChances.get(block); + + return integer == null ? 0 : integer; + } + + private void a(World world, BlockPosition blockposition, int i, Random random, int j) { // Vortex + IBlockData iblockdata = world.getTypeIfLoaded(blockposition.getX(), blockposition.getY(), blockposition.getZ()); + if (iblockdata != null) { + int k = this.c(iblockdata.getBlock()); + + if (random.nextInt(i) < k) { + // CraftBukkit start + org.bukkit.block.Block theBlock = world.getWorld().getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()); + + BlockBurnEvent event = new BlockBurnEvent(theBlock); + world.getServer().getPluginManager().callEvent(event); + + if (event.isCancelled()) { + return; + } + // CraftBukkit end + + if (random.nextInt(j + 10) < 5 && !world.isRainingAt(blockposition)) { + int l = j + random.nextInt(5) / 4; + + if (l > 15) { + l = 15; + } + + world.setTypeAndData(blockposition, this.getBlockData().set(BlockFire.AGE, l), 3); + } else { + fireExtinguished(world, blockposition); // CraftBukkit + } + + if (iblockdata.getBlock() == Blocks.TNT) { + Blocks.TNT.postBreak(world, blockposition, iblockdata.set(BlockTNT.EXPLODE, Boolean.TRUE)); + } + } + } + } + + private boolean f(World world, BlockPosition blockposition) { + for (EnumDirection enumdirection : EnumDirection.values()) { + if (this.e(world, blockposition.getX() + enumdirection.getAdjacentX(), blockposition.getY() + enumdirection.getAdjacentY(), blockposition.getZ() + enumdirection.getAdjacentZ())) { + return true; + } + } + + return false; + } + + private int m(World world, BlockPosition blockposition) { + if (!world.isEmpty(blockposition)) { + return 0; + } else { + int i = 0; + + for (EnumDirection enumdirection : EnumDirection.values()) { + i = Math.max(this.d(world.getType(blockposition.shift(enumdirection)).getBlock()), i); + } + + return i; + } + } + + public boolean A() { + return false; + } + + public boolean e(IBlockAccess iblockaccess, BlockPosition blockposition) { + return e(iblockaccess, blockposition.getX(), blockposition.getY(), blockposition.getZ()); + } + + public boolean e(IBlockAccess iblockaccess, int x, int y, int z) { + return this.d(iblockaccess.getType(x, y, z).getBlock()) > 0; + } + + public boolean canPlace(World world, BlockPosition blockposition) { + return World.a(world, blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()) || this.f(world, blockposition); + } + + public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) { + if (!World.a(world, blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()) && !this.f(world, blockposition)) { + fireExtinguished(world, blockposition); // CraftBukkit - fuel block gone + } + + } + + public void onPlace(World world, BlockPosition blockposition, IBlockData iblockdata) { + if (world.worldProvider.getDimension() > 0 || !Blocks.PORTAL.e(world, blockposition)) { + if (!World.a(world, blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()) && !this.f(world, blockposition)) { + fireExtinguished(world, blockposition); // CraftBukkit - fuel block broke + } else { + world.a(blockposition, this, this.a(world) + world.random.nextInt(10)); + } + } + } + + public MaterialMapColor g(IBlockData iblockdata) { + return MaterialMapColor.f; + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockFire.AGE, i); + } + + public int toLegacyData(IBlockData iblockdata) { + return iblockdata.get(BlockFire.AGE); + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, BlockFire.AGE, BlockFire.NORTH, BlockFire.EAST, BlockFire.SOUTH, BlockFire.WEST, BlockFire.UPPER, BlockFire.FLIP, BlockFire.ALT); + } + + // CraftBukkit start + private void fireExtinguished(World world, BlockPosition position) { + if (!CraftEventFactory.callBlockFadeEvent(world.getWorld().getBlockAt(position.getX(), position.getY(), position.getZ()), Blocks.AIR).isCancelled()) { + world.setAir(position); + } + } + // CraftBukkit end +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockFloorSign.java b/azurite-server/src/main/java/net/minecraft/server/BlockFloorSign.java new file mode 100644 index 0000000..f39b198 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockFloorSign.java @@ -0,0 +1,31 @@ +package net.minecraft.server; + +public class BlockFloorSign extends BlockSign { + + public static final BlockStateInteger ROTATION = BlockStateInteger.of("rotation", 0, 15); + + public BlockFloorSign() { + this.j(this.blockStateList.getBlockData().set(BlockFloorSign.ROTATION, 0)); + } + + public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) { + if (!world.getType(blockposition.down()).getBlock().getMaterial().isBuildable()) { + this.b(world, blockposition, iblockdata, 0); + world.setAir(blockposition); + } + + super.doPhysics(world, blockposition, iblockdata, block); + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockFloorSign.ROTATION, i); + } + + public int toLegacyData(IBlockData iblockdata) { + return iblockdata.get(BlockFloorSign.ROTATION); + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, BlockFloorSign.ROTATION); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockFlowerPot.java b/azurite-server/src/main/java/net/minecraft/server/BlockFlowerPot.java new file mode 100644 index 0000000..0a0e7ec --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockFlowerPot.java @@ -0,0 +1,418 @@ +package net.minecraft.server; + +import java.util.Random; + +public class BlockFlowerPot extends BlockContainer { + + public static final BlockStateInteger LEGACY_DATA = BlockStateInteger.of("legacy_data", 0, 15); + public static final BlockStateEnum CONTENTS = BlockStateEnum.of("contents", BlockFlowerPot.EnumFlowerPotContents.class); + + public BlockFlowerPot() { + super(Material.ORIENTABLE); + this.j(this.blockStateList.getBlockData().set(BlockFlowerPot.CONTENTS, BlockFlowerPot.EnumFlowerPotContents.EMPTY).set(BlockFlowerPot.LEGACY_DATA, 0)); + this.j(); + } + + public String getName() { + return LocaleI18n.get("item.flowerPot.name"); + } + + public void j() { + float f = 0.375F; + float f1 = f / 2.0F; + + this.a(0.5F - f1, 0.0F, 0.5F - f1, 0.5F + f1, f, 0.5F + f1); + } + + public boolean c() { + return false; + } + + public int b() { + return 3; + } + + public boolean d() { + return false; + } + + public boolean interact(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman, EnumDirection enumdirection, float f, float f1, float f2) { + ItemStack itemstack = entityhuman.inventory.getItemInHand(); + + if (itemstack != null && itemstack.getItem() instanceof ItemBlock) { + TileEntityFlowerPot tileentityflowerpot = this.f(world, blockposition); + + if (tileentityflowerpot == null) { + return false; + } else if (tileentityflowerpot.b() != null) { + return false; + } else { + Block block = Block.asBlock(itemstack.getItem()); + + if (!this.a(block, itemstack.getData())) { + return false; + } else { + tileentityflowerpot.a(itemstack.getItem(), itemstack.getData()); + tileentityflowerpot.update(); + world.notify(blockposition); + entityhuman.b(StatisticList.T); + if (!entityhuman.abilities.canInstantlyBuild && --itemstack.count <= 0) { + entityhuman.inventory.setItem(entityhuman.inventory.itemInHandIndex, null); + } + + return true; + } + } + } else { + return false; + } + } + + private boolean a(Block block, int i) { + return block == Blocks.YELLOW_FLOWER || block == Blocks.RED_FLOWER || block == Blocks.CACTUS || block == Blocks.BROWN_MUSHROOM || block == Blocks.RED_MUSHROOM || block == Blocks.SAPLING || block == Blocks.DEADBUSH || block == Blocks.TALLGRASS && i == BlockLongGrass.EnumTallGrassType.FERN.a(); + } + + public int getDropData(World world, BlockPosition blockposition) { + TileEntityFlowerPot tileentityflowerpot = this.f(world, blockposition); + + return tileentityflowerpot != null && tileentityflowerpot.b() != null ? tileentityflowerpot.c() : 0; + } + + public boolean canPlace(World world, BlockPosition blockposition) { + return super.canPlace(world, blockposition) && World.a(world, blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()); + } + + public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) { + if (!World.a(world, blockposition.getX(), blockposition.getY() - 1, blockposition.getZ())) { + this.b(world, blockposition, iblockdata, 0); + world.setAir(blockposition); + } + + } + + public void remove(World world, BlockPosition blockposition, IBlockData iblockdata) { + TileEntityFlowerPot tileentityflowerpot = this.f(world, blockposition); + + if (tileentityflowerpot != null && tileentityflowerpot.b() != null) { + a(world, blockposition, new ItemStack(tileentityflowerpot.b(), 1, tileentityflowerpot.c())); + tileentityflowerpot.a( null, 0 ); // Spigot + } + + super.remove(world, blockposition, iblockdata); + } + + public void a(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman) { + super.a(world, blockposition, iblockdata, entityhuman); + if (entityhuman.abilities.canInstantlyBuild) { + TileEntityFlowerPot tileentityflowerpot = this.f(world, blockposition); + + if (tileentityflowerpot != null) { + tileentityflowerpot.a(null, 0); + } + } + + } + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + return Items.FLOWER_POT; + } + + private TileEntityFlowerPot f(World world, BlockPosition blockposition) { + TileEntity tileentity = world.getTileEntity(blockposition); + + return tileentity instanceof TileEntityFlowerPot ? (TileEntityFlowerPot) tileentity : null; + } + + public TileEntity a(World world, int i) { + Block object = null; + int j = 0; + + switch (i) { + case 1: + object = Blocks.RED_FLOWER; + j = BlockFlowers.EnumFlowerVarient.POPPY.b(); + break; + + case 2: + object = Blocks.YELLOW_FLOWER; + break; + + case 3: + object = Blocks.SAPLING; + j = BlockWood.EnumLogVariant.OAK.a(); + break; + + case 4: + object = Blocks.SAPLING; + j = BlockWood.EnumLogVariant.SPRUCE.a(); + break; + + case 5: + object = Blocks.SAPLING; + j = BlockWood.EnumLogVariant.BIRCH.a(); + break; + + case 6: + object = Blocks.SAPLING; + j = BlockWood.EnumLogVariant.JUNGLE.a(); + break; + + case 7: + object = Blocks.RED_MUSHROOM; + break; + + case 8: + object = Blocks.BROWN_MUSHROOM; + break; + + case 9: + object = Blocks.CACTUS; + break; + + case 10: + object = Blocks.DEADBUSH; + break; + + case 11: + object = Blocks.TALLGRASS; + j = BlockLongGrass.EnumTallGrassType.FERN.a(); + break; + + case 12: + object = Blocks.SAPLING; + j = BlockWood.EnumLogVariant.ACACIA.a(); + break; + + case 13: + object = Blocks.SAPLING; + j = BlockWood.EnumLogVariant.DARK_OAK.a(); + } + + return new TileEntityFlowerPot(Item.getItemOf(object), j); + } + + public BlockStateList getStateList() { + return new BlockStateList(this, BlockFlowerPot.CONTENTS, BlockFlowerPot.LEGACY_DATA); + } + + public int toLegacyData(IBlockData iblockdata) { + return iblockdata.get(BlockFlowerPot.LEGACY_DATA); + } + + public IBlockData updateState(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { + BlockFlowerPot.EnumFlowerPotContents blockflowerpot_enumflowerpotcontents = BlockFlowerPot.EnumFlowerPotContents.EMPTY; + TileEntity tileentity = iblockaccess.getTileEntity(blockposition); + + if (tileentity instanceof TileEntityFlowerPot) { + TileEntityFlowerPot tileentityflowerpot = (TileEntityFlowerPot) tileentity; + Item item = tileentityflowerpot.b(); + + if (item instanceof ItemBlock) { + int i = tileentityflowerpot.c(); + Block block = Block.asBlock(item); + + if (block == Blocks.SAPLING) { + switch (BlockFlowerPot.SyntheticClass_1.a[BlockWood.EnumLogVariant.a(i).ordinal()]) { + case 1: + blockflowerpot_enumflowerpotcontents = BlockFlowerPot.EnumFlowerPotContents.OAK_SAPLING; + break; + + case 2: + blockflowerpot_enumflowerpotcontents = BlockFlowerPot.EnumFlowerPotContents.SPRUCE_SAPLING; + break; + + case 3: + blockflowerpot_enumflowerpotcontents = BlockFlowerPot.EnumFlowerPotContents.BIRCH_SAPLING; + break; + + case 4: + blockflowerpot_enumflowerpotcontents = BlockFlowerPot.EnumFlowerPotContents.JUNGLE_SAPLING; + break; + + case 5: + blockflowerpot_enumflowerpotcontents = BlockFlowerPot.EnumFlowerPotContents.ACACIA_SAPLING; + break; + + case 6: + blockflowerpot_enumflowerpotcontents = BlockFlowerPot.EnumFlowerPotContents.DARK_OAK_SAPLING; + break; + + default: + blockflowerpot_enumflowerpotcontents = BlockFlowerPot.EnumFlowerPotContents.EMPTY; + } + } else if (block == Blocks.TALLGRASS) { + switch (i) { + case 0: + blockflowerpot_enumflowerpotcontents = BlockFlowerPot.EnumFlowerPotContents.DEAD_BUSH; + break; + + case 2: + blockflowerpot_enumflowerpotcontents = BlockFlowerPot.EnumFlowerPotContents.FERN; + break; + + default: + blockflowerpot_enumflowerpotcontents = BlockFlowerPot.EnumFlowerPotContents.EMPTY; + } + } else if (block == Blocks.YELLOW_FLOWER) { + blockflowerpot_enumflowerpotcontents = BlockFlowerPot.EnumFlowerPotContents.DANDELION; + } else if (block == Blocks.RED_FLOWER) { + switch (BlockFlowerPot.SyntheticClass_1.b[BlockFlowers.EnumFlowerVarient.a(BlockFlowers.EnumFlowerType.RED, i).ordinal()]) { + case 1: + blockflowerpot_enumflowerpotcontents = BlockFlowerPot.EnumFlowerPotContents.POPPY; + break; + + case 2: + blockflowerpot_enumflowerpotcontents = BlockFlowerPot.EnumFlowerPotContents.BLUE_ORCHID; + break; + + case 3: + blockflowerpot_enumflowerpotcontents = BlockFlowerPot.EnumFlowerPotContents.ALLIUM; + break; + + case 4: + blockflowerpot_enumflowerpotcontents = BlockFlowerPot.EnumFlowerPotContents.HOUSTONIA; + break; + + case 5: + blockflowerpot_enumflowerpotcontents = BlockFlowerPot.EnumFlowerPotContents.RED_TULIP; + break; + + case 6: + blockflowerpot_enumflowerpotcontents = BlockFlowerPot.EnumFlowerPotContents.ORANGE_TULIP; + break; + + case 7: + blockflowerpot_enumflowerpotcontents = BlockFlowerPot.EnumFlowerPotContents.WHITE_TULIP; + break; + + case 8: + blockflowerpot_enumflowerpotcontents = BlockFlowerPot.EnumFlowerPotContents.PINK_TULIP; + break; + + case 9: + blockflowerpot_enumflowerpotcontents = BlockFlowerPot.EnumFlowerPotContents.OXEYE_DAISY; + break; + + default: + blockflowerpot_enumflowerpotcontents = BlockFlowerPot.EnumFlowerPotContents.EMPTY; + } + } else if (block == Blocks.RED_MUSHROOM) { + blockflowerpot_enumflowerpotcontents = BlockFlowerPot.EnumFlowerPotContents.MUSHROOM_RED; + } else if (block == Blocks.BROWN_MUSHROOM) { + blockflowerpot_enumflowerpotcontents = BlockFlowerPot.EnumFlowerPotContents.MUSHROOM_BROWN; + } else if (block == Blocks.DEADBUSH) { + blockflowerpot_enumflowerpotcontents = BlockFlowerPot.EnumFlowerPotContents.DEAD_BUSH; + } else if (block == Blocks.CACTUS) { + blockflowerpot_enumflowerpotcontents = BlockFlowerPot.EnumFlowerPotContents.CACTUS; + } + } + } + + return iblockdata.set(BlockFlowerPot.CONTENTS, blockflowerpot_enumflowerpotcontents); + } + + static class SyntheticClass_1 { + + static final int[] a; + static final int[] b = new int[BlockFlowers.EnumFlowerVarient.values().length]; + + static { + try { + BlockFlowerPot.SyntheticClass_1.b[BlockFlowers.EnumFlowerVarient.POPPY.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockFlowerPot.SyntheticClass_1.b[BlockFlowers.EnumFlowerVarient.BLUE_ORCHID.ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockFlowerPot.SyntheticClass_1.b[BlockFlowers.EnumFlowerVarient.ALLIUM.ordinal()] = 3; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockFlowerPot.SyntheticClass_1.b[BlockFlowers.EnumFlowerVarient.HOUSTONIA.ordinal()] = 4; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockFlowerPot.SyntheticClass_1.b[BlockFlowers.EnumFlowerVarient.RED_TULIP.ordinal()] = 5; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockFlowerPot.SyntheticClass_1.b[BlockFlowers.EnumFlowerVarient.ORANGE_TULIP.ordinal()] = 6; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockFlowerPot.SyntheticClass_1.b[BlockFlowers.EnumFlowerVarient.WHITE_TULIP.ordinal()] = 7; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockFlowerPot.SyntheticClass_1.b[BlockFlowers.EnumFlowerVarient.PINK_TULIP.ordinal()] = 8; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockFlowerPot.SyntheticClass_1.b[BlockFlowers.EnumFlowerVarient.OXEYE_DAISY.ordinal()] = 9; + } catch (NoSuchFieldError ignored) { + } + + a = new int[BlockWood.EnumLogVariant.values().length]; + + try { + BlockFlowerPot.SyntheticClass_1.a[BlockWood.EnumLogVariant.OAK.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockFlowerPot.SyntheticClass_1.a[BlockWood.EnumLogVariant.SPRUCE.ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockFlowerPot.SyntheticClass_1.a[BlockWood.EnumLogVariant.BIRCH.ordinal()] = 3; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockFlowerPot.SyntheticClass_1.a[BlockWood.EnumLogVariant.JUNGLE.ordinal()] = 4; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockFlowerPot.SyntheticClass_1.a[BlockWood.EnumLogVariant.ACACIA.ordinal()] = 5; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockFlowerPot.SyntheticClass_1.a[BlockWood.EnumLogVariant.DARK_OAK.ordinal()] = 6; + } catch (NoSuchFieldError ignored) { + } + + } + } + + public enum EnumFlowerPotContents implements INamable { + + EMPTY("empty"), POPPY("rose"), BLUE_ORCHID("blue_orchid"), ALLIUM("allium"), HOUSTONIA("houstonia"), RED_TULIP("red_tulip"), ORANGE_TULIP("orange_tulip"), WHITE_TULIP("white_tulip"), PINK_TULIP("pink_tulip"), OXEYE_DAISY("oxeye_daisy"), DANDELION("dandelion"), OAK_SAPLING("oak_sapling"), SPRUCE_SAPLING("spruce_sapling"), BIRCH_SAPLING("birch_sapling"), JUNGLE_SAPLING("jungle_sapling"), ACACIA_SAPLING("acacia_sapling"), DARK_OAK_SAPLING("dark_oak_sapling"), MUSHROOM_RED("mushroom_red"), MUSHROOM_BROWN("mushroom_brown"), DEAD_BUSH("dead_bush"), FERN("fern"), CACTUS("cactus"); + + private final String w; + + EnumFlowerPotContents(String s) { + this.w = s; + } + + public String toString() { + return this.w; + } + + public String getName() { + return this.w; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockFlowers.java b/azurite-server/src/main/java/net/minecraft/server/BlockFlowers.java new file mode 100644 index 0000000..778579e --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockFlowers.java @@ -0,0 +1,127 @@ +package net.minecraft.server; + +import com.google.common.base.Predicate; +import com.google.common.collect.Collections2; +import com.google.common.collect.Lists; + +import java.util.Collection; + +public abstract class BlockFlowers extends BlockPlant { + + protected BlockStateEnum TYPE; + + protected BlockFlowers() { + this.j(this.blockStateList.getBlockData().set(this.n(), this.l() == BlockFlowers.EnumFlowerType.RED ? BlockFlowers.EnumFlowerVarient.POPPY : BlockFlowers.EnumFlowerVarient.DANDELION)); + } + + public int getDropData(IBlockData iblockdata) { + return iblockdata.get(this.n()).b(); + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(this.n(), BlockFlowers.EnumFlowerVarient.a(this.l(), i)); + } + + public abstract BlockFlowers.EnumFlowerType l(); + + public IBlockState n() { + if (this.TYPE == null) { + this.TYPE = BlockStateEnum.a("type", BlockFlowers.EnumFlowerVarient.class, blockflowers_enumflowervarient -> blockflowers_enumflowervarient.a() == BlockFlowers.this.l()); + } + + return this.TYPE; + } + + public int toLegacyData(IBlockData iblockdata) { + return iblockdata.get(this.n()).b(); + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, this.n()); + } + + public enum EnumFlowerVarient implements INamable { + + DANDELION(BlockFlowers.EnumFlowerType.YELLOW, 0, "dandelion"), POPPY(BlockFlowers.EnumFlowerType.RED, 0, "poppy"), BLUE_ORCHID(BlockFlowers.EnumFlowerType.RED, 1, "blue_orchid", "blueOrchid"), ALLIUM(BlockFlowers.EnumFlowerType.RED, 2, "allium"), HOUSTONIA(BlockFlowers.EnumFlowerType.RED, 3, "houstonia"), RED_TULIP(BlockFlowers.EnumFlowerType.RED, 4, "red_tulip", "tulipRed"), ORANGE_TULIP(BlockFlowers.EnumFlowerType.RED, 5, "orange_tulip", "tulipOrange"), WHITE_TULIP(BlockFlowers.EnumFlowerType.RED, 6, "white_tulip", "tulipWhite"), PINK_TULIP(BlockFlowers.EnumFlowerType.RED, 7, "pink_tulip", "tulipPink"), OXEYE_DAISY(BlockFlowers.EnumFlowerType.RED, 8, "oxeye_daisy", "oxeyeDaisy"); + + private static final BlockFlowers.EnumFlowerVarient[][] k = new BlockFlowers.EnumFlowerVarient[BlockFlowers.EnumFlowerType.values().length][]; + private final BlockFlowers.EnumFlowerType l; + private final int m; + private final String n; + private final String o; + + EnumFlowerVarient(BlockFlowers.EnumFlowerType blockflowers_enumflowertype, int i, String s) { + this(blockflowers_enumflowertype, i, s, s); + } + + EnumFlowerVarient(BlockFlowers.EnumFlowerType blockflowers_enumflowertype, int i, String s, String s1) { + this.l = blockflowers_enumflowertype; + this.m = i; + this.n = s; + this.o = s1; + } + + public BlockFlowers.EnumFlowerType a() { + return this.l; + } + + public int b() { + return this.m; + } + + public static BlockFlowers.EnumFlowerVarient a(BlockFlowers.EnumFlowerType blockflowers_enumflowertype, int i) { + BlockFlowers.EnumFlowerVarient[] ablockflowers_enumflowervarient = BlockFlowers.EnumFlowerVarient.k[blockflowers_enumflowertype.ordinal()]; + + if (i < 0 || i >= ablockflowers_enumflowervarient.length) { + i = 0; + } + + return ablockflowers_enumflowervarient[i]; + } + + public String toString() { + return this.n; + } + + public String getName() { + return this.n; + } + + public String d() { + return this.o; + } + + static { + BlockFlowers.EnumFlowerType[] ablockflowers_enumflowertype = BlockFlowers.EnumFlowerType.values(); + int i = ablockflowers_enumflowertype.length; + + for (int j = 0; j < i; ++j) { + final BlockFlowers.EnumFlowerType blockflowers_enumflowertype = ablockflowers_enumflowertype[j]; + Collection collection = Collections2.filter(Lists.newArrayList(values()), new Predicate() { + public boolean a(BlockFlowers.EnumFlowerVarient blockflowers_enumflowervarient) { + return blockflowers_enumflowervarient.a() == blockflowers_enumflowertype; + } + + public boolean apply(Object object) { + return this.a((BlockFlowers.EnumFlowerVarient) object); + } + }); + + BlockFlowers.EnumFlowerVarient.k[blockflowers_enumflowertype.ordinal()] = (BlockFlowers.EnumFlowerVarient[]) collection.toArray(new BlockFlowers.EnumFlowerVarient[collection.size()]); + } + + } + } + + public enum EnumFlowerType { + + YELLOW, RED; + + EnumFlowerType() { + } + + public BlockFlowers a() { + return this == BlockFlowers.EnumFlowerType.YELLOW ? Blocks.YELLOW_FLOWER : Blocks.RED_FLOWER; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockFlowing.java b/azurite-server/src/main/java/net/minecraft/server/BlockFlowing.java new file mode 100644 index 0000000..1a3feea --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockFlowing.java @@ -0,0 +1,358 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.AzuriteConfig; +import org.bukkit.Bukkit; +import org.bukkit.block.BlockFace; +import org.bukkit.craftbukkit.block.CraftBlock; +import org.bukkit.event.block.BlockFromToEvent; + +import java.util.Iterator; +import java.util.Random; +import java.util.Set; + +public class BlockFlowing extends BlockFluids { + + int a; + + protected BlockFlowing(Material material) { + super(material); + } + + private void f(World world, BlockPosition blockposition, IBlockData iblockdata) { + world.setTypeAndData(blockposition, b(this.material).getBlockData().set(BlockFlowing.LEVEL, iblockdata.get(BlockFlowing.LEVEL)), 2); + } + + public void b(World world, BlockPosition blockposition, IBlockData iblockdata, Random random) { + // CraftBukkit start + int x = blockposition.getX(), y = blockposition.getY(), z = blockposition.getZ(); + + org.bukkit.block.Block source = world.getWorld().getBlockAt(x, y, z); + // CraftBukkit end + int i = iblockdata.get(BlockFlowing.LEVEL); + byte b0 = 1; + if (this.material == Material.LAVA && !world.worldProvider.n()) { + b0 = 2; + } + + BlockPosition pos = new BlockPosition(x, y - 1, z); + IBlockData iblockdata1 = world.getType(x, y - 1, z); + + int j = this.getFlowSpeed(world, x, y, z); // PaperSpigot + int k; + + if (i > 0) { + int l = -100; + + this.a = 0; + + EnumDirection enumdirection; + + for (Iterator iterator = EnumDirection.EnumDirectionLimit.HORIZONTAL.iterator(); iterator.hasNext(); l = this.a(world, x + enumdirection.getAdjacentX(), y, z + enumdirection.getAdjacentZ(), l)) { + enumdirection = iterator.next(); + } + + int i1 = l + b0; + + if (i1 >= 8 || l < 0) { + i1 = -1; + } + + int eInt = e(world, x, y + 1, z); + if (eInt >= 0) { + k = eInt; + if (k >= 8) { + i1 = k; + } else { + i1 = k + 8; + } + } + + if (AzuriteConfig.infiniteWaterSources.getValue() && this.a >= 2 && this.material == Material.WATER) { + Block block = iblockdata1.getBlock(); + if (block.getMaterial().isBuildable()) { + i1 = 0; + } else if (block.getMaterial() == this.material && iblockdata1.get(BlockFlowing.LEVEL) == 0) { + i1 = 0; + } + } + + if (!world.paperSpigotConfig.fastDrainLava && this.material == Material.LAVA && i1 < 8 && i1 > i && random.nextInt(4) != 0) { // PaperSpigot + j *= 4; + } + + if (i1 == i) { + this.f(world, blockposition, iblockdata); + } else { + i = i1; + if (i1 < 0 || canFastDrain(world, x, y, z)) { // PaperSpigot - Fast draining + world.setAir(blockposition); + } else { + iblockdata = iblockdata.set(BlockFlowing.LEVEL, i1); + world.setTypeAndData(blockposition, iblockdata, 2); + world.a(blockposition, this, j); + // PaperSpigot start - Optimize draining + world.d(x - 1, y, z, this); + world.d(x + 1, y, z, this); + world.d(x, y + 1, z, this); + world.d(x, y, z - 1, this); + world.d(x, y, z + 1, this); + // PaperSpigot end + } + } + } else { + this.f(world, blockposition, iblockdata); + } + + if (world.getType(x, y, z).getBlock().getMaterial() != material) + return; + + // PaperSpigot - Stop updating flowing block if material has changed + IBlockData iblockdata2 = world.getType(x, y - 1, z); + + if (this.h(iblockdata2.getBlock())) { + if (checkSponge(source)) + return; + + BlockFromToEvent event = new BlockFromToEvent(source, BlockFace.DOWN); + Bukkit.getPluginManager().callEvent(event); + + if (!event.isCancelled()) { + if (AzuriteConfig.stoneGenerating.getValue() && material == Material.LAVA && world.getType(x, y - 1, z).getBlock().getMaterial() == Material.WATER) { + world.setTypeUpdate(pos, Blocks.STONE.getBlockData()); + fizz(world, x, y - 1, z); + return; + } + + if (i >= 8) { + flow(world, pos, iblockdata2, i); + } else { + flow(world, pos, iblockdata2, i + 8); + } + } + } else if (i >= 0 && (i == 0 || this.g(iblockdata2.getBlock()))) { + Set set = this.f(world, x, y, z); + + k = i + b0; + if (i >= 8) { + k = 1; + } + + if (k >= 8) { + return; + } + + for (EnumDirection enumdirection1 : set) { + BlockFace blockFace = CraftBlock.notchToBlockFace(enumdirection1); + + if (checkSponge(source)) + return; + + BlockFromToEvent event = new BlockFromToEvent(source, blockFace); + Bukkit.getPluginManager().callEvent(event); + + if (!event.isCancelled()) { + BlockPosition shifted = blockposition.shift(enumdirection1); + this.flow(world, shifted, world.getType(shifted), k); + } + } + } + + } + + public boolean checkSponge(org.bukkit.block.Block source) { + int radius = AzuriteConfig.spongeRadius.getValue(); + + if (radius > 0 && AzuriteConfig.spongePreventWaterFlow.getValue()) { + radius += 1; + for (int searchX = -radius; searchX <= radius; searchX++) { + for (int searchY = -radius; searchY <= radius; searchY++) { + for (int searchZ = -radius; searchZ <= radius; searchZ++) { + if (source.getRelative(searchX, searchY, searchZ).getType() == org.bukkit.Material.SPONGE) { + return true; + } + } + } + } + } + return false; + } + + private void flow(World world, BlockPosition blockposition, IBlockData iblockdata, int i) { + int x = blockposition.getX(), y = blockposition.getY(), z = blockposition.getZ(); + Block block = iblockdata.getBlock(); + if (world.isLoaded(x, y, z) && this.h(block)) { // CraftBukkit - add isLoaded check + if (block != Blocks.AIR) { + if (this.material != Material.LAVA) { + block.b(world, blockposition, iblockdata, 0); + } + } + + world.setTypeAndData(blockposition, this.getBlockData().set(LEVEL, i), 3, false, false); + } + } + + private int a(World world, int x, int y, int z, int i, EnumDirection enumdirection) { + int j = 1000; + for (EnumDirection enumdirection1 : EnumDirection.EnumDirectionLimit.HORIZONTAL) { + if (enumdirection1 != enumdirection) { + int x1 = x + enumdirection.getAdjacentX(); + int y1 = y + enumdirection.getAdjacentY(); + int z1 = z + enumdirection.getAdjacentZ(); + IBlockData iblockdata = world.getType(x1, y1, z1); + Block block = iblockdata.getBlock(); + if (!this.g(block) && (block.getMaterial() != this.material || iblockdata.get(BlockFlowing.LEVEL) > 0)) { + if (!this.g(world.getType(x1, y1 - 1, z1).getBlock())) { + return i; + } + + if (i < 4) { + int k = this.a(world, x1, y1, z1, i + 1, enumdirection1.opposite()); + + if (k < j) { + j = k; + } + } + } + } + } + + return j; + } + + private Set f(World world, int x, int y, int z) { + int i = 1000; + Set enumset = new ArraySet<>(); + for (EnumDirection enumdirection : EnumDirection.EnumDirectionLimit.HORIZONTAL) { + int x1 = x + enumdirection.getAdjacentX(), y1 = y + enumdirection.getAdjacentY(), z1 = z + enumdirection.getAdjacentZ(); + IBlockData iblockdata = world.getType(x1, y1, z1); + Block block = iblockdata.getBlock(); + if (!this.g(block) && (block.getMaterial() != this.material || iblockdata.get(BlockFlowing.LEVEL) > 0)) { + int j; + + if (this.g(world.getType(x1, y1 - 1, z1).getBlock())) { + j = this.a(world, x1, y1, z1, 4, enumdirection.opposite()); + } else { + j = 0; + } + if (j < i) { + enumset.clear(); + } + + if (j <= i) { + enumset.add(enumdirection); + i = j; + } + } + } + + return enumset; + } + + private boolean g(Block block) { + return block instanceof BlockDoor + || (!AzuriteConfig.waterDestroyRedstone.getValue() && (block instanceof BlockButtonAbstract || block instanceof BlockRedstoneWire || block instanceof BlockDiodeAbstract || block instanceof BlockLever || block instanceof BlockRedstoneTorch)) + || block == Blocks.STANDING_SIGN + || block == Blocks.LADDER + || block == Blocks.REEDS + || (block.material == Material.PORTAL || block.material.isSolid()) + || (!AzuriteConfig.waterDestroysWeb.getValue() && block == Blocks.WEB); + } + + protected int a(World world, int x, int y, int z, int i) { + int j = this.e(world, x, y, z); + + if (j < 0) { + return i; + } else { + if (j == 0) { + ++this.a; + } + + if (j >= 8) { + j = 0; + } + + return i >= 0 && j >= i ? i : j; + } + } + + private boolean h(Block block) { + Material material = block.getMaterial(); + return material != this.material && material != Material.LAVA && !this.g(block); + } + + public boolean lookUpData(World world, int x, int y, int z, Material material, int data) { + IBlockData state = world.getType(x, y, z); + return state.getBlock().getMaterial() == material && getData(state) < data; + } + + public void onPlace(World world, BlockPosition blockposition, IBlockData iblockdata) { + if (!this.e(world, blockposition, iblockdata)) { + world.a(blockposition, this, this.getFlowSpeed(world, blockposition.getX(), blockposition.getY(), blockposition.getZ())); // PaperSpigot + } + } + + public int getFlowSpeed(World world, int x, int y, int z) { + if (this.getMaterial() == Material.LAVA) { + return world.worldProvider.o() ? world.paperSpigotConfig.lavaFlowSpeedNether : world.paperSpigotConfig.lavaFlowSpeedNormal; + } else if (this.getMaterial() == Material.WATER) { + if (world.getType(x, y, z - 1).getBlock().getMaterial() == Material.LAVA || world.getType(x, y, z + 1).getBlock().getMaterial() == Material.LAVA || world.getType(x - 1, y, z).getBlock().getMaterial() == Material.LAVA || world.getType(x + 1, y, z).getBlock().getMaterial() == Material.LAVA) { + return world.paperSpigotConfig.waterOverLavaFlowSpeed; + } else { + return 5; + } + } + return super.a(world); + } + + /** + * PaperSpigot - Data check method for fast draining + */ + public int getData(World world, int x, int y, int z) { + int data = this.e(world, x, y, z); + return data < 8 ? data : 0; + } + + public int getData(IBlockData block) { + int data = block.getBlock().getMaterial() == this.material ? block.get(BlockFluids.LEVEL) : -1; + return data < 8 ? data : 0; + } + + public boolean canFastDrain(World world, int x, int y, int z) { + boolean result = false; + int data = getData(world, x, y, z); + if (this.material == Material.WATER) { + if (world.paperSpigotConfig.fastDrainWater) { + result = true; + if (getData(world, x, y - 1, z) < 0) { + result = false; + } else if (lookUpData(world, x, y, z - 1, Material.WATER, data)) { + result = false; + } else if (lookUpData(world, x, y, z + 1, Material.WATER, data)) { + result = false; + } else if (lookUpData(world, x - 1, y, z, Material.WATER, data)) { + result = false; + } else if (lookUpData(world, x + 1, y, z, Material.WATER, data)) { + result = false; + } + } + } else if (this.material == Material.LAVA) { + if (world.paperSpigotConfig.fastDrainLava) { + result = true; + if (getData(world, x, y - 1, z) < 0 || world.getType(x, y + 1, z).getBlock().getMaterial() != Material.AIR) { + result = false; + } else if (lookUpData(world, x, y, z - 1, Material.LAVA, data)) { + result = false; + } else if (lookUpData(world, x, y, z + 1, Material.LAVA, data)) { + result = false; + } else if (lookUpData(world, x - 1, y, z, Material.LAVA, data)) { + result = false; + } else if (lookUpData(world, x + 1, y, z, Material.LAVA, data)) { + result = false; + } + } + } + return result; + } + +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockFluids.java b/azurite-server/src/main/java/net/minecraft/server/BlockFluids.java new file mode 100644 index 0000000..b46f391 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockFluids.java @@ -0,0 +1,227 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.AzuriteConfig; + +import java.util.List; +import java.util.Random; + +public abstract class BlockFluids extends Block { + + public static final BlockStateInteger LEVEL = BlockStateInteger.of("level", 0, 15); + + protected BlockFluids(Material material) { + super(material); + this.j(this.blockStateList.getBlockData().set(BlockFluids.LEVEL, 0)); + this.a(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + this.a(true); + } + + @Override + public void a(World world, BlockPosition blockposition, IBlockData iblockdata, AxisAlignedBB axisalignedbb, List list, Entity entity) { + if (entity instanceof EntityFallingBlock || entity instanceof EntityTNTPrimed) + return; + super.a(world, blockposition, iblockdata, axisalignedbb, list, entity); + } + + public boolean b(IBlockAccess iblockaccess, BlockPosition blockposition) { + return this.material != Material.LAVA; + } + + public static float b(int i) { + if (i >= 8) { + i = 0; + } + + return (float) (i + 1) / 9.0F; + } + + protected int e(IBlockAccess iblockaccess, int x, int y, int z) { + IBlockData b = iblockaccess.getType(x, y, z); + return b.getBlock().getMaterial() == this.material ? b.get(BlockFluids.LEVEL) : -1; + } + + protected int f(IBlockAccess iblockaccess, int x, int y, int z) { + int i = this.e(iblockaccess, x, y, z); + + return i >= 8 ? 0 : i; + } + + protected int e(IBlockData b) { + return b.getBlock().getMaterial() == this.material ? b.get(BlockFluids.LEVEL) : -1; + } + + protected int f(IBlockData b) { + int i = this.e(b); + + return i >= 8 ? 0 : i; + } + + public boolean d() { + return false; + } + + public boolean c() { + return false; + } + + public boolean a(IBlockData iblockdata, boolean flag) { + return flag && iblockdata.get(BlockFluids.LEVEL) == 0; + } + + public boolean bA(IBlockAccess iblockaccess, int x, int y, int z, EnumDirection enumdirection) { + Material material = iblockaccess.getType(x, y, z).getBlock().getMaterial(); + + return material != this.material && (enumdirection == EnumDirection.UP || (material != Material.ICE && material.isBuildable())); + } + + public AxisAlignedBB a(World world, BlockPosition blockposition, IBlockData iblockdata) { + return null; + } + + public int b() { + return 1; + } + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + return null; + } + + public int a(Random random) { + return 0; + } + + protected Vec3D h(IBlockAccess iblockaccess, BlockPosition blockposition) { + Vec3D.MutableVec3D mutableVec3D = new Vec3D.MutableVec3D(); // Azurite + int bX = blockposition.getX(), bY = blockposition.getY(), bZ = blockposition.getZ(); + int i = this.f(iblockaccess, bX, bY, bZ); + + int x, y, z; + + for (EnumDirection enumdirection : EnumDirection.EnumDirectionLimit.HORIZONTAL) { + x = bX + enumdirection.getAdjacentX(); + y = bY + enumdirection.getAdjacentY(); + z = bZ + enumdirection.getAdjacentZ(); + + int j = this.f(iblockaccess, x, y, z); + int k; + + if (j < 0) { + if (!iblockaccess.getType(x, y, z).getBlock().getMaterial().isSolid()) { + j = this.f(iblockaccess, x, y - 1, z); + if (j >= 0) { + k = j - (i - 8); + mutableVec3D.add(((x - bX) * k), ((y - bY) * k), ((z - bZ) * k)); // Azurite + } + } + } else { + k = j - i; + mutableVec3D.add(((x - bX) * k), ((y - bY) * k), ((z - bZ) * k)); // Azurite + } + } + + if (iblockaccess.getType(bX, bY, bZ).get(BlockFluids.LEVEL) >= 8) { + for (EnumDirection enumdirection : EnumDirection.EnumDirectionLimit.HORIZONTAL) { + x = bX + enumdirection.getAdjacentX(); + y = bY + enumdirection.getAdjacentY(); + z = bZ + enumdirection.getAdjacentZ(); + + if (this.bA(iblockaccess, x, y, z, enumdirection) + || this.bA(iblockaccess, x, y + 1, z, enumdirection)) { + mutableVec3D.a().add(0.0D, -6.0D, 0.0D); + break; + } + } + } + + return mutableVec3D.a(); + } + + public Vec3D a(World world, BlockPosition blockposition, Entity entity, Vec3D vec3d) { + return vec3d.e(this.h(world, blockposition)); + } + + public int a(World world) { + return this.material == Material.WATER ? 5 : (this.material == Material.LAVA ? (world.worldProvider.o() ? 10 : 30) : 0); + } + + public void onPlace(World world, BlockPosition blockposition, IBlockData iblockdata) { + this.e(world, blockposition, iblockdata); + } + + public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) { + this.e(world, blockposition, iblockdata); + } + + public boolean e(World world, BlockPosition blockposition, IBlockData iblockdata) { + if (this.material == Material.LAVA) { + boolean flag = false; + + int x = blockposition.getX(), y = blockposition.getY(), z = blockposition.getZ(); + for (EnumDirection enumdirection : EnumDirection.values()) { + if (enumdirection != EnumDirection.DOWN && world.getType(x + enumdirection.getAdjacentX(), y + enumdirection.getAdjacentY(), z + enumdirection.getAdjacentZ()).getBlock().getMaterial() == Material.WATER) { + flag = true; + break; + } + } + + if (flag) { + int integer = iblockdata.get(BlockFluids.LEVEL); + if (integer >= 0) { + if (integer == 0 && AzuriteConfig.obsidianGenerating.getValue()) { + world.setTypeUpdate(blockposition, Blocks.OBSIDIAN.getBlockData()); + } else if (AzuriteConfig.cobbleGenerating.getValue()) { + world.setTypeUpdate(blockposition, Blocks.COBBLESTONE.getBlockData()); + } + fizz(world, blockposition); + return true; + } + } + } + + return false; + } + + protected void fizz(World world, BlockPosition blockposition) { + fizz(world, blockposition.getX(), blockposition.getY(), blockposition.getZ()); + } + + protected void fizz(World world, int d0, int d1, int d2) { + if (AzuriteConfig.fluidFizzSounds.getValue()) { + world.makeSound(d0 + 0.5D, d1 + 0.5D, d2 + 0.5D, "random.fizz", 0.5F, 2.6F + (world.random.nextFloat() - world.random.nextFloat()) * 0.8F); + for (int i = 0; i < 8; i++) + world.addParticle(EnumParticle.SMOKE_LARGE, d0 + Math.random(), d1 + 1.2D, d2 + Math.random(), 0.0D, 0.0D, 0.0D, EnumParticle.EMPTY_ARRAY); + } + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockFluids.LEVEL, i); + } + + public int toLegacyData(IBlockData iblockdata) { + return iblockdata.get(BlockFluids.LEVEL); + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, BlockFluids.LEVEL); + } + + public static BlockFlowing a(Material material) { + if (material == Material.WATER) { + return Blocks.FLOWING_WATER; + } else if (material == Material.LAVA) { + return Blocks.FLOWING_LAVA; + } else { + throw new IllegalArgumentException("Invalid material"); + } + } + + public static BlockStationary b(Material material) { + if (material == Material.WATER) { + return Blocks.WATER; + } else if (material == Material.LAVA) { + return Blocks.LAVA; + } else { + throw new IllegalArgumentException("Invalid material"); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockFurnace.java b/azurite-server/src/main/java/net/minecraft/server/BlockFurnace.java new file mode 100644 index 0000000..b026653 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockFurnace.java @@ -0,0 +1,138 @@ +package net.minecraft.server; + +import java.util.Random; + +public class BlockFurnace extends BlockContainer { + + public static final BlockStateDirection FACING = BlockStateDirection.of("facing", EnumDirection.EnumDirectionLimit.HORIZONTAL); + private static boolean N; + + protected BlockFurnace(boolean flag) { + super(Material.STONE); + this.j(this.blockStateList.getBlockData().set(BlockFurnace.FACING, EnumDirection.NORTH)); + } + + public static void a(boolean flag, World world, BlockPosition blockposition) { + IBlockData iblockdata = world.getType(blockposition); + TileEntity tileentity = world.getTileEntity(blockposition); + + BlockFurnace.N = true; + if (flag) { + world.setTypeAndData(blockposition, Blocks.LIT_FURNACE.getBlockData().set(BlockFurnace.FACING, iblockdata.get(BlockFurnace.FACING)), 3); + world.setTypeAndData(blockposition, Blocks.LIT_FURNACE.getBlockData().set(BlockFurnace.FACING, iblockdata.get(BlockFurnace.FACING)), 3); + } else { + world.setTypeAndData(blockposition, Blocks.FURNACE.getBlockData().set(BlockFurnace.FACING, iblockdata.get(BlockFurnace.FACING)), 3); + world.setTypeAndData(blockposition, Blocks.FURNACE.getBlockData().set(BlockFurnace.FACING, iblockdata.get(BlockFurnace.FACING)), 3); + } + + BlockFurnace.N = false; + if (tileentity != null) { + tileentity.D(); + world.setTileEntity(blockposition, tileentity); + } + + } + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + return Item.getItemOf(Blocks.FURNACE); + } + + /* // PandaSpigot - comment out - SPIGOT-1401 + public void onPlace(World world, BlockPosition blockposition, IBlockData iblockdata) { + this.e(world, blockposition, iblockdata); + } + + private void e(World world, BlockPosition blockposition, IBlockData iblockdata) { + Block block = world.getType(blockposition.north()).getBlock(); + Block block1 = world.getType(blockposition.south()).getBlock(); + Block block2 = world.getType(blockposition.west()).getBlock(); + Block block3 = world.getType(blockposition.east()).getBlock(); + EnumDirection enumdirection = iblockdata.get(BlockFurnace.FACING); + + if (enumdirection == EnumDirection.NORTH && block.o() && !block1.o()) { + enumdirection = EnumDirection.SOUTH; + } else if (enumdirection == EnumDirection.SOUTH && block1.o() && !block.o()) { + enumdirection = EnumDirection.NORTH; + } else if (enumdirection == EnumDirection.WEST && block2.o() && !block3.o()) { + enumdirection = EnumDirection.EAST; + } else if (enumdirection == EnumDirection.EAST && block3.o() && !block2.o()) { + enumdirection = EnumDirection.WEST; + } + + world.setTypeAndData(blockposition, iblockdata.set(BlockFurnace.FACING, enumdirection), 2); + } + */ // PandaSpigot + + public boolean interact(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman, EnumDirection enumdirection, float f, float f1, float f2) { + TileEntity tileentity = world.getTileEntity(blockposition); + + if (tileentity instanceof TileEntityFurnace) { + entityhuman.openContainer((TileEntityFurnace) tileentity); + } + + return true; + } + + public TileEntity a(World world, int i) { + return new TileEntityFurnace(); + } + + public IBlockData getPlacedState(World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2, int i, EntityLiving entityliving) { + return this.getBlockData().set(BlockFurnace.FACING, entityliving.getDirection().opposite()); + } + + public void postPlace(World world, BlockPosition blockposition, IBlockData iblockdata, EntityLiving entityliving, ItemStack itemstack) { + world.setTypeAndData(blockposition, iblockdata.set(BlockFurnace.FACING, entityliving.getDirection().opposite()), 2); + if (itemstack.hasName()) { + TileEntity tileentity = world.getTileEntity(blockposition); + + if (tileentity instanceof TileEntityFurnace) { + ((TileEntityFurnace) tileentity).a(itemstack.getName()); + } + } + + } + + public void remove(World world, BlockPosition blockposition, IBlockData iblockdata) { + if (!BlockFurnace.N) { + TileEntity tileentity = world.getTileEntity(blockposition); + + if (tileentity instanceof TileEntityFurnace) { + InventoryUtils.dropInventory(world, blockposition, (TileEntityFurnace) tileentity); + world.updateAdjacentComparators(blockposition, this); + } + } + + super.remove(world, blockposition, iblockdata); + } + + public boolean isComplexRedstone() { + return true; + } + + public int l(World world, BlockPosition blockposition) { + return Container.a(world.getTileEntity(blockposition)); + } + + public int b() { + return 3; + } + + public IBlockData fromLegacyData(int i) { + EnumDirection enumdirection = EnumDirection.fromType1(i); + + if (enumdirection.k() == EnumDirection.EnumAxis.Y) { + enumdirection = EnumDirection.NORTH; + } + + return this.getBlockData().set(BlockFurnace.FACING, enumdirection); + } + + public int toLegacyData(IBlockData iblockdata) { + return iblockdata.get(BlockFurnace.FACING).a(); + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, BlockFurnace.FACING); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockGlass.java b/azurite-server/src/main/java/net/minecraft/server/BlockGlass.java new file mode 100644 index 0000000..7879084 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockGlass.java @@ -0,0 +1,23 @@ +package net.minecraft.server; + +import java.util.Random; + +public class BlockGlass extends BlockHalfTransparent { + + public BlockGlass(Material material, boolean flag) { + super(material, flag); + this.a(CreativeModeTab.b); + } + + public int a(Random random) { + return 0; + } + + public boolean d() { + return false; + } + + protected boolean I() { + return true; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockGrass.java b/azurite-server/src/main/java/net/minecraft/server/BlockGrass.java new file mode 100644 index 0000000..a17096e --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockGrass.java @@ -0,0 +1,218 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.AzuriteConfig; +import org.bukkit.Bukkit; +import org.bukkit.block.BlockState; +import org.bukkit.craftbukkit.event.CraftEventFactory; +import org.bukkit.craftbukkit.util.CraftMagicNumbers; +import org.bukkit.event.block.BlockFadeEvent; +import org.bukkit.event.block.BlockSpreadEvent; + +import java.util.Random; + +public class BlockGrass extends Block implements IBlockFragilePlantElement { + + public static final BlockStateBoolean SNOWY = BlockStateBoolean.of("snowy"); + + protected BlockGrass() { + super(Material.GRASS); + this.j(this.blockStateList.getBlockData().set(BlockGrass.SNOWY, false)); + this.a(true); + this.a(CreativeModeTab.b); + } + + public IBlockData updateState(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { + Block block = iblockaccess.getType(blockposition.getX(), blockposition.getY() + 1, blockposition.getZ()).getBlock(); + return iblockdata.set(BlockGrass.SNOWY, block == Blocks.SNOW || block == Blocks.SNOW_LAYER); + } + + @Override + public void optimizedTick(Chunk chunk, int x, int y, int z, IBlockData iblockdata, Random random) { + int lightLevel = 0; + + boolean grassSpread = AzuriteConfig.grassSpread.getValue(); + boolean grassSpreadLight = AzuriteConfig.grassSpreadLight.getValue(); + + if (grassSpread || grassSpreadLight) { + lightLevel = chunk.getLightLevelWithNeighbours(x & 15, y + 1, z & 15); + } + + if (grassSpread && lightLevel < 4 && chunk.getTypeAbs(x, y + 1, z).p() > 2) { + // CraftBukkit start + // world.setTypeUpdate(blockposition, Blocks.DIRT.getBlockData()); + org.bukkit.World bworld = chunk.world.getWorld(); + BlockState blockState = bworld.getBlockAt(x, y, z).getState(); + blockState.setType(CraftMagicNumbers.getMaterial(Blocks.DIRT)); + + BlockFadeEvent event = new BlockFadeEvent(blockState.getBlock(), blockState); + Bukkit.getServer().getPluginManager().callEvent(event); + + if (!event.isCancelled()) { + blockState.update(true); + } + // CraftBukkit end + } else if (!grassSpreadLight || lightLevel >= 9) { + int growthIterations = Math.min(4, Math.max(20, (int) (4 * 100F / chunk.world.growthOdds))); + Chunk cache = null; // Azurite - Reduce chunk lookups + + for (int i = 0; i < growthIterations; ++i) { // Spigot + int offsetX = random.nextInt(3) - 1; + int offsetY = random.nextInt(5) - 3; + int offsetZ = random.nextInt(3) - 1; + int chunkX = x + offsetX >> 4; + int chunkZ = z + offsetZ >> 4; + + Chunk fetch; + if (cache != null && cache.locX == chunkX && cache.locZ == chunkZ) { + fetch = cache; + } else { + fetch = chunk.world.getChunkAt(chunkX, chunkZ); + cache = fetch; + } + + IBlockData iblockdata1 = fetch.getBlockData(x + offsetX, y + offsetY, z + offsetZ); + + if (iblockdata1.getBlock() == Blocks.DIRT && iblockdata1.get(BlockDirt.VARIANT) == BlockDirt.EnumDirtVariant.DIRT + && fetch.getLightLevelWithNeighbours((x & 15) + offsetX, y + offsetY + 1, (z & 15) + offsetZ) >= 4 + && fetch.getTypePossibleOutOfBounds((x & 15) + offsetX, y + offsetY + 1, (z & 15) + offsetZ).p() <= 2) { + // CraftBukkit start + // world.setTypeUpdate(blockposition1, Blocks.GRASS.getBlockData()); + org.bukkit.World bworld = chunk.world.getWorld(); + BlockState blockState = bworld.getBlockAt(x + offsetX, y + offsetY, z + offsetZ).getState(); + blockState.setType(CraftMagicNumbers.getMaterial(Blocks.GRASS)); + + BlockSpreadEvent event = new BlockSpreadEvent(blockState.getBlock(), bworld.getBlockAt(x + offsetX, y + offsetY, z + offsetZ), blockState); + Bukkit.getServer().getPluginManager().callEvent(event); + + if (!event.isCancelled()) { + blockState.update(true); + } + // CraftBukkit end + } + } + } + } + + public void b(World world, BlockPosition blockposition, IBlockData iblockdata, Random random) { + int x = blockposition.getX(), y = blockposition.getY(), z = blockposition.getZ(); + + int lightLevel = 0; + if (AzuriteConfig.grassSpread.getValue() || AzuriteConfig.grassSpreadLight.getValue()) + lightLevel = world.getLightLevel(x, y + 1, z); + + if (AzuriteConfig.grassSpread.getValue() && lightLevel < 4 && world.getType(x, y + 1, z).getBlock().p() > 2) { + // CraftBukkit start + // world.setTypeUpdate(blockposition, Blocks.DIRT.getBlockData()); + org.bukkit.World bworld = world.getWorld(); + BlockState blockState = bworld.getBlockAt(x, y, z).getState(); + blockState.setType(CraftMagicNumbers.getMaterial(Blocks.DIRT)); + + BlockFadeEvent event = new BlockFadeEvent(blockState.getBlock(), blockState); + world.getServer().getPluginManager().callEvent(event); + + if (!event.isCancelled()) { + blockState.update(true); + } + // CraftBukkit end + } else if (!AzuriteConfig.grassSpreadLight.getValue() || lightLevel >= 9) { + for (int i = 0; i < Math.min(4, Math.max(20, (int) (4 * 100F / world.growthOdds))); ++i) { // Spigot + BlockPosition blockposition1 = blockposition.a(random.nextInt(3) - 1, random.nextInt(5) - 3, random.nextInt(3) - 1); + Block block = world.getType(blockposition1.getX(), blockposition1.getY() + 1, blockposition1.getZ()).getBlock(); + IBlockData iblockdata1 = world.getType(blockposition1); + + if (iblockdata1.getBlock() == Blocks.DIRT + && iblockdata1.get(BlockDirt.VARIANT) == BlockDirt.EnumDirtVariant.DIRT + && world.getLightLevel(blockposition1.getX(), blockposition1.getY() + 1, blockposition1.getZ()) >= 4 && block.p() <= 2) { + // CraftBukkit start + // world.setTypeUpdate(blockposition1, Blocks.GRASS.getBlockData()); + org.bukkit.World bworld = world.getWorld(); + BlockState blockState = bworld + .getBlockAt(blockposition1.getX(), blockposition1.getY(), blockposition1.getZ()) + .getState(); + blockState.setType(CraftMagicNumbers.getMaterial(Blocks.GRASS)); + + BlockSpreadEvent event = new BlockSpreadEvent(blockState.getBlock(), bworld.getBlockAt(x, y, z), + blockState); + world.getServer().getPluginManager().callEvent(event); + + if (!event.isCancelled()) { + blockState.update(true); + } + // CraftBukkit end + } + } + } + } + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + return Blocks.DIRT.getDropType( + Blocks.DIRT.getBlockData().set(BlockDirt.VARIANT, BlockDirt.EnumDirtVariant.DIRT), random, i); + } + + public boolean a(World world, BlockPosition blockposition, IBlockData iblockdata, boolean flag) { + return true; + } + + public boolean a(World world, Random random, BlockPosition blockposition, IBlockData iblockdata) { + return true; + } + + public void b(World world, Random random, BlockPosition blockposition, IBlockData iblockdata) { + BlockPosition blockposition1 = blockposition.up(); + int i = 0; + + while (i < 128) { + BlockPosition blockposition2 = blockposition1; + int j = 0; + + while (true) { + if (j < i / 16) { + blockposition2 = blockposition2.a(random.nextInt(3) - 1, + (random.nextInt(3) - 1) * random.nextInt(3) / 2, random.nextInt(3) - 1); + if (world.getType(blockposition2.getX(), blockposition2.getY() - 1, blockposition2.getZ()).getBlock() == Blocks.GRASS + && !world.getType(blockposition2).getBlock().isOccluding()) { + ++j; + continue; + } + } else if (world.getType(blockposition2).getBlock().material == Material.AIR) { + if (random.nextInt(8) == 0) { + BlockFlowers.EnumFlowerVarient blockflowers_enumflowervarient = world.getBiome(blockposition2) + .a(random, blockposition2); + BlockFlowers blockflowers = blockflowers_enumflowervarient.a().a(); + IBlockData iblockdata1 = blockflowers.getBlockData().set(blockflowers.n(), + blockflowers_enumflowervarient); + + if (blockflowers.f(world, blockposition2, iblockdata1)) { + // world.setTypeAndData(blockposition2, iblockdata1, 3); // CraftBukkit + CraftEventFactory.handleBlockGrowEvent(world, blockposition2.getX(), blockposition2.getY(), + blockposition2.getZ(), iblockdata1.getBlock(), + iblockdata1.getBlock().toLegacyData(iblockdata1)); // CraftBukkit + } + } else { + IBlockData iblockdata2 = Blocks.TALLGRASS.getBlockData().set(BlockLongGrass.TYPE, + BlockLongGrass.EnumTallGrassType.GRASS); + + if (Blocks.TALLGRASS.f(world, blockposition2, iblockdata2)) { + // world.setTypeAndData(blockposition2, iblockdata2, 3); // CraftBukkit + CraftEventFactory.handleBlockGrowEvent(world, blockposition2.getX(), blockposition2.getY(), + blockposition2.getZ(), iblockdata2.getBlock(), + iblockdata2.getBlock().toLegacyData(iblockdata2)); // CraftBukkit + } + } + } + + ++i; + break; + } + } + + } + + public int toLegacyData(IBlockData iblockdata) { + return 0; + } + + public BlockStateList getStateList() { + return new BlockStateList(this, new IBlockState[]{BlockGrass.SNOWY}); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockGravel.java b/azurite-server/src/main/java/net/minecraft/server/BlockGravel.java new file mode 100644 index 0000000..d910b79 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockGravel.java @@ -0,0 +1,20 @@ +package net.minecraft.server; + +import java.util.Random; + +public class BlockGravel extends BlockFalling { + + public BlockGravel() {} + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + if (i > 3) { + i = 3; + } + + return random.nextInt(10 - i * 3) == 0 ? Items.FLINT : Item.getItemOf(this); + } + + public MaterialMapColor g(IBlockData iblockdata) { + return MaterialMapColor.m; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockHalfTransparent.java b/azurite-server/src/main/java/net/minecraft/server/BlockHalfTransparent.java new file mode 100644 index 0000000..19a6477 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockHalfTransparent.java @@ -0,0 +1,16 @@ +package net.minecraft.server; + +public class BlockHalfTransparent extends Block { + + protected BlockHalfTransparent(Material material, boolean flag) { + this(material, flag, material.r()); + } + + protected BlockHalfTransparent(Material material, boolean flag, MaterialMapColor materialmapcolor) { + super(material, materialmapcolor); + } + + public boolean c() { + return false; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockHardenedClay.java b/azurite-server/src/main/java/net/minecraft/server/BlockHardenedClay.java new file mode 100644 index 0000000..7b12023 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockHardenedClay.java @@ -0,0 +1,13 @@ +package net.minecraft.server; + +public class BlockHardenedClay extends Block { + + public BlockHardenedClay() { + super(Material.STONE); + this.a(CreativeModeTab.b); + } + + public MaterialMapColor g(IBlockData iblockdata) { + return MaterialMapColor.q; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockHay.java b/azurite-server/src/main/java/net/minecraft/server/BlockHay.java new file mode 100644 index 0000000..adb7255 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockHay.java @@ -0,0 +1,48 @@ +package net.minecraft.server; + +public class BlockHay extends BlockRotatable { + + public BlockHay() { + super(Material.GRASS, MaterialMapColor.t); + this.j(this.blockStateList.getBlockData().set(BlockHay.AXIS, EnumDirection.EnumAxis.Y)); + this.a(CreativeModeTab.b); + } + + public IBlockData fromLegacyData(int i) { + EnumDirection.EnumAxis enumdirection_enumaxis = EnumDirection.EnumAxis.Y; + int j = i & 12; + + if (j == 4) { + enumdirection_enumaxis = EnumDirection.EnumAxis.X; + } else if (j == 8) { + enumdirection_enumaxis = EnumDirection.EnumAxis.Z; + } + + return this.getBlockData().set(BlockHay.AXIS, enumdirection_enumaxis); + } + + public int toLegacyData(IBlockData iblockdata) { + int i = 0; + EnumDirection.EnumAxis enumdirection_enumaxis = iblockdata.get(BlockHay.AXIS); + + if (enumdirection_enumaxis == EnumDirection.EnumAxis.X) { + i |= 4; + } else if (enumdirection_enumaxis == EnumDirection.EnumAxis.Z) { + i |= 8; + } + + return i; + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, BlockHay.AXIS); + } + + protected ItemStack i(IBlockData iblockdata) { + return new ItemStack(Item.getItemOf(this), 1, 0); + } + + public IBlockData getPlacedState(World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2, int i, EntityLiving entityliving) { + return super.getPlacedState(world, blockposition, enumdirection, f, f1, f2, i, entityliving).set(BlockHay.AXIS, enumdirection.k()); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockHopper.java b/azurite-server/src/main/java/net/minecraft/server/BlockHopper.java new file mode 100644 index 0000000..e2c00b5 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockHopper.java @@ -0,0 +1,145 @@ +package net.minecraft.server; + +import java.util.List; + +public class BlockHopper extends BlockContainer { + + public static final BlockStateDirection FACING = BlockStateDirection.of("facing", enumdirection -> enumdirection != EnumDirection.UP); + public static final BlockStateBoolean ENABLED = BlockStateBoolean.of("enabled"); + + public BlockHopper() { + super(Material.ORE, MaterialMapColor.m); + this.j(this.blockStateList.getBlockData().set(BlockHopper.FACING, EnumDirection.DOWN).set(BlockHopper.ENABLED, true)); + this.a(CreativeModeTab.d); + this.a(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + } + + public static EnumDirection b(int i) { + return EnumDirection.fromType1(i & 7); + } + + public static boolean f(int i) { + return (i & 8) != 8; + } + + public void updateShape(IBlockAccess iblockaccess, BlockPosition blockposition) { + this.a(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + } + + public void a(World world, BlockPosition blockposition, IBlockData iblockdata, AxisAlignedBB axisalignedbb, List list, Entity entity) { + a(0.0F, 0.625F, 0.125F, 1.0F, 1.0F, 0.0F); + super.a(world, blockposition, iblockdata, axisalignedbb, list, entity); + a(0.0F, 0.625F, 0.875F, 1.0F, 1.0F, 1.0F); + super.a(world, blockposition, iblockdata, axisalignedbb, list, entity); + a(0.125F, 0.625F, 0.0F, 0.0F, 1.0F, 1.0F); + super.a(world, blockposition, iblockdata, axisalignedbb, list, entity); + a(0.875F, 0.625F, 0.0F, 1.0F, 1.0F, 1.0F); + super.a(world, blockposition, iblockdata, axisalignedbb, list, entity); + a(0.0F, 0.0F, 0.0F, 1.0F, 0.625F, 1.0F); + super.a(world, blockposition, iblockdata, axisalignedbb, list, entity); + updateShape(world, blockposition); + } + + public IBlockData getPlacedState(World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2, int i, EntityLiving entityliving) { + EnumDirection enumdirection1 = enumdirection.opposite(); + + if (enumdirection1 == EnumDirection.UP) { + enumdirection1 = EnumDirection.DOWN; + } + + return this.getBlockData().set(BlockHopper.FACING, enumdirection1).set(BlockHopper.ENABLED, true); + } + + public TileEntity a(World world, int i) { + return new TileEntityHopper(); + } + + public void postPlace(World world, BlockPosition blockposition, IBlockData iblockdata, EntityLiving entityliving, ItemStack itemstack) { + super.postPlace(world, blockposition, iblockdata, entityliving, itemstack); + if (itemstack.hasName()) { + TileEntity tileentity = world.getTileEntity(blockposition); + + if (tileentity instanceof TileEntityHopper) { + ((TileEntityHopper) tileentity).a(itemstack.getName()); + } + } + + } + + public void onPlace(World world, BlockPosition blockposition, IBlockData iblockdata) { + this.e(world, blockposition, iblockdata); + } + + public boolean interact(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman, EnumDirection enumdirection, float f, float f1, float f2) { + TileEntity tileentity = world.getTileEntity(blockposition); + + if (tileentity instanceof TileEntityHopper) { + entityhuman.openContainer((TileEntityHopper) tileentity); + entityhuman.b(StatisticList.P); + } + + return true; + } + + public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) { + this.e(world, blockposition, iblockdata); + } + + private void e(World world, BlockPosition blockposition, IBlockData iblockdata) { + boolean flag = !world.isBlockIndirectlyPowered(blockposition); + + if (flag != iblockdata.get(BlockHopper.ENABLED)) { + world.setTypeAndData(blockposition, iblockdata.set(BlockHopper.ENABLED, flag), 4, false, false); + } + + } + + public void remove(World world, BlockPosition blockposition, IBlockData iblockdata) { + TileEntity tileentity = world.getTileEntity(blockposition); + + if (tileentity instanceof TileEntityHopper) { + InventoryUtils.dropInventory(world, blockposition, (TileEntityHopper) tileentity); + world.updateAdjacentComparators(blockposition, this); + } + + super.remove(world, blockposition, iblockdata); + } + + public int b() { + return 3; + } + + public boolean d() { + return false; + } + + public boolean c() { + return false; + } + + public boolean isComplexRedstone() { + return true; + } + + public int l(World world, BlockPosition blockposition) { + return Container.a(world.getTileEntity(blockposition)); + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockHopper.FACING, b(i)).set(BlockHopper.ENABLED, f(i)); + } + + public int toLegacyData(IBlockData iblockdata) { + int i = iblockdata.get(BlockHopper.FACING).a(); + + if (!iblockdata.get(BlockHopper.ENABLED)) { + i |= 8; + } + + return i; + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, BlockHopper.FACING, BlockHopper.ENABLED); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockHugeMushroom.java b/azurite-server/src/main/java/net/minecraft/server/BlockHugeMushroom.java new file mode 100644 index 0000000..d446d0b --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockHugeMushroom.java @@ -0,0 +1,121 @@ +package net.minecraft.server; + +import java.util.Random; + +public class BlockHugeMushroom extends Block { + + public static final BlockStateEnum VARIANT = BlockStateEnum.of("variant", BlockHugeMushroom.EnumHugeMushroomVariant.class); + private final Block b; + + public BlockHugeMushroom(Material material, MaterialMapColor materialmapcolor, Block block) { + super(material, materialmapcolor); + this.j(this.blockStateList.getBlockData().set(BlockHugeMushroom.VARIANT, BlockHugeMushroom.EnumHugeMushroomVariant.ALL_OUTSIDE)); + this.b = block; + } + + public int a(Random random) { + return Math.max(0, random.nextInt(10) - 7); + } + + public MaterialMapColor g(IBlockData iblockdata) { + switch (BlockHugeMushroom.SyntheticClass_1.a[iblockdata.get(BlockHugeMushroom.VARIANT).ordinal()]) { + case 1: + return MaterialMapColor.e; + + case 2: + + case 3: + return MaterialMapColor.d; + + default: + return super.g(iblockdata); + } + } + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + return Item.getItemOf(this.b); + } + + public IBlockData getPlacedState(World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2, int i, EntityLiving entityliving) { + return this.getBlockData(); + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockHugeMushroom.VARIANT, BlockHugeMushroom.EnumHugeMushroomVariant.a(i)); + } + + public int toLegacyData(IBlockData iblockdata) { + return iblockdata.get(BlockHugeMushroom.VARIANT).a(); + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, BlockHugeMushroom.VARIANT); + } + + static class SyntheticClass_1 { + + static final int[] a = new int[BlockHugeMushroom.EnumHugeMushroomVariant.values().length]; + + static { + try { + BlockHugeMushroom.SyntheticClass_1.a[BlockHugeMushroom.EnumHugeMushroomVariant.ALL_STEM.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockHugeMushroom.SyntheticClass_1.a[BlockHugeMushroom.EnumHugeMushroomVariant.ALL_INSIDE.ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockHugeMushroom.SyntheticClass_1.a[BlockHugeMushroom.EnumHugeMushroomVariant.STEM.ordinal()] = 3; + } catch (NoSuchFieldError ignored) { + } + + } + } + + public enum EnumHugeMushroomVariant implements INamable { + + NORTH_WEST(1, "north_west"), NORTH(2, "north"), NORTH_EAST(3, "north_east"), WEST(4, "west"), CENTER(5, "center"), EAST(6, "east"), SOUTH_WEST(7, "south_west"), SOUTH(8, "south"), SOUTH_EAST(9, "south_east"), STEM(10, "stem"), ALL_INSIDE(0, "all_inside"), ALL_OUTSIDE(14, "all_outside"), ALL_STEM(15, "all_stem"); + + private static final BlockHugeMushroom.EnumHugeMushroomVariant[] n = new BlockHugeMushroom.EnumHugeMushroomVariant[16]; + private final int o; + private final String p; + + EnumHugeMushroomVariant(int i, String s) { + this.o = i; + this.p = s; + } + + public int a() { + return this.o; + } + + public String toString() { + return this.p; + } + + public static BlockHugeMushroom.EnumHugeMushroomVariant a(int i) { + if (i < 0 || i >= BlockHugeMushroom.EnumHugeMushroomVariant.n.length) { + i = 0; + } + + BlockHugeMushroom.EnumHugeMushroomVariant blockhugemushroom_enumhugemushroomvariant = BlockHugeMushroom.EnumHugeMushroomVariant.n[i]; + + return blockhugemushroom_enumhugemushroomvariant == null ? BlockHugeMushroom.EnumHugeMushroomVariant.n[0] : blockhugemushroom_enumhugemushroomvariant; + } + + public String getName() { + return this.p; + } + + static { + BlockHugeMushroom.EnumHugeMushroomVariant[] ablockhugemushroom_enumhugemushroomvariant = values(); + + for (EnumHugeMushroomVariant blockhugemushroom_enumhugemushroomvariant : ablockhugemushroom_enumhugemushroomvariant) { + EnumHugeMushroomVariant.n[blockhugemushroom_enumhugemushroomvariant.a()] = blockhugemushroom_enumhugemushroomvariant; + } + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockIce.java b/azurite-server/src/main/java/net/minecraft/server/BlockIce.java new file mode 100644 index 0000000..a16d933 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockIce.java @@ -0,0 +1,65 @@ +package net.minecraft.server; + +import java.util.Random; + +public class BlockIce extends BlockHalfTransparent { + + public BlockIce() { + super(Material.ICE, false); + this.frictionFactor = 0.98F; + this.a(true); + this.a(CreativeModeTab.b); + } + + public void a(World world, EntityHuman entityhuman, BlockPosition blockposition, IBlockData iblockdata, TileEntity tileentity) { + entityhuman.b(StatisticList.MINE_BLOCK_COUNT[Block.getId(this)]); + entityhuman.applyExhaustion(0.025F); + if (this.I() && EnchantmentManager.hasSilkTouchEnchantment(entityhuman)) { + ItemStack itemstack = this.i(iblockdata); + + if (itemstack != null) { + a(world, blockposition, itemstack); + } + } else { + if (world.worldProvider.n()) { + world.setAir(blockposition); + return; + } + + int i = EnchantmentManager.getBonusBlockLootEnchantmentLevel(entityhuman); + + this.b(world, blockposition, iblockdata, i); + Material material = world.getType(blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()).getBlock().getMaterial(); + + if (material.isSolid() || material.isLiquid()) { + world.setTypeUpdate(blockposition, Blocks.FLOWING_WATER.getBlockData()); + } + } + + } + + public int a(Random random) { + return 0; + } + + public void b(World world, BlockPosition blockposition, IBlockData iblockdata, Random random) { + if (world.b(EnumSkyBlock.BLOCK, blockposition) > 11 - this.p()) { + // CraftBukkit start + if (org.bukkit.craftbukkit.event.CraftEventFactory.callBlockFadeEvent(world.getWorld().getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()), world.worldProvider.n() ? Blocks.AIR : Blocks.WATER).isCancelled()) { + return; + } + // CraftBukkit end + + if (world.worldProvider.n()) { + world.setAir(blockposition); + } else { + this.b(world, blockposition, world.getType(blockposition), 0); + world.setTypeUpdate(blockposition, Blocks.WATER.getBlockData()); + } + } + } + + public int k() { + return 0; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockJukeBox.java b/azurite-server/src/main/java/net/minecraft/server/BlockJukeBox.java new file mode 100644 index 0000000..d8ae4c4 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockJukeBox.java @@ -0,0 +1,143 @@ +package net.minecraft.server; + +public class BlockJukeBox extends BlockContainer { + + public static final BlockStateBoolean HAS_RECORD = BlockStateBoolean.of("has_record"); + + protected BlockJukeBox() { + super(Material.WOOD, MaterialMapColor.l); + this.j(this.blockStateList.getBlockData().set(BlockJukeBox.HAS_RECORD, false)); + this.a(CreativeModeTab.c); + } + + public boolean interact(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman, EnumDirection enumdirection, float f, float f1, float f2) { + if (iblockdata.get(BlockJukeBox.HAS_RECORD)) { + this.dropRecord(world, blockposition, iblockdata); + iblockdata = iblockdata.set(BlockJukeBox.HAS_RECORD, false); + world.setTypeAndData(blockposition, iblockdata, 2); + return true; + } else { + return false; + } + } + + public void a(World world, BlockPosition blockposition, IBlockData iblockdata, ItemStack itemstack) { + TileEntity tileentity = world.getTileEntity(blockposition); + + if (tileentity instanceof BlockJukeBox.TileEntityRecordPlayer) { + ((BlockJukeBox.TileEntityRecordPlayer) tileentity).setRecord(new ItemStack(itemstack.getItem(), 1, itemstack.getData())); + world.setTypeAndData(blockposition, iblockdata.set(BlockJukeBox.HAS_RECORD, true), 2); + } + } + + public void dropRecord(World world, BlockPosition blockposition, IBlockData iblockdata) { + TileEntity tileentity = world.getTileEntity(blockposition); + + if (tileentity instanceof BlockJukeBox.TileEntityRecordPlayer) { + BlockJukeBox.TileEntityRecordPlayer blockjukebox_tileentityrecordplayer = (BlockJukeBox.TileEntityRecordPlayer) tileentity; + ItemStack itemstack = blockjukebox_tileentityrecordplayer.getRecord(); + + if (itemstack != null) { + world.triggerEffect(1005, blockposition, 0); + world.a(blockposition, (String) null); + blockjukebox_tileentityrecordplayer.setRecord(null); + float f = 0.7F; + double d0 = (double) (world.random.nextFloat() * f) + (double) (1.0F - f) * 0.5D; + double d1 = (double) (world.random.nextFloat() * f) + (double) (1.0F - f) * 0.2D + 0.6D; + double d2 = (double) (world.random.nextFloat() * f) + (double) (1.0F - f) * 0.5D; + ItemStack itemstack1 = itemstack.cloneItemStack(); + EntityItem entityitem = new EntityItem(world, (double) blockposition.getX() + d0, (double) blockposition.getY() + d1, (double) blockposition.getZ() + d2, itemstack1); + + entityitem.p(); + world.addEntity(entityitem); + } + } + } + + public void remove(World world, BlockPosition blockposition, IBlockData iblockdata) { + this.dropRecord(world, blockposition, iblockdata); + super.remove(world, blockposition, iblockdata); + } + + public void dropNaturally(World world, BlockPosition blockposition, IBlockData iblockdata, float f, int i) { + super.dropNaturally(world, blockposition, iblockdata, f, 0); + } + + public TileEntity a(World world, int i) { + return new BlockJukeBox.TileEntityRecordPlayer(); + } + + public boolean isComplexRedstone() { + return true; + } + + public int l(World world, BlockPosition blockposition) { + TileEntity tileentity = world.getTileEntity(blockposition); + + if (tileentity instanceof BlockJukeBox.TileEntityRecordPlayer) { + ItemStack itemstack = ((BlockJukeBox.TileEntityRecordPlayer) tileentity).getRecord(); + + if (itemstack != null) { + return Item.getId(itemstack.getItem()) + 1 - Item.getId(Items.RECORD_13); + } + } + + return 0; + } + + public int b() { + return 3; + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockJukeBox.HAS_RECORD, i > 0); + } + + public int toLegacyData(IBlockData iblockdata) { + return iblockdata.get(BlockJukeBox.HAS_RECORD) ? 1 : 0; + } + + public BlockStateList getStateList() { + return new BlockStateList(this, new IBlockState[]{BlockJukeBox.HAS_RECORD}); + } + + public static class TileEntityRecordPlayer extends TileEntity { + + private ItemStack record; + + public TileEntityRecordPlayer() { + } + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + if (nbttagcompound.hasKeyOfType("RecordItem", 10)) { + this.setRecord(ItemStack.createStack(nbttagcompound.getCompound("RecordItem"))); + } else if (nbttagcompound.getInt("Record") > 0) { + this.setRecord(new ItemStack(Item.getById(nbttagcompound.getInt("Record")), 1, 0)); + } + + } + + public void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + if (this.getRecord() != null) { + nbttagcompound.set("RecordItem", this.getRecord().save(new NBTTagCompound())); + } + + } + + public ItemStack getRecord() { + return this.record; + } + + public void setRecord(ItemStack itemstack) { + // CraftBukkit start - There can only be one + if (itemstack != null) { + itemstack.count = 1; + } + // CraftBukkit end + this.record = itemstack; + this.update(); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockLadder.java b/azurite-server/src/main/java/net/minecraft/server/BlockLadder.java new file mode 100644 index 0000000..ec93e61 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockLadder.java @@ -0,0 +1,112 @@ +package net.minecraft.server; + +public class BlockLadder extends Block { + public static final BlockStateDirection FACING = BlockStateDirection.of("facing", EnumDirection.EnumDirectionLimit.HORIZONTAL); + + protected BlockLadder() { + super(Material.ORIENTABLE); + j(this.blockStateList.getBlockData().set(FACING, EnumDirection.NORTH)); + a(CreativeModeTab.c); + } + + public AxisAlignedBB a(World paramWorld, BlockPosition paramBlockPosition, IBlockData paramIBlockData) { + updateShape(paramWorld, paramBlockPosition); + return super.a(paramWorld, paramBlockPosition, paramIBlockData); + } + + public void updateShape(IBlockAccess paramIBlockAccess, BlockPosition paramBlockPosition) { + IBlockData iBlockData = paramIBlockAccess.getType(paramBlockPosition); + if (iBlockData.getBlock() != this) + return; + switch (SyntheticClass_1.a[iBlockData.get(BlockLadder.FACING).ordinal()]) { + case 1: + a(0.0F, 0.0F, 1.0F - 0.125F, 1.0F, 1.0F, 1.0F); + return; + case 2: + a(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 0.125F); + return; + case 3: + a(1.0F - 0.125F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + return; + } + a(0.0F, 0.0F, 0.0F, 0.125F, 1.0F, 1.0F); + } + + public boolean c() { + return false; + } + + public boolean d() { + return false; + } + + public boolean canPlace(World world, BlockPosition pos) { + return world.getType(pos.getX(), pos.getY(), pos.getZ() - 1).getBlock().isOccluding() || world.getType(pos.getX() + 1, pos.getY(), pos.getZ()).getBlock().isOccluding() || world.getType(pos.getX() - 1, pos.getY(), pos.getZ()).getBlock().isOccluding() || world.getType(pos.getX(), pos.getY(), pos.getZ() + 1).getBlock().isOccluding(); + } + + public IBlockData getPlacedState(World paramWorld, BlockPosition paramBlockPosition, EnumDirection paramEnumDirection, float paramFloat1, float paramFloat2, float paramFloat3, int paramInt, EntityLiving paramEntityLiving) { + if (paramEnumDirection.k().c() && a(paramWorld, paramBlockPosition, paramEnumDirection)) + return getBlockData().set(FACING, paramEnumDirection); + for (EnumDirection enumDirection : EnumDirection.EnumDirectionLimit.HORIZONTAL) { + if (a(paramWorld, paramBlockPosition, enumDirection)) + return getBlockData().set(FACING, enumDirection); + } + return getBlockData(); + } + + public void doPhysics(World paramWorld, BlockPosition paramBlockPosition, IBlockData paramIBlockData, Block paramBlock) { + EnumDirection enumDirection = paramIBlockData.get(FACING); + if (!a(paramWorld, paramBlockPosition, enumDirection)) { + b(paramWorld, paramBlockPosition, paramIBlockData, 0); + paramWorld.setAir(paramBlockPosition); + } + super.doPhysics(paramWorld, paramBlockPosition, paramIBlockData, paramBlock); + } + + protected boolean a(World paramWorld, BlockPosition paramBlockPosition, EnumDirection paramEnumDirection) { + return paramWorld.getType(paramBlockPosition.shift(paramEnumDirection.opposite())).getBlock().isOccluding(); + } + + public IBlockData fromLegacyData(int paramInt) { + EnumDirection enumDirection = EnumDirection.fromType1(paramInt); + if (enumDirection.k() == EnumDirection.EnumAxis.Y) + enumDirection = EnumDirection.NORTH; + return getBlockData().set(FACING, enumDirection); + } + + public int toLegacyData(IBlockData paramIBlockData) { + return paramIBlockData.get(FACING).a(); + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, FACING); + } + + static class SyntheticClass_1 { + + static final int[] a = new int[EnumDirection.values().length]; + + static { + try { + SyntheticClass_1.a[EnumDirection.NORTH.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.a[EnumDirection.SOUTH.ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.a[EnumDirection.WEST.ordinal()] = 3; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.a[EnumDirection.EAST.ordinal()] = 4; + } catch (NoSuchFieldError ignored) { + } + + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockLeaves.java b/azurite-server/src/main/java/net/minecraft/server/BlockLeaves.java new file mode 100644 index 0000000..9465930 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockLeaves.java @@ -0,0 +1,202 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.AzuriteConfig; +import org.bukkit.event.block.LeavesDecayEvent; + +import java.util.Random; + +public abstract class BlockLeaves extends BlockTransparent { + + public static final BlockStateBoolean DECAYABLE = BlockStateBoolean.of("decayable"); + public static final BlockStateBoolean CHECK_DECAY = BlockStateBoolean.of("check_decay"); + int[] N; + + public BlockLeaves() { + super(Material.LEAVES, false); + this.a(true); + this.a(CreativeModeTab.c); + this.c(0.2F); + this.e(1); + this.a(BlockLeaves.h); + } + + public void remove(World world, BlockPosition blockposition, IBlockData iblockdata) { + if (AzuriteConfig.leafDecaying.getValue()) { + byte b0 = 1; + int i = b0 + 1; + int j = blockposition.getX(); + int k = blockposition.getY(); + int l = blockposition.getZ(); + + if (world.areChunksLoadedBetween(j - i, k - i, l - i, j + i, k + i, l + i)) { + for (int i1 = -b0; i1 <= b0; ++i1) { + for (int j1 = -b0; j1 <= b0; ++j1) { + for (int k1 = -b0; k1 <= b0; ++k1) { + BlockPosition blockposition1 = blockposition.a(i1, j1, k1); + IBlockData iblockdata1 = world.getType(blockposition1); + + if (iblockdata1.getBlock().getMaterial() == Material.LEAVES && !iblockdata1.get(BlockLeaves.CHECK_DECAY)) { + world.setTypeAndData(blockposition1, iblockdata1.set(BlockLeaves.CHECK_DECAY, true), 4); + } + } + } + } + } + } + } + + public void b(World world, BlockPosition blockposition, IBlockData iblockdata, Random random) { + if (AzuriteConfig.leafDecaying.getValue() && iblockdata.get(BlockLeaves.CHECK_DECAY) && iblockdata.get(BlockLeaves.DECAYABLE)) { + // Vortex start - Optimized leaf decay + int j = blockposition.getX(), k = blockposition.getY(), l = blockposition.getZ(); + + if (this.N == null) { + this.N = new int[32768]; + } + + if (world.areChunksLoadedBetween(j - 5, k - 5, l - 5, j + 5, k + 5, l + 5)) { + int k1; + int l1; + int i2; + + for (k1 = -4; k1 <= 4; ++k1) { + for (l1 = -4; l1 <= 4; ++l1) { + for (i2 = -4; i2 <= 4; ++i2) { + Block block = world.getType(j + k1, k + l1, l + i2).getBlock(); + + int i1 = (k1 + 16) * 1024 + (l1 + 16) * 32 + i2 + 16; + if (block != Blocks.LOG && block != Blocks.LOG2) { + if (block.getMaterial() == Material.LEAVES) { + this.N[i1] = -2; + } else { + this.N[i1] = -1; + } + } else { + this.N[i1] = 0; + } + } + } + } + + for (k1 = 1; k1 <= 4; ++k1) { + for (l1 = -4; l1 <= 4; ++l1) { + for (i2 = -4; i2 <= 4; ++i2) { + for (int j2 = -4; j2 <= 4; ++j2) { + int x = l1 + 16, bitX = x * 1024; + int y = i2 + 16, bitY = y * 32, + bitZ = j2 + 16; + + if (this.N[bitX + bitY + bitZ] == k1 - 1) { + + int i1 = (x - 1) * 1024 + bitY + bitZ; + if (this.N[i1] == -2) { + this.N[i1] = k1; + } + + int i3 = (x + 1) * 1024 + bitY + bitZ; + if (this.N[i3] == -2) { + this.N[i3] = k1; + } + + int i4 = bitX + (y - 1) * 32 + bitZ; + if (this.N[i4] == -2) { + this.N[i4] = k1; + } + + int i5 = bitX + (y + 1) * 32 + bitZ; + if (this.N[i5] == -2) { + this.N[i5] = k1; + } + + int i6 = bitX + bitY + (bitZ - 1); + if (this.N[i6] == -2) { + this.N[i6] = k1; + } + + int i7 = bitX + bitY + (bitZ + 1); + if (this.N[i7] == -2) { + this.N[i7] = k1; + } + } + } + } + } + } + } + + int k2 = this.N[16912]; + + if (k2 >= 0) { + world.setTypeAndData(blockposition, iblockdata.set(BlockLeaves.CHECK_DECAY, false), 4); + } else { + this.e(world, blockposition); + } + // Vortex end + } + + } + + private void e(World world, BlockPosition blockposition) { + // CraftBukkit start + LeavesDecayEvent event = new LeavesDecayEvent( + world.getWorld().getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ())); + world.getServer().getPluginManager().callEvent(event); + + if (event.isCancelled() || world.getType(blockposition).getBlock() != this) { + return; + } + // CraftBukkit end + this.b(world, blockposition, world.getType(blockposition), 0); + world.setAir(blockposition); + } + + public int a(Random random) { + return random.nextInt(20) == 0 ? 1 : 0; + } + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + return Item.getItemOf(Blocks.SAPLING); + } + + public void dropNaturally(World world, BlockPosition blockposition, IBlockData iblockdata, float f, int i) { + int j = this.d(iblockdata); + + if (i > 0) { + j -= 2 << i; + if (j < 10) { + j = 10; + } + } + + if (world.random.nextInt(j) == 0) { + a(world, blockposition, new ItemStack(getDropType(iblockdata, world.random, i), 1, this.getDropData(iblockdata))); + } + + j = 200; + if (i > 0) { + j -= 10 << i; + if (j < 40) { + j = 40; + } + } + + this.a(world, blockposition, iblockdata, j); + } + + protected void a(World world, BlockPosition blockposition, IBlockData iblockdata, int i) { + } + + protected int d(IBlockData iblockdata) { + return 20; + } + + public boolean c() { + return !this.R; + } + + public boolean w() { + return false; + } + + public abstract BlockWood.EnumLogVariant b(int i); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockLeaves1.java b/azurite-server/src/main/java/net/minecraft/server/BlockLeaves1.java new file mode 100644 index 0000000..d97a79d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockLeaves1.java @@ -0,0 +1,64 @@ +package net.minecraft.server; + +public class BlockLeaves1 extends BlockLeaves { + + public static final BlockStateEnum VARIANT = BlockStateEnum.a("variant", BlockWood.EnumLogVariant.class, blockwood_enumlogvariant -> blockwood_enumlogvariant.a() < 4); + + public BlockLeaves1() { + this.j(this.blockStateList.getBlockData().set(BlockLeaves1.VARIANT, BlockWood.EnumLogVariant.OAK).set(BlockLeaves1.CHECK_DECAY, Boolean.TRUE).set(BlockLeaves1.DECAYABLE, Boolean.TRUE)); + } + + protected void a(World world, BlockPosition blockposition, IBlockData iblockdata, int i) { + if (iblockdata.get(BlockLeaves1.VARIANT) == BlockWood.EnumLogVariant.OAK && world.random.nextInt(i) == 0) { + a(world, blockposition, new ItemStack(Items.APPLE, 1, 0)); + } + + } + + protected int d(IBlockData iblockdata) { + return iblockdata.get(BlockLeaves1.VARIANT) == BlockWood.EnumLogVariant.JUNGLE ? 40 : super.d(iblockdata); + } + + protected ItemStack i(IBlockData iblockdata) { + return new ItemStack(Item.getItemOf(this), 1, iblockdata.get(BlockLeaves1.VARIANT).a()); + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockLeaves1.VARIANT, this.b(i)).set(BlockLeaves1.DECAYABLE, (i & 4) == 0).set(BlockLeaves1.CHECK_DECAY, (i & 8) > 0); + } + + public int toLegacyData(IBlockData iblockdata) { + byte b0 = 0; + int i = b0 | iblockdata.get(BlockLeaves1.VARIANT).a(); + + if (!iblockdata.get(BlockLeaves1.DECAYABLE)) { + i |= 4; + } + + if (iblockdata.get(BlockLeaves1.CHECK_DECAY)) { + i |= 8; + } + + return i; + } + + public BlockWood.EnumLogVariant b(int i) { + return BlockWood.EnumLogVariant.a((i & 3) % 4); + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, BlockLeaves1.VARIANT, BlockLeaves1.CHECK_DECAY, BlockLeaves1.DECAYABLE); + } + + public int getDropData(IBlockData iblockdata) { + return iblockdata.get(BlockLeaves1.VARIANT).a(); + } + + public void a(World world, EntityHuman entityhuman, BlockPosition blockposition, IBlockData iblockdata, TileEntity tileentity) { + if (entityhuman.bZ() != null && entityhuman.bZ().getItem() == Items.SHEARS) { + a(world, blockposition, new ItemStack(Item.getItemOf(this), 1, iblockdata.get(BlockLeaves1.VARIANT).a())); + } else { + super.a(world, entityhuman, blockposition, iblockdata, tileentity); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockLeaves2.java b/azurite-server/src/main/java/net/minecraft/server/BlockLeaves2.java new file mode 100644 index 0000000..3515d2c --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockLeaves2.java @@ -0,0 +1,66 @@ +package net.minecraft.server; + +public class BlockLeaves2 extends BlockLeaves { + + public static final BlockStateEnum VARIANT = BlockStateEnum.a("variant", BlockWood.EnumLogVariant.class, blockwood_enumlogvariant -> blockwood_enumlogvariant.a() >= 4); + + public BlockLeaves2() { + this.j(this.blockStateList.getBlockData().set(BlockLeaves2.VARIANT, BlockWood.EnumLogVariant.ACACIA).set(BlockLeaves2.CHECK_DECAY, Boolean.TRUE).set(BlockLeaves2.DECAYABLE, Boolean.TRUE)); + } + + protected void a(World world, BlockPosition blockposition, IBlockData iblockdata, int i) { + if (iblockdata.get(BlockLeaves2.VARIANT) == BlockWood.EnumLogVariant.DARK_OAK && world.random.nextInt(i) == 0) { + a(world, blockposition, new ItemStack(Items.APPLE, 1, 0)); + } + + } + + public int getDropData(IBlockData iblockdata) { + return iblockdata.get(BlockLeaves2.VARIANT).a(); + } + + public int getDropData(World world, BlockPosition blockposition) { + IBlockData iblockdata = world.getType(blockposition); + + return iblockdata.getBlock().toLegacyData(iblockdata) & 3; + } + + protected ItemStack i(IBlockData iblockdata) { + return new ItemStack(Item.getItemOf(this), 1, iblockdata.get(BlockLeaves2.VARIANT).a() - 4); + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockLeaves2.VARIANT, this.b(i)).set(BlockLeaves2.DECAYABLE, (i & 4) == 0).set(BlockLeaves2.CHECK_DECAY, (i & 8) > 0); + } + + public int toLegacyData(IBlockData iblockdata) { + byte b0 = 0; + int i = b0 | iblockdata.get(BlockLeaves2.VARIANT).a() - 4; + + if (!iblockdata.get(BlockLeaves2.DECAYABLE)) { + i |= 4; + } + + if (iblockdata.get(BlockLeaves2.CHECK_DECAY)) { + i |= 8; + } + + return i; + } + + public BlockWood.EnumLogVariant b(int i) { + return BlockWood.EnumLogVariant.a((i & 3) + 4); + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, BlockLeaves2.VARIANT, BlockLeaves2.CHECK_DECAY, BlockLeaves2.DECAYABLE); + } + + public void a(World world, EntityHuman entityhuman, BlockPosition blockposition, IBlockData iblockdata, TileEntity tileentity) { + if (entityhuman.bZ() != null && entityhuman.bZ().getItem() == Items.SHEARS) { + a(world, blockposition, new ItemStack(Item.getItemOf(this), 1, iblockdata.get(BlockLeaves2.VARIANT).a() - 4)); + } else { + super.a(world, entityhuman, blockposition, iblockdata, tileentity); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockLever.java b/azurite-server/src/main/java/net/minecraft/server/BlockLever.java new file mode 100644 index 0000000..329401d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockLever.java @@ -0,0 +1,402 @@ +package net.minecraft.server; + +import org.bukkit.event.block.BlockRedstoneEvent; + +import java.util.Iterator; + +public class BlockLever extends Block { + + public static final BlockStateEnum FACING = BlockStateEnum.of("facing", BlockLever.EnumLeverPosition.class); + public static final BlockStateBoolean POWERED = BlockStateBoolean.of("powered"); + + protected BlockLever() { + super(Material.ORIENTABLE); + this.j(this.blockStateList.getBlockData().set(BlockLever.FACING, BlockLever.EnumLeverPosition.NORTH).set(BlockLever.POWERED, false)); + this.a(CreativeModeTab.d); + } + + protected static boolean a(World world, BlockPosition blockposition, EnumDirection enumdirection) { + return BlockButtonAbstract.a(world, blockposition, enumdirection); + } + + public static int a(EnumDirection enumdirection) { + switch (BlockLever.SyntheticClass_1.a[enumdirection.ordinal()]) { + case 1: + return 0; + + case 2: + return 5; + + case 3: + return 4; + + case 4: + return 3; + + case 5: + return 2; + + case 6: + return 1; + + default: + return -1; + } + } + + public AxisAlignedBB a(World world, BlockPosition blockposition, IBlockData iblockdata) { + return null; + } + + public boolean c() { + return false; + } + + public boolean d() { + return false; + } + + public boolean canPlace(World world, BlockPosition blockposition, EnumDirection enumdirection) { + return a(world, blockposition, enumdirection.opposite()); + } + + public boolean canPlace(World world, BlockPosition blockposition) { + for (EnumDirection enumdirection : EnumDirection.values()) { + if (a(world, blockposition, enumdirection)) { + return true; + } + } + + return false; + } + + public IBlockData getPlacedState(World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2, int i, EntityLiving entityliving) { + IBlockData iblockdata = this.getBlockData().set(BlockLever.POWERED, Boolean.FALSE); + + if (a(world, blockposition, enumdirection.opposite())) { + return iblockdata.set(BlockLever.FACING, BlockLever.EnumLeverPosition.a(enumdirection, entityliving.getDirection())); + } else { + Iterator iterator = EnumDirection.EnumDirectionLimit.HORIZONTAL.iterator(); + + EnumDirection enumdirection1; + + do { + if (!iterator.hasNext()) { + if (World.a(world, blockposition.getX(), blockposition.getY() - 1, blockposition.getZ())) { + return iblockdata.set(BlockLever.FACING, BlockLever.EnumLeverPosition.a(EnumDirection.UP, entityliving.getDirection())); + } + + return iblockdata; + } + + enumdirection1 = iterator.next(); + } while (enumdirection1 == enumdirection || !a(world, blockposition, enumdirection1.opposite())); + + return iblockdata.set(BlockLever.FACING, BlockLever.EnumLeverPosition.a(enumdirection1, entityliving.getDirection())); + } + } + + public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) { + if (this.e(world, blockposition, iblockdata) && !a(world, blockposition, iblockdata.get(BlockLever.FACING).c().opposite())) { + this.b(world, blockposition, iblockdata, 0); + world.setAir(blockposition); + } + + } + + private boolean e(World world, BlockPosition blockposition, IBlockData iblockdata) { + if (this.canPlace(world, blockposition)) { + return true; + } else { + this.b(world, blockposition, iblockdata, 0); + world.setAir(blockposition); + return false; + } + } + + public void updateShape(IBlockAccess iblockaccess, BlockPosition blockposition) { + float f = 0.1875F; + + switch (BlockLever.SyntheticClass_1.b[(iblockaccess.getType(blockposition).get(BlockLever.FACING)).ordinal()]) { + case 1: + this.a(0.0F, 0.2F, 0.5F - f, f * 2.0F, 0.8F, 0.5F + f); + break; + + case 2: + this.a(1.0F - f * 2.0F, 0.2F, 0.5F - f, 1.0F, 0.8F, 0.5F + f); + break; + + case 3: + this.a(0.5F - f, 0.2F, 0.0F, 0.5F + f, 0.8F, f * 2.0F); + break; + + case 4: + this.a(0.5F - f, 0.2F, 1.0F - f * 2.0F, 0.5F + f, 0.8F, 1.0F); + break; + + case 5: + case 6: + f = 0.25F; + this.a(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, 0.6F, 0.5F + f); + break; + + case 7: + case 8: + f = 0.25F; + this.a(0.5F - f, 0.4F, 0.5F - f, 0.5F + f, 1.0F, 0.5F + f); + } + + } + + public boolean interact(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman, EnumDirection enumdirection, float f, float f1, float f2) { + // CraftBukkit start - Interact Lever + boolean powered = iblockdata.get(POWERED); + org.bukkit.block.Block block = world.getWorld().getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()); + int old = (powered) ? 15 : 0; + int current = (!powered) ? 15 : 0; + + BlockRedstoneEvent eventRedstone = new BlockRedstoneEvent(block, old, current); + world.getServer().getPluginManager().callEvent(eventRedstone); + + if ((eventRedstone.getNewCurrent() > 0) == (powered)) { + return true; + } + // CraftBukkit end + + iblockdata = iblockdata.a(BlockLever.POWERED); + world.setTypeAndData(blockposition, iblockdata, 3); + world.makeSound((double) blockposition.getX() + 0.5D, (double) blockposition.getY() + 0.5D, (double) blockposition.getZ() + 0.5D, "random.click", 0.3F, iblockdata.get(BlockLever.POWERED) ? 0.6F : 0.5F); + world.applyPhysics(blockposition, this); + EnumDirection enumdirection1 = iblockdata.get(BlockLever.FACING).c(); + + world.applyPhysics(blockposition.shift(enumdirection1.opposite()), this); + return true; + } + + public void remove(World world, BlockPosition blockposition, IBlockData iblockdata) { + if (iblockdata.get(BlockLever.POWERED)) { + world.applyPhysics(blockposition, this); + EnumDirection enumdirection = iblockdata.get(BlockLever.FACING).c(); + + world.applyPhysics(blockposition.shift(enumdirection.opposite()), this); + } + + super.remove(world, blockposition, iblockdata); + } + + public int a(IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata, EnumDirection enumdirection) { + return iblockdata.get(BlockLever.POWERED) ? 15 : 0; + } + + public int b(IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata, EnumDirection enumdirection) { + return !iblockdata.get(BlockLever.POWERED) ? 0 : (iblockdata.get(BlockLever.FACING).c() == enumdirection ? 15 : 0); + } + + public boolean isPowerSource() { + return true; + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockLever.FACING, BlockLever.EnumLeverPosition.a(i & 7)).set(BlockLever.POWERED, (i & 8) > 0); + } + + public int toLegacyData(IBlockData iblockdata) { + byte b0 = 0; + int i = b0 | iblockdata.get(BlockLever.FACING).a(); + + if (iblockdata.get(BlockLever.POWERED)) { + i |= 8; + } + + return i; + } + + public BlockStateList getStateList() { + return new BlockStateList(this, BlockLever.FACING, BlockLever.POWERED); + } + + public enum EnumLeverPosition implements INamable { + + DOWN_X(0, "down_x", EnumDirection.DOWN), EAST(1, "east", EnumDirection.EAST), WEST(2, "west", EnumDirection.WEST), SOUTH(3, "south", EnumDirection.SOUTH), NORTH(4, "north", EnumDirection.NORTH), UP_Z(5, "up_z", EnumDirection.UP), UP_X(6, "up_x", EnumDirection.UP), DOWN_Z(7, "down_z", EnumDirection.DOWN); + + private static final BlockLever.EnumLeverPosition[] i = new BlockLever.EnumLeverPosition[values().length]; + + static { + for (EnumLeverPosition blocklever_enumleverposition : values()) { + EnumLeverPosition.i[blocklever_enumleverposition.a()] = blocklever_enumleverposition; + } + + } + + private final int j; + private final String k; + private final EnumDirection l; + + EnumLeverPosition(int i, String s, EnumDirection enumdirection) { + this.j = i; + this.k = s; + this.l = enumdirection; + } + + public static BlockLever.EnumLeverPosition a(int i) { + if (i < 0 || i >= BlockLever.EnumLeverPosition.i.length) { + i = 0; + } + + return BlockLever.EnumLeverPosition.i[i]; + } + + public static BlockLever.EnumLeverPosition a(EnumDirection enumdirection, EnumDirection enumdirection1) { + switch (BlockLever.SyntheticClass_1.a[enumdirection.ordinal()]) { + case 1: + switch (BlockLever.SyntheticClass_1.c[enumdirection1.k().ordinal()]) { + case 1: + return BlockLever.EnumLeverPosition.DOWN_X; + + case 2: + return BlockLever.EnumLeverPosition.DOWN_Z; + + default: + throw new IllegalArgumentException("Invalid entityFacing " + enumdirection1 + " for facing " + enumdirection); + } + + case 2: + switch (BlockLever.SyntheticClass_1.c[enumdirection1.k().ordinal()]) { + case 1: + return BlockLever.EnumLeverPosition.UP_X; + + case 2: + return BlockLever.EnumLeverPosition.UP_Z; + + default: + throw new IllegalArgumentException("Invalid entityFacing " + enumdirection1 + " for facing " + enumdirection); + } + + case 3: + return BlockLever.EnumLeverPosition.NORTH; + + case 4: + return BlockLever.EnumLeverPosition.SOUTH; + + case 5: + return BlockLever.EnumLeverPosition.WEST; + + case 6: + return BlockLever.EnumLeverPosition.EAST; + + default: + throw new IllegalArgumentException("Invalid facing: " + enumdirection); + } + } + + public int a() { + return this.j; + } + + public EnumDirection c() { + return this.l; + } + + public String toString() { + return this.k; + } + + public String getName() { + return this.k; + } + } + + static class SyntheticClass_1 { + + static final int[] a; + static final int[] b; + static final int[] c = new int[EnumDirection.EnumAxis.values().length]; + + static { + try { + BlockLever.SyntheticClass_1.c[EnumDirection.EnumAxis.X.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockLever.SyntheticClass_1.c[EnumDirection.EnumAxis.Z.ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + } + + b = new int[BlockLever.EnumLeverPosition.values().length]; + + try { + BlockLever.SyntheticClass_1.b[BlockLever.EnumLeverPosition.EAST.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockLever.SyntheticClass_1.b[BlockLever.EnumLeverPosition.WEST.ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockLever.SyntheticClass_1.b[BlockLever.EnumLeverPosition.SOUTH.ordinal()] = 3; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockLever.SyntheticClass_1.b[BlockLever.EnumLeverPosition.NORTH.ordinal()] = 4; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockLever.SyntheticClass_1.b[BlockLever.EnumLeverPosition.UP_Z.ordinal()] = 5; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockLever.SyntheticClass_1.b[BlockLever.EnumLeverPosition.UP_X.ordinal()] = 6; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockLever.SyntheticClass_1.b[BlockLever.EnumLeverPosition.DOWN_X.ordinal()] = 7; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockLever.SyntheticClass_1.b[BlockLever.EnumLeverPosition.DOWN_Z.ordinal()] = 8; + } catch (NoSuchFieldError ignored) { + } + + a = new int[EnumDirection.values().length]; + + try { + BlockLever.SyntheticClass_1.a[EnumDirection.DOWN.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockLever.SyntheticClass_1.a[EnumDirection.UP.ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockLever.SyntheticClass_1.a[EnumDirection.NORTH.ordinal()] = 3; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockLever.SyntheticClass_1.a[EnumDirection.SOUTH.ordinal()] = 4; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockLever.SyntheticClass_1.a[EnumDirection.WEST.ordinal()] = 5; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockLever.SyntheticClass_1.a[EnumDirection.EAST.ordinal()] = 6; + } catch (NoSuchFieldError ignored) { + } + + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockLightStone.java b/azurite-server/src/main/java/net/minecraft/server/BlockLightStone.java new file mode 100644 index 0000000..b50dc9a --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockLightStone.java @@ -0,0 +1,27 @@ +package net.minecraft.server; + +import java.util.Random; + +public class BlockLightStone extends Block { + + public BlockLightStone(Material material) { + super(material); + this.a(CreativeModeTab.b); + } + + public int getDropCount(int i, Random random) { + return MathHelper.clamp(this.a(random) + random.nextInt(i + 1), 1, 4); + } + + public int a(Random random) { + return 2 + random.nextInt(3); + } + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + return Items.GLOWSTONE_DUST; + } + + public MaterialMapColor g(IBlockData iblockdata) { + return MaterialMapColor.d; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockLog1.java b/azurite-server/src/main/java/net/minecraft/server/BlockLog1.java new file mode 100644 index 0000000..d87967a --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockLog1.java @@ -0,0 +1,142 @@ +package net.minecraft.server; + +public class BlockLog1 extends BlockLogAbstract { + + public static final BlockStateEnum VARIANT = BlockStateEnum.a("variant", BlockWood.EnumLogVariant.class, blockwood_enumlogvariant -> blockwood_enumlogvariant.a() < 4); + + public BlockLog1() { + this.j(this.blockStateList.getBlockData().set(BlockLog1.VARIANT, BlockWood.EnumLogVariant.OAK).set(BlockLog1.AXIS, BlockLogAbstract.EnumLogRotation.Y)); + } + + public MaterialMapColor g(IBlockData iblockdata) { + BlockWood.EnumLogVariant blockwood_enumlogvariant = iblockdata.get(BlockLog1.VARIANT); + + switch (BlockLog1.SyntheticClass_1.b[iblockdata.get(BlockLog1.AXIS).ordinal()]) { + case 1: + case 2: + case 3: + default: + switch (BlockLog1.SyntheticClass_1.a[blockwood_enumlogvariant.ordinal()]) { + case 1: + default: + return BlockWood.EnumLogVariant.SPRUCE.c(); + + case 2: + return BlockWood.EnumLogVariant.DARK_OAK.c(); + + case 3: + return MaterialMapColor.p; + + } + + case 4: + return blockwood_enumlogvariant.c(); + } + } + + public IBlockData fromLegacyData(int i) { + IBlockData iblockdata = this.getBlockData().set(BlockLog1.VARIANT, BlockWood.EnumLogVariant.a((i & 3) % 4)); + + switch (i & 12) { + case 0: + iblockdata = iblockdata.set(BlockLog1.AXIS, BlockLogAbstract.EnumLogRotation.Y); + break; + + case 4: + iblockdata = iblockdata.set(BlockLog1.AXIS, BlockLogAbstract.EnumLogRotation.X); + break; + + case 8: + iblockdata = iblockdata.set(BlockLog1.AXIS, BlockLogAbstract.EnumLogRotation.Z); + break; + + default: + iblockdata = iblockdata.set(BlockLog1.AXIS, BlockLogAbstract.EnumLogRotation.NONE); + } + + return iblockdata; + } + + public int toLegacyData(IBlockData iblockdata) { + byte b0 = 0; + int i = b0 | iblockdata.get(BlockLog1.VARIANT).a(); + + switch (BlockLog1.SyntheticClass_1.b[iblockdata.get(BlockLog1.AXIS).ordinal()]) { + case 1: + i |= 4; + break; + + case 2: + i |= 8; + break; + + case 3: + i |= 12; + } + + return i; + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, BlockLog1.VARIANT, BlockLog1.AXIS); + } + + protected ItemStack i(IBlockData iblockdata) { + return new ItemStack(Item.getItemOf(this), 1, iblockdata.get(BlockLog1.VARIANT).a()); + } + + public int getDropData(IBlockData iblockdata) { + return iblockdata.get(BlockLog1.VARIANT).a(); + } + + static class SyntheticClass_1 { + + static final int[] a; + static final int[] b = new int[BlockLogAbstract.EnumLogRotation.values().length]; + + static { + try { + BlockLog1.SyntheticClass_1.b[BlockLogAbstract.EnumLogRotation.X.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockLog1.SyntheticClass_1.b[BlockLogAbstract.EnumLogRotation.Z.ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockLog1.SyntheticClass_1.b[BlockLogAbstract.EnumLogRotation.NONE.ordinal()] = 3; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockLog1.SyntheticClass_1.b[BlockLogAbstract.EnumLogRotation.Y.ordinal()] = 4; + } catch (NoSuchFieldError ignored) { + } + + a = new int[BlockWood.EnumLogVariant.values().length]; + + try { + BlockLog1.SyntheticClass_1.a[BlockWood.EnumLogVariant.OAK.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockLog1.SyntheticClass_1.a[BlockWood.EnumLogVariant.SPRUCE.ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockLog1.SyntheticClass_1.a[BlockWood.EnumLogVariant.BIRCH.ordinal()] = 3; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockLog1.SyntheticClass_1.a[BlockWood.EnumLogVariant.JUNGLE.ordinal()] = 4; + } catch (NoSuchFieldError ignored) { + } + + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockLog2.java b/azurite-server/src/main/java/net/minecraft/server/BlockLog2.java new file mode 100644 index 0000000..25f2599 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockLog2.java @@ -0,0 +1,138 @@ +package net.minecraft.server; + +import com.google.common.base.Predicate; + +public class BlockLog2 extends BlockLogAbstract { + + public static final BlockStateEnum VARIANT = BlockStateEnum.a("variant", BlockWood.EnumLogVariant.class, new Predicate() { + public boolean a(BlockWood.EnumLogVariant blockwood_enumlogvariant) { + return blockwood_enumlogvariant.a() >= 4; + } + + public boolean apply(Object object) { + return this.a((BlockWood.EnumLogVariant) object); + } + }); + + public BlockLog2() { + this.j(this.blockStateList.getBlockData().set(BlockLog2.VARIANT, BlockWood.EnumLogVariant.ACACIA).set(BlockLog2.AXIS, BlockLogAbstract.EnumLogRotation.Y)); + } + + public MaterialMapColor g(IBlockData iblockdata) { + BlockWood.EnumLogVariant blockwood_enumlogvariant = iblockdata.get(BlockLog2.VARIANT); + + switch (BlockLog2.SyntheticClass_1.b[iblockdata.get(BlockLog2.AXIS).ordinal()]) { + case 1: + case 2: + case 3: + default: + switch (BlockLog2.SyntheticClass_1.a[blockwood_enumlogvariant.ordinal()]) { + case 1: + default: + return MaterialMapColor.m; + + case 2: + return BlockWood.EnumLogVariant.DARK_OAK.c(); + } + + case 4: + return blockwood_enumlogvariant.c(); + } + } + + public IBlockData fromLegacyData(int i) { + IBlockData iblockdata = this.getBlockData().set(BlockLog2.VARIANT, BlockWood.EnumLogVariant.a((i & 3) + 4)); + + switch (i & 12) { + case 0: + iblockdata = iblockdata.set(BlockLog2.AXIS, BlockLogAbstract.EnumLogRotation.Y); + break; + + case 4: + iblockdata = iblockdata.set(BlockLog2.AXIS, BlockLogAbstract.EnumLogRotation.X); + break; + + case 8: + iblockdata = iblockdata.set(BlockLog2.AXIS, BlockLogAbstract.EnumLogRotation.Z); + break; + + default: + iblockdata = iblockdata.set(BlockLog2.AXIS, BlockLogAbstract.EnumLogRotation.NONE); + } + + return iblockdata; + } + + public int toLegacyData(IBlockData iblockdata) { + byte b0 = 0; + int i = b0 | iblockdata.get(BlockLog2.VARIANT).a() - 4; + + switch (BlockLog2.SyntheticClass_1.b[iblockdata.get(BlockLog2.AXIS).ordinal()]) { + case 1: + i |= 4; + break; + + case 2: + i |= 8; + break; + + case 3: + i |= 12; + } + + return i; + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, BlockLog2.VARIANT, BlockLog2.AXIS); + } + + protected ItemStack i(IBlockData iblockdata) { + return new ItemStack(Item.getItemOf(this), 1, iblockdata.get(BlockLog2.VARIANT).a() - 4); + } + + public int getDropData(IBlockData iblockdata) { + return iblockdata.get(BlockLog2.VARIANT).a() - 4; + } + + static class SyntheticClass_1 { + + static final int[] a; + static final int[] b = new int[BlockLogAbstract.EnumLogRotation.values().length]; + + static { + try { + BlockLog2.SyntheticClass_1.b[BlockLogAbstract.EnumLogRotation.X.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockLog2.SyntheticClass_1.b[BlockLogAbstract.EnumLogRotation.Z.ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockLog2.SyntheticClass_1.b[BlockLogAbstract.EnumLogRotation.NONE.ordinal()] = 3; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockLog2.SyntheticClass_1.b[BlockLogAbstract.EnumLogRotation.Y.ordinal()] = 4; + } catch (NoSuchFieldError ignored) { + } + + a = new int[BlockWood.EnumLogVariant.values().length]; + + try { + BlockLog2.SyntheticClass_1.a[BlockWood.EnumLogVariant.ACACIA.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockLog2.SyntheticClass_1.a[BlockWood.EnumLogVariant.DARK_OAK.ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + } + + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockLogAbstract.java b/azurite-server/src/main/java/net/minecraft/server/BlockLogAbstract.java new file mode 100644 index 0000000..bb0bf98 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockLogAbstract.java @@ -0,0 +1,92 @@ +package net.minecraft.server; + +public abstract class BlockLogAbstract extends BlockRotatable { + + public static final BlockStateEnum AXIS = BlockStateEnum.of("axis", BlockLogAbstract.EnumLogRotation.class); + + public BlockLogAbstract() { + super(Material.WOOD); + this.a(CreativeModeTab.b); + this.c(2.0F); + this.a(BlockLogAbstract.f); + } + + public void remove(World world, BlockPosition blockposition, IBlockData iblockdata) { + byte b0 = 4; + int i = b0 + 1; + + if (world.areChunksLoadedBetween(blockposition.a(-i, -i, -i), blockposition.a(i, i, i))) { + + for (BlockPosition blockposition1 : BlockPosition.a(blockposition.a(-b0, -b0, -b0), blockposition.a(b0, b0, b0))) { + IBlockData iblockdata1 = world.getType(blockposition1); + + if (iblockdata1.getBlock().getMaterial() == Material.LEAVES && !iblockdata1.get(BlockLeaves.CHECK_DECAY)) { + world.setTypeAndData(blockposition1, iblockdata1.set(BlockLeaves.CHECK_DECAY, true), 4); + } + } + + } + } + + public IBlockData getPlacedState(World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2, int i, EntityLiving entityliving) { + return super.getPlacedState(world, blockposition, enumdirection, f, f1, f2, i, entityliving).set(BlockLogAbstract.AXIS, BlockLogAbstract.EnumLogRotation.a(enumdirection.k())); + } + + static class SyntheticClass_1 { + + static final int[] a = new int[EnumDirection.EnumAxis.values().length]; + + static { + try { + BlockLogAbstract.SyntheticClass_1.a[EnumDirection.EnumAxis.X.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockLogAbstract.SyntheticClass_1.a[EnumDirection.EnumAxis.Y.ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockLogAbstract.SyntheticClass_1.a[EnumDirection.EnumAxis.Z.ordinal()] = 3; + } catch (NoSuchFieldError ignored) { + } + + } + } + + public enum EnumLogRotation implements INamable { + + X("x"), Y("y"), Z("z"), NONE("none"); + + private final String e; + + EnumLogRotation(String s) { + this.e = s; + } + + public String toString() { + return this.e; + } + + public static BlockLogAbstract.EnumLogRotation a(EnumDirection.EnumAxis enumdirection_enumaxis) { + switch (BlockLogAbstract.SyntheticClass_1.a[enumdirection_enumaxis.ordinal()]) { + case 1: + return BlockLogAbstract.EnumLogRotation.X; + + case 2: + return BlockLogAbstract.EnumLogRotation.Y; + + case 3: + return BlockLogAbstract.EnumLogRotation.Z; + + default: + return BlockLogAbstract.EnumLogRotation.NONE; + } + } + + public String getName() { + return this.e; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockLongGrass.java b/azurite-server/src/main/java/net/minecraft/server/BlockLongGrass.java new file mode 100644 index 0000000..58b9847 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockLongGrass.java @@ -0,0 +1,126 @@ +package net.minecraft.server; + +import java.util.Random; + +public class BlockLongGrass extends BlockPlant implements IBlockFragilePlantElement { + + public static final BlockStateEnum TYPE = BlockStateEnum.of("type", BlockLongGrass.EnumTallGrassType.class); + + protected BlockLongGrass() { + super(Material.REPLACEABLE_PLANT); + this.j(this.blockStateList.getBlockData().set(BlockLongGrass.TYPE, BlockLongGrass.EnumTallGrassType.DEAD_BUSH)); + float f = 0.4F; + + this.a(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, 0.8F, 0.5F + f); + } + + public boolean f(World world, BlockPosition blockposition, IBlockData iblockdata) { + return this.c(world.getType(blockposition.down()).getBlock()); + } + + public boolean a(World world, BlockPosition blockposition) { + return true; + } + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + return random.nextInt(8) == 0 ? Items.WHEAT_SEEDS : null; + } + + public int getDropCount(int i, Random random) { + return 1 + random.nextInt(i * 2 + 1); + } + + public void a(World world, EntityHuman entityhuman, BlockPosition blockposition, IBlockData iblockdata, TileEntity tileentity) { + if (entityhuman.bZ() != null && entityhuman.bZ().getItem() == Items.SHEARS) { + a(world, blockposition, new ItemStack(Blocks.TALLGRASS, 1, iblockdata.get(BlockLongGrass.TYPE).a())); + } else { + super.a(world, entityhuman, blockposition, iblockdata, tileentity); + } + + } + + public int getDropData(World world, BlockPosition blockposition) { + IBlockData iblockdata = world.getType(blockposition); + + return iblockdata.getBlock().toLegacyData(iblockdata); + } + + public boolean a(World world, BlockPosition blockposition, IBlockData iblockdata, boolean flag) { + return iblockdata.get(BlockLongGrass.TYPE) != BlockLongGrass.EnumTallGrassType.DEAD_BUSH; + } + + public boolean a(World world, Random random, BlockPosition blockposition, IBlockData iblockdata) { + return true; + } + + public void b(World world, Random random, BlockPosition blockposition, IBlockData iblockdata) { + BlockTallPlant.EnumTallFlowerVariants blocktallplant_enumtallflowervariants = BlockTallPlant.EnumTallFlowerVariants.GRASS; + + if (iblockdata.get(BlockLongGrass.TYPE) == BlockLongGrass.EnumTallGrassType.FERN) { + blocktallplant_enumtallflowervariants = BlockTallPlant.EnumTallFlowerVariants.FERN; + } + + if (Blocks.DOUBLE_PLANT.canPlace(world, blockposition)) { + Blocks.DOUBLE_PLANT.a(world, blockposition, blocktallplant_enumtallflowervariants, 2); + } + + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockLongGrass.TYPE, BlockLongGrass.EnumTallGrassType.a(i)); + } + + public int toLegacyData(IBlockData iblockdata) { + return iblockdata.get(BlockLongGrass.TYPE).a(); + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, BlockLongGrass.TYPE); + } + + public enum EnumTallGrassType implements INamable { + + DEAD_BUSH(0, "dead_bush"), GRASS(1, "tall_grass"), FERN(2, "fern"); + + private static final BlockLongGrass.EnumTallGrassType[] d = new BlockLongGrass.EnumTallGrassType[values().length]; + private final int e; + private final String f; + + EnumTallGrassType(int i, String s) { + this.e = i; + this.f = s; + } + + public int a() { + return this.e; + } + + public String toString() { + return this.f; + } + + public static BlockLongGrass.EnumTallGrassType a(int i) { + if (i < 0 || i >= BlockLongGrass.EnumTallGrassType.d.length) { + i = 0; + } + + return BlockLongGrass.EnumTallGrassType.d[i]; + } + + public String getName() { + return this.f; + } + + static { + BlockLongGrass.EnumTallGrassType[] ablocklonggrass_enumtallgrasstype = values(); + int i = ablocklonggrass_enumtallgrasstype.length; + + for (int j = 0; j < i; ++j) { + BlockLongGrass.EnumTallGrassType blocklonggrass_enumtallgrasstype = ablocklonggrass_enumtallgrasstype[j]; + + BlockLongGrass.EnumTallGrassType.d[blocklonggrass_enumtallgrasstype.a()] = blocklonggrass_enumtallgrasstype; + } + + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockMelon.java b/azurite-server/src/main/java/net/minecraft/server/BlockMelon.java new file mode 100644 index 0000000..9365fe0 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockMelon.java @@ -0,0 +1,23 @@ +package net.minecraft.server; + +import java.util.Random; + +public class BlockMelon extends Block { + + protected BlockMelon() { + super(Material.PUMPKIN, MaterialMapColor.u); + this.a(CreativeModeTab.b); + } + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + return Items.MELON; + } + + public int a(Random random) { + return 3 + random.nextInt(5); + } + + public int getDropCount(int i, Random random) { + return Math.min(9, this.a(random) + random.nextInt(1 + i)); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockMinecartDetector.java b/azurite-server/src/main/java/net/minecraft/server/BlockMinecartDetector.java new file mode 100644 index 0000000..4b4fa00 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockMinecartDetector.java @@ -0,0 +1,174 @@ +package net.minecraft.server; + +import com.google.common.base.Predicate; +import org.bukkit.event.block.BlockRedstoneEvent; + +import java.util.List; +import java.util.Random; + +public class BlockMinecartDetector extends BlockMinecartTrackAbstract { + + public static final BlockStateEnum SHAPE = BlockStateEnum.a("shape", + EnumTrackPosition.class, new Predicate() { + public boolean a( + EnumTrackPosition blockminecarttrackabstract_enumtrackposition) { + return blockminecarttrackabstract_enumtrackposition != EnumTrackPosition.NORTH_EAST + && blockminecarttrackabstract_enumtrackposition != EnumTrackPosition.NORTH_WEST + && blockminecarttrackabstract_enumtrackposition != EnumTrackPosition.SOUTH_EAST + && blockminecarttrackabstract_enumtrackposition != EnumTrackPosition.SOUTH_WEST; + } + + public boolean apply(Object object) { + return this.a((EnumTrackPosition) object); + } + }); + public static final BlockStateBoolean POWERED = BlockStateBoolean.of("powered"); + + public BlockMinecartDetector() { + super(true); + this.j(this.blockStateList.getBlockData().set(BlockMinecartDetector.POWERED, Boolean.FALSE).set(BlockMinecartDetector.SHAPE, EnumTrackPosition.NORTH_SOUTH)); + this.a(true); + } + + public int a(World world) { + return 20; + } + + public boolean isPowerSource() { + return true; + } + + public void a(World world, BlockPosition blockposition, IBlockData iblockdata, Entity entity) { + if (!iblockdata.get(BlockMinecartDetector.POWERED)) { + this.e(world, blockposition, iblockdata); + } + } + + public void b(World world, BlockPosition blockposition, IBlockData iblockdata, Random random) { + if (iblockdata.get(BlockMinecartDetector.POWERED)) { + this.e(world, blockposition, iblockdata); + } + } + + public int a(IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata, + EnumDirection enumdirection) { + return iblockdata.get(BlockMinecartDetector.POWERED) ? 15 : 0; + } + + public int b(IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata, + EnumDirection enumdirection) { + return !iblockdata.get(BlockMinecartDetector.POWERED) ? 0 + : (enumdirection == EnumDirection.UP ? 15 : 0); + } + + private void e(World world, BlockPosition blockposition, IBlockData iblockdata) { + boolean flag = iblockdata.get(BlockMinecartDetector.POWERED); + boolean flag1 = false; + List list = this.a(world, blockposition, EntityMinecartAbstract.class); + + if (!list.isEmpty()) { + flag1 = true; + } + + // CraftBukkit start + final int x = blockposition.getX(), y = blockposition.getY(), z = blockposition.getZ(); + if (flag != flag1) { + org.bukkit.block.Block block = world.getWorld().getBlockAt(x, y, z); + + BlockRedstoneEvent eventRedstone = new BlockRedstoneEvent(block, flag ? 15 : 0, flag1 ? 15 : 0); + world.getServer().getPluginManager().callEvent(eventRedstone); + + flag1 = eventRedstone.getNewCurrent() > 0; + } + // CraftBukkit end + + if (flag1 && !flag) { + world.setTypeAndData(blockposition, iblockdata.set(BlockMinecartDetector.POWERED, true), 3); + world.applyPhysics(x, y, z, this); + world.applyPhysics(x, y - 1, z, this); + world.b(x, y, z, x, y, z); + } + + if (!flag1 && flag) { + world.setTypeAndData(blockposition, iblockdata.set(BlockMinecartDetector.POWERED, false), 3); + world.applyPhysics(x, y, z, this); + world.applyPhysics(x, y - 1, z, this); + world.b(x, y, z, x, y, z); + } + + if (flag1) { + world.a(blockposition, this, this.a(world)); + } + + world.updateAdjacentComparators(new BlockPosition(x, y, z), this); + } + + public void onPlace(World world, BlockPosition blockposition, IBlockData iblockdata) { + super.onPlace(world, blockposition, iblockdata); + this.e(world, blockposition, iblockdata); + } + + public IBlockState n() { + return BlockMinecartDetector.SHAPE; + } + + public boolean isComplexRedstone() { + return true; + } + + public int l(World world, BlockPosition blockposition) { + if (world.getType(blockposition).get(BlockMinecartDetector.POWERED)) { + List list = this.a(world, blockposition, EntityMinecartCommandBlock.class); + + if (!list.isEmpty()) { + return list.get(0).getCommandBlock().j(); + } + + List list1 = this.a(world, blockposition, EntityMinecartAbstract.class, + IEntitySelector.c); + + if (!list1.isEmpty()) { + return Container.b((IInventory) list1.get(0)); + } + } + + return 0; + } + + protected List a(World world, BlockPosition blockposition, Class oclass, + Predicate... apredicate) { + AxisAlignedBB axisalignedbb = this.a(blockposition); + + return apredicate.length != 1 ? world.a(oclass, axisalignedbb) : world.a(oclass, axisalignedbb, apredicate[0]); + } + + private AxisAlignedBB a(BlockPosition blockposition) { + + return new AxisAlignedBB(blockposition.getX() + 0.2F, blockposition.getY(), + blockposition.getZ() + 0.2F, (blockposition.getX() + 1) - 0.2F, + (blockposition.getY() + 1) - 0.2F, + (blockposition.getZ() + 1) - 0.2F); + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData() + .set(BlockMinecartDetector.SHAPE, EnumTrackPosition.a(i & 7)) + .set(BlockMinecartDetector.POWERED, (i & 8) > 0); + } + + public int toLegacyData(IBlockData iblockdata) { + byte b0 = 0; + int i = b0 | iblockdata.get(BlockMinecartDetector.SHAPE).a(); + + if (iblockdata.get(BlockMinecartDetector.POWERED)) { + i |= 8; + } + + return i; + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, + BlockMinecartDetector.SHAPE, BlockMinecartDetector.POWERED); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockMinecartTrack.java b/azurite-server/src/main/java/net/minecraft/server/BlockMinecartTrack.java new file mode 100644 index 0000000..45ad6f6 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockMinecartTrack.java @@ -0,0 +1,34 @@ +package net.minecraft.server; + +public class BlockMinecartTrack extends BlockMinecartTrackAbstract { + + public static final BlockStateEnum SHAPE = BlockStateEnum.of("shape", BlockMinecartTrackAbstract.EnumTrackPosition.class); + + protected BlockMinecartTrack() { + super(false); + this.j(this.blockStateList.getBlockData().set(BlockMinecartTrack.SHAPE, BlockMinecartTrackAbstract.EnumTrackPosition.NORTH_SOUTH)); + } + + protected void b(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) { + if (block.isPowerSource() && (new BlockMinecartTrackAbstract.MinecartTrackLogic(world, blockposition, iblockdata)).a() == 3) { + this.a(world, blockposition, iblockdata, false); + } + + } + + public IBlockState n() { + return BlockMinecartTrack.SHAPE; + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockMinecartTrack.SHAPE, BlockMinecartTrackAbstract.EnumTrackPosition.a(i)); + } + + public int toLegacyData(IBlockData iblockdata) { + return iblockdata.get(BlockMinecartTrack.SHAPE).a(); + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, BlockMinecartTrack.SHAPE); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockMinecartTrackAbstract.java b/azurite-server/src/main/java/net/minecraft/server/BlockMinecartTrackAbstract.java new file mode 100644 index 0000000..21c3b63 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockMinecartTrackAbstract.java @@ -0,0 +1,590 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; + +import java.util.List; + +public abstract class BlockMinecartTrackAbstract extends Block { + + protected final boolean a; + + protected BlockMinecartTrackAbstract(boolean flag) { + super(Material.ORIENTABLE); + this.a = flag; + this.a(0.0F, 0.0F, 0.0F, 1.0F, 0.125F, 1.0F); + this.a(CreativeModeTab.e); + } + + public static boolean e(World world, BlockPosition blockposition) { + return d(world.getType(blockposition)); + } + + public static boolean e(World world, int x, int y, int z) { + return d(world.getType(x, y, z)); + } + + public static boolean d(IBlockData iblockdata) { + Block block = iblockdata.getBlock(); + + return block == Blocks.RAIL || block == Blocks.GOLDEN_RAIL || block == Blocks.DETECTOR_RAIL + || block == Blocks.ACTIVATOR_RAIL; + } + + public AxisAlignedBB a(World world, BlockPosition blockposition, IBlockData iblockdata) { + return null; + } + + public boolean c() { + return false; + } + + public MovingObjectPosition a(World world, BlockPosition blockposition, Vec3D vec3d, Vec3D vec3d1) { + this.updateShape(world, blockposition); + return super.a(world, blockposition, vec3d, vec3d1); + } + + public void updateShape(IBlockAccess iblockaccess, BlockPosition blockposition) { + IBlockData iblockdata = iblockaccess.getType(blockposition); + EnumTrackPosition blockminecarttrackabstract_enumtrackposition = iblockdata.getBlock() == this ? iblockdata.get(this.n()) : null; + + if (blockminecarttrackabstract_enumtrackposition != null && blockminecarttrackabstract_enumtrackposition.c()) { + this.a(0.0F, 0.0F, 0.0F, 1.0F, 0.625F, 1.0F); + } else { + this.a(0.0F, 0.0F, 0.0F, 1.0F, 0.125F, 1.0F); + } + + } + + public boolean d() { + return false; + } + + public boolean canPlace(World world, BlockPosition blockposition) { + return World.a(world, blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()); + } + + public void onPlace(World world, BlockPosition blockposition, IBlockData iblockdata) { + iblockdata = this.a(world, blockposition, iblockdata, true); + if (this.a) { + this.doPhysics(world, blockposition, iblockdata, this); + } + } + + public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) { + EnumTrackPosition blockminecarttrackabstract_enumtrackposition = iblockdata.get(this.n()); + boolean flag = !World.a(world, blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()); + + if (blockminecarttrackabstract_enumtrackposition == EnumTrackPosition.ASCENDING_EAST + && !World.a(world, blockposition.getX() + 1, blockposition.getY(), blockposition.getZ())) { + flag = true; + } else if (blockminecarttrackabstract_enumtrackposition == EnumTrackPosition.ASCENDING_WEST + && !World.a(world, blockposition.getX() - 1, blockposition.getY(), blockposition.getZ())) { + flag = true; + } else if (blockminecarttrackabstract_enumtrackposition == EnumTrackPosition.ASCENDING_NORTH + && !World.a(world, blockposition.getX(), blockposition.getY(), blockposition.getZ() - 1)) { + flag = true; + } else if (blockminecarttrackabstract_enumtrackposition == EnumTrackPosition.ASCENDING_SOUTH + && !World.a(world, blockposition.getX(), blockposition.getY(), blockposition.getZ() + 1)) { + flag = true; + } + + if (flag && !world.isEmpty(blockposition)) { // CraftBukkit - SPIGOT-424, MC-73474 + this.b(world, blockposition, iblockdata, 0); + world.setAir(blockposition); + } else { + this.b(world, blockposition, iblockdata, block); + } + + } + + protected void b(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) { + } + + protected IBlockData a(World world, BlockPosition blockposition, IBlockData iblockdata, boolean flag) { + return new MinecartTrackLogic(world, blockposition, iblockdata).a(world.isBlockIndirectlyPowered(blockposition), flag).b(); + } + + public int k() { + return 0; + } + + public void remove(World world, BlockPosition blockposition, IBlockData iblockdata) { + super.remove(world, blockposition, iblockdata); + if (iblockdata.get(this.n()).c()) { + world.applyPhysics(blockposition.getX(), blockposition.getY() + 1, blockposition.getZ(), this); + } + + if (this.a) { + world.applyPhysics(blockposition.getX(), blockposition.getY(), blockposition.getZ(), this); + world.applyPhysics(blockposition.getX(), blockposition.getY() - 1, blockposition.getZ(), this); + } + + } + + public abstract IBlockState n(); + + public enum EnumTrackPosition implements INamable { + + NORTH_SOUTH(0, "north_south"), EAST_WEST(1, "east_west"), ASCENDING_EAST(2, "ascending_east"), + ASCENDING_WEST(3, "ascending_west"), ASCENDING_NORTH(4, "ascending_north"), + ASCENDING_SOUTH(5, "ascending_south"), SOUTH_EAST(6, "south_east"), SOUTH_WEST(7, "south_west"), + NORTH_WEST(8, "north_west"), NORTH_EAST(9, "north_east"); + + private static final EnumTrackPosition[] k = new EnumTrackPosition[values().length]; + + static { + for (EnumTrackPosition blockminecarttrackabstract_enumtrackposition : values()) { + EnumTrackPosition.k[blockminecarttrackabstract_enumtrackposition.a()] = blockminecarttrackabstract_enumtrackposition; + } + + } + + private final int l; + private final String m; + + EnumTrackPosition(int i, String s) { + this.l = i; + this.m = s; + } + + public static EnumTrackPosition a(int i) { + if (i < 0 || i >= EnumTrackPosition.k.length) { + i = 0; + } + + return EnumTrackPosition.k[i]; + } + + public int a() { + return this.l; + } + + public String toString() { + return this.m; + } + + public boolean c() { + return this == EnumTrackPosition.ASCENDING_NORTH + || this == EnumTrackPosition.ASCENDING_EAST + || this == EnumTrackPosition.ASCENDING_SOUTH + || this == EnumTrackPosition.ASCENDING_WEST; + } + + public String getName() { + return this.m; + } + } + + static class SyntheticClass_1 { + + static final int[] a = new int[EnumTrackPosition.values().length]; + + static { + try { + SyntheticClass_1.a[EnumTrackPosition.NORTH_SOUTH.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.a[EnumTrackPosition.EAST_WEST.ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.a[EnumTrackPosition.ASCENDING_EAST.ordinal()] = 3; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.a[EnumTrackPosition.ASCENDING_WEST.ordinal()] = 4; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.a[EnumTrackPosition.ASCENDING_NORTH.ordinal()] = 5; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.a[EnumTrackPosition.ASCENDING_SOUTH.ordinal()] = 6; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.a[EnumTrackPosition.SOUTH_EAST.ordinal()] = 7; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.a[EnumTrackPosition.SOUTH_WEST.ordinal()] = 8; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.a[EnumTrackPosition.NORTH_WEST.ordinal()] = 9; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.a[EnumTrackPosition.NORTH_EAST.ordinal()] = 10; + } catch (NoSuchFieldError ignored) { + } + + } + } + + public class MinecartTrackLogic { + + private final World b; + private final BlockPosition c; + private final BlockMinecartTrackAbstract d; + private final boolean f; + private final List g = Lists.newArrayList(); + private IBlockData e; + + public MinecartTrackLogic(World world, BlockPosition blockposition, IBlockData iblockdata) { + this.b = world; + this.c = blockposition; + this.e = iblockdata; + this.d = (BlockMinecartTrackAbstract) iblockdata.getBlock(); + EnumTrackPosition blockminecarttrackabstract_enumtrackposition = iblockdata + .get(BlockMinecartTrackAbstract.this.n()); + + this.f = this.d.a; + this.a(blockminecarttrackabstract_enumtrackposition); + } + + private void a(EnumTrackPosition blockminecarttrackabstract_enumtrackposition) { + this.g.clear(); + switch (SyntheticClass_1.a[blockminecarttrackabstract_enumtrackposition + .ordinal()]) { + case 1: + this.g.add(this.c.north()); + this.g.add(this.c.south()); + break; + + case 2: + this.g.add(this.c.west()); + this.g.add(this.c.east()); + break; + + case 3: + this.g.add(this.c.west()); + this.g.add(this.c.east().up()); + break; + + case 4: + this.g.add(this.c.west().up()); + this.g.add(this.c.east()); + break; + + case 5: + this.g.add(this.c.north().up()); + this.g.add(this.c.south()); + break; + + case 6: + this.g.add(this.c.north()); + this.g.add(this.c.south().up()); + break; + + case 7: + this.g.add(this.c.east()); + this.g.add(this.c.south()); + break; + + case 8: + this.g.add(this.c.west()); + this.g.add(this.c.south()); + break; + + case 9: + this.g.add(this.c.west()); + this.g.add(this.c.north()); + break; + + case 10: + this.g.add(this.c.east()); + this.g.add(this.c.north()); + } + + } + + private void c() { + for (int i = 0; i < this.g.size(); ++i) { + MinecartTrackLogic blockminecarttrackabstract_minecarttracklogic = this.b(this.g.get(i)); + + if (blockminecarttrackabstract_minecarttracklogic != null + && blockminecarttrackabstract_minecarttracklogic.a(this)) { + this.g.set(i, blockminecarttrackabstract_minecarttracklogic.c); + } else { + this.g.remove(i--); + } + } + + } + + private boolean a(BlockPosition blockposition) { + return BlockMinecartTrackAbstract.e(this.b, blockposition) + || BlockMinecartTrackAbstract.e(this.b, blockposition.getX(), blockposition.getY() + 1, blockposition.getZ()) + || BlockMinecartTrackAbstract.e(this.b, blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()); + } + + private MinecartTrackLogic b(BlockPosition blockposition) { + IBlockData iblockdata = this.b.getType(blockposition); + + if (BlockMinecartTrackAbstract.d(iblockdata)) { + return BlockMinecartTrackAbstract.this.new MinecartTrackLogic(this.b, blockposition, iblockdata); + } else { + BlockPosition blockposition1 = blockposition.up(); + + iblockdata = this.b.getType(blockposition1); + if (BlockMinecartTrackAbstract.d(iblockdata)) { + return BlockMinecartTrackAbstract.this.new MinecartTrackLogic(this.b, blockposition1, iblockdata); + } else { + blockposition1 = blockposition.down(); + iblockdata = this.b.getType(blockposition1); + return BlockMinecartTrackAbstract.d(iblockdata) + ? BlockMinecartTrackAbstract.this.new MinecartTrackLogic(this.b, blockposition1, iblockdata) + : null; + } + } + } + + private boolean a(MinecartTrackLogic blockminecarttrackabstract_minecarttracklogic) { + return this.c(blockminecarttrackabstract_minecarttracklogic.c); + } + + private boolean c(BlockPosition blockposition) { + for (BlockPosition blockposition1 : this.g) { + if (blockposition1.getX() == blockposition.getX() && blockposition1.getZ() == blockposition.getZ()) { + return true; + } + } + return false; + } + + protected int a() { + int i = 0; + for (EnumDirection enumdirection : EnumDirection.EnumDirectionLimit.HORIZONTAL) { + if (this.a(this.c.shift(enumdirection))) { + ++i; + } + } + return i; + } + + private boolean b(MinecartTrackLogic blockminecarttrackabstract_minecarttracklogic) { + return this.a(blockminecarttrackabstract_minecarttracklogic) || this.g.size() != 2; + } + + private void c(MinecartTrackLogic blockminecarttrackabstract_minecarttracklogic) { + this.g.add(blockminecarttrackabstract_minecarttracklogic.c); + BlockPosition blockposition = this.c.north(); + BlockPosition blockposition1 = this.c.south(); + BlockPosition blockposition2 = this.c.west(); + BlockPosition blockposition3 = this.c.east(); + boolean flag = this.c(blockposition); + boolean flag1 = this.c(blockposition1); + boolean flag2 = this.c(blockposition2); + boolean flag3 = this.c(blockposition3); + EnumTrackPosition blockminecarttrackabstract_enumtrackposition = null; + + if (flag || flag1) { + blockminecarttrackabstract_enumtrackposition = EnumTrackPosition.NORTH_SOUTH; + } + + if (flag2 || flag3) { + blockminecarttrackabstract_enumtrackposition = EnumTrackPosition.EAST_WEST; + } + + if (!this.f) { + if (flag1 && flag3 && !flag && !flag2) { + blockminecarttrackabstract_enumtrackposition = EnumTrackPosition.SOUTH_EAST; + } + + if (flag1 && flag2 && !flag && !flag3) { + blockminecarttrackabstract_enumtrackposition = EnumTrackPosition.SOUTH_WEST; + } + + if (flag && flag2 && !flag1 && !flag3) { + blockminecarttrackabstract_enumtrackposition = EnumTrackPosition.NORTH_WEST; + } + + if (flag && flag3 && !flag1 && !flag2) { + blockminecarttrackabstract_enumtrackposition = EnumTrackPosition.NORTH_EAST; + } + } + + if (blockminecarttrackabstract_enumtrackposition == EnumTrackPosition.NORTH_SOUTH) { + if (BlockMinecartTrackAbstract.e(this.b, blockposition.getX(), blockposition.getY() + 1, blockposition.getZ())) { + blockminecarttrackabstract_enumtrackposition = EnumTrackPosition.ASCENDING_NORTH; + } + + if (BlockMinecartTrackAbstract.e(this.b, blockposition1.getX(), blockposition1.getY() + 1, blockposition1.getZ())) { + blockminecarttrackabstract_enumtrackposition = EnumTrackPosition.ASCENDING_SOUTH; + } + } + + if (blockminecarttrackabstract_enumtrackposition == EnumTrackPosition.EAST_WEST) { + if (BlockMinecartTrackAbstract.e(this.b, blockposition3.getX(), blockposition3.getY() + 1, blockposition3.getZ())) { + blockminecarttrackabstract_enumtrackposition = EnumTrackPosition.ASCENDING_EAST; + } + + if (BlockMinecartTrackAbstract.e(this.b, blockposition2.getX(), blockposition2.getY() + 1, blockposition2.getZ())) { + blockminecarttrackabstract_enumtrackposition = EnumTrackPosition.ASCENDING_WEST; + } + } + + if (blockminecarttrackabstract_enumtrackposition == null) { + blockminecarttrackabstract_enumtrackposition = EnumTrackPosition.NORTH_SOUTH; + } + + this.e = this.e.set(this.d.n(), blockminecarttrackabstract_enumtrackposition); + this.b.setTypeAndData(this.c, this.e, 3); + } + + private boolean d(BlockPosition blockposition) { + MinecartTrackLogic blockminecarttrackabstract_minecarttracklogic = this + .b(blockposition); + + if (blockminecarttrackabstract_minecarttracklogic == null) { + return false; + } else { + blockminecarttrackabstract_minecarttracklogic.c(); + return blockminecarttrackabstract_minecarttracklogic.b(this); + } + } + + public MinecartTrackLogic a(boolean flag, boolean flag1) { + BlockPosition blockposition = this.c.north(); + BlockPosition blockposition1 = this.c.south(); + BlockPosition blockposition2 = this.c.west(); + BlockPosition blockposition3 = this.c.east(); + boolean flag2 = this.d(blockposition); + boolean flag3 = this.d(blockposition1); + boolean flag4 = this.d(blockposition2); + boolean flag5 = this.d(blockposition3); + EnumTrackPosition blockminecarttrackabstract_enumtrackposition = null; + + if ((flag2 || flag3) && !flag4 && !flag5) { + blockminecarttrackabstract_enumtrackposition = EnumTrackPosition.NORTH_SOUTH; + } + + if ((flag4 || flag5) && !flag2 && !flag3) { + blockminecarttrackabstract_enumtrackposition = EnumTrackPosition.EAST_WEST; + } + + if (!this.f) { + if (flag3 && flag5 && !flag2 && !flag4) { + blockminecarttrackabstract_enumtrackposition = EnumTrackPosition.SOUTH_EAST; + } + + if (flag3 && flag4 && !flag2 && !flag5) { + blockminecarttrackabstract_enumtrackposition = EnumTrackPosition.SOUTH_WEST; + } + + if (flag2 && flag4 && !flag3 && !flag5) { + blockminecarttrackabstract_enumtrackposition = EnumTrackPosition.NORTH_WEST; + } + + if (flag2 && flag5 && !flag3 && !flag4) { + blockminecarttrackabstract_enumtrackposition = EnumTrackPosition.NORTH_EAST; + } + } + + if (blockminecarttrackabstract_enumtrackposition == null) { + if (flag2 || flag3) { + blockminecarttrackabstract_enumtrackposition = EnumTrackPosition.NORTH_SOUTH; + } + + if (flag4 || flag5) { + blockminecarttrackabstract_enumtrackposition = EnumTrackPosition.EAST_WEST; + } + + if (!this.f) { + if (flag) { + if (flag3 && flag5) { + blockminecarttrackabstract_enumtrackposition = EnumTrackPosition.SOUTH_EAST; + } + + if (flag4 && flag3) { + blockminecarttrackabstract_enumtrackposition = EnumTrackPosition.SOUTH_WEST; + } + + if (flag5 && flag2) { + blockminecarttrackabstract_enumtrackposition = EnumTrackPosition.NORTH_EAST; + } + + if (flag2 && flag4) { + blockminecarttrackabstract_enumtrackposition = EnumTrackPosition.NORTH_WEST; + } + } else { + if (flag2 && flag4) { + blockminecarttrackabstract_enumtrackposition = EnumTrackPosition.NORTH_WEST; + } + + if (flag5 && flag2) { + blockminecarttrackabstract_enumtrackposition = EnumTrackPosition.NORTH_EAST; + } + + if (flag4 && flag3) { + blockminecarttrackabstract_enumtrackposition = EnumTrackPosition.SOUTH_WEST; + } + + if (flag3 && flag5) { + blockminecarttrackabstract_enumtrackposition = EnumTrackPosition.SOUTH_EAST; + } + } + } + } + + if (blockminecarttrackabstract_enumtrackposition == EnumTrackPosition.NORTH_SOUTH) { + if (BlockMinecartTrackAbstract.e(this.b, blockposition.getX(), blockposition.getY() + 1, blockposition.getZ())) { + blockminecarttrackabstract_enumtrackposition = EnumTrackPosition.ASCENDING_NORTH; + } + + if (BlockMinecartTrackAbstract.e(this.b, blockposition1.getX(), blockposition1.getY() + 1, blockposition1.getZ())) { + blockminecarttrackabstract_enumtrackposition = EnumTrackPosition.ASCENDING_SOUTH; + } + } + + if (blockminecarttrackabstract_enumtrackposition == EnumTrackPosition.EAST_WEST) { + if (BlockMinecartTrackAbstract.e(this.b, blockposition3.getX(), blockposition3.getY() + 1, blockposition3.getZ())) { + blockminecarttrackabstract_enumtrackposition = EnumTrackPosition.ASCENDING_EAST; + } + + if (BlockMinecartTrackAbstract.e(this.b, blockposition2.getX(), blockposition2.getY() + 1, blockposition2.getZ())) { + blockminecarttrackabstract_enumtrackposition = EnumTrackPosition.ASCENDING_WEST; + } + } + + if (blockminecarttrackabstract_enumtrackposition == null) { + blockminecarttrackabstract_enumtrackposition = EnumTrackPosition.NORTH_SOUTH; + } + + this.a(blockminecarttrackabstract_enumtrackposition); + this.e = this.e.set(this.d.n(), blockminecarttrackabstract_enumtrackposition); + if (flag1 || this.b.getType(this.c) != this.e) { + this.b.setTypeAndData(this.c, this.e, 3); + + for (BlockPosition blockPosition : this.g) { + MinecartTrackLogic blockminecarttrackabstract_minecarttracklogic = this.b(blockPosition); + + if (blockminecarttrackabstract_minecarttracklogic != null) { + blockminecarttrackabstract_minecarttracklogic.c(); + if (blockminecarttrackabstract_minecarttracklogic.b(this)) { + blockminecarttrackabstract_minecarttracklogic.c(this); + } + } + } + } + + return this; + } + + public IBlockData b() { + return this.e; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockMobSpawner.java b/azurite-server/src/main/java/net/minecraft/server/BlockMobSpawner.java new file mode 100644 index 0000000..b4a506e --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockMobSpawner.java @@ -0,0 +1,40 @@ +package net.minecraft.server; + +import java.util.Random; + +public class BlockMobSpawner extends BlockContainer { + + protected BlockMobSpawner() { + super(Material.STONE); + } + + public TileEntity a(World world, int i) { + return new TileEntityMobSpawner(); + } + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + return null; + } + + public int a(Random random) { + return 0; + } + + public void dropNaturally(World world, BlockPosition blockposition, IBlockData iblockdata, float f, int i) { + super.dropNaturally(world, blockposition, iblockdata, f, i); + } + + @Override + public int getExpDrop(World world, IBlockData iblockdata, int enchantmentLevel) { + return 15 + world.random.nextInt(15) + world.random.nextInt(15); + // CraftBukkit end + } + + public boolean c() { + return false; + } + + public int b() { + return 3; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockMonsterEggs.java b/azurite-server/src/main/java/net/minecraft/server/BlockMonsterEggs.java new file mode 100644 index 0000000..dc3a5f2 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockMonsterEggs.java @@ -0,0 +1,206 @@ +package net.minecraft.server; + +import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason; + +import java.util.Random; + +public class BlockMonsterEggs extends Block { + + public static final BlockStateEnum VARIANT = BlockStateEnum.of("variant", BlockMonsterEggs.EnumMonsterEggVarient.class); + + public BlockMonsterEggs() { + super(Material.CLAY); + this.j(this.blockStateList.getBlockData().set(BlockMonsterEggs.VARIANT, BlockMonsterEggs.EnumMonsterEggVarient.STONE)); + this.c(0.0F); + this.a(CreativeModeTab.c); + } + + public int a(Random random) { + return 0; + } + + public static boolean d(IBlockData iblockdata) { + Block block = iblockdata.getBlock(); + + return iblockdata == Blocks.STONE.getBlockData().set(BlockStone.VARIANT, BlockStone.EnumStoneVariant.STONE) || block == Blocks.COBBLESTONE || block == Blocks.STONEBRICK; + } + + protected ItemStack i(IBlockData iblockdata) { + switch (BlockMonsterEggs.SyntheticClass_1.a[iblockdata.get(BlockMonsterEggs.VARIANT).ordinal()]) { + case 1: + return new ItemStack(Blocks.COBBLESTONE); + + case 2: + return new ItemStack(Blocks.STONEBRICK); + + case 3: + return new ItemStack(Blocks.STONEBRICK, 1, BlockSmoothBrick.EnumStonebrickType.MOSSY.a()); + + case 4: + return new ItemStack(Blocks.STONEBRICK, 1, BlockSmoothBrick.EnumStonebrickType.CRACKED.a()); + + case 5: + return new ItemStack(Blocks.STONEBRICK, 1, BlockSmoothBrick.EnumStonebrickType.CHISELED.a()); + + default: + return new ItemStack(Blocks.STONE); + } + } + + public void dropNaturally(World world, BlockPosition blockposition, IBlockData iblockdata, float f, int i) { + if (world.getGameRules().getBoolean("doTileDrops")) { + EntitySilverfish entitysilverfish = new EntitySilverfish(world); + + entitysilverfish.setPositionRotation((double) blockposition.getX() + 0.5D, blockposition.getY(), (double) blockposition.getZ() + 0.5D, 0.0F, 0.0F); + world.addEntity(entitysilverfish, SpawnReason.SILVERFISH_BLOCK); // CraftBukkit - add SpawnReason + entitysilverfish.y(); + } + + } + + public int getDropData(World world, BlockPosition blockposition) { + IBlockData iblockdata = world.getType(blockposition); + + return iblockdata.getBlock().toLegacyData(iblockdata); + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockMonsterEggs.VARIANT, BlockMonsterEggs.EnumMonsterEggVarient.a(i)); + } + + public int toLegacyData(IBlockData iblockdata) { + return iblockdata.get(BlockMonsterEggs.VARIANT).a(); + } + + public BlockStateList getStateList() { + return new BlockStateList(this, BlockMonsterEggs.VARIANT); + } + + static class SyntheticClass_1 { + + static final int[] a = new int[BlockMonsterEggs.EnumMonsterEggVarient.values().length]; + + static { + try { + BlockMonsterEggs.SyntheticClass_1.a[BlockMonsterEggs.EnumMonsterEggVarient.COBBLESTONE.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockMonsterEggs.SyntheticClass_1.a[BlockMonsterEggs.EnumMonsterEggVarient.STONEBRICK.ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockMonsterEggs.SyntheticClass_1.a[BlockMonsterEggs.EnumMonsterEggVarient.MOSSY_STONEBRICK.ordinal()] = 3; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockMonsterEggs.SyntheticClass_1.a[BlockMonsterEggs.EnumMonsterEggVarient.CRACKED_STONEBRICK.ordinal()] = 4; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockMonsterEggs.SyntheticClass_1.a[BlockMonsterEggs.EnumMonsterEggVarient.CHISELED_STONEBRICK.ordinal()] = 5; + } catch (NoSuchFieldError ignored) { + } + + } + } + + public enum EnumMonsterEggVarient implements INamable { + + STONE(0, "stone") { + public IBlockData d() { + return Blocks.STONE.getBlockData().set(BlockStone.VARIANT, BlockStone.EnumStoneVariant.STONE); + } + }, COBBLESTONE(1, "cobblestone", "cobble") { + public IBlockData d() { + return Blocks.COBBLESTONE.getBlockData(); + } + }, STONEBRICK(2, "stone_brick", "brick") { + public IBlockData d() { + return Blocks.STONEBRICK.getBlockData().set(BlockSmoothBrick.VARIANT, BlockSmoothBrick.EnumStonebrickType.DEFAULT); + } + }, MOSSY_STONEBRICK(3, "mossy_brick", "mossybrick") { + public IBlockData d() { + return Blocks.STONEBRICK.getBlockData().set(BlockSmoothBrick.VARIANT, BlockSmoothBrick.EnumStonebrickType.MOSSY); + } + }, CRACKED_STONEBRICK(4, "cracked_brick", "crackedbrick") { + public IBlockData d() { + return Blocks.STONEBRICK.getBlockData().set(BlockSmoothBrick.VARIANT, BlockSmoothBrick.EnumStonebrickType.CRACKED); + } + }, CHISELED_STONEBRICK(5, "chiseled_brick", "chiseledbrick") { + public IBlockData d() { + return Blocks.STONEBRICK.getBlockData().set(BlockSmoothBrick.VARIANT, BlockSmoothBrick.EnumStonebrickType.CHISELED); + } + }; + + private static final BlockMonsterEggs.EnumMonsterEggVarient[] g = new BlockMonsterEggs.EnumMonsterEggVarient[values().length]; + private final int h; + private final String i; + private final String j; + + EnumMonsterEggVarient(int i, String s) { + this(i, s, s); + } + + EnumMonsterEggVarient(int i, String s, String s1) { + this.h = i; + this.i = s; + this.j = s1; + } + + public int a() { + return this.h; + } + + public String toString() { + return this.i; + } + + public static BlockMonsterEggs.EnumMonsterEggVarient a(int i) { + if (i < 0 || i >= BlockMonsterEggs.EnumMonsterEggVarient.g.length) { + i = 0; + } + + return BlockMonsterEggs.EnumMonsterEggVarient.g[i]; + } + + public String getName() { + return this.i; + } + + public String c() { + return this.j; + } + + public abstract IBlockData d(); + + public static BlockMonsterEggs.EnumMonsterEggVarient a(IBlockData iblockdata) { + for (EnumMonsterEggVarient blockmonstereggs_enummonstereggvarient : values()) { + if (iblockdata == blockmonstereggs_enummonstereggvarient.d()) { + return blockmonstereggs_enummonstereggvarient; + } + } + + return BlockMonsterEggs.EnumMonsterEggVarient.STONE; + } + + EnumMonsterEggVarient(int i, String s, BlockMonsterEggs.SyntheticClass_1 blockmonstereggs_syntheticclass_1) { + this(i, s); + } + + EnumMonsterEggVarient(int i, String s, String s1, BlockMonsterEggs.SyntheticClass_1 blockmonstereggs_syntheticclass_1) { + this(i, s, s1); + } + + static { + for (EnumMonsterEggVarient blockmonstereggs_enummonstereggvarient : values()) { + EnumMonsterEggVarient.g[blockmonstereggs_enummonstereggvarient.a()] = blockmonstereggs_enummonstereggvarient; + } + + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockMushroom.java b/azurite-server/src/main/java/net/minecraft/server/BlockMushroom.java new file mode 100644 index 0000000..b5fe203 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockMushroom.java @@ -0,0 +1,111 @@ +package net.minecraft.server; + +import org.bukkit.TreeType; +import org.bukkit.block.BlockState; +import org.bukkit.event.block.BlockSpreadEvent; + +import java.util.Random; +// CraftBukkit end + +public class BlockMushroom extends BlockPlant implements IBlockFragilePlantElement { + + protected BlockMushroom() { + float f = 0.2F; + + this.a(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, f * 2.0F, 0.5F + f); + this.a(true); + } + + public void b(World world, BlockPosition blockposition, IBlockData iblockdata, Random random) { + final int sourceX = blockposition.getX(), sourceY = blockposition.getY(), sourceZ = blockposition.getZ(); // CraftBukkit + if (random.nextInt(Math.max(1, (int) world.growthOdds / world.spigotConfig.mushroomModifier * 25)) == 0) { // Spigot int i = 5; + int i = 5; + + for (BlockPosition blockposition1 : BlockPosition.b(blockposition.a(-4, -1, -4), blockposition.a(4, 1, 4))) { + if (world.getType(blockposition1).getBlock() == this) { + --i; + if (i <= 0) { + return; + } + } + } + + BlockPosition blockposition2 = blockposition.a(random.nextInt(3) - 1, random.nextInt(2) - random.nextInt(2), random.nextInt(3) - 1); + + for (int j = 0; j < 4; ++j) { + if (world.isEmpty(blockposition2) && this.f(world, blockposition2, this.getBlockData())) { + blockposition = blockposition2; + } + + blockposition2 = blockposition.a(random.nextInt(3) - 1, random.nextInt(2) - random.nextInt(2), random.nextInt(3) - 1); + } + + if (world.isEmpty(blockposition2) && this.f(world, blockposition2, this.getBlockData())) { + // CraftBukkit start + // world.setTypeAndData(blockposition2, this.getBlockData(), 2); + org.bukkit.World bworld = world.getWorld(); + BlockState blockState = bworld.getBlockAt(blockposition2.getX(), blockposition2.getY(), blockposition2.getZ()).getState(); + blockState.setType(org.bukkit.craftbukkit.util.CraftMagicNumbers.getMaterial(this)); // nms: this.id, 0, 2 + + BlockSpreadEvent event = new BlockSpreadEvent(blockState.getBlock(), bworld.getBlockAt(sourceX, sourceY, sourceZ), blockState); + world.getServer().getPluginManager().callEvent(event); + + if (!event.isCancelled()) { + blockState.update(true); + } + // CraftBukkit end + } + } + + } + + public boolean canPlace(World world, BlockPosition blockposition) { + return super.canPlace(world, blockposition) && this.f(world, blockposition, this.getBlockData()); + } + + protected boolean c(Block block) { + return block.o(); + } + + public boolean f(World world, BlockPosition blockposition, IBlockData iblockdata) { + if (blockposition.getY() >= 0 && blockposition.getY() < 256) { + IBlockData iblockdata1 = world.getType(blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()); + + return iblockdata1.getBlock() == Blocks.MYCELIUM || (iblockdata1.getBlock() == Blocks.DIRT && iblockdata1.get(BlockDirt.VARIANT) == BlockDirt.EnumDirtVariant.PODZOL || world.k(blockposition) < 13 && this.c(iblockdata1.getBlock())); + } else { + return false; + } + } + + public boolean d(World world, BlockPosition blockposition, IBlockData iblockdata, Random random) { + world.setAir(blockposition); + WorldGenHugeMushroom worldgenhugemushroom = null; + + if (this == Blocks.BROWN_MUSHROOM) { + BlockSapling.treeType = TreeType.BROWN_MUSHROOM; // CraftBukkit + worldgenhugemushroom = new WorldGenHugeMushroom(Blocks.BROWN_MUSHROOM_BLOCK); + } else if (this == Blocks.RED_MUSHROOM) { + BlockSapling.treeType = TreeType.RED_MUSHROOM; // CraftBukkit + worldgenhugemushroom = new WorldGenHugeMushroom(Blocks.RED_MUSHROOM_BLOCK); + } + + if (worldgenhugemushroom != null && worldgenhugemushroom.generate(world, random, blockposition)) { + return true; + } else { + world.setTypeAndData(blockposition, iblockdata, 3); + return false; + } + } + + public boolean a(World world, BlockPosition blockposition, IBlockData iblockdata, boolean flag) { + return true; + } + + public boolean a(World world, Random random, BlockPosition blockposition, IBlockData iblockdata) { + return random.nextFloat() < 0.4D; + } + + public void b(World world, Random random, BlockPosition blockposition, IBlockData iblockdata) { + this.d(world, blockposition, iblockdata, random); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockMycel.java b/azurite-server/src/main/java/net/minecraft/server/BlockMycel.java new file mode 100644 index 0000000..3755e74 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockMycel.java @@ -0,0 +1,83 @@ +package net.minecraft.server; + +import org.bukkit.block.BlockState; +import org.bukkit.craftbukkit.util.CraftMagicNumbers; +import org.bukkit.event.block.BlockFadeEvent; +import org.bukkit.event.block.BlockSpreadEvent; + +import java.util.Random; +// CraftBukkit end + +public class BlockMycel extends Block { + + public static final BlockStateBoolean SNOWY = BlockStateBoolean.of("snowy"); + + protected BlockMycel() { + super(Material.GRASS, MaterialMapColor.z); + this.j(this.blockStateList.getBlockData().set(BlockMycel.SNOWY, false)); + this.a(true); + this.a(CreativeModeTab.b); + } + + public IBlockData updateState(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { + Block block = iblockaccess.getType(blockposition.getX(), blockposition.getY() + 1, blockposition.getZ()).getBlock(); + + return iblockdata.set(BlockMycel.SNOWY, block == Blocks.SNOW || block == Blocks.SNOW_LAYER); + } + + public void b(World world, BlockPosition blockposition, IBlockData iblockdata, Random random) { + int lightLevel = world.getLightLevel(blockposition.getX(), blockposition.getY() + 1, blockposition.getZ()); + if (lightLevel < 4 && world.getType(blockposition.getX(), blockposition.getY() + 1, blockposition.getZ()).getBlock().p() > 2) { + // CraftBukkit start + // world.setTypeUpdate(blockposition, Blocks.DIRT.getBlockData().set(BlockDirt.VARIANT, EnumDirtVariant.DIRT)); + org.bukkit.World bworld = world.getWorld(); + BlockState blockState = bworld.getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()).getState(); + blockState.setType(CraftMagicNumbers.getMaterial(Blocks.DIRT)); + + BlockFadeEvent event = new BlockFadeEvent(blockState.getBlock(), blockState); + world.getServer().getPluginManager().callEvent(event); + + if (!event.isCancelled()) { + blockState.update(true); + } + // CraftBukkit end + } else { + if (lightLevel >= 9) { + for (int i = 0; i < Math.min(4, Math.max(20, (int) (4 * 100F / world.growthOdds))); ++i) { // Spigot + BlockPosition blockposition1 = blockposition.a(random.nextInt(3) - 1, random.nextInt(5) - 3, random.nextInt(3) - 1); + IBlockData iblockdata1 = world.getType(blockposition1); + Block block = world.getType(blockposition1.getX(), blockposition1.getY() + 1, blockposition1.getZ()).getBlock(); + + if (iblockdata1.getBlock() == Blocks.DIRT && iblockdata1.get(BlockDirt.VARIANT) == BlockDirt.EnumDirtVariant.DIRT && world.getLightLevel(blockposition1.getX(), blockposition1.getY() + 1, blockposition1.getZ()) >= 4 && block.p() <= 2) { + // CraftBukkit start + // world.setTypeUpdate(blockposition1, this.getBlockData()); + org.bukkit.World bworld = world.getWorld(); + BlockState blockState = bworld.getBlockAt(blockposition1.getX(), blockposition1.getY(), blockposition1.getZ()).getState(); + blockState.setType(CraftMagicNumbers.getMaterial(this)); + + BlockSpreadEvent event = new BlockSpreadEvent(blockState.getBlock(), bworld.getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()), blockState); + world.getServer().getPluginManager().callEvent(event); + + if (!event.isCancelled()) { + blockState.update(true); + } + // CraftBukkit end + } + } + } + + } + } + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + return Blocks.DIRT.getDropType(Blocks.DIRT.getBlockData().set(BlockDirt.VARIANT, BlockDirt.EnumDirtVariant.DIRT), random, i); + } + + public int toLegacyData(IBlockData iblockdata) { + return 0; + } + + public BlockStateList getStateList() { + return new BlockStateList(this, new IBlockState[]{BlockMycel.SNOWY}); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockNetherWart.java b/azurite-server/src/main/java/net/minecraft/server/BlockNetherWart.java new file mode 100644 index 0000000..127d83f --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockNetherWart.java @@ -0,0 +1,74 @@ +package net.minecraft.server; + +import java.util.Random; + +public class BlockNetherWart extends BlockPlant { + + public static final BlockStateInteger AGE = BlockStateInteger.of("age", 0, 3); + + protected BlockNetherWart() { + super(Material.PLANT, MaterialMapColor.D); + this.j(this.blockStateList.getBlockData().set(BlockNetherWart.AGE, 0)); + this.a(true); + float f = 0.5F; + + this.a(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, 0.25F, 0.5F + f); + this.a((CreativeModeTab) null); + } + + protected boolean c(Block block) { + return block == Blocks.SOUL_SAND; + } + + public boolean f(World world, BlockPosition blockposition, IBlockData iblockdata) { + return this.c(world.getType(blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()).getBlock()); + } + + public void b(World world, BlockPosition blockposition, IBlockData iblockdata, Random random) { + int i = iblockdata.get(BlockNetherWart.AGE); + + if (i < 3 && random.nextInt(Math.max(1, (int) world.growthOdds / world.spigotConfig.wartModifier * 10)) == 0) { // Spigot + iblockdata = iblockdata.set(BlockNetherWart.AGE, i + 1); + // world.setTypeAndData(blockposition, iblockdata, 2); // CraftBukkit + org.bukkit.craftbukkit.event.CraftEventFactory.handleBlockGrowEvent(world, blockposition.getX(), blockposition.getY(), blockposition.getZ(), this, toLegacyData(iblockdata)); // CraftBukkit + } + + super.b(world, blockposition, iblockdata, random); + } + + public void dropNaturally(World world, BlockPosition blockposition, IBlockData iblockdata, float f, int i) { + int j = 1; + + if (iblockdata.get(BlockNetherWart.AGE) >= 3) { + j = 2 + world.random.nextInt(3); + if (i > 0) { + j += world.random.nextInt(i + 1); + } + } + + for (int k = 0; k < j; ++k) { + a(world, blockposition, new ItemStack(Items.NETHER_WART)); + } + + } + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + return null; + } + + public int a(Random random) { + return 0; + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockNetherWart.AGE, i); + } + + public int toLegacyData(IBlockData iblockdata) { + return iblockdata.get(BlockNetherWart.AGE); + } + + public BlockStateList getStateList() { + return new BlockStateList(this, BlockNetherWart.AGE); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockNetherbrick.java b/azurite-server/src/main/java/net/minecraft/server/BlockNetherbrick.java new file mode 100644 index 0000000..4ddcbd6 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockNetherbrick.java @@ -0,0 +1,13 @@ +package net.minecraft.server; + +public class BlockNetherbrick extends Block { + + public BlockNetherbrick() { + super(Material.STONE); + this.a(CreativeModeTab.b); + } + + public MaterialMapColor g(IBlockData iblockdata) { + return MaterialMapColor.K; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockNote.java b/azurite-server/src/main/java/net/minecraft/server/BlockNote.java new file mode 100644 index 0000000..e32adfa --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockNote.java @@ -0,0 +1,78 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; + +import java.util.List; + +public class BlockNote extends BlockContainer { + + private static final List a = Lists.newArrayList("harp", "bd", "snare", "hat", "bassattack"); + + public BlockNote() { + super(Material.WOOD); + this.a(CreativeModeTab.d); + } + + public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) { + boolean flag = world.isBlockIndirectlyPowered(blockposition); + TileEntity tileentity = world.getTileEntity(blockposition); + + if (tileentity instanceof TileEntityNote) { + TileEntityNote tileentitynote = (TileEntityNote) tileentity; + + if (tileentitynote.f != flag) { + if (flag) { + tileentitynote.play(world, blockposition); + } + + tileentitynote.f = flag; + } + } + + } + + public boolean interact(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman, EnumDirection enumdirection, float f, float f1, float f2) { + TileEntity tileentity = world.getTileEntity(blockposition); + + if (tileentity instanceof TileEntityNote) { + TileEntityNote tileentitynote = (TileEntityNote) tileentity; + + tileentitynote.b(); + tileentitynote.play(world, blockposition); + } + + return true; + } + + public void attack(World world, BlockPosition blockposition, EntityHuman entityhuman) { + TileEntity tileentity = world.getTileEntity(blockposition); + + if (tileentity instanceof TileEntityNote) { + ((TileEntityNote) tileentity).play(world, blockposition); + } + } + + public TileEntity a(World world, int i) { + return new TileEntityNote(); + } + + private String b(int i) { + if (i < 0 || i >= BlockNote.a.size()) { + i = 0; + } + + return BlockNote.a.get(i); + } + + public boolean a(World world, BlockPosition blockposition, IBlockData iblockdata, int i, int j) { + float f = (float) Math.pow(2.0D, (double) (j - 12) / 12.0D); + + world.makeSound((double) blockposition.getX() + 0.5D, (double) blockposition.getY() + 0.5D, (double) blockposition.getZ() + 0.5D, "note." + this.b(i), 3.0F, f); + world.addParticle(EnumParticle.NOTE, (double) blockposition.getX() + 0.5D, (double) blockposition.getY() + 1.2D, (double) blockposition.getZ() + 0.5D, (double) j / 24.0D, 0.0D, 0.0D, EnumParticle.EMPTY_ARRAY); + return true; + } + + public int b() { + return 3; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockObsidian.java b/azurite-server/src/main/java/net/minecraft/server/BlockObsidian.java new file mode 100644 index 0000000..cec0dee --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockObsidian.java @@ -0,0 +1,20 @@ +package net.minecraft.server; + +import java.util.Random; + +public class BlockObsidian extends Block { + + public BlockObsidian() { + super(Material.STONE); + a(CreativeModeTab.b); + } + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + return Item.getItemOf(Blocks.OBSIDIAN); + } + + public MaterialMapColor g(IBlockData iblockdata) { + return MaterialMapColor.E; + } + +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockOre.java b/azurite-server/src/main/java/net/minecraft/server/BlockOre.java new file mode 100644 index 0000000..4eed029 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockOre.java @@ -0,0 +1,73 @@ +package net.minecraft.server; + +import java.util.Random; + +public class BlockOre extends Block { + + public BlockOre() { + this(Material.STONE.r()); + } + + public BlockOre(MaterialMapColor materialmapcolor) { + super(Material.STONE, materialmapcolor); + this.a(CreativeModeTab.b); + } + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + return this == Blocks.COAL_ORE ? Items.COAL : (this == Blocks.DIAMOND_ORE ? Items.DIAMOND : (this == Blocks.LAPIS_ORE ? Items.DYE : (this == Blocks.EMERALD_ORE ? Items.EMERALD : (this == Blocks.QUARTZ_ORE ? Items.QUARTZ : Item.getItemOf(this))))); + } + + public int a(Random random) { + return this == Blocks.LAPIS_ORE ? 4 + random.nextInt(5) : 1; + } + + public int getDropCount(int i, Random random) { + if (i > 0 && Item.getItemOf(this) != this.getDropType(this.P().a().iterator().next(), random, i)) { + int j = random.nextInt(i + 2) - 1; + + if (j < 0) { + j = 0; + } + + return this.a(random) * (j + 1); + } else { + return this.a(random); + } + } + + public void dropNaturally(World world, BlockPosition blockposition, IBlockData iblockdata, float f, int i) { + super.dropNaturally(world, blockposition, iblockdata, f, i); + } + + @Override + public int getExpDrop(World world, IBlockData iblockdata, int i) { + if (this.getDropType(iblockdata, world.random, i) != Item.getItemOf(this)) { + int j = 0; + + if (this == Blocks.COAL_ORE) { + j = MathHelper.nextInt(world.random, 0, 2); + } else if (this == Blocks.DIAMOND_ORE) { + j = MathHelper.nextInt(world.random, 3, 7); + } else if (this == Blocks.EMERALD_ORE) { + j = MathHelper.nextInt(world.random, 3, 7); + } else if (this == Blocks.LAPIS_ORE) { + j = MathHelper.nextInt(world.random, 2, 5); + } else if (this == Blocks.QUARTZ_ORE) { + j = MathHelper.nextInt(world.random, 2, 5); + } + + return j; + } + + return 0; + // CraftBukkit end + } + + public int getDropData(World world, BlockPosition blockposition) { + return 0; + } + + public int getDropData(IBlockData iblockdata) { + return this == Blocks.LAPIS_ORE ? EnumColor.BLUE.getInvColorIndex() : 0; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockPackedIce.java b/azurite-server/src/main/java/net/minecraft/server/BlockPackedIce.java new file mode 100644 index 0000000..38f0184 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockPackedIce.java @@ -0,0 +1,16 @@ +package net.minecraft.server; + +import java.util.Random; + +public class BlockPackedIce extends Block { + + public BlockPackedIce() { + super(Material.SNOW_LAYER); + this.frictionFactor = 0.98F; + this.a(CreativeModeTab.b); + } + + public int a(Random random) { + return 0; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockPiston.java b/azurite-server/src/main/java/net/minecraft/server/BlockPiston.java new file mode 100644 index 0000000..63f5cc7 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockPiston.java @@ -0,0 +1,443 @@ +package net.minecraft.server; + +import com.google.common.collect.ImmutableList; +import dev.azurite.spigot.configs.AzuriteConfig; +import org.bukkit.craftbukkit.block.CraftBlock; +import org.bukkit.event.block.BlockPistonExtendEvent; +import org.bukkit.event.block.BlockPistonRetractEvent; + +import java.util.AbstractList; +import java.util.List; +// CraftBukkit end + +public class BlockPiston extends Block { + + public static final BlockStateDirection FACING = BlockStateDirection.of("facing"); + public static final BlockStateBoolean EXTENDED = BlockStateBoolean.of("extended"); + private final boolean sticky; + + public BlockPiston(boolean flag) { + super(Material.PISTON); + this.j(this.blockStateList.getBlockData().set(BlockPiston.FACING, EnumDirection.NORTH).set(BlockPiston.EXTENDED, false)); + this.sticky = flag; + this.a(BlockPiston.i); + this.c(0.5F); + this.a(CreativeModeTab.d); + } + + public static EnumDirection b(int i) { + int j = i & 7; + + return j > 5 ? null : EnumDirection.fromType1(j); + } + + public static EnumDirection a(World world, BlockPosition blockposition, EntityLiving entityliving) { + if (MathHelper.e((float) entityliving.locX - blockposition.getX()) < 2.0F && MathHelper.e((float) entityliving.locZ - (float) blockposition.getZ()) < 2.0F) { + double d0 = entityliving.locY + entityliving.getHeadHeight(); + + if (d0 - (double) blockposition.getY() > 2.0D) { + return EnumDirection.UP; + } + + if ((double) blockposition.getY() - d0 > 0.0D) { + return EnumDirection.DOWN; + } + } + + return entityliving.getDirection().opposite(); + } + + public static boolean a(Block block, World world, BlockPosition blockposition, EnumDirection enumdirection, boolean flag) { + if (block == Blocks.OBSIDIAN) { + return false; + } else if (!world.getWorldBorder().a(blockposition)) { + return false; + } else if (blockposition.getY() >= 0 && (enumdirection != EnumDirection.DOWN || blockposition.getY() != 0)) { + if (blockposition.getY() <= world.getHeight() - 1 && (enumdirection != EnumDirection.UP || blockposition.getY() != world.getHeight() - 1)) { + if (block != Blocks.PISTON && block != Blocks.STICKY_PISTON) { + if (block.g(world, blockposition) == -1.0F || block.k() == 2) { + return false; + } else if (block.k() == 1) { + return flag; + } + } else if (world.getType(blockposition).get(BlockPiston.EXTENDED)) { + return false; + } + + return !(block instanceof IContainer); + } else { + return false; + } + } else { + return false; + } + } + + public boolean c() { + return false; + } + + public void postPlace(World world, BlockPosition blockposition, IBlockData iblockdata, EntityLiving entityliving, ItemStack itemstack) { + world.setTypeAndData(blockposition, iblockdata.set(BlockPiston.FACING, a(world, blockposition, entityliving)), 2); + this.e(world, blockposition, iblockdata); + + } + + public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) { + this.e(world, blockposition, iblockdata); + + } + + public void onPlace(World world, BlockPosition blockposition, IBlockData iblockdata) { + if (world.getTileEntity(blockposition) == null) { + this.e(world, blockposition, iblockdata); + } + + } + + public IBlockData getPlacedState(World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2, int i, EntityLiving entityliving) { + return this.getBlockData().set(BlockPiston.FACING, a(world, blockposition, entityliving)).set(BlockPiston.EXTENDED, Boolean.FALSE); + } + + private void e(World world, BlockPosition blockposition, IBlockData iblockdata) { + EnumDirection enumdirection = iblockdata.get(BlockPiston.FACING); + boolean flag = this.a(world, blockposition, enumdirection); + + if (flag && !iblockdata.get(BlockPiston.EXTENDED)) { + if ((new PistonExtendsChecker(world, blockposition, enumdirection, true)).a()) { + world.playBlockAction(blockposition, this, 0, enumdirection.a()); + } + } else if (!flag && iblockdata.get(BlockPiston.EXTENDED)) { + // CraftBukkit start + if (!this.sticky) { + org.bukkit.block.Block block = world.getWorld().getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()); + BlockPistonRetractEvent event = new BlockPistonRetractEvent(block, ImmutableList.of(), CraftBlock.notchToBlockFace(enumdirection)); + world.getServer().getPluginManager().callEvent(event); + + if (event.isCancelled()) { + return; + } + } + // CraftBukkit end + world.setTypeAndData(blockposition, iblockdata.set(BlockPiston.EXTENDED, false), 2); + world.playBlockAction(blockposition, this, 1, enumdirection.a()); + } + + } + + private boolean a(World world, BlockPosition blockposition, EnumDirection enumdirection) { + for (EnumDirection enumdirection1 : EnumDirection.values()) { + if (enumdirection1 != enumdirection && world.isBlockFacePowered(blockposition.shift(enumdirection1), enumdirection1)) { + return true; + } + } + if (world.isBlockFacePowered(blockposition, EnumDirection.DOWN)) { + return true; + } else { + BlockPosition blockposition1 = blockposition.up(); + for (EnumDirection enumdirection2 : EnumDirection.values()) { + if (enumdirection2 != EnumDirection.DOWN && world.isBlockFacePowered(blockposition1.shift(enumdirection2), enumdirection2)) { + return true; + } + } + return false; + } + } + + public boolean a(World world, BlockPosition blockposition, IBlockData iblockdata, int i, int j) { + EnumDirection enumdirection = iblockdata.get(BlockPiston.FACING); + + boolean flag = this.a(world, blockposition, enumdirection); + + if (flag && i == 1) { + world.setTypeAndData(blockposition, iblockdata.set(BlockPiston.EXTENDED, true), 2); + return false; + } + + if (!flag && i == 0) { + return false; + } + + if (i == 0) { + if (!this.a(world, blockposition, enumdirection, true)) { + return false; + } + + world.setTypeAndData(blockposition, iblockdata.set(BlockPiston.EXTENDED, true), 2); + world.makeSound(blockposition.getX() + 0.5D, blockposition.getY() + 0.5D, blockposition.getZ() + 0.5D, "tile.piston.out", 0.5F, world.random.nextFloat() * 0.25F + 0.6F); + } else if (i == 1) { + TileEntity tileentity = world.getTileEntity(blockposition.shift(enumdirection)); + + if (tileentity instanceof TileEntityPiston) { + ((TileEntityPiston) tileentity).h(); + } + + world.setTypeAndData(blockposition, Blocks.PISTON_EXTENSION.getBlockData().set(BlockPistonMoving.FACING, enumdirection).set(BlockPistonMoving.TYPE, this.sticky ? BlockPistonExtension.EnumPistonType.STICKY : BlockPistonExtension.EnumPistonType.DEFAULT), 3); + world.setTileEntity(blockposition, BlockPistonMoving.a(this.fromLegacyData(j), enumdirection, false, true)); + if (this.sticky) { + BlockPosition blockposition1 = blockposition.a(enumdirection.getAdjacentX() * 2, enumdirection.getAdjacentY() * 2, enumdirection.getAdjacentZ() * 2); + Block block = world.getType(blockposition1).getBlock(); + boolean flag1 = false; + + if (block == Blocks.PISTON_EXTENSION) { + TileEntity tileentity1 = world.getTileEntity(blockposition1); + + if (tileentity1 instanceof TileEntityPiston) { + TileEntityPiston tileentitypiston = (TileEntityPiston) tileentity1; + + if (tileentitypiston.e() == enumdirection && tileentitypiston.d()) { + tileentitypiston.h(); + flag1 = true; + } + } + } + + if (!flag1 && a(block, world, blockposition1, enumdirection.opposite(), false) && (block.k() == 0 || block == Blocks.PISTON || block == Blocks.STICKY_PISTON)) { // CraftBukkit - remove 'block.getMaterial() != Material.AIR' condition + this.a(world, blockposition, enumdirection, false); + } + } else { + world.setAir(blockposition.shift(enumdirection)); + } + + world.makeSound(blockposition.getX() + 0.5D, blockposition.getY() + 0.5D, blockposition.getZ() + 0.5D, "tile.piston.in", 0.5F, world.random.nextFloat() * 0.15F + 0.6F); + } + + return true; + } + + public void updateShape(IBlockAccess iblockaccess, BlockPosition blockposition) { + IBlockData iblockdata = iblockaccess.getType(blockposition); + + if (iblockdata.getBlock() == this && iblockdata.get(BlockPiston.EXTENDED)) { + EnumDirection enumdirection = iblockdata.get(BlockPiston.FACING); + + if (enumdirection != null) { + switch (BlockPiston.SyntheticClass_1.a[enumdirection.ordinal()]) { + case 1: + this.a(0.0F, 0.25F, 0.0F, 1.0F, 1.0F, 1.0F); + break; + + case 2: + this.a(0.0F, 0.0F, 0.0F, 1.0F, 0.75F, 1.0F); + break; + + case 3: + this.a(0.0F, 0.0F, 0.25F, 1.0F, 1.0F, 1.0F); + break; + + case 4: + this.a(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 0.75F); + break; + + case 5: + this.a(0.25F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + break; + + case 6: + this.a(0.0F, 0.0F, 0.0F, 0.75F, 1.0F, 1.0F); + } + } + } else { + this.a(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + } + + } + + public void j() { + this.a(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + } + + public void a(World world, BlockPosition blockposition, IBlockData iblockdata, AxisAlignedBB axisalignedbb, List list, Entity entity) { + this.a(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + super.a(world, blockposition, iblockdata, axisalignedbb, list, entity); + } + + public AxisAlignedBB a(World world, BlockPosition blockposition, IBlockData iblockdata) { + this.updateShape(world, blockposition); + return super.a(world, blockposition, iblockdata); + } + + public boolean d() { + return false; + } + + private boolean a(World world, BlockPosition blockposition, EnumDirection enumdirection, boolean flag) { + if (!flag) { + world.setAir(blockposition.shift(enumdirection)); + } + + PistonExtendsChecker pistonextendschecker = new PistonExtendsChecker(world, blockposition, enumdirection, flag); + List list = pistonextendschecker.getMovedBlocks(); + List list1 = pistonextendschecker.getBrokenBlocks(); + + if (!pistonextendschecker.a()) { + return false; + } else { + // CraftBukkit start + final org.bukkit.block.Block bblock = world.getWorld().getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()); + + final List moved = pistonextendschecker.getMovedBlocks(); + final List broken = pistonextendschecker.getBrokenBlocks(); + + List blocks = new AbstractList() { + + @Override + public int size() { + return moved.size() + broken.size(); + } + + @Override + public org.bukkit.block.Block get(int index) { + if (index >= size() || index < 0) { + throw new ArrayIndexOutOfBoundsException(index); + } + BlockPosition pos = (index < moved.size() ? moved.get(index) : broken.get(index - moved.size())); + return bblock.getWorld().getBlockAt(pos.getX(), pos.getY(), pos.getZ()); + } + }; + + int i = list.size() + list1.size(); + Block[] ablock = new Block[i]; + EnumDirection enumdirection1 = flag ? enumdirection : enumdirection.opposite(); + + org.bukkit.event.block.BlockPistonEvent event; + if (flag) { + event = new BlockPistonExtendEvent(bblock, blocks, CraftBlock.notchToBlockFace(enumdirection1)); + } else { + event = new BlockPistonRetractEvent(bblock, blocks, CraftBlock.notchToBlockFace(enumdirection1)); + } + if (blocks.size() > AzuriteConfig.pistonMaxBlockPush.getValue()) { + event.setCancelled(true); + } + world.getServer().getPluginManager().callEvent(event); + + if (event.isCancelled()) { + for (BlockPosition b : broken) { + world.notify(b); + } + for (BlockPosition b : moved) { + world.notify(b); + world.notify(b.shift(enumdirection1)); + } + return false; + } + // CraftBukkit end + + int j; + BlockPosition blockposition1; + + for (j = list1.size() - 1; j >= 0; --j) { + blockposition1 = list1.get(j); + Block block = world.getType(blockposition1).getBlock(); + + block.b(world, blockposition1, world.getType(blockposition1), 0); + world.setAir(blockposition1); + --i; + ablock[i] = block; + } + + IBlockData iblockdata; + + for (j = list.size() - 1; j >= 0; --j) { + blockposition1 = list.get(j); + iblockdata = world.getType(blockposition1); + Block block1 = iblockdata.getBlock(); + + block1.toLegacyData(iblockdata); + world.setAir(blockposition1); + blockposition1 = blockposition1.shift(enumdirection1); + world.setTypeAndData(blockposition1, Blocks.PISTON_EXTENSION.getBlockData().set(BlockPiston.FACING, enumdirection), 4); + world.setTileEntity(blockposition1, BlockPistonMoving.a(iblockdata, enumdirection, flag, false)); + --i; + ablock[i] = block1; + } + + BlockPosition blockposition2 = blockposition.shift(enumdirection); + + if (flag) { + BlockPistonExtension.EnumPistonType blockpistonextension_enumpistontype = this.sticky ? BlockPistonExtension.EnumPistonType.STICKY : BlockPistonExtension.EnumPistonType.DEFAULT; + + iblockdata = Blocks.PISTON_HEAD.getBlockData().set(BlockPistonExtension.FACING, enumdirection).set(BlockPistonExtension.TYPE, blockpistonextension_enumpistontype); + IBlockData iblockdata1 = Blocks.PISTON_EXTENSION.getBlockData().set(BlockPistonMoving.FACING, enumdirection).set(BlockPistonMoving.TYPE, this.sticky ? BlockPistonExtension.EnumPistonType.STICKY : BlockPistonExtension.EnumPistonType.DEFAULT); + + world.setTypeAndData(blockposition2, iblockdata1, 4); + world.setTileEntity(blockposition2, BlockPistonMoving.a(iblockdata, enumdirection, true, false)); + } + + int k; + + for (k = list1.size() - 1; k >= 0; --k) { + world.applyPhysics(list1.get(k), ablock[i++]); + } + + for (k = list.size() - 1; k >= 0; --k) { + world.applyPhysics(list.get(k), ablock[i++]); + } + + if (flag) { + world.applyPhysics(blockposition2, Blocks.PISTON_HEAD); + world.applyPhysics(blockposition, this); + } + + return true; + } + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockPiston.FACING, b(i)).set(BlockPiston.EXTENDED, (i & 8) > 0); + } + + public int toLegacyData(IBlockData iblockdata) { + byte b0 = 0; + int i = b0 | iblockdata.get(BlockPiston.FACING).a(); + + if (iblockdata.get(BlockPiston.EXTENDED)) { + i |= 8; + } + + return i; + } + + public BlockStateList getStateList() { + return new BlockStateList(this, BlockPiston.FACING, BlockPiston.EXTENDED); + } + + static class SyntheticClass_1 { + + static final int[] a = new int[EnumDirection.values().length]; + + static { + try { + BlockPiston.SyntheticClass_1.a[EnumDirection.DOWN.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockPiston.SyntheticClass_1.a[EnumDirection.UP.ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockPiston.SyntheticClass_1.a[EnumDirection.NORTH.ordinal()] = 3; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockPiston.SyntheticClass_1.a[EnumDirection.SOUTH.ordinal()] = 4; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockPiston.SyntheticClass_1.a[EnumDirection.WEST.ordinal()] = 5; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockPiston.SyntheticClass_1.a[EnumDirection.EAST.ordinal()] = 6; + } catch (NoSuchFieldError ignored) { + } + + } + } +} + \ No newline at end of file diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockPistonExtension.java b/azurite-server/src/main/java/net/minecraft/server/BlockPistonExtension.java new file mode 100644 index 0000000..3ae92a6 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockPistonExtension.java @@ -0,0 +1,215 @@ +package net.minecraft.server; + +import java.util.List; +import java.util.Random; + +public class BlockPistonExtension extends Block { + public static final BlockStateDirection FACING = BlockStateDirection.of("facing"); + + public static final BlockStateEnum TYPE = BlockStateEnum.of("type", EnumPistonType.class); + + public static final BlockStateBoolean SHORT = BlockStateBoolean.of("short"); + + public BlockPistonExtension() { + super(Material.PISTON); + j(this.blockStateList.getBlockData().set(FACING, EnumDirection.NORTH).set(TYPE, EnumPistonType.DEFAULT).set(SHORT, Boolean.FALSE)); + a(i); + c(0.5F); + } + + public static EnumDirection b(int paramInt) { + int i = paramInt & 0x7; + if (i > 5) + return null; + return EnumDirection.fromType1(i); + } + + public void a(World paramWorld, BlockPosition paramBlockPosition, IBlockData paramIBlockData, EntityHuman paramEntityHuman) { + if (paramEntityHuman.abilities.canInstantlyBuild) { + EnumDirection enumDirection = paramIBlockData.get(FACING); + if (enumDirection != null) { + BlockPosition blockPosition = paramBlockPosition.shift(enumDirection.opposite()); + Block block = paramWorld.getType(blockPosition).getBlock(); + if (block == Blocks.PISTON || block == Blocks.STICKY_PISTON) + paramWorld.setAir(blockPosition); + } + } + super.a(paramWorld, paramBlockPosition, paramIBlockData, paramEntityHuman); + } + + public void remove(World paramWorld, BlockPosition paramBlockPosition, IBlockData paramIBlockData) { + super.remove(paramWorld, paramBlockPosition, paramIBlockData); + EnumDirection enumDirection = paramIBlockData.get(FACING).opposite(); + paramBlockPosition = paramBlockPosition.shift(enumDirection); + IBlockData iBlockData = paramWorld.getType(paramBlockPosition); + if ((iBlockData.getBlock() == Blocks.PISTON || iBlockData.getBlock() == Blocks.STICKY_PISTON) && iBlockData.get(BlockPiston.EXTENDED)) { + iBlockData.getBlock().b(paramWorld, paramBlockPosition, iBlockData, 0); + paramWorld.setAir(paramBlockPosition); + } + } + + public boolean c() { + return false; + } + + public boolean d() { + return false; + } + + public boolean canPlace(World paramWorld, BlockPosition paramBlockPosition) { + return false; + } + + public boolean canPlace(World paramWorld, BlockPosition paramBlockPosition, EnumDirection paramEnumDirection) { + return false; + } + + public int a(Random paramRandom) { + return 0; + } + + public void a(World paramWorld, BlockPosition paramBlockPosition, IBlockData paramIBlockData, AxisAlignedBB paramAxisAlignedBB, List paramList, Entity paramEntity) { + d(paramIBlockData); + super.a(paramWorld, paramBlockPosition, paramIBlockData, paramAxisAlignedBB, paramList, paramEntity); + e(paramIBlockData); + super.a(paramWorld, paramBlockPosition, paramIBlockData, paramAxisAlignedBB, paramList, paramEntity); + a(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + } + + private void e(IBlockData paramIBlockData) { + switch (BlockPistonExtension.SyntheticClass_1.a[(paramIBlockData.get(FACING)).ordinal()]) { + case 1: + a(0.375F, 0.25F, 0.375F, 0.625F, 1.0F, 0.625F); + break; + case 2: + a(0.375F, 0.0F, 0.375F, 0.625F, 0.75F, 0.625F); + break; + case 3: + a(0.25F, 0.375F, 0.25F, 0.75F, 0.625F, 1.0F); + break; + case 4: + a(0.25F, 0.375F, 0.0F, 0.75F, 0.625F, 0.75F); + break; + case 5: + a(0.375F, 0.25F, 0.25F, 0.625F, 0.75F, 1.0F); + break; + case 6: + a(0.0F, 0.375F, 0.25F, 0.75F, 0.625F, 0.75F); + break; + } + } + + public void updateShape(IBlockAccess paramIBlockAccess, BlockPosition paramBlockPosition) { + d(paramIBlockAccess.getType(paramBlockPosition)); + } + + public void d(IBlockData paramIBlockData) { + EnumDirection enumDirection = paramIBlockData.get(FACING); + if (enumDirection == null) + return; + switch (BlockPistonExtension.SyntheticClass_1.a[enumDirection.ordinal()]) { + case 1: + a(0.0F, 0.0F, 0.0F, 1.0F, 0.25F, 1.0F); + break; + case 2: + a(0.0F, 0.75F, 0.0F, 1.0F, 1.0F, 1.0F); + break; + case 3: + a(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 0.25F); + break; + case 4: + a(0.0F, 0.0F, 0.75F, 1.0F, 1.0F, 1.0F); + break; + case 5: + a(0.0F, 0.0F, 0.0F, 0.25F, 1.0F, 1.0F); + break; + case 6: + a(0.75F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + break; + } + } + + public void doPhysics(World paramWorld, BlockPosition paramBlockPosition, IBlockData paramIBlockData, Block paramBlock) { + EnumDirection enumDirection = paramIBlockData.get(FACING); + BlockPosition blockPosition = paramBlockPosition.shift(enumDirection.opposite()); + IBlockData iBlockData = paramWorld.getType(blockPosition); + if (iBlockData.getBlock() != Blocks.PISTON && iBlockData.getBlock() != Blocks.STICKY_PISTON) { + paramWorld.setAir(paramBlockPosition); + } else { + iBlockData.getBlock().doPhysics(paramWorld, blockPosition, iBlockData, paramBlock); + } + } + + public IBlockData fromLegacyData(int paramInt) { + return getBlockData().set(FACING, b(paramInt)).set(TYPE, ((paramInt & 0x8) > 0) ? EnumPistonType.STICKY : EnumPistonType.DEFAULT); + } + + public int toLegacyData(IBlockData paramIBlockData) { + int i = 0; + i |= paramIBlockData.get(FACING).a(); + if (paramIBlockData.get(TYPE) == EnumPistonType.STICKY) + i |= 0x8; + return i; + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, FACING, TYPE, SHORT); + } + + static class SyntheticClass_1 { + + static final int[] a = new int[EnumDirection.values().length]; + + static { + try { + BlockPistonExtension.SyntheticClass_1.a[EnumDirection.DOWN.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockPistonExtension.SyntheticClass_1.a[EnumDirection.UP.ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockPistonExtension.SyntheticClass_1.a[EnumDirection.NORTH.ordinal()] = 3; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockPistonExtension.SyntheticClass_1.a[EnumDirection.SOUTH.ordinal()] = 4; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockPistonExtension.SyntheticClass_1.a[EnumDirection.WEST.ordinal()] = 5; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockPistonExtension.SyntheticClass_1.a[EnumDirection.EAST.ordinal()] = 6; + } catch (NoSuchFieldError ignored) { + } + + } + } + + public enum EnumPistonType implements INamable { + DEFAULT("normal"), + STICKY("sticky"); + + private final String c; + + EnumPistonType(String param1String1) { + this.c = param1String1; + } + + public String toString() { + return this.c; + } + + public String getName() { + return this.c; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockPistonMoving.java b/azurite-server/src/main/java/net/minecraft/server/BlockPistonMoving.java new file mode 100644 index 0000000..06b0236 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockPistonMoving.java @@ -0,0 +1,170 @@ +package net.minecraft.server; + +import java.util.Random; + +public class BlockPistonMoving extends BlockContainer { + public static final BlockStateDirection FACING = BlockPistonExtension.FACING; + + public static final BlockStateEnum TYPE = BlockPistonExtension.TYPE; + + public BlockPistonMoving() { + super(Material.PISTON); + j(this.blockStateList.getBlockData().set(FACING, EnumDirection.NORTH).set(TYPE, BlockPistonExtension.EnumPistonType.DEFAULT)); + c(-1.0F); + } + + public static TileEntity a(IBlockData paramIBlockData, EnumDirection paramEnumDirection, boolean paramBoolean1, boolean paramBoolean2) { + return new TileEntityPiston(paramIBlockData, paramEnumDirection, paramBoolean1, paramBoolean2); + } + + public TileEntity a(World paramWorld, int paramInt) { + return null; + } + + public void remove(World paramWorld, BlockPosition paramBlockPosition, IBlockData paramIBlockData) { + TileEntity tileEntity = paramWorld.getTileEntity(paramBlockPosition); + if (tileEntity instanceof TileEntityPiston) { + ((TileEntityPiston) tileEntity).h(); + } else { + super.remove(paramWorld, paramBlockPosition, paramIBlockData); + } + } + + public boolean canPlace(World paramWorld, BlockPosition paramBlockPosition) { + return false; + } + + public boolean canPlace(World paramWorld, BlockPosition paramBlockPosition, EnumDirection paramEnumDirection) { + return false; + } + + public void postBreak(World paramWorld, BlockPosition paramBlockPosition, IBlockData paramIBlockData) { + BlockPosition blockPosition = paramBlockPosition.shift(paramIBlockData.get(FACING).opposite()); + IBlockData iBlockData = paramWorld.getType(blockPosition); + if (iBlockData.getBlock() instanceof BlockPiston && iBlockData.get(BlockPiston.EXTENDED)) + paramWorld.setAir(blockPosition); + } + + public boolean c() { + return false; + } + + public boolean d() { + return false; + } + + public boolean interact(World paramWorld, BlockPosition paramBlockPosition, IBlockData paramIBlockData, EntityHuman paramEntityHuman, EnumDirection paramEnumDirection, float paramFloat1, float paramFloat2, float paramFloat3) { + if (paramWorld.getTileEntity(paramBlockPosition) == null) { + paramWorld.setAir(paramBlockPosition); + return true; + } + return false; + } + + public Item getDropType(IBlockData paramIBlockData, Random paramRandom, int paramInt) { + return null; + } + + public void dropNaturally(World paramWorld, BlockPosition paramBlockPosition, IBlockData paramIBlockData, float paramFloat, int paramInt) { + TileEntityPiston tileEntityPiston = e((IBlockAccess) paramWorld, paramBlockPosition); + if (tileEntityPiston == null) + return; + IBlockData iBlockData = tileEntityPiston.b(); + iBlockData.getBlock().b(paramWorld, paramBlockPosition, iBlockData, 0); + } + + public MovingObjectPosition a(World paramWorld, BlockPosition paramBlockPosition, Vec3D paramVec3D1, Vec3D paramVec3D2) { + return null; + } + + public void doPhysics(World paramWorld, BlockPosition paramBlockPosition, IBlockData paramIBlockData, Block paramBlock) { + paramWorld.getTileEntity(paramBlockPosition); + } + + public AxisAlignedBB a(World paramWorld, BlockPosition paramBlockPosition, IBlockData paramIBlockData) { + TileEntityPiston tileEntityPiston = e((IBlockAccess) paramWorld, paramBlockPosition); + if (tileEntityPiston == null) + return null; + float f = tileEntityPiston.a(0.0F); + if (tileEntityPiston.d()) + f = 1.0F - f; + return a(paramWorld, paramBlockPosition, tileEntityPiston.b(), f, tileEntityPiston.e()); + } + + public void updateShape(IBlockAccess paramIBlockAccess, BlockPosition paramBlockPosition) { + TileEntityPiston tileEntityPiston = e(paramIBlockAccess, paramBlockPosition); + if (tileEntityPiston != null) { + IBlockData iBlockData = tileEntityPiston.b(); + Block block = iBlockData.getBlock(); + if (block == this || block.getMaterial() == Material.AIR) + return; + float f = tileEntityPiston.a(0.0F); + if (tileEntityPiston.d()) + f = 1.0F - f; + block.updateShape(paramIBlockAccess, paramBlockPosition); + if (block == Blocks.PISTON || block == Blocks.STICKY_PISTON) + f = 0.0F; + EnumDirection enumDirection = tileEntityPiston.e(); + this.minX = block.B() - (enumDirection.getAdjacentX() * f); + this.minY = block.D() - (enumDirection.getAdjacentY() * f); + this.minZ = block.F() - (enumDirection.getAdjacentZ() * f); + this.maxX = block.C() - (enumDirection.getAdjacentX() * f); + this.maxY = block.E() - (enumDirection.getAdjacentY() * f); + this.maxZ = block.G() - (enumDirection.getAdjacentZ() * f); + } + } + + public AxisAlignedBB a(World paramWorld, BlockPosition paramBlockPosition, IBlockData paramIBlockData, float paramFloat, EnumDirection paramEnumDirection) { + Block block = paramIBlockData.getBlock(); + if (block == this || block.getMaterial() == Material.AIR) + return null; + AxisAlignedBB axisAlignedBB = block.a(paramWorld, paramBlockPosition, paramIBlockData); + if (axisAlignedBB == null) + return null; + double d1 = axisAlignedBB.a; + double d2 = axisAlignedBB.b; + double d3 = axisAlignedBB.c; + double d4 = axisAlignedBB.d; + double d5 = axisAlignedBB.e; + double d6 = axisAlignedBB.f; + if (paramEnumDirection.getAdjacentX() < 0) { + d1 -= (paramEnumDirection.getAdjacentX() * paramFloat); + } else { + d4 -= (paramEnumDirection.getAdjacentX() * paramFloat); + } + if (paramEnumDirection.getAdjacentY() < 0) { + d2 -= (paramEnumDirection.getAdjacentY() * paramFloat); + } else { + d5 -= (paramEnumDirection.getAdjacentY() * paramFloat); + } + if (paramEnumDirection.getAdjacentZ() < 0) { + d3 -= (paramEnumDirection.getAdjacentZ() * paramFloat); + } else { + d6 -= (paramEnumDirection.getAdjacentZ() * paramFloat); + } + return new AxisAlignedBB(d1, d2, d3, d4, d5, d6); + } + + private TileEntityPiston e(IBlockAccess paramIBlockAccess, BlockPosition paramBlockPosition) { + TileEntity tileEntity = paramIBlockAccess.getTileEntity(paramBlockPosition); + if (tileEntity instanceof TileEntityPiston) + return (TileEntityPiston) tileEntity; + return null; + } + + public IBlockData fromLegacyData(int paramInt) { + return getBlockData().set(FACING, BlockPistonExtension.b(paramInt)).set(TYPE, ((paramInt & 0x8) > 0) ? BlockPistonExtension.EnumPistonType.STICKY : BlockPistonExtension.EnumPistonType.DEFAULT); + } + + public int toLegacyData(IBlockData paramIBlockData) { + int i = 0; + i |= paramIBlockData.get(FACING).a(); + if (paramIBlockData.get(TYPE) == BlockPistonExtension.EnumPistonType.STICKY) + i |= 0x8; + return i; + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, FACING, TYPE); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockPlant.java b/azurite-server/src/main/java/net/minecraft/server/BlockPlant.java new file mode 100644 index 0000000..4694f39 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockPlant.java @@ -0,0 +1,99 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.AzuriteConfig; +import org.bukkit.Bukkit; +import org.bukkit.event.block.BlockPhysicsEvent; + +import java.util.Random; +// CraftBukkit end + +public class BlockPlant extends Block { + + protected BlockPlant() { + this(Material.PLANT); + } + + protected BlockPlant(Material material) { + this(material, material.r()); + } + + protected BlockPlant(Material material, MaterialMapColor materialmapcolor) { + super(material, materialmapcolor); + this.a(true); + float f = 0.2F; + + this.a(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, f * 3.0F, 0.5F + f); + this.a(CreativeModeTab.c); + } + + public boolean canPlace(World world, BlockPosition blockposition) { + return super.canPlace(world, blockposition) && this.c(world.getType(blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()).getBlock()); + } + + protected boolean c(Block block) { + return block == Blocks.GRASS || block == Blocks.DIRT || block == Blocks.FARMLAND; + } + + public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) { + super.doPhysics(world, blockposition, iblockdata, block); + this.e(world, blockposition, iblockdata); + } + + public void b(World world, BlockPosition blockposition, IBlockData iblockdata, Random random) { + if (AzuriteConfig.dropFloatingPlants.getValue()) + this.e(world, blockposition, iblockdata); + } + + protected void e(World world, BlockPosition blockposition, IBlockData iblockdata) { + if (!this.f(world, blockposition, iblockdata)) { + // CraftBukkit Start + org.bukkit.block.Block block = world.getWorld().getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()); + BlockPhysicsEvent event = new BlockPhysicsEvent(block, block.getTypeId()); + Bukkit.getPluginManager().callEvent(event); + + if (event.isCancelled()) { + return; + } + // CraftBukkit end + this.b(world, blockposition, iblockdata, 0); + world.setTypeAndData(blockposition, Blocks.AIR.getBlockData(), 3); + } + } + + /* @Override + public void optimizedTick(Chunk chunk, int x, int y, int z, IBlockData iblockdata, Random random) { + // TODO: further remove block position + BlockPosition blockPosition = new BlockPosition(x, y, z); + if (!this.f(chunk.world, blockPosition, iblockdata)) { + // CraftBukkit Start + org.bukkit.block.Block block = chunk.bukkitChunk.getBlock(x, y, z); + BlockPhysicsEvent event = new BlockPhysicsEvent(block, block.getTypeId()); + + Bukkit.getServer().getPluginManager().callEvent(event); + + if (event.isCancelled()) { + return; + } + // CraftBukkit end + dropNaturally(chunk.world, x, y, z, iblockdata, 1.0F, 0); + + chunk.world.setTypeAndData(blockPosition, Blocks.AIR.getBlockData(), 3); + } + } */ + + public boolean f(World world, BlockPosition blockposition, IBlockData iblockdata) { + return this.c(world.getType(blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()).getBlock()); + } + + public AxisAlignedBB a(World world, BlockPosition blockposition, IBlockData iblockdata) { + return null; + } + + public boolean c() { + return false; + } + + public boolean d() { + return false; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockPortal.java b/azurite-server/src/main/java/net/minecraft/server/BlockPortal.java new file mode 100644 index 0000000..6633be2 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockPortal.java @@ -0,0 +1,362 @@ +package net.minecraft.server; + +import com.google.common.cache.LoadingCache; +import org.bukkit.event.entity.EntityPortalEnterEvent; +import org.bukkit.event.world.PortalCreateEvent; + +import java.util.Random; + +public class BlockPortal extends BlockHalfTransparent { + + public static final BlockStateEnum AXIS = BlockStateEnum.of("axis", EnumDirection.EnumAxis.class, EnumDirection.EnumAxis.X, EnumDirection.EnumAxis.Z); + + public BlockPortal() { + super(Material.PORTAL, false); + this.j(this.blockStateList.getBlockData().set(BlockPortal.AXIS, EnumDirection.EnumAxis.X)); + this.a(true); + } + + public void b(World world, BlockPosition blockposition, IBlockData iblockdata, Random random) { + super.b(world, blockposition, iblockdata, random); + + if (world.spigotConfig.enableZombiePigmenPortalSpawns && world.worldProvider.d() && world.getGameRules().getBoolean("doMobSpawning") && random.nextInt(2000) < world.getDifficulty().a()) { // Spigot + int i = blockposition.getY(); + + BlockPosition blockposition1; + + for (blockposition1 = blockposition; !World.a(world, blockposition1) && blockposition1.getY() > 0; blockposition1 = blockposition1.down()) { + } + + if (i > 0 && !world.getType(blockposition1.getX(), blockposition1.getY() + 1, blockposition1.getZ()).getBlock().isOccluding()) { + // CraftBukkit - set spawn reason to NETHER_PORTAL + Entity entity = ItemMonsterEgg.spawnCreature(world, 57, (double) blockposition1.getX() + 0.5D, (double) blockposition1.getY() + 1.1D, (double) blockposition1.getZ() + 0.5D, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.NETHER_PORTAL); + + if (entity != null) { + entity.portalCooldown = entity.aq(); + } + } + } + + } + + public AxisAlignedBB a(World world, BlockPosition blockposition, IBlockData iblockdata) { + return null; + } + + public void updateShape(IBlockAccess iblockaccess, BlockPosition blockposition) { + EnumDirection.EnumAxis enumdirection_enumaxis = iblockaccess.getType(blockposition).get(BlockPortal.AXIS); + float f = 0.125F; + float f1 = 0.125F; + + if (enumdirection_enumaxis == EnumDirection.EnumAxis.X) { + f = 0.5F; + } + + if (enumdirection_enumaxis == EnumDirection.EnumAxis.Z) { + f1 = 0.5F; + } + + this.a(0.5F - f, 0.0F, 0.5F - f1, 0.5F + f, 1.0F, 0.5F + f1); + } + + public static int a(EnumDirection.EnumAxis enumdirection_enumaxis) { + return enumdirection_enumaxis == EnumDirection.EnumAxis.X ? 1 : (enumdirection_enumaxis == EnumDirection.EnumAxis.Z ? 2 : 0); + } + + public boolean d() { + return false; + } + + public boolean e(World world, BlockPosition blockposition) { + BlockPortal.Shape blockportal_shape = new BlockPortal.Shape(world, blockposition, EnumDirection.EnumAxis.X); + + if (blockportal_shape.d() && blockportal_shape.e == 0) { + // CraftBukkit start - return portalcreator + return blockportal_shape.createPortal(); + // return true; + } else { + BlockPortal.Shape blockportal_shape1 = new BlockPortal.Shape(world, blockposition, EnumDirection.EnumAxis.Z); + + if (blockportal_shape1.d() && blockportal_shape1.e == 0) { + return blockportal_shape1.createPortal(); + // return true; + // CraftBukkit end + } else { + return false; + } + } + } + + public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) { + EnumDirection.EnumAxis enumdirection_enumaxis = iblockdata.get(BlockPortal.AXIS); + BlockPortal.Shape blockportal_shape; + + if (enumdirection_enumaxis == EnumDirection.EnumAxis.X) { + blockportal_shape = new BlockPortal.Shape(world, blockposition, EnumDirection.EnumAxis.X); + if (!blockportal_shape.d() || blockportal_shape.e < blockportal_shape.width * blockportal_shape.height) { + world.setTypeUpdate(blockposition, Blocks.AIR.getBlockData()); + } + } else if (enumdirection_enumaxis == EnumDirection.EnumAxis.Z) { + blockportal_shape = new BlockPortal.Shape(world, blockposition, EnumDirection.EnumAxis.Z); + if (!blockportal_shape.d() || blockportal_shape.e < blockportal_shape.width * blockportal_shape.height) { + world.setTypeUpdate(blockposition, Blocks.AIR.getBlockData()); + } + } + + } + + public int a(Random random) { + return 0; + } + + public void a(World world, BlockPosition blockposition, IBlockData iblockdata, Entity entity) { + if (entity.vehicle == null && entity.passenger == null) { + // CraftBukkit start - Entity in portal + EntityPortalEnterEvent event = new EntityPortalEnterEvent(entity.getBukkitEntity(), new org.bukkit.Location(world.getWorld(), blockposition.getX(), blockposition.getY(), blockposition.getZ())); + world.getServer().getPluginManager().callEvent(event); + // CraftBukkit end + entity.d(blockposition); + } + + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockPortal.AXIS, (i & 3) == 2 ? EnumDirection.EnumAxis.Z : EnumDirection.EnumAxis.X); + } + + public int toLegacyData(IBlockData iblockdata) { + return a(iblockdata.get(BlockPortal.AXIS)); + } + + public BlockStateList getStateList() { + return new BlockStateList(this, BlockPortal.AXIS); + } + + public ShapeDetector.ShapeDetectorCollection f(World world, BlockPosition blockposition) { + EnumDirection.EnumAxis enumdirection_enumaxis = EnumDirection.EnumAxis.Z; + BlockPortal.Shape blockportal_shape = new BlockPortal.Shape(world, blockposition, EnumDirection.EnumAxis.X); + LoadingCache loadingcache = ShapeDetector.a(world, true); + + if (!blockportal_shape.d()) { + enumdirection_enumaxis = EnumDirection.EnumAxis.X; + blockportal_shape = new BlockPortal.Shape(world, blockposition, EnumDirection.EnumAxis.Z); + } + + if (!blockportal_shape.d()) { + return new ShapeDetector.ShapeDetectorCollection(blockposition, EnumDirection.NORTH, EnumDirection.UP, loadingcache, 1, 1, 1); + } else { + int[] aint = new int[EnumDirection.EnumAxisDirection.values().length]; + EnumDirection enumdirection = blockportal_shape.c.f(); + BlockPosition blockposition1 = blockportal_shape.position.up(blockportal_shape.a() - 1); + EnumDirection.EnumAxisDirection[] aenumdirection_enumaxisdirection = EnumDirection.EnumAxisDirection.values(); + int i = aenumdirection_enumaxisdirection.length; + + int j; + + for (j = 0; j < i; ++j) { + EnumDirection.EnumAxisDirection enumdirection_enumaxisdirection = aenumdirection_enumaxisdirection[j]; + ShapeDetector.ShapeDetectorCollection shapedetector_shapedetectorcollection = new ShapeDetector.ShapeDetectorCollection(enumdirection.c() == enumdirection_enumaxisdirection ? blockposition1 : blockposition1.shift(blockportal_shape.c, blockportal_shape.b() - 1), EnumDirection.a(enumdirection_enumaxisdirection, enumdirection_enumaxis), EnumDirection.UP, loadingcache, blockportal_shape.b(), blockportal_shape.a(), 1); + + for (int k = 0; k < blockportal_shape.b(); ++k) { + for (int l = 0; l < blockportal_shape.a(); ++l) { + ShapeDetectorBlock shapedetectorblock = shapedetector_shapedetectorcollection.a(k, l, 1); + + if (shapedetectorblock.a() != null && shapedetectorblock.a().getBlock().getMaterial() != Material.AIR) { + ++aint[enumdirection_enumaxisdirection.ordinal()]; + } + } + } + } + + EnumDirection.EnumAxisDirection enumdirection_enumaxisdirection1 = EnumDirection.EnumAxisDirection.POSITIVE; + EnumDirection.EnumAxisDirection[] aenumdirection_enumaxisdirection1 = EnumDirection.EnumAxisDirection.values(); + + j = aenumdirection_enumaxisdirection1.length; + + for (int i1 = 0; i1 < j; ++i1) { + EnumDirection.EnumAxisDirection enumdirection_enumaxisdirection2 = aenumdirection_enumaxisdirection1[i1]; + + if (aint[enumdirection_enumaxisdirection2.ordinal()] < aint[enumdirection_enumaxisdirection1.ordinal()]) { + enumdirection_enumaxisdirection1 = enumdirection_enumaxisdirection2; + } + } + + return new ShapeDetector.ShapeDetectorCollection(enumdirection.c() == enumdirection_enumaxisdirection1 ? blockposition1 : blockposition1.shift(blockportal_shape.c, blockportal_shape.b() - 1), EnumDirection.a(enumdirection_enumaxisdirection1, enumdirection_enumaxis), EnumDirection.UP, loadingcache, blockportal_shape.b(), blockportal_shape.a(), 1); + } + } + + public static class Shape { + + private final World a; + private final EnumDirection.EnumAxis b; + private final EnumDirection c; + private final EnumDirection d; + private int e = 0; + private BlockPosition position; + private int height; + private int width; + java.util.Collection blocks = new java.util.HashSet<>(); // CraftBukkit - add field + + public Shape(World world, BlockPosition blockposition, EnumDirection.EnumAxis enumdirection_enumaxis) { + this.a = world; + this.b = enumdirection_enumaxis; + if (enumdirection_enumaxis == EnumDirection.EnumAxis.X) { + this.d = EnumDirection.EAST; + this.c = EnumDirection.WEST; + } else { + this.d = EnumDirection.NORTH; + this.c = EnumDirection.SOUTH; + } + + for (BlockPosition blockposition1 = blockposition; blockposition.getY() > blockposition1.getY() - 21 && blockposition.getY() > 0 && this.a(world.getType(blockposition.down()).getBlock()); blockposition = blockposition.down()) { + } + + int i = this.a(blockposition, this.d) - 1; + + if (i >= 0) { + this.position = blockposition.shift(this.d, i); + this.width = this.a(this.position, this.c); + if (this.width < 2 || this.width > 21) { + this.position = null; + this.width = 0; + } + } + + if (this.position != null) { + this.height = this.c(); + } + + } + + protected int a(BlockPosition blockposition, EnumDirection enumdirection) { + int i; + + for (i = 0; i < 22; ++i) { + BlockPosition blockposition1 = blockposition.shift(enumdirection, i); + + if (!this.a(this.a.getType(blockposition1).getBlock()) || this.a.getType(blockposition1.getX(), blockposition1.getY() - 1, blockposition1.getZ()).getBlock() != Blocks.OBSIDIAN) { + break; + } + } + + Block block = this.a.getType(blockposition.shift(enumdirection, i)).getBlock(); + + return block == Blocks.OBSIDIAN ? i : 0; + } + + public int a() { + return this.height; + } + + public int b() { + return this.width; + } + + protected int c() { + // CraftBukkit start + this.blocks.clear(); + org.bukkit.World bworld = this.a.getWorld(); + // CraftBukkit end + int i; + + label56: + for (this.height = 0; this.height < 21; ++this.height) { + for (i = 0; i < this.width; ++i) { + BlockPosition blockposition = this.position.shift(this.c, i).up(this.height); + Block block = this.a.getType(blockposition).getBlock(); + + if (!this.a(block)) { + break label56; + } + + if (block == Blocks.PORTAL) { + ++this.e; + } + + if (i == 0) { + block = this.a.getType(blockposition.shift(this.d)).getBlock(); + if (block != Blocks.OBSIDIAN) { + break label56; + // CraftBukkit start - add the block to our list + } else { + BlockPosition pos = blockposition.shift(this.d); + blocks.add(bworld.getBlockAt(pos.getX(), pos.getY(), pos.getZ())); + // CraftBukkit end + } + } else if (i == this.width - 1) { + block = this.a.getType(blockposition.shift(this.c)).getBlock(); + if (block != Blocks.OBSIDIAN) { + break label56; + // CraftBukkit start - add the block to our list + } else { + BlockPosition pos = blockposition.shift(this.c); + blocks.add(bworld.getBlockAt(pos.getX(), pos.getY(), pos.getZ())); + // CraftBukkit end + } + } + } + } + + for (i = 0; i < this.width; ++i) { + if (this.a.getType(this.position.shift(this.c, i).up(this.height)).getBlock() != Blocks.OBSIDIAN) { + this.height = 0; + break; + // CraftBukkit start - add the block to our list + } else { + BlockPosition pos = this.position.shift(this.c, i).up(this.height); + blocks.add(bworld.getBlockAt(pos.getX(), pos.getY(), pos.getZ())); + // CraftBukkit end + } + } + + if (this.height <= 21 && this.height >= 3) { + return this.height; + } else { + this.position = null; + this.width = 0; + this.height = 0; + return 0; + } + } + + protected boolean a(Block block) { + return block.material == Material.AIR || block == Blocks.FIRE || block == Blocks.PORTAL; + } + + public boolean d() { + return this.position != null && this.width >= 2 && this.width <= 21 && this.height >= 3 && this.height <= 21; + } + + // CraftBukkit start - return boolean + public boolean createPortal() { + org.bukkit.World bworld = this.a.getWorld(); + + // Copy below for loop + for (int i = 0; i < this.width; ++i) { + BlockPosition blockposition = this.position.shift(this.c, i); + + for (int j = 0; j < this.height; ++j) { + BlockPosition pos = blockposition.up(j); + blocks.add(bworld.getBlockAt(pos.getX(), pos.getY(), pos.getZ())); + } + } + + PortalCreateEvent event = new PortalCreateEvent(blocks, bworld, PortalCreateEvent.CreateReason.FIRE); + this.a.getServer().getPluginManager().callEvent(event); + + if (event.isCancelled()) { + return false; + } + // CraftBukkit end + for (int i = 0; i < this.width; ++i) { + BlockPosition blockposition = this.position.shift(this.c, i); + + for (int j = 0; j < this.height; ++j) { + this.a.setTypeAndData(blockposition.up(j), Blocks.PORTAL.getBlockData().set(BlockPortal.AXIS, this.b), 2); + } + } + + return true; // CraftBukkit + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockPosition.java b/azurite-server/src/main/java/net/minecraft/server/BlockPosition.java new file mode 100644 index 0000000..c18aef6 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockPosition.java @@ -0,0 +1,288 @@ +package net.minecraft.server; + +import com.google.common.collect.AbstractIterator; +import org.jetbrains.annotations.NotNull; + +import java.util.Iterator; + +public class BlockPosition extends BaseBlockPosition { + public static final BlockPosition ZERO = new BlockPosition(0, 0, 0); + + private static final int c = 1 + MathHelper.c(MathHelper.b(30000000)); + private static final int d = c; + private static final int e = 64 - c - d; + private static final int f = d; + private static final int g = f + e; + + private static final long h = (1L << c) - 1L; + private static final long i = (1L << e) - 1L; + private static final long j = (1L << d) - 1L; + + public BlockPosition(int i, int j, int k) { + super(i, j, k); + } + + public BlockPosition(double d0, double d1, double d2) { + super(d0, d1, d2); + } + + public BlockPosition(Entity entity) { + this(entity.locX, entity.locY, entity.locZ); + } + + public BlockPosition(Vec3D vec3d) { + this(vec3d.a, vec3d.b, vec3d.c); + } + + public BlockPosition(BaseBlockPosition baseblockposition) { + this(baseblockposition.getX(), baseblockposition.getY(), baseblockposition.getZ()); + } + + public BlockPosition a(double d0, double d1, double d2) { + return (d0 == 0.0D && d1 == 0.0D && d2 == 0.0D) ? this : new BlockPosition(getX() + d0, getY() + d1, getZ() + d2); + } + + public BlockPosition a(int i, int j, int k) { + return (i == 0 && j == 0 && k == 0) ? this : new BlockPosition(getX() + i, getY() + j, getZ() + k); + } + + public BlockPosition a(BaseBlockPosition baseblockposition) { + return (baseblockposition.getX() == 0 && baseblockposition.getY() == 0 && baseblockposition.getZ() == 0) ? this : new BlockPosition(getX() + baseblockposition.getX(), getY() + baseblockposition.getY(), getZ() + baseblockposition.getZ()); + } + + public BlockPosition b(BaseBlockPosition baseblockposition) { + return (baseblockposition.getX() == 0 && baseblockposition.getY() == 0 && baseblockposition.getZ() == 0) ? this : new BlockPosition(getX() - baseblockposition.getX(), getY() - baseblockposition.getY(), getZ() - baseblockposition.getZ()); + } + + public BlockPosition up() { + return new BlockPosition(this.getX(), this.getY() + 1, this.getZ()); // Paper - Optimize BlockPosition + } + + public BlockPosition up(int i) { + return i == 0 ? this : new BlockPosition(this.getX(), this.getY() + i, this.getZ()); // Paper - Optimize + // BlockPosition + } + + public BlockPosition down() { + return new BlockPosition(this.getX(), this.getY() - 1, this.getZ()); // Paper - Optimize BlockPosition + } + + public BlockPosition down(int i) { + return i == 0 ? this : new BlockPosition(this.getX(), this.getY() - i, this.getZ()); // Paper - Optimize + // BlockPosition + } + + public BlockPosition north() { + return new BlockPosition(this.getX(), this.getY(), this.getZ() - 1); // Paper - Optimize BlockPosition + } + + public BlockPosition north(int i) { + return i == 0 ? this : new BlockPosition(this.getX(), this.getY(), this.getZ() - i); // Paper - Optimize + // BlockPosition + } + + public BlockPosition south() { + return new BlockPosition(this.getX(), this.getY(), this.getZ() + 1); // Paper - Optimize BlockPosition + } + + public BlockPosition south(int i) { + return i == 0 ? this : new BlockPosition(this.getX(), this.getY(), this.getZ() + i); // Paper - Optimize + // BlockPosition + } + + public BlockPosition west() { + return new BlockPosition(this.getX() - 1, this.getY(), this.getZ()); // Paper - Optimize BlockPosition + } + + public BlockPosition west(int i) { + return i == 0 ? this : new BlockPosition(this.getX() - i, this.getY(), this.getZ()); // Paper - Optimize + // BlockPosition + } + + public BlockPosition east() { + return new BlockPosition(this.getX() + 1, this.getY(), this.getZ()); // Paper - Optimize BlockPosition + } + + public BlockPosition east(int i) { + return i == 0 ? this : new BlockPosition(this.getX() + i, this.getY(), this.getZ()); // Paper - Optimize + // BlockPosition + } + + public BlockPosition shift(EnumDirection enumdirection) { + // Paper Start - Optimize BlockPosition + switch (enumdirection) { + case UP: + return new BlockPosition(this.getX(), this.getY() + 1, this.getZ()); + case DOWN: + return new BlockPosition(this.getX(), this.getY() - 1, this.getZ()); + case NORTH: + return new BlockPosition(this.getX(), this.getY(), this.getZ() - 1); + case SOUTH: + return new BlockPosition(this.getX(), this.getY(), this.getZ() + 1); + case WEST: + return new BlockPosition(this.getX() - 1, this.getY(), this.getZ()); + case EAST: + return new BlockPosition(this.getX() + 1, this.getY(), this.getZ()); + default: + return new BlockPosition(this.getX() + enumdirection.getAdjacentX(), + this.getY() + enumdirection.getAdjacentY(), this.getZ() + enumdirection.getAdjacentZ()); + } + // Paper End + } + + public BlockPosition shift(EnumDirection enumdirection, int i) { + if (i == 0) + return this; + switch (enumdirection) { + case UP: + return new BlockPosition(getX(), getY() + i, getZ()); + case DOWN: + return new BlockPosition(getX(), getY() - i, getZ()); + case NORTH: + return new BlockPosition(getX(), getY(), getZ() - i); + case SOUTH: + return new BlockPosition(getX(), getY(), getZ() + i); + case WEST: + return new BlockPosition(getX() - i, getY(), getZ()); + case EAST: + return new BlockPosition(getX() + i, getY(), getZ()); + default: + return new BlockPosition(getX() + enumdirection.getAdjacentX() * i, getY() + enumdirection.getAdjacentY() * i, getZ() + enumdirection.getAdjacentZ() * i); + } + } + + public BlockPosition c(BaseBlockPosition baseblockposition) { + return new BlockPosition(getY() * baseblockposition.getZ() - getZ() * baseblockposition.getY(), getZ() * baseblockposition.getX() - getX() * baseblockposition.getZ(), getX() * baseblockposition.getY() - getY() * baseblockposition.getX()); + } + + public long asLong() { + return (getX() & h) << g | (getY() & i) << f | (getZ() & j); + } + + public static long asLong(int x, int y, int z) { + return (x & h) << g | (y & i) << f | (z & j); + } + + public static BlockPosition fromLong(long i) { + return new BlockPosition((int) (i << 64 - g - c >> 64 - c), (int) (i << 64 - f - e >> 64 - e), (int) (i << 64 - d >> 64 - d)); + } + + public static int getXFromLong(long i) { + return (int) (i << 64 - g - c >> 64 - c); + } + + public static int getYFromLong(long i) { + return (int) (i << 64 - f - e >> 64 - e); + } + + public static int getZFromLong(long i) { + return (int) (i << 64 - d >> 64 - d); + } + + public static Iterable a(final BlockPosition blockposition, final BlockPosition blockposition1) { + return new Iterable() { + public @NotNull Iterator iterator() { + return new AbstractIterator() { + private BlockPosition b = null; + + protected BlockPosition computeNext() { + if (this.b == null) { + this.b = blockposition; + return this.b; + } + if (this.b.equals(blockposition1)) + return endOfData(); + int i = this.b.getX(); + int j = this.b.getY(); + int k = this.b.getZ(); + if (i < blockposition1.getX()) { + i++; + } else if (j < blockposition1.getY()) { + i = blockposition.getX(); + j++; + } else if (k < blockposition1.getZ()) { + i = blockposition.getX(); + j = blockposition.getY(); + k++; + } + this.b = new BlockPosition(i, j, k); + return this.b; + } + }; + } + }; + } + + public static Iterable b(final BlockPosition blockposition, final BlockPosition blockposition1) { + return new Iterable() { + public @NotNull Iterator iterator() { + return new AbstractIterator() { + private MutableBlockPosition b = null; + + protected MutableBlockPosition computeNext() { + if (this.b == null) { + this.b = new MutableBlockPosition(blockposition.getX(), blockposition.getY(), blockposition.getZ()); + return this.b; + } + if (this.b.equals(blockposition1)) + return endOfData(); + int i = this.b.getX(); + int j = this.b.getY(); + int k = this.b.getZ(); + if (i < blockposition1.getX()) { + i++; + } else if (j < blockposition1.getY()) { + i = blockposition.getX(); + j++; + } else if (k < blockposition1.getZ()) { + i = blockposition.getX(); + j = blockposition.getY(); + k++; + } + this.b.setX(i); + this.b.setY(j); + this.b.setZ(k); + return this.b; + } + }; + } + }; + } + + public BaseBlockPosition d(BaseBlockPosition baseblockposition) { + return c(baseblockposition); + } + + public static final class MutableBlockPosition extends BlockPosition { + + public MutableBlockPosition() { + this(0, 0, 0); + } + + public MutableBlockPosition(int i, int j, int k) { + super(0, 0, 0); + setX(i); + setY(j); + setZ(k); + } + + public void setY(int y) { + ((BaseBlockPosition) this).c = y; + } + + public void setZ(int z) { + ((BaseBlockPosition) this).d = z; + } + + public MutableBlockPosition setValues(int x, int y, int z) { + return c(x, y, z); + } + + public MutableBlockPosition c(int i, int j, int k) { + setX(i); + setY(j); + setZ(k); + return this; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockPotatoes.java b/azurite-server/src/main/java/net/minecraft/server/BlockPotatoes.java new file mode 100644 index 0000000..9d23627 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockPotatoes.java @@ -0,0 +1,22 @@ +package net.minecraft.server; + +public class BlockPotatoes extends BlockCrops { + + public BlockPotatoes() { + } + + protected Item l() { + return Items.POTATO; + } + + protected Item n() { + return Items.POTATO; + } + + public void dropNaturally(World world, BlockPosition blockposition, IBlockData iblockdata, float f, int i) { + super.dropNaturally(world, blockposition, iblockdata, f, i); + if (iblockdata.get(BlockPotatoes.AGE) >= 7 && world.random.nextInt(50) == 0) { + a(world, blockposition, new ItemStack(Items.POISONOUS_POTATO)); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockPowered.java b/azurite-server/src/main/java/net/minecraft/server/BlockPowered.java new file mode 100644 index 0000000..798ae26 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockPowered.java @@ -0,0 +1,16 @@ +package net.minecraft.server; + +public class BlockPowered extends Block { + + public BlockPowered(Material material, MaterialMapColor materialmapcolor) { + super(material, materialmapcolor); + } + + public boolean isPowerSource() { + return true; + } + + public int a(IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata, EnumDirection enumdirection) { + return 15; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockPoweredRail.java b/azurite-server/src/main/java/net/minecraft/server/BlockPoweredRail.java new file mode 100644 index 0000000..4ff3746 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockPoweredRail.java @@ -0,0 +1,196 @@ +package net.minecraft.server; + +import com.google.common.base.Predicate; +import org.bukkit.craftbukkit.event.CraftEventFactory; + +public class BlockPoweredRail extends BlockMinecartTrackAbstract { + + public static final BlockStateEnum SHAPE = BlockStateEnum.a("shape", BlockMinecartTrackAbstract.EnumTrackPosition.class, new Predicate() { + public boolean a(BlockMinecartTrackAbstract.EnumTrackPosition blockminecarttrackabstract_enumtrackposition) { + return blockminecarttrackabstract_enumtrackposition != BlockMinecartTrackAbstract.EnumTrackPosition.NORTH_EAST && blockminecarttrackabstract_enumtrackposition != BlockMinecartTrackAbstract.EnumTrackPosition.NORTH_WEST && blockminecarttrackabstract_enumtrackposition != BlockMinecartTrackAbstract.EnumTrackPosition.SOUTH_EAST && blockminecarttrackabstract_enumtrackposition != BlockMinecartTrackAbstract.EnumTrackPosition.SOUTH_WEST; + } + + public boolean apply(Object object) { + return this.a((BlockMinecartTrackAbstract.EnumTrackPosition) object); + } + }); + public static final BlockStateBoolean POWERED = BlockStateBoolean.of("powered"); + + protected BlockPoweredRail() { + super(true); + this.j(this.blockStateList.getBlockData().set(BlockPoweredRail.SHAPE, BlockMinecartTrackAbstract.EnumTrackPosition.NORTH_SOUTH).set(BlockPoweredRail.POWERED, Boolean.FALSE)); + } + + protected boolean a(World world, BlockPosition blockposition, IBlockData iblockdata, boolean flag, int i) { + if (i >= 8) { + return false; + } else { + int j = blockposition.getX(); + int k = blockposition.getY(); + int l = blockposition.getZ(); + boolean flag1 = true; + BlockMinecartTrackAbstract.EnumTrackPosition blockminecarttrackabstract_enumtrackposition = iblockdata.get(BlockPoweredRail.SHAPE); + + switch (BlockPoweredRail.SyntheticClass_1.a[blockminecarttrackabstract_enumtrackposition.ordinal()]) { + case 1: + if (flag) { + ++l; + } else { + --l; + } + break; + + case 2: + if (flag) { + --j; + } else { + ++j; + } + break; + + case 3: + if (flag) { + --j; + } else { + ++j; + ++k; + flag1 = false; + } + + blockminecarttrackabstract_enumtrackposition = BlockMinecartTrackAbstract.EnumTrackPosition.EAST_WEST; + break; + + case 4: + if (flag) { + --j; + ++k; + flag1 = false; + } else { + ++j; + } + + blockminecarttrackabstract_enumtrackposition = BlockMinecartTrackAbstract.EnumTrackPosition.EAST_WEST; + break; + + case 5: + if (flag) { + ++l; + } else { + --l; + ++k; + flag1 = false; + } + + blockminecarttrackabstract_enumtrackposition = BlockMinecartTrackAbstract.EnumTrackPosition.NORTH_SOUTH; + break; + + case 6: + if (flag) { + ++l; + ++k; + flag1 = false; + } else { + --l; + } + + blockminecarttrackabstract_enumtrackposition = BlockMinecartTrackAbstract.EnumTrackPosition.NORTH_SOUTH; + } + + return this.a(world, new BlockPosition(j, k, l), flag, i, blockminecarttrackabstract_enumtrackposition) || flag1 && this.a(world, new BlockPosition(j, k - 1, l), flag, i, blockminecarttrackabstract_enumtrackposition); + } + } + + protected boolean a(World world, BlockPosition blockposition, boolean flag, int i, BlockMinecartTrackAbstract.EnumTrackPosition blockminecarttrackabstract_enumtrackposition) { + IBlockData iblockdata = world.getType(blockposition); + + if (iblockdata.getBlock() != this) { + return false; + } else { + BlockMinecartTrackAbstract.EnumTrackPosition blockminecarttrackabstract_enumtrackposition1 = iblockdata.get(BlockPoweredRail.SHAPE); + + return (blockminecarttrackabstract_enumtrackposition != EnumTrackPosition.EAST_WEST || (blockminecarttrackabstract_enumtrackposition1 != EnumTrackPosition.NORTH_SOUTH && blockminecarttrackabstract_enumtrackposition1 != EnumTrackPosition.ASCENDING_NORTH && blockminecarttrackabstract_enumtrackposition1 != EnumTrackPosition.ASCENDING_SOUTH)) && ((blockminecarttrackabstract_enumtrackposition != EnumTrackPosition.NORTH_SOUTH || (blockminecarttrackabstract_enumtrackposition1 != EnumTrackPosition.EAST_WEST && blockminecarttrackabstract_enumtrackposition1 != EnumTrackPosition.ASCENDING_EAST && blockminecarttrackabstract_enumtrackposition1 != EnumTrackPosition.ASCENDING_WEST)) && (iblockdata.get(BlockPoweredRail.POWERED) && (world.isBlockIndirectlyPowered(blockposition) || this.a(world, blockposition, iblockdata, flag, i + 1)))); + } + } + + protected void b(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) { + boolean flag = iblockdata.get(BlockPoweredRail.POWERED); + boolean flag1 = world.isBlockIndirectlyPowered(blockposition) || this.a(world, blockposition, iblockdata, true, 0) || this.a(world, blockposition, iblockdata, false, 0); + + if (flag1 != flag) { + // CraftBukkit start + int power = iblockdata.get(POWERED) ? 15 : 0; + int newPower = CraftEventFactory.callRedstoneChange(world, blockposition.getX(), blockposition.getY(), blockposition.getZ(), power, 15 - power).getNewCurrent(); + if (newPower == power) { + return; + } + // CraftBukkit end + world.setTypeAndData(blockposition, iblockdata.set(BlockPoweredRail.POWERED, flag1), 3); + world.applyPhysics(blockposition.getX(), blockposition.getY() - 1, blockposition.getZ(), this); + if (iblockdata.get(BlockPoweredRail.SHAPE).c()) { + world.applyPhysics(blockposition.getX(), blockposition.getY() + 1, blockposition.getZ(), this); + } + } + + } + + public IBlockState n() { + return BlockPoweredRail.SHAPE; + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockPoweredRail.SHAPE, BlockMinecartTrackAbstract.EnumTrackPosition.a(i & 7)).set(BlockPoweredRail.POWERED, (i & 8) > 0); + } + + public int toLegacyData(IBlockData iblockdata) { + byte b0 = 0; + int i = b0 | iblockdata.get(BlockPoweredRail.SHAPE).a(); + + if (iblockdata.get(BlockPoweredRail.POWERED)) { + i |= 8; + } + + return i; + } + + public BlockStateList getStateList() { + return new BlockStateList(this, BlockPoweredRail.SHAPE, BlockPoweredRail.POWERED); + } + + static class SyntheticClass_1 { + + static final int[] a = new int[BlockMinecartTrackAbstract.EnumTrackPosition.values().length]; + + static { + try { + BlockPoweredRail.SyntheticClass_1.a[BlockMinecartTrackAbstract.EnumTrackPosition.NORTH_SOUTH.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockPoweredRail.SyntheticClass_1.a[BlockMinecartTrackAbstract.EnumTrackPosition.EAST_WEST.ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockPoweredRail.SyntheticClass_1.a[BlockMinecartTrackAbstract.EnumTrackPosition.ASCENDING_EAST.ordinal()] = 3; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockPoweredRail.SyntheticClass_1.a[BlockMinecartTrackAbstract.EnumTrackPosition.ASCENDING_WEST.ordinal()] = 4; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockPoweredRail.SyntheticClass_1.a[BlockMinecartTrackAbstract.EnumTrackPosition.ASCENDING_NORTH.ordinal()] = 5; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockPoweredRail.SyntheticClass_1.a[BlockMinecartTrackAbstract.EnumTrackPosition.ASCENDING_SOUTH.ordinal()] = 6; + } catch (NoSuchFieldError ignored) { + } + + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockPredicate.java b/azurite-server/src/main/java/net/minecraft/server/BlockPredicate.java new file mode 100644 index 0000000..28af027 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockPredicate.java @@ -0,0 +1,24 @@ +package net.minecraft.server; + +import com.google.common.base.Predicate; + +public class BlockPredicate implements Predicate { + + private final Block a; + + private BlockPredicate(Block block) { + this.a = block; + } + + public static BlockPredicate a(Block block) { + return new BlockPredicate(block); + } + + public boolean a(IBlockData iblockdata) { + return iblockdata != null && iblockdata.getBlock() == this.a; + } + + public boolean apply(IBlockData object) { + return this.a(object); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockPressurePlateAbstract.java b/azurite-server/src/main/java/net/minecraft/server/BlockPressurePlateAbstract.java new file mode 100644 index 0000000..1a60a30 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockPressurePlateAbstract.java @@ -0,0 +1,170 @@ +package net.minecraft.server; + +import org.bukkit.event.block.BlockRedstoneEvent; + +import java.util.Random; + +public abstract class BlockPressurePlateAbstract extends Block { + + protected BlockPressurePlateAbstract(Material material) { + this(material, material.r()); + } + + protected BlockPressurePlateAbstract(Material material, MaterialMapColor materialmapcolor) { + super(material, materialmapcolor); + this.a(CreativeModeTab.d); + this.a(true); + } + + public void updateShape(IBlockAccess iblockaccess, BlockPosition blockposition) { + this.d(iblockaccess.getType(blockposition)); + } + + protected void d(IBlockData iblockdata) { + if (e(iblockdata) > 0) { + this.a(0.0625F, 0.0F, 0.0625F, 0.9375F, 0.03125F, 0.9375F); + } else { + this.a(0.0625F, 0.0F, 0.0625F, 0.9375F, 0.0625F, 0.9375F); + } + + } + + public int a(World world) { + return 20; + } + + public AxisAlignedBB a(World world, BlockPosition blockposition, IBlockData iblockdata) { + return null; + } + + public boolean c() { + return false; + } + + public boolean d() { + return false; + } + + public boolean b(IBlockAccess iblockaccess, BlockPosition blockposition) { + return true; + } + + public boolean g() { + return true; + } + + public boolean canPlace(World world, BlockPosition blockposition) { + return this.m(world, blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()); + } + + public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) { + if (!this.m(world, blockposition.getX(), blockposition.getY() - 1, blockposition.getZ())) { + this.b(world, blockposition, iblockdata, 0); + world.setAir(blockposition); + } + + } + + private boolean m(World world, int x, int y, int z) { + IBlockData data = world.getType(x, y, z); + return World.a(data) || data.getBlock() instanceof BlockFence; + } + + public void b(World world, BlockPosition blockposition, IBlockData iblockdata, Random random) { + int i = this.e(iblockdata); + + if (i > 0) { + this.a(world, blockposition, iblockdata, i); + } + + } + + public void a(World world, BlockPosition blockposition, IBlockData iblockdata, Entity entity) { + int i = this.e(iblockdata); + + if (i == 0) { + this.a(world, blockposition, iblockdata, i); + } + + } + + protected void a(World world, BlockPosition blockposition, IBlockData iblockdata, int i) { + int j = this.f(world, blockposition); + boolean flag = i > 0; + boolean flag1 = j > 0; + + // CraftBukkit start - Interact Pressure Plate + org.bukkit.World bworld = world.getWorld(); + org.bukkit.plugin.PluginManager manager = world.getServer().getPluginManager(); + + if (flag != flag1) { + BlockRedstoneEvent eventRedstone = new BlockRedstoneEvent(bworld.getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()), i, j); + manager.callEvent(eventRedstone); + + flag1 = eventRedstone.getNewCurrent() > 0; + j = eventRedstone.getNewCurrent(); + } + // CraftBukkit end + + if (i != j) { + iblockdata = this.a(iblockdata, j); + world.setTypeAndData(blockposition, iblockdata, 2); + this.e(world, blockposition); + world.b(blockposition, blockposition); + } + + if (!flag1 && flag) { + world.makeSound((double) blockposition.getX() + 0.5D, (double) blockposition.getY() + 0.1D, (double) blockposition.getZ() + 0.5D, "random.click", 0.3F, 0.5F); + } else if (flag1 && !flag) { + world.makeSound((double) blockposition.getX() + 0.5D, (double) blockposition.getY() + 0.1D, (double) blockposition.getZ() + 0.5D, "random.click", 0.3F, 0.6F); + } + + if (flag1) { + world.a(blockposition, this, this.a(world)); + } + + } + + protected AxisAlignedBB getBoundingBox(BlockPosition blockposition) { + return new AxisAlignedBB(((float) blockposition.getX() + 0.125F), blockposition.getY(), ((float) blockposition.getZ() + 0.125F), ((float) (blockposition.getX() + 1) - 0.125F), (double) blockposition.getY() + 0.25D, ((float) (blockposition.getZ() + 1) - 0.125F)); + } + + public void remove(World world, BlockPosition blockposition, IBlockData iblockdata) { + if (this.e(iblockdata) > 0) { + this.e(world, blockposition); + } + + super.remove(world, blockposition, iblockdata); + } + + protected void e(World world, BlockPosition blockposition) { + world.applyPhysics(blockposition, this); + world.applyPhysics(blockposition.down(), this); + } + + public int a(IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata, EnumDirection enumdirection) { + return this.e(iblockdata); + } + + public int b(IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata, EnumDirection enumdirection) { + return enumdirection == EnumDirection.UP ? this.e(iblockdata) : 0; + } + + public boolean isPowerSource() { + return true; + } + + public void j() { + this.a(0.0F, 0.375F, 0.0F, 1.0F, 0.625F, 1.0F); + } + + public int k() { + return 1; + } + + protected abstract int f(World world, BlockPosition blockposition); + + protected abstract int e(IBlockData iblockdata); + + protected abstract IBlockData a(IBlockData iblockdata, int i); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockPressurePlateBinary.java b/azurite-server/src/main/java/net/minecraft/server/BlockPressurePlateBinary.java new file mode 100644 index 0000000..df14d2d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockPressurePlateBinary.java @@ -0,0 +1,112 @@ +package net.minecraft.server; + +import org.bukkit.event.entity.EntityInteractEvent; + +import java.util.List; + +public class BlockPressurePlateBinary extends BlockPressurePlateAbstract { + + public static final BlockStateBoolean POWERED = BlockStateBoolean.of("powered"); + private final BlockPressurePlateBinary.EnumMobType b; + + protected BlockPressurePlateBinary(Material material, BlockPressurePlateBinary.EnumMobType blockpressureplatebinary_enummobtype) { + super(material); + this.j(this.blockStateList.getBlockData().set(BlockPressurePlateBinary.POWERED, Boolean.FALSE)); + this.b = blockpressureplatebinary_enummobtype; + } + + protected int e(IBlockData iblockdata) { + return iblockdata.get(BlockPressurePlateBinary.POWERED) ? 15 : 0; + } + + protected IBlockData a(IBlockData iblockdata, int i) { + return iblockdata.set(BlockPressurePlateBinary.POWERED, i > 0); + } + + protected int f(World world, BlockPosition blockposition) { + AxisAlignedBB axisalignedbb = this.getBoundingBox(blockposition); + List list; + + switch (BlockPressurePlateBinary.SyntheticClass_1.a[this.b.ordinal()]) { + case 1: + list = world.getEntities(null, axisalignedbb); + break; + + case 2: + list = world.a(EntityLiving.class, axisalignedbb); + break; + + default: + return 0; + } + + if (!list.isEmpty()) { + + for (Entity entity : list) { + + // CraftBukkit start - Call interact event when turning on a pressure plate + if (this.e(world.getType(blockposition)) == 0) { + org.bukkit.World bworld = world.getWorld(); + org.bukkit.plugin.PluginManager manager = world.getServer().getPluginManager(); + org.bukkit.event.Cancellable cancellable; + + if (entity instanceof EntityHuman) { + cancellable = org.bukkit.craftbukkit.event.CraftEventFactory.callPlayerInteractEvent((EntityHuman) entity, org.bukkit.event.block.Action.PHYSICAL, blockposition, null, null); + } else { + cancellable = new EntityInteractEvent(entity.getBukkitEntity(), bworld.getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ())); + manager.callEvent((EntityInteractEvent) cancellable); + } + + // We only want to block turning the plate on if all events are cancelled + if (cancellable.isCancelled()) { + continue; + } + } + // CraftBukkit end + + if (!entity.aI()) { + return 15; + } + } + } + + return 0; + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockPressurePlateBinary.POWERED, i == 1); + } + + public int toLegacyData(IBlockData iblockdata) { + return iblockdata.get(BlockPressurePlateBinary.POWERED) ? 1 : 0; + } + + public BlockStateList getStateList() { + return new BlockStateList(this, BlockPressurePlateBinary.POWERED); + } + + static class SyntheticClass_1 { + + static final int[] a = new int[BlockPressurePlateBinary.EnumMobType.values().length]; + + static { + try { + BlockPressurePlateBinary.SyntheticClass_1.a[BlockPressurePlateBinary.EnumMobType.EVERYTHING.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockPressurePlateBinary.SyntheticClass_1.a[BlockPressurePlateBinary.EnumMobType.MOBS.ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + } + + } + } + + public enum EnumMobType { + + EVERYTHING, MOBS; + + EnumMobType() {} + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockPressurePlateWeighted.java b/azurite-server/src/main/java/net/minecraft/server/BlockPressurePlateWeighted.java new file mode 100644 index 0000000..9199b4b --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockPressurePlateWeighted.java @@ -0,0 +1,76 @@ +package net.minecraft.server; + +import org.bukkit.event.entity.EntityInteractEvent; + +public class BlockPressurePlateWeighted extends BlockPressurePlateAbstract { + + public static final BlockStateInteger POWER = BlockStateInteger.of("power", 0, 15); + private final int weight; + + protected BlockPressurePlateWeighted(Material material, int i) { + this(material, i, material.r()); + } + + protected BlockPressurePlateWeighted(Material material, int i, MaterialMapColor materialmapcolor) { + super(material, materialmapcolor); + this.j(this.blockStateList.getBlockData().set(BlockPressurePlateWeighted.POWER, 0)); + this.weight = i; + } + + protected int f(World world, BlockPosition blockposition) { + // CraftBukkit start + //int i = Math.min(world.a(Entity.class, this.a(blockposition)).size(), this.b); + int i = 0; + + for (Entity entity : world.a(Entity.class, this.getBoundingBox(blockposition))) { + org.bukkit.event.Cancellable cancellable; + + if (entity instanceof EntityHuman) { + cancellable = org.bukkit.craftbukkit.event.CraftEventFactory.callPlayerInteractEvent((EntityHuman) entity, org.bukkit.event.block.Action.PHYSICAL, blockposition, null, null); + } else { + cancellable = new EntityInteractEvent(entity.getBukkitEntity(), world.getWorld().getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ())); + world.getServer().getPluginManager().callEvent((EntityInteractEvent) cancellable); + } + + // We only want to block turning the plate on if all events are cancelled + if (!cancellable.isCancelled()) { + i++; + } + } + + i = Math.min(i, this.weight); + // CraftBukkit end + + if (i > 0) { + float f = (float) i / (float) this.weight; + + return MathHelper.f(f * 15.0F); + } else { + return 0; + } + } + + protected int e(IBlockData iblockdata) { + return iblockdata.get(BlockPressurePlateWeighted.POWER); + } + + protected IBlockData a(IBlockData iblockdata, int i) { + return iblockdata.set(BlockPressurePlateWeighted.POWER, i); + } + + public int a(World world) { + return 10; + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockPressurePlateWeighted.POWER, i); + } + + public int toLegacyData(IBlockData iblockdata) { + return iblockdata.get(BlockPressurePlateWeighted.POWER); + } + + public BlockStateList getStateList() { + return new BlockStateList(this, BlockPressurePlateWeighted.POWER); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockPrismarine.java b/azurite-server/src/main/java/net/minecraft/server/BlockPrismarine.java new file mode 100644 index 0000000..e087ac5 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockPrismarine.java @@ -0,0 +1,86 @@ +package net.minecraft.server; + +public class BlockPrismarine extends Block { + + public static final BlockStateEnum VARIANT = BlockStateEnum.of("variant", BlockPrismarine.EnumPrismarineVariant.class); + public static final int b = BlockPrismarine.EnumPrismarineVariant.ROUGH.a(); + public static final int N = BlockPrismarine.EnumPrismarineVariant.BRICKS.a(); + public static final int O = BlockPrismarine.EnumPrismarineVariant.DARK.a(); + + public BlockPrismarine() { + super(Material.STONE); + this.j(this.blockStateList.getBlockData().set(BlockPrismarine.VARIANT, BlockPrismarine.EnumPrismarineVariant.ROUGH)); + this.a(CreativeModeTab.b); + } + + public String getName() { + return LocaleI18n.get(this.a() + "." + BlockPrismarine.EnumPrismarineVariant.ROUGH.c() + ".name"); + } + + public MaterialMapColor g(IBlockData iblockdata) { + return iblockdata.get(BlockPrismarine.VARIANT) == BlockPrismarine.EnumPrismarineVariant.ROUGH ? MaterialMapColor.y : MaterialMapColor.G; + } + + public int getDropData(IBlockData iblockdata) { + return iblockdata.get(BlockPrismarine.VARIANT).a(); + } + + public int toLegacyData(IBlockData iblockdata) { + return iblockdata.get(BlockPrismarine.VARIANT).a(); + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, BlockPrismarine.VARIANT); + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockPrismarine.VARIANT, BlockPrismarine.EnumPrismarineVariant.a(i)); + } + + public enum EnumPrismarineVariant implements INamable { + + ROUGH(0, "prismarine", "rough"), BRICKS(1, "prismarine_bricks", "bricks"), DARK(2, "dark_prismarine", "dark"); + + private static final BlockPrismarine.EnumPrismarineVariant[] d = new BlockPrismarine.EnumPrismarineVariant[values().length]; + private final int e; + private final String f; + private final String g; + + EnumPrismarineVariant(int i, String s, String s1) { + this.e = i; + this.f = s; + this.g = s1; + } + + public int a() { + return this.e; + } + + public String toString() { + return this.f; + } + + public static BlockPrismarine.EnumPrismarineVariant a(int i) { + if (i < 0 || i >= BlockPrismarine.EnumPrismarineVariant.d.length) { + i = 0; + } + + return BlockPrismarine.EnumPrismarineVariant.d[i]; + } + + public String getName() { + return this.f; + } + + public String c() { + return this.g; + } + + static { + for (EnumPrismarineVariant blockprismarine_enumprismarinevariant : values()) { + EnumPrismarineVariant.d[blockprismarine_enumprismarinevariant.a()] = blockprismarine_enumprismarinevariant; + } + + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockPumpkin.java b/azurite-server/src/main/java/net/minecraft/server/BlockPumpkin.java new file mode 100644 index 0000000..ecc5c3b --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockPumpkin.java @@ -0,0 +1,164 @@ +package net.minecraft.server; + +import com.google.common.base.Predicate; +import org.bukkit.craftbukkit.util.BlockStateListPopulator; +import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason; +// CraftBukkit end + +public class BlockPumpkin extends BlockDirectional { + + private ShapeDetector snowGolemPart; + private ShapeDetector snowGolem; + private ShapeDetector ironGolemPart; + private ShapeDetector ironGolem; + private static final Predicate Q = new Predicate() { + public boolean a(IBlockData iblockdata) { + return iblockdata != null && (iblockdata.getBlock() == Blocks.PUMPKIN || iblockdata.getBlock() == Blocks.LIT_PUMPKIN); + } + + public boolean apply(Object object) { + return this.a((IBlockData) object); + } + }; + + protected BlockPumpkin() { + super(Material.PUMPKIN, MaterialMapColor.q); + this.j(this.blockStateList.getBlockData().set(BlockPumpkin.FACING, EnumDirection.NORTH)); + this.a(true); + this.a(CreativeModeTab.b); + } + + public void onPlace(World world, BlockPosition blockposition, IBlockData iblockdata) { + super.onPlace(world, blockposition, iblockdata); + this.f(world, blockposition); + } + + public boolean e(World world, BlockPosition blockposition) { + return this.getDetectorSnowGolemPart().a(world, blockposition) != null || this.getDetectorIronGolemPart().a(world, blockposition) != null; + } + + private void f(World world, BlockPosition blockposition) { + ShapeDetector.ShapeDetectorCollection shapedetector_shapedetectorcollection; + int i; + int j; + + if ((shapedetector_shapedetectorcollection = this.getDetectorSnowGolem().a(world, blockposition)) != null) { + BlockStateListPopulator blockList = new BlockStateListPopulator(world.getWorld()); // CraftBukkit - Use BlockStateListPopulator + for (i = 0; i < this.getDetectorSnowGolem().b(); ++i) { + ShapeDetectorBlock shapedetectorblock = shapedetector_shapedetectorcollection.a(0, i, 0); + + // CraftBukkit start + // world.setTypeAndData(shapedetectorblock.d(), Blocks.AIR.getBlockData(), 2); + BlockPosition pos = shapedetectorblock.getPosition(); + blockList.setTypeId(pos.getX(), pos.getY(), pos.getZ(), 0); + // CraftBukkit end + } + + EntitySnowman entitysnowman = new EntitySnowman(world); + BlockPosition blockposition1 = shapedetector_shapedetectorcollection.a(0, 2, 0).getPosition(); + + entitysnowman.setPositionRotation((double) blockposition1.getX() + 0.5D, (double) blockposition1.getY() + 0.05D, (double) blockposition1.getZ() + 0.5D, 0.0F, 0.0F); + // CraftBukkit start + if (world.addEntity(entitysnowman, SpawnReason.BUILD_SNOWMAN)) { + blockList.updateList(); + + for (j = 0; j < 120; ++j) { + world.addParticle(EnumParticle.SNOW_SHOVEL, (double) blockposition1.getX() + world.random.nextDouble(), (double) blockposition1.getY() + world.random.nextDouble() * 2.5D, (double) blockposition1.getZ() + world.random.nextDouble(), 0.0D, 0.0D, 0.0D, EnumParticle.EMPTY_ARRAY); + } + + for (j = 0; j < this.getDetectorSnowGolem().b(); ++j) { + ShapeDetectorBlock shapedetectorblock1 = shapedetector_shapedetectorcollection.a(0, j, 0); + + world.update(shapedetectorblock1.getPosition(), Blocks.AIR); + } + } // CraftBukkit end + } else if ((shapedetector_shapedetectorcollection = this.getDetectorIronGolem().a(world, blockposition)) != null) { + BlockStateListPopulator blockList = new BlockStateListPopulator(world.getWorld()); // CraftBukkit - Use BlockStateListPopulator + for (i = 0; i < this.getDetectorIronGolem().c(); ++i) { + for (int k = 0; k < this.getDetectorIronGolem().b(); ++k) { + // CraftBukkit start + // world.setTypeAndData(shapedetectorcollection.a(i, k, 0).d(), Blocks.AIR.getBlockData(), 2); + BlockPosition pos = shapedetector_shapedetectorcollection.a(i, k, 0).getPosition(); + blockList.setTypeId(pos.getX(), pos.getY(), pos.getZ(), 0); + // CraftBukkit end + } + } + + BlockPosition blockposition2 = shapedetector_shapedetectorcollection.a(1, 2, 0).getPosition(); + EntityIronGolem entityirongolem = new EntityIronGolem(world); + + entityirongolem.setPlayerCreated(true); + entityirongolem.setPositionRotation((double) blockposition2.getX() + 0.5D, (double) blockposition2.getY() + 0.05D, (double) blockposition2.getZ() + 0.5D, 0.0F, 0.0F); + + // CraftBukkit start + if (world.addEntity(entityirongolem, SpawnReason.BUILD_IRONGOLEM)) { + blockList.updateList(); + + for (j = 0; j < 120; ++j) { + world.addParticle(EnumParticle.SNOWBALL, blockposition2.getX() + world.random.nextDouble(), blockposition2.getY() + world.random.nextDouble() * 3.9D, blockposition2.getZ() + world.random.nextDouble(), 0.0D, 0.0D, 0.0D, EnumParticle.EMPTY_ARRAY); + } + + for (j = 0; j < this.getDetectorIronGolem().c(); ++j) { + for (int l = 0; l < this.getDetectorIronGolem().b(); ++l) { + ShapeDetectorBlock shapedetectorblock2 = shapedetector_shapedetectorcollection.a(j, l, 0); + + world.update(shapedetectorblock2.getPosition(), Blocks.AIR); + } + } + } // CraftBukkit end + } + + } + + public boolean canPlace(World world, BlockPosition blockposition) { + return world.getType(blockposition).getBlock().material.isReplaceable() && World.a(world, blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()); + } + + public IBlockData getPlacedState(World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2, int i, EntityLiving entityliving) { + return this.getBlockData().set(BlockPumpkin.FACING, entityliving.getDirection().opposite()); + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockPumpkin.FACING, EnumDirection.fromType2(i)); + } + + public int toLegacyData(IBlockData iblockdata) { + return iblockdata.get(BlockPumpkin.FACING).b(); + } + + public BlockStateList getStateList() { + return new BlockStateList(this, BlockPumpkin.FACING); + } + + protected ShapeDetector getDetectorSnowGolemPart() { + if (this.snowGolemPart == null) { + this.snowGolemPart = ShapeDetectorBuilder.a().a(new String[] { " ", "#", "#"}).a('#', ShapeDetectorBlock.a(BlockStatePredicate.a(Blocks.SNOW))).b(); + } + + return this.snowGolemPart; + } + + protected ShapeDetector getDetectorSnowGolem() { + if (this.snowGolem == null) { + this.snowGolem = ShapeDetectorBuilder.a().a(new String[] { "^", "#", "#"}).a('^', ShapeDetectorBlock.a(BlockPumpkin.Q)).a('#', ShapeDetectorBlock.a(BlockStatePredicate.a(Blocks.SNOW))).b(); + } + + return this.snowGolem; + } + + protected ShapeDetector getDetectorIronGolemPart() { + if (this.ironGolemPart == null) { + this.ironGolemPart = ShapeDetectorBuilder.a().a(new String[] { "~ ~", "###", "~#~"}).a('#', ShapeDetectorBlock.a(BlockStatePredicate.a(Blocks.IRON_BLOCK))).a('~', ShapeDetectorBlock.a(BlockStatePredicate.a(Blocks.AIR))).b(); + } + + return this.ironGolemPart; + } + + protected ShapeDetector getDetectorIronGolem() { + if (this.ironGolem == null) { + this.ironGolem = ShapeDetectorBuilder.a().a(new String[] { "~^~", "###", "~#~"}).a('^', ShapeDetectorBlock.a(BlockPumpkin.Q)).a('#', ShapeDetectorBlock.a(BlockStatePredicate.a(Blocks.IRON_BLOCK))).a('~', ShapeDetectorBlock.a(BlockStatePredicate.a(Blocks.AIR))).b(); + } + + return this.ironGolem; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockQuartz.java b/azurite-server/src/main/java/net/minecraft/server/BlockQuartz.java new file mode 100644 index 0000000..557e1f7 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockQuartz.java @@ -0,0 +1,124 @@ +package net.minecraft.server; + +public class BlockQuartz extends Block { + + public static final BlockStateEnum VARIANT = BlockStateEnum.of("variant", BlockQuartz.EnumQuartzVariant.class); + + public BlockQuartz() { + super(Material.STONE); + this.j(this.blockStateList.getBlockData().set(BlockQuartz.VARIANT, BlockQuartz.EnumQuartzVariant.DEFAULT)); + this.a(CreativeModeTab.b); + } + + public IBlockData getPlacedState(World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2, int i, EntityLiving entityliving) { + if (i == BlockQuartz.EnumQuartzVariant.LINES_Y.a()) { + switch (BlockQuartz.SyntheticClass_1.a[enumdirection.k().ordinal()]) { + case 1: + return this.getBlockData().set(BlockQuartz.VARIANT, BlockQuartz.EnumQuartzVariant.LINES_Z); + + case 2: + return this.getBlockData().set(BlockQuartz.VARIANT, BlockQuartz.EnumQuartzVariant.LINES_X); + + case 3: + default: + return this.getBlockData().set(BlockQuartz.VARIANT, BlockQuartz.EnumQuartzVariant.LINES_Y); + } + } else { + return i == BlockQuartz.EnumQuartzVariant.CHISELED.a() ? this.getBlockData().set(BlockQuartz.VARIANT, BlockQuartz.EnumQuartzVariant.CHISELED) : this.getBlockData().set(BlockQuartz.VARIANT, BlockQuartz.EnumQuartzVariant.DEFAULT); + } + } + + public int getDropData(IBlockData iblockdata) { + BlockQuartz.EnumQuartzVariant blockquartz_enumquartzvariant = iblockdata.get(BlockQuartz.VARIANT); + + return blockquartz_enumquartzvariant != BlockQuartz.EnumQuartzVariant.LINES_X && blockquartz_enumquartzvariant != BlockQuartz.EnumQuartzVariant.LINES_Z ? blockquartz_enumquartzvariant.a() : BlockQuartz.EnumQuartzVariant.LINES_Y.a(); + } + + protected ItemStack i(IBlockData iblockdata) { + BlockQuartz.EnumQuartzVariant blockquartz_enumquartzvariant = iblockdata.get(BlockQuartz.VARIANT); + + return blockquartz_enumquartzvariant != BlockQuartz.EnumQuartzVariant.LINES_X && blockquartz_enumquartzvariant != BlockQuartz.EnumQuartzVariant.LINES_Z ? super.i(iblockdata) : new ItemStack(Item.getItemOf(this), 1, BlockQuartz.EnumQuartzVariant.LINES_Y.a()); + } + + public MaterialMapColor g(IBlockData iblockdata) { + return MaterialMapColor.p; + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockQuartz.VARIANT, BlockQuartz.EnumQuartzVariant.a(i)); + } + + public int toLegacyData(IBlockData iblockdata) { + return iblockdata.get(BlockQuartz.VARIANT).a(); + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, BlockQuartz.VARIANT); + } + + static class SyntheticClass_1 { + + static final int[] a = new int[EnumDirection.EnumAxis.values().length]; + + static { + try { + BlockQuartz.SyntheticClass_1.a[EnumDirection.EnumAxis.Z.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockQuartz.SyntheticClass_1.a[EnumDirection.EnumAxis.X.ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockQuartz.SyntheticClass_1.a[EnumDirection.EnumAxis.Y.ordinal()] = 3; + } catch (NoSuchFieldError ignored) { + } + + } + } + + public enum EnumQuartzVariant implements INamable { + + DEFAULT(0, "default", "default"), CHISELED(1, "chiseled", "chiseled"), LINES_Y(2, "lines_y", "lines"), LINES_X(3, "lines_x", "lines"), LINES_Z(4, "lines_z", "lines"); + + private static final BlockQuartz.EnumQuartzVariant[] f = new BlockQuartz.EnumQuartzVariant[values().length]; + private final int g; + private final String h; + private final String i; + + EnumQuartzVariant(int i, String s, String s1) { + this.g = i; + this.h = s; + this.i = s1; + } + + public int a() { + return this.g; + } + + public String toString() { + return this.i; + } + + public static BlockQuartz.EnumQuartzVariant a(int i) { + if (i < 0 || i >= BlockQuartz.EnumQuartzVariant.f.length) { + i = 0; + } + + return BlockQuartz.EnumQuartzVariant.f[i]; + } + + public String getName() { + return this.h; + } + + static { + for (EnumQuartzVariant blockquartz_enumquartzvariant : values()) { + EnumQuartzVariant.f[blockquartz_enumquartzvariant.a()] = blockquartz_enumquartzvariant; + } + + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockRedFlowers.java b/azurite-server/src/main/java/net/minecraft/server/BlockRedFlowers.java new file mode 100644 index 0000000..0f4a18e --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockRedFlowers.java @@ -0,0 +1,10 @@ +package net.minecraft.server; + +public class BlockRedFlowers extends BlockFlowers { + + public BlockRedFlowers() {} + + public BlockFlowers.EnumFlowerType l() { + return BlockFlowers.EnumFlowerType.RED; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockRedSandstone.java b/azurite-server/src/main/java/net/minecraft/server/BlockRedSandstone.java new file mode 100644 index 0000000..344d91c --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockRedSandstone.java @@ -0,0 +1,75 @@ +package net.minecraft.server; + +public class BlockRedSandstone extends Block { + + public static final BlockStateEnum TYPE = BlockStateEnum.of("type", BlockRedSandstone.EnumRedSandstoneVariant.class); + + public BlockRedSandstone() { + super(Material.STONE, BlockSand.EnumSandVariant.RED_SAND.c()); + this.j(this.blockStateList.getBlockData().set(BlockRedSandstone.TYPE, BlockRedSandstone.EnumRedSandstoneVariant.DEFAULT)); + this.a(CreativeModeTab.b); + } + + public int getDropData(IBlockData iblockdata) { + return iblockdata.get(BlockRedSandstone.TYPE).a(); + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockRedSandstone.TYPE, BlockRedSandstone.EnumRedSandstoneVariant.a(i)); + } + + public int toLegacyData(IBlockData iblockdata) { + return iblockdata.get(BlockRedSandstone.TYPE).a(); + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, BlockRedSandstone.TYPE); + } + + public enum EnumRedSandstoneVariant implements INamable { + + DEFAULT(0, "red_sandstone", "default"), CHISELED(1, "chiseled_red_sandstone", "chiseled"), SMOOTH(2, "smooth_red_sandstone", "smooth"); + + private static final BlockRedSandstone.EnumRedSandstoneVariant[] d = new BlockRedSandstone.EnumRedSandstoneVariant[values().length]; + private final int e; + private final String f; + private final String g; + + EnumRedSandstoneVariant(int i, String s, String s1) { + this.e = i; + this.f = s; + this.g = s1; + } + + public int a() { + return this.e; + } + + public String toString() { + return this.f; + } + + public static BlockRedSandstone.EnumRedSandstoneVariant a(int i) { + if (i < 0 || i >= BlockRedSandstone.EnumRedSandstoneVariant.d.length) { + i = 0; + } + + return BlockRedSandstone.EnumRedSandstoneVariant.d[i]; + } + + public String getName() { + return this.f; + } + + public String c() { + return this.g; + } + + static { + for (EnumRedSandstoneVariant blockredsandstone_enumredsandstonevariant : values()) { + EnumRedSandstoneVariant.d[blockredsandstone_enumredsandstonevariant.a()] = blockredsandstone_enumredsandstonevariant; + } + + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockRedstoneComparator.java b/azurite-server/src/main/java/net/minecraft/server/BlockRedstoneComparator.java new file mode 100644 index 0000000..59a7be7 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockRedstoneComparator.java @@ -0,0 +1,280 @@ +package net.minecraft.server; + +import com.google.common.base.Predicate; + +import java.util.List; +import java.util.Random; + +public class BlockRedstoneComparator extends BlockDiodeAbstract implements IContainer { + + public static final BlockStateBoolean POWERED = BlockStateBoolean.of("powered"); + public static final BlockStateEnum MODE = BlockStateEnum.of("mode", BlockRedstoneComparator.EnumComparatorMode.class); + + public BlockRedstoneComparator(boolean flag) { + super(flag); + this.j(this.blockStateList.getBlockData().set(BlockRedstoneComparator.FACING, EnumDirection.NORTH).set(BlockRedstoneComparator.POWERED, Boolean.FALSE).set(BlockRedstoneComparator.MODE, BlockRedstoneComparator.EnumComparatorMode.COMPARE)); + this.isTileEntity = true; + } + + public String getName() { + return LocaleI18n.get("item.comparator.name"); + } + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + return Items.COMPARATOR; + } + + protected int d(IBlockData iblockdata) { + return 2; + } + + protected IBlockData e(IBlockData iblockdata) { + Boolean obool = iblockdata.get(BlockRedstoneComparator.POWERED); + BlockRedstoneComparator.EnumComparatorMode blockredstonecomparator_enumcomparatormode = iblockdata.get(BlockRedstoneComparator.MODE); + EnumDirection enumdirection = iblockdata.get(BlockRedstoneComparator.FACING); + + return Blocks.POWERED_COMPARATOR.getBlockData().set(BlockRedstoneComparator.FACING, enumdirection).set(BlockRedstoneComparator.POWERED, obool).set(BlockRedstoneComparator.MODE, blockredstonecomparator_enumcomparatormode); + } + + protected IBlockData k(IBlockData iblockdata) { + Boolean obool = iblockdata.get(BlockRedstoneComparator.POWERED); + BlockRedstoneComparator.EnumComparatorMode blockredstonecomparator_enumcomparatormode = iblockdata.get(BlockRedstoneComparator.MODE); + EnumDirection enumdirection = iblockdata.get(BlockRedstoneComparator.FACING); + + return Blocks.UNPOWERED_COMPARATOR.getBlockData().set(BlockRedstoneComparator.FACING, enumdirection).set(BlockRedstoneComparator.POWERED, obool).set(BlockRedstoneComparator.MODE, blockredstonecomparator_enumcomparatormode); + } + + protected boolean l(IBlockData iblockdata) { + return this.N || iblockdata.get(BlockRedstoneComparator.POWERED); + } + + protected int a(IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata) { + TileEntity tileentity = iblockaccess.getTileEntity(blockposition); + + return tileentity instanceof TileEntityComparator ? ((TileEntityComparator) tileentity).b() : 0; + } + + private int j(World world, BlockPosition blockposition, IBlockData iblockdata) { + return iblockdata.get(BlockRedstoneComparator.MODE) == BlockRedstoneComparator.EnumComparatorMode.SUBTRACT ? + Math.max(this.f(world, blockposition, iblockdata) - this.c(world, blockposition, iblockdata), 0) : this.f(world, blockposition, iblockdata); + } + + protected boolean e(World world, BlockPosition blockposition, IBlockData iblockdata) { + int i = this.f(world, blockposition, iblockdata); + + if (i >= 15) { + return true; + } else if (i == 0) { + return false; + } else { + int j = this.c(world, blockposition, iblockdata); + + return j == 0 || i >= j; + } + } + + protected int f(World world, BlockPosition blockposition, IBlockData iblockdata) { + int i = super.f(world, blockposition, iblockdata); + EnumDirection enumdirection = iblockdata.get(BlockRedstoneComparator.FACING); + BlockPosition blockposition1 = blockposition.shift(enumdirection); + Block block = world.getType(blockposition1).getBlock(); + + if (block.isComplexRedstone()) { + i = block.l(world, blockposition1); + } else if (i < 15 && block.isOccluding()) { + blockposition1 = blockposition1.shift(enumdirection); + block = world.getType(blockposition1).getBlock(); + if (block.isComplexRedstone()) { + i = block.l(world, blockposition1); + } else if (block.getMaterial() == Material.AIR) { + EntityItemFrame entityitemframe = this.a(world, enumdirection, blockposition1); + + if (entityitemframe != null) { + i = entityitemframe.q(); + } + } + } + + return i; + } + + private EntityItemFrame a(World world, final EnumDirection enumdirection, BlockPosition blockposition) { + List list = world.a(EntityItemFrame.class, new AxisAlignedBB(blockposition.getX(), blockposition.getY(), blockposition.getZ(), blockposition.getX() + 1, (blockposition.getY() + 1), (blockposition.getZ() + 1)), (Predicate) entity -> entity != null && entity.getDirection() == enumdirection); + + return list.size() == 1 ? list.get(0) : null; + } + + public boolean interact(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman, EnumDirection enumdirection, float f, float f1, float f2) { + if (!entityhuman.abilities.mayBuild) { + return false; + } else { + iblockdata = iblockdata.a(BlockRedstoneComparator.MODE); + world.makeSound((double) blockposition.getX() + 0.5D, (double) blockposition.getY() + 0.5D, (double) blockposition.getZ() + 0.5D, "random.click", 0.3F, iblockdata.get(BlockRedstoneComparator.MODE) == BlockRedstoneComparator.EnumComparatorMode.SUBTRACT ? 0.55F : 0.5F); + world.setTypeAndData(blockposition, iblockdata, 2); + this.k(world, blockposition, iblockdata); + return true; + } + } + + protected void g(World world, BlockPosition blockposition, IBlockData iblockdata) { + if (!world.a(blockposition, this)) { + int i = this.j(world, blockposition, iblockdata); + TileEntity tileentity = world.getTileEntity(blockposition); + int j = tileentity instanceof TileEntityComparator ? ((TileEntityComparator) tileentity).b() : 0; + + if (i != j || this.l(iblockdata) != this.e(world, blockposition, iblockdata)) { + if (this.i(world, blockposition, iblockdata)) { + world.a(blockposition, this, 2, -1); + } else { + world.a(blockposition, this, 2, 0); + } + } + + } + } + + protected void g(World world, Chunk chunk, BlockPosition blockposition, IBlockData iblockdata) { + if (!world.a(blockposition, this)) { + int i = this.j(world, blockposition, iblockdata); + TileEntity tileentity = world.getTileEntity(chunk, blockposition, iblockdata.getBlock()); + int j = tileentity instanceof TileEntityComparator ? ((TileEntityComparator) tileentity).b() : 0; + + if (i != j || this.l(iblockdata) != this.e(world, blockposition, iblockdata)) { + if (this.i(world, blockposition, iblockdata)) { + world.a(blockposition, chunk, this, 2, -1); + } else { + world.a(blockposition, chunk, this, 2, 0); + } + } + + } + } + + private void k(World world, BlockPosition blockposition, IBlockData iblockdata) { + int i = this.j(world, blockposition, iblockdata); + TileEntity tileentity = world.getTileEntity(blockposition); + int j = 0; + + if (tileentity instanceof TileEntityComparator) { + TileEntityComparator tileentitycomparator = (TileEntityComparator) tileentity; + + j = tileentitycomparator.b(); + tileentitycomparator.a(i); + } + + if (j != i || iblockdata.get(BlockRedstoneComparator.MODE) == BlockRedstoneComparator.EnumComparatorMode.COMPARE) { + boolean flag = this.e(world, blockposition, iblockdata); + boolean flag1 = this.l(iblockdata); + + if (flag1 && !flag) { + world.setTypeAndData(blockposition, iblockdata.set(BlockRedstoneComparator.POWERED, false), 2); + } else if (!flag1 && flag) { + world.setTypeAndData(blockposition, iblockdata.set(BlockRedstoneComparator.POWERED, true), 2); + } + + this.h(world, blockposition, iblockdata); + } + } + + private void k(World world, Chunk chunk, BlockPosition blockposition, IBlockData iblockdata) { + int i = this.j(world, blockposition, iblockdata); + TileEntity tileentity = world.getTileEntity(chunk, blockposition, iblockdata.getBlock()); + int j = 0; + + if (tileentity instanceof TileEntityComparator) { + TileEntityComparator tileentitycomparator = (TileEntityComparator) tileentity; + + j = tileentitycomparator.b(); + tileentitycomparator.a(i); + } + + if (j != i || iblockdata.get(BlockRedstoneComparator.MODE) == BlockRedstoneComparator.EnumComparatorMode.COMPARE) { + boolean flag = this.e(world, blockposition, iblockdata); + boolean flag1 = this.l(iblockdata); + + if (flag1 && !flag) { + world.setTypeAndData(chunk, blockposition, iblockdata.set(BlockRedstoneComparator.POWERED, false), 2, false, false); + } else if (!flag1 && flag) { + world.setTypeAndData(chunk, blockposition, iblockdata.set(BlockRedstoneComparator.POWERED, true), 2, false, false); + } + + this.h(world, blockposition, iblockdata); + } + } + + public void b(World world, BlockPosition blockposition, IBlockData iblockdata, Random random) { + if (this.N) { + world.setTypeAndData(blockposition, this.k(iblockdata).set(BlockRedstoneComparator.POWERED, true), 4); + } + + this.k(world, blockposition, iblockdata); + } + + public void onPlace(World world, BlockPosition blockposition, IBlockData iblockdata) { + super.onPlace(world, blockposition, iblockdata); + world.setTileEntity(blockposition, this.a(world, 0)); + } + + public void remove(World world, BlockPosition blockposition, IBlockData iblockdata) { + super.remove(world, blockposition, iblockdata); + world.t(blockposition); + this.h(world, blockposition, iblockdata); + } + + public boolean a(World world, BlockPosition blockposition, IBlockData iblockdata, int i, int j) { + super.a(world, blockposition, iblockdata, i, j); + TileEntity tileentity = world.getTileEntity(blockposition); + + return tileentity != null && tileentity.c(i, j); + } + + public TileEntity a(World world, int i) { + return new TileEntityComparator(); + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockRedstoneComparator.FACING, EnumDirection.fromType2(i)).set(BlockRedstoneComparator.POWERED, (i & 8) > 0).set(BlockRedstoneComparator.MODE, (i & 4) > 0 ? BlockRedstoneComparator.EnumComparatorMode.SUBTRACT : BlockRedstoneComparator.EnumComparatorMode.COMPARE); + } + + public int toLegacyData(IBlockData iblockdata) { + byte b0 = 0; + int i = b0 | iblockdata.get(BlockRedstoneComparator.FACING).b(); + + if (iblockdata.get(BlockRedstoneComparator.POWERED)) { + i |= 8; + } + + if (iblockdata.get(BlockRedstoneComparator.MODE) == BlockRedstoneComparator.EnumComparatorMode.SUBTRACT) { + i |= 4; + } + + return i; + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, BlockRedstoneComparator.FACING, BlockRedstoneComparator.MODE, BlockRedstoneComparator.POWERED); + } + + public IBlockData getPlacedState(World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2, int i, EntityLiving entityliving) { + return this.getBlockData().set(BlockRedstoneComparator.FACING, entityliving.getDirection().opposite()).set(BlockRedstoneComparator.POWERED, Boolean.FALSE).set(BlockRedstoneComparator.MODE, BlockRedstoneComparator.EnumComparatorMode.COMPARE); + } + + public enum EnumComparatorMode implements INamable { + + COMPARE("compare"), SUBTRACT("subtract"); + + private final String c; + + EnumComparatorMode(String s) { + this.c = s; + } + + public String toString() { + return this.c; + } + + public String getName() { + return this.c; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockRedstoneLamp.java b/azurite-server/src/main/java/net/minecraft/server/BlockRedstoneLamp.java new file mode 100644 index 0000000..b2c9875 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockRedstoneLamp.java @@ -0,0 +1,67 @@ +package net.minecraft.server; + +import org.bukkit.craftbukkit.event.CraftEventFactory; + +import java.util.Random; + +public class BlockRedstoneLamp extends Block { + + private final boolean a; + + public BlockRedstoneLamp(boolean flag) { + super(Material.BUILDABLE_GLASS); + this.a = flag; + if (flag) { + this.a(1.0F); + } + + } + + public void onPlace(World world, BlockPosition blockposition, IBlockData iblockdata) { + if (this.a && !world.isBlockIndirectlyPowered(blockposition)) { + world.setTypeAndData(blockposition, Blocks.REDSTONE_LAMP.getBlockData(), 2); + } else if (!this.a && world.isBlockIndirectlyPowered(blockposition)) { + // CraftBukkit start + if (CraftEventFactory.callRedstoneChange(world, blockposition.getX(), blockposition.getY(), blockposition.getZ(), 0, 15).getNewCurrent() != 15) { + return; + } + // CraftBukkit end + world.setTypeAndData(blockposition, Blocks.LIT_REDSTONE_LAMP.getBlockData(), 2); + } + + } + + public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) { + if (this.a && !world.isBlockIndirectlyPowered(blockposition)) { + world.a(blockposition, this, 4); + } else if (!this.a && world.isBlockIndirectlyPowered(blockposition)) { + // CraftBukkit start + if (CraftEventFactory.callRedstoneChange(world, blockposition.getX(), blockposition.getY(), blockposition.getZ(), 0, 15).getNewCurrent() != 15) { + return; + } + // CraftBukkit end + world.setTypeAndData(blockposition, Blocks.LIT_REDSTONE_LAMP.getBlockData(), 2); + } + + } + + public void b(World world, BlockPosition blockposition, IBlockData iblockdata, Random random) { + if (this.a && !world.isBlockIndirectlyPowered(blockposition)) { + // CraftBukkit start + if (CraftEventFactory.callRedstoneChange(world, blockposition.getX(), blockposition.getY(), blockposition.getZ(), 15, 0).getNewCurrent() != 0) { + return; + } + // CraftBukkit end + world.setTypeAndData(blockposition, Blocks.REDSTONE_LAMP.getBlockData(), 2); + } + + } + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + return Item.getItemOf(Blocks.REDSTONE_LAMP); + } + + protected ItemStack i(IBlockData iblockdata) { + return new ItemStack(Blocks.REDSTONE_LAMP); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockRedstoneOre.java b/azurite-server/src/main/java/net/minecraft/server/BlockRedstoneOre.java new file mode 100644 index 0000000..e1153aa --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockRedstoneOre.java @@ -0,0 +1,154 @@ +package net.minecraft.server; + +import org.bukkit.craftbukkit.event.CraftEventFactory; +import org.bukkit.event.entity.EntityInteractEvent; + +import java.util.Random; +// CraftBukkit end + +public class BlockRedstoneOre extends Block { + + public BlockRedstoneOre(boolean flag) { + super(Material.STONE); + if (flag) { + this.a(true); + } + + } + + public int a(World world) { + return 30; + } + + public void attack(World world, BlockPosition blockposition, EntityHuman entityhuman) { + this.e(world, blockposition, entityhuman); // CraftBukkit - add entityhuman + super.attack(world, blockposition, entityhuman); + } + + public void a(World world, BlockPosition blockposition, Entity entity) { + // CraftBukkit start + + if (entity instanceof EntityHuman) { + org.bukkit.event.player.PlayerInteractEvent event = org.bukkit.craftbukkit.event.CraftEventFactory.callPlayerInteractEvent((EntityHuman) entity, org.bukkit.event.block.Action.PHYSICAL, blockposition, null, null); + if (!event.isCancelled()) { + this.e(world, blockposition, entity); // add entity + super.a(world, blockposition, entity); + } + } else { + EntityInteractEvent event = new EntityInteractEvent(entity.getBukkitEntity(), world.getWorld().getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ())); + world.getServer().getPluginManager().callEvent(event); + if (!event.isCancelled()) { + this.e(world, blockposition, entity); // add entity + super.a(world, blockposition, entity); + } + } + // CraftBukkit end + } + + public boolean interact(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman, EnumDirection enumdirection, float f, float f1, float f2) { + this.e(world, blockposition, entityhuman); // CraftBukkit - add entityhuman + return super.interact(world, blockposition, iblockdata, entityhuman, enumdirection, f, f1, f2); + } + + private void e(World world, BlockPosition blockposition, Entity entity) { // CraftBukkit - add Entity + // this.f(world, blockposition); Vortex - useless... + if (this == Blocks.REDSTONE_ORE) { + // CraftBukkit start + if (CraftEventFactory.callEntityChangeBlockEvent(entity, blockposition.getX(), blockposition.getY(), blockposition.getZ(), Blocks.LIT_REDSTONE_ORE, 0).isCancelled()) { + return; + } + // CraftBukkit end + world.setTypeUpdate(blockposition, Blocks.LIT_REDSTONE_ORE.getBlockData()); + } + + } + + public void b(World world, BlockPosition blockposition, IBlockData iblockdata, Random random) { + if (this == Blocks.LIT_REDSTONE_ORE) { + // CraftBukkit start + if (CraftEventFactory.callBlockFadeEvent(world.getWorld().getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()), Blocks.REDSTONE_ORE).isCancelled()) { + return; + } + // CraftBukkit end + world.setTypeUpdate(blockposition, Blocks.REDSTONE_ORE.getBlockData()); + } + + } + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + return Items.REDSTONE; + } + + public int getDropCount(int i, Random random) { + return this.a(random) + random.nextInt(i + 1); + } + + public int a(Random random) { + return 4 + random.nextInt(2); + } + + public void dropNaturally(World world, BlockPosition blockposition, IBlockData iblockdata, float f, int i) { + super.dropNaturally(world, blockposition, iblockdata, f, i); + /* CraftBukkit start - Delegated to getExpDrop + if (this.getDropType(iblockdata, world.random, i) != Item.getItemOf(this)) { + int j = 1 + world.random.nextInt(5); + + this.dropExperience(world, blockposition, j); + } + // */ + } + + @Override + public int getExpDrop(World world, IBlockData data, int i) { + if (this.getDropType(data, world.random, i) != Item.getItemOf(this)) { + + return 1 + world.random.nextInt(5); + } + return 0; + // CraftBukkit end + } + + private void f(World world, BlockPosition blockposition) { + Random random = world.random; + double d0 = 0.0625D; + + for (int i = 0; i < 6; ++i) { + double d1 = ((float) blockposition.getX() + random.nextFloat()); + double d2 = ((float) blockposition.getY() + random.nextFloat()); + double d3 = ((float) blockposition.getZ() + random.nextFloat()); + + if (i == 0 && !world.getType(blockposition.getX(), blockposition.getY() + 1, blockposition.getZ()).getBlock().c()) { + d2 = (double) blockposition.getY() + d0 + 1.0D; + } + + if (i == 1 && !world.getType(blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()).getBlock().c()) { + d2 = (double) blockposition.getY() - d0; + } + + if (i == 2 && !world.getType(blockposition.getX(), blockposition.getY(), blockposition.getZ() + 1).getBlock().c()) { + d3 = (double) blockposition.getZ() + d0 + 1.0D; + } + + if (i == 3 && !world.getType(blockposition.getX(), blockposition.getY(), blockposition.getZ() - 1).getBlock().c()) { + d3 = (double) blockposition.getZ() - d0; + } + + if (i == 4 && !world.getType(blockposition.getX() + 1, blockposition.getY(), blockposition.getZ()).getBlock().c()) { + d1 = (double) blockposition.getX() + d0 + 1.0D; + } + + if (i == 5 && !world.getType(blockposition.getX() - 1, blockposition.getY(), blockposition.getZ()).getBlock().c()) { + d1 = (double) blockposition.getX() - d0; + } + + if (d1 < (double) blockposition.getX() || d1 > (double) (blockposition.getX() + 1) || d2 < 0.0D || d2 > (double) (blockposition.getY() + 1) || d3 < (double) blockposition.getZ() || d3 > (double) (blockposition.getZ() + 1)) { + world.addParticle(EnumParticle.REDSTONE, d1, d2, d3, 0.0D, 0.0D, 0.0D, EnumParticle.EMPTY_ARRAY); + } + } + + } + + protected ItemStack i(IBlockData iblockdata) { + return new ItemStack(Blocks.REDSTONE_ORE); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockRedstoneTorch.java b/azurite-server/src/main/java/net/minecraft/server/BlockRedstoneTorch.java new file mode 100644 index 0000000..aa76038 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockRedstoneTorch.java @@ -0,0 +1,110 @@ +package net.minecraft.server; + +import org.bukkit.event.block.BlockRedstoneEvent; + +import java.util.Random; + +public class BlockRedstoneTorch extends BlockTorch { + + private final boolean isOn; + + protected BlockRedstoneTorch(boolean flag) { + this.isOn = flag; + this.a(true); + this.a((CreativeModeTab) null); + } + + public int a(World world) { + return 2; + } + + public void applyPhysics(World world, BlockPosition blockposition) { + if (isOn) { + int x = blockposition.getX(), y = blockposition.getY(), z = blockposition.getZ(); + world.applyPhysics(x, y - 1, z, this); + world.applyPhysics(x, y + 1, z, this); + world.applyPhysics(x - 1, y, z, this); + world.applyPhysics(x + 1, y, z, this); + world.applyPhysics(x, y, z + 1, this); + world.applyPhysics(x, y, z - 1, this); + } + } + + public void onPlace(World world, BlockPosition blockposition, IBlockData iblockdata) { + applyPhysics(world, blockposition); + } + + public void remove(World world, BlockPosition blockposition, IBlockData iblockdata) { + applyPhysics(world, blockposition); + } + + public int a(IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata, EnumDirection enumdirection) { + return isOn && iblockdata.get(BlockRedstoneTorch.FACING) != enumdirection ? 15 : 0; + } + + private boolean g(World world, BlockPosition blockposition, IBlockData iblockdata) { + EnumDirection enumdirection = iblockdata.get(BlockRedstoneTorch.FACING).opposite(); + + return world.isBlockFacePowered(blockposition.shift(enumdirection), enumdirection); + } + + public void b(World world, BlockPosition blockposition, IBlockData iblockdata, Random random) { + boolean flag = this.g(world, blockposition, iblockdata); + + if (isOn != flag) { + return; + } + + // CraftBukkit start + org.bukkit.plugin.PluginManager manager = world.getServer().getPluginManager(); + org.bukkit.block.Block block = world.getWorld().getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()); + int oldCurrent = isOn ? 15 : 0; + + BlockRedstoneEvent event = new BlockRedstoneEvent(block, oldCurrent, oldCurrent); + // CraftBukkit end + + if (isOn) { + // CraftBukkit start + event.setNewCurrent(0); + manager.callEvent(event); + if (event.getNewCurrent() != 0) { + return; + } + // CraftBukkit end + world.setTypeAndData(blockposition, Blocks.UNLIT_REDSTONE_TORCH.getBlockData().set(BlockRedstoneTorch.FACING, iblockdata.get(BlockRedstoneTorch.FACING)), 3); + } else { + // CraftBukkit start + event.setNewCurrent(15); + manager.callEvent(event); + if (event.getNewCurrent() != 15) { + return; + } + // CraftBukkit end + world.setTypeAndData(blockposition, Blocks.REDSTONE_TORCH.getBlockData().set(BlockRedstoneTorch.FACING, iblockdata.get(BlockRedstoneTorch.FACING)), 3); + } + + } + + public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) { + if (!e(world, blockposition, iblockdata) && isOn == g(world, blockposition, iblockdata)) { + world.a(blockposition, this, a(world)); + } + } + + public int b(IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata, EnumDirection enumdirection) { + return enumdirection == EnumDirection.DOWN ? this.a(iblockaccess, blockposition, iblockdata, enumdirection) : 0; + } + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + return Item.getItemOf(Blocks.REDSTONE_TORCH); + } + + public boolean isPowerSource() { + return true; + } + + public boolean b(Block block) { + return block == Blocks.UNLIT_REDSTONE_TORCH || block == Blocks.REDSTONE_TORCH; + } + +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockRedstoneWire.java b/azurite-server/src/main/java/net/minecraft/server/BlockRedstoneWire.java new file mode 100644 index 0000000..2a05bf2 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockRedstoneWire.java @@ -0,0 +1,370 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; +import org.bukkit.event.block.BlockRedstoneEvent; + +import java.util.*; + +public class BlockRedstoneWire extends Block { + + public static final BlockStateEnum NORTH = BlockStateEnum.of("north", + BlockRedstoneWire.EnumRedstoneWireConnection.class); + public static final BlockStateEnum EAST = BlockStateEnum.of("east", + BlockRedstoneWire.EnumRedstoneWireConnection.class); + public static final BlockStateEnum SOUTH = BlockStateEnum.of("south", + BlockRedstoneWire.EnumRedstoneWireConnection.class); + public static final BlockStateEnum WEST = BlockStateEnum.of("west", + BlockRedstoneWire.EnumRedstoneWireConnection.class); + public static final BlockStateInteger POWER = BlockStateInteger.of("power", 0, 15); + private final Set R = Sets.newHashSet(); + private boolean Q = true; + + public BlockRedstoneWire() { + super(Material.ORIENTABLE); + this.j(this.blockStateList.getBlockData() + .set(BlockRedstoneWire.NORTH, BlockRedstoneWire.EnumRedstoneWireConnection.NONE) + .set(BlockRedstoneWire.EAST, BlockRedstoneWire.EnumRedstoneWireConnection.NONE) + .set(BlockRedstoneWire.SOUTH, BlockRedstoneWire.EnumRedstoneWireConnection.NONE) + .set(BlockRedstoneWire.WEST, BlockRedstoneWire.EnumRedstoneWireConnection.NONE) + .set(BlockRedstoneWire.POWER, 0)); + this.a(0.0F, 0.0F, 0.0F, 1.0F, 0.0625F, 1.0F); + } + + protected static boolean e(IBlockAccess iblockaccess, BlockPosition blockposition) { + return d(iblockaccess.getType(blockposition)); + } + + protected static boolean d(IBlockData iblockdata) { + return a(iblockdata, null); + } + + protected static boolean a(IBlockData iblockdata, EnumDirection enumdirection) { + Block block = iblockdata.getBlock(); + + if (block == Blocks.REDSTONE_WIRE) { + return true; + } else if (Blocks.UNPOWERED_REPEATER.e(block)) { + EnumDirection enumdirection1 = iblockdata.get(BlockRepeater.FACING); + + return enumdirection1 == enumdirection || enumdirection1.opposite() == enumdirection; + } else { + return block.isPowerSource() && enumdirection != null; + } + } + + public IBlockData updateState(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { + iblockdata = iblockdata.set(BlockRedstoneWire.WEST, this.c(iblockaccess, blockposition, EnumDirection.WEST)); + iblockdata = iblockdata.set(BlockRedstoneWire.EAST, this.c(iblockaccess, blockposition, EnumDirection.EAST)); + iblockdata = iblockdata.set(BlockRedstoneWire.NORTH, this.c(iblockaccess, blockposition, EnumDirection.NORTH)); + iblockdata = iblockdata.set(BlockRedstoneWire.SOUTH, this.c(iblockaccess, blockposition, EnumDirection.SOUTH)); + return iblockdata; + } + + private BlockRedstoneWire.EnumRedstoneWireConnection c(IBlockAccess iblockaccess, BlockPosition blockposition, + EnumDirection enumdirection) { + BlockPosition blockposition1 = blockposition.shift(enumdirection); + Block block = iblockaccess.getType(blockposition.shift(enumdirection)).getBlock(); + + if (!a(iblockaccess.getType(blockposition1), enumdirection) + && (block.u() || !d(iblockaccess.getType(blockposition1.getX(), blockposition1.getY() - 1, blockposition1.getZ())))) { + Block block1 = iblockaccess.getType(blockposition.getX(), blockposition.getY() + 1, blockposition.getZ()).getBlock(); + + return !block1.u() && block.u() && d(iblockaccess.getType(blockposition1.getX(), blockposition1.getY() + 1, blockposition1.getZ())) + ? BlockRedstoneWire.EnumRedstoneWireConnection.UP + : BlockRedstoneWire.EnumRedstoneWireConnection.NONE; + } else { + return BlockRedstoneWire.EnumRedstoneWireConnection.SIDE; + } + } + + public AxisAlignedBB a(World world, BlockPosition blockposition, IBlockData iblockdata) { + return null; + } + + public boolean c() { + return false; + } + + public boolean d() { + return false; + } + + public boolean canPlace(World world, BlockPosition blockposition) { + IBlockData data = world.getType(blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()); + return World.a(data) || data.getBlock() == Blocks.GLOWSTONE; + } + + public boolean canPlace(World world, Chunk chunk, BlockPosition blockposition) { + IBlockData data = world.getType(chunk, blockposition.getX(), blockposition.getY() - 1, blockposition.getZ(), true); + return World.a(data) || data.getBlock() == Blocks.GLOWSTONE; + } + + private void e(World world, BlockPosition blockposition, IBlockData iblockdata) { + this.a(world, blockposition, blockposition, iblockdata); + ArrayList arraylist = Lists.newArrayList(this.R); + + this.R.clear(); + + for (BlockPosition blockposition1 : arraylist) { + world.applyPhysics(blockposition1, this); + } + } + + private void a(World world, BlockPosition blockposition, BlockPosition blockposition1, IBlockData iblockdata) { + IBlockData iblockdata1 = iblockdata; + int i = iblockdata.get(BlockRedstoneWire.POWER); + byte b0 = 0; + int j = this.getPower(world, blockposition1, b0); + + this.Q = false; + int k = world.A(blockposition); + + this.Q = true; + if (k > 0 && k > j - 1) { + j = k; + } + + int l = 0; + + for (EnumDirection enumdirection : EnumDirection.EnumDirectionLimit.HORIZONTAL) { + BlockPosition blockposition2 = blockposition.shift(enumdirection); + boolean flag = blockposition2.getX() != blockposition1.getX() + || blockposition2.getZ() != blockposition1.getZ(); + + if (flag) { + l = this.getPower(world, blockposition2, l); + } + + if (world.getType(blockposition2).getBlock().isOccluding() + && !world.getType(blockposition.getX(), blockposition.getY() + 1, blockposition.getZ()).getBlock().isOccluding()) { + if (flag && blockposition.getY() >= blockposition1.getY()) { + l = this.getPower(world, blockposition2.up(), l); + } + } else if (!world.getType(blockposition2).getBlock().isOccluding() && flag + && blockposition.getY() <= blockposition1.getY()) { + l = this.getPower(world, blockposition2.down(), l); + } + } + + if (l > j) { + j = l - 1; + } else if (j > 0) { + --j; + } else { + j = 0; + } + + if (k > j - 1) { + j = k; + } + + // CraftBukkit start + if (i != j) { + BlockRedstoneEvent event = new BlockRedstoneEvent( + world.getWorld().getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()), i, + j); + world.getServer().getPluginManager().callEvent(event); + + j = event.getNewCurrent(); + } + // CraftBukkit end + + if (i != j) { + iblockdata = iblockdata.set(BlockRedstoneWire.POWER, j); + if (world.getType(blockposition) == iblockdata1) { + world.setTypeAndData(blockposition, iblockdata, 2); + } + + this.R.add(blockposition); + + for (EnumDirection enumdirection1 : EnumDirection.values()) { + this.R.add(blockposition.shift(enumdirection1)); + } + + } + + } + + public void e(World world, BlockPosition blockposition) { + if (world.getType(blockposition).getBlock() == this) { + world.applyPhysics(blockposition, this); + + for (EnumDirection direction : EnumDirection.values()) { + world.applyPhysics(blockposition.getX() + direction.getAdjacentX(), blockposition.getY() + direction.getAdjacentY(), blockposition.getZ() + direction.getAdjacentZ(), this); + } + } + } + + public void onPlace(World world, BlockPosition blockposition, IBlockData iblockdata) { + this.e(world, blockposition, iblockdata); + Iterator iterator = EnumDirection.EnumDirectionLimit.VERTICAL.iterator(); + + EnumDirection enumdirection; + + while (iterator.hasNext()) { + enumdirection = iterator.next(); + world.applyPhysics(blockposition.shift(enumdirection), this); + } + + iterator = EnumDirection.EnumDirectionLimit.HORIZONTAL.iterator(); + + while (iterator.hasNext()) { + enumdirection = iterator.next(); + this.e(world, blockposition.shift(enumdirection)); + } + + iterator = EnumDirection.EnumDirectionLimit.HORIZONTAL.iterator(); + + while (iterator.hasNext()) { + enumdirection = iterator.next(); + BlockPosition blockposition1 = blockposition.shift(enumdirection); + + if (world.getType(blockposition1).getBlock().isOccluding()) { + this.e(world, blockposition1.up()); + } else { + this.e(world, blockposition1.down()); + } + } + + } + + public void remove(World world, BlockPosition blockposition, IBlockData iblockdata) { + super.remove(world, blockposition, iblockdata); + for (EnumDirection enumdirection : EnumDirection.values()) { + world.applyPhysics(blockposition.shift(enumdirection), this); + } + + this.e(world, blockposition, iblockdata); + Iterator iterator = EnumDirection.EnumDirectionLimit.HORIZONTAL.iterator(); + + EnumDirection enumdirection1; + + while (iterator.hasNext()) { + enumdirection1 = iterator.next(); + this.e(world, blockposition.shift(enumdirection1)); + } + + iterator = EnumDirection.EnumDirectionLimit.HORIZONTAL.iterator(); + + while (iterator.hasNext()) { + enumdirection1 = iterator.next(); + BlockPosition blockposition1 = blockposition.shift(enumdirection1); + + if (world.getType(blockposition1).getBlock().isOccluding()) { + this.e(world, blockposition1.up()); + } else { + this.e(world, blockposition1.down()); + } + } + + } + + public int getPower(World world, BlockPosition blockposition, int i) { + IBlockData data = world.getType(blockposition); + if (data.getBlock() != this) { + return i; + } else { + return Math.max(data.get(BlockRedstoneWire.POWER), i); + } + } + + public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) { + if (this.canPlace(world, blockposition)) { + this.e(world, blockposition, iblockdata); + } else { + this.b(world, blockposition, iblockdata, 0); + world.setAir(blockposition); + } + } + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + return Items.REDSTONE; + } + + public int b(IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata, EnumDirection enumdirection) { + return !this.Q ? 0 : this.a(iblockaccess, blockposition, iblockdata, enumdirection); + } + + public int a(IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata, EnumDirection enumdirection) { + if (!this.Q) { + return 0; + } else { + int i = iblockdata.get(BlockRedstoneWire.POWER); + + if (i == 0) { + return 0; + } else if (enumdirection == EnumDirection.UP) { + return i; + } else { + EnumSet enumset = EnumSet.noneOf(EnumDirection.class); + + for (EnumDirection enumdirection1 : EnumDirection.EnumDirectionLimit.HORIZONTAL) { + if (this.d(iblockaccess, blockposition, enumdirection1)) { + enumset.add(enumdirection1); + } + } + + if (enumdirection.k().c() && enumset.isEmpty()) { + return i; + } else if (enumset.contains(enumdirection) && !enumset.contains(enumdirection.f()) + && !enumset.contains(enumdirection.e())) { + return i; + } else { + return 0; + } + } + } + } + + private boolean d(IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection) { + BlockPosition blockposition1 = blockposition.shift(enumdirection); + IBlockData iblockdata = iblockaccess.getType(blockposition1); + Block block = iblockdata.getBlock(); + boolean flag = block.isOccluding(); + boolean flag1 = iblockaccess.getType(blockposition.getX(), blockposition.getY() + 1, blockposition.getZ()).getBlock().isOccluding(); + + return !flag1 && flag && e(iblockaccess, blockposition1.up()) || (a(iblockdata, enumdirection) || (block == Blocks.POWERED_REPEATER + && iblockdata.get(BlockDiodeAbstract.FACING) == enumdirection || !flag && e(iblockaccess, blockposition1.down()))); + } + + public boolean isPowerSource() { + return this.Q; + } + + public void setPowerSource(boolean powerSource) { + this.Q = powerSource; + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockRedstoneWire.POWER, i); + } + + public int toLegacyData(IBlockData iblockdata) { + return iblockdata.get(BlockRedstoneWire.POWER); + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, BlockRedstoneWire.NORTH, BlockRedstoneWire.EAST, + BlockRedstoneWire.SOUTH, BlockRedstoneWire.WEST, BlockRedstoneWire.POWER); + } + + public enum EnumRedstoneWireConnection implements INamable { + + UP("up"), SIDE("side"), NONE("none"); + + private final String d; + + EnumRedstoneWireConnection(String s) { + this.d = s; + } + + public String toString() { + return this.getName(); + } + + public String getName() { + return this.d; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockReed.java b/azurite-server/src/main/java/net/minecraft/server/BlockReed.java new file mode 100644 index 0000000..c48212a --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockReed.java @@ -0,0 +1,137 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.AzuriteConfig; + +import java.util.Iterator; +import java.util.Random; + +public class BlockReed extends Block { + + public static final BlockStateInteger AGE = BlockStateInteger.of("age", 0, 15); + + protected BlockReed() { + super(Material.PLANT); + this.j(this.blockStateList.getBlockData().set(BlockReed.AGE, 0)); + float f = 0.375F; + + this.a(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, 1.0F, 0.5F + f); + this.a(true); + } + + public void b(World world, BlockPosition blockposition, IBlockData iblockdata, Random random) { + if ((world.getType(blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()).getBlock() == Blocks.REEDS || (AzuriteConfig.dropFloatingPlants.getValue() && e(world, blockposition, iblockdata))) && world.isEmpty(blockposition.getX(), blockposition.getY() + 1, blockposition.getZ())) { + int i; + + for (i = 1; world.getType(blockposition.getX(), blockposition.getY() - i, blockposition.getZ()).getBlock() == this; ++i) { + } + + if (i < world.paperSpigotConfig.reedMaxHeight) { // PaperSpigot - Configurable max growth height for reed blocks) { + int j = iblockdata.get(BlockReed.AGE); + + if (j >= (byte) range(3, (world.growthOdds / world.spigotConfig.caneModifier * 15) + 0.5F, 15)) { // Spigot + // CraftBukkit start + // world.setTypeUpdate(blockposition.up(), this.getBlockData()); // CraftBukkit + BlockPosition upPos = blockposition.up(); + org.bukkit.craftbukkit.event.CraftEventFactory.handleBlockGrowEvent(world, upPos.getX(), upPos.getY(), upPos.getZ(), this, 0); + world.setTypeAndData(blockposition, iblockdata.set(BlockReed.AGE, 0), 4); + // CraftBukkit end + } else { + world.setTypeAndData(blockposition, iblockdata.set(BlockReed.AGE, j + 1), 4); + } + } + } + } + + /* // Vortex - optimized reed ticking + @Override + public void optimizedTick(World world, Chunk chunk, BlockPosition blockposition, IBlockData iblockdata, Random random) { + if ((world.getType(blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()).getBlock() == Blocks.REEDS || (AzuriteConfig.dropFloatingPlants.getValue() && e(world, blockposition, iblockdata))) && world.isEmpty(blockposition.getX(), blockposition.getY() + 1, blockposition.getZ())) { + int i; + + for (i = 1; world.getType(chunk, blockposition.getX(), blockposition.getY() - i, blockposition.getZ(), true).getBlock() == this; ++i) { + } + + if (i < world.paperSpigotConfig.reedMaxHeight) { + int j = iblockdata.get(BlockReed.AGE); + + if (j >= (byte) range(3, (world.growthOdds / world.spigotConfig.caneModifier * 15) + 0.5F, 15)) { // Spigot + BlockPosition upPos = blockposition.up(); + org.bukkit.craftbukkit.event.CraftEventFactory.handleBlockGrowEvent(world, upPos.getX(), upPos.getY(), upPos.getZ(), this, 0); + world.setTypeAndData(chunk, blockposition, iblockdata.set(BlockReed.AGE, 0), 4, true, false); + } else { + world.setTypeAndData(chunk, blockposition, iblockdata.set(BlockReed.AGE, j + 1), 4, true, false); + } + } + } + } */ + + public boolean canPlace(World world, BlockPosition blockposition) { + Block block = world.getType(blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()).getBlock(); + + if (block == this) { + return true; + } else if (block != Blocks.GRASS && block != Blocks.DIRT && block != Blocks.SAND) { + return false; + } else { + Iterator iterator = EnumDirection.EnumDirectionLimit.HORIZONTAL.iterator(); + + EnumDirection enumdirection; + + do { + if (!iterator.hasNext()) { + return false; + } + + enumdirection = iterator.next(); + } while (world.getType(blockposition.shift(enumdirection).down()).getBlock().getMaterial() != Material.WATER); + + return true; + } + } + + public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) { + this.e(world, blockposition, iblockdata); + } + + protected final boolean e(World world, BlockPosition blockposition, IBlockData iblockdata) { + if (this.e(world, blockposition)) { + return true; + } else { + this.b(world, blockposition, iblockdata, 0); + world.setAir(blockposition); + return false; + } + } + + public boolean e(World world, BlockPosition blockposition) { + return this.canPlace(world, blockposition); + } + + public AxisAlignedBB a(World world, BlockPosition blockposition, IBlockData iblockdata) { + return null; + } + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + return Items.REEDS; + } + + public boolean c() { + return false; + } + + public boolean d() { + return false; + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockReed.AGE, i); + } + + public int toLegacyData(IBlockData iblockdata) { + return iblockdata.get(BlockReed.AGE); + } + + public BlockStateList getStateList() { + return new BlockStateList(this, BlockReed.AGE); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockRepeater.java b/azurite-server/src/main/java/net/minecraft/server/BlockRepeater.java new file mode 100644 index 0000000..a886c70 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockRepeater.java @@ -0,0 +1,76 @@ +package net.minecraft.server; + +import java.util.Random; + +public class BlockRepeater extends BlockDiodeAbstract { + + public static final BlockStateBoolean LOCKED = BlockStateBoolean.of("locked"); + public static final BlockStateInteger DELAY = BlockStateInteger.of("delay", 1, 4); + + protected BlockRepeater(boolean flag) { + super(flag); + this.j(this.blockStateList.getBlockData().set(BlockRepeater.FACING, EnumDirection.NORTH).set(BlockRepeater.DELAY, 1).set(BlockRepeater.LOCKED, false)); + } + + public String getName() { + return LocaleI18n.get("item.diode.name"); + } + + public IBlockData updateState(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { + return iblockdata.set(LOCKED, this.b(iblockaccess, blockposition, iblockdata)); + } + + public boolean interact(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman, EnumDirection enumdirection, float f, float f1, float f2) { + if (!entityhuman.abilities.mayBuild) { + return false; + } else { + world.setTypeAndData(blockposition, iblockdata.a(BlockRepeater.DELAY), 3, false, false); + return true; + } + } + + protected int d(IBlockData iblockdata) { + return iblockdata.get(BlockRepeater.DELAY) * 2; + } + + protected IBlockData e(IBlockData iblockdata) { + return Blocks.POWERED_REPEATER.getBlockData().set(FACING, iblockdata.get(FACING)).set(DELAY, iblockdata.get(DELAY)).set(LOCKED, iblockdata.get(BlockRepeater.LOCKED)); + } + + protected IBlockData k(IBlockData iblockdata) { + return Blocks.UNPOWERED_REPEATER.getBlockData().set(FACING, iblockdata.get(FACING)).set(DELAY, iblockdata.get(DELAY)).set(LOCKED, iblockdata.get(BlockRepeater.LOCKED)); + } + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + return Items.REPEATER; + } + + public boolean b(IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata) { + return c(iblockaccess, blockposition, iblockdata) > 0; + } + + protected boolean c(Block block) { + return d(block); + } + + public void remove(World world, BlockPosition blockposition, IBlockData iblockdata) { + super.remove(world, blockposition, iblockdata); + this.h(world, blockposition, iblockdata); + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockRepeater.FACING, EnumDirection.fromType2(i)).set(BlockRepeater.LOCKED, false).set(BlockRepeater.DELAY, 1 + (i >> 2)); + } + + public int toLegacyData(IBlockData iblockdata) { + byte b0 = 0; + int i = b0 | iblockdata.get(BlockRepeater.FACING).b(); + + i |= iblockdata.get(BlockRepeater.DELAY) - 1 << 2; + return i; + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, BlockRepeater.FACING, BlockRepeater.DELAY, BlockRepeater.LOCKED); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockRotatable.java b/azurite-server/src/main/java/net/minecraft/server/BlockRotatable.java new file mode 100644 index 0000000..186eb0a --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockRotatable.java @@ -0,0 +1,14 @@ +package net.minecraft.server; + +public abstract class BlockRotatable extends Block { + + public static final BlockStateEnum AXIS = BlockStateEnum.of("axis", EnumDirection.EnumAxis.class); + + protected BlockRotatable(Material material) { + super(material, material.r()); + } + + protected BlockRotatable(Material material, MaterialMapColor materialmapcolor) { + super(material, materialmapcolor); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockSand.java b/azurite-server/src/main/java/net/minecraft/server/BlockSand.java new file mode 100644 index 0000000..1b769e4 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockSand.java @@ -0,0 +1,83 @@ +package net.minecraft.server; + +public class BlockSand extends BlockFalling { + + public static final BlockStateEnum VARIANT = BlockStateEnum.of("variant", BlockSand.EnumSandVariant.class); + + public BlockSand() { + this.j(this.blockStateList.getBlockData().set(BlockSand.VARIANT, BlockSand.EnumSandVariant.SAND)); + } + + public int getDropData(IBlockData iblockdata) { + return iblockdata.get(BlockSand.VARIANT).a(); + } + + public MaterialMapColor g(IBlockData iblockdata) { + return iblockdata.get(BlockSand.VARIANT).c(); + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockSand.VARIANT, BlockSand.EnumSandVariant.a(i)); + } + + public int toLegacyData(IBlockData iblockdata) { + return iblockdata.get(BlockSand.VARIANT).a(); + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, BlockSand.VARIANT); + } + + public enum EnumSandVariant implements INamable { + + SAND(0, "sand", "default", MaterialMapColor.d), RED_SAND(1, "red_sand", "red", MaterialMapColor.q); + + private static final BlockSand.EnumSandVariant[] c = new BlockSand.EnumSandVariant[values().length]; + private final int d; + private final String e; + private final MaterialMapColor f; + private final String g; + + EnumSandVariant(int i, String s, String s1, MaterialMapColor materialmapcolor) { + this.d = i; + this.e = s; + this.f = materialmapcolor; + this.g = s1; + } + + public int a() { + return this.d; + } + + public String toString() { + return this.e; + } + + public MaterialMapColor c() { + return this.f; + } + + public static BlockSand.EnumSandVariant a(int i) { + if (i < 0 || i >= BlockSand.EnumSandVariant.c.length) { + i = 0; + } + + return BlockSand.EnumSandVariant.c[i]; + } + + public String getName() { + return this.e; + } + + public String d() { + return this.g; + } + + static { + for (EnumSandVariant blocksand_enumsandvariant : values()) { + EnumSandVariant.c[blocksand_enumsandvariant.a()] = blocksand_enumsandvariant; + } + + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockSandStone.java b/azurite-server/src/main/java/net/minecraft/server/BlockSandStone.java new file mode 100644 index 0000000..828097a --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockSandStone.java @@ -0,0 +1,79 @@ +package net.minecraft.server; + +public class BlockSandStone extends Block { + + public static final BlockStateEnum TYPE = BlockStateEnum.of("type", BlockSandStone.EnumSandstoneVariant.class); + + public BlockSandStone() { + super(Material.STONE); + this.j(this.blockStateList.getBlockData().set(BlockSandStone.TYPE, BlockSandStone.EnumSandstoneVariant.DEFAULT)); + this.a(CreativeModeTab.b); + } + + public int getDropData(IBlockData iblockdata) { + return iblockdata.get(BlockSandStone.TYPE).a(); + } + + public MaterialMapColor g(IBlockData iblockdata) { + return MaterialMapColor.d; + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockSandStone.TYPE, BlockSandStone.EnumSandstoneVariant.a(i)); + } + + public int toLegacyData(IBlockData iblockdata) { + return iblockdata.get(BlockSandStone.TYPE).a(); + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, BlockSandStone.TYPE); + } + + public enum EnumSandstoneVariant implements INamable { + + DEFAULT(0, "sandstone", "default"), CHISELED(1, "chiseled_sandstone", "chiseled"), SMOOTH(2, "smooth_sandstone", "smooth"); + + private static final BlockSandStone.EnumSandstoneVariant[] d = new BlockSandStone.EnumSandstoneVariant[values().length]; + private final int e; + private final String f; + private final String g; + + EnumSandstoneVariant(int i, String s, String s1) { + this.e = i; + this.f = s; + this.g = s1; + } + + public int a() { + return this.e; + } + + public String toString() { + return this.f; + } + + public static BlockSandStone.EnumSandstoneVariant a(int i) { + if (i < 0 || i >= BlockSandStone.EnumSandstoneVariant.d.length) { + i = 0; + } + + return BlockSandStone.EnumSandstoneVariant.d[i]; + } + + public String getName() { + return this.f; + } + + public String c() { + return this.g; + } + + static { + for (EnumSandstoneVariant blocksandstone_enumsandstonevariant : values()) { + EnumSandstoneVariant.d[blocksandstone_enumsandstonevariant.a()] = blocksandstone_enumsandstonevariant; + } + + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockSapling.java b/azurite-server/src/main/java/net/minecraft/server/BlockSapling.java new file mode 100644 index 0000000..4372c23 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockSapling.java @@ -0,0 +1,270 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.AzuriteConfig; +import org.bukkit.Location; +import org.bukkit.TreeType; +import org.bukkit.block.BlockState; +import org.bukkit.event.world.StructureGrowEvent; + +import java.util.List; +import java.util.Random; +// CraftBukkit end + +public class BlockSapling extends BlockPlant implements IBlockFragilePlantElement { + + public static final BlockStateEnum TYPE = BlockStateEnum.of("type", BlockWood.EnumLogVariant.class); + public static final BlockStateInteger STAGE = BlockStateInteger.of("stage", 0, 1); + public static TreeType treeType; // CraftBukkit + + protected BlockSapling() { + this.j(this.blockStateList.getBlockData().set(BlockSapling.TYPE, BlockWood.EnumLogVariant.OAK).set(BlockSapling.STAGE, 0)); + float f = 0.4F; + + this.a(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, f * 2.0F, 0.5F + f); + this.a(CreativeModeTab.c); + } + + public String getName() { + return LocaleI18n.get(this.a() + "." + BlockWood.EnumLogVariant.OAK.d() + ".name"); + } + + public void b(World world, BlockPosition blockposition, IBlockData iblockdata, Random random) { + if (AzuriteConfig.dropFloatingPlants.getValue()) { + super.b(world, blockposition, iblockdata, random); + } else if (!f(world, blockposition, iblockdata)) { + return; + } + if (world.isLightLevel(blockposition.getX(), blockposition.getY() + 1, blockposition.getZ(), 9) && (random.nextInt(Math.max(2, (int) ((world.growthOdds / world.spigotConfig.saplingModifier * 7) + 0.5F))) == 0)) { // Spigot) { // PandaSpigot - Use isLightLevel + // CraftBukkit start + world.captureTreeGeneration = true; + // CraftBukkit end + this.grow(world, blockposition, iblockdata, random); + // CraftBukkit start + world.captureTreeGeneration = false; + if (!world.capturedBlockStates.isEmpty()) { + TreeType treeType = BlockSapling.treeType; + BlockSapling.treeType = null; + Location location = new Location(world.getWorld(), blockposition.getX(), blockposition.getY(), blockposition.getZ()); + List blocks = (List) world.capturedBlockStates.clone(); + world.capturedBlockStates.clear(); + StructureGrowEvent event = null; + if (treeType != null) { + event = new StructureGrowEvent(location, treeType, false, null, blocks); + org.bukkit.Bukkit.getPluginManager().callEvent(event); + } + if (event == null || !event.isCancelled()) { + for (BlockState blockstate : blocks) { + blockstate.update(true); + } + } + } + // CraftBukkit end + } + + } + + public void grow(World world, BlockPosition blockposition, IBlockData iblockdata, Random random) { + if (iblockdata.get(BlockSapling.STAGE) == 0) { + world.setTypeAndData(blockposition, iblockdata.a(BlockSapling.STAGE), 4); + } else { + this.e(world, blockposition, iblockdata, random); + } + + } + + public void e(World world, BlockPosition blockposition, IBlockData iblockdata, Random random) { + // CraftBukkit start - Turn ternary operator into if statement to set treeType + // Object object = random.nextInt(10) == 0 ? new WorldGenBigTree(true) : new WorldGenTrees(true); + Object object; + if (random.nextInt(10) == 0) { + treeType = TreeType.BIG_TREE; + object = new WorldGenBigTree(true); + } else { + treeType = TreeType.TREE; + object = new WorldGenTrees(true); + } + // CraftBukkit end + int i = 0; + int j = 0; + boolean flag = false; + IBlockData iblockdata1; + + switch (BlockSapling.SyntheticClass_1.a[(iblockdata.get(BlockSapling.TYPE)).ordinal()]) { + case 1: + label66: + for (i = 0; i >= -1; --i) { + for (j = 0; j >= -1; --j) { + if (this.a(world, blockposition, i, j, BlockWood.EnumLogVariant.SPRUCE)) { + treeType = TreeType.MEGA_REDWOOD; // CraftBukkit + object = new WorldGenMegaTree(false, random.nextBoolean()); + flag = true; + break label66; + } + } + } + + if (!flag) { + j = 0; + i = 0; + treeType = TreeType.REDWOOD; // CraftBukkit + object = new WorldGenTaiga2(true); + } + break; + + case 2: + treeType = TreeType.BIRCH; // CraftBukkit + object = new WorldGenForest(true, false); + break; + + case 3: + iblockdata1 = Blocks.LOG.getBlockData().set(BlockLog1.VARIANT, BlockWood.EnumLogVariant.JUNGLE); + IBlockData iblockdata2 = Blocks.LEAVES.getBlockData().set(BlockLeaves1.VARIANT, BlockWood.EnumLogVariant.JUNGLE).set(BlockLeaves.CHECK_DECAY, false); + + label78: + for (i = 0; i >= -1; --i) { + for (j = 0; j >= -1; --j) { + if (this.a(world, blockposition, i, j, BlockWood.EnumLogVariant.JUNGLE)) { + treeType = TreeType.JUNGLE; // CraftBukkit + object = new WorldGenJungleTree(true, 10, 20, iblockdata1, iblockdata2); + flag = true; + break label78; + } + } + } + + if (!flag) { + j = 0; + i = 0; + treeType = TreeType.SMALL_JUNGLE; // CraftBukkit + object = new WorldGenTrees(true, 4 + random.nextInt(7), iblockdata1, iblockdata2, false); + } + break; + + case 4: + treeType = TreeType.ACACIA; // CraftBukkit + object = new WorldGenAcaciaTree(true); + break; + + case 5: + label90: + for (i = 0; i >= -1; --i) { + for (j = 0; j >= -1; --j) { + if (this.a(world, blockposition, i, j, BlockWood.EnumLogVariant.DARK_OAK)) { + treeType = TreeType.DARK_OAK; // CraftBukkit + object = new WorldGenForestTree(true); + flag = true; + break label90; + } + } + } + + if (!flag) { + return; + } + + case 6: + } + + iblockdata1 = Blocks.AIR.getBlockData(); + if (flag) { + world.setTypeAndData(blockposition.a(i, 0, j), iblockdata1, 4); + world.setTypeAndData(blockposition.a(i + 1, 0, j), iblockdata1, 4); + world.setTypeAndData(blockposition.a(i, 0, j + 1), iblockdata1, 4); + world.setTypeAndData(blockposition.a(i + 1, 0, j + 1), iblockdata1, 4); + } else { + world.setTypeAndData(blockposition, iblockdata1, 4); + } + + if (!((WorldGenerator) object).generate(world, random, blockposition.a(i, 0, j))) { + if (flag) { + world.setTypeAndData(blockposition.a(i, 0, j), iblockdata, 4); + world.setTypeAndData(blockposition.a(i + 1, 0, j), iblockdata, 4); + world.setTypeAndData(blockposition.a(i, 0, j + 1), iblockdata, 4); + world.setTypeAndData(blockposition.a(i + 1, 0, j + 1), iblockdata, 4); + } else { + world.setTypeAndData(blockposition, iblockdata, 4); + } + } + + } + + private boolean a(World world, BlockPosition blockposition, int i, int j, BlockWood.EnumLogVariant blockwood_enumlogvariant) { + return this.a(world, blockposition.a(i, 0, j), blockwood_enumlogvariant) && this.a(world, blockposition.a(i + 1, 0, j), blockwood_enumlogvariant) && this.a(world, blockposition.a(i, 0, j + 1), blockwood_enumlogvariant) && this.a(world, blockposition.a(i + 1, 0, j + 1), blockwood_enumlogvariant); + } + + public boolean a(World world, BlockPosition blockposition, BlockWood.EnumLogVariant blockwood_enumlogvariant) { + IBlockData iblockdata = world.getType(blockposition); + + return iblockdata.getBlock() == this && iblockdata.get(BlockSapling.TYPE) == blockwood_enumlogvariant; + } + + public int getDropData(IBlockData iblockdata) { + return (iblockdata.get(BlockSapling.TYPE)).a(); + } + + public boolean a(World world, BlockPosition blockposition, IBlockData iblockdata, boolean flag) { + return true; + } + + public boolean a(World world, Random random, BlockPosition blockposition, IBlockData iblockdata) { + return (double) world.random.nextFloat() < 0.45D; + } + + public void b(World world, Random random, BlockPosition blockposition, IBlockData iblockdata) { + this.grow(world, blockposition, iblockdata, random); + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockSapling.TYPE, BlockWood.EnumLogVariant.a(i & 7)).set(BlockSapling.STAGE, (i & 8) >> 3); + } + + public int toLegacyData(IBlockData iblockdata) { + byte b0 = 0; + int i = b0 | (iblockdata.get(BlockSapling.TYPE)).a(); + + i |= iblockdata.get(BlockSapling.STAGE) << 3; + return i; + } + + public BlockStateList getStateList() { + return new BlockStateList(this, BlockSapling.TYPE, BlockSapling.STAGE); + } + + static class SyntheticClass_1 { + + static final int[] a = new int[BlockWood.EnumLogVariant.values().length]; + + static { + try { + BlockSapling.SyntheticClass_1.a[BlockWood.EnumLogVariant.SPRUCE.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockSapling.SyntheticClass_1.a[BlockWood.EnumLogVariant.BIRCH.ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockSapling.SyntheticClass_1.a[BlockWood.EnumLogVariant.JUNGLE.ordinal()] = 3; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockSapling.SyntheticClass_1.a[BlockWood.EnumLogVariant.ACACIA.ordinal()] = 4; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockSapling.SyntheticClass_1.a[BlockWood.EnumLogVariant.DARK_OAK.ordinal()] = 5; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockSapling.SyntheticClass_1.a[BlockWood.EnumLogVariant.OAK.ordinal()] = 6; + } catch (NoSuchFieldError ignored) { + } + + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockSeaLantern.java b/azurite-server/src/main/java/net/minecraft/server/BlockSeaLantern.java new file mode 100644 index 0000000..9e7b525 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockSeaLantern.java @@ -0,0 +1,31 @@ +package net.minecraft.server; + +import java.util.Random; + +public class BlockSeaLantern extends Block { + + public BlockSeaLantern(Material material) { + super(material); + this.a(CreativeModeTab.b); + } + + public int a(Random random) { + return 2 + random.nextInt(2); + } + + public int getDropCount(int i, Random random) { + return MathHelper.clamp(this.a(random) + random.nextInt(i + 1), 1, 5); + } + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + return Items.PRISMARINE_CRYSTALS; + } + + public MaterialMapColor g(IBlockData iblockdata) { + return MaterialMapColor.p; + } + + protected boolean I() { + return true; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockSign.java b/azurite-server/src/main/java/net/minecraft/server/BlockSign.java new file mode 100644 index 0000000..3c1b022 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockSign.java @@ -0,0 +1,52 @@ +package net.minecraft.server; + +import java.util.Random; + +public class BlockSign extends BlockContainer { + + protected BlockSign() { + super(Material.WOOD); + float f = 0.25F; + float f1 = 1.0F; + + this.a(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, f1, 0.5F + f); + } + + public AxisAlignedBB a(World world, BlockPosition blockposition, IBlockData iblockdata) { + return null; + } + + public boolean d() { + return false; + } + + public boolean b(IBlockAccess iblockaccess, BlockPosition blockposition) { + return true; + } + + public boolean c() { + return false; + } + + public boolean g() { + return true; + } + + public TileEntity a(World world, int i) { + return new TileEntitySign(); + } + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + return Items.SIGN; + } + + public boolean interact(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman, EnumDirection enumdirection, float f, float f1, float f2) { + TileEntity tileentity = world.getTileEntity(blockposition); + + return tileentity instanceof TileEntitySign && ((TileEntitySign) tileentity).b(entityhuman); + } + + public boolean canPlace(World world, BlockPosition blockposition) { + return !this.e(world, blockposition) && super.canPlace(world, blockposition); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockSkull.java b/azurite-server/src/main/java/net/minecraft/server/BlockSkull.java new file mode 100644 index 0000000..c92ab51 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockSkull.java @@ -0,0 +1,268 @@ +package net.minecraft.server; + +import com.google.common.base.Predicate; +import org.bukkit.craftbukkit.util.BlockStateListPopulator; +import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason; + +import java.util.Iterator; +import java.util.Random; +// CraftBukkit end + +public class BlockSkull extends BlockContainer { + + public static final BlockStateDirection FACING = BlockStateDirection.of("facing"); + public static final BlockStateBoolean NODROP = BlockStateBoolean.of("nodrop"); + private static final Predicate N = new Predicate() { + public boolean a(ShapeDetectorBlock shapedetectorblock) { + return shapedetectorblock.a() != null && shapedetectorblock.a().getBlock() == Blocks.SKULL && shapedetectorblock.b() instanceof TileEntitySkull && ((TileEntitySkull) shapedetectorblock.b()).getSkullType() == 1; + } + + public boolean apply(Object object) { + return this.a((ShapeDetectorBlock) object); + } + }; + private ShapeDetector O; + private ShapeDetector P; + + protected BlockSkull() { + super(Material.ORIENTABLE); + this.j(this.blockStateList.getBlockData().set(BlockSkull.FACING, EnumDirection.NORTH).set(BlockSkull.NODROP, false)); + this.a(0.25F, 0.0F, 0.25F, 0.75F, 0.5F, 0.75F); + } + + public String getName() { + return LocaleI18n.get("tile.skull.skeleton.name"); + } + + public boolean c() { + return false; + } + + public boolean d() { + return false; + } + + public void updateShape(IBlockAccess iblockaccess, BlockPosition blockposition) { + switch (BlockSkull.SyntheticClass_1.a[iblockaccess.getType(blockposition).get(BlockSkull.FACING).ordinal()]) { + case 1: + default: + this.a(0.25F, 0.0F, 0.25F, 0.75F, 0.5F, 0.75F); + break; + + case 2: + this.a(0.25F, 0.25F, 0.5F, 0.75F, 0.75F, 1.0F); + break; + + case 3: + this.a(0.25F, 0.25F, 0.0F, 0.75F, 0.75F, 0.5F); + break; + + case 4: + this.a(0.5F, 0.25F, 0.25F, 1.0F, 0.75F, 0.75F); + break; + + case 5: + this.a(0.0F, 0.25F, 0.25F, 0.5F, 0.75F, 0.75F); + } + + } + + public AxisAlignedBB a(World world, BlockPosition blockposition, IBlockData iblockdata) { + this.updateShape(world, blockposition); + return super.a(world, blockposition, iblockdata); + } + + public IBlockData getPlacedState(World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2, int i, EntityLiving entityliving) { + return this.getBlockData().set(BlockSkull.FACING, entityliving.getDirection()).set(BlockSkull.NODROP, false); + } + + public TileEntity a(World world, int i) { + return new TileEntitySkull(); + } + + public int getDropData(World world, BlockPosition blockposition) { + TileEntity tileentity = world.getTileEntity(blockposition); + + return tileentity instanceof TileEntitySkull ? ((TileEntitySkull) tileentity).getSkullType() : super.getDropData(world, blockposition); + } + + // CraftBukkit start - Special case dropping so we can get info from the tile entity + @Override + public void dropNaturally(World world, BlockPosition blockposition, IBlockData iblockdata, float f, int i) { + if (world.random.nextFloat() < f) { + ItemStack itemstack = new ItemStack(Items.SKULL, 1, this.getDropData(world, blockposition)); + TileEntitySkull tileentityskull = (TileEntitySkull) world.getTileEntity(blockposition); + + if (tileentityskull.getSkullType() == 3 && tileentityskull.getGameProfile() != null) { + itemstack.setTag(new NBTTagCompound()); + NBTTagCompound nbttagcompound = new NBTTagCompound(); + + GameProfileSerializer.serialize(nbttagcompound, tileentityskull.getGameProfile()); + itemstack.getTag().set("SkullOwner", nbttagcompound); + } + + a(world, blockposition, itemstack); + } + } + // CraftBukkit end + + public void a(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman) { + if (entityhuman.abilities.canInstantlyBuild) { + iblockdata = iblockdata.set(BlockSkull.NODROP, true); + world.setTypeAndData(blockposition, iblockdata, 4); + } + + super.a(world, blockposition, iblockdata, entityhuman); + } + + public void remove(World world, BlockPosition blockposition, IBlockData iblockdata) { + super.remove(world, blockposition, iblockdata); + } + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + return Items.SKULL; + } + + public boolean b(World world, BlockPosition blockposition, ItemStack itemstack) { + return itemstack.getData() == 1 && blockposition.getY() >= 2 && world.getDifficulty() != EnumDifficulty.PEACEFUL && this.l().a(world, blockposition) != null; + } + + public void a(World world, BlockPosition blockposition, TileEntitySkull tileentityskull) { + if (world.captureBlockStates) return; // CraftBukkit + if (tileentityskull.getSkullType() == 1 && blockposition.getY() >= 2 && world.getDifficulty() != EnumDifficulty.PEACEFUL) { + ShapeDetector shapedetector = this.n(); + ShapeDetector.ShapeDetectorCollection shapedetector_shapedetectorcollection = shapedetector.a(world, blockposition); + + if (shapedetector_shapedetectorcollection != null) { + // CraftBukkit start - Use BlockStateListPopulator + BlockStateListPopulator blockList = new BlockStateListPopulator(world.getWorld()); + int i; + + for (i = 0; i < 3; ++i) { + ShapeDetectorBlock shapedetectorblock = shapedetector_shapedetectorcollection.a(i, 0, 0); + + // CraftBukkit start + // world.setTypeAndData(shapedetectorblock.getPosition(), shapedetectorblock.a().set(BlockSkull.NODROP, Boolean.valueOf(true)), 2); + BlockPosition pos = shapedetectorblock.getPosition(); + IBlockData data = shapedetectorblock.a().set(BlockSkull.NODROP, true); + blockList.setTypeAndData(pos.getX(), pos.getY(), pos.getZ(), data.getBlock(), data.getBlock().toLegacyData(data), 2); + // CraftBukkit end + } + + for (i = 0; i < shapedetector.c(); ++i) { + for (int j = 0; j < shapedetector.b(); ++j) { + ShapeDetectorBlock shapedetectorblock1 = shapedetector_shapedetectorcollection.a(i, j, 0); + + // CraftBukkit start + // world.setTypeAndData(shapedetectorblock1.getPosition(), Blocks.AIR.getBlockData(), 2); + BlockPosition pos = shapedetectorblock1.getPosition(); + blockList.setTypeAndData(pos.getX(), pos.getY(), pos.getZ(), Blocks.AIR, 0, 2); + // CraftBukkit end + } + } + + BlockPosition blockposition1 = shapedetector_shapedetectorcollection.a(1, 0, 0).getPosition(); + EntityWither entitywither = new EntityWither(world); + BlockPosition blockposition2 = shapedetector_shapedetectorcollection.a(1, 2, 0).getPosition(); + + entitywither.setPositionRotation((double) blockposition2.getX() + 0.5D, (double) blockposition2.getY() + 0.55D, (double) blockposition2.getZ() + 0.5D, shapedetector_shapedetectorcollection.b().k() == EnumDirection.EnumAxis.X ? 0.0F : 90.0F, 0.0F); + entitywither.aI = shapedetector_shapedetectorcollection.b().k() == EnumDirection.EnumAxis.X ? 0.0F : 90.0F; + entitywither.n(); + Iterator iterator = world.a(EntityHuman.class, entitywither.getBoundingBox().grow(50.0D, 50.0D, 50.0D)).iterator(); + + // CraftBukkit start + if (world.addEntity(entitywither, SpawnReason.BUILD_WITHER)) { + blockList.updateList(); + + while (iterator.hasNext()) { + EntityHuman entityhuman = iterator.next(); + entityhuman.b(AchievementList.I); + } + + int k; + + for (k = 0; k < 120; ++k) { + world.addParticle(EnumParticle.SNOWBALL, blockposition1.getX() + world.random.nextDouble(), (blockposition1.getY() - 2) + world.random.nextDouble() * 3.9D, blockposition1.getZ() + world.random.nextDouble(), 0.0D, 0.0D, 0.0D, EnumParticle.EMPTY_ARRAY); + } + + for (k = 0; k < shapedetector.c(); ++k) { + for (int l = 0; l < shapedetector.b(); ++l) { + ShapeDetectorBlock shapedetectorblock2 = shapedetector_shapedetectorcollection.a(k, l, 0); + + world.update(shapedetectorblock2.getPosition(), Blocks.AIR); + } + } + } // CraftBukkit end + + } + } + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockSkull.FACING, EnumDirection.fromType1(i & 7)).set(BlockSkull.NODROP, (i & 8) > 0); + } + + public int toLegacyData(IBlockData iblockdata) { + byte b0 = 0; + int i = b0 | iblockdata.get(BlockSkull.FACING).a(); + + if (iblockdata.get(BlockSkull.NODROP)) { + i |= 8; + } + + return i; + } + + public BlockStateList getStateList() { + return new BlockStateList(this, BlockSkull.FACING, BlockSkull.NODROP); + } + + protected ShapeDetector l() { + if (this.O == null) { + this.O = ShapeDetectorBuilder.a().a(new String[]{" ", "###", "~#~"}).a('#', ShapeDetectorBlock.a(BlockStatePredicate.a(Blocks.SOUL_SAND))).a('~', ShapeDetectorBlock.a(BlockStatePredicate.a(Blocks.AIR))).b(); + } + + return this.O; + } + + protected ShapeDetector n() { + if (this.P == null) { + this.P = ShapeDetectorBuilder.a().a(new String[]{"^^^", "###", "~#~"}).a('#', ShapeDetectorBlock.a(BlockStatePredicate.a(Blocks.SOUL_SAND))).a('^', BlockSkull.N).a('~', ShapeDetectorBlock.a(BlockStatePredicate.a(Blocks.AIR))).b(); + } + + return this.P; + } + + static class SyntheticClass_1 { + + static final int[] a = new int[EnumDirection.values().length]; + + static { + try { + BlockSkull.SyntheticClass_1.a[EnumDirection.UP.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockSkull.SyntheticClass_1.a[EnumDirection.NORTH.ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockSkull.SyntheticClass_1.a[EnumDirection.SOUTH.ordinal()] = 3; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockSkull.SyntheticClass_1.a[EnumDirection.WEST.ordinal()] = 4; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockSkull.SyntheticClass_1.a[EnumDirection.EAST.ordinal()] = 5; + } catch (NoSuchFieldError ignored) { + } + + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockSlime.java b/azurite-server/src/main/java/net/minecraft/server/BlockSlime.java new file mode 100644 index 0000000..331bafa --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockSlime.java @@ -0,0 +1,39 @@ +package net.minecraft.server; + +public class BlockSlime extends BlockHalfTransparent { + + public BlockSlime() { + super(Material.CLAY, false, MaterialMapColor.c); + this.a(CreativeModeTab.c); + this.frictionFactor = 0.8F; + } + + public void fallOn(World world, BlockPosition blockposition, Entity entity, float f) { + if (entity.isSneaking()) { + super.fallOn(world, blockposition, entity, f); + } else { + entity.e(f, 0.0F); + } + + } + + public void a(World world, Entity entity) { + if (entity.isSneaking()) { + super.a(world, entity); + } else if (entity.motY < 0.0D) { + entity.motY = -entity.motY; + } + + } + + public void a(World world, BlockPosition blockposition, Entity entity) { + if (Math.abs(entity.motY) < 0.1D && !entity.isSneaking()) { + double d0 = 0.4D + Math.abs(entity.motY) * 0.2D; + + entity.motX *= d0; + entity.motZ *= d0; + } + + super.a(world, blockposition, entity); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockSlowSand.java b/azurite-server/src/main/java/net/minecraft/server/BlockSlowSand.java new file mode 100644 index 0000000..05d6ce4 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockSlowSand.java @@ -0,0 +1,18 @@ +package net.minecraft.server; + +public class BlockSlowSand extends Block { + + public BlockSlowSand() { + super(Material.SAND, MaterialMapColor.B); + this.a(CreativeModeTab.b); + } + + public AxisAlignedBB a(World world, BlockPosition blockposition, IBlockData iblockdata) { + return new AxisAlignedBB(blockposition.getX(), blockposition.getY(), blockposition.getZ(), (blockposition.getX() + 1), (float) (blockposition.getY() + 1) - 0.125F, (blockposition.getZ() + 1)); + } + + public void a(World world, BlockPosition blockposition, IBlockData iblockdata, Entity entity) { + entity.motX *= 0.4D; + entity.motZ *= 0.4D; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockSmoothBrick.java b/azurite-server/src/main/java/net/minecraft/server/BlockSmoothBrick.java new file mode 100644 index 0000000..f090891 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockSmoothBrick.java @@ -0,0 +1,79 @@ +package net.minecraft.server; + +public class BlockSmoothBrick extends Block { + + public static final BlockStateEnum VARIANT = BlockStateEnum.of("variant", BlockSmoothBrick.EnumStonebrickType.class); + public static final int b = BlockSmoothBrick.EnumStonebrickType.DEFAULT.a(); + public static final int N = BlockSmoothBrick.EnumStonebrickType.MOSSY.a(); + public static final int O = BlockSmoothBrick.EnumStonebrickType.CRACKED.a(); + public static final int P = BlockSmoothBrick.EnumStonebrickType.CHISELED.a(); + + public BlockSmoothBrick() { + super(Material.STONE); + this.j(this.blockStateList.getBlockData().set(BlockSmoothBrick.VARIANT, BlockSmoothBrick.EnumStonebrickType.DEFAULT)); + this.a(CreativeModeTab.b); + } + + public int getDropData(IBlockData iblockdata) { + return iblockdata.get(BlockSmoothBrick.VARIANT).a(); + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockSmoothBrick.VARIANT, BlockSmoothBrick.EnumStonebrickType.a(i)); + } + + public int toLegacyData(IBlockData iblockdata) { + return iblockdata.get(BlockSmoothBrick.VARIANT).a(); + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, BlockSmoothBrick.VARIANT); + } + + public enum EnumStonebrickType implements INamable { + + DEFAULT(0, "stonebrick", "default"), MOSSY(1, "mossy_stonebrick", "mossy"), CRACKED(2, "cracked_stonebrick", "cracked"), CHISELED(3, "chiseled_stonebrick", "chiseled"); + + private static final BlockSmoothBrick.EnumStonebrickType[] e = new BlockSmoothBrick.EnumStonebrickType[values().length]; + private final int f; + private final String g; + private final String h; + + EnumStonebrickType(int i, String s, String s1) { + this.f = i; + this.g = s; + this.h = s1; + } + + public int a() { + return this.f; + } + + public String toString() { + return this.g; + } + + public static BlockSmoothBrick.EnumStonebrickType a(int i) { + if (i < 0 || i >= BlockSmoothBrick.EnumStonebrickType.e.length) { + i = 0; + } + + return BlockSmoothBrick.EnumStonebrickType.e[i]; + } + + public String getName() { + return this.g; + } + + public String c() { + return this.h; + } + + static { + for (EnumStonebrickType blocksmoothbrick_enumstonebricktype : values()) { + EnumStonebrickType.e[blocksmoothbrick_enumstonebricktype.a()] = blocksmoothbrick_enumstonebricktype; + } + + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockSnow.java b/azurite-server/src/main/java/net/minecraft/server/BlockSnow.java new file mode 100644 index 0000000..f32748f --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockSnow.java @@ -0,0 +1,114 @@ +package net.minecraft.server; + +import java.util.Random; + +public class BlockSnow extends Block { + + public static final BlockStateInteger LAYERS = BlockStateInteger.of("layers", 1, 8); + + protected BlockSnow() { + super(Material.PACKED_ICE); + this.j(this.blockStateList.getBlockData().set(BlockSnow.LAYERS, 1)); + this.a(0.0F, 0.0F, 0.0F, 1.0F, 0.125F, 1.0F); + this.a(true); + this.a(CreativeModeTab.c); + this.j(); + } + + public boolean b(IBlockAccess iblockaccess, BlockPosition blockposition) { + return iblockaccess.getType(blockposition).get(BlockSnow.LAYERS) < 5; + } + + public AxisAlignedBB a(World world, BlockPosition blockposition, IBlockData iblockdata) { + int i = iblockdata.get(BlockSnow.LAYERS) - 1; + float f = 0.125F; + + return new AxisAlignedBB((double) blockposition.getX() + this.minX, (double) blockposition.getY() + this.minY, (double) blockposition.getZ() + this.minZ, (double) blockposition.getX() + this.maxX, (float) blockposition.getY() + (float) i * f, (double) blockposition.getZ() + this.maxZ); + } + + public boolean c() { + return false; + } + + public boolean d() { + return false; + } + + public void j() { + this.b(0); + } + + public void updateShape(IBlockAccess iblockaccess, BlockPosition blockposition) { + IBlockData iblockdata = iblockaccess.getType(blockposition); + + this.b(iblockdata.get(BlockSnow.LAYERS)); + } + + protected void b(int i) { + this.a(0.0F, 0.0F, 0.0F, 1.0F, (float) i / 8.0F, 1.0F); + } + + public boolean canPlace(World world, BlockPosition blockposition) { + IBlockData iblockdata = world.getType(blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()); + Block block = iblockdata.getBlock(); + + return block != Blocks.ICE && block != Blocks.PACKED_ICE && (block.getMaterial() == Material.LEAVES || (block == this && iblockdata.get(BlockSnow.LAYERS) >= 7 || block.c() && block.material.isSolid())); + } + + public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) { + this.e(world, blockposition, iblockdata); + } + + private boolean e(World world, BlockPosition blockposition, IBlockData iblockdata) { + if (!this.canPlace(world, blockposition)) { + this.b(world, blockposition, iblockdata, 0); + world.setAir(blockposition); + return false; + } else { + return true; + } + } + + public void a(World world, EntityHuman entityhuman, BlockPosition blockposition, IBlockData iblockdata, TileEntity tileentity) { + a(world, blockposition, new ItemStack(Items.SNOWBALL, iblockdata.get(BlockSnow.LAYERS) + 1, 0)); + world.setAir(blockposition); + entityhuman.b(StatisticList.MINE_BLOCK_COUNT[Block.getId(this)]); + } + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + return Items.SNOWBALL; + } + + public int a(Random random) { + return 0; + } + + public void b(World world, BlockPosition blockposition, IBlockData iblockdata, Random random) { + if (world.b(EnumSkyBlock.BLOCK, blockposition) > 11) { + // CraftBukkit start + if (org.bukkit.craftbukkit.event.CraftEventFactory.callBlockFadeEvent(world.getWorld().getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()), Blocks.AIR).isCancelled()) { + return; + } + // CraftBukkit end + this.b(world, blockposition, world.getType(blockposition), 0); + world.setAir(blockposition); + } + + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockSnow.LAYERS, (i & 7) + 1); + } + + public boolean a(World world, BlockPosition blockposition) { + return world.getType(blockposition).get(BlockSnow.LAYERS) == 1; + } + + public int toLegacyData(IBlockData iblockdata) { + return iblockdata.get(BlockSnow.LAYERS) - 1; + } + + public BlockStateList getStateList() { + return new BlockStateList(this, BlockSnow.LAYERS); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockSnowBlock.java b/azurite-server/src/main/java/net/minecraft/server/BlockSnowBlock.java new file mode 100644 index 0000000..e4604fa --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockSnowBlock.java @@ -0,0 +1,25 @@ +package net.minecraft.server; + +import java.util.Random; + +public class BlockSnowBlock extends Block { + protected BlockSnowBlock() { + super(Material.SNOW_BLOCK); + this.a(CreativeModeTab.b); + } + + public Item getDropType(IBlockData var1, Random var2, int var3) { + return Items.SNOWBALL; + } + + public int a(Random var1) { + return 4; + } + +/* public void b(World var1, BlockPosition var2, IBlockData var3, Random var4) { + if (var1.b(EnumSkyBlock.BLOCK, var2) > 11) { + this.b(var1, var2, var1.getType(var2), 0); + var1.setAir(var2); + } + }*/ +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockSoil.java b/azurite-server/src/main/java/net/minecraft/server/BlockSoil.java new file mode 100644 index 0000000..f76749f --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockSoil.java @@ -0,0 +1,133 @@ +package net.minecraft.server; + +import org.bukkit.craftbukkit.event.CraftEventFactory; +import org.bukkit.event.entity.EntityInteractEvent; + +import java.util.Iterator; +import java.util.Random; +// CraftBukkit end + +public class BlockSoil extends Block { + + public static final BlockStateInteger MOISTURE = BlockStateInteger.of("moisture", 0, 7); + + protected BlockSoil() { + super(Material.EARTH); + this.j(this.blockStateList.getBlockData().set(BlockSoil.MOISTURE, 0)); + this.a(true); + this.a(0.0F, 0.0F, 0.0F, 1.0F, 0.9375F, 1.0F); + this.e(255); + } + + public AxisAlignedBB a(World world, BlockPosition blockposition, IBlockData iblockdata) { + return new AxisAlignedBB(blockposition.getX(), blockposition.getY(), blockposition.getZ(), (blockposition.getX() + 1), (blockposition.getY() + 1), (blockposition.getZ() + 1)); + } + + public boolean c() { + return false; + } + + public boolean d() { + return false; + } + + public void b(World world, BlockPosition blockposition, IBlockData iblockdata, Random random) { + int i = iblockdata.get(BlockSoil.MOISTURE); + + if (!this.f(world, blockposition) && !world.isRainingAt(blockposition.getX(), blockposition.getY() + 1, blockposition.getZ())) { + if (i > 0) { + world.setTypeAndData(blockposition, iblockdata.set(BlockSoil.MOISTURE, i - 1), 2); + } else if (!this.e(world, blockposition)) { + // CraftBukkit start + org.bukkit.block.Block block = world.getWorld().getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()); + if (CraftEventFactory.callBlockFadeEvent(block, Blocks.DIRT).isCancelled()) { + return; + } + // CraftBukkit end + world.setTypeUpdate(blockposition, Blocks.DIRT.getBlockData()); + } + } else if (i < 7) { + world.setTypeAndData(blockposition, iblockdata.set(BlockSoil.MOISTURE, 7), 2); + } + + } + + public void fallOn(World world, BlockPosition blockposition, Entity entity, float f) { + super.fallOn(world, blockposition, entity, f); // CraftBukkit - moved here as game rules / events shouldn't affect fall damage. + if (entity instanceof EntityLiving) { + if (world.random.nextFloat() < f - 0.5F) { + if (!(entity instanceof EntityHuman) && !world.getGameRules().getBoolean("mobGriefing")) { + return; + } + + // CraftBukkit start - Interact soil + org.bukkit.event.Cancellable cancellable; + if (entity instanceof EntityHuman) { + cancellable = CraftEventFactory.callPlayerInteractEvent((EntityHuman) entity, org.bukkit.event.block.Action.PHYSICAL, blockposition, null, null); + } else { + cancellable = new EntityInteractEvent(entity.getBukkitEntity(), world.getWorld().getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ())); + world.getServer().getPluginManager().callEvent((EntityInteractEvent) cancellable); + } + + if (cancellable.isCancelled()) { + return; + } + + if (CraftEventFactory.callEntityChangeBlockEvent(entity, blockposition.getX(), blockposition.getY(), blockposition.getZ(), Blocks.DIRT, 0).isCancelled()) { + return; + } + // CraftBukkit end + + world.setTypeUpdate(blockposition, Blocks.DIRT.getBlockData()); + } + + // super.fallOn(world, blockposition, entity, f); // CraftBukkit - moved up + } + } + + private boolean e(World world, BlockPosition blockposition) { + Block block = world.getType(blockposition.getX(), blockposition.getY() + 1, blockposition.getZ()).getBlock(); + + return block instanceof BlockCrops || block instanceof BlockStem; + } + + private boolean f(World world, BlockPosition blockposition) { + Iterator iterator = BlockPosition.b(blockposition.a(-4, 0, -4), blockposition.a(4, 1, 4)).iterator(); + + BlockPosition.MutableBlockPosition blockposition_mutableblockposition; + + do { + if (!iterator.hasNext()) { + return false; + } + + blockposition_mutableblockposition = iterator.next(); + } while (world.getType(blockposition_mutableblockposition).getBlock().getMaterial() != Material.WATER); + + return true; + } + + public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) { + super.doPhysics(world, blockposition, iblockdata, block); + if (world.getType(blockposition.getX(), blockposition.getY() + 1, blockposition.getZ()).getBlock().getMaterial().isBuildable()) { + world.setTypeUpdate(blockposition, Blocks.DIRT.getBlockData()); + } + + } + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + return Blocks.DIRT.getDropType(Blocks.DIRT.getBlockData().set(BlockDirt.VARIANT, BlockDirt.EnumDirtVariant.DIRT), random, i); + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockSoil.MOISTURE, i & 7); + } + + public int toLegacyData(IBlockData iblockdata) { + return iblockdata.get(BlockSoil.MOISTURE); + } + + public BlockStateList getStateList() { + return new BlockStateList(this, BlockSoil.MOISTURE); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockSponge.java b/azurite-server/src/main/java/net/minecraft/server/BlockSponge.java new file mode 100644 index 0000000..9e80df4 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockSponge.java @@ -0,0 +1,136 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; +import dev.azurite.spigot.utils.Utils; +import dev.azurite.spigot.configs.AzuriteConfig; + +import java.util.ArrayList; +import java.util.LinkedList; + +public class BlockSponge extends Block { + + public static final BlockStateBoolean WET = BlockStateBoolean.of("wet"); + + protected BlockSponge() { + super(Material.SPONGE); + this.j(this.blockStateList.getBlockData().set(BlockSponge.WET, false)); + this.a(CreativeModeTab.b); + } + + public String getName() { + return LocaleI18n.get(this.a() + ".dry.name"); + } + + public int getDropData(IBlockData iblockdata) { + return iblockdata.get(BlockSponge.WET) ? 1 : 0; + } + + public void onPlace(World world, BlockPosition blockposition, IBlockData iblockdata) { + this.e(world, blockposition, iblockdata); + } + + public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) { + this.e(world, blockposition, iblockdata); + super.doPhysics(world, blockposition, iblockdata, block); + } + + protected void e(World world, BlockPosition blockposition, IBlockData iblockdata) { + if (!iblockdata.get(BlockSponge.WET) && e(world, blockposition)) { + world.setTypeAndData(blockposition, iblockdata.set(BlockSponge.WET, Boolean.TRUE), 2); + world.triggerEffect(2001, blockposition, Block.getId(Blocks.WATER)); + } + } + + public void remove(World world, BlockPosition blockposition, IBlockData iblockdata) { + super.remove(world, blockposition, iblockdata); + int radius = AzuriteConfig.spongeRadius.getValue(); + + if (radius > 0 && AzuriteConfig.spongePreventWaterFlow.getValue()) { + for (int searchX = -radius; searchX <= radius; searchX++) { + for (int searchY = -radius; searchY <= radius; searchY++) { + for (int searchZ = -radius; searchZ <= radius; searchZ++) { + world.applyPhysics(blockposition.a(searchX, searchY, searchZ), Blocks.AIR); + } + } + } + } + } + + private boolean e(World world, BlockPosition blockposition) { + int radius = AzuriteConfig.spongeRadius.getValue(); + + if (radius > 0) { + boolean found = false; + Chunk chunk = null; + for (int searchX = -radius; searchX <= radius; searchX++) { + for (int searchY = -radius; searchY <= radius; searchY++) { + for (int searchZ = -radius; searchZ <= radius; searchZ++) { + BlockPosition pos = blockposition.a(searchX, searchY, searchZ); + + int chunkX = pos.getX() >> 4, chunkZ = pos.getZ() >> 4; + if (Utils.isInvalidChunk(chunk, chunkX, chunkZ)) + chunk = world.getChunkAt(chunkX, chunkZ); + + if (world.getType(chunk, pos).getBlock().getMaterial() == Material.WATER) { + world.setTypeAndData(chunk, pos, Blocks.AIR.getBlockData(), 2, true, false); + found = true; + } + } + } + } + + return found; + } + + LinkedList> linkedlist = Lists.newLinkedList(); + ArrayList arraylist = Lists.newArrayList(); + + linkedlist.add(new Tuple<>(blockposition, 0)); + int i = 0; + + BlockPosition blockposition1; + + while (!linkedlist.isEmpty()) { + Tuple tuple = linkedlist.poll(); + + blockposition1 = tuple.a(); + int j = tuple.b(); + + for (EnumDirection enumdirection : EnumDirection.values()) { + BlockPosition blockposition2 = blockposition1.shift(enumdirection); + + if (world.getType(blockposition2).getBlock().getMaterial() == Material.WATER) { + world.setTypeAndData(blockposition2, Blocks.AIR.getBlockData(), 2); + arraylist.add(blockposition2); + ++i; + if (j < 6) { + linkedlist.add(new Tuple<>(blockposition2, j + 1)); + } + } + } + + if (i > 64) { + break; + } + } + + for (BlockPosition blockPosition : arraylist) { + blockposition1 = blockPosition; + world.applyPhysics(blockposition1, Blocks.AIR); + } + + return i > 0; + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockSponge.WET, (i & 1) == 1); + } + + public int toLegacyData(IBlockData iblockdata) { + return iblockdata.get(BlockSponge.WET) ? 1 : 0; + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, BlockSponge.WET); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockStainedGlass.java b/azurite-server/src/main/java/net/minecraft/server/BlockStainedGlass.java new file mode 100644 index 0000000..fe3707d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockStainedGlass.java @@ -0,0 +1,54 @@ +package net.minecraft.server; + +import java.util.Random; + +public class BlockStainedGlass extends BlockHalfTransparent { + + public static final BlockStateEnum COLOR = BlockStateEnum.of("color", EnumColor.class); + + public BlockStainedGlass(Material material) { + super(material, false); + this.j(this.blockStateList.getBlockData().set(BlockStainedGlass.COLOR, EnumColor.WHITE)); + this.a(CreativeModeTab.b); + } + + public int getDropData(IBlockData iblockdata) { + return iblockdata.get(BlockStainedGlass.COLOR).getColorIndex(); + } + + public MaterialMapColor g(IBlockData iblockdata) { + return iblockdata.get(BlockStainedGlass.COLOR).e(); + } + + public int a(Random random) { + return 0; + } + + protected boolean I() { + return true; + } + + public boolean d() { + return false; + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockStainedGlass.COLOR, EnumColor.fromColorIndex(i)); + } + + public void onPlace(World world, BlockPosition blockposition, IBlockData iblockdata) { + BlockBeacon.f(world, blockposition); + } + + public void remove(World world, BlockPosition blockposition, IBlockData iblockdata) { + BlockBeacon.f(world, blockposition); + } + + public int toLegacyData(IBlockData iblockdata) { + return iblockdata.get(BlockStainedGlass.COLOR).getColorIndex(); + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, BlockStainedGlass.COLOR); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockStainedGlassPane.java b/azurite-server/src/main/java/net/minecraft/server/BlockStainedGlassPane.java new file mode 100644 index 0000000..8f550c3 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockStainedGlassPane.java @@ -0,0 +1,40 @@ +package net.minecraft.server; + +public class BlockStainedGlassPane extends BlockThin { + + public static final BlockStateEnum COLOR = BlockStateEnum.of("color", EnumColor.class); + + public BlockStainedGlassPane() { + super(Material.SHATTERABLE, false); + this.j(this.blockStateList.getBlockData().set(BlockStainedGlassPane.NORTH, false).set(BlockStainedGlassPane.EAST, false).set(BlockStainedGlassPane.SOUTH, false).set(BlockStainedGlassPane.WEST, false).set(BlockStainedGlassPane.COLOR, EnumColor.WHITE)); + this.a(CreativeModeTab.c); + } + + public int getDropData(IBlockData iblockdata) { + return iblockdata.get(BlockStainedGlassPane.COLOR).getColorIndex(); + } + + public MaterialMapColor g(IBlockData iblockdata) { + return iblockdata.get(BlockStainedGlassPane.COLOR).e(); + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockStainedGlassPane.COLOR, EnumColor.fromColorIndex(i)); + } + + public int toLegacyData(IBlockData iblockdata) { + return iblockdata.get(BlockStainedGlassPane.COLOR).getColorIndex(); + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, BlockStainedGlassPane.NORTH, BlockStainedGlassPane.EAST, BlockStainedGlassPane.WEST, BlockStainedGlassPane.SOUTH, BlockStainedGlassPane.COLOR); + } + + public void onPlace(World world, BlockPosition blockposition, IBlockData iblockdata) { + BlockBeacon.f(world, blockposition); + } + + public void remove(World world, BlockPosition blockposition, IBlockData iblockdata) { + BlockBeacon.f(world, blockposition); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockStairs.java b/azurite-server/src/main/java/net/minecraft/server/BlockStairs.java new file mode 100644 index 0000000..8ef4973 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockStairs.java @@ -0,0 +1,520 @@ +package net.minecraft.server; + +import java.util.Arrays; +import java.util.List; +import java.util.Random; + +public class BlockStairs extends Block { + public static final BlockStateDirection FACING = BlockStateDirection.of("facing", EnumDirection.EnumDirectionLimit.HORIZONTAL); + + public static final BlockStateEnum HALF = BlockStateEnum.of("half", EnumHalf.class); + + public static final BlockStateEnum SHAPE = BlockStateEnum.of("shape", EnumStairShape.class); + + private static final int[][] O = new int[][]{{4, 5}, {5, 7}, {6, 7}, {4, 6}, {0, 1}, {1, 3}, {2, 3}, {0, 2}}; + + private final Block P; + + private final IBlockData Q; + + private boolean R; + + private int S; + + protected BlockStairs(IBlockData paramIBlockData) { + super((paramIBlockData.getBlock()).material); + j(this.blockStateList.getBlockData().set(FACING, EnumDirection.NORTH).set(HALF, EnumHalf.BOTTOM).set(SHAPE, EnumStairShape.STRAIGHT)); + this.P = paramIBlockData.getBlock(); + this.Q = paramIBlockData; + c(this.P.strength); + b(this.P.durability / 3.0F); + a(this.P.stepSound); + e(255); + a(CreativeModeTab.b); + } + + public static boolean c(Block paramBlock) { + return paramBlock instanceof BlockStairs; + } + + public static boolean a(IBlockAccess iblockaccess, int x, int y, int z, IBlockData paramIBlockData) { + IBlockData iBlockData = iblockaccess.getType(x, y, z); + Block block = iBlockData.getBlock(); + return c(block) && iBlockData.get(HALF) == paramIBlockData.get(HALF) && iBlockData.get(FACING) == paramIBlockData.get(FACING); + } + + public void updateShape(IBlockAccess iblockaccess, BlockPosition blockposition) { + if (this.R) { + a(0.5F * (this.S % 2), 0.5F * (this.S / 4 % 2), 0.5F * (this.S / 2 % 2), 0.5F + 0.5F * (this.S % 2), 0.5F + 0.5F * (this.S / 4 % 2), 0.5F + 0.5F * (this.S / 2 % 2)); + } else { + a(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + } + } + + public boolean c() { + return false; + } + + public boolean d() { + return false; + } + + public void e(IBlockAccess iblockaccess, BlockPosition blockposition) { + if (iblockaccess.getType(blockposition).get(HALF) == EnumHalf.TOP) { + a(0.0F, 0.5F, 0.0F, 1.0F, 1.0F, 1.0F); + } else { + a(0.0F, 0.0F, 0.0F, 1.0F, 0.5F, 1.0F); + } + } + + public int f(IBlockAccess iblockaccess, BlockPosition blockposition) { + IBlockData iBlockData = iblockaccess.getType(blockposition); + EnumDirection enumDirection = iBlockData.get(FACING); + EnumHalf enumHalf = iBlockData.get(HALF); + boolean bool = enumHalf == EnumHalf.TOP; + if (enumDirection == EnumDirection.EAST) { + IBlockData iBlockData1 = iblockaccess.getType(blockposition.getX() + 1, blockposition.getY(), blockposition.getZ()); + Block block = iBlockData1.getBlock(); + if (c(block) && enumHalf == iBlockData1.get(HALF)) { + EnumDirection enumDirection1 = iBlockData1.get(FACING); + if (enumDirection1 == EnumDirection.NORTH && !a(iblockaccess, blockposition.getX(), blockposition.getY(), blockposition.getZ() + 1, iBlockData)) + return bool ? 1 : 2; + if (enumDirection1 == EnumDirection.SOUTH && !a(iblockaccess, blockposition.getX(), blockposition.getY(), blockposition.getZ() - 1, iBlockData)) + return bool ? 2 : 1; + } + } else if (enumDirection == EnumDirection.WEST) { + IBlockData iBlockData1 = iblockaccess.getType(blockposition.getX() - 1, blockposition.getY(), blockposition.getZ()); + Block block = iBlockData1.getBlock(); + if (c(block) && enumHalf == iBlockData1.get(HALF)) { + EnumDirection enumDirection1 = iBlockData1.get(FACING); + if (enumDirection1 == EnumDirection.NORTH && !a(iblockaccess, blockposition.getX(), blockposition.getY(), blockposition.getZ() + 1, iBlockData)) + return bool ? 2 : 1; + if (enumDirection1 == EnumDirection.SOUTH && !a(iblockaccess, blockposition.getX(), blockposition.getY(), blockposition.getZ() - 1, iBlockData)) + return bool ? 1 : 2; + } + } else if (enumDirection == EnumDirection.SOUTH) { + IBlockData iBlockData1 = iblockaccess.getType(blockposition.getX(), blockposition.getY(), blockposition.getZ() + 1); + Block block = iBlockData1.getBlock(); + if (c(block) && enumHalf == iBlockData1.get(HALF)) { + EnumDirection enumDirection1 = iBlockData1.get(FACING); + if (enumDirection1 == EnumDirection.WEST && !a(iblockaccess, blockposition.getX() + 1, blockposition.getY(), blockposition.getZ(), iBlockData)) + return bool ? 2 : 1; + if (enumDirection1 == EnumDirection.EAST && !a(iblockaccess, blockposition.getX() - 1, blockposition.getY(), blockposition.getZ(), iBlockData)) + return bool ? 1 : 2; + } + } else if (enumDirection == EnumDirection.NORTH) { + IBlockData iBlockData1 = iblockaccess.getType(blockposition.getX(), blockposition.getY(), blockposition.getZ() - 1); + Block block = iBlockData1.getBlock(); + if (c(block) && enumHalf == iBlockData1.get(HALF)) { + EnumDirection enumDirection1 = iBlockData1.get(FACING); + if (enumDirection1 == EnumDirection.WEST && !a(iblockaccess, blockposition.getX() + 1, blockposition.getY(), blockposition.getZ(), iBlockData)) + return bool ? 1 : 2; + if (enumDirection1 == EnumDirection.EAST && !a(iblockaccess, blockposition.getX() - 1, blockposition.getY(), blockposition.getZ(), iBlockData)) + return bool ? 2 : 1; + } + } + return 0; + } + + public int g(IBlockAccess iblockaccess, BlockPosition blockposition) { + IBlockData iBlockData = iblockaccess.getType(blockposition); + EnumDirection enumDirection = iBlockData.get(FACING); + EnumHalf enumHalf = iBlockData.get(HALF); + boolean bool = enumHalf == EnumHalf.TOP; + if (enumDirection == EnumDirection.EAST) { + IBlockData iBlockData1 = iblockaccess.getType(blockposition.getX() - 1, blockposition.getY(), blockposition.getZ()); + Block block = iBlockData1.getBlock(); + if (c(block) && enumHalf == iBlockData1.get(HALF)) { + EnumDirection enumDirection1 = iBlockData1.get(FACING); + if (enumDirection1 == EnumDirection.NORTH && !a(iblockaccess, blockposition.getX(), blockposition.getY(), blockposition.getZ() - 1, iBlockData)) + return bool ? 1 : 2; + if (enumDirection1 == EnumDirection.SOUTH && !a(iblockaccess, blockposition.getX(), blockposition.getY(), blockposition.getZ() + 1, iBlockData)) + return bool ? 2 : 1; + } + } else if (enumDirection == EnumDirection.WEST) { + IBlockData iBlockData1 = iblockaccess.getType(blockposition.getX() + 1, blockposition.getY(), blockposition.getZ()); + Block block = iBlockData1.getBlock(); + if (c(block) && enumHalf == iBlockData1.get(HALF)) { + EnumDirection enumDirection1 = iBlockData1.get(FACING); + if (enumDirection1 == EnumDirection.NORTH && !a(iblockaccess, blockposition.getX(), blockposition.getY(), blockposition.getZ() - 1, iBlockData)) + return bool ? 2 : 1; + if (enumDirection1 == EnumDirection.SOUTH && !a(iblockaccess, blockposition.getX(), blockposition.getY(), blockposition.getZ() + 1, iBlockData)) + return bool ? 1 : 2; + } + } else if (enumDirection == EnumDirection.SOUTH) { + IBlockData iBlockData1 = iblockaccess.getType(blockposition.getX(), blockposition.getY(), blockposition.getZ() - 1); + Block block = iBlockData1.getBlock(); + if (c(block) && enumHalf == iBlockData1.get(HALF)) { + EnumDirection enumDirection1 = iBlockData1.get(FACING); + if (enumDirection1 == EnumDirection.WEST && !a(iblockaccess, blockposition.getX() - 1, blockposition.getY(), blockposition.getZ(), iBlockData)) + return bool ? 2 : 1; + if (enumDirection1 == EnumDirection.EAST && !a(iblockaccess, blockposition.getX() + 1, blockposition.getY(), blockposition.getZ(), iBlockData)) + return bool ? 1 : 2; + } + } else if (enumDirection == EnumDirection.NORTH) { + IBlockData iBlockData1 = iblockaccess.getType(blockposition.getX(), blockposition.getY(), blockposition.getZ() + 1); + Block block = iBlockData1.getBlock(); + if (c(block) && enumHalf == iBlockData1.get(HALF)) { + EnumDirection enumDirection1 = iBlockData1.get(FACING); + if (enumDirection1 == EnumDirection.WEST && !a(iblockaccess, blockposition.getX() - 1, blockposition.getY(), blockposition.getZ(), iBlockData)) + return bool ? 1 : 2; + if (enumDirection1 == EnumDirection.EAST && !a(iblockaccess, blockposition.getX() + 1, blockposition.getY(), blockposition.getZ(), iBlockData)) + return bool ? 2 : 1; + } + } + return 0; + } + + public boolean h(IBlockAccess iblockaccess, BlockPosition blockposition) { + IBlockData iBlockData = iblockaccess.getType(blockposition); + EnumDirection enumDirection = iBlockData.get(FACING); + EnumHalf enumHalf = iBlockData.get(HALF); + boolean bool1 = enumHalf == EnumHalf.TOP; + float f1 = 0.5F; + float f2 = 1.0F; + if (bool1) { + f1 = 0.0F; + f2 = 0.5F; + } + float f3 = 0.0F; + float f4 = 1.0F; + float f5 = 0.0F; + float f6 = 0.5F; + boolean bool2 = true; + if (enumDirection == EnumDirection.EAST) { + f3 = 0.5F; + f6 = 1.0F; + IBlockData iBlockData1 = iblockaccess.getType(blockposition.getX() + 1, blockposition.getY(), blockposition.getZ()); + Block block = iBlockData1.getBlock(); + if (c(block) && enumHalf == iBlockData1.get(HALF)) { + EnumDirection enumDirection1 = iBlockData1.get(FACING); + if (enumDirection1 == EnumDirection.NORTH && !a(iblockaccess, blockposition.getX(), blockposition.getY(), blockposition.getZ() + 1, iBlockData)) { + f6 = 0.5F; + bool2 = false; + } else if (enumDirection1 == EnumDirection.SOUTH && !a(iblockaccess, blockposition.getX(), blockposition.getY(), blockposition.getZ() - 1, iBlockData)) { + f5 = 0.5F; + bool2 = false; + } + } + } else if (enumDirection == EnumDirection.WEST) { + f4 = 0.5F; + f6 = 1.0F; + IBlockData iBlockData1 = iblockaccess.getType(blockposition.getX() - 1, blockposition.getY(), blockposition.getZ()); + Block block = iBlockData1.getBlock(); + if (c(block) && enumHalf == iBlockData1.get(HALF)) { + EnumDirection enumDirection1 = iBlockData1.get(FACING); + if (enumDirection1 == EnumDirection.NORTH && !a(iblockaccess, blockposition.getX(), blockposition.getY(), blockposition.getZ() + 1, iBlockData)) { + f6 = 0.5F; + bool2 = false; + } else if (enumDirection1 == EnumDirection.SOUTH && !a(iblockaccess, blockposition.getX(), blockposition.getY(), blockposition.getZ() - 1, iBlockData)) { + f5 = 0.5F; + bool2 = false; + } + } + } else if (enumDirection == EnumDirection.SOUTH) { + f5 = 0.5F; + f6 = 1.0F; + IBlockData iBlockData1 = iblockaccess.getType(blockposition.getX(), blockposition.getY(), blockposition.getZ() + 1); + Block block = iBlockData1.getBlock(); + if (c(block) && enumHalf == iBlockData1.get(HALF)) { + EnumDirection enumDirection1 = iBlockData1.get(FACING); + if (enumDirection1 == EnumDirection.WEST && !a(iblockaccess, blockposition.getX() + 1, blockposition.getY(), blockposition.getZ(), iBlockData)) { + f4 = 0.5F; + bool2 = false; + } else if (enumDirection1 == EnumDirection.EAST && !a(iblockaccess, blockposition.getX() - 1, blockposition.getY(), blockposition.getZ(), iBlockData)) { + f3 = 0.5F; + bool2 = false; + } + } + } else if (enumDirection == EnumDirection.NORTH) { + IBlockData iBlockData1 = iblockaccess.getType(blockposition.getX(), blockposition.getY(), blockposition.getZ() - 1); + Block block = iBlockData1.getBlock(); + if (c(block) && enumHalf == iBlockData1.get(HALF)) { + EnumDirection enumDirection1 = iBlockData1.get(FACING); + if (enumDirection1 == EnumDirection.WEST && !a(iblockaccess, blockposition.getX() + 1, blockposition.getY(), blockposition.getZ(), iBlockData)) { + f4 = 0.5F; + bool2 = false; + } else if (enumDirection1 == EnumDirection.EAST && !a(iblockaccess, blockposition.getX() - 1, blockposition.getY(), blockposition.getZ(), iBlockData)) { + f3 = 0.5F; + bool2 = false; + } + } + } + a(f3, f1, f5, f4, f2, f6); + return bool2; + } + + public boolean i(IBlockAccess iblockaccess, BlockPosition blockposition) { + IBlockData iBlockData = iblockaccess.getType(blockposition); + EnumDirection enumDirection = iBlockData.get(FACING); + EnumHalf enumHalf = iBlockData.get(HALF); + boolean bool1 = enumHalf == EnumHalf.TOP; + float f1 = 0.5F; + float f2 = 1.0F; + if (bool1) { + f1 = 0.0F; + f2 = 0.5F; + } + float f3 = 0.0F; + float f4 = 0.5F; + float f5 = 0.5F; + float f6 = 1.0F; + boolean bool2 = false; + if (enumDirection == EnumDirection.EAST) { + IBlockData iBlockData1 = iblockaccess.getType(blockposition.getX() - 1, blockposition.getY(), blockposition.getZ()); + Block block = iBlockData1.getBlock(); + if (c(block) && enumHalf == iBlockData1.get(HALF)) { + EnumDirection enumDirection1 = iBlockData1.get(FACING); + if (enumDirection1 == EnumDirection.NORTH && !a(iblockaccess, blockposition.getX(), blockposition.getY(), blockposition.getZ() - 1, iBlockData)) { + f5 = 0.0F; + f6 = 0.5F; + bool2 = true; + } else if (enumDirection1 == EnumDirection.SOUTH && !a(iblockaccess, blockposition.getX(), blockposition.getY(), blockposition.getZ() + 1, iBlockData)) { + bool2 = true; + } + } + } else if (enumDirection == EnumDirection.WEST) { + IBlockData iBlockData1 = iblockaccess.getType(blockposition.getX() + 1, blockposition.getY(), blockposition.getZ()); + Block block = iBlockData1.getBlock(); + if (c(block) && enumHalf == iBlockData1.get(HALF)) { + f3 = 0.5F; + f4 = 1.0F; + EnumDirection enumDirection1 = iBlockData1.get(FACING); + if (enumDirection1 == EnumDirection.NORTH && !a(iblockaccess, blockposition.getX(), blockposition.getY(), blockposition.getZ() - 1, iBlockData)) { + f5 = 0.0F; + f6 = 0.5F; + bool2 = true; + } else if (enumDirection1 == EnumDirection.SOUTH && !a(iblockaccess, blockposition.getX(), blockposition.getY(), blockposition.getZ() + 1, iBlockData)) { + bool2 = true; + } + } + } else if (enumDirection == EnumDirection.SOUTH) { + IBlockData iBlockData1 = iblockaccess.getType(blockposition.getX(), blockposition.getY(), blockposition.getZ() - 1); + Block block = iBlockData1.getBlock(); + if (c(block) && enumHalf == iBlockData1.get(HALF)) { + f5 = 0.0F; + f6 = 0.5F; + EnumDirection enumDirection1 = iBlockData1.get(FACING); + if (enumDirection1 == EnumDirection.WEST && !a(iblockaccess, blockposition.getX() - 1, blockposition.getY(), blockposition.getZ(), iBlockData)) { + bool2 = true; + } else if (enumDirection1 == EnumDirection.EAST && !a(iblockaccess, blockposition.getX() + 1, blockposition.getY(), blockposition.getZ(), iBlockData)) { + f3 = 0.5F; + f4 = 1.0F; + bool2 = true; + } + } + } else if (enumDirection == EnumDirection.NORTH) { + IBlockData iBlockData1 = iblockaccess.getType(blockposition.getX(), blockposition.getY(), blockposition.getZ() + 1); + Block block = iBlockData1.getBlock(); + if (c(block) && enumHalf == iBlockData1.get(HALF)) { + EnumDirection enumDirection1 = iBlockData1.get(FACING); + if (enumDirection1 == EnumDirection.WEST && !a(iblockaccess, blockposition.getX() - 1, blockposition.getY(), blockposition.getZ(), iBlockData)) { + bool2 = true; + } else if (enumDirection1 == EnumDirection.EAST && !a(iblockaccess, blockposition.getX() + 1, blockposition.getY(), blockposition.getZ(), iBlockData)) { + f3 = 0.5F; + f4 = 1.0F; + bool2 = true; + } + } + } + if (bool2) + a(f3, f1, f5, f4, f2, f6); + return bool2; + } + + public void a(World paramWorld, BlockPosition blockposition, IBlockData paramIBlockData, AxisAlignedBB paramAxisAlignedBB, List paramList, Entity paramEntity) { + e(paramWorld, blockposition); + super.a(paramWorld, blockposition, paramIBlockData, paramAxisAlignedBB, paramList, paramEntity); + boolean bool = h(paramWorld, blockposition); + super.a(paramWorld, blockposition, paramIBlockData, paramAxisAlignedBB, paramList, paramEntity); + if (bool && + i(paramWorld, blockposition)) + super.a(paramWorld, blockposition, paramIBlockData, paramAxisAlignedBB, paramList, paramEntity); + a(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + } + + public void attack(World paramWorld, BlockPosition blockposition, EntityHuman paramEntityHuman) { + this.P.attack(paramWorld, blockposition, paramEntityHuman); + } + + public void postBreak(World paramWorld, BlockPosition blockposition, IBlockData paramIBlockData) { + this.P.postBreak(paramWorld, blockposition, paramIBlockData); + } + + public float a(Entity paramEntity) { + return this.P.a(paramEntity); + } + + public int a(World paramWorld) { + return this.P.a(paramWorld); + } + + public Vec3D a(World paramWorld, BlockPosition blockposition, Entity paramEntity, Vec3D paramVec3D) { + return this.P.a(paramWorld, blockposition, paramEntity, paramVec3D); + } + + public boolean A() { + return this.P.A(); + } + + public boolean a(IBlockData paramIBlockData, boolean paramBoolean) { + return this.P.a(paramIBlockData, paramBoolean); + } + + public boolean canPlace(World paramWorld, BlockPosition blockposition) { + return this.P.canPlace(paramWorld, blockposition); + } + + public void onPlace(World paramWorld, BlockPosition blockposition, IBlockData paramIBlockData) { + doPhysics(paramWorld, blockposition, this.Q, Blocks.AIR); + this.P.onPlace(paramWorld, blockposition, this.Q); + } + + public void remove(World paramWorld, BlockPosition blockposition, IBlockData paramIBlockData) { + this.P.remove(paramWorld, blockposition, this.Q); + } + + public void a(World paramWorld, BlockPosition blockposition, Entity paramEntity) { + this.P.a(paramWorld, blockposition, paramEntity); + } + + public void b(World paramWorld, BlockPosition blockposition, IBlockData paramIBlockData, Random paramRandom) { + this.P.b(paramWorld, blockposition, paramIBlockData, paramRandom); + } + + public boolean interact(World paramWorld, BlockPosition blockposition, IBlockData paramIBlockData, EntityHuman paramEntityHuman, EnumDirection paramEnumDirection, float paramFloat1, float paramFloat2, float paramFloat3) { + return this.P.interact(paramWorld, blockposition, this.Q, paramEntityHuman, EnumDirection.DOWN, 0.0F, 0.0F, 0.0F); + } + + public void wasExploded(World paramWorld, BlockPosition blockposition, Explosion paramExplosion) { + this.P.wasExploded(paramWorld, blockposition, paramExplosion); + } + + public MaterialMapColor g(IBlockData paramIBlockData) { + return this.P.g(this.Q); + } + + public IBlockData getPlacedState(World paramWorld, BlockPosition blockposition, EnumDirection paramEnumDirection, float paramFloat1, float paramFloat2, float paramFloat3, int paramInt, EntityLiving paramEntityLiving) { + IBlockData iBlockData = super.getPlacedState(paramWorld, blockposition, paramEnumDirection, paramFloat1, paramFloat2, paramFloat3, paramInt, paramEntityLiving); + iBlockData = iBlockData.set(FACING, paramEntityLiving.getDirection()).set(SHAPE, EnumStairShape.STRAIGHT); + if (paramEnumDirection == EnumDirection.DOWN || (paramEnumDirection != EnumDirection.UP && paramFloat2 > 0.5D)) + return iBlockData.set(HALF, EnumHalf.TOP); + return iBlockData.set(HALF, EnumHalf.BOTTOM); + } + + public MovingObjectPosition a(World paramWorld, BlockPosition blockposition, Vec3D paramVec3D1, Vec3D paramVec3D2) { + MovingObjectPosition[] arrayOfMovingObjectPosition = new MovingObjectPosition[8]; + IBlockData iBlockData = paramWorld.getType(blockposition); + int i = iBlockData.get(FACING).b(); + boolean bool = iBlockData.get(HALF) == EnumHalf.TOP; + int[] arrayOfInt = O[i + (bool ? 4 : 0)]; + this.R = true; + for (byte b = 0; b < 8; b++) { + this.S = b; + if (Arrays.binarySearch(arrayOfInt, b) < 0) + arrayOfMovingObjectPosition[b] = super.a(paramWorld, blockposition, paramVec3D1, paramVec3D2); + } + for (int j : arrayOfInt) + arrayOfMovingObjectPosition[j] = null; + MovingObjectPosition movingObjectPosition = null; + double d = 0.0D; + for (MovingObjectPosition movingObjectPosition1 : arrayOfMovingObjectPosition) { + if (movingObjectPosition1 != null) { + double d1 = movingObjectPosition1.pos.distanceSquared(paramVec3D2); + if (d1 > d) { + movingObjectPosition = movingObjectPosition1; + d = d1; + } + } + } + return movingObjectPosition; + } + + public IBlockData fromLegacyData(int paramInt) { + IBlockData iBlockData = getBlockData().set(HALF, ((paramInt & 0x4) > 0) ? EnumHalf.TOP : EnumHalf.BOTTOM); + iBlockData = iBlockData.set(FACING, EnumDirection.fromType1(5 - (paramInt & 0x3))); + return iBlockData; + } + + public int toLegacyData(IBlockData paramIBlockData) { + int i = 0; + if (paramIBlockData.get(HALF) == EnumHalf.TOP) + i |= 0x4; + i |= 5 - paramIBlockData.get(FACING).a(); + return i; + } + + public IBlockData updateState(IBlockData paramIBlockData, IBlockAccess iblockaccess, BlockPosition blockposition) { + if (h(iblockaccess, blockposition)) { + switch (g(iblockaccess, blockposition)) { + case 0: + paramIBlockData = paramIBlockData.set(SHAPE, EnumStairShape.STRAIGHT); + break; + case 1: + paramIBlockData = paramIBlockData.set(SHAPE, EnumStairShape.INNER_RIGHT); + break; + case 2: + paramIBlockData = paramIBlockData.set(SHAPE, EnumStairShape.INNER_LEFT); + break; + } + } else { + switch (f(iblockaccess, blockposition)) { + case 0: + paramIBlockData = paramIBlockData.set(SHAPE, EnumStairShape.STRAIGHT); + break; + case 1: + paramIBlockData = paramIBlockData.set(SHAPE, EnumStairShape.OUTER_RIGHT); + break; + case 2: + paramIBlockData = paramIBlockData.set(SHAPE, EnumStairShape.OUTER_LEFT); + break; + } + } + return paramIBlockData; + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, FACING, HALF, SHAPE); + } + + public enum EnumHalf implements INamable { + TOP("top"), + BOTTOM("bottom"); + + private final String c; + + EnumHalf(String param1String1) { + this.c = param1String1; + } + + public String toString() { + return this.c; + } + + public String getName() { + return this.c; + } + } + + public enum EnumStairShape implements INamable { + STRAIGHT("straight"), + INNER_LEFT("inner_left"), + INNER_RIGHT("inner_right"), + OUTER_LEFT("outer_left"), + OUTER_RIGHT("outer_right"); + + private final String f; + + EnumStairShape(String param1String1) { + this.f = param1String1; + } + + public String toString() { + return this.f; + } + + public String getName() { + return this.f; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockState.java b/azurite-server/src/main/java/net/minecraft/server/BlockState.java new file mode 100644 index 0000000..4202a2f --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockState.java @@ -0,0 +1,60 @@ +package net.minecraft.server; + +import com.google.common.base.Objects; +import net.techcable.tacospigot.BlockStateRegistry; + +public abstract class BlockState> implements IBlockState { + + private final Class a; + private final String b; + private int id = -1; + + protected BlockState(String s, Class oclass) { + this.a = oclass; + this.b = s; + } + + // TacoSpigot start + @Override + public int getId() { + assert id >= 0 : "Id not initialized"; + return id; + } + + @Override + public void tryInitId() { + if (id < 0) { + this.id = BlockStateRegistry.getId(this); + } + } + // TacoSpigot end + + + public String a() { + return this.b; + } + + public Class b() { + return this.a; + } + + public String toString() { + return Objects.toStringHelper(this).add("name", this.b).add("clazz", this.a).add("values", this.c()).toString(); + } + + public boolean equals(Object object) { + if (this == object) { + return true; + } else if (object != null && this.getClass() == object.getClass()) { + BlockState blockstate = (BlockState) object; + + return this.a.equals(blockstate.a) && this.b.equals(blockstate.b); + } else { + return false; + } + } + + public int hashCode() { + return 31 * this.a.hashCode() + this.b.hashCode(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockStateBoolean.java b/azurite-server/src/main/java/net/minecraft/server/BlockStateBoolean.java new file mode 100644 index 0000000..46cecf7 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockStateBoolean.java @@ -0,0 +1,49 @@ +// Decompiled with: CFR 0.152 +// Class Version: 8 +package net.minecraft.server; + +import com.google.common.collect.ImmutableSet; + +import java.util.Collection; + +public class BlockStateBoolean + extends BlockState { + private final ImmutableSet a; + + protected BlockStateBoolean(String s) { + super(s, Boolean.class); + this.a = ImmutableSet.of(Boolean.TRUE, Boolean.FALSE); + } + + @Override + public int getValueId(Boolean value) { + return value ? 1 : 0; + } + + @Override + public Boolean getByValueId(int id) { + switch (id) { + case 0: { + return false; + } + case 1: { + return true; + } + } + throw new IllegalArgumentException("Invalid id: " + id); + } + + @Override + public Collection c() { + return this.a; + } + + public static BlockStateBoolean of(String s) { + return new BlockStateBoolean(s); + } + + @Override + public String a(Boolean obool) { + return obool.toString(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockStateDirection.java b/azurite-server/src/main/java/net/minecraft/server/BlockStateDirection.java new file mode 100644 index 0000000..46339a2 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockStateDirection.java @@ -0,0 +1,26 @@ +package net.minecraft.server; + +import com.google.common.base.Predicate; +import com.google.common.base.Predicates; +import com.google.common.collect.Collections2; +import com.google.common.collect.Lists; +import java.util.Collection; + +public class BlockStateDirection extends BlockStateEnum { + + protected BlockStateDirection(String s, Collection collection) { + super(s, EnumDirection.class, collection); + } + + public static BlockStateDirection of(String s) { + return of(s, Predicates.alwaysTrue()); + } + + public static BlockStateDirection of(String s, Predicate predicate) { + return a(s, Collections2.filter(Lists.newArrayList(EnumDirection.values()), predicate)); + } + + public static BlockStateDirection a(String s, Collection collection) { + return new BlockStateDirection(s, collection); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockStateEnum.java b/azurite-server/src/main/java/net/minecraft/server/BlockStateEnum.java new file mode 100644 index 0000000..9a63cba --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockStateEnum.java @@ -0,0 +1,66 @@ +package net.minecraft.server; + +import com.google.common.base.Predicate; +import com.google.common.base.Predicates; +import com.google.common.collect.Collections2; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; + +import java.util.Collection; +import java.util.Map; + +public class BlockStateEnum & INamable> extends BlockState { + private final ImmutableSet a; + + private final Map b = Maps.newHashMap(); + + protected BlockStateEnum(String paramString, Class paramClass, Collection paramCollection) { + super(paramString, paramClass); + this.a = ImmutableSet.copyOf(paramCollection); + for (Enum enum_ : paramCollection) { + String str = ((INamable)enum_).getName(); + if (this.b.containsKey(str)) + throw new IllegalArgumentException("Multiple values have the same name '" + str + "'"); + this.b.put(str, (T)enum_); + } + } + + public Collection c() { + return this.a; + } + + public String a(T paramT) { + return paramT.getName(); + } + + @Override + public int getValueId(T value) { + return value.ordinal(); + } + + @Override + public T getByValueId(int id) { + Enum[] values = this.b().getEnumConstants(); + if (id >= 0 && id < values.length) { + return (T)values[id]; + } + throw new IllegalArgumentException("Invalid id: " + id); + } + + public static & INamable> BlockStateEnum of(String paramString, Class paramClass) { + return a(paramString, paramClass, Predicates.alwaysTrue()); + } + + public static & INamable> BlockStateEnum a(String paramString, Class paramClass, Predicate paramPredicate) { + return a(paramString, paramClass, Collections2.filter(Lists.newArrayList(paramClass.getEnumConstants()), paramPredicate)); + } + + public static & INamable> BlockStateEnum of(String paramString, Class paramClass, T... paramVarArgs) { + return a(paramString, paramClass, Lists.newArrayList(paramVarArgs)); + } + + public static & INamable> BlockStateEnum a(String paramString, Class paramClass, Collection paramCollection) { + return new BlockStateEnum(paramString, paramClass, paramCollection); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockStateInteger.java b/azurite-server/src/main/java/net/minecraft/server/BlockStateInteger.java new file mode 100644 index 0000000..4febe29 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockStateInteger.java @@ -0,0 +1,92 @@ +package net.minecraft.server; + +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Sets; + +import java.util.Collection; +import java.util.HashSet; + +public class BlockStateInteger extends BlockState { + private final ImmutableSet a; + private final int min; + private final int max; + private final int range; + + @Override + public int getValueId(Integer value) { + if (value < this.min) { + throw new IllegalArgumentException("Too small: " + value); + } + if (value > this.max) { + throw new IllegalArgumentException("Too large: " + value); + } + return value - this.min; + } + + @Override + public Integer getByValueId(int id) { + if (id < 0) { + throw new IllegalArgumentException("Negative id: " + id); + } + if (id > this.range) { + throw new IllegalArgumentException("Id is out of range: " + id); + } + return id; + } + + protected BlockStateInteger(String s, int i, int j) { + super(s, Integer.class); + this.min = i; + this.max = j; + this.range = this.max - this.min; + if (i < 0) { + throw new IllegalArgumentException("Min value of " + s + " must be 0 or greater"); + } + if (j <= i) { + throw new IllegalArgumentException("Max value of " + s + " must be greater than min (" + i + ")"); + } + HashSet hashset = Sets.newHashSet(); + int k = i; + while (k <= j) { + hashset.add(k); + ++k; + } + this.a = ImmutableSet.copyOf(hashset); + } + + @Override + public Collection c() { + return this.a; + } + + @Override + public boolean equals(Object object) { + if (this == object) { + return true; + } + if (object != null && this.getClass() == object.getClass()) { + if (!super.equals(object)) { + return false; + } + BlockStateInteger blockstateinteger = (BlockStateInteger) object; + return this.a.equals(blockstateinteger.a); + } + return false; + } + + @Override + public int hashCode() { + int i = super.hashCode(); + i = 31 * i + this.a.hashCode(); + return i; + } + + public static BlockStateInteger of(String s, int i, int j) { + return new BlockStateInteger(s, i, j); + } + + @Override + public String a(Integer integer) { + return integer.toString(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockStateList.java b/azurite-server/src/main/java/net/minecraft/server/BlockStateList.java new file mode 100644 index 0000000..338c678 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockStateList.java @@ -0,0 +1,179 @@ +package net.minecraft.server; + +import com.google.common.base.Function; +import com.google.common.base.Objects; +import com.google.common.collect.*; +import net.techcable.tacospigot.ImmutableArrayMap; +import net.techcable.tacospigot.ImmutableArrayTable; + +import java.util.*; + +public class BlockStateList { + + private static final Function b = iblockstate -> iblockstate == null ? "" : iblockstate.a(); + private final Block c; + private final ImmutableList> d; + private final ImmutableList e; + + public BlockStateList(Block block, IBlockState... aiblockstate) { + this.c = block; + Arrays.sort(aiblockstate, new Comparator() { + public int a(IBlockState iblockstate, IBlockState iblockstate1) { + return iblockstate.a().compareTo(iblockstate1.a()); + } + + public int compare(Object object, Object object1) { + return this.a((IBlockState) object, (IBlockState) object1); + } + }); + for (IBlockState state : aiblockstate) state.tryInitId(); // TacoSpigot + this.d = ImmutableList.copyOf(aiblockstate); + LinkedHashMap linkedhashmap = Maps.newLinkedHashMap(); + List arraylist = Lists.newArrayList(); + Iterable> iterable = IteratorUtils.a(this.e()); + + for (List list : iterable) { + Map map = MapGeneratorUtils.b(this.d, list); + BlockData blockstatelist_blockdata = new BlockData(block, ImmutableMap.copyOf(map), null); + + linkedhashmap.put(map, blockstatelist_blockdata); + arraylist.add(blockstatelist_blockdata); + } + + for (BlockStateList.BlockData iblockdata : arraylist) { + iblockdata.a(linkedhashmap); + } + + this.e = ImmutableList.copyOf(arraylist); + } + + public ImmutableList a() { + return this.e; + } + + private List> e() { + ArrayList> arraylist = Lists.newArrayList(); + + for (int i = 0; i < this.d.size(); ++i) { + arraylist.add(((IBlockState) this.d.get(i)).c()); + } + + return arraylist; + } + + public IBlockData getBlockData() { + return this.e.get(0); + } + + public Block getBlock() { + return this.c; + } + + public Collection> d() { + return this.d; + } + + public String toString() { + return Objects.toStringHelper(this).add("block", Block.REGISTRY.c(this.c)).add("properties", Iterables.transform(this.d, BlockStateList.b)).toString(); + } + + static class BlockData extends BlockDataAbstract { + + private final Block a; + // TacoSpigot start + private final ImmutableMap b; + private final Map bAsArrayMap; + private Table c; + // TacoSpigot end + + private BlockData(Block block, ImmutableMap immutablemap) { + this.a = block; + // TacoSpigot start + this.b = immutablemap; + this.bAsArrayMap = new ImmutableArrayMap<>(IBlockState.INDEXER, immutablemap); + } + + public Collection a() { + return Collections.unmodifiableCollection(this.bAsArrayMap.keySet()); + } + + public > T get(IBlockState iblockstate) { + // TacoSpigot start - runtime check -> assertion + assert this.bAsArrayMap.containsKey(iblockstate) : "Cannot get property " + iblockstate + " as it does not exist in " + this.a.P(); + Object value = this.bAsArrayMap.get(iblockstate); + assert value == b.get(iblockstate) : "Array map gave data " + value + " and regular map gave data " + b.get(iblockstate); + assert value != null : "Null value for state " + iblockstate + " and data " + this; + assert iblockstate.b().isInstance(value) : "Value " + value + " for state " + iblockstate + " and data " + this + " not instanceof " + iblockstate.b().getTypeName(); + return (T) value; + // TacoSpigot end + } + + public , V extends T> IBlockData set(IBlockState iblockstate, V v0) { + // TacoSpigot start - runtime check -> assertion + assert iblockstate != null : "Null block state"; + assert v0 != null : "Null value for block state " + iblockstate; + assert this.bAsArrayMap.containsKey(iblockstate) : "Cannot set property " + iblockstate + " as it does not exist in " + this.a.P(); + assert iblockstate.c().contains(v0) : "Cannot set property " + iblockstate + " to " + v0 + " on block " + Block.REGISTRY.c(this.a) + ", it is not an allowed value"; + IBlockData data = this.bAsArrayMap.get(iblockstate) == v0 ? this : this.c.get(iblockstate, v0); + assert data != null : "No block data with property " + iblockstate + " and value " + v0 + " for block data " + this; + return data; + // TacoSpigot end + } + + public ImmutableMap b() { + return this.b; // TacoSpigot + } + + public Map asArrayMap() { + return bAsArrayMap; // TacoSpigot + } + + public Block getBlock() { + return this.a; + } + + public boolean equals(Object object) { + return this == object; + } + + public int hashCode() { + return this.bAsArrayMap.hashCode(); + } + + public void a(Map, BlockStateList.BlockData> map) { + if (this.c != null) { + throw new IllegalStateException(); + } else { + HashBasedTable hashbasedtable = HashBasedTable.create(); + + for (IBlockState iblockstate : this.bAsArrayMap.keySet()) { + for (Object o : iblockstate.c()) { + Comparable comparable = (Comparable) o; + + if (comparable != this.get(iblockstate)) { // TacoSpigot - use this.get(iblockstate) instead of this.bAsArrayMap.get(iblockstate) + assert map.get(this.b(iblockstate, comparable)) != null : "Map doesn't contain block data with state " + iblockstate + " and comparable " + comparable + b(iblockstate, comparable); // TacoSpigot - assert present + hashbasedtable.put(iblockstate, comparable, map.get(this.b(iblockstate, comparable))); + } + } + } + + this.c = new ImmutableArrayTable( + IBlockState.INDEXER, + (IBlockState state, Comparable value) -> state.getValueId(value), + hashbasedtable + ); + } + } + + private Map b(IBlockState iblockstate, Comparable comparable) { + HashMap hashmap = Maps.newHashMap(this.bAsArrayMap); + + hashmap.put(iblockstate, comparable); + return hashmap; + } + + BlockData(Block block, ImmutableMap immutablemap, Object object) { + this(block, immutablemap); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockStatePredicate.java b/azurite-server/src/main/java/net/minecraft/server/BlockStatePredicate.java new file mode 100644 index 0000000..a6944d0 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockStatePredicate.java @@ -0,0 +1,55 @@ +package net.minecraft.server; + +import com.google.common.base.Predicate; +import com.google.common.collect.Maps; + +import java.util.Iterator; +import java.util.Map; +import java.util.Map.Entry; + +public class BlockStatePredicate implements Predicate { + + private final BlockStateList a; + private final Map b = Maps.newHashMap(); + + private BlockStatePredicate(BlockStateList blockstatelist) { + this.a = blockstatelist; + } + + public static BlockStatePredicate a(Block block) { + return new BlockStatePredicate(block.P()); + } + + public boolean a(IBlockData iblockdata) { + if (iblockdata != null && iblockdata.getBlock().equals(this.a.getBlock())) { + Iterator> iterator = this.b.entrySet().iterator(); + + Entry entry; + Comparable comparable; + + do { + if (!iterator.hasNext()) { + return true; + } + + entry = iterator.next(); + comparable = iblockdata.get(entry.getKey()); + } while (entry.getValue().apply(comparable)); + + } + return false; + } + + public > BlockStatePredicate a(IBlockState iblockstate, Predicate predicate) { + if (!this.a.d().contains(iblockstate)) { + throw new IllegalArgumentException(this.a + " cannot support property " + iblockstate); + } else { + this.b.put(iblockstate, predicate); + return this; + } + } + + public boolean apply(IBlockData object) { + return this.a(object); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockStationary.java b/azurite-server/src/main/java/net/minecraft/server/BlockStationary.java new file mode 100644 index 0000000..534d2e3 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockStationary.java @@ -0,0 +1,94 @@ +package net.minecraft.server; + +import org.bukkit.craftbukkit.event.CraftEventFactory; + +import java.util.Random; + +public class BlockStationary extends BlockFluids { + + protected BlockStationary(Material material) { + super(material); + this.a(false); + if (material == Material.LAVA) { + this.a(true); + } + + } + + public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) { + if (!this.e(world, blockposition, iblockdata)) { + this.f(world, blockposition, iblockdata); + } + + } + + private void f(World world, BlockPosition blockposition, IBlockData iblockdata) { + BlockFlowing blockflowing = a(this.material); + + world.setTypeAndData(blockposition, blockflowing.getBlockData().set(BlockStationary.LEVEL, iblockdata.get(BlockStationary.LEVEL)), 2); + world.a(blockposition, blockflowing, this.a(world)); + } + + public void b(World world, BlockPosition blockposition, IBlockData iblockdata, Random random) { + if (this.material == Material.LAVA) { + if (world.getGameRules().getBoolean("doFireTick")) { + int i = random.nextInt(3); + + if (i > 0) { + BlockPosition blockposition1 = blockposition; + + for (int j = 0; j < i; ++j) { + blockposition1 = blockposition1.a(random.nextInt(3) - 1, 1, random.nextInt(3) - 1); + Block block = world.getType(blockposition1).getBlock(); + + if (block.material == Material.AIR) { + if (this.f(world, blockposition1)) { + // CraftBukkit start - Prevent lava putting something on fire + if (world.getType(blockposition1).getBlock() != Blocks.FIRE) { + if (CraftEventFactory.callBlockIgniteEvent(world, blockposition1.getX(), blockposition1.getY(), blockposition1.getZ(), blockposition.getX(), blockposition.getY(), blockposition.getZ()).isCancelled()) { + continue; + } + } + // CraftBukkit end + world.setTypeUpdate(blockposition1, Blocks.FIRE.getBlockData()); + return; + } + } else if (block.material.isSolid()) { + return; + } + } + } else { + for (int k = 0; k < 3; ++k) { + BlockPosition blockposition2 = blockposition.a(random.nextInt(3) - 1, 0, random.nextInt(3) - 1); + BlockPosition up = blockposition2.up(); + if (world.isEmpty(up) && this.m(world, blockposition2)) { + // CraftBukkit start - Prevent lava putting something on fire + if (world.getType(up).getBlock() != Blocks.FIRE) { + if (CraftEventFactory.callBlockIgniteEvent(world, up.getX(), up.getY(), up.getZ(), blockposition.getX(), blockposition.getY(), blockposition.getZ()).isCancelled()) { + continue; + } + } + // CraftBukkit end + world.setTypeUpdate(up, Blocks.FIRE.getBlockData()); + } + } + } + + } + } + } + + protected boolean f(World world, BlockPosition blockposition) { + for (EnumDirection enumdirection : EnumDirection.values()) { + if (this.m(world, blockposition.shift(enumdirection))) { + return true; + } + } + + return false; + } + + private boolean m(World world, BlockPosition blockposition) { + return world.getType(blockposition).getBlock().getMaterial().isBurnable(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockStem.java b/azurite-server/src/main/java/net/minecraft/server/BlockStem.java new file mode 100644 index 0000000..3e1562b --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockStem.java @@ -0,0 +1,147 @@ +package net.minecraft.server; + +import com.google.common.base.Predicate; +import org.bukkit.craftbukkit.event.CraftEventFactory; + +import java.util.Random; + +public class BlockStem extends BlockPlant implements IBlockFragilePlantElement { + + public static final BlockStateInteger AGE = BlockStateInteger.of("age", 0, 7); + public static final BlockStateDirection FACING = BlockStateDirection.of("facing", new Predicate() { + public boolean a(EnumDirection enumdirection) { + return enumdirection != EnumDirection.DOWN; + } + + public boolean apply(Object object) { + return this.a((EnumDirection) object); + } + }); + private final Block blockFruit; + + protected BlockStem(Block block) { + this.j(this.blockStateList.getBlockData().set(BlockStem.AGE, 0).set(BlockStem.FACING, EnumDirection.UP)); + this.blockFruit = block; + this.a(true); + float f = 0.125F; + + this.a(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, 0.25F, 0.5F + f); + this.a((CreativeModeTab) null); + } + + public IBlockData updateState(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { + iblockdata = iblockdata.set(BlockStem.FACING, EnumDirection.UP); + + for (EnumDirection enumdirection : EnumDirection.EnumDirectionLimit.HORIZONTAL) { + if (iblockaccess.getType(blockposition.shift(enumdirection)).getBlock() == this.blockFruit) { + iblockdata = iblockdata.set(BlockStem.FACING, enumdirection); + break; + } + } + + return iblockdata; + } + + protected boolean c(Block block) { + return block == Blocks.FARMLAND; + } + + public void b(World world, BlockPosition blockposition, IBlockData iblockdata, Random random) { + super.b(world, blockposition, iblockdata, random); + if (world.isLightLevel(blockposition.getX(), blockposition.getY() + 1, blockposition.getZ(), 9)) { + float f = BlockCrops.a(this, world, blockposition); + + if (random.nextInt((int) (world.growthOdds / (this == Blocks.PUMPKIN_STEM ? world.spigotConfig.pumpkinModifier : world.spigotConfig.melonModifier) * (25.0F / f)) + 1) == 0) { // Spigot + int i = iblockdata.get(BlockStem.AGE); + + if (i < 7) { + iblockdata = iblockdata.set(BlockStem.AGE, i + 1); + // world.setTypeAndData(blockposition, iblockdata, 2); // CraftBukkit + CraftEventFactory.handleBlockGrowEvent(world, blockposition.getX(), blockposition.getY(), blockposition.getZ(), this, toLegacyData(iblockdata)); // CraftBukkit + } else { + + for (EnumDirection enumdirection : EnumDirection.EnumDirectionLimit.HORIZONTAL) { + if (world.getType(blockposition.shift(enumdirection)).getBlock() == this.blockFruit) { + return; + } + } + + blockposition = blockposition.shift(EnumDirection.EnumDirectionLimit.HORIZONTAL.a(random)); + Block block = world.getType(blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()).getBlock(); + + if (world.getType(blockposition).getBlock().material == Material.AIR && (block == Blocks.FARMLAND || block == Blocks.DIRT || block == Blocks.GRASS)) { + // world.setTypeUpdate(blockposition, this.blockFruit.getBlockData()); // CraftBukkit + CraftEventFactory.handleBlockGrowEvent(world, blockposition.getX(), blockposition.getY(), blockposition.getZ(), this.blockFruit, 0); // CraftBukkit + } + } + } + + } + } + + public void g(World world, BlockPosition blockposition, IBlockData iblockdata) { + int i = iblockdata.get(BlockStem.AGE) + MathHelper.nextInt(world.random, 2, 5); + CraftEventFactory.handleBlockGrowEvent(world, blockposition.getX(), blockposition.getY(), blockposition.getZ(), this, Math.min(7, i)); // CraftBukkit + } + + public void j() { + float f = 0.125F; + + this.a(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, 0.25F, 0.5F + f); + } + + public void updateShape(IBlockAccess iblockaccess, BlockPosition blockposition) { + this.maxY = (float) (iblockaccess.getType(blockposition).get(BlockStem.AGE) * 2 + 2) / 16.0F; + float f = 0.125F; + + this.a(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, (float) this.maxY, 0.5F + f); + } + + public void dropNaturally(World world, BlockPosition blockposition, IBlockData iblockdata, float f, int i) { + super.dropNaturally(world, blockposition, iblockdata, f, i); + Item item = this.l(); + + if (item != null) { + int j = iblockdata.get(BlockStem.AGE); + + for (int k = 0; k < 3; ++k) { + if (world.random.nextInt(15) <= j) { + a(world, blockposition, new ItemStack(item)); + } + } + + } + } + + protected Item l() { + return this.blockFruit == Blocks.PUMPKIN ? Items.PUMPKIN_SEEDS : (this.blockFruit == Blocks.MELON_BLOCK ? Items.MELON_SEEDS : null); + } + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + return null; + } + + public boolean a(World world, BlockPosition blockposition, IBlockData iblockdata, boolean flag) { + return iblockdata.get(BlockStem.AGE) != 7; + } + + public boolean a(World world, Random random, BlockPosition blockposition, IBlockData iblockdata) { + return true; + } + + public void b(World world, Random random, BlockPosition blockposition, IBlockData iblockdata) { + this.g(world, blockposition, iblockdata); + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockStem.AGE, i); + } + + public int toLegacyData(IBlockData iblockdata) { + return iblockdata.get(BlockStem.AGE); + } + + public BlockStateList getStateList() { + return new BlockStateList(this, BlockStem.AGE, BlockStem.FACING); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockStep.java b/azurite-server/src/main/java/net/minecraft/server/BlockStep.java new file mode 100644 index 0000000..e69bbe0 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockStep.java @@ -0,0 +1,10 @@ +package net.minecraft.server; + +public class BlockStep extends BlockDoubleStepAbstract { + + public BlockStep() {} + + public boolean l() { + return false; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockStepAbstract.java b/azurite-server/src/main/java/net/minecraft/server/BlockStepAbstract.java new file mode 100644 index 0000000..f44ece5 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockStepAbstract.java @@ -0,0 +1,103 @@ +package net.minecraft.server; + +import java.util.List; +import java.util.Random; + +public abstract class BlockStepAbstract extends Block { + public static final BlockStateEnum HALF = BlockStateEnum.of("half", EnumSlabHalf.class); + + public BlockStepAbstract(Material paramMaterial) { + super(paramMaterial); + if (l()) { + this.r = true; + } else { + a(0.0F, 0.0F, 0.0F, 1.0F, 0.5F, 1.0F); + } + e(255); + } + + protected boolean I() { + return false; + } + + public void updateShape(IBlockAccess paramIBlockAccess, BlockPosition paramBlockPosition) { + if (l()) { + a(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + return; + } + IBlockData iBlockData = paramIBlockAccess.getType(paramBlockPosition); + if (iBlockData.getBlock() == this) + if (iBlockData.get(HALF) == EnumSlabHalf.TOP) { + a(0.0F, 0.5F, 0.0F, 1.0F, 1.0F, 1.0F); + } else { + a(0.0F, 0.0F, 0.0F, 1.0F, 0.5F, 1.0F); + } + } + + public void j() { + if (l()) { + a(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + } else { + a(0.0F, 0.0F, 0.0F, 1.0F, 0.5F, 1.0F); + } + } + + public void a(World paramWorld, BlockPosition paramBlockPosition, IBlockData paramIBlockData, AxisAlignedBB paramAxisAlignedBB, List paramList, Entity paramEntity) { + updateShape(paramWorld, paramBlockPosition); + super.a(paramWorld, paramBlockPosition, paramIBlockData, paramAxisAlignedBB, paramList, paramEntity); + } + + public boolean c() { + return l(); + } + + public IBlockData getPlacedState(World paramWorld, BlockPosition paramBlockPosition, EnumDirection paramEnumDirection, float paramFloat1, float paramFloat2, float paramFloat3, int paramInt, EntityLiving paramEntityLiving) { + IBlockData iBlockData = super.getPlacedState(paramWorld, paramBlockPosition, paramEnumDirection, paramFloat1, paramFloat2, paramFloat3, paramInt, paramEntityLiving).set(HALF, EnumSlabHalf.BOTTOM); + if (l()) + return iBlockData; + if (paramEnumDirection == EnumDirection.DOWN || (paramEnumDirection != EnumDirection.UP && paramFloat2 > 0.5D)) + return iBlockData.set(HALF, EnumSlabHalf.TOP); + return iBlockData; + } + + public int a(Random paramRandom) { + if (l()) + return 2; + return 1; + } + + public boolean d() { + return l(); + } + + public abstract String b(int paramInt); + + public int getDropData(World paramWorld, BlockPosition paramBlockPosition) { + return super.getDropData(paramWorld, paramBlockPosition) & 0x7; + } + + public abstract boolean l(); + + public abstract IBlockState n(); + + public abstract Object a(ItemStack paramItemStack); + + public enum EnumSlabHalf implements INamable { + TOP("top"), + BOTTOM("bottom"); + + private final String c; + + EnumSlabHalf(String param1String1) { + this.c = param1String1; + } + + public String toString() { + return this.c; + } + + public String getName() { + return this.c; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockStone.java b/azurite-server/src/main/java/net/minecraft/server/BlockStone.java new file mode 100644 index 0000000..9e59d11 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockStone.java @@ -0,0 +1,107 @@ +package net.minecraft.server; + +/** + * @since 11/12/2017 + */ +import java.util.Random; + +public class BlockStone extends Block { + public static final BlockStateEnum VARIANT = BlockStateEnum.of("variant", BlockStone.EnumStoneVariant.class); + + public BlockStone() { + super(Material.STONE); + this.j(this.blockStateList.getBlockData().set(VARIANT, BlockStone.EnumStoneVariant.STONE)); + this.a(CreativeModeTab.b); + } + + public String getName() { + return LocaleI18n.get(this.a() + "." + BlockStone.EnumStoneVariant.STONE.d() + ".name"); + } + + public MaterialMapColor g(IBlockData var1) { + return (var1.get(VARIANT)).c(); + } + + public Item getDropType(IBlockData var1, Random var2, int var3) { + return var1.get(VARIANT) == BlockStone.EnumStoneVariant.STONE ? Item.getItemOf(Blocks.COBBLESTONE) : Item.getItemOf(Blocks.STONE); + } + + public int getDropData(IBlockData var1) { + return (var1.get(VARIANT)).a(); + } + + public IBlockData fromLegacyData(int var1) { + return this.getBlockData().set(VARIANT, BlockStone.EnumStoneVariant.a(var1)); + } + + public int toLegacyData(IBlockData var1) { + return (var1.get(VARIANT)).a(); + } + + public BlockStateList getStateList() { + return new BlockStateList(this, new IBlockState[]{VARIANT}); + } + + public enum EnumStoneVariant implements INamable { + STONE(0, MaterialMapColor.m, "stone"), + GRANITE(1, MaterialMapColor.l, "granite"), + GRANITE_SMOOTH(2, MaterialMapColor.l, "smooth_granite", "graniteSmooth"), + DIORITE(3, MaterialMapColor.p, "diorite"), + DIORITE_SMOOTH(4, MaterialMapColor.p, "smooth_diorite", "dioriteSmooth"), + ANDESITE(5, MaterialMapColor.m, "andesite"), + ANDESITE_SMOOTH(6, MaterialMapColor.m, "smooth_andesite", "andesiteSmooth"); + + private static final BlockStone.EnumStoneVariant[] h = new BlockStone.EnumStoneVariant[values().length]; + private final int i; + private final String j; + private final String k; + private final MaterialMapColor l; + + EnumStoneVariant(int var3, MaterialMapColor var4, String var5) { + this(var3, var4, var5, var5); + } + + EnumStoneVariant(int var3, MaterialMapColor var4, String var5, String var6) { + this.i = var3; + this.j = var5; + this.k = var6; + this.l = var4; + } + + public int a() { + return this.i; + } + + public MaterialMapColor c() { + return this.l; + } + + public String toString() { + return this.j; + } + + public static BlockStone.EnumStoneVariant a(int var0) { + if (var0 < 0 || var0 >= h.length) { + var0 = 0; + } + + return h[var0]; + } + + public String getName() { + return this.j; + } + + public String d() { + return this.k; + } + + static { + for (EnumStoneVariant var3 : values()) { + h[var3.a()] = var3; + } + + } + } +} + diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockStoneButton.java b/azurite-server/src/main/java/net/minecraft/server/BlockStoneButton.java new file mode 100644 index 0000000..d07bb7c --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockStoneButton.java @@ -0,0 +1,8 @@ +package net.minecraft.server; + +public class BlockStoneButton extends BlockButtonAbstract { + + protected BlockStoneButton() { + super(false); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockStoneStep2.java b/azurite-server/src/main/java/net/minecraft/server/BlockStoneStep2.java new file mode 100644 index 0000000..e1e4081 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockStoneStep2.java @@ -0,0 +1,10 @@ +package net.minecraft.server; + +public class BlockStoneStep2 extends BlockDoubleStoneStepAbstract { + + public BlockStoneStep2() {} + + public boolean l() { + return false; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockTNT.java b/azurite-server/src/main/java/net/minecraft/server/BlockTNT.java new file mode 100644 index 0000000..5f01b3d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockTNT.java @@ -0,0 +1,111 @@ +package net.minecraft.server; + +public class BlockTNT extends Block { + + public static final BlockStateBoolean EXPLODE = BlockStateBoolean.of("explode"); + + public BlockTNT() { + super(Material.TNT); + this.j(this.blockStateList.getBlockData().set(BlockTNT.EXPLODE, false)); + this.a(CreativeModeTab.d); + } + + public void onPlace(World world, BlockPosition blockposition, IBlockData iblockdata) { + super.onPlace(world, blockposition, iblockdata); + + if (world.isBlockIndirectlyPowered(blockposition)) { + this.postBreak(world, blockposition, iblockdata.set(BlockTNT.EXPLODE, true)); + world.setAir(blockposition); + } + } + + public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) { + if (world.isBlockIndirectlyPowered(blockposition)) { + this.postBreak(world, blockposition, iblockdata.set(BlockTNT.EXPLODE, true)); + world.setAir(blockposition); + } + } + + public void wasExploded(World world, BlockPosition blockposition, Explosion explosion) { + org.bukkit.Location loc = explosion.source instanceof EntityTNTPrimed ? ((EntityTNTPrimed) explosion.source).sourceLoc : new org.bukkit.Location(world.getWorld(), blockposition.getX(), blockposition.getY(), blockposition.getZ()); // PaperSpigot + // PaperSpigot start - Fix cannons + double y = blockposition.getY(); + if (!world.paperSpigotConfig.fixCannons) y += 0.5; + EntityTNTPrimed entitytntprimed = new EntityTNTPrimed(loc, world, (float) blockposition.getX() + 0.5F, y, (float) blockposition.getZ() + 0.5F, explosion.getSource()); // PaperSpigot - add loc + // PaperSpigot end + + entitytntprimed.fuseTicks = world.random.nextInt(entitytntprimed.fuseTicks / 4) + entitytntprimed.fuseTicks / 8; + world.addEntity(entitytntprimed); + } + + public void postBreak(World world, BlockPosition blockposition, IBlockData iblockdata) { + this.a(world, blockposition, iblockdata, (EntityLiving) null); + } + + public void a(World world, BlockPosition blockposition, IBlockData iblockdata, EntityLiving entityliving) { + if (iblockdata.get(BlockTNT.EXPLODE)) { + org.bukkit.Location loc = new org.bukkit.Location(world.getWorld(), blockposition.getX(), blockposition.getY(), blockposition.getZ()); // PaperSpigot + // PaperSpigot start - Fix cannons + double y = blockposition.getY(); + if (!world.paperSpigotConfig.fixCannons) y += 0.5; + EntityTNTPrimed entitytntprimed = new EntityTNTPrimed(loc, world, (float) blockposition.getX() + 0.5F, y, (float) blockposition.getZ() + 0.5F, entityliving); // PaperSpigot - add loc + // PaperSpigot end + + world.addEntity(entitytntprimed); + world.makeSound(entitytntprimed, "game.tnt.primed", 1.0F, 1.0F); + } + } + + public boolean interact(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman, EnumDirection enumdirection, float f, float f1, float f2) { + if (entityhuman.bZ() != null) { + Item item = entityhuman.bZ().getItem(); + + if (item == Items.FLINT_AND_STEEL || item == Items.FIRE_CHARGE) { + this.a(world, blockposition, iblockdata.set(BlockTNT.EXPLODE, Boolean.TRUE), (EntityLiving) entityhuman); + world.setAir(blockposition); + if (item == Items.FLINT_AND_STEEL) { + entityhuman.bZ().damage(1, entityhuman); + } else if (!entityhuman.abilities.canInstantlyBuild) { + --entityhuman.bZ().count; + } + + return true; + } + } + + return super.interact(world, blockposition, iblockdata, entityhuman, enumdirection, f, f1, f2); + } + + public void a(World world, BlockPosition blockposition, IBlockData iblockdata, Entity entity) { + if (entity instanceof EntityArrow) { + EntityArrow entityarrow = (EntityArrow) entity; + + if (entityarrow.isBurning()) { + // CraftBukkit start + if (org.bukkit.craftbukkit.event.CraftEventFactory.callEntityChangeBlockEvent(entityarrow, blockposition.getX(), blockposition.getY(), blockposition.getZ(), Blocks.AIR, 0).isCancelled()) { + return; + } + // CraftBukkit end + this.a(world, blockposition, world.getType(blockposition).set(BlockTNT.EXPLODE, Boolean.TRUE), entityarrow.shooter instanceof EntityLiving ? (EntityLiving) entityarrow.shooter : null); + world.setAir(blockposition); + } + } + + } + + public boolean a(Explosion explosion) { + return false; + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockTNT.EXPLODE, (i & 1) > 0); + } + + public int toLegacyData(IBlockData iblockdata) { + return iblockdata.get(BlockTNT.EXPLODE) ? 1 : 0; + } + + public BlockStateList getStateList() { + return new BlockStateList(this, BlockTNT.EXPLODE); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockTallPlant.java b/azurite-server/src/main/java/net/minecraft/server/BlockTallPlant.java new file mode 100644 index 0000000..45ea45a --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockTallPlant.java @@ -0,0 +1,265 @@ +package net.minecraft.server; + +import java.util.Random; + +public class BlockTallPlant extends BlockPlant implements IBlockFragilePlantElement { + + public static final BlockStateEnum VARIANT = BlockStateEnum.of("variant", BlockTallPlant.EnumTallFlowerVariants.class); + public static final BlockStateEnum HALF = BlockStateEnum.of("half", BlockTallPlant.EnumTallPlantHalf.class); + public static final BlockStateEnum N = BlockDirectional.FACING; + + public BlockTallPlant() { + super(Material.REPLACEABLE_PLANT); + this.j(this.blockStateList.getBlockData().set(BlockTallPlant.VARIANT, BlockTallPlant.EnumTallFlowerVariants.SUNFLOWER).set(BlockTallPlant.HALF, BlockTallPlant.EnumTallPlantHalf.LOWER).set(BlockTallPlant.N, EnumDirection.NORTH)); + this.c(0.0F); + this.a(BlockTallPlant.h); + this.c("doublePlant"); + } + + public void updateShape(IBlockAccess iblockaccess, BlockPosition blockposition) { + this.a(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + } + + public BlockTallPlant.EnumTallFlowerVariants e(IBlockAccess iblockaccess, BlockPosition blockposition) { + IBlockData iblockdata = iblockaccess.getType(blockposition); + + if (iblockdata.getBlock() == this) { + iblockdata = this.updateState(iblockdata, iblockaccess, blockposition); + return iblockdata.get(BlockTallPlant.VARIANT); + } else { + return BlockTallPlant.EnumTallFlowerVariants.FERN; + } + } + + public boolean canPlace(World world, BlockPosition blockposition) { + return super.canPlace(world, blockposition) && world.isEmpty(blockposition.getX(), blockposition.getY() + 1, blockposition.getZ()); + } + + public boolean a(World world, BlockPosition blockposition) { + IBlockData iblockdata = world.getType(blockposition); + + if (iblockdata.getBlock() != this) { + return true; + } else { + BlockTallPlant.EnumTallFlowerVariants blocktallplant_enumtallflowervariants = this.updateState(iblockdata, world, blockposition).get(BlockTallPlant.VARIANT); + + return blocktallplant_enumtallflowervariants == BlockTallPlant.EnumTallFlowerVariants.FERN || blocktallplant_enumtallflowervariants == BlockTallPlant.EnumTallFlowerVariants.GRASS; + } + } + + protected void e(World world, BlockPosition blockposition, IBlockData iblockdata) { + if (!this.f(world, blockposition, iblockdata)) { + boolean flag = iblockdata.get(BlockTallPlant.HALF) == BlockTallPlant.EnumTallPlantHalf.UPPER; + BlockPosition blockposition1 = flag ? blockposition : blockposition.up(); + BlockPosition blockposition2 = flag ? blockposition.down() : blockposition; + Object object = flag ? this : world.getType(blockposition1).getBlock(); + Object object1 = flag ? world.getType(blockposition2).getBlock() : this; + + if (object == this) { + world.setTypeAndData(blockposition1, Blocks.AIR.getBlockData(), 2); + } + + if (object1 == this) { + world.setTypeAndData(blockposition2, Blocks.AIR.getBlockData(), 3); + if (!flag) { + this.b(world, blockposition2, iblockdata, 0); + } + } + + } + } + + public boolean f(World world, BlockPosition blockposition, IBlockData iblockdata) { + if (iblockdata.get(BlockTallPlant.HALF) == BlockTallPlant.EnumTallPlantHalf.UPPER) { + return world.getType(blockposition.down()).getBlock() == this; + } else { + IBlockData iblockdata1 = world.getType(blockposition.up()); + + return iblockdata1.getBlock() == this && super.f(world, blockposition, iblockdata1); + } + } + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + if (iblockdata.get(BlockTallPlant.HALF) == BlockTallPlant.EnumTallPlantHalf.UPPER) { + return null; + } else { + BlockTallPlant.EnumTallFlowerVariants blocktallplant_enumtallflowervariants = iblockdata.get(BlockTallPlant.VARIANT); + + return blocktallplant_enumtallflowervariants == BlockTallPlant.EnumTallFlowerVariants.FERN ? null : (blocktallplant_enumtallflowervariants == BlockTallPlant.EnumTallFlowerVariants.GRASS ? (random.nextInt(8) == 0 ? Items.WHEAT_SEEDS : null) : Item.getItemOf(this)); + } + } + + public int getDropData(IBlockData iblockdata) { + return iblockdata.get(BlockTallPlant.HALF) != BlockTallPlant.EnumTallPlantHalf.UPPER && iblockdata.get(BlockTallPlant.VARIANT) != BlockTallPlant.EnumTallFlowerVariants.GRASS ? iblockdata.get(BlockTallPlant.VARIANT).a() : 0; + } + + public void a(World world, BlockPosition blockposition, BlockTallPlant.EnumTallFlowerVariants blocktallplant_enumtallflowervariants, int i) { + world.setTypeAndData(blockposition, this.getBlockData().set(BlockTallPlant.HALF, BlockTallPlant.EnumTallPlantHalf.LOWER).set(BlockTallPlant.VARIANT, blocktallplant_enumtallflowervariants), i); + world.setTypeAndData(blockposition.up(), this.getBlockData().set(BlockTallPlant.HALF, BlockTallPlant.EnumTallPlantHalf.UPPER), i); + } + + public void postPlace(World world, BlockPosition blockposition, IBlockData iblockdata, EntityLiving entityliving, ItemStack itemstack) { + world.setTypeAndData(blockposition.up(), this.getBlockData().set(BlockTallPlant.HALF, BlockTallPlant.EnumTallPlantHalf.UPPER), 2); + } + + public void a(World world, EntityHuman entityhuman, BlockPosition blockposition, IBlockData iblockdata, TileEntity tileentity) { + if (entityhuman.bZ() == null || entityhuman.bZ().getItem() != Items.SHEARS || iblockdata.get(BlockTallPlant.HALF) != BlockTallPlant.EnumTallPlantHalf.LOWER || !this.b(world, blockposition, iblockdata, entityhuman)) { + super.a(world, entityhuman, blockposition, iblockdata, tileentity); + } + } + + public void a(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman) { + if (iblockdata.get(BlockTallPlant.HALF) == BlockTallPlant.EnumTallPlantHalf.UPPER) { + if (world.getType(blockposition.down()).getBlock() == this) { + if (!entityhuman.abilities.canInstantlyBuild) { + IBlockData iblockdata1 = world.getType(blockposition.down()); + BlockTallPlant.EnumTallFlowerVariants blocktallplant_enumtallflowervariants = iblockdata1.get(BlockTallPlant.VARIANT); + + if (blocktallplant_enumtallflowervariants != BlockTallPlant.EnumTallFlowerVariants.FERN && blocktallplant_enumtallflowervariants != BlockTallPlant.EnumTallFlowerVariants.GRASS) { + world.setAir(blockposition.down(), true); + } else { + if (entityhuman.bZ() != null && entityhuman.bZ().getItem() == Items.SHEARS) { + this.b(world, blockposition, iblockdata1, entityhuman); + world.setAir(blockposition.down()); + } else { + world.setAir(blockposition.down(), true); + } + } + } else { + world.setAir(blockposition.down()); + } + } + } else if (entityhuman.abilities.canInstantlyBuild && world.getType(blockposition.up()).getBlock() == this) { + world.setTypeAndData(blockposition.up(), Blocks.AIR.getBlockData(), 2); + } + + super.a(world, blockposition, iblockdata, entityhuman); + } + + private boolean b(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman) { + BlockTallPlant.EnumTallFlowerVariants blocktallplant_enumtallflowervariants = iblockdata.get(BlockTallPlant.VARIANT); + + if (blocktallplant_enumtallflowervariants != BlockTallPlant.EnumTallFlowerVariants.FERN && blocktallplant_enumtallflowervariants != BlockTallPlant.EnumTallFlowerVariants.GRASS) { + return false; + } else { + int i = (blocktallplant_enumtallflowervariants == BlockTallPlant.EnumTallFlowerVariants.GRASS ? BlockLongGrass.EnumTallGrassType.GRASS : BlockLongGrass.EnumTallGrassType.FERN).a(); + + a(world, blockposition, new ItemStack(Blocks.TALLGRASS, 2, i)); + return true; + } + } + + public int getDropData(World world, BlockPosition blockposition) { + return this.e(world, blockposition).a(); + } + + public boolean a(World world, BlockPosition blockposition, IBlockData iblockdata, boolean flag) { + BlockTallPlant.EnumTallFlowerVariants blocktallplant_enumtallflowervariants = this.e(world, blockposition); + + return blocktallplant_enumtallflowervariants != BlockTallPlant.EnumTallFlowerVariants.GRASS && blocktallplant_enumtallflowervariants != BlockTallPlant.EnumTallFlowerVariants.FERN; + } + + public boolean a(World world, Random random, BlockPosition blockposition, IBlockData iblockdata) { + return true; + } + + public void b(World world, Random random, BlockPosition blockposition, IBlockData iblockdata) { + a(world, blockposition, new ItemStack(this, 1, this.e(world, blockposition).a())); + } + + public IBlockData fromLegacyData(int i) { + return (i & 8) > 0 ? this.getBlockData().set(BlockTallPlant.HALF, BlockTallPlant.EnumTallPlantHalf.UPPER) : this.getBlockData().set(BlockTallPlant.HALF, BlockTallPlant.EnumTallPlantHalf.LOWER).set(BlockTallPlant.VARIANT, BlockTallPlant.EnumTallFlowerVariants.a(i & 7)); + } + + public IBlockData updateState(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { + if (iblockdata.get(BlockTallPlant.HALF) == BlockTallPlant.EnumTallPlantHalf.UPPER) { + IBlockData iblockdata1 = iblockaccess.getType(blockposition.down()); + + if (iblockdata1.getBlock() == this) { + iblockdata = iblockdata.set(BlockTallPlant.VARIANT, iblockdata1.get(BlockTallPlant.VARIANT)); + } + } + + return iblockdata; + } + + public int toLegacyData(IBlockData iblockdata) { + return iblockdata.get(BlockTallPlant.HALF) == BlockTallPlant.EnumTallPlantHalf.UPPER ? 8 | iblockdata.get(BlockTallPlant.N).b() : iblockdata.get(BlockTallPlant.VARIANT).a(); + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, BlockTallPlant.HALF, BlockTallPlant.VARIANT, BlockTallPlant.N); + } + + public enum EnumTallPlantHalf implements INamable { + + UPPER, LOWER; + + EnumTallPlantHalf() { + } + + public String toString() { + return this.getName(); + } + + public String getName() { + return this == BlockTallPlant.EnumTallPlantHalf.UPPER ? "upper" : "lower"; + } + } + + public enum EnumTallFlowerVariants implements INamable { + + SUNFLOWER(0, "sunflower"), SYRINGA(1, "syringa"), GRASS(2, "double_grass", "grass"), FERN(3, "double_fern", "fern"), ROSE(4, "double_rose", "rose"), PAEONIA(5, "paeonia"); + + private static final BlockTallPlant.EnumTallFlowerVariants[] g = new BlockTallPlant.EnumTallFlowerVariants[values().length]; + private final int h; + private final String i; + private final String j; + + EnumTallFlowerVariants(int i, String s) { + this(i, s, s); + } + + EnumTallFlowerVariants(int i, String s, String s1) { + this.h = i; + this.i = s; + this.j = s1; + } + + public int a() { + return this.h; + } + + public String toString() { + return this.i; + } + + public static BlockTallPlant.EnumTallFlowerVariants a(int i) { + if (i < 0 || i >= BlockTallPlant.EnumTallFlowerVariants.g.length) { + i = 0; + } + + return BlockTallPlant.EnumTallFlowerVariants.g[i]; + } + + public String getName() { + return this.i; + } + + public String c() { + return this.j; + } + + static { + BlockTallPlant.EnumTallFlowerVariants[] ablocktallplant_enumtallflowervariants = values(); + int i = ablocktallplant_enumtallflowervariants.length; + + for (int j = 0; j < i; ++j) { + BlockTallPlant.EnumTallFlowerVariants blocktallplant_enumtallflowervariants = ablocktallplant_enumtallflowervariants[j]; + + BlockTallPlant.EnumTallFlowerVariants.g[blocktallplant_enumtallflowervariants.a()] = blocktallplant_enumtallflowervariants; + } + + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockThin.java b/azurite-server/src/main/java/net/minecraft/server/BlockThin.java new file mode 100644 index 0000000..5dfcd77 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockThin.java @@ -0,0 +1,125 @@ +package net.minecraft.server; + +import java.util.List; +import java.util.Random; + +public class BlockThin extends Block { + + public static final BlockStateBoolean NORTH = BlockStateBoolean.of("north"); + public static final BlockStateBoolean EAST = BlockStateBoolean.of("east"); + public static final BlockStateBoolean SOUTH = BlockStateBoolean.of("south"); + public static final BlockStateBoolean WEST = BlockStateBoolean.of("west"); + private final boolean a; + + protected BlockThin(Material material, boolean flag) { + super(material); + this.j(this.blockStateList.getBlockData().set(BlockThin.NORTH, false).set(BlockThin.EAST, false).set(BlockThin.SOUTH, false).set(BlockThin.WEST, false)); + this.a = flag; + this.a(CreativeModeTab.c); + } + + public IBlockData updateState(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { + return iblockdata.set(BlockThin.NORTH, this.c(iblockaccess.getType(blockposition.north()).getBlock())).set(BlockThin.SOUTH, this.c(iblockaccess.getType(blockposition.south()).getBlock())).set(BlockThin.WEST, this.c(iblockaccess.getType(blockposition.west()).getBlock())).set(BlockThin.EAST, this.c(iblockaccess.getType(blockposition.east()).getBlock())); + } + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + return !this.a ? null : super.getDropType(iblockdata, random, i); + } + + public boolean c() { + return false; + } + + public boolean d() { + return false; + } + + public void a(World world, BlockPosition blockposition, IBlockData iblockdata, AxisAlignedBB axisalignedbb, List list, Entity entity) { + boolean flag = this.c(world.getType(blockposition.north()).getBlock()); + boolean flag1 = this.c(world.getType(blockposition.south()).getBlock()); + boolean flag2 = this.c(world.getType(blockposition.west()).getBlock()); + boolean flag3 = this.c(world.getType(blockposition.east()).getBlock()); + + if ((!flag2 || !flag3) && (flag2 || flag3 || flag || flag1)) { + if (flag2) { + this.a(0.0F, 0.0F, 0.4375F, 0.5F, 1.0F, 0.5625F); + super.a(world, blockposition, iblockdata, axisalignedbb, list, entity); + } else if (flag3) { + this.a(0.5F, 0.0F, 0.4375F, 1.0F, 1.0F, 0.5625F); + super.a(world, blockposition, iblockdata, axisalignedbb, list, entity); + } + } else { + this.a(0.0F, 0.0F, 0.4375F, 1.0F, 1.0F, 0.5625F); + super.a(world, blockposition, iblockdata, axisalignedbb, list, entity); + } + + if ((!flag || !flag1) && (flag2 || flag3 || flag || flag1)) { + if (flag) { + this.a(0.4375F, 0.0F, 0.0F, 0.5625F, 1.0F, 0.5F); + super.a(world, blockposition, iblockdata, axisalignedbb, list, entity); + } else if (flag1) { + this.a(0.4375F, 0.0F, 0.5F, 0.5625F, 1.0F, 1.0F); + super.a(world, blockposition, iblockdata, axisalignedbb, list, entity); + } + } else { + this.a(0.4375F, 0.0F, 0.0F, 0.5625F, 1.0F, 1.0F); + super.a(world, blockposition, iblockdata, axisalignedbb, list, entity); + } + + } + + public void j() { + this.a(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + } + + public void updateShape(IBlockAccess iblockaccess, BlockPosition blockposition) { + float f = 0.4375F; + float f1 = 0.5625F; + float f2 = 0.4375F; + float f3 = 0.5625F; + boolean flag = this.c(iblockaccess.getType(blockposition.north()).getBlock()); + boolean flag1 = this.c(iblockaccess.getType(blockposition.south()).getBlock()); + boolean flag2 = this.c(iblockaccess.getType(blockposition.west()).getBlock()); + boolean flag3 = this.c(iblockaccess.getType(blockposition.east()).getBlock()); + + if ((!flag2 || !flag3) && (flag2 || flag3 || flag || flag1)) { + if (flag2) { + f = 0.0F; + } else if (flag3) { + f1 = 1.0F; + } + } else { + f = 0.0F; + f1 = 1.0F; + } + + if ((!flag || !flag1) && (flag2 || flag3 || flag || flag1)) { + if (flag) { + f2 = 0.0F; + } else if (flag1) { + f3 = 1.0F; + } + } else { + f2 = 0.0F; + f3 = 1.0F; + } + + this.a(f, 0.0F, f2, f1, 1.0F, f3); + } + + public final boolean c(Block block) { + return block.o() || block == Blocks.GLASS || block == Blocks.STAINED_GLASS || block == Blocks.STAINED_GLASS_PANE || block instanceof BlockThin; + } + + protected boolean I() { + return true; + } + + public int toLegacyData(IBlockData iblockdata) { + return 0; + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, BlockThin.NORTH, BlockThin.EAST, BlockThin.WEST, BlockThin.SOUTH); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockTorch.java b/azurite-server/src/main/java/net/minecraft/server/BlockTorch.java new file mode 100644 index 0000000..23c54e4 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockTorch.java @@ -0,0 +1,245 @@ +package net.minecraft.server; + +import java.util.Iterator; + +public class BlockTorch extends Block { + + public static final BlockStateDirection FACING = BlockStateDirection.of("facing", enumdirection -> enumdirection != EnumDirection.DOWN); + + protected BlockTorch() { + super(Material.ORIENTABLE); + this.j(this.blockStateList.getBlockData().set(BlockTorch.FACING, EnumDirection.UP)); + this.a(true); + this.a(CreativeModeTab.c); + } + + public AxisAlignedBB a(World world, BlockPosition blockposition, IBlockData iblockdata) { + return null; + } + + public boolean c() { + return false; + } + + public boolean d() { + return false; + } + + private boolean e(World world, BlockPosition blockposition) { + if (World.a(world, blockposition)) { + return true; + } else { + Block block = world.getType(blockposition).getBlock(); + + return block instanceof BlockFence || block == Blocks.GLASS || block == Blocks.COBBLESTONE_WALL || block == Blocks.STAINED_GLASS; + } + } + + public boolean canPlace(World world, BlockPosition blockposition) { + Iterator iterator = BlockTorch.FACING.c().iterator(); + + EnumDirection enumdirection; + + do { + if (!iterator.hasNext()) { + return false; + } + + enumdirection = iterator.next(); + } while (!this.a(world, blockposition, enumdirection)); + + return true; + } + + private boolean a(World world, BlockPosition blockposition, EnumDirection enumdirection) { + BlockPosition blockposition1 = blockposition.shift(enumdirection.opposite()); + + return enumdirection.k().c() && world.d(blockposition1, true) || enumdirection.equals(EnumDirection.UP) && this.e(world, blockposition1); + } + + public IBlockData getPlacedState(World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2, int i, EntityLiving entityliving) { + if (this.a(world, blockposition, enumdirection)) { + return this.getBlockData().set(BlockTorch.FACING, enumdirection); + } else { + Iterator iterator = EnumDirection.EnumDirectionLimit.HORIZONTAL.iterator(); + + EnumDirection enumdirection1; + + do { + if (!iterator.hasNext()) { + return this.getBlockData(); + } + + enumdirection1 = iterator.next(); + } while (!world.d(blockposition.shift(enumdirection1.opposite()), true)); + + return this.getBlockData().set(BlockTorch.FACING, enumdirection1); + } + } + + public void onPlace(World world, BlockPosition blockposition, IBlockData iblockdata) { + this.f(world, blockposition, iblockdata); + } + + public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) { + this.e(world, blockposition, iblockdata); + } + + protected boolean e(World world, BlockPosition blockposition, IBlockData iblockdata) { + if (!this.f(world, blockposition, iblockdata)) { + return true; + } else { + EnumDirection enumdirection = iblockdata.get(BlockTorch.FACING); + EnumDirection.EnumAxis enumdirection_enumaxis = enumdirection.k(); + EnumDirection enumdirection1 = enumdirection.opposite(); + boolean flag = false; + + if (enumdirection_enumaxis.c() && !world.d(blockposition.shift(enumdirection1), true)) { + flag = true; + } else if (enumdirection_enumaxis.b() && !this.e(world, blockposition.shift(enumdirection1))) { + flag = true; + } + + if (flag) { + this.b(world, blockposition, iblockdata, 0); + world.setAir(blockposition); + return true; + } else { + return false; + } + } + } + + protected boolean f(World world, BlockPosition blockposition, IBlockData iblockdata) { + if (iblockdata.getBlock() == this && this.a(world, blockposition, iblockdata.get(BlockTorch.FACING))) { + return true; + } else { + if (world.getType(blockposition).getBlock() == this) { + this.b(world, blockposition, iblockdata, 0); + world.setAir(blockposition); + } + + return false; + } + } + + public MovingObjectPosition a(World world, BlockPosition blockposition, Vec3D vec3d, Vec3D vec3d1) { + EnumDirection enumdirection = world.getType(blockposition).get(BlockTorch.FACING); + float f = 0.15F; + + if (enumdirection == EnumDirection.EAST) { + this.a(0.0F, 0.2F, 0.5F - f, f * 2.0F, 0.8F, 0.5F + f); + } else if (enumdirection == EnumDirection.WEST) { + this.a(1.0F - f * 2.0F, 0.2F, 0.5F - f, 1.0F, 0.8F, 0.5F + f); + } else if (enumdirection == EnumDirection.SOUTH) { + this.a(0.5F - f, 0.2F, 0.0F, 0.5F + f, 0.8F, f * 2.0F); + } else if (enumdirection == EnumDirection.NORTH) { + this.a(0.5F - f, 0.2F, 1.0F - f * 2.0F, 0.5F + f, 0.8F, 1.0F); + } else { + f = 0.1F; + this.a(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, 0.6F, 0.5F + f); + } + + return super.a(world, blockposition, vec3d, vec3d1); + } + + public IBlockData fromLegacyData(int i) { + IBlockData iblockdata = this.getBlockData(); + + switch (i) { + case 1: + iblockdata = iblockdata.set(BlockTorch.FACING, EnumDirection.EAST); + break; + + case 2: + iblockdata = iblockdata.set(BlockTorch.FACING, EnumDirection.WEST); + break; + + case 3: + iblockdata = iblockdata.set(BlockTorch.FACING, EnumDirection.SOUTH); + break; + + case 4: + iblockdata = iblockdata.set(BlockTorch.FACING, EnumDirection.NORTH); + break; + + case 5: + default: + iblockdata = iblockdata.set(BlockTorch.FACING, EnumDirection.UP); + } + + return iblockdata; + } + + public int toLegacyData(IBlockData iblockdata) { + byte b0 = 0; + int i; + + switch (BlockTorch.SyntheticClass_1.a[iblockdata.get(BlockTorch.FACING).ordinal()]) { + case 1: + i = b0 | 1; + break; + + case 2: + i = b0 | 2; + break; + + case 3: + i = b0 | 3; + break; + + case 4: + i = b0 | 4; + break; + + case 5: + case 6: + default: + i = b0 | 5; + } + + return i; + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, BlockTorch.FACING); + } + + static class SyntheticClass_1 { + + static final int[] a = new int[EnumDirection.values().length]; + + static { + try { + BlockTorch.SyntheticClass_1.a[EnumDirection.EAST.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockTorch.SyntheticClass_1.a[EnumDirection.WEST.ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockTorch.SyntheticClass_1.a[EnumDirection.SOUTH.ordinal()] = 3; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockTorch.SyntheticClass_1.a[EnumDirection.NORTH.ordinal()] = 4; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockTorch.SyntheticClass_1.a[EnumDirection.DOWN.ordinal()] = 5; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockTorch.SyntheticClass_1.a[EnumDirection.UP.ordinal()] = 6; + } catch (NoSuchFieldError ignored) { + } + + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockTransparent.java b/azurite-server/src/main/java/net/minecraft/server/BlockTransparent.java new file mode 100644 index 0000000..eb8339f --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockTransparent.java @@ -0,0 +1,15 @@ +package net.minecraft.server; + +public class BlockTransparent extends Block { + + protected boolean R; + + protected BlockTransparent(Material material, boolean flag) { + super(material); + this.R = flag; + } + + public boolean c() { + return false; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockTrapdoor.java b/azurite-server/src/main/java/net/minecraft/server/BlockTrapdoor.java new file mode 100644 index 0000000..05da25b --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockTrapdoor.java @@ -0,0 +1,238 @@ +package net.minecraft.server; + +import org.bukkit.event.block.BlockRedstoneEvent; + +public class BlockTrapdoor extends Block { + + public static final BlockStateDirection FACING = BlockStateDirection.of("facing", EnumDirection.EnumDirectionLimit.HORIZONTAL); + public static final BlockStateBoolean OPEN = BlockStateBoolean.of("open"); + public static final BlockStateEnum HALF = BlockStateEnum.of("half", EnumTrapdoorHalf.class); + + protected BlockTrapdoor(Material material) { + super(material); + this.j(this.blockStateList.getBlockData().set(BlockTrapdoor.FACING, EnumDirection.NORTH).set(BlockTrapdoor.OPEN, false).set(BlockTrapdoor.HALF, EnumTrapdoorHalf.BOTTOM)); + this.a(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + this.a(CreativeModeTab.d); + } + + protected static EnumDirection b(int i) { + switch (i & 3) { + case 0: + return EnumDirection.NORTH; + + case 1: + return EnumDirection.SOUTH; + + case 2: + return EnumDirection.WEST; + + case 3: + default: + return EnumDirection.EAST; + } + } + + protected static int a(EnumDirection enumdirection) { + switch (SyntheticClass_1.a[enumdirection.ordinal()]) { + case 1: + return 0; + + case 2: + return 1; + + case 3: + return 2; + + case 4: + default: + return 3; + } + } + + private static boolean c(Block block) { + return block.material.k() && block.d() || block == Blocks.GLOWSTONE || block instanceof BlockStepAbstract || block instanceof BlockStairs; + } + + public boolean c() { + return false; + } + + public boolean d() { + return false; + } + + public boolean b(IBlockAccess iblockaccess, BlockPosition blockposition) { + return !iblockaccess.getType(blockposition).get(BlockTrapdoor.OPEN); + } + + public AxisAlignedBB a(World world, BlockPosition blockposition, IBlockData iblockdata) { + updateShape(world, blockposition); + return super.a(world, blockposition, iblockdata); + } + + public void updateShape(IBlockAccess iblockaccess, BlockPosition blockposition) { + d(iblockaccess.getType(blockposition)); + } + + public void j() { + this.a(0.0F, 0.40625F, 0.0F, 1.0F, 0.59375F, 1.0F); + } + + public void d(IBlockData iblockdata) { + if (iblockdata.getBlock() == this) { + if (iblockdata.get(BlockTrapdoor.HALF) == EnumTrapdoorHalf.TOP) { + a(0.0F, 0.8125F, 0.0F, 1.0F, 1.0F, 1.0F); + } else { + a(0.0F, 0.0F, 0.0F, 1.0F, 0.1875F, 1.0F); + } + + if (iblockdata.get(BlockTrapdoor.OPEN)) { + EnumDirection enumdirection = iblockdata.get(BlockTrapdoor.FACING); + + if (enumdirection == EnumDirection.NORTH) { + a(0.0F, 0.0F, 0.8125F, 1.0F, 1.0F, 1.0F); + } else if (enumdirection == EnumDirection.SOUTH) { + a(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 0.1875F); + } else if (enumdirection == EnumDirection.WEST) { + a(0.8125F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + } else if (enumdirection == EnumDirection.EAST) { + a(0.0F, 0.0F, 0.0F, 0.1875F, 1.0F, 1.0F); + } + } + + } + } + + public boolean interact(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman, EnumDirection enumdirection, float f, float f1, float f2) { + if (this.material != Material.ORE) { + iblockdata = iblockdata.a(BlockTrapdoor.OPEN); + world.setTypeAndData(blockposition, iblockdata, 2); + world.a(entityhuman, iblockdata.get(BlockTrapdoor.OPEN) ? 1003 : 1006, blockposition, 0); + } + return true; + } + + public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) { + BlockPosition blockposition1 = blockposition.shift(iblockdata.get(BlockTrapdoor.FACING).opposite()); + + if (!c(world.getType(blockposition1).getBlock())) { + world.setAir(blockposition); + this.b(world, blockposition, iblockdata, 0); + } else { + boolean flag = world.isBlockIndirectlyPowered(blockposition); + + if (flag || block.isPowerSource()) { + // CraftBukkit start + org.bukkit.World bworld = world.getWorld(); + org.bukkit.block.Block bblock = bworld.getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()); + + int power = bblock.getBlockPower(); + int oldPower = iblockdata.get(OPEN) ? 15 : 0; + + if (oldPower == 0 ^ power == 0 || block.isPowerSource()) { + BlockRedstoneEvent eventRedstone = new BlockRedstoneEvent(bblock, oldPower, power); + world.getServer().getPluginManager().callEvent(eventRedstone); + flag = eventRedstone.getNewCurrent() > 0; + } + // CraftBukkit end + boolean flag1 = iblockdata.get(BlockTrapdoor.OPEN); + + if (flag1 != flag) { + world.setTypeAndData(blockposition, iblockdata.set(BlockTrapdoor.OPEN, flag), 2); + world.a(null, flag ? 1003 : 1006, blockposition, 0); + } + } + + } + } + + public MovingObjectPosition a(World world, BlockPosition blockposition, Vec3D vec3d, Vec3D vec3d1) { + updateShape(world, blockposition); + return super.a(world, blockposition, vec3d, vec3d1); + } + + public IBlockData getPlacedState(World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2, int i, EntityLiving entityliving) { + IBlockData iblockdata = this.getBlockData(); + + if (enumdirection.k().c()) { + iblockdata = iblockdata.set(BlockTrapdoor.FACING, enumdirection).set(BlockTrapdoor.OPEN, false); + iblockdata = iblockdata.set(BlockTrapdoor.HALF, f1 > 0.5F ? EnumTrapdoorHalf.TOP : EnumTrapdoorHalf.BOTTOM); + } + + return iblockdata; + } + + public boolean canPlace(World world, BlockPosition blockposition, EnumDirection enumdirection) { + return !enumdirection.k().b() && c(world.getType(blockposition.shift(enumdirection.opposite())).getBlock()); + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockTrapdoor.FACING, b(i)).set(BlockTrapdoor.OPEN, (i & 4) != 0).set(BlockTrapdoor.HALF, (i & 8) == 0 ? EnumTrapdoorHalf.BOTTOM : EnumTrapdoorHalf.TOP); + } + + public int toLegacyData(IBlockData iblockdata) { + byte b0 = 0; + int i = b0 | a(iblockdata.get(BlockTrapdoor.FACING)); + + if (iblockdata.get(BlockTrapdoor.OPEN)) { + i |= 4; + } + + if (iblockdata.get(BlockTrapdoor.HALF) == EnumTrapdoorHalf.TOP) { + i |= 8; + } + + return i; + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, BlockTrapdoor.FACING, BlockTrapdoor.OPEN, BlockTrapdoor.HALF); + } + + public enum EnumTrapdoorHalf implements INamable { + + TOP("top"), BOTTOM("bottom"); + + private final String c; + + EnumTrapdoorHalf(String s) { + this.c = s; + } + + public String toString() { + return this.c; + } + + public String getName() { + return this.c; + } + } + + static class SyntheticClass_1 { + + static final int[] a = new int[EnumDirection.values().length]; + + static { + try { + SyntheticClass_1.a[EnumDirection.NORTH.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.a[EnumDirection.SOUTH.ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.a[EnumDirection.WEST.ordinal()] = 3; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.a[EnumDirection.EAST.ordinal()] = 4; + } catch (NoSuchFieldError ignored) { + } + + } + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockTripwire.java b/azurite-server/src/main/java/net/minecraft/server/BlockTripwire.java new file mode 100644 index 0000000..d6b6220 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockTripwire.java @@ -0,0 +1,251 @@ +package net.minecraft.server; + +import org.bukkit.event.entity.EntityInteractEvent; + +import java.util.List; +import java.util.Random; + +public class BlockTripwire extends Block { + + public static final BlockStateBoolean POWERED = BlockStateBoolean.of("powered"); + public static final BlockStateBoolean SUSPENDED = BlockStateBoolean.of("suspended"); + public static final BlockStateBoolean ATTACHED = BlockStateBoolean.of("attached"); + public static final BlockStateBoolean DISARMED = BlockStateBoolean.of("disarmed"); + public static final BlockStateBoolean NORTH = BlockStateBoolean.of("north"); + public static final BlockStateBoolean EAST = BlockStateBoolean.of("east"); + public static final BlockStateBoolean SOUTH = BlockStateBoolean.of("south"); + public static final BlockStateBoolean WEST = BlockStateBoolean.of("west"); + + public BlockTripwire() { + super(Material.ORIENTABLE); + this.j(this.blockStateList.getBlockData() + .set(BlockTripwire.POWERED, false) + .set(BlockTripwire.SUSPENDED, false) + .set(BlockTripwire.ATTACHED, false) + .set(BlockTripwire.DISARMED, false).set(BlockTripwire.NORTH, false) + .set(BlockTripwire.EAST, false) + .set(BlockTripwire.SOUTH, false) + .set(BlockTripwire.WEST, false)); + this.a(0.0F, 0.0F, 0.0F, 1.0F, 0.15625F, 1.0F); + this.a(true); + } + + public static boolean c(IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata, EnumDirection enumdirection) { + BlockPosition blockposition1 = blockposition.shift(enumdirection); + IBlockData iblockdata1 = iblockaccess.getType(blockposition1); + Block block = iblockdata1.getBlock(); + + if (block == Blocks.TRIPWIRE_HOOK) { + EnumDirection enumdirection1 = enumdirection.opposite(); + + return iblockdata1.get(BlockTripwireHook.FACING) == enumdirection1; + } else if (block == Blocks.TRIPWIRE) { + boolean flag = iblockdata.get(BlockTripwire.SUSPENDED); + boolean flag1 = iblockdata1.get(BlockTripwire.SUSPENDED); + + return flag == flag1; + } else { + return false; + } + } + + public IBlockData updateState(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { + return iblockdata.set(BlockTripwire.NORTH, c(iblockaccess, blockposition, iblockdata, EnumDirection.NORTH)).set(BlockTripwire.EAST, c(iblockaccess, blockposition, iblockdata, EnumDirection.EAST)) + .set(BlockTripwire.SOUTH, c(iblockaccess, blockposition, iblockdata, EnumDirection.SOUTH)) + .set(BlockTripwire.WEST, c(iblockaccess, blockposition, iblockdata, EnumDirection.WEST)); + } + + public AxisAlignedBB a(World world, BlockPosition blockposition, IBlockData iblockdata) { + return null; + } + + public boolean c() { + return false; + } + + public boolean d() { + return false; + } + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + return Items.STRING; + } + + public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) { + boolean flag = iblockdata.get(BlockTripwire.SUSPENDED); + boolean flag1 = !World.a(world, blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()); + + if (flag != flag1) { + this.b(world, blockposition, iblockdata, 0); + world.setAir(blockposition); + } + + } + + public void updateShape(IBlockAccess iblockaccess, BlockPosition blockposition) { + IBlockData iblockdata = iblockaccess.getType(blockposition); + boolean flag = iblockdata.get(BlockTripwire.ATTACHED); + boolean flag1 = iblockdata.get(BlockTripwire.SUSPENDED); + + if (!flag1) { + this.a(0.0F, 0.0F, 0.0F, 1.0F, 0.09375F, 1.0F); + } else if (!flag) { + this.a(0.0F, 0.0F, 0.0F, 1.0F, 0.5F, 1.0F); + } else { + this.a(0.0F, 0.0625F, 0.0F, 1.0F, 0.15625F, 1.0F); + } + + } + + public void onPlace(World world, BlockPosition blockposition, IBlockData iblockdata) { + iblockdata = iblockdata.set(BlockTripwire.SUSPENDED, !World.a(world, blockposition.getX(), blockposition.getY() - 1, blockposition.getZ())); + world.setTypeAndData(blockposition, iblockdata, 3); + this.e(world, blockposition, iblockdata); + } + + public void remove(World world, BlockPosition blockposition, IBlockData iblockdata) { + this.e(world, blockposition, iblockdata.set(BlockTripwire.POWERED, true)); + } + + public void a(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman) { + if (entityhuman.bZ() != null && entityhuman.bZ().getItem() == Items.SHEARS) { + world.setTypeAndData(blockposition, iblockdata.set(BlockTripwire.DISARMED, true), 4); + } + + } + + private void e(World world, BlockPosition blockposition, IBlockData iblockdata) { + EnumDirection[] aenumdirection = new EnumDirection[]{EnumDirection.SOUTH, EnumDirection.WEST}; + int i = aenumdirection.length; + int j = 0; + + while (j < i) { + EnumDirection enumdirection = aenumdirection[j]; + int k = 1; + + while (true) { + if (k < 42) { + BlockPosition blockposition1 = blockposition.shift(enumdirection, k); + IBlockData iblockdata1 = world.getType(blockposition1); + + if (iblockdata1.getBlock() == Blocks.TRIPWIRE_HOOK) { + if (iblockdata1.get(BlockTripwireHook.FACING) == enumdirection.opposite()) { + Blocks.TRIPWIRE_HOOK.a(world, blockposition1, iblockdata1, false, true, k, iblockdata); + } + } else if (iblockdata1.getBlock() == Blocks.TRIPWIRE) { + ++k; + continue; + } + } + + ++j; + break; + } + } + + } + + public void a(World world, BlockPosition blockposition, IBlockData iblockdata, Entity entity) { + if (!iblockdata.get(BlockTripwire.POWERED)) { + this.e(world, blockposition); + } + } + + public void b(World world, BlockPosition blockposition, IBlockData iblockdata, Random random) { + if (world.getType(blockposition).get(BlockTripwire.POWERED)) { + this.e(world, blockposition); + } + } + + private void e(World world, BlockPosition blockposition) { + IBlockData iblockdata = world.getType(blockposition); + boolean flag = iblockdata.get(BlockTripwire.POWERED); + boolean flag1 = false; + List list = world.getEntities(null, new AxisAlignedBB((double) blockposition.getX() + this.minX, (double) blockposition.getY() + this.minY, (double) blockposition.getZ() + this.minZ, (double) blockposition.getX() + this.maxX, (double) blockposition.getY() + this.maxY, (double) blockposition.getZ() + this.maxZ)); + + if (!list.isEmpty()) { + + for (Entity entity : list) { + if (!entity.aI()) { + flag1 = true; + break; + } + } + } + + // CraftBukkit start - Call interact even when triggering connected tripwire + if (flag != flag1 && flag1 && iblockdata.get(ATTACHED)) { + org.bukkit.World bworld = world.getWorld(); + org.bukkit.plugin.PluginManager manager = world.getServer().getPluginManager(); + org.bukkit.block.Block block = bworld.getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()); + boolean allowed = false; + + // If all of the events are cancelled block the tripwire trigger, else allow + for (Entity object : list) { + if (object != null) { + org.bukkit.event.Cancellable cancellable; + + if (object instanceof EntityHuman) { + cancellable = org.bukkit.craftbukkit.event.CraftEventFactory.callPlayerInteractEvent((EntityHuman) object, org.bukkit.event.block.Action.PHYSICAL, blockposition, null, null); + } else { + cancellable = new EntityInteractEvent(object.getBukkitEntity(), block); + manager.callEvent((EntityInteractEvent) cancellable); + } + if (!cancellable.isCancelled()) { + allowed = true; + break; + } + } + } + + if (!allowed) { + return; + } + } + // CraftBukkit end + + if (flag1 != flag) { + iblockdata = iblockdata.set(BlockTripwire.POWERED, flag1); + world.setTypeAndData(blockposition, iblockdata, 3); + this.e(world, blockposition, iblockdata); + } + + if (flag1) { + world.a(blockposition, this, this.a(world)); + } + + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockTripwire.POWERED, (i & 1) > 0) + .set(BlockTripwire.SUSPENDED, (i & 2) > 0 + ).set(BlockTripwire.ATTACHED, (i & 4) > 0 + ).set(BlockTripwire.DISARMED, (i & 8) > 0); + } + + public int toLegacyData(IBlockData iblockdata) { + int i = 0; + + if (iblockdata.get(BlockTripwire.POWERED)) { + i |= 1; + } + + if (iblockdata.get(BlockTripwire.SUSPENDED)) { + i |= 2; + } + + if (iblockdata.get(BlockTripwire.ATTACHED)) { + i |= 4; + } + + if (iblockdata.get(BlockTripwire.DISARMED)) { + i |= 8; + } + + return i; + } + + public BlockStateList getStateList() { + return new BlockStateList(this, BlockTripwire.POWERED, BlockTripwire.SUSPENDED, BlockTripwire.ATTACHED, BlockTripwire.DISARMED, BlockTripwire.NORTH, BlockTripwire.EAST, BlockTripwire.WEST, BlockTripwire.SOUTH); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockTripwireHook.java b/azurite-server/src/main/java/net/minecraft/server/BlockTripwireHook.java new file mode 100644 index 0000000..15c4702 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockTripwireHook.java @@ -0,0 +1,309 @@ +package net.minecraft.server; + +import com.google.common.base.Objects; +import org.bukkit.event.block.BlockRedstoneEvent; + +import java.util.Iterator; +import java.util.Random; + +public class BlockTripwireHook extends Block { + + public static final BlockStateDirection FACING = BlockStateDirection.of("facing", EnumDirection.EnumDirectionLimit.HORIZONTAL); + public static final BlockStateBoolean POWERED = BlockStateBoolean.of("powered"); + public static final BlockStateBoolean ATTACHED = BlockStateBoolean.of("attached"); + public static final BlockStateBoolean SUSPENDED = BlockStateBoolean.of("suspended"); + + public BlockTripwireHook() { + super(Material.ORIENTABLE); + this.j(this.blockStateList.getBlockData().set(BlockTripwireHook.FACING, EnumDirection.NORTH).set(BlockTripwireHook.POWERED, false).set(BlockTripwireHook.ATTACHED, false).set(BlockTripwireHook.SUSPENDED, false)); + this.a(CreativeModeTab.d); + this.a(true); + } + + public IBlockData updateState(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { + return iblockdata.set(BlockTripwireHook.SUSPENDED, !World.a(iblockaccess, blockposition.getX(), blockposition.getY() - 1, blockposition.getZ())); + } + + public AxisAlignedBB a(World world, BlockPosition blockposition, IBlockData iblockdata) { + return null; + } + + public boolean c() { + return false; + } + + public boolean d() { + return false; + } + + public boolean canPlace(World world, BlockPosition blockposition, EnumDirection enumdirection) { + return enumdirection.k().c() && world.getType(blockposition.shift(enumdirection.opposite())).getBlock().isOccluding(); + } + + public boolean canPlace(World world, BlockPosition blockposition) { + Iterator iterator = EnumDirection.EnumDirectionLimit.HORIZONTAL.iterator(); + + EnumDirection enumdirection; + + do { + if (!iterator.hasNext()) { + return false; + } + + enumdirection = iterator.next(); + } while (!world.getType(blockposition.shift(enumdirection)).getBlock().isOccluding()); + + return true; + } + + public IBlockData getPlacedState(World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2, int i, EntityLiving entityliving) { + IBlockData iblockdata = this.getBlockData().set(BlockTripwireHook.POWERED, false).set(BlockTripwireHook.ATTACHED, false).set(BlockTripwireHook.SUSPENDED, Boolean.FALSE); + + if (enumdirection.k().c()) { + iblockdata = iblockdata.set(BlockTripwireHook.FACING, enumdirection); + } + + return iblockdata; + } + + public void postPlace(World world, BlockPosition blockposition, IBlockData iblockdata, EntityLiving entityliving, ItemStack itemstack) { + this.a(world, blockposition, iblockdata, false, false, -1, null); + } + + public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) { + if (block != this) { + if (this.e(world, blockposition, iblockdata)) { + EnumDirection enumdirection = iblockdata.get(BlockTripwireHook.FACING); + + if (!world.getType(blockposition.shift(enumdirection.opposite())).getBlock().isOccluding()) { + this.b(world, blockposition, iblockdata, 0); + world.setAir(blockposition); + } + } + + } + } + + public void a(World world, BlockPosition blockposition, IBlockData iblockdata, boolean flag, boolean flag1, int i, IBlockData iblockdata1) { + EnumDirection enumdirection = iblockdata.get(BlockTripwireHook.FACING); + boolean flag2 = iblockdata.get(BlockTripwireHook.ATTACHED); + boolean flag3 = iblockdata.get(BlockTripwireHook.POWERED); + boolean flag4 = !World.a(world, blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()); + boolean flag5 = !flag; + boolean flag6 = false; + int j = 0; + IBlockData[] aiblockdata = new IBlockData[42]; + + BlockPosition blockposition1; + + for (int k = 1; k < 42; ++k) { + blockposition1 = blockposition.shift(enumdirection, k); + IBlockData iblockdata2 = world.getType(blockposition1); + + if (iblockdata2.getBlock() == Blocks.TRIPWIRE_HOOK) { + if (iblockdata2.get(BlockTripwireHook.FACING) == enumdirection.opposite()) { + j = k; + } + break; + } + + if (iblockdata2.getBlock() != Blocks.TRIPWIRE && k != i) { + aiblockdata[k] = null; + flag5 = false; + } else { + if (k == i) { + iblockdata2 = Objects.firstNonNull(iblockdata1, iblockdata2); + } + + boolean flag7 = !iblockdata2.get(BlockTripwire.DISARMED); + boolean flag8 = iblockdata2.get(BlockTripwire.POWERED); + boolean flag9 = iblockdata2.get(BlockTripwire.SUSPENDED); + + flag5 &= flag9 == flag4; + flag6 |= flag7 && flag8; + aiblockdata[k] = iblockdata2; + if (k == i) { + world.a(blockposition, this, this.a(world)); + flag5 &= flag7; + } + } + } + + flag5 &= j > 1; + flag6 &= flag5; + IBlockData iblockdata3 = this.getBlockData().set(BlockTripwireHook.ATTACHED, flag5).set(BlockTripwireHook.POWERED, flag6); + + if (j > 0) { + blockposition1 = blockposition.shift(enumdirection, j); + EnumDirection enumdirection1 = enumdirection.opposite(); + + world.setTypeAndData(blockposition1, iblockdata3.set(BlockTripwireHook.FACING, enumdirection1), 3); + this.a(world, blockposition1, enumdirection1); + this.a(world, blockposition1, flag5, flag6, flag2, flag3); + } + + // CraftBukkit start + org.bukkit.block.Block block = world.getWorld().getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()); + + BlockRedstoneEvent eventRedstone = new BlockRedstoneEvent(block, 15, 0); + world.getServer().getPluginManager().callEvent(eventRedstone); + + if (eventRedstone.getNewCurrent() > 0) { + return; + } + // CraftBukkit end + + this.a(world, blockposition, flag5, flag6, flag2, flag3); + if (!flag) { + world.setTypeAndData(blockposition, iblockdata3.set(BlockTripwireHook.FACING, enumdirection), 3); + if (flag1) { + this.a(world, blockposition, enumdirection); + } + } + + if (flag2 != flag5) { + for (int l = 1; l < j; ++l) { + BlockPosition blockposition2 = blockposition.shift(enumdirection, l); + IBlockData iblockdata4 = aiblockdata[l]; + + if (iblockdata4 != null && world.getType(blockposition2).getBlock() != Blocks.AIR) { + world.setTypeAndData(blockposition2, iblockdata4.set(BlockTripwireHook.ATTACHED, flag5), 3); + } + } + } + + } + + public void b(World world, BlockPosition blockposition, IBlockData iblockdata, Random random) { + this.a(world, blockposition, iblockdata, false, true, -1, null); + } + + private void a(World world, BlockPosition blockposition, boolean flag, boolean flag1, boolean flag2, boolean flag3) { + if (flag1 && !flag3) { + world.makeSound((double) blockposition.getX() + 0.5D, (double) blockposition.getY() + 0.1D, (double) blockposition.getZ() + 0.5D, "random.click", 0.4F, 0.6F); + } else if (!flag1 && flag3) { + world.makeSound((double) blockposition.getX() + 0.5D, (double) blockposition.getY() + 0.1D, (double) blockposition.getZ() + 0.5D, "random.click", 0.4F, 0.5F); + } else if (flag && !flag2) { + world.makeSound((double) blockposition.getX() + 0.5D, (double) blockposition.getY() + 0.1D, (double) blockposition.getZ() + 0.5D, "random.click", 0.4F, 0.7F); + } else if (!flag && flag2) { + world.makeSound((double) blockposition.getX() + 0.5D, (double) blockposition.getY() + 0.1D, (double) blockposition.getZ() + 0.5D, "random.bowhit", 0.4F, 1.2F / (world.random.nextFloat() * 0.2F + 0.9F)); + } + + } + + private void a(World world, BlockPosition blockposition, EnumDirection enumdirection) { + world.applyPhysics(blockposition, this); + world.applyPhysics(blockposition.shift(enumdirection.opposite()), this); + } + + private boolean e(World world, BlockPosition blockposition, IBlockData iblockdata) { + if (!this.canPlace(world, blockposition)) { + this.b(world, blockposition, iblockdata, 0); + world.setAir(blockposition); + return false; + } else { + return true; + } + } + + public void updateShape(IBlockAccess iblockaccess, BlockPosition blockposition) { + float f = 0.1875F; + + switch (BlockTripwireHook.SyntheticClass_1.a[iblockaccess.getType(blockposition).get(BlockTripwireHook.FACING).ordinal()]) { + case 1: + this.a(0.0F, 0.2F, 0.5F - f, f * 2.0F, 0.8F, 0.5F + f); + break; + + case 2: + this.a(1.0F - f * 2.0F, 0.2F, 0.5F - f, 1.0F, 0.8F, 0.5F + f); + break; + + case 3: + this.a(0.5F - f, 0.2F, 0.0F, 0.5F + f, 0.8F, f * 2.0F); + break; + + case 4: + this.a(0.5F - f, 0.2F, 1.0F - f * 2.0F, 0.5F + f, 0.8F, 1.0F); + } + + } + + public void remove(World world, BlockPosition blockposition, IBlockData iblockdata) { + boolean flag = iblockdata.get(BlockTripwireHook.ATTACHED); + boolean flag1 = iblockdata.get(BlockTripwireHook.POWERED); + + if (flag || flag1) { + this.a(world, blockposition, iblockdata, true, false, -1, null); + } + + if (flag1) { + world.applyPhysics(blockposition, this); + world.applyPhysics(blockposition.shift(iblockdata.get(BlockTripwireHook.FACING).opposite()), this); + } + + super.remove(world, blockposition, iblockdata); + } + + public int a(IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata, EnumDirection enumdirection) { + return iblockdata.get(BlockTripwireHook.POWERED) ? 15 : 0; + } + + public int b(IBlockAccess iblockaccess, BlockPosition blockposition, IBlockData iblockdata, EnumDirection enumdirection) { + return !iblockdata.get(BlockTripwireHook.POWERED) ? 0 : (iblockdata.get(BlockTripwireHook.FACING) == enumdirection ? 15 : 0); + } + + public boolean isPowerSource() { + return true; + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockTripwireHook.FACING, EnumDirection.fromType2(i & 3)).set(BlockTripwireHook.POWERED, (i & 8) > 0).set(BlockTripwireHook.ATTACHED, (i & 4) > 0); + } + + public int toLegacyData(IBlockData iblockdata) { + byte b0 = 0; + int i = b0 | iblockdata.get(BlockTripwireHook.FACING).b(); + + if (iblockdata.get(BlockTripwireHook.POWERED)) { + i |= 8; + } + + if (iblockdata.get(BlockTripwireHook.ATTACHED)) { + i |= 4; + } + + return i; + } + + public BlockStateList getStateList() { + return new BlockStateList(this, BlockTripwireHook.FACING, BlockTripwireHook.POWERED, BlockTripwireHook.ATTACHED, BlockTripwireHook.SUSPENDED); + } + + static class SyntheticClass_1 { + + static final int[] a = new int[EnumDirection.values().length]; + + static { + try { + BlockTripwireHook.SyntheticClass_1.a[EnumDirection.EAST.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockTripwireHook.SyntheticClass_1.a[EnumDirection.WEST.ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockTripwireHook.SyntheticClass_1.a[EnumDirection.SOUTH.ordinal()] = 3; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockTripwireHook.SyntheticClass_1.a[EnumDirection.NORTH.ordinal()] = 4; + } catch (NoSuchFieldError ignored) { + } + + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockVine.java b/azurite-server/src/main/java/net/minecraft/server/BlockVine.java new file mode 100644 index 0000000..db4f1d3 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockVine.java @@ -0,0 +1,420 @@ +package net.minecraft.server; + +import org.bukkit.craftbukkit.event.CraftEventFactory; + +import java.util.Iterator; +import java.util.Random; + +public class BlockVine extends Block { + + public static final BlockStateBoolean UP = BlockStateBoolean.of("up"); + public static final BlockStateBoolean NORTH = BlockStateBoolean.of("north"); + public static final BlockStateBoolean EAST = BlockStateBoolean.of("east"); + public static final BlockStateBoolean SOUTH = BlockStateBoolean.of("south"); + public static final BlockStateBoolean WEST = BlockStateBoolean.of("west"); + public static final BlockStateBoolean[] Q = {BlockVine.UP, BlockVine.NORTH, BlockVine.SOUTH, BlockVine.WEST, BlockVine.EAST}; + + public BlockVine() { + super(Material.REPLACEABLE_PLANT); + this.j(this.blockStateList.getBlockData().set(BlockVine.UP, false).set(BlockVine.NORTH, false).set(BlockVine.EAST, false).set(BlockVine.SOUTH, false).set(BlockVine.WEST, false)); + this.a(true); + this.a(CreativeModeTab.c); + } + + public static BlockStateBoolean getDirection(EnumDirection enumdirection) { + switch (BlockVine.SyntheticClass_1.a[enumdirection.ordinal()]) { + case 1: + return BlockVine.UP; + + case 2: + return BlockVine.NORTH; + + case 3: + return BlockVine.SOUTH; + + case 4: + return BlockVine.EAST; + + case 5: + return BlockVine.WEST; + + default: + throw new IllegalArgumentException(enumdirection + " is an invalid choice"); + } + } + + public static int d(IBlockData iblockdata) { + int i = 0; + + for (BlockStateBoolean blockstateboolean : Q) { + if (iblockdata.get(blockstateboolean)) { + ++i; + } + } + + return i; + } + + public IBlockData updateState(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) { + return iblockdata.set(BlockVine.UP, iblockaccess.getType(blockposition.getX(), blockposition.getY() + 1, blockposition.getZ()).getBlock().u()); + } + + public void j() { + this.a(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + } + + public boolean c() { + return false; + } + + public boolean d() { + return false; + } + + public boolean a(World world, BlockPosition blockposition) { + return true; + } + + public void updateShape(IBlockAccess iblockaccess, BlockPosition blockposition) { + float f1 = 1.0F; + float f2 = 1.0F; + float f3 = 1.0F; + float f4 = 0.0F; + float f5 = 0.0F; + float f6 = 0.0F; + boolean flag = false; + + if (iblockaccess.getType(blockposition).get(BlockVine.WEST)) { + f4 = 0.0625F; + f1 = 0.0F; + f2 = 0.0F; + f5 = 1.0F; + f3 = 0.0F; + f6 = 1.0F; + flag = true; + } + + if (iblockaccess.getType(blockposition).get(BlockVine.EAST)) { + f1 = Math.min(f1, 0.9375F); + f4 = 1.0F; + f2 = 0.0F; + f5 = 1.0F; + f3 = 0.0F; + f6 = 1.0F; + flag = true; + } + + if (iblockaccess.getType(blockposition).get(BlockVine.NORTH)) { + f6 = Math.max(f6, 0.0625F); + f3 = 0.0F; + f1 = 0.0F; + f4 = 1.0F; + f2 = 0.0F; + f5 = 1.0F; + flag = true; + } + + if (iblockaccess.getType(blockposition).get(BlockVine.SOUTH)) { + f3 = Math.min(f3, 0.9375F); + f6 = 1.0F; + f1 = 0.0F; + f4 = 1.0F; + f2 = 0.0F; + f5 = 1.0F; + flag = true; + } + + if (!flag && this.c(iblockaccess.getType(blockposition.getX(), blockposition.getY() + 1, blockposition.getZ()).getBlock())) { + f2 = 0.9375F; + f5 = 1.0F; + f1 = 0.0F; + f4 = 1.0F; + f3 = 0.0F; + f6 = 1.0F; + } + + this.a(f1, f2, f3, f4, f5, f6); + } + + public AxisAlignedBB a(World world, BlockPosition blockposition, IBlockData iblockdata) { + return null; + } + + public boolean canPlace(World world, BlockPosition blockposition, EnumDirection enumdirection) { + switch (BlockVine.SyntheticClass_1.a[enumdirection.ordinal()]) { + case 1: + return this.c(world.getType(blockposition.getX(), blockposition.getY() + 1, blockposition.getZ()).getBlock()); + + case 2: + case 3: + case 4: + case 5: + return this.c(world.getType(blockposition.shift(enumdirection.opposite())).getBlock()); + + default: + return false; + } + } + + private boolean c(Block block) { + return block.d() && block.material.isSolid(); + } + + private boolean e(World world, BlockPosition blockposition, IBlockData iblockdata) { + IBlockData iblockdata1 = iblockdata; + + for (EnumDirection enumdirection : EnumDirection.EnumDirectionLimit.HORIZONTAL) { + BlockStateBoolean blockstateboolean = getDirection(enumdirection); + + if (iblockdata.get(blockstateboolean) && !this.c(world.getType(blockposition.shift(enumdirection)).getBlock())) { + IBlockData iblockdata2 = world.getType(blockposition.getX(), blockposition.getY() + 1, blockposition.getZ()); + + if (iblockdata2.getBlock() != this || !iblockdata2.get(blockstateboolean)) { + iblockdata = iblockdata.set(blockstateboolean, false); + } + } + } + + if (d(iblockdata) == 0) { + return false; + } else { + if (iblockdata1 != iblockdata) { + world.setTypeAndData(blockposition, iblockdata, 2); + } + + return true; + } + } + + public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) { + if (!this.e(world, blockposition, iblockdata)) { + this.b(world, blockposition, iblockdata, 0); + world.setAir(blockposition); + } + + } + + public void b(World world, BlockPosition blockposition, IBlockData iblockdata, Random random) { + if (world.random.nextInt(4) == 0) { + byte b0 = 4; + int i = 5; + boolean flag = false; + + label188: + for (int j = -b0; j <= b0; ++j) { + for (int k = -b0; k <= b0; ++k) { + for (int l = -1; l <= 1; ++l) { + if (world.getType(blockposition.a(j, l, k)).getBlock() == this) { + --i; + if (i <= 0) { + flag = true; + break label188; + } + } + } + } + } + + EnumDirection enumdirection = EnumDirection.a(random); + BlockPosition blockposition1 = blockposition.up(); + EnumDirection enumdirection1; + + if (enumdirection == EnumDirection.UP && blockposition.getY() < 255 && world.isEmpty(blockposition1)) { + if (!flag) { + IBlockData iblockdata1 = iblockdata; + + for (EnumDirection enumDirection : EnumDirection.EnumDirectionLimit.HORIZONTAL) { + enumdirection1 = enumDirection; + if (random.nextBoolean() || !this.c(world.getType(blockposition1.shift(enumdirection1)).getBlock())) { + iblockdata1 = iblockdata1.set(getDirection(enumdirection1), Boolean.FALSE); + } + } + + if (iblockdata1.get(BlockVine.NORTH) || iblockdata1.get(BlockVine.EAST) || iblockdata1.get(BlockVine.SOUTH) || iblockdata1.get(BlockVine.WEST)) { + // CraftBukkit start - Call BlockSpreadEvent + // world.setTypeAndData(blockposition1, iblockdata1, 2); + org.bukkit.block.Block source = world.getWorld().getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()); + org.bukkit.block.Block block = world.getWorld().getBlockAt(blockposition1.getX(), blockposition1.getY(), blockposition1.getZ()); + CraftEventFactory.handleBlockSpreadEvent(block, source, this, toLegacyData(iblockdata1)); + // CraftBukkit end + } + + } + } else { + BlockPosition blockposition2; + + if (enumdirection.k().c() && !iblockdata.get(getDirection(enumdirection))) { + if (!flag) { + blockposition2 = blockposition.shift(enumdirection); + Block block = world.getType(blockposition2).getBlock(); + + if (block.material == Material.AIR) { + enumdirection1 = enumdirection.e(); + EnumDirection enumdirection2 = enumdirection.f(); + boolean flag1 = iblockdata.get(getDirection(enumdirection1)); + boolean flag2 = iblockdata.get(getDirection(enumdirection2)); + BlockPosition blockposition3 = blockposition2.shift(enumdirection1); + BlockPosition blockposition4 = blockposition2.shift(enumdirection2); + + // CraftBukkit start - Call BlockSpreadEvent + org.bukkit.block.Block source = world.getWorld().getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()); + org.bukkit.block.Block bukkitBlock = world.getWorld().getBlockAt(blockposition2.getX(), blockposition2.getY(), blockposition2.getZ()); + + if (flag1 && this.c(world.getType(blockposition3).getBlock())) { + CraftEventFactory.handleBlockSpreadEvent(bukkitBlock, source, this, toLegacyData(this.getBlockData().set(getDirection(enumdirection1), true))); + } else if (flag2 && this.c(world.getType(blockposition4).getBlock())) { + CraftEventFactory.handleBlockSpreadEvent(bukkitBlock, source, this, toLegacyData(this.getBlockData().set(getDirection(enumdirection2), true))); + } else if (flag1 && world.isEmpty(blockposition3) && this.c(world.getType(blockposition.shift(enumdirection1)).getBlock())) { + bukkitBlock = world.getWorld().getBlockAt(blockposition3.getX(), blockposition3.getY(), blockposition3.getZ()); + CraftEventFactory.handleBlockSpreadEvent(bukkitBlock, source, this, toLegacyData(this.getBlockData().set(getDirection(enumdirection.opposite()), true))); + } else if (flag2 && world.isEmpty(blockposition4) && this.c(world.getType(blockposition.shift(enumdirection2)).getBlock())) { + bukkitBlock = world.getWorld().getBlockAt(blockposition4.getX(), blockposition4.getY(), blockposition4.getZ()); + CraftEventFactory.handleBlockSpreadEvent(bukkitBlock, source, this, toLegacyData(this.getBlockData().set(getDirection(enumdirection.opposite()), true))); + } else if (this.c(world.getType(blockposition2.getX(), blockposition2.getY() + 1, blockposition2.getZ()).getBlock())) { + CraftEventFactory.handleBlockSpreadEvent(bukkitBlock, source, this, toLegacyData(this.getBlockData())); + } + // CraftBukkit end + } else if (block.material.k() && block.d()) { + world.setTypeAndData(blockposition, iblockdata.set(getDirection(enumdirection), true), 2); + } + + } + } else { + if (blockposition.getY() > 1) { + blockposition2 = blockposition.down(); + IBlockData iblockdata2 = world.getType(blockposition2); + Block block1 = iblockdata2.getBlock(); + IBlockData iblockdata3; + Iterator iterator1; + EnumDirection enumdirection3; + + if (block1.material == Material.AIR) { + iblockdata3 = iblockdata; + iterator1 = EnumDirection.EnumDirectionLimit.HORIZONTAL.iterator(); + + while (iterator1.hasNext()) { + enumdirection3 = iterator1.next(); + if (random.nextBoolean()) { + iblockdata3 = iblockdata3.set(getDirection(enumdirection3), false); + } + } + + if (iblockdata3.get(BlockVine.NORTH) || iblockdata3.get(BlockVine.EAST) || iblockdata3.get(BlockVine.SOUTH) || iblockdata3.get(BlockVine.WEST)) { + // CraftBukkit start - Call BlockSpreadEvent + // world.setTypeAndData(blockposition2, iblockdata3, 2); + org.bukkit.block.Block source = world.getWorld().getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()); + org.bukkit.block.Block bukkitBlock = world.getWorld().getBlockAt(blockposition2.getX(), blockposition2.getY(), blockposition2.getZ()); + CraftEventFactory.handleBlockSpreadEvent(bukkitBlock, source, this, toLegacyData(iblockdata3)); + // CraftBukkit end + } + } else if (block1 == this) { + iblockdata3 = iblockdata2; + iterator1 = EnumDirection.EnumDirectionLimit.HORIZONTAL.iterator(); + + while (iterator1.hasNext()) { + enumdirection3 = iterator1.next(); + BlockStateBoolean blockstateboolean = getDirection(enumdirection3); + + if (random.nextBoolean() && iblockdata.get(blockstateboolean)) { + iblockdata3 = iblockdata3.set(blockstateboolean, Boolean.TRUE); + } + } + + if (iblockdata3.get(BlockVine.NORTH) || iblockdata3.get(BlockVine.EAST) || iblockdata3.get(BlockVine.SOUTH) || iblockdata3.get(BlockVine.WEST)) { + world.setTypeAndData(blockposition2, iblockdata3, 2); + } + } + } + + } + } + } + } + + public IBlockData getPlacedState(World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2, int i, EntityLiving entityliving) { + IBlockData iblockdata = this.getBlockData().set(BlockVine.UP, false).set(BlockVine.NORTH, false).set(BlockVine.EAST, false).set(BlockVine.SOUTH, false).set(BlockVine.WEST, false); + + return enumdirection.k().c() ? iblockdata.set(getDirection(enumdirection.opposite()), true) : iblockdata; + } + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + return null; + } + + public int a(Random random) { + return 0; + } + + public void a(World world, EntityHuman entityhuman, BlockPosition blockposition, IBlockData iblockdata, TileEntity tileentity) { + if (entityhuman.bZ() != null && entityhuman.bZ().getItem() == Items.SHEARS) { + entityhuman.b(StatisticList.MINE_BLOCK_COUNT[Block.getId(this)]); + a(world, blockposition, new ItemStack(Blocks.VINE, 1, 0)); + } else { + super.a(world, entityhuman, blockposition, iblockdata, tileentity); + } + + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockVine.SOUTH, (i & 1) > 0).set(BlockVine.WEST, (i & 2) > 0).set(BlockVine.NORTH, (i & 4) > 0).set(BlockVine.EAST, (i & 8) > 0); + } + + public int toLegacyData(IBlockData iblockdata) { + int i = 0; + + if (iblockdata.get(BlockVine.SOUTH)) { + i |= 1; + } + + if (iblockdata.get(BlockVine.WEST)) { + i |= 2; + } + + if (iblockdata.get(BlockVine.NORTH)) { + i |= 4; + } + + if (iblockdata.get(BlockVine.EAST)) { + i |= 8; + } + + return i; + } + + public BlockStateList getStateList() { + return new BlockStateList(this, BlockVine.UP, BlockVine.NORTH, BlockVine.EAST, BlockVine.SOUTH, BlockVine.WEST); + } + + static class SyntheticClass_1 { + + static final int[] a = new int[EnumDirection.values().length]; + + static { + try { + BlockVine.SyntheticClass_1.a[EnumDirection.UP.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockVine.SyntheticClass_1.a[EnumDirection.NORTH.ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockVine.SyntheticClass_1.a[EnumDirection.SOUTH.ordinal()] = 3; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockVine.SyntheticClass_1.a[EnumDirection.EAST.ordinal()] = 4; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockVine.SyntheticClass_1.a[EnumDirection.WEST.ordinal()] = 5; + } catch (NoSuchFieldError ignored) { + } + + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockWallSign.java b/azurite-server/src/main/java/net/minecraft/server/BlockWallSign.java new file mode 100644 index 0000000..4a69854 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockWallSign.java @@ -0,0 +1,95 @@ +package net.minecraft.server; + +public class BlockWallSign extends BlockSign { + + public static final BlockStateDirection FACING = BlockStateDirection.of("facing", EnumDirection.EnumDirectionLimit.HORIZONTAL); + + public BlockWallSign() { + this.j(this.blockStateList.getBlockData().set(BlockWallSign.FACING, EnumDirection.NORTH)); + } + + public void updateShape(IBlockAccess iblockaccess, BlockPosition blockposition) { + EnumDirection enumdirection = iblockaccess.getType(blockposition).get(BlockWallSign.FACING); + float f = 0.28125F; + float f1 = 0.78125F; + float f2 = 0.0F; + float f3 = 1.0F; + float f4 = 0.125F; + + this.a(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + switch (BlockWallSign.SyntheticClass_1.a[enumdirection.ordinal()]) { + case 1: + this.a(f2, f, 1.0F - f4, f3, f1, 1.0F); + break; + + case 2: + this.a(f2, f, 0.0F, f3, f1, f4); + break; + + case 3: + this.a(1.0F - f4, f, f2, 1.0F, f1, f3); + break; + + case 4: + this.a(0.0F, f, f2, f4, f1, f3); + } + + } + + public void doPhysics(World world, BlockPosition blockposition, IBlockData iblockdata, Block block) { + EnumDirection enumdirection = iblockdata.get(BlockWallSign.FACING); + + if (!world.getType(blockposition.shift(enumdirection.opposite())).getBlock().getMaterial().isBuildable()) { + this.b(world, blockposition, iblockdata, 0); + world.setAir(blockposition); + } + + super.doPhysics(world, blockposition, iblockdata, block); + } + + public IBlockData fromLegacyData(int i) { + EnumDirection enumdirection = EnumDirection.fromType1(i); + + if (enumdirection.k() == EnumDirection.EnumAxis.Y) { + enumdirection = EnumDirection.NORTH; + } + + return this.getBlockData().set(BlockWallSign.FACING, enumdirection); + } + + public int toLegacyData(IBlockData iblockdata) { + return iblockdata.get(BlockWallSign.FACING).a(); + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, BlockWallSign.FACING); + } + + static class SyntheticClass_1 { + + static final int[] a = new int[EnumDirection.values().length]; + + static { + try { + BlockWallSign.SyntheticClass_1.a[EnumDirection.NORTH.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockWallSign.SyntheticClass_1.a[EnumDirection.SOUTH.ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockWallSign.SyntheticClass_1.a[EnumDirection.WEST.ordinal()] = 3; + } catch (NoSuchFieldError ignored) { + } + + try { + BlockWallSign.SyntheticClass_1.a[EnumDirection.EAST.ordinal()] = 4; + } catch (NoSuchFieldError ignored) { + } + + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockWaterLily.java b/azurite-server/src/main/java/net/minecraft/server/BlockWaterLily.java new file mode 100644 index 0000000..6e7b29a --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockWaterLily.java @@ -0,0 +1,43 @@ +package net.minecraft.server; + +import java.util.List; + +public class BlockWaterLily extends BlockPlant { + + protected BlockWaterLily() { + float f = 0.5F; + float f1 = 0.015625F; + + this.a(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, f1, 0.5F + f); + this.a(CreativeModeTab.c); + } + + public void a(World world, BlockPosition blockposition, IBlockData iblockdata, AxisAlignedBB axisalignedbb, List list, Entity entity) { + if (!(entity instanceof EntityBoat)) { + super.a(world, blockposition, iblockdata, axisalignedbb, list, entity); + } + + } + + public AxisAlignedBB a(World world, BlockPosition blockposition, IBlockData iblockdata) { + return new AxisAlignedBB((double) blockposition.getX() + this.minX, (double) blockposition.getY() + this.minY, (double) blockposition.getZ() + this.minZ, (double) blockposition.getX() + this.maxX, (double) blockposition.getY() + this.maxY, (double) blockposition.getZ() + this.maxZ); + } + + protected boolean c(Block block) { + return block == Blocks.WATER; + } + + public boolean f(World world, BlockPosition blockposition, IBlockData iblockdata) { + if (blockposition.getY() >= 0 && blockposition.getY() < 256) { + IBlockData iblockdata1 = world.getType(blockposition.down()); + + return iblockdata1.getBlock().getMaterial() == Material.WATER && iblockdata1.get(BlockFluids.LEVEL) == 0; + } else { + return false; + } + } + + public int toLegacyData(IBlockData iblockdata) { + return 0; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockWeb.java b/azurite-server/src/main/java/net/minecraft/server/BlockWeb.java new file mode 100644 index 0000000..244e633 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockWeb.java @@ -0,0 +1,35 @@ +package net.minecraft.server; + +import java.util.Random; + +public class BlockWeb extends Block { + + public BlockWeb() { + super(Material.WEB); + this.a(CreativeModeTab.c); + } + + public void a(World world, BlockPosition blockposition, IBlockData iblockdata, Entity entity) { + entity.aA(); + } + + public boolean c() { + return false; + } + + public AxisAlignedBB a(World world, BlockPosition blockposition, IBlockData iblockdata) { + return null; + } + + public boolean d() { + return false; + } + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + return Items.STRING; + } + + protected boolean I() { + return true; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockWood.java b/azurite-server/src/main/java/net/minecraft/server/BlockWood.java new file mode 100644 index 0000000..15f3ef8 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockWood.java @@ -0,0 +1,89 @@ +package net.minecraft.server; + +public class BlockWood extends Block { + + public static final BlockStateEnum VARIANT = BlockStateEnum.of("variant", BlockWood.EnumLogVariant.class); + + public BlockWood() { + super(Material.WOOD); + this.j(this.blockStateList.getBlockData().set(BlockWood.VARIANT, BlockWood.EnumLogVariant.OAK)); + this.a(CreativeModeTab.b); + } + + public int getDropData(IBlockData iblockdata) { + return iblockdata.get(BlockWood.VARIANT).a(); + } + + public IBlockData fromLegacyData(int i) { + return this.getBlockData().set(BlockWood.VARIANT, BlockWood.EnumLogVariant.a(i)); + } + + public MaterialMapColor g(IBlockData iblockdata) { + return iblockdata.get(BlockWood.VARIANT).c(); + } + + public int toLegacyData(IBlockData iblockdata) { + return iblockdata.get(BlockWood.VARIANT).a(); + } + + protected BlockStateList getStateList() { + return new BlockStateList(this, BlockWood.VARIANT); + } + + public enum EnumLogVariant implements INamable { + + OAK(0, "oak", MaterialMapColor.o), SPRUCE(1, "spruce", MaterialMapColor.J), BIRCH(2, "birch", MaterialMapColor.d), JUNGLE(3, "jungle", MaterialMapColor.l), ACACIA(4, "acacia", MaterialMapColor.q), DARK_OAK(5, "dark_oak", "big_oak", MaterialMapColor.B); + + private static final BlockWood.EnumLogVariant[] g = new BlockWood.EnumLogVariant[values().length]; + private final int h; + private final String i; + private final String j; + private final MaterialMapColor k; + + EnumLogVariant(int i, String s, MaterialMapColor materialmapcolor) { + this(i, s, s, materialmapcolor); + } + + EnumLogVariant(int i, String s, String s1, MaterialMapColor materialmapcolor) { + this.h = i; + this.i = s; + this.j = s1; + this.k = materialmapcolor; + } + + public int a() { + return this.h; + } + + public MaterialMapColor c() { + return this.k; + } + + public String toString() { + return this.i; + } + + public static BlockWood.EnumLogVariant a(int i) { + if (i < 0 || i >= BlockWood.EnumLogVariant.g.length) { + i = 0; + } + + return BlockWood.EnumLogVariant.g[i]; + } + + public String getName() { + return this.i; + } + + public String d() { + return this.j; + } + + static { + for (EnumLogVariant blockwood_enumlogvariant : values()) { + EnumLogVariant.g[blockwood_enumlogvariant.a()] = blockwood_enumlogvariant; + } + + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockWoodButton.java b/azurite-server/src/main/java/net/minecraft/server/BlockWoodButton.java new file mode 100644 index 0000000..e62cc86 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockWoodButton.java @@ -0,0 +1,8 @@ +package net.minecraft.server; + +public class BlockWoodButton extends BlockButtonAbstract { + + protected BlockWoodButton() { + super(true); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockWoodStep.java b/azurite-server/src/main/java/net/minecraft/server/BlockWoodStep.java new file mode 100644 index 0000000..9b4ad90 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockWoodStep.java @@ -0,0 +1,10 @@ +package net.minecraft.server; + +public class BlockWoodStep extends BlockWoodenStep { + + public BlockWoodStep() {} + + public boolean l() { + return false; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockWoodenStep.java b/azurite-server/src/main/java/net/minecraft/server/BlockWoodenStep.java new file mode 100644 index 0000000..a3697fa --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockWoodenStep.java @@ -0,0 +1,69 @@ +package net.minecraft.server; + +import java.util.Random; + +public abstract class BlockWoodenStep extends BlockStepAbstract { + + public static final BlockStateEnum VARIANT = BlockStateEnum.of("variant", BlockWood.EnumLogVariant.class); + + public BlockWoodenStep() { + super(Material.WOOD); + IBlockData iblockdata = this.blockStateList.getBlockData(); + + if (!this.l()) { + iblockdata = iblockdata.set(BlockWoodenStep.HALF, BlockStepAbstract.EnumSlabHalf.BOTTOM); + } + + this.j(iblockdata.set(BlockWoodenStep.VARIANT, BlockWood.EnumLogVariant.OAK)); + this.a(CreativeModeTab.b); + } + + public MaterialMapColor g(IBlockData iblockdata) { + return iblockdata.get(BlockWoodenStep.VARIANT).c(); + } + + public Item getDropType(IBlockData iblockdata, Random random, int i) { + return Item.getItemOf(Blocks.WOODEN_SLAB); + } + + public String b(int i) { + return super.a() + "." + BlockWood.EnumLogVariant.a(i).d(); + } + + public IBlockState n() { + return BlockWoodenStep.VARIANT; + } + + public Object a(ItemStack itemstack) { + return BlockWood.EnumLogVariant.a(itemstack.getData() & 7); + } + + public IBlockData fromLegacyData(int i) { + IBlockData iblockdata = this.getBlockData().set(BlockWoodenStep.VARIANT, BlockWood.EnumLogVariant.a(i & 7)); + + if (!this.l()) { + iblockdata = iblockdata.set(BlockWoodenStep.HALF, (i & 8) == 0 ? BlockStepAbstract.EnumSlabHalf.BOTTOM : BlockStepAbstract.EnumSlabHalf.TOP); + } + + return iblockdata; + } + + public int toLegacyData(IBlockData iblockdata) { + byte b0 = 0; + int i = b0 | iblockdata.get(BlockWoodenStep.VARIANT).a(); + + if (!this.l() && iblockdata.get(BlockWoodenStep.HALF) == BlockStepAbstract.EnumSlabHalf.TOP) { + i |= 8; + } + + return i; + } + + protected BlockStateList getStateList() { + return this.l() ? new BlockStateList(this, BlockWoodenStep.VARIANT) : new BlockStateList(this, BlockWoodenStep.HALF, BlockWoodenStep.VARIANT); + } + + public int getDropData(IBlockData iblockdata) { + return iblockdata.get(BlockWoodenStep.VARIANT).a(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockWorkbench.java b/azurite-server/src/main/java/net/minecraft/server/BlockWorkbench.java new file mode 100644 index 0000000..54f204d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockWorkbench.java @@ -0,0 +1,45 @@ +package net.minecraft.server; + +public class BlockWorkbench extends Block { + + protected BlockWorkbench() { + super(Material.WOOD); + this.a(CreativeModeTab.c); + } + + public boolean interact(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman, EnumDirection enumdirection, float f, float f1, float f2) { + entityhuman.openTileEntity(new TileEntityContainerWorkbench(world, blockposition)); + return true; + } + + public static class TileEntityContainerWorkbench implements ITileEntityContainer { + + private final World a; + private final BlockPosition b; + + public TileEntityContainerWorkbench(World world, BlockPosition blockposition) { + this.a = world; + this.b = blockposition; + } + + public String getName() { + return null; + } + + public boolean hasCustomName() { + return false; + } + + public IChatBaseComponent getScoreboardDisplayName() { + return new ChatMessage(Blocks.CRAFTING_TABLE.a() + ".name"); + } + + public Container createContainer(PlayerInventory playerinventory, EntityHuman entityhuman) { + return new ContainerWorkbench(playerinventory, this.a, this.b); + } + + public String getContainerName() { + return "minecraft:crafting_table"; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BlockYellowFlowers.java b/azurite-server/src/main/java/net/minecraft/server/BlockYellowFlowers.java new file mode 100644 index 0000000..50c4009 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BlockYellowFlowers.java @@ -0,0 +1,10 @@ +package net.minecraft.server; + +public class BlockYellowFlowers extends BlockFlowers { + + public BlockYellowFlowers() {} + + public BlockFlowers.EnumFlowerType l() { + return BlockFlowers.EnumFlowerType.YELLOW; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/Blocks.java b/azurite-server/src/main/java/net/minecraft/server/Blocks.java new file mode 100644 index 0000000..58d86bb --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/Blocks.java @@ -0,0 +1,412 @@ +package net.minecraft.server; + +public class Blocks { + + public static final Block AIR; + public static final Block STONE; + public static final BlockGrass GRASS; + public static final Block DIRT; + public static final Block COBBLESTONE; + public static final Block PLANKS; + public static final Block SAPLING; + public static final Block BEDROCK; + public static final BlockFlowing FLOWING_WATER; + public static final BlockStationary WATER; + public static final BlockFlowing FLOWING_LAVA; + public static final BlockStationary LAVA; + public static final BlockSand SAND; + public static final Block GRAVEL; + public static final Block GOLD_ORE; + public static final Block IRON_ORE; + public static final Block COAL_ORE; + public static final Block LOG; + public static final Block LOG2; + public static final BlockLeaves LEAVES; + public static final BlockLeaves LEAVES2; + public static final Block SPONGE; + public static final Block GLASS; + public static final Block LAPIS_ORE; + public static final Block LAPIS_BLOCK; + public static final Block DISPENSER; + public static final Block SANDSTONE; + public static final Block NOTEBLOCK; + public static final Block BED; + public static final Block GOLDEN_RAIL; + public static final Block DETECTOR_RAIL; + public static final BlockPiston STICKY_PISTON; + public static final Block WEB; + public static final BlockLongGrass TALLGRASS; + public static final BlockDeadBush DEADBUSH; + public static final BlockPiston PISTON; + public static final BlockPistonExtension PISTON_HEAD; + public static final Block WOOL; + public static final BlockPistonMoving PISTON_EXTENSION; + public static final BlockFlowers YELLOW_FLOWER; + public static final BlockFlowers RED_FLOWER; + public static final BlockPlant BROWN_MUSHROOM; + public static final BlockPlant RED_MUSHROOM; + public static final Block GOLD_BLOCK; + public static final Block IRON_BLOCK; + public static final BlockStepAbstract DOUBLE_STONE_SLAB; + public static final BlockStepAbstract STONE_SLAB; + public static final Block BRICK_BLOCK; + public static final Block TNT; + public static final Block BOOKSHELF; + public static final Block MOSSY_COBBLESTONE; + public static final Block OBSIDIAN; + public static final Block TORCH; + public static final BlockFire FIRE; + public static final Block MOB_SPAWNER; + public static final Block OAK_STAIRS; + public static final BlockChest CHEST; + public static final BlockRedstoneWire REDSTONE_WIRE; + public static final Block DIAMOND_ORE; + public static final Block DIAMOND_BLOCK; + public static final Block CRAFTING_TABLE; + public static final Block WHEAT; + public static final Block FARMLAND; + public static final Block FURNACE; + public static final Block LIT_FURNACE; + public static final Block STANDING_SIGN; + public static final Block WOODEN_DOOR; + public static final Block SPRUCE_DOOR; + public static final Block BIRCH_DOOR; + public static final Block JUNGLE_DOOR; + public static final Block ACACIA_DOOR; + public static final Block DARK_OAK_DOOR; + public static final Block LADDER; + public static final Block RAIL; + public static final Block STONE_STAIRS; + public static final Block WALL_SIGN; + public static final Block LEVER; + public static final Block STONE_PRESSURE_PLATE; + public static final Block IRON_DOOR; + public static final Block WOODEN_PRESSURE_PLATE; + public static final Block REDSTONE_ORE; + public static final Block LIT_REDSTONE_ORE; + public static final Block UNLIT_REDSTONE_TORCH; + public static final Block REDSTONE_TORCH; + public static final Block STONE_BUTTON; + public static final Block SNOW_LAYER; + public static final Block ICE; + public static final Block SNOW; + public static final BlockCactus CACTUS; + public static final Block CLAY; + public static final BlockReed REEDS; + public static final Block JUKEBOX; + public static final Block FENCE; + public static final Block SPRUCE_FENCE; + public static final Block BIRCH_FENCE; + public static final Block JUNGLE_FENCE; + public static final Block DARK_OAK_FENCE; + public static final Block ACACIA_FENCE; + public static final Block PUMPKIN; + public static final Block NETHERRACK; + public static final Block SOUL_SAND; + public static final Block GLOWSTONE; + public static final BlockPortal PORTAL; + public static final Block LIT_PUMPKIN; + public static final Block CAKE; + public static final BlockRepeater UNPOWERED_REPEATER; + public static final BlockRepeater POWERED_REPEATER; + public static final Block TRAPDOOR; + public static final Block MONSTER_EGG; + public static final Block STONEBRICK; + public static final Block BROWN_MUSHROOM_BLOCK; + public static final Block RED_MUSHROOM_BLOCK; + public static final Block IRON_BARS; + public static final Block GLASS_PANE; + public static final Block MELON_BLOCK; + public static final Block PUMPKIN_STEM; + public static final Block MELON_STEM; + public static final Block VINE; + public static final Block FENCE_GATE; + public static final Block SPRUCE_FENCE_GATE; + public static final Block BIRCH_FENCE_GATE; + public static final Block JUNGLE_FENCE_GATE; + public static final Block DARK_OAK_FENCE_GATE; + public static final Block ACACIA_FENCE_GATE; + public static final Block BRICK_STAIRS; + public static final Block STONE_BRICK_STAIRS; + public static final BlockMycel MYCELIUM; + public static final Block WATERLILY; + public static final Block NETHER_BRICK; + public static final Block NETHER_BRICK_FENCE; + public static final Block NETHER_BRICK_STAIRS; + public static final Block NETHER_WART; + public static final Block ENCHANTING_TABLE; + public static final Block BREWING_STAND; + public static final BlockCauldron cauldron; + public static final Block END_PORTAL; + public static final Block END_PORTAL_FRAME; + public static final Block END_STONE; + public static final Block DRAGON_EGG; + public static final Block REDSTONE_LAMP; + public static final Block LIT_REDSTONE_LAMP; + public static final BlockStepAbstract DOUBLE_WOODEN_SLAB; + public static final BlockStepAbstract WOODEN_SLAB; + public static final Block COCOA; + public static final Block SANDSTONE_STAIRS; + public static final Block EMERALD_ORE; + public static final Block ENDER_CHEST; + public static final BlockTripwireHook TRIPWIRE_HOOK; + public static final Block TRIPWIRE; + public static final Block EMERALD_BLOCK; + public static final Block SPRUCE_STAIRS; + public static final Block BIRCH_STAIRS; + public static final Block JUNGLE_STAIRS; + public static final Block COMMAND_BLOCK; + public static final BlockBeacon BEACON; + public static final Block COBBLESTONE_WALL; + public static final Block FLOWER_POT; + public static final Block CARROTS; + public static final Block POTATOES; + public static final Block WOODEN_BUTTON; + public static final BlockSkull SKULL; + public static final Block ANVIL; + public static final Block TRAPPED_CHEST; + public static final Block LIGHT_WEIGHTED_PRESSURE_PLATE; + public static final Block HEAVY_WEIGHTED_PRESSURE_PLATE; + public static final BlockRedstoneComparator UNPOWERED_COMPARATOR; + public static final BlockRedstoneComparator POWERED_COMPARATOR; + public static final BlockDaylightDetector DAYLIGHT_DETECTOR; + public static final BlockDaylightDetector DAYLIGHT_DETECTOR_INVERTED; + public static final Block REDSTONE_BLOCK; + public static final Block QUARTZ_ORE; + public static final BlockHopper HOPPER; + public static final Block QUARTZ_BLOCK; + public static final Block QUARTZ_STAIRS; + public static final Block ACTIVATOR_RAIL; + public static final Block DROPPER; + public static final Block STAINED_HARDENED_CLAY; + public static final Block BARRIER; + public static final Block IRON_TRAPDOOR; + public static final Block HAY_BLOCK; + public static final Block CARPET; + public static final Block HARDENED_CLAY; + public static final Block COAL_BLOCK; + public static final Block PACKED_ICE; + public static final Block ACACIA_STAIRS; + public static final Block DARK_OAK_STAIRS; + public static final Block SLIME; + public static final BlockTallPlant DOUBLE_PLANT; + public static final BlockStainedGlass STAINED_GLASS; + public static final BlockStainedGlassPane STAINED_GLASS_PANE; + public static final Block PRISMARINE; + public static final Block SEA_LANTERN; + public static final Block STANDING_BANNER; + public static final Block WALL_BANNER; + public static final Block RED_SANDSTONE; + public static final Block RED_SANDSTONE_STAIRS; + public static final BlockStepAbstract DOUBLE_STONE_SLAB2; + public static final BlockStepAbstract STONE_SLAB2; + + private static Block get(String s) { + return (Block) Block.REGISTRY.get(new MinecraftKey(s)); + } + + static { + if (!DispenserRegistry.a()) { + throw new RuntimeException("Accessed Blocks before Bootstrap!"); + } else { + AIR = get("air"); + STONE = get("stone"); + GRASS = (BlockGrass) get("grass"); + DIRT = get("dirt"); + COBBLESTONE = get("cobblestone"); + PLANKS = get("planks"); + SAPLING = get("sapling"); + BEDROCK = get("bedrock"); + FLOWING_WATER = (BlockFlowing) get("flowing_water"); + WATER = (BlockStationary) get("water"); + FLOWING_LAVA = (BlockFlowing) get("flowing_lava"); + LAVA = (BlockStationary) get("lava"); + SAND = (BlockSand) get("sand"); + GRAVEL = get("gravel"); + GOLD_ORE = get("gold_ore"); + IRON_ORE = get("iron_ore"); + COAL_ORE = get("coal_ore"); + LOG = get("log"); + LOG2 = get("log2"); + LEAVES = (BlockLeaves) get("leaves"); + LEAVES2 = (BlockLeaves) get("leaves2"); + SPONGE = get("sponge"); + GLASS = get("glass"); + LAPIS_ORE = get("lapis_ore"); + LAPIS_BLOCK = get("lapis_block"); + DISPENSER = get("dispenser"); + SANDSTONE = get("sandstone"); + NOTEBLOCK = get("noteblock"); + BED = get("bed"); + GOLDEN_RAIL = get("golden_rail"); + DETECTOR_RAIL = get("detector_rail"); + STICKY_PISTON = (BlockPiston) get("sticky_piston"); + WEB = get("web"); + TALLGRASS = (BlockLongGrass) get("tallgrass"); + DEADBUSH = (BlockDeadBush) get("deadbush"); + PISTON = (BlockPiston) get("piston"); + PISTON_HEAD = (BlockPistonExtension) get("piston_head"); + WOOL = get("wool"); + PISTON_EXTENSION = (BlockPistonMoving) get("piston_extension"); + YELLOW_FLOWER = (BlockFlowers) get("yellow_flower"); + RED_FLOWER = (BlockFlowers) get("red_flower"); + BROWN_MUSHROOM = (BlockPlant) get("brown_mushroom"); + RED_MUSHROOM = (BlockPlant) get("red_mushroom"); + GOLD_BLOCK = get("gold_block"); + IRON_BLOCK = get("iron_block"); + DOUBLE_STONE_SLAB = (BlockStepAbstract) get("double_stone_slab"); + STONE_SLAB = (BlockStepAbstract) get("stone_slab"); + BRICK_BLOCK = get("brick_block"); + TNT = get("tnt"); + BOOKSHELF = get("bookshelf"); + MOSSY_COBBLESTONE = get("mossy_cobblestone"); + OBSIDIAN = get("obsidian"); + TORCH = get("torch"); + FIRE = (BlockFire) get("fire"); + MOB_SPAWNER = get("mob_spawner"); + OAK_STAIRS = get("oak_stairs"); + CHEST = (BlockChest) get("chest"); + REDSTONE_WIRE = (BlockRedstoneWire) get("redstone_wire"); + DIAMOND_ORE = get("diamond_ore"); + DIAMOND_BLOCK = get("diamond_block"); + CRAFTING_TABLE = get("crafting_table"); + WHEAT = get("wheat"); + FARMLAND = get("farmland"); + FURNACE = get("furnace"); + LIT_FURNACE = get("lit_furnace"); + STANDING_SIGN = get("standing_sign"); + WOODEN_DOOR = get("wooden_door"); + SPRUCE_DOOR = get("spruce_door"); + BIRCH_DOOR = get("birch_door"); + JUNGLE_DOOR = get("jungle_door"); + ACACIA_DOOR = get("acacia_door"); + DARK_OAK_DOOR = get("dark_oak_door"); + LADDER = get("ladder"); + RAIL = get("rail"); + STONE_STAIRS = get("stone_stairs"); + WALL_SIGN = get("wall_sign"); + LEVER = get("lever"); + STONE_PRESSURE_PLATE = get("stone_pressure_plate"); + IRON_DOOR = get("iron_door"); + WOODEN_PRESSURE_PLATE = get("wooden_pressure_plate"); + REDSTONE_ORE = get("redstone_ore"); + LIT_REDSTONE_ORE = get("lit_redstone_ore"); + UNLIT_REDSTONE_TORCH = get("unlit_redstone_torch"); + REDSTONE_TORCH = get("redstone_torch"); + STONE_BUTTON = get("stone_button"); + SNOW_LAYER = get("snow_layer"); + ICE = get("ice"); + SNOW = get("snow"); + CACTUS = (BlockCactus) get("cactus"); + CLAY = get("clay"); + REEDS = (BlockReed) get("reeds"); + JUKEBOX = get("jukebox"); + FENCE = get("fence"); + SPRUCE_FENCE = get("spruce_fence"); + BIRCH_FENCE = get("birch_fence"); + JUNGLE_FENCE = get("jungle_fence"); + DARK_OAK_FENCE = get("dark_oak_fence"); + ACACIA_FENCE = get("acacia_fence"); + PUMPKIN = get("pumpkin"); + NETHERRACK = get("netherrack"); + SOUL_SAND = get("soul_sand"); + GLOWSTONE = get("glowstone"); + PORTAL = (BlockPortal) get("portal"); + LIT_PUMPKIN = get("lit_pumpkin"); + CAKE = get("cake"); + UNPOWERED_REPEATER = (BlockRepeater) get("unpowered_repeater"); + POWERED_REPEATER = (BlockRepeater) get("powered_repeater"); + TRAPDOOR = get("trapdoor"); + MONSTER_EGG = get("monster_egg"); + STONEBRICK = get("stonebrick"); + BROWN_MUSHROOM_BLOCK = get("brown_mushroom_block"); + RED_MUSHROOM_BLOCK = get("red_mushroom_block"); + IRON_BARS = get("iron_bars"); + GLASS_PANE = get("glass_pane"); + MELON_BLOCK = get("melon_block"); + PUMPKIN_STEM = get("pumpkin_stem"); + MELON_STEM = get("melon_stem"); + VINE = get("vine"); + FENCE_GATE = get("fence_gate"); + SPRUCE_FENCE_GATE = get("spruce_fence_gate"); + BIRCH_FENCE_GATE = get("birch_fence_gate"); + JUNGLE_FENCE_GATE = get("jungle_fence_gate"); + DARK_OAK_FENCE_GATE = get("dark_oak_fence_gate"); + ACACIA_FENCE_GATE = get("acacia_fence_gate"); + BRICK_STAIRS = get("brick_stairs"); + STONE_BRICK_STAIRS = get("stone_brick_stairs"); + MYCELIUM = (BlockMycel) get("mycelium"); + WATERLILY = get("waterlily"); + NETHER_BRICK = get("nether_brick"); + NETHER_BRICK_FENCE = get("nether_brick_fence"); + NETHER_BRICK_STAIRS = get("nether_brick_stairs"); + NETHER_WART = get("nether_wart"); + ENCHANTING_TABLE = get("enchanting_table"); + BREWING_STAND = get("brewing_stand"); + cauldron = (BlockCauldron) get("cauldron"); + END_PORTAL = get("end_portal"); + END_PORTAL_FRAME = get("end_portal_frame"); + END_STONE = get("end_stone"); + DRAGON_EGG = get("dragon_egg"); + REDSTONE_LAMP = get("redstone_lamp"); + LIT_REDSTONE_LAMP = get("lit_redstone_lamp"); + DOUBLE_WOODEN_SLAB = (BlockStepAbstract) get("double_wooden_slab"); + WOODEN_SLAB = (BlockStepAbstract) get("wooden_slab"); + COCOA = get("cocoa"); + SANDSTONE_STAIRS = get("sandstone_stairs"); + EMERALD_ORE = get("emerald_ore"); + ENDER_CHEST = get("ender_chest"); + TRIPWIRE_HOOK = (BlockTripwireHook) get("tripwire_hook"); + TRIPWIRE = get("tripwire"); + EMERALD_BLOCK = get("emerald_block"); + SPRUCE_STAIRS = get("spruce_stairs"); + BIRCH_STAIRS = get("birch_stairs"); + JUNGLE_STAIRS = get("jungle_stairs"); + COMMAND_BLOCK = get("command_block"); + BEACON = (BlockBeacon) get("beacon"); + COBBLESTONE_WALL = get("cobblestone_wall"); + FLOWER_POT = get("flower_pot"); + CARROTS = get("carrots"); + POTATOES = get("potatoes"); + WOODEN_BUTTON = get("wooden_button"); + SKULL = (BlockSkull) get("skull"); + ANVIL = get("anvil"); + TRAPPED_CHEST = get("trapped_chest"); + LIGHT_WEIGHTED_PRESSURE_PLATE = get("light_weighted_pressure_plate"); + HEAVY_WEIGHTED_PRESSURE_PLATE = get("heavy_weighted_pressure_plate"); + UNPOWERED_COMPARATOR = (BlockRedstoneComparator) get("unpowered_comparator"); + POWERED_COMPARATOR = (BlockRedstoneComparator) get("powered_comparator"); + DAYLIGHT_DETECTOR = (BlockDaylightDetector) get("daylight_detector"); + DAYLIGHT_DETECTOR_INVERTED = (BlockDaylightDetector) get("daylight_detector_inverted"); + REDSTONE_BLOCK = get("redstone_block"); + QUARTZ_ORE = get("quartz_ore"); + HOPPER = (BlockHopper) get("hopper"); + QUARTZ_BLOCK = get("quartz_block"); + QUARTZ_STAIRS = get("quartz_stairs"); + ACTIVATOR_RAIL = get("activator_rail"); + DROPPER = get("dropper"); + STAINED_HARDENED_CLAY = get("stained_hardened_clay"); + BARRIER = get("barrier"); + IRON_TRAPDOOR = get("iron_trapdoor"); + HAY_BLOCK = get("hay_block"); + CARPET = get("carpet"); + HARDENED_CLAY = get("hardened_clay"); + COAL_BLOCK = get("coal_block"); + PACKED_ICE = get("packed_ice"); + ACACIA_STAIRS = get("acacia_stairs"); + DARK_OAK_STAIRS = get("dark_oak_stairs"); + SLIME = get("slime"); + DOUBLE_PLANT = (BlockTallPlant) get("double_plant"); + STAINED_GLASS = (BlockStainedGlass) get("stained_glass"); + STAINED_GLASS_PANE = (BlockStainedGlassPane) get("stained_glass_pane"); + PRISMARINE = get("prismarine"); + SEA_LANTERN = get("sea_lantern"); + STANDING_BANNER = get("standing_banner"); + WALL_BANNER = get("wall_banner"); + RED_SANDSTONE = get("red_sandstone"); + RED_SANDSTONE_STAIRS = get("red_sandstone_stairs"); + DOUBLE_STONE_SLAB2 = (BlockStepAbstract) get("double_stone_slab2"); + STONE_SLAB2 = (BlockStepAbstract) get("stone_slab2"); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/BoundingBox.java b/azurite-server/src/main/java/net/minecraft/server/BoundingBox.java new file mode 100644 index 0000000..7bf4586 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/BoundingBox.java @@ -0,0 +1,24 @@ +package net.minecraft.server; + +import org.bukkit.block.Block; +import org.bukkit.craftbukkit.CraftWorld; +import org.bukkit.util.Vector; + +public class BoundingBox { + private final Vector max, min; + + public BoundingBox(Block block) { + IBlockData blockData = ((CraftWorld) block.getWorld()).getHandle().getType(block.getX(), block.getY(), block.getZ()); + net.minecraft.server.Block blockNative = blockData.getBlock(); + min = new Vector(block.getX() + blockNative.B(), block.getY() + blockNative.D(), block.getZ() + blockNative.F()); + max = new Vector(block.getX() + blockNative.C(), block.getY() + blockNative.E(), block.getZ() + blockNative.G()); + } + + public Vector getMax() { + return max; + } + + public Vector getMin() { + return min; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CancelledPacketHandleException.java b/azurite-server/src/main/java/net/minecraft/server/CancelledPacketHandleException.java new file mode 100644 index 0000000..63b7db3 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CancelledPacketHandleException.java @@ -0,0 +1,15 @@ +package net.minecraft.server; + +public final class CancelledPacketHandleException extends RuntimeException { + + public static final CancelledPacketHandleException INSTANCE = new CancelledPacketHandleException(); + + private CancelledPacketHandleException() { + this.setStackTrace(new StackTraceElement[0]); + } + + public synchronized Throwable fillInStackTrace() { + this.setStackTrace(new StackTraceElement[0]); + return this; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CannonCache.java b/azurite-server/src/main/java/net/minecraft/server/CannonCache.java new file mode 100644 index 0000000..0c022b4 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CannonCache.java @@ -0,0 +1,56 @@ +package net.minecraft.server; + +public class CannonCache { + private AxisAlignedBB boundingBox; + private double + locX, + locY, + locZ, + lastX, + lastY, + lastZ, + motX, + motY, + motZ, + lastMotX, + lastMotY, + lastMotZ; + + private boolean onGround; + + public boolean move(Entity entity) { + if (entity.locX == lastX && entity.locY == lastY && entity.locZ == lastZ && entity.motX == lastMotX && entity.motY == lastMotY && entity.motZ == lastMotZ) { + entity.boundingBox = boundingBox; + entity.onGround = onGround; + entity.locX = locX; + entity.locY = locY; + entity.locZ = locZ; + entity.motX = motX; + entity.motY = motY; + entity.motZ = motZ; + return true; + } + return false; + } + + public void cache(Entity entity) { + onGround = entity.onGround; + boundingBox = entity.boundingBox; + lastX = entity.lastX; + lastY = entity.lastY; + lastZ = entity.lastZ; + lastMotX = entity.lastMotX; + lastMotY = entity.lastMotY; + lastMotZ = entity.lastMotZ; + locX = entity.locX; + locY = entity.locY; + locZ = entity.locZ; + motX = entity.motX; + motY = entity.motY; + motZ = entity.motZ; + } + + public void clear() { + lastX = Double.MAX_VALUE; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ChatBaseComponent.java b/azurite-server/src/main/java/net/minecraft/server/ChatBaseComponent.java new file mode 100644 index 0000000..4e4069d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ChatBaseComponent.java @@ -0,0 +1,112 @@ +package net.minecraft.server; + +import com.google.common.base.Function; +import com.google.common.collect.Iterators; +import com.google.common.collect.Lists; + +import java.util.Iterator; +import java.util.List; + +public abstract class ChatBaseComponent implements IChatBaseComponent { + + protected List a = Lists.newArrayList(); + private ChatModifier b; + + public ChatBaseComponent() {} + + public IChatBaseComponent addSibling(IChatBaseComponent ichatbasecomponent) { + ichatbasecomponent.getChatModifier().setChatModifier(this.getChatModifier()); + this.a.add(ichatbasecomponent); + return this; + } + + public List a() { + return this.a; + } + + public IChatBaseComponent a(String s) { + return this.addSibling(new ChatComponentText(s)); + } + + public IChatBaseComponent setChatModifier(ChatModifier chatmodifier) { + this.b = chatmodifier; + + for (IChatBaseComponent ichatbasecomponent : this.a) { + ichatbasecomponent.getChatModifier().setChatModifier(this.getChatModifier()); + } + + return this; + } + + public ChatModifier getChatModifier() { + if (this.b == null) { + this.b = new ChatModifier(); + + for (IChatBaseComponent ichatbasecomponent : this.a) { + ichatbasecomponent.getChatModifier().setChatModifier(this.b); + } + } + + return this.b; + } + + public Iterator iterator() { + return Iterators.concat(Iterators.forArray(this), a(this.a)); + } + + public final String c() { + StringBuilder stringbuilder = new StringBuilder(); + + for (IChatBaseComponent ichatbasecomponent : this) { + stringbuilder.append(ichatbasecomponent.getText()); + } + + return stringbuilder.toString(); + } + + public static Iterator a(Iterable iterable) { + Iterator iterator = Iterators.concat(Iterators.transform(iterable.iterator(), new Function() { + public Iterator a(IChatBaseComponent ichatbasecomponent) { + return ichatbasecomponent.iterator(); + } + + public Object apply(Object object) { + return this.a((IChatBaseComponent) object); + } + })); + + iterator = Iterators.transform(iterator, new Function() { + public IChatBaseComponent a(IChatBaseComponent ichatbasecomponent) { + IChatBaseComponent ichatbasecomponent1 = ichatbasecomponent.f(); + + ichatbasecomponent1.setChatModifier(ichatbasecomponent1.getChatModifier().n()); + return ichatbasecomponent1; + } + + public Object apply(Object object) { + return this.a((IChatBaseComponent) object); + } + }); + return iterator; + } + + public boolean equals(Object object) { + if (this == object) { + return true; + } else if (!(object instanceof ChatBaseComponent)) { + return false; + } else { + ChatBaseComponent chatbasecomponent = (ChatBaseComponent) object; + + return this.a.equals(chatbasecomponent.a) && this.getChatModifier().equals(chatbasecomponent.getChatModifier()); + } + } + + public int hashCode() { + return 31 * this.getChatModifier().hashCode() + this.a.hashCode(); // CraftBukkit - fix null pointer + } + + public String toString() { + return "BaseComponent{style=" + this.b + ", siblings=" + this.a + '}'; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ChatClickable.java b/azurite-server/src/main/java/net/minecraft/server/ChatClickable.java new file mode 100644 index 0000000..d319fa3 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ChatClickable.java @@ -0,0 +1,96 @@ +package net.minecraft.server; + +import com.google.common.collect.Maps; +import java.util.Map; + +public class ChatClickable { + + private final ChatClickable.EnumClickAction a; + private final String b; + + public ChatClickable(ChatClickable.EnumClickAction chatclickable_enumclickaction, String s) { + this.a = chatclickable_enumclickaction; + this.b = s; + } + + public ChatClickable.EnumClickAction a() { + return this.a; + } + + public String b() { + return this.b; + } + + public boolean equals(Object object) { + if (this == object) { + return true; + } else if (object != null && this.getClass() == object.getClass()) { + ChatClickable chatclickable = (ChatClickable) object; + + if (this.a != chatclickable.a) { + return false; + } else { + if (this.b != null) { + if (!this.b.equals(chatclickable.b)) { + return false; + } + } else if (chatclickable.b != null) { + return false; + } + + return true; + } + } else { + return false; + } + } + + public String toString() { + return "ClickEvent{action=" + this.a + ", value=\'" + this.b + '\'' + '}'; + } + + public int hashCode() { + int i = this.a.hashCode(); + + i = 31 * i + (this.b != null ? this.b.hashCode() : 0); + return i; + } + + public static enum EnumClickAction { + + OPEN_URL("open_url", true), OPEN_FILE("open_file", false), RUN_COMMAND("run_command", true), TWITCH_USER_INFO("twitch_user_info", false), SUGGEST_COMMAND("suggest_command", true), CHANGE_PAGE("change_page", true); + + private static final Map g = Maps.newHashMap(); + private final boolean h; + private final String i; + + private EnumClickAction(String s, boolean flag) { + this.i = s; + this.h = flag; + } + + public boolean a() { + return this.h; + } + + public String b() { + return this.i; + } + + public static ChatClickable.EnumClickAction a(String s) { + return (ChatClickable.EnumClickAction) ChatClickable.EnumClickAction.g.get(s); + } + + static { + ChatClickable.EnumClickAction[] achatclickable_enumclickaction = values(); + int i = achatclickable_enumclickaction.length; + + for (int j = 0; j < i; ++j) { + ChatClickable.EnumClickAction chatclickable_enumclickaction = achatclickable_enumclickaction[j]; + + ChatClickable.EnumClickAction.g.put(chatclickable_enumclickaction.b(), chatclickable_enumclickaction); + } + + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ChatComponentScore.java b/azurite-server/src/main/java/net/minecraft/server/ChatComponentScore.java new file mode 100644 index 0000000..26f903d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ChatComponentScore.java @@ -0,0 +1,82 @@ +package net.minecraft.server; + +import java.util.Iterator; + +public class ChatComponentScore extends ChatBaseComponent { + + private final String b; + private final String c; + private String d = ""; + + public ChatComponentScore(String s, String s1) { + this.b = s; + this.c = s1; + } + + public String g() { + return this.b; + } + + public String h() { + return this.c; + } + + public void b(String s) { + this.d = s; + } + + public String getText() { + MinecraftServer minecraftserver = MinecraftServer.getServer(); + + if (minecraftserver != null && minecraftserver.O() && UtilColor.b(this.d)) { + Scoreboard scoreboard = minecraftserver.getWorldServer(0).getScoreboard(); + ScoreboardObjective scoreboardobjective = scoreboard.getObjective(this.c); + + if (scoreboard.b(this.b, scoreboardobjective)) { + ScoreboardScore scoreboardscore = scoreboard.getPlayerScoreForObjective(this.b, scoreboardobjective); + + this.b(String.format("%d", new Object[] { Integer.valueOf(scoreboardscore.getScore())})); + } else { + this.d = ""; + } + } + + return this.d; + } + + public ChatComponentScore i() { + ChatComponentScore chatcomponentscore = new ChatComponentScore(this.b, this.c); + + chatcomponentscore.b(this.d); + chatcomponentscore.setChatModifier(this.getChatModifier().clone()); + Iterator iterator = this.a().iterator(); + + while (iterator.hasNext()) { + IChatBaseComponent ichatbasecomponent = (IChatBaseComponent) iterator.next(); + + chatcomponentscore.addSibling(ichatbasecomponent.f()); + } + + return chatcomponentscore; + } + + public boolean equals(Object object) { + if (this == object) { + return true; + } else if (!(object instanceof ChatComponentScore)) { + return false; + } else { + ChatComponentScore chatcomponentscore = (ChatComponentScore) object; + + return this.b.equals(chatcomponentscore.b) && this.c.equals(chatcomponentscore.c) && super.equals(object); + } + } + + public String toString() { + return "ScoreComponent{name=\'" + this.b + '\'' + "objective=\'" + this.c + '\'' + ", siblings=" + this.a + ", style=" + this.getChatModifier() + '}'; + } + + public IChatBaseComponent f() { + return this.i(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ChatComponentSelector.java b/azurite-server/src/main/java/net/minecraft/server/ChatComponentSelector.java new file mode 100644 index 0000000..2acccbe --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ChatComponentSelector.java @@ -0,0 +1,55 @@ +package net.minecraft.server; + +import java.util.Iterator; + +public class ChatComponentSelector extends ChatBaseComponent { + + private final String b; + + public ChatComponentSelector(String s) { + this.b = s; + } + + public String g() { + return this.b; + } + + public String getText() { + return this.b; + } + + public ChatComponentSelector h() { + ChatComponentSelector chatcomponentselector = new ChatComponentSelector(this.b); + + chatcomponentselector.setChatModifier(this.getChatModifier().clone()); + Iterator iterator = this.a().iterator(); + + while (iterator.hasNext()) { + IChatBaseComponent ichatbasecomponent = (IChatBaseComponent) iterator.next(); + + chatcomponentselector.addSibling(ichatbasecomponent.f()); + } + + return chatcomponentselector; + } + + public boolean equals(Object object) { + if (this == object) { + return true; + } else if (!(object instanceof ChatComponentSelector)) { + return false; + } else { + ChatComponentSelector chatcomponentselector = (ChatComponentSelector) object; + + return this.b.equals(chatcomponentselector.b) && super.equals(object); + } + } + + public String toString() { + return "SelectorComponent{pattern=\'" + this.b + '\'' + ", siblings=" + this.a + ", style=" + this.getChatModifier() + '}'; + } + + public IChatBaseComponent f() { + return this.h(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ChatComponentText.java b/azurite-server/src/main/java/net/minecraft/server/ChatComponentText.java new file mode 100644 index 0000000..42cb342 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ChatComponentText.java @@ -0,0 +1,55 @@ +package net.minecraft.server; + +import java.util.Iterator; + +public class ChatComponentText extends ChatBaseComponent { + + private final String b; + + public ChatComponentText(String s) { + this.b = s; + } + + public String g() { + return this.b; + } + + public String getText() { + return this.b; + } + + public ChatComponentText h() { + ChatComponentText chatcomponenttext = new ChatComponentText(this.b); + + chatcomponenttext.setChatModifier(this.getChatModifier().clone()); + Iterator iterator = this.a().iterator(); + + while (iterator.hasNext()) { + IChatBaseComponent ichatbasecomponent = (IChatBaseComponent) iterator.next(); + + chatcomponenttext.addSibling(ichatbasecomponent.f()); + } + + return chatcomponenttext; + } + + public boolean equals(Object object) { + if (this == object) { + return true; + } else if (!(object instanceof ChatComponentText)) { + return false; + } else { + ChatComponentText chatcomponenttext = (ChatComponentText) object; + + return this.b.equals(chatcomponenttext.g()) && super.equals(object); + } + } + + public String toString() { + return "TextComponent{text=\'" + this.b + '\'' + ", siblings=" + this.a + ", style=" + this.getChatModifier() + '}'; + } + + public IChatBaseComponent f() { + return this.h(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ChatComponentUtils.java b/azurite-server/src/main/java/net/minecraft/server/ChatComponentUtils.java new file mode 100644 index 0000000..941a604 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ChatComponentUtils.java @@ -0,0 +1,70 @@ +package net.minecraft.server; + +import java.util.Iterator; +import java.util.List; + +public class ChatComponentUtils { + + public static IChatBaseComponent filterForDisplay(ICommandListener icommandlistener, IChatBaseComponent ichatbasecomponent, Entity entity) throws CommandException { + Object object = null; + + if (ichatbasecomponent instanceof ChatComponentScore) { + ChatComponentScore chatcomponentscore = (ChatComponentScore) ichatbasecomponent; + String s = chatcomponentscore.g(); + + if (PlayerSelector.isPattern(s)) { + List list = PlayerSelector.getPlayers(icommandlistener, s, Entity.class); + + if (list.size() != 1) { + throw new ExceptionEntityNotFound(); + } + + s = ((Entity) list.get(0)).getName(); + } + + object = entity != null && s.equals("*") ? new ChatComponentScore(entity.getName(), chatcomponentscore.h()) : new ChatComponentScore(s, chatcomponentscore.h()); + ((ChatComponentScore) object).b(chatcomponentscore.getText()); + } else if (ichatbasecomponent instanceof ChatComponentSelector) { + String s1 = ((ChatComponentSelector) ichatbasecomponent).g(); + + object = PlayerSelector.getPlayerNames(icommandlistener, s1); + if (object == null) { + object = new ChatComponentText(""); + } + } else if (ichatbasecomponent instanceof ChatComponentText) { + object = new ChatComponentText(((ChatComponentText) ichatbasecomponent).g()); + } else { + if (!(ichatbasecomponent instanceof ChatMessage)) { + return ichatbasecomponent; + } + + Object[] aobject = ((ChatMessage) ichatbasecomponent).j(); + + for (int i = 0; i < aobject.length; ++i) { + Object object1 = aobject[i]; + + if (object1 instanceof IChatBaseComponent) { + aobject[i] = filterForDisplay(icommandlistener, (IChatBaseComponent) object1, entity); + } + } + + object = new ChatMessage(((ChatMessage) ichatbasecomponent).i(), aobject); + } + + ChatModifier chatmodifier = ichatbasecomponent.getChatModifier(); + + if (chatmodifier != null) { + ((IChatBaseComponent) object).setChatModifier(chatmodifier.clone()); + } + + Iterator iterator = ichatbasecomponent.a().iterator(); + + while (iterator.hasNext()) { + IChatBaseComponent ichatbasecomponent1 = (IChatBaseComponent) iterator.next(); + + ((IChatBaseComponent) object).addSibling(filterForDisplay(icommandlistener, ichatbasecomponent1, entity)); + } + + return (IChatBaseComponent) object; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ChatDeserializer.java b/azurite-server/src/main/java/net/minecraft/server/ChatDeserializer.java new file mode 100644 index 0000000..4d679ea --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ChatDeserializer.java @@ -0,0 +1,131 @@ +package net.minecraft.server; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonSyntaxException; +import org.apache.commons.lang3.StringUtils; + +public class ChatDeserializer { + + public static boolean d(JsonObject jsonobject, String s) { + return !g(jsonobject, s) ? false : jsonobject.get(s).isJsonArray(); + } + + public static boolean g(JsonObject jsonobject, String s) { + return jsonobject == null ? false : jsonobject.get(s) != null; + } + + public static String a(JsonElement jsonelement, String s) { + if (jsonelement.isJsonPrimitive()) { + return jsonelement.getAsString(); + } else { + throw new JsonSyntaxException("Expected " + s + " to be a string, was " + d(jsonelement)); + } + } + + public static String h(JsonObject jsonobject, String s) { + if (jsonobject.has(s)) { + return a(jsonobject.get(s), s); + } else { + throw new JsonSyntaxException("Missing " + s + ", expected to find a string"); + } + } + + public static boolean b(JsonElement jsonelement, String s) { + if (jsonelement.isJsonPrimitive()) { + return jsonelement.getAsBoolean(); + } else { + throw new JsonSyntaxException("Expected " + s + " to be a Boolean, was " + d(jsonelement)); + } + } + + public static boolean a(JsonObject jsonobject, String s, boolean flag) { + return jsonobject.has(s) ? b(jsonobject.get(s), s) : flag; + } + + public static float d(JsonElement jsonelement, String s) { + if (jsonelement.isJsonPrimitive() && jsonelement.getAsJsonPrimitive().isNumber()) { + return jsonelement.getAsFloat(); + } else { + throw new JsonSyntaxException("Expected " + s + " to be a Float, was " + d(jsonelement)); + } + } + + public static float a(JsonObject jsonobject, String s, float f) { + return jsonobject.has(s) ? d(jsonobject.get(s), s) : f; + } + + public static int f(JsonElement jsonelement, String s) { + if (jsonelement.isJsonPrimitive() && jsonelement.getAsJsonPrimitive().isNumber()) { + return jsonelement.getAsInt(); + } else { + throw new JsonSyntaxException("Expected " + s + " to be a Int, was " + d(jsonelement)); + } + } + + public static int m(JsonObject jsonobject, String s) { + if (jsonobject.has(s)) { + return f(jsonobject.get(s), s); + } else { + throw new JsonSyntaxException("Missing " + s + ", expected to find a Int"); + } + } + + public static int a(JsonObject jsonobject, String s, int i) { + return jsonobject.has(s) ? f(jsonobject.get(s), s) : i; + } + + public static JsonObject l(JsonElement jsonelement, String s) { + if (jsonelement.isJsonObject()) { + return jsonelement.getAsJsonObject(); + } else { + throw new JsonSyntaxException("Expected " + s + " to be a JsonObject, was " + d(jsonelement)); + } + } + + public static JsonArray m(JsonElement jsonelement, String s) { + if (jsonelement.isJsonArray()) { + return jsonelement.getAsJsonArray(); + } else { + throw new JsonSyntaxException("Expected " + s + " to be a JsonArray, was " + d(jsonelement)); + } + } + + public static JsonArray t(JsonObject jsonobject, String s) { + if (jsonobject.has(s)) { + return m(jsonobject.get(s), s); + } else { + throw new JsonSyntaxException("Missing " + s + ", expected to find a JsonArray"); + } + } + + public static String d(JsonElement jsonelement) { + String s = StringUtils.abbreviateMiddle(String.valueOf(jsonelement), "...", 10); + + if (jsonelement == null) { + return "null (missing)"; + } else if (jsonelement.isJsonNull()) { + return "null (json)"; + } else if (jsonelement.isJsonArray()) { + return "an array (" + s + ")"; + } else if (jsonelement.isJsonObject()) { + return "an object (" + s + ")"; + } else { + if (jsonelement.isJsonPrimitive()) { + JsonPrimitive jsonprimitive = jsonelement.getAsJsonPrimitive(); + + if (jsonprimitive.isNumber()) { + return "a number (" + s + ")"; + } + + if (jsonprimitive.isBoolean()) { + return "a boolean (" + s + ")"; + } + } + + return s; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ChatHoverable.java b/azurite-server/src/main/java/net/minecraft/server/ChatHoverable.java new file mode 100644 index 0000000..6c13f31 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ChatHoverable.java @@ -0,0 +1,96 @@ +package net.minecraft.server; + +import com.google.common.collect.Maps; +import java.util.Map; + +public class ChatHoverable { + + private final ChatHoverable.EnumHoverAction a; + private final IChatBaseComponent b; + + public ChatHoverable(ChatHoverable.EnumHoverAction chathoverable_enumhoveraction, IChatBaseComponent ichatbasecomponent) { + this.a = chathoverable_enumhoveraction; + this.b = ichatbasecomponent; + } + + public ChatHoverable.EnumHoverAction a() { + return this.a; + } + + public IChatBaseComponent b() { + return this.b; + } + + public boolean equals(Object object) { + if (this == object) { + return true; + } else if (object != null && this.getClass() == object.getClass()) { + ChatHoverable chathoverable = (ChatHoverable) object; + + if (this.a != chathoverable.a) { + return false; + } else { + if (this.b != null) { + if (!this.b.equals(chathoverable.b)) { + return false; + } + } else if (chathoverable.b != null) { + return false; + } + + return true; + } + } else { + return false; + } + } + + public String toString() { + return "HoverEvent{action=" + this.a + ", value=\'" + this.b + '\'' + '}'; + } + + public int hashCode() { + int i = this.a.hashCode(); + + i = 31 * i + (this.b != null ? this.b.hashCode() : 0); + return i; + } + + public static enum EnumHoverAction { + + SHOW_TEXT("show_text", true), SHOW_ACHIEVEMENT("show_achievement", true), SHOW_ITEM("show_item", true), SHOW_ENTITY("show_entity", true); + + private static final Map e = Maps.newHashMap(); + private final boolean f; + private final String g; + + private EnumHoverAction(String s, boolean flag) { + this.g = s; + this.f = flag; + } + + public boolean a() { + return this.f; + } + + public String b() { + return this.g; + } + + public static ChatHoverable.EnumHoverAction a(String s) { + return (ChatHoverable.EnumHoverAction) ChatHoverable.EnumHoverAction.e.get(s); + } + + static { + ChatHoverable.EnumHoverAction[] achathoverable_enumhoveraction = values(); + int i = achathoverable_enumhoveraction.length; + + for (int j = 0; j < i; ++j) { + ChatHoverable.EnumHoverAction chathoverable_enumhoveraction = achathoverable_enumhoveraction[j]; + + ChatHoverable.EnumHoverAction.e.put(chathoverable_enumhoveraction.b(), chathoverable_enumhoveraction); + } + + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ChatMessage.java b/azurite-server/src/main/java/net/minecraft/server/ChatMessage.java new file mode 100644 index 0000000..6b6936f --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ChatMessage.java @@ -0,0 +1,242 @@ +package net.minecraft.server; + +import com.google.common.collect.Iterators; +import com.google.common.collect.Lists; +import java.util.Arrays; +import java.util.IllegalFormatException; +import java.util.Iterator; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class ChatMessage extends ChatBaseComponent { + + private final String d; + private final Object[] e; + private final Object f = new Object(); + private long g = -1L; + List b = Lists.newArrayList(); + public static final Pattern c = Pattern.compile("%(?:(\\d+)\\$)?([A-Za-z%]|$)"); + + public ChatMessage(String s, Object... aobject) { + this.d = s; + this.e = aobject; + Object[] aobject1 = aobject; + int i = aobject.length; + + for (int j = 0; j < i; ++j) { + Object object = aobject1[j]; + + if (object instanceof IChatBaseComponent) { + ((IChatBaseComponent) object).getChatModifier().setChatModifier(this.getChatModifier()); + } + } + + } + + synchronized void g() { + Object object = this.f; + + synchronized (this.f) { + long i = LocaleI18n.a(); + + if (i == this.g) { + return; + } + + this.g = i; + this.b.clear(); + } + + try { + this.b(LocaleI18n.get(this.d)); + } catch (ChatMessageException chatmessageexception) { + this.b.clear(); + + try { + this.b(LocaleI18n.b(this.d)); + } catch (ChatMessageException chatmessageexception1) { + throw chatmessageexception; + } + } + + } + + protected void b(String s) { + boolean flag = false; + Matcher matcher = ChatMessage.c.matcher(s); + int i = 0; + int j = 0; + + try { + int k; + + for (; matcher.find(j); j = k) { + int l = matcher.start(); + + k = matcher.end(); + if (l > j) { + ChatComponentText chatcomponenttext = new ChatComponentText(String.format(s.substring(j, l), new Object[0])); + + chatcomponenttext.getChatModifier().setChatModifier(this.getChatModifier()); + this.b.add(chatcomponenttext); + } + + String s1 = matcher.group(2); + String s2 = s.substring(l, k); + + if ("%".equals(s1) && "%%".equals(s2)) { + ChatComponentText chatcomponenttext1 = new ChatComponentText("%"); + + chatcomponenttext1.getChatModifier().setChatModifier(this.getChatModifier()); + this.b.add(chatcomponenttext1); + } else { + if (!"s".equals(s1)) { + throw new ChatMessageException(this, "Unsupported format: \'" + s2 + "\'"); + } + + String s3 = matcher.group(1); + int i1 = s3 != null ? Integer.parseInt(s3) - 1 : i++; + + if (i1 < this.e.length) { + this.b.add(this.a(i1)); + } + } + } + + if (j < s.length()) { + ChatComponentText chatcomponenttext2 = new ChatComponentText(String.format(s.substring(j), new Object[0])); + + chatcomponenttext2.getChatModifier().setChatModifier(this.getChatModifier()); + this.b.add(chatcomponenttext2); + } + + } catch (IllegalFormatException illegalformatexception) { + throw new ChatMessageException(this, illegalformatexception); + } + } + + private IChatBaseComponent a(int i) { + if (i >= this.e.length) { + throw new ChatMessageException(this, i); + } else { + Object object = this.e[i]; + Object object1; + + if (object instanceof IChatBaseComponent) { + object1 = (IChatBaseComponent) object; + } else { + object1 = new ChatComponentText(object == null ? "null" : object.toString()); + ((IChatBaseComponent) object1).getChatModifier().setChatModifier(this.getChatModifier()); + } + + return (IChatBaseComponent) object1; + } + } + + public IChatBaseComponent setChatModifier(ChatModifier chatmodifier) { + super.setChatModifier(chatmodifier); + Object[] aobject = this.e; + int i = aobject.length; + + for (int j = 0; j < i; ++j) { + Object object = aobject[j]; + + if (object instanceof IChatBaseComponent) { + ((IChatBaseComponent) object).getChatModifier().setChatModifier(this.getChatModifier()); + } + } + + if (this.g > -1L) { + Iterator iterator = this.b.iterator(); + + while (iterator.hasNext()) { + IChatBaseComponent ichatbasecomponent = (IChatBaseComponent) iterator.next(); + + ichatbasecomponent.getChatModifier().setChatModifier(chatmodifier); + } + } + + return this; + } + + public Iterator iterator() { + this.g(); + return Iterators.concat(a((Iterable) this.b), a((Iterable) this.a)); + } + + public String getText() { + this.g(); + StringBuilder stringbuilder = new StringBuilder(); + Iterator iterator = this.b.iterator(); + + while (iterator.hasNext()) { + IChatBaseComponent ichatbasecomponent = (IChatBaseComponent) iterator.next(); + + stringbuilder.append(ichatbasecomponent.getText()); + } + + return stringbuilder.toString(); + } + + public ChatMessage h() { + Object[] aobject = new Object[this.e.length]; + + for (int i = 0; i < this.e.length; ++i) { + if (this.e[i] instanceof IChatBaseComponent) { + aobject[i] = ((IChatBaseComponent) this.e[i]).f(); + } else { + aobject[i] = this.e[i]; + } + } + + ChatMessage chatmessage = new ChatMessage(this.d, aobject); + + chatmessage.setChatModifier(this.getChatModifier().clone()); + Iterator iterator = this.a().iterator(); + + while (iterator.hasNext()) { + IChatBaseComponent ichatbasecomponent = (IChatBaseComponent) iterator.next(); + + chatmessage.addSibling(ichatbasecomponent.f()); + } + + return chatmessage; + } + + public boolean equals(Object object) { + if (this == object) { + return true; + } else if (!(object instanceof ChatMessage)) { + return false; + } else { + ChatMessage chatmessage = (ChatMessage) object; + + return Arrays.equals(this.e, chatmessage.e) && this.d.equals(chatmessage.d) && super.equals(object); + } + } + + public int hashCode() { + int i = super.hashCode(); + + i = 31 * i + this.d.hashCode(); + i = 31 * i + Arrays.hashCode(this.e); + return i; + } + + public String toString() { + return "TranslatableComponent{key=\'" + this.d + '\'' + ", args=" + Arrays.toString(this.e) + ", siblings=" + this.a + ", style=" + this.getChatModifier() + '}'; + } + + public String i() { + return this.d; + } + + public Object[] j() { + return this.e; + } + + public IChatBaseComponent f() { + return this.h(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ChatMessageException.java b/azurite-server/src/main/java/net/minecraft/server/ChatMessageException.java new file mode 100644 index 0000000..65a5225 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ChatMessageException.java @@ -0,0 +1,16 @@ +package net.minecraft.server; + +public class ChatMessageException extends IllegalArgumentException { + + public ChatMessageException(ChatMessage chatmessage, String s) { + super(String.format("Error parsing: %s: %s", new Object[] { chatmessage, s})); + } + + public ChatMessageException(ChatMessage chatmessage, int i) { + super(String.format("Invalid index %d requested for %s", new Object[] { Integer.valueOf(i), chatmessage})); + } + + public ChatMessageException(ChatMessage chatmessage, Throwable throwable) { + super(String.format("Error while parsing: %s", new Object[] { chatmessage}), throwable); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ChatModifier.java b/azurite-server/src/main/java/net/minecraft/server/ChatModifier.java new file mode 100644 index 0000000..06977fe --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ChatModifier.java @@ -0,0 +1,433 @@ +package net.minecraft.server; + +import com.google.gson.*; + +import java.lang.reflect.Type; + +public class ChatModifier { + + private ChatModifier a; + private EnumChatFormat b; + private Boolean c; + private Boolean d; + private Boolean e; + private Boolean f; + private Boolean g; + private ChatClickable h; + private ChatHoverable i; + private String j; + private static final ChatModifier k = new ChatModifier() { + public EnumChatFormat getColor() { + return null; + } + + public boolean isBold() { + return false; + } + + public boolean isItalic() { + return false; + } + + public boolean isStrikethrough() { + return false; + } + + public boolean isUnderlined() { + return false; + } + + public boolean isRandom() { + return false; + } + + public ChatClickable h() { + return null; + } + + public ChatHoverable i() { + return null; + } + + public String j() { + return null; + } + + public ChatModifier setColor(EnumChatFormat enumchatformat) { + throw new UnsupportedOperationException(); + } + + public ChatModifier setBold(Boolean obool) { + throw new UnsupportedOperationException(); + } + + public ChatModifier setItalic(Boolean obool) { + throw new UnsupportedOperationException(); + } + + public ChatModifier setStrikethrough(Boolean obool) { + throw new UnsupportedOperationException(); + } + + public ChatModifier setUnderline(Boolean obool) { + throw new UnsupportedOperationException(); + } + + public ChatModifier setRandom(Boolean obool) { + throw new UnsupportedOperationException(); + } + + public ChatModifier setChatClickable(ChatClickable chatclickable) { + throw new UnsupportedOperationException(); + } + + public ChatModifier setChatHoverable(ChatHoverable chathoverable) { + throw new UnsupportedOperationException(); + } + + public ChatModifier setChatModifier(ChatModifier chatmodifier) { + throw new UnsupportedOperationException(); + } + + public String toString() { + return "Style.ROOT"; + } + + public ChatModifier clone() { + return this; + } + + public ChatModifier n() { + return this; + } + }; + + public ChatModifier() {} + + public EnumChatFormat getColor() { + return this.b == null ? this.o().getColor() : this.b; + } + + public boolean isBold() { + return this.c == null ? this.o().isBold() : this.c; + } + + public boolean isItalic() { + return this.d == null ? this.o().isItalic() : this.d; + } + + public boolean isStrikethrough() { + return this.f == null ? this.o().isStrikethrough() : this.f; + } + + public boolean isUnderlined() { + return this.e == null ? this.o().isUnderlined() : this.e; + } + + public boolean isRandom() { + return this.g == null ? this.o().isRandom() : this.g; + } + + public boolean g() { + return this.c == null && this.d == null && this.f == null && this.e == null && this.g == null && this.b == null && this.h == null && this.i == null; + } + + public ChatClickable h() { + return this.h == null ? this.o().h() : this.h; + } + + public ChatHoverable i() { + return this.i == null ? this.o().i() : this.i; + } + + public String j() { + return this.j == null ? this.o().j() : this.j; + } + + public ChatModifier setColor(EnumChatFormat enumchatformat) { + this.b = enumchatformat; + return this; + } + + public ChatModifier setBold(Boolean obool) { + this.c = obool; + return this; + } + + public ChatModifier setItalic(Boolean obool) { + this.d = obool; + return this; + } + + public ChatModifier setStrikethrough(Boolean obool) { + this.f = obool; + return this; + } + + public ChatModifier setUnderline(Boolean obool) { + this.e = obool; + return this; + } + + public ChatModifier setRandom(Boolean obool) { + this.g = obool; + return this; + } + + public ChatModifier setChatClickable(ChatClickable chatclickable) { + this.h = chatclickable; + return this; + } + + public ChatModifier setChatHoverable(ChatHoverable chathoverable) { + this.i = chathoverable; + return this; + } + + public ChatModifier setInsertion(String s) { + this.j = s; + return this; + } + + public ChatModifier setChatModifier(ChatModifier chatmodifier) { + this.a = chatmodifier; + return this; + } + + private ChatModifier o() { + return this.a == null ? ChatModifier.k : this.a; + } + + public String toString() { + return "Style{hasParent=" + (this.a != null) + ", color=" + this.b + ", bold=" + this.c + ", italic=" + this.d + ", underlined=" + this.e + ", obfuscated=" + this.g + ", clickEvent=" + this.h() + ", hoverEvent=" + this.i() + ", insertion=" + this.j() + '}'; + } + + public boolean equals(Object object) { + if (this == object) { + return true; + } else if (!(object instanceof ChatModifier)) { + return false; + } else { + ChatModifier chatmodifier = (ChatModifier) object; + + if (this.isBold() == chatmodifier.isBold() && this.getColor() == chatmodifier.getColor() && this.isItalic() == chatmodifier.isItalic() && this.isRandom() == chatmodifier.isRandom() && this.isStrikethrough() == chatmodifier.isStrikethrough() && this.isUnderlined() == chatmodifier.isUnderlined()) { + label65: { + if (this.h() != null) { + if (!this.h().equals(chatmodifier.h())) { + break label65; + } + } else if (chatmodifier.h() != null) { + break label65; + } + + if (this.i() != null) { + if (!this.i().equals(chatmodifier.i())) { + break label65; + } + } else if (chatmodifier.i() != null) { + break label65; + } + + if (this.j() != null) { + if (!this.j().equals(chatmodifier.j())) { + break label65; + } + } else if (chatmodifier.j() != null) { + break label65; + } + + return true; + } + } + + return false; + } + } + + public int hashCode() { + // CraftBukkit start - fix npe + int i = b == null ? 0 : this.b.hashCode(); + + i = 31 * i + (c == null ? 0 : this.c.hashCode()); + i = 31 * i + (d == null ? 0 : this.d.hashCode()); + i = 31 * i + (e == null ? 0 : this.e.hashCode()); + i = 31 * i + (f == null ? 0 : this.f.hashCode()); + i = 31 * i + (g == null ? 0 : this.g.hashCode()); + i = 31 * i + (h == null ? 0 : this.h.hashCode()); + i = 31 * i + (this.i == null ? 0 : this.i.hashCode()); + i = 31 * i + (j == null ? 0 : this.j.hashCode()); + // CraftBukkit end + return i; + } + + public ChatModifier clone() { + ChatModifier chatmodifier = new ChatModifier(); + + chatmodifier.c = this.c; + chatmodifier.d = this.d; + chatmodifier.f = this.f; + chatmodifier.e = this.e; + chatmodifier.g = this.g; + chatmodifier.b = this.b; + chatmodifier.h = this.h; + chatmodifier.i = this.i; + chatmodifier.a = this.a; + chatmodifier.j = this.j; + return chatmodifier; + } + + public ChatModifier n() { + ChatModifier chatmodifier = new ChatModifier(); + + chatmodifier.setBold(this.isBold()); + chatmodifier.setItalic(this.isItalic()); + chatmodifier.setStrikethrough(this.isStrikethrough()); + chatmodifier.setUnderline(this.isUnderlined()); + chatmodifier.setRandom(this.isRandom()); + chatmodifier.setColor(this.getColor()); + chatmodifier.setChatClickable(this.h()); + chatmodifier.setChatHoverable(this.i()); + chatmodifier.setInsertion(this.j()); + return chatmodifier; + } + + public static class ChatModifierSerializer implements JsonDeserializer, JsonSerializer { + + public ChatModifierSerializer() {} + + public ChatModifier a(JsonElement jsonelement, Type type, JsonDeserializationContext jsondeserializationcontext) throws JsonParseException { + if (jsonelement.isJsonObject()) { + ChatModifier chatmodifier = new ChatModifier(); + JsonObject jsonobject = jsonelement.getAsJsonObject(); + + if (jsonobject == null) { + return null; + } else { + if (jsonobject.has("bold")) { + chatmodifier.c = jsonobject.get("bold").getAsBoolean(); + } + + if (jsonobject.has("italic")) { + chatmodifier.d = jsonobject.get("italic").getAsBoolean(); + } + + if (jsonobject.has("underlined")) { + chatmodifier.e = jsonobject.get("underlined").getAsBoolean(); + } + + if (jsonobject.has("strikethrough")) { + chatmodifier.f = jsonobject.get("strikethrough").getAsBoolean(); + } + + if (jsonobject.has("obfuscated")) { + chatmodifier.g = jsonobject.get("obfuscated").getAsBoolean(); + } + + if (jsonobject.has("color")) { + chatmodifier.b = jsondeserializationcontext.deserialize(jsonobject.get("color"), EnumChatFormat.class); + } + + if (jsonobject.has("insertion")) { + chatmodifier.j = jsonobject.get("insertion").getAsString(); + } + + JsonObject jsonobject1; + JsonPrimitive jsonprimitive; + + if (jsonobject.has("clickEvent")) { + jsonobject1 = jsonobject.getAsJsonObject("clickEvent"); + if (jsonobject1 != null) { + jsonprimitive = jsonobject1.getAsJsonPrimitive("action"); + ChatClickable.EnumClickAction chatclickable_enumclickaction = jsonprimitive == null ? null : ChatClickable.EnumClickAction.a(jsonprimitive.getAsString()); + JsonPrimitive jsonprimitive1 = jsonobject1.getAsJsonPrimitive("value"); + String s = jsonprimitive1 == null ? null : jsonprimitive1.getAsString(); + + if (chatclickable_enumclickaction != null && s != null && chatclickable_enumclickaction.a()) { + chatmodifier.h = new ChatClickable(chatclickable_enumclickaction, s); + } + } + } + + if (jsonobject.has("hoverEvent")) { + jsonobject1 = jsonobject.getAsJsonObject("hoverEvent"); + if (jsonobject1 != null) { + jsonprimitive = jsonobject1.getAsJsonPrimitive("action"); + ChatHoverable.EnumHoverAction chathoverable_enumhoveraction = jsonprimitive == null ? null : ChatHoverable.EnumHoverAction.a(jsonprimitive.getAsString()); + IChatBaseComponent ichatbasecomponent = jsondeserializationcontext.deserialize(jsonobject1.get("value"), IChatBaseComponent.class); + + if (chathoverable_enumhoveraction != null && ichatbasecomponent != null && chathoverable_enumhoveraction.a()) { + chatmodifier.i = new ChatHoverable(chathoverable_enumhoveraction, ichatbasecomponent); + } + } + } + + return chatmodifier; + } + } else { + return null; + } + } + + public JsonElement a(ChatModifier chatmodifier, Type type, JsonSerializationContext jsonserializationcontext) { + if (chatmodifier.g()) { + return null; + } else { + JsonObject jsonobject = new JsonObject(); + + if (chatmodifier.c != null) { + jsonobject.addProperty("bold", chatmodifier.c); + } + + if (chatmodifier.d != null) { + jsonobject.addProperty("italic", chatmodifier.d); + } + + if (chatmodifier.e != null) { + jsonobject.addProperty("underlined", chatmodifier.e); + } + + if (chatmodifier.f != null) { + jsonobject.addProperty("strikethrough", chatmodifier.f); + } + + if (chatmodifier.g != null) { + jsonobject.addProperty("obfuscated", chatmodifier.g); + } + + if (chatmodifier.b != null) { + jsonobject.add("color", jsonserializationcontext.serialize(chatmodifier.b)); + } + + if (chatmodifier.j != null) { + jsonobject.add("insertion", jsonserializationcontext.serialize(chatmodifier.j)); + } + + JsonObject jsonobject1; + + if (chatmodifier.h != null) { + jsonobject1 = new JsonObject(); + jsonobject1.addProperty("action", chatmodifier.h.a().b()); + jsonobject1.addProperty("value", chatmodifier.h.b()); + jsonobject.add("clickEvent", jsonobject1); + } + + if (chatmodifier.i != null) { + jsonobject1 = new JsonObject(); + jsonobject1.addProperty("action", chatmodifier.i.a().b()); + jsonobject1.add("value", jsonserializationcontext.serialize(chatmodifier.i.b())); + jsonobject.add("hoverEvent", jsonobject1); + } + + return jsonobject; + } + } + + public JsonElement serialize(ChatModifier object, Type type, JsonSerializationContext jsonserializationcontext) { // CraftBukkit - fix decompile error + return this.a(object, type, jsonserializationcontext); + } + + public ChatModifier deserialize(JsonElement jsonelement, Type type, JsonDeserializationContext jsondeserializationcontext) throws JsonParseException { // CraftBukkit - fix decompile error + return this.a(jsonelement, type, jsondeserializationcontext); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ChatTypeAdapterFactory.java b/azurite-server/src/main/java/net/minecraft/server/ChatTypeAdapterFactory.java new file mode 100644 index 0000000..2f2dbcd --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ChatTypeAdapterFactory.java @@ -0,0 +1,60 @@ +package net.minecraft.server; + +import com.google.common.collect.Maps; +import com.google.gson.Gson; +import com.google.gson.TypeAdapter; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonToken; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.HashMap; +import java.util.Locale; + +public class ChatTypeAdapterFactory implements TypeAdapterFactory { + + public ChatTypeAdapterFactory() {} + + public TypeAdapter create(Gson gson, TypeToken typetoken) { + Class oclass = typetoken.getRawType(); + + if (!oclass.isEnum()) { + return null; + } else { + final HashMap hashmap = Maps.newHashMap(); + Object[] aobject = oclass.getEnumConstants(); + int i = aobject.length; + + for (int j = 0; j < i; ++j) { + Object object = aobject[j]; + + hashmap.put(this.a(object), (T) object); + } + + return new TypeAdapter() { + public void write(JsonWriter jsonwriter, T t0) throws IOException { + if (t0 == null) { + jsonwriter.nullValue(); + } else { + jsonwriter.value(ChatTypeAdapterFactory.this.a(t0)); + } + + } + + public T read(JsonReader jsonreader) throws IOException { + if (jsonreader.peek() == JsonToken.NULL) { + jsonreader.nextNull(); + return null; + } else { + return hashmap.get(jsonreader.nextString()); + } + } + }; + } + } + + private String a(Object object) { + return object instanceof Enum ? ((Enum) object).name().toLowerCase(Locale.US) : object.toString().toLowerCase(Locale.US); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ChestLock.java b/azurite-server/src/main/java/net/minecraft/server/ChestLock.java new file mode 100644 index 0000000..cfee9f0 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ChestLock.java @@ -0,0 +1,33 @@ +package net.minecraft.server; + +public class ChestLock { + + public static final ChestLock a = new ChestLock(""); + private final String b; + + public ChestLock(String s) { + this.b = s; + } + + public boolean a() { + return this.b == null || this.b.isEmpty(); + } + + public String b() { + return this.b; + } + + public void a(NBTTagCompound nbttagcompound) { + nbttagcompound.setString("Lock", this.b); + } + + public static ChestLock b(NBTTagCompound nbttagcompound) { + if (nbttagcompound.hasKeyOfType("Lock", 8)) { + String s = nbttagcompound.getString("Lock"); + + return new ChestLock(s); + } else { + return ChestLock.a; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/Chunk.java b/azurite-server/src/main/java/net/minecraft/server/Chunk.java new file mode 100644 index 0000000..97188fa --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/Chunk.java @@ -0,0 +1,1623 @@ +package net.minecraft.server; + +import com.google.common.base.Predicate; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import dev.azurite.spigot.configs.AzuriteConfig; +import dev.azurite.spigot.optimizations.ObjectMapList; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.bukkit.Bukkit; +import org.bukkit.craftbukkit.util.LongHash; + +import java.util.*; +import java.util.concurrent.atomic.AtomicInteger; + +public class Chunk { + + private static final Logger c = LogManager.getLogger(); + public final World world; + public final int[] heightMap; + public final int locX; + public final int locZ; + public final Map tileEntities; + public final List[] entitySlices; + private final ChunkSection[] sections; + private final byte[] e; + private final int[] f; + private final boolean[] g; + private final int[] itemCounts = new int[16]; + private final int[] inventoryEntityCounts = new int[16]; + public AtomicInteger pendingLightUpdates = new AtomicInteger(); + public long lightUpdateTime; + public org.bukkit.Chunk bukkitChunk; + public boolean mustSave; + protected gnu.trove.map.hash.TObjectIntHashMap> entityCount = new gnu.trove.map.hash.TObjectIntHashMap<>(); // Spigot + private boolean h; + private boolean k; + private boolean done; + private boolean lit; + public boolean q; + private boolean r; + private long lastSaved; + private int t; + private long u; + private int v; + private PacketPlayOutMapChunk.ChunkMap chunkMap; + private int emptySectionBits; + + // CraftBukkit start - Neighbor loaded cache for chunk lighting and entity ticking + private int neighbors = 0x1 << 12; + + // Vortex - start + public final long chunkHashKey; + private final BlockPosition chunkPosition; + private final ChunkCoordIntPair chunkCoord; + private final Random chunkRandom; // cache random in EntitySlime + // Vortex - end + + public Chunk(World world, int i, int j) { + this.sections = new ChunkSection[16]; + this.e = new byte[256]; + this.f = new int[256]; + this.g = new boolean[256]; + this.tileEntities = Maps.newHashMap(); + this.v = 4096; + this.entitySlices = new List[16]; // Spigot + this.world = world; + this.locX = i; + this.locZ = j; + this.heightMap = new int[256]; + + // Vortex - start + chunkHashKey = LongHash.toLong(locX, locZ); + chunkCoord = new ChunkCoordIntPair(locX, locZ); + chunkRandom = new Random(world.getSeed() + (locX * locX * 4987142L) + (locX * 5947611L) + (locZ * locZ * 4392871L) + (locZ * 389711L) ^ 987234911L); + chunkPosition = new BlockPosition(locX << 4, 0, locZ << 4); + + for (int k = 0; k < this.entitySlices.length; ++k) { + this.entitySlices[k] = new ObjectMapList<>(Entity.class); // Azurite - Object map list from SpottedLeaf instead of UnsafeList + } + // Vortex - end + + Arrays.fill(this.f, -999); + Arrays.fill(this.e, (byte) -1); + + // CraftBukkit start + if (!(this instanceof EmptyChunk)) { + this.bukkitChunk = new org.bukkit.craftbukkit.CraftChunk(this); + } + } + + //Vortex End + + public Chunk(World world, ChunkSnapshot chunksnapshot, int i, int j) { + this(world, i, j); + boolean flag = !world.worldProvider.o(); + + for (int k = 0; k < 16; ++k) { + for (int l = 0; l < 16; ++l) { + for (int i1 = 0; i1 < 256; ++i1) { + int j1 = k * 256 * 16 | l * 256 | i1; + IBlockData iblockdata = chunksnapshot.a(j1); + + if (iblockdata.getBlock().getMaterial() != Material.AIR) { + int k1 = i1 >> 4; + + ChunkSection section = sections[k1]; + if (section == null) { + section = new ChunkSection(k1 << 4, flag, world.shouldSectionsHaveTickList()); + sections[k1] = section; + } + + section.setType(k, i1 & 15, l, iblockdata); + } + } + } + } + + } + + public PacketPlayOutMapChunk.ChunkMap getChunkMap(boolean groundUpContinuous, int primaryBitMask) { + if (!AzuriteConfig.cacheChunkMaps.getValue() || !groundUpContinuous || (primaryBitMask != 0 && primaryBitMask != '\uffff')) { + return PacketPlayOutMapChunk.serializeToChunkMap(this, groundUpContinuous, !world.worldProvider.o(), primaryBitMask); + } + + if (primaryBitMask == 0) { + PacketPlayOutMapChunk.ChunkMap chunkMap = new PacketPlayOutMapChunk.ChunkMap(); + chunkMap.a = new byte[0]; + return chunkMap; + } + + boolean isDirty = false; + for (int i = 0; i < sections.length; ++i) { + ChunkSection section = sections[i]; + if (section == null) { + if ((emptySectionBits & (1 << i)) == 0) { + isDirty = true; + emptySectionBits |= (1 << i); + } + } else { + if ((emptySectionBits & (1 << i)) == 1) { + isDirty = true; + emptySectionBits &= ~(1 << i); + section.isDirty = false; + } else if (section.isDirty) { + isDirty = true; + section.isDirty = false; + } + } + } + + if (isDirty || chunkMap == null) { + chunkMap = PacketPlayOutMapChunk.serializeToChunkMap(this, true, !world.worldProvider.o(), '\uffff'); + } + + return chunkMap; + } + // CraftBukkit end + + public boolean areNeighborsLoaded(int radius) { + switch (radius) { + case 2: + return neighbors == Integer.MAX_VALUE >> 6; + case 1: + final int mask = + // x z offset x z offset x z offset + (0x1 << (5 + 1 + 12)) | (0x1 << (1 + 12)) | (0x1 << (-1 * 5 + 1 + 12)) | + (0x1 << (5 + 12)) | (0x1 << (12)) | (0x1 << (-1 * 5 + 12)) | + (0x1 << (5 - 1 + 12)) | (0x1 << (-1 + 12)) | (0x1 << (-1 * 5 - 1 + 12)); + return (neighbors & mask) == mask; + default: + throw new UnsupportedOperationException(String.valueOf(radius)); + } + } + + //Vortex Start + public IBlockData getBlockData(int x, int y, int z) { + if (y >= 0 && y >> 4 < this.sections.length) { + ChunkSection chunksection = this.sections[y >> 4]; + if (chunksection != null) { + return chunksection.getType(x & 15, y & 15, z & 15); + } + } + return Blocks.AIR.getBlockData(); + } + + public void setNeighborLoaded(int x, int z) { + neighbors |= 0x1 << (x * 5 + 12 + z); + } + // CraftBukkit end + + public void setNeighborUnloaded(int x, int z) { + neighbors &= ~(0x1 << (x * 5 + 12 + z)); + } + + public boolean a(int i, int j) { + return i == locX && j == locZ; + } + + public int f(BlockPosition blockposition) { + return b(blockposition.getX() & 15, blockposition.getZ() & 15); + } + + public int f(int x, int z) { + return b(x & 15, z & 15); + } + + public int b(int i, int j) { + return heightMap[j << 4 | i]; + } + + public int g() { + for (int i = sections.length - 1; i >= 0; --i) { + ChunkSection section = sections[i]; + if (section != null) + return section.getYPosition(); + } + + return 0; + } + + public ChunkSection[] getSections() { + return this.sections; + } + + public ChunkSection getSection(int y) { + if (y >= 0 && y >> 4 < this.sections.length) { + return this.sections[y >> 4]; + } + return null; + } + + public void initLighting() { + int i = g(); + + t = Integer.MAX_VALUE; + + for (int j = 0; j < 16; ++j) { + int k = 0; + + while (k < 16) { + this.f[j + (k << 4)] = -999; + int l = i + 16; + + while (true) { + if (l > 0) { + if (this.e(j, l - 1, k) == 0) { + --l; + continue; + } + + this.heightMap[k << 4 | j] = l; + if (l < this.t) { + this.t = l; + } + } + + if (!this.world.worldProvider.o()) { + l = 15; + int i1 = i + 16 - 1; + BlockPosition.MutableBlockPosition blockPosition = new BlockPosition.MutableBlockPosition(); // Azurite + + do { + int j1 = this.e(j, i1, k); + + if (j1 == 0 && l != 15) { + j1 = 1; + } + + l -= j1; + if (l > 0) { + ChunkSection chunksection = this.sections[i1 >> 4]; + + if (chunksection != null) { + chunksection.a(j, i1 & 15, k, l); + blockPosition.setValues(chunkPosition.getX() + j, i1, chunkPosition.getZ() + k); + this.world.n(blockPosition); + } + } + + --i1; + } while (i1 > 0 && l > 0); + } + + ++k; + break; + } + } + } + + this.q = true; + } + + private void d(int i, int j) { + this.g[i + j * 16] = true; + this.k = true; + } + + public int a(int x, int y, int z, int i) { + int j = x & 15; + int l = z & 15; + ChunkSection chunksection = this.sections[y >> 4]; + + if (chunksection == null) { + return !this.world.worldProvider.o() && i < EnumSkyBlock.SKY.c ? EnumSkyBlock.SKY.c - i : 0; + } else { + int i1 = this.world.worldProvider.o() ? 0 : chunksection.d(j, y & 15, l); + + i1 -= i; + int j1 = chunksection.e(j, y & 15, l); + + if (j1 > i1) { + i1 = j1; + } + + return i1; + } + } + + private void h(boolean flag) { + if (areNeighborsLoaded(1)) { + for (int i = 0; i < 16; ++i) { + for (int j = 0; j < 16; ++j) { + int index = i + j * 16; // VortexSpigot + if (g[index]) { + g[index] = false; + int k = this.b(i, j); + int l = this.locX * 16 + i; + int i1 = this.locZ * 16 + j; + int j1 = Integer.MAX_VALUE; + + for (EnumDirection enumdirection : EnumDirection.EnumDirectionLimit.HORIZONTAL) { + j1 = Math.min(j1, world.b(l + enumdirection.getAdjacentX(), i1 + enumdirection.getAdjacentZ(), true)); + } + + c(l, i1, j1, true); + + for (EnumDirection enumdirection : EnumDirection.EnumDirectionLimit.HORIZONTAL) { + c(l + enumdirection.getAdjacentX(), i1 + enumdirection.getAdjacentZ(), k, true); + } + + if (flag) { + return; + } + } + } + } + this.k = false; + } + } + + private void c(int i, int j, int k) { + c(i, j, k, false); + } + + private void c(int i, int j, int k, boolean chunkAlreadyLoaded) { + int l = world.getHighestBlockYAt(i, j, chunkAlreadyLoaded); + + if (l > k) { + a(i, j, k, l + 1, !AzuriteConfig.disableBlockLighting.getValue()); + } else if (l < k) { + a(i, j, l, k + 1, !AzuriteConfig.disableBlockLighting.getValue()); + } + + } + + public void a(EnumSkyBlock enumskyblock, int x, int y, int z, int i) { + ChunkSection chunksection = this.sections[y >> 4]; + + if (chunksection == null) { + chunksection = this.sections[y >> 4] = new ChunkSection(y >> 4 << 4, !this.world.worldProvider.o(), world.shouldSectionsHaveTickList()); + this.initLighting(); + } + + this.q = true; + if (enumskyblock == EnumSkyBlock.SKY) { + if (!this.world.worldProvider.o()) { + chunksection.a(x & 15, y & 15, z & 15, i); + } + } else if (enumskyblock == EnumSkyBlock.BLOCK) { + chunksection.b(x & 15, y & 15, z & 15, i); + } + + } + + private void a(int i, int j, int k, int l, boolean lightUpdate) { + if (l > k) { + Chunk chunk = this.world.getChunkIfLoaded(i >> 4, j >> 4); // Vortex + if (chunk == null || !chunk.areNeighborsLoaded(1)) + return; + if (lightUpdate) + for (int i1 = k; i1 < l; ++i1) + this.world.updateLight(EnumSkyBlock.SKY, i, i1, j, chunk); // PaperSpigot - Asynchronous lighting updates + this.q = true; + } + } + + private void d(int i, int j, int k, boolean lightUpdate) { + int l = this.heightMap[k << 4 | i] & 255; + int i1 = Math.max(j, l); + + while (i1 > 0 && this.e(i, i1 - 1, k) == 0) { + --i1; + } + + if (i1 != l) { + this.world.a(i + this.locX * 16, k + this.locZ * 16, i1, l); + this.heightMap[k << 4 | i] = i1; + int j1 = this.locX * 16 + i; + int k1 = this.locZ * 16 + k; + int l1; + int i2; + + if (!this.world.worldProvider.o()) { + ChunkSection chunksection; + + if (i1 < l) { + for (l1 = i1; l1 < l; ++l1) { + chunksection = this.sections[l1 >> 4]; + if (chunksection != null) { + chunksection.a(i, l1 & 15, k, 15); + this.world.n(new BlockPosition(chunkPosition.getX() + i, l1, chunkPosition.getZ() + k)); + } + } + } else { + for (l1 = l; l1 < i1; ++l1) { + chunksection = this.sections[l1 >> 4]; + if (chunksection != null) { + chunksection.a(i, l1 & 15, k, 0); + this.world.n(new BlockPosition(chunkPosition.getX() + i, l1, chunkPosition.getZ() + k)); + } + } + } + + l1 = 15; + + while (i1 > 0 && l1 > 0) { + --i1; + i2 = this.e(i, i1, k); + if (i2 == 0) { + i2 = 1; + } + + l1 -= i2; + if (l1 < 0) { + l1 = 0; + } + + ChunkSection chunksection1 = this.sections[i1 >> 4]; + + if (chunksection1 != null) { + chunksection1.a(i, i1 & 15, k, l1); + } + } + } + + l1 = this.heightMap[k << 4 | i]; + i2 = l; + int j2 = l1; + + if (l1 < l) { + i2 = l1; + j2 = l; + } + + if (l1 < this.t) { + this.t = l1; + } + + if (!this.world.worldProvider.o()) { + for (EnumDirection enumdirection : EnumDirection.EnumDirectionLimit.HORIZONTAL) { + this.a(j1 + enumdirection.getAdjacentX(), k1 + enumdirection.getAdjacentZ(), i2, j2, lightUpdate); + } + + this.a(j1, k1, i2, j2, lightUpdate); + } + + this.q = true; + } + } + + public int b(BlockPosition blockposition) { + return this.getType(blockposition).p(); + } + + private int e(int i, int j, int k) { + return this.getType(i, j, k).p(); + } + + public Block getType(int i, int j, int k) { + Block block = Blocks.AIR; + + if (j >= 0 && j >> 4 < this.sections.length) { + ChunkSection chunksection = this.sections[j >> 4]; + + if (chunksection != null) { + try { + block = chunksection.b(i, j & 15, k); + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.a(throwable, "Getting block"); + + throw new ReportedException(crashreport); + } + } + } + + return block; + } + + public Block getTypeAbs(int i, int j, int k) { + try { + return getType(i & 15, j, k & 15); + } catch (ReportedException reportedexception) { + CrashReportSystemDetails crashreportsystemdetails = reportedexception.a().a("Block being got"); + crashreportsystemdetails.a("Location", () -> CrashReportSystemDetails.a(new BlockPosition(Chunk.this.locX * 16 + i, j, Chunk.this.locZ * 16 + k))); + throw reportedexception; + } + } + + public Block getType(BlockPosition blockposition) { + try { + return getType(blockposition.getX() & 15, blockposition.getY(), blockposition.getZ() & 15); + } catch (ReportedException reportedexception) { + CrashReportSystemDetails crashreportsystemdetails = reportedexception.a().a("Block being got"); + + crashreportsystemdetails.a("Location", () -> CrashReportSystemDetails.a(blockposition)); + throw reportedexception; + } + } + + public IBlockData a(BlockPosition blockposition, IBlockData iblockdata) { + return a(blockposition, iblockdata, true); + } + + public IBlockData a(BlockPosition blockposition, IBlockData iblockdata, boolean lightUpdate) { + if (lightUpdate && AzuriteConfig.disableBlockLighting.getValue()) + lightUpdate = false; + int i = blockposition.getX() & 15, j = blockposition.getY(), k = blockposition.getZ() & 15; + int l = k << 4 | i; + + if (j >= this.f[l] - 1) { + this.f[l] = -999; + } + + int i1 = this.heightMap[l]; + IBlockData iblockdata1 = this.getBlockData(blockposition); + + if (iblockdata1 == iblockdata) { + return null; + } else { + Block block = iblockdata.getBlock(); + Block block1 = iblockdata1.getBlock(); + ChunkSection chunksection = this.sections[j >> 4]; + boolean flag = false; + + if (chunksection == null) { + if (block == Blocks.AIR) { + return null; + } + + chunksection = this.sections[j >> 4] = new ChunkSection(j >> 4 << 4, !this.world.worldProvider.o(), world.shouldSectionsHaveTickList()); + flag = j >= i1; + } + + chunksection.setType(i, j & 15, k, iblockdata); + if (block1 != block) { + block1.remove(this.world, blockposition, iblockdata1); + } + + if (chunksection.getType(i, j & 15, k).getBlock() != block) { + return null; + } else { + if (flag) { + this.initLighting(); + } else { + int j1 = block.p(); + int k1 = block1.p(); + + if (j1 > 0) { + if (j >= i1) { + this.d(i, j + 1, k, lightUpdate); + } + } else if (j == i1 - 1) { + this.d(i, j, k, lightUpdate); + } + + if (j1 != k1 && (j1 < k1 || this.getBrightness(EnumSkyBlock.SKY, blockposition) > 0 || this.getBrightness(EnumSkyBlock.BLOCK, blockposition) > 0)) { + this.d(i, k); + } + } + + TileEntity tileentity; + + if (block1 instanceof IContainer) { + tileentity = this.a(blockposition, Chunk.EnumTileEntityState.CHECK); + if (tileentity != null) { + tileentity.E(); + } + } + + // CraftBukkit - Don't place while processing the BlockPlaceEvent, unless it's a + // BlockContainer. Prevents blocks such as TNT from activating when cancelled. + if (block1 != block && (!world.captureBlockStates || block instanceof BlockContainer)) { + block.onPlace(world, blockposition, iblockdata); + } + + if (block instanceof IContainer) { + tileentity = this.a(blockposition, Chunk.EnumTileEntityState.CHECK); + if (tileentity == null) { + tileentity = ((IContainer) block).a(this.world, block.toLegacyData(iblockdata)); + world.setTileEntity(blockposition, tileentity); + } + + if (tileentity != null) { + tileentity.E(); + } + } + + this.q = true; + return iblockdata1; + } + } + } + + // PaperSpigot start - Optimize getBlockData + public IBlockData getBlockData(BlockPosition blockposition) { + return getBlockData(blockposition.getX(), blockposition.getY(), blockposition.getZ()); + } + + private int g(int i, int j, int k) { + if (j >> 4 >= this.sections.length) { + return 0; + } else { + ChunkSection chunksection = this.sections[j >> 4]; + + return chunksection != null ? chunksection.c(i, j & 15, k) : 0; + } + } + + public int c(BlockPosition blockposition) { + return this.g(blockposition.getX() & 15, blockposition.getY(), blockposition.getZ() & 15); + } + + public int getBrightness(EnumSkyBlock enumskyblock, int x, int y, int z) { + int i = x & 15; + int k = z & 15; + ChunkSection chunksection = this.sections[y >> 4]; + return chunksection == null ? (this.d(x, y, z) ? enumskyblock.c : 0) + : (enumskyblock == EnumSkyBlock.SKY ? (this.world.worldProvider.o() ? 0 : chunksection.d(i, y & 15, k)) + : (enumskyblock == EnumSkyBlock.BLOCK ? chunksection.e(i, y & 15, k) : enumskyblock.c)); + } + + public int getBrightness(EnumSkyBlock enumskyblock, BlockPosition blockposition) { + return getBrightness(enumskyblock, blockposition.getX(), blockposition.getY(), blockposition.getZ()); + } + + public void a(EnumSkyBlock enumskyblock, BlockPosition blockposition, int i) { + int j = blockposition.getX() & 15, k = blockposition.getY(), l = blockposition.getZ() & 15; + ChunkSection chunksection = this.sections[k >> 4]; + + if (chunksection == null) { + chunksection = this.sections[k >> 4] = new ChunkSection(k >> 4 << 4, !this.world.worldProvider.o(), world.shouldSectionsHaveTickList()); + this.initLighting(); + } + + this.q = true; + if (enumskyblock == EnumSkyBlock.SKY) { + if (!this.world.worldProvider.o()) { + chunksection.a(j, k & 15, l, i); + } + } else if (enumskyblock == EnumSkyBlock.BLOCK) { + chunksection.b(j, k & 15, l, i); + } + + } + + // Vortex Start + public boolean d(int x, int y, int z) { + return y >= this.heightMap[z & 15 << 4 | x & 15]; + } + + public BiomeBase getBiome(int x, int z, WorldChunkManager worldchunkmanager) { + int i = x & 15; + int j = z & 15; + int k = this.e[j << 4 | i] & 255; + BiomeBase biomebase; + + if (k == 255) { + k = BiomeBase.PLAINS.id; // Azurite + this.e[j << 4 | i] = (byte) (k & 255); + } + + biomebase = BiomeBase.getBiome(k); + return biomebase == null ? BiomeBase.PLAINS : biomebase; + } + + // Vortex End + + public int a(BlockPosition blockposition, int i) { + return a(blockposition.getX(), blockposition.getY(), blockposition.getZ(), i); + } + + public void addCannonEntity(Entity entity) { + r = true; + int k = MathHelper.floor(entity.locY / 16.0D); + if (k < 0) { + k = 0; + } + if (k >= entitySlices.length) { + k = entitySlices.length - 1; + } + entity.ad = true; + entity.ae = locX; + entity.af = k; + entity.ag = locZ; + entitySlices[k].add(entity); + } + + public void a(Entity entity) { + this.r = true; + int i = MathHelper.floor(entity.locX / 16.0D); + int j = MathHelper.floor(entity.locZ / 16.0D); + + if (i != this.locX || j != this.locZ) { + // CraftBukkit start + Bukkit.getLogger().warning("Wrong location for " + entity + " in world '" + world.getWorld().getName() + "'!"); + // Chunk.c.warn("Wrong location! (" + i + ", " + j + ") should be (" + this.locX + ", " + this.locZ + "), " + entity, new Object[] { entity}); + Bukkit.getLogger().warning("Entity is at " + entity.locX + "," + entity.locZ + " (chunk " + i + "," + j + ") but was stored in chunk " + this.locX + "," + this.locZ); + // CraftBukkit end + entity.die(); + } + + int k = MathHelper.floor(entity.locY / 16.0D); + + if (k < 0) { + k = 0; + } + + if (k >= entitySlices.length) { + k = entitySlices.length - 1; + } + + entity.ad = true; + entity.ae = this.locX; + entity.af = k; + entity.ag = this.locZ; + + entitySlices[k].add(entity); + + // PaperSpigot start - update counts + if (entity instanceof EntityItem) { + itemCounts[k]++; + } else if (entity instanceof IInventory) { + inventoryEntityCounts[k]++; + } + // PaperSpigot end + + // Spigot start - increment creature type count + // Keep this synced up with World.a(Class) + if (entity instanceof EntityInsentient) { + EntityInsentient entityinsentient = (EntityInsentient) entity; + if (entityinsentient.isTypeNotPersistent() && entityinsentient.isPersistent()) { + return; + } + } + for (EnumCreatureType creatureType : EnumCreatureType.values()) { + if (creatureType.a().isAssignableFrom(entity.getClass())) { + this.entityCount.adjustOrPutValue(creatureType.a(), 1, 1); + } + } + // Spigot end + } + + public int getBlockDurability(int x, int y, int z) { + if (y >= 0 && y >> 4 < sections.length) { + ChunkSection chunksection = sections[y >> 4]; + if (chunksection != null) + return chunksection.getBlockDurability(x & 0xF, y & 0xF, z & 0xF); + } + return 0; + } + + public void setBlockDurability(int x, int y, int z, int durability) { + if (y >= 0 && y >> 4 < sections.length) { + ChunkSection chunksection = sections[y >> 4]; + if (chunksection != null) + chunksection.setBlockDurability(x & 0xF, y & 0xF, z & 0xF, durability); + } + } + + public int getItemCount(BlockPosition blockPosition) { + int k = MathHelper.floor(blockPosition.getY() / 16.0D); + k = Math.max(0, k); + k = Math.min(this.entitySlices.length - 1, k); + return itemCounts[k]; + } + + public void b(Entity entity) { + this.a(entity, entity.af); + } + + public void a(Entity entity, int i) { + if (i < 0) { + i = 0; + } + + if (i >= this.entitySlices.length) { + i = this.entitySlices.length - 1; + } + + // PaperSpigot start + //this.entitySlices[i].remove(entity)) + if (!entitySlices[i].remove(entity)) + return; + // PaperSpigot end + + // PaperSpigot start - update counts + if (entity instanceof EntityItem) { + itemCounts[i]--; + } else if (entity instanceof IInventory) { + inventoryEntityCounts[i]--; + } + // PaperSpigot end + // Spigot start - decrement creature type count + // Keep this synced up with World.a(Class) + if (entity instanceof EntityInsentient) { + EntityInsentient entityinsentient = (EntityInsentient) entity; + if (entityinsentient.isTypeNotPersistent() && entityinsentient.isPersistent()) { + return; + } + } + for (EnumCreatureType creatureType : EnumCreatureType.values()) { + if (creatureType.a().isAssignableFrom(entity.getClass())) { + this.entityCount.adjustValue(creatureType.a(), -1); + } + } + // Spigot end + } + + public void removeCannonEntity(Entity entity, int i) { + if (i < 0) { + i = 0; + } + if (i >= entitySlices.length) { + i = entitySlices.length - 1; + } + entitySlices[i].remove(entity); + } + + public boolean d(BlockPosition blockposition) { + return d(blockposition.getX(), blockposition.getY(), blockposition.getZ()); + } + + public TileEntity i(BlockPosition blockposition) { + Block block = this.getType(blockposition); + return !block.isTileEntity() ? null : ((IContainer) block).a(this.world, this.c(blockposition)); + } + + public TileEntity a(BlockPosition blockposition, Chunk.EnumTileEntityState chunk_enumtileentitystate) { + // CraftBukkit start + TileEntity tileentity = null; + if (world.captureBlockStates) { + tileentity = world.capturedTileEntities.get(blockposition); + } + if (tileentity == null) { + tileentity = this.tileEntities.get(blockposition); + } + // CraftBukkit end + + if (tileentity == null) { + if (chunk_enumtileentitystate == Chunk.EnumTileEntityState.IMMEDIATE) { + tileentity = this.i(blockposition); + this.world.setTileEntity(blockposition, tileentity); + } else if (chunk_enumtileentitystate == Chunk.EnumTileEntityState.QUEUED) { + throw new IllegalStateException("Clientside tile entity request"); + } + } else if (tileentity.x()) { + this.tileEntities.remove(blockposition); + return null; + } + + return tileentity; + } + + public void a(TileEntity tileentity) { + this.a(tileentity.getPosition(), tileentity); + if (this.h) { + this.world.a(tileentity); + } + + } + + public void a(BlockPosition blockposition, TileEntity tileentity) { + tileentity.a(this.world); + tileentity.a(blockposition); + if (this.getType(blockposition) instanceof IContainer) { + if (this.tileEntities.containsKey(blockposition)) { + this.tileEntities.get(blockposition).y(); + } + + tileentity.D(); + this.tileEntities.put(blockposition, tileentity); + // CraftBukkit start + // PaperSpigot start - Remove invalid mob spawner tile entities + } else if (this.world.paperSpigotConfig.removeInvalidMobSpawnerTEs && tileentity instanceof TileEntityMobSpawner && + org.bukkit.craftbukkit.util.CraftMagicNumbers.getMaterial(getType(blockposition)) != org.bukkit.Material.MOB_SPAWNER) { + this.tileEntities.remove(blockposition); + // PaperSpigot end + } + } + + public void e(BlockPosition blockposition) { + if (this.h) { + TileEntity tileentity = this.tileEntities.remove(blockposition); + + if (tileentity != null) { + tileentity.y(); + } + } + + } + + public void addEntities() { + this.h = true; + this.world.a(this.tileEntities.values()); + + for (List entitySlice : this.entitySlices) { + + for (Entity entity : entitySlice) { + entity.ah(); + } + + this.world.b(entitySlice); + } + + } + + public void removeEntities() { + h = false; + + for (TileEntity tileentity : this.tileEntities.values()) { + // Spigot Start + if (tileentity instanceof IInventory) { + for (org.bukkit.entity.HumanEntity h : Lists.newArrayList(((IInventory) tileentity).getViewers())) { + if (h instanceof org.bukkit.craftbukkit.entity.CraftHumanEntity) { + ((org.bukkit.craftbukkit.entity.CraftHumanEntity) h).getHandle().closeInventory(); + } + } + } + // Spigot End + + world.b(tileentity); + } + + for (List entitySlice : entitySlices) { + // CraftBukkit start + List newList = Lists.newArrayList(entitySlice); + Iterator iter = newList.iterator(); + while (iter.hasNext()) { + Entity entity = iter.next(); + // Spigot Start + if (entity instanceof IInventory) { + for (org.bukkit.entity.HumanEntity h : Lists.newArrayList(((IInventory) entity).getViewers())) { + if (h instanceof org.bukkit.craftbukkit.entity.CraftHumanEntity) { + ((org.bukkit.craftbukkit.entity.CraftHumanEntity) h).getHandle().closeInventory(); + } + } + } + // Spigot End + + // Do not pass along players, as doing so can get them stuck outside of time. + // (which for example disables inventory icon updates and prevents block breaking) + if (entity instanceof EntityPlayer) { + iter.remove(); + } + } + + world.c(newList); + // CraftBukkit end + } + + } + + public void e() { + this.q = true; + } + + public void a(Entity entity, AxisAlignedBB axisalignedbb, List list, Predicate predicate) { + int i = MathHelper.floor((axisalignedbb.b - 2.0D) / 16.0D); + int j = MathHelper.floor((axisalignedbb.e + 2.0D) / 16.0D); + + i = MathHelper.clamp(i, 0, entitySlices.length - 1); + j = MathHelper.clamp(j, 0, entitySlices.length - 1); + + for (int k = i; k <= j; ++k) { + List slice = entitySlices[k]; + if (!slice.isEmpty()) { + Iterator iterator = slice.iterator(); + + // PaperSpigot start - Don't search for inventories if we have none, and that is all we want + /* + * We check if they want inventories by seeing if it is the static `IEntitySelector.c` + * + * Make sure the inventory selector stays in sync. + * It should be the one that checks `var1 instanceof IInventory && var1.isAlive()` + */ + if (predicate == IEntitySelector.c && inventoryEntityCounts[k] <= 0) continue; + + while (iterator.hasNext()) { + Entity entity1 = iterator.next(); + + if (entity1.getBoundingBox().b(axisalignedbb) && entity1 != entity) { + if (predicate == null || predicate.apply(entity1)) { + list.add(entity1); + } + + Entity[] aentity = entity1.aB(); + + if (aentity != null) { + for (Entity value : aentity) { + entity1 = value; + if (entity1 != entity && entity1.getBoundingBox().b(axisalignedbb) && (predicate == null || predicate.apply(entity1))) { + list.add(entity1); + } + } + } + } + } + } + } + + } + + public void a(Class oclass, AxisAlignedBB axisalignedbb, List list, Predicate predicate) { + int i = MathHelper.floor((axisalignedbb.b - 2.0D) / 16.0D); + int j = MathHelper.floor((axisalignedbb.e + 2.0D) / 16.0D); + + i = MathHelper.clamp(i, 0, entitySlices.length - 1); + j = MathHelper.clamp(j, 0, entitySlices.length - 1); + + // PaperSpigot start + int[] counts; + if (EntityItem.class.isAssignableFrom(oclass)) { // PandaSpigot + counts = itemCounts; + } else if (IInventory.class.isAssignableFrom(oclass)) { + counts = inventoryEntityCounts; + } else { + counts = null; + } + // PaperSpigot end + + for (int k = i; k <= j; ++k) { + if (counts != null && counts[k] <= 0) + continue; // PaperSpigot - Don't check a chunk if it doesn't have the type we are looking for + + for (Entity entity : entitySlices[k]) { + if (oclass.isInstance(entity) && entity.getBoundingBox().b(axisalignedbb) && (predicate == null || predicate.apply((T) entity))) { // CraftBukkit - fix decompile error // Spigot + list.add((T) entity); // Fix decompile error + } + } + } + } + + public boolean a(boolean flag) { + if (flag) { + return this.r && this.world.getTime() != this.lastSaved || this.q; + + } else if (this.q && this.world.getAutoSaveWorldData().getLastAutosaveTimeStamp() >= this.lastSaved) { + return true; + + } else { + return this.r && this.world.getTime() >= this.lastSaved + (MinecraftServer.getServer().autosavePeriod * 4L); + } + } + + public Random a(long i) { + return chunkRandom; + } + + public boolean isEmpty() { + return false; + } + + public void loadNearby(IChunkProvider ichunkprovider, IChunkProvider ichunkprovider1, int i, int j) { + boolean flag = ichunkprovider.isChunkLoaded(i, j - 1); + boolean flag1 = ichunkprovider.isChunkLoaded(i + 1, j); + boolean flag2 = ichunkprovider.isChunkLoaded(i, j + 1); + boolean flag3 = ichunkprovider.isChunkLoaded(i - 1, j); + boolean flag4 = ichunkprovider.isChunkLoaded(i - 1, j - 1); + boolean flag5 = ichunkprovider.isChunkLoaded(i + 1, j + 1); + boolean flag6 = ichunkprovider.isChunkLoaded(i - 1, j + 1); + boolean flag7 = ichunkprovider.isChunkLoaded(i + 1, j - 1); + + if (flag1 && flag2 && flag5) { + if (!this.done) { + ichunkprovider.getChunkAt(ichunkprovider1, i, j); + } else { + ichunkprovider.a(ichunkprovider1, this, i, j); + } + } + + Chunk chunk; + + if (flag3 && flag2 && flag6) { + chunk = ichunkprovider.getOrCreateChunk(i - 1, j); + if (!chunk.done) { + ichunkprovider.getChunkAt(ichunkprovider1, i - 1, j); + } else { + ichunkprovider.a(ichunkprovider1, chunk, i - 1, j); + } + } + + if (flag && flag1 && flag7) { + chunk = ichunkprovider.getOrCreateChunk(i, j - 1); + if (!chunk.done) { + ichunkprovider.getChunkAt(ichunkprovider1, i, j - 1); + } else { + ichunkprovider.a(ichunkprovider1, chunk, i, j - 1); + } + } + + if (flag4 && flag && flag3) { + chunk = ichunkprovider.getOrCreateChunk(i - 1, j - 1); + if (!chunk.done) { + ichunkprovider.getChunkAt(ichunkprovider1, i - 1, j - 1); + } else { + ichunkprovider.a(ichunkprovider1, chunk, i - 1, j - 1); + } + } + + } + + public BlockPosition h(BlockPosition blockposition) { + return h(blockposition.getX(), blockposition.getZ()); + } + + public BlockPosition h(int x, int z) { + int i = x & 15; + int j = z & 15; + int k = i | j << 4; + int y = f[k]; + + if (y == -999) { + y = g() + 15; + + int i1 = -1; + + while (y > 0 && i1 == -1) { + Block block = getType(i, y, j); + Material material = block.getMaterial(); + + if (!material.isSolid() && !material.isLiquid()) { + y--; + } else { + i1 = y + 1; + } + } + + y = i1; + f[k] = i1; + } + + return new BlockPosition(x, y, z); + } + + public int getPrecipitationHeight(int x, int z) { + int k = x | z << 4; + int y = f[k]; + + if (y == -999) { + y = g() + 15; + + int i1 = -1; + + while (y > 0 && i1 == -1) { + Block block = getType(x, y, z); + Material material = block.getMaterial(); + + if (!material.isSolid() && !material.isLiquid()) { + y--; + } else { + i1 = y + 1; + } + } + + y = i1; + f[k] = i1; + } + + return y; + } + + public void b(boolean flag) { + if (this.k && !this.world.worldProvider.o() && !flag) { + this.recheckGaps(false); // PaperSpigot - Asynchronous lighting updates + } + + if (!this.lit && this.done && this.world.spigotConfig.randomLightUpdates) { // Spigot - also use random light updates setting to determine if we should relight + this.n(); + } + } + + /** + * PaperSpigot - Recheck gaps asynchronously. + */ + public void recheckGaps(boolean isClientSide) { + if (!world.paperSpigotConfig.useAsyncLighting) { + this.h(isClientSide); + return; + } + + world.lightingExecutor.submit(() -> h(isClientSide)); + } + + public boolean isReady() { + // Spigot Start + /* + * As of 1.7, Mojang added a check to make sure that only chunks which have been lit are sent to the client. + * Unfortunately this interferes with our modified chunk ticking algorithm, which will only tick chunks distant from the player on a very infrequent basis. + * We cannot unfortunately do this lighting stage during chunk gen as it appears to put a lot more noticeable load on the server, than when it is done at play time. + * For now at least we will simply send all chunks, in accordance with pre 1.7 behaviour. + */ + return true; + // Spigot End + } + + public ChunkCoordIntPair j() { // Vortex - cache + return chunkCoord; + } + + public boolean c(int i, int j) { + if (i < 0) { + i = 0; + } + + if (j >= 256) { + j = 255; + } + + for (int k = i; k <= j; k += 16) { + ChunkSection chunksection = this.sections[k >> 4]; + + if (chunksection != null && !chunksection.a()) { + return false; + } + } + + return true; + } + + public void a(ChunkSection[] achunksection) { + if (this.sections.length != achunksection.length) { + Chunk.c.warn("Could not set level chunk sections, array length is {} instead of {}", achunksection.length, this.sections.length); + } else { + System.arraycopy(achunksection, 0, this.sections, 0, this.sections.length); + } + } + + public BiomeBase getBiome(BlockPosition blockposition, WorldChunkManager worldchunkmanager) { + return getBiome(blockposition.getX(), blockposition.getZ(), worldchunkmanager); + } + + public byte[] getBiomeIndex() { + return this.e; + } + + public void a(byte[] abyte) { + if (this.e.length != abyte.length) { + Chunk.c.warn("Could not set level chunk biomes, array length is {} instead of {}", abyte.length, this.e.length); + } else { + System.arraycopy(abyte, 0, this.e, 0, this.e.length); + } + } + + public void l() { + this.v = 0; + } + + public void m() { + for (int i = 0; i < 8; ++i) { + if (this.v >= 4096) { + return; + } + + int j = this.v % 16; + int k = this.v / 16 % 16; + int l = this.v / 256; + + ++this.v; + + for (int i1 = 0; i1 < 16; ++i1) { + int x = chunkPosition.getX() + k, y = chunkPosition.getY() + ((j << 4) + i1), z = chunkPosition.getZ() + l; + boolean flag = i1 == 0 || i1 == 15 || k == 0 || k == 15 || l == 0 || l == 15; + + ChunkSection section = sections[j]; // Vortex - only one array iteration + if (section == null && flag || section != null && section.b(k, i1, l).getMaterial() == Material.AIR) { + { + if (this.world.getType(x, y - 1, z).getBlock().r() > 0) { + this.world.x(x, y - 1, z); + } + } + { + if (this.world.getType(x, y + 1, z).getBlock().r() > 0) { + this.world.x(x, y + 1, z); + } + } + { + if (this.world.getType(x, y, z - 1).getBlock().r() > 0) { + this.world.x(x, y, z - 1); + } + } + { + if (this.world.getType(x, y, z + 1).getBlock().r() > 0) { + this.world.x(x, y, z + 1); + } + } + { + if (this.world.getType(x - 1, y, z).getBlock().r() > 0) { + this.world.x(x - 1, y, z); + } + } + { + if (this.world.getType(x + 1, y, z).getBlock().r() > 0) { + this.world.x(x + 1, y, z); + } + } + + this.world.x(x, y, z); + } + } + + /* for (int i1 = 0; i1 < 16; ++i1) { + int x = chunkPosition.getX() + k, y = chunkPosition.getY() + ((j << 4) + i1), z = chunkPosition.getZ() + l; + boolean flag = i1 == 0 || i1 == 15 || k == 0 || k == 15 || l == 0 || l == 15; + + ChunkSection section = sections[j]; // Vortex - only one array iteration + if (section == null && flag || section != null && section.b(k, i1, l).getMaterial() == Material.AIR) { + // Up + if (this.world.getType(x, y + 1, z).getBlock().r() > 0) { + this.world.x(x, y + 1, z); + } + // Down + if (this.world.getType(x, y - 1, z).getBlock().r() > 0) { + this.world.x(x, y - 1, z); + } + // North + if (this.world.getType(x, y, z - 1).getBlock().r() > 0) { + this.world.x(x, y, z - 1); + } + // South + if (this.world.getType(x, y, z + 1).getBlock().r() > 0) { + this.world.x(x, y, z + 1); + } + // West + if (this.world.getType(x - 1, y, z).getBlock().r() > 0) { + this.world.x(x - 1, y, z); + } + // East + if (this.world.getType(x + 1, y, z).getBlock().r() > 0) { + this.world.x(x + 1, y, z); + } + // Self + this.world.x(x, y, z); + } + } */ + } + + } + + public void n() { + this.done = true; + this.lit = true; + + if (!this.world.worldProvider.o()) { + if (this.world.areChunksLoadedBetween(chunkPosition.a(-1, 0, -1), chunkPosition.a(16, this.world.F(), 16))) { + label42: + for (int i = 0; i < 16; ++i) { + for (int j = 0; j < 16; ++j) { + if (!this.e(i, j)) { + this.lit = false; + break label42; + } + } + } + + if (this.lit) { + for (EnumDirection enumdirection : EnumDirection.EnumDirectionLimit.HORIZONTAL) { + this.world.getChunkAtWorldCoords(chunkPosition.shift(enumdirection, enumdirection.c() == EnumDirection.EnumAxisDirection.POSITIVE ? 16 : 1)).a(enumdirection.opposite()); + } + + this.y(); + } + } else { + this.lit = false; + } + } + + } + + private void y() { + Arrays.fill(this.g, true); + this.h(false); + } + + private void a(EnumDirection enumdirection) { + if (this.done) { + int i; + + if (enumdirection == EnumDirection.EAST) { + for (i = 0; i < 16; ++i) { + this.e(15, i); + } + } else if (enumdirection == EnumDirection.WEST) { + for (i = 0; i < 16; ++i) { + this.e(0, i); + } + } else if (enumdirection == EnumDirection.SOUTH) { + for (i = 0; i < 16; ++i) { + this.e(i, 15); + } + } else if (enumdirection == EnumDirection.NORTH) { + for (i = 0; i < 16; ++i) { + this.e(i, 0); + } + } + + } + } + + private boolean e(int i, int j) { + int k = this.g(); + boolean flag = false; + boolean flag1 = false; + + int x = chunkPosition.getX() + i, z = chunkPosition.getZ() + j; + + int y; + + for (y = k + 16 - 1; y > this.world.F() || y > 0 && !flag1; --y) { + int i1 = getTypeAbs(x, y, z).p(); + + if (i1 == 255 && y < this.world.F()) { + flag1 = true; + } + + if (!flag && i1 > 0) { + flag = true; + } else if (flag && i1 == 0 && !this.world.x(x, y, z)) { + return false; + } + } + + for (; y > 0; --y) { + if (getTypeAbs(x, y, z).r() > 0) { + this.world.x(x, y, z); + } + } + + return true; + } + + public boolean o() { + return this.h; + } + + public World getWorld() { + return this.world; + } + + public int[] q() { + return this.heightMap; + } + + public void a(int[] aint) { + if (this.heightMap.length != aint.length) { + Chunk.c.warn("Could not set level chunk heightmap, array length is {} instead of {}", aint.length, this.heightMap.length); + } else { + System.arraycopy(aint, 0, this.heightMap, 0, this.heightMap.length); + } + } + + public Map getTileEntities() { + return this.tileEntities; + } + + public List[] getEntitySlices() { + return this.entitySlices; + } + + public boolean isDone() { + return this.done; + } + + public void d(boolean flag) { + this.done = flag; + } + + public boolean u() { + return this.lit; + } + + public void e(boolean flag) { + this.lit = flag; + } + + public void f(boolean flag) { + this.q = flag; + } + + public void g(boolean flag) { + this.r = flag; + } + + public void setLastSaved(long i) { + this.lastSaved = i; + } + + public int v() { + return this.t; + } + + public long w() { + return this.u; + } + + public void c(long i) { + this.u = i; + } + + public enum EnumTileEntityState { + + IMMEDIATE, QUEUED, CHECK; + + EnumTileEntityState() { + } + } + + // Beanes - optimized neighbour light check + + public int getLightLevel(int x, int y, int z) { + if (AzuriteConfig.disableBlockLighting.getValue()) + return 15; + + + if (y >= 256) { + y = 255; + } + + // Out of these chunk bounds -> use world light provider + if (x < 0 || x > 15 || z < 0 || z > 15) { + return world.getLightLevel(locX * 16 + x, y, locZ * 16 + z); + } + + return this.a(x, y, z, world.I); + } + + public Block getTypePossibleOutOfBounds(int x, int y, int z) { + Block block = Blocks.AIR; + + if (x < 0 || x > 15 | z > 15 || z < 0) { + return this.world.getType(locX * 16 + x, y, locZ * 16 + z, false).getBlock(); + } + + if (y >= 0 && y >> 4 < this.sections.length) { + ChunkSection chunksection = this.sections[y >> 4]; + + if (chunksection != null) { + try { + block = chunksection.b(x, y & 15, z); + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.a(throwable, "Getting block"); + + throw new ReportedException(crashreport); + } + } + } + + return block; + } + + public int getLightLevelWithNeighbours(int x, int y, int z) { + if (AzuriteConfig.disableBlockLighting.getValue()) + return 15; + + if (x >= -30000000 && z >= -30000000 && x < 30000000 && z < 30000000) { + if (this.getTypePossibleOutOfBounds(x, y, z).s()) { + int top = this.getLightLevel(x, y + 1, z); + int east = this.getLightLevel(x + 1, y, z); + int west = this.getLightLevel(x - 1, y, z); + int south = this.getLightLevel(x, y, z + 1); + int north = this.getLightLevel(x, y, z - 1); + + if (east > top) { + top = east; + } + + if (west > top) { + top = west; + } + + if (south > top) { + top = south; + } + + if (north > top) { + top = north; + } + + return top; + } else if (y < 0) { + return 0; + } else { + if (x < 0 || x > 15 || z < 0 || z > 15) { + return world.getLightLevel(locX * 16 + x, y, locZ * 16 + z); + } + + return getLightLevel(x, y, z); + } + } else { + return 15; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ChunkCache.java b/azurite-server/src/main/java/net/minecraft/server/ChunkCache.java new file mode 100644 index 0000000..d046d82 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ChunkCache.java @@ -0,0 +1,83 @@ +package net.minecraft.server; + +public class ChunkCache implements IBlockAccess { + + protected int a; + protected int b; + protected Chunk[][] c; + protected boolean d; + protected World e; + + public ChunkCache(World world, BlockPosition blockposition, BlockPosition blockposition1, int i) { + this.e = world; + this.a = blockposition.getX() - i >> 4; + this.b = blockposition.getZ() - i >> 4; + int j = blockposition1.getX() + i >> 4; + int k = blockposition1.getZ() + i >> 4; + + this.c = new Chunk[j - this.a + 1][k - this.b + 1]; + this.d = true; + + int l; + int i1; + + for (l = this.a; l <= j; ++l) { + for (i1 = this.b; i1 <= k; ++i1) { + this.c[l - this.a][i1 - this.b] = world.getChunkAt(l, i1); + } + } + + for (l = blockposition.getX() >> 4; l <= blockposition1.getX() >> 4; ++l) { + for (i1 = blockposition.getZ() >> 4; i1 <= blockposition1.getZ() >> 4; ++i1) { + Chunk chunk = this.c[l - this.a][i1 - this.b]; + + if (chunk != null && !chunk.c(blockposition.getY(), blockposition1.getY())) { + this.d = false; + } + } + } + + } + + public TileEntity getTileEntity(BlockPosition blockposition) { + return this.c[(blockposition.getX() >> 4) - this.a][(blockposition.getZ() >> 4) - this.b].a(blockposition, Chunk.EnumTileEntityState.IMMEDIATE); + } + + public IBlockData getType(BlockPosition blockposition) { + return getType(blockposition.getX(), blockposition.getY(), blockposition.getZ()); + } + + @Override + public IBlockData getType(int x, int y, int z) { + if (y >= 0 && y < 256) { + int i = (x >> 4) - a; + int j = (z >> 4) - b; + + if (i >= 0 && i < c.length && j >= 0) { + Chunk[] chunks = c[i]; + + if(j < chunks.length) { + Chunk chunk = chunks[j]; + + if (chunk != null) { + ChunkSection section = chunk.getSections()[y >> 4]; + if (section != null) + return section.getType(x & 15, y & 15, z & 15); + } + } + } + } + + return Blocks.AIR.getBlockData(); + } + + public boolean isEmpty(BlockPosition blockposition) { + return this.getType(blockposition).getBlock().getMaterial() == Material.AIR; + } + + public int getBlockPower(BlockPosition blockposition, EnumDirection enumdirection) { + IBlockData iblockdata = this.getType(blockposition); + + return iblockdata.getBlock().b(this, blockposition, iblockdata, enumdirection); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ChunkCoordIntPair.java b/azurite-server/src/main/java/net/minecraft/server/ChunkCoordIntPair.java new file mode 100644 index 0000000..652c079 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ChunkCoordIntPair.java @@ -0,0 +1,71 @@ +package net.minecraft.server; + +public class ChunkCoordIntPair { + + public final int x; + public final int z; + + public ChunkCoordIntPair(int i, int j) { + this.x = i; + this.z = j; + } + + public static long a(int i, int j) { + return (long) i & 4294967295L | ((long) j & 4294967295L) << 32; + } + + public int hashCode() { + int i = 1664525 * this.x + 1013904223; + int j = 1664525 * (this.z ^ -559038737) + 1013904223; + + return i ^ j; + } + + public boolean equals(Object object) { + if (this == object) { + return true; + } else if (!(object instanceof ChunkCoordIntPair)) { + return false; + } else { + ChunkCoordIntPair chunkcoordintpair = (ChunkCoordIntPair) object; + + return this.x == chunkcoordintpair.x && this.z == chunkcoordintpair.z; + } + } + + public int a() { + return (this.x << 4) + 8; + } + + public int b() { + return (this.z << 4) + 8; + } + + public int c() { + return this.x << 4; + } + + public int d() { + return this.z << 4; + } + + public int e() { + return (this.x << 4) + 15; + } + + public int f() { + return (this.z << 4) + 15; + } + + public BlockPosition a(int i, int j, int k) { + return new BlockPosition((this.x << 4) + i, j, (this.z << 4) + k); + } + + public BlockPosition a(int i) { + return new BlockPosition(this.a(), i, this.b()); + } + + public String toString() { + return "[" + this.x + ", " + this.z + "]"; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ChunkProviderDebug.java b/azurite-server/src/main/java/net/minecraft/server/ChunkProviderDebug.java new file mode 100644 index 0000000..09fb254 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ChunkProviderDebug.java @@ -0,0 +1,130 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; + +import java.util.List; + +public class ChunkProviderDebug implements IChunkProvider { + + private static final List a = Lists.newArrayList(); + private static final int b; + private static final int c; + + static { + + for (Block block : Block.REGISTRY) { + ChunkProviderDebug.a.addAll(block.P().a()); + } + + b = MathHelper.f(MathHelper.c((float) ChunkProviderDebug.a.size())); + c = MathHelper.f((float) ChunkProviderDebug.a.size() / (float) ChunkProviderDebug.b); + } + + private final World d; + + public ChunkProviderDebug(World world) { + this.d = world; + } + + public static IBlockData b(int i, int j) { + IBlockData iblockdata = null; + + if (i > 0 && j > 0 && i % 2 != 0 && j % 2 != 0) { + i /= 2; + j /= 2; + if (i <= ChunkProviderDebug.b && j <= ChunkProviderDebug.c) { + int k = MathHelper.a(i * ChunkProviderDebug.b + j); + + if (k < ChunkProviderDebug.a.size()) { + iblockdata = ChunkProviderDebug.a.get(k); + } + } + } + + return iblockdata; + } + + public Chunk getOrCreateChunk(int i, int j) { + ChunkSnapshot chunksnapshot = new ChunkSnapshot(); + + int k; + + for (int l = 0; l < 16; ++l) { + for (int i1 = 0; i1 < 16; ++i1) { + int j1 = i * 16 + l; + + k = j * 16 + i1; + chunksnapshot.a(l, 60, i1, Blocks.BARRIER.getBlockData()); + IBlockData iblockdata = b(j1, k); + + if (iblockdata != null) { + chunksnapshot.a(l, 70, i1, iblockdata); + } + } + } + + Chunk chunk = new Chunk(this.d, chunksnapshot, i, j); + + chunk.initLighting(); + BiomeBase[] abiomebase = this.d.getWorldChunkManager().getBiomeBlock(null, i * 16, j * 16, 16, 16); + byte[] abyte = chunk.getBiomeIndex(); + + for (k = 0; k < abyte.length; ++k) { + abyte[k] = (byte) abiomebase[k].id; + } + + chunk.initLighting(); + return chunk; + } + + public boolean isChunkLoaded(int i, int j) { + return true; + } + + public void getChunkAt(IChunkProvider ichunkprovider, int i, int j) { + } + + public boolean a(IChunkProvider ichunkprovider, Chunk chunk, int i, int j) { + return false; + } + + public boolean saveChunks(boolean flag, IProgressUpdate iprogressupdate) { + return true; + } + + public void c() { + } + + public boolean unloadChunks() { + return false; + } + + public boolean canSave() { + return true; + } + + public String getName() { + return "DebugLevelSource"; + } + + public List getMobsFor(EnumCreatureType enumcreaturetype, BlockPosition blockposition) { + BiomeBase biomebase = this.d.getBiome(blockposition); + + return biomebase.getMobs(enumcreaturetype); + } + + public BlockPosition findNearestMapFeature(World world, String s, BlockPosition blockposition) { + return null; + } + + public int getLoadedChunks() { + return 0; + } + + public void recreateStructures(Chunk chunk, int i, int j) { + } + + public Chunk getChunkAt(BlockPosition blockposition) { + return this.getOrCreateChunk(blockposition.getX() >> 4, blockposition.getZ() >> 4); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ChunkProviderFlat.java b/azurite-server/src/main/java/net/minecraft/server/ChunkProviderFlat.java new file mode 100644 index 0000000..980c5f6 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ChunkProviderFlat.java @@ -0,0 +1,226 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; + +import java.util.List; +import java.util.Map; +import java.util.Random; + +public class ChunkProviderFlat implements IChunkProvider { + + private final World a; + private final Random b; + private final IBlockData[] c = new IBlockData[256]; + private final WorldGenFlatInfo d; + private final List e = Lists.newArrayList(); + private final boolean f; + private final boolean g; + private WorldGenLakes h; + private WorldGenLakes i; + + public ChunkProviderFlat(World world, long i, boolean flag, String s) { + this.a = world; + this.b = new Random(i); + this.d = WorldGenFlatInfo.a(s); + if (flag) { + Map> map = this.d.b(); + + if (map.containsKey("village") && world.paperSpigotConfig.generateVillage) { // PaperSpigot + Map map1 = map.get("village"); + + if (!map1.containsKey("size")) { + map1.put("size", "1"); + } + + this.e.add(new WorldGenVillage(map1)); + } + + if (map.containsKey("biome_1") && world.paperSpigotConfig.generateTemple) { // PaperSpigot + this.e.add(new WorldGenLargeFeature(map.get("biome_1"))); + } + + if (map.containsKey("mineshaft") && world.paperSpigotConfig.generateMineshaft) { // PaperSpigot + this.e.add(new WorldGenMineshaft(map.get("mineshaft"))); + } + + if (map.containsKey("stronghold") && world.paperSpigotConfig.generateStronghold) { // PaperSpigot + this.e.add(new WorldGenStronghold(map.get("stronghold"))); + } + + if (map.containsKey("oceanmonument") && world.paperSpigotConfig.generateMonument) { // PaperSpigot + this.e.add(new WorldGenMonument(map.get("oceanmonument"))); + } + } + + if (this.d.b().containsKey("lake")) { + this.h = new WorldGenLakes(Blocks.WATER); + } + + if (this.d.b().containsKey("lava_lake")) { + this.i = new WorldGenLakes(Blocks.LAVA); + } + + this.g = world.paperSpigotConfig.generateDungeon && this.d.b().containsKey("dungeon"); // PaperSpigot + int j = 0; + int k = 0; + boolean flag1 = true; + + for (WorldGenFlatLayerInfo worldgenflatlayerinfo : this.d.c()) { + for (int l = worldgenflatlayerinfo.d(); l < worldgenflatlayerinfo.d() + worldgenflatlayerinfo.b(); ++l) { + IBlockData iblockdata = worldgenflatlayerinfo.c(); + + if (iblockdata.getBlock() != Blocks.AIR) { + flag1 = false; + this.c[l] = iblockdata; + } + } + + if (worldgenflatlayerinfo.c().getBlock() == Blocks.AIR) { + k += worldgenflatlayerinfo.b(); + } else { + j += worldgenflatlayerinfo.b() + k; + k = 0; + } + } + + world.b(j); + this.f = !flag1 && this.d.b().containsKey("decoration"); + } + + public Chunk getOrCreateChunk(int i, int j) { + ChunkSnapshot chunksnapshot = new ChunkSnapshot(); + + int k; + + for (int l = 0; l < this.c.length; ++l) { + IBlockData iblockdata = this.c[l]; + + if (iblockdata != null) { + for (int i1 = 0; i1 < 16; ++i1) { + for (k = 0; k < 16; ++k) { + chunksnapshot.a(i1, l, k, iblockdata); + } + } + } + } + + for (StructureGenerator structureGenerator : this.e) { + + structureGenerator.a(this, this.a, i, j, chunksnapshot); + } + + Chunk chunk = new Chunk(this.a, chunksnapshot, i, j); + BiomeBase[] abiomebase = this.a.getWorldChunkManager().getBiomeBlock(null, i * 16, j * 16, 16, 16); + byte[] abyte = chunk.getBiomeIndex(); + + for (k = 0; k < abyte.length; ++k) { + abyte[k] = (byte) abiomebase[k].id; + } + + chunk.initLighting(); + return chunk; + } + + public boolean isChunkLoaded(int i, int j) { + return true; + } + + public void getChunkAt(IChunkProvider ichunkprovider, int i, int j) { + int k = i * 16; + int l = j * 16; + BlockPosition blockposition = new BlockPosition(k, 0, l); + BiomeBase biomebase = this.a.getBiome(k + 16, 0, l + 16); + boolean flag = false; + + this.b.setSeed(this.a.getSeed()); + long i1 = this.b.nextLong() / 2L * 2L + 1L; + long j1 = this.b.nextLong() / 2L * 2L + 1L; + + this.b.setSeed((long) i * i1 + (long) j * j1 ^ this.a.getSeed()); + ChunkCoordIntPair chunkcoordintpair = new ChunkCoordIntPair(i, j); + + for (StructureGenerator structuregenerator : this.e) { + boolean flag1 = structuregenerator.a(this.a, this.b, chunkcoordintpair); + + if (structuregenerator instanceof WorldGenVillage) { + flag |= flag1; + } + } + + if (this.h != null && !flag && this.b.nextInt(4) == 0) { + this.h.generate(this.a, this.b, blockposition.a(this.b.nextInt(16) + 8, this.b.nextInt(256), this.b.nextInt(16) + 8)); + } + + if (this.i != null && !flag && this.b.nextInt(8) == 0) { + BlockPosition blockposition1 = blockposition.a(this.b.nextInt(16) + 8, this.b.nextInt(this.b.nextInt(248) + 8), this.b.nextInt(16) + 8); + + if (blockposition1.getY() < this.a.F() || this.b.nextInt(10) == 0) { + this.i.generate(this.a, this.b, blockposition1); + } + } + + if (this.g) { + for (int k1 = 0; k1 < 8; ++k1) { + (new WorldGenDungeons()).generate(this.a, this.b, blockposition.a(this.b.nextInt(16) + 8, this.b.nextInt(256), this.b.nextInt(16) + 8)); + } + } + + if (this.f) { + biomebase.a(this.a, this.b, blockposition); + } + + } + + public boolean a(IChunkProvider ichunkprovider, Chunk chunk, int i, int j) { + return false; + } + + public boolean saveChunks(boolean flag, IProgressUpdate iprogressupdate) { + return true; + } + + public void c() {} + + public boolean unloadChunks() { + return false; + } + + public boolean canSave() { + return true; + } + + public String getName() { + return "FlatLevelSource"; + } + + public List getMobsFor(EnumCreatureType enumcreaturetype, BlockPosition blockposition) { + return a.getBiome(blockposition).getMobs(enumcreaturetype); + } + + public BlockPosition findNearestMapFeature(World world, String s, BlockPosition blockposition) { + if ("Stronghold".equals(s)) { + + for (StructureGenerator structuregenerator : this.e) { + if (structuregenerator instanceof WorldGenStronghold) { + return structuregenerator.getNearestGeneratedFeature(world, blockposition); + } + } + } + + return null; + } + + public int getLoadedChunks() { + return 0; + } + + public void recreateStructures(Chunk chunk, int i, int j) { + for (StructureGenerator structuregenerator : this.e) { + structuregenerator.a(this, this.a, i, j, null); + } + } + + public Chunk getChunkAt(BlockPosition blockposition) { + return this.getOrCreateChunk(blockposition.getX() >> 4, blockposition.getZ() >> 4); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ChunkProviderGenerate.java b/azurite-server/src/main/java/net/minecraft/server/ChunkProviderGenerate.java new file mode 100644 index 0000000..9df00b0 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ChunkProviderGenerate.java @@ -0,0 +1,477 @@ +package net.minecraft.server; + +import java.util.List; +import java.util.Random; + +public class ChunkProviderGenerate implements IChunkProvider { + + private final Random h; + private final NoiseGeneratorOctaves i; + private final NoiseGeneratorOctaves j; + private final NoiseGeneratorOctaves k; + private final NoiseGenerator3 l; + public NoiseGeneratorOctaves a; + public NoiseGeneratorOctaves b; + public NoiseGeneratorOctaves c; + private final World m; + private final boolean n; + private final WorldType o; + private final double[] p; + private final float[] q; + private CustomWorldSettingsFinal r; + private Block s; + private double[] t; + private final WorldGenBase u; + private final WorldGenStronghold v; + private final WorldGenVillage w; + private final WorldGenMineshaft x; + private final WorldGenLargeFeature y; + private final WorldGenBase z; + private final WorldGenMonument A; + private BiomeBase[] B; + double[] d; + double[] e; + double[] f; + double[] g; + + public ChunkProviderGenerate(World world, long i, boolean flag, String s) { + this.s = Blocks.WATER; + this.t = new double[256]; + this.u = new WorldGenCaves(); + this.v = new WorldGenStronghold(); + this.w = new WorldGenVillage(); + this.x = new WorldGenMineshaft(); + this.y = new WorldGenLargeFeature(); + this.z = new WorldGenCanyon(); + this.A = new WorldGenMonument(); + this.m = world; + this.n = flag; + this.o = world.getWorldData().getType(); + this.h = new Random(i); + this.i = new NoiseGeneratorOctaves(this.h, 16); + this.j = new NoiseGeneratorOctaves(this.h, 16); + this.k = new NoiseGeneratorOctaves(this.h, 8); + this.l = new NoiseGenerator3(this.h, 4); + this.a = new NoiseGeneratorOctaves(this.h, 10); + this.b = new NoiseGeneratorOctaves(this.h, 16); + this.c = new NoiseGeneratorOctaves(this.h, 8); + this.p = new double[825]; + this.q = new float[25]; + + for (int j = -2; j <= 2; ++j) { + for (int k = -2; k <= 2; ++k) { + float f = 10.0F / MathHelper.c((float) (j * j + k * k) + 0.2F); + this.q[j + 2 + (k + 2) * 5] = f; + } + } + + if (s != null) { + this.r = CustomWorldSettingsFinal.CustomWorldSettings.a(s).b(); + this.s = this.r.E ? Blocks.LAVA : Blocks.WATER; + world.b(this.r.q); + } + } + + public void a(int i, int j, ChunkSnapshot chunksnapshot) { + this.B = this.m.getWorldChunkManager().getBiomes(this.B, i * 4 - 2, j * 4 - 2, 10, 10); + this.a(i * 4, 0, j * 4); + + for (int k = 0; k < 4; ++k) { + int l = k * 5; + int i1 = (k + 1) * 5; + + for (int j1 = 0; j1 < 4; ++j1) { + int k1 = (l + j1) * 33; + int l1 = (l + j1 + 1) * 33; + int i2 = (i1 + j1) * 33; + int j2 = (i1 + j1 + 1) * 33; + + for (int k2 = 0; k2 < 32; ++k2) { + double d0 = 0.125D; + double d1 = this.p[k1 + k2]; + double d2 = this.p[l1 + k2]; + double d3 = this.p[i2 + k2]; + double d4 = this.p[j2 + k2]; + double d5 = (this.p[k1 + k2 + 1] - d1) * d0; + double d6 = (this.p[l1 + k2 + 1] - d2) * d0; + double d7 = (this.p[i2 + k2 + 1] - d3) * d0; + double d8 = (this.p[j2 + k2 + 1] - d4) * d0; + + for (int l2 = 0; l2 < 8; ++l2) { + double d10 = d1; + double d11 = d2; + double d12 = (d3 - d1) * 0.25D; + double d13 = (d4 - d2) * 0.25D; + + for (int i3 = 0; i3 < 4; ++i3) { + double d15 = (d11 - d10) * 0.25D; + double d16 = d10 - d15; + + for (int j3 = 0; j3 < 4; ++j3) { + if ((d16 += d15) > 0.0D) { + chunksnapshot.a(k * 4 + i3, k2 * 8 + l2, j1 * 4 + j3, Blocks.STONE.getBlockData()); + } else if (k2 * 8 + l2 < this.r.q) { + chunksnapshot.a(k * 4 + i3, k2 * 8 + l2, j1 * 4 + j3, this.s.getBlockData()); + } + } + + d10 += d12; + d11 += d13; + } + + d1 += d5; + d2 += d6; + d3 += d7; + d4 += d8; + } + } + } + } + } + + public void a(int i, int j, ChunkSnapshot chunksnapshot, BiomeBase[] abiomebase) { + double d0 = 0.03125D; + this.t = this.l.a(this.t, (i * 16), (j * 16), 16, 16, d0 * 2.0D, d0 * 2.0D, 1.0D); + + for (int k = 0; k < 16; ++k) { + for (int l = 0; l < 16; ++l) { + BiomeBase biomebase = abiomebase[l + k * 16]; + biomebase.a(this.m, this.h, chunksnapshot, i * 16 + k, j * 16 + l, this.t[l + k * 16]); + } + } + } + + public Chunk getOrCreateChunk(int i, int j) { + this.h.setSeed((long) i * 341873128712L + (long) j * 132897987541L); + ChunkSnapshot chunksnapshot = new ChunkSnapshot(); + + this.a(i, j, chunksnapshot); + this.B = this.m.getWorldChunkManager().getBiomeBlock(this.B, i * 16, j * 16, 16, 16); + this.a(i, j, chunksnapshot, this.B); + + if (this.r.r && this.m.paperSpigotConfig.generateCaves && this.m.generatorConfig.cavesMultiplier.getValue() > 0) { // PaperSpigot + this.u.a(this, this.m, i, j, chunksnapshot); + } + + if (this.r.z && this.m.paperSpigotConfig.generateCanyon) { // PaperSpigot + this.z.a(this, this.m, i, j, chunksnapshot); + } + + if (this.r.w && this.n && this.m.paperSpigotConfig.generateMineshaft) { // PaperSpigot + this.x.a(this, this.m, i, j, chunksnapshot); + } + + if (this.r.v && this.n && this.m.paperSpigotConfig.generateVillage) { // PaperSpigot + this.w.a(this, this.m, i, j, chunksnapshot); + } + + if (this.r.u && this.n && this.m.paperSpigotConfig.generateStronghold) { // PaperSpigot + this.v.a(this, this.m, i, j, chunksnapshot); + } + + if (this.r.x && this.n && this.m.paperSpigotConfig.generateTemple) { // PaperSpigot + this.y.a(this, this.m, i, j, chunksnapshot); + } + + if (this.r.y && this.n && this.m.paperSpigotConfig.generateMonument) { // PaperSpigot + this.A.a(this, this.m, i, j, chunksnapshot); + } + + Chunk chunk = new Chunk(this.m, chunksnapshot, i, j); + byte[] abyte = chunk.getBiomeIndex(); + + for (int k = 0; k < abyte.length; ++k) { + abyte[k] = (byte) this.B[k].id; + } + + chunk.initLighting(); + return chunk; + } + + private void a(int i, int j, int k) { + this.g = this.b.a(this.g, i, k, 5, 5, this.r.e, this.r.f, this.r.g); + float f = this.r.a; + float f1 = this.r.b; + + this.d = this.k.a(this.d, i, j, k, 5, 33, 5, (f / this.r.h), (f1 / this.r.i), (f / this.r.j)); + this.e = this.i.a(this.e, i, j, k, 5, 33, 5, f, f1, f); + this.f = this.j.a(this.f, i, j, k, 5, 33, 5, f, f1, f); + int l = 0; + int i1 = 0; + + for (int j1 = 0; j1 < 5; ++j1) { + for (int k1 = 0; k1 < 5; ++k1) { + float f2 = 0.0F; + float f3 = 0.0F; + float f4 = 0.0F; + byte b0 = 2; + BiomeBase biomebase = this.B[j1 + 2 + (k1 + 2) * 10]; + + for (int l1 = -b0; l1 <= b0; ++l1) { + for (int i2 = -b0; i2 <= b0; ++i2) { + BiomeBase biomebase1 = this.B[j1 + l1 + 2 + (k1 + i2 + 2) * 10]; + float f5 = this.r.n + biomebase1.an * this.r.m; + float f6 = this.r.p + biomebase1.ao * this.r.o; + + if (this.o == WorldType.AMPLIFIED && f5 > 0.0F) { + f5 = 1.0F + f5 * 2.0F; + f6 = 1.0F + f6 * 4.0F; + } + + float f7 = this.q[l1 + 2 + (i2 + 2) * 5] / (f5 + 2.0F); + + if (biomebase1.an > biomebase.an) { + f7 /= 2.0F; + } + + f2 += f6 * f7; + f3 += f5 * f7; + f4 += f7; + } + } + + f2 /= f4; + f3 /= f4; + f2 = f2 * 0.9F + 0.1F; + f3 = (f3 * 4.0F - 1.0F) / 8.0F; + double d0 = this.g[i1] / 8000.0D; + + if (d0 < 0.0D) { + d0 = -d0 * 0.3D; + } + + d0 = d0 * 3.0D - 2.0D; + if (d0 < 0.0D) { + d0 /= 2.0D; + if (d0 < -1.0D) { + d0 = -1.0D; + } + + d0 /= 1.4D; + d0 /= 2.0D; + } else { + if (d0 > 1.0D) { + d0 = 1.0D; + } + + d0 /= 8.0D; + } + + ++i1; + double d1 = f3; + double d2 = f2; + + d1 += d0 * 0.2D; + d1 = d1 * (double) this.r.k / 8.0D; + double d3 = (double) this.r.k + d1 * 4.0D; + + for (int j2 = 0; j2 < 33; ++j2) { + double d4 = ((double) j2 - d3) * (double) this.r.l * 128.0D / 256.0D / d2; + + if (d4 < 0.0D) { + d4 *= 4.0D; + } + + double d5 = this.e[l] / (double) this.r.d; + double d6 = this.f[l] / (double) this.r.c; + double d7 = (this.d[l] / 10.0D + 1.0D) / 2.0D; + double d8 = MathHelper.b(d5, d6, d7) - d4; + + if (j2 > 29) { + double d9 = ((float) (j2 - 29) / 3.0F); + + d8 = d8 * (1.0D - d9) + -10.0D * d9; + } + + this.p[l] = d8; + ++l; + } + } + } + + } + + public boolean isChunkLoaded(int i, int j) { + return true; + } + + public void getChunkAt(IChunkProvider ichunkprovider, int i, int j) { + BlockFalling.instaFall = true; + int k = i * 16; + int l = j * 16; + BlockPosition blockposition = new BlockPosition(k, 0, l); + BiomeBase biomebase = this.m.getBiome(blockposition.a(16, 0, 16)); + + this.h.setSeed(this.m.getSeed()); + long i1 = this.h.nextLong() / 2L * 2L + 1L; + long j1 = this.h.nextLong() / 2L * 2L + 1L; + + this.h.setSeed((long) i * i1 + (long) j * j1 ^ this.m.getSeed()); + boolean flag = false; + ChunkCoordIntPair chunkcoordintpair = new ChunkCoordIntPair(i, j); + + if (this.r.w && this.n && this.m.paperSpigotConfig.generateMineshaft) { // PaperSpigot + this.x.a(this.m, this.h, chunkcoordintpair); + } + + if (this.r.v && this.n && this.m.paperSpigotConfig.generateVillage) { // PaperSpigot + flag = this.w.a(this.m, this.h, chunkcoordintpair); + } + + if (this.r.u && this.n && this.m.paperSpigotConfig.generateStronghold) { // PaperSpigot + this.v.a(this.m, this.h, chunkcoordintpair); + } + + if (this.r.x && this.n && this.m.paperSpigotConfig.generateTemple) { // PaperSpigot + this.y.a(this.m, this.h, chunkcoordintpair); + } + + if (this.r.y && this.n && this.m.paperSpigotConfig.generateMonument) { // PaperSpigot + this.A.a(this.m, this.h, chunkcoordintpair); + } + + int k1; + int l1; + int i2; + int radiusSqrd = m.generatorConfig.spawnBiomeRadius.getValue() * m.generatorConfig.spawnBiomeRadius.getValue(); + + if (biomebase != BiomeBase.DESERT && biomebase != BiomeBase.DESERT_HILLS && this.r.A && !flag && this.h.nextInt(this.r.B) == 0) { + k1 = this.h.nextInt(16) + 8; + l1 = this.h.nextInt(256); + i2 = this.h.nextInt(16) + 8; + int x = blockposition.getX() + k1; + int z = blockposition.getZ() + i2; + boolean spawn = x * x + z * z < radiusSqrd; + + if ((!spawn && m.generatorConfig.generateWaterLakes.getValue()) || m.generatorConfig.spawnBiomeLakes.getValue()) { + (new WorldGenLakes(Blocks.WATER)).generate(this.m, this.h, blockposition.a(k1, l1, i2)); + } + } + + if (!flag && this.h.nextInt(this.r.D / 10) == 0 && this.r.C) { + k1 = this.h.nextInt(16) + 8; + l1 = this.h.nextInt(this.h.nextInt(248) + 8); + i2 = this.h.nextInt(16) + 8; + int x = blockposition.getX() + k1; + int z = blockposition.getZ() + i2; + boolean spawn = x * x + z * z < radiusSqrd; + + if (l1 < this.m.F() || this.h.nextInt(this.r.D / 8) == 0) { + if ((!spawn && m.generatorConfig.generateLavaLakes.getValue()) || m.generatorConfig.spawnBiomeLakes.getValue()) { + (new WorldGenLakes(Blocks.LAVA)).generate(this.m, this.h, blockposition.a(k1, l1, i2)); + } + } + } + + if (this.r.s && this.m.paperSpigotConfig.generateDungeon) { // PaperSpigot + for (k1 = 0; k1 < this.r.t; ++k1) { + l1 = this.h.nextInt(16) + 8; + i2 = this.h.nextInt(256); + int j2 = this.h.nextInt(16) + 8; + + (new WorldGenDungeons()).generate(this.m, this.h, blockposition.a(l1, i2, j2)); + } + } + + biomebase.a(this.m, this.h, new BlockPosition(k, 0, l)); + SpawnerCreature.a(this.m, biomebase, k + 8, l + 8, 16, 16, this.h); + blockposition = blockposition.a(8, 0, 8); + + for (k1 = 0; k1 < 16; ++k1) { + for (l1 = 0; l1 < 16; ++l1) { + BlockPosition blockposition1 = this.m.q(blockposition.a(k1, 0, l1)); + BlockPosition blockposition2 = blockposition1.down(); + + if (this.m.v(blockposition2)) { + this.m.setTypeAndData(blockposition2, Blocks.ICE.getBlockData(), 2); + } + + if (this.m.f(blockposition1, true)) { + this.m.setTypeAndData(blockposition1, Blocks.SNOW_LAYER.getBlockData(), 2); + } + } + } + + BlockFalling.instaFall = false; + } + + public boolean a(IChunkProvider ichunkprovider, Chunk chunk, int i, int j) { + boolean flag = false; + + if (this.r.y && this.n && chunk.w() < 3600L) { + flag = this.A.a(this.m, this.h, new ChunkCoordIntPair(i, j)); + } + + return flag; + } + + public boolean saveChunks(boolean flag, IProgressUpdate iprogressupdate) { + return true; + } + + public void c() { + } + + public boolean unloadChunks() { + return false; + } + + public boolean canSave() { + return true; + } + + public String getName() { + return "RandomLevelSource"; + } + + public List getMobsFor(EnumCreatureType enumcreaturetype, BlockPosition blockposition) { + BiomeBase biomebase = this.m.getBiome(blockposition); + + if (this.n) { + if (enumcreaturetype == EnumCreatureType.MONSTER && this.y.a(blockposition)) { + return this.y.b(); + } + + if (enumcreaturetype == EnumCreatureType.MONSTER && this.r.y && this.A.a(this.m, blockposition)) { + return this.A.b(); + } + } + + return biomebase.getMobs(enumcreaturetype); + } + + public BlockPosition findNearestMapFeature(World world, String s, BlockPosition blockposition) { + return "Stronghold".equals(s) && this.v != null ? this.v.getNearestGeneratedFeature(world, blockposition) : null; + } + + public int getLoadedChunks() { + return 0; + } + + public void recreateStructures(Chunk chunk, int i, int j) { + if (this.r.w && this.n && this.m.paperSpigotConfig.generateMineshaft) { // PaperSpigot + this.x.a(this, this.m, i, j, null); + } + + if (this.r.v && this.n && this.m.paperSpigotConfig.generateVillage) { // PaperSpigot + this.w.a(this, this.m, i, j, null); + } + + if (this.r.u && this.n && this.m.paperSpigotConfig.generateStronghold) { // PaperSpigot + this.v.a(this, this.m, i, j, null); + } + + if (this.r.x && this.n && this.m.paperSpigotConfig.generateTemple) { // PaperSpigot + this.y.a(this, this.m, i, j, null); + } + + if (this.r.y && this.n && this.m.paperSpigotConfig.generateMonument) { // PaperSpigot + this.A.a(this, this.m, i, j, null); + } + + } + + public Chunk getChunkAt(BlockPosition blockposition) { + return this.getOrCreateChunk(blockposition.getX() >> 4, blockposition.getZ() >> 4); + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/net/minecraft/server/ChunkProviderHell.java b/azurite-server/src/main/java/net/minecraft/server/ChunkProviderHell.java new file mode 100644 index 0000000..861898a --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ChunkProviderHell.java @@ -0,0 +1,390 @@ +package net.minecraft.server; + +import java.util.List; +import java.util.Random; + +public class ChunkProviderHell implements IChunkProvider { + + private final World h; + private final boolean i; + private final Random j; + private double[] k = new double[256]; + private double[] l = new double[256]; + private double[] m = new double[256]; + private double[] n; + private final NoiseGeneratorOctaves o; + private final NoiseGeneratorOctaves p; + private final NoiseGeneratorOctaves q; + private final NoiseGeneratorOctaves r; + private final NoiseGeneratorOctaves s; + public final NoiseGeneratorOctaves a; + public final NoiseGeneratorOctaves b; + private final WorldGenFire t = new WorldGenFire(); + private final WorldGenLightStone1 u = new WorldGenLightStone1(); + private final WorldGenLightStone2 v = new WorldGenLightStone2(); + private final WorldGenerator w; + private final WorldGenHellLava x; + private final WorldGenHellLava y; + private final WorldGenMushrooms z; + private final WorldGenMushrooms A; + private final WorldGenNether B; + private final WorldGenBase C; + double[] c; + double[] d; + double[] e; + double[] f; + double[] g; + + public ChunkProviderHell(World world, boolean flag, long i) { + this.w = new WorldGenMinable(Blocks.QUARTZ_ORE.getBlockData(), 14, BlockPredicate.a(Blocks.NETHERRACK)); + this.x = new WorldGenHellLava(Blocks.FLOWING_LAVA, true); + this.y = new WorldGenHellLava(Blocks.FLOWING_LAVA, false); + this.z = new WorldGenMushrooms(Blocks.BROWN_MUSHROOM); + this.A = new WorldGenMushrooms(Blocks.RED_MUSHROOM); + this.B = new WorldGenNether(); + this.C = new WorldGenCavesHell(); + this.h = world; + this.i = flag; + this.j = new Random(i); + this.o = new NoiseGeneratorOctaves(this.j, 16); + this.p = new NoiseGeneratorOctaves(this.j, 16); + this.q = new NoiseGeneratorOctaves(this.j, 8); + this.r = new NoiseGeneratorOctaves(this.j, 4); + this.s = new NoiseGeneratorOctaves(this.j, 4); + this.a = new NoiseGeneratorOctaves(this.j, 10); + this.b = new NoiseGeneratorOctaves(this.j, 16); + world.b(63); + } + + public void a(int i, int j, ChunkSnapshot chunksnapshot) { + byte b0 = 4; + int k = this.h.F() / 2 + 1; + int l = b0 + 1; + byte b1 = 17; + int i1 = b0 + 1; + + this.n = this.a(this.n, i * b0, 0, j * b0, l, b1, i1); + + for (int j1 = 0; j1 < b0; ++j1) { + for (int k1 = 0; k1 < b0; ++k1) { + for (int l1 = 0; l1 < 16; ++l1) { + double d1 = this.n[((j1) * i1 + k1) * b1 + l1]; + double d2 = this.n[((j1) * i1 + k1 + 1) * b1 + l1]; + double d3 = this.n[((j1 + 1) * i1 + k1) * b1 + l1]; + double d4 = this.n[((j1 + 1) * i1 + k1 + 1) * b1 + l1]; + double d5 = (this.n[((j1) * i1 + k1) * b1 + l1 + 1] - d1) * 0.125D; + double d6 = (this.n[((j1) * i1 + k1 + 1) * b1 + l1 + 1] - d2) * 0.125D; + double d7 = (this.n[((j1 + 1) * i1 + k1) * b1 + l1 + 1] - d3) * 0.125D; + double d8 = (this.n[((j1 + 1) * i1 + k1 + 1) * b1 + l1 + 1] - d4) * 0.125D; + + for (int i2 = 0; i2 < 8; ++i2) { + double d10 = d1; + double d11 = d2; + double d12 = (d3 - d1) * 0.25D; + double d13 = (d4 - d2) * 0.25D; + + for (int j2 = 0; j2 < 4; ++j2) { + double d15 = d10; + double d16 = (d11 - d10) * 0.25D; + + for (int k2 = 0; k2 < 4; ++k2) { + IBlockData iblockdata = null; + + if (l1 * 8 + i2 < k) { + iblockdata = Blocks.LAVA.getBlockData(); + } + + if (d15 > 0.0D) { + iblockdata = Blocks.NETHERRACK.getBlockData(); + } + + int l2 = j2 + j1 * 4; + int i3 = i2 + l1 * 8; + int j3 = k2 + k1 * 4; + + chunksnapshot.a(l2, i3, j3, iblockdata); + d15 += d16; + } + + d10 += d12; + d11 += d13; + } + + d1 += d5; + d2 += d6; + d3 += d7; + d4 += d8; + } + } + } + } + + } + + public void b(int i, int j, ChunkSnapshot chunksnapshot) { + int k = this.h.F() + 1; + + this.k = this.r.a(this.k, i * 16, j * 16, 0, 16, 16, 1, 0.03125D, 0.03125D, 1.0D); + this.l = this.r.a(this.l, i * 16, 109, j * 16, 16, 1, 16, 0.03125D, 1.0D, 0.03125D); + this.m = this.s.a(this.m, i * 16, j * 16, 0, 16, 16, 1, 0.0625, 0.0625, 0.0625); // Vortex - less calc + + for (int l = 0; l < 16; ++l) { + for (int i1 = 0; i1 < 16; ++i1) { + boolean flag = this.k[l + i1 * 16] + this.j.nextDouble() * 0.2D > 0.0D; + boolean flag1 = this.l[l + i1 * 16] + this.j.nextDouble() * 0.2D > 0.0D; + int j1 = (int) (this.m[l + i1 * 16] / 3.0D + 3.0D + this.j.nextDouble() * 0.25D); + int k1 = -1; + IBlockData iblockdata = Blocks.NETHERRACK.getBlockData(); + IBlockData iblockdata1 = Blocks.NETHERRACK.getBlockData(); + + for (int l1 = 127; l1 >= 0; --l1) { + // PaperSpigot start - Configurable flat bedrock worldgen + if (l1 < 127 - (h.generatorConfig.flatBedrock.getValue() || h.paperSpigotConfig.generateFlatBedrock ? 0 : this.j.nextInt(5)) && + l1 > (h.generatorConfig.flatBedrock.getValue() || h.paperSpigotConfig.generateFlatBedrock ? 0 : this.j.nextInt(5))) { + // PaperSpigot end + IBlockData iblockdata2 = chunksnapshot.a(i1, l1, l); + + if (iblockdata2.getBlock() != null && iblockdata2.getBlock().getMaterial() != Material.AIR) { + if (iblockdata2.getBlock() == Blocks.NETHERRACK) { + if (k1 == -1) { + if (j1 <= 0) { + iblockdata = null; + iblockdata1 = Blocks.NETHERRACK.getBlockData(); + } else if (l1 >= k - 4 && l1 <= k + 1) { + iblockdata = Blocks.NETHERRACK.getBlockData(); + iblockdata1 = Blocks.NETHERRACK.getBlockData(); + if (flag1) { + iblockdata = Blocks.GRAVEL.getBlockData(); + } + + if (flag) { + iblockdata = Blocks.SOUL_SAND.getBlockData(); + iblockdata1 = Blocks.SOUL_SAND.getBlockData(); + } + } + + if (l1 < k && (iblockdata == null || iblockdata.getBlock().getMaterial() == Material.AIR)) { + iblockdata = Blocks.LAVA.getBlockData(); + } + + k1 = j1; + if (l1 >= k - 1) { + chunksnapshot.a(i1, l1, l, iblockdata); + } else { + chunksnapshot.a(i1, l1, l, iblockdata1); + } + } else if (k1 > 0) { + --k1; + chunksnapshot.a(i1, l1, l, iblockdata1); + } + } + } else { + k1 = -1; + } + } else { + chunksnapshot.a(i1, l1, l, Blocks.BEDROCK.getBlockData()); + } + } + } + } + + } + + public Chunk getOrCreateChunk(int i, int j) { + this.j.setSeed((long) i * 341873128712L + (long) j * 132897987541L); + ChunkSnapshot chunksnapshot = new ChunkSnapshot(); + + this.a(i, j, chunksnapshot); + this.b(i, j, chunksnapshot); + if (this.h.paperSpigotConfig.generateCaves) this.C.a(this, this.h, i, j, chunksnapshot); // PaperSpigot + if (this.i && this.h.paperSpigotConfig.generateFortress) { // PaperSpigot + this.B.a(this, this.h, i, j, chunksnapshot); + } + + Chunk chunk = new Chunk(this.h, chunksnapshot, i, j); + BiomeBase[] abiomebase = this.h.getWorldChunkManager().getBiomeBlock(null, i * 16, j * 16, 16, 16); + byte[] abyte = chunk.getBiomeIndex(); + + for (int k = 0; k < abyte.length; ++k) { + abyte[k] = (byte) abiomebase[k].id; + } + + chunk.l(); + return chunk; + } + + private double[] a(double[] adouble, int i, int j, int k, int l, int i1, int j1) { + if (adouble == null) { + adouble = new double[l * i1 * j1]; + } + + double d0 = 684.412D; + double d1 = 2053.236D; + + this.f = this.a.a(this.f, i, j, k, l, 1, j1, 1.0D, 0.0D, 1.0D); + this.g = this.b.a(this.g, i, j, k, l, 1, j1, 100.0D, 0.0D, 100.0D); + this.c = this.q.a(this.c, i, j, k, l, i1, j1, d0 / 80.0D, d1 / 60.0D, d0 / 80.0D); + this.d = this.o.a(this.d, i, j, k, l, i1, j1, d0, d1, d0); + this.e = this.p.a(this.e, i, j, k, l, i1, j1, d0, d1, d0); + int k1 = 0; + double[] adouble1 = new double[i1]; + + int l1; + + for (l1 = 0; l1 < i1; ++l1) { + adouble1[l1] = Math.cos((double) l1 * 3.141592653589793D * 6.0D / (double) i1) * 2.0D; + double d2 = l1; + + if (l1 > i1 / 2) { + d2 = i1 - 1 - l1; + } + + if (d2 < 4.0D) { + d2 = 4.0D - d2; + adouble1[l1] -= d2 * d2 * d2 * 10.0D; + } + } + + for (l1 = 0; l1 < l; ++l1) { + for (int i2 = 0; i2 < j1; ++i2) { + double d3 = 0.0D; + + for (int j2 = 0; j2 < i1; ++j2) { + double d4; + double d5 = adouble1[j2]; + double d6 = this.d[k1] / 512.0D; + double d7 = this.e[k1] / 512.0D; + double d8 = (this.c[k1] / 10.0D + 1.0D) / 2.0D; + + if (d8 < 0.0D) { + d4 = d6; + } else if (d8 > 1.0D) { + d4 = d7; + } else { + d4 = d6 + (d7 - d6) * d8; + } + + d4 -= d5; + double d9; + + if (j2 > i1 - 4) { + d9 = (float) (j2 - (i1 - 4)) / 3.0F; + d4 = d4 * (1.0D - d9) + -10.0D * d9; + } + + if ((double) j2 < d3) { + d9 = (d3 - (double) j2) / 4.0D; + d9 = MathHelper.a(d9, 0.0D, 1.0D); + d4 = d4 * (1.0D - d9) + -10.0D * d9; + } + + adouble[k1] = d4; + ++k1; + } + } + } + + return adouble; + } + + public boolean isChunkLoaded(int i, int j) { + return true; + } + + public void getChunkAt(IChunkProvider ichunkprovider, int i, int j) { + BlockFalling.instaFall = true; + BlockPosition blockposition = new BlockPosition(i * 16, 0, j * 16); + this.B.a(this.h, this.j, new ChunkCoordIntPair(i, j)); + + int k; + + for (k = 0; k < 8; ++k) { + this.y.generate(this.h, this.j, blockposition.a(this.j.nextInt(16) + 8, this.j.nextInt(120) + 4, this.j.nextInt(16) + 8)); + } + + for (k = 0; k < this.j.nextInt(this.j.nextInt(10) + 1) + 1; ++k) { + this.t.generate(this.h, this.j, blockposition.a(this.j.nextInt(16) + 8, this.j.nextInt(120) + 4, this.j.nextInt(16) + 8)); + } + + for (k = 0; k < this.j.nextInt(this.j.nextInt(10) + 1); ++k) { + this.u.generate(this.h, this.j, blockposition.a(this.j.nextInt(16) + 8, this.j.nextInt(120) + 4, this.j.nextInt(16) + 8)); + } + + for (k = 0; k < 10; ++k) { + this.v.generate(this.h, this.j, blockposition.a(this.j.nextInt(16) + 8, this.j.nextInt(128), this.j.nextInt(16) + 8)); + } + + if (this.j.nextBoolean()) { + this.z.generate(this.h, this.j, blockposition.a(this.j.nextInt(16) + 8, this.j.nextInt(128), this.j.nextInt(16) + 8)); + } + + if (this.j.nextBoolean()) { + this.A.generate(this.h, this.j, blockposition.a(this.j.nextInt(16) + 8, this.j.nextInt(128), this.j.nextInt(16) + 8)); + } + + for (k = 0; k < 16; ++k) { + this.w.generate(this.h, this.j, blockposition.a(this.j.nextInt(16), this.j.nextInt(108) + 10, this.j.nextInt(16))); + } + + for (k = 0; k < 16; ++k) { + this.x.generate(this.h, this.j, blockposition.a(this.j.nextInt(16), this.j.nextInt(108) + 10, this.j.nextInt(16))); + } + + BlockFalling.instaFall = false; + } + + public boolean a(IChunkProvider ichunkprovider, Chunk chunk, int i, int j) { + return false; + } + + public boolean saveChunks(boolean flag, IProgressUpdate iprogressupdate) { + return true; + } + + public void c() { + } + + public boolean unloadChunks() { + return false; + } + + public boolean canSave() { + return true; + } + + public String getName() { + return "HellRandomLevelSource"; + } + + public List getMobsFor(EnumCreatureType enumcreaturetype, BlockPosition blockposition) { + if (enumcreaturetype == EnumCreatureType.MONSTER) { + if (this.B.b(blockposition)) { + return this.B.b(); + } + + if (this.B.a(this.h, blockposition) && this.h.getType(blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()).getBlock() == Blocks.NETHER_BRICK) { + return this.B.b(); + } + } + + BiomeBase biomebase = this.h.getBiome(blockposition); + + return biomebase.getMobs(enumcreaturetype); + } + + public BlockPosition findNearestMapFeature(World world, String s, BlockPosition blockposition) { + return null; + } + + public int getLoadedChunks() { + return 0; + } + + public void recreateStructures(Chunk chunk, int i, int j) { + if (this.h.paperSpigotConfig.generateFortress) this.B.a(this, this.h, i, j, null); // PaperSpigot + } + + public Chunk getChunkAt(BlockPosition blockposition) { + return this.getOrCreateChunk(blockposition.getX() >> 4, blockposition.getZ() >> 4); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ChunkProviderServer.java b/azurite-server/src/main/java/net/minecraft/server/ChunkProviderServer.java new file mode 100644 index 0000000..2dfe0e6 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ChunkProviderServer.java @@ -0,0 +1,460 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.AzuriteConfig; +import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.longs.LongIterator; +import it.unimi.dsi.fastutil.longs.LongOpenHashSet; +import it.unimi.dsi.fastutil.longs.LongSet; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.bukkit.Server; +import org.bukkit.craftbukkit.chunkio.ChunkIOExecutor; +import org.bukkit.craftbukkit.util.LongHash; +import org.bukkit.event.world.ChunkUnloadEvent; + +import java.io.IOException; +import java.util.List; +import java.util.Random; +// CraftBukkit end + +public class ChunkProviderServer implements IChunkProvider { + + private static final Logger b = LogManager.getLogger(); + public LongSet unloadQueue = new LongOpenHashSet(); // Azurite - Use LongOpenHashSet + public Chunk emptyChunk; + public IChunkProvider chunkProvider; + public IChunkLoader chunkLoader; + public boolean forceChunkLoad = false; // CraftBukkit - true -> falsee + protected Chunk lastChunkByPos = null; + public Long2ObjectOpenHashMap chunks = new Long2ObjectOpenHashMap(8192, 0.5f) { + @Override + public Chunk get(long key) { + if (lastChunkByPos != null && key == lastChunkByPos.chunkHashKey) + return lastChunkByPos; + return lastChunkByPos = super.get(key); + } + + @Override + public Chunk remove(long key) { + if (lastChunkByPos != null && key == lastChunkByPos.chunkHashKey) + lastChunkByPos = null; + return super.remove(key); + } + }; + public WorldServer world; + + public ChunkProviderServer(WorldServer worldserver, IChunkLoader ichunkloader, IChunkProvider ichunkprovider) { + emptyChunk = new EmptyChunk(worldserver, Integer.MIN_VALUE, Integer.MAX_VALUE); + world = worldserver; + chunkLoader = ichunkloader; + chunkProvider = ichunkprovider; + } + + public boolean isChunkLoaded(int i, int j) { + return chunks.containsKey(LongHash.toLong(i, j)); // CraftBukkit + } + + // CraftBukkit start - Change return type to Collection and return the values of our chunk map + public java.util.Collection a() { + // return this.chunkList; + return chunks.values(); + // CraftBukkit end + } + + public void queueUnload(long hash, int i, int j) { + world.chunkTickList.remove(hash); // Azurite - remove from ticking + + if (AzuriteConfig.chunkUnloading.getValue()) { + // PaperSpigot start - Asynchronous lighting updates + Chunk chunk = chunks.get(hash); + if (chunk != null) { + if (chunk.world.paperSpigotConfig.useAsyncLighting && (chunk.pendingLightUpdates.get() > 0 || chunk.world.getTime() - chunk.lightUpdateTime < 20)) + return; + for (List entities : chunk.entitySlices) { + for (Entity entity : entities) { + if (entity.loadChunks) { + return; + } + } + } + if (world.worldProvider.e()) { + if (!world.c(i, j)) { + unloadQueue.add(hash); // Vortex + chunk.mustSave = true; + } + } else { + unloadQueue.add(hash); // Vortex + chunk.mustSave = true; + } + } + } + } + + public void queueUnload(int i, int j) { + queueUnload(LongHash.toLong(i, j), i, j); + } + + public void b() { + for (Chunk chunk : chunks.values()) { + queueUnload(chunk.locX, chunk.locZ); + } + } + + // CraftBukkit start - Add async variant, provide compatibility + public Chunk getChunkIfLoaded(int x, int z) { + return chunks.get(LongHash.toLong(x, z)); + } + + public Chunk getChunkIfLoaded(long hash) { + return chunks.get(hash); + } + + public Chunk getChunkAt(int i, int j) { + return getChunkAt(LongHash.toLong(i, j), i, j, null); + } + + public Chunk getChunkAt(int i, int j, Runnable runnable) { + return getChunkAt(LongHash.toLong(i, j), i, j, runnable); + } + + public Chunk getChunkAt(long hash, int i, int j) { + return getChunkAt(hash, i, j, null); + } + + public Chunk getChunkAt(long hash, int i, int j, Runnable runnable) { + unloadQueue.remove(hash); + Chunk chunk = this.chunks.get(hash); + ChunkRegionLoader loader = null; + + if (this.chunkLoader instanceof ChunkRegionLoader) { + loader = (ChunkRegionLoader) this.chunkLoader; + } + + // We can only use the queue for already generated chunks + if (chunk == null && loader != null && loader.chunkExists(i, j)) { + if (runnable != null) { + ChunkIOExecutor.queueChunkLoad(world, loader, this, i, j, runnable); + return null; + } else { + chunk = ChunkIOExecutor.syncChunkLoad(world, loader, this, i, j); + } + } else if (chunk == null) { + chunk = originalGetChunkAt(i, j); + } + + // If we didn't load the chunk async and have a callback run it now + if (runnable != null) { + runnable.run(); + } + + return chunk; + } + + public Chunk getChunkAtWithoutCreation(int i, int j) { + long hash = LongHash.toLong(i, j); + unloadQueue.remove(hash); + Chunk chunk = chunks.get(hash); + ChunkRegionLoader loader = null; + if (chunkLoader instanceof ChunkRegionLoader) + loader = (ChunkRegionLoader) chunkLoader; + + if (chunk == null && loader != null && loader.chunkExists(i, j)) + chunk = ChunkIOExecutor.syncChunkLoad(world, loader, this, i, j); + + return chunk; + } + + public Chunk originalGetChunkAt(int i, int j) { + long key = LongHash.toLong(i, j); + this.unloadQueue.remove(key); + Chunk chunk = this.chunks.get(key); + boolean newChunk = false; + // CraftBukkit end + + Server server = world.getServer(); + + if (chunk == null) { + chunk = this.loadChunk(i, j); + if (chunk == null) { + if (this.chunkProvider == null) { + chunk = this.emptyChunk; + } else { + try { + chunk = this.chunkProvider.getOrCreateChunk(i, j); + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.a(throwable, "Exception generating new chunk"); + CrashReportSystemDetails crashreportsystemdetails = crashreport.a("Chunk to be generated"); + + crashreportsystemdetails.a("Location", String.format("%d,%d", i, j)); + crashreportsystemdetails.a("Position hash", key); // CraftBukkit - Use LongHash + crashreportsystemdetails.a("Generator", this.chunkProvider.getName()); + throw new ReportedException(crashreport); + } + } + newChunk = true; // CraftBukkit + } + + this.chunks.put(key, chunk); + + chunk.addEntities(); + + // CraftBukkit start + if (server != null) { + /* + * If it's a new world, the first few chunks are generated inside + * the World constructor. We can't reliably alter that, so we have + * no way of creating a CraftWorld/CraftServer at that point. + */ + server.getPluginManager().callEvent(new org.bukkit.event.world.ChunkLoadEvent(chunk.bukkitChunk, newChunk)); + } + + // Update neighbor counts + for (int x = -2; x < 3; x++) { + for (int z = -2; z < 3; z++) { + if (x == 0 && z == 0) { + continue; + } + + Chunk neighbor = this.getChunkIfLoaded(chunk.locX + x, chunk.locZ + z); + if (neighbor != null) { + neighbor.setNeighborLoaded(-x, -z); + chunk.setNeighborLoaded(x, z); + } + } + } + // CraftBukkit end + chunk.loadNearby(this, this, i, j); + } + + return chunk; + } + + public Chunk getOrCreateChunk(long hash, int i, int j) { + Chunk chunk = chunks.get(hash); + chunk = chunk == null ? (!world.ad() && !forceChunkLoad ? emptyChunk : getChunkAt(hash, i, j)) : chunk; + + if (chunk == emptyChunk) return chunk; + if (i != chunk.locX || j != chunk.locZ) { + // Paper start + String msg = "Chunk (" + chunk.locX + ", " + chunk.locZ + ") stored at (" + i + ", " + j + ") in world '" + world.getWorld().getName() + "'"; + b.error(msg); + b.error(chunk.getClass().getName()); + Throwable ex = new Throwable(); + ex.fillInStackTrace(); + ex.printStackTrace(); + // Paper end + } + return chunk; + } + + public Chunk getOrCreateChunk(int i, int j) { + return getOrCreateChunk(LongHash.toLong(i, j), i, j); + } + + public Chunk loadChunk(int i, int j) { + if (this.chunkLoader == null) { + return null; + } else { + try { + Chunk chunk = this.chunkLoader.a(this.world, i, j); + + if (chunk != null) { + chunk.setLastSaved(this.world.getTime()); + if (this.chunkProvider != null) { + this.chunkProvider.recreateStructures(chunk, i, j); + } + } + + return chunk; + } catch (Exception exception) { + // Paper start + String msg = "Couldn't load chunk"; + ChunkProviderServer.b.error(msg, exception); + // Paper end + return null; + } + } + } + + public void saveChunkNOP(Chunk chunk) { + if (this.chunkLoader != null) { + try { + this.chunkLoader.b(this.world, chunk); + } catch (Exception exception) { + ChunkProviderServer.b.error("Couldn't save entities", exception); + } + } + } + + public void saveChunk(Chunk chunk) { + if (this.chunkLoader != null) { + try { + chunk.setLastSaved(this.world.getTime()); + this.chunkLoader.a(this.world, chunk); + } catch (IOException ioexception) { + ChunkProviderServer.b.error("Couldn't save chunk", ioexception); + } catch (ExceptionWorldConflict exceptionworldconflict) { + ChunkProviderServer.b.error("Couldn't save chunk; already in use by another instance of Minecraft?", exceptionworldconflict); + } + } + } + + public void getChunkAt(IChunkProvider ichunkprovider, int i, int j) { + Chunk chunk = this.getOrCreateChunk(i, j); + + if (!chunk.isDone()) { + chunk.n(); + if (this.chunkProvider != null) { + this.chunkProvider.getChunkAt(ichunkprovider, i, j); + + // CraftBukkit start + BlockSand.instaFall = true; + Random random = new Random(); + random.setSeed(world.getSeed()); + long xRand = random.nextLong() / 2L * 2L + 1L; + long zRand = random.nextLong() / 2L * 2L + 1L; + random.setSeed((long) i * xRand + (long) j * zRand ^ world.getSeed()); + + org.bukkit.World world = this.world.getWorld(); + if (world != null) { + this.world.populating = true; + try { + for (org.bukkit.generator.BlockPopulator populator : world.getPopulators()) { + populator.populate(world, random, chunk.bukkitChunk); + } + } finally { + this.world.populating = false; + } + } + BlockSand.instaFall = false; + this.world.getServer().getPluginManager().callEvent(new org.bukkit.event.world.ChunkPopulateEvent(chunk.bukkitChunk)); + // CraftBukkit end + + chunk.e(); + } + } + } + + public boolean a(IChunkProvider ichunkprovider, Chunk chunk, int i, int j) { + if (this.chunkProvider != null && this.chunkProvider.a(ichunkprovider, chunk, i, j)) { + getOrCreateChunk(i, j).e(); + return true; + } else { + return false; + } + } + + public boolean saveChunks(boolean flag, IProgressUpdate iprogressupdate) { + // CraftBukkit start + int i = 0; + for (Chunk chunk : this.chunks.values()) { + if (flag) + saveChunkNOP(chunk); + if (chunk.a(flag)) { + saveChunk(chunk); + chunk.f(false); + i++; + if (i >= AzuriteConfig.autoSaveChunksPerTick.getValue() && !flag) { + this.world.getAutoSaveWorldData().addAutoSaveChunkCount(i); + return false; + } + } + } + if (!flag) { + this.world.getAutoSaveWorldData().addAutoSaveChunkCount(i); + } + return true; + } + + public void c() { + if (this.chunkLoader != null) { + this.chunkLoader.b(); + } + } + + public boolean unloadChunks() { + if (!world.savingDisabled) { + // CraftBukkit start + Server server = world.getServer(); + + int perTick = AzuriteConfig.unloadPerTick.getValue(); + LongIterator iterator = unloadQueue.iterator(); + for (int i = 0; i < perTick && iterator.hasNext(); i++) { + long chunkCoordinates; + + // Azurite - Catch exception and cancel loop + try { + chunkCoordinates = iterator.nextLong(); + iterator.remove(); + } catch (Exception e) { + break; + } + + Chunk chunk = chunks.get(chunkCoordinates); + if (chunk == null) // Vortex + continue; + + ChunkUnloadEvent event = new ChunkUnloadEvent(chunk.bukkitChunk); + server.getPluginManager().callEvent(event); + if (!event.isCancelled()) { + chunk.removeEntities(); + saveChunk(chunk); + saveChunkNOP(chunk); + chunks.remove(chunkCoordinates); // CraftBukkit + world.chunkTickList.remove(chunk); // Beanes - optimized chunk ticking + + // Update neighbor counts + for (int x = -2; x < 3; x++) { + for (int z = -2; z < 3; z++) { + if (x == 0 && z == 0) { + continue; + } + + Chunk neighbor = this.getChunkIfLoaded(chunk.locX + x, chunk.locZ + z); + if (neighbor != null) { + neighbor.setNeighborUnloaded(-x, -z); + chunk.setNeighborUnloaded(x, z); + } + } + } + } + } + // CraftBukkit end + + if (chunkLoader != null) { + chunkLoader.a(); + } + } + + return chunkProvider.unloadChunks(); + } + + public boolean canSave() { + return !this.world.savingDisabled; + } + + public String getName() { + // CraftBukkit - this.chunks.count() -> .size() + return "ServerChunkCache: " + this.chunks.size() + " Drop: " + this.unloadQueue.size(); + } + + public List getMobsFor(EnumCreatureType enumcreaturetype, BlockPosition blockposition) { + return this.chunkProvider.getMobsFor(enumcreaturetype, blockposition); + } + + public BlockPosition findNearestMapFeature(World world, String s, BlockPosition blockposition) { + return this.chunkProvider.findNearestMapFeature(world, s, blockposition); + } + + public int getLoadedChunks() { + // CraftBukkit - this.chunks.count() -> this.chunks.size() + return this.chunks.size(); + } + + public void recreateStructures(Chunk chunk, int i, int j) { + } + + public Chunk getChunkAt(BlockPosition blockposition) { + return this.getOrCreateChunk(blockposition.getX() >> 4, blockposition.getZ() >> 4); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ChunkProviderTheEnd.java b/azurite-server/src/main/java/net/minecraft/server/ChunkProviderTheEnd.java new file mode 100644 index 0000000..1f0f629 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ChunkProviderTheEnd.java @@ -0,0 +1,262 @@ +package net.minecraft.server; + +import java.util.List; +import java.util.Random; + +public class ChunkProviderTheEnd implements IChunkProvider { + + public NoiseGeneratorOctaves a; + public NoiseGeneratorOctaves b; + double[] c; + double[] d; + double[] e; + double[] f; + double[] g; + private final Random h; + private final NoiseGeneratorOctaves i; + private final NoiseGeneratorOctaves j; + private final NoiseGeneratorOctaves k; + private final World l; + private double[] m; + private BiomeBase[] n; + + public ChunkProviderTheEnd(World world, long i) { + this.l = world; + this.h = new Random(i); + this.i = new NoiseGeneratorOctaves(this.h, 16); + this.j = new NoiseGeneratorOctaves(this.h, 16); + this.k = new NoiseGeneratorOctaves(this.h, 8); + this.a = new NoiseGeneratorOctaves(this.h, 10); + this.b = new NoiseGeneratorOctaves(this.h, 16); + } + + public void a(int i, int j, ChunkSnapshot chunksnapshot) { + byte b0 = 2; + int k = b0 + 1; + byte b1 = 33; + int l = b0 + 1; + + this.m = this.a(this.m, i * b0, 0, j * b0, k, b1, l); + + for (int i1 = 0; i1 < b0; ++i1) { + for (int j1 = 0; j1 < b0; ++j1) { + for (int k1 = 0; k1 < 32; ++k1) { + double d1 = this.m[((i1) * l + j1) * b1 + k1]; + double d2 = this.m[((i1) * l + j1 + 1) * b1 + k1]; + double d3 = this.m[((i1 + 1) * l + j1) * b1 + k1]; + double d4 = this.m[((i1 + 1) * l + j1 + 1) * b1 + k1]; + double d5 = (this.m[((i1) * l + j1) * b1 + k1 + 1] - d1) * 0.25D; + double d6 = (this.m[((i1) * l + j1 + 1) * b1 + k1 + 1] - d2) * 0.25D; + double d7 = (this.m[((i1 + 1) * l + j1) * b1 + k1 + 1] - d3) * 0.25D; + double d8 = (this.m[((i1 + 1) * l + j1 + 1) * b1 + k1 + 1] - d4) * 0.25D; + + for (int l1 = 0; l1 < 4; ++l1) { + double d10 = d1; + double d11 = d2; + double d12 = (d3 - d1) * 0.125D; + double d13 = (d4 - d2) * 0.125D; + + for (int i2 = 0; i2 < 8; ++i2) { + double d15 = d10; + double d16 = (d11 - d10) * 0.125D; + + for (int j2 = 0; j2 < 8; ++j2) { + IBlockData iblockdata = null; + + if (d15 > 0.0D) { + iblockdata = Blocks.END_STONE.getBlockData(); + } + + int k2 = i2 + i1 * 8; + int l2 = l1 + k1 * 4; + int i3 = j2 + j1 * 8; + + chunksnapshot.a(k2, l2, i3, iblockdata); + d15 += d16; + } + + d10 += d12; + d11 += d13; + } + + d1 += d5; + d2 += d6; + d3 += d7; + d4 += d8; + } + } + } + } + + } + + public void a(ChunkSnapshot chunksnapshot) { + for (int i = 0; i < 16; ++i) { + for (int j = 0; j < 16; ++j) { + byte b0 = 1; + int k = -1; + IBlockData iblockdata = Blocks.END_STONE.getBlockData(); + IBlockData iblockdata1 = Blocks.END_STONE.getBlockData(); + + for (int l = 127; l >= 0; --l) { + IBlockData iblockdata2 = chunksnapshot.a(i, l, j); + + if (iblockdata2.getBlock().getMaterial() == Material.AIR) { + k = -1; + } else if (iblockdata2.getBlock() == Blocks.STONE) { + if (k == -1) { + + k = b0; + chunksnapshot.a(i, l, j, iblockdata); + } else if (k > 0) { + --k; + chunksnapshot.a(i, l, j, iblockdata1); + } + } + } + } + } + + } + + public Chunk getOrCreateChunk(int i, int j) { + this.h.setSeed((long) i * 341873128712L + (long) j * 132897987541L); + ChunkSnapshot chunksnapshot = new ChunkSnapshot(); + + this.n = this.l.getWorldChunkManager().getBiomeBlock(this.n, i * 16, j * 16, 16, 16); + this.a(i, j, chunksnapshot); + this.a(chunksnapshot); + Chunk chunk = new Chunk(this.l, chunksnapshot, i, j); + byte[] abyte = chunk.getBiomeIndex(); + + for (int k = 0; k < abyte.length; ++k) { + abyte[k] = (byte) this.n[k].id; + } + + chunk.initLighting(); + return chunk; + } + + private double[] a(double[] adouble, int i, int j, int k, int l, int i1, int j1) { + if (adouble == null) { + adouble = new double[l * i1 * j1]; + } + + double d0 = 684.412D; + double d1 = 684.412D; + + this.f = this.a.a(this.f, i, k, l, j1, 1.121D, 1.121D, 0.5D); + this.g = this.b.a(this.g, i, k, l, j1, 200.0D, 200.0D, 0.5D); + d0 *= 2.0D; + this.c = this.k.a(this.c, i, j, k, l, i1, j1, d0 / 80.0D, d1 / 160.0D, d0 / 80.0D); + this.d = this.i.a(this.d, i, j, k, l, i1, j1, d0, d1, d0); + this.e = this.j.a(this.e, i, j, k, l, i1, j1, d0, d1, d0); + int k1 = 0; + + for (int l1 = 0; l1 < l; ++l1) { + for (int i2 = 0; i2 < j1; ++i2) { + float f = (float) (l1 + i); + float f1 = (float) (i2 + k); + float f2 = 100.0F - MathHelper.c(f * f + f1 * f1) * 8.0F; + + if (f2 > 80.0F) { + f2 = 80.0F; + } + + if (f2 < -100.0F) { + f2 = -100.0F; + } + + for (int j2 = 0; j2 < i1; ++j2) { + double d2; + double d3 = this.d[k1] / 512.0D; + double d4 = this.e[k1] / 512.0D; + double d5 = (this.c[k1] / 10.0D + 1.0D) / 2.0D; + + if (d5 < 0.0D) { + d2 = d3; + } else if (d5 > 1.0D) { + d2 = d4; + } else { + d2 = d3 + (d4 - d3) * d5; + } + + d2 -= 8.0D; + d2 += f2; + byte b0 = 2; + double d6; + + if (j2 > i1 / 2 - b0) { + d6 = ((float) (j2 - (i1 / 2 - b0)) / 64.0F); + d6 = MathHelper.a(d6, 0.0D, 1.0D); + d2 = d2 * (1.0D - d6) + -3000.0D * d6; + } + + b0 = 8; + if (j2 < b0) { + d6 = ((float) (b0 - j2) / ((float) b0 - 1.0F)); + d2 = d2 * (1.0D - d6) + -30.0D * d6; + } + + adouble[k1] = d2; + ++k1; + } + } + } + + return adouble; + } + + public boolean isChunkLoaded(int i, int j) { + return true; + } + + public void getChunkAt(IChunkProvider ichunkprovider, int i, int j) { + BlockFalling.instaFall = true; + BlockPosition blockposition = new BlockPosition(i * 16, 0, j * 16); + this.l.getBiome(blockposition.getX() + 16, 0, blockposition.getZ() + 16).a(this.l, this.l.random, blockposition); + BlockFalling.instaFall = false; + } + + public boolean a(IChunkProvider ichunkprovider, Chunk chunk, int i, int j) { + return false; + } + + public boolean saveChunks(boolean flag, IProgressUpdate iprogressupdate) { + return true; + } + + public void c() { + } + + public boolean unloadChunks() { + return false; + } + + public boolean canSave() { + return true; + } + + public String getName() { + return "RandomLevelSource"; + } + + public List getMobsFor(EnumCreatureType enumcreaturetype, BlockPosition blockposition) { + return this.l.getBiome(blockposition).getMobs(enumcreaturetype); + } + + public BlockPosition findNearestMapFeature(World world, String s, BlockPosition blockposition) { + return null; + } + + public int getLoadedChunks() { + return 0; + } + + public void recreateStructures(Chunk chunk, int i, int j) { + } + + public Chunk getChunkAt(BlockPosition blockposition) { + return this.getOrCreateChunk(blockposition.getX() >> 4, blockposition.getZ() >> 4); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ChunkRegionLoader.java b/azurite-server/src/main/java/net/minecraft/server/ChunkRegionLoader.java new file mode 100644 index 0000000..aeb0327 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ChunkRegionLoader.java @@ -0,0 +1,454 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.AzuriteConfig; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.io.*; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; + +public class ChunkRegionLoader implements IChunkLoader, IAsyncChunkSaver { + + private static final Logger a = LogManager.getLogger(); + private final File d; + public Map b = new ConcurrentHashMap<>(); + public Set c = Collections.newSetFromMap(new ConcurrentHashMap<>()); + private boolean e = false; + + public ChunkRegionLoader(File file) { + this.d = file; + } + + // CraftBukkit start + public boolean chunkExists(int i, int j) { + ChunkCoordIntPair chunkcoordintpair = new ChunkCoordIntPair(i, j); + + if (this.c.contains(chunkcoordintpair)) { + if (this.b.containsKey(chunkcoordintpair)) { + return true; + } + } + + RegionFile region = RegionFileCache.a(this.d, i, j, false); // PaperSpigot + return region != null && region.chunkExists(i & 31, j & 31); // PaperSpigot + } + // CraftBukkit end + + // CraftBukkit start - Add async variant, provide compatibility + public Chunk a(World world, int i, int j) throws IOException { + Object[] data = loadChunk(world, i, j); + if (data != null) { + Chunk chunk = (Chunk) data[0]; + NBTTagCompound nbttagcompound = (NBTTagCompound) data[1]; + loadEntities(chunk, nbttagcompound.getCompound("Level"), world); + return chunk; + } + + return null; + } + + public Object[] loadChunk(World world, int i, int j) throws IOException { + // CraftBukkit end + ChunkCoordIntPair chunkcoordintpair = new ChunkCoordIntPair(i, j); + NBTTagCompound nbttagcompound = this.b.get(chunkcoordintpair); + + if (nbttagcompound == null) { + DataInputStream datainputstream = RegionFileCache.c(this.d, i, j); + + if (datainputstream == null) { + return null; + } + + nbttagcompound = NBTCompressedStreamTools.a(datainputstream); + } + + return this.a(world, i, j, nbttagcompound); + } + + protected Object[] a(World world, int i, int j, NBTTagCompound nbttagcompound) { // CraftBukkit - return Chunk -> + // Object[] + if (!nbttagcompound.hasKeyOfType("Level", 10)) { + ChunkRegionLoader.a.error("Chunk file at {},{} is missing level data, skipping", i, j); + return null; + } else { + NBTTagCompound nbttagcompound1 = nbttagcompound.getCompound("Level"); + + if (!nbttagcompound1.hasKeyOfType("Sections", 9)) { + ChunkRegionLoader.a.error("Chunk file at {},{} is missing block data, skipping", i, j); + return null; + } else { + Chunk chunk = this.a(world, nbttagcompound1); + + if (!chunk.a(i, j)) { + ChunkRegionLoader.a + .error("Chunk file at {},{} is in the wrong location; relocating. (Expected {}, {}, got {}, {})", i, j, i, j, chunk.locX, chunk.locZ); + nbttagcompound1.setInt("xPos", i); + nbttagcompound1.setInt("zPos", j); + + // CraftBukkit start - Have to move tile entities since we don't load them at + // this stage + NBTTagList tileEntities = nbttagcompound.getCompound("Level").getList("TileEntities", 10); + if (tileEntities != null) { + for (int te = 0; te < tileEntities.size(); te++) { + NBTTagCompound tileEntity = tileEntities.get(te); + int x = tileEntity.getInt("x") - chunk.locX * 16; + int z = tileEntity.getInt("z") - chunk.locZ * 16; + tileEntity.setInt("x", i * 16 + x); + tileEntity.setInt("z", j * 16 + z); + } + } + // CraftBukkit end + chunk = this.a(world, nbttagcompound1); + } + + // CraftBukkit start + Object[] data = new Object[2]; + data[0] = chunk; + data[1] = nbttagcompound; + return data; + // CraftBukkit end + } + } + } + + public void a(World world, Chunk chunk) throws IOException, ExceptionWorldConflict { + // Azurite - don't check session on every chunk save + // world.checkSession(); + + try { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + + nbttagcompound.set("Level", nbttagcompound1); + this.a(chunk, world, nbttagcompound1); + this.a(chunk.j(), nbttagcompound); + } catch (Exception exception) { + ChunkRegionLoader.a.error("Failed to save chunk", exception); + } + + } + + protected void a(ChunkCoordIntPair chunkcoordintpair, NBTTagCompound nbttagcompound) { + if (!this.c.contains(chunkcoordintpair)) { + this.b.put(chunkcoordintpair, nbttagcompound); + } + + FileIOThread.a().a(this); + } + + public boolean c() { + if (this.b.isEmpty()) { + if (this.e) { + ChunkRegionLoader.a.info("ThreadedAnvilChunkStorage ({}): All chunks are saved", + this.d.getName()); + } + + return false; + } else { + ChunkCoordIntPair chunkcoordintpair = this.b.keySet().iterator().next(); + + try { + this.c.add(chunkcoordintpair); + NBTTagCompound nbttagcompound = this.b.remove(chunkcoordintpair); + + if (nbttagcompound != null) { + try { + this.b(chunkcoordintpair, nbttagcompound); + } catch (Exception exception) { + ChunkRegionLoader.a.error("Failed to save chunk", exception); + } + } + } finally { + this.c.remove(chunkcoordintpair); + } + + return true; + } + } + + private void b(ChunkCoordIntPair chunkcoordintpair, NBTTagCompound nbttagcompound) throws IOException { + DataOutputStream dataoutputstream = RegionFileCache.d(this.d, chunkcoordintpair.x, chunkcoordintpair.z); + + NBTCompressedStreamTools.a(nbttagcompound, (DataOutput) dataoutputstream); + dataoutputstream.close(); + } + + public void b(World world, Chunk chunk) throws IOException { + } + + public void a() { + } + + public void b() { + try { + this.e = true; + + while (true) { + this.c(); + } + } finally { + this.e = false; + } + + } + + private void a(Chunk chunk, World world, NBTTagCompound nbttagcompound) { + nbttagcompound.setByte("V", (byte) 1); + nbttagcompound.setInt("xPos", chunk.locX); + nbttagcompound.setInt("zPos", chunk.locZ); + nbttagcompound.setLong("LastUpdate", world.getTime()); + nbttagcompound.setIntArray("HeightMap", chunk.q()); + nbttagcompound.setBoolean("TerrainPopulated", chunk.isDone()); + nbttagcompound.setBoolean("LightPopulated", chunk.u()); + nbttagcompound.setLong("InhabitedTime", chunk.w()); + ChunkSection[] achunksection = chunk.getSections(); + NBTTagList nbttaglist = new NBTTagList(); + boolean flag = !world.worldProvider.o(); + int i = achunksection.length; + + NBTTagCompound nbttagcompound1; + + for (int j = 0; j < i; ++j) { + ChunkSection chunksection = achunksection[j]; + + if (chunksection != null) { + nbttagcompound1 = new NBTTagCompound(); + nbttagcompound1.setByte("Y", (byte) (chunksection.getYPosition() >> 4 & 255)); + byte[] abyte = new byte[chunksection.getIdArray().length]; + NibbleArray nibblearray = new NibbleArray(); + NibbleArray nibblearray1 = null; + + for (int k = 0; k < chunksection.getIdArray().length; ++k) { + char c0 = chunksection.getIdArray()[k]; + int l = k & 15; + int i1 = k >> 8 & 15; + int j1 = k >> 4 & 15; + + if (c0 >> 12 != 0) { + if (nibblearray1 == null) { + nibblearray1 = new NibbleArray(); + } + + nibblearray1.a(l, i1, j1, c0 >> 12); + } + + abyte[k] = (byte) (c0 >> 4 & 255); + nibblearray.a(l, i1, j1, c0 & 15); + } + + nbttagcompound1.setByteArray("Blocks", abyte); + nbttagcompound1.setByteArray("Data", nibblearray.a()); + if (nibblearray1 != null) { + nbttagcompound1.setByteArray("Add", nibblearray1.a()); + } + + nbttagcompound1.setByteArray("BlockLight", chunksection.getEmittedLightArray().a()); + if (flag) { + nbttagcompound1.setByteArray("SkyLight", chunksection.getSkyLightArray().a()); + } else { + nbttagcompound1.setByteArray("SkyLight", new byte[chunksection.getEmittedLightArray().a().length]); + } + + nbttaglist.add(nbttagcompound1); + } + } + + nbttagcompound.set("Sections", nbttaglist); + nbttagcompound.setByteArray("Biomes", chunk.getBiomeIndex()); + chunk.g(false); + NBTTagList nbttaglist1 = new NBTTagList(); + + Iterator iterator; + + for (i = 0; i < chunk.getEntitySlices().length; ++i) { + iterator = chunk.getEntitySlices()[i].iterator(); + + while (iterator.hasNext()) { + Entity entity = (Entity) iterator.next(); + + nbttagcompound1 = new NBTTagCompound(); + if (entity.d(nbttagcompound1)) { + chunk.g(true); + nbttaglist1.add(nbttagcompound1); + } + } + } + + nbttagcompound.set("Entities", nbttaglist1); + NBTTagList nbttaglist2 = new NBTTagList(); + + iterator = chunk.getTileEntities().values().iterator(); + + while (iterator.hasNext()) { + TileEntity tileentity = (TileEntity) iterator.next(); + + nbttagcompound1 = new NBTTagCompound(); + tileentity.b(nbttagcompound1); + nbttaglist2.add(nbttagcompound1); + } + + nbttagcompound.set("TileEntities", nbttaglist2); + + List list = world.a(chunk, false); + if (list != null) { + long k1 = world.getTime(); + NBTTagList nbttaglist3 = new NBTTagList(); + + for (NextTickListEntry nextticklistentry : list) { + NBTTagCompound nbttagcompound2 = new NBTTagCompound(); + MinecraftKey minecraftkey = Block.REGISTRY.c(nextticklistentry.a()); + + nbttagcompound2.setString("i", minecraftkey == null ? "" : minecraftkey.toString()); + nbttagcompound2.setInt("x", nextticklistentry.a.getX()); + nbttagcompound2.setInt("y", nextticklistentry.a.getY()); + nbttagcompound2.setInt("z", nextticklistentry.a.getZ()); + nbttagcompound2.setInt("t", (int) (nextticklistentry.b - k1)); + nbttagcompound2.setInt("p", nextticklistentry.c); + nbttaglist3.add(nbttagcompound2); + } + + nbttagcompound.set("TileTicks", nbttaglist3); + } + + } + + private Chunk a(World world, NBTTagCompound nbttagcompound) { + int i = nbttagcompound.getInt("xPos"); + int j = nbttagcompound.getInt("zPos"); + Chunk chunk = new Chunk(world, i, j); + + chunk.a(nbttagcompound.getIntArray("HeightMap")); + chunk.d(nbttagcompound.getBoolean("TerrainPopulated")); + chunk.e(nbttagcompound.getBoolean("LightPopulated")); + chunk.c(nbttagcompound.getLong("InhabitedTime")); + NBTTagList nbttaglist = nbttagcompound.getList("Sections", 10); + byte b0 = 16; + ChunkSection[] achunksection = new ChunkSection[b0]; + boolean flag = !world.worldProvider.o(); + + for (int k = 0; k < nbttaglist.size(); ++k) { + NBTTagCompound nbttagcompound1 = nbttaglist.get(k); + byte b1 = nbttagcompound1.getByte("Y"); + ChunkSection chunksection = new ChunkSection(b1 << 4, flag, world.shouldSectionsHaveTickList()); + byte[] abyte = nbttagcompound1.getByteArray("Blocks"); + NibbleArray nibblearray = new NibbleArray(nbttagcompound1.getByteArray("Data")); + NibbleArray nibblearray1 = nbttagcompound1.hasKeyOfType("Add", 7) + ? new NibbleArray(nbttagcompound1.getByteArray("Add")) + : null; + char[] achar = new char[abyte.length]; + + for (int l = 0; l < achar.length; ++l) { + int i1 = l & 15; + int j1 = l >> 8 & 15; + int k1 = l >> 4 & 15; + + // CraftBukkit start - fix broken blocks + + int ex = nibblearray1 != null ? nibblearray1.a(i1, j1, k1) : 0; + int id = (abyte[l] & 255); + int data = nibblearray.a(i1, j1, k1); + int packed = ex << 12 | id << 4 | data; + if (Block.d.a(packed) == null) { + Block block = Block.getById(ex << 8 | id); + if (block != null) { + try { + data = block.toLegacyData(block.fromLegacyData(data)); + } catch (Exception ignored) { + data = block.toLegacyData(block.getBlockData()); + } + packed = ex << 12 | id << 4 | data; + } + } + achar[l] = (char) packed; + // CraftBukkit end + } + + chunksection.a(achar); + chunksection.a(new NibbleArray(nbttagcompound1.getByteArray("BlockLight"))); + if (flag) { + chunksection.b(new NibbleArray(nbttagcompound1.getByteArray("SkyLight"))); + } + + chunksection.recalcBlockCounts(); + + if (AzuriteConfig.nullifyEmptySections.getValue() && chunksection.a()) { + continue; + } + + achunksection[b1] = chunksection; + } + + chunk.a(achunksection); + if (nbttagcompound.hasKeyOfType("Biomes", 7)) { + chunk.a(nbttagcompound.getByteArray("Biomes")); + } + + // CraftBukkit start - End this method here and split off entity loading to + // another method + return chunk; + } + + public void loadEntities(Chunk chunk, NBTTagCompound nbttagcompound, World world) { + NBTTagList nbttaglist1 = nbttagcompound.getList("Entities", 10); + + if (nbttaglist1 != null) { + for (int i2 = 0; i2 < nbttaglist1.size(); ++i2) { + NBTTagCompound nbttagcompound2 = nbttaglist1.get(i2); + Entity entity = EntityTypes.a(nbttagcompound2, world); + + chunk.g(true); + if (entity != null) { + chunk.a(entity); + Entity entity1 = entity; + + for (NBTTagCompound nbttagcompound3 = nbttagcompound2; nbttagcompound3.hasKeyOfType("Riding", + 10); nbttagcompound3 = nbttagcompound3.getCompound("Riding")) { + Entity entity2 = EntityTypes.a(nbttagcompound3.getCompound("Riding"), world); + + if (entity2 != null) { + chunk.a(entity2); + entity1.mount(entity2); + } + + entity1 = entity2; + } + } + } + } + + NBTTagList nbttaglist2 = nbttagcompound.getList("TileEntities", 10); + + if (nbttaglist2 != null) { + for (int j2 = 0; j2 < nbttaglist2.size(); ++j2) { + NBTTagCompound nbttagcompound4 = nbttaglist2.get(j2); + TileEntity tileentity = TileEntity.c(nbttagcompound4); + + if (tileentity != null) { + chunk.a(tileentity); + } + } + } + + if (nbttagcompound.hasKeyOfType("TileTicks", 9) && AzuriteConfig.tickBlocks.getValue()) { // Beanes - don't add pending updates if ticking blcoks is disabled + NBTTagList nbttaglist3 = nbttagcompound.getList("TileTicks", 10); + + if (nbttaglist3 != null) { + for (int k2 = 0; k2 < nbttaglist3.size(); ++k2) { + NBTTagCompound nbttagcompound5 = nbttaglist3.get(k2); + Block block; + + if (nbttagcompound5.hasKeyOfType("i", 8)) { + block = Block.getByName(nbttagcompound5.getString("i")); + } else { + block = Block.getById(nbttagcompound5.getInt("i")); + } + + world.b(new BlockPosition(nbttagcompound5.getInt("x"), nbttagcompound5.getInt("y"), + nbttagcompound5.getInt("z")), block, nbttagcompound5.getInt("t"), + nbttagcompound5.getInt("p")); + } + } + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ChunkSection.java b/azurite-server/src/main/java/net/minecraft/server/ChunkSection.java new file mode 100644 index 0000000..df60a3b --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ChunkSection.java @@ -0,0 +1,268 @@ +package net.minecraft.server; + +import dev.azurite.spigot.api.chunk.ChunkSectionSnapshot; +import dev.azurite.spigot.configs.AzuriteConfig; +import dev.azurite.spigot.optimizations.SectionTickList; + +public class ChunkSection { + + boolean isDirty; // PaperSpigot + private int yPos; + private int nonEmptyBlockCount; + private int tickingBlockCount; + private char[] blockIds; + private int[] blockDurabilities; + private NibbleArray emittedLight; + private NibbleArray skyLight; + private final SectionTickList tickList; // Beanes - optimized random ticking + + public ChunkSection(int i, boolean flag) { + this(i, flag, true); + } + + public ChunkSection(int i, boolean flag, boolean hasRandomTicking) { + this.yPos = i; + this.blockIds = new char[4096]; + if (AzuriteConfig.explosionDestroyer.getValue()) + this.blockDurabilities = new int[4096]; + this.emittedLight = new NibbleArray(); + if (flag) { + this.skyLight = new NibbleArray(); + } + + if (hasRandomTicking) { + this.tickList = new SectionTickList(); + } else { + this.tickList = null; + } + } + + public ChunkSection(int y, boolean flag, char[] blockIds) { + this(y, flag, blockIds, true); + } + + // CraftBukkit start + public ChunkSection(int y, boolean flag, char[] blockIds, boolean hasRandomTicking) { + this.yPos = y; + this.blockIds = blockIds; + if (AzuriteConfig.explosionDestroyer.getValue()) + this.blockDurabilities = new int[4096]; + this.emittedLight = new NibbleArray(); + if (flag) { + this.skyLight = new NibbleArray(); + } + + if (hasRandomTicking) { + this.tickList = new SectionTickList(); + } else { + this.tickList = null; + } + recalcBlockCounts(); + } + // CraftBukkit end + + // Azurite - fetch block id + public char getBlockId(int id) { + return blockIds[id]; + } + + public IBlockData getType(int x, int y, int z) { + IBlockData iblockdata = Block.d.a(blockIds[y << 8 | z << 4 | x]); + return iblockdata != null ? iblockdata : Blocks.AIR.getBlockData(); + } + + public IBlockData getType(int id) { + IBlockData iblockdata = Block.d.a(blockIds[id]); + return iblockdata != null ? iblockdata : Blocks.AIR.getBlockData(); + } + + public void setType(int x, int y, int z, IBlockData iblockdata) { + IBlockData iblockdata1 = getType(x, y, z); + Block block = iblockdata1.getBlock(); + Block block1 = iblockdata.getBlock(); + int id = y << 8 | z << 4 | x; + + if (block != Blocks.AIR) { + --nonEmptyBlockCount; + if (block.isTicking()) { + --tickingBlockCount; + if (tickList != null) { + tickList.remove((short) id); + } + } + if (block.explosionDurability > 0) { + blockDurabilities[id] = 0; + } + } + + if (block1 != Blocks.AIR) { + ++nonEmptyBlockCount; + if (block1.isTicking()) { + ++tickingBlockCount; + if (tickList != null) { + tickList.add((short) id); + } + } + if (block1.explosionDurability > 0) { + blockDurabilities[id] = block1.explosionDurability; + } + } + + blockIds[id] = (char) Block.d.b(iblockdata); + isDirty = true; // PaperSpigot + } + + public void setBlockDurability(int i, int j, int k, int durability) { + blockDurabilities[j << 8 | k << 4 | i] = durability; + } + + public int getBlockDurability(int i, int j, int k) { + int id = j << 8 | k << 4 | i; + int durability = blockDurabilities[id]; + if (durability == 0) { + int explosionDurability = getType(i, j, k).getBlock().explosionDurability; + if (explosionDurability > 0) { + blockDurabilities[id] = explosionDurability; + return explosionDurability; + } else { + return -1; + } + } + return durability; + } + + public Block b(int i, int j, int k) { + return this.getType(i, j, k).getBlock(); + } + + public int c(int i, int j, int k) { + IBlockData iblockdata = this.getType(i, j, k); + + return iblockdata.getBlock().toLegacyData(iblockdata); + } + + public boolean a() { + return this.nonEmptyBlockCount == 0; + } + + public boolean shouldTick() { + return this.tickingBlockCount > 0; + } + + public int getTickingBlockCount() { + return this.tickingBlockCount; + } + + public int getYPosition() { + return this.yPos; + } + + public void a(int i, int j, int k, int l) { + this.skyLight.a(i, j, k, l); + isDirty = true; // PaperSpigot + } + + public int d(int i, int j, int k) { + return this.skyLight.a(i, j, k); + } + + public void b(int i, int j, int k, int l) { + this.emittedLight.a(i, j, k, l); + isDirty = true; // PaperSpigot + } + + public int e(int i, int j, int k) { + return this.emittedLight.a(i, j, k); + } + + public void recalcBlockCounts() { + this.nonEmptyBlockCount = 0; + this.tickingBlockCount = 0; + if (tickList != null) { + tickList.clear(); + } + + for (int i = 0; i < 16; ++i) { + for (int j = 0; j < 16; ++j) { + for (int k = 0; k < 16; ++k) { + int loc = j << 8 | k << 4 | i; + Block block = getType(loc).getBlock(); + + if (block != Blocks.AIR) { + ++nonEmptyBlockCount; + if (block.isTicking()) { + ++tickingBlockCount; + if (tickList != null) { + tickList.add((short) loc); + } + } + if (block.explosionDurability > 0) { + blockDurabilities[loc] = block.explosionDurability; + } + } + } + } + } + } + + public char[] getIdArray() { + return this.blockIds; + } + + public void a(char[] achar) { + this.blockIds = achar; + } + + public NibbleArray getEmittedLightArray() { + return this.emittedLight; + } + + public NibbleArray getSkyLightArray() { + return this.skyLight; + } + + public void a(NibbleArray nibblearray) { + this.emittedLight = nibblearray; + } + + public void b(NibbleArray nibblearray) { + this.skyLight = nibblearray; + } + + private char[] clone(char[] chars) { + if (chars != null) + return chars.clone(); + return null; + } + + private NibbleArray clone(NibbleArray array) { + if (array != null) + return array.clone(); + return null; + } + + public ChunkSectionSnapshot createSnapshot() { + return new ChunkSectionSnapshot( + yPos, + nonEmptyBlockCount, + tickingBlockCount, + clone(blockIds), + clone(emittedLight), + clone(skyLight), + isDirty); + } + + public void restoreSnapshot(ChunkSectionSnapshot snap) { + yPos = snap.getYPos(); + nonEmptyBlockCount = snap.getNonEmptyBlockCount(); + tickingBlockCount = snap.getTickingBlockCount(); + blockIds = clone(snap.getBlockIds()); + emittedLight = clone(snap.getEmittedLight()); + skyLight = clone(snap.getSkyLight()); + isDirty = snap.isDirty(); + } + + public SectionTickList getTickList() { + return tickList; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ChunkSnapshot.java b/azurite-server/src/main/java/net/minecraft/server/ChunkSnapshot.java new file mode 100644 index 0000000..4ce9e5d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ChunkSnapshot.java @@ -0,0 +1,41 @@ +package net.minecraft.server; + +public class ChunkSnapshot { + + private final short[] a = new short[65536]; + private final IBlockData b; + + public ChunkSnapshot() { + this.b = Blocks.AIR.getBlockData(); + } + + public IBlockData a(int i, int j, int k) { + int l = i << 12 | k << 8 | j; + + return this.a(l); + } + + public IBlockData a(int i) { + if (i >= 0 && i < this.a.length) { + IBlockData iblockdata = (IBlockData) Block.d.a(this.a[i]); + + return iblockdata != null ? iblockdata : this.b; + } else { + throw new IndexOutOfBoundsException("The coordinate is out of range"); + } + } + + public void a(int i, int j, int k, IBlockData iblockdata) { + int l = i << 12 | k << 8 | j; + + this.a(l, iblockdata); + } + + public void a(int i, IBlockData iblockdata) { + if (i >= 0 && i < this.a.length) { + this.a[i] = (short) Block.d.b(iblockdata); + } else { + throw new IndexOutOfBoundsException("The coordinate is out of range"); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CombatEntry.java b/azurite-server/src/main/java/net/minecraft/server/CombatEntry.java new file mode 100644 index 0000000..a0a1d98 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CombatEntry.java @@ -0,0 +1,44 @@ +package net.minecraft.server; + +public class CombatEntry { + + private final DamageSource a; + private final int b; + private final float c; + private final float d; + private final String e; + private final float f; + + public CombatEntry(DamageSource damagesource, int i, float f, float f1, String s, float f2) { + this.a = damagesource; + this.b = i; + this.c = f1; + this.d = f; + this.e = s; + this.f = f2; + } + + public DamageSource a() { + return this.a; + } + + public float c() { + return this.c; + } + + public boolean f() { + return this.a.getEntity() instanceof EntityLiving; + } + + public String g() { + return this.e; + } + + public IChatBaseComponent h() { + return this.a().getEntity() == null ? null : this.a().getEntity().getScoreboardDisplayName(); + } + + public float i() { + return this.a == DamageSource.OUT_OF_WORLD ? Float.MAX_VALUE : this.f; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CombatTracker.java b/azurite-server/src/main/java/net/minecraft/server/CombatTracker.java new file mode 100644 index 0000000..b824e45 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CombatTracker.java @@ -0,0 +1,189 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; + +import java.util.Iterator; +import java.util.List; + +public class CombatTracker { + private final List a = Lists.newArrayList(); + private final EntityLiving b; + private int c; + private int d; + private int e; + private boolean f; + private boolean g; + private String h; + + public CombatTracker(EntityLiving var1) { + this.b = var1; + } + + public void a() { + j(); + if (b.k_()) { + Block var1 = b.world.getType(MathHelper.floor(b.locX), MathHelper.floor(b.getBoundingBox().b), MathHelper.floor(b.locZ)).getBlock(); + if (var1 == Blocks.LADDER) { + h = "ladder"; + } else if (var1 == Blocks.VINE) { + h = "vines"; + } + } else if (b.V()) { + h = "water"; + } + } + + public void a(DamageSource var1, float var2, float var3) { + this.g(); + this.a(); + CombatEntry var4 = new CombatEntry(var1, this.b.ticksLived, var2, var3, this.h, this.b.fallDistance); + this.a.add(var4); + this.c = this.b.ticksLived; + this.g = true; + if (var4.f() && !this.f && this.b.isAlive()) { + this.f = true; + this.d = this.b.ticksLived; + this.e = this.d; + this.b.enterCombat(); + } + + } + + public IChatBaseComponent b() { + if (this.a.isEmpty()) { + return new ChatMessage("death.attack.generic", this.b.getScoreboardDisplayName()); + } else { + CombatEntry var1 = this.i(); + CombatEntry var2 = this.a.get(this.a.size() - 1); + IChatBaseComponent var4 = var2.h(); + Entity var5 = var2.a().getEntity(); + IChatBaseComponent var3; + if (var1 != null && var2.a() == DamageSource.FALL) { + IChatBaseComponent var6 = var1.h(); + if (var1.a() != DamageSource.FALL && var1.a() != DamageSource.OUT_OF_WORLD) { + if (var6 == null || var6.equals(var4)) { + if (var4 != null) { + ItemStack var9 = var5 instanceof EntityLiving ? ((EntityLiving) var5).bA() : null; + if (var9 != null && var9.hasName()) { + var3 = new ChatMessage("death.fell.finish.item", this.b.getScoreboardDisplayName(), var4, var9.C()); + } else { + var3 = new ChatMessage("death.fell.finish", this.b.getScoreboardDisplayName(), var4); + } + } else { + var3 = new ChatMessage("death.fell.killer", this.b.getScoreboardDisplayName()); + } + } else { + Entity var7 = var1.a().getEntity(); + ItemStack var8 = var7 instanceof EntityLiving ? ((EntityLiving) var7).bA() : null; + if (var8 != null && var8.hasName()) { + var3 = new ChatMessage("death.fell.assist.item", this.b.getScoreboardDisplayName(), var6, var8.C()); + } else { + var3 = new ChatMessage("death.fell.assist", this.b.getScoreboardDisplayName(), var6); + } + } + } else { + var3 = new ChatMessage("death.fell.accident." + this.a(var1), this.b.getScoreboardDisplayName()); + } + } else { + var3 = var2.a().getLocalizedDeathMessage(this.b); + } + + return var3; + } + } + + public EntityLiving c() { + EntityLiving var1 = null; + EntityHuman var2 = null; + float var3 = 0.0F; + float var4 = 0.0F; + Iterator var5 = this.a.iterator(); + + while (true) { + CombatEntry var6; + do { + do { + if (!var5.hasNext()) { + if (var2 != null && var4 >= var3 / 3.0F) { + return var2; + } + + return var1; + } + + var6 = var5.next(); + if (var6.a().getEntity() instanceof EntityHuman && (var2 == null || var6.c() > var4)) { + var4 = var6.c(); + var2 = (EntityHuman) var6.a().getEntity(); + } + } while (!(var6.a().getEntity() instanceof EntityLiving)); + } while (var1 != null && !(var6.c() > var3)); + + var3 = var6.c(); + var1 = (EntityLiving) var6.a().getEntity(); + } + } + + private CombatEntry i() { + CombatEntry var1 = null; + CombatEntry var2 = null; + byte var3 = 0; + float var4 = 0.0F; + + for (int var5 = 0; var5 < this.a.size(); ++var5) { + CombatEntry var6 = this.a.get(var5); + CombatEntry var7 = var5 > 0 ? this.a.get(var5 - 1) : null; + if ((var6.a() == DamageSource.FALL || var6.a() == DamageSource.OUT_OF_WORLD) && var6.i() > 0.0F && (var1 == null || var6.i() > var4)) { + if (var5 > 0) { + var1 = var7; + } else { + var1 = var6; + } + + var4 = var6.i(); + } + + if (var6.g() != null && (var2 == null || var6.c() > (float) var3)) { + var2 = var6; + } + } + + if (var4 > 5.0F && var1 != null) { + return var1; + } else { + return null; + } + } + + private String a(CombatEntry var1) { + return var1.g() == null ? "generic" : var1.g(); + } + + public int f() { + return f ? b.ticksLived - d : e - d; + } + + private void j() { + h = null; + } + + public void g() { + int var1 = f ? 300 : 100; + if (g && (!b.isAlive() || b.ticksLived - c > var1)) { + boolean var2 = f; + g = false; + f = false; + e = b.ticksLived; + if (var2) { + this.b.exitCombat(); + } + + a.clear(); + } + + } + + public EntityLiving h() { + return this.b; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandAbstract.java b/azurite-server/src/main/java/net/minecraft/server/CommandAbstract.java new file mode 100644 index 0000000..d38e0d8 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandAbstract.java @@ -0,0 +1,553 @@ +package net.minecraft.server; + +import com.eatthepath.uuid.FastUUID; +import com.google.common.base.Functions; +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; +import com.google.common.primitives.Doubles; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.UUID; + +public abstract class CommandAbstract implements ICommand { + + private static ICommandDispatcher a; + + public CommandAbstract() {} + + public int a() { + return 4; + } + + public List b() { + return Collections.emptyList(); + } + + public boolean canUse(ICommandListener icommandlistener) { + return icommandlistener.a(this.a(), this.getCommand()); + } + + public List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { + return null; + } + + public static int a(String s) throws ExceptionInvalidNumber { + try { + return Integer.parseInt(s); + } catch (NumberFormatException numberformatexception) { + throw new ExceptionInvalidNumber("commands.generic.num.invalid", new Object[] { s}); + } + } + + public static int a(String s, int i) throws ExceptionInvalidNumber { + return a(s, i, Integer.MAX_VALUE); + } + + public static int a(String s, int i, int j) throws ExceptionInvalidNumber { + int k = a(s); + + if (k < i) { + throw new ExceptionInvalidNumber("commands.generic.num.tooSmall", new Object[] { Integer.valueOf(k), Integer.valueOf(i)}); + } else if (k > j) { + throw new ExceptionInvalidNumber("commands.generic.num.tooBig", new Object[] { Integer.valueOf(k), Integer.valueOf(j)}); + } else { + return k; + } + } + + public static long b(String s) throws ExceptionInvalidNumber { + try { + return Long.parseLong(s); + } catch (NumberFormatException numberformatexception) { + throw new ExceptionInvalidNumber("commands.generic.num.invalid", new Object[] { s}); + } + } + + public static long a(String s, long i, long j) throws ExceptionInvalidNumber { + long k = b(s); + + if (k < i) { + throw new ExceptionInvalidNumber("commands.generic.num.tooSmall", new Object[] { Long.valueOf(k), Long.valueOf(i)}); + } else if (k > j) { + throw new ExceptionInvalidNumber("commands.generic.num.tooBig", new Object[] { Long.valueOf(k), Long.valueOf(j)}); + } else { + return k; + } + } + + public static BlockPosition a(ICommandListener icommandlistener, String[] astring, int i, boolean flag) throws ExceptionInvalidNumber { + BlockPosition blockposition = icommandlistener.getChunkCoordinates(); + + return new BlockPosition(b((double) blockposition.getX(), astring[i], -30000000, 30000000, flag), b((double) blockposition.getY(), astring[i + 1], 0, 256, false), b((double) blockposition.getZ(), astring[i + 2], -30000000, 30000000, flag)); + } + + public static double c(String s) throws ExceptionInvalidNumber { + try { + double d0 = Double.parseDouble(s); + + if (!Doubles.isFinite(d0)) { + throw new ExceptionInvalidNumber("commands.generic.num.invalid", new Object[] { s}); + } else { + return d0; + } + } catch (NumberFormatException numberformatexception) { + throw new ExceptionInvalidNumber("commands.generic.num.invalid", new Object[] { s}); + } + } + + public static double a(String s, double d0) throws ExceptionInvalidNumber { + return a(s, d0, Double.MAX_VALUE); + } + + public static double a(String s, double d0, double d1) throws ExceptionInvalidNumber { + double d2 = c(s); + + if (d2 < d0) { + throw new ExceptionInvalidNumber("commands.generic.double.tooSmall", new Object[] { Double.valueOf(d2), Double.valueOf(d0)}); + } else if (d2 > d1) { + throw new ExceptionInvalidNumber("commands.generic.double.tooBig", new Object[] { Double.valueOf(d2), Double.valueOf(d1)}); + } else { + return d2; + } + } + + public static boolean d(String s) throws CommandException { + if (!s.equals("true") && !s.equals("1")) { + if (!s.equals("false") && !s.equals("0")) { + throw new CommandException("commands.generic.boolean.invalid", new Object[] { s}); + } else { + return false; + } + } else { + return true; + } + } + + public static EntityPlayer b(ICommandListener icommandlistener) throws ExceptionPlayerNotFound { + if (icommandlistener instanceof EntityPlayer) { + return (EntityPlayer) icommandlistener; + } else { + throw new ExceptionPlayerNotFound("You must specify which player you wish to perform this action on.", new Object[0]); + } + } + + public static EntityPlayer a(ICommandListener icommandlistener, String s) throws ExceptionPlayerNotFound { + EntityPlayer entityplayer = PlayerSelector.getPlayer(icommandlistener, s); + + if (entityplayer == null) { + try { + entityplayer = MinecraftServer.getServer().getPlayerList().a(FastUUID.parseUUID(s)); + } catch (IllegalArgumentException illegalargumentexception) { + ; + } + } + + if (entityplayer == null) { + entityplayer = MinecraftServer.getServer().getPlayerList().getPlayer(s); + } + + if (entityplayer == null) { + throw new ExceptionPlayerNotFound(); + } else { + return entityplayer; + } + } + + public static Entity b(ICommandListener icommandlistener, String s) throws ExceptionEntityNotFound { + return a(icommandlistener, s, Entity.class); + } + + public static T a(ICommandListener icommandlistener, String s, Class oclass) throws ExceptionEntityNotFound { + Entity object = PlayerSelector.getEntity(icommandlistener, s, oclass); + MinecraftServer minecraftserver = MinecraftServer.getServer(); + + if (object == null) { + object = minecraftserver.getPlayerList().getPlayer(s); + } + + if (object == null) { + try { + UUID uuid = FastUUID.parseUUID(s); + + object = minecraftserver.a(uuid); + if (object == null) { + object = minecraftserver.getPlayerList().a(uuid); + } + } catch (IllegalArgumentException illegalargumentexception) { + throw new ExceptionEntityNotFound("commands.generic.entity.invalidUuid", new Object[0]); + } + } + + if (object != null && oclass.isAssignableFrom(object.getClass())) { + return (T) object; + } else { + throw new ExceptionEntityNotFound(); + } + } + + public static List c(ICommandListener icommandlistener, String s) throws ExceptionEntityNotFound { + return (List) (PlayerSelector.isPattern(s) ? PlayerSelector.getPlayers(icommandlistener, s, Entity.class) : Lists.newArrayList(new Entity[] { b(icommandlistener, s)})); + } + + public static String d(ICommandListener icommandlistener, String s) throws ExceptionPlayerNotFound { + try { + return a(icommandlistener, s).getName(); + } catch (ExceptionPlayerNotFound exceptionplayernotfound) { + if (PlayerSelector.isPattern(s)) { + throw exceptionplayernotfound; + } else { + return s; + } + } + } + + public static String e(ICommandListener icommandlistener, String s) throws ExceptionEntityNotFound { + try { + return a(icommandlistener, s).getName(); + } catch (ExceptionPlayerNotFound exceptionplayernotfound) { + try { + return b(icommandlistener, s).getUniqueID().toString(); + } catch (ExceptionEntityNotFound exceptionentitynotfound) { + if (PlayerSelector.isPattern(s)) { + throw exceptionentitynotfound; + } else { + return s; + } + } + } + } + + public static IChatBaseComponent a(ICommandListener icommandlistener, String[] astring, int i) throws ExceptionPlayerNotFound { + return b(icommandlistener, astring, i, false); + } + + public static IChatBaseComponent b(ICommandListener icommandlistener, String[] astring, int i, boolean flag) throws ExceptionPlayerNotFound { + ChatComponentText chatcomponenttext = new ChatComponentText(""); + + for (int j = i; j < astring.length; ++j) { + if (j > i) { + chatcomponenttext.a(" "); + } + + Object object = new ChatComponentText(astring[j]); + + if (flag) { + IChatBaseComponent ichatbasecomponent = PlayerSelector.getPlayerNames(icommandlistener, astring[j]); + + if (ichatbasecomponent == null) { + if (PlayerSelector.isPattern(astring[j])) { + throw new ExceptionPlayerNotFound(); + } + } else { + object = ichatbasecomponent; + } + } + + chatcomponenttext.addSibling((IChatBaseComponent) object); + } + + return chatcomponenttext; + } + + public static String a(String[] astring, int i) { + StringBuilder stringbuilder = new StringBuilder(); + + for (int j = i; j < astring.length; ++j) { + if (j > i) { + stringbuilder.append(" "); + } + + String s = astring[j]; + + stringbuilder.append(s); + } + + return stringbuilder.toString(); + } + + public static CommandAbstract.CommandNumber a(double d0, String s, boolean flag) throws ExceptionInvalidNumber { + return a(d0, s, -30000000, 30000000, flag); + } + + public static CommandAbstract.CommandNumber a(double d0, String s, int i, int j, boolean flag) throws ExceptionInvalidNumber { + boolean flag1 = s.startsWith("~"); + + if (flag1 && Double.isNaN(d0)) { + throw new ExceptionInvalidNumber("commands.generic.num.invalid", new Object[] { Double.valueOf(d0)}); + } else { + double d1 = 0.0D; + + if (!flag1 || s.length() > 1) { + boolean flag2 = s.contains("."); + + if (flag1) { + s = s.substring(1); + } + + d1 += c(s); + if (!flag2 && !flag1 && flag) { + d1 += 0.5D; + } + } + + if (i != 0 || j != 0) { + if (d1 < (double) i) { + throw new ExceptionInvalidNumber("commands.generic.double.tooSmall", new Object[] { Double.valueOf(d1), Integer.valueOf(i)}); + } + + if (d1 > (double) j) { + throw new ExceptionInvalidNumber("commands.generic.double.tooBig", new Object[] { Double.valueOf(d1), Integer.valueOf(j)}); + } + } + + return new CommandAbstract.CommandNumber(d1 + (flag1 ? d0 : 0.0D), d1, flag1); + } + } + + public static double b(double d0, String s, boolean flag) throws ExceptionInvalidNumber { + return b(d0, s, -30000000, 30000000, flag); + } + + public static double b(double d0, String s, int i, int j, boolean flag) throws ExceptionInvalidNumber { + boolean flag1 = s.startsWith("~"); + + if (flag1 && Double.isNaN(d0)) { + throw new ExceptionInvalidNumber("commands.generic.num.invalid", new Object[] { Double.valueOf(d0)}); + } else { + double d1 = flag1 ? d0 : 0.0D; + + if (!flag1 || s.length() > 1) { + boolean flag2 = s.contains("."); + + if (flag1) { + s = s.substring(1); + } + + d1 += c(s); + if (!flag2 && !flag1 && flag) { + d1 += 0.5D; + } + } + + if (i != 0 || j != 0) { + if (d1 < (double) i) { + throw new ExceptionInvalidNumber("commands.generic.double.tooSmall", new Object[] { Double.valueOf(d1), Integer.valueOf(i)}); + } + + if (d1 > (double) j) { + throw new ExceptionInvalidNumber("commands.generic.double.tooBig", new Object[] { Double.valueOf(d1), Integer.valueOf(j)}); + } + } + + return d1; + } + } + + public static Item f(ICommandListener icommandlistener, String s) throws ExceptionInvalidNumber { + MinecraftKey minecraftkey = new MinecraftKey(s); + Item item = (Item) Item.REGISTRY.get(minecraftkey); + + if (item == null) { + throw new ExceptionInvalidNumber("commands.give.item.notFound", new Object[] { minecraftkey}); + } else { + return item; + } + } + + public static Block g(ICommandListener icommandlistener, String s) throws ExceptionInvalidNumber { + MinecraftKey minecraftkey = new MinecraftKey(s); + + if (!Block.REGISTRY.d(minecraftkey)) { + throw new ExceptionInvalidNumber("commands.give.block.notFound", new Object[] { minecraftkey}); + } else { + Block block = (Block) Block.REGISTRY.get(minecraftkey); + + if (block == null) { + throw new ExceptionInvalidNumber("commands.give.block.notFound", new Object[] { minecraftkey}); + } else { + return block; + } + } + } + + public static String a(Object[] aobject) { + StringBuilder stringbuilder = new StringBuilder(); + + for (int i = 0; i < aobject.length; ++i) { + String s = aobject[i].toString(); + + if (i > 0) { + if (i == aobject.length - 1) { + stringbuilder.append(" and "); + } else { + stringbuilder.append(", "); + } + } + + stringbuilder.append(s); + } + + return stringbuilder.toString(); + } + + public static IChatBaseComponent a(List list) { + ChatComponentText chatcomponenttext = new ChatComponentText(""); + + for (int i = 0; i < list.size(); ++i) { + if (i > 0) { + if (i == list.size() - 1) { + chatcomponenttext.a(" and "); + } else if (i > 0) { + chatcomponenttext.a(", "); + } + } + + chatcomponenttext.addSibling((IChatBaseComponent) list.get(i)); + } + + return chatcomponenttext; + } + + public static String a(Collection collection) { + return a(collection.toArray(new String[collection.size()])); + } + + public static List a(String[] astring, int i, BlockPosition blockposition) { + if (blockposition == null) { + return null; + } else { + int j = astring.length - 1; + String s; + + if (j == i) { + s = Integer.toString(blockposition.getX()); + } else if (j == i + 1) { + s = Integer.toString(blockposition.getY()); + } else { + if (j != i + 2) { + return null; + } + + s = Integer.toString(blockposition.getZ()); + } + + return Lists.newArrayList(new String[] { s}); + } + } + + public static List b(String[] astring, int i, BlockPosition blockposition) { + if (blockposition == null) { + return null; + } else { + int j = astring.length - 1; + String s; + + if (j == i) { + s = Integer.toString(blockposition.getX()); + } else { + if (j != i + 1) { + return null; + } + + s = Integer.toString(blockposition.getZ()); + } + + return Lists.newArrayList(new String[] { s}); + } + } + + public static boolean a(String s, String s1) { + return s1.regionMatches(true, 0, s, 0, s.length()); + } + + public static List a(String[] astring, String... astring1) { + return a(astring, (Collection) Arrays.asList(astring1)); + } + + public static List a(String[] astring, Collection collection) { + String s = astring[astring.length - 1]; + ArrayList arraylist = Lists.newArrayList(); + + if (!collection.isEmpty()) { + Iterator iterator = Iterables.transform(collection, Functions.toStringFunction()).iterator(); + + while (iterator.hasNext()) { + String s1 = (String) iterator.next(); + + if (a(s, s1)) { + arraylist.add(s1); + } + } + + if (arraylist.isEmpty()) { + iterator = collection.iterator(); + + while (iterator.hasNext()) { + Object object = iterator.next(); + + if (object instanceof MinecraftKey && a(s, ((MinecraftKey) object).a())) { + arraylist.add(String.valueOf(object)); + } + } + } + } + + return arraylist; + } + + public boolean isListStart(String[] astring, int i) { + return false; + } + + public static void a(ICommandListener icommandlistener, ICommand icommand, String s, Object... aobject) { + a(icommandlistener, icommand, 0, s, aobject); + } + + public static void a(ICommandListener icommandlistener, ICommand icommand, int i, String s, Object... aobject) { + if (CommandAbstract.a != null) { + CommandAbstract.a.a(icommandlistener, icommand, i, s, aobject); + } + + } + + public static void a(ICommandDispatcher icommanddispatcher) { + CommandAbstract.a = icommanddispatcher; + } + + public int a(ICommand icommand) { + return this.getCommand().compareTo(icommand.getCommand()); + } + + public int compareTo(ICommand object) { + return this.a(object); + } + + public static class CommandNumber { + + private final double a; + private final double b; + private final boolean c; + + protected CommandNumber(double d0, double d1, boolean flag) { + this.a = d0; + this.b = d1; + this.c = flag; + } + + public double a() { + return this.a; + } + + public double b() { + return this.b; + } + + public boolean c() { + return this.c; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandAchievement.java b/azurite-server/src/main/java/net/minecraft/server/CommandAchievement.java new file mode 100644 index 0000000..c668da5 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandAchievement.java @@ -0,0 +1,169 @@ +package net.minecraft.server; + +import com.google.common.base.Predicate; +import com.google.common.collect.Iterators; +import com.google.common.collect.Lists; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; + +public class CommandAchievement extends CommandAbstract { + + public CommandAchievement() {} + + public String getCommand() { + return "achievement"; + } + + public int a() { + return 2; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.achievement.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + if (astring.length < 2) { + throw new ExceptionUsage("commands.achievement.usage", new Object[0]); + } else { + final Statistic statistic = StatisticList.getStatistic(astring[1]); + + if (statistic == null && !astring[1].equals("*")) { + throw new CommandException("commands.achievement.unknownAchievement", new Object[] { astring[1]}); + } else { + final EntityPlayer entityplayer = astring.length >= 3 ? a(icommandlistener, astring[2]) : b(icommandlistener); + boolean flag = astring[0].equalsIgnoreCase("give"); + boolean flag1 = astring[0].equalsIgnoreCase("take"); + + if (flag || flag1) { + if (statistic == null) { + Iterator iterator; + Achievement achievement; + + if (flag) { + iterator = AchievementList.e.iterator(); + + while (iterator.hasNext()) { + achievement = (Achievement) iterator.next(); + entityplayer.b((Statistic) achievement); + } + + a(icommandlistener, this, "commands.achievement.give.success.all", new Object[] { entityplayer.getName()}); + } else if (flag1) { + iterator = Lists.reverse(AchievementList.e).iterator(); + + while (iterator.hasNext()) { + achievement = (Achievement) iterator.next(); + entityplayer.a((Statistic) achievement); + } + + a(icommandlistener, this, "commands.achievement.take.success.all", new Object[] { entityplayer.getName()}); + } + + } else { + if (statistic instanceof Achievement) { + Achievement achievement1 = (Achievement) statistic; + ArrayList arraylist; + + if (flag) { + if (entityplayer.getStatisticManager().hasAchievement(achievement1)) { + throw new CommandException("commands.achievement.alreadyHave", new Object[] { entityplayer.getName(), statistic.j()}); + } + + for (arraylist = Lists.newArrayList(); achievement1.c != null && !entityplayer.getStatisticManager().hasAchievement(achievement1.c); achievement1 = achievement1.c) { + arraylist.add(achievement1.c); + } + + Iterator iterator1 = Lists.reverse(arraylist).iterator(); + + while (iterator1.hasNext()) { + Achievement achievement2 = (Achievement) iterator1.next(); + + entityplayer.b((Statistic) achievement2); + } + } else if (flag1) { + if (!entityplayer.getStatisticManager().hasAchievement(achievement1)) { + throw new CommandException("commands.achievement.dontHave", new Object[] { entityplayer.getName(), statistic.j()}); + } + + arraylist = Lists.newArrayList(Iterators.filter(AchievementList.e.iterator(), new Predicate() { + public boolean a(Achievement achievement) { + return entityplayer.getStatisticManager().hasAchievement(achievement) && achievement != statistic; + } + + public boolean apply(Object object) { + return this.a((Achievement) object); + } + })); + ArrayList arraylist1 = Lists.newArrayList(arraylist); + Iterator iterator2 = arraylist.iterator(); + + Achievement achievement3; + + while (iterator2.hasNext()) { + achievement3 = (Achievement) iterator2.next(); + Achievement achievement4 = achievement3; + + boolean flag2; + + for (flag2 = false; achievement4 != null; achievement4 = achievement4.c) { + if (achievement4 == statistic) { + flag2 = true; + } + } + + if (!flag2) { + for (achievement4 = achievement3; achievement4 != null; achievement4 = achievement4.c) { + arraylist1.remove(achievement3); + } + } + } + + iterator2 = arraylist1.iterator(); + + while (iterator2.hasNext()) { + achievement3 = (Achievement) iterator2.next(); + entityplayer.a((Statistic) achievement3); + } + } + } + + if (flag) { + entityplayer.b(statistic); + a(icommandlistener, this, "commands.achievement.give.success.one", new Object[] { entityplayer.getName(), statistic.j()}); + } else if (flag1) { + entityplayer.a(statistic); + a(icommandlistener, this, "commands.achievement.take.success.one", new Object[] { statistic.j(), entityplayer.getName()}); + } + + } + } + } + } + } + + public List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { + if (astring.length == 1) { + return a(astring, new String[] { "give", "take"}); + } else if (astring.length != 2) { + return astring.length == 3 ? a(astring, MinecraftServer.getServer().getPlayers()) : null; + } else { + ArrayList arraylist = Lists.newArrayList(); + Iterator iterator = StatisticList.stats.iterator(); + + while (iterator.hasNext()) { + Statistic statistic = (Statistic) iterator.next(); + + arraylist.add(statistic.name); + } + + return a(astring, (Collection) arraylist); + } + } + + public boolean isListStart(String[] astring, int i) { + return i == 2; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandBan.java b/azurite-server/src/main/java/net/minecraft/server/CommandBan.java new file mode 100644 index 0000000..83d1d9f --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandBan.java @@ -0,0 +1,60 @@ +package net.minecraft.server; + +import com.mojang.authlib.GameProfile; +import java.util.Date; +import java.util.List; + +public class CommandBan extends CommandAbstract { + + public CommandBan() {} + + public String getCommand() { + return "ban"; + } + + public int a() { + return 3; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.ban.usage"; + } + + public boolean canUse(ICommandListener icommandlistener) { + return MinecraftServer.getServer().getPlayerList().getProfileBans().isEnabled() && super.canUse(icommandlistener); + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + if (astring.length >= 1 && astring[0].length() > 0) { + MinecraftServer minecraftserver = MinecraftServer.getServer(); + GameProfile gameprofile = minecraftserver.getUserCache().getProfile(astring[0]); + + if (gameprofile == null) { + throw new CommandException("commands.ban.failed", new Object[] { astring[0]}); + } else { + String s = null; + + if (astring.length >= 2) { + s = a(icommandlistener, astring, 1).c(); + } + + GameProfileBanEntry gameprofilebanentry = new GameProfileBanEntry(gameprofile, (Date) null, icommandlistener.getName(), (Date) null, s); + + minecraftserver.getPlayerList().getProfileBans().add(gameprofilebanentry); + EntityPlayer entityplayer = minecraftserver.getPlayerList().getPlayer(astring[0]); + + if (entityplayer != null) { + entityplayer.playerConnection.disconnect("You are banned from this server."); + } + + a(icommandlistener, this, "commands.ban.success", new Object[] { astring[0]}); + } + } else { + throw new ExceptionUsage("commands.ban.usage", new Object[0]); + } + } + + public List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { + return astring.length >= 1 ? a(astring, MinecraftServer.getServer().getPlayers()) : null; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandBanIp.java b/azurite-server/src/main/java/net/minecraft/server/CommandBanIp.java new file mode 100644 index 0000000..8042f01 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandBanIp.java @@ -0,0 +1,79 @@ +package net.minecraft.server; + +import java.util.Date; +import java.util.Iterator; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class CommandBanIp extends CommandAbstract { + + public static final Pattern a = Pattern.compile("^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"); + + public CommandBanIp() {} + + public String getCommand() { + return "ban-ip"; + } + + public int a() { + return 3; + } + + public boolean canUse(ICommandListener icommandlistener) { + return MinecraftServer.getServer().getPlayerList().getIPBans().isEnabled() && super.canUse(icommandlistener); + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.banip.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + if (astring.length >= 1 && astring[0].length() > 1) { + IChatBaseComponent ichatbasecomponent = astring.length >= 2 ? a(icommandlistener, astring, 1) : null; + Matcher matcher = CommandBanIp.a.matcher(astring[0]); + + if (matcher.matches()) { + this.a(icommandlistener, astring[0], ichatbasecomponent == null ? null : ichatbasecomponent.c()); + } else { + EntityPlayer entityplayer = MinecraftServer.getServer().getPlayerList().getPlayer(astring[0]); + + if (entityplayer == null) { + throw new ExceptionPlayerNotFound("commands.banip.invalid", new Object[0]); + } + + this.a(icommandlistener, entityplayer.w(), ichatbasecomponent == null ? null : ichatbasecomponent.c()); + } + + } else { + throw new ExceptionUsage("commands.banip.usage", new Object[0]); + } + } + + public List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { + return astring.length == 1 ? a(astring, MinecraftServer.getServer().getPlayers()) : null; + } + + protected void a(ICommandListener icommandlistener, String s, String s1) { + IpBanEntry ipbanentry = new IpBanEntry(s, (Date) null, icommandlistener.getName(), (Date) null, s1); + + MinecraftServer.getServer().getPlayerList().getIPBans().add(ipbanentry); + List list = MinecraftServer.getServer().getPlayerList().b(s); + String[] astring = new String[list.size()]; + int i = 0; + + EntityPlayer entityplayer; + + for (Iterator iterator = list.iterator(); iterator.hasNext(); astring[i++] = entityplayer.getName()) { + entityplayer = (EntityPlayer) iterator.next(); + entityplayer.playerConnection.disconnect("You have been IP banned."); + } + + if (list.isEmpty()) { + a(icommandlistener, this, "commands.banip.success", new Object[] { s}); + } else { + a(icommandlistener, this, "commands.banip.success.players", new Object[] { s, a((Object[]) astring)}); + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandBanList.java b/azurite-server/src/main/java/net/minecraft/server/CommandBanList.java new file mode 100644 index 0000000..eacc3d4 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandBanList.java @@ -0,0 +1,39 @@ +package net.minecraft.server; + +import java.util.List; + +public class CommandBanList extends CommandAbstract { + + public CommandBanList() {} + + public String getCommand() { + return "banlist"; + } + + public int a() { + return 3; + } + + public boolean canUse(ICommandListener icommandlistener) { + return (MinecraftServer.getServer().getPlayerList().getIPBans().isEnabled() || MinecraftServer.getServer().getPlayerList().getProfileBans().isEnabled()) && super.canUse(icommandlistener); + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.banlist.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + if (astring.length >= 1 && astring[0].equalsIgnoreCase("ips")) { + icommandlistener.sendMessage(new ChatMessage("commands.banlist.ips", new Object[] { Integer.valueOf(MinecraftServer.getServer().getPlayerList().getIPBans().getEntries().length)})); + icommandlistener.sendMessage(new ChatComponentText(a((Object[]) MinecraftServer.getServer().getPlayerList().getIPBans().getEntries()))); + } else { + icommandlistener.sendMessage(new ChatMessage("commands.banlist.players", new Object[] { Integer.valueOf(MinecraftServer.getServer().getPlayerList().getProfileBans().getEntries().length)})); + icommandlistener.sendMessage(new ChatComponentText(a((Object[]) MinecraftServer.getServer().getPlayerList().getProfileBans().getEntries()))); + } + + } + + public List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { + return astring.length == 1 ? a(astring, new String[] { "players", "ips"}) : null; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandBlockData.java b/azurite-server/src/main/java/net/minecraft/server/CommandBlockData.java new file mode 100644 index 0000000..d4264b3 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandBlockData.java @@ -0,0 +1,71 @@ +package net.minecraft.server; + +import java.util.List; + +public class CommandBlockData extends CommandAbstract { + + public CommandBlockData() {} + + public String getCommand() { + return "blockdata"; + } + + public int a() { + return 2; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.blockdata.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + if (astring.length < 4) { + throw new ExceptionUsage("commands.blockdata.usage", new Object[0]); + } else { + icommandlistener.a(CommandObjectiveExecutor.EnumCommandResult.AFFECTED_BLOCKS, 0); + BlockPosition blockposition = a(icommandlistener, astring, 0, false); + World world = icommandlistener.getWorld(); + + if (!world.isLoaded(blockposition)) { + throw new CommandException("commands.blockdata.outOfWorld", new Object[0]); + } else { + TileEntity tileentity = world.getTileEntity(blockposition); + + if (tileentity == null) { + throw new CommandException("commands.blockdata.notValid", new Object[0]); + } else { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + + tileentity.b(nbttagcompound); + NBTTagCompound nbttagcompound1 = (NBTTagCompound) nbttagcompound.clone(); + + NBTTagCompound nbttagcompound2; + + try { + nbttagcompound2 = MojangsonParser.parse(a(icommandlistener, astring, 3).c()); + } catch (MojangsonParseException mojangsonparseexception) { + throw new CommandException("commands.blockdata.tagError", new Object[] { mojangsonparseexception.getMessage()}); + } + + nbttagcompound.a(nbttagcompound2); + nbttagcompound.setInt("x", blockposition.getX()); + nbttagcompound.setInt("y", blockposition.getY()); + nbttagcompound.setInt("z", blockposition.getZ()); + if (nbttagcompound.equals(nbttagcompound1)) { + throw new CommandException("commands.blockdata.failed", new Object[] { nbttagcompound.toString()}); + } else { + tileentity.a(nbttagcompound); + tileentity.update(); + world.notify(blockposition); + icommandlistener.a(CommandObjectiveExecutor.EnumCommandResult.AFFECTED_BLOCKS, 1); + a(icommandlistener, this, "commands.blockdata.success", new Object[] { nbttagcompound.toString()}); + } + } + } + } + } + + public List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { + return astring.length > 0 && astring.length <= 3 ? a(astring, 0, blockposition) : null; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandBlockListenerAbstract.java b/azurite-server/src/main/java/net/minecraft/server/CommandBlockListenerAbstract.java new file mode 100644 index 0000000..d6194eb --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandBlockListenerAbstract.java @@ -0,0 +1,297 @@ +package net.minecraft.server; + +import com.google.common.base.Joiner; +import org.bukkit.craftbukkit.command.VanillaCommandWrapper; + +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.concurrent.Callable; +import java.util.logging.Level; +// CraftBukkit end + +public abstract class CommandBlockListenerAbstract implements ICommandListener { + + private static final SimpleDateFormat a = new SimpleDateFormat("HH:mm:ss"); + private int b; + private boolean c = true; + private IChatBaseComponent d = null; + private String e = ""; + private String f = "@"; + private final CommandObjectiveExecutor g = new CommandObjectiveExecutor(); + protected org.bukkit.command.CommandSender sender; // CraftBukkit - add sender + + public CommandBlockListenerAbstract() {} + + public int j() { + return this.b; + } + + public IChatBaseComponent k() { + return this.d; + } + + public void a(NBTTagCompound nbttagcompound) { + nbttagcompound.setString("Command", this.e); + nbttagcompound.setInt("SuccessCount", this.b); + nbttagcompound.setString("CustomName", this.f); + nbttagcompound.setBoolean("TrackOutput", this.c); + if (this.d != null && this.c) { + nbttagcompound.setString("LastOutput", IChatBaseComponent.ChatSerializer.a(this.d)); + } + + this.g.b(nbttagcompound); + } + + public void b(NBTTagCompound nbttagcompound) { + this.e = nbttagcompound.getString("Command"); + this.b = nbttagcompound.getInt("SuccessCount"); + if (nbttagcompound.hasKeyOfType("CustomName", 8)) { + this.f = nbttagcompound.getString("CustomName"); + } + + if (nbttagcompound.hasKeyOfType("TrackOutput", 1)) { + this.c = nbttagcompound.getBoolean("TrackOutput"); + } + + if (nbttagcompound.hasKeyOfType("LastOutput", 8) && this.c) { + this.d = IChatBaseComponent.ChatSerializer.a(nbttagcompound.getString("LastOutput")); + } + + this.g.a(nbttagcompound); + } + + public boolean a(int i, String s) { + return i <= 2; + } + + public void setCommand(String s) { + this.e = s; + this.b = 0; + } + + public String getCommand() { + return this.e; + } + + public void a(World world) { + + MinecraftServer minecraftserver = MinecraftServer.getServer(); + + if (minecraftserver != null && minecraftserver.O() && minecraftserver.getEnableCommandBlock()) { + ICommandHandler icommandhandler = minecraftserver.getCommandHandler(); + + try { + this.d = null; + // this.b = icommandhandler.a(this, this.e); + // CraftBukkit start - Handle command block commands using Bukkit dispatcher + this.b = executeCommand(this, sender, this.e); + // CraftBukkit end + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.a(throwable, "Executing command block"); + CrashReportSystemDetails crashreportsystemdetails = crashreport.a("Command to be executed"); + + crashreportsystemdetails.a("Command", new Callable() { + public String a() throws Exception { + return CommandBlockListenerAbstract.this.getCommand(); + } + + public Object call() throws Exception { + return this.a(); + } + }); + crashreportsystemdetails.a("Name", new Callable() { + public String a() throws Exception { + return CommandBlockListenerAbstract.this.getName(); + } + + public Object call() throws Exception { + return this.a(); + } + }); + throw new ReportedException(crashreport); + } + } else { + this.b = 0; + } + + } + + // CraftBukkit start + public static int executeCommand(ICommandListener sender, org.bukkit.command.CommandSender bSender, String command) { + org.bukkit.command.SimpleCommandMap commandMap = sender.getWorld().getServer().getCommandMap(); + Joiner joiner = Joiner.on(" "); + if (command.startsWith("/")) { + command = command.substring(1); + } + String[] args = command.split(" "); + ArrayList commands = new ArrayList(); + + String cmd = args[0]; + if (cmd.startsWith("minecraft:")) cmd = cmd.substring("minecraft:".length()); + if (cmd.startsWith("bukkit:")) cmd = cmd.substring("bukkit:".length()); + + // Block disallowed commands + if (cmd.equalsIgnoreCase("stop") || cmd.equalsIgnoreCase("kick") || cmd.equalsIgnoreCase("op") + || cmd.equalsIgnoreCase("deop") || cmd.equalsIgnoreCase("ban") || cmd.equalsIgnoreCase("ban-ip") + || cmd.equalsIgnoreCase("pardon") || cmd.equalsIgnoreCase("pardon-ip") || cmd.equalsIgnoreCase("reload")) { + return 0; + } + + // If the world has no players don't run + if (sender.getWorld().players.isEmpty()) { + return 0; + } + + // Handle vanilla commands; + org.bukkit.command.Command commandBlockCommand = commandMap.getCommand(args[0]); + if (sender.getWorld().getServer().getCommandBlockOverride(args[0])) { + commandBlockCommand = commandMap.getCommand("minecraft:" + args[0]); + } + if (commandBlockCommand instanceof VanillaCommandWrapper) { + command = command.trim(); + if (command.startsWith("/")) { + command = command.substring(1); + } + String as[] = command.split(" "); + as = VanillaCommandWrapper.dropFirstArgument(as); + if (!((VanillaCommandWrapper) commandBlockCommand).testPermission(bSender)) { + return 0; + } + return ((VanillaCommandWrapper) commandBlockCommand).dispatchVanillaCommand(bSender, sender, as); + } + + // Make sure this is a valid command + if (commandMap.getCommand(args[0]) == null) { + return 0; + } + + commands.add(args); + + // Find positions of command block syntax, if any + WorldServer[] prev = MinecraftServer.getServer().worldServer; + MinecraftServer server = MinecraftServer.getServer(); + server.worldServer = new WorldServer[server.worlds.size()]; + server.worldServer[0] = (WorldServer) sender.getWorld(); + int bpos = 0; + for (int pos = 1; pos < server.worldServer.length; pos++) { + WorldServer world = server.worlds.get(bpos++); + if (server.worldServer[0] == world) { + pos--; + continue; + } + server.worldServer[pos] = world; + } + try { + ArrayList newCommands = new ArrayList(); + for (int i = 0; i < args.length; i++) { + if (PlayerSelector.isPattern(args[i])) { + for (int j = 0; j < commands.size(); j++) { + newCommands.addAll(buildCommands(sender, commands.get(j), i)); + } + ArrayList temp = commands; + commands = newCommands; + newCommands = temp; + newCommands.clear(); + } + } + } finally { + MinecraftServer.getServer().worldServer = prev; + } + + int completed = 0; + + // Now dispatch all of the commands we ended up with + for (int i = 0; i < commands.size(); i++) { + try { + if (commandMap.dispatch(bSender, joiner.join(java.util.Arrays.asList(commands.get(i))))) { + completed++; + } + } catch (Throwable exception) { + if (sender.f() instanceof EntityMinecartCommandBlock) { + MinecraftServer.getServer().server.getLogger().log(Level.WARNING, String.format("MinecartCommandBlock at (%d,%d,%d) failed to handle command", sender.getChunkCoordinates().getX(), sender.getChunkCoordinates().getY(), sender.getChunkCoordinates().getZ()), exception); + } else if (sender instanceof CommandBlockListenerAbstract) { + CommandBlockListenerAbstract listener = (CommandBlockListenerAbstract) sender; + MinecraftServer.getServer().server.getLogger().log(Level.WARNING, String.format("CommandBlock at (%d,%d,%d) failed to handle command", listener.getChunkCoordinates().getX(), listener.getChunkCoordinates().getY(), listener.getChunkCoordinates().getZ()), exception); + } else { + MinecraftServer.getServer().server.getLogger().log(Level.WARNING, String.format("Unknown CommandBlock failed to handle command"), exception); + } + } + } + + return completed; + } + + private static ArrayList buildCommands(ICommandListener sender, String[] args, int pos) { + ArrayList commands = new ArrayList(); + java.util.List players = (java.util.List)PlayerSelector.getPlayers(sender, args[pos], EntityPlayer.class); + + if (players != null) { + for (EntityPlayer player : players) { + if (player.world != sender.getWorld()) { + continue; + } + String[] command = args.clone(); + command[pos] = player.getName(); + commands.add(command); + } + } + + return commands; + } + // CraftBukkit end + + public String getName() { + return this.f; + } + + public IChatBaseComponent getScoreboardDisplayName() { + return new ChatComponentText(this.getName()); + } + + public void setName(String s) { + this.f = s; + } + + public void sendMessage(IChatBaseComponent ichatbasecomponent) { + if (this.c && this.getWorld() != null) { + this.d = (new ChatComponentText("[" + CommandBlockListenerAbstract.a.format(new Date()) + "] ")).addSibling(ichatbasecomponent); + this.h(); + } + + } + + public boolean getSendCommandFeedback() { + MinecraftServer minecraftserver = MinecraftServer.getServer(); + + return minecraftserver == null || !minecraftserver.O() || minecraftserver.worldServer[0].getGameRules().getBoolean("commandBlockOutput"); + } + + public void a(CommandObjectiveExecutor.EnumCommandResult commandobjectiveexecutor_enumcommandresult, int i) { + this.g.a(this, commandobjectiveexecutor_enumcommandresult, i); + } + + public abstract void h(); + + public void b(IChatBaseComponent ichatbasecomponent) { + this.d = ichatbasecomponent; + } + + public void a(boolean flag) { + this.c = flag; + } + + public boolean m() { + return this.c; + } + + public boolean a(EntityHuman entityhuman) { + if (!entityhuman.abilities.canInstantlyBuild) { + return false; + } else return true; + } + + public CommandObjectiveExecutor n() { + return this.g; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandClear.java b/azurite-server/src/main/java/net/minecraft/server/CommandClear.java new file mode 100644 index 0000000..2bc317d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandClear.java @@ -0,0 +1,72 @@ +package net.minecraft.server; + +import java.util.Collection; +import java.util.List; + +public class CommandClear extends CommandAbstract { + + public CommandClear() {} + + public String getCommand() { + return "clear"; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.clear.usage"; + } + + public int a() { + return 2; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + EntityPlayer entityplayer = astring.length == 0 ? b(icommandlistener) : a(icommandlistener, astring[0]); + Item item = astring.length >= 2 ? f(icommandlistener, astring[1]) : null; + int i = astring.length >= 3 ? a(astring[2], -1) : -1; + int j = astring.length >= 4 ? a(astring[3], -1) : -1; + NBTTagCompound nbttagcompound = null; + + if (astring.length >= 5) { + try { + nbttagcompound = MojangsonParser.parse(a(astring, 4)); + } catch (MojangsonParseException mojangsonparseexception) { + throw new CommandException("commands.clear.tagError", new Object[] { mojangsonparseexception.getMessage()}); + } + } + + if (astring.length >= 2 && item == null) { + throw new CommandException("commands.clear.failure", new Object[] { entityplayer.getName()}); + } else { + int k = entityplayer.inventory.a(item, i, j, nbttagcompound); + + entityplayer.defaultContainer.b(); + if (!entityplayer.abilities.canInstantlyBuild) { + entityplayer.broadcastCarriedItem(); + } + + icommandlistener.a(CommandObjectiveExecutor.EnumCommandResult.AFFECTED_ITEMS, k); + if (k == 0) { + throw new CommandException("commands.clear.failure", new Object[] { entityplayer.getName()}); + } else { + if (j == 0) { + icommandlistener.sendMessage(new ChatMessage("commands.clear.testing", new Object[] { entityplayer.getName(), Integer.valueOf(k)})); + } else { + a(icommandlistener, this, "commands.clear.success", new Object[] { entityplayer.getName(), Integer.valueOf(k)}); + } + + } + } + } + + public List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { + return astring.length == 1 ? a(astring, this.d()) : (astring.length == 2 ? a(astring, (Collection) Item.REGISTRY.keySet()) : null); + } + + protected String[] d() { + return MinecraftServer.getServer().getPlayers(); + } + + public boolean isListStart(String[] astring, int i) { + return i == 0; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandClone.java b/azurite-server/src/main/java/net/minecraft/server/CommandClone.java new file mode 100644 index 0000000..34012e8 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandClone.java @@ -0,0 +1,225 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +public class CommandClone extends CommandAbstract { + + public CommandClone() {} + + public String getCommand() { + return "clone"; + } + + public int a() { + return 2; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.clone.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + if (astring.length < 9) { + throw new ExceptionUsage("commands.clone.usage", new Object[0]); + } else { + icommandlistener.a(CommandObjectiveExecutor.EnumCommandResult.AFFECTED_BLOCKS, 0); + BlockPosition blockposition = a(icommandlistener, astring, 0, false); + BlockPosition blockposition1 = a(icommandlistener, astring, 3, false); + BlockPosition blockposition2 = a(icommandlistener, astring, 6, false); + StructureBoundingBox structureboundingbox = new StructureBoundingBox(blockposition, blockposition1); + StructureBoundingBox structureboundingbox1 = new StructureBoundingBox(blockposition2, blockposition2.a(structureboundingbox.b())); + int i = structureboundingbox.c() * structureboundingbox.d() * structureboundingbox.e(); + + if (i > '\u8000') { + throw new CommandException("commands.clone.tooManyBlocks", new Object[] { Integer.valueOf(i), Integer.valueOf('\u8000')}); + } else { + boolean flag = false; + Block block = null; + int j = -1; + + if ((astring.length < 11 || !astring[10].equals("force") && !astring[10].equals("move")) && structureboundingbox.a(structureboundingbox1)) { + throw new CommandException("commands.clone.noOverlap", new Object[0]); + } else { + if (astring.length >= 11 && astring[10].equals("move")) { + flag = true; + } + + if (structureboundingbox.b >= 0 && structureboundingbox.e < 256 && structureboundingbox1.b >= 0 && structureboundingbox1.e < 256) { + World world = icommandlistener.getWorld(); + + if (world.a(structureboundingbox) && world.a(structureboundingbox1)) { + boolean flag1 = false; + + if (astring.length >= 10) { + if (astring[9].equals("masked")) { + flag1 = true; + } else if (astring[9].equals("filtered")) { + if (astring.length < 12) { + throw new ExceptionUsage("commands.clone.usage", new Object[0]); + } + + block = g(icommandlistener, astring[11]); + if (astring.length >= 13) { + j = a(astring[12], 0, 15); + } + } + } + + ArrayList arraylist = Lists.newArrayList(); + ArrayList arraylist1 = Lists.newArrayList(); + ArrayList arraylist2 = Lists.newArrayList(); + LinkedList linkedlist = Lists.newLinkedList(); + BlockPosition blockposition3 = new BlockPosition(structureboundingbox1.a - structureboundingbox.a, structureboundingbox1.b - structureboundingbox.b, structureboundingbox1.c - structureboundingbox.c); + + for (int k = structureboundingbox.c; k <= structureboundingbox.f; ++k) { + for (int l = structureboundingbox.b; l <= structureboundingbox.e; ++l) { + for (int i1 = structureboundingbox.a; i1 <= structureboundingbox.d; ++i1) { + BlockPosition blockposition4 = new BlockPosition(i1, l, k); + BlockPosition blockposition5 = blockposition4.a(blockposition3); + IBlockData iblockdata = world.getType(blockposition4); + + if ((!flag1 || iblockdata.getBlock() != Blocks.AIR) && (block == null || iblockdata.getBlock() == block && (j < 0 || iblockdata.getBlock().toLegacyData(iblockdata) == j))) { + TileEntity tileentity = world.getTileEntity(blockposition4); + + if (tileentity != null) { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + + tileentity.b(nbttagcompound); + arraylist1.add(new CommandClone.CommandCloneStoredTileEntity(blockposition5, iblockdata, nbttagcompound)); + linkedlist.addLast(blockposition4); + } else if (!iblockdata.getBlock().o() && !iblockdata.getBlock().d()) { + arraylist2.add(new CommandClone.CommandCloneStoredTileEntity(blockposition5, iblockdata, (NBTTagCompound) null)); + linkedlist.addFirst(blockposition4); + } else { + arraylist.add(new CommandClone.CommandCloneStoredTileEntity(blockposition5, iblockdata, (NBTTagCompound) null)); + linkedlist.addLast(blockposition4); + } + } + } + } + } + + if (flag) { + Iterator iterator; + BlockPosition blockposition6; + + for (iterator = linkedlist.iterator(); iterator.hasNext(); world.setTypeAndData(blockposition6, Blocks.BARRIER.getBlockData(), 2)) { + blockposition6 = (BlockPosition) iterator.next(); + TileEntity tileentity1 = world.getTileEntity(blockposition6); + + if (tileentity1 instanceof IInventory) { + ((IInventory) tileentity1).l(); + } + } + + iterator = linkedlist.iterator(); + + while (iterator.hasNext()) { + blockposition6 = (BlockPosition) iterator.next(); + world.setTypeAndData(blockposition6, Blocks.AIR.getBlockData(), 3); + } + } + + ArrayList arraylist3 = Lists.newArrayList(); + + arraylist3.addAll(arraylist); + arraylist3.addAll(arraylist1); + arraylist3.addAll(arraylist2); + List list = Lists.reverse(arraylist3); + + Iterator iterator1; + CommandClone.CommandCloneStoredTileEntity commandclone_commandclonestoredtileentity; + TileEntity tileentity2; + + for (iterator1 = list.iterator(); iterator1.hasNext(); world.setTypeAndData(commandclone_commandclonestoredtileentity.a, Blocks.BARRIER.getBlockData(), 2)) { + commandclone_commandclonestoredtileentity = (CommandClone.CommandCloneStoredTileEntity) iterator1.next(); + tileentity2 = world.getTileEntity(commandclone_commandclonestoredtileentity.a); + if (tileentity2 instanceof IInventory) { + ((IInventory) tileentity2).l(); + } + } + + i = 0; + iterator1 = arraylist3.iterator(); + + while (iterator1.hasNext()) { + commandclone_commandclonestoredtileentity = (CommandClone.CommandCloneStoredTileEntity) iterator1.next(); + if (world.setTypeAndData(commandclone_commandclonestoredtileentity.a, commandclone_commandclonestoredtileentity.b, 2)) { + ++i; + } + } + + for (iterator1 = arraylist1.iterator(); iterator1.hasNext(); world.setTypeAndData(commandclone_commandclonestoredtileentity.a, commandclone_commandclonestoredtileentity.b, 2)) { + commandclone_commandclonestoredtileentity = (CommandClone.CommandCloneStoredTileEntity) iterator1.next(); + tileentity2 = world.getTileEntity(commandclone_commandclonestoredtileentity.a); + if (commandclone_commandclonestoredtileentity.c != null && tileentity2 != null) { + commandclone_commandclonestoredtileentity.c.setInt("x", commandclone_commandclonestoredtileentity.a.getX()); + commandclone_commandclonestoredtileentity.c.setInt("y", commandclone_commandclonestoredtileentity.a.getY()); + commandclone_commandclonestoredtileentity.c.setInt("z", commandclone_commandclonestoredtileentity.a.getZ()); + tileentity2.a(commandclone_commandclonestoredtileentity.c); + tileentity2.update(); + } + } + + iterator1 = list.iterator(); + + while (iterator1.hasNext()) { + commandclone_commandclonestoredtileentity = (CommandClone.CommandCloneStoredTileEntity) iterator1.next(); + world.update(commandclone_commandclonestoredtileentity.a, commandclone_commandclonestoredtileentity.b.getBlock()); + } + + List list1 = world.a(structureboundingbox, false); + + if (list1 != null) { + Iterator iterator2 = list1.iterator(); + + while (iterator2.hasNext()) { + NextTickListEntry nextticklistentry = (NextTickListEntry) iterator2.next(); + + if (structureboundingbox.b((BaseBlockPosition) nextticklistentry.a)) { + BlockPosition blockposition7 = nextticklistentry.a.a(blockposition3); + + world.b(blockposition7, nextticklistentry.a(), (int) (nextticklistentry.b - world.getWorldData().getTime()), nextticklistentry.c); + } + } + } + + if (i <= 0) { + throw new CommandException("commands.clone.failed", new Object[0]); + } else { + icommandlistener.a(CommandObjectiveExecutor.EnumCommandResult.AFFECTED_BLOCKS, i); + a(icommandlistener, this, "commands.clone.success", new Object[] { Integer.valueOf(i)}); + } + } else { + throw new CommandException("commands.clone.outOfWorld", new Object[0]); + } + } else { + throw new CommandException("commands.clone.outOfWorld", new Object[0]); + } + } + } + } + } + + public List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { + return astring.length > 0 && astring.length <= 3 ? a(astring, 0, blockposition) : (astring.length > 3 && astring.length <= 6 ? a(astring, 3, blockposition) : (astring.length > 6 && astring.length <= 9 ? a(astring, 6, blockposition) : (astring.length == 10 ? a(astring, new String[] { "replace", "masked", "filtered"}) : (astring.length == 11 ? a(astring, new String[] { "normal", "force", "move"}) : (astring.length == 12 && "filtered".equals(astring[9]) ? a(astring, (Collection) Block.REGISTRY.keySet()) : null))))); + } + + static class CommandCloneStoredTileEntity { + + public final BlockPosition a; + public final IBlockData b; + public final NBTTagCompound c; + + public CommandCloneStoredTileEntity(BlockPosition blockposition, IBlockData iblockdata, NBTTagCompound nbttagcompound) { + this.a = blockposition; + this.b = iblockdata; + this.c = nbttagcompound; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandDebug.java b/azurite-server/src/main/java/net/minecraft/server/CommandDebug.java new file mode 100644 index 0000000..916298c --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandDebug.java @@ -0,0 +1,141 @@ +package net.minecraft.server; + +import java.io.File; +import java.io.FileWriter; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +public class CommandDebug extends CommandAbstract { + + private static final Logger a = LogManager.getLogger(); + private long b; + private int c; + + public CommandDebug() {} + + public String getCommand() { + return "debug"; + } + + public int a() { + return 3; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.debug.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + if (astring.length < 1) { + throw new ExceptionUsage("commands.debug.usage", new Object[0]); + } else { + if (astring[0].equals("start")) { + if (astring.length != 1) { + throw new ExceptionUsage("commands.debug.usage", new Object[0]); + } + + a(icommandlistener, this, "commands.debug.start", new Object[0]); + MinecraftServer.getServer().au(); + this.b = MinecraftServer.az(); + this.c = MinecraftServer.getServer().at(); + } else { + if (!astring[0].equals("stop")) { + throw new ExceptionUsage("commands.debug.usage", new Object[0]); + } + + if (astring.length != 1) { + throw new ExceptionUsage("commands.debug.usage", new Object[0]); + } + + if (!MinecraftServer.getServer().methodProfiler.a) { + throw new CommandException("commands.debug.notStarted", new Object[0]); + } + + long i = MinecraftServer.az(); + int j = MinecraftServer.getServer().at(); + long k = i - this.b; + int l = j - this.c; + + this.a(k, l); + MinecraftServer.getServer().methodProfiler.a = false; + a(icommandlistener, this, "commands.debug.stop", new Object[] { Float.valueOf((float) k / 1000.0F), Integer.valueOf(l)}); + } + + } + } + + private void a(long i, int j) { + File file = new File(MinecraftServer.getServer().d("debug"), "profile-results-" + (new SimpleDateFormat("yyyy-MM-dd_HH.mm.ss")).format(new Date()) + ".txt"); + + file.getParentFile().mkdirs(); + + try { + FileWriter filewriter = new FileWriter(file); + + filewriter.write(this.b(i, j)); + filewriter.close(); + } catch (Throwable throwable) { + CommandDebug.a.error("Could not save profiler results to " + file, throwable); + } + + } + + private String b(long i, int j) { + StringBuilder stringbuilder = new StringBuilder(); + + stringbuilder.append("---- Minecraft Profiler Results ----\n"); + stringbuilder.append("// "); + stringbuilder.append(d()); + stringbuilder.append("\n\n"); + stringbuilder.append("Time span: ").append(i).append(" ms\n"); + stringbuilder.append("Tick span: ").append(j).append(" ticks\n"); + stringbuilder.append("// This is approximately ").append(String.format("%.2f", new Object[] { Float.valueOf((float) j / ((float) i / 1000.0F))})).append(" ticks per second. It should be ").append(20).append(" ticks per second\n\n"); + stringbuilder.append("--- BEGIN PROFILE DUMP ---\n\n"); + this.a(0, "root", stringbuilder); + stringbuilder.append("--- END PROFILE DUMP ---\n\n"); + return stringbuilder.toString(); + } + + private void a(int i, String s, StringBuilder stringbuilder) { + List list = MinecraftServer.getServer().methodProfiler.b(s); + + if (list != null && list.size() >= 3) { + for (int j = 1; j < list.size(); ++j) { + MethodProfiler.ProfilerInfo methodprofiler_profilerinfo = (MethodProfiler.ProfilerInfo) list.get(j); + + stringbuilder.append(String.format("[%02d] ", new Object[] { Integer.valueOf(i)})); + + for (int k = 0; k < i; ++k) { + stringbuilder.append(" "); + } + + stringbuilder.append(methodprofiler_profilerinfo.c).append(" - ").append(String.format("%.2f", new Object[] { Double.valueOf(methodprofiler_profilerinfo.a)})).append("%/").append(String.format("%.2f", new Object[] { Double.valueOf(methodprofiler_profilerinfo.b)})).append("%\n"); + if (!methodprofiler_profilerinfo.c.equals("unspecified")) { + try { + this.a(i + 1, s + "." + methodprofiler_profilerinfo.c, stringbuilder); + } catch (Exception exception) { + stringbuilder.append("[[ EXCEPTION ").append(exception).append(" ]]"); + } + } + } + + } + } + + private static String d() { + String[] astring = new String[] { "Shiny numbers!", "Am I not running fast enough? :(", "I\'m working as hard as I can!", "Will I ever be good enough for you? :(", "Speedy. Zoooooom!", "Hello world", "40% better than a crash report.", "Now with extra numbers", "Now with less numbers", "Now with the same numbers", "You should add flames to things, it makes them go faster!", "Do you feel the need for... optimization?", "*cracks redstone whip*", "Maybe if you treated it better then it\'ll have more motivation to work faster! Poor server."}; + + try { + return astring[(int) (System.nanoTime() % (long) astring.length)]; + } catch (Throwable throwable) { + return "Witty comment unavailable :("; + } + } + + public List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { + return astring.length == 1 ? a(astring, new String[] { "start", "stop"}) : null; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandDeop.java b/azurite-server/src/main/java/net/minecraft/server/CommandDeop.java new file mode 100644 index 0000000..34d98bb --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandDeop.java @@ -0,0 +1,41 @@ +package net.minecraft.server; + +import com.mojang.authlib.GameProfile; +import java.util.List; + +public class CommandDeop extends CommandAbstract { + + public CommandDeop() {} + + public String getCommand() { + return "deop"; + } + + public int a() { + return 3; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.deop.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + if (astring.length == 1 && astring[0].length() > 0) { + MinecraftServer minecraftserver = MinecraftServer.getServer(); + GameProfile gameprofile = minecraftserver.getPlayerList().getOPs().a(astring[0]); + + if (gameprofile == null) { + throw new CommandException("commands.deop.failed", new Object[] { astring[0]}); + } else { + minecraftserver.getPlayerList().removeOp(gameprofile); + a(icommandlistener, this, "commands.deop.success", new Object[] { astring[0]}); + } + } else { + throw new ExceptionUsage("commands.deop.usage", new Object[0]); + } + } + + public List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { + return astring.length == 1 ? a(astring, MinecraftServer.getServer().getPlayerList().n()) : null; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandDifficulty.java b/azurite-server/src/main/java/net/minecraft/server/CommandDifficulty.java new file mode 100644 index 0000000..dd59948 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandDifficulty.java @@ -0,0 +1,39 @@ +package net.minecraft.server; + +import java.util.List; + +public class CommandDifficulty extends CommandAbstract { + + public CommandDifficulty() {} + + public String getCommand() { + return "difficulty"; + } + + public int a() { + return 2; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.difficulty.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + if (astring.length <= 0) { + throw new ExceptionUsage("commands.difficulty.usage", new Object[0]); + } else { + EnumDifficulty enumdifficulty = this.e(astring[0]); + + MinecraftServer.getServer().a(enumdifficulty); + a(icommandlistener, this, "commands.difficulty.success", new Object[] { new ChatMessage(enumdifficulty.b(), new Object[0])}); + } + } + + protected EnumDifficulty e(String s) throws ExceptionInvalidNumber { + return !s.equalsIgnoreCase("peaceful") && !s.equalsIgnoreCase("p") ? (!s.equalsIgnoreCase("easy") && !s.equalsIgnoreCase("e") ? (!s.equalsIgnoreCase("normal") && !s.equalsIgnoreCase("n") ? (!s.equalsIgnoreCase("hard") && !s.equalsIgnoreCase("h") ? EnumDifficulty.getById(a(s, 0, 3)) : EnumDifficulty.HARD) : EnumDifficulty.NORMAL) : EnumDifficulty.EASY) : EnumDifficulty.PEACEFUL; + } + + public List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { + return astring.length == 1 ? a(astring, new String[] { "peaceful", "easy", "normal", "hard"}) : null; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandDispatcher.java b/azurite-server/src/main/java/net/minecraft/server/CommandDispatcher.java new file mode 100644 index 0000000..95a940f --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandDispatcher.java @@ -0,0 +1,108 @@ +package net.minecraft.server; + +public class CommandDispatcher extends CommandHandler implements ICommandDispatcher { + + public CommandDispatcher() { + a(new CommandTime()); + a(new CommandGamemode()); + a(new CommandDifficulty()); + a(new CommandGamemodeDefault()); + a(new CommandKill()); + a(new CommandToggleDownfall()); + a(new CommandWeather()); + a(new CommandXp()); + a(new CommandTp()); + a(new CommandGive()); + a(new CommandReplaceItem()); + a(new CommandStats()); + a(new CommandEffect()); + a(new CommandEnchant()); + a(new CommandParticle()); + a(new CommandMe()); + a(new CommandSeed()); + a(new CommandHelp()); + a(new CommandTell()); + a(new CommandSay()); + a(new CommandSpawnpoint()); + a(new CommandSetWorldSpawn()); + a(new CommandGamerule()); + a(new CommandClear()); + a(new CommandTestFor()); + a(new CommandSpreadPlayers()); + a(new CommandPlaySound()); + a(new CommandScoreboard()); + a(new CommandExecute()); + a(new CommandTrigger()); + a(new CommandAchievement()); + a(new CommandSummon()); + a(new CommandSetBlock()); + a(new CommandFill()); + a(new CommandClone()); + a(new CommandTestForBlocks()); + a(new CommandBlockData()); + a(new CommandTestForBlock()); + a(new CommandTellRaw()); + a(new CommandWorldBorder()); + a(new CommandTitle()); + a(new CommandEntityData()); + a(new CommandOp()); + a(new CommandDeop()); + a(new CommandStop()); + a(new CommandSaveAll()); + a(new CommandSaveOff()); + a(new CommandSaveOn()); + a(new CommandBanIp()); + a(new CommandPardonIP()); + a(new CommandBan()); + a(new CommandBanList()); + a(new CommandPardon()); + a(new CommandKick()); + a(new CommandList()); + a(new CommandWhitelist()); + a(new CommandIdleTimeout()); + + CommandAbstract.a(this); + } + + public void a(ICommandListener icommandlistener, ICommand icommand, int i, String s, Object... aobject) { + boolean flag = true; + MinecraftServer minecraftserver = MinecraftServer.getServer(); + + if (!icommandlistener.getSendCommandFeedback()) { + flag = false; + } + + ChatMessage chatmessage = new ChatMessage("chat.type.admin", icommandlistener.getName(), new ChatMessage(s, aobject)); + + chatmessage.getChatModifier().setColor(EnumChatFormat.GRAY); + chatmessage.getChatModifier().setItalic(Boolean.TRUE); + if (flag) { + + for (EntityPlayer entityhuman : minecraftserver.getPlayerList().v()) { + if (entityhuman != icommandlistener && minecraftserver.getPlayerList().isOp(entityhuman.getProfile()) && icommand.canUse(icommandlistener)) { + boolean flag1 = icommandlistener instanceof MinecraftServer && MinecraftServer.getServer().r(); + boolean flag2 = icommandlistener instanceof RemoteControlCommandListener && MinecraftServer.getServer().q(); + + if (flag1 || flag2 || !(icommandlistener instanceof RemoteControlCommandListener) && !(icommandlistener instanceof MinecraftServer)) { + entityhuman.sendMessage(chatmessage); + } + } + } + } + + if (icommandlistener != minecraftserver && minecraftserver.worldServer[0].getGameRules().getBoolean("logAdminCommands") && !org.spigotmc.SpigotConfig.silentCommandBlocks) { // Spigot + minecraftserver.sendMessage(chatmessage); + } + + boolean flag3 = minecraftserver.worldServer[0].getGameRules().getBoolean("sendCommandFeedback"); + + if (icommandlistener instanceof CommandBlockListenerAbstract) { + flag3 = ((CommandBlockListenerAbstract) icommandlistener).m(); + } + + if ((i & 1) != 1 && flag3 || icommandlistener instanceof MinecraftServer) { + icommandlistener.sendMessage(new ChatMessage(s, aobject)); + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandEffect.java b/azurite-server/src/main/java/net/minecraft/server/CommandEffect.java new file mode 100644 index 0000000..743d385 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandEffect.java @@ -0,0 +1,107 @@ +package net.minecraft.server; + +import java.util.Collection; +import java.util.List; + +public class CommandEffect extends CommandAbstract { + + public CommandEffect() {} + + public String getCommand() { + return "effect"; + } + + public int a() { + return 2; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.effect.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + if (astring.length < 2) { + throw new ExceptionUsage("commands.effect.usage", new Object[0]); + } else { + EntityLiving entityliving = (EntityLiving) a(icommandlistener, astring[0], EntityLiving.class); + + if (astring[1].equals("clear")) { + if (entityliving.getEffects().isEmpty()) { + throw new CommandException("commands.effect.failure.notActive.all", new Object[] { entityliving.getName()}); + } else { + entityliving.removeAllEffects(); + a(icommandlistener, this, "commands.effect.success.removed.all", new Object[] { entityliving.getName()}); + } + } else { + int i; + + try { + i = a(astring[1], 1); + } catch (ExceptionInvalidNumber exceptioninvalidnumber) { + MobEffectList mobeffectlist = MobEffectList.b(astring[1]); + + if (mobeffectlist == null) { + throw exceptioninvalidnumber; + } + + i = mobeffectlist.id; + } + + int j = 600; + int k = 30; + int l = 0; + + if (i >= 0 && i < MobEffectList.byId.length && MobEffectList.byId[i] != null) { + MobEffectList mobeffectlist1 = MobEffectList.byId[i]; + + if (astring.length >= 3) { + k = a(astring[2], 0, 1000000); + if (mobeffectlist1.isInstant()) { + j = k; + } else { + j = k * 20; + } + } else if (mobeffectlist1.isInstant()) { + j = 1; + } + + if (astring.length >= 4) { + l = a(astring[3], 0, 255); + } + + boolean flag = true; + + if (astring.length >= 5 && "true".equalsIgnoreCase(astring[4])) { + flag = false; + } + + if (k > 0) { + MobEffect mobeffect = new MobEffect(i, j, l, false, flag); + + entityliving.addEffect(mobeffect); + a(icommandlistener, this, "commands.effect.success", new Object[] { new ChatMessage(mobeffect.g(), new Object[0]), Integer.valueOf(i), Integer.valueOf(l), entityliving.getName(), Integer.valueOf(k)}); + } else if (entityliving.hasEffect(i)) { + entityliving.removeEffect(i); + a(icommandlistener, this, "commands.effect.success.removed", new Object[] { new ChatMessage(mobeffectlist1.a(), new Object[0]), entityliving.getName()}); + } else { + throw new CommandException("commands.effect.failure.notActive", new Object[] { new ChatMessage(mobeffectlist1.a(), new Object[0]), entityliving.getName()}); + } + } else { + throw new ExceptionInvalidNumber("commands.effect.notFound", new Object[] { Integer.valueOf(i)}); + } + } + } + } + + public List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { + return astring.length == 1 ? a(astring, this.d()) : (astring.length == 2 ? a(astring, (Collection) MobEffectList.c()) : (astring.length == 5 ? a(astring, new String[] { "true", "false"}) : null)); + } + + protected String[] d() { + return MinecraftServer.getServer().getPlayers(); + } + + public boolean isListStart(String[] astring, int i) { + return i == 0; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandEnchant.java b/azurite-server/src/main/java/net/minecraft/server/CommandEnchant.java new file mode 100644 index 0000000..500a6a9 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandEnchant.java @@ -0,0 +1,98 @@ +package net.minecraft.server; + +import java.util.Collection; +import java.util.List; + +public class CommandEnchant extends CommandAbstract { + + public CommandEnchant() {} + + public String getCommand() { + return "enchant"; + } + + public int a() { + return 2; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.enchant.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + if (astring.length < 2) { + throw new ExceptionUsage("commands.enchant.usage", new Object[0]); + } else { + EntityPlayer entityplayer = a(icommandlistener, astring[0]); + + icommandlistener.a(CommandObjectiveExecutor.EnumCommandResult.AFFECTED_ITEMS, 0); + + int i; + + try { + i = a(astring[1], 0); + } catch (ExceptionInvalidNumber exceptioninvalidnumber) { + Enchantment enchantment = Enchantment.getByName(astring[1]); + + if (enchantment == null) { + throw exceptioninvalidnumber; + } + + i = enchantment.id; + } + + int j = 1; + ItemStack itemstack = entityplayer.bZ(); + + if (itemstack == null) { + throw new CommandException("commands.enchant.noItem", new Object[0]); + } else { + Enchantment enchantment1 = Enchantment.getById(i); + + if (enchantment1 == null) { + throw new ExceptionInvalidNumber("commands.enchant.notFound", new Object[] { Integer.valueOf(i)}); + } else if (!enchantment1.canEnchant(itemstack)) { + throw new CommandException("commands.enchant.cantEnchant", new Object[0]); + } else { + if (astring.length >= 3) { + j = a(astring[2], enchantment1.getStartLevel(), enchantment1.getMaxLevel()); + } + + if (itemstack.hasTag()) { + NBTTagList nbttaglist = itemstack.getEnchantments(); + + if (nbttaglist != null) { + for (int k = 0; k < nbttaglist.size(); ++k) { + short short0 = nbttaglist.get(k).getShort("id"); + + if (Enchantment.getById(short0) != null) { + Enchantment enchantment2 = Enchantment.getById(short0); + + if (!enchantment2.a(enchantment1)) { + throw new CommandException("commands.enchant.cantCombine", new Object[] { enchantment1.d(j), enchantment2.d(nbttaglist.get(k).getShort("lvl"))}); + } + } + } + } + } + + itemstack.addEnchantment(enchantment1, j); + a(icommandlistener, this, "commands.enchant.success", new Object[0]); + icommandlistener.a(CommandObjectiveExecutor.EnumCommandResult.AFFECTED_ITEMS, 1); + } + } + } + } + + public List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { + return astring.length == 1 ? a(astring, this.d()) : (astring.length == 2 ? a(astring, (Collection) Enchantment.getEffects()) : null); + } + + protected String[] d() { + return MinecraftServer.getServer().getPlayers(); + } + + public boolean isListStart(String[] astring, int i) { + return i == 0; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandEntityData.java b/azurite-server/src/main/java/net/minecraft/server/CommandEntityData.java new file mode 100644 index 0000000..464c1d3 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandEntityData.java @@ -0,0 +1,57 @@ +package net.minecraft.server; + +public class CommandEntityData extends CommandAbstract { + + public CommandEntityData() {} + + public String getCommand() { + return "entitydata"; + } + + public int a() { + return 2; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.entitydata.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + if (astring.length < 2) { + throw new ExceptionUsage("commands.entitydata.usage", new Object[0]); + } else { + Entity entity = b(icommandlistener, astring[0]); + + if (entity instanceof EntityHuman) { + throw new CommandException("commands.entitydata.noPlayers", new Object[] { entity.getScoreboardDisplayName()}); + } else { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + + entity.e(nbttagcompound); + NBTTagCompound nbttagcompound1 = (NBTTagCompound) nbttagcompound.clone(); + + NBTTagCompound nbttagcompound2; + + try { + nbttagcompound2 = MojangsonParser.parse(a(icommandlistener, astring, 1).c()); + } catch (MojangsonParseException mojangsonparseexception) { + throw new CommandException("commands.entitydata.tagError", new Object[] { mojangsonparseexception.getMessage()}); + } + + nbttagcompound2.remove("UUIDMost"); + nbttagcompound2.remove("UUIDLeast"); + nbttagcompound.a(nbttagcompound2); + if (nbttagcompound.equals(nbttagcompound1)) { + throw new CommandException("commands.entitydata.failed", new Object[] { nbttagcompound.toString()}); + } else { + entity.f(nbttagcompound); + a(icommandlistener, this, "commands.entitydata.success", new Object[] { nbttagcompound.toString()}); + } + } + } + } + + public boolean isListStart(String[] astring, int i) { + return i == 0; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandException.java b/azurite-server/src/main/java/net/minecraft/server/CommandException.java new file mode 100644 index 0000000..abe7b7b --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandException.java @@ -0,0 +1,15 @@ +package net.minecraft.server; + +public class CommandException extends Exception { + + private final Object[] a; + + public CommandException(String s, Object... aobject) { + super(s); + this.a = aobject; + } + + public Object[] getArgs() { + return this.a; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandExecute.java b/azurite-server/src/main/java/net/minecraft/server/CommandExecute.java new file mode 100644 index 0000000..8c1b5f7 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandExecute.java @@ -0,0 +1,143 @@ +package net.minecraft.server; + +import org.bukkit.craftbukkit.command.ProxiedNativeCommandSender; +import org.bukkit.craftbukkit.command.VanillaCommandWrapper; + +import java.util.List; + + +public class CommandExecute extends CommandAbstract { + + public CommandExecute() { + } + + public String getCommand() { + return "execute"; + } + + public int a() { + return 2; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.execute.usage"; + } + + public void execute(final ICommandListener icommandlistener, String[] astring) throws CommandException { + if (astring.length < 5) { + throw new ExceptionUsage("commands.execute.usage"); + } else { + final Entity entity = a(icommandlistener, astring[0], Entity.class); + final double d0 = b(entity.locX, astring[1], false); + final double d1 = b(entity.locY, astring[2], false); + final double d2 = b(entity.locZ, astring[3], false); + final BlockPosition blockposition = new BlockPosition(d0, d1, d2); + byte b0 = 4; + + if ("detect".equals(astring[4]) && astring.length > 10) { + World world = entity.getWorld(); + double d3 = b(d0, astring[5], false); + double d4 = b(d1, astring[6], false); + double d5 = b(d2, astring[7], false); + Block block = g(icommandlistener, astring[8]); + int i = a(astring[9], -1, 15); + IBlockData iblockdata = world.getType(MathHelper.floor(d3), MathHelper.floor(d4), MathHelper.floor(d5)); + + if (iblockdata.getBlock() != block || i >= 0 && iblockdata.getBlock().toLegacyData(iblockdata) != i) { + throw new CommandException("commands.execute.failed", "detect", entity.getName()); + } + + b0 = 10; + } + + String s = a(astring, b0); + ICommandListener icommandlistener1 = new ICommandListener() { + public String getName() { + return entity.getName(); + } + + public IChatBaseComponent getScoreboardDisplayName() { + return entity.getScoreboardDisplayName(); + } + + public void sendMessage(IChatBaseComponent ichatbasecomponent) { + icommandlistener.sendMessage(ichatbasecomponent); + } + + public boolean a(int i, String s) { + return icommandlistener.a(i, s); + } + + public BlockPosition getChunkCoordinates() { + return blockposition; + } + + public Vec3D d() { + return new Vec3D(d0, d1, d2); + } + + public World getWorld() { + return entity.world; + } + + public Entity f() { + return entity; + } + + public boolean getSendCommandFeedback() { + MinecraftServer minecraftserver = MinecraftServer.getServer(); + + return minecraftserver == null || minecraftserver.worldServer[0].getGameRules().getBoolean("commandBlockOutput"); + } + + public void a(CommandObjectiveExecutor.EnumCommandResult commandobjectiveexecutor_enumcommandresult, int i) { + entity.a(commandobjectiveexecutor_enumcommandresult, i); + } + }; + + try { + // CraftBukkit start + org.bukkit.command.CommandSender sender; + if (icommandlistener instanceof DedicatedServer) { + sender = MinecraftServer.getServer().server.getConsoleSender(); + } else if (icommandlistener instanceof CommandBlockListenerAbstract) { + sender = ((CommandBlockListenerAbstract) icommandlistener).sender; + } else if (VanillaCommandWrapper.lastSender != null) { + sender = VanillaCommandWrapper.lastSender; + } else if (icommandlistener.f() != null) { + sender = icommandlistener.f().getBukkitEntity(); + } else { + throw new CommandException("Unhandled executor " + icommandlistener.getClass().getSimpleName()); + } + int j = CommandBlockListenerAbstract.executeCommand(icommandlistener1, new ProxiedNativeCommandSender(icommandlistener1, sender, entity.getBukkitEntity()), s); + // CraftBukkit end + + if (j < 1) { + throw new CommandException("commands.execute.allInvocationsFailed", s); + } + } catch (Throwable throwable) { + // CraftBukkit start + if (throwable instanceof CommandException) { + throw (CommandException) throwable; + } + // CraftBukkit end + throw new CommandException("commands.execute.failed", s, entity.getName()); + } + } + } + + public List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { + return astring.length == 1 ? a(astring, MinecraftServer.getServer().getPlayers()) : (astring.length > 1 && astring.length <= 4 ? a(astring, 1, blockposition) : (astring.length > 5 && astring.length <= 8 && "detect".equals(astring[4]) ? a(astring, 5, blockposition) : (astring.length == 9 && "detect".equals(astring[4]) ? a(astring, Block.REGISTRY.keySet()) : null))); + } + + public boolean isListStart(String[] astring, int i) { + return i == 0; + } + + // CraftBukkit start - fix decompiler error + @Override + public int compareTo(ICommand o) { + return a(o); + } + // CraftBukkit end +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandFill.java b/azurite-server/src/main/java/net/minecraft/server/CommandFill.java new file mode 100644 index 0000000..aab43b1 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandFill.java @@ -0,0 +1,168 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; + +public class CommandFill extends CommandAbstract { + + public CommandFill() {} + + public String getCommand() { + return "fill"; + } + + public int a() { + return 2; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.fill.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + if (astring.length < 7) { + throw new ExceptionUsage("commands.fill.usage", new Object[0]); + } else { + icommandlistener.a(CommandObjectiveExecutor.EnumCommandResult.AFFECTED_BLOCKS, 0); + BlockPosition blockposition = a(icommandlistener, astring, 0, false); + BlockPosition blockposition1 = a(icommandlistener, astring, 3, false); + Block block = CommandAbstract.g(icommandlistener, astring[6]); + int i = 0; + + if (astring.length >= 8) { + i = a(astring[7], 0, 15); + } + + BlockPosition blockposition2 = new BlockPosition(Math.min(blockposition.getX(), blockposition1.getX()), Math.min(blockposition.getY(), blockposition1.getY()), Math.min(blockposition.getZ(), blockposition1.getZ())); + BlockPosition blockposition3 = new BlockPosition(Math.max(blockposition.getX(), blockposition1.getX()), Math.max(blockposition.getY(), blockposition1.getY()), Math.max(blockposition.getZ(), blockposition1.getZ())); + int j = (blockposition3.getX() - blockposition2.getX() + 1) * (blockposition3.getY() - blockposition2.getY() + 1) * (blockposition3.getZ() - blockposition2.getZ() + 1); + + if (j > '\u8000') { + throw new CommandException("commands.fill.tooManyBlocks", new Object[] { Integer.valueOf(j), Integer.valueOf('\u8000')}); + } else if (blockposition2.getY() >= 0 && blockposition3.getY() < 256) { + World world = icommandlistener.getWorld(); + + for (int k = blockposition2.getZ(); k < blockposition3.getZ() + 16; k += 16) { + for (int l = blockposition2.getX(); l < blockposition3.getX() + 16; l += 16) { + if (!world.isLoaded(new BlockPosition(l, blockposition3.getY() - blockposition2.getY(), k))) { + throw new CommandException("commands.fill.outOfWorld", new Object[0]); + } + } + } + + NBTTagCompound nbttagcompound = new NBTTagCompound(); + boolean flag = false; + + if (astring.length >= 10 && block.isTileEntity()) { + String s = a(icommandlistener, astring, 9).c(); + + try { + nbttagcompound = MojangsonParser.parse(s); + flag = true; + } catch (MojangsonParseException mojangsonparseexception) { + throw new CommandException("commands.fill.tagError", new Object[] { mojangsonparseexception.getMessage()}); + } + } + + ArrayList arraylist = Lists.newArrayList(); + + j = 0; + + for (int i1 = blockposition2.getZ(); i1 <= blockposition3.getZ(); ++i1) { + for (int j1 = blockposition2.getY(); j1 <= blockposition3.getY(); ++j1) { + for (int k1 = blockposition2.getX(); k1 <= blockposition3.getX(); ++k1) { + BlockPosition blockposition4 = new BlockPosition(k1, j1, i1); + IBlockData iblockdata; + + if (astring.length >= 9) { + if (!astring[8].equals("outline") && !astring[8].equals("hollow")) { + if (astring[8].equals("destroy")) { + world.setAir(blockposition4, true); + } else if (astring[8].equals("keep")) { + if (!world.isEmpty(blockposition4)) { + continue; + } + } else if (astring[8].equals("replace") && !block.isTileEntity()) { + if (astring.length > 9) { + Block block1 = CommandAbstract.g(icommandlistener, astring[9]); + + if (world.getType(blockposition4).getBlock() != block1) { + continue; + } + } + + if (astring.length > 10) { + int l1 = CommandAbstract.a(astring[10]); + + iblockdata = world.getType(blockposition4); + if (iblockdata.getBlock().toLegacyData(iblockdata) != l1) { + continue; + } + } + } + } else if (k1 != blockposition2.getX() && k1 != blockposition3.getX() && j1 != blockposition2.getY() && j1 != blockposition3.getY() && i1 != blockposition2.getZ() && i1 != blockposition3.getZ()) { + if (astring[8].equals("hollow")) { + world.setTypeAndData(blockposition4, Blocks.AIR.getBlockData(), 2); + arraylist.add(blockposition4); + } + continue; + } + } + + TileEntity tileentity = world.getTileEntity(blockposition4); + + if (tileentity != null) { + if (tileentity instanceof IInventory) { + ((IInventory) tileentity).l(); + } + + world.setTypeAndData(blockposition4, Blocks.BARRIER.getBlockData(), block == Blocks.BARRIER ? 2 : 4); + } + + iblockdata = block.fromLegacyData(i); + if (world.setTypeAndData(blockposition4, iblockdata, 2)) { + arraylist.add(blockposition4); + ++j; + if (flag) { + TileEntity tileentity1 = world.getTileEntity(blockposition4); + + if (tileentity1 != null) { + nbttagcompound.setInt("x", blockposition4.getX()); + nbttagcompound.setInt("y", blockposition4.getY()); + nbttagcompound.setInt("z", blockposition4.getZ()); + tileentity1.a(nbttagcompound); + } + } + } + } + } + } + + Iterator iterator = arraylist.iterator(); + + while (iterator.hasNext()) { + BlockPosition blockposition5 = (BlockPosition) iterator.next(); + Block block2 = world.getType(blockposition5).getBlock(); + + world.update(blockposition5, block2); + } + + if (j <= 0) { + throw new CommandException("commands.fill.failed", new Object[0]); + } else { + icommandlistener.a(CommandObjectiveExecutor.EnumCommandResult.AFFECTED_BLOCKS, j); + a(icommandlistener, this, "commands.fill.success", new Object[] { Integer.valueOf(j)}); + } + } else { + throw new CommandException("commands.fill.outOfWorld", new Object[0]); + } + } + } + + public List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { + return astring.length > 0 && astring.length <= 3 ? a(astring, 0, blockposition) : (astring.length > 3 && astring.length <= 6 ? a(astring, 3, blockposition) : (astring.length == 7 ? a(astring, (Collection) Block.REGISTRY.keySet()) : (astring.length == 9 ? a(astring, new String[] { "replace", "destroy", "keep", "hollow", "outline"}) : (astring.length == 10 && "replace".equals(astring[8]) ? a(astring, (Collection) Block.REGISTRY.keySet()) : null)))); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandGamemode.java b/azurite-server/src/main/java/net/minecraft/server/CommandGamemode.java new file mode 100644 index 0000000..ca2aba5 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandGamemode.java @@ -0,0 +1,80 @@ +package net.minecraft.server; + +import java.util.Arrays; +import java.util.List; + +public class CommandGamemode extends CommandAbstract { + + public CommandGamemode() {} + + public String getCommand() { + return "gamemode"; + } + + public int a() { + return 2; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.gamemode.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + if (astring.length <= 0) { + throw new ExceptionUsage("commands.gamemode.usage", new Object[0]); + } else { + WorldSettings.EnumGamemode worldsettings_enumgamemode = this.h(icommandlistener, astring[0]); + EntityPlayer entityplayer = astring.length >= 2 ? a(icommandlistener, astring[1]) : b(icommandlistener); + + entityplayer.a(worldsettings_enumgamemode); + // CraftBukkit start - handle event cancelling the change + if (entityplayer.playerInteractManager.getGameMode() != worldsettings_enumgamemode) { + icommandlistener.sendMessage(new ChatComponentText("Failed to set the gamemode of '" + entityplayer.getName() + "'")); + return; + } + // CraftBukkit end + + entityplayer.fallDistance = 0.0F; + if (icommandlistener.getWorld().getGameRules().getBoolean("sendCommandFeedback")) { + entityplayer.sendMessage(new ChatMessage("gameMode.changed", new Object[0])); + } + + ChatMessage chatmessage = new ChatMessage("gameMode." + worldsettings_enumgamemode.b(), new Object[0]); + + if (entityplayer != icommandlistener) { + a(icommandlistener, this, 1, "commands.gamemode.success.other", new Object[] { entityplayer.getName(), chatmessage}); + } else { + a(icommandlistener, this, 1, "commands.gamemode.success.self", new Object[] { chatmessage}); + } + + } + } + + protected WorldSettings.EnumGamemode h(ICommandListener icommandlistener, String s) throws ExceptionInvalidNumber { + return !s.equalsIgnoreCase(WorldSettings.EnumGamemode.SURVIVAL.b()) && !s.equalsIgnoreCase("s") ? (!s.equalsIgnoreCase(WorldSettings.EnumGamemode.CREATIVE.b()) && !s.equalsIgnoreCase("c") ? (!s.equalsIgnoreCase(WorldSettings.EnumGamemode.ADVENTURE.b()) && !s.equalsIgnoreCase("a") ? (!s.equalsIgnoreCase(WorldSettings.EnumGamemode.SPECTATOR.b()) && !s.equalsIgnoreCase("sp") ? WorldSettings.a(a(s, 0, WorldSettings.EnumGamemode.values().length - 2)) : WorldSettings.EnumGamemode.SPECTATOR) : WorldSettings.EnumGamemode.ADVENTURE) : WorldSettings.EnumGamemode.CREATIVE) : WorldSettings.EnumGamemode.SURVIVAL; + } + + public List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { + return astring.length == 1 ? a(astring, new String[] { "survival", "creative", "adventure", "spectator"}) : (astring.length == 2 ? a(astring, this.d()) : null); + } + + protected String[] d() { + return MinecraftServer.getServer().getPlayers(); + } + + public boolean isListStart(String[] astring, int i) { + return i == 1; + } + + @Override + public List b() { + return Arrays.asList("gm"); + } + + // CraftBukkit start - fix decompiler error + @Override + public int compareTo(ICommand o) { + return a((ICommand) o); + } + // CraftBukkit end +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandGamemodeDefault.java b/azurite-server/src/main/java/net/minecraft/server/CommandGamemodeDefault.java new file mode 100644 index 0000000..a4c96f2 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandGamemodeDefault.java @@ -0,0 +1,49 @@ +package net.minecraft.server; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +public class CommandGamemodeDefault extends CommandGamemode { + + public CommandGamemodeDefault() {} + + public String getCommand() { + return "defaultgamemode"; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.defaultgamemode.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + if (astring.length <= 0) { + throw new ExceptionUsage("commands.defaultgamemode.usage", new Object[0]); + } else { + WorldSettings.EnumGamemode worldsettings_enumgamemode = this.h(icommandlistener, astring[0]); + + this.a(worldsettings_enumgamemode); + a(icommandlistener, this, "commands.defaultgamemode.success", new Object[] { new ChatMessage("gameMode." + worldsettings_enumgamemode.b(), new Object[0])}); + } + } + + @Override + public List b() { + return new ArrayList<>(); + } + + protected void a(WorldSettings.EnumGamemode worldsettings_enumgamemode) { + MinecraftServer minecraftserver = MinecraftServer.getServer(); + + minecraftserver.setGamemode(worldsettings_enumgamemode); + EntityPlayer entityplayer; + + if (minecraftserver.getForceGamemode()) { + for (Iterator iterator = MinecraftServer.getServer().getPlayerList().v().iterator(); iterator.hasNext(); entityplayer.fallDistance = 0.0F) { + entityplayer = (EntityPlayer) iterator.next(); + entityplayer.a(worldsettings_enumgamemode); + } + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandGamerule.java b/azurite-server/src/main/java/net/minecraft/server/CommandGamerule.java new file mode 100644 index 0000000..12a2d6e --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandGamerule.java @@ -0,0 +1,104 @@ +package net.minecraft.server; + +import dev.azurite.spigot.Azurite; +import dev.azurite.spigot.configs.AzuriteConfig; + +import java.util.List; + +public class CommandGamerule extends CommandAbstract { + + public CommandGamerule() { + } + + public static void a(GameRules gamerules, String s) { + if ("reducedDebugInfo".equals(s)) { + int i = gamerules.getBoolean(s) ? 22 : 23; + + for (EntityPlayer entityplayer : MinecraftServer.getServer().getPlayerList().v()) { + entityplayer.playerConnection.sendPacket(new PacketPlayOutEntityStatus(entityplayer, (byte) i)); + } + } + + } + + public String getCommand() { + return "gamerule"; + } + + public int a() { + return 2; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.gamerule.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + GameRules gamerules = icommandlistener.getWorld().getGameRules(); // CraftBukkit - Use current world + String s = astring.length > 0 ? astring[0] : ""; + String s1 = astring.length > 1 ? a(astring, 1) : ""; + + switch (astring.length) { + case 0: + icommandlistener.sendMessage(new ChatComponentText(a(gamerules.getGameRules()))); + break; + + case 1: + if (!gamerules.contains(s)) { + throw new CommandException("commands.gamerule.norule", s); + } + + String s2 = gamerules.get(s); + + icommandlistener.sendMessage((new ChatComponentText(s)).a(" = ").a(s2)); + icommandlistener.a(CommandObjectiveExecutor.EnumCommandResult.QUERY_RESULT, gamerules.c(s)); + break; + + default: + if (gamerules.a(s, GameRules.EnumGameRuleType.BOOLEAN_VALUE) && !"true".equals(s1) && !"false".equals(s1)) { + throw new CommandException("commands.generic.boolean.invalid", s1); + } + + switch (s) { + case "doMobSpawning": { + AzuriteConfig.naturalMobSpawn.set(Boolean.parseBoolean(s1), false); + Azurite.getInstance().getAzuriteConfig().save(false); + } + default: { + gamerules.set(s, s1); + a(gamerules, s); + } + } + + a(icommandlistener, this, "commands.gamerule.success"); + } + + } + + public List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { + if (astring.length == 1) { + return a(astring, this.d().getGameRules()); + } else { + if (astring.length == 2) { + GameRules gamerules = this.d(); + + if (gamerules.a(astring[0], GameRules.EnumGameRuleType.BOOLEAN_VALUE)) { + return a(astring, "true", "false"); + } + } + + return null; + } + } + + private GameRules d() { + return MinecraftServer.getServer().getWorldServer(0).getGameRules(); + } + + // CraftBukkit start - fix decompile error + @Override + public int compareTo(ICommand o) { + return a(o); + } + // CraftBukkit end +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandGive.java b/azurite-server/src/main/java/net/minecraft/server/CommandGive.java new file mode 100644 index 0000000..2449723 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandGive.java @@ -0,0 +1,82 @@ +package net.minecraft.server; + +import java.util.Collection; +import java.util.List; + +public class CommandGive extends CommandAbstract { + + public CommandGive() {} + + public String getCommand() { + return "give"; + } + + public int a() { + return 2; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.give.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + if (astring.length < 2) { + throw new ExceptionUsage("commands.give.usage", new Object[0]); + } else { + EntityPlayer entityplayer = a(icommandlistener, astring[0]); + Item item = f(icommandlistener, astring[1]); + int i = astring.length >= 3 ? a(astring[2], 1, 64) : 1; + int j = astring.length >= 4 ? a(astring[3]) : 0; + ItemStack itemstack = new ItemStack(item, i, j); + + if (astring.length >= 5) { + String s = a(icommandlistener, astring, 4).c(); + + try { + itemstack.setTag(MojangsonParser.parse(s)); + } catch (MojangsonParseException mojangsonparseexception) { + throw new CommandException("commands.give.tagError", new Object[] { mojangsonparseexception.getMessage()}); + } + } + + boolean flag = entityplayer.inventory.pickup(itemstack); + + if (flag) { + entityplayer.world.makeSound(entityplayer, "random.pop", 0.2F, ((entityplayer.bc().nextFloat() - entityplayer.bc().nextFloat()) * 0.7F + 1.0F) * 2.0F); + entityplayer.defaultContainer.b(); + } + + EntityItem entityitem; + + if (flag && itemstack.count <= 0) { + itemstack.count = 1; + icommandlistener.a(CommandObjectiveExecutor.EnumCommandResult.AFFECTED_ITEMS, i); + entityitem = entityplayer.drop(itemstack, false); + if (entityitem != null) { + entityitem.v(); + } + } else { + icommandlistener.a(CommandObjectiveExecutor.EnumCommandResult.AFFECTED_ITEMS, i - itemstack.count); + entityitem = entityplayer.drop(itemstack, false); + if (entityitem != null) { + entityitem.q(); + entityitem.b(entityplayer.getName()); + } + } + + a(icommandlistener, this, "commands.give.success", new Object[] { itemstack.C(), Integer.valueOf(i), entityplayer.getName()}); + } + } + + public List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { + return astring.length == 1 ? a(astring, this.d()) : (astring.length == 2 ? a(astring, (Collection) Item.REGISTRY.keySet()) : null); + } + + protected String[] d() { + return MinecraftServer.getServer().getPlayers(); + } + + public boolean isListStart(String[] astring, int i) { + return i == 0; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandHandler.java b/azurite-server/src/main/java/net/minecraft/server/CommandHandler.java new file mode 100644 index 0000000..f0c7e1f --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandHandler.java @@ -0,0 +1,186 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import com.google.common.collect.Sets; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.Map.Entry; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +public class CommandHandler implements ICommandHandler { + + private static final Logger a = LogManager.getLogger(); + private final Map b = Maps.newHashMap(); + private final Set c = Sets.newHashSet(); + + public CommandHandler() {} + + public int a(ICommandListener icommandlistener, String s) { + s = s.trim(); + if (s.startsWith("/")) { + s = s.substring(1); + } + + String[] astring = s.split(" "); + String s1 = astring[0]; + + astring = a(astring); + ICommand icommand = (ICommand) this.b.get(s1); + int i = this.a(icommand, astring); + int j = 0; + ChatMessage chatmessage; + + if (icommand == null) { + chatmessage = new ChatMessage("commands.generic.notFound", new Object[0]); + chatmessage.getChatModifier().setColor(EnumChatFormat.RED); + icommandlistener.sendMessage(chatmessage); + } else if (icommand.canUse(icommandlistener)) { + if (i > -1) { + List list = PlayerSelector.getPlayers(icommandlistener, astring[i], Entity.class); + String s2 = astring[i]; + + icommandlistener.a(CommandObjectiveExecutor.EnumCommandResult.AFFECTED_ENTITIES, list.size()); + Iterator iterator = list.iterator(); + + while (iterator.hasNext()) { + Entity entity = (Entity) iterator.next(); + + astring[i] = entity.getUniqueID().toString(); + if (this.a(icommandlistener, astring, icommand, s)) { + ++j; + } + } + + astring[i] = s2; + } else { + icommandlistener.a(CommandObjectiveExecutor.EnumCommandResult.AFFECTED_ENTITIES, 1); + if (this.a(icommandlistener, astring, icommand, s)) { + ++j; + } + } + } else { + chatmessage = new ChatMessage("commands.generic.permission", new Object[0]); + chatmessage.getChatModifier().setColor(EnumChatFormat.RED); + icommandlistener.sendMessage(chatmessage); + } + + icommandlistener.a(CommandObjectiveExecutor.EnumCommandResult.SUCCESS_COUNT, j); + return j; + } + + protected boolean a(ICommandListener icommandlistener, String[] astring, ICommand icommand, String s) { + ChatMessage chatmessage; + + try { + icommand.execute(icommandlistener, astring); + return true; + } catch (ExceptionUsage exceptionusage) { + chatmessage = new ChatMessage("commands.generic.usage", new Object[] { new ChatMessage(exceptionusage.getMessage(), exceptionusage.getArgs())}); + chatmessage.getChatModifier().setColor(EnumChatFormat.RED); + icommandlistener.sendMessage(chatmessage); + } catch (CommandException commandexception) { + chatmessage = new ChatMessage(commandexception.getMessage(), commandexception.getArgs()); + chatmessage.getChatModifier().setColor(EnumChatFormat.RED); + icommandlistener.sendMessage(chatmessage); + } catch (Throwable throwable) { + chatmessage = new ChatMessage("commands.generic.exception", new Object[0]); + chatmessage.getChatModifier().setColor(EnumChatFormat.RED); + icommandlistener.sendMessage(chatmessage); + CommandHandler.a.warn("Couldn\'t process command: \'" + s + "\'"); + } + + return false; + } + + public ICommand a(ICommand icommand) { + this.b.put(icommand.getCommand(), icommand); + this.c.add(icommand); + Iterator iterator = icommand.b().iterator(); + + while (iterator.hasNext()) { + String s = (String) iterator.next(); + ICommand icommand1 = (ICommand) this.b.get(s); + + if (icommand1 == null || !icommand1.getCommand().equals(s)) { + this.b.put(s, icommand); + } + } + + return icommand; + } + + private static String[] a(String[] astring) { + String[] astring1 = new String[astring.length - 1]; + + System.arraycopy(astring, 1, astring1, 0, astring.length - 1); + return astring1; + } + + public List a(ICommandListener icommandlistener, String s, BlockPosition blockposition) { + String[] astring = s.split(" ", -1); + String s1 = astring[0]; + + if (astring.length == 1) { + ArrayList arraylist = Lists.newArrayList(); + Iterator iterator = this.b.entrySet().iterator(); + + while (iterator.hasNext()) { + Entry entry = (Entry) iterator.next(); + + if (CommandAbstract.a(s1, (String) entry.getKey()) && ((ICommand) entry.getValue()).canUse(icommandlistener)) { + arraylist.add(entry.getKey()); + } + } + + return arraylist; + } else { + if (astring.length > 1) { + ICommand icommand = (ICommand) this.b.get(s1); + + if (icommand != null && icommand.canUse(icommandlistener)) { + return icommand.tabComplete(icommandlistener, a(astring), blockposition); + } + } + + return null; + } + } + + public List a(ICommandListener icommandlistener) { + ArrayList arraylist = Lists.newArrayList(); + Iterator iterator = this.c.iterator(); + + while (iterator.hasNext()) { + ICommand icommand = (ICommand) iterator.next(); + + if (icommand.canUse(icommandlistener)) { + arraylist.add(icommand); + } + } + + return arraylist; + } + + public Map getCommands() { + return this.b; + } + + private int a(ICommand icommand, String[] astring) { + if (icommand == null) { + return -1; + } else { + for (int i = 0; i < astring.length; ++i) { + if (icommand.isListStart(astring, i) && PlayerSelector.isList(astring[i])) { + return i; + } + } + + return -1; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandHelp.java b/azurite-server/src/main/java/net/minecraft/server/CommandHelp.java new file mode 100644 index 0000000..b490b13 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandHelp.java @@ -0,0 +1,97 @@ +package net.minecraft.server; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Set; + +public class CommandHelp extends CommandAbstract { + + public CommandHelp() {} + + public String getCommand() { + return "help"; + } + + public int a() { + return 0; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.help.usage"; + } + + public List b() { + return Arrays.asList(new String[] { "?"}); + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + List list = this.d(icommandlistener); + boolean flag = true; + int i = (list.size() - 1) / 7; + boolean flag1 = false; + + int j; + + try { + j = astring.length == 0 ? 0 : a(astring[0], 1, i + 1) - 1; + } catch (ExceptionInvalidNumber exceptioninvalidnumber) { + Map map = this.d(); + ICommand icommand = (ICommand) map.get(astring[0]); + + if (icommand != null) { + throw new ExceptionUsage(icommand.getUsage(icommandlistener), new Object[0]); + } + + if (MathHelper.a(astring[0], -1) != -1) { + throw exceptioninvalidnumber; + } + + throw new ExceptionUnknownCommand(); + } + + int k = Math.min((j + 1) * 7, list.size()); + ChatMessage chatmessage = new ChatMessage("commands.help.header", new Object[] { Integer.valueOf(j + 1), Integer.valueOf(i + 1)}); + + chatmessage.getChatModifier().setColor(EnumChatFormat.DARK_GREEN); + icommandlistener.sendMessage(chatmessage); + + for (int l = j * 7; l < k; ++l) { + ICommand icommand1 = (ICommand) list.get(l); + ChatMessage chatmessage1 = new ChatMessage(icommand1.getUsage(icommandlistener), new Object[0]); + + chatmessage1.getChatModifier().setChatClickable(new ChatClickable(ChatClickable.EnumClickAction.SUGGEST_COMMAND, "/" + icommand1.getCommand() + " ")); + icommandlistener.sendMessage(chatmessage1); + } + + if (j == 0 && icommandlistener instanceof EntityHuman) { + ChatMessage chatmessage2 = new ChatMessage("commands.help.footer", new Object[0]); + + chatmessage2.getChatModifier().setColor(EnumChatFormat.GREEN); + icommandlistener.sendMessage(chatmessage2); + } + + } + + protected List d(ICommandListener icommandlistener) { + List list = MinecraftServer.getServer().getCommandHandler().a(icommandlistener); + + Collections.sort(list); + return list; + } + + protected Map d() { + return MinecraftServer.getServer().getCommandHandler().getCommands(); + } + + public List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { + if (astring.length == 1) { + Set set = this.d().keySet(); + + return a(astring, (String[]) set.toArray(new String[set.size()])); + } else { + return null; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandIdleTimeout.java b/azurite-server/src/main/java/net/minecraft/server/CommandIdleTimeout.java new file mode 100644 index 0000000..2d11e2e --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandIdleTimeout.java @@ -0,0 +1,29 @@ +package net.minecraft.server; + +public class CommandIdleTimeout extends CommandAbstract { + + public CommandIdleTimeout() {} + + public String getCommand() { + return "setidletimeout"; + } + + public int a() { + return 3; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.setidletimeout.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + if (astring.length != 1) { + throw new ExceptionUsage("commands.setidletimeout.usage", new Object[0]); + } else { + int i = a(astring[0], 0); + + MinecraftServer.getServer().setIdleTimeout(i); + a(icommandlistener, this, "commands.setidletimeout.success", new Object[] { Integer.valueOf(i)}); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandKick.java b/azurite-server/src/main/java/net/minecraft/server/CommandKick.java new file mode 100644 index 0000000..909087d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandKick.java @@ -0,0 +1,51 @@ +package net.minecraft.server; + +import java.util.List; + +public class CommandKick extends CommandAbstract { + + public CommandKick() {} + + public String getCommand() { + return "kick"; + } + + public int a() { + return 3; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.kick.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + if (astring.length > 0 && astring[0].length() > 1) { + EntityPlayer entityplayer = MinecraftServer.getServer().getPlayerList().getPlayer(astring[0]); + String s = "Kicked by an operator."; + boolean flag = false; + + if (entityplayer == null) { + throw new ExceptionPlayerNotFound(); + } else { + if (astring.length >= 2) { + s = a(icommandlistener, astring, 1).c(); + flag = true; + } + + entityplayer.playerConnection.disconnect(s); + if (flag) { + a(icommandlistener, this, "commands.kick.success.reason", new Object[] { entityplayer.getName(), s}); + } else { + a(icommandlistener, this, "commands.kick.success", new Object[] { entityplayer.getName()}); + } + + } + } else { + throw new ExceptionUsage("commands.kick.usage", new Object[0]); + } + } + + public List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { + return astring.length >= 1 ? a(astring, MinecraftServer.getServer().getPlayers()) : null; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandKill.java b/azurite-server/src/main/java/net/minecraft/server/CommandKill.java new file mode 100644 index 0000000..682909b --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandKill.java @@ -0,0 +1,42 @@ +package net.minecraft.server; + +import java.util.List; + +public class CommandKill extends CommandAbstract { + + public CommandKill() {} + + public String getCommand() { + return "kill"; + } + + public int a() { + return 2; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.kill.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + if (astring.length == 0) { + EntityPlayer entityplayer = b(icommandlistener); + + entityplayer.G(); + a(icommandlistener, this, "commands.kill.successful", new Object[] { entityplayer.getScoreboardDisplayName()}); + } else { + Entity entity = b(icommandlistener, astring[0]); + + entity.G(); + a(icommandlistener, this, "commands.kill.successful", new Object[] { entity.getScoreboardDisplayName()}); + } + } + + public boolean isListStart(String[] astring, int i) { + return i == 0; + } + + public List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { + return astring.length == 1 ? a(astring, MinecraftServer.getServer().getPlayers()) : null; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandList.java b/azurite-server/src/main/java/net/minecraft/server/CommandList.java new file mode 100644 index 0000000..f72f4bc --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandList.java @@ -0,0 +1,26 @@ +package net.minecraft.server; + +public class CommandList extends CommandAbstract { + + public CommandList() {} + + public String getCommand() { + return "list"; + } + + public int a() { + return 0; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.players.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + int i = MinecraftServer.getServer().I(); + + icommandlistener.sendMessage(new ChatMessage("commands.players.list", new Object[] { Integer.valueOf(i), Integer.valueOf(MinecraftServer.getServer().J())})); + icommandlistener.sendMessage(new ChatComponentText(MinecraftServer.getServer().getPlayerList().b(astring.length > 0 && "uuids".equalsIgnoreCase(astring[0])))); + icommandlistener.a(CommandObjectiveExecutor.EnumCommandResult.QUERY_RESULT, i); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandMe.java b/azurite-server/src/main/java/net/minecraft/server/CommandMe.java new file mode 100644 index 0000000..a1bb5a4 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandMe.java @@ -0,0 +1,34 @@ +package net.minecraft.server; + +import java.util.List; + +public class CommandMe extends CommandAbstract { + + public CommandMe() {} + + public String getCommand() { + return "me"; + } + + public int a() { + return 0; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.me.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + if (astring.length <= 0) { + throw new ExceptionUsage("commands.me.usage", new Object[0]); + } else { + IChatBaseComponent ichatbasecomponent = b(icommandlistener, astring, 0, !(icommandlistener instanceof EntityHuman)); + + MinecraftServer.getServer().getPlayerList().sendMessage(new ChatMessage("chat.type.emote", new Object[] { icommandlistener.getScoreboardDisplayName(), ichatbasecomponent})); + } + } + + public List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { + return a(astring, MinecraftServer.getServer().getPlayers()); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandObjectiveExecutor.java b/azurite-server/src/main/java/net/minecraft/server/CommandObjectiveExecutor.java new file mode 100644 index 0000000..53bf236 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandObjectiveExecutor.java @@ -0,0 +1,231 @@ +package net.minecraft.server; + +public class CommandObjectiveExecutor { + + private static final int a = CommandObjectiveExecutor.EnumCommandResult.values().length; + private static final String[] b = new String[CommandObjectiveExecutor.a]; + private String[] c; + private String[] d; + + public CommandObjectiveExecutor() { + this.c = CommandObjectiveExecutor.b; + this.d = CommandObjectiveExecutor.b; + } + + public void a(final ICommandListener icommandlistener, CommandObjectiveExecutor.EnumCommandResult commandobjectiveexecutor_enumcommandresult, int i) { + String s = this.c[commandobjectiveexecutor_enumcommandresult.a()]; + + if (s != null) { + ICommandListener icommandlistener1 = new ICommandListener() { + public String getName() { + return icommandlistener.getName(); + } + + public IChatBaseComponent getScoreboardDisplayName() { + return icommandlistener.getScoreboardDisplayName(); + } + + public void sendMessage(IChatBaseComponent ichatbasecomponent) { + icommandlistener.sendMessage(ichatbasecomponent); + } + + public boolean a(int i, String s) { + return true; + } + + public BlockPosition getChunkCoordinates() { + return icommandlistener.getChunkCoordinates(); + } + + public Vec3D d() { + return icommandlistener.d(); + } + + public World getWorld() { + return icommandlistener.getWorld(); + } + + public Entity f() { + return icommandlistener.f(); + } + + public boolean getSendCommandFeedback() { + return icommandlistener.getSendCommandFeedback(); + } + + public void a(CommandObjectiveExecutor.EnumCommandResult commandobjectiveexecutor_enumcommandresult, int i) { + icommandlistener.a(commandobjectiveexecutor_enumcommandresult, i); + } + }; + + String s1; + + try { + s1 = CommandAbstract.e(icommandlistener1, s); + } catch (ExceptionEntityNotFound exceptionentitynotfound) { + return; + } + + String s2 = this.d[commandobjectiveexecutor_enumcommandresult.a()]; + + if (s2 != null) { + Scoreboard scoreboard = icommandlistener.getWorld().getScoreboard(); + ScoreboardObjective scoreboardobjective = scoreboard.getObjective(s2); + + if (scoreboardobjective != null) { + if (scoreboard.b(s1, scoreboardobjective)) { + ScoreboardScore scoreboardscore = scoreboard.getPlayerScoreForObjective(s1, scoreboardobjective); + + scoreboardscore.setScore(i); + } + } + } + } + } + + public void a(NBTTagCompound nbttagcompound) { + if (nbttagcompound.hasKeyOfType("CommandStats", 10)) { + NBTTagCompound nbttagcompound1 = nbttagcompound.getCompound("CommandStats"); + CommandObjectiveExecutor.EnumCommandResult[] acommandobjectiveexecutor_enumcommandresult = CommandObjectiveExecutor.EnumCommandResult.values(); + int i = acommandobjectiveexecutor_enumcommandresult.length; + + for (int j = 0; j < i; ++j) { + CommandObjectiveExecutor.EnumCommandResult commandobjectiveexecutor_enumcommandresult = acommandobjectiveexecutor_enumcommandresult[j]; + String s = commandobjectiveexecutor_enumcommandresult.b() + "Name"; + String s1 = commandobjectiveexecutor_enumcommandresult.b() + "Objective"; + + if (nbttagcompound1.hasKeyOfType(s, 8) && nbttagcompound1.hasKeyOfType(s1, 8)) { + String s2 = nbttagcompound1.getString(s); + String s3 = nbttagcompound1.getString(s1); + + a(this, commandobjectiveexecutor_enumcommandresult, s2, s3); + } + } + + } + } + + public void b(NBTTagCompound nbttagcompound) { + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + CommandObjectiveExecutor.EnumCommandResult[] acommandobjectiveexecutor_enumcommandresult = CommandObjectiveExecutor.EnumCommandResult.values(); + int i = acommandobjectiveexecutor_enumcommandresult.length; + + for (int j = 0; j < i; ++j) { + CommandObjectiveExecutor.EnumCommandResult commandobjectiveexecutor_enumcommandresult = acommandobjectiveexecutor_enumcommandresult[j]; + String s = this.c[commandobjectiveexecutor_enumcommandresult.a()]; + String s1 = this.d[commandobjectiveexecutor_enumcommandresult.a()]; + + if (s != null && s1 != null) { + nbttagcompound1.setString(commandobjectiveexecutor_enumcommandresult.b() + "Name", s); + nbttagcompound1.setString(commandobjectiveexecutor_enumcommandresult.b() + "Objective", s1); + } + } + + if (!nbttagcompound1.isEmpty()) { + nbttagcompound.set("CommandStats", nbttagcompound1); + } + + } + + public static void a(CommandObjectiveExecutor commandobjectiveexecutor, CommandObjectiveExecutor.EnumCommandResult commandobjectiveexecutor_enumcommandresult, String s, String s1) { + if (s != null && s.length() != 0 && s1 != null && s1.length() != 0) { + if (commandobjectiveexecutor.c == CommandObjectiveExecutor.b || commandobjectiveexecutor.d == CommandObjectiveExecutor.b) { + commandobjectiveexecutor.c = new String[CommandObjectiveExecutor.a]; + commandobjectiveexecutor.d = new String[CommandObjectiveExecutor.a]; + } + + commandobjectiveexecutor.c[commandobjectiveexecutor_enumcommandresult.a()] = s; + commandobjectiveexecutor.d[commandobjectiveexecutor_enumcommandresult.a()] = s1; + } else { + a(commandobjectiveexecutor, commandobjectiveexecutor_enumcommandresult); + } + } + + private static void a(CommandObjectiveExecutor commandobjectiveexecutor, CommandObjectiveExecutor.EnumCommandResult commandobjectiveexecutor_enumcommandresult) { + if (commandobjectiveexecutor.c != CommandObjectiveExecutor.b && commandobjectiveexecutor.d != CommandObjectiveExecutor.b) { + commandobjectiveexecutor.c[commandobjectiveexecutor_enumcommandresult.a()] = null; + commandobjectiveexecutor.d[commandobjectiveexecutor_enumcommandresult.a()] = null; + boolean flag = true; + CommandObjectiveExecutor.EnumCommandResult[] acommandobjectiveexecutor_enumcommandresult = CommandObjectiveExecutor.EnumCommandResult.values(); + int i = acommandobjectiveexecutor_enumcommandresult.length; + + for (int j = 0; j < i; ++j) { + CommandObjectiveExecutor.EnumCommandResult commandobjectiveexecutor_enumcommandresult1 = acommandobjectiveexecutor_enumcommandresult[j]; + + if (commandobjectiveexecutor.c[commandobjectiveexecutor_enumcommandresult1.a()] != null && commandobjectiveexecutor.d[commandobjectiveexecutor_enumcommandresult1.a()] != null) { + flag = false; + break; + } + } + + if (flag) { + commandobjectiveexecutor.c = CommandObjectiveExecutor.b; + commandobjectiveexecutor.d = CommandObjectiveExecutor.b; + } + + } + } + + public void a(CommandObjectiveExecutor commandobjectiveexecutor) { + CommandObjectiveExecutor.EnumCommandResult[] acommandobjectiveexecutor_enumcommandresult = CommandObjectiveExecutor.EnumCommandResult.values(); + int i = acommandobjectiveexecutor_enumcommandresult.length; + + for (int j = 0; j < i; ++j) { + CommandObjectiveExecutor.EnumCommandResult commandobjectiveexecutor_enumcommandresult = acommandobjectiveexecutor_enumcommandresult[j]; + + a(this, commandobjectiveexecutor_enumcommandresult, commandobjectiveexecutor.c[commandobjectiveexecutor_enumcommandresult.a()], commandobjectiveexecutor.d[commandobjectiveexecutor_enumcommandresult.a()]); + } + + } + + public static enum EnumCommandResult { + + SUCCESS_COUNT(0, "SuccessCount"), AFFECTED_BLOCKS(1, "AffectedBlocks"), AFFECTED_ENTITIES(2, "AffectedEntities"), AFFECTED_ITEMS(3, "AffectedItems"), QUERY_RESULT(4, "QueryResult"); + + final int f; + final String g; + + private EnumCommandResult(int i, String s) { + this.f = i; + this.g = s; + } + + public int a() { + return this.f; + } + + public String b() { + return this.g; + } + + public static String[] c() { + String[] astring = new String[values().length]; + int i = 0; + CommandObjectiveExecutor.EnumCommandResult[] acommandobjectiveexecutor_enumcommandresult = values(); + int j = acommandobjectiveexecutor_enumcommandresult.length; + + for (int k = 0; k < j; ++k) { + CommandObjectiveExecutor.EnumCommandResult commandobjectiveexecutor_enumcommandresult = acommandobjectiveexecutor_enumcommandresult[k]; + + astring[i++] = commandobjectiveexecutor_enumcommandresult.b(); + } + + return astring; + } + + public static CommandObjectiveExecutor.EnumCommandResult a(String s) { + CommandObjectiveExecutor.EnumCommandResult[] acommandobjectiveexecutor_enumcommandresult = values(); + int i = acommandobjectiveexecutor_enumcommandresult.length; + + for (int j = 0; j < i; ++j) { + CommandObjectiveExecutor.EnumCommandResult commandobjectiveexecutor_enumcommandresult = acommandobjectiveexecutor_enumcommandresult[j]; + + if (commandobjectiveexecutor_enumcommandresult.b().equals(s)) { + return commandobjectiveexecutor_enumcommandresult; + } + } + + return null; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandOp.java b/azurite-server/src/main/java/net/minecraft/server/CommandOp.java new file mode 100644 index 0000000..dedac55 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandOp.java @@ -0,0 +1,60 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; +import com.mojang.authlib.GameProfile; +import java.util.ArrayList; +import java.util.List; + +public class CommandOp extends CommandAbstract { + + public CommandOp() {} + + public String getCommand() { + return "op"; + } + + public int a() { + return 3; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.op.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + if (astring.length == 1 && astring[0].length() > 0) { + MinecraftServer minecraftserver = MinecraftServer.getServer(); + GameProfile gameprofile = minecraftserver.getUserCache().getProfile(astring[0]); + + if (gameprofile == null) { + throw new CommandException("commands.op.failed", new Object[] { astring[0]}); + } else { + minecraftserver.getPlayerList().addOp(gameprofile); + a(icommandlistener, this, "commands.op.success", new Object[] { astring[0]}); + } + } else { + throw new ExceptionUsage("commands.op.usage", new Object[0]); + } + } + + public List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { + if (astring.length == 1) { + String s = astring[astring.length - 1]; + ArrayList arraylist = Lists.newArrayList(); + GameProfile[] agameprofile = MinecraftServer.getServer().L(); + int i = agameprofile.length; + + for (int j = 0; j < i; ++j) { + GameProfile gameprofile = agameprofile[j]; + + if (!MinecraftServer.getServer().getPlayerList().isOp(gameprofile) && a(s, gameprofile.getName())) { + arraylist.add(gameprofile.getName()); + } + } + + return arraylist; + } else { + return null; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandPardon.java b/azurite-server/src/main/java/net/minecraft/server/CommandPardon.java new file mode 100644 index 0000000..dd507b2 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandPardon.java @@ -0,0 +1,45 @@ +package net.minecraft.server; + +import com.mojang.authlib.GameProfile; +import java.util.List; + +public class CommandPardon extends CommandAbstract { + + public CommandPardon() {} + + public String getCommand() { + return "pardon"; + } + + public int a() { + return 3; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.unban.usage"; + } + + public boolean canUse(ICommandListener icommandlistener) { + return MinecraftServer.getServer().getPlayerList().getProfileBans().isEnabled() && super.canUse(icommandlistener); + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + if (astring.length == 1 && astring[0].length() > 0) { + MinecraftServer minecraftserver = MinecraftServer.getServer(); + GameProfile gameprofile = minecraftserver.getPlayerList().getProfileBans().a(astring[0]); + + if (gameprofile == null) { + throw new CommandException("commands.unban.failed", new Object[] { astring[0]}); + } else { + minecraftserver.getPlayerList().getProfileBans().remove(gameprofile); + a(icommandlistener, this, "commands.unban.success", new Object[] { astring[0]}); + } + } else { + throw new ExceptionUsage("commands.unban.usage", new Object[0]); + } + } + + public List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { + return astring.length == 1 ? a(astring, MinecraftServer.getServer().getPlayerList().getProfileBans().getEntries()) : null; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandPardonIP.java b/azurite-server/src/main/java/net/minecraft/server/CommandPardonIP.java new file mode 100644 index 0000000..843513c --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandPardonIP.java @@ -0,0 +1,44 @@ +package net.minecraft.server; + +import java.util.List; +import java.util.regex.Matcher; + +public class CommandPardonIP extends CommandAbstract { + + public CommandPardonIP() {} + + public String getCommand() { + return "pardon-ip"; + } + + public int a() { + return 3; + } + + public boolean canUse(ICommandListener icommandlistener) { + return MinecraftServer.getServer().getPlayerList().getIPBans().isEnabled() && super.canUse(icommandlistener); + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.unbanip.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + if (astring.length == 1 && astring[0].length() > 1) { + Matcher matcher = CommandBanIp.a.matcher(astring[0]); + + if (matcher.matches()) { + MinecraftServer.getServer().getPlayerList().getIPBans().remove(astring[0]); + a(icommandlistener, this, "commands.unbanip.success", new Object[] { astring[0]}); + } else { + throw new ExceptionInvalidSyntax("commands.unbanip.invalid", new Object[0]); + } + } else { + throw new ExceptionUsage("commands.unbanip.usage", new Object[0]); + } + } + + public List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { + return astring.length == 1 ? a(astring, MinecraftServer.getServer().getPlayerList().getIPBans().getEntries()) : null; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandParticle.java b/azurite-server/src/main/java/net/minecraft/server/CommandParticle.java new file mode 100644 index 0000000..4fd20bb --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandParticle.java @@ -0,0 +1,99 @@ +package net.minecraft.server; + +import java.util.List; + +public class CommandParticle extends CommandAbstract { + + public CommandParticle() {} + + public String getCommand() { + return "particle"; + } + + public int a() { + return 2; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.particle.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + if (astring.length < 8) { + throw new ExceptionUsage("commands.particle.usage", new Object[0]); + } else { + boolean flag = false; + EnumParticle enumparticle = null; + EnumParticle[] aenumparticle = EnumParticle.values(); + int i = aenumparticle.length; + + for (int j = 0; j < i; ++j) { + EnumParticle enumparticle1 = aenumparticle[j]; + + if (enumparticle1.f()) { + if (astring[0].startsWith(enumparticle1.b())) { + flag = true; + enumparticle = enumparticle1; + break; + } + } else if (astring[0].equals(enumparticle1.b())) { + flag = true; + enumparticle = enumparticle1; + break; + } + } + + if (!flag) { + throw new CommandException("commands.particle.notFound", new Object[] { astring[0]}); + } else { + String s = astring[0]; + Vec3D vec3d = icommandlistener.d(); + double d0 = (double) ((float) b(vec3d.a, astring[1], true)); + double d1 = (double) ((float) b(vec3d.b, astring[2], true)); + double d2 = (double) ((float) b(vec3d.c, astring[3], true)); + double d3 = (double) ((float) c(astring[4])); + double d4 = (double) ((float) c(astring[5])); + double d5 = (double) ((float) c(astring[6])); + double d6 = (double) ((float) c(astring[7])); + int k = 0; + + if (astring.length > 8) { + k = a(astring[8], 0); + } + + boolean flag1 = false; + + if (astring.length > 9 && "force".equals(astring[9])) { + flag1 = true; + } + + World world = icommandlistener.getWorld(); + + if (world instanceof WorldServer) { + WorldServer worldserver = (WorldServer) world; + int[] aint = new int[enumparticle.d()]; + + if (enumparticle.f()) { + String[] astring1 = astring[0].split("_", 3); + + for (int l = 1; l < astring1.length; ++l) { + try { + aint[l - 1] = Integer.parseInt(astring1[l]); + } catch (NumberFormatException numberformatexception) { + throw new CommandException("commands.particle.notFound", new Object[] { astring[0]}); + } + } + } + + worldserver.a(enumparticle, flag1, d0, d1, d2, k, d3, d4, d5, d6, aint); + a(icommandlistener, this, "commands.particle.success", new Object[] { s, Integer.valueOf(Math.max(k, 1))}); + } + + } + } + } + + public List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { + return astring.length == 1 ? a(astring, EnumParticle.a()) : (astring.length > 1 && astring.length <= 4 ? a(astring, 1, blockposition) : (astring.length == 10 ? a(astring, new String[] { "normal", "force"}) : null)); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandPlaySound.java b/azurite-server/src/main/java/net/minecraft/server/CommandPlaySound.java new file mode 100644 index 0000000..5d051ff --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandPlaySound.java @@ -0,0 +1,100 @@ +package net.minecraft.server; + +import java.util.List; + +public class CommandPlaySound extends CommandAbstract { + + public CommandPlaySound() {} + + public String getCommand() { + return "playsound"; + } + + public int a() { + return 2; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.playsound.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + if (astring.length < 2) { + throw new ExceptionUsage(this.getUsage(icommandlistener), new Object[0]); + } else { + byte b0 = 0; + int i = b0 + 1; + String s = astring[b0]; + EntityPlayer entityplayer = a(icommandlistener, astring[i++]); + Vec3D vec3d = icommandlistener.d(); + double d0 = vec3d.a; + + if (astring.length > i) { + d0 = b(d0, astring[i++], true); + } + + double d1 = vec3d.b; + + if (astring.length > i) { + d1 = b(d1, astring[i++], 0, 0, false); + } + + double d2 = vec3d.c; + + if (astring.length > i) { + d2 = b(d2, astring[i++], true); + } + + double d3 = 1.0D; + + if (astring.length > i) { + d3 = a(astring[i++], 0.0D, 3.4028234663852886E38D); + } + + double d4 = 1.0D; + + if (astring.length > i) { + d4 = a(astring[i++], 0.0D, 2.0D); + } + + double d5 = 0.0D; + + if (astring.length > i) { + d5 = a(astring[i], 0.0D, 1.0D); + } + + double d6 = d3 > 1.0D ? d3 * 16.0D : 16.0D; + double d7 = entityplayer.f(d0, d1, d2); + + if (d7 > d6) { + if (d5 <= 0.0D) { + throw new CommandException("commands.playsound.playerTooFar", new Object[] { entityplayer.getName()}); + } + + double d8 = d0 - entityplayer.locX; + double d9 = d1 - entityplayer.locY; + double d10 = d2 - entityplayer.locZ; + double d11 = Math.sqrt(d8 * d8 + d9 * d9 + d10 * d10); + + if (d11 > 0.0D) { + d0 = entityplayer.locX + d8 / d11 * 2.0D; + d1 = entityplayer.locY + d9 / d11 * 2.0D; + d2 = entityplayer.locZ + d10 / d11 * 2.0D; + } + + d3 = d5; + } + + entityplayer.playerConnection.sendPacket(new PacketPlayOutNamedSoundEffect(s, d0, d1, d2, (float) d3, (float) d4)); + a(icommandlistener, this, "commands.playsound.success", new Object[] { s, entityplayer.getName()}); + } + } + + public List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { + return astring.length == 2 ? a(astring, MinecraftServer.getServer().getPlayers()) : (astring.length > 2 && astring.length <= 5 ? a(astring, 2, blockposition) : null); + } + + public boolean isListStart(String[] astring, int i) { + return i == 1; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandPublish.java b/azurite-server/src/main/java/net/minecraft/server/CommandPublish.java new file mode 100644 index 0000000..0800672 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandPublish.java @@ -0,0 +1,25 @@ +package net.minecraft.server; + +public class CommandPublish extends CommandAbstract { + + public CommandPublish() {} + + public String getCommand() { + return "publish"; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.publish.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + String s = MinecraftServer.getServer().a(WorldSettings.EnumGamemode.SURVIVAL, false); + + if (s != null) { + a(icommandlistener, this, "commands.publish.started", new Object[] { s}); + } else { + a(icommandlistener, this, "commands.publish.failed", new Object[0]); + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandReplaceItem.java b/azurite-server/src/main/java/net/minecraft/server/CommandReplaceItem.java new file mode 100644 index 0000000..4f6b19b --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandReplaceItem.java @@ -0,0 +1,185 @@ +package net.minecraft.server; + +import com.google.common.collect.Maps; +import java.util.Collection; +import java.util.List; +import java.util.Map; + +public class CommandReplaceItem extends CommandAbstract { + + private static final Map a = Maps.newHashMap(); + + public CommandReplaceItem() {} + + public String getCommand() { + return "replaceitem"; + } + + public int a() { + return 2; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.replaceitem.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + if (astring.length < 1) { + throw new ExceptionUsage("commands.replaceitem.usage", new Object[0]); + } else { + boolean flag; + + if (astring[0].equals("entity")) { + flag = false; + } else { + if (!astring[0].equals("block")) { + throw new ExceptionUsage("commands.replaceitem.usage", new Object[0]); + } + + flag = true; + } + + byte b0; + + if (flag) { + if (astring.length < 6) { + throw new ExceptionUsage("commands.replaceitem.block.usage", new Object[0]); + } + + b0 = 4; + } else { + if (astring.length < 4) { + throw new ExceptionUsage("commands.replaceitem.entity.usage", new Object[0]); + } + + b0 = 2; + } + + int i = b0 + 1; + int j = this.e(astring[b0]); + + Item item; + + try { + item = f(icommandlistener, astring[i]); + } catch (ExceptionInvalidNumber exceptioninvalidnumber) { + if (Block.getByName(astring[i]) != Blocks.AIR) { + throw exceptioninvalidnumber; + } + + item = null; + } + + ++i; + int k = astring.length > i ? a(astring[i++], 1, 64) : 1; + int l = astring.length > i ? a(astring[i++]) : 0; + ItemStack itemstack = new ItemStack(item, k, l); + + if (astring.length > i) { + String s = a(icommandlistener, astring, i).c(); + + try { + itemstack.setTag(MojangsonParser.parse(s)); + } catch (MojangsonParseException mojangsonparseexception) { + throw new CommandException("commands.replaceitem.tagError", new Object[] { mojangsonparseexception.getMessage()}); + } + } + + if (itemstack.getItem() == null) { + itemstack = null; + } + + if (flag) { + icommandlistener.a(CommandObjectiveExecutor.EnumCommandResult.AFFECTED_ITEMS, 0); + BlockPosition blockposition = a(icommandlistener, astring, 1, false); + World world = icommandlistener.getWorld(); + TileEntity tileentity = world.getTileEntity(blockposition); + + if (tileentity == null || !(tileentity instanceof IInventory)) { + throw new CommandException("commands.replaceitem.noContainer", new Object[] { Integer.valueOf(blockposition.getX()), Integer.valueOf(blockposition.getY()), Integer.valueOf(blockposition.getZ())}); + } + + IInventory iinventory = (IInventory) tileentity; + + if (j >= 0 && j < iinventory.getSize()) { + iinventory.setItem(j, itemstack); + } + } else { + Entity entity = b(icommandlistener, astring[1]); + + icommandlistener.a(CommandObjectiveExecutor.EnumCommandResult.AFFECTED_ITEMS, 0); + if (entity instanceof EntityHuman) { + ((EntityHuman) entity).defaultContainer.b(); + } + + if (!entity.d(j, itemstack)) { + throw new CommandException("commands.replaceitem.failed", new Object[] { Integer.valueOf(j), Integer.valueOf(k), itemstack == null ? "Air" : itemstack.C()}); + } + + if (entity instanceof EntityHuman) { + ((EntityHuman) entity).defaultContainer.b(); + } + } + + icommandlistener.a(CommandObjectiveExecutor.EnumCommandResult.AFFECTED_ITEMS, k); + a(icommandlistener, this, "commands.replaceitem.success", new Object[] { Integer.valueOf(j), Integer.valueOf(k), itemstack == null ? "Air" : itemstack.C()}); + } + } + + private int e(String s) throws CommandException { + if (!CommandReplaceItem.a.containsKey(s)) { + throw new CommandException("commands.generic.parameter.invalid", new Object[] { s}); + } else { + return ((Integer) CommandReplaceItem.a.get(s)).intValue(); + } + } + + public List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { + return astring.length == 1 ? a(astring, new String[] { "entity", "block"}) : (astring.length == 2 && astring[0].equals("entity") ? a(astring, this.d()) : (astring.length >= 2 && astring.length <= 4 && astring[0].equals("block") ? a(astring, 1, blockposition) : ((astring.length != 3 || !astring[0].equals("entity")) && (astring.length != 5 || !astring[0].equals("block")) ? ((astring.length != 4 || !astring[0].equals("entity")) && (astring.length != 6 || !astring[0].equals("block")) ? null : a(astring, (Collection) Item.REGISTRY.keySet())) : a(astring, (Collection) CommandReplaceItem.a.keySet())))); + } + + protected String[] d() { + return MinecraftServer.getServer().getPlayers(); + } + + public boolean isListStart(String[] astring, int i) { + return astring.length > 0 && astring[0].equals("entity") && i == 1; + } + + static { + int i; + + for (i = 0; i < 54; ++i) { + CommandReplaceItem.a.put("slot.container." + i, Integer.valueOf(i)); + } + + for (i = 0; i < 9; ++i) { + CommandReplaceItem.a.put("slot.hotbar." + i, Integer.valueOf(i)); + } + + for (i = 0; i < 27; ++i) { + CommandReplaceItem.a.put("slot.inventory." + i, Integer.valueOf(9 + i)); + } + + for (i = 0; i < 27; ++i) { + CommandReplaceItem.a.put("slot.enderchest." + i, Integer.valueOf(200 + i)); + } + + for (i = 0; i < 8; ++i) { + CommandReplaceItem.a.put("slot.villager." + i, Integer.valueOf(300 + i)); + } + + for (i = 0; i < 15; ++i) { + CommandReplaceItem.a.put("slot.horse." + i, Integer.valueOf(500 + i)); + } + + CommandReplaceItem.a.put("slot.weapon", Integer.valueOf(99)); + CommandReplaceItem.a.put("slot.armor.head", Integer.valueOf(103)); + CommandReplaceItem.a.put("slot.armor.chest", Integer.valueOf(102)); + CommandReplaceItem.a.put("slot.armor.legs", Integer.valueOf(101)); + CommandReplaceItem.a.put("slot.armor.feet", Integer.valueOf(100)); + CommandReplaceItem.a.put("slot.horse.saddle", Integer.valueOf(400)); + CommandReplaceItem.a.put("slot.horse.armor", Integer.valueOf(401)); + CommandReplaceItem.a.put("slot.horse.chest", Integer.valueOf(499)); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandSaveAll.java b/azurite-server/src/main/java/net/minecraft/server/CommandSaveAll.java new file mode 100644 index 0000000..62b2e0f --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandSaveAll.java @@ -0,0 +1,60 @@ +package net.minecraft.server; + +public class CommandSaveAll extends CommandAbstract { + + public CommandSaveAll() {} + + public String getCommand() { + return "save-all"; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.save.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + MinecraftServer minecraftserver = MinecraftServer.getServer(); + + icommandlistener.sendMessage(new ChatMessage("commands.save.start", new Object[0])); + if (minecraftserver.getPlayerList() != null) { + minecraftserver.getPlayerList().savePlayers(); + } + + try { + int i; + WorldServer worldserver; + boolean flag; + + for (i = 0; i < minecraftserver.worldServer.length; ++i) { + if (minecraftserver.worldServer[i] != null) { + worldserver = minecraftserver.worldServer[i]; + flag = worldserver.savingDisabled; + worldserver.savingDisabled = false; + worldserver.save(true, (IProgressUpdate) null); + worldserver.savingDisabled = flag; + } + } + + if (astring.length > 0 && "flush".equals(astring[0])) { + icommandlistener.sendMessage(new ChatMessage("commands.save.flushStart", new Object[0])); + + for (i = 0; i < minecraftserver.worldServer.length; ++i) { + if (minecraftserver.worldServer[i] != null) { + worldserver = minecraftserver.worldServer[i]; + flag = worldserver.savingDisabled; + worldserver.savingDisabled = false; + worldserver.flushSave(); + worldserver.savingDisabled = flag; + } + } + + icommandlistener.sendMessage(new ChatMessage("commands.save.flushEnd", new Object[0])); + } + } catch (ExceptionWorldConflict exceptionworldconflict) { + a(icommandlistener, this, "commands.save.failed", new Object[] { exceptionworldconflict.getMessage()}); + return; + } + + a(icommandlistener, this, "commands.save.success", new Object[0]); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandSaveOff.java b/azurite-server/src/main/java/net/minecraft/server/CommandSaveOff.java new file mode 100644 index 0000000..0b490e9 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandSaveOff.java @@ -0,0 +1,36 @@ +package net.minecraft.server; + +public class CommandSaveOff extends CommandAbstract { + + public CommandSaveOff() {} + + public String getCommand() { + return "save-off"; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.save-off.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + MinecraftServer minecraftserver = MinecraftServer.getServer(); + boolean flag = false; + + for (int i = 0; i < minecraftserver.worldServer.length; ++i) { + if (minecraftserver.worldServer[i] != null) { + WorldServer worldserver = minecraftserver.worldServer[i]; + + if (!worldserver.savingDisabled) { + worldserver.savingDisabled = true; + flag = true; + } + } + } + + if (flag) { + a(icommandlistener, this, "commands.save.disabled", new Object[0]); + } else { + throw new CommandException("commands.save-off.alreadyOff", new Object[0]); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandSaveOn.java b/azurite-server/src/main/java/net/minecraft/server/CommandSaveOn.java new file mode 100644 index 0000000..205c5c7 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandSaveOn.java @@ -0,0 +1,36 @@ +package net.minecraft.server; + +public class CommandSaveOn extends CommandAbstract { + + public CommandSaveOn() {} + + public String getCommand() { + return "save-on"; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.save-on.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + MinecraftServer minecraftserver = MinecraftServer.getServer(); + boolean flag = false; + + for (int i = 0; i < minecraftserver.worldServer.length; ++i) { + if (minecraftserver.worldServer[i] != null) { + WorldServer worldserver = minecraftserver.worldServer[i]; + + if (worldserver.savingDisabled) { + worldserver.savingDisabled = false; + flag = true; + } + } + } + + if (flag) { + a(icommandlistener, this, "commands.save.enabled", new Object[0]); + } else { + throw new CommandException("commands.save-on.alreadyOn", new Object[0]); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandSay.java b/azurite-server/src/main/java/net/minecraft/server/CommandSay.java new file mode 100644 index 0000000..501075c --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandSay.java @@ -0,0 +1,34 @@ +package net.minecraft.server; + +import java.util.List; + +public class CommandSay extends CommandAbstract { + + public CommandSay() {} + + public String getCommand() { + return "say"; + } + + public int a() { + return 1; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.say.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + if (astring.length > 0 && astring[0].length() > 0) { + IChatBaseComponent ichatbasecomponent = b(icommandlistener, astring, 0, true); + + MinecraftServer.getServer().getPlayerList().sendMessage(new ChatMessage("chat.type.announcement", new Object[] { icommandlistener.getScoreboardDisplayName(), ichatbasecomponent})); + } else { + throw new ExceptionUsage("commands.say.usage", new Object[0]); + } + } + + public List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { + return astring.length >= 1 ? a(astring, MinecraftServer.getServer().getPlayers()) : null; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandScoreboard.java b/azurite-server/src/main/java/net/minecraft/server/CommandScoreboard.java new file mode 100644 index 0000000..27d08a7 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandScoreboard.java @@ -0,0 +1,1003 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +public class CommandScoreboard extends CommandAbstract { + + public CommandScoreboard() {} + + public String getCommand() { + return "scoreboard"; + } + + public int a() { + return 2; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.scoreboard.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + if (!this.b(icommandlistener, astring)) { + if (astring.length < 1) { + throw new ExceptionUsage("commands.scoreboard.usage", new Object[0]); + } else { + if (astring[0].equalsIgnoreCase("objectives")) { + if (astring.length == 1) { + throw new ExceptionUsage("commands.scoreboard.objectives.usage", new Object[0]); + } + + if (astring[1].equalsIgnoreCase("list")) { + this.d(icommandlistener); + } else if (astring[1].equalsIgnoreCase("add")) { + if (astring.length < 4) { + throw new ExceptionUsage("commands.scoreboard.objectives.add.usage", new Object[0]); + } + + this.b(icommandlistener, astring, 2); + } else if (astring[1].equalsIgnoreCase("remove")) { + if (astring.length != 3) { + throw new ExceptionUsage("commands.scoreboard.objectives.remove.usage", new Object[0]); + } + + this.h(icommandlistener, astring[2]); + } else { + if (!astring[1].equalsIgnoreCase("setdisplay")) { + throw new ExceptionUsage("commands.scoreboard.objectives.usage", new Object[0]); + } + + if (astring.length != 3 && astring.length != 4) { + throw new ExceptionUsage("commands.scoreboard.objectives.setdisplay.usage", new Object[0]); + } + + this.j(icommandlistener, astring, 2); + } + } else if (astring[0].equalsIgnoreCase("players")) { + if (astring.length == 1) { + throw new ExceptionUsage("commands.scoreboard.players.usage", new Object[0]); + } + + if (astring[1].equalsIgnoreCase("list")) { + if (astring.length > 3) { + throw new ExceptionUsage("commands.scoreboard.players.list.usage", new Object[0]); + } + + this.k(icommandlistener, astring, 2); + } else if (astring[1].equalsIgnoreCase("add")) { + if (astring.length < 5) { + throw new ExceptionUsage("commands.scoreboard.players.add.usage", new Object[0]); + } + + this.l(icommandlistener, astring, 2); + } else if (astring[1].equalsIgnoreCase("remove")) { + if (astring.length < 5) { + throw new ExceptionUsage("commands.scoreboard.players.remove.usage", new Object[0]); + } + + this.l(icommandlistener, astring, 2); + } else if (astring[1].equalsIgnoreCase("set")) { + if (astring.length < 5) { + throw new ExceptionUsage("commands.scoreboard.players.set.usage", new Object[0]); + } + + this.l(icommandlistener, astring, 2); + } else if (astring[1].equalsIgnoreCase("reset")) { + if (astring.length != 3 && astring.length != 4) { + throw new ExceptionUsage("commands.scoreboard.players.reset.usage", new Object[0]); + } + + this.m(icommandlistener, astring, 2); + } else if (astring[1].equalsIgnoreCase("enable")) { + if (astring.length != 4) { + throw new ExceptionUsage("commands.scoreboard.players.enable.usage", new Object[0]); + } + + this.n(icommandlistener, astring, 2); + } else if (astring[1].equalsIgnoreCase("test")) { + if (astring.length != 5 && astring.length != 6) { + throw new ExceptionUsage("commands.scoreboard.players.test.usage", new Object[0]); + } + + this.o(icommandlistener, astring, 2); + } else { + if (!astring[1].equalsIgnoreCase("operation")) { + throw new ExceptionUsage("commands.scoreboard.players.usage", new Object[0]); + } + + if (astring.length != 7) { + throw new ExceptionUsage("commands.scoreboard.players.operation.usage", new Object[0]); + } + + this.p(icommandlistener, astring, 2); + } + } else { + if (!astring[0].equalsIgnoreCase("teams")) { + throw new ExceptionUsage("commands.scoreboard.usage", new Object[0]); + } + + if (astring.length == 1) { + throw new ExceptionUsage("commands.scoreboard.teams.usage", new Object[0]); + } + + if (astring[1].equalsIgnoreCase("list")) { + if (astring.length > 3) { + throw new ExceptionUsage("commands.scoreboard.teams.list.usage", new Object[0]); + } + + this.f(icommandlistener, astring, 2); + } else if (astring[1].equalsIgnoreCase("add")) { + if (astring.length < 3) { + throw new ExceptionUsage("commands.scoreboard.teams.add.usage", new Object[0]); + } + + this.c(icommandlistener, astring, 2); + } else if (astring[1].equalsIgnoreCase("remove")) { + if (astring.length != 3) { + throw new ExceptionUsage("commands.scoreboard.teams.remove.usage", new Object[0]); + } + + this.e(icommandlistener, astring, 2); + } else if (astring[1].equalsIgnoreCase("empty")) { + if (astring.length != 3) { + throw new ExceptionUsage("commands.scoreboard.teams.empty.usage", new Object[0]); + } + + this.i(icommandlistener, astring, 2); + } else if (astring[1].equalsIgnoreCase("join")) { + if (astring.length < 4 && (astring.length != 3 || !(icommandlistener instanceof EntityHuman))) { + throw new ExceptionUsage("commands.scoreboard.teams.join.usage", new Object[0]); + } + + this.g(icommandlistener, astring, 2); + } else if (astring[1].equalsIgnoreCase("leave")) { + if (astring.length < 3 && !(icommandlistener instanceof EntityHuman)) { + throw new ExceptionUsage("commands.scoreboard.teams.leave.usage", new Object[0]); + } + + this.h(icommandlistener, astring, 2); + } else { + if (!astring[1].equalsIgnoreCase("option")) { + throw new ExceptionUsage("commands.scoreboard.teams.usage", new Object[0]); + } + + if (astring.length != 4 && astring.length != 5) { + throw new ExceptionUsage("commands.scoreboard.teams.option.usage", new Object[0]); + } + + this.d(icommandlistener, astring, 2); + } + } + + } + } + } + + private boolean b(ICommandListener icommandlistener, String[] astring) throws CommandException { + int i = -1; + + for (int j = 0; j < astring.length; ++j) { + if (this.isListStart(astring, j) && "*".equals(astring[j])) { + if (i >= 0) { + throw new CommandException("commands.scoreboard.noMultiWildcard", new Object[0]); + } + + i = j; + } + } + + if (i < 0) { + return false; + } else { + ArrayList arraylist = Lists.newArrayList(this.d().getPlayers()); + String s = astring[i]; + ArrayList arraylist1 = Lists.newArrayList(); + Iterator iterator = arraylist.iterator(); + + while (iterator.hasNext()) { + String s1 = (String) iterator.next(); + + astring[i] = s1; + + try { + this.execute(icommandlistener, astring); + arraylist1.add(s1); + } catch (CommandException commandexception) { + ChatMessage chatmessage = new ChatMessage(commandexception.getMessage(), commandexception.getArgs()); + + chatmessage.getChatModifier().setColor(EnumChatFormat.RED); + icommandlistener.sendMessage(chatmessage); + } + } + + astring[i] = s; + icommandlistener.a(CommandObjectiveExecutor.EnumCommandResult.AFFECTED_ENTITIES, arraylist1.size()); + if (arraylist1.size() == 0) { + throw new ExceptionUsage("commands.scoreboard.allMatchesFailed", new Object[0]); + } else { + return true; + } + } + } + + protected Scoreboard d() { + return MinecraftServer.getServer().getWorldServer(0).getScoreboard(); + } + + protected ScoreboardObjective a(String s, boolean flag) throws CommandException { + Scoreboard scoreboard = this.d(); + ScoreboardObjective scoreboardobjective = scoreboard.getObjective(s); + + if (scoreboardobjective == null) { + throw new CommandException("commands.scoreboard.objectiveNotFound", new Object[] { s}); + } else if (flag && scoreboardobjective.getCriteria().isReadOnly()) { + throw new CommandException("commands.scoreboard.objectiveReadOnly", new Object[] { s}); + } else { + return scoreboardobjective; + } + } + + protected ScoreboardTeam e(String s) throws CommandException { + Scoreboard scoreboard = this.d(); + ScoreboardTeam scoreboardteam = scoreboard.getTeam(s); + + if (scoreboardteam == null) { + throw new CommandException("commands.scoreboard.teamNotFound", new Object[] { s}); + } else { + return scoreboardteam; + } + } + + protected void b(ICommandListener icommandlistener, String[] astring, int i) throws CommandException { + String s = astring[i++]; + String s1 = astring[i++]; + Scoreboard scoreboard = this.d(); + IScoreboardCriteria iscoreboardcriteria = (IScoreboardCriteria) IScoreboardCriteria.criteria.get(s1); + + if (iscoreboardcriteria == null) { + throw new ExceptionUsage("commands.scoreboard.objectives.add.wrongType", new Object[] { s1}); + } else if (scoreboard.getObjective(s) != null) { + throw new CommandException("commands.scoreboard.objectives.add.alreadyExists", new Object[] { s}); + } else if (s.length() > 16) { + throw new ExceptionInvalidSyntax("commands.scoreboard.objectives.add.tooLong", new Object[] { s, Integer.valueOf(16)}); + } else if (s.length() == 0) { + throw new ExceptionUsage("commands.scoreboard.objectives.add.usage", new Object[0]); + } else { + if (astring.length > i) { + String s2 = a(icommandlistener, astring, i).c(); + + if (s2.length() > 32) { + throw new ExceptionInvalidSyntax("commands.scoreboard.objectives.add.displayTooLong", new Object[] { s2, Integer.valueOf(32)}); + } + + if (s2.length() > 0) { + scoreboard.registerObjective(s, iscoreboardcriteria).setDisplayName(s2); + } else { + scoreboard.registerObjective(s, iscoreboardcriteria); + } + } else { + scoreboard.registerObjective(s, iscoreboardcriteria); + } + + a(icommandlistener, this, "commands.scoreboard.objectives.add.success", new Object[] { s}); + } + } + + protected void c(ICommandListener icommandlistener, String[] astring, int i) throws CommandException { + String s = astring[i++]; + Scoreboard scoreboard = this.d(); + + if (scoreboard.getTeam(s) != null) { + throw new CommandException("commands.scoreboard.teams.add.alreadyExists", new Object[] { s}); + } else if (s.length() > 16) { + throw new ExceptionInvalidSyntax("commands.scoreboard.teams.add.tooLong", new Object[] { s, Integer.valueOf(16)}); + } else if (s.length() == 0) { + throw new ExceptionUsage("commands.scoreboard.teams.add.usage", new Object[0]); + } else { + if (astring.length > i) { + String s1 = a(icommandlistener, astring, i).c(); + + if (s1.length() > 32) { + throw new ExceptionInvalidSyntax("commands.scoreboard.teams.add.displayTooLong", new Object[] { s1, Integer.valueOf(32)}); + } + + if (s1.length() > 0) { + scoreboard.createTeam(s).setDisplayName(s1); + } else { + scoreboard.createTeam(s); + } + } else { + scoreboard.createTeam(s); + } + + a(icommandlistener, this, "commands.scoreboard.teams.add.success", new Object[] { s}); + } + } + + protected void d(ICommandListener icommandlistener, String[] astring, int i) throws CommandException { + ScoreboardTeam scoreboardteam = this.e(astring[i++]); + + if (scoreboardteam != null) { + String s = astring[i++].toLowerCase(); + + if (!s.equalsIgnoreCase("color") && !s.equalsIgnoreCase("friendlyfire") && !s.equalsIgnoreCase("seeFriendlyInvisibles") && !s.equalsIgnoreCase("nametagVisibility") && !s.equalsIgnoreCase("deathMessageVisibility")) { + throw new ExceptionUsage("commands.scoreboard.teams.option.usage", new Object[0]); + } else if (astring.length == 4) { + if (s.equalsIgnoreCase("color")) { + throw new ExceptionUsage("commands.scoreboard.teams.option.noValue", new Object[] { s, a(EnumChatFormat.a(true, false))}); + } else if (!s.equalsIgnoreCase("friendlyfire") && !s.equalsIgnoreCase("seeFriendlyInvisibles")) { + if (!s.equalsIgnoreCase("nametagVisibility") && !s.equalsIgnoreCase("deathMessageVisibility")) { + throw new ExceptionUsage("commands.scoreboard.teams.option.usage", new Object[0]); + } else { + throw new ExceptionUsage("commands.scoreboard.teams.option.noValue", new Object[] { s, a((Object[]) ScoreboardTeamBase.EnumNameTagVisibility.a())}); + } + } else { + throw new ExceptionUsage("commands.scoreboard.teams.option.noValue", new Object[] { s, a((Collection) Arrays.asList(new String[] { "true", "false"}))}); + } + } else { + String s1 = astring[i]; + + if (s.equalsIgnoreCase("color")) { + EnumChatFormat enumchatformat = EnumChatFormat.b(s1); + + if (enumchatformat == null || enumchatformat.isFormat()) { + throw new ExceptionUsage("commands.scoreboard.teams.option.noValue", new Object[] { s, a(EnumChatFormat.a(true, false))}); + } + + scoreboardteam.a(enumchatformat); + scoreboardteam.setPrefix(enumchatformat.toString()); + scoreboardteam.setSuffix(EnumChatFormat.RESET.toString()); + } else if (s.equalsIgnoreCase("friendlyfire")) { + if (!s1.equalsIgnoreCase("true") && !s1.equalsIgnoreCase("false")) { + throw new ExceptionUsage("commands.scoreboard.teams.option.noValue", new Object[] { s, a((Collection) Arrays.asList(new String[] { "true", "false"}))}); + } + + scoreboardteam.setAllowFriendlyFire(s1.equalsIgnoreCase("true")); + } else if (s.equalsIgnoreCase("seeFriendlyInvisibles")) { + if (!s1.equalsIgnoreCase("true") && !s1.equalsIgnoreCase("false")) { + throw new ExceptionUsage("commands.scoreboard.teams.option.noValue", new Object[] { s, a((Collection) Arrays.asList(new String[] { "true", "false"}))}); + } + + scoreboardteam.setCanSeeFriendlyInvisibles(s1.equalsIgnoreCase("true")); + } else { + ScoreboardTeamBase.EnumNameTagVisibility scoreboardteambase_enumnametagvisibility; + + if (s.equalsIgnoreCase("nametagVisibility")) { + scoreboardteambase_enumnametagvisibility = ScoreboardTeamBase.EnumNameTagVisibility.a(s1); + if (scoreboardteambase_enumnametagvisibility == null) { + throw new ExceptionUsage("commands.scoreboard.teams.option.noValue", new Object[] { s, a((Object[]) ScoreboardTeamBase.EnumNameTagVisibility.a())}); + } + + scoreboardteam.setNameTagVisibility(scoreboardteambase_enumnametagvisibility); + } else if (s.equalsIgnoreCase("deathMessageVisibility")) { + scoreboardteambase_enumnametagvisibility = ScoreboardTeamBase.EnumNameTagVisibility.a(s1); + if (scoreboardteambase_enumnametagvisibility == null) { + throw new ExceptionUsage("commands.scoreboard.teams.option.noValue", new Object[] { s, a((Object[]) ScoreboardTeamBase.EnumNameTagVisibility.a())}); + } + + scoreboardteam.b(scoreboardteambase_enumnametagvisibility); + } + } + + a(icommandlistener, this, "commands.scoreboard.teams.option.success", new Object[] { s, scoreboardteam.getName(), s1}); + } + } + } + + protected void e(ICommandListener icommandlistener, String[] astring, int i) throws CommandException { + Scoreboard scoreboard = this.d(); + ScoreboardTeam scoreboardteam = this.e(astring[i]); + + if (scoreboardteam != null) { + scoreboard.removeTeam(scoreboardteam); + a(icommandlistener, this, "commands.scoreboard.teams.remove.success", new Object[] { scoreboardteam.getName()}); + } + } + + protected void f(ICommandListener icommandlistener, String[] astring, int i) throws CommandException { + Scoreboard scoreboard = this.d(); + + if (astring.length > i) { + ScoreboardTeam scoreboardteam = this.e(astring[i]); + + if (scoreboardteam == null) { + return; + } + + Collection collection = scoreboardteam.getPlayerNameSet(); + + icommandlistener.a(CommandObjectiveExecutor.EnumCommandResult.QUERY_RESULT, collection.size()); + if (collection.size() <= 0) { + throw new CommandException("commands.scoreboard.teams.list.player.empty", new Object[] { scoreboardteam.getName()}); + } + + ChatMessage chatmessage = new ChatMessage("commands.scoreboard.teams.list.player.count", new Object[] { Integer.valueOf(collection.size()), scoreboardteam.getName()}); + + chatmessage.getChatModifier().setColor(EnumChatFormat.DARK_GREEN); + icommandlistener.sendMessage(chatmessage); + icommandlistener.sendMessage(new ChatComponentText(a(collection.toArray()))); + } else { + Collection collection1 = scoreboard.getTeams(); + + icommandlistener.a(CommandObjectiveExecutor.EnumCommandResult.QUERY_RESULT, collection1.size()); + if (collection1.size() <= 0) { + throw new CommandException("commands.scoreboard.teams.list.empty", new Object[0]); + } + + ChatMessage chatmessage1 = new ChatMessage("commands.scoreboard.teams.list.count", new Object[] { Integer.valueOf(collection1.size())}); + + chatmessage1.getChatModifier().setColor(EnumChatFormat.DARK_GREEN); + icommandlistener.sendMessage(chatmessage1); + Iterator iterator = collection1.iterator(); + + while (iterator.hasNext()) { + ScoreboardTeam scoreboardteam1 = (ScoreboardTeam) iterator.next(); + + icommandlistener.sendMessage(new ChatMessage("commands.scoreboard.teams.list.entry", new Object[] { scoreboardteam1.getName(), scoreboardteam1.getDisplayName(), Integer.valueOf(scoreboardteam1.getPlayerNameSet().size())})); + } + } + + } + + protected void g(ICommandListener icommandlistener, String[] astring, int i) throws CommandException { + Scoreboard scoreboard = this.d(); + String s = astring[i++]; + HashSet hashset = Sets.newHashSet(); + HashSet hashset1 = Sets.newHashSet(); + String s1; + + if (icommandlistener instanceof EntityHuman && i == astring.length) { + s1 = b(icommandlistener).getName(); + if (scoreboard.addPlayerToTeam(s1, s)) { + hashset.add(s1); + } else { + hashset1.add(s1); + } + } else { + while (i < astring.length) { + s1 = astring[i++]; + if (s1.startsWith("@")) { + List list = c(icommandlistener, s1); + Iterator iterator = list.iterator(); + + while (iterator.hasNext()) { + Entity entity = (Entity) iterator.next(); + String s2 = e(icommandlistener, entity.getUniqueID().toString()); + + if (scoreboard.addPlayerToTeam(s2, s)) { + hashset.add(s2); + } else { + hashset1.add(s2); + } + } + } else { + String s3 = e(icommandlistener, s1); + + if (scoreboard.addPlayerToTeam(s3, s)) { + hashset.add(s3); + } else { + hashset1.add(s3); + } + } + } + } + + if (!hashset.isEmpty()) { + icommandlistener.a(CommandObjectiveExecutor.EnumCommandResult.AFFECTED_ENTITIES, hashset.size()); + a(icommandlistener, this, "commands.scoreboard.teams.join.success", new Object[] { Integer.valueOf(hashset.size()), s, a(hashset.toArray(new String[hashset.size()]))}); + } + + if (!hashset1.isEmpty()) { + throw new CommandException("commands.scoreboard.teams.join.failure", new Object[] { Integer.valueOf(hashset1.size()), s, a(hashset1.toArray(new String[hashset1.size()]))}); + } + } + + protected void h(ICommandListener icommandlistener, String[] astring, int i) throws CommandException { + Scoreboard scoreboard = this.d(); + HashSet hashset = Sets.newHashSet(); + HashSet hashset1 = Sets.newHashSet(); + String s; + + if (icommandlistener instanceof EntityHuman && i == astring.length) { + s = b(icommandlistener).getName(); + if (scoreboard.removePlayerFromTeam(s)) { + hashset.add(s); + } else { + hashset1.add(s); + } + } else { + while (i < astring.length) { + s = astring[i++]; + if (s.startsWith("@")) { + List list = c(icommandlistener, s); + Iterator iterator = list.iterator(); + + while (iterator.hasNext()) { + Entity entity = (Entity) iterator.next(); + String s1 = e(icommandlistener, entity.getUniqueID().toString()); + + if (scoreboard.removePlayerFromTeam(s1)) { + hashset.add(s1); + } else { + hashset1.add(s1); + } + } + } else { + String s2 = e(icommandlistener, s); + + if (scoreboard.removePlayerFromTeam(s2)) { + hashset.add(s2); + } else { + hashset1.add(s2); + } + } + } + } + + if (!hashset.isEmpty()) { + icommandlistener.a(CommandObjectiveExecutor.EnumCommandResult.AFFECTED_ENTITIES, hashset.size()); + a(icommandlistener, this, "commands.scoreboard.teams.leave.success", new Object[] { Integer.valueOf(hashset.size()), a(hashset.toArray(new String[hashset.size()]))}); + } + + if (!hashset1.isEmpty()) { + throw new CommandException("commands.scoreboard.teams.leave.failure", new Object[] { Integer.valueOf(hashset1.size()), a(hashset1.toArray(new String[hashset1.size()]))}); + } + } + + protected void i(ICommandListener icommandlistener, String[] astring, int i) throws CommandException { + Scoreboard scoreboard = this.d(); + ScoreboardTeam scoreboardteam = this.e(astring[i]); + + if (scoreboardteam != null) { + ArrayList arraylist = Lists.newArrayList(scoreboardteam.getPlayerNameSet()); + + icommandlistener.a(CommandObjectiveExecutor.EnumCommandResult.AFFECTED_ENTITIES, arraylist.size()); + if (arraylist.isEmpty()) { + throw new CommandException("commands.scoreboard.teams.empty.alreadyEmpty", new Object[] { scoreboardteam.getName()}); + } else { + Iterator iterator = arraylist.iterator(); + + while (iterator.hasNext()) { + String s = (String) iterator.next(); + + scoreboard.removePlayerFromTeam(s, scoreboardteam); + } + + a(icommandlistener, this, "commands.scoreboard.teams.empty.success", new Object[] { Integer.valueOf(arraylist.size()), scoreboardteam.getName()}); + } + } + } + + protected void h(ICommandListener icommandlistener, String s) throws CommandException { + Scoreboard scoreboard = this.d(); + ScoreboardObjective scoreboardobjective = this.a(s, false); + + scoreboard.unregisterObjective(scoreboardobjective); + a(icommandlistener, this, "commands.scoreboard.objectives.remove.success", new Object[] { s}); + } + + protected void d(ICommandListener icommandlistener) throws CommandException { + Scoreboard scoreboard = this.d(); + Collection collection = scoreboard.getObjectives(); + + if (collection.size() <= 0) { + throw new CommandException("commands.scoreboard.objectives.list.empty", new Object[0]); + } else { + ChatMessage chatmessage = new ChatMessage("commands.scoreboard.objectives.list.count", new Object[] { Integer.valueOf(collection.size())}); + + chatmessage.getChatModifier().setColor(EnumChatFormat.DARK_GREEN); + icommandlistener.sendMessage(chatmessage); + Iterator iterator = collection.iterator(); + + while (iterator.hasNext()) { + ScoreboardObjective scoreboardobjective = (ScoreboardObjective) iterator.next(); + + icommandlistener.sendMessage(new ChatMessage("commands.scoreboard.objectives.list.entry", new Object[] { scoreboardobjective.getName(), scoreboardobjective.getDisplayName(), scoreboardobjective.getCriteria().getName()})); + } + + } + } + + protected void j(ICommandListener icommandlistener, String[] astring, int i) throws CommandException { + Scoreboard scoreboard = this.d(); + String s = astring[i++]; + int j = Scoreboard.getSlotForName(s); + ScoreboardObjective scoreboardobjective = null; + + if (astring.length == 4) { + scoreboardobjective = this.a(astring[i], false); + } + + if (j < 0) { + throw new CommandException("commands.scoreboard.objectives.setdisplay.invalidSlot", new Object[] { s}); + } else { + scoreboard.setDisplaySlot(j, scoreboardobjective); + if (scoreboardobjective != null) { + a(icommandlistener, this, "commands.scoreboard.objectives.setdisplay.successSet", new Object[] { Scoreboard.getSlotName(j), scoreboardobjective.getName()}); + } else { + a(icommandlistener, this, "commands.scoreboard.objectives.setdisplay.successCleared", new Object[] { Scoreboard.getSlotName(j)}); + } + + } + } + + protected void k(ICommandListener icommandlistener, String[] astring, int i) throws CommandException { + Scoreboard scoreboard = this.d(); + + if (astring.length > i) { + String s = e(icommandlistener, astring[i]); + Map map = scoreboard.getPlayerObjectives(s); + + icommandlistener.a(CommandObjectiveExecutor.EnumCommandResult.QUERY_RESULT, map.size()); + if (map.size() <= 0) { + throw new CommandException("commands.scoreboard.players.list.player.empty", new Object[] { s}); + } + + ChatMessage chatmessage = new ChatMessage("commands.scoreboard.players.list.player.count", new Object[] { Integer.valueOf(map.size()), s}); + + chatmessage.getChatModifier().setColor(EnumChatFormat.DARK_GREEN); + icommandlistener.sendMessage(chatmessage); + Iterator iterator = map.values().iterator(); + + while (iterator.hasNext()) { + ScoreboardScore scoreboardscore = (ScoreboardScore) iterator.next(); + + icommandlistener.sendMessage(new ChatMessage("commands.scoreboard.players.list.player.entry", new Object[] { Integer.valueOf(scoreboardscore.getScore()), scoreboardscore.getObjective().getDisplayName(), scoreboardscore.getObjective().getName()})); + } + } else { + Collection collection = scoreboard.getPlayers(); + + icommandlistener.a(CommandObjectiveExecutor.EnumCommandResult.QUERY_RESULT, collection.size()); + if (collection.size() <= 0) { + throw new CommandException("commands.scoreboard.players.list.empty", new Object[0]); + } + + ChatMessage chatmessage1 = new ChatMessage("commands.scoreboard.players.list.count", new Object[] { Integer.valueOf(collection.size())}); + + chatmessage1.getChatModifier().setColor(EnumChatFormat.DARK_GREEN); + icommandlistener.sendMessage(chatmessage1); + icommandlistener.sendMessage(new ChatComponentText(a(collection.toArray()))); + } + + } + + protected void l(ICommandListener icommandlistener, String[] astring, int i) throws CommandException { + String s = astring[i - 1]; + int j = i; + String s1 = e(icommandlistener, astring[i++]); + + if (s1.length() > 40) { + throw new ExceptionInvalidSyntax("commands.scoreboard.players.name.tooLong", new Object[] { s1, Integer.valueOf(40)}); + } else { + ScoreboardObjective scoreboardobjective = this.a(astring[i++], true); + int k = s.equalsIgnoreCase("set") ? a(astring[i++]) : a(astring[i++], 0); + + if (astring.length > i) { + Entity entity = b(icommandlistener, astring[j]); + + try { + NBTTagCompound nbttagcompound = MojangsonParser.parse(a(astring, i)); + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + + entity.e(nbttagcompound1); + if (!GameProfileSerializer.a(nbttagcompound, nbttagcompound1, true)) { + throw new CommandException("commands.scoreboard.players.set.tagMismatch", new Object[] { s1}); + } + } catch (MojangsonParseException mojangsonparseexception) { + throw new CommandException("commands.scoreboard.players.set.tagError", new Object[] { mojangsonparseexception.getMessage()}); + } + } + + Scoreboard scoreboard = this.d(); + ScoreboardScore scoreboardscore = scoreboard.getPlayerScoreForObjective(s1, scoreboardobjective); + + if (s.equalsIgnoreCase("set")) { + scoreboardscore.setScore(k); + } else if (s.equalsIgnoreCase("add")) { + scoreboardscore.addScore(k); + } else { + scoreboardscore.removeScore(k); + } + + a(icommandlistener, this, "commands.scoreboard.players.set.success", new Object[] { scoreboardobjective.getName(), s1, Integer.valueOf(scoreboardscore.getScore())}); + } + } + + protected void m(ICommandListener icommandlistener, String[] astring, int i) throws CommandException { + Scoreboard scoreboard = this.d(); + String s = e(icommandlistener, astring[i++]); + + if (astring.length > i) { + ScoreboardObjective scoreboardobjective = this.a(astring[i++], false); + + scoreboard.resetPlayerScores(s, scoreboardobjective); + a(icommandlistener, this, "commands.scoreboard.players.resetscore.success", new Object[] { scoreboardobjective.getName(), s}); + } else { + scoreboard.resetPlayerScores(s, (ScoreboardObjective) null); + a(icommandlistener, this, "commands.scoreboard.players.reset.success", new Object[] { s}); + } + + } + + protected void n(ICommandListener icommandlistener, String[] astring, int i) throws CommandException { + Scoreboard scoreboard = this.d(); + String s = d(icommandlistener, astring[i++]); + + if (s.length() > 40) { + throw new ExceptionInvalidSyntax("commands.scoreboard.players.name.tooLong", new Object[] { s, Integer.valueOf(40)}); + } else { + ScoreboardObjective scoreboardobjective = this.a(astring[i], false); + + if (scoreboardobjective.getCriteria() != IScoreboardCriteria.c) { + throw new CommandException("commands.scoreboard.players.enable.noTrigger", new Object[] { scoreboardobjective.getName()}); + } else { + ScoreboardScore scoreboardscore = scoreboard.getPlayerScoreForObjective(s, scoreboardobjective); + + scoreboardscore.a(false); + a(icommandlistener, this, "commands.scoreboard.players.enable.success", new Object[] { scoreboardobjective.getName(), s}); + } + } + } + + protected void o(ICommandListener icommandlistener, String[] astring, int i) throws CommandException { + Scoreboard scoreboard = this.d(); + String s = e(icommandlistener, astring[i++]); + + if (s.length() > 40) { + throw new ExceptionInvalidSyntax("commands.scoreboard.players.name.tooLong", new Object[] { s, Integer.valueOf(40)}); + } else { + ScoreboardObjective scoreboardobjective = this.a(astring[i++], false); + + if (!scoreboard.b(s, scoreboardobjective)) { + throw new CommandException("commands.scoreboard.players.test.notFound", new Object[] { scoreboardobjective.getName(), s}); + } else { + int j = astring[i].equals("*") ? Integer.MIN_VALUE : a(astring[i]); + + ++i; + int k = i < astring.length && !astring[i].equals("*") ? a(astring[i], j) : Integer.MAX_VALUE; + ScoreboardScore scoreboardscore = scoreboard.getPlayerScoreForObjective(s, scoreboardobjective); + + if (scoreboardscore.getScore() >= j && scoreboardscore.getScore() <= k) { + a(icommandlistener, this, "commands.scoreboard.players.test.success", new Object[] { Integer.valueOf(scoreboardscore.getScore()), Integer.valueOf(j), Integer.valueOf(k)}); + } else { + throw new CommandException("commands.scoreboard.players.test.failed", new Object[] { Integer.valueOf(scoreboardscore.getScore()), Integer.valueOf(j), Integer.valueOf(k)}); + } + } + } + } + + protected void p(ICommandListener icommandlistener, String[] astring, int i) throws CommandException { + Scoreboard scoreboard = this.d(); + String s = e(icommandlistener, astring[i++]); + ScoreboardObjective scoreboardobjective = this.a(astring[i++], true); + String s1 = astring[i++]; + String s2 = e(icommandlistener, astring[i++]); + ScoreboardObjective scoreboardobjective1 = this.a(astring[i], false); + + if (s.length() > 40) { + throw new ExceptionInvalidSyntax("commands.scoreboard.players.name.tooLong", new Object[] { s, Integer.valueOf(40)}); + } else if (s2.length() > 40) { + throw new ExceptionInvalidSyntax("commands.scoreboard.players.name.tooLong", new Object[] { s2, Integer.valueOf(40)}); + } else { + ScoreboardScore scoreboardscore = scoreboard.getPlayerScoreForObjective(s, scoreboardobjective); + + if (!scoreboard.b(s2, scoreboardobjective1)) { + throw new CommandException("commands.scoreboard.players.operation.notFound", new Object[] { scoreboardobjective1.getName(), s2}); + } else { + ScoreboardScore scoreboardscore1 = scoreboard.getPlayerScoreForObjective(s2, scoreboardobjective1); + + if (s1.equals("+=")) { + scoreboardscore.setScore(scoreboardscore.getScore() + scoreboardscore1.getScore()); + } else if (s1.equals("-=")) { + scoreboardscore.setScore(scoreboardscore.getScore() - scoreboardscore1.getScore()); + } else if (s1.equals("*=")) { + scoreboardscore.setScore(scoreboardscore.getScore() * scoreboardscore1.getScore()); + } else if (s1.equals("/=")) { + if (scoreboardscore1.getScore() != 0) { + scoreboardscore.setScore(scoreboardscore.getScore() / scoreboardscore1.getScore()); + } + } else if (s1.equals("%=")) { + if (scoreboardscore1.getScore() != 0) { + scoreboardscore.setScore(scoreboardscore.getScore() % scoreboardscore1.getScore()); + } + } else if (s1.equals("=")) { + scoreboardscore.setScore(scoreboardscore1.getScore()); + } else if (s1.equals("<")) { + scoreboardscore.setScore(Math.min(scoreboardscore.getScore(), scoreboardscore1.getScore())); + } else if (s1.equals(">")) { + scoreboardscore.setScore(Math.max(scoreboardscore.getScore(), scoreboardscore1.getScore())); + } else { + if (!s1.equals("><")) { + throw new CommandException("commands.scoreboard.players.operation.invalidOperation", new Object[] { s1}); + } + + int j = scoreboardscore.getScore(); + + scoreboardscore.setScore(scoreboardscore1.getScore()); + scoreboardscore1.setScore(j); + } + + a(icommandlistener, this, "commands.scoreboard.players.operation.success", new Object[0]); + } + } + } + + public List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { + if (astring.length == 1) { + return a(astring, new String[] { "objectives", "players", "teams"}); + } else { + if (astring[0].equalsIgnoreCase("objectives")) { + if (astring.length == 2) { + return a(astring, new String[] { "list", "add", "remove", "setdisplay"}); + } + + if (astring[1].equalsIgnoreCase("add")) { + if (astring.length == 4) { + Set set = IScoreboardCriteria.criteria.keySet(); + + return a(astring, (Collection) set); + } + } else if (astring[1].equalsIgnoreCase("remove")) { + if (astring.length == 3) { + return a(astring, (Collection) this.a(false)); + } + } else if (astring[1].equalsIgnoreCase("setdisplay")) { + if (astring.length == 3) { + return a(astring, Scoreboard.h()); + } + + if (astring.length == 4) { + return a(astring, (Collection) this.a(false)); + } + } + } else if (astring[0].equalsIgnoreCase("players")) { + if (astring.length == 2) { + return a(astring, new String[] { "set", "add", "remove", "reset", "list", "enable", "test", "operation"}); + } + + if (!astring[1].equalsIgnoreCase("set") && !astring[1].equalsIgnoreCase("add") && !astring[1].equalsIgnoreCase("remove") && !astring[1].equalsIgnoreCase("reset")) { + if (astring[1].equalsIgnoreCase("enable")) { + if (astring.length == 3) { + return a(astring, MinecraftServer.getServer().getPlayers()); + } + + if (astring.length == 4) { + return a(astring, (Collection) this.e()); + } + } else if (!astring[1].equalsIgnoreCase("list") && !astring[1].equalsIgnoreCase("test")) { + if (astring[1].equalsIgnoreCase("operation")) { + if (astring.length == 3) { + return a(astring, this.d().getPlayers()); + } + + if (astring.length == 4) { + return a(astring, (Collection) this.a(true)); + } + + if (astring.length == 5) { + return a(astring, new String[] { "+=", "-=", "*=", "/=", "%=", "=", "<", ">", "><"}); + } + + if (astring.length == 6) { + return a(astring, MinecraftServer.getServer().getPlayers()); + } + + if (astring.length == 7) { + return a(astring, (Collection) this.a(false)); + } + } + } else { + if (astring.length == 3) { + return a(astring, this.d().getPlayers()); + } + + if (astring.length == 4 && astring[1].equalsIgnoreCase("test")) { + return a(astring, (Collection) this.a(false)); + } + } + } else { + if (astring.length == 3) { + return a(astring, MinecraftServer.getServer().getPlayers()); + } + + if (astring.length == 4) { + return a(astring, (Collection) this.a(true)); + } + } + } else if (astring[0].equalsIgnoreCase("teams")) { + if (astring.length == 2) { + return a(astring, new String[] { "add", "remove", "join", "leave", "empty", "list", "option"}); + } + + if (astring[1].equalsIgnoreCase("join")) { + if (astring.length == 3) { + return a(astring, this.d().getTeamNames()); + } + + if (astring.length >= 4) { + return a(astring, MinecraftServer.getServer().getPlayers()); + } + } else { + if (astring[1].equalsIgnoreCase("leave")) { + return a(astring, MinecraftServer.getServer().getPlayers()); + } + + if (!astring[1].equalsIgnoreCase("empty") && !astring[1].equalsIgnoreCase("list") && !astring[1].equalsIgnoreCase("remove")) { + if (astring[1].equalsIgnoreCase("option")) { + if (astring.length == 3) { + return a(astring, this.d().getTeamNames()); + } + + if (astring.length == 4) { + return a(astring, new String[] { "color", "friendlyfire", "seeFriendlyInvisibles", "nametagVisibility", "deathMessageVisibility"}); + } + + if (astring.length == 5) { + if (astring[3].equalsIgnoreCase("color")) { + return a(astring, EnumChatFormat.a(true, false)); + } + + if (astring[3].equalsIgnoreCase("nametagVisibility") || astring[3].equalsIgnoreCase("deathMessageVisibility")) { + return a(astring, ScoreboardTeamBase.EnumNameTagVisibility.a()); + } + + if (astring[3].equalsIgnoreCase("friendlyfire") || astring[3].equalsIgnoreCase("seeFriendlyInvisibles")) { + return a(astring, new String[] { "true", "false"}); + } + } + } + } else if (astring.length == 3) { + return a(astring, this.d().getTeamNames()); + } + } + } + + return null; + } + } + + protected List a(boolean flag) { + Collection collection = this.d().getObjectives(); + ArrayList arraylist = Lists.newArrayList(); + Iterator iterator = collection.iterator(); + + while (iterator.hasNext()) { + ScoreboardObjective scoreboardobjective = (ScoreboardObjective) iterator.next(); + + if (!flag || !scoreboardobjective.getCriteria().isReadOnly()) { + arraylist.add(scoreboardobjective.getName()); + } + } + + return arraylist; + } + + protected List e() { + Collection collection = this.d().getObjectives(); + ArrayList arraylist = Lists.newArrayList(); + Iterator iterator = collection.iterator(); + + while (iterator.hasNext()) { + ScoreboardObjective scoreboardobjective = (ScoreboardObjective) iterator.next(); + + if (scoreboardobjective.getCriteria() == IScoreboardCriteria.c) { + arraylist.add(scoreboardobjective.getName()); + } + } + + return arraylist; + } + + public boolean isListStart(String[] astring, int i) { + return !astring[0].equalsIgnoreCase("players") ? (astring[0].equalsIgnoreCase("teams") ? i == 2 : false) : (astring.length > 1 && astring[1].equalsIgnoreCase("operation") ? i == 2 || i == 5 : i == 2); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandSeed.java b/azurite-server/src/main/java/net/minecraft/server/CommandSeed.java new file mode 100644 index 0000000..1545eb7 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandSeed.java @@ -0,0 +1,28 @@ +package net.minecraft.server; + +public class CommandSeed extends CommandAbstract { + + public CommandSeed() {} + + public boolean canUse(ICommandListener icommandlistener) { + return MinecraftServer.getServer().T() || super.canUse(icommandlistener); + } + + public String getCommand() { + return "seed"; + } + + public int a() { + return 2; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.seed.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + Object object = icommandlistener instanceof EntityHuman ? ((EntityHuman) icommandlistener).world : MinecraftServer.getServer().getWorldServer(0); + + icommandlistener.sendMessage(new ChatMessage("commands.seed.success", new Object[] { Long.valueOf(((World) object).getSeed())})); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandSetBlock.java b/azurite-server/src/main/java/net/minecraft/server/CommandSetBlock.java new file mode 100644 index 0000000..0e4e11f --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandSetBlock.java @@ -0,0 +1,103 @@ +package net.minecraft.server; + +import java.util.Collection; +import java.util.List; + +public class CommandSetBlock extends CommandAbstract { + + public CommandSetBlock() {} + + public String getCommand() { + return "setblock"; + } + + public int a() { + return 2; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.setblock.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + if (astring.length < 4) { + throw new ExceptionUsage("commands.setblock.usage", new Object[0]); + } else { + icommandlistener.a(CommandObjectiveExecutor.EnumCommandResult.AFFECTED_BLOCKS, 0); + BlockPosition blockposition = a(icommandlistener, astring, 0, false); + Block block = CommandAbstract.g(icommandlistener, astring[3]); + int i = 0; + + if (astring.length >= 5) { + i = a(astring[4], 0, 15); + } + + World world = icommandlistener.getWorld(); + + if (!world.isLoaded(blockposition)) { + throw new CommandException("commands.setblock.outOfWorld", new Object[0]); + } else { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + boolean flag = false; + + if (astring.length >= 7 && block.isTileEntity()) { + String s = a(icommandlistener, astring, 6).c(); + + try { + nbttagcompound = MojangsonParser.parse(s); + flag = true; + } catch (MojangsonParseException mojangsonparseexception) { + throw new CommandException("commands.setblock.tagError", new Object[] { mojangsonparseexception.getMessage()}); + } + } + + if (astring.length >= 6) { + if (astring[5].equals("destroy")) { + world.setAir(blockposition, true); + if (block == Blocks.AIR) { + a(icommandlistener, this, "commands.setblock.success", new Object[0]); + return; + } + } else if (astring[5].equals("keep") && !world.isEmpty(blockposition)) { + throw new CommandException("commands.setblock.noChange", new Object[0]); + } + } + + TileEntity tileentity = world.getTileEntity(blockposition); + + if (tileentity != null) { + if (tileentity instanceof IInventory) { + ((IInventory) tileentity).l(); + } + + world.setTypeAndData(blockposition, Blocks.AIR.getBlockData(), block == Blocks.AIR ? 2 : 4); + } + + IBlockData iblockdata = block.fromLegacyData(i); + + if (!world.setTypeAndData(blockposition, iblockdata, 2)) { + throw new CommandException("commands.setblock.noChange", new Object[0]); + } else { + if (flag) { + TileEntity tileentity1 = world.getTileEntity(blockposition); + + if (tileentity1 != null) { + nbttagcompound.setInt("x", blockposition.getX()); + nbttagcompound.setInt("y", blockposition.getY()); + nbttagcompound.setInt("z", blockposition.getZ()); + tileentity1.a(nbttagcompound); + } + } + + world.update(blockposition, iblockdata.getBlock()); + icommandlistener.a(CommandObjectiveExecutor.EnumCommandResult.AFFECTED_BLOCKS, 1); + a(icommandlistener, this, "commands.setblock.success", new Object[0]); + } + } + } + } + + public List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { + return astring.length > 0 && astring.length <= 3 ? a(astring, 0, blockposition) : (astring.length == 4 ? a(astring, (Collection) Block.REGISTRY.keySet()) : (astring.length == 6 ? a(astring, new String[] { "replace", "destroy", "keep"}) : null)); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandSetWorldSpawn.java b/azurite-server/src/main/java/net/minecraft/server/CommandSetWorldSpawn.java new file mode 100644 index 0000000..209d503 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandSetWorldSpawn.java @@ -0,0 +1,42 @@ +package net.minecraft.server; + +import java.util.List; + +public class CommandSetWorldSpawn extends CommandAbstract { + + public CommandSetWorldSpawn() {} + + public String getCommand() { + return "setworldspawn"; + } + + public int a() { + return 2; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.setworldspawn.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + BlockPosition blockposition; + + if (astring.length == 0) { + blockposition = b(icommandlistener).getChunkCoordinates(); + } else { + if (astring.length != 3 || icommandlistener.getWorld() == null) { + throw new ExceptionUsage("commands.setworldspawn.usage", new Object[0]); + } + + blockposition = a(icommandlistener, astring, 0, true); + } + + icommandlistener.getWorld().B(blockposition); + MinecraftServer.getServer().getPlayerList().sendAll(new PacketPlayOutSpawnPosition(blockposition)); + a(icommandlistener, this, "commands.setworldspawn.success", new Object[] { Integer.valueOf(blockposition.getX()), Integer.valueOf(blockposition.getY()), Integer.valueOf(blockposition.getZ())}); + } + + public List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { + return astring.length > 0 && astring.length <= 3 ? a(astring, 0, blockposition) : null; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandSpawnpoint.java b/azurite-server/src/main/java/net/minecraft/server/CommandSpawnpoint.java new file mode 100644 index 0000000..aa9434b --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandSpawnpoint.java @@ -0,0 +1,43 @@ +package net.minecraft.server; + +import java.util.List; + +public class CommandSpawnpoint extends CommandAbstract { + + public CommandSpawnpoint() {} + + public String getCommand() { + return "spawnpoint"; + } + + public int a() { + return 2; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.spawnpoint.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + if (astring.length > 1 && astring.length < 4) { + throw new ExceptionUsage("commands.spawnpoint.usage", new Object[0]); + } else { + EntityPlayer entityplayer = astring.length > 0 ? a(icommandlistener, astring[0]) : b(icommandlistener); + BlockPosition blockposition = astring.length > 3 ? a(icommandlistener, astring, 1, true) : entityplayer.getChunkCoordinates(); + + if (entityplayer.world != null) { + entityplayer.setRespawnPosition(blockposition, true); + a(icommandlistener, this, "commands.spawnpoint.success", new Object[] { entityplayer.getName(), Integer.valueOf(blockposition.getX()), Integer.valueOf(blockposition.getY()), Integer.valueOf(blockposition.getZ())}); + } + + } + } + + public List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { + return astring.length == 1 ? a(astring, MinecraftServer.getServer().getPlayers()) : (astring.length > 1 && astring.length <= 4 ? a(astring, 1, blockposition) : null); + } + + public boolean isListStart(String[] astring, int i) { + return i == 0; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandSpreadPlayers.java b/azurite-server/src/main/java/net/minecraft/server/CommandSpreadPlayers.java new file mode 100644 index 0000000..53c5d92 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandSpreadPlayers.java @@ -0,0 +1,347 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import com.google.common.collect.Sets; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Random; + +public class CommandSpreadPlayers extends CommandAbstract { + + public CommandSpreadPlayers() {} + + public String getCommand() { + return "spreadplayers"; + } + + public int a() { + return 2; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.spreadplayers.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + if (astring.length < 6) { + throw new ExceptionUsage("commands.spreadplayers.usage", new Object[0]); + } else { + byte b0 = 0; + BlockPosition blockposition = icommandlistener.getChunkCoordinates(); + double d0 = (double) blockposition.getX(); + int i = b0 + 1; + double d1 = b(d0, astring[b0], true); + double d2 = b((double) blockposition.getZ(), astring[i++], true); + double d3 = a(astring[i++], 0.0D); + double d4 = a(astring[i++], d3 + 1.0D); + boolean flag = d(astring[i++]); + ArrayList arraylist = Lists.newArrayList(); + + while (i < astring.length) { + String s = astring[i++]; + + if (PlayerSelector.isPattern(s)) { + List list = PlayerSelector.getPlayers(icommandlistener, s, Entity.class); + + if (list.size() == 0) { + throw new ExceptionEntityNotFound(); + } + + arraylist.addAll(list); + } else { + EntityPlayer entityplayer = MinecraftServer.getServer().getPlayerList().getPlayer(s); + + if (entityplayer == null) { + throw new ExceptionPlayerNotFound(); + } + + arraylist.add(entityplayer); + } + } + + icommandlistener.a(CommandObjectiveExecutor.EnumCommandResult.AFFECTED_ENTITIES, arraylist.size()); + if (arraylist.isEmpty()) { + throw new ExceptionEntityNotFound(); + } else { + icommandlistener.sendMessage(new ChatMessage("commands.spreadplayers.spreading." + (flag ? "teams" : "players"), new Object[] { Integer.valueOf(arraylist.size()), Double.valueOf(d4), Double.valueOf(d1), Double.valueOf(d2), Double.valueOf(d3)})); + this.a(icommandlistener, arraylist, new CommandSpreadPlayers.Location2D(d1, d2), d3, d4, ((Entity) arraylist.get(0)).world, flag); + } + } + } + + private void a(ICommandListener icommandlistener, List list, CommandSpreadPlayers.Location2D commandspreadplayers_location2d, double d0, double d1, World world, boolean flag) throws CommandException { + Random random = new Random(); + double d2 = commandspreadplayers_location2d.a - d1; + double d3 = commandspreadplayers_location2d.b - d1; + double d4 = commandspreadplayers_location2d.a + d1; + double d5 = commandspreadplayers_location2d.b + d1; + CommandSpreadPlayers.Location2D[] acommandspreadplayers_location2d = this.a(random, flag ? this.b(list) : list.size(), d2, d3, d4, d5); + int i = this.a(commandspreadplayers_location2d, d0, world, random, d2, d3, d4, d5, acommandspreadplayers_location2d, flag); + double d6 = this.a(list, world, acommandspreadplayers_location2d, flag); + + a(icommandlistener, this, "commands.spreadplayers.success." + (flag ? "teams" : "players"), new Object[] { Integer.valueOf(acommandspreadplayers_location2d.length), Double.valueOf(commandspreadplayers_location2d.a), Double.valueOf(commandspreadplayers_location2d.b)}); + if (acommandspreadplayers_location2d.length > 1) { + icommandlistener.sendMessage(new ChatMessage("commands.spreadplayers.info." + (flag ? "teams" : "players"), new Object[] { String.format("%.2f", new Object[] { Double.valueOf(d6)}), Integer.valueOf(i)})); + } + + } + + private int b(List list) { + HashSet hashset = Sets.newHashSet(); + Iterator iterator = list.iterator(); + + while (iterator.hasNext()) { + Entity entity = (Entity) iterator.next(); + + if (entity instanceof EntityHuman) { + hashset.add(((EntityHuman) entity).getScoreboardTeam()); + } else { + hashset.add((Object) null); + } + } + + return hashset.size(); + } + + private int a(CommandSpreadPlayers.Location2D commandspreadplayers_location2d, double d0, World world, Random random, double d1, double d2, double d3, double d4, CommandSpreadPlayers.Location2D[] acommandspreadplayers_location2d, boolean flag) throws CommandException { + boolean flag1 = true; + double d5 = 3.4028234663852886E38D; + + int i; + + for (i = 0; i < 10000 && flag1; ++i) { + flag1 = false; + d5 = 3.4028234663852886E38D; + + int j; + CommandSpreadPlayers.Location2D commandspreadplayers_location2d1; + + for (int k = 0; k < acommandspreadplayers_location2d.length; ++k) { + CommandSpreadPlayers.Location2D commandspreadplayers_location2d2 = acommandspreadplayers_location2d[k]; + + j = 0; + commandspreadplayers_location2d1 = new CommandSpreadPlayers.Location2D(); + + for (int l = 0; l < acommandspreadplayers_location2d.length; ++l) { + if (k != l) { + CommandSpreadPlayers.Location2D commandspreadplayers_location2d3 = acommandspreadplayers_location2d[l]; + double d6 = commandspreadplayers_location2d2.a(commandspreadplayers_location2d3); + + d5 = Math.min(d6, d5); + if (d6 < d0) { + ++j; + commandspreadplayers_location2d1.a += commandspreadplayers_location2d3.a - commandspreadplayers_location2d2.a; + commandspreadplayers_location2d1.b += commandspreadplayers_location2d3.b - commandspreadplayers_location2d2.b; + } + } + } + + if (j > 0) { + commandspreadplayers_location2d1.a /= (double) j; + commandspreadplayers_location2d1.b /= (double) j; + double d7 = (double) commandspreadplayers_location2d1.b(); + + if (d7 > 0.0D) { + commandspreadplayers_location2d1.a(); + commandspreadplayers_location2d2.b(commandspreadplayers_location2d1); + } else { + commandspreadplayers_location2d2.a(random, d1, d2, d3, d4); + } + + flag1 = true; + } + + if (commandspreadplayers_location2d2.a(d1, d2, d3, d4)) { + flag1 = true; + } + } + + if (!flag1) { + CommandSpreadPlayers.Location2D[] acommandspreadplayers_location2d1 = acommandspreadplayers_location2d; + int i1 = acommandspreadplayers_location2d.length; + + for (j = 0; j < i1; ++j) { + commandspreadplayers_location2d1 = acommandspreadplayers_location2d1[j]; + if (!commandspreadplayers_location2d1.b(world)) { + commandspreadplayers_location2d1.a(random, d1, d2, d3, d4); + flag1 = true; + } + } + } + } + + if (i >= 10000) { + throw new CommandException("commands.spreadplayers.failure." + (flag ? "teams" : "players"), new Object[] { Integer.valueOf(acommandspreadplayers_location2d.length), Double.valueOf(commandspreadplayers_location2d.a), Double.valueOf(commandspreadplayers_location2d.b), String.format("%.2f", new Object[] { Double.valueOf(d5)})}); + } else { + return i; + } + } + + private double a(List list, World world, CommandSpreadPlayers.Location2D[] acommandspreadplayers_location2d, boolean flag) { + double d0 = 0.0D; + int i = 0; + HashMap hashmap = Maps.newHashMap(); + + for (int j = 0; j < list.size(); ++j) { + Entity entity = (Entity) list.get(j); + CommandSpreadPlayers.Location2D commandspreadplayers_location2d; + + if (flag) { + ScoreboardTeamBase scoreboardteambase = entity instanceof EntityHuman ? ((EntityHuman) entity).getScoreboardTeam() : null; + + if (!hashmap.containsKey(scoreboardteambase)) { + hashmap.put(scoreboardteambase, acommandspreadplayers_location2d[i++]); + } + + commandspreadplayers_location2d = (CommandSpreadPlayers.Location2D) hashmap.get(scoreboardteambase); + } else { + commandspreadplayers_location2d = acommandspreadplayers_location2d[i++]; + } + + entity.enderTeleportTo((double) ((float) MathHelper.floor(commandspreadplayers_location2d.a) + 0.5F), (double) commandspreadplayers_location2d.a(world), (double) MathHelper.floor(commandspreadplayers_location2d.b) + 0.5D); + double d1 = Double.MAX_VALUE; + + for (int k = 0; k < acommandspreadplayers_location2d.length; ++k) { + if (commandspreadplayers_location2d != acommandspreadplayers_location2d[k]) { + double d2 = commandspreadplayers_location2d.a(acommandspreadplayers_location2d[k]); + + d1 = Math.min(d2, d1); + } + } + + d0 += d1; + } + + d0 /= (double) list.size(); + return d0; + } + + private CommandSpreadPlayers.Location2D[] a(Random random, int i, double d0, double d1, double d2, double d3) { + CommandSpreadPlayers.Location2D[] acommandspreadplayers_location2d = new CommandSpreadPlayers.Location2D[i]; + + for (int j = 0; j < acommandspreadplayers_location2d.length; ++j) { + CommandSpreadPlayers.Location2D commandspreadplayers_location2d = new CommandSpreadPlayers.Location2D(); + + commandspreadplayers_location2d.a(random, d0, d1, d2, d3); + acommandspreadplayers_location2d[j] = commandspreadplayers_location2d; + } + + return acommandspreadplayers_location2d; + } + + public List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { + return astring.length >= 1 && astring.length <= 2 ? b(astring, 0, blockposition) : null; + } + + // CraftBukkit start - fix decompile error + @Override + public int compareTo(ICommand o) { + return a(o); + } + // CraftBukkit end + + static class Location2D { + + double a; + double b; + + Location2D() {} + + Location2D(double d0, double d1) { + this.a = d0; + this.b = d1; + } + + double a(CommandSpreadPlayers.Location2D commandspreadplayers_location2d) { + double d0 = this.a - commandspreadplayers_location2d.a; + double d1 = this.b - commandspreadplayers_location2d.b; + + return Math.sqrt(d0 * d0 + d1 * d1); + } + + void a() { + double d0 = (double) this.b(); + + this.a /= d0; + this.b /= d0; + } + + float b() { + return MathHelper.sqrt(this.a * this.a + this.b * this.b); + } + + public void b(CommandSpreadPlayers.Location2D commandspreadplayers_location2d) { + this.a -= commandspreadplayers_location2d.a; + this.b -= commandspreadplayers_location2d.b; + } + + public boolean a(double d0, double d1, double d2, double d3) { + boolean flag = false; + + if (this.a < d0) { + this.a = d0; + flag = true; + } else if (this.a > d2) { + this.a = d2; + flag = true; + } + + if (this.b < d1) { + this.b = d1; + flag = true; + } else if (this.b > d3) { + this.b = d3; + flag = true; + } + + return flag; + } + + public int a(World world) { + BlockPosition blockposition = new BlockPosition(this.a, 256.0D, this.b); + + do { + if (blockposition.getY() <= 0) { + return 257; + } + + blockposition = blockposition.down(); + } while (getType(world, blockposition).getBlock().getMaterial() == Material.AIR); // CraftBukkit + + return blockposition.getY() + 1; + } + + public boolean b(World world) { + BlockPosition blockposition = new BlockPosition(this.a, 256.0D, this.b); + + Material material; + + do { + if (blockposition.getY() <= 0) { + return false; + } + + blockposition = blockposition.down(); + material = getType(world, blockposition).getBlock().getMaterial(); // CraftBukkit + } while (material == Material.AIR); + + return !material.isLiquid() && material != Material.FIRE; + } + + public void a(Random random, double d0, double d1, double d2, double d3) { + this.a = MathHelper.a(random, d0, d2); + this.b = MathHelper.a(random, d1, d3); + } + + // CraftBukkit start - add a version of getType which force loads chunks + private static IBlockData getType(World world, BlockPosition position) { + ((ChunkProviderServer) world.chunkProvider).getChunkAt(position.getX() >> 4, position.getZ() >> 4); + return world.getType(position); + } + // CraftBukkit end + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandStats.java b/azurite-server/src/main/java/net/minecraft/server/CommandStats.java new file mode 100644 index 0000000..7d58f6f --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandStats.java @@ -0,0 +1,166 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; + +public class CommandStats extends CommandAbstract { + + public CommandStats() {} + + public String getCommand() { + return "stats"; + } + + public int a() { + return 2; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.stats.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + if (astring.length < 1) { + throw new ExceptionUsage("commands.stats.usage", new Object[0]); + } else { + boolean flag; + + if (astring[0].equals("entity")) { + flag = false; + } else { + if (!astring[0].equals("block")) { + throw new ExceptionUsage("commands.stats.usage", new Object[0]); + } + + flag = true; + } + + byte b0; + + if (flag) { + if (astring.length < 5) { + throw new ExceptionUsage("commands.stats.block.usage", new Object[0]); + } + + b0 = 4; + } else { + if (astring.length < 3) { + throw new ExceptionUsage("commands.stats.entity.usage", new Object[0]); + } + + b0 = 2; + } + + int i = b0 + 1; + String s = astring[b0]; + + if ("set".equals(s)) { + if (astring.length < i + 3) { + if (i == 5) { + throw new ExceptionUsage("commands.stats.block.set.usage", new Object[0]); + } + + throw new ExceptionUsage("commands.stats.entity.set.usage", new Object[0]); + } + } else { + if (!"clear".equals(s)) { + throw new ExceptionUsage("commands.stats.usage", new Object[0]); + } + + if (astring.length < i + 1) { + if (i == 5) { + throw new ExceptionUsage("commands.stats.block.clear.usage", new Object[0]); + } + + throw new ExceptionUsage("commands.stats.entity.clear.usage", new Object[0]); + } + } + + CommandObjectiveExecutor.EnumCommandResult commandobjectiveexecutor_enumcommandresult = CommandObjectiveExecutor.EnumCommandResult.a(astring[i++]); + + if (commandobjectiveexecutor_enumcommandresult == null) { + throw new CommandException("commands.stats.failed", new Object[0]); + } else { + World world = icommandlistener.getWorld(); + CommandObjectiveExecutor commandobjectiveexecutor; + BlockPosition blockposition; + TileEntity tileentity; + + if (flag) { + blockposition = a(icommandlistener, astring, 1, false); + tileentity = world.getTileEntity(blockposition); + if (tileentity == null) { + throw new CommandException("commands.stats.noCompatibleBlock", new Object[] { Integer.valueOf(blockposition.getX()), Integer.valueOf(blockposition.getY()), Integer.valueOf(blockposition.getZ())}); + } + + if (tileentity instanceof TileEntityCommand) { + commandobjectiveexecutor = ((TileEntityCommand) tileentity).c(); + } else { + if (!(tileentity instanceof TileEntitySign)) { + throw new CommandException("commands.stats.noCompatibleBlock", new Object[] { Integer.valueOf(blockposition.getX()), Integer.valueOf(blockposition.getY()), Integer.valueOf(blockposition.getZ())}); + } + + commandobjectiveexecutor = ((TileEntitySign) tileentity).d(); + } + } else { + Entity entity = b(icommandlistener, astring[1]); + + commandobjectiveexecutor = entity.aU(); + } + + if ("set".equals(s)) { + String s1 = astring[i++]; + String s2 = astring[i]; + + if (s1.length() == 0 || s2.length() == 0) { + throw new CommandException("commands.stats.failed", new Object[0]); + } + + CommandObjectiveExecutor.a(commandobjectiveexecutor, commandobjectiveexecutor_enumcommandresult, s1, s2); + a(icommandlistener, this, "commands.stats.success", new Object[] { commandobjectiveexecutor_enumcommandresult.b(), s2, s1}); + } else if ("clear".equals(s)) { + CommandObjectiveExecutor.a(commandobjectiveexecutor, commandobjectiveexecutor_enumcommandresult, (String) null, (String) null); + a(icommandlistener, this, "commands.stats.cleared", new Object[] { commandobjectiveexecutor_enumcommandresult.b()}); + } + + if (flag) { + blockposition = a(icommandlistener, astring, 1, false); + tileentity = world.getTileEntity(blockposition); + tileentity.update(); + } + + } + } + } + + public List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { + return astring.length == 1 ? a(astring, new String[] { "entity", "block"}) : (astring.length == 2 && astring[0].equals("entity") ? a(astring, this.d()) : (astring.length >= 2 && astring.length <= 4 && astring[0].equals("block") ? a(astring, 1, blockposition) : ((astring.length != 3 || !astring[0].equals("entity")) && (astring.length != 5 || !astring[0].equals("block")) ? ((astring.length != 4 || !astring[0].equals("entity")) && (astring.length != 6 || !astring[0].equals("block")) ? ((astring.length != 6 || !astring[0].equals("entity")) && (astring.length != 8 || !astring[0].equals("block")) ? null : a(astring, (Collection) this.e())) : a(astring, CommandObjectiveExecutor.EnumCommandResult.c())) : a(astring, new String[] { "set", "clear"})))); + } + + protected String[] d() { + return MinecraftServer.getServer().getPlayers(); + } + + protected List e() { + Collection collection = MinecraftServer.getServer().getWorldServer(0).getScoreboard().getObjectives(); + ArrayList arraylist = Lists.newArrayList(); + Iterator iterator = collection.iterator(); + + while (iterator.hasNext()) { + ScoreboardObjective scoreboardobjective = (ScoreboardObjective) iterator.next(); + + if (!scoreboardobjective.getCriteria().isReadOnly()) { + arraylist.add(scoreboardobjective.getName()); + } + } + + return arraylist; + } + + public boolean isListStart(String[] astring, int i) { + return astring.length > 0 && astring[0].equals("entity") && i == 1; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandStop.java b/azurite-server/src/main/java/net/minecraft/server/CommandStop.java new file mode 100644 index 0000000..40b8a57 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandStop.java @@ -0,0 +1,22 @@ +package net.minecraft.server; + +public class CommandStop extends CommandAbstract { + + public CommandStop() {} + + public String getCommand() { + return "stop"; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.stop.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + if (MinecraftServer.getServer().worldServer != null) { + a(icommandlistener, this, "commands.stop.start", new Object[0]); + } + + MinecraftServer.getServer().safeShutdown(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandSummon.java b/azurite-server/src/main/java/net/minecraft/server/CommandSummon.java new file mode 100644 index 0000000..0581ec1 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandSummon.java @@ -0,0 +1,104 @@ +package net.minecraft.server; + +import java.util.Collection; +import java.util.List; + +public class CommandSummon extends CommandAbstract { + + public CommandSummon() {} + + public String getCommand() { + return "summon"; + } + + public int a() { + return 2; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.summon.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + if (astring.length < 1) { + throw new ExceptionUsage("commands.summon.usage", new Object[0]); + } else { + String s = astring[0]; + BlockPosition blockposition = icommandlistener.getChunkCoordinates(); + Vec3D vec3d = icommandlistener.d(); + double d0 = vec3d.a; + double d1 = vec3d.b; + double d2 = vec3d.c; + + if (astring.length >= 4) { + d0 = b(d0, astring[1], true); + d1 = b(d1, astring[2], false); + d2 = b(d2, astring[3], true); + blockposition = new BlockPosition(d0, d1, d2); + } + + World world = icommandlistener.getWorld(); + + if (!world.isLoaded(blockposition)) { + throw new CommandException("commands.summon.outOfWorld", new Object[0]); + } else if ("LightningBolt".equals(s)) { + world.strikeLightning(new EntityLightning(world, d0, d1, d2)); + a(icommandlistener, this, "commands.summon.success", new Object[0]); + } else { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + boolean flag = false; + + if (astring.length >= 5) { + IChatBaseComponent ichatbasecomponent = a(icommandlistener, astring, 4); + + try { + nbttagcompound = MojangsonParser.parse(ichatbasecomponent.c()); + flag = true; + } catch (MojangsonParseException mojangsonparseexception) { + throw new CommandException("commands.summon.tagError", new Object[] { mojangsonparseexception.getMessage()}); + } + } + + nbttagcompound.setString("id", s); + + Entity entity; + + try { + entity = EntityTypes.a(nbttagcompound, world); + } catch (RuntimeException runtimeexception) { + throw new CommandException("commands.summon.failed", new Object[0]); + } + + if (entity == null) { + throw new CommandException("commands.summon.failed", new Object[0]); + } else { + entity.setPositionRotation(d0, d1, d2, entity.yaw, entity.pitch); + if (!flag && entity instanceof EntityInsentient) { + ((EntityInsentient) entity).prepare(world.E(new BlockPosition(entity)), (GroupDataEntity) null); + } + + world.addEntity(entity); + Entity entity1 = entity; + + for (NBTTagCompound nbttagcompound1 = nbttagcompound; entity1 != null && nbttagcompound1.hasKeyOfType("Riding", 10); nbttagcompound1 = nbttagcompound1.getCompound("Riding")) { + Entity entity2 = EntityTypes.a(nbttagcompound1.getCompound("Riding"), world); + + if (entity2 != null) { + entity2.setPositionRotation(d0, d1, d2, entity2.yaw, entity2.pitch); + world.addEntity(entity2); + entity1.mount(entity2); + } + + entity1 = entity2; + } + + a(icommandlistener, this, "commands.summon.success", new Object[0]); + } + } + } + } + + public List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { + return astring.length == 1 ? a(astring, (Collection) EntityTypes.b()) : (astring.length > 1 && astring.length <= 4 ? a(astring, 1, blockposition) : null); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandTell.java b/azurite-server/src/main/java/net/minecraft/server/CommandTell.java new file mode 100644 index 0000000..2739214 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandTell.java @@ -0,0 +1,54 @@ +package net.minecraft.server; + +import java.util.Arrays; +import java.util.List; + +public class CommandTell extends CommandAbstract { + + public CommandTell() {} + + public List b() { + return Arrays.asList(new String[] { "w", "msg"}); + } + + public String getCommand() { + return "tell"; + } + + public int a() { + return 0; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.message.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + if (astring.length < 2) { + throw new ExceptionUsage("commands.message.usage", new Object[0]); + } else { + EntityPlayer entityplayer = a(icommandlistener, astring[0]); + + if (entityplayer == icommandlistener) { + throw new ExceptionPlayerNotFound("commands.message.sameTarget", new Object[0]); + } else { + IChatBaseComponent ichatbasecomponent = b(icommandlistener, astring, 1, !(icommandlistener instanceof EntityHuman)); + ChatMessage chatmessage = new ChatMessage("commands.message.display.incoming", new Object[] { icommandlistener.getScoreboardDisplayName(), ichatbasecomponent.f()}); + ChatMessage chatmessage1 = new ChatMessage("commands.message.display.outgoing", new Object[] { entityplayer.getScoreboardDisplayName(), ichatbasecomponent.f()}); + + chatmessage.getChatModifier().setColor(EnumChatFormat.GRAY).setItalic(Boolean.valueOf(true)); + chatmessage1.getChatModifier().setColor(EnumChatFormat.GRAY).setItalic(Boolean.valueOf(true)); + entityplayer.sendMessage(chatmessage); + icommandlistener.sendMessage(chatmessage1); + } + } + } + + public List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { + return a(astring, MinecraftServer.getServer().getPlayers()); + } + + public boolean isListStart(String[] astring, int i) { + return i == 0; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandTellRaw.java b/azurite-server/src/main/java/net/minecraft/server/CommandTellRaw.java new file mode 100644 index 0000000..f7975a7 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandTellRaw.java @@ -0,0 +1,49 @@ +package net.minecraft.server; + +import com.google.gson.JsonParseException; +import java.util.List; +import org.apache.commons.lang3.exception.ExceptionUtils; + +public class CommandTellRaw extends CommandAbstract { + + public CommandTellRaw() {} + + public String getCommand() { + return "tellraw"; + } + + public int a() { + return 2; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.tellraw.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + if (astring.length < 2) { + throw new ExceptionUsage("commands.tellraw.usage", new Object[0]); + } else { + EntityPlayer entityplayer = a(icommandlistener, astring[0]); + String s = a(astring, 1); + + try { + IChatBaseComponent ichatbasecomponent = IChatBaseComponent.ChatSerializer.a(s); + + entityplayer.sendMessage(ChatComponentUtils.filterForDisplay(icommandlistener, ichatbasecomponent, entityplayer)); + } catch (JsonParseException jsonparseexception) { + Throwable throwable = ExceptionUtils.getRootCause(jsonparseexception); + + throw new ExceptionInvalidSyntax("commands.tellraw.jsonException", new Object[] { throwable == null ? "" : throwable.getMessage()}); + } + } + } + + public List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { + return astring.length == 1 ? a(astring, MinecraftServer.getServer().getPlayers()) : null; + } + + public boolean isListStart(String[] astring, int i) { + return i == 0; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandTestFor.java b/azurite-server/src/main/java/net/minecraft/server/CommandTestFor.java new file mode 100644 index 0000000..07dbdc1 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandTestFor.java @@ -0,0 +1,56 @@ +package net.minecraft.server; + +import java.util.List; + +public class CommandTestFor extends CommandAbstract { + + public CommandTestFor() {} + + public String getCommand() { + return "testfor"; + } + + public int a() { + return 2; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.testfor.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + if (astring.length < 1) { + throw new ExceptionUsage("commands.testfor.usage", new Object[0]); + } else { + Entity entity = b(icommandlistener, astring[0]); + NBTTagCompound nbttagcompound = null; + + if (astring.length >= 2) { + try { + nbttagcompound = MojangsonParser.parse(a(astring, 1)); + } catch (MojangsonParseException mojangsonparseexception) { + throw new CommandException("commands.testfor.tagError", new Object[] { mojangsonparseexception.getMessage()}); + } + } + + if (nbttagcompound != null) { + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + + entity.e(nbttagcompound1); + if (!GameProfileSerializer.a(nbttagcompound, nbttagcompound1, true)) { + throw new CommandException("commands.testfor.failure", new Object[] { entity.getName()}); + } + } + + a(icommandlistener, this, "commands.testfor.success", new Object[] { entity.getName()}); + } + } + + public boolean isListStart(String[] astring, int i) { + return i == 0; + } + + public List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { + return astring.length == 1 ? a(astring, MinecraftServer.getServer().getPlayers()) : null; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandTestForBlock.java b/azurite-server/src/main/java/net/minecraft/server/CommandTestForBlock.java new file mode 100644 index 0000000..6362d75 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandTestForBlock.java @@ -0,0 +1,98 @@ +package net.minecraft.server; + +import java.util.Collection; +import java.util.List; + +public class CommandTestForBlock extends CommandAbstract { + + public CommandTestForBlock() {} + + public String getCommand() { + return "testforblock"; + } + + public int a() { + return 2; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.testforblock.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + if (astring.length < 4) { + throw new ExceptionUsage("commands.testforblock.usage", new Object[0]); + } else { + icommandlistener.a(CommandObjectiveExecutor.EnumCommandResult.AFFECTED_BLOCKS, 0); + BlockPosition blockposition = a(icommandlistener, astring, 0, false); + Block block = Block.getByName(astring[3]); + + if (block == null) { + throw new ExceptionInvalidNumber("commands.setblock.notFound", new Object[] { astring[3]}); + } else { + int i = -1; + + if (astring.length >= 5) { + i = a(astring[4], -1, 15); + } + + World world = icommandlistener.getWorld(); + + if (!world.isLoaded(blockposition)) { + throw new CommandException("commands.testforblock.outOfWorld", new Object[0]); + } else { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + boolean flag = false; + + if (astring.length >= 6 && block.isTileEntity()) { + String s = a(icommandlistener, astring, 5).c(); + + try { + nbttagcompound = MojangsonParser.parse(s); + flag = true; + } catch (MojangsonParseException mojangsonparseexception) { + throw new CommandException("commands.setblock.tagError", new Object[] { mojangsonparseexception.getMessage()}); + } + } + + IBlockData iblockdata = world.getType(blockposition); + Block block1 = iblockdata.getBlock(); + + if (block1 != block) { + throw new CommandException("commands.testforblock.failed.tile", new Object[] { Integer.valueOf(blockposition.getX()), Integer.valueOf(blockposition.getY()), Integer.valueOf(blockposition.getZ()), block1.getName(), block.getName()}); + } else { + if (i > -1) { + int j = iblockdata.getBlock().toLegacyData(iblockdata); + + if (j != i) { + throw new CommandException("commands.testforblock.failed.data", new Object[] { Integer.valueOf(blockposition.getX()), Integer.valueOf(blockposition.getY()), Integer.valueOf(blockposition.getZ()), Integer.valueOf(j), Integer.valueOf(i)}); + } + } + + if (flag) { + TileEntity tileentity = world.getTileEntity(blockposition); + + if (tileentity == null) { + throw new CommandException("commands.testforblock.failed.tileEntity", new Object[] { Integer.valueOf(blockposition.getX()), Integer.valueOf(blockposition.getY()), Integer.valueOf(blockposition.getZ())}); + } + + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + + tileentity.b(nbttagcompound1); + if (!GameProfileSerializer.a(nbttagcompound, nbttagcompound1, true)) { + throw new CommandException("commands.testforblock.failed.nbt", new Object[] { Integer.valueOf(blockposition.getX()), Integer.valueOf(blockposition.getY()), Integer.valueOf(blockposition.getZ())}); + } + } + + icommandlistener.a(CommandObjectiveExecutor.EnumCommandResult.AFFECTED_BLOCKS, 1); + a(icommandlistener, this, "commands.testforblock.success", new Object[] { Integer.valueOf(blockposition.getX()), Integer.valueOf(blockposition.getY()), Integer.valueOf(blockposition.getZ())}); + } + } + } + } + } + + public List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { + return astring.length > 0 && astring.length <= 3 ? a(astring, 0, blockposition) : (astring.length == 4 ? a(astring, (Collection) Block.REGISTRY.keySet()) : null); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandTestForBlocks.java b/azurite-server/src/main/java/net/minecraft/server/CommandTestForBlocks.java new file mode 100644 index 0000000..05d95ea --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandTestForBlocks.java @@ -0,0 +1,109 @@ +package net.minecraft.server; + +import java.util.List; + +public class CommandTestForBlocks extends CommandAbstract { + + public CommandTestForBlocks() {} + + public String getCommand() { + return "testforblocks"; + } + + public int a() { + return 2; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.compare.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + if (astring.length < 9) { + throw new ExceptionUsage("commands.compare.usage", new Object[0]); + } else { + icommandlistener.a(CommandObjectiveExecutor.EnumCommandResult.AFFECTED_BLOCKS, 0); + BlockPosition blockposition = a(icommandlistener, astring, 0, false); + BlockPosition blockposition1 = a(icommandlistener, astring, 3, false); + BlockPosition blockposition2 = a(icommandlistener, astring, 6, false); + StructureBoundingBox structureboundingbox = new StructureBoundingBox(blockposition, blockposition1); + StructureBoundingBox structureboundingbox1 = new StructureBoundingBox(blockposition2, blockposition2.a(structureboundingbox.b())); + int i = structureboundingbox.c() * structureboundingbox.d() * structureboundingbox.e(); + + if (i > 524288) { + throw new CommandException("commands.compare.tooManyBlocks", new Object[] { Integer.valueOf(i), Integer.valueOf(524288)}); + } else if (structureboundingbox.b >= 0 && structureboundingbox.e < 256 && structureboundingbox1.b >= 0 && structureboundingbox1.e < 256) { + World world = icommandlistener.getWorld(); + + if (world.a(structureboundingbox) && world.a(structureboundingbox1)) { + boolean flag = false; + + if (astring.length > 9 && astring[9].equals("masked")) { + flag = true; + } + + i = 0; + BlockPosition blockposition3 = new BlockPosition(structureboundingbox1.a - structureboundingbox.a, structureboundingbox1.b - structureboundingbox.b, structureboundingbox1.c - structureboundingbox.c); + BlockPosition.MutableBlockPosition blockposition_mutableblockposition = new BlockPosition.MutableBlockPosition(); + BlockPosition.MutableBlockPosition blockposition_mutableblockposition1 = new BlockPosition.MutableBlockPosition(); + + for (int j = structureboundingbox.c; j <= structureboundingbox.f; ++j) { + for (int k = structureboundingbox.b; k <= structureboundingbox.e; ++k) { + for (int l = structureboundingbox.a; l <= structureboundingbox.d; ++l) { + blockposition_mutableblockposition.c(l, k, j); + blockposition_mutableblockposition1.c(l + blockposition3.getX(), k + blockposition3.getY(), j + blockposition3.getZ()); + boolean flag1 = false; + IBlockData iblockdata = world.getType(blockposition_mutableblockposition); + + if (!flag || iblockdata.getBlock() != Blocks.AIR) { + if (iblockdata == world.getType(blockposition_mutableblockposition1)) { + TileEntity tileentity = world.getTileEntity(blockposition_mutableblockposition); + TileEntity tileentity1 = world.getTileEntity(blockposition_mutableblockposition1); + + if (tileentity != null && tileentity1 != null) { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + + tileentity.b(nbttagcompound); + nbttagcompound.remove("x"); + nbttagcompound.remove("y"); + nbttagcompound.remove("z"); + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + + tileentity1.b(nbttagcompound1); + nbttagcompound1.remove("x"); + nbttagcompound1.remove("y"); + nbttagcompound1.remove("z"); + if (!nbttagcompound.equals(nbttagcompound1)) { + flag1 = true; + } + } else if (tileentity != null) { + flag1 = true; + } + } else { + flag1 = true; + } + + ++i; + if (flag1) { + throw new CommandException("commands.compare.failed", new Object[0]); + } + } + } + } + } + + icommandlistener.a(CommandObjectiveExecutor.EnumCommandResult.AFFECTED_BLOCKS, i); + a(icommandlistener, this, "commands.compare.success", new Object[] { Integer.valueOf(i)}); + } else { + throw new CommandException("commands.compare.outOfWorld", new Object[0]); + } + } else { + throw new CommandException("commands.compare.outOfWorld", new Object[0]); + } + } + } + + public List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { + return astring.length > 0 && astring.length <= 3 ? a(astring, 0, blockposition) : (astring.length > 3 && astring.length <= 6 ? a(astring, 3, blockposition) : (astring.length > 6 && astring.length <= 9 ? a(astring, 6, blockposition) : (astring.length == 10 ? a(astring, new String[] { "masked", "all"}) : null))); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandTime.java b/azurite-server/src/main/java/net/minecraft/server/CommandTime.java new file mode 100644 index 0000000..ec835de --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandTime.java @@ -0,0 +1,85 @@ +package net.minecraft.server; + +import java.util.List; + +public class CommandTime extends CommandAbstract { + + public CommandTime() {} + + public String getCommand() { + return "time"; + } + + public int a() { + return 2; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.time.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + if (astring.length > 1) { + int i; + + if (astring[0].equals("set")) { + if (astring[1].equals("day")) { + i = 1000; + } else if (astring[1].equals("night")) { + i = 13000; + } else { + i = a(astring[1], 0); + } + + this.a(icommandlistener, i); + a(icommandlistener, this, "commands.time.set", new Object[] { Integer.valueOf(i)}); + return; + } + + if (astring[0].equals("add")) { + i = a(astring[1], 0); + this.b(icommandlistener, i); + a(icommandlistener, this, "commands.time.added", new Object[] { Integer.valueOf(i)}); + return; + } + + if (astring[0].equals("query")) { + if (astring[1].equals("daytime")) { + i = (int) (icommandlistener.getWorld().getDayTime() % 2147483647L); + icommandlistener.a(CommandObjectiveExecutor.EnumCommandResult.QUERY_RESULT, i); + a(icommandlistener, this, "commands.time.query", new Object[] { Integer.valueOf(i)}); + return; + } + + if (astring[1].equals("gametime")) { + i = (int) (icommandlistener.getWorld().getTime() % 2147483647L); + icommandlistener.a(CommandObjectiveExecutor.EnumCommandResult.QUERY_RESULT, i); + a(icommandlistener, this, "commands.time.query", new Object[] { Integer.valueOf(i)}); + return; + } + } + } + + throw new ExceptionUsage("commands.time.usage", new Object[0]); + } + + public List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { + return astring.length == 1 ? a(astring, new String[] { "set", "add", "query"}) : (astring.length == 2 && astring[0].equals("set") ? a(astring, new String[] { "day", "night"}) : (astring.length == 2 && astring[0].equals("query") ? a(astring, new String[] { "daytime", "gametime"}) : null)); + } + + protected void a(ICommandListener icommandlistener, int i) { + for (int j = 0; j < MinecraftServer.getServer().worldServer.length; ++j) { + MinecraftServer.getServer().worldServer[j].setDayTime((long) i); + } + + } + + protected void b(ICommandListener icommandlistener, int i) { + for (int j = 0; j < MinecraftServer.getServer().worldServer.length; ++j) { + WorldServer worldserver = MinecraftServer.getServer().worldServer[j]; + + worldserver.setDayTime(worldserver.getDayTime() + (long) i); + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandTitle.java b/azurite-server/src/main/java/net/minecraft/server/CommandTitle.java new file mode 100644 index 0000000..74c40d8 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandTitle.java @@ -0,0 +1,95 @@ +package net.minecraft.server; + +import com.google.gson.JsonParseException; +import java.util.List; +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +public class CommandTitle extends CommandAbstract { + + private static final Logger a = LogManager.getLogger(); + + public CommandTitle() {} + + public String getCommand() { + return "title"; + } + + public int a() { + return 2; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.title.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + if (astring.length < 2) { + throw new ExceptionUsage("commands.title.usage", new Object[0]); + } else { + if (astring.length < 3) { + if ("title".equals(astring[1]) || "subtitle".equals(astring[1])) { + throw new ExceptionUsage("commands.title.usage.title", new Object[0]); + } + + if ("times".equals(astring[1])) { + throw new ExceptionUsage("commands.title.usage.times", new Object[0]); + } + } + + EntityPlayer entityplayer = a(icommandlistener, astring[0]); + PacketPlayOutTitle.EnumTitleAction packetplayouttitle_enumtitleaction = PacketPlayOutTitle.EnumTitleAction.a(astring[1]); + + if (packetplayouttitle_enumtitleaction != PacketPlayOutTitle.EnumTitleAction.CLEAR && packetplayouttitle_enumtitleaction != PacketPlayOutTitle.EnumTitleAction.RESET) { + if (packetplayouttitle_enumtitleaction == PacketPlayOutTitle.EnumTitleAction.TIMES) { + if (astring.length != 5) { + throw new ExceptionUsage("commands.title.usage", new Object[0]); + } else { + int i = a(astring[2]); + int j = a(astring[3]); + int k = a(astring[4]); + PacketPlayOutTitle packetplayouttitle = new PacketPlayOutTitle(i, j, k); + + entityplayer.playerConnection.sendPacket(packetplayouttitle); + a(icommandlistener, this, "commands.title.success", new Object[0]); + } + } else if (astring.length < 3) { + throw new ExceptionUsage("commands.title.usage", new Object[0]); + } else { + String s = a(astring, 2); + + IChatBaseComponent ichatbasecomponent; + + try { + ichatbasecomponent = IChatBaseComponent.ChatSerializer.a(s); + } catch (JsonParseException jsonparseexception) { + Throwable throwable = ExceptionUtils.getRootCause(jsonparseexception); + + throw new ExceptionInvalidSyntax("commands.tellraw.jsonException", new Object[] { throwable == null ? "" : throwable.getMessage()}); + } + + PacketPlayOutTitle packetplayouttitle1 = new PacketPlayOutTitle(packetplayouttitle_enumtitleaction, ChatComponentUtils.filterForDisplay(icommandlistener, ichatbasecomponent, entityplayer)); + + entityplayer.playerConnection.sendPacket(packetplayouttitle1); + a(icommandlistener, this, "commands.title.success", new Object[0]); + } + } else if (astring.length != 2) { + throw new ExceptionUsage("commands.title.usage", new Object[0]); + } else { + PacketPlayOutTitle packetplayouttitle2 = new PacketPlayOutTitle(packetplayouttitle_enumtitleaction, (IChatBaseComponent) null); + + entityplayer.playerConnection.sendPacket(packetplayouttitle2); + a(icommandlistener, this, "commands.title.success", new Object[0]); + } + } + } + + public List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { + return astring.length == 1 ? a(astring, MinecraftServer.getServer().getPlayers()) : (astring.length == 2 ? a(astring, PacketPlayOutTitle.EnumTitleAction.a()) : null); + } + + public boolean isListStart(String[] astring, int i) { + return i == 0; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandToggleDownfall.java b/azurite-server/src/main/java/net/minecraft/server/CommandToggleDownfall.java new file mode 100644 index 0000000..54f2060 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandToggleDownfall.java @@ -0,0 +1,29 @@ +package net.minecraft.server; + +public class CommandToggleDownfall extends CommandAbstract { + + public CommandToggleDownfall() {} + + public String getCommand() { + return "toggledownfall"; + } + + public int a() { + return 2; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.downfall.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + this.d(); + a(icommandlistener, this, "commands.downfall.success", new Object[0]); + } + + protected void d() { + WorldData worlddata = MinecraftServer.getServer().worldServer[0].getWorldData(); + + worlddata.setStorm(!worlddata.hasStorm()); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandTp.java b/azurite-server/src/main/java/net/minecraft/server/CommandTp.java new file mode 100644 index 0000000..008b8c8 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandTp.java @@ -0,0 +1,132 @@ +package net.minecraft.server; + +import java.util.EnumSet; +import java.util.List; + +public class CommandTp extends CommandAbstract { + + public CommandTp() {} + + public String getCommand() { + return "tp"; + } + + public int a() { + return 2; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.tp.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + if (astring.length < 1) { + throw new ExceptionUsage("commands.tp.usage", new Object[0]); + } else { + byte b0 = 0; + Object object; + + if (astring.length != 2 && astring.length != 4 && astring.length != 6) { + object = b(icommandlistener); + } else { + object = b(icommandlistener, astring[0]); + b0 = 1; + } + + if (astring.length != 1 && astring.length != 2) { + if (astring.length < b0 + 3) { + throw new ExceptionUsage("commands.tp.usage", new Object[0]); + } else if (((Entity) object).world != null) { + int i = b0 + 1; + CommandAbstract.CommandNumber commandabstract_commandnumber = a(((Entity) object).locX, astring[b0], true); + CommandAbstract.CommandNumber commandabstract_commandnumber1 = a(((Entity) object).locY, astring[i++], 0, 0, false); + CommandAbstract.CommandNumber commandabstract_commandnumber2 = a(((Entity) object).locZ, astring[i++], true); + CommandAbstract.CommandNumber commandabstract_commandnumber3 = a((double) ((Entity) object).yaw, astring.length > i ? astring[i++] : "~", false); + CommandAbstract.CommandNumber commandabstract_commandnumber4 = a((double) ((Entity) object).pitch, astring.length > i ? astring[i] : "~", false); + float f; + + if (object instanceof EntityPlayer) { + EnumSet enumset = EnumSet.noneOf(PacketPlayOutPosition.EnumPlayerTeleportFlags.class); + + if (commandabstract_commandnumber.c()) { + enumset.add(PacketPlayOutPosition.EnumPlayerTeleportFlags.X); + } + + if (commandabstract_commandnumber1.c()) { + enumset.add(PacketPlayOutPosition.EnumPlayerTeleportFlags.Y); + } + + if (commandabstract_commandnumber2.c()) { + enumset.add(PacketPlayOutPosition.EnumPlayerTeleportFlags.Z); + } + + if (commandabstract_commandnumber4.c()) { + enumset.add(PacketPlayOutPosition.EnumPlayerTeleportFlags.X_ROT); + } + + if (commandabstract_commandnumber3.c()) { + enumset.add(PacketPlayOutPosition.EnumPlayerTeleportFlags.Y_ROT); + } + + f = (float) commandabstract_commandnumber3.b(); + if (!commandabstract_commandnumber3.c()) { + f = MathHelper.g(f); + } + + float f1 = (float) commandabstract_commandnumber4.b(); + + if (!commandabstract_commandnumber4.c()) { + f1 = MathHelper.g(f1); + } + + if (f1 > 90.0F || f1 < -90.0F) { + f1 = MathHelper.g(180.0F - f1); + f = MathHelper.g(f + 180.0F); + } + + ((Entity) object).mount((Entity) null); + ((EntityPlayer) object).playerConnection.a(commandabstract_commandnumber.b(), commandabstract_commandnumber1.b(), commandabstract_commandnumber2.b(), f, f1, enumset); + ((Entity) object).f(f); + } else { + float f2 = (float) MathHelper.g(commandabstract_commandnumber3.a()); + + f = (float) MathHelper.g(commandabstract_commandnumber4.a()); + if (f > 90.0F || f < -90.0F) { + f = MathHelper.g(180.0F - f); + f2 = MathHelper.g(f2 + 180.0F); + } + + ((Entity) object).setPositionRotation(commandabstract_commandnumber.a(), commandabstract_commandnumber1.a(), commandabstract_commandnumber2.a(), f2, f); + ((Entity) object).f(f2); + } + + a(icommandlistener, this, "commands.tp.success.coordinates", new Object[] { ((Entity) object).getName(), Double.valueOf(commandabstract_commandnumber.a()), Double.valueOf(commandabstract_commandnumber1.a()), Double.valueOf(commandabstract_commandnumber2.a())}); + } + } else { + Entity entity = b(icommandlistener, astring[astring.length - 1]); + + // CraftBukkit Start + // Use Bukkit teleport method in all cases. It has cross dimensional handling, events + if (((Entity) object).getBukkitEntity().teleport(entity.getBukkitEntity(), org.bukkit.event.player.PlayerTeleportEvent.TeleportCause.COMMAND)) { + a(icommandlistener, this, "commands.tp.success", new Object[]{((Entity) object).getName(), entity.getName()}); + // CraftBukkit End + } + } + } + } + + public List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { + return astring.length != 1 && astring.length != 2 ? null : a(astring, MinecraftServer.getServer().getPlayers()); + } + + public boolean isListStart(String[] astring, int i) { + return i == 0; + } + + // CraftBukkit start - fix decompile error + @Override + public int compareTo(ICommand o) { + return a((ICommand) o); + } + // CraftBukkit end +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandTrigger.java b/azurite-server/src/main/java/net/minecraft/server/CommandTrigger.java new file mode 100644 index 0000000..3b0d304 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandTrigger.java @@ -0,0 +1,98 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +public class CommandTrigger extends CommandAbstract { + + public CommandTrigger() {} + + public String getCommand() { + return "trigger"; + } + + public int a() { + return 0; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.trigger.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + if (astring.length < 3) { + throw new ExceptionUsage("commands.trigger.usage", new Object[0]); + } else { + EntityPlayer entityplayer; + + if (icommandlistener instanceof EntityPlayer) { + entityplayer = (EntityPlayer) icommandlistener; + } else { + Entity entity = icommandlistener.f(); + + if (!(entity instanceof EntityPlayer)) { + throw new CommandException("commands.trigger.invalidPlayer", new Object[0]); + } + + entityplayer = (EntityPlayer) entity; + } + + Scoreboard scoreboard = MinecraftServer.getServer().getWorldServer(0).getScoreboard(); + ScoreboardObjective scoreboardobjective = scoreboard.getObjective(astring[0]); + + if (scoreboardobjective != null && scoreboardobjective.getCriteria() == IScoreboardCriteria.c) { + int i = a(astring[2]); + + if (!scoreboard.b(entityplayer.getName(), scoreboardobjective)) { + throw new CommandException("commands.trigger.invalidObjective", new Object[] { astring[0]}); + } else { + ScoreboardScore scoreboardscore = scoreboard.getPlayerScoreForObjective(entityplayer.getName(), scoreboardobjective); + + if (scoreboardscore.g()) { + throw new CommandException("commands.trigger.disabled", new Object[] { astring[0]}); + } else { + if ("set".equals(astring[1])) { + scoreboardscore.setScore(i); + } else { + if (!"add".equals(astring[1])) { + throw new CommandException("commands.trigger.invalidMode", new Object[] { astring[1]}); + } + + scoreboardscore.addScore(i); + } + + scoreboardscore.a(true); + if (entityplayer.playerInteractManager.isCreative()) { + a(icommandlistener, this, "commands.trigger.success", new Object[] { astring[0], astring[1], astring[2]}); + } + + } + } + } else { + throw new CommandException("commands.trigger.invalidObjective", new Object[] { astring[0]}); + } + } + } + + public List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { + if (astring.length == 1) { + Scoreboard scoreboard = MinecraftServer.getServer().getWorldServer(0).getScoreboard(); + ArrayList arraylist = Lists.newArrayList(); + Iterator iterator = scoreboard.getObjectives().iterator(); + + while (iterator.hasNext()) { + ScoreboardObjective scoreboardobjective = (ScoreboardObjective) iterator.next(); + + if (scoreboardobjective.getCriteria() == IScoreboardCriteria.c) { + arraylist.add(scoreboardobjective.getName()); + } + } + + return a(astring, (String[]) arraylist.toArray(new String[arraylist.size()])); + } else { + return astring.length == 2 ? a(astring, new String[] { "add", "set"}) : null; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandWeather.java b/azurite-server/src/main/java/net/minecraft/server/CommandWeather.java new file mode 100644 index 0000000..2a8861f --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandWeather.java @@ -0,0 +1,68 @@ +package net.minecraft.server; + +import java.util.List; +import java.util.Random; + +public class CommandWeather extends CommandAbstract { + + public CommandWeather() {} + + public String getCommand() { + return "weather"; + } + + public int a() { + return 2; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.weather.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + if (astring.length >= 1 && astring.length <= 2) { + int i = (300 + (new Random()).nextInt(600)) * 20; + + if (astring.length >= 2) { + i = a(astring[1], 1, 1000000) * 20; + } + + WorldServer worldserver = MinecraftServer.getServer().worldServer[0]; + WorldData worlddata = worldserver.getWorldData(); + + if ("clear".equalsIgnoreCase(astring[0])) { + worlddata.i(i); + worlddata.setWeatherDuration(0); + worlddata.setThunderDuration(0); + worlddata.setStorm(false); + worlddata.setThundering(false); + a(icommandlistener, this, "commands.weather.clear", new Object[0]); + } else if ("rain".equalsIgnoreCase(astring[0])) { + worlddata.i(0); + worlddata.setWeatherDuration(i); + worlddata.setThunderDuration(i); + worlddata.setStorm(true); + worlddata.setThundering(false); + a(icommandlistener, this, "commands.weather.rain", new Object[0]); + } else { + if (!"thunder".equalsIgnoreCase(astring[0])) { + throw new ExceptionUsage("commands.weather.usage", new Object[0]); + } + + worlddata.i(0); + worlddata.setWeatherDuration(i); + worlddata.setThunderDuration(i); + worlddata.setStorm(true); + worlddata.setThundering(true); + a(icommandlistener, this, "commands.weather.thunder", new Object[0]); + } + + } else { + throw new ExceptionUsage("commands.weather.usage", new Object[0]); + } + } + + public List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { + return astring.length == 1 ? a(astring, new String[] { "clear", "rain", "thunder"}) : null; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandWhitelist.java b/azurite-server/src/main/java/net/minecraft/server/CommandWhitelist.java new file mode 100644 index 0000000..7c29357 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandWhitelist.java @@ -0,0 +1,92 @@ +package net.minecraft.server; + +import com.mojang.authlib.GameProfile; +import java.util.List; + +public class CommandWhitelist extends CommandAbstract { + + public CommandWhitelist() {} + + public String getCommand() { + return "whitelist"; + } + + public int a() { + return 3; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.whitelist.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + if (astring.length < 1) { + throw new ExceptionUsage("commands.whitelist.usage", new Object[0]); + } else { + MinecraftServer minecraftserver = MinecraftServer.getServer(); + + if (astring[0].equals("on")) { + minecraftserver.getPlayerList().setHasWhitelist(true); + a(icommandlistener, this, "commands.whitelist.enabled", new Object[0]); + } else if (astring[0].equals("off")) { + minecraftserver.getPlayerList().setHasWhitelist(false); + a(icommandlistener, this, "commands.whitelist.disabled", new Object[0]); + } else if (astring[0].equals("list")) { + icommandlistener.sendMessage(new ChatMessage("commands.whitelist.list", new Object[] { Integer.valueOf(minecraftserver.getPlayerList().getWhitelisted().length), Integer.valueOf(minecraftserver.getPlayerList().getSeenPlayers().length)})); + String[] astring1 = minecraftserver.getPlayerList().getWhitelisted(); + + icommandlistener.sendMessage(new ChatComponentText(a((Object[]) astring1))); + } else { + GameProfile gameprofile; + + if (astring[0].equals("add")) { + if (astring.length < 2) { + throw new ExceptionUsage("commands.whitelist.add.usage", new Object[0]); + } + + gameprofile = minecraftserver.getUserCache().getProfile(astring[1]); + if (gameprofile == null) { + throw new CommandException("commands.whitelist.add.failed", new Object[] { astring[1]}); + } + + minecraftserver.getPlayerList().addWhitelist(gameprofile); + a(icommandlistener, this, "commands.whitelist.add.success", new Object[] { astring[1]}); + } else if (astring[0].equals("remove")) { + if (astring.length < 2) { + throw new ExceptionUsage("commands.whitelist.remove.usage", new Object[0]); + } + + gameprofile = minecraftserver.getPlayerList().getWhitelist().a(astring[1]); + if (gameprofile == null) { + throw new CommandException("commands.whitelist.remove.failed", new Object[] { astring[1]}); + } + + minecraftserver.getPlayerList().removeWhitelist(gameprofile); + a(icommandlistener, this, "commands.whitelist.remove.success", new Object[] { astring[1]}); + } else if (astring[0].equals("reload")) { + minecraftserver.getPlayerList().reloadWhitelist(); + a(icommandlistener, this, "commands.whitelist.reloaded", new Object[0]); + } + } + + } + } + + public List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { + if (astring.length == 1) { + return a(astring, new String[] { "on", "off", "list", "add", "remove", "reload"}); + } else { + if (astring.length == 2) { + if (astring[0].equals("remove")) { + return a(astring, MinecraftServer.getServer().getPlayerList().getWhitelisted()); + } + + if (astring[0].equals("add")) { + return a(astring, MinecraftServer.getServer().getUserCache().a()); + } + } + + return null; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandWorldBorder.java b/azurite-server/src/main/java/net/minecraft/server/CommandWorldBorder.java new file mode 100644 index 0000000..fb24117 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandWorldBorder.java @@ -0,0 +1,148 @@ +package net.minecraft.server; + +import java.util.List; + +public class CommandWorldBorder extends CommandAbstract { + + public CommandWorldBorder() {} + + public String getCommand() { + return "worldborder"; + } + + public int a() { + return 2; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.worldborder.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + if (astring.length < 1) { + throw new ExceptionUsage("commands.worldborder.usage", new Object[0]); + } else { + WorldBorder worldborder = this.d(); + double d0; + double d1; + long i; + + if (astring[0].equals("set")) { + if (astring.length != 2 && astring.length != 3) { + throw new ExceptionUsage("commands.worldborder.set.usage", new Object[0]); + } + + d0 = worldborder.j(); + d1 = a(astring[1], 1.0D, 6.0E7D); + i = astring.length > 2 ? a(astring[2], 0L, 9223372036854775L) * 1000L : 0L; + if (i > 0L) { + worldborder.transitionSizeBetween(d0, d1, i); + if (d0 > d1) { + a(icommandlistener, this, "commands.worldborder.setSlowly.shrink.success", new Object[] { String.format("%.1f", new Object[] { Double.valueOf(d1)}), String.format("%.1f", new Object[] { Double.valueOf(d0)}), Long.toString(i / 1000L)}); + } else { + a(icommandlistener, this, "commands.worldborder.setSlowly.grow.success", new Object[] { String.format("%.1f", new Object[] { Double.valueOf(d1)}), String.format("%.1f", new Object[] { Double.valueOf(d0)}), Long.toString(i / 1000L)}); + } + } else { + worldborder.setSize(d1); + a(icommandlistener, this, "commands.worldborder.set.success", new Object[] { String.format("%.1f", new Object[] { Double.valueOf(d1)}), String.format("%.1f", new Object[] { Double.valueOf(d0)})}); + } + } else if (astring[0].equals("add")) { + if (astring.length != 2 && astring.length != 3) { + throw new ExceptionUsage("commands.worldborder.add.usage", new Object[0]); + } + + d0 = worldborder.getSize(); + d1 = d0 + a(astring[1], -d0, 6.0E7D - d0); + i = worldborder.i() + (astring.length > 2 ? a(astring[2], 0L, 9223372036854775L) * 1000L : 0L); + if (i > 0L) { + worldborder.transitionSizeBetween(d0, d1, i); + if (d0 > d1) { + a(icommandlistener, this, "commands.worldborder.setSlowly.shrink.success", new Object[] { String.format("%.1f", new Object[] { Double.valueOf(d1)}), String.format("%.1f", new Object[] { Double.valueOf(d0)}), Long.toString(i / 1000L)}); + } else { + a(icommandlistener, this, "commands.worldborder.setSlowly.grow.success", new Object[] { String.format("%.1f", new Object[] { Double.valueOf(d1)}), String.format("%.1f", new Object[] { Double.valueOf(d0)}), Long.toString(i / 1000L)}); + } + } else { + worldborder.setSize(d1); + a(icommandlistener, this, "commands.worldborder.set.success", new Object[] { String.format("%.1f", new Object[] { Double.valueOf(d1)}), String.format("%.1f", new Object[] { Double.valueOf(d0)})}); + } + } else if (astring[0].equals("center")) { + if (astring.length != 3) { + throw new ExceptionUsage("commands.worldborder.center.usage", new Object[0]); + } + + BlockPosition blockposition = icommandlistener.getChunkCoordinates(); + double d2 = b((double) blockposition.getX() + 0.5D, astring[1], true); + double d3 = b((double) blockposition.getZ() + 0.5D, astring[2], true); + + worldborder.setCenter(d2, d3); + a(icommandlistener, this, "commands.worldborder.center.success", new Object[] { Double.valueOf(d2), Double.valueOf(d3)}); + } else if (astring[0].equals("damage")) { + if (astring.length < 2) { + throw new ExceptionUsage("commands.worldborder.damage.usage", new Object[0]); + } + + if (astring[1].equals("buffer")) { + if (astring.length != 3) { + throw new ExceptionUsage("commands.worldborder.damage.buffer.usage", new Object[0]); + } + + d0 = a(astring[2], 0.0D); + d1 = worldborder.getDamageBuffer(); + worldborder.setDamageBuffer(d0); + a(icommandlistener, this, "commands.worldborder.damage.buffer.success", new Object[] { String.format("%.1f", new Object[] { Double.valueOf(d0)}), String.format("%.1f", new Object[] { Double.valueOf(d1)})}); + } else if (astring[1].equals("amount")) { + if (astring.length != 3) { + throw new ExceptionUsage("commands.worldborder.damage.amount.usage", new Object[0]); + } + + d0 = a(astring[2], 0.0D); + d1 = worldborder.getDamageAmount(); + worldborder.setDamageAmount(d0); + a(icommandlistener, this, "commands.worldborder.damage.amount.success", new Object[] { String.format("%.2f", new Object[] { Double.valueOf(d0)}), String.format("%.2f", new Object[] { Double.valueOf(d1)})}); + } + } else if (astring[0].equals("warning")) { + if (astring.length < 2) { + throw new ExceptionUsage("commands.worldborder.warning.usage", new Object[0]); + } + + int j = a(astring[2], 0); + int k; + + if (astring[1].equals("time")) { + if (astring.length != 3) { + throw new ExceptionUsage("commands.worldborder.warning.time.usage", new Object[0]); + } + + k = worldborder.getWarningTime(); + worldborder.setWarningTime(j); + a(icommandlistener, this, "commands.worldborder.warning.time.success", new Object[] { Integer.valueOf(j), Integer.valueOf(k)}); + } else if (astring[1].equals("distance")) { + if (astring.length != 3) { + throw new ExceptionUsage("commands.worldborder.warning.distance.usage", new Object[0]); + } + + k = worldborder.getWarningDistance(); + worldborder.setWarningDistance(j); + a(icommandlistener, this, "commands.worldborder.warning.distance.success", new Object[] { Integer.valueOf(j), Integer.valueOf(k)}); + } + } else { + if (!astring[0].equals("get")) { + throw new ExceptionUsage("commands.worldborder.usage", new Object[0]); + } + + d0 = worldborder.getSize(); + icommandlistener.a(CommandObjectiveExecutor.EnumCommandResult.QUERY_RESULT, MathHelper.floor(d0 + 0.5D)); + icommandlistener.sendMessage(new ChatMessage("commands.worldborder.get.success", new Object[] { String.format("%.0f", new Object[] { Double.valueOf(d0)})})); + } + + } + } + + protected WorldBorder d() { + return MinecraftServer.getServer().worldServer[0].getWorldBorder(); + } + + public List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { + return astring.length == 1 ? a(astring, new String[] { "set", "center", "damage", "warning", "add", "get"}) : (astring.length == 2 && astring[0].equals("damage") ? a(astring, new String[] { "buffer", "amount"}) : (astring.length >= 2 && astring.length <= 3 && astring[0].equals("center") ? b(astring, 1, blockposition) : (astring.length == 2 && astring[0].equals("warning") ? a(astring, new String[] { "time", "distance"}) : null))); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CommandXp.java b/azurite-server/src/main/java/net/minecraft/server/CommandXp.java new file mode 100644 index 0000000..0f391b6 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CommandXp.java @@ -0,0 +1,74 @@ +package net.minecraft.server; + +import java.util.List; + +public class CommandXp extends CommandAbstract { + + public CommandXp() {} + + public String getCommand() { + return "xp"; + } + + public int a() { + return 2; + } + + public String getUsage(ICommandListener icommandlistener) { + return "commands.xp.usage"; + } + + public void execute(ICommandListener icommandlistener, String[] astring) throws CommandException { + if (astring.length <= 0) { + throw new ExceptionUsage("commands.xp.usage", new Object[0]); + } else { + String s = astring[0]; + boolean flag = s.endsWith("l") || s.endsWith("L"); + + if (flag && s.length() > 1) { + s = s.substring(0, s.length() - 1); + } + + int i = a(s); + boolean flag1 = i < 0; + + if (flag1) { + i *= -1; + } + + EntityPlayer entityplayer = astring.length > 1 ? a(icommandlistener, astring[1]) : b(icommandlistener); + + if (flag) { + icommandlistener.a(CommandObjectiveExecutor.EnumCommandResult.QUERY_RESULT, entityplayer.expLevel); + if (flag1) { + entityplayer.levelDown(-i); + a(icommandlistener, this, "commands.xp.success.negative.levels", new Object[] { Integer.valueOf(i), entityplayer.getName()}); + } else { + entityplayer.levelDown(i); + a(icommandlistener, this, "commands.xp.success.levels", new Object[] { Integer.valueOf(i), entityplayer.getName()}); + } + } else { + icommandlistener.a(CommandObjectiveExecutor.EnumCommandResult.QUERY_RESULT, entityplayer.expTotal); + if (flag1) { + throw new CommandException("commands.xp.failure.widthdrawXp", new Object[0]); + } + + entityplayer.giveExp(i); + a(icommandlistener, this, "commands.xp.success", new Object[] { Integer.valueOf(i), entityplayer.getName()}); + } + + } + } + + public List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition) { + return astring.length == 2 ? a(astring, this.d()) : null; + } + + protected String[] d() { + return MinecraftServer.getServer().getPlayers(); + } + + public boolean isListStart(String[] astring, int i) { + return i == 1; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/Container.java b/azurite-server/src/main/java/net/minecraft/server/Container.java new file mode 100644 index 0000000..f23b14b --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/Container.java @@ -0,0 +1,628 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; +import dev.azurite.spigot.configs.AzuriteConfig; +import org.bukkit.craftbukkit.inventory.CraftInventory; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.event.Event.Result; +import org.bukkit.event.inventory.InventoryDragEvent; +import org.bukkit.event.inventory.InventoryType; +import org.bukkit.inventory.InventoryView; + +import java.util.*; + +public abstract class Container { + + public List b = Lists.newArrayList(); // Item Stacks (live updated inventory compared to slots) + public List c = Lists.newArrayList(); // Slots (basically last sent ItemStacks) + public int windowId; + private int dragType = -1; + private int g; + private final Set h = new ArraySet<>(); // Vortex + protected List listeners = Lists.newArrayList(); + private final Set i = new ArraySet<>(); // Vortex + protected int tickCount; // Spigot + + // CraftBukkit start + public boolean checkReachable = true; + + public abstract InventoryView getBukkitView(); + + public void transferTo(Container other, org.bukkit.craftbukkit.entity.CraftHumanEntity player) { + InventoryView source = this.getBukkitView(), destination = other.getBukkitView(); + ((CraftInventory) source.getTopInventory()).getInventory().onClose(player); + ((CraftInventory) source.getBottomInventory()).getInventory().onClose(player); + ((CraftInventory) destination.getTopInventory()).getInventory().onOpen(player); + ((CraftInventory) destination.getBottomInventory()).getInventory().onOpen(player); + } + // CraftBukkit end + + public Container() { + } + + protected Slot a(Slot slot) { + slot.rawSlotIndex = this.c.size(); + this.c.add(slot); + this.b.add(null); // CraftBukkit - fix decompile error + return slot; + } + + public void addSlotListener(ICrafting icrafting) { + if (this.listeners.contains(icrafting)) { + throw new IllegalArgumentException("Listener already listening"); + } else { + this.listeners.add(icrafting); + icrafting.a(this, this.a()); + this.b(); + } + } + + public List a() { + ArrayList arraylist = Lists.newArrayList(); + + for (Slot slot : this.c) { + arraylist.add(slot.getItem()); + } + + return arraylist; + } + + public void updateSlotsToLatest() { + for (int slotIndex = 0; slotIndex < this.c.size(); slotIndex++) { + ItemStack lastItemStack = this.c.get(slotIndex).getItem(); + ItemStack newItemStack = (lastItemStack == null) ? null : lastItemStack.cloneItemStack(); + this.b.set(slotIndex, newItemStack); + } + } + + public void b() { + for (int slotIndex = 0; slotIndex < this.c.size(); slotIndex++) { + ItemStack lastItemStack = this.c.get(slotIndex).getItem(); + ItemStack newItemStack = this.b.get(slotIndex); + if (!ItemStack.fastMatches(newItemStack, lastItemStack) || (this.tickCount % 20 == 0 && !ItemStack.matches(newItemStack, lastItemStack))) { + newItemStack = (lastItemStack == null) ? null : lastItemStack.cloneItemStack(); + this.b.set(slotIndex, newItemStack); + for (ICrafting listener : this.listeners) + listener.a(this, slotIndex, newItemStack); + } + } + this.tickCount++; + } + + public boolean a(EntityHuman entityhuman, int i) { + return false; + } + + public Slot getSlot(IInventory iinventory, int i) { + for (Slot slot : this.c) { + if (slot.a(iinventory, i)) { + return slot; + } + } + + return null; + } + + public Slot getSlot(int i) { + final int lastIndex = this.c.size() - 1; + + if (i > lastIndex) { + i = lastIndex; + } + + return this.c.get(i); + } + + public ItemStack b(EntityHuman entityhuman, int i) { + Slot slot = this.c.get(i); + + return slot != null ? slot.getItem() : null; + } + + public ItemStack clickItem(int i, int j, int k, EntityHuman entityhuman) { + ItemStack itemstack = null; + PlayerInventory playerinventory = entityhuman.inventory; + int l; + ItemStack itemstack1; + + if (k == 5) { + int i1 = this.g; + + this.g = c(j); + if ((i1 != 1 || this.g != 2) && i1 != this.g) { + this.d(); + } else if (playerinventory.getCarried() == null) { + this.d(); + } else if (this.g == 0) { + this.dragType = b(j); + if (a(this.dragType, entityhuman)) { + this.g = 1; + this.h.clear(); + } else { + this.d(); + } + } else if (this.g == 1) { + Slot slot = i < this.c.size() ? this.c.get(i) : null; // Paper - Ensure drag in bounds + + if (slot != null && a(slot, playerinventory.getCarried(), true) && slot.isAllowed(playerinventory.getCarried()) && playerinventory.getCarried().count > this.h.size() && this.b(slot)) { + this.h.add(slot); + } + } else if (this.g == 2) { + if (!this.h.isEmpty()) { + itemstack1 = playerinventory.getCarried().cloneItemStack(); + l = playerinventory.getCarried().count; + Iterator iterator = this.h.iterator(); + + Map draggedSlots = new HashMap<>(); // CraftBukkit - Store slots from drag in map (raw slot id -> new stack) + while (iterator.hasNext()) { + Slot slot1 = iterator.next(); + + if (slot1 != null && a(slot1, playerinventory.getCarried(), true) && slot1.isAllowed(playerinventory.getCarried()) && playerinventory.getCarried().count >= this.h.size() && this.b(slot1)) { + ItemStack itemstack2 = itemstack1.cloneItemStack(); + int j1 = slot1.hasItem() ? slot1.getItem().count : 0; + + a(this.h, this.dragType, itemstack2, j1); + if (itemstack2.count > itemstack2.getMaxStackSize()) { + itemstack2.count = itemstack2.getMaxStackSize(); + } + + if (itemstack2.count > slot1.getMaxStackSize(itemstack2)) { + itemstack2.count = slot1.getMaxStackSize(itemstack2); + } + + l -= itemstack2.count - j1; + // slot1.set(itemstack2); + draggedSlots.put(slot1.rawSlotIndex, itemstack2); // CraftBukkit - Put in map instead of setting + } + } + + // CraftBukkit start - InventoryDragEvent + InventoryView view = getBukkitView(); + org.bukkit.inventory.ItemStack newcursor = CraftItemStack.asCraftMirror(itemstack1); + newcursor.setAmount(l); + Map eventmap = new HashMap<>(); + for (Map.Entry ditem : draggedSlots.entrySet()) { + eventmap.put(ditem.getKey(), CraftItemStack.asBukkitCopy(ditem.getValue())); + } + + // It's essential that we set the cursor to the new value here to prevent item duplication if a plugin closes the inventory. + ItemStack oldCursor = playerinventory.getCarried(); + playerinventory.setCarried(CraftItemStack.asNMSCopy(newcursor)); + + InventoryDragEvent event = new InventoryDragEvent(view, (newcursor.getType() != org.bukkit.Material.AIR ? newcursor : null), CraftItemStack.asBukkitCopy(oldCursor), this.dragType == 1, eventmap); + entityhuman.world.getServer().getPluginManager().callEvent(event); + + // Whether or not a change was made to the inventory that requires an update. + boolean needsUpdate = event.getResult() != Result.DEFAULT; + + if (event.getResult() != Result.DENY) { + for (Map.Entry dslot : draggedSlots.entrySet()) { + view.setItem(dslot.getKey(), CraftItemStack.asBukkitCopy(dslot.getValue())); + } + // The only time the carried item will be set to null is if the inventory is closed by the server. + // If the inventory is closed by the server, then the cursor items are dropped. This is why we change the cursor early. + if (playerinventory.getCarried() != null) { + playerinventory.setCarried(CraftItemStack.asNMSCopy(event.getCursor())); + needsUpdate = true; + } + } else { + playerinventory.setCarried(oldCursor); + } + + if (needsUpdate) { + ((EntityPlayer) entityhuman).updateInventory(this); + } + // CraftBukkit end + } + + this.d(); + } else { + this.d(); + } + } else if (this.g != 0) { + this.d(); + } else { + Slot slot2; + int k1; + ItemStack itemstack3; + + if ((k == 0 || k == 1) && (j == 0 || j == 1)) { + if (i == -999) { + if (playerinventory.getCarried() != null) { + if (j == 0) { + entityhuman.drop(playerinventory.getCarried(), true); + playerinventory.setCarried(null); + } else { + // CraftBukkit start - Store a reference + ItemStack itemstack4 = playerinventory.getCarried(); + if (itemstack4.count > 0) { + entityhuman.drop(itemstack4.cloneAndSubtract(1), true); + } + + if (itemstack4.count == 0) { + // CraftBukkit end + playerinventory.setCarried(null); + } + } + } + } else if (k == 1) { + if (i < 0) { + return null; + } + + slot2 = this.c.get(i); + if (slot2 != null && slot2.isAllowed(entityhuman)) { + itemstack1 = this.b(entityhuman, i); + if (itemstack1 != null) { + Item item = itemstack1.getItem(); + + itemstack = itemstack1.cloneItemStack(); + if (slot2.getItem() != null && slot2.getItem().getItem() == item) { + this.a(i, j, true, entityhuman); + } + } + } + } else { + if (i < 0) { + return null; + } + + slot2 = this.c.get(i); + if (slot2 != null) { + itemstack1 = slot2.getItem(); + ItemStack itemstack4 = playerinventory.getCarried(); + + if (itemstack1 != null) { + itemstack = itemstack1.cloneItemStack(); + } + + if (itemstack1 == null) { + if (itemstack4 != null && slot2.isAllowed(itemstack4)) { + k1 = j == 0 ? itemstack4.count : 1; + if (k1 > slot2.getMaxStackSize(itemstack4)) { + k1 = slot2.getMaxStackSize(itemstack4); + } + + if (itemstack4.count >= k1) { + slot2.set(itemstack4.cloneAndSubtract(k1)); + } + + if (itemstack4.count == 0) { + playerinventory.setCarried(null); + // CraftBukkit start - Update client cursor if we didn't empty it + } else { + entityhuman.sendPacket(new PacketPlayOutSetSlot(-1, -1, entityhuman.inventory.getCarried())); + } + // CraftBukkit end + } + } else if (slot2.isAllowed(entityhuman)) { + if (itemstack4 == null) { + k1 = j == 0 ? itemstack1.count : (itemstack1.count + 1) / 2; + itemstack3 = slot2.a(k1); + playerinventory.setCarried(itemstack3); + if (itemstack1.count == 0) { + slot2.set(null); + } + + slot2.a(entityhuman, playerinventory.getCarried()); + } else if (slot2.isAllowed(itemstack4)) { + if (itemstack1.getItem() == itemstack4.getItem() && itemstack1.getData() == itemstack4.getData() && ItemStack.equals(itemstack1, itemstack4)) { + k1 = j == 0 ? itemstack4.count : 1; + if (k1 > slot2.getMaxStackSize(itemstack4) - itemstack1.count) { + k1 = slot2.getMaxStackSize(itemstack4) - itemstack1.count; + } + + if (k1 > itemstack4.getMaxStackSize() - itemstack1.count) { + k1 = itemstack4.getMaxStackSize() - itemstack1.count; + } + + itemstack4.cloneAndSubtract(k1); + if (itemstack4.count == 0) { + playerinventory.setCarried(null); + // CraftBukkit start - Update client cursor if we didn't empty it + } else { + entityhuman.sendPacket(new PacketPlayOutSetSlot(-1, -1, entityhuman.inventory.getCarried())); + } + // CraftBukkit end + + itemstack1.count += k1; + } else if (itemstack4.count <= slot2.getMaxStackSize(itemstack4)) { + slot2.set(itemstack4); + playerinventory.setCarried(itemstack1); + } + } else if (itemstack1.getItem() == itemstack4.getItem() && itemstack4.getMaxStackSize() > 1 && (!itemstack1.usesData() || itemstack1.getData() == itemstack4.getData()) && ItemStack.equals(itemstack1, itemstack4)) { + k1 = itemstack1.count; + // CraftBukkit start - itemstack4.getMaxStackSize() -> maxStack + int maxStack = Math.min(itemstack4.getMaxStackSize(), slot2.getMaxStackSize()); + if (k1 > 0 && k1 + itemstack4.count <= maxStack) { + itemstack4.count += k1; + itemstack1 = slot2.a(k1); + if (itemstack1.count == 0) { + slot2.set(null); + } + + slot2.a(entityhuman, playerinventory.getCarried()); + // CraftBukkit start - Update client cursor if we didn't empty it + } else { + entityhuman.sendPacket(new PacketPlayOutSetSlot(-1, -1, entityhuman.inventory.getCarried())); + } + // CraftBukkit end + } + } + + slot2.f(); + // CraftBukkit start - Make sure the client has the right slot contents + if (slot2.getMaxStackSize() != 64) { + entityhuman.sendPacket(new PacketPlayOutSetSlot(this.windowId, slot2.rawSlotIndex, slot2.getItem())); + // Updating a crafting inventory makes the client reset the result slot, have to send it again + if (this.getBukkitView().getType() == InventoryType.WORKBENCH || this.getBukkitView().getType() == InventoryType.CRAFTING) { + entityhuman.sendPacket(new PacketPlayOutSetSlot(this.windowId, 0, this.getSlot(0).getItem())); + } + } + // CraftBukkit end + } + } + } else if (k == 2 && j >= 0 && j < 9) { + slot2 = this.c.get(i); + if (slot2.isAllowed(entityhuman)) { + itemstack1 = playerinventory.getItem(j); + boolean flag = itemstack1 == null || slot2.inventory == playerinventory && slot2.isAllowed(itemstack1); + + k1 = -1; + if (!flag) { + k1 = playerinventory.getFirstEmptySlotIndex(); + flag = k1 > -1; + } + + if (slot2.hasItem() && flag) { + itemstack3 = slot2.getItem(); + playerinventory.setItem(j, itemstack3.cloneItemStack()); + if ((slot2.inventory != playerinventory || !slot2.isAllowed(itemstack1)) && itemstack1 != null) { + if (k1 > -1) { + playerinventory.pickup(itemstack1); + slot2.a(itemstack3.count); + slot2.set(null); + slot2.a(entityhuman, itemstack3); + } + } else { + slot2.a(itemstack3.count); + slot2.set(itemstack1); + slot2.a(entityhuman, itemstack3); + } + } else if (!slot2.hasItem() && itemstack1 != null && slot2.isAllowed(itemstack1)) { + playerinventory.setItem(j, null); + slot2.set(itemstack1); + } + } + } else if (k == 3 && entityhuman.abilities.canInstantlyBuild && playerinventory.getCarried() == null && i >= 0) { + slot2 = this.c.get(i); + if (slot2 != null && slot2.hasItem()) { + itemstack1 = slot2.getItem().cloneItemStack(); + itemstack1.count = itemstack1.getMaxStackSize(); + playerinventory.setCarried(itemstack1); + } + } else if (k == 4 && playerinventory.getCarried() == null && i >= 0) { + slot2 = this.c.get(i); + if (slot2 != null && slot2.hasItem() && slot2.isAllowed(entityhuman)) { + itemstack1 = slot2.a(j == 0 ? 1 : slot2.getItem().count); + slot2.a(entityhuman, itemstack1); + entityhuman.drop(itemstack1, true); + } + } else if (k == 6 && i >= 0) { + slot2 = this.c.get(i); + itemstack1 = playerinventory.getCarried(); + if (itemstack1 != null && (slot2 == null || !slot2.hasItem() || !slot2.isAllowed(entityhuman))) { + l = j == 0 ? 0 : this.c.size() - 1; + k1 = j == 0 ? 1 : -1; + + for (int l1 = 0; l1 < 2; ++l1) { + for (int i2 = l; i2 >= 0 && i2 < this.c.size() && itemstack1.count < itemstack1.getMaxStackSize(); i2 += k1) { + Slot slot3 = this.c.get(i2); + + if (slot3.hasItem() && a(slot3, itemstack1, true) && slot3.isAllowed(entityhuman) && this.a(itemstack1, slot3) && (l1 != 0 || slot3.getItem().count != slot3.getItem().getMaxStackSize())) { + int j2 = Math.min(itemstack1.getMaxStackSize() - itemstack1.count, slot3.getItem().count); + ItemStack itemstack5 = slot3.a(j2); + + itemstack1.count += j2; + if (itemstack5.count <= 0) { + slot3.set(null); + } + + slot3.a(entityhuman, itemstack5); + } + } + } + } + + this.b(); + } + } + + return itemstack; + } + + public boolean a(ItemStack itemstack, Slot slot) { + return true; + } + + protected void a(int i, int j, boolean flag, EntityHuman entityhuman) { + this.clickItem(i, j, 1, entityhuman); + } + + public void b(EntityHuman entityhuman) { + PlayerInventory playerinventory = entityhuman.inventory; + + if (playerinventory.getCarried() != null) { + entityhuman.drop(playerinventory.getCarried(), false); + playerinventory.setCarried(null); + } + + } + + public void a(IInventory iinventory) { + this.b(); + } + + public void setItem(int i, ItemStack itemstack) { + this.getSlot(i).set(itemstack); + } + + public boolean c(EntityHuman entityhuman) { + return !this.i.contains(entityhuman); + } + + public void a(EntityHuman entityhuman, boolean flag) { + if (flag) { + this.i.remove(entityhuman); + } else { + this.i.add(entityhuman); + } + + } + + public abstract boolean a(EntityHuman entityhuman); + + protected boolean a(ItemStack itemstack, int i, int j, boolean flag) { + boolean flag1 = false; + int k = i; + + if (flag) { + k = j - 1; + } + + Slot slot; + ItemStack itemstack1; + + if (itemstack.isStackable()) { + while (itemstack.count > 0 && (!flag && k < j || flag && k >= i)) { + slot = this.c.get(k); + itemstack1 = slot.getItem(); + if (itemstack1 != null && itemstack1.getItem() == itemstack.getItem() && (!itemstack.usesData() || itemstack.getData() == itemstack1.getData()) && ItemStack.equals(itemstack, itemstack1)) { + int l = itemstack1.count + itemstack.count; + + // CraftBukkit start - itemstack.getMaxStackSize() -> maxStack + int maxStack = Math.min(itemstack.getMaxStackSize(), slot.getMaxStackSize()); + if (l <= maxStack) { + itemstack.count = 0; + itemstack1.count = l; + slot.f(); + flag1 = true; + } else if (itemstack1.count < maxStack) { + itemstack.count -= maxStack - itemstack1.count; + itemstack1.count = maxStack; + slot.f(); + flag1 = true; + } + // CraftBukkit end + } + + if (flag) { + --k; + } else { + ++k; + } + } + } + + if (itemstack.count > 0) { + if (flag) { + k = j - 1; + } else { + k = i; + } + + while (!flag && k < j || flag && k >= i) { + slot = this.c.get(k); + itemstack1 = slot.getItem(); + if (itemstack1 == null) { + slot.set(itemstack.cloneItemStack()); + slot.f(); + itemstack.count = 0; + flag1 = true; + break; + } + + if (flag) { + --k; + } else { + ++k; + } + } + } + + return flag1; + } + + public static int b(int i) { + return i >> 2 & 3; + } + + public static int c(int i) { + return i & 3; + } + + public static boolean a(int i, EntityHuman entityhuman) { + return i == 0 || (i == 1 || i == 2 && entityhuman.abilities.canInstantlyBuild); + } + + protected void d() { + this.g = 0; + this.h.clear(); + } + + public static boolean a(Slot slot, ItemStack itemstack, boolean flag) { + boolean flag1 = slot == null || !slot.hasItem(); + + if (slot != null && slot.hasItem() && itemstack != null && itemstack.doMaterialsMatch(slot.getItem()) && ItemStack.equals(slot.getItem(), itemstack)) { + flag1 |= slot.getItem().count + (flag ? 0 : itemstack.count) <= itemstack.getMaxStackSize(); + } + + return flag1; + } + + public static void a(Set set, int i, ItemStack itemstack, int j) { + switch (i) { + case 0: + itemstack.count = MathHelper.d((float) itemstack.count / (float) set.size()); + break; + + case 1: + itemstack.count = 1; + break; + + case 2: + itemstack.count = itemstack.getItem().getMaxStackSize(); + } + + itemstack.count += j; + } + + public boolean b(Slot slot) { + return true; + } + + public static int a(TileEntity tileentity) { + return tileentity instanceof IInventory ? b((IInventory) tileentity) : 0; + } + + public static int b(IInventory iinventory) { + if (iinventory == null) { + return 0; + } else { + int i = 0; + float f = 0.0F; + + for (int j = 0; j < iinventory.getSize(); ++j) { + ItemStack itemstack = iinventory.getItem(j); + + if (itemstack != null) { + f += (float) itemstack.count / (float) Math.min(iinventory.getMaxStackSize(), itemstack.getMaxStackSize()); + ++i; + } + } + + f /= (float) iinventory.getSize(); + return MathHelper.d(f * 14.0F) + (i > 0 ? 1 : 0); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ContainerAnvil.java b/azurite-server/src/main/java/net/minecraft/server/ContainerAnvil.java new file mode 100644 index 0000000..357a989 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ContainerAnvil.java @@ -0,0 +1,475 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.AzuriteConfig; +import org.apache.commons.lang3.StringUtils; +import org.bukkit.Bukkit; +import org.bukkit.craftbukkit.inventory.CraftInventoryView; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.PrepareItemAnvilRepairEvent; + +import java.util.Iterator; +import java.util.Map; + +public class ContainerAnvil extends Container { + + private final IInventory g = new InventoryCraftResult(); + private final IInventory h = new InventorySubcontainer("Repair", true, 2) { + public void update() { + super.update(); + ContainerAnvil.this.a(this); + } + }; + private final World i; + private final BlockPosition j; + public int a; + private int k; + private String l; + private final EntityHuman m; + // CraftBukkit start + private CraftInventoryView bukkitEntity = null; + private final PlayerInventory player; + // CraftBukkit end + + public ContainerAnvil(PlayerInventory playerinventory, final World world, final BlockPosition blockposition, EntityHuman entityhuman) { + this.player = playerinventory; // CraftBukkit + this.j = blockposition; + this.i = world; + this.m = entityhuman; + this.a(new Slot(this.h, 0, 27, 47)); + this.a(new Slot(this.h, 1, 76, 47)); + this.a(new Slot(this.g, 2, 134, 47) { + public boolean isAllowed(ItemStack itemstack) { + return false; + } + + public boolean isAllowed(EntityHuman entityhuman) { + return (entityhuman.abilities.canInstantlyBuild || entityhuman.expLevel >= ContainerAnvil.this.a) && ContainerAnvil.this.a > 0 && this.hasItem(); + } + + public void a(EntityHuman entityhuman, ItemStack itemstack) { + + if (!entityhuman.abilities.canInstantlyBuild) { + entityhuman.levelDown(-ContainerAnvil.this.a); + } + + ContainerAnvil.this.h.setItem(0, null); + if (ContainerAnvil.this.k > 0) { + ItemStack itemstack1 = ContainerAnvil.this.h.getItem(1); + + if (itemstack1 != null && itemstack1.count > ContainerAnvil.this.k) { + itemstack1.count -= ContainerAnvil.this.k; + ContainerAnvil.this.h.setItem(1, itemstack1); + } else { + ContainerAnvil.this.h.setItem(1, null); + } + } else { + ContainerAnvil.this.h.setItem(1, null); + } + + ContainerAnvil.this.a = 0; + IBlockData iblockdata = world.getType(blockposition); + + if (!entityhuman.abilities.canInstantlyBuild && iblockdata.getBlock() == Blocks.ANVIL && entityhuman.bc().nextFloat() < 0.12F) { + int i = iblockdata.get(BlockAnvil.DAMAGE); + + ++i; + if (i > 2) { + world.setAir(blockposition); + world.triggerEffect(1020, blockposition, 0); + } else { + world.setTypeAndData(blockposition, iblockdata.set(BlockAnvil.DAMAGE, i), 2); + world.triggerEffect(1021, blockposition, 0); + } + } else { + world.triggerEffect(1021, blockposition, 0); + } + + ((Player) m.getBukkitEntity()).updateInventory(); + } + }); + + int i; + + for (i = 0; i < 3; ++i) { + for (int j = 0; j < 9; ++j) { + this.a(new Slot(playerinventory, j + i * 9 + 9, 8 + j * 18, 84 + i * 18)); + } + } + + for (i = 0; i < 9; ++i) { + this.a(new Slot(playerinventory, i, 8 + i * 18, 142)); + } + } + + public void a(IInventory iinventory) { + super.a(iinventory); + if (iinventory == this.h) { + this.e(); + } + } + + public void e() { + ItemStack item = this.h.getItem(0); + this.a = AzuriteConfig.oldAnvilSystem.getValue() ? 0 : 1; // Rivals + int i = 0; + byte b0 = 0; + int b1 = 0; // Rivals - int + int j1 = 0; // Rivals + int l1 = 0; // Rivals + if (item == null) { + this.g.setItem(0, null); + this.a = 0; + } else { + ItemStack result = item.cloneItemStack(); + ItemStack second = this.h.getItem(1); + Map map = EnchantmentManager.a(result); + boolean flag7 = false; + int anvilUseCost = b0 + item.getRepairCost() + ((second == null) ? 0 : second.getRepairCost()); + + // Ambassator - Add config option to remove anvil uses + if (AzuriteConfig.removeAnvilUses.getValue()) { + anvilUseCost = 0; + } + + this.k = 0; + if (second != null) { + flag7 = (second.getItem() == Items.ENCHANTED_BOOK && !Items.ENCHANTED_BOOK.h(second).isEmpty()); + if (result.e() && result.getItem().a(item, second)) { + int something = Math.min(result.h(), result.j() / 4); + if (something <= 0) { + this.g.setItem(0, null); + this.a = 0; + return; + } + int l; + for (l = 0; something > 0 && l < second.count; l++) { + int i1 = result.h() - something; + result.setData(i1); + + // Rivals start + if (AzuriteConfig.oldAnvilSystem.getValue()) { + i += Math.max(1, something / 100) + map.size(); + } else { + ++i; + } + // Rivals end + + something = Math.min(result.h(), result.j() / 4); + } + this.k = l; + } else { + if (!flag7 && (result.getItem() != second.getItem() || !result.e())) { + this.g.setItem(0, null); + this.a = 0; + return; + } + if (result.e() && !flag7) { + int k = item.j() - item.h(); + int l = second.j() - second.h(); + int i1 = l + result.j() * 12 / 100; + int k1 = k + i1; + j1 = result.j() - k1; + if (j1 < 0) + j1 = 0; + if (j1 < result.getData()) { + result.setData(j1); + // Rivals start + if (AzuriteConfig.oldAnvilSystem.getValue()) { + i += Math.max(1, i1 / 100); + } else { + i += 2; + } + // Rivals end + } + } + Map map1 = EnchantmentManager.a(second); + for (Integer i1 : map1.keySet()) { + Enchantment enchantment = Enchantment.getById(i1); + if (enchantment != null) { + j1 = map.getOrDefault(i1, 0); + l1 = map1.get(i1); + int i2; + + if (j1 == l1) { + i2 = ++l1; + } else { + i2 = Math.max(l1, j1); + } + l1 = i2; + int w = l1 - j1; // Rivals + boolean flag8 = enchantment.canEnchant(item) && enchantment.getEnchantLimit() != 0; + if (this.m.abilities.canInstantlyBuild || item.getItem() == Items.ENCHANTED_BOOK) + flag8 = true; + for (int j2 : map.keySet()) { + if (j2 != i1 && !enchantment.a(Enchantment.getById(j2))) { + flag8 = false; + + // Rivals start + if (AzuriteConfig.oldAnvilSystem.getValue()) { + i += w; + } else { + ++i; + } + // Rivals end + } + } + if (flag8) { + // Azurite start - Enchant limits + int maxLevel = (Math.min(enchantment.getMaxLevel(), enchantment.getEnchantLimit())); + + if (l1 > maxLevel) + l1 = maxLevel; + // Azurite end + + map.put(i1, l1); + int k2 = getK2(enchantment, flag7); + + if (AzuriteConfig.oldAnvilSystem.getValue()) { + i += k2 * w; + } else { + i += k2 * l1; + } + } + } + } + } + } + if (StringUtils.isBlank(this.l)) { + if (item.hasName()) { + // Rivals start + if (AzuriteConfig.oldAnvilSystem.getValue()) { + b1 = item.e() ? 7 : item.count * 5; + } else { + b1 = 1; + } + // Rivals end + i += b1; + result.r(); + } + } else if (!this.l.equals(item.getName())) { + // Rivals start + if (AzuriteConfig.oldAnvilSystem.getValue()) { + b1 = item.e() ? 7 : item.count * 5; + } else { + b1 = 1; + } + // Rivals end + i += b1; + // Rivals start + if (AzuriteConfig.oldAnvilSystem.getValue() && result.hasName()) { + anvilUseCost += b1 / 2; + } + // Rivals end + result.c(this.l); + } + + // Rivals start + if (AzuriteConfig.oldAnvilSystem.getValue()) { + int cost = 0; + + for (Iterator iterator = map.keySet().iterator(); iterator.hasNext(); anvilUseCost += cost + j1 * l1) { + int i1 = iterator.next(); + Enchantment enchantment = Enchantment.getById(i1); + + if (enchantment != null) { + j1 = map.getOrDefault(i1, 0); + l1 = 0; + ++cost; + switch (enchantment.getRandomWeight()) { + case 1: + l1 = 8; + break; + + case 2: + l1 = 4; + + case 3: + case 4: + case 6: + case 7: + case 8: + case 9: + default: + break; + + case 5: + l1 = 2; + break; + + case 10: + l1 = 1; + } + + if (flag7) { + l1 = Math.max(1, l1 / 2); + } + } + } + } + + if (flag7) { + anvilUseCost = Math.max(1, anvilUseCost / 2); + } + // Rivals end + + this.a = anvilUseCost + i; + if (i <= 0) + result = null; + if (b1 == i && b1 > 0 && this.a >= 40) + this.a = 39; + if (this.a >= 40 && !this.m.abilities.canInstantlyBuild) + result = null; + if (result != null) { + int k = result.getRepairCost(); + if (second != null && k < second.getRepairCost()) + k = second.getRepairCost(); + + // Rivals start + if (AzuriteConfig.oldAnvilSystem.getValue()) { + if (result.hasName()) { + k -= 9; + } + + if (k < 0) + k = 0; + + k += 2; + } else { + k = k * 2 + 1; + } + // Rivals end + + // Ambassator - Add config option to remove anvil uses + if (!AzuriteConfig.removeAnvilUses.getValue()) { + result.setRepairCost(k); + } + + EnchantmentManager.a(map, result); + PrepareItemAnvilRepairEvent event = new PrepareItemAnvilRepairEvent(getBukkitView(), this.m.getBukkitEntity(), this.m.world.getWorld().getBlockAt(this.j.getX(), this.j.getY(), this.j.getZ()), this.a, CraftItemStack.asBukkitCopy(item), CraftItemStack.asBukkitCopy(second), CraftItemStack.asBukkitCopy(result)); + Bukkit.getServer().getPluginManager().callEvent(event); + if (event.isCancelled() || event.getResult().getType() == org.bukkit.Material.AIR) + return; + this.a = event.getRepairCost(); + result = CraftItemStack.asNMSCopy(event.getResult()); + } + this.g.setItem(0, result); + b(); + + // Ambassator - Broadcast Repair Cost to fix 1.7 bugs + for (ICrafting listener : this.listeners) { + listener.setContainerData(this, 0, this.a); + } + } + } + + private static int getK2(Enchantment enchantment, boolean flag7) { + int k2 = 0; + switch (enchantment.getRandomWeight()) { + case 1: + k2 = 8; + break; + case 2: + k2 = 4; + break; + case 5: + k2 = 2; + break; + case 10: + k2 = 1; + break; + } + if (flag7) + k2 = Math.max(1, k2 / 2); + return k2; + } + + public void addSlotListener(ICrafting icrafting) { + super.addSlotListener(icrafting); + icrafting.setContainerData(this, 0, this.a); + } + + public void b(EntityHuman entityhuman) { + super.b(entityhuman); + + for (int i = 0; i < this.h.getSize(); ++i) { + ItemStack itemstack = this.h.splitWithoutUpdate(i); + + if (itemstack != null) { + entityhuman.drop(itemstack, false); + } + } + + } + + public boolean a(EntityHuman entityhuman) { + if (!this.checkReachable) return true; // CraftBukkit + return this.i.getType(this.j).getBlock() == Blocks.ANVIL && entityhuman.e(this.j.getX() + 0.5D, this.j.getY() + 0.5D, this.j.getZ() + 0.5D) <= 64.0D; + } + + public ItemStack b(EntityHuman entityhuman, int i) { + ItemStack itemstack = null; + Slot slot = this.c.get(i); + + if (slot != null && slot.hasItem()) { + ItemStack itemstack1 = slot.getItem(); + + itemstack = itemstack1.cloneItemStack(); + if (i == 2) { + if (!this.a(itemstack1, 3, 39, true)) { + return null; + } + + slot.a(itemstack1, itemstack); + } else if (i != 0 && i != 1) { + if (i < 39 && !this.a(itemstack1, 0, 2, false)) { + return null; + } + } else if (!this.a(itemstack1, 3, 39, false)) { + return null; + } + + if (itemstack1.count == 0) { + slot.set(null); + } else { + slot.f(); + } + + if (itemstack1.count == itemstack.count) { + return null; + } + + slot.a(entityhuman, itemstack1); + } + + return itemstack; + } + + public void a(String s) { + this.l = s; + if (this.getSlot(2).hasItem()) { + ItemStack itemstack = this.getSlot(2).getItem(); + + if (StringUtils.isBlank(s)) { + itemstack.r(); + } else { + itemstack.c(this.l); + } + } + + this.e(); + } + + // CraftBukkit start + @Override + public CraftInventoryView getBukkitView() { + if (bukkitEntity != null) { + return bukkitEntity; + } + + org.bukkit.craftbukkit.inventory.CraftInventory inventory = new org.bukkit.craftbukkit.inventory.CraftInventoryAnvil(this.h, this.g); + bukkitEntity = new CraftInventoryView(this.player.player.getBukkitEntity(), inventory, this); + return bukkitEntity; + } + // CraftBukkit end +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ContainerBeacon.java b/azurite-server/src/main/java/net/minecraft/server/ContainerBeacon.java new file mode 100644 index 0000000..c0a17cd --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ContainerBeacon.java @@ -0,0 +1,132 @@ +package net.minecraft.server; + +import org.bukkit.craftbukkit.inventory.CraftInventoryView; + +public class ContainerBeacon extends Container { + + private final IInventory beacon; + private final SlotBeacon f; + // CraftBukkit start + private CraftInventoryView bukkitEntity = null; + private final PlayerInventory player; + // CraftBukkit end + + public ContainerBeacon(IInventory iinventory, IInventory iinventory1) { + player = (PlayerInventory) iinventory; // CraftBukkit - TODO: check this + this.beacon = iinventory1; + this.a((this.f = new SlotBeacon(iinventory1, 0, 136, 110))); + byte b0 = 36; + short short0 = 137; + + int i; + + for (i = 0; i < 3; ++i) { + for (int j = 0; j < 9; ++j) { + this.a(new Slot(iinventory, j + i * 9 + 9, b0 + j * 18, short0 + i * 18)); + } + } + + for (i = 0; i < 9; ++i) { + this.a(new Slot(iinventory, i, b0 + i * 18, 58 + short0)); + } + + } + + public void addSlotListener(ICrafting icrafting) { + super.addSlotListener(icrafting); + icrafting.setContainerData(this, this.beacon); + } + + public IInventory e() { + return this.beacon; + } + + public void b(EntityHuman entityhuman) { + super.b(entityhuman); + ItemStack itemstack = this.f.a(this.f.getMaxStackSize()); + + if (itemstack != null) { + entityhuman.drop(itemstack, false); + } + + } + + public boolean a(EntityHuman entityhuman) { + if (!this.checkReachable) return true; // CraftBukkit + return this.beacon.a(entityhuman); + } + + public ItemStack b(EntityHuman entityhuman, int i) { + ItemStack itemstack = null; + Slot slot = this.c.get(i); + + if (slot != null && slot.hasItem()) { + ItemStack itemstack1 = slot.getItem(); + + itemstack = itemstack1.cloneItemStack(); + if (i == 0) { + if (!this.a(itemstack1, 1, 37, true)) { + return null; + } + + slot.a(itemstack1, itemstack); + } else if (!this.f.hasItem() && this.f.isAllowed(itemstack1) && itemstack1.count == 1) { + if (!this.a(itemstack1, 0, 1, false)) { + return null; + } + } else if (i < 28) { + if (!this.a(itemstack1, 28, 37, false)) { + return null; + } + } else if (i < 37) { + if (!this.a(itemstack1, 1, 28, false)) { + return null; + } + } else if (!this.a(itemstack1, 1, 37, false)) { + return null; + } + + if (itemstack1.count == 0) { + slot.set(null); + } else { + slot.f(); + } + + if (itemstack1.count == itemstack.count) { + return null; + } + + slot.a(entityhuman, itemstack1); + } + + return itemstack; + } + + static class SlotBeacon extends Slot { + + public SlotBeacon(IInventory iinventory, int i, int j, int k) { + super(iinventory, i, j, k); + } + + public boolean isAllowed(ItemStack itemstack) { + return itemstack != null && (itemstack.getItem() == Items.EMERALD || itemstack.getItem() == Items.DIAMOND || itemstack.getItem() == Items.GOLD_INGOT || itemstack.getItem() == Items.IRON_INGOT); + } + + public int getMaxStackSize() { + return 1; + } + } + + // CraftBukkit start + @Override + public CraftInventoryView getBukkitView() { + if (bukkitEntity != null) { + return bukkitEntity; + } + + org.bukkit.craftbukkit.inventory.CraftInventory inventory = new org.bukkit.craftbukkit.inventory.CraftInventoryBeacon((TileEntityBeacon) this.beacon); // TODO - check this + bukkitEntity = new CraftInventoryView(this.player.player.getBukkitEntity(), inventory, this); + return bukkitEntity; + } + // CraftBukkit end +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ContainerBrewingStand.java b/azurite-server/src/main/java/net/minecraft/server/ContainerBrewingStand.java new file mode 100644 index 0000000..f74d9ce --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ContainerBrewingStand.java @@ -0,0 +1,171 @@ +package net.minecraft.server; + +// CraftBukkit start + +import org.bukkit.craftbukkit.inventory.CraftInventoryBrewer; +import org.bukkit.craftbukkit.inventory.CraftInventoryView; +// CraftBukkit end + +public class ContainerBrewingStand extends Container { + + private final IInventory brewingStand; + private final Slot f; + private int g; + + // CraftBukkit start + private CraftInventoryView bukkitEntity = null; + private final PlayerInventory player; + // CraftBukkit end + + public ContainerBrewingStand(PlayerInventory playerinventory, IInventory iinventory) { + player = playerinventory; // CraftBukkit + this.brewingStand = iinventory; + this.a(new SlotPotionBottle(playerinventory.player, iinventory, 0, 56, 46)); + this.a(new SlotPotionBottle(playerinventory.player, iinventory, 1, 79, 53)); + this.a(new SlotPotionBottle(playerinventory.player, iinventory, 2, 102, 46)); + this.f = this.a(new SlotBrewing(iinventory, 3, 79, 17)); + + int i; + + for (i = 0; i < 3; ++i) { + for (int j = 0; j < 9; ++j) { + this.a(new Slot(playerinventory, j + i * 9 + 9, 8 + j * 18, 84 + i * 18)); + } + } + + for (i = 0; i < 9; ++i) { + this.a(new Slot(playerinventory, i, 8 + i * 18, 142)); + } + + } + + public void addSlotListener(ICrafting icrafting) { + super.addSlotListener(icrafting); + icrafting.setContainerData(this, this.brewingStand); + } + + public void b() { + super.b(); + + for (ICrafting listener : this.listeners) { + if (this.g != this.brewingStand.getProperty(0)) { + listener.setContainerData(this, 0, this.brewingStand.getProperty(0)); + } + } + + this.g = this.brewingStand.getProperty(0); + } + + public boolean a(EntityHuman entityhuman) { + if (!this.checkReachable) return true; // CraftBukkit + return this.brewingStand.a(entityhuman); + } + + public ItemStack b(EntityHuman entityhuman, int i) { + ItemStack itemstack = null; + Slot slot = this.c.get(i); + + if (slot != null && slot.hasItem()) { + ItemStack itemstack1 = slot.getItem(); + + itemstack = itemstack1.cloneItemStack(); + if (i > 2 && i != 3) { + if (!this.f.hasItem() && this.f.isAllowed(itemstack1)) { + if (!this.a(itemstack1, 3, 4, false)) { + return null; + } + } else if (SlotPotionBottle.b_(itemstack)) { + if (!this.a(itemstack1, 0, 3, false)) { + return null; + } + } else if (i < 31) { + if (!this.a(itemstack1, 31, 40, false)) { + return null; + } + } else if (i < 40) { + if (!this.a(itemstack1, 4, 31, false)) { + return null; + } + } else if (!this.a(itemstack1, 4, 40, false)) { + return null; + } + } else { + if (!this.a(itemstack1, 4, 40, true)) { + return null; + } + + slot.a(itemstack1, itemstack); + } + + if (itemstack1.count == 0) { + slot.set(null); + } else { + slot.f(); + } + + if (itemstack1.count == itemstack.count) { + return null; + } + + slot.a(entityhuman, itemstack1); + } + + return itemstack; + } + + static class SlotBrewing extends Slot { + + public SlotBrewing(IInventory iinventory, int i, int j, int k) { + super(iinventory, i, j, k); + } + + public boolean isAllowed(ItemStack itemstack) { + return itemstack != null && itemstack.getItem().l(itemstack); + } + + public int getMaxStackSize() { + return 64; + } + } + + static class SlotPotionBottle extends Slot { + + private final EntityHuman a; + + public SlotPotionBottle(EntityHuman entityhuman, IInventory iinventory, int i, int j, int k) { + super(iinventory, i, j, k); + this.a = entityhuman; + } + + public boolean isAllowed(ItemStack itemstack) { + return b_(itemstack); + } + + public int getMaxStackSize() { + return 1; + } + + public void a(EntityHuman entityhuman, ItemStack itemstack) { + if (itemstack.getItem() == Items.POTION && itemstack.getData() > 0) { + this.a.b(AchievementList.B); + } + super.a(entityhuman, itemstack); + } + + public static boolean b_(ItemStack itemstack) { + return itemstack != null && (itemstack.getItem() == Items.POTION || itemstack.getItem() == Items.GLASS_BOTTLE); + } + } + + // CraftBukkit start + @Override + public CraftInventoryView getBukkitView() { + if (bukkitEntity != null) { + return bukkitEntity; + } + + bukkitEntity = new CraftInventoryView(this.player.player.getBukkitEntity(), new CraftInventoryBrewer(this.brewingStand), this); + return bukkitEntity; + } + // CraftBukkit end +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ContainerChest.java b/azurite-server/src/main/java/net/minecraft/server/ContainerChest.java new file mode 100644 index 0000000..e530321 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ContainerChest.java @@ -0,0 +1,107 @@ +package net.minecraft.server; + +// CraftBukkit start +import org.bukkit.craftbukkit.inventory.CraftInventory; +import org.bukkit.craftbukkit.inventory.CraftInventoryView; +// CraftBukkit end + +public class ContainerChest extends Container { + + private final IInventory container; + private final int f; + // CraftBukkit start + private CraftInventoryView bukkitEntity = null; + private final PlayerInventory player; + + @Override + public CraftInventoryView getBukkitView() { + if (bukkitEntity != null) { + return bukkitEntity; + } + + CraftInventory inventory; + if (this.container instanceof PlayerInventory) { + inventory = new org.bukkit.craftbukkit.inventory.CraftInventoryPlayer((PlayerInventory) this.container); + } else if (this.container instanceof InventoryLargeChest) { + inventory = new org.bukkit.craftbukkit.inventory.CraftInventoryDoubleChest((InventoryLargeChest) this.container); + } else { + inventory = new CraftInventory(this.container); + } + + bukkitEntity = new CraftInventoryView(this.player.player.getBukkitEntity(), inventory, this); + return bukkitEntity; + } + // CraftBukkit end + + public ContainerChest(IInventory iinventory, IInventory iinventory1, EntityHuman entityhuman) { + this.container = iinventory1; + this.f = iinventory1.getSize() / 9; + iinventory1.startOpen(entityhuman); + int i = (this.f - 4) * 18; + + // CraftBukkit start - Save player + // TODO: Should we check to make sure it really is an InventoryPlayer? + this.player = (PlayerInventory) iinventory; + // CraftBukkit end + + int j; + int k; + + for (j = 0; j < this.f; ++j) { + for (k = 0; k < 9; ++k) { + this.a(new Slot(iinventory1, k + j * 9, 8 + k * 18, 18 + j * 18)); + } + } + + for (j = 0; j < 3; ++j) { + for (k = 0; k < 9; ++k) { + this.a(new Slot(iinventory, k + j * 9 + 9, 8 + k * 18, 103 + j * 18 + i)); + } + } + + for (j = 0; j < 9; ++j) { + this.a(new Slot(iinventory, j, 8 + j * 18, 161 + i)); + } + + } + + public boolean a(EntityHuman entityhuman) { + if (!this.checkReachable) return true; // CraftBukkit + return this.container.a(entityhuman); + } + + public ItemStack b(EntityHuman entityhuman, int i) { + ItemStack itemstack = null; + Slot slot = this.c.get(i); + + if (slot != null && slot.hasItem()) { + ItemStack itemstack1 = slot.getItem(); + + itemstack = itemstack1.cloneItemStack(); + if (i < this.f * 9) { + if (!this.a(itemstack1, this.f * 9, this.c.size(), true)) { + return null; + } + } else if (!this.a(itemstack1, 0, this.f * 9, false)) { + return null; + } + + if (itemstack1.count == 0) { + slot.set(null); + } else { + slot.f(); + } + } + + return itemstack; + } + + public void b(EntityHuman entityhuman) { + super.b(entityhuman); + this.container.closeContainer(entityhuman); + } + + public IInventory e() { + return this.container; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ContainerDispenser.java b/azurite-server/src/main/java/net/minecraft/server/ContainerDispenser.java new file mode 100644 index 0000000..7bba2d9 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ContainerDispenser.java @@ -0,0 +1,93 @@ +package net.minecraft.server; + +// CraftBukkit start +import org.bukkit.craftbukkit.inventory.CraftInventory; +import org.bukkit.craftbukkit.inventory.CraftInventoryView; +// CraftBukkit end + +public class ContainerDispenser extends Container { + + public IInventory items; + // CraftBukkit start + private CraftInventoryView bukkitEntity = null; + private final PlayerInventory player; + // CraftBukkit end + + public ContainerDispenser(IInventory iinventory, IInventory iinventory1) { + this.items = iinventory1; + // CraftBukkit start - Save player + // TODO: Should we check to make sure it really is an InventoryPlayer? + this.player = (PlayerInventory)iinventory; + // CraftBukkit end + + int i; + int j; + + for (i = 0; i < 3; ++i) { + for (j = 0; j < 3; ++j) { + this.a(new Slot(iinventory1, j + i * 3, 62 + j * 18, 17 + i * 18)); + } + } + + for (i = 0; i < 3; ++i) { + for (j = 0; j < 9; ++j) { + this.a(new Slot(iinventory, j + i * 9 + 9, 8 + j * 18, 84 + i * 18)); + } + } + + for (i = 0; i < 9; ++i) { + this.a(new Slot(iinventory, i, 8 + i * 18, 142)); + } + + } + + public boolean a(EntityHuman entityhuman) { + if (!this.checkReachable) return true; // CraftBukkit + return this.items.a(entityhuman); + } + + public ItemStack b(EntityHuman entityhuman, int i) { + ItemStack itemstack = null; + Slot slot = this.c.get(i); + + if (slot != null && slot.hasItem()) { + ItemStack itemstack1 = slot.getItem(); + + itemstack = itemstack1.cloneItemStack(); + if (i < 9) { + if (!this.a(itemstack1, 9, 45, true)) { + return null; + } + } else if (!this.a(itemstack1, 0, 9, false)) { + return null; + } + + if (itemstack1.count == 0) { + slot.set(null); + } else { + slot.f(); + } + + if (itemstack1.count == itemstack.count) { + return null; + } + + slot.a(entityhuman, itemstack1); + } + + return itemstack; + } + + // CraftBukkit start + @Override + public CraftInventoryView getBukkitView() { + if (bukkitEntity != null) { + return bukkitEntity; + } + + CraftInventory inventory = new CraftInventory(this.items); + bukkitEntity = new CraftInventoryView(this.player.player.getBukkitEntity(), inventory, this); + return bukkitEntity; + } + // CraftBukkit end +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ContainerEnchantTable.java b/azurite-server/src/main/java/net/minecraft/server/ContainerEnchantTable.java new file mode 100644 index 0000000..ed56714 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ContainerEnchantTable.java @@ -0,0 +1,391 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.AzuriteConfig; +import org.bukkit.craftbukkit.inventory.CraftInventoryEnchanting; +import org.bukkit.craftbukkit.inventory.CraftInventoryView; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.entity.Player; +import org.bukkit.event.enchantment.EnchantItemEvent; +import org.bukkit.event.enchantment.PrepareItemEnchantEvent; + +import java.util.List; +import java.util.Map; +import java.util.Random; + +public class ContainerEnchantTable extends Container { + + // CraftBukkit - make type specific (changed from IInventory) + public InventorySubcontainer enchantSlots = new InventorySubcontainer("Enchant", true, 2) { + public void update() { + super.update(); + ContainerEnchantTable.this.a(this); + } + }; + private World world; + private final BlockPosition position; + private final Random k = new Random(); + public int f; + public int[] costs = new int[3]; + public int[] h = {-1, -1, -1}; + // CraftBukkit start + private CraftInventoryView bukkitEntity = null; + private final Player player; + // CraftBukkit end + + public ContainerEnchantTable(PlayerInventory playerinventory, World world, BlockPosition blockposition) { + this.world = world; + this.position = blockposition; + if (!AzuriteConfig.oldEnchantingSystem.getValue()) + this.f = playerinventory.player.cj(); + this.a(new Slot(this.enchantSlots, 0, 15, 47) { + public boolean isAllowed(ItemStack itemstack) { + return true; + } + + public int getMaxStackSize() { + return 1; + } + }); + this.a(new Slot(this.enchantSlots, 1, 35, 47) { + { + if (AzuriteConfig.oldEnchantingSystem.getValue()) + set(new ItemStack(Items.DYE, 64, 4)); + } + + public boolean isAllowed(ItemStack itemstack) { + return !AzuriteConfig.oldEnchantingSystem.getValue() && + itemstack.getItem() == Items.DYE && + EnumColor.fromInvColorIndex(itemstack.getData()) == EnumColor.BLUE; + } + }); + + int i; + + for (i = 0; i < 3; ++i) { + for (int j = 0; j < 9; ++j) { + this.a(new Slot(playerinventory, j + i * 9 + 9, 8 + j * 18, 84 + i * 18)); + } + } + + for (i = 0; i < 9; ++i) { + this.a(new Slot(playerinventory, i, 8 + i * 18, 142)); + } + + // CraftBukkit start + player = (Player) playerinventory.player.getBukkitEntity(); + // CraftBukkit end + } + + public void addSlotListener(ICrafting icrafting) { + super.addSlotListener(icrafting); + icrafting.setContainerData(this, 0, this.costs[0]); + icrafting.setContainerData(this, 1, this.costs[1]); + icrafting.setContainerData(this, 2, this.costs[2]); + + if (!AzuriteConfig.oldEnchantingSystem.getValue()) { + icrafting.setContainerData(this, 3, this.f & -16); + icrafting.setContainerData(this, 4, this.h[0]); + icrafting.setContainerData(this, 5, this.h[1]); + icrafting.setContainerData(this, 6, this.h[2]); + } + } + + public void b() { + super.b(); + + for (ICrafting icrafting : this.listeners) { + icrafting.setContainerData(this, 0, this.costs[0]); + icrafting.setContainerData(this, 1, this.costs[1]); + icrafting.setContainerData(this, 2, this.costs[2]); + if (!AzuriteConfig.oldEnchantingSystem.getValue()) { + icrafting.setContainerData(this, 3, this.f & -16); + icrafting.setContainerData(this, 4, this.h[0]); + icrafting.setContainerData(this, 5, this.h[1]); + icrafting.setContainerData(this, 6, this.h[2]); + } + } + + } + + public void a(IInventory iinventory) { + if (iinventory == this.enchantSlots) { + ItemStack itemstack = iinventory.getItem(0); + int i; + + if (itemstack != null) { // CraftBukkit - relax condition + i = 0; + + int j; + + for (j = -1; j <= 1; ++j) { + for (int k = -1; k <= 1; ++k) { + if ((j != 0 || k != 0) && this.world.isEmpty(this.position.a(k, 0, j)) && this.world.isEmpty(this.position.a(k, 1, j))) { + if (this.world.getType(this.position.a(k * 2, 0, j * 2)).getBlock() == Blocks.BOOKSHELF) { + ++i; + } + + if (this.world.getType(this.position.a(k * 2, 1, j * 2)).getBlock() == Blocks.BOOKSHELF) { + ++i; + } + + if (k != 0 && j != 0) { + if (this.world.getType(this.position.a(k * 2, 0, j)).getBlock() == Blocks.BOOKSHELF) { + ++i; + } + + if (this.world.getType(this.position.a(k * 2, 1, j)).getBlock() == Blocks.BOOKSHELF) { + ++i; + } + + if (this.world.getType(this.position.a(k, 0, j * 2)).getBlock() == Blocks.BOOKSHELF) { + ++i; + } + + if (this.world.getType(this.position.a(k, 1, j * 2)).getBlock() == Blocks.BOOKSHELF) { + ++i; + } + } + } + } + } + + if (!AzuriteConfig.oldEnchantingSystem.getValue()) + this.k.setSeed(this.f); + + for (j = 0; j < 3; ++j) { + this.costs[j] = EnchantmentManager.a(this.k, j, i, itemstack); + this.h[j] = -1; + if (this.costs[j] < j + 1) { + this.costs[j] = 0; + } + } + + // CraftBukkit start + CraftItemStack item = CraftItemStack.asCraftMirror(itemstack); + PrepareItemEnchantEvent event = new PrepareItemEnchantEvent(player, this.getBukkitView(), this.world.getWorld().getBlockAt(position.getX(), position.getY(), position.getZ()), item, this.costs, i); + event.setCancelled(!itemstack.v()); + this.world.getServer().getPluginManager().callEvent(event); + + if (event.isCancelled()) { + for (i = 0; i < 3; ++i) { + this.costs[i] = 0; + } + return; + } + // CraftBukkit end + + for (j = 0; j < 3; ++j) { + if (this.costs[j] > 0) { + List list = this.a(itemstack, j, this.costs[j]); + + if (list != null && !list.isEmpty()) { + WeightedRandomEnchant weightedrandomenchant = list.get(this.k.nextInt(list.size())); + + this.h[j] = weightedrandomenchant.enchantment.id | weightedrandomenchant.level << 8; + } + } + } + + this.b(); + } else { + for (i = 0; i < 3; ++i) { + this.costs[i] = 0; + this.h[i] = -1; + } + } + } + + } + + public boolean a(EntityHuman entityhuman, int i) { + ItemStack itemstack = this.enchantSlots.getItem(0); + ItemStack itemstack1 = this.enchantSlots.getItem(1); + int j = i + 1; + int cost = costs[i]; + + if (!AzuriteConfig.oldEnchantingSystem.getValue() && (itemstack1 == null || itemstack1.count < j) && !entityhuman.abilities.canInstantlyBuild) { + return false; + } else if (cost > 0 && itemstack != null && (entityhuman.expLevel >= j && entityhuman.expLevel >= cost || entityhuman.abilities.canInstantlyBuild)) { + + List list = this.a(itemstack, i, cost); + // CraftBukkit start - Provide an empty enchantment list + if (list == null) { + list = new java.util.ArrayList<>(); + } + // CraftBukkit end + boolean flag = itemstack.getItem() == Items.BOOK; + + // CraftBukkit start + Map enchants = new java.util.HashMap<>(); + for (WeightedRandomEnchant instance : list) { + enchants.put(org.bukkit.enchantments.Enchantment.getById(instance.enchantment.id), instance.level); + } + CraftItemStack item = CraftItemStack.asCraftMirror(itemstack); + + EnchantItemEvent event = new EnchantItemEvent((Player) entityhuman.getBukkitEntity(), this.getBukkitView(), this.world.getWorld().getBlockAt(position.getX(), position.getY(), position.getZ()), item, this.costs[i], enchants, i); + this.world.getServer().getPluginManager().callEvent(event); + + int level = event.getExpLevelCost(); + if (event.isCancelled() || (level > entityhuman.expLevel && !entityhuman.abilities.canInstantlyBuild) || event.getEnchantsToAdd().isEmpty()) { + return false; + } + if (flag) { + itemstack.setItem(Items.ENCHANTED_BOOK); + } + + for (Map.Entry entry : event.getEnchantsToAdd().entrySet()) { + try { + if (flag) { + int enchantId = entry.getKey().getId(); + Enchantment ench = Enchantment.getById(enchantId); + if (ench == null) + continue; + + WeightedRandomEnchant enchantment = new WeightedRandomEnchant(ench, entry.getValue()); + Items.ENCHANTED_BOOK.a(itemstack, enchantment); + } else { + item.addUnsafeEnchantment(entry.getKey(), entry.getValue()); + } + } catch (IllegalArgumentException e) { + /* Just swallow invalid enchantments */ + } + } + + // CraftBukkit end + + if (!AzuriteConfig.oldEnchantingSystem.getValue()) { + entityhuman.enchantDone(j); + + if (!entityhuman.abilities.canInstantlyBuild) { + itemstack1.count -= j; + if (itemstack1.count <= 0) { + this.enchantSlots.setItem(1, null); + } + } + } else { + entityhuman.levelDown(-level); + } + + this.enchantSlots.update(); + if (!AzuriteConfig.oldEnchantingSystem.getValue()) + this.f = entityhuman.cj(); + this.a(this.enchantSlots); + entityhuman.b(StatisticList.W); + player.updateInventory(); + return true; + + } else { + return false; + } + } + + private List a(ItemStack itemstack, int i, int j) { + if (!AzuriteConfig.oldEnchantingSystem.getValue()) + this.k.setSeed(this.f + i); + List list = EnchantmentManager.b(this.k, itemstack, j); + + if (itemstack.getItem() == Items.BOOK && list != null && list.size() > 1) { + list.remove(this.k.nextInt(list.size())); + } + + return list; + } + + public void b(EntityHuman entityhuman) { + super.b(entityhuman); + // CraftBukkit Start - If an enchantable was opened from a null location, set the world to the player's world, preventing a crash + if (this.world == null) { + this.world = entityhuman.getWorld(); + } + // CraftBukkit end + + if (!AzuriteConfig.oldEnchantingSystem.getValue()) { + for (int i = 0; i < this.enchantSlots.getSize(); ++i) { + ItemStack itemstack = this.enchantSlots.splitWithoutUpdate(i); + + if (itemstack != null) { + entityhuman.drop(itemstack, false); + } + } + } else { + ItemStack itemstack = this.enchantSlots.splitWithoutUpdate(0); + if (itemstack != null) + entityhuman.drop(itemstack, false); + + enchantSlots.setItem(1, null); + } + } + + public boolean a(EntityHuman entityhuman) { + if (!this.checkReachable) return true; // CraftBukkit + return this.world.getType(this.position).getBlock() == Blocks.ENCHANTING_TABLE && entityhuman.e((double) this.position.getX() + 0.5D, (double) this.position.getY() + 0.5D, (double) this.position.getZ() + 0.5D) <= 64.0D; + } + + public ItemStack b(EntityHuman entityhuman, int i) { + ItemStack itemstack = null; + Slot slot = this.c.get(i); + + if (slot != null && slot.hasItem()) { + ItemStack itemstack1 = slot.getItem(); + + itemstack = itemstack1.cloneItemStack(); + if (i == 0) { + if (!this.a(itemstack1, 2, 38, true)) { + return null; + } + } else if (i == 1) { + if (!this.a(itemstack1, 2, 38, true)) { + return null; + } + } else if (itemstack1.getItem() == Items.DYE && EnumColor.fromInvColorIndex(itemstack1.getData()) == EnumColor.BLUE) { + if (!this.a(itemstack1, 1, 2, true)) { + return null; + } + } else { + Slot item = c.get(0); + if (item.hasItem() || !item.isAllowed(itemstack1)) { + return null; + } + + if (itemstack1.hasTag() && itemstack1.count == 1) { + item.set(itemstack1.cloneItemStack()); + itemstack1.count = 0; + } else if (itemstack1.count >= 1) { + // Spigot start + ItemStack clone = itemstack1.cloneItemStack(); + clone.count = 1; + item.set(clone); + // Spigot end + --itemstack1.count; + } + } + + if (itemstack1.count == 0) { + slot.set(null); + } else { + slot.f(); + } + + if (itemstack1.count == itemstack.count) { + return null; + } + + slot.a(entityhuman, itemstack1); + } + + return itemstack; + } + + // CraftBukkit start + @Override + public CraftInventoryView getBukkitView() { + if (bukkitEntity != null) { + return bukkitEntity; + } + + CraftInventoryEnchanting inventory = new CraftInventoryEnchanting(this.enchantSlots); + bukkitEntity = new CraftInventoryView(this.player, inventory, this); + return bukkitEntity; + } + // CraftBukkit end +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ContainerFurnace.java b/azurite-server/src/main/java/net/minecraft/server/ContainerFurnace.java new file mode 100644 index 0000000..e81aca3 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ContainerFurnace.java @@ -0,0 +1,139 @@ +package net.minecraft.server; + +// CraftBukkit start +import org.bukkit.craftbukkit.inventory.CraftInventoryFurnace; +import org.bukkit.craftbukkit.inventory.CraftInventoryView; +// CraftBukkit end + +public class ContainerFurnace extends Container { + + private final IInventory furnace; + private int f; + private int g; + private int h; + private int i; + + // CraftBukkit start + private CraftInventoryView bukkitEntity = null; + private final PlayerInventory player; + + @Override + public CraftInventoryView getBukkitView() { + if (bukkitEntity != null) { + return bukkitEntity; + } + + CraftInventoryFurnace inventory = new CraftInventoryFurnace((TileEntityFurnace) this.furnace); + bukkitEntity = new CraftInventoryView(this.player.player.getBukkitEntity(), inventory, this); + return bukkitEntity; + } + // CraftBukkit end + + public ContainerFurnace(PlayerInventory playerinventory, IInventory iinventory) { + this.furnace = iinventory; + this.a(new Slot(iinventory, 0, 56, 17)); + this.a(new SlotFurnaceFuel(iinventory, 1, 56, 53)); + this.a(new SlotFurnaceResult(playerinventory.player, iinventory, 2, 116, 35)); + this.player = playerinventory; // CraftBukkit - save player + + int i; + + for (i = 0; i < 3; ++i) { + for (int j = 0; j < 9; ++j) { + this.a(new Slot(playerinventory, j + i * 9 + 9, 8 + j * 18, 84 + i * 18)); + } + } + + for (i = 0; i < 9; ++i) { + this.a(new Slot(playerinventory, i, 8 + i * 18, 142)); + } + + } + + public void addSlotListener(ICrafting icrafting) { + super.addSlotListener(icrafting); + icrafting.setContainerData(this, this.furnace); + } + + public void b() { + super.b(); + + for (ICrafting icrafting : this.listeners) { + if (this.f != this.furnace.getProperty(2)) { + icrafting.setContainerData(this, 2, this.furnace.getProperty(2)); + } + + if (this.h != this.furnace.getProperty(0)) { + icrafting.setContainerData(this, 0, this.furnace.getProperty(0)); + } + + if (this.i != this.furnace.getProperty(1)) { + icrafting.setContainerData(this, 1, this.furnace.getProperty(1)); + } + + if (this.g != this.furnace.getProperty(3)) { + icrafting.setContainerData(this, 3, this.furnace.getProperty(3)); + } + } + + this.f = this.furnace.getProperty(2); + this.h = this.furnace.getProperty(0); + this.i = this.furnace.getProperty(1); + this.g = this.furnace.getProperty(3); + } + + public boolean a(EntityHuman entityhuman) { + if (!this.checkReachable) return true; // CraftBukkit + return this.furnace.a(entityhuman); + } + + public ItemStack b(EntityHuman entityhuman, int i) { + ItemStack itemstack = null; + Slot slot = this.c.get(i); + + if (slot != null && slot.hasItem()) { + ItemStack itemstack1 = slot.getItem(); + + itemstack = itemstack1.cloneItemStack(); + if (i == 2) { + if (!this.a(itemstack1, 3, 39, true)) { + return null; + } + + slot.a(itemstack1, itemstack); + } else if (i != 1 && i != 0) { + if (RecipesFurnace.getInstance().getResult(itemstack1) != null) { + if (!this.a(itemstack1, 0, 1, false)) { + return null; + } + } else if (TileEntityFurnace.isFuel(itemstack1)) { + if (!this.a(itemstack1, 1, 2, false)) { + return null; + } + } else if (i >= 3 && i < 30) { + if (!this.a(itemstack1, 30, 39, false)) { + return null; + } + } else if (i >= 30 && i < 39 && !this.a(itemstack1, 3, 30, false)) { + return null; + } + } else if (!this.a(itemstack1, 3, 39, false)) { + return null; + } + + if (itemstack1.count == 0) { + slot.set(null); + } else { + slot.f(); + } + + if (itemstack1.count == itemstack.count) { + return null; + } + + slot.a(entityhuman, itemstack1); + } + + return itemstack; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ContainerHopper.java b/azurite-server/src/main/java/net/minecraft/server/ContainerHopper.java new file mode 100644 index 0000000..878a68c --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ContainerHopper.java @@ -0,0 +1,87 @@ +package net.minecraft.server; + +// CraftBukkit start +import org.bukkit.craftbukkit.inventory.CraftInventory; +import org.bukkit.craftbukkit.inventory.CraftInventoryView; +// CraftBukkit end + +public class ContainerHopper extends Container { + + private final IInventory hopper; + + // CraftBukkit start + private CraftInventoryView bukkitEntity = null; + private final PlayerInventory player; + + @Override + public CraftInventoryView getBukkitView() { + if (bukkitEntity != null) { + return bukkitEntity; + } + + CraftInventory inventory = new CraftInventory(this.hopper); + bukkitEntity = new CraftInventoryView(this.player.player.getBukkitEntity(), inventory, this); + return bukkitEntity; + } + // CraftBukkit end + + public ContainerHopper(PlayerInventory playerinventory, IInventory iinventory, EntityHuman entityhuman) { + this.hopper = iinventory; + this.player = playerinventory; // CraftBukkit - save player + iinventory.startOpen(entityhuman); + byte b0 = 51; + + int i; + + for (i = 0; i < iinventory.getSize(); ++i) { + this.a(new Slot(iinventory, i, 44 + i * 18, 20)); + } + + for (i = 0; i < 3; ++i) { + for (int j = 0; j < 9; ++j) { + this.a(new Slot(playerinventory, j + i * 9 + 9, 8 + j * 18, i * 18 + b0)); + } + } + + for (i = 0; i < 9; ++i) { + this.a(new Slot(playerinventory, i, 8 + i * 18, 58 + b0)); + } + + } + + public boolean a(EntityHuman entityhuman) { + if (!this.checkReachable) return true; // CraftBukkit + return this.hopper.a(entityhuman); + } + + public ItemStack b(EntityHuman entityhuman, int i) { + ItemStack itemstack = null; + Slot slot = this.c.get(i); + + if (slot != null && slot.hasItem()) { + ItemStack itemstack1 = slot.getItem(); + + itemstack = itemstack1.cloneItemStack(); + if (i < this.hopper.getSize()) { + if (!this.a(itemstack1, this.hopper.getSize(), this.c.size(), true)) { + return null; + } + } else if (!this.a(itemstack1, 0, this.hopper.getSize(), false)) { + return null; + } + + if (itemstack1.count == 0) { + slot.set(null); + } else { + slot.f(); + } + } + + return itemstack; + } + + public void b(EntityHuman entityhuman) { + super.b(entityhuman); + this.hopper.closeContainer(entityhuman); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ContainerHorse.java b/azurite-server/src/main/java/net/minecraft/server/ContainerHorse.java new file mode 100644 index 0000000..33753b3 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ContainerHorse.java @@ -0,0 +1,113 @@ +package net.minecraft.server; + +// CraftBukkit start +import org.bukkit.craftbukkit.inventory.CraftInventory; +import org.bukkit.craftbukkit.inventory.CraftInventoryView; +import org.bukkit.inventory.InventoryView; +// CraftBukkit end + +public class ContainerHorse extends Container { + + private final IInventory a; + private final EntityHorse f; + + // CraftBukkit start + CraftInventoryView bukkitEntity; + PlayerInventory player; + + @Override + public InventoryView getBukkitView() { + if (bukkitEntity != null) { + return bukkitEntity; + } + + CraftInventory inventory = new org.bukkit.craftbukkit.inventory.CraftInventoryHorse(this.a); + return bukkitEntity = new CraftInventoryView(player.player.getBukkitEntity(), inventory, this); + } + + public ContainerHorse(IInventory iinventory, final IInventory iinventory1, final EntityHorse entityhorse, EntityHuman entityhuman) { + player = (PlayerInventory) iinventory; + // CraftBukkit end + this.a = iinventory1; + this.f = entityhorse; + byte b0 = 3; + + iinventory1.startOpen(entityhuman); + int i = (b0 - 4) * 18; + + this.a(new Slot(iinventory1, 0, 8, 18) { + public boolean isAllowed(ItemStack itemstack) { + return super.isAllowed(itemstack) && itemstack.getItem() == Items.SADDLE && !this.hasItem(); + } + }); + this.a(new Slot(iinventory1, 1, 8, 36) { + public boolean isAllowed(ItemStack itemstack) { + return super.isAllowed(itemstack) && entityhorse.cO() && EntityHorse.a(itemstack.getItem()); + } + }); + int j; + int k; + + if (entityhorse.hasChest()) { + for (j = 0; j < b0; ++j) { + for (k = 0; k < 5; ++k) { + this.a(new Slot(iinventory1, 2 + k + j * 5, 80 + k * 18, 18 + j * 18)); + } + } + } + + for (j = 0; j < 3; ++j) { + for (k = 0; k < 9; ++k) { + this.a(new Slot(iinventory, k + j * 9 + 9, 8 + k * 18, 102 + j * 18 + i)); + } + } + + for (j = 0; j < 9; ++j) { + this.a(new Slot(iinventory, j, 8 + j * 18, 160 + i)); + } + + } + + public boolean a(EntityHuman entityhuman) { + return this.a.a(entityhuman) && this.f.isAlive() && this.f.g((Entity) entityhuman) < 8.0F; + } + + public ItemStack b(EntityHuman entityhuman, int i) { + ItemStack itemstack = null; + Slot slot = this.c.get(i); + + if (slot != null && slot.hasItem()) { + ItemStack itemstack1 = slot.getItem(); + + itemstack = itemstack1.cloneItemStack(); + if (i < this.a.getSize()) { + if (!this.a(itemstack1, this.a.getSize(), this.c.size(), true)) { + return null; + } + } else if (this.getSlot(1).isAllowed(itemstack1) && !this.getSlot(1).hasItem()) { + if (!this.a(itemstack1, 1, 2, false)) { + return null; + } + } else if (this.getSlot(0).isAllowed(itemstack1)) { + if (!this.a(itemstack1, 0, 1, false)) { + return null; + } + } else if (this.a.getSize() <= 2 || !this.a(itemstack1, 2, this.a.getSize(), false)) { + return null; + } + + if (itemstack1.count == 0) { + slot.set(null); + } else { + slot.f(); + } + } + + return itemstack; + } + + public void b(EntityHuman entityhuman) { + super.b(entityhuman); + this.a.closeContainer(entityhuman); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ContainerMerchant.java b/azurite-server/src/main/java/net/minecraft/server/ContainerMerchant.java new file mode 100644 index 0000000..077da70 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ContainerMerchant.java @@ -0,0 +1,129 @@ +package net.minecraft.server; + +import org.bukkit.craftbukkit.inventory.CraftInventoryView; + +public class ContainerMerchant extends Container { + + private final IMerchant merchant; + private final InventoryMerchant f; + + // CraftBukkit start + private CraftInventoryView bukkitEntity = null; + private final PlayerInventory player; + + @Override + public CraftInventoryView getBukkitView() { + if (bukkitEntity == null) { + bukkitEntity = new CraftInventoryView(this.player.player.getBukkitEntity(), new org.bukkit.craftbukkit.inventory.CraftInventoryMerchant(f), this); + } + return bukkitEntity; + } + // CraftBukkit end + + public ContainerMerchant(PlayerInventory playerinventory, IMerchant imerchant, World world) { + this.merchant = imerchant; + this.f = new InventoryMerchant(playerinventory.player, imerchant); + this.a(new Slot(this.f, 0, 36, 53)); + this.a(new Slot(this.f, 1, 62, 53)); + this.a((new SlotMerchantResult(playerinventory.player, imerchant, this.f, 2, 120, 53))); + this.player = playerinventory; // CraftBukkit - save player + + int i; + + for (i = 0; i < 3; ++i) { + for (int j = 0; j < 9; ++j) { + this.a(new Slot(playerinventory, j + i * 9 + 9, 8 + j * 18, 84 + i * 18)); + } + } + + for (i = 0; i < 9; ++i) { + this.a(new Slot(playerinventory, i, 8 + i * 18, 142)); + } + + } + + public InventoryMerchant e() { + return this.f; + } + + public void addSlotListener(ICrafting icrafting) { + super.addSlotListener(icrafting); + } + + public void b() { + super.b(); + } + + public void a(IInventory iinventory) { + this.f.h(); + super.a(iinventory); + } + + public void d(int i) { + this.f.d(i); + } + + public boolean a(EntityHuman entityhuman) { + return this.merchant.v_() == entityhuman; + } + + public ItemStack b(EntityHuman entityhuman, int i) { + ItemStack itemstack = null; + Slot slot = this.c.get(i); + + if (slot != null && slot.hasItem()) { + ItemStack itemstack1 = slot.getItem(); + + itemstack = itemstack1.cloneItemStack(); + if (i == 2) { + if (!this.a(itemstack1, 3, 39, true)) { + return null; + } + + slot.a(itemstack1, itemstack); + } else if (i != 0 && i != 1) { + if (i >= 3 && i < 30) { + if (!this.a(itemstack1, 30, 39, false)) { + return null; + } + } else if (i >= 30 && i < 39 && !this.a(itemstack1, 3, 30, false)) { + return null; + } + } else if (!this.a(itemstack1, 3, 39, false)) { + return null; + } + + if (itemstack1.count == 0) { + slot.set(null); + } else { + slot.f(); + } + + if (itemstack1.count == itemstack.count) { + return null; + } + + slot.a(entityhuman, itemstack1); + } + + return itemstack; + } + + public void b(EntityHuman entityhuman) { + super.b(entityhuman); + this.merchant.a_((EntityHuman) null); + super.b(entityhuman); + + ItemStack itemstack = this.f.splitWithoutUpdate(0); + + if (itemstack != null) { + entityhuman.drop(itemstack, false); + } + + itemstack = this.f.splitWithoutUpdate(1); + if (itemstack != null) { + entityhuman.drop(itemstack, false); + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ContainerPlayer.java b/azurite-server/src/main/java/net/minecraft/server/ContainerPlayer.java new file mode 100644 index 0000000..4ee6832 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ContainerPlayer.java @@ -0,0 +1,317 @@ +package net.minecraft.server; + +// CraftBukkit start +import dev.azurite.spigot.configs.AzuriteConfig; +import dev.azurite.spigot.utils.UnimplementedList; +import org.bukkit.craftbukkit.inventory.CraftInventoryCrafting; +import org.bukkit.craftbukkit.inventory.CraftInventoryView; +// CraftBukkit end + +public class ContainerPlayer extends Container { + + public InventoryCrafting craftInventory; + public InventoryCraftResult resultInventory; + public boolean g; + private final EntityHuman h; + // CraftBukkit start + private CraftInventoryView bukkitEntity = null; + public final PlayerInventory player; + // CraftBukkit end + + public ContainerPlayer(final PlayerInventory playerinventory, boolean flag, EntityHuman entityhuman) { + this.g = flag; + this.h = entityhuman; + this.resultInventory = new InventoryCraftResult(); // CraftBukkit - moved to before InventoryCrafting construction + this.craftInventory = new InventoryCrafting(this, 2, 2, playerinventory.player); // CraftBukkit - pass player + this.craftInventory.resultInventory = this.resultInventory; // CraftBukkit - let InventoryCrafting know about its result slot + this.player = playerinventory; // CraftBukkit - save player + this.a(new SlotResult(playerinventory.player, this.craftInventory, this.resultInventory, 0, 144, 36)); + + int j; + + for (int i = 0; i < 2; ++i) { + for (j = 0; j < 2; ++j) { + this.a(new Slot(this.craftInventory, j + i * 2, 88 + j * 18, 26 + i * 18)); + } + } + + for (int ii = 0; ii < 4; ++ii) { + final int i = ii; + this.a(new Slot(playerinventory, playerinventory.getSize() - 1 - ii, 8, 8 + ii * 18) { + public int getMaxStackSize() { + return 1; + } + + public boolean isAllowed(ItemStack itemstack) { + return itemstack != null && (itemstack.getItem() instanceof ItemArmor ? ((ItemArmor) itemstack.getItem()).b == i : ((itemstack.getItem() == Item.getItemOf(Blocks.PUMPKIN) || itemstack.getItem() == Items.SKULL) && i == 0)); + } + }); + } + + for (int i = 0; i < 3; ++i) { + for (j = 0; j < 9; ++j) { + this.a(new Slot(playerinventory, j + (i + 1) * 9, 8 + j * 18, 84 + i * 18)); + } + } + + for (int i = 0; i < 9; ++i) { + this.a(new Slot(playerinventory, i, 8 + i * 18, 142)); + } + + // Beanes - we use an array instead for faster lookup + this.b = new UnimplementedList<>(); + } + + public void a(IInventory iinventory) { + CraftingManager.getInstance().lastCraftView = getBukkitView(); + ItemStack craftResult = CraftingManager.getInstance().craft(this.craftInventory, this.h.world); + this.resultInventory.setItem(0, craftResult); + if (super.listeners.isEmpty()) { + return; + } + + EntityPlayer player = (EntityPlayer) super.listeners.get(0); // TODO: Is this _always_ correct? Seems like it. + player.playerConnection.sendPacket(new PacketPlayOutSetSlot(player.activeContainer.windowId, 0, craftResult)); + } + + public void b(EntityHuman entityhuman) { + super.b(entityhuman); + + for (int i = 0; i < 4; ++i) { + ItemStack itemstack = this.craftInventory.splitWithoutUpdate(i); + + if (itemstack != null) { + entityhuman.drop(itemstack, false); + } + } + + this.resultInventory.setItem(0, null); + } + + public boolean a(EntityHuman entityhuman) { + return true; + } + + public ItemStack b(EntityHuman entityhuman, int i) { + ItemStack itemstack = null; + Slot slot = this.c.get(i); + + if (slot != null && slot.hasItem()) { + ItemStack itemstack1 = slot.getItem(); + + itemstack = itemstack1.cloneItemStack(); + if (i == 0) { + if (!this.a(itemstack1, 9, 45, true)) { + return null; + } + + slot.a(itemstack1, itemstack); + } else if (i < 5) { + if (!this.a(itemstack1, 9, 45, false)) { + return null; + } + } else if (i < 9) { + if (!this.a(itemstack1, 9, 45, false)) { + return null; + } + } else if (itemstack.getItem() instanceof ItemArmor && !this.c.get(5 + ((ItemArmor) itemstack.getItem()).b).hasItem()) { + int j = 5 + ((ItemArmor) itemstack.getItem()).b; + + if (!this.a(itemstack1, j, j + 1, false)) { + return null; + } + } else if (i < 36) { + if (!this.a(itemstack1, 36, 45, false)) { + return null; + } + } else if (i < 45) { + if (!this.a(itemstack1, 9, 36, false)) { + return null; + } + } else if (!this.a(itemstack1, 9, 45, false)) { + return null; + } + + if (itemstack1.count == 0) { + slot.set(null); + } else { + slot.f(); + } + + if (itemstack1.count == itemstack.count) { + return null; + } + + slot.a(entityhuman, itemstack1); + } + + return itemstack; + } + + public boolean a(ItemStack itemstack, Slot slot) { + return slot.inventory != this.resultInventory && super.a(itemstack, slot); + } + + // CraftBukkit start + @Override + public CraftInventoryView getBukkitView() { + if (bukkitEntity != null) { + return bukkitEntity; + } + + bukkitEntity = new CraftInventoryView(this.player.player.getBukkitEntity(), new CraftInventoryCrafting(this.craftInventory, this.resultInventory), this); + return bukkitEntity; + } + // CraftBukkit end + + // Beanes - more optimized inventory update + item use desync fix + @Override + public void b() { + // Update result slot + this.updateSlot(this.resultInventory.items[0], 0); + + // Update crafting slots + this.updateSlot(this.craftInventory.items[0],1); + this.updateSlot(this.craftInventory.items[1], 2); + this.updateSlot(this.craftInventory.items[2], 3); + this.updateSlot(this.craftInventory.items[3], 4); + + // Update armor slots + this.updateSlot(this.player.armor[3], 5); + this.updateSlot(this.player.armor[2], 6); + this.updateSlot(this.player.armor[1], 7); + this.updateSlot(this.player.armor[0], 8); + + // Update inventory slots + this.updateSlot(this.player.items[9], 9); + this.updateSlot(this.player.items[10], 10); + this.updateSlot(this.player.items[11], 11); + this.updateSlot(this.player.items[12], 12); + this.updateSlot(this.player.items[13], 13); + this.updateSlot(this.player.items[15], 15); + this.updateSlot(this.player.items[16], 16); + this.updateSlot(this.player.items[14], 14); + this.updateSlot(this.player.items[17], 17); + this.updateSlot(this.player.items[18], 18); + this.updateSlot(this.player.items[19], 19); + this.updateSlot(this.player.items[20], 20); + this.updateSlot(this.player.items[21], 21); + this.updateSlot(this.player.items[22], 22); + this.updateSlot(this.player.items[23], 23); + this.updateSlot(this.player.items[24], 24); + this.updateSlot(this.player.items[25], 25); + this.updateSlot(this.player.items[26], 26); + this.updateSlot(this.player.items[27], 27); + this.updateSlot(this.player.items[28], 28); + this.updateSlot(this.player.items[29], 29); + this.updateSlot(this.player.items[30], 30); + this.updateSlot(this.player.items[31], 31); + this.updateSlot(this.player.items[32], 32); + this.updateSlot(this.player.items[33], 33); + this.updateSlot(this.player.items[34], 34); + this.updateSlot(this.player.items[35], 35); + + // Calculate using slot for item use desync + int slotUsing = -1; + int slotEating = -1; + + if (AzuriteConfig.patchItemDesyncBug.getValue()) { + ItemStack itemInHand = this.player.getItemInHand(); + if (itemInHand != null) { + EnumAnimation animation = itemInHand.getItem().e(itemInHand); + + if (animation == EnumAnimation.BLOCK || animation == EnumAnimation.BOW) { + slotUsing = this.player.itemInHandIndex; + } + } + } + + if (player.player.isEating() && AzuriteConfig.patchDropEatRunBug.getValue()) { + ItemStack itemInHand = this.player.getItemInHand(); + if (itemInHand != null) { + EnumAnimation animation = itemInHand.getItem().e(itemInHand); + + if (animation == EnumAnimation.EAT) { + slotEating = this.player.itemInHandIndex; + } + } + } + + // Update hotbar slots + for (int slotIndex = 36; slotIndex <= 44; slotIndex++) { + int inventoryIndex = slotIndex - 36; + + if (inventoryIndex == slotEating) { + this.updateSlotWithEatTransaction(this.player.items[inventoryIndex], slotIndex); + } else if (inventoryIndex != slotUsing) { + this.updateSlot(this.player.items[inventoryIndex], slotIndex); + } else { + this.updateSlotNoDurability(this.player.items[inventoryIndex], slotIndex); + } + + + } + + this.tickCount++; + } + + private final ItemStack[] lastItemStacks = new ItemStack[45]; + + // Beanes - we override this so we dont add null to this.b (as this.b is not implemented) + @Override + protected Slot a(Slot slot) { + slot.rawSlotIndex = this.c.size(); + this.c.add(slot); + return slot; + } + + + // Beanes - we override this so we dont add update this.b (as this.b is not implemented) + @Override + public void updateSlotsToLatest() { + for (int slotIndex = 0; slotIndex < this.c.size(); slotIndex++) { + ItemStack lastItemStack = this.c.get(slotIndex).getItem(); + ItemStack newItemStack = (lastItemStack == null) ? null : lastItemStack.cloneItemStack(); + this.lastItemStacks[slotIndex] = newItemStack; + } + } + + private void updateSlot(ItemStack lastItemStack, int slotIndex) { + ItemStack newItemStack = lastItemStacks[slotIndex]; + if (!ItemStack.fastMatches(newItemStack, lastItemStack) || (this.tickCount % 20 == 0 && !ItemStack.matches(newItemStack, lastItemStack))) { + newItemStack = (lastItemStack == null) ? null : lastItemStack.cloneItemStack(); + lastItemStacks[slotIndex] = newItemStack; + for (ICrafting listener : this.listeners) + listener.a(this, slotIndex, newItemStack); + } + } + + private void updateSlotNoDurability(ItemStack lastItemStack, int slotIndex) { + ItemStack newItemStack = lastItemStacks[slotIndex]; + if (!ItemStack.fastMatchesWithoutDurability(newItemStack, lastItemStack) || (this.tickCount % 20 == 0 && !ItemStack.matchesWithoutDurability(newItemStack, lastItemStack))) { + newItemStack = (lastItemStack == null) ? null : lastItemStack.cloneItemStack(); + lastItemStacks[slotIndex] = newItemStack; + for (ICrafting listener : this.listeners) + listener.a(this, slotIndex, newItemStack); + } + } + + private void updateSlotWithEatTransaction(ItemStack lastItemStack, int slotIndex) { + ItemStack newItemStack = lastItemStacks[slotIndex]; + if (!ItemStack.fastMatches(newItemStack, lastItemStack) || (this.tickCount % 20 == 0 && !ItemStack.matches(newItemStack, lastItemStack))) { + newItemStack = (lastItemStack == null) ? null : lastItemStack.cloneItemStack(); + lastItemStacks[slotIndex] = newItemStack; + for (ICrafting listener : this.listeners) { + if (listener == player.player) { + player.player.sendPacket(new PacketPlayOutTransaction( + 0, + (short) (Short.MAX_VALUE - 1), + false + )); + } + + listener.a(this, slotIndex, newItemStack); + } + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ContainerWorkbench.java b/azurite-server/src/main/java/net/minecraft/server/ContainerWorkbench.java new file mode 100644 index 0000000..e3ee7e1 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ContainerWorkbench.java @@ -0,0 +1,144 @@ +package net.minecraft.server; + +// CraftBukkit start +import org.bukkit.craftbukkit.inventory.CraftInventoryCrafting; +import org.bukkit.craftbukkit.inventory.CraftInventoryView; +// CraftBukkit end + +public class ContainerWorkbench extends Container { + + public InventoryCrafting craftInventory; // CraftBukkit - move initialization into constructor + public IInventory resultInventory; // CraftBukkit - move initialization into constructor + private final World g; + private final BlockPosition h; + // CraftBukkit start + private CraftInventoryView bukkitEntity = null; + private final PlayerInventory player; + // CraftBukkit end + + public ContainerWorkbench(PlayerInventory playerinventory, World world, BlockPosition blockposition) { + // CraftBukkit start - Switched order of IInventory construction and stored player + this.resultInventory = new InventoryCraftResult(); + this.craftInventory = new InventoryCrafting(this, 3, 3, playerinventory.player); // CraftBukkit - pass player + this.craftInventory.resultInventory = this.resultInventory; + this.player = playerinventory; + // CraftBukkit end + this.g = world; + this.h = blockposition; + this.a(new SlotResult(playerinventory.player, this.craftInventory, this.resultInventory, 0, 124, 35)); + + int i; + int j; + + for (i = 0; i < 3; ++i) { + for (j = 0; j < 3; ++j) { + this.a(new Slot(this.craftInventory, j + i * 3, 30 + j * 18, 17 + i * 18)); + } + } + + for (i = 0; i < 3; ++i) { + for (j = 0; j < 9; ++j) { + this.a(new Slot(playerinventory, j + i * 9 + 9, 8 + j * 18, 84 + i * 18)); + } + } + + for (i = 0; i < 9; ++i) { + this.a(new Slot(playerinventory, i, 8 + i * 18, 142)); + } + + this.a(this.craftInventory); + } + + public void a(IInventory iinventory) { + // this.resultInventory.setItem(0, CraftingManager.getInstance().craft(this.craftInventory, this.g)); + // CraftBukkit start + CraftingManager.getInstance().lastCraftView = getBukkitView(); + ItemStack craftResult = CraftingManager.getInstance().craft(this.craftInventory, this.g); + this.resultInventory.setItem(0, craftResult); + if (super.listeners.size() < 1) { + return; + } + // See CraftBukkit PR #39 + if (craftResult != null && craftResult.getItem() == Items.FILLED_MAP) { + return; + } + EntityPlayer player = (EntityPlayer) super.listeners.get(0); // TODO: Is this _always_ correct? Seems like it. + player.playerConnection.sendPacket(new PacketPlayOutSetSlot(player.activeContainer.windowId, 0, craftResult)); + // CraftBukkit end + } + + public void b(EntityHuman entityhuman) { + super.b(entityhuman); + for (int i = 0; i < 9; ++i) { + ItemStack itemstack = this.craftInventory.splitWithoutUpdate(i); + + if (itemstack != null) { + entityhuman.drop(itemstack, false); + } + } + + } + + public boolean a(EntityHuman entityhuman) { + if (!this.checkReachable) return true; // CraftBukkit + return this.g.getType(this.h).getBlock() == Blocks.CRAFTING_TABLE && entityhuman.e((double) this.h.getX() + 0.5D, (double) this.h.getY() + 0.5D, (double) this.h.getZ() + 0.5D) <= 64.0D; + } + + public ItemStack b(EntityHuman entityhuman, int i) { + ItemStack itemstack = null; + Slot slot = this.c.get(i); + + if (slot != null && slot.hasItem()) { + ItemStack itemstack1 = slot.getItem(); + + itemstack = itemstack1.cloneItemStack(); + if (i == 0) { + if (!this.a(itemstack1, 10, 46, true)) { + return null; + } + + slot.a(itemstack1, itemstack); + } else if (i >= 10 && i < 37) { + if (!this.a(itemstack1, 37, 46, false)) { + return null; + } + } else if (i >= 37 && i < 46) { + if (!this.a(itemstack1, 10, 37, false)) { + return null; + } + } else if (!this.a(itemstack1, 10, 46, false)) { + return null; + } + + if (itemstack1.count == 0) { + slot.set(null); + } else { + slot.f(); + } + + if (itemstack1.count == itemstack.count) { + return null; + } + + slot.a(entityhuman, itemstack1); + } + + return itemstack; + } + + public boolean a(ItemStack itemstack, Slot slot) { + return slot.inventory != this.resultInventory && super.a(itemstack, slot); + } + + // CraftBukkit start + @Override + public CraftInventoryView getBukkitView() { + if (bukkitEntity != null) { + return bukkitEntity; + } + + bukkitEntity = new CraftInventoryView(this.player.player.getBukkitEntity(), new CraftInventoryCrafting(this.craftInventory, this.resultInventory), this); + return bukkitEntity; + } + // CraftBukkit end +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ControllerJump.java b/azurite-server/src/main/java/net/minecraft/server/ControllerJump.java new file mode 100644 index 0000000..df25ccb --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ControllerJump.java @@ -0,0 +1,19 @@ +package net.minecraft.server; + +public class ControllerJump { + private final EntityInsentient b; + protected boolean a; + + public ControllerJump(EntityInsentient var1) { + this.b = var1; + } + + public void a() { + this.a = true; + } + + public void b() { + this.b.i(this.a); + this.a = false; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ControllerLook.java b/azurite-server/src/main/java/net/minecraft/server/ControllerLook.java new file mode 100644 index 0000000..4f573ee --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ControllerLook.java @@ -0,0 +1,100 @@ +package net.minecraft.server; + +public class ControllerLook { + + private EntityInsentient a; + private float b; + private float c; + private boolean d; + private double e; + private double f; + private double g; + + public ControllerLook(EntityInsentient entityinsentient) { + this.a = entityinsentient; + } + + public void a(Entity entity, float f, float f1) { + this.e = entity.locX; + if (entity instanceof EntityLiving) { + this.f = entity.locY + (double) entity.getHeadHeight(); + } else { + this.f = (entity.getBoundingBox().b + entity.getBoundingBox().e) / 2.0D; + } + + this.g = entity.locZ; + this.b = f; + this.c = f1; + this.d = true; + } + + public void a(double d0, double d1, double d2, float f, float f1) { + this.e = d0; + this.f = d1; + this.g = d2; + this.b = f; + this.c = f1; + this.d = true; + } + + public void a() { + this.a.pitch = 0.0F; + if (this.d) { + this.d = false; + double d0 = this.e - this.a.locX; + double d1 = this.f - (this.a.locY + (double) this.a.getHeadHeight()); + double d2 = this.g - this.a.locZ; + double d3 = (double) MathHelper.sqrt(d0 * d0 + d2 * d2); + float f = (float) (MathHelper.b(d2, d0) * 180.0D / 3.1415927410125732D) - 90.0F; + float f1 = (float) (-(MathHelper.b(d1, d3) * 180.0D / 3.1415927410125732D)); + + this.a.pitch = this.a(this.a.pitch, f1, this.c); + this.a.aK = this.a(this.a.aK, f, this.b); + } else { + this.a.aK = this.a(this.a.aK, this.a.aI, 10.0F); + } + + float f2 = MathHelper.g(this.a.aK - this.a.aI); + + if (!this.a.getNavigation().m()) { + if (f2 < -75.0F) { + this.a.aK = this.a.aI - 75.0F; + } + + if (f2 > 75.0F) { + this.a.aK = this.a.aI + 75.0F; + } + } + + } + + private float a(float f, float f1, float f2) { + float f3 = MathHelper.g(f1 - f); + + if (f3 > f2) { + f3 = f2; + } + + if (f3 < -f2) { + f3 = -f2; + } + + return f + f3; + } + + public boolean b() { + return this.d; + } + + public double e() { + return this.e; + } + + public double f() { + return this.f; + } + + public double g() { + return this.g; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ControllerMove.java b/azurite-server/src/main/java/net/minecraft/server/ControllerMove.java new file mode 100644 index 0000000..051840c --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ControllerMove.java @@ -0,0 +1,86 @@ +package net.minecraft.server; + +public class ControllerMove { + protected EntityInsentient a; + protected double b; + protected double c; + protected double d; + protected double e; + protected boolean f; + + public ControllerMove(EntityInsentient var1) { + this.a = var1; + this.b = var1.locX; + this.c = var1.locY; + this.d = var1.locZ; + } + + public boolean a() { + return this.f; + } + + public double b() { + return this.e; + } + + public void a(double var1, double var3, double var5, double var7) { + this.b = var1; + this.c = var3; + this.d = var5; + this.e = var7; + this.f = true; + } + + public void c() { + this.a.n(0.0F); + if (this.f) { + this.f = false; + int var1 = MathHelper.floor(this.a.getBoundingBox().b + 0.5); + double var2 = this.b - this.a.locX; + double var4 = this.d - this.a.locZ; + double var6 = this.c - (double)var1; + double var8 = var2 * var2 + var6 * var6 + var4 * var4; + if (!(var8 < 2.500000277905201E-7)) { + float var10 = (float)(MathHelper.b(var4, var2) * 180.0 / 3.1415927410125732) - 90.0F; + this.a.yaw = this.a(this.a.yaw, var10, 30.0F); + this.a.k((float)(this.e * this.a.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).getValue())); + if (var6 > 0.0 && var2 * var2 + var4 * var4 < 1.0) { + this.a.getControllerJump().a(); + } + + } + } + } + + protected float a(float var1, float var2, float var3) { + float var4 = MathHelper.g(var2 - var1); + if (var4 > var3) { + var4 = var3; + } + + if (var4 < -var3) { + var4 = -var3; + } + + float var5 = var1 + var4; + if (var5 < 0.0F) { + var5 += 360.0F; + } else if (var5 > 360.0F) { + var5 -= 360.0F; + } + + return var5; + } + + public double d() { + return this.b; + } + + public double e() { + return this.c; + } + + public double f() { + return this.d; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/Convertable.java b/azurite-server/src/main/java/net/minecraft/server/Convertable.java new file mode 100644 index 0000000..92bfb05 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/Convertable.java @@ -0,0 +1,14 @@ +package net.minecraft.server; + +public interface Convertable { + + IDataManager a(String s, boolean flag); + + void d(); + + boolean e(String s); + + boolean isConvertable(String s); + + boolean convert(String s, IProgressUpdate iprogressupdate); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/Counter.java b/azurite-server/src/main/java/net/minecraft/server/Counter.java new file mode 100644 index 0000000..cbfe88b --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/Counter.java @@ -0,0 +1,3 @@ +package net.minecraft.server; + +public interface Counter {} diff --git a/azurite-server/src/main/java/net/minecraft/server/CounterStatistic.java b/azurite-server/src/main/java/net/minecraft/server/CounterStatistic.java new file mode 100644 index 0000000..a466533 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CounterStatistic.java @@ -0,0 +1,18 @@ +package net.minecraft.server; + +public class CounterStatistic extends Statistic { + + public CounterStatistic(String s, IChatBaseComponent ichatbasecomponent, Counter counter) { + super(s, ichatbasecomponent, counter); + } + + public CounterStatistic(String s, IChatBaseComponent ichatbasecomponent) { + super(s, ichatbasecomponent); + } + + public Statistic h() { + super.h(); + StatisticList.c.add(this); + return this; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CraftingManager.java b/azurite-server/src/main/java/net/minecraft/server/CraftingManager.java new file mode 100644 index 0000000..4e5b4f3 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CraftingManager.java @@ -0,0 +1,311 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import org.bukkit.craftbukkit.event.CraftEventFactory; + +import java.util.*; + +public class CraftingManager { + + private static final CraftingManager a = new CraftingManager(); + public List recipes = Lists.newArrayList(); + // CraftBukkit start + + public org.bukkit.inventory.InventoryView lastCraftView; + // CraftBukkit end + + public CraftingManager() { + (new RecipesTools()).a(this); + (new RecipesWeapons()).a(this); + (new RecipeIngots()).a(this); + (new RecipesFood()).a(this); + (new RecipesCrafting()).a(this); + (new RecipesArmor()).a(this); + (new RecipesDyes()).a(this); + this.recipes.add(new RecipeArmorDye()); + this.recipes.add(new RecipeBookClone()); + this.recipes.add(new RecipeMapClone()); + this.recipes.add(new RecipeMapExtend()); + this.recipes.add(new RecipeFireworks()); + this.recipes.add(new RecipeRepair()); + (new RecipesBanner()).a(this); + this.registerShapedRecipe(new ItemStack(Items.PAPER, 3), "###", '#', Items.REEDS); + this.registerShapelessRecipe(new ItemStack(Items.BOOK, 1), Items.PAPER, Items.PAPER, Items.PAPER, Items.LEATHER); + this.registerShapelessRecipe(new ItemStack(Items.WRITABLE_BOOK, 1), Items.BOOK, new ItemStack(Items.DYE, 1, EnumColor.BLACK.getInvColorIndex()), Items.FEATHER); + this.registerShapedRecipe(new ItemStack(Blocks.FENCE, 3), "W#W", "W#W", '#', Items.STICK, 'W', new ItemStack(Blocks.PLANKS, 1, BlockWood.EnumLogVariant.OAK.a())); + this.registerShapedRecipe(new ItemStack(Blocks.BIRCH_FENCE, 3), "W#W", "W#W", '#', Items.STICK, 'W', new ItemStack(Blocks.PLANKS, 1, BlockWood.EnumLogVariant.BIRCH.a())); + this.registerShapedRecipe(new ItemStack(Blocks.SPRUCE_FENCE, 3), "W#W", "W#W", '#', Items.STICK, 'W', new ItemStack(Blocks.PLANKS, 1, BlockWood.EnumLogVariant.SPRUCE.a())); + this.registerShapedRecipe(new ItemStack(Blocks.JUNGLE_FENCE, 3), "W#W", "W#W", '#', Items.STICK, 'W', new ItemStack(Blocks.PLANKS, 1, BlockWood.EnumLogVariant.JUNGLE.a())); + this.registerShapedRecipe(new ItemStack(Blocks.ACACIA_FENCE, 3), "W#W", "W#W", '#', Items.STICK, 'W', new ItemStack(Blocks.PLANKS, 1, 4 + BlockWood.EnumLogVariant.ACACIA.a() - 4)); + this.registerShapedRecipe(new ItemStack(Blocks.DARK_OAK_FENCE, 3), "W#W", "W#W", '#', Items.STICK, 'W', new ItemStack(Blocks.PLANKS, 1, 4 + BlockWood.EnumLogVariant.DARK_OAK.a() - 4)); + this.registerShapedRecipe(new ItemStack(Blocks.COBBLESTONE_WALL, 6, BlockCobbleWall.EnumCobbleVariant.NORMAL.a()), "###", "###", '#', Blocks.COBBLESTONE); + this.registerShapedRecipe(new ItemStack(Blocks.COBBLESTONE_WALL, 6, BlockCobbleWall.EnumCobbleVariant.MOSSY.a()), "###", "###", '#', Blocks.MOSSY_COBBLESTONE); + this.registerShapedRecipe(new ItemStack(Blocks.NETHER_BRICK_FENCE, 6), "###", "###", '#', Blocks.NETHER_BRICK); + this.registerShapedRecipe(new ItemStack(Blocks.FENCE_GATE, 1), "#W#", "#W#", '#', Items.STICK, 'W', new ItemStack(Blocks.PLANKS, 1, BlockWood.EnumLogVariant.OAK.a())); + this.registerShapedRecipe(new ItemStack(Blocks.BIRCH_FENCE_GATE, 1), "#W#", "#W#", '#', Items.STICK, 'W', new ItemStack(Blocks.PLANKS, 1, BlockWood.EnumLogVariant.BIRCH.a())); + this.registerShapedRecipe(new ItemStack(Blocks.SPRUCE_FENCE_GATE, 1), "#W#", "#W#", '#', Items.STICK, 'W', new ItemStack(Blocks.PLANKS, 1, BlockWood.EnumLogVariant.SPRUCE.a())); + this.registerShapedRecipe(new ItemStack(Blocks.JUNGLE_FENCE_GATE, 1), "#W#", "#W#", '#', Items.STICK, 'W', new ItemStack(Blocks.PLANKS, 1, BlockWood.EnumLogVariant.JUNGLE.a())); + this.registerShapedRecipe(new ItemStack(Blocks.ACACIA_FENCE_GATE, 1), "#W#", "#W#", '#', Items.STICK, 'W', new ItemStack(Blocks.PLANKS, 1, 4 + BlockWood.EnumLogVariant.ACACIA.a() - 4)); + this.registerShapedRecipe(new ItemStack(Blocks.DARK_OAK_FENCE_GATE, 1), "#W#", "#W#", '#', Items.STICK, 'W', new ItemStack(Blocks.PLANKS, 1, 4 + BlockWood.EnumLogVariant.DARK_OAK.a() - 4)); + this.registerShapedRecipe(new ItemStack(Blocks.JUKEBOX, 1), "###", "#X#", "###", '#', Blocks.PLANKS, 'X', Items.DIAMOND); + this.registerShapedRecipe(new ItemStack(Items.LEAD, 2), "~~ ", "~O ", " ~", '~', Items.STRING, 'O', Items.SLIME); + this.registerShapedRecipe(new ItemStack(Blocks.NOTEBLOCK, 1), "###", "#X#", "###", '#', Blocks.PLANKS, 'X', Items.REDSTONE); + this.registerShapedRecipe(new ItemStack(Blocks.BOOKSHELF, 1), "###", "XXX", "###", '#', Blocks.PLANKS, 'X', Items.BOOK); + this.registerShapedRecipe(new ItemStack(Blocks.SNOW, 1), "##", "##", '#', Items.SNOWBALL); + this.registerShapedRecipe(new ItemStack(Blocks.SNOW_LAYER, 6), "###", '#', Blocks.SNOW); + this.registerShapedRecipe(new ItemStack(Blocks.CLAY, 1), "##", "##", '#', Items.CLAY_BALL); + this.registerShapedRecipe(new ItemStack(Blocks.BRICK_BLOCK, 1), "##", "##", '#', Items.BRICK); + this.registerShapedRecipe(new ItemStack(Blocks.GLOWSTONE, 1), "##", "##", '#', Items.GLOWSTONE_DUST); + this.registerShapedRecipe(new ItemStack(Blocks.QUARTZ_BLOCK, 1), "##", "##", '#', Items.QUARTZ); + this.registerShapedRecipe(new ItemStack(Blocks.WOOL, 1), "##", "##", '#', Items.STRING); + this.registerShapedRecipe(new ItemStack(Blocks.TNT, 1), "X#X", "#X#", "X#X", 'X', Items.GUNPOWDER, '#', Blocks.SAND); + this.registerShapedRecipe(new ItemStack(Blocks.STONE_SLAB, 6, BlockDoubleStepAbstract.EnumStoneSlabVariant.COBBLESTONE.a()), "###", '#', Blocks.COBBLESTONE); + this.registerShapedRecipe(new ItemStack(Blocks.STONE_SLAB, 6, BlockDoubleStepAbstract.EnumStoneSlabVariant.STONE.a()), "###", '#', new ItemStack(Blocks.STONE, BlockStone.EnumStoneVariant.STONE.a())); + this.registerShapedRecipe(new ItemStack(Blocks.STONE_SLAB, 6, BlockDoubleStepAbstract.EnumStoneSlabVariant.SAND.a()), "###", '#', Blocks.SANDSTONE); + this.registerShapedRecipe(new ItemStack(Blocks.STONE_SLAB, 6, BlockDoubleStepAbstract.EnumStoneSlabVariant.BRICK.a()), "###", '#', Blocks.BRICK_BLOCK); + this.registerShapedRecipe(new ItemStack(Blocks.STONE_SLAB, 6, BlockDoubleStepAbstract.EnumStoneSlabVariant.SMOOTHBRICK.a()), "###", '#', Blocks.STONEBRICK); + this.registerShapedRecipe(new ItemStack(Blocks.STONE_SLAB, 6, BlockDoubleStepAbstract.EnumStoneSlabVariant.NETHERBRICK.a()), "###", '#', Blocks.NETHER_BRICK); + this.registerShapedRecipe(new ItemStack(Blocks.STONE_SLAB, 6, BlockDoubleStepAbstract.EnumStoneSlabVariant.QUARTZ.a()), "###", '#', Blocks.QUARTZ_BLOCK); + this.registerShapedRecipe(new ItemStack(Blocks.STONE_SLAB2, 6, BlockDoubleStoneStepAbstract.EnumStoneSlab2Variant.RED_SANDSTONE.a()), "###", '#', Blocks.RED_SANDSTONE); + this.registerShapedRecipe(new ItemStack(Blocks.WOODEN_SLAB, 6, 0), "###", '#', new ItemStack(Blocks.PLANKS, 1, BlockWood.EnumLogVariant.OAK.a())); + this.registerShapedRecipe(new ItemStack(Blocks.WOODEN_SLAB, 6, BlockWood.EnumLogVariant.BIRCH.a()), "###", '#', new ItemStack(Blocks.PLANKS, 1, BlockWood.EnumLogVariant.BIRCH.a())); + this.registerShapedRecipe(new ItemStack(Blocks.WOODEN_SLAB, 6, BlockWood.EnumLogVariant.SPRUCE.a()), "###", '#', new ItemStack(Blocks.PLANKS, 1, BlockWood.EnumLogVariant.SPRUCE.a())); + this.registerShapedRecipe(new ItemStack(Blocks.WOODEN_SLAB, 6, BlockWood.EnumLogVariant.JUNGLE.a()), "###", '#', new ItemStack(Blocks.PLANKS, 1, BlockWood.EnumLogVariant.JUNGLE.a())); + this.registerShapedRecipe(new ItemStack(Blocks.WOODEN_SLAB, 6, 4 + BlockWood.EnumLogVariant.ACACIA.a() - 4), "###", '#', new ItemStack(Blocks.PLANKS, 1, 4 + BlockWood.EnumLogVariant.ACACIA.a() - 4)); + this.registerShapedRecipe(new ItemStack(Blocks.WOODEN_SLAB, 6, 4 + BlockWood.EnumLogVariant.DARK_OAK.a() - 4), "###", '#', new ItemStack(Blocks.PLANKS, 1, 4 + BlockWood.EnumLogVariant.DARK_OAK.a() - 4)); + this.registerShapedRecipe(new ItemStack(Blocks.LADDER, 3), "# #", "###", "# #", '#', Items.STICK); + this.registerShapedRecipe(new ItemStack(Items.WOODEN_DOOR, 3), "##", "##", "##", '#', new ItemStack(Blocks.PLANKS, 1, BlockWood.EnumLogVariant.OAK.a())); + this.registerShapedRecipe(new ItemStack(Items.SPRUCE_DOOR, 3), "##", "##", "##", '#', new ItemStack(Blocks.PLANKS, 1, BlockWood.EnumLogVariant.SPRUCE.a())); + this.registerShapedRecipe(new ItemStack(Items.BIRCH_DOOR, 3), "##", "##", "##", '#', new ItemStack(Blocks.PLANKS, 1, BlockWood.EnumLogVariant.BIRCH.a())); + this.registerShapedRecipe(new ItemStack(Items.JUNGLE_DOOR, 3), "##", "##", "##", '#', new ItemStack(Blocks.PLANKS, 1, BlockWood.EnumLogVariant.JUNGLE.a())); + this.registerShapedRecipe(new ItemStack(Items.ACACIA_DOOR, 3), "##", "##", "##", '#', new ItemStack(Blocks.PLANKS, 1, BlockWood.EnumLogVariant.ACACIA.a())); + this.registerShapedRecipe(new ItemStack(Items.DARK_OAK_DOOR, 3), "##", "##", "##", '#', new ItemStack(Blocks.PLANKS, 1, BlockWood.EnumLogVariant.DARK_OAK.a())); + this.registerShapedRecipe(new ItemStack(Blocks.TRAPDOOR, 2), "###", "###", '#', Blocks.PLANKS); + this.registerShapedRecipe(new ItemStack(Items.IRON_DOOR, 3), "##", "##", "##", '#', Items.IRON_INGOT); + this.registerShapedRecipe(new ItemStack(Blocks.IRON_TRAPDOOR, 1), "##", "##", '#', Items.IRON_INGOT); + this.registerShapedRecipe(new ItemStack(Items.SIGN, 3), "###", "###", " X ", '#', Blocks.PLANKS, 'X', Items.STICK); + this.registerShapedRecipe(new ItemStack(Items.CAKE, 1), "AAA", "BEB", "CCC", 'A', Items.MILK_BUCKET, 'B', Items.SUGAR, 'C', Items.WHEAT, 'E', Items.EGG); + this.registerShapedRecipe(new ItemStack(Items.SUGAR, 1), "#", '#', Items.REEDS); + this.registerShapedRecipe(new ItemStack(Blocks.PLANKS, 4, BlockWood.EnumLogVariant.OAK.a()), "#", '#', new ItemStack(Blocks.LOG, 1, BlockWood.EnumLogVariant.OAK.a())); + this.registerShapedRecipe(new ItemStack(Blocks.PLANKS, 4, BlockWood.EnumLogVariant.SPRUCE.a()), "#", '#', new ItemStack(Blocks.LOG, 1, BlockWood.EnumLogVariant.SPRUCE.a())); + this.registerShapedRecipe(new ItemStack(Blocks.PLANKS, 4, BlockWood.EnumLogVariant.BIRCH.a()), "#", '#', new ItemStack(Blocks.LOG, 1, BlockWood.EnumLogVariant.BIRCH.a())); + this.registerShapedRecipe(new ItemStack(Blocks.PLANKS, 4, BlockWood.EnumLogVariant.JUNGLE.a()), "#", '#', new ItemStack(Blocks.LOG, 1, BlockWood.EnumLogVariant.JUNGLE.a())); + this.registerShapedRecipe(new ItemStack(Blocks.PLANKS, 4, 4 + BlockWood.EnumLogVariant.ACACIA.a() - 4), "#", '#', new ItemStack(Blocks.LOG2, 1, BlockWood.EnumLogVariant.ACACIA.a() - 4)); + this.registerShapedRecipe(new ItemStack(Blocks.PLANKS, 4, 4 + BlockWood.EnumLogVariant.DARK_OAK.a() - 4), "#", '#', new ItemStack(Blocks.LOG2, 1, BlockWood.EnumLogVariant.DARK_OAK.a() - 4)); + this.registerShapedRecipe(new ItemStack(Items.STICK, 4), "#", "#", '#', Blocks.PLANKS); + this.registerShapedRecipe(new ItemStack(Blocks.TORCH, 4), "X", "#", 'X', Items.COAL, '#', Items.STICK); + this.registerShapedRecipe(new ItemStack(Blocks.TORCH, 4), "X", "#", 'X', new ItemStack(Items.COAL, 1, 1), '#', Items.STICK); + this.registerShapedRecipe(new ItemStack(Items.BOWL, 4), "# #", " # ", '#', Blocks.PLANKS); + this.registerShapedRecipe(new ItemStack(Items.GLASS_BOTTLE, 3), "# #", " # ", '#', Blocks.GLASS); + this.registerShapedRecipe(new ItemStack(Blocks.RAIL, 16), "X X", "X#X", "X X", 'X', Items.IRON_INGOT, '#', Items.STICK); + this.registerShapedRecipe(new ItemStack(Blocks.GOLDEN_RAIL, 6), "X X", "X#X", "XRX", 'X', Items.GOLD_INGOT, 'R', Items.REDSTONE, '#', Items.STICK); + this.registerShapedRecipe(new ItemStack(Blocks.ACTIVATOR_RAIL, 6), "XSX", "X#X", "XSX", 'X', Items.IRON_INGOT, '#', Blocks.REDSTONE_TORCH, 'S', Items.STICK); + this.registerShapedRecipe(new ItemStack(Blocks.DETECTOR_RAIL, 6), "X X", "X#X", "XRX", 'X', Items.IRON_INGOT, 'R', Items.REDSTONE, '#', Blocks.STONE_PRESSURE_PLATE); + this.registerShapedRecipe(new ItemStack(Items.MINECART, 1), "# #", "###", '#', Items.IRON_INGOT); + this.registerShapedRecipe(new ItemStack(Items.CAULDRON, 1), "# #", "# #", "###", '#', Items.IRON_INGOT); + this.registerShapedRecipe(new ItemStack(Items.BREWING_STAND, 1), " B ", "###", '#', Blocks.COBBLESTONE, 'B', Items.BLAZE_ROD); + this.registerShapedRecipe(new ItemStack(Blocks.LIT_PUMPKIN, 1), "A", "B", 'A', Blocks.PUMPKIN, 'B', Blocks.TORCH); + this.registerShapedRecipe(new ItemStack(Items.CHEST_MINECART, 1), "A", "B", 'A', Blocks.CHEST, 'B', Items.MINECART); + this.registerShapedRecipe(new ItemStack(Items.FURNACE_MINECART, 1), "A", "B", 'A', Blocks.FURNACE, 'B', Items.MINECART); + this.registerShapedRecipe(new ItemStack(Items.TNT_MINECART, 1), "A", "B", 'A', Blocks.TNT, 'B', Items.MINECART); + this.registerShapedRecipe(new ItemStack(Items.HOPPER_MINECART, 1), "A", "B", 'A', Blocks.HOPPER, 'B', Items.MINECART); + this.registerShapedRecipe(new ItemStack(Items.BOAT, 1), "# #", "###", '#', Blocks.PLANKS); + this.registerShapedRecipe(new ItemStack(Items.BUCKET, 1), "# #", " # ", '#', Items.IRON_INGOT); + this.registerShapedRecipe(new ItemStack(Items.FLOWER_POT, 1), "# #", " # ", '#', Items.BRICK); + this.registerShapelessRecipe(new ItemStack(Items.FLINT_AND_STEEL, 1), new ItemStack(Items.IRON_INGOT, 1), new ItemStack(Items.FLINT, 1)); + this.registerShapedRecipe(new ItemStack(Items.BREAD, 1), "###", '#', Items.WHEAT); + this.registerShapedRecipe(new ItemStack(Blocks.OAK_STAIRS, 4), "# ", "## ", "###", '#', new ItemStack(Blocks.PLANKS, 1, BlockWood.EnumLogVariant.OAK.a())); + this.registerShapedRecipe(new ItemStack(Blocks.BIRCH_STAIRS, 4), "# ", "## ", "###", '#', new ItemStack(Blocks.PLANKS, 1, BlockWood.EnumLogVariant.BIRCH.a())); + this.registerShapedRecipe(new ItemStack(Blocks.SPRUCE_STAIRS, 4), "# ", "## ", "###", '#', new ItemStack(Blocks.PLANKS, 1, BlockWood.EnumLogVariant.SPRUCE.a())); + this.registerShapedRecipe(new ItemStack(Blocks.JUNGLE_STAIRS, 4), "# ", "## ", "###", '#', new ItemStack(Blocks.PLANKS, 1, BlockWood.EnumLogVariant.JUNGLE.a())); + this.registerShapedRecipe(new ItemStack(Blocks.ACACIA_STAIRS, 4), "# ", "## ", "###", '#', new ItemStack(Blocks.PLANKS, 1, 4 + BlockWood.EnumLogVariant.ACACIA.a() - 4)); + this.registerShapedRecipe(new ItemStack(Blocks.DARK_OAK_STAIRS, 4), "# ", "## ", "###", '#', new ItemStack(Blocks.PLANKS, 1, 4 + BlockWood.EnumLogVariant.DARK_OAK.a() - 4)); + this.registerShapedRecipe(new ItemStack(Items.FISHING_ROD, 1), " #", " #X", "# X", '#', Items.STICK, 'X', Items.STRING); + this.registerShapedRecipe(new ItemStack(Items.CARROT_ON_A_STICK, 1), "# ", " X", '#', Items.FISHING_ROD, 'X', Items.CARROT); + this.registerShapedRecipe(new ItemStack(Blocks.STONE_STAIRS, 4), "# ", "## ", "###", '#', Blocks.COBBLESTONE); + this.registerShapedRecipe(new ItemStack(Blocks.BRICK_STAIRS, 4), "# ", "## ", "###", '#', Blocks.BRICK_BLOCK); + this.registerShapedRecipe(new ItemStack(Blocks.STONE_BRICK_STAIRS, 4), "# ", "## ", "###", '#', Blocks.STONEBRICK); + this.registerShapedRecipe(new ItemStack(Blocks.NETHER_BRICK_STAIRS, 4), "# ", "## ", "###", '#', Blocks.NETHER_BRICK); + this.registerShapedRecipe(new ItemStack(Blocks.SANDSTONE_STAIRS, 4), "# ", "## ", "###", '#', Blocks.SANDSTONE); + this.registerShapedRecipe(new ItemStack(Blocks.RED_SANDSTONE_STAIRS, 4), "# ", "## ", "###", '#', Blocks.RED_SANDSTONE); + this.registerShapedRecipe(new ItemStack(Blocks.QUARTZ_STAIRS, 4), "# ", "## ", "###", '#', Blocks.QUARTZ_BLOCK); + this.registerShapedRecipe(new ItemStack(Items.PAINTING, 1), "###", "#X#", "###", '#', Items.STICK, 'X', Blocks.WOOL); + this.registerShapedRecipe(new ItemStack(Items.ITEM_FRAME, 1), "###", "#X#", "###", '#', Items.STICK, 'X', Items.LEATHER); + this.registerShapedRecipe(new ItemStack(Items.GOLDEN_APPLE, 1, 0), "###", "#X#", "###", '#', Items.GOLD_INGOT, 'X', Items.APPLE); + this.registerShapedRecipe(new ItemStack(Items.GOLDEN_APPLE, 1, 1), "###", "#X#", "###", '#', Blocks.GOLD_BLOCK, 'X', Items.APPLE); + this.registerShapedRecipe(new ItemStack(Items.GOLDEN_CARROT, 1, 0), "###", "#X#", "###", '#', Items.GOLD_NUGGET, 'X', Items.CARROT); + this.registerShapedRecipe(new ItemStack(Items.SPECKLED_MELON, 1), "###", "#X#", "###", '#', Items.GOLD_NUGGET, 'X', Items.MELON); + this.registerShapedRecipe(new ItemStack(Blocks.LEVER, 1), "X", "#", '#', Blocks.COBBLESTONE, 'X', Items.STICK); + this.registerShapedRecipe(new ItemStack(Blocks.TRIPWIRE_HOOK, 2), "I", "S", "#", '#', Blocks.PLANKS, 'S', Items.STICK, 'I', Items.IRON_INGOT); + this.registerShapedRecipe(new ItemStack(Blocks.REDSTONE_TORCH, 1), "X", "#", '#', Items.STICK, 'X', Items.REDSTONE); + this.registerShapedRecipe(new ItemStack(Items.REPEATER, 1), "#X#", "III", '#', Blocks.REDSTONE_TORCH, 'X', Items.REDSTONE, 'I', new ItemStack(Blocks.STONE, 1, BlockStone.EnumStoneVariant.STONE.a())); + this.registerShapedRecipe(new ItemStack(Items.COMPARATOR, 1), " # ", "#X#", "III", '#', Blocks.REDSTONE_TORCH, 'X', Items.QUARTZ, 'I', new ItemStack(Blocks.STONE, 1, BlockStone.EnumStoneVariant.STONE.a())); + this.registerShapedRecipe(new ItemStack(Items.CLOCK, 1), " # ", "#X#", " # ", '#', Items.GOLD_INGOT, 'X', Items.REDSTONE); + this.registerShapedRecipe(new ItemStack(Items.COMPASS, 1), " # ", "#X#", " # ", '#', Items.IRON_INGOT, 'X', Items.REDSTONE); + this.registerShapedRecipe(new ItemStack(Items.MAP, 1), "###", "#X#", "###", '#', Items.PAPER, 'X', Items.COMPASS); + this.registerShapedRecipe(new ItemStack(Blocks.STONE_BUTTON, 1), "#", '#', new ItemStack(Blocks.STONE, 1, BlockStone.EnumStoneVariant.STONE.a())); + this.registerShapedRecipe(new ItemStack(Blocks.WOODEN_BUTTON, 1), "#", '#', Blocks.PLANKS); + this.registerShapedRecipe(new ItemStack(Blocks.STONE_PRESSURE_PLATE, 1), "##", '#', new ItemStack(Blocks.STONE, 1, BlockStone.EnumStoneVariant.STONE.a())); + this.registerShapedRecipe(new ItemStack(Blocks.WOODEN_PRESSURE_PLATE, 1), "##", '#', Blocks.PLANKS); + this.registerShapedRecipe(new ItemStack(Blocks.HEAVY_WEIGHTED_PRESSURE_PLATE, 1), "##", '#', Items.IRON_INGOT); + this.registerShapedRecipe(new ItemStack(Blocks.LIGHT_WEIGHTED_PRESSURE_PLATE, 1), "##", '#', Items.GOLD_INGOT); + this.registerShapedRecipe(new ItemStack(Blocks.DISPENSER, 1), "###", "#X#", "#R#", '#', Blocks.COBBLESTONE, 'X', Items.BOW, 'R', Items.REDSTONE); + this.registerShapedRecipe(new ItemStack(Blocks.DROPPER, 1), "###", "# #", "#R#", '#', Blocks.COBBLESTONE, 'R', Items.REDSTONE); + this.registerShapedRecipe(new ItemStack(Blocks.PISTON, 1), "TTT", "#X#", "#R#", '#', Blocks.COBBLESTONE, 'X', Items.IRON_INGOT, 'R', Items.REDSTONE, 'T', Blocks.PLANKS); + this.registerShapedRecipe(new ItemStack(Blocks.STICKY_PISTON, 1), "S", "P", 'S', Items.SLIME, 'P', Blocks.PISTON); + this.registerShapedRecipe(new ItemStack(Items.BED, 1), "###", "XXX", '#', Blocks.WOOL, 'X', Blocks.PLANKS); + this.registerShapedRecipe(new ItemStack(Blocks.ENCHANTING_TABLE, 1), " B ", "D#D", "###", '#', Blocks.OBSIDIAN, 'B', Items.BOOK, 'D', Items.DIAMOND); + this.registerShapedRecipe(new ItemStack(Blocks.ANVIL, 1), "III", " i ", "iii", 'I', Blocks.IRON_BLOCK, 'i', Items.IRON_INGOT); + this.registerShapedRecipe(new ItemStack(Items.LEATHER), "##", "##", '#', Items.RABBIT_HIDE); + this.registerShapelessRecipe(new ItemStack(Items.ENDER_EYE, 1), Items.ENDER_PEARL, Items.BLAZE_POWDER); + this.registerShapelessRecipe(new ItemStack(Items.FIRE_CHARGE, 3), Items.GUNPOWDER, Items.BLAZE_POWDER, Items.COAL); + this.registerShapelessRecipe(new ItemStack(Items.FIRE_CHARGE, 3), Items.GUNPOWDER, Items.BLAZE_POWDER, new ItemStack(Items.COAL, 1, 1)); + this.registerShapedRecipe(new ItemStack(Blocks.DAYLIGHT_DETECTOR), "GGG", "QQQ", "WWW", 'G', Blocks.GLASS, 'Q', Items.QUARTZ, 'W', Blocks.WOODEN_SLAB); + this.registerShapedRecipe(new ItemStack(Blocks.HOPPER), "I I", "ICI", " I ", 'I', Items.IRON_INGOT, 'C', Blocks.CHEST); + this.registerShapedRecipe(new ItemStack(Items.ARMOR_STAND, 1), "///", " / ", "/_/", '/', Items.STICK, '_', new ItemStack(Blocks.STONE_SLAB, 1, BlockDoubleStepAbstract.EnumStoneSlabVariant.STONE.a())); + sort(); + } + + public static CraftingManager getInstance() { + return CraftingManager.a; + } + + // CraftBukkit start + public void sort() { + Collections.sort(this.recipes, new Comparator() { + public int a(IRecipe irecipe, IRecipe irecipe1) { + return irecipe instanceof ShapelessRecipes && irecipe1 instanceof ShapedRecipes ? 1 : (irecipe1 instanceof ShapelessRecipes && irecipe instanceof ShapedRecipes ? -1 : (irecipe1.a() < irecipe.a() ? -1 : (irecipe1.a() > irecipe.a() ? 1 : 0))); + } + + public int compare(Object object, Object object1) { + return this.a((IRecipe) object, (IRecipe) object1); + } + }); + } + + public ShapedRecipes registerShapedRecipe(ItemStack itemstack, Object... aobject) { + String s = ""; + int i = 0; + int j = 0; + int k = 0; + + if (aobject[i] instanceof String[]) { + String[] astring = (String[]) aobject[i++]; + + for (String s1 : astring) { + ++k; + j = s1.length(); + s = s + s1; + } + } else { + while (aobject[i] instanceof String) { + String s2 = (String) aobject[i++]; + + ++k; + j = s2.length(); + s = s + s2; + } + } + + HashMap hashmap; + + for (hashmap = Maps.newHashMap(); i < aobject.length; i += 2) { + Character character = (Character) aobject[i]; + ItemStack itemstack1 = null; + + if (aobject[i + 1] instanceof Item) { + itemstack1 = new ItemStack((Item) aobject[i + 1]); + } else if (aobject[i + 1] instanceof Block) { + itemstack1 = new ItemStack((Block) aobject[i + 1], 1, 32767); + } else if (aobject[i + 1] instanceof ItemStack) { + itemstack1 = (ItemStack) aobject[i + 1]; + } + + hashmap.put(character, itemstack1); + } + + ItemStack[] aitemstack = new ItemStack[j * k]; + + for (int i1 = 0; i1 < j * k; ++i1) { + char c0 = s.charAt(i1); + + if (hashmap.containsKey(c0)) { + aitemstack[i1] = hashmap.get(c0).cloneItemStack(); + } else { + aitemstack[i1] = null; + } + } + + ShapedRecipes shapedrecipes = new ShapedRecipes(j, k, aitemstack, itemstack); + + this.recipes.add(shapedrecipes); + return shapedrecipes; + } + + public void registerShapelessRecipe(ItemStack itemstack, Object... aobject) { + ArrayList arraylist = Lists.newArrayList(); + + for (Object object : aobject) { + if (object instanceof ItemStack) { + arraylist.add(((ItemStack) object).cloneItemStack()); + } else if (object instanceof Item) { + arraylist.add(new ItemStack((Item) object)); + } else { + if (!(object instanceof Block)) { + throw new IllegalArgumentException("Invalid shapeless recipe: unknown type " + object.getClass().getName() + "!"); + } + + arraylist.add(new ItemStack((Block) object)); + } + } + + this.recipes.add(new ShapelessRecipes(itemstack, arraylist)); + } + + public void a(IRecipe irecipe) { + this.recipes.add(irecipe); + } + + public ItemStack craft(InventoryCrafting inventorycrafting, World world) { + Iterator iterator = this.recipes.iterator(); + + IRecipe irecipe; + + do { + if (!iterator.hasNext()) { + inventorycrafting.currentRecipe = null; // CraftBukkit - Clear recipe when no recipe is found + return null; + } + + irecipe = iterator.next(); + } while (!irecipe.a(inventorycrafting, world)); + + // CraftBukkit start - INVENTORY_PRE_CRAFT event + inventorycrafting.currentRecipe = irecipe; + ItemStack result = irecipe.craftItem(inventorycrafting); + return CraftEventFactory.callPreCraftEvent(inventorycrafting, result, lastCraftView, false); + // CraftBukkit end + } + + public ItemStack[] b(InventoryCrafting inventorycrafting, World world) { + + for (IRecipe irecipe : this.recipes) { + if (irecipe.a(inventorycrafting, world)) { + return irecipe.b(inventorycrafting); + } + } + + ItemStack[] aitemstack = new ItemStack[inventorycrafting.getSize()]; + + for (int i = 0; i < aitemstack.length; ++i) { + aitemstack[i] = inventorycrafting.getItem(i); + } + + return aitemstack; + } + + public List getRecipes() { + return this.recipes; + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/net/minecraft/server/CraftingStatistic.java b/azurite-server/src/main/java/net/minecraft/server/CraftingStatistic.java new file mode 100644 index 0000000..9f11859 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CraftingStatistic.java @@ -0,0 +1,17 @@ +package net.minecraft.server; + +public class CraftingStatistic extends Statistic { + + private final Item a; + + public CraftingStatistic(String s, String s1, IChatBaseComponent ichatbasecomponent, Item item) { + super(s + s1, ichatbasecomponent); + this.a = item; + int i = Item.getId(item); + + if (i != 0) { + IScoreboardCriteria.criteria.put(s + i, this.k()); + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CrashReport.java b/azurite-server/src/main/java/net/minecraft/server/CrashReport.java new file mode 100644 index 0000000..127fa8c --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CrashReport.java @@ -0,0 +1,313 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang3.ArrayUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.jetbrains.annotations.NotNull; + +import java.io.File; +import java.io.FileWriter; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.lang.management.ManagementFactory; +import java.lang.management.RuntimeMXBean; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; +import java.util.concurrent.Callable; + +public class CrashReport { + + private static final Logger a = LogManager.getLogger(); + private final String b; + private final Throwable c; + private final CrashReportSystemDetails d = new CrashReportSystemDetails(this, "System Details"); + private final List e = Lists.newArrayList(); + private File f; + private boolean g = true; + private StackTraceElement[] h = new StackTraceElement[0]; + + public CrashReport(String s, Throwable throwable) { + this.b = s; + this.c = throwable; + this.h(); + } + + private void h() { + this.d.a("Minecraft Version", new Callable() { + public String a() { + return "1.8.8"; + } + + public String call() { + return this.a(); + } + }); + this.d.a("Operating System", new Callable() { + public String a() { + return System.getProperty("os.name") + " (" + System.getProperty("os.arch") + ") version " + System.getProperty("os.version"); + } + + public String call() { + return this.a(); + } + }); + this.d.a("Java Version", new Callable() { + public String a() { + return System.getProperty("java.version") + ", " + System.getProperty("java.vendor"); + } + + public String call() { + return this.a(); + } + }); + this.d.a("Java VM Version", new Callable() { + public String a() { + return System.getProperty("java.vm.name") + " (" + System.getProperty("java.vm.info") + "), " + System.getProperty("java.vm.vendor"); + } + + public String call() { + return this.a(); + } + }); + this.d.a("Memory", new Callable() { + public String a() { + Runtime runtime = Runtime.getRuntime(); + long i = runtime.maxMemory(); + long j = runtime.totalMemory(); + long k = runtime.freeMemory(); + long l = i / 1024L / 1024L; + long i1 = j / 1024L / 1024L; + long j1 = k / 1024L / 1024L; + + return k + " bytes (" + j1 + " MB) / " + j + " bytes (" + i1 + " MB) up to " + i + " bytes (" + l + " MB)"; + } + + public String call() { + return this.a(); + } + }); + this.d.a("JVM Flags", new Callable() { + public String a() { + RuntimeMXBean runtimemxbean = ManagementFactory.getRuntimeMXBean(); + List list = runtimemxbean.getInputArguments(); + int i = 0; + StringBuilder stringbuilder = new StringBuilder(); + + for (String s : list) { + if (s.startsWith("-X")) { + if (i++ > 0) { + stringbuilder.append(" "); + } + + stringbuilder.append(s); + } + } + + return String.format("%d total; %s", i, stringbuilder); + } + + public String call() { + return this.a(); + } + }); + this.d.a("IntCache", new Callable() { + public String a() { + return IntCache.b(); + } + + public String call() { + return this.a(); + } + }); + this.d.a("CraftBukkit Information", new org.bukkit.craftbukkit.CraftCrashReport()); // CraftBukkit + } + + public String a() { + return this.b; + } + + public Throwable b() { + return this.c; + } + + public void a(StringBuilder stringbuilder) { + if ((this.h == null || this.h.length == 0) && !this.e.isEmpty()) { + this.h = ArrayUtils.subarray(this.e.get(0).a(), 0, 1); + } + + if (this.h != null && this.h.length > 0) { + stringbuilder.append("-- Head --\n"); + stringbuilder.append("Stacktrace:\n"); + StackTraceElement[] astacktraceelement = this.h; + + for (StackTraceElement stacktraceelement : astacktraceelement) { + stringbuilder.append("\t").append("at ").append(stacktraceelement.toString()); + stringbuilder.append("\n"); + } + + stringbuilder.append("\n"); + } + + for (CrashReportSystemDetails crashreportsystemdetails : this.e) { + crashreportsystemdetails.a(stringbuilder); + stringbuilder.append("\n\n"); + } + + this.d.a(stringbuilder); + } + + public String d() { + StringWriter stringwriter = null; + PrintWriter printwriter = null; + Throwable object = getThrowable(); + + String s; + + try { + stringwriter = new StringWriter(); + printwriter = new PrintWriter(stringwriter); + object.printStackTrace(printwriter); + s = stringwriter.toString(); + } finally { + IOUtils.closeQuietly(stringwriter); + IOUtils.closeQuietly(printwriter); + } + + return s; + } + + private @NotNull Throwable getThrowable() { + Throwable object = this.c; + + if (object.getMessage() == null) { + if (object instanceof NullPointerException) { + object = new NullPointerException(this.b); + } else if (object instanceof StackOverflowError) { + object = new StackOverflowError(this.b); + } else if (object instanceof OutOfMemoryError) { + object = new OutOfMemoryError(this.b); + } + + object.setStackTrace(this.c.getStackTrace()); + } + return object; + } + + public String e() { + StringBuilder stringbuilder = new StringBuilder(); + + stringbuilder.append("---- Minecraft Crash Report ----\n"); + stringbuilder.append("// "); + stringbuilder.append(i()); + stringbuilder.append("\n\n"); + stringbuilder.append("Time: "); + stringbuilder.append((new SimpleDateFormat()).format(new Date())); + stringbuilder.append("\n"); + stringbuilder.append("Description: "); + stringbuilder.append(this.b); + stringbuilder.append("\n\n"); + stringbuilder.append(this.d()); + stringbuilder.append("\n\nA detailed walkthrough of the error, its code path and all known details is as follows:\n"); + + for (int i = 0; i < 87; ++i) { + stringbuilder.append("-"); + } + + stringbuilder.append("\n\n"); + this.a(stringbuilder); + return stringbuilder.toString(); + } + + public boolean a(File file) { + if (this.f != null) { + return false; + } else { + if (file.getParentFile() != null) { + file.getParentFile().mkdirs(); + } + + try { + FileWriter filewriter = new FileWriter(file); + + filewriter.write(this.e()); + filewriter.close(); + this.f = file; + return true; + } catch (Throwable throwable) { + CrashReport.a.error("Could not save crash report to {}", file, throwable); + return false; + } + } + } + + public CrashReportSystemDetails g() { + return this.d; + } + + public CrashReportSystemDetails a(String s) { + return this.a(s, 1); + } + + public CrashReportSystemDetails a(String s, int i) { + CrashReportSystemDetails crashreportsystemdetails = new CrashReportSystemDetails(this, s); + + if (this.g) { + int j = crashreportsystemdetails.a(i); + StackTraceElement[] astacktraceelement = this.c.getStackTrace(); + StackTraceElement stacktraceelement = null; + StackTraceElement stacktraceelement1 = null; + int k = astacktraceelement.length - j; + + if (k < 0) { + System.out.println("Negative index in crash report handler (" + astacktraceelement.length + "/" + j + ")"); + } + + if (0 <= k && k < astacktraceelement.length) { + stacktraceelement = astacktraceelement[k]; + if (astacktraceelement.length + 1 - j < astacktraceelement.length) { + stacktraceelement1 = astacktraceelement[astacktraceelement.length + 1 - j]; + } + } + + this.g = crashreportsystemdetails.a(stacktraceelement, stacktraceelement1); + if (j > 0 && !this.e.isEmpty()) { + CrashReportSystemDetails crashreportsystemdetails1 = this.e.get(this.e.size() - 1); + + crashreportsystemdetails1.b(j); + } else if (astacktraceelement.length >= j && 0 <= k && k < astacktraceelement.length) { + this.h = new StackTraceElement[k]; + System.arraycopy(astacktraceelement, 0, this.h, 0, this.h.length); + } else { + this.g = false; + } + } + + this.e.add(crashreportsystemdetails); + return crashreportsystemdetails; + } + + private static String i() { + String[] astring = new String[] { "Who set us up the TNT?", "Everything's going to plan. No, really, that was supposed to happen.", "Uh... Did I do that?", "Oops.", "Why did you do that?", "I feel sad now :(", "My bad.", "I'm sorry, Dave.", "I let you down. Sorry :(", "On the bright side, I bought you a teddy bear!", "Daisy, daisy...", "Oh - I know what I did wrong!", "Hey, that tickles! Hehehe!", "I blame Dinnerbone.", "You should try our sister game, Minceraft!", "Don't be sad. I'll do better next time, I promise!", "Don't be sad, have a hug! <3", "I just don't know what went wrong :(", "Shall we play a game?", "Quite honestly, I wouldn't worry myself about that.", "I bet Cylons wouldn't have this problem.", "Sorry :(", "Surprise! Haha. Well, this is awkward.", "Would you like a cupcake?", "Hi. I'm Minecraft, and I'm a crashaholic.", "Ooh. Shiny.", "This doesn't make any sense!", "Why is it breaking :(", "Don't do that.", "Ouch. That hurt :(", "You're mean.", "This is a token for 1 free hug. Redeem at your nearest Mojangsta: [~~HUG~~]", "There are four lights!", "But it works on my machine."}; + + try { + return astring[(int) (System.nanoTime() % (long) astring.length)]; + } catch (Throwable throwable) { + return "Witty comment unavailable :("; + } + } + + public static CrashReport a(Throwable throwable, String s) { + CrashReport crashreport; + + if (throwable instanceof ReportedException) { + crashreport = ((ReportedException) throwable).a(); + } else { + crashreport = new CrashReport(s, throwable); + } + + return crashreport; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CrashReportSystemDetails.java b/azurite-server/src/main/java/net/minecraft/server/CrashReportSystemDetails.java new file mode 100644 index 0000000..cd972eb --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CrashReportSystemDetails.java @@ -0,0 +1,265 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; +import java.util.Iterator; +import java.util.List; +import java.util.concurrent.Callable; + +public class CrashReportSystemDetails { + + private final CrashReport a; + private final String b; + private final List c = Lists.newArrayList(); + private StackTraceElement[] d = new StackTraceElement[0]; + + public CrashReportSystemDetails(CrashReport crashreport, String s) { + this.a = crashreport; + this.b = s; + } + + public static String a(double d0, double d1, double d2) { + return String.format("%.2f,%.2f,%.2f - %s", new Object[] { Double.valueOf(d0), Double.valueOf(d1), Double.valueOf(d2), a(new BlockPosition(d0, d1, d2))}); + } + + public static String a(BlockPosition blockposition) { + int i = blockposition.getX(); + int j = blockposition.getY(); + int k = blockposition.getZ(); + StringBuilder stringbuilder = new StringBuilder(); + + try { + stringbuilder.append(String.format("World: (%d,%d,%d)", new Object[] { Integer.valueOf(i), Integer.valueOf(j), Integer.valueOf(k)})); + } catch (Throwable throwable) { + stringbuilder.append("(Error finding world loc)"); + } + + stringbuilder.append(", "); + + int l; + int i1; + int j1; + int k1; + int l1; + int i2; + int j2; + int k2; + int l2; + + try { + l = i >> 4; + i1 = k >> 4; + j1 = i & 15; + k1 = j >> 4; + l1 = k & 15; + i2 = l << 4; + j2 = i1 << 4; + k2 = (l + 1 << 4) - 1; + l2 = (i1 + 1 << 4) - 1; + stringbuilder.append(String.format("Chunk: (at %d,%d,%d in %d,%d; contains blocks %d,0,%d to %d,255,%d)", new Object[] { Integer.valueOf(j1), Integer.valueOf(k1), Integer.valueOf(l1), Integer.valueOf(l), Integer.valueOf(i1), Integer.valueOf(i2), Integer.valueOf(j2), Integer.valueOf(k2), Integer.valueOf(l2)})); + } catch (Throwable throwable1) { + stringbuilder.append("(Error finding chunk loc)"); + } + + stringbuilder.append(", "); + + try { + l = i >> 9; + i1 = k >> 9; + j1 = l << 5; + k1 = i1 << 5; + l1 = (l + 1 << 5) - 1; + i2 = (i1 + 1 << 5) - 1; + j2 = l << 9; + k2 = i1 << 9; + l2 = (l + 1 << 9) - 1; + int i3 = (i1 + 1 << 9) - 1; + + stringbuilder.append(String.format("Region: (%d,%d; contains chunks %d,%d to %d,%d, blocks %d,0,%d to %d,255,%d)", new Object[] { Integer.valueOf(l), Integer.valueOf(i1), Integer.valueOf(j1), Integer.valueOf(k1), Integer.valueOf(l1), Integer.valueOf(i2), Integer.valueOf(j2), Integer.valueOf(k2), Integer.valueOf(l2), Integer.valueOf(i3)})); + } catch (Throwable throwable2) { + stringbuilder.append("(Error finding world loc)"); + } + + return stringbuilder.toString(); + } + + public void a(String s, Callable callable) { + try { + this.a(s, callable.call()); + } catch (Throwable throwable) { + this.a(s, throwable); + } + + } + + public void a(String s, Object object) { + this.c.add(new CrashReportSystemDetails.CrashReportDetail(s, object)); + } + + public void a(String s, Throwable throwable) { + this.a(s, (Object) throwable); + } + + public int a(int i) { + StackTraceElement[] astacktraceelement = Thread.currentThread().getStackTrace(); + + if (astacktraceelement.length <= 0) { + return 0; + } else { + this.d = new StackTraceElement[astacktraceelement.length - 3 - i]; + System.arraycopy(astacktraceelement, 3 + i, this.d, 0, this.d.length); + return this.d.length; + } + } + + public boolean a(StackTraceElement stacktraceelement, StackTraceElement stacktraceelement1) { + if (this.d.length != 0 && stacktraceelement != null) { + StackTraceElement stacktraceelement2 = this.d[0]; + + if (stacktraceelement2.isNativeMethod() == stacktraceelement.isNativeMethod() && stacktraceelement2.getClassName().equals(stacktraceelement.getClassName()) && stacktraceelement2.getFileName().equals(stacktraceelement.getFileName()) && stacktraceelement2.getMethodName().equals(stacktraceelement.getMethodName())) { + if (stacktraceelement1 != null != this.d.length > 1) { + return false; + } else if (stacktraceelement1 != null && !this.d[1].equals(stacktraceelement1)) { + return false; + } else { + this.d[0] = stacktraceelement; + return true; + } + } else { + return false; + } + } else { + return false; + } + } + + public void b(int i) { + StackTraceElement[] astacktraceelement = new StackTraceElement[this.d.length - i]; + + System.arraycopy(this.d, 0, astacktraceelement, 0, astacktraceelement.length); + this.d = astacktraceelement; + } + + public void a(StringBuilder stringbuilder) { + stringbuilder.append("-- ").append(this.b).append(" --\n"); + stringbuilder.append("Details:"); + Iterator iterator = this.c.iterator(); + + while (iterator.hasNext()) { + CrashReportSystemDetails.CrashReportDetail crashreportsystemdetails_crashreportdetail = (CrashReportSystemDetails.CrashReportDetail) iterator.next(); + + stringbuilder.append("\n\t"); + stringbuilder.append(crashreportsystemdetails_crashreportdetail.a()); + stringbuilder.append(": "); + stringbuilder.append(crashreportsystemdetails_crashreportdetail.b()); + } + + if (this.d != null && this.d.length > 0) { + stringbuilder.append("\nStacktrace:"); + StackTraceElement[] astacktraceelement = this.d; + int i = astacktraceelement.length; + + for (int j = 0; j < i; ++j) { + StackTraceElement stacktraceelement = astacktraceelement[j]; + + stringbuilder.append("\n\tat "); + stringbuilder.append(stacktraceelement.toString()); + } + } + + } + + public StackTraceElement[] a() { + return this.d; + } + + public static void a(CrashReportSystemDetails crashreportsystemdetails, final BlockPosition blockposition, final Block block, final int i) { + final int j = Block.getId(block); + + crashreportsystemdetails.a("Block type", new Callable() { + public String a() throws Exception { + try { + return String.format("ID #%d (%s // %s)", new Object[] { Integer.valueOf(i), block.a(), block.getClass().getCanonicalName()}); + } catch (Throwable throwable) { + return "ID #" + i; + } + } + + public Object call() throws Exception { + return this.a(); + } + }); + crashreportsystemdetails.a("Block data value", new Callable() { + public String a() throws Exception { + if (i < 0) { + return "Unknown? (Got " + i + ")"; + } else { + String s = String.format("%4s", new Object[] { Integer.toBinaryString(i)}).replace(" ", "0"); + + return String.format("%1$d / 0x%1$X / 0b%2$s", new Object[] { Integer.valueOf(i), s}); + } + } + + public Object call() throws Exception { + return this.a(); + } + }); + crashreportsystemdetails.a("Block location", new Callable() { + public String a() throws Exception { + return CrashReportSystemDetails.a(blockposition); + } + + public Object call() throws Exception { + return this.a(); + } + }); + } + + public static void a(CrashReportSystemDetails crashreportsystemdetails, final BlockPosition blockposition, final IBlockData iblockdata) { + crashreportsystemdetails.a("Block", new Callable() { + public String a() throws Exception { + return iblockdata.toString(); + } + + public Object call() throws Exception { + return this.a(); + } + }); + crashreportsystemdetails.a("Block location", new Callable() { + public String a() throws Exception { + return CrashReportSystemDetails.a(blockposition); + } + + public Object call() throws Exception { + return this.a(); + } + }); + } + + static class CrashReportDetail { + + private final String a; + private final String b; + + public CrashReportDetail(String s, Object object) { + this.a = s; + if (object == null) { + this.b = "~~NULL~~"; + } else if (object instanceof Throwable) { + Throwable throwable = (Throwable) object; + + this.b = "~~ERROR~~ " + throwable.getClass().getSimpleName() + ": " + throwable.getMessage(); + } else { + this.b = object.toString(); + } + + } + + public String a() { + return this.a; + } + + public String b() { + return this.b; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CreativeModeTab.java b/azurite-server/src/main/java/net/minecraft/server/CreativeModeTab.java new file mode 100644 index 0000000..f726a40 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CreativeModeTab.java @@ -0,0 +1,62 @@ +package net.minecraft.server; + +public abstract class CreativeModeTab { + + public static final CreativeModeTab[] a = new CreativeModeTab[12]; + public static final CreativeModeTab b = new CreativeModeTab(0, "buildingBlocks") { + }; + public static final CreativeModeTab c = new CreativeModeTab(1, "decorations") { + }; + public static final CreativeModeTab d = new CreativeModeTab(2, "redstone") { + }; + public static final CreativeModeTab e = new CreativeModeTab(3, "transportation") { + }; + public static final CreativeModeTab f = (new CreativeModeTab(4, "misc") { + }).a(new EnchantmentSlotType[] { EnchantmentSlotType.ALL}); + public static final CreativeModeTab g = (new CreativeModeTab(5, "search") { + }).a("item_search.png"); + public static final CreativeModeTab h = new CreativeModeTab(6, "food") { + }; + public static final CreativeModeTab i = (new CreativeModeTab(7, "tools") { + }).a(new EnchantmentSlotType[] { EnchantmentSlotType.DIGGER, EnchantmentSlotType.FISHING_ROD, EnchantmentSlotType.BREAKABLE}); + public static final CreativeModeTab j = (new CreativeModeTab(8, "combat") { + }).a(new EnchantmentSlotType[] { EnchantmentSlotType.ARMOR, EnchantmentSlotType.ARMOR_FEET, EnchantmentSlotType.ARMOR_HEAD, EnchantmentSlotType.ARMOR_LEGS, EnchantmentSlotType.ARMOR_TORSO, EnchantmentSlotType.BOW, EnchantmentSlotType.WEAPON}); + public static final CreativeModeTab k = new CreativeModeTab(9, "brewing") { + }; + public static final CreativeModeTab l = new CreativeModeTab(10, "materials") { + }; + public static final CreativeModeTab m = (new CreativeModeTab(11, "inventory") { + }).a("inventory.png").k().i(); + private final int n; + private final String o; + private String p = "items.png"; + private boolean q = true; + private boolean r = true; + private EnchantmentSlotType[] s; + + public CreativeModeTab(int i, String s) { + this.n = i; + this.o = s; + CreativeModeTab.a[i] = this; + } + + public CreativeModeTab a(String s) { + this.p = s; + return this; + } + + public CreativeModeTab i() { + this.r = false; + return this; + } + + public CreativeModeTab k() { + this.q = false; + return this; + } + + public CreativeModeTab a(EnchantmentSlotType... aenchantmentslottype) { + this.s = aenchantmentslottype; + return this; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/CustomWorldSettingsFinal.java b/azurite-server/src/main/java/net/minecraft/server/CustomWorldSettingsFinal.java new file mode 100644 index 0000000..2528260 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/CustomWorldSettingsFinal.java @@ -0,0 +1,659 @@ +package net.minecraft.server; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import java.lang.reflect.Type; + +public class CustomWorldSettingsFinal { + + public final float a; + public final float b; + public final float c; + public final float d; + public final float e; + public final float f; + public final float g; + public final float h; + public final float i; + public final float j; + public final float k; + public final float l; + public final float m; + public final float n; + public final float o; + public final float p; + public final int q; + public final boolean r; + public final boolean s; + public final int t; + public final boolean u; + public final boolean v; + public final boolean w; + public final boolean x; + public final boolean y; + public final boolean z; + public final boolean A; + public final int B; + public final boolean C; + public final int D; + public final boolean E; + public final int F; + public final int G; + public final int H; + public final int I; + public final int J; + public final int K; + public final int L; + public final int M; + public final int N; + public final int O; + public final int P; + public final int Q; + public final int R; + public final int S; + public final int T; + public final int U; + public final int V; + public final int W; + public final int X; + public final int Y; + public final int Z; + public final int aa; + public final int ab; + public final int ac; + public final int ad; + public final int ae; + public final int af; + public final int ag; + public final int ah; + public final int ai; + public final int aj; + public final int ak; + public final int al; + public final int am; + public final int an; + public final int ao; + public final int ap; + public final int aq; + public final int ar; + public final int as; + public final int at; + public final int au; + public final int av; + public final int aw; + public final int ax; + public final int ay; + public final int az; + + private CustomWorldSettingsFinal(CustomWorldSettingsFinal.CustomWorldSettings customworldsettingsfinal_customworldsettings) { + this.a = customworldsettingsfinal_customworldsettings.b; + this.b = customworldsettingsfinal_customworldsettings.c; + this.c = customworldsettingsfinal_customworldsettings.d; + this.d = customworldsettingsfinal_customworldsettings.e; + this.e = customworldsettingsfinal_customworldsettings.f; + this.f = customworldsettingsfinal_customworldsettings.g; + this.g = customworldsettingsfinal_customworldsettings.h; + this.h = customworldsettingsfinal_customworldsettings.i; + this.i = customworldsettingsfinal_customworldsettings.j; + this.j = customworldsettingsfinal_customworldsettings.k; + this.k = customworldsettingsfinal_customworldsettings.l; + this.l = customworldsettingsfinal_customworldsettings.m; + this.m = customworldsettingsfinal_customworldsettings.n; + this.n = customworldsettingsfinal_customworldsettings.o; + this.o = customworldsettingsfinal_customworldsettings.p; + this.p = customworldsettingsfinal_customworldsettings.q; + this.q = customworldsettingsfinal_customworldsettings.r; + this.r = customworldsettingsfinal_customworldsettings.s; + this.s = customworldsettingsfinal_customworldsettings.t; + this.t = customworldsettingsfinal_customworldsettings.u; + this.u = customworldsettingsfinal_customworldsettings.v; + this.v = customworldsettingsfinal_customworldsettings.w; + this.w = customworldsettingsfinal_customworldsettings.x; + this.x = customworldsettingsfinal_customworldsettings.y; + this.y = customworldsettingsfinal_customworldsettings.z; + this.z = customworldsettingsfinal_customworldsettings.A; + this.A = customworldsettingsfinal_customworldsettings.B; + this.B = customworldsettingsfinal_customworldsettings.C; + this.C = customworldsettingsfinal_customworldsettings.D; + this.D = customworldsettingsfinal_customworldsettings.E; + this.E = customworldsettingsfinal_customworldsettings.F; + this.F = customworldsettingsfinal_customworldsettings.G; + this.G = customworldsettingsfinal_customworldsettings.H; + this.H = customworldsettingsfinal_customworldsettings.I; + this.I = customworldsettingsfinal_customworldsettings.J; + this.J = customworldsettingsfinal_customworldsettings.K; + this.K = customworldsettingsfinal_customworldsettings.L; + this.L = customworldsettingsfinal_customworldsettings.M; + this.M = customworldsettingsfinal_customworldsettings.N; + this.N = customworldsettingsfinal_customworldsettings.O; + this.O = customworldsettingsfinal_customworldsettings.P; + this.P = customworldsettingsfinal_customworldsettings.Q; + this.Q = customworldsettingsfinal_customworldsettings.R; + this.R = customworldsettingsfinal_customworldsettings.S; + this.S = customworldsettingsfinal_customworldsettings.T; + this.T = customworldsettingsfinal_customworldsettings.U; + this.U = customworldsettingsfinal_customworldsettings.V; + this.V = customworldsettingsfinal_customworldsettings.W; + this.W = customworldsettingsfinal_customworldsettings.X; + this.X = customworldsettingsfinal_customworldsettings.Y; + this.Y = customworldsettingsfinal_customworldsettings.Z; + this.Z = customworldsettingsfinal_customworldsettings.aa; + this.aa = customworldsettingsfinal_customworldsettings.ab; + this.ab = customworldsettingsfinal_customworldsettings.ac; + this.ac = customworldsettingsfinal_customworldsettings.ad; + this.ad = customworldsettingsfinal_customworldsettings.ae; + this.ae = customworldsettingsfinal_customworldsettings.af; + this.af = customworldsettingsfinal_customworldsettings.ag; + this.ag = customworldsettingsfinal_customworldsettings.ah; + this.ah = customworldsettingsfinal_customworldsettings.ai; + this.ai = customworldsettingsfinal_customworldsettings.aj; + this.aj = customworldsettingsfinal_customworldsettings.ak; + this.ak = customworldsettingsfinal_customworldsettings.al; + this.al = customworldsettingsfinal_customworldsettings.am; + this.am = customworldsettingsfinal_customworldsettings.an; + this.an = customworldsettingsfinal_customworldsettings.ao; + this.ao = customworldsettingsfinal_customworldsettings.ap; + this.ap = customworldsettingsfinal_customworldsettings.aq; + this.aq = customworldsettingsfinal_customworldsettings.ar; + this.ar = customworldsettingsfinal_customworldsettings.as; + this.as = customworldsettingsfinal_customworldsettings.at; + this.at = customworldsettingsfinal_customworldsettings.au; + this.au = customworldsettingsfinal_customworldsettings.av; + this.av = customworldsettingsfinal_customworldsettings.aw; + this.aw = customworldsettingsfinal_customworldsettings.ax; + this.ax = customworldsettingsfinal_customworldsettings.ay; + this.ay = customworldsettingsfinal_customworldsettings.az; + this.az = customworldsettingsfinal_customworldsettings.aA; + } + + CustomWorldSettingsFinal(CustomWorldSettingsFinal.CustomWorldSettings customworldsettingsfinal_customworldsettings, CustomWorldSettingsFinal.SyntheticClass_1 customworldsettingsfinal_syntheticclass_1) { + this(customworldsettingsfinal_customworldsettings); + } + + static class SyntheticClass_1 { } + + public static class CustomWorldSettingsSerializer implements JsonDeserializer, JsonSerializer { + + public CustomWorldSettingsSerializer() {} + + public CustomWorldSettingsFinal.CustomWorldSettings a(JsonElement jsonelement, Type type, JsonDeserializationContext jsondeserializationcontext) throws JsonParseException { + JsonObject jsonobject = jsonelement.getAsJsonObject(); + CustomWorldSettingsFinal.CustomWorldSettings customworldsettingsfinal_customworldsettings = new CustomWorldSettingsFinal.CustomWorldSettings(); + + try { + customworldsettingsfinal_customworldsettings.b = ChatDeserializer.a(jsonobject, "coordinateScale", customworldsettingsfinal_customworldsettings.b); + customworldsettingsfinal_customworldsettings.c = ChatDeserializer.a(jsonobject, "heightScale", customworldsettingsfinal_customworldsettings.c); + customworldsettingsfinal_customworldsettings.e = ChatDeserializer.a(jsonobject, "lowerLimitScale", customworldsettingsfinal_customworldsettings.e); + customworldsettingsfinal_customworldsettings.d = ChatDeserializer.a(jsonobject, "upperLimitScale", customworldsettingsfinal_customworldsettings.d); + customworldsettingsfinal_customworldsettings.f = ChatDeserializer.a(jsonobject, "depthNoiseScaleX", customworldsettingsfinal_customworldsettings.f); + customworldsettingsfinal_customworldsettings.g = ChatDeserializer.a(jsonobject, "depthNoiseScaleZ", customworldsettingsfinal_customworldsettings.g); + customworldsettingsfinal_customworldsettings.h = ChatDeserializer.a(jsonobject, "depthNoiseScaleExponent", customworldsettingsfinal_customworldsettings.h); + customworldsettingsfinal_customworldsettings.i = ChatDeserializer.a(jsonobject, "mainNoiseScaleX", customworldsettingsfinal_customworldsettings.i); + customworldsettingsfinal_customworldsettings.j = ChatDeserializer.a(jsonobject, "mainNoiseScaleY", customworldsettingsfinal_customworldsettings.j); + customworldsettingsfinal_customworldsettings.k = ChatDeserializer.a(jsonobject, "mainNoiseScaleZ", customworldsettingsfinal_customworldsettings.k); + customworldsettingsfinal_customworldsettings.l = ChatDeserializer.a(jsonobject, "baseSize", customworldsettingsfinal_customworldsettings.l); + customworldsettingsfinal_customworldsettings.m = ChatDeserializer.a(jsonobject, "stretchY", customworldsettingsfinal_customworldsettings.m); + customworldsettingsfinal_customworldsettings.n = ChatDeserializer.a(jsonobject, "biomeDepthWeight", customworldsettingsfinal_customworldsettings.n); + customworldsettingsfinal_customworldsettings.o = ChatDeserializer.a(jsonobject, "biomeDepthOffset", customworldsettingsfinal_customworldsettings.o); + customworldsettingsfinal_customworldsettings.p = ChatDeserializer.a(jsonobject, "biomeScaleWeight", customworldsettingsfinal_customworldsettings.p); + customworldsettingsfinal_customworldsettings.q = ChatDeserializer.a(jsonobject, "biomeScaleOffset", customworldsettingsfinal_customworldsettings.q); + customworldsettingsfinal_customworldsettings.r = ChatDeserializer.a(jsonobject, "seaLevel", customworldsettingsfinal_customworldsettings.r); + customworldsettingsfinal_customworldsettings.s = ChatDeserializer.a(jsonobject, "useCaves", customworldsettingsfinal_customworldsettings.s); + customworldsettingsfinal_customworldsettings.t = ChatDeserializer.a(jsonobject, "useDungeons", customworldsettingsfinal_customworldsettings.t); + customworldsettingsfinal_customworldsettings.u = ChatDeserializer.a(jsonobject, "dungeonChance", customworldsettingsfinal_customworldsettings.u); + customworldsettingsfinal_customworldsettings.v = ChatDeserializer.a(jsonobject, "useStrongholds", customworldsettingsfinal_customworldsettings.v); + customworldsettingsfinal_customworldsettings.w = ChatDeserializer.a(jsonobject, "useVillages", customworldsettingsfinal_customworldsettings.w); + customworldsettingsfinal_customworldsettings.x = ChatDeserializer.a(jsonobject, "useMineShafts", customworldsettingsfinal_customworldsettings.x); + customworldsettingsfinal_customworldsettings.y = ChatDeserializer.a(jsonobject, "useTemples", customworldsettingsfinal_customworldsettings.y); + customworldsettingsfinal_customworldsettings.z = ChatDeserializer.a(jsonobject, "useMonuments", customworldsettingsfinal_customworldsettings.z); + customworldsettingsfinal_customworldsettings.A = ChatDeserializer.a(jsonobject, "useRavines", customworldsettingsfinal_customworldsettings.A); + customworldsettingsfinal_customworldsettings.B = ChatDeserializer.a(jsonobject, "useWaterLakes", customworldsettingsfinal_customworldsettings.B); + customworldsettingsfinal_customworldsettings.C = ChatDeserializer.a(jsonobject, "waterLakeChance", customworldsettingsfinal_customworldsettings.C); + customworldsettingsfinal_customworldsettings.D = ChatDeserializer.a(jsonobject, "useLavaLakes", customworldsettingsfinal_customworldsettings.D); + customworldsettingsfinal_customworldsettings.E = ChatDeserializer.a(jsonobject, "lavaLakeChance", customworldsettingsfinal_customworldsettings.E); + customworldsettingsfinal_customworldsettings.F = ChatDeserializer.a(jsonobject, "useLavaOceans", customworldsettingsfinal_customworldsettings.F); + customworldsettingsfinal_customworldsettings.G = ChatDeserializer.a(jsonobject, "fixedBiome", customworldsettingsfinal_customworldsettings.G); + if (customworldsettingsfinal_customworldsettings.G < 38 && customworldsettingsfinal_customworldsettings.G >= -1) { + if (customworldsettingsfinal_customworldsettings.G >= BiomeBase.HELL.id) { + customworldsettingsfinal_customworldsettings.G += 2; + } + } else { + customworldsettingsfinal_customworldsettings.G = -1; + } + + customworldsettingsfinal_customworldsettings.H = ChatDeserializer.a(jsonobject, "biomeSize", customworldsettingsfinal_customworldsettings.H); + customworldsettingsfinal_customworldsettings.I = ChatDeserializer.a(jsonobject, "riverSize", customworldsettingsfinal_customworldsettings.I); + customworldsettingsfinal_customworldsettings.J = ChatDeserializer.a(jsonobject, "dirtSize", customworldsettingsfinal_customworldsettings.J); + customworldsettingsfinal_customworldsettings.K = ChatDeserializer.a(jsonobject, "dirtCount", customworldsettingsfinal_customworldsettings.K); + customworldsettingsfinal_customworldsettings.L = ChatDeserializer.a(jsonobject, "dirtMinHeight", customworldsettingsfinal_customworldsettings.L); + customworldsettingsfinal_customworldsettings.M = ChatDeserializer.a(jsonobject, "dirtMaxHeight", customworldsettingsfinal_customworldsettings.M); + customworldsettingsfinal_customworldsettings.N = ChatDeserializer.a(jsonobject, "gravelSize", customworldsettingsfinal_customworldsettings.N); + customworldsettingsfinal_customworldsettings.O = ChatDeserializer.a(jsonobject, "gravelCount", customworldsettingsfinal_customworldsettings.O); + customworldsettingsfinal_customworldsettings.P = ChatDeserializer.a(jsonobject, "gravelMinHeight", customworldsettingsfinal_customworldsettings.P); + customworldsettingsfinal_customworldsettings.Q = ChatDeserializer.a(jsonobject, "gravelMaxHeight", customworldsettingsfinal_customworldsettings.Q); + customworldsettingsfinal_customworldsettings.R = ChatDeserializer.a(jsonobject, "graniteSize", customworldsettingsfinal_customworldsettings.R); + customworldsettingsfinal_customworldsettings.S = ChatDeserializer.a(jsonobject, "graniteCount", customworldsettingsfinal_customworldsettings.S); + customworldsettingsfinal_customworldsettings.T = ChatDeserializer.a(jsonobject, "graniteMinHeight", customworldsettingsfinal_customworldsettings.T); + customworldsettingsfinal_customworldsettings.U = ChatDeserializer.a(jsonobject, "graniteMaxHeight", customworldsettingsfinal_customworldsettings.U); + customworldsettingsfinal_customworldsettings.V = ChatDeserializer.a(jsonobject, "dioriteSize", customworldsettingsfinal_customworldsettings.V); + customworldsettingsfinal_customworldsettings.W = ChatDeserializer.a(jsonobject, "dioriteCount", customworldsettingsfinal_customworldsettings.W); + customworldsettingsfinal_customworldsettings.X = ChatDeserializer.a(jsonobject, "dioriteMinHeight", customworldsettingsfinal_customworldsettings.X); + customworldsettingsfinal_customworldsettings.Y = ChatDeserializer.a(jsonobject, "dioriteMaxHeight", customworldsettingsfinal_customworldsettings.Y); + customworldsettingsfinal_customworldsettings.Z = ChatDeserializer.a(jsonobject, "andesiteSize", customworldsettingsfinal_customworldsettings.Z); + customworldsettingsfinal_customworldsettings.aa = ChatDeserializer.a(jsonobject, "andesiteCount", customworldsettingsfinal_customworldsettings.aa); + customworldsettingsfinal_customworldsettings.ab = ChatDeserializer.a(jsonobject, "andesiteMinHeight", customworldsettingsfinal_customworldsettings.ab); + customworldsettingsfinal_customworldsettings.ac = ChatDeserializer.a(jsonobject, "andesiteMaxHeight", customworldsettingsfinal_customworldsettings.ac); + customworldsettingsfinal_customworldsettings.ad = ChatDeserializer.a(jsonobject, "coalSize", customworldsettingsfinal_customworldsettings.ad); + customworldsettingsfinal_customworldsettings.ae = ChatDeserializer.a(jsonobject, "coalCount", customworldsettingsfinal_customworldsettings.ae); + customworldsettingsfinal_customworldsettings.af = ChatDeserializer.a(jsonobject, "coalMinHeight", customworldsettingsfinal_customworldsettings.af); + customworldsettingsfinal_customworldsettings.ag = ChatDeserializer.a(jsonobject, "coalMaxHeight", customworldsettingsfinal_customworldsettings.ag); + customworldsettingsfinal_customworldsettings.ah = ChatDeserializer.a(jsonobject, "ironSize", customworldsettingsfinal_customworldsettings.ah); + customworldsettingsfinal_customworldsettings.ai = ChatDeserializer.a(jsonobject, "ironCount", customworldsettingsfinal_customworldsettings.ai); + customworldsettingsfinal_customworldsettings.aj = ChatDeserializer.a(jsonobject, "ironMinHeight", customworldsettingsfinal_customworldsettings.aj); + customworldsettingsfinal_customworldsettings.ak = ChatDeserializer.a(jsonobject, "ironMaxHeight", customworldsettingsfinal_customworldsettings.ak); + customworldsettingsfinal_customworldsettings.al = ChatDeserializer.a(jsonobject, "goldSize", customworldsettingsfinal_customworldsettings.al); + customworldsettingsfinal_customworldsettings.am = ChatDeserializer.a(jsonobject, "goldCount", customworldsettingsfinal_customworldsettings.am); + customworldsettingsfinal_customworldsettings.an = ChatDeserializer.a(jsonobject, "goldMinHeight", customworldsettingsfinal_customworldsettings.an); + customworldsettingsfinal_customworldsettings.ao = ChatDeserializer.a(jsonobject, "goldMaxHeight", customworldsettingsfinal_customworldsettings.ao); + customworldsettingsfinal_customworldsettings.ap = ChatDeserializer.a(jsonobject, "redstoneSize", customworldsettingsfinal_customworldsettings.ap); + customworldsettingsfinal_customworldsettings.aq = ChatDeserializer.a(jsonobject, "redstoneCount", customworldsettingsfinal_customworldsettings.aq); + customworldsettingsfinal_customworldsettings.ar = ChatDeserializer.a(jsonobject, "redstoneMinHeight", customworldsettingsfinal_customworldsettings.ar); + customworldsettingsfinal_customworldsettings.as = ChatDeserializer.a(jsonobject, "redstoneMaxHeight", customworldsettingsfinal_customworldsettings.as); + customworldsettingsfinal_customworldsettings.at = ChatDeserializer.a(jsonobject, "diamondSize", customworldsettingsfinal_customworldsettings.at); + customworldsettingsfinal_customworldsettings.au = ChatDeserializer.a(jsonobject, "diamondCount", customworldsettingsfinal_customworldsettings.au); + customworldsettingsfinal_customworldsettings.av = ChatDeserializer.a(jsonobject, "diamondMinHeight", customworldsettingsfinal_customworldsettings.av); + customworldsettingsfinal_customworldsettings.aw = ChatDeserializer.a(jsonobject, "diamondMaxHeight", customworldsettingsfinal_customworldsettings.aw); + customworldsettingsfinal_customworldsettings.ax = ChatDeserializer.a(jsonobject, "lapisSize", customworldsettingsfinal_customworldsettings.ax); + customworldsettingsfinal_customworldsettings.ay = ChatDeserializer.a(jsonobject, "lapisCount", customworldsettingsfinal_customworldsettings.ay); + customworldsettingsfinal_customworldsettings.az = ChatDeserializer.a(jsonobject, "lapisCenterHeight", customworldsettingsfinal_customworldsettings.az); + customworldsettingsfinal_customworldsettings.aA = ChatDeserializer.a(jsonobject, "lapisSpread", customworldsettingsfinal_customworldsettings.aA); + } catch (Exception exception) { + ; + } + + return customworldsettingsfinal_customworldsettings; + } + + public JsonElement a(CustomWorldSettingsFinal.CustomWorldSettings customworldsettingsfinal_customworldsettings, Type type, JsonSerializationContext jsonserializationcontext) { + JsonObject jsonobject = new JsonObject(); + + jsonobject.addProperty("coordinateScale", customworldsettingsfinal_customworldsettings.b); + jsonobject.addProperty("heightScale", customworldsettingsfinal_customworldsettings.c); + jsonobject.addProperty("lowerLimitScale", customworldsettingsfinal_customworldsettings.e); + jsonobject.addProperty("upperLimitScale", customworldsettingsfinal_customworldsettings.d); + jsonobject.addProperty("depthNoiseScaleX", customworldsettingsfinal_customworldsettings.f); + jsonobject.addProperty("depthNoiseScaleZ", customworldsettingsfinal_customworldsettings.g); + jsonobject.addProperty("depthNoiseScaleExponent", customworldsettingsfinal_customworldsettings.h); + jsonobject.addProperty("mainNoiseScaleX", customworldsettingsfinal_customworldsettings.i); + jsonobject.addProperty("mainNoiseScaleY", customworldsettingsfinal_customworldsettings.j); + jsonobject.addProperty("mainNoiseScaleZ", customworldsettingsfinal_customworldsettings.k); + jsonobject.addProperty("baseSize", customworldsettingsfinal_customworldsettings.l); + jsonobject.addProperty("stretchY", customworldsettingsfinal_customworldsettings.m); + jsonobject.addProperty("biomeDepthWeight", customworldsettingsfinal_customworldsettings.n); + jsonobject.addProperty("biomeDepthOffset", customworldsettingsfinal_customworldsettings.o); + jsonobject.addProperty("biomeScaleWeight", customworldsettingsfinal_customworldsettings.p); + jsonobject.addProperty("biomeScaleOffset", customworldsettingsfinal_customworldsettings.q); + jsonobject.addProperty("seaLevel", customworldsettingsfinal_customworldsettings.r); + jsonobject.addProperty("useCaves", customworldsettingsfinal_customworldsettings.s); + jsonobject.addProperty("useDungeons", customworldsettingsfinal_customworldsettings.t); + jsonobject.addProperty("dungeonChance", customworldsettingsfinal_customworldsettings.u); + jsonobject.addProperty("useStrongholds", customworldsettingsfinal_customworldsettings.v); + jsonobject.addProperty("useVillages", customworldsettingsfinal_customworldsettings.w); + jsonobject.addProperty("useMineShafts", customworldsettingsfinal_customworldsettings.x); + jsonobject.addProperty("useTemples", customworldsettingsfinal_customworldsettings.y); + jsonobject.addProperty("useMonuments", customworldsettingsfinal_customworldsettings.z); + jsonobject.addProperty("useRavines", customworldsettingsfinal_customworldsettings.A); + jsonobject.addProperty("useWaterLakes", customworldsettingsfinal_customworldsettings.B); + jsonobject.addProperty("waterLakeChance", customworldsettingsfinal_customworldsettings.C); + jsonobject.addProperty("useLavaLakes", customworldsettingsfinal_customworldsettings.D); + jsonobject.addProperty("lavaLakeChance", customworldsettingsfinal_customworldsettings.E); + jsonobject.addProperty("useLavaOceans", customworldsettingsfinal_customworldsettings.F); + jsonobject.addProperty("fixedBiome", customworldsettingsfinal_customworldsettings.G); + jsonobject.addProperty("biomeSize", customworldsettingsfinal_customworldsettings.H); + jsonobject.addProperty("riverSize", customworldsettingsfinal_customworldsettings.I); + jsonobject.addProperty("dirtSize", customworldsettingsfinal_customworldsettings.J); + jsonobject.addProperty("dirtCount", customworldsettingsfinal_customworldsettings.K); + jsonobject.addProperty("dirtMinHeight", customworldsettingsfinal_customworldsettings.L); + jsonobject.addProperty("dirtMaxHeight", customworldsettingsfinal_customworldsettings.M); + jsonobject.addProperty("gravelSize", customworldsettingsfinal_customworldsettings.N); + jsonobject.addProperty("gravelCount", customworldsettingsfinal_customworldsettings.O); + jsonobject.addProperty("gravelMinHeight", customworldsettingsfinal_customworldsettings.P); + jsonobject.addProperty("gravelMaxHeight", customworldsettingsfinal_customworldsettings.Q); + jsonobject.addProperty("graniteSize", customworldsettingsfinal_customworldsettings.R); + jsonobject.addProperty("graniteCount", customworldsettingsfinal_customworldsettings.S); + jsonobject.addProperty("graniteMinHeight", customworldsettingsfinal_customworldsettings.T); + jsonobject.addProperty("graniteMaxHeight", customworldsettingsfinal_customworldsettings.U); + jsonobject.addProperty("dioriteSize", customworldsettingsfinal_customworldsettings.V); + jsonobject.addProperty("dioriteCount", customworldsettingsfinal_customworldsettings.W); + jsonobject.addProperty("dioriteMinHeight", customworldsettingsfinal_customworldsettings.X); + jsonobject.addProperty("dioriteMaxHeight", customworldsettingsfinal_customworldsettings.Y); + jsonobject.addProperty("andesiteSize", customworldsettingsfinal_customworldsettings.Z); + jsonobject.addProperty("andesiteCount", customworldsettingsfinal_customworldsettings.aa); + jsonobject.addProperty("andesiteMinHeight", customworldsettingsfinal_customworldsettings.ab); + jsonobject.addProperty("andesiteMaxHeight", customworldsettingsfinal_customworldsettings.ac); + jsonobject.addProperty("coalSize", customworldsettingsfinal_customworldsettings.ad); + jsonobject.addProperty("coalCount", customworldsettingsfinal_customworldsettings.ae); + jsonobject.addProperty("coalMinHeight", customworldsettingsfinal_customworldsettings.af); + jsonobject.addProperty("coalMaxHeight", customworldsettingsfinal_customworldsettings.ag); + jsonobject.addProperty("ironSize", customworldsettingsfinal_customworldsettings.ah); + jsonobject.addProperty("ironCount", customworldsettingsfinal_customworldsettings.ai); + jsonobject.addProperty("ironMinHeight", customworldsettingsfinal_customworldsettings.aj); + jsonobject.addProperty("ironMaxHeight", customworldsettingsfinal_customworldsettings.ak); + jsonobject.addProperty("goldSize", customworldsettingsfinal_customworldsettings.al); + jsonobject.addProperty("goldCount", customworldsettingsfinal_customworldsettings.am); + jsonobject.addProperty("goldMinHeight", customworldsettingsfinal_customworldsettings.an); + jsonobject.addProperty("goldMaxHeight", customworldsettingsfinal_customworldsettings.ao); + jsonobject.addProperty("redstoneSize", customworldsettingsfinal_customworldsettings.ap); + jsonobject.addProperty("redstoneCount", customworldsettingsfinal_customworldsettings.aq); + jsonobject.addProperty("redstoneMinHeight", customworldsettingsfinal_customworldsettings.ar); + jsonobject.addProperty("redstoneMaxHeight", customworldsettingsfinal_customworldsettings.as); + jsonobject.addProperty("diamondSize", customworldsettingsfinal_customworldsettings.at); + jsonobject.addProperty("diamondCount", customworldsettingsfinal_customworldsettings.au); + jsonobject.addProperty("diamondMinHeight", customworldsettingsfinal_customworldsettings.av); + jsonobject.addProperty("diamondMaxHeight", customworldsettingsfinal_customworldsettings.aw); + jsonobject.addProperty("lapisSize", customworldsettingsfinal_customworldsettings.ax); + jsonobject.addProperty("lapisCount", customworldsettingsfinal_customworldsettings.ay); + jsonobject.addProperty("lapisCenterHeight", customworldsettingsfinal_customworldsettings.az); + jsonobject.addProperty("lapisSpread", customworldsettingsfinal_customworldsettings.aA); + return jsonobject; + } + + public CustomWorldSettingsFinal.CustomWorldSettings deserialize(JsonElement jsonelement, Type type, JsonDeserializationContext jsondeserializationcontext) throws JsonParseException { + return this.a(jsonelement, type, jsondeserializationcontext); + } + + public JsonElement serialize(CustomWorldSettingsFinal.CustomWorldSettings object, Type type, JsonSerializationContext jsonserializationcontext) { + return this.a(object, type, jsonserializationcontext); + } + } + + public static class CustomWorldSettings { + + static final Gson a = (new GsonBuilder()).registerTypeAdapter(CustomWorldSettingsFinal.CustomWorldSettings.class, new CustomWorldSettingsFinal.CustomWorldSettingsSerializer()).create(); + public float b = 684.412F; + public float c = 684.412F; + public float d = 512.0F; + public float e = 512.0F; + public float f = 200.0F; + public float g = 200.0F; + public float h = 0.5F; + public float i = 80.0F; + public float j = 160.0F; + public float k = 80.0F; + public float l = 8.5F; + public float m = 12.0F; + public float n = 1.0F; + public float o = 0.0F; + public float p = 1.0F; + public float q = 0.0F; + public int r = 63; + public boolean s = true; + public boolean t = true; + public int u = 8; + public boolean v = true; + public boolean w = true; + public boolean x = true; + public boolean y = true; + public boolean z = true; + public boolean A = true; + public boolean B = true; + public int C = 4; + public boolean D = true; + public int E = 80; + public boolean F = false; + public int G = -1; + public int H = 4; + public int I = 4; + public int J = 33; + public int K = 10; + public int L = 0; + public int M = 256; + public int N = 33; + public int O = 8; + public int P = 0; + public int Q = 256; + public int R = 33; + public int S = 10; + public int T = 0; + public int U = 80; + public int V = 33; + public int W = 10; + public int X = 0; + public int Y = 80; + public int Z = 33; + public int aa = 10; + public int ab = 0; + public int ac = 80; + public int ad = 17; + public int ae = 20; + public int af = 0; + public int ag = 128; + public int ah = 9; + public int ai = 20; + public int aj = 0; + public int ak = 64; + public int al = 9; + public int am = 2; + public int an = 0; + public int ao = 32; + public int ap = 8; + public int aq = 8; + public int ar = 0; + public int as = 16; + public int at = 8; + public int au = 1; + public int av = 0; + public int aw = 16; + public int ax = 7; + public int ay = 1; + public int az = 16; + public int aA = 16; + + public static CustomWorldSettingsFinal.CustomWorldSettings a(String s) { + if (s.length() == 0) { + return new CustomWorldSettingsFinal.CustomWorldSettings(); + } else { + try { + return (CustomWorldSettingsFinal.CustomWorldSettings) CustomWorldSettingsFinal.CustomWorldSettings.a.fromJson(s, CustomWorldSettingsFinal.CustomWorldSettings.class); + } catch (Exception exception) { + return new CustomWorldSettingsFinal.CustomWorldSettings(); + } + } + } + + public String toString() { + return CustomWorldSettingsFinal.CustomWorldSettings.a.toJson(this); + } + + public CustomWorldSettings() { + this.a(); + } + + public void a() { + this.b = 684.412F; + this.c = 684.412F; + this.d = 512.0F; + this.e = 512.0F; + this.f = 200.0F; + this.g = 200.0F; + this.h = 0.5F; + this.i = 80.0F; + this.j = 160.0F; + this.k = 80.0F; + this.l = 8.5F; + this.m = 12.0F; + this.n = 1.0F; + this.o = 0.0F; + this.p = 1.0F; + this.q = 0.0F; + this.r = 63; + this.s = true; + this.t = true; + this.u = 8; + this.v = true; + this.w = true; + this.x = true; + this.y = true; + this.z = true; + this.A = true; + this.B = true; + this.C = 4; + this.D = true; + this.E = 80; + this.F = false; + this.G = -1; + this.H = 4; + this.I = 4; + this.J = 33; + this.K = 10; + this.L = 0; + this.M = 256; + this.N = 33; + this.O = 8; + this.P = 0; + this.Q = 256; + this.R = 33; + this.S = 10; + this.T = 0; + this.U = 80; + this.V = 33; + this.W = 10; + this.X = 0; + this.Y = 80; + this.Z = 33; + this.aa = 10; + this.ab = 0; + this.ac = 80; + this.ad = 17; + this.ae = 20; + this.af = 0; + this.ag = 128; + this.ah = 9; + this.ai = 20; + this.aj = 0; + this.ak = 64; + this.al = 9; + this.am = 2; + this.an = 0; + this.ao = 32; + this.ap = 8; + this.aq = 8; + this.ar = 0; + this.as = 16; + this.at = 8; + this.au = 1; + this.av = 0; + this.aw = 16; + this.ax = 7; + this.ay = 1; + this.az = 16; + this.aA = 16; + } + + public boolean equals(Object object) { + if (this == object) { + return true; + } else if (object != null && this.getClass() == object.getClass()) { + CustomWorldSettingsFinal.CustomWorldSettings customworldsettingsfinal_customworldsettings = (CustomWorldSettingsFinal.CustomWorldSettings) object; + + return this.aa != customworldsettingsfinal_customworldsettings.aa ? false : (this.ac != customworldsettingsfinal_customworldsettings.ac ? false : (this.ab != customworldsettingsfinal_customworldsettings.ab ? false : (this.Z != customworldsettingsfinal_customworldsettings.Z ? false : (Float.compare(customworldsettingsfinal_customworldsettings.l, this.l) != 0 ? false : (Float.compare(customworldsettingsfinal_customworldsettings.o, this.o) != 0 ? false : (Float.compare(customworldsettingsfinal_customworldsettings.n, this.n) != 0 ? false : (Float.compare(customworldsettingsfinal_customworldsettings.q, this.q) != 0 ? false : (Float.compare(customworldsettingsfinal_customworldsettings.p, this.p) != 0 ? false : (this.H != customworldsettingsfinal_customworldsettings.H ? false : (this.ae != customworldsettingsfinal_customworldsettings.ae ? false : (this.ag != customworldsettingsfinal_customworldsettings.ag ? false : (this.af != customworldsettingsfinal_customworldsettings.af ? false : (this.ad != customworldsettingsfinal_customworldsettings.ad ? false : (Float.compare(customworldsettingsfinal_customworldsettings.b, this.b) != 0 ? false : (Float.compare(customworldsettingsfinal_customworldsettings.h, this.h) != 0 ? false : (Float.compare(customworldsettingsfinal_customworldsettings.f, this.f) != 0 ? false : (Float.compare(customworldsettingsfinal_customworldsettings.g, this.g) != 0 ? false : (this.au != customworldsettingsfinal_customworldsettings.au ? false : (this.aw != customworldsettingsfinal_customworldsettings.aw ? false : (this.av != customworldsettingsfinal_customworldsettings.av ? false : (this.at != customworldsettingsfinal_customworldsettings.at ? false : (this.W != customworldsettingsfinal_customworldsettings.W ? false : (this.Y != customworldsettingsfinal_customworldsettings.Y ? false : (this.X != customworldsettingsfinal_customworldsettings.X ? false : (this.V != customworldsettingsfinal_customworldsettings.V ? false : (this.K != customworldsettingsfinal_customworldsettings.K ? false : (this.M != customworldsettingsfinal_customworldsettings.M ? false : (this.L != customworldsettingsfinal_customworldsettings.L ? false : (this.J != customworldsettingsfinal_customworldsettings.J ? false : (this.u != customworldsettingsfinal_customworldsettings.u ? false : (this.G != customworldsettingsfinal_customworldsettings.G ? false : (this.am != customworldsettingsfinal_customworldsettings.am ? false : (this.ao != customworldsettingsfinal_customworldsettings.ao ? false : (this.an != customworldsettingsfinal_customworldsettings.an ? false : (this.al != customworldsettingsfinal_customworldsettings.al ? false : (this.S != customworldsettingsfinal_customworldsettings.S ? false : (this.U != customworldsettingsfinal_customworldsettings.U ? false : (this.T != customworldsettingsfinal_customworldsettings.T ? false : (this.R != customworldsettingsfinal_customworldsettings.R ? false : (this.O != customworldsettingsfinal_customworldsettings.O ? false : (this.Q != customworldsettingsfinal_customworldsettings.Q ? false : (this.P != customworldsettingsfinal_customworldsettings.P ? false : (this.N != customworldsettingsfinal_customworldsettings.N ? false : (Float.compare(customworldsettingsfinal_customworldsettings.c, this.c) != 0 ? false : (this.ai != customworldsettingsfinal_customworldsettings.ai ? false : (this.ak != customworldsettingsfinal_customworldsettings.ak ? false : (this.aj != customworldsettingsfinal_customworldsettings.aj ? false : (this.ah != customworldsettingsfinal_customworldsettings.ah ? false : (this.az != customworldsettingsfinal_customworldsettings.az ? false : (this.ay != customworldsettingsfinal_customworldsettings.ay ? false : (this.ax != customworldsettingsfinal_customworldsettings.ax ? false : (this.aA != customworldsettingsfinal_customworldsettings.aA ? false : (this.E != customworldsettingsfinal_customworldsettings.E ? false : (Float.compare(customworldsettingsfinal_customworldsettings.e, this.e) != 0 ? false : (Float.compare(customworldsettingsfinal_customworldsettings.i, this.i) != 0 ? false : (Float.compare(customworldsettingsfinal_customworldsettings.j, this.j) != 0 ? false : (Float.compare(customworldsettingsfinal_customworldsettings.k, this.k) != 0 ? false : (this.aq != customworldsettingsfinal_customworldsettings.aq ? false : (this.as != customworldsettingsfinal_customworldsettings.as ? false : (this.ar != customworldsettingsfinal_customworldsettings.ar ? false : (this.ap != customworldsettingsfinal_customworldsettings.ap ? false : (this.I != customworldsettingsfinal_customworldsettings.I ? false : (this.r != customworldsettingsfinal_customworldsettings.r ? false : (Float.compare(customworldsettingsfinal_customworldsettings.m, this.m) != 0 ? false : (Float.compare(customworldsettingsfinal_customworldsettings.d, this.d) != 0 ? false : (this.s != customworldsettingsfinal_customworldsettings.s ? false : (this.t != customworldsettingsfinal_customworldsettings.t ? false : (this.D != customworldsettingsfinal_customworldsettings.D ? false : (this.F != customworldsettingsfinal_customworldsettings.F ? false : (this.x != customworldsettingsfinal_customworldsettings.x ? false : (this.A != customworldsettingsfinal_customworldsettings.A ? false : (this.v != customworldsettingsfinal_customworldsettings.v ? false : (this.y != customworldsettingsfinal_customworldsettings.y ? false : (this.z != customworldsettingsfinal_customworldsettings.z ? false : (this.w != customworldsettingsfinal_customworldsettings.w ? false : (this.B != customworldsettingsfinal_customworldsettings.B ? false : this.C == customworldsettingsfinal_customworldsettings.C)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))); + } else { + return false; + } + } + + public int hashCode() { + int i = this.b != 0.0F ? Float.floatToIntBits(this.b) : 0; + + i = 31 * i + (this.c != 0.0F ? Float.floatToIntBits(this.c) : 0); + i = 31 * i + (this.d != 0.0F ? Float.floatToIntBits(this.d) : 0); + i = 31 * i + (this.e != 0.0F ? Float.floatToIntBits(this.e) : 0); + i = 31 * i + (this.f != 0.0F ? Float.floatToIntBits(this.f) : 0); + i = 31 * i + (this.g != 0.0F ? Float.floatToIntBits(this.g) : 0); + i = 31 * i + (this.h != 0.0F ? Float.floatToIntBits(this.h) : 0); + i = 31 * i + (this.i != 0.0F ? Float.floatToIntBits(this.i) : 0); + i = 31 * i + (this.j != 0.0F ? Float.floatToIntBits(this.j) : 0); + i = 31 * i + (this.k != 0.0F ? Float.floatToIntBits(this.k) : 0); + i = 31 * i + (this.l != 0.0F ? Float.floatToIntBits(this.l) : 0); + i = 31 * i + (this.m != 0.0F ? Float.floatToIntBits(this.m) : 0); + i = 31 * i + (this.n != 0.0F ? Float.floatToIntBits(this.n) : 0); + i = 31 * i + (this.o != 0.0F ? Float.floatToIntBits(this.o) : 0); + i = 31 * i + (this.p != 0.0F ? Float.floatToIntBits(this.p) : 0); + i = 31 * i + (this.q != 0.0F ? Float.floatToIntBits(this.q) : 0); + i = 31 * i + this.r; + i = 31 * i + (this.s ? 1 : 0); + i = 31 * i + (this.t ? 1 : 0); + i = 31 * i + this.u; + i = 31 * i + (this.v ? 1 : 0); + i = 31 * i + (this.w ? 1 : 0); + i = 31 * i + (this.x ? 1 : 0); + i = 31 * i + (this.y ? 1 : 0); + i = 31 * i + (this.z ? 1 : 0); + i = 31 * i + (this.A ? 1 : 0); + i = 31 * i + (this.B ? 1 : 0); + i = 31 * i + this.C; + i = 31 * i + (this.D ? 1 : 0); + i = 31 * i + this.E; + i = 31 * i + (this.F ? 1 : 0); + i = 31 * i + this.G; + i = 31 * i + this.H; + i = 31 * i + this.I; + i = 31 * i + this.J; + i = 31 * i + this.K; + i = 31 * i + this.L; + i = 31 * i + this.M; + i = 31 * i + this.N; + i = 31 * i + this.O; + i = 31 * i + this.P; + i = 31 * i + this.Q; + i = 31 * i + this.R; + i = 31 * i + this.S; + i = 31 * i + this.T; + i = 31 * i + this.U; + i = 31 * i + this.V; + i = 31 * i + this.W; + i = 31 * i + this.X; + i = 31 * i + this.Y; + i = 31 * i + this.Z; + i = 31 * i + this.aa; + i = 31 * i + this.ab; + i = 31 * i + this.ac; + i = 31 * i + this.ad; + i = 31 * i + this.ae; + i = 31 * i + this.af; + i = 31 * i + this.ag; + i = 31 * i + this.ah; + i = 31 * i + this.ai; + i = 31 * i + this.aj; + i = 31 * i + this.ak; + i = 31 * i + this.al; + i = 31 * i + this.am; + i = 31 * i + this.an; + i = 31 * i + this.ao; + i = 31 * i + this.ap; + i = 31 * i + this.aq; + i = 31 * i + this.ar; + i = 31 * i + this.as; + i = 31 * i + this.at; + i = 31 * i + this.au; + i = 31 * i + this.av; + i = 31 * i + this.aw; + i = 31 * i + this.ax; + i = 31 * i + this.ay; + i = 31 * i + this.az; + i = 31 * i + this.aA; + return i; + } + + public CustomWorldSettingsFinal b() { + return new CustomWorldSettingsFinal(this, (CustomWorldSettingsFinal.SyntheticClass_1) null); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/DamageSource.java b/azurite-server/src/main/java/net/minecraft/server/DamageSource.java new file mode 100644 index 0000000..63075c9 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/DamageSource.java @@ -0,0 +1,170 @@ +package net.minecraft.server; + +public class DamageSource { + + public static DamageSource FIRE = (new DamageSource("inFire")).setExplosion(); + public static DamageSource LIGHTNING = new DamageSource("lightningBolt"); + public static DamageSource BURN = (new DamageSource("onFire")).setIgnoreArmor().setExplosion(); + public static DamageSource LAVA = (new DamageSource("lava")).setExplosion(); + public static DamageSource STUCK = (new DamageSource("inWall")).setIgnoreArmor(); + public static DamageSource DROWN = (new DamageSource("drown")).setIgnoreArmor(); + public static DamageSource STARVE = (new DamageSource("starve")).setIgnoreArmor().m(); + public static DamageSource CACTUS = new DamageSource("cactus"); + public static DamageSource FALL = (new DamageSource("fall")).setIgnoreArmor(); + public static DamageSource OUT_OF_WORLD = (new DamageSource("outOfWorld")).setIgnoreArmor().l(); + public static DamageSource GENERIC = (new DamageSource("generic")).setIgnoreArmor(); + public static DamageSource MAGIC = (new DamageSource("magic")).setIgnoreArmor().setMagic(); + public static DamageSource WITHER = (new DamageSource("wither")).setIgnoreArmor(); + public static DamageSource ANVIL = new DamageSource("anvil"); + public static DamageSource FALLING_BLOCK = new DamageSource("fallingBlock"); + private boolean q; + private boolean r; + private boolean s; + private float t = 0.3F; + private boolean u; + private boolean v; + private boolean w; + private boolean x; + private boolean y; + public String translationIndex; + + public static DamageSource mobAttack(EntityLiving entityliving) { + return new EntityDamageSource("mob", entityliving); + } + + public static EntityDamageSource playerAttack(EntityHuman entityhuman) { // Rivals + return new EntityDamageSource("player", entityhuman); + } + + public static DamageSource arrow(EntityArrow entityarrow, Entity entity) { + return (new EntityDamageSourceIndirect("arrow", entityarrow, entity)).b(); + } + + public static DamageSource fireball(EntityFireball entityfireball, Entity entity) { + return entity == null ? (new EntityDamageSourceIndirect("onFire", entityfireball, entityfireball)).setExplosion().b() : (new EntityDamageSourceIndirect("fireball", entityfireball, entity)).setExplosion().b(); + } + + public static DamageSource projectile(Entity entity, Entity entity1) { + return (new EntityDamageSourceIndirect("thrown", entity, entity1)).b(); + } + + public static DamageSource b(Entity entity, Entity entity1) { + return (new EntityDamageSourceIndirect("indirectMagic", entity, entity1)).setIgnoreArmor().setMagic(); + } + + public static DamageSource a(Entity entity) { + return (new EntityDamageSource("thorns", entity)).v().setMagic(); + } + + public static DamageSource explosion(Explosion explosion) { + return explosion != null && explosion.getSource() != null ? (new EntityDamageSource("explosion.player", explosion.getSource())).q().d() : (new DamageSource("explosion")).q().d(); + } + + public boolean a() { + return this.v; + } + + public DamageSource b() { + this.v = true; + return this; + } + + public boolean isExplosion() { + return this.y; + } + + public DamageSource d() { + this.y = true; + return this; + } + + public boolean ignoresArmor() { + return this.q; + } + + public float getExhaustionCost() { + return this.t; + } + + public boolean ignoresInvulnerability() { + return this.r; + } + + public boolean isStarvation() { + return this.s; + } + + protected DamageSource(String s) { + this.translationIndex = s; + } + + public Entity i() { + return this.getEntity(); + } + + public Entity getEntity() { + return null; + } + + protected DamageSource setIgnoreArmor() { + this.q = true; + this.t = 0.0F; + return this; + } + + protected DamageSource l() { + this.r = true; + return this; + } + + protected DamageSource m() { + this.s = true; + this.t = 0.0F; + return this; + } + + protected DamageSource setExplosion() { + this.u = true; + return this; + } + + public IChatBaseComponent getLocalizedDeathMessage(EntityLiving entityliving) { + EntityLiving entityliving1 = entityliving.bt(); + String s = "death.attack." + this.translationIndex; + String s1 = s + ".player"; + + return entityliving1 != null && LocaleI18n.c(s1) ? new ChatMessage(s1, entityliving.getScoreboardDisplayName(), entityliving1.getScoreboardDisplayName()) : new ChatMessage(s, entityliving.getScoreboardDisplayName()); + } + + public boolean o() { + return this.u; + } + + public String p() { + return this.translationIndex; + } + + public DamageSource q() { + this.w = true; + return this; + } + + public boolean r() { + return this.w; + } + + public boolean isMagic() { + return this.x; + } + + public DamageSource setMagic() { + this.x = true; + return this; + } + + public boolean u() { + Entity entity = this.getEntity(); + + return entity instanceof EntityHuman && ((EntityHuman) entity).abilities.canInstantlyBuild; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/DataWatcher.java b/azurite-server/src/main/java/net/minecraft/server/DataWatcher.java new file mode 100644 index 0000000..ad93931 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/DataWatcher.java @@ -0,0 +1,347 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; +import dev.azurite.spigot.optimizations.ProtocolUtils; +import dev.azurite.spigot.utils.NettyUtil; +import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; +import org.apache.commons.lang3.ObjectUtils; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class DataWatcher { + + private static final Object2IntOpenHashMap> classToId = new Object2IntOpenHashMap<>(10, 0.5f); + + private final Entity a; + private boolean b = true; + public final WatchableArrayMap dataValues = new WatchableArrayMap(); + private final Map d = dataValues; // Old plugins comp + private boolean e; + + public DataWatcher(Entity entity) { + this.a = entity; + } + + public void a(int i, T t0) { + int integer = classToId.getInt(t0.getClass()); // Spigot + + if (integer == -1) { // Spigot + throw new IllegalArgumentException("Unknown data type: " + t0.getClass()); + } else if (i > 31) { + throw new IllegalArgumentException("Data value id is too big with " + i + "! (Max is " + 31 + ")"); + } else if (this.dataValues.containsKey(i)) { // Spigot + throw new IllegalArgumentException("Duplicate id value for " + i + "!"); + } else { + this.dataValues.put(i, new WatchableObject(integer, i, t0)); // Spigot + this.b = false; + } + } + + public void add(int i, int j) { + this.dataValues.put(i, new WatchableObject(j, i, null)); // Spigot + this.b = false; + } + + public byte getByte(int i) { + return (byte) this.j(i).b(); + } + + public short getShort(int i) { + return (short) this.j(i).b(); + } + + public int getInt(int i) { + return (int) this.j(i).b(); + } + + public float getFloat(int i) { + return (float) this.j(i).b(); + } + + public String getString(int i) { + return (String) this.j(i).b(); + } + + public ItemStack getItemStack(int i) { + return (ItemStack) this.j(i).b(); + } + + private WatchableObject j(int i) { + return this.dataValues.get(i); + } + + public Vector3f h(int i) { + return (Vector3f) this.j(i).b(); + } + + public void watch(int index, T newValue) { + WatchableObject datawatcher_watchableobject = this.j(index); + if (ObjectUtils.notEqual(newValue, datawatcher_watchableobject.b())) { + datawatcher_watchableobject.a(newValue); + this.a.i(index); + datawatcher_watchableobject.a(true); + this.e = true; + } + } + + // Beanes - reduce packets + public void setWithoutUpdate(int index, T newValue) { + WatchableObject datawatcher_watchableobject = this.j(index); + if (ObjectUtils.notEqual(newValue, datawatcher_watchableobject.b())) { + datawatcher_watchableobject.a(newValue); + this.a.i(index); + } + } + + public void update(int i) { + this.j(i).d = true; + this.e = true; + } + + public boolean a() { + return this.e; + } + + public static void a(List list, PacketDataSerializer packetdataserializer) throws IOException { + if (list != null) { + for (WatchableObject watchableObject : list) { + a(packetdataserializer, watchableObject); + } + } + + packetdataserializer.writeByte(127); + } + + public List b() { + ArrayList arraylist = null; + + if (this.e) { + for (WatchableObject datawatcher_watchableobject : this.dataValues.values()) { + if (datawatcher_watchableobject.d()) { + datawatcher_watchableobject.a(false); + if (arraylist == null) { + arraylist = Lists.newArrayList(); + } + + // Spigot start - copy ItemStacks to prevent ConcurrentModificationExceptions + if (datawatcher_watchableobject.b() instanceof ItemStack) { + datawatcher_watchableobject = new WatchableObject( + datawatcher_watchableobject.c(), + datawatcher_watchableobject.a(), + ((ItemStack) datawatcher_watchableobject.b()).cloneItemStack() + ); + } + // Spigot end + + arraylist.add(datawatcher_watchableobject); + } + } + } + + this.e = false; + return arraylist; + } + + public void a(PacketDataSerializer packetdataserializer) throws IOException { + for (WatchableObject watchableObject : this.dataValues.values()) { + a(packetdataserializer, watchableObject); + } + packetdataserializer.writeByte(127); + } + + public List c() { + ArrayList arraylist = Lists.newArrayList(); // Spigot + arraylist.addAll(this.dataValues.values()); // Spigot + // Spigot start - copy ItemStacks to prevent ConcurrentModificationExceptions + for ( int i = 0; i < arraylist.size(); i++ ) + { + WatchableObject watchableobject = arraylist.get( i ); + if ( watchableobject.b() instanceof ItemStack ) + { + watchableobject = new WatchableObject( + watchableobject.c(), + watchableobject.a(), + ( (ItemStack) watchableobject.b() ).cloneItemStack() + ); + arraylist.set( i, watchableobject ); + } + } + // Spigot end + return arraylist; + } + + private static void a(PacketDataSerializer packetdataserializer, WatchableObject datawatcher_watchableobject) { + int i = (datawatcher_watchableobject.c() << 5 | datawatcher_watchableobject.a() & 31) & 255; + + packetdataserializer.writeByte(i); + switch (datawatcher_watchableobject.c()) { + case 0: + packetdataserializer.writeByte((byte) datawatcher_watchableobject.b()); + break; + + case 1: + packetdataserializer.writeShort((short)datawatcher_watchableobject.b()); + break; + + case 2: + packetdataserializer.writeInt((int) datawatcher_watchableobject.b()); + break; + + case 3: + packetdataserializer.writeFloat((float) datawatcher_watchableobject.b()); + break; + + case 4: + packetdataserializer.a((String) datawatcher_watchableobject.b()); + break; + + case 5: + packetdataserializer.a((ItemStack) datawatcher_watchableobject.b()); + break; + + case 6: + BlockPosition blockposition = (BlockPosition) datawatcher_watchableobject.b(); + + packetdataserializer.writeInt(blockposition.getX()); + packetdataserializer.writeInt(blockposition.getY()); + packetdataserializer.writeInt(blockposition.getZ()); + break; + + case 7: + Vector3f vector3f = (Vector3f) datawatcher_watchableobject.b(); + + packetdataserializer.writeFloat(vector3f.getX()); + packetdataserializer.writeFloat(vector3f.getY()); + packetdataserializer.writeFloat(vector3f.getZ()); + } + + } + + public static List b(PacketDataSerializer packetdataserializer) throws IOException { + ArrayList arraylist = null; + + for (byte b0 = packetdataserializer.readByte(); b0 != 127; b0 = packetdataserializer.readByte()) { + if (arraylist == null) { + arraylist = Lists.newArrayList(); + } + + int i = (b0 & 224) >> 5; + int j = b0 & 31; + WatchableObject datawatcher_watchableobject = null; + + switch (i) { + case 0: + datawatcher_watchableobject = new WatchableObject(i, j, packetdataserializer.readByte()); + break; + + case 1: + datawatcher_watchableobject = new WatchableObject(i, j, packetdataserializer.readShort()); + break; + + case 2: + datawatcher_watchableobject = new WatchableObject(i, j, packetdataserializer.readInt()); + break; + + case 3: + datawatcher_watchableobject = new WatchableObject(i, j, packetdataserializer.readFloat()); + break; + + case 4: + datawatcher_watchableobject = new WatchableObject(i, j, packetdataserializer.c(32767)); + break; + + case 5: + datawatcher_watchableobject = new WatchableObject(i, j, packetdataserializer.i()); + break; + + case 6: + datawatcher_watchableobject = new WatchableObject(i, j, new BlockPosition(packetdataserializer.readInt(), packetdataserializer.readInt(), packetdataserializer.readInt())); + break; + + case 7: + datawatcher_watchableobject = new WatchableObject(i, j, new Vector3f(packetdataserializer.readFloat(), packetdataserializer.readFloat(), packetdataserializer.readFloat())); + } + + arraylist.add(datawatcher_watchableobject); + } + + return arraylist; + } + + public boolean d() { + return this.b; + } + + public void e() { + this.e = false; + } + + static { + // Spigot Start - remove valueOf + classToId.put(Byte.class, 0); + classToId.put(Short.class, 1); + classToId.put(Integer.class, 2); + classToId.put(Float.class, 3); + classToId.put(String.class, 4); + classToId.put(ItemStack.class, 5); + classToId.put(BlockPosition.class, 6); + classToId.put(Vector3f.class, 7); + // Spigot End + } + + public static class WatchableObject { + + private final int a, b; + private Object c; + private boolean d; + + public WatchableObject(int i, int j, Object object) { + this.b = j; + this.c = object; + this.a = i; + this.d = true; + } + + public int a() { + return this.b; + } + + public void a(Object object) { + this.c = object; + } + + public Object b() { + return this.c; + } + + public int c() { + return this.a; + } + + public boolean d() { + return this.d; + } + + public void a(boolean flag) { + this.d = flag; + } + + @Override + public WatchableObject clone() { + WatchableObject watchableObject = new WatchableObject(this.a, this.b, this.c); + watchableObject.a(this.d); + return watchableObject; + } + } + + // Beanes - pvpgym updated item desync patch + public WatchableObject cloneById(int i) { + WatchableObject obj = this.j(i); + return obj == null ? null : new WatchableObject(obj.c(), obj.a(), obj.b()); + } + + +} diff --git a/azurite-server/src/main/java/net/minecraft/server/DedicatedPlayerList.java b/azurite-server/src/main/java/net/minecraft/server/DedicatedPlayerList.java new file mode 100644 index 0000000..75dc45f --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/DedicatedPlayerList.java @@ -0,0 +1,148 @@ +package net.minecraft.server; + +import com.mojang.authlib.GameProfile; +import java.io.IOException; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +public class DedicatedPlayerList extends PlayerList { + + private static final Logger f = LogManager.getLogger(); + + public DedicatedPlayerList(DedicatedServer dedicatedserver) { + super(dedicatedserver); + this.a(dedicatedserver.a("view-distance", 10)); + this.maxPlayers = dedicatedserver.a("max-players", 20); + this.setHasWhitelist(dedicatedserver.a("white-list", false)); + if (!dedicatedserver.T()) { + this.getProfileBans().a(true); + this.getIPBans().a(true); + } + + this.z(); + this.x(); + this.y(); + this.w(); + this.A(); + this.C(); + this.B(); + if (!this.getWhitelist().c().exists()) { + this.D(); + } + + } + + public void setHasWhitelist(boolean flag) { + super.setHasWhitelist(flag); + this.getServer().a("white-list", (Object) Boolean.valueOf(flag)); + this.getServer().a(); + } + + public void addOp(GameProfile gameprofile) { + super.addOp(gameprofile); + this.B(); + } + + public void removeOp(GameProfile gameprofile) { + super.removeOp(gameprofile); + this.B(); + } + + public void removeWhitelist(GameProfile gameprofile) { + super.removeWhitelist(gameprofile); + this.D(); + } + + public void addWhitelist(GameProfile gameprofile) { + super.addWhitelist(gameprofile); + this.D(); + } + + public void reloadWhitelist() { + this.C(); + } + + private void w() { + try { + this.getIPBans().save(); + } catch (IOException ioexception) { + DedicatedPlayerList.f.warn("Failed to save ip banlist: ", ioexception); + } + + } + + private void x() { + try { + this.getProfileBans().save(); + } catch (IOException ioexception) { + DedicatedPlayerList.f.warn("Failed to save user banlist: ", ioexception); + } + + } + + private void y() { + try { + this.getIPBans().load(); + } catch (IOException ioexception) { + DedicatedPlayerList.f.warn("Failed to load ip banlist: ", ioexception); + } + + } + + private void z() { + try { + this.getProfileBans().load(); + } catch (IOException ioexception) { + DedicatedPlayerList.f.warn("Failed to load user banlist: ", ioexception); + } + + } + + private void A() { + try { + this.getOPs().load(); + } catch (Exception exception) { + DedicatedPlayerList.f.warn("Failed to load operators list: ", exception); + } + + } + + private void B() { + try { + this.getOPs().save(); + } catch (Exception exception) { + DedicatedPlayerList.f.warn("Failed to save operators list: ", exception); + } + + } + + private void C() { + try { + this.getWhitelist().load(); + } catch (Exception exception) { + DedicatedPlayerList.f.warn("Failed to load white-list: ", exception); + } + + } + + private void D() { + try { + this.getWhitelist().save(); + } catch (Exception exception) { + DedicatedPlayerList.f.warn("Failed to save white-list: ", exception); + } + + } + + public boolean isWhitelisted(GameProfile gameprofile) { + return !this.getHasWhitelist() || this.isOp(gameprofile) || this.getWhitelist().isWhitelisted(gameprofile); + } + + public DedicatedServer getServer() { + return (DedicatedServer) super.getServer(); + } + + public boolean f(GameProfile gameprofile) { + return this.getOPs().b(gameprofile); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/DedicatedServer.java b/azurite-server/src/main/java/net/minecraft/server/DedicatedServer.java new file mode 100644 index 0000000..dd66965 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/DedicatedServer.java @@ -0,0 +1,565 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; +import dev.azurite.spigot.Azurite; +import dev.azurite.spigot.console.AzuriteConsole; +import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.bukkit.craftbukkit.util.Waitable; +import org.bukkit.event.server.RemoteServerCommandEvent; +import org.bukkit.event.server.ServerCommandEvent; +import org.bukkit.plugin.PluginLoadOrder; +import org.github.paperspigot.PaperSpigotConfig; +import org.spigotmc.SpigotConfig; + +import java.io.File; +import java.io.IOException; +import java.net.InetAddress; +import java.net.Proxy; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.TimeUnit; +// CraftBukkit end + +public class DedicatedServer extends MinecraftServer implements IMinecraftServer { + + public static final Logger LOGGER = LogManager.getLogger(); + public PropertyManager propertyManager; + private final List l = Collections.synchronizedList(Lists.newArrayList()); // CraftBukkit - fix decompile error + public RemoteStatusListener m; + public RemoteControlListener n; + public boolean generateStructures; + public WorldSettings.EnumGamemode r; + public boolean s; + + // CraftBukkit start - Signature changed + public DedicatedServer(joptsimple.OptionSet options) { + super(options, Proxy.NO_PROXY, a); + // CraftBukkit end + new Thread("Server Infinisleeper") { + { + setDaemon(true); + start(); + } + + public void run() { + while (true) { + try { + Thread.sleep(2147483647L); + } catch (InterruptedException ignored) { + } + } + } + }; + } + + public boolean init() throws IOException { + Thread thread = new Thread("Server console handler") { + public void run() { + // CraftBukkit start + if (!org.bukkit.craftbukkit.Main.useConsole) { + return; + } + // CraftBukkit end + + new AzuriteConsole(DedicatedServer.this).start(); + } + }; + + // CraftBukkit start - TODO: handle command-line logging arguments + java.util.logging.Logger global = java.util.logging.Logger.getLogger(""); + global.setUseParentHandlers(false); + for (java.util.logging.Handler handler : global.getHandlers()) { + global.removeHandler(handler); + } + global.addHandler(new org.bukkit.craftbukkit.util.ForwardLogHandler()); + final org.apache.logging.log4j.Logger logger = LogManager.getRootLogger(); + + System.setOut(org.apache.logging.log4j.io.IoBuilder.forLogger(logger).setLevel(Level.INFO).buildPrintStream()); + System.setErr(org.apache.logging.log4j.io.IoBuilder.forLogger(logger).setLevel(Level.WARN).buildPrintStream()); + + thread.setDaemon(true); + thread.start(); + + DedicatedServer.LOGGER.info("Starting minecraft server version 1.8.8"); + if (Runtime.getRuntime().maxMemory() / 1024 / 1024 < 128) { + DedicatedServer.LOGGER.warn("To start the server with more ram, launch it as 'java -Xmx1024M -Xms1024M -jar minecraft_server.jar'"); + } + propertyManager = new PropertyManager(options); + generateStructures = propertyManager.getBoolean("generate-structures", true); + c(propertyManager.getString("server-ip", "")); + setSpawnAnimals(propertyManager.getBoolean("spawn-animals", true)); + setSpawnNPCs(propertyManager.getBoolean("spawn-npcs", true)); + setPVP(propertyManager.getBoolean("pvp", true)); + setAllowFlight(propertyManager.getBoolean("allow-flight", false)); + setResourcePack(propertyManager.getString("resource-pack", ""), propertyManager.getString("resource-pack-hash", "")); + setMotd(propertyManager.getString("motd", "A Minecraft Server")); + setForceGamemode(propertyManager.getBoolean("force-gamemode", false)); + setIdleTimeout(propertyManager.getInt("player-idle-timeout", 0)); + + if (propertyManager.getInt("difficulty", 1) < 0) { + propertyManager.setProperty("difficulty", 0); + } else if (propertyManager.getInt("difficulty", 1) > 3) { + propertyManager.setProperty("difficulty", 3); + } + + int i = propertyManager.getInt("gamemode", WorldSettings.EnumGamemode.SURVIVAL.getId()); + r = WorldSettings.a(i); + InetAddress inetaddress = null; + + if (!getServerIp().isEmpty()) { + inetaddress = InetAddress.getByName(getServerIp()); + } + if (R() < 0) { + setPort(propertyManager.getInt("server-port", 25565)); + } + + a(new DedicatedPlayerList(this)); + SpigotConfig.init((File) options.valueOf("spigot-settings")); + SpigotConfig.registerCommands(); + PaperSpigotConfig.init((File) options.valueOf("paper-settings")); + Azurite.getInstance().registerCommands(false); + + if (getOnlineMode()) { + a(MinecraftEncryption.b()); + } + + DedicatedServer.LOGGER.info("Starting Minecraft server on {}:{}", getServerIp().isEmpty() ? '*' : getServerIp(), R()); + + if (!SpigotConfig.lateBind) { + try { + + aq().a(inetaddress, R()); + + } catch (IOException e) { + DedicatedServer.LOGGER.warn("**** FAILED TO BIND TO PORT!"); + DedicatedServer.LOGGER.warn("The exception was: {}", e.toString()); + DedicatedServer.LOGGER.warn("Perhaps a server is already running on that port?"); + z(); + } + } + if (!server.getOnlineMode()) { + DedicatedServer.LOGGER.warn("**** SERVER IS RUNNING IN OFFLINE/INSECURE MODE!"); + DedicatedServer.LOGGER.warn("The server will make no attempt to authenticate usernames. Beware."); + if (SpigotConfig.bungee) { + DedicatedServer.LOGGER.warn("Whilst this makes it possible to use BungeeCord, unless access to your server is properly restricted, it also opens up the ability for hackers to connect with any username they choose."); + DedicatedServer.LOGGER.warn("Please see http://www.spigotmc.org/wiki/firewall-guide/ for further information."); + } else { + DedicatedServer.LOGGER.warn("While this makes the game possible to play without internet access, it also opens up the ability for hackers to connect with any username they choose."); + } + DedicatedServer.LOGGER.warn("To change this, set 'online-mode' to 'true' in the server.properties file."); + } + if (aR()) { + getUserCache().c(); + } + server.loadPlugins(); + server.enablePlugins(PluginLoadOrder.STARTUP); + Azurite.getInstance().registerListeners(); + DedicatedServer.HAS_PROTOCOL_SUPPORT = server.getPluginManager().isPluginEnabled("ProtocolSupport"); + + if (NameReferencingFileConverter.a(propertyManager)) { + convertable = new WorldLoaderServer(server.getWorldContainer()); // CraftBukkit - moved from MinecraftServer constructor + long j = System.nanoTime(); + + if (U() == null) { + setWorld(propertyManager.getString("level-name", "world")); + } + + String s = propertyManager.getString("level-seed", ""); + String s1 = propertyManager.getString("level-type", "DEFAULT"); + String s2 = propertyManager.getString("generator-settings", ""); + long k = super.s.nextLong(); + + if (!s.isEmpty()) { + try { + long l = Long.parseLong(s); + + if (l != 0L) { + k = l; + } + } catch (NumberFormatException numberformatexception) { + k = s.hashCode(); + } + } + + WorldType worldtype = WorldType.getType(s1); + + if (worldtype == null) { + worldtype = WorldType.NORMAL; + } + + aB(); + getEnableCommandBlock(); + p(); + aK(); + + LOGGER.info("Preparing level \"{}\"", U()); + a(U(), U(), k, worldtype, s2); + + LOGGER.info("Done ({})! For help, type \"help\" or \"?\"", String.format("%.3fs", (System.nanoTime() - j) / 1.0E9D)); + + if (propertyManager.getBoolean("enable-query", false)) { + m = new RemoteStatusListener(this); + m.a(); + } + + if (propertyManager.getBoolean("enable-rcon", false)) { + n = new RemoteControlListener(this); + n.a(); + remoteConsole = new org.bukkit.craftbukkit.command.CraftRemoteConsoleCommandSender(); // CraftBukkit + } + + // CraftBukkit start + if (server.getBukkitSpawnRadius() > -1) { + propertyManager.properties.remove("spawn-protection"); + propertyManager.getInt("spawn-protection", server.getBukkitSpawnRadius()); + server.removeBukkitSpawnRadius(); + propertyManager.savePropertiesFile(); + } + // CraftBukkit end + + if (org.spigotmc.SpigotConfig.lateBind) { + try { + this.aq().a(inetaddress, this.R()); + } catch (IOException ioexception) { + DedicatedServer.LOGGER.warn("**** FAILED TO BIND TO PORT! "); + DedicatedServer.LOGGER.warn(" The exception was: {}", ioexception.toString()); + DedicatedServer.LOGGER.warn(" Perhaps a server is already running on that port?"); + return false; + } + } + + System.gc(); // Vortex + return true; + + } else { + return false; + } + } + + // CraftBukkit start + public PropertyManager getPropertyManager() { + return propertyManager; + } + // CraftBukkit end + + public boolean getGenerateStructures() { + return generateStructures; + } + + public WorldSettings.EnumGamemode getGamemode() { + return r; + } + + public void setGamemode(WorldSettings.EnumGamemode worldsettings_enumgamemode) { + super.setGamemode(worldsettings_enumgamemode); + r = worldsettings_enumgamemode; + } + + public EnumDifficulty getDifficulty() { + return EnumDifficulty.getById(propertyManager.getInt("difficulty", EnumDifficulty.NORMAL.a())); + } + + public boolean isHardcore() { + return propertyManager.getBoolean("hardcore", false); + } + + public CrashReport b(CrashReport crashreport) { + crashreport = super.b(crashreport); + crashreport.g().a("Is Modded", () -> { + String s = getServerModName(); + return !s.equals("vanilla") ? "Definitely; Server brand changed to '" + s + "'" : "Unknown (can't tell)"; + }); + crashreport.g().a("Type", () -> "Dedicated Server (map_server.txt)"); + return crashreport; + } + + public void z() { + System.exit(0); + } + + public void B() { // CraftBukkit - fix decompile error + super.B(); + aO(); + } + + public boolean getAllowNether() { + return propertyManager.getBoolean("allow-nether", true); + } + + public boolean getSpawnMonsters() { + return propertyManager.getBoolean("spawn-monsters", true); + } + + public boolean getSnooperEnabled() { + return propertyManager.getBoolean("snooper-enabled", true); + } + + public void issueCommand(String s, ICommandListener icommandlistener) { + l.add(new ServerCommand(s, icommandlistener)); + } + + public void aO() { + while (!l.isEmpty()) { + ServerCommand servercommand = l.remove(0); + // CraftBukkit start - ServerCommand for preprocessing + ServerCommandEvent event = new ServerCommandEvent(console, servercommand.command); + server.getPluginManager().callEvent(event); + if (event.isCancelled()) continue; + servercommand = new ServerCommand(event.getCommand(), servercommand.source); + server.dispatchServerCommand(console, servercommand); + // CraftBukkit end + } + } + + public boolean ae() { + return true; + } + + public boolean ai() { + return propertyManager.getBoolean("use-native-transport", true); + } + + public DedicatedPlayerList aP() { + return (DedicatedPlayerList) super.getPlayerList(); + } + + public int a(String s, int i) { + return propertyManager.getInt(s, i); + } + + public String a(String s, String s1) { + return propertyManager.getString(s, s1); + } + + public boolean a(String s, boolean flag) { + return propertyManager.getBoolean(s, flag); + } + + public void a(String s, Object object) { + propertyManager.setProperty(s, object); + } + + public void a() { + propertyManager.savePropertiesFile(); + } + + public String b() { + File file = propertyManager.c(); + + return file != null ? file.getAbsolutePath() : "No settings file"; + } + + public void aQ() { + ServerGUI.a(this); + s = true; + } + + public boolean as() { + return s; + } + + public String a(WorldSettings.EnumGamemode worldsettings_enumgamemode, boolean flag) { + return ""; + } + + public boolean getEnableCommandBlock() { + return propertyManager.getBoolean("enable-command-block", false); + } + + public int getSpawnProtection() { + return propertyManager.getInt("spawn-protection", super.getSpawnProtection()); + } + + public boolean a(World world, BlockPosition blockposition, EntityHuman entityhuman) { + if (world.worldProvider.getDimension() != 0) { + return false; + } else if (aP().getOPs().isEmpty()) { + return false; + } else if (aP().isOp(entityhuman.getProfile())) { + return false; + } else if (getSpawnProtection() <= 0) { + return false; + } else { + BlockPosition blockposition1 = world.getSpawn(); + int i = MathHelper.a(blockposition.getX() - blockposition1.getX()); + int j = MathHelper.a(blockposition.getZ() - blockposition1.getZ()); + int k = Math.max(i, j); + + return k <= getSpawnProtection(); + } + } + + public long aS() { + return TimeUnit.MINUTES.toMillis(1L); + } + + public int p() { + return propertyManager.getInt("op-permission-level", 4); + } + + public void setIdleTimeout(int i) { + super.setIdleTimeout(i); + propertyManager.setProperty("player-idle-timeout", i); + a(); + } + + public boolean q() { + return propertyManager.getBoolean("broadcast-rcon-to-ops", true); + } + + public boolean r() { + return propertyManager.getBoolean("broadcast-console-to-ops", true); + } + + public boolean aB() { + return propertyManager.getBoolean("announce-player-achievements", true); + } + + public int aI() { + int i = propertyManager.getInt("max-world-size", super.aI()); + + if (i < 1) { + i = 1; + } else if (i > super.aI()) { + i = super.aI(); + } + + return i; + } + + public int aK() { + return propertyManager.getInt("network-compression-threshold", super.aK()); + } + + public boolean aR() { + boolean flag = false; + + int i; + + for (i = 0; !flag && i <= 2; ++i) { + if (i > 0) { + LOGGER.warn("Encountered a problem while converting the user banlist, retrying in a few seconds"); + aU(); + } + + flag = NameReferencingFileConverter.a(this); + } + + boolean flag1 = false; + + for (i = 0; !flag1 && i <= 2; ++i) { + if (i > 0) { + LOGGER.warn("Encountered a problem while converting the ip banlist, retrying in a few seconds"); + aU(); + } + + flag1 = NameReferencingFileConverter.b(this); + } + + boolean flag2 = false; + + for (i = 0; !flag2 && i <= 2; ++i) { + if (i > 0) { + LOGGER.warn("Encountered a problem while converting the op list, retrying in a few seconds"); + aU(); + } + + flag2 = NameReferencingFileConverter.c(this); + } + + boolean flag3 = false; + + for (i = 0; !flag3 && i <= 2; ++i) { + if (i > 0) { + LOGGER.warn("Encountered a problem while converting the whitelist, retrying in a few seconds"); + aU(); + } + + flag3 = NameReferencingFileConverter.d(this); + } + + boolean flag4 = false; + + for (i = 0; !flag4 && i <= 2; ++i) { + if (i > 0) { + LOGGER.warn("Encountered a problem while converting the player save files, retrying in a few seconds"); + aU(); + } + + flag4 = NameReferencingFileConverter.a(this, propertyManager); + } + + return flag || flag1 || flag2 || flag3 || flag4; + } + + private void aU() { + try { + Thread.sleep(5000L); + } catch (InterruptedException ignored) { + } + } + + public String getPlugins() { + // CraftBukkit start - Whole method + StringBuilder result = new StringBuilder(); + org.bukkit.plugin.Plugin[] plugins = server.getPluginManager().getPlugins(); + + result.append(server.getName()); + result.append(" on Bukkit "); + result.append(server.getBukkitVersion()); + + if (plugins.length > 0 && server.getQueryPlugins()) { + result.append(": "); + + for (int i = 0; i < plugins.length; i++) { + if (i > 0) { + result.append("; "); + } + + result.append(plugins[i].getDescription().getName()); + result.append(" "); + result.append(plugins[i].getDescription().getVersion().replaceAll(";", ",")); + } + } + + return result.toString(); + // CraftBukkit end + } + + // CraftBukkit start - fire RemoteServerCommandEvent + public String executeRemoteCommand(final String s) { + Waitable waitable = new Waitable() { + @Override + protected String evaluate() { + RemoteControlCommandListener.getInstance().i(); + // Event changes start + RemoteServerCommandEvent event = new RemoteServerCommandEvent(remoteConsole, s); + server.getPluginManager().callEvent(event); + if (event.isCancelled()) { + return ""; + } + // Event change end + ServerCommand serverCommand = new ServerCommand(event.getCommand(), + RemoteControlCommandListener.getInstance()); + server.dispatchServerCommand(remoteConsole, serverCommand); + return RemoteControlCommandListener.getInstance().j(); + } + }; + postToMainThreadRunnable(waitable); + try { + return waitable.get(); + } catch (java.util.concurrent.ExecutionException e) { + throw new RuntimeException("Exception processing rcon command " + s, e.getCause()); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); // Maintain interrupted state + throw new RuntimeException("Interrupted processing rcon command " + s, e); + } + // CraftBukkit end + } + + public PlayerList getPlayerList() { + return aP(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/DemoPlayerInteractManager.java b/azurite-server/src/main/java/net/minecraft/server/DemoPlayerInteractManager.java new file mode 100644 index 0000000..15eeb6d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/DemoPlayerInteractManager.java @@ -0,0 +1,91 @@ +package net.minecraft.server; + +public class DemoPlayerInteractManager extends PlayerInteractManager { + + private boolean c; + private boolean d; + private int e; + private int f; + + public DemoPlayerInteractManager(World world) { + super(world); + } + + public void a() { + super.a(); + ++this.f; + long i = this.world.getTime(); + long j = i / 24000L + 1L; + + if (!this.c && this.f > 20) { + this.c = true; + this.player.playerConnection.sendPacket(new PacketPlayOutGameStateChange(5, 0.0F)); + } + + this.d = i > 120500L; + if (this.d) { + ++this.e; + } + + if (i % 24000L == 500L) { + if (j <= 6L) { + this.player.sendMessage(new ChatMessage("demo.day." + j, new Object[0])); + } + } else if (j == 1L) { + if (i == 100L) { + this.player.playerConnection.sendPacket(new PacketPlayOutGameStateChange(5, 101.0F)); + } else if (i == 175L) { + this.player.playerConnection.sendPacket(new PacketPlayOutGameStateChange(5, 102.0F)); + } else if (i == 250L) { + this.player.playerConnection.sendPacket(new PacketPlayOutGameStateChange(5, 103.0F)); + } + } else if (j == 5L && i % 24000L == 22000L) { + this.player.sendMessage(new ChatMessage("demo.day.warning", new Object[0])); + } + + } + + private void f() { + if (this.e > 100) { + this.player.sendMessage(new ChatMessage("demo.reminder", new Object[0])); + this.e = 0; + } + + } + + public void a(BlockPosition blockposition, EnumDirection enumdirection) { + if (this.d) { + this.f(); + } else { + super.a(blockposition, enumdirection); + } + } + + public void a(BlockPosition blockposition) { + if (!this.d) { + super.a(blockposition); + } + } + + public boolean breakBlock(BlockPosition blockposition) { + return this.d ? false : super.breakBlock(blockposition); + } + + public boolean useItem(EntityHuman entityhuman, World world, ItemStack itemstack) { + if (this.d) { + this.f(); + return false; + } else { + return super.useItem(entityhuman, world, itemstack); + } + } + + public boolean interact(EntityHuman entityhuman, World world, ItemStack itemstack, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2) { + if (this.d) { + this.f(); + return false; + } else { + return super.interact(entityhuman, world, itemstack, blockposition, enumdirection, f, f1, f2); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/DemoWorldServer.java b/azurite-server/src/main/java/net/minecraft/server/DemoWorldServer.java new file mode 100644 index 0000000..de19f10 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/DemoWorldServer.java @@ -0,0 +1,12 @@ +package net.minecraft.server; + +public class DemoWorldServer extends WorldServer { + + private static final long I = (long) "North Carolina".hashCode(); + public static final WorldSettings a = (new WorldSettings(DemoWorldServer.I, WorldSettings.EnumGamemode.SURVIVAL, true, false, WorldType.NORMAL)).a(); + + public DemoWorldServer(MinecraftServer minecraftserver, IDataManager idatamanager, WorldData worlddata, int i, MethodProfiler methodprofiler, org.bukkit.World.Environment env, org.bukkit.generator.ChunkGenerator gen) { + super(minecraftserver, idatamanager, worlddata, i, methodprofiler, env, gen); + this.worldData.a(DemoWorldServer.a); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/DifficultyDamageScaler.java b/azurite-server/src/main/java/net/minecraft/server/DifficultyDamageScaler.java new file mode 100644 index 0000000..a8fe1bd --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/DifficultyDamageScaler.java @@ -0,0 +1,38 @@ +package net.minecraft.server; + +public class DifficultyDamageScaler { + + private final EnumDifficulty a; + private final float b; + + public DifficultyDamageScaler(EnumDifficulty enumdifficulty, long i, long j, float f) { + this.a = enumdifficulty; + this.b = this.a(enumdifficulty, i, j, f); + } + + public float c() { + return this.b < 2.0F ? 0.0F : (this.b > 4.0F ? 1.0F : (this.b - 2.0F) / 2.0F); + } + + private float a(EnumDifficulty enumdifficulty, long i, long j, float f) { + if (enumdifficulty == EnumDifficulty.PEACEFUL) { + return 0.0F; + } else { + boolean flag = enumdifficulty == EnumDifficulty.HARD; + float f1 = 0.75F; + float f2 = MathHelper.a(((float) i + -72000.0F) / 1440000.0F, 0.0F, 1.0F) * 0.25F; + + f1 += f2; + float f3 = 0.0F; + + f3 += MathHelper.a((float) j / 3600000.0F, 0.0F, 1.0F) * (flag ? 1.0F : 0.75F); + f3 += MathHelper.a(f * 0.25F, 0.0F, f2); + if (enumdifficulty == EnumDifficulty.EASY) { + f3 *= 0.5F; + } + + f1 += f3; + return (float) enumdifficulty.a() * f1; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/DispenseBehaviorItem.java b/azurite-server/src/main/java/net/minecraft/server/DispenseBehaviorItem.java new file mode 100644 index 0000000..b7bd975 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/DispenseBehaviorItem.java @@ -0,0 +1,108 @@ +package net.minecraft.server; + +// CraftBukkit start + +import dev.azurite.spigot.configs.AzuriteConfig; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.event.block.BlockDispenseEvent; +// CraftBukkit end + +public class DispenseBehaviorItem implements IDispenseBehavior { + + public DispenseBehaviorItem() { + } + + // CraftBukkit start - void -> boolean return, IPosition -> ISourceBlock last argument + public static boolean a(World world, ItemStack itemstack, int i, EnumDirection enumdirection, ISourceBlock isourceblock) { + IPosition iposition = BlockDispenser.a(isourceblock); + // CraftBukkit end + double d0 = iposition.getX(); + double d1 = iposition.getY(); + double d2 = iposition.getZ(); + + if (enumdirection.k() == EnumDirection.EnumAxis.Y) { + d1 -= 0.125D; + } else { + d1 -= 0.15625D; + } + + EntityItem entityitem = new EntityItem(world, d0, d1, d2, itemstack); + double d3 = world.random.nextDouble() * 0.1D + 0.2D; + + entityitem.motX = (double) enumdirection.getAdjacentX() * d3; + entityitem.motY = 0.20000000298023224D; + entityitem.motZ = (double) enumdirection.getAdjacentZ() * d3; + entityitem.motX += world.random.nextGaussian() * 0.007499999832361937D * (double) i; + entityitem.motY += world.random.nextGaussian() * 0.007499999832361937D * (double) i; + entityitem.motZ += world.random.nextGaussian() * 0.007499999832361937D * (double) i; + + // CraftBukkit start + org.bukkit.block.Block block = world.getWorld().getBlockAt(isourceblock.getBlockPosition().getX(), isourceblock.getBlockPosition().getY(), isourceblock.getBlockPosition().getZ()); + CraftItemStack craftItem = CraftItemStack.asCraftMirror(itemstack); + + BlockDispenseEvent event = new BlockDispenseEvent(block, craftItem.clone(), new org.bukkit.util.Vector(entityitem.motX, entityitem.motY, entityitem.motZ)); + if (!BlockDispenser.eventFired) { + world.getServer().getPluginManager().callEvent(event); + } + + if (event.isCancelled()) { + return false; + } + + entityitem.setItemStack(CraftItemStack.asNMSCopy(event.getItem())); + entityitem.motX = event.getVelocity().getX(); + entityitem.motY = event.getVelocity().getY(); + entityitem.motZ = event.getVelocity().getZ(); + + if (!event.getItem().getType().equals(craftItem.getType())) { + // Chain to handler for new item + ItemStack eventStack = CraftItemStack.asNMSCopy(event.getItem()); + IDispenseBehavior idispensebehavior = BlockDispenser.REGISTRY.get(eventStack.getItem()); + if (idispensebehavior != IDispenseBehavior.NONE && idispensebehavior.getClass() != DispenseBehaviorItem.class) { + idispensebehavior.a(isourceblock, eventStack); + } else { + world.addEntity(entityitem); + } + return false; + } + + world.addEntity(entityitem); + + return true; + // CraftBukkit end + } + + public final ItemStack a(ISourceBlock isourceblock, ItemStack itemstack) { + ItemStack itemstack1 = this.b(isourceblock, itemstack); + + this.a(isourceblock); + this.a(isourceblock, BlockDispenser.b(isourceblock.f())); + return itemstack1; + } + + protected ItemStack b(ISourceBlock isourceblock, ItemStack itemstack) { + EnumDirection enumdirection = BlockDispenser.b(isourceblock.f()); + ItemStack itemstack1 = itemstack.cloneAndSubtract(1); + + // CraftBukkit start + if (!a(isourceblock.getWorld(), itemstack1, 6, enumdirection, isourceblock)) { + itemstack.count++; + } + // CraftBukkit end + return itemstack; + } + + protected void a(ISourceBlock isourceblock) { + if (AzuriteConfig.dispenserEffects.getValue()) + isourceblock.getWorld().triggerEffect(1000, isourceblock.getBlockPosition(), 0); + } + + protected void a(ISourceBlock isourceblock, EnumDirection enumdirection) { + if (AzuriteConfig.dispenserEffects.getValue()) + isourceblock.getWorld().triggerEffect(2000, isourceblock.getBlockPosition(), this.a(enumdirection)); + } + + private int a(EnumDirection enumdirection) { + return enumdirection.getAdjacentX() + 1 + (enumdirection.getAdjacentZ() + 1) * 3; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/DispenseBehaviorProjectile.java b/azurite-server/src/main/java/net/minecraft/server/DispenseBehaviorProjectile.java new file mode 100644 index 0000000..01727c2 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/DispenseBehaviorProjectile.java @@ -0,0 +1,66 @@ +package net.minecraft.server; + +// CraftBukkit start +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.event.block.BlockDispenseEvent; +// CraftBukkit end + +public abstract class DispenseBehaviorProjectile extends DispenseBehaviorItem { + + public DispenseBehaviorProjectile() {} + + public ItemStack b(ISourceBlock isourceblock, ItemStack itemstack) { + World world = isourceblock.getWorld(); + IPosition iposition = BlockDispenser.a(isourceblock); + EnumDirection enumdirection = BlockDispenser.b(isourceblock.f()); + IProjectile iprojectile = this.a(world, iposition); + + // iprojectile.shoot((double) enumdirection.getAdjacentX(), (double) ((float) enumdirection.getAdjacentY() + 0.1F), (double) enumdirection.getAdjacentZ(), this.b(), this.a()); + // CraftBukkit start + ItemStack itemstack1 = itemstack.cloneAndSubtract(1); + org.bukkit.block.Block block = world.getWorld().getBlockAt(isourceblock.getBlockPosition().getX(), isourceblock.getBlockPosition().getY(), isourceblock.getBlockPosition().getZ()); + CraftItemStack craftItem = CraftItemStack.asCraftMirror(itemstack1); + + BlockDispenseEvent event = new BlockDispenseEvent(block, craftItem.clone(), new org.bukkit.util.Vector(enumdirection.getAdjacentX(), (float) enumdirection.getAdjacentY() + 0.1F, (double) enumdirection.getAdjacentZ())); + if (!BlockDispenser.eventFired) { + world.getServer().getPluginManager().callEvent(event); + } + + if (event.isCancelled()) { + itemstack.count++; + return itemstack; + } + + if (!event.getItem().equals(craftItem)) { + itemstack.count++; + // Chain to handler for new item + ItemStack eventStack = CraftItemStack.asNMSCopy(event.getItem()); + IDispenseBehavior idispensebehavior = BlockDispenser.REGISTRY.get(eventStack.getItem()); + if (idispensebehavior != IDispenseBehavior.NONE && idispensebehavior != this) { + idispensebehavior.a(isourceblock, eventStack); + return itemstack; + } + } + + iprojectile.shoot(event.getVelocity().getX(), event.getVelocity().getY(), event.getVelocity().getZ(), this.getPower(), this.a()); + ((Entity) iprojectile).projectileSource = new org.bukkit.craftbukkit.projectiles.CraftBlockProjectileSource(isourceblock.getTileEntity()); + // CraftBukkit end + world.addEntity((Entity) iprojectile); + // itemstack.a(1); // CraftBukkit - Handled during event processing + return itemstack; + } + + protected void a(ISourceBlock isourceblock) { + isourceblock.getWorld().triggerEffect(1002, isourceblock.getBlockPosition(), 0); + } + + protected abstract IProjectile a(World world, IPosition iposition); + + protected float a() { + return 6.0F; + } + + protected float getPower() { + return 1.1F; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/DispenserRegistry.java b/azurite-server/src/main/java/net/minecraft/server/DispenserRegistry.java new file mode 100644 index 0000000..f92e239 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/DispenserRegistry.java @@ -0,0 +1,658 @@ +package net.minecraft.server; + +import com.mojang.authlib.GameProfile; +import dev.azurite.spigot.configs.AzuriteConfig; +import org.apache.commons.lang3.StringUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.bukkit.Location; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.event.block.BlockDispenseEvent; + +import java.io.PrintStream; +import java.util.Random; +// CraftBukkit end + +public class DispenserRegistry { + + private static final PrintStream a = System.out; + private static final Logger c = LogManager.getLogger(); + private static boolean b = false; + + public static boolean a() { + return DispenserRegistry.b; + } + + static void b() { + BlockDispenser.REGISTRY.a(Items.ARROW, new DispenseBehaviorProjectile() { + protected IProjectile a(World world, IPosition iposition) { + EntityArrow entityarrow = new EntityArrow(world, iposition.getX(), iposition.getY(), iposition.getZ()); + + entityarrow.fromPlayer = 1; + return entityarrow; + } + }); + BlockDispenser.REGISTRY.a(Items.EGG, new DispenseBehaviorProjectile() { + protected IProjectile a(World world, IPosition iposition) { + return new EntityEgg(world, iposition.getX(), iposition.getY(), iposition.getZ()); + } + }); + BlockDispenser.REGISTRY.a(Items.SNOWBALL, new DispenseBehaviorProjectile() { + protected IProjectile a(World world, IPosition iposition) { + return new EntitySnowball(world, iposition.getX(), iposition.getY(), iposition.getZ()); + } + }); + BlockDispenser.REGISTRY.a(Items.EXPERIENCE_BOTTLE, new DispenseBehaviorProjectile() { + protected IProjectile a(World world, IPosition iposition) { + return new EntityThrownExpBottle(world, iposition.getX(), iposition.getY(), iposition.getZ()); + } + + protected float a() { + return super.a() * 0.5F; + } + + protected float getPower() { + return super.getPower() * 1.25F; + } + }); + BlockDispenser.REGISTRY.a(Items.POTION, new IDispenseBehavior() { + private final DispenseBehaviorItem b = new DispenseBehaviorItem(); + + public ItemStack a(ISourceBlock isourceblock, final ItemStack itemstack) { + return ItemPotion.f(itemstack.getData()) ? (new DispenseBehaviorProjectile() { + protected IProjectile a(World world, IPosition iposition) { + return new EntityPotion(world, iposition.getX(), iposition.getY(), iposition.getZ(), itemstack.cloneItemStack()); + } + + protected float a() { + return super.a() * 0.5F; + } + + protected float getPower() { + return super.getPower() * 1.25F; + } + }).a(isourceblock, itemstack) : this.b.a(isourceblock, itemstack); + } + }); + BlockDispenser.REGISTRY.a(Items.SPAWN_EGG, new DispenseBehaviorItem() { + public ItemStack b(ISourceBlock isourceblock, ItemStack itemstack) { + EnumDirection enumdirection = BlockDispenser.b(isourceblock.f()); + double d0 = isourceblock.getX() + (double) enumdirection.getAdjacentX(); + double d1 = (float) isourceblock.getBlockPosition().getY() + 0.2F; + double d2 = isourceblock.getZ() + (double) enumdirection.getAdjacentZ(); + // Entity entity = ItemMonsterEgg.a(isourceblock.getWorld(), itemstack.getData(), d0, d1, d2); + + // CraftBukkit start + World world = isourceblock.getWorld(); + ItemStack itemstack1 = itemstack.cloneAndSubtract(1); + org.bukkit.block.Block block = world.getWorld().getBlockAt(isourceblock.getBlockPosition().getX(), isourceblock.getBlockPosition().getY(), isourceblock.getBlockPosition().getZ()); + CraftItemStack craftItem = CraftItemStack.asCraftMirror(itemstack1); + + BlockDispenseEvent event = new BlockDispenseEvent(block, craftItem.clone(), new org.bukkit.util.Vector(d0, d1, d2)); + if (!BlockDispenser.eventFired) { + world.getServer().getPluginManager().callEvent(event); + } + + if (event.isCancelled()) { + itemstack.count++; + return itemstack; + } + + if (!event.getItem().equals(craftItem)) { + itemstack.count++; + // Chain to handler for new item + ItemStack eventStack = CraftItemStack.asNMSCopy(event.getItem()); + IDispenseBehavior idispensebehavior = BlockDispenser.REGISTRY.get(eventStack.getItem()); + if (idispensebehavior != IDispenseBehavior.NONE && idispensebehavior != this) { + idispensebehavior.a(isourceblock, eventStack); + return itemstack; + } + } + + Entity entity = ItemMonsterEgg.spawnCreature(isourceblock.getWorld(), itemstack.getData(), event.getVelocity().getX(), event.getVelocity().getY(), event.getVelocity().getZ(), org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.DISPENSE_EGG); + + if (entity instanceof EntityLiving && itemstack.hasName()) { + entity.setCustomName(itemstack.getName()); + } + + // itemstack.a(1); // Handled during event processing + // CraftBukkit end + return itemstack; + } + }); + BlockDispenser.REGISTRY.a(Items.FIREWORKS, new DispenseBehaviorItem() { + public ItemStack b(ISourceBlock isourceblock, ItemStack itemstack) { + EnumDirection enumdirection = BlockDispenser.b(isourceblock.f()); + double d0 = isourceblock.getX() + (double) enumdirection.getAdjacentX(); + double d1 = (float) isourceblock.getBlockPosition().getY() + 0.2F; + double d2 = isourceblock.getZ() + (double) enumdirection.getAdjacentZ(); + // CraftBukkit start + World world = isourceblock.getWorld(); + ItemStack itemstack1 = itemstack.cloneAndSubtract(1); + org.bukkit.block.Block block = world.getWorld().getBlockAt(isourceblock.getBlockPosition().getX(), isourceblock.getBlockPosition().getY(), isourceblock.getBlockPosition().getZ()); + CraftItemStack craftItem = CraftItemStack.asCraftMirror(itemstack1); + + BlockDispenseEvent event = new BlockDispenseEvent(block, craftItem.clone(), new org.bukkit.util.Vector(d0, d1, d2)); + if (!BlockDispenser.eventFired) { + world.getServer().getPluginManager().callEvent(event); + } + + if (event.isCancelled()) { + itemstack.count++; + return itemstack; + } + + if (!event.getItem().equals(craftItem)) { + itemstack.count++; + // Chain to handler for new item + ItemStack eventStack = CraftItemStack.asNMSCopy(event.getItem()); + IDispenseBehavior idispensebehavior = BlockDispenser.REGISTRY.get(eventStack.getItem()); + if (idispensebehavior != IDispenseBehavior.NONE && idispensebehavior != this) { + idispensebehavior.a(isourceblock, eventStack); + return itemstack; + } + } + + itemstack1 = CraftItemStack.asNMSCopy(event.getItem()); + EntityFireworks entityfireworks = new EntityFireworks(isourceblock.getWorld(), event.getVelocity().getX(), event.getVelocity().getY(), event.getVelocity().getZ(), itemstack1); + + isourceblock.getWorld().addEntity(entityfireworks); + // itemstack.a(1); // Handled during event processing + // CraftBukkit end + return itemstack; + } + + protected void a(ISourceBlock isourceblock) { + isourceblock.getWorld().triggerEffect(1002, isourceblock.getBlockPosition(), 0); + } + }); + BlockDispenser.REGISTRY.a(Items.FIRE_CHARGE, new DispenseBehaviorItem() { + public ItemStack b(ISourceBlock isourceblock, ItemStack itemstack) { + EnumDirection enumdirection = BlockDispenser.b(isourceblock.f()); + IPosition iposition = BlockDispenser.a(isourceblock); + double d0 = iposition.getX() + (double) ((float) enumdirection.getAdjacentX() * 0.3F); + double d1 = iposition.getY() + (double) ((float) enumdirection.getAdjacentY() * 0.3F); + double d2 = iposition.getZ() + (double) ((float) enumdirection.getAdjacentZ() * 0.3F); + World world = isourceblock.getWorld(); + Random random = world.random; + double d3 = random.nextGaussian() * 0.05D + (double) enumdirection.getAdjacentX(); + double d4 = random.nextGaussian() * 0.05D + (double) enumdirection.getAdjacentY(); + double d5 = random.nextGaussian() * 0.05D + (double) enumdirection.getAdjacentZ(); + + // CraftBukkit start + ItemStack itemstack1 = itemstack.cloneAndSubtract(1); + org.bukkit.block.Block block = world.getWorld().getBlockAt(isourceblock.getBlockPosition().getX(), isourceblock.getBlockPosition().getY(), isourceblock.getBlockPosition().getZ()); + CraftItemStack craftItem = CraftItemStack.asCraftMirror(itemstack1); + + BlockDispenseEvent event = new BlockDispenseEvent(block, craftItem.clone(), new org.bukkit.util.Vector(d3, d4, d5)); + if (!BlockDispenser.eventFired) { + world.getServer().getPluginManager().callEvent(event); + } + + if (event.isCancelled()) { + itemstack.count++; + return itemstack; + } + + if (!event.getItem().equals(craftItem)) { + itemstack.count++; + // Chain to handler for new item + ItemStack eventStack = CraftItemStack.asNMSCopy(event.getItem()); + IDispenseBehavior idispensebehavior = BlockDispenser.REGISTRY.get(eventStack.getItem()); + if (idispensebehavior != IDispenseBehavior.NONE && idispensebehavior != this) { + idispensebehavior.a(isourceblock, eventStack); + return itemstack; + } + } + + EntitySmallFireball entitysmallfireball = new EntitySmallFireball(world, d0, d1, d2, event.getVelocity().getX(), event.getVelocity().getY(), event.getVelocity().getZ()); + entitysmallfireball.projectileSource = new org.bukkit.craftbukkit.projectiles.CraftBlockProjectileSource(isourceblock.getTileEntity()); + + world.addEntity(entitysmallfireball); + // itemstack.a(1); // Handled during event processing + // CraftBukkit end + return itemstack; + } + + protected void a(ISourceBlock isourceblock) { + isourceblock.getWorld().triggerEffect(1009, isourceblock.getBlockPosition(), 0); + } + }); + BlockDispenser.REGISTRY.a(Items.BOAT, new DispenseBehaviorItem() { + private final DispenseBehaviorItem b = new DispenseBehaviorItem(); + + public ItemStack b(ISourceBlock isourceblock, ItemStack itemstack) { + EnumDirection enumdirection = BlockDispenser.b(isourceblock.f()); + World world = isourceblock.getWorld(); + double d0 = isourceblock.getX() + (double) ((float) enumdirection.getAdjacentX() * 1.125F); + double d1 = isourceblock.getY() + (double) ((float) enumdirection.getAdjacentY() * 1.125F); + double d2 = isourceblock.getZ() + (double) ((float) enumdirection.getAdjacentZ() * 1.125F); + BlockPosition blockposition = isourceblock.getBlockPosition().shift(enumdirection); + Material material = world.getType(blockposition).getBlock().getMaterial(); + double d3; + + if (Material.WATER.equals(material)) { + d3 = 1.0D; + } else { + if (!Material.AIR.equals(material) || !Material.WATER.equals(world.getType(blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()).getBlock().getMaterial())) { + return this.b.a(isourceblock, itemstack); + } + + d3 = 0.0D; + } + + // EntityBoat entityboat = new EntityBoat(world, d0, d1 + d3, d2); + // CraftBukkit start + ItemStack itemstack1 = itemstack.cloneAndSubtract(1); + org.bukkit.block.Block block = world.getWorld().getBlockAt(isourceblock.getBlockPosition().getX(), isourceblock.getBlockPosition().getY(), isourceblock.getBlockPosition().getZ()); + CraftItemStack craftItem = CraftItemStack.asCraftMirror(itemstack1); + + BlockDispenseEvent event = new BlockDispenseEvent(block, craftItem.clone(), new org.bukkit.util.Vector(d0, d1 + d3, d2)); + if (!BlockDispenser.eventFired) { + world.getServer().getPluginManager().callEvent(event); + } + + if (event.isCancelled()) { + itemstack.count++; + return itemstack; + } + + if (!event.getItem().equals(craftItem)) { + itemstack.count++; + // Chain to handler for new item + ItemStack eventStack = CraftItemStack.asNMSCopy(event.getItem()); + IDispenseBehavior idispensebehavior = BlockDispenser.REGISTRY.get(eventStack.getItem()); + if (idispensebehavior != IDispenseBehavior.NONE && idispensebehavior != this) { + idispensebehavior.a(isourceblock, eventStack); + return itemstack; + } + } + + EntityBoat entityboat = new EntityBoat(world, event.getVelocity().getX(), event.getVelocity().getY(), event.getVelocity().getZ()); + // CraftBukkit end + + world.addEntity(entityboat); + // itemstack.a(1); // CraftBukkit - handled during event processing + return itemstack; + } + + protected void a(ISourceBlock isourceblock) { + isourceblock.getWorld().triggerEffect(1000, isourceblock.getBlockPosition(), 0); + } + }); + DispenseBehaviorItem dispensebehavioritem = new DispenseBehaviorItem() { + private final DispenseBehaviorItem b = new DispenseBehaviorItem(); + + public ItemStack b(ISourceBlock isourceblock, ItemStack itemstack) { + ItemBucket itembucket = (ItemBucket) itemstack.getItem(); + BlockPosition blockposition = isourceblock.getBlockPosition().shift(BlockDispenser.b(isourceblock.f())); + + // CraftBukkit start + World world = isourceblock.getWorld(); + int x = blockposition.getX(); + int y = blockposition.getY(); + int z = blockposition.getZ(); + if (world.isEmpty(blockposition) || !world.getType(blockposition).getBlock().getMaterial().isBuildable()) { + org.bukkit.block.Block block = world.getWorld().getBlockAt(isourceblock.getBlockPosition().getX(), isourceblock.getBlockPosition().getY(), isourceblock.getBlockPosition().getZ()); + CraftItemStack craftItem = CraftItemStack.asCraftMirror(itemstack); + + BlockDispenseEvent event = new BlockDispenseEvent(block, craftItem.clone(), new org.bukkit.util.Vector(x, y, z)); + if (!BlockDispenser.eventFired) { + world.getServer().getPluginManager().callEvent(event); + } + + if (event.isCancelled()) { + return itemstack; + } + + if (!event.getItem().equals(craftItem)) { + // Chain to handler for new item + ItemStack eventStack = CraftItemStack.asNMSCopy(event.getItem()); + IDispenseBehavior idispensebehavior = BlockDispenser.REGISTRY.get(eventStack.getItem()); + if (idispensebehavior != IDispenseBehavior.NONE && idispensebehavior != this) { + idispensebehavior.a(isourceblock, eventStack); + return itemstack; + } + } + + itembucket = (ItemBucket) CraftItemStack.asNMSCopy(event.getItem()).getItem(); + } + // CraftBukkit end + + if (itembucket.a(null, isourceblock.getWorld(), blockposition)) { + // CraftBukkit start - Handle stacked buckets + Item item = Items.BUCKET; + if (--itemstack.count == 0) { + itemstack.setItem(Items.BUCKET); + itemstack.count = 1; + } else if (((TileEntityDispenser) isourceblock.getTileEntity()).addItem(new ItemStack(item)) < 0) { + this.b.a(isourceblock, new ItemStack(item)); + } + // CraftBukkit end + return itemstack; + } else { + return this.b.a(isourceblock, itemstack); + } + } + }; + + BlockDispenser.REGISTRY.a(Items.LAVA_BUCKET, dispensebehavioritem); + BlockDispenser.REGISTRY.a(Items.WATER_BUCKET, dispensebehavioritem); + BlockDispenser.REGISTRY.a(Items.BUCKET, new DispenseBehaviorItem() { + private final DispenseBehaviorItem b = new DispenseBehaviorItem(); + + public ItemStack b(ISourceBlock isourceblock, ItemStack itemstack) { + World world = isourceblock.getWorld(); + BlockPosition blockposition = isourceblock.getBlockPosition().shift(BlockDispenser.b(isourceblock.f())); + IBlockData iblockdata = world.getType(blockposition); + Block block = iblockdata.getBlock(); + Material material = block.getMaterial(); + Item item; + + if (Material.WATER.equals(material) && block instanceof BlockFluids && iblockdata.get(BlockFluids.LEVEL) == 0) { + item = Items.WATER_BUCKET; + } else { + if (!Material.LAVA.equals(material) || !(block instanceof BlockFluids) || iblockdata.get(BlockFluids.LEVEL) != 0) { + return super.b(isourceblock, itemstack); + } + + item = Items.LAVA_BUCKET; + } + + // CraftBukkit start + org.bukkit.block.Block bukkitBlock = world.getWorld().getBlockAt(isourceblock.getBlockPosition().getX(), isourceblock.getBlockPosition().getY(), isourceblock.getBlockPosition().getZ()); + CraftItemStack craftItem = CraftItemStack.asCraftMirror(itemstack); + + BlockDispenseEvent event = new BlockDispenseEvent(bukkitBlock, craftItem.clone(), new org.bukkit.util.Vector(blockposition.getX(), blockposition.getY(), blockposition.getZ())); + if (!BlockDispenser.eventFired) { + world.getServer().getPluginManager().callEvent(event); + } + + if (event.isCancelled()) { + return itemstack; + } + + if (!event.getItem().equals(craftItem)) { + // Chain to handler for new item + ItemStack eventStack = CraftItemStack.asNMSCopy(event.getItem()); + IDispenseBehavior idispensebehavior = BlockDispenser.REGISTRY.get(eventStack.getItem()); + if (idispensebehavior != IDispenseBehavior.NONE && idispensebehavior != this) { + idispensebehavior.a(isourceblock, eventStack); + return itemstack; + } + } + // CraftBukkit end + + world.setAir(blockposition); + if (--itemstack.count == 0) { + itemstack.setItem(item); + itemstack.count = 1; + } else if (((TileEntityDispenser) isourceblock.getTileEntity()).addItem(new ItemStack(item)) < 0) { + this.b.a(isourceblock, new ItemStack(item)); + } + + return itemstack; + } + }); + BlockDispenser.REGISTRY.a(Items.FLINT_AND_STEEL, new DispenseBehaviorItem() { + private boolean b = true; + + protected ItemStack b(ISourceBlock isourceblock, ItemStack itemstack) { + World world = isourceblock.getWorld(); + BlockPosition blockposition = isourceblock.getBlockPosition().shift(BlockDispenser.b(isourceblock.f())); + + // CraftBukkit start + org.bukkit.block.Block block = world.getWorld().getBlockAt(isourceblock.getBlockPosition().getX(), isourceblock.getBlockPosition().getY(), isourceblock.getBlockPosition().getZ()); + CraftItemStack craftItem = CraftItemStack.asCraftMirror(itemstack); + + BlockDispenseEvent event = new BlockDispenseEvent(block, craftItem.clone(), new org.bukkit.util.Vector(0, 0, 0)); + if (!BlockDispenser.eventFired) { + world.getServer().getPluginManager().callEvent(event); + } + + if (event.isCancelled()) { + return itemstack; + } + + if (!event.getItem().equals(craftItem)) { + // Chain to handler for new item + ItemStack eventStack = CraftItemStack.asNMSCopy(event.getItem()); + IDispenseBehavior idispensebehavior = BlockDispenser.REGISTRY.get(eventStack.getItem()); + if (idispensebehavior != IDispenseBehavior.NONE && idispensebehavior != this) { + idispensebehavior.a(isourceblock, eventStack); + return itemstack; + } + } + // CraftBukkit end + + if (world.isEmpty(blockposition)) { + // CraftBukkit start - Ignition by dispensing flint and steel + if (!org.bukkit.craftbukkit.event.CraftEventFactory.callBlockIgniteEvent(world, blockposition.getX(), blockposition.getY(), blockposition.getZ(), isourceblock.getBlockPosition().getX(), isourceblock.getBlockPosition().getY(), isourceblock.getBlockPosition().getZ()).isCancelled()) { + world.setTypeUpdate(blockposition, Blocks.FIRE.getBlockData()); + if (itemstack.isDamaged(1, world.random)) { + itemstack.count = 0; + } + } + // CraftBukkit end + } else if (world.getType(blockposition).getBlock() == Blocks.TNT) { + Blocks.TNT.postBreak(world, blockposition, Blocks.TNT.getBlockData().set(BlockTNT.EXPLODE, Boolean.TRUE)); + world.setAir(blockposition); + } else { + this.b = false; + } + + return itemstack; + } + + protected void a(ISourceBlock isourceblock) { + if (this.b) { + isourceblock.getWorld().triggerEffect(1000, isourceblock.getBlockPosition(), 0); + } else { + isourceblock.getWorld().triggerEffect(1001, isourceblock.getBlockPosition(), 0); + } + + } + }); + BlockDispenser.REGISTRY.a(Items.DYE, new DispenseBehaviorItem() { + private boolean b = true; + + protected ItemStack b(ISourceBlock isourceblock, ItemStack itemstack) { + if (EnumColor.WHITE == EnumColor.fromInvColorIndex(itemstack.getData())) { + World world = isourceblock.getWorld(); + BlockPosition blockposition = isourceblock.getBlockPosition().shift(BlockDispenser.b(isourceblock.f())); + + // CraftBukkit start + org.bukkit.block.Block block = world.getWorld().getBlockAt(isourceblock.getBlockPosition().getX(), isourceblock.getBlockPosition().getY(), isourceblock.getBlockPosition().getZ()); + CraftItemStack craftItem = CraftItemStack.asCraftMirror(itemstack); // Spigot + + BlockDispenseEvent event = new BlockDispenseEvent(block, craftItem.clone(), new org.bukkit.util.Vector(0, 0, 0)); + if (!BlockDispenser.eventFired) { + world.getServer().getPluginManager().callEvent(event); + } + + if (event.isCancelled()) { + return itemstack; + } + + if (!event.getItem().equals(craftItem)) { + // Chain to handler for new item + ItemStack eventStack = CraftItemStack.asNMSCopy(event.getItem()); + IDispenseBehavior idispensebehavior = BlockDispenser.REGISTRY.get(eventStack.getItem()); + if (idispensebehavior != IDispenseBehavior.NONE && idispensebehavior != this) { + idispensebehavior.a(isourceblock, eventStack); + return itemstack; + } + } + // CraftBukkit end + + if (ItemDye.a(itemstack, world, blockposition)) { + world.triggerEffect(2005, blockposition, 0); + } else { + this.b = false; + } + + return itemstack; + } else { + return super.b(isourceblock, itemstack); + } + } + + protected void a(ISourceBlock isourceblock) { + if (this.b) { + isourceblock.getWorld().triggerEffect(1000, isourceblock.getBlockPosition(), 0); + } else { + isourceblock.getWorld().triggerEffect(1001, isourceblock.getBlockPosition(), 0); + } + + } + }); + BlockDispenser.REGISTRY.a(Item.getItemOf(Blocks.TNT), new DispenseBehaviorItem() { + protected ItemStack b(ISourceBlock isourceblock, ItemStack itemstack) { + World world = isourceblock.getWorld(); + BlockPosition blockposition = isourceblock.getBlockPosition().shift(BlockDispenser.b(isourceblock.f())); + EntityTNTPrimed entitytntprimed; + + double y = blockposition.getY(); + if (!world.paperSpigotConfig.fixCannons) y += 0.5; + + if (AzuriteConfig.fireTNTDispenseEvent.getValue()) { + org.bukkit.block.Block block = world.getWorld().getBlockAt(isourceblock.getBlockPosition().getX(), isourceblock.getBlockPosition().getY(), isourceblock.getBlockPosition().getZ()); + CraftItemStack craftItem = CraftItemStack.asCraftMirror(itemstack.cloneAndSubtract(1)); + + BlockDispenseEvent event = new BlockDispenseEvent(block, craftItem.clone(), new org.bukkit.util.Vector(blockposition.getX() + 0.5, y, blockposition.getZ() + 0.5)); + + if (!BlockDispenser.eventFired) { + world.getServer().getPluginManager().callEvent(event); + } + + if (event.isCancelled()) { + itemstack.count++; + return itemstack; + } + + if (!event.getItem().equals(craftItem)) { + itemstack.count++; + // Chain to handler for new item + ItemStack eventStack = CraftItemStack.asNMSCopy(event.getItem()); + IDispenseBehavior idispensebehavior = BlockDispenser.REGISTRY.get(eventStack.getItem()); + if (idispensebehavior != IDispenseBehavior.NONE && idispensebehavior != this) { + idispensebehavior.a(isourceblock, eventStack); + return itemstack; + } + } + entitytntprimed = new EntityTNTPrimed(block.getLocation(), world, event.getVelocity().getX(), event.getVelocity().getY(), event.getVelocity().getZ(), null); // PaperSpigot + } else { + itemstack.count--; + entitytntprimed = new EntityTNTPrimed(new Location(world.getWorld(), blockposition.getX(), y, blockposition.getZ()), world, blockposition.getX() + 0.5, y, blockposition.getZ() + 0.5, null); // PaperSpigot } + } + world.queueSpawn(entitytntprimed); + return itemstack; + } + }); + BlockDispenser.REGISTRY.a(Items.SKULL, new DispenseBehaviorItem() { + private boolean b = true; + + protected ItemStack b(ISourceBlock isourceblock, ItemStack itemstack) { + World world = isourceblock.getWorld(); + EnumDirection enumdirection = BlockDispenser.b(isourceblock.f()); + BlockPosition blockposition = isourceblock.getBlockPosition().shift(enumdirection); + BlockSkull blockskull = Blocks.SKULL; + + if (world.isEmpty(blockposition) && blockskull.b(world, blockposition, itemstack)) { + world.setTypeAndData(blockposition, blockskull.getBlockData().set(BlockSkull.FACING, EnumDirection.UP), 3); + TileEntity tileentity = world.getTileEntity(blockposition); + + if (tileentity instanceof TileEntitySkull) { + if (itemstack.getData() == 3) { + GameProfile gameprofile = null; + + if (itemstack.hasTag()) { + NBTTagCompound nbttagcompound = itemstack.getTag(); + + if (nbttagcompound.hasKeyOfType("SkullOwner", 10)) { + gameprofile = GameProfileSerializer.deserialize(nbttagcompound.getCompound("SkullOwner")); + } else if (nbttagcompound.hasKeyOfType("SkullOwner", 8)) { + String s = nbttagcompound.getString("SkullOwner"); + + if (!StringUtils.isEmpty(s)) { + gameprofile = new GameProfile(null, s); + } + } + } + + ((TileEntitySkull) tileentity).setGameProfile(gameprofile); + } else { + ((TileEntitySkull) tileentity).setSkullType(itemstack.getData()); + } + + ((TileEntitySkull) tileentity).setRotation(enumdirection.opposite().b() * 4); + Blocks.SKULL.a(world, blockposition, (TileEntitySkull) tileentity); + } + + --itemstack.count; + } else { + this.b = false; + } + + return itemstack; + } + + protected void a(ISourceBlock isourceblock) { + if (this.b) { + isourceblock.getWorld().triggerEffect(1000, isourceblock.getBlockPosition(), 0); + } else { + isourceblock.getWorld().triggerEffect(1001, isourceblock.getBlockPosition(), 0); + } + + } + }); + BlockDispenser.REGISTRY.a(Item.getItemOf(Blocks.PUMPKIN), new DispenseBehaviorItem() { + private boolean b = true; + + protected ItemStack b(ISourceBlock isourceblock, ItemStack itemstack) { + World world = isourceblock.getWorld(); + BlockPosition blockposition = isourceblock.getBlockPosition().shift(BlockDispenser.b(isourceblock.f())); + BlockPumpkin blockpumpkin = (BlockPumpkin) Blocks.PUMPKIN; + + if (world.isEmpty(blockposition) && blockpumpkin.e(world, blockposition)) { + world.setTypeAndData(blockposition, blockpumpkin.getBlockData(), 3); + + --itemstack.count; + } else { + this.b = false; + } + + return itemstack; + } + + protected void a(ISourceBlock isourceblock) { + if (this.b) { + isourceblock.getWorld().triggerEffect(1000, isourceblock.getBlockPosition(), 0); + } else { + isourceblock.getWorld().triggerEffect(1001, isourceblock.getBlockPosition(), 0); + } + + } + }); + } + + public static void c() { + if (!DispenserRegistry.b) { + DispenserRegistry.b = true; + if (DispenserRegistry.c.isDebugEnabled()) { + d(); + } + + Block.S(); + BlockFire.l(); + Item.t(); + StatisticList.a(); + b(); + } + } + + private static void d() { + System.setErr(new RedirectStream("STDERR", System.err)); + System.setOut(new RedirectStream("STDOUT", DispenserRegistry.a)); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EULA.java b/azurite-server/src/main/java/net/minecraft/server/EULA.java new file mode 100644 index 0000000..c872029 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EULA.java @@ -0,0 +1,62 @@ +package net.minecraft.server; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.util.Properties; +import org.apache.commons.io.IOUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +public class EULA { + + private static final Logger a = LogManager.getLogger(); + private final File b; + private final boolean c; + + public EULA(File file) { + this.b = file; + this.c = this.a(file); + } + + private boolean a(File file) { + FileInputStream fileinputstream = null; + boolean flag = false; + + try { + Properties properties = new Properties(); + + fileinputstream = new FileInputStream(file); + properties.load(fileinputstream); + flag = Boolean.parseBoolean(properties.getProperty("eula", "false")); + } catch (Exception exception) { + EULA.a.warn("Failed to load " + file); + this.b(); + } finally { + IOUtils.closeQuietly(fileinputstream); + } + + return flag; + } + + public boolean a() { + return this.c; + } + + public void b() { + FileOutputStream fileoutputstream = null; + + try { + Properties properties = new Properties(); + + fileoutputstream = new FileOutputStream(this.b); + properties.setProperty("eula", "false"); + properties.store(fileoutputstream, "By changing the setting below to TRUE you are indicating your agreement to our EULA (https://account.mojang.com/documents/minecraft_eula)."); + } catch (Exception exception) { + EULA.a.warn("Failed to save " + this.b, exception); + } finally { + IOUtils.closeQuietly(fileoutputstream); + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EmptyChunk.java b/azurite-server/src/main/java/net/minecraft/server/EmptyChunk.java new file mode 100644 index 0000000..8bd79af --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EmptyChunk.java @@ -0,0 +1,90 @@ +package net.minecraft.server; + +import com.google.common.base.Predicate; +import java.util.List; +import java.util.Random; + +public class EmptyChunk extends Chunk { + + public EmptyChunk(World world, int i, int j) { + super(world, i, j); + } + + public boolean a(int i, int j) { + return i == this.locX && j == this.locZ; + } + + public int b(int i, int j) { + return 0; + } + + public void initLighting() {} + + public Block getType(BlockPosition blockposition) { + return Blocks.AIR; + } + + public int b(BlockPosition blockposition) { + return 255; + } + + public int c(BlockPosition blockposition) { + return 0; + } + + public int getBrightness(EnumSkyBlock enumskyblock, BlockPosition blockposition) { + return enumskyblock.c; + } + + public void a(EnumSkyBlock enumskyblock, BlockPosition blockposition, int i) {} + + public int a(BlockPosition blockposition, int i) { + return 0; + } + + public void a(Entity entity) {} + + public void b(Entity entity) {} + + public void a(Entity entity, int i) {} + + public boolean d(BlockPosition blockposition) { + return false; + } + + public TileEntity a(BlockPosition blockposition, Chunk.EnumTileEntityState chunk_enumtileentitystate) { + return null; + } + + public void a(TileEntity tileentity) {} + + public void a(BlockPosition blockposition, TileEntity tileentity) {} + + public void e(BlockPosition blockposition) {} + + public void addEntities() {} + + public void removeEntities() {} + + public void e() {} + + public void a(Entity entity, AxisAlignedBB axisalignedbb, List list, Predicate predicate) {} + + public void a(Class oclass, AxisAlignedBB axisalignedbb, List list, Predicate predicate) {} + + public boolean a(boolean flag) { + return false; + } + + public Random a(long i) { + return new Random(this.getWorld().getSeed() + (long) (this.locX * this.locX * 4987142) + (long) (this.locX * 5947611) + (long) (this.locZ * this.locZ) * 4392871L + (long) (this.locZ * 389711) ^ i); + } + + public boolean isEmpty() { + return true; + } + + public boolean c(int i, int j) { + return true; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/Enchantment.java b/azurite-server/src/main/java/net/minecraft/server/Enchantment.java new file mode 100644 index 0000000..cd23506 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/Enchantment.java @@ -0,0 +1,144 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; + +import java.util.ArrayList; +import java.util.Map; +import java.util.Set; + +public abstract class Enchantment { + + // CraftBukkit - update CraftEnchant.getName(i) if this changes + private static final Enchantment[] byId = new Enchantment[256]; + public static final Enchantment[] b; + private static final Map E = Maps.newHashMap(); + public static final Enchantment PROTECTION_ENVIRONMENTAL = new EnchantmentProtection(0, new MinecraftKey("protection"), 10, 0); + public static final Enchantment PROTECTION_FIRE = new EnchantmentProtection(1, new MinecraftKey("fire_protection"), 5, 1); + public static final Enchantment PROTECTION_FALL = new EnchantmentProtection(2, new MinecraftKey("feather_falling"), 5, 2); + public static final Enchantment PROTECTION_EXPLOSIONS = new EnchantmentProtection(3, new MinecraftKey("blast_protection"), 2, 3); + public static final Enchantment PROTECTION_PROJECTILE = new EnchantmentProtection(4, new MinecraftKey("projectile_protection"), 5, 4); + public static final Enchantment OXYGEN = new EnchantmentOxygen(5, new MinecraftKey("respiration"), 2); + public static final Enchantment WATER_WORKER = new EnchantmentWaterWorker(6, new MinecraftKey("aqua_affinity"), 2); + public static final Enchantment THORNS = new EnchantmentThorns(7, new MinecraftKey("thorns"), 1); + public static final Enchantment DEPTH_STRIDER = new EnchantmentDepthStrider(8, new MinecraftKey("depth_strider"), 2); + public static final Enchantment DAMAGE_ALL = new EnchantmentWeaponDamage(16, new MinecraftKey("sharpness"), 10, 0); + public static final Enchantment DAMAGE_UNDEAD = new EnchantmentWeaponDamage(17, new MinecraftKey("smite"), 5, 1); + public static final Enchantment DAMAGE_ARTHROPODS = new EnchantmentWeaponDamage(18, new MinecraftKey("bane_of_arthropods"), 5, 2); + public static final Enchantment KNOCKBACK = new EnchantmentKnockback(19, new MinecraftKey("knockback"), 5); + public static final Enchantment FIRE_ASPECT = new EnchantmentFire(20, new MinecraftKey("fire_aspect"), 2); + public static final Enchantment LOOT_BONUS_MOBS = new EnchantmentLootBonus(21, new MinecraftKey("looting"), 2, EnchantmentSlotType.WEAPON); + public static final Enchantment DIG_SPEED = new EnchantmentDigging(32, new MinecraftKey("efficiency"), 10); + public static final Enchantment SILK_TOUCH = new EnchantmentSilkTouch(33, new MinecraftKey("silk_touch"), 1); + public static final Enchantment DURABILITY = new EnchantmentDurability(34, new MinecraftKey("unbreaking"), 5); + public static final Enchantment LOOT_BONUS_BLOCKS = new EnchantmentLootBonus(35, new MinecraftKey("fortune"), 2, EnchantmentSlotType.DIGGER); + public static final Enchantment ARROW_DAMAGE = new EnchantmentArrowDamage(48, new MinecraftKey("power"), 10); + public static final Enchantment ARROW_KNOCKBACK = new EnchantmentArrowKnockback(49, new MinecraftKey("punch"), 2); + public static final Enchantment ARROW_FIRE = new EnchantmentFlameArrows(50, new MinecraftKey("flame"), 2); + public static final Enchantment ARROW_INFINITE = new EnchantmentInfiniteArrows(51, new MinecraftKey("infinity"), 1); + public static final Enchantment LUCK = new EnchantmentLootBonus(61, new MinecraftKey("luck_of_the_sea"), 2, EnchantmentSlotType.FISHING_ROD); + public static final Enchantment LURE = new EnchantmentLure(62, new MinecraftKey("lure"), 2, EnchantmentSlotType.FISHING_ROD); + public final int id; + private final int weight; + public EnchantmentSlotType slot; + protected String name; + + public static Enchantment getById(int i) { + return i >= 0 && i < Enchantment.byId.length ? Enchantment.byId[i] : null; + } + + protected Enchantment(int i, MinecraftKey minecraftkey, int j, EnchantmentSlotType enchantmentslottype) { + this.id = i; + this.weight = j; + this.slot = enchantmentslottype; + if (Enchantment.byId[i] != null) { + throw new IllegalArgumentException("Duplicate enchantment id!"); + } else { + Enchantment.byId[i] = this; + Enchantment.E.put(minecraftkey, this); + } + + org.bukkit.enchantments.Enchantment.registerEnchantment(new org.bukkit.craftbukkit.enchantments.CraftEnchantment(this)); // CraftBukkit + } + + public static Enchantment getByName(String s) { + return Enchantment.E.get(new MinecraftKey(s)); + } + + public static Set getEffects() { + return Enchantment.E.keySet(); + } + + public int getRandomWeight() { + return this.weight; + } + + public int getStartLevel() { + return 1; + } + + public int getMaxLevel() { + return Math.max(1, getEnchantLimit()); + } + + public int getEnchantLimit() { + return -1; + } + + public int a(int i) { + return 1 + i * 10; + } + + public int b(int i) { + return this.a(i) + 5; + } + + public int a(int i, DamageSource damagesource) { + return 0; + } + + public float a(int i, EnumMonsterType enummonstertype) { + return 0.0F; + } + + public boolean a(Enchantment enchantment) { + return this != enchantment; + } + + public Enchantment c(String s) { + this.name = s; + return this; + } + + public String a() { + return "enchantment." + this.name; + } + + public String d(int i) { + String s = LocaleI18n.get(this.a()); + + return s + " " + LocaleI18n.get("enchantment.level." + i); + } + + public boolean canEnchant(ItemStack itemstack) { + return this.slot.canEnchant(itemstack.getItem()); + } + + public void a(EntityLiving entityliving, Entity entity, int i) { + } + + public void b(EntityLiving entityliving, Entity entity, int i) { + } + + static { + ArrayList arraylist = Lists.newArrayList(); + + for (Enchantment enchantment : Enchantment.byId) { + if (enchantment != null) { + arraylist.add(enchantment); + } + } + + b = arraylist.toArray(new Enchantment[0]); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EnchantmentArrowDamage.java b/azurite-server/src/main/java/net/minecraft/server/EnchantmentArrowDamage.java new file mode 100644 index 0000000..f31e504 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EnchantmentArrowDamage.java @@ -0,0 +1,29 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.EnchantConfig; + +public class EnchantmentArrowDamage extends Enchantment { + + public EnchantmentArrowDamage(int var1, MinecraftKey var2, int var3) { + super(var1, var2, var3, EnchantmentSlotType.BOW); + this.c("arrowDamage"); + } + + public int a(int var1) { + return 1 + (var1 - 1) * 10; + } + + public int b(int var1) { + return this.a(var1) + 15; + } + + @Override + public int getMaxLevel() { + return Math.max(5, getEnchantLimit()); + } + + @Override + public int getEnchantLimit() { + return EnchantConfig.power.getValue(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EnchantmentArrowKnockback.java b/azurite-server/src/main/java/net/minecraft/server/EnchantmentArrowKnockback.java new file mode 100644 index 0000000..2cc7fb7 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EnchantmentArrowKnockback.java @@ -0,0 +1,29 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.EnchantConfig; + +public class EnchantmentArrowKnockback extends Enchantment { + + public EnchantmentArrowKnockback(int var1, MinecraftKey var2, int var3) { + super(var1, var2, var3, EnchantmentSlotType.BOW); + this.c("arrowKnockback"); + } + + public int a(int var1) { + return 12 + (var1 - 1) * 20; + } + + public int b(int var1) { + return this.a(var1) + 25; + } + + @Override + public int getMaxLevel() { + return Math.max(2, getEnchantLimit()); + } + + @Override + public int getEnchantLimit() { + return EnchantConfig.punch.getValue(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EnchantmentDepthStrider.java b/azurite-server/src/main/java/net/minecraft/server/EnchantmentDepthStrider.java new file mode 100644 index 0000000..f06bf5a --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EnchantmentDepthStrider.java @@ -0,0 +1,29 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.EnchantConfig; + +public class EnchantmentDepthStrider extends Enchantment { + + public EnchantmentDepthStrider(int var1, MinecraftKey var2, int var3) { + super(var1, var2, var3, EnchantmentSlotType.ARMOR_FEET); + this.c("waterWalker"); + } + + public int a(int var1) { + return var1 * 10; + } + + public int b(int var1) { + return this.a(var1) + 15; + } + + @Override + public int getMaxLevel() { + return Math.max(3, getEnchantLimit()); + } + + @Override + public int getEnchantLimit() { + return EnchantConfig.depthStrider.getValue(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EnchantmentDigging.java b/azurite-server/src/main/java/net/minecraft/server/EnchantmentDigging.java new file mode 100644 index 0000000..8d3b223 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EnchantmentDigging.java @@ -0,0 +1,33 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.EnchantConfig; + +public class EnchantmentDigging extends Enchantment { + + protected EnchantmentDigging(int var1, MinecraftKey var2, int var3) { + super(var1, var2, var3, EnchantmentSlotType.DIGGER); + this.c("digging"); + } + + public int a(int var1) { + return 1 + 10 * (var1 - 1); + } + + public int b(int var1) { + return super.a(var1) + 50; + } + + @Override + public int getMaxLevel() { + return Math.max(5, getEnchantLimit()); + } + + @Override + public int getEnchantLimit() { + return EnchantConfig.efficiency.getValue(); + } + + public boolean canEnchant(ItemStack var1) { + return var1.getItem() == Items.SHEARS || super.canEnchant(var1); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EnchantmentDurability.java b/azurite-server/src/main/java/net/minecraft/server/EnchantmentDurability.java new file mode 100644 index 0000000..c6c3b3a --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EnchantmentDurability.java @@ -0,0 +1,44 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.AzuriteConfig; +import dev.azurite.spigot.configs.EnchantConfig; + +import java.util.Random; + +public class EnchantmentDurability extends Enchantment { + + protected EnchantmentDurability(int var1, MinecraftKey var2, int var3) { + super(var1, var2, var3, EnchantmentSlotType.BREAKABLE); + this.c("durability"); + } + + public int a(int var1) { + return 5 + (var1 - 1) * 8; + } + + public int b(int var1) { + return super.a(var1) + 50; + } + + @Override + public int getMaxLevel() { + return Math.max(3, getEnchantLimit()); + } + + @Override + public int getEnchantLimit() { + return EnchantConfig.unbreaking.getValue(); + } + + public boolean canEnchant(ItemStack var1) { + return var1.e() || super.canEnchant(var1); + } + + public static boolean a(ItemStack var0, int var1, Random var2) { + if (var0.getItem() instanceof ItemArmor && var2.nextFloat() < AzuriteConfig.armorDurabilityRandomness.getValue()) { + return false; + } else { + return var2.nextInt(var1 + 1) > 0; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EnchantmentFire.java b/azurite-server/src/main/java/net/minecraft/server/EnchantmentFire.java new file mode 100644 index 0000000..c2c1d86 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EnchantmentFire.java @@ -0,0 +1,29 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.EnchantConfig; + +public class EnchantmentFire extends Enchantment { + + protected EnchantmentFire(int var1, MinecraftKey var2, int var3) { + super(var1, var2, var3, EnchantmentSlotType.WEAPON); + this.c("fire"); + } + + public int a(int var1) { + return 10 + 20 * (var1 - 1); + } + + public int b(int var1) { + return super.a(var1) + 50; + } + + @Override + public int getMaxLevel() { + return Math.max(2, getEnchantLimit()); + } + + @Override + public int getEnchantLimit() { + return EnchantConfig.fireAspect.getValue(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EnchantmentFlameArrows.java b/azurite-server/src/main/java/net/minecraft/server/EnchantmentFlameArrows.java new file mode 100644 index 0000000..2f58b80 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EnchantmentFlameArrows.java @@ -0,0 +1,24 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.EnchantConfig; + +public class EnchantmentFlameArrows extends Enchantment { + + public EnchantmentFlameArrows(int var1, MinecraftKey var2, int var3) { + super(var1, var2, var3, EnchantmentSlotType.BOW); + this.c("arrowFire"); + } + + public int a(int var1) { + return 20; + } + + public int b(int var1) { + return 50; + } + + @Override + public int getEnchantLimit() { + return EnchantConfig.flame.getValue(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EnchantmentInfiniteArrows.java b/azurite-server/src/main/java/net/minecraft/server/EnchantmentInfiniteArrows.java new file mode 100644 index 0000000..ce947be --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EnchantmentInfiniteArrows.java @@ -0,0 +1,24 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.EnchantConfig; + +public class EnchantmentInfiniteArrows extends Enchantment { + + public EnchantmentInfiniteArrows(int var1, MinecraftKey var2, int var3) { + super(var1, var2, var3, EnchantmentSlotType.BOW); + this.c("arrowInfinite"); + } + + public int a(int var1) { + return 20; + } + + public int b(int var1) { + return 50; + } + + @Override + public int getEnchantLimit() { + return EnchantConfig.infinity.getValue(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EnchantmentKnockback.java b/azurite-server/src/main/java/net/minecraft/server/EnchantmentKnockback.java new file mode 100644 index 0000000..f5f9586 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EnchantmentKnockback.java @@ -0,0 +1,29 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.EnchantConfig; + +public class EnchantmentKnockback extends Enchantment { + + protected EnchantmentKnockback(int var1, MinecraftKey var2, int var3) { + super(var1, var2, var3, EnchantmentSlotType.WEAPON); + this.c("knockback"); + } + + public int a(int var1) { + return 5 + 20 * (var1 - 1); + } + + public int b(int var1) { + return super.a(var1) + 50; + } + + @Override + public int getMaxLevel() { + return Math.max(2, getEnchantLimit()); + } + + @Override + public int getEnchantLimit() { + return EnchantConfig.knockback.getValue(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EnchantmentLootBonus.java b/azurite-server/src/main/java/net/minecraft/server/EnchantmentLootBonus.java new file mode 100644 index 0000000..972d1c9 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EnchantmentLootBonus.java @@ -0,0 +1,48 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.EnchantConfig; + +public class EnchantmentLootBonus extends Enchantment { + + protected EnchantmentLootBonus(int var1, MinecraftKey var2, int var3, EnchantmentSlotType var4) { + super(var1, var2, var3, var4); + if (var4 == EnchantmentSlotType.DIGGER) { + this.c("lootBonusDigger"); + } else if (var4 == EnchantmentSlotType.FISHING_ROD) { + this.c("lootBonusFishing"); + } else { + this.c("lootBonus"); + } + } + + public int a(int var1) { + return 15 + (var1 - 1) * 9; + } + + public int b(int var1) { + return super.a(var1) + 50; + } + + @Override + public int getMaxLevel() { + return Math.max(3, getEnchantLimit()); + } + + @Override + public int getEnchantLimit() { + switch (name) { + case "lootBonusDigger": + return EnchantConfig.fortune.getValue(); + case "lootBonusFishing": + return EnchantConfig.luckOfTheSea.getValue(); + case "lootBonus": + return EnchantConfig.looting.getValue(); + } + + return -1; + } + + public boolean a(Enchantment var1) { + return super.a(var1) && var1.id != SILK_TOUCH.id; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EnchantmentLure.java b/azurite-server/src/main/java/net/minecraft/server/EnchantmentLure.java new file mode 100644 index 0000000..6ee8705 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EnchantmentLure.java @@ -0,0 +1,29 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.EnchantConfig; + +public class EnchantmentLure extends Enchantment { + + protected EnchantmentLure(int var1, MinecraftKey var2, int var3, EnchantmentSlotType var4) { + super(var1, var2, var3, var4); + this.c("fishingSpeed"); + } + + public int a(int var1) { + return 15 + (var1 - 1) * 9; + } + + public int b(int var1) { + return super.a(var1) + 50; + } + + @Override + public int getMaxLevel() { + return Math.max(3, getEnchantLimit()); + } + + @Override + public int getEnchantLimit() { + return EnchantConfig.lure.getValue(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EnchantmentManager.java b/azurite-server/src/main/java/net/minecraft/server/EnchantmentManager.java new file mode 100644 index 0000000..a3e0916 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EnchantmentManager.java @@ -0,0 +1,438 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import dev.azurite.spigot.configs.AzuriteConfig; + +import java.util.*; + +public class EnchantmentManager { + + private static final Random a = new Random(); + private static final EnchantmentModifierProtection b = new EnchantmentModifierProtection(null); + private static final EnchantmentModifierDamage c = new EnchantmentModifierDamage(null); + private static final EnchantmentModifierThorns d = new EnchantmentModifierThorns(null); + private static final EnchantmentModifierArthropods e = new EnchantmentModifierArthropods(null); + + public static int getEnchantmentLevel(int i, ItemStack itemstack) { + if (itemstack != null) { + NBTTagList nbttaglist = itemstack.getEnchantments(); + + if (nbttaglist != null) { + for (int j = 0; j < nbttaglist.size(); ++j) { + NBTTagCompound compound = nbttaglist.get(j); + if (compound.getShort("id") == i) { + return compound.getShort("lvl"); + } + } + + } + } + return 0; + } + + public static LinkedHashMap a(ItemStack itemstack) { + LinkedHashMap linkedhashmap = Maps.newLinkedHashMap(); + NBTTagList nbttaglist = itemstack.getItem() == Items.ENCHANTED_BOOK ? Items.ENCHANTED_BOOK.h(itemstack) : itemstack.getEnchantments(); + + if (nbttaglist != null) { + for (int i = 0; i < nbttaglist.size(); ++i) { + NBTTagCompound compound = nbttaglist.get(i); + linkedhashmap.put((int) compound.getShort("id"), (int) compound.getShort("lvl")); + } + } + + return linkedhashmap; + } + + public static void a(Map map, ItemStack itemstack) { + NBTTagList nbttaglist = new NBTTagList(); + + for (int i : map.keySet()) { + Enchantment enchantment = Enchantment.getById(i); + + if (enchantment != null && enchantment.getEnchantLimit() != 0) { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + + nbttagcompound.setShort("id", (short) i); + nbttagcompound.setShort("lvl", (short) ((int) map.get(i))); + nbttaglist.add(nbttagcompound); + if (itemstack.getItem() == Items.ENCHANTED_BOOK) { + Items.ENCHANTED_BOOK.a(itemstack, new WeightedRandomEnchant(enchantment, map.get(i))); + } + } + } + + if (!nbttaglist.isEmpty()) { + if (itemstack.getItem() != Items.ENCHANTED_BOOK) { + itemstack.a("ench", nbttaglist); + } + } else if (itemstack.hasTag()) { + itemstack.getTag().remove("ench"); + } + + } + + public static int a(int i, ItemStack[] aitemstack) { + if (aitemstack == null) { + return 0; + } else { + int j = 0; + for (ItemStack itemstack : aitemstack) { + int i1 = getEnchantmentLevel(i, itemstack); + + if (i1 > j) { + j = i1; + } + } + + return j; + } + } + + private static void a(EnchantmentModifier enchantmentmanager_enchantmentmodifier, ItemStack itemstack) { + if (itemstack != null) { + NBTTagList nbttaglist = itemstack.getEnchantments(); + + if (nbttaglist != null) { + for (int i = 0; i < nbttaglist.size(); ++i) { + NBTTagCompound compound = nbttaglist.get(i); + Enchantment enchantment = Enchantment.getById(compound.getShort("id")); + if (enchantment != null) { + enchantmentmanager_enchantmentmodifier.a(enchantment, compound.getShort("lvl")); + } + } + + } + } + } + + private static void a(EnchantmentModifier enchantmentmanager_enchantmentmodifier, ItemStack[] aitemstack) { + for (ItemStack itemstack : aitemstack) { + a(enchantmentmanager_enchantmentmodifier, itemstack); + } + } + + public static int a(ItemStack[] aitemstack, DamageSource damagesource) { + b.a = 0; + b.b = damagesource; + a(b, aitemstack); + if (b.a > 25) { + b.a = 25; + } else if (b.a < 0) { + b.a = 0; + } + b.b = null; + + if (!AzuriteConfig.protRandomness.getValue()) { + if (AzuriteConfig.protRandomnessIfDisabledUseMedian.getValue()) { + int base = (EnchantmentManager.b.a + 1) >> 1; + int maxRandom = (EnchantmentManager.b.a >> 1) + 1; + return base + (AzuriteConfig.protRandomness.getValue() + ? EnchantmentManager.a.nextInt(maxRandom) + : maxRandom / 2); // Median when RNG is disabled + } else { + return b.a; + } + } + + return (b.a + 1 >> 1) + a.nextInt((b.a >> 1) + 1); + } + + public static float a(ItemStack itemstack, EnumMonsterType enummonstertype) { + c.a = 0.0F; + c.b = enummonstertype; + a(c, itemstack); + return c.a; + } + + public static void a(EntityLiving entityliving, Entity entity) { + d.b = entity; + d.a = entityliving; + if (entityliving != null) { + a(d, entityliving.getEquipment()); + } + + if (entity instanceof EntityHuman && entityliving != null) { + a(d, entityliving.bA()); + } + + d.a = null; + d.b = null; + } + + public static void b(EntityLiving entityliving, Entity entity) { + e.a = entityliving; + e.b = entity; + if (entityliving != null) { + a(e, entityliving.getEquipment()); + } + + if (entityliving instanceof EntityHuman) { + a(e, entityliving.bA()); + } + + e.a = null; + e.b = null; + } + + public static int a(EntityLiving entityliving) { + return getEnchantmentLevel(Enchantment.KNOCKBACK.id, entityliving.bA()); + } + + public static int getFireAspectEnchantmentLevel(EntityLiving entityliving) { + return getEnchantmentLevel(Enchantment.FIRE_ASPECT.id, entityliving.bA()); + } + + public static int getOxygenEnchantmentLevel(Entity entity) { + return a(Enchantment.OXYGEN.id, entity.getEquipment()); + } + + public static int b(Entity entity) { + return a(Enchantment.DEPTH_STRIDER.id, entity.getEquipment()); + } + + public static int getDigSpeedEnchantmentLevel(EntityLiving entityliving) { + return getEnchantmentLevel(Enchantment.DIG_SPEED.id, entityliving.bA()); + } + + public static boolean hasSilkTouchEnchantment(EntityLiving entityliving) { + return getEnchantmentLevel(Enchantment.SILK_TOUCH.id, entityliving.bA()) > 0; + } + + public static int getBonusBlockLootEnchantmentLevel(EntityLiving entityliving) { + return getEnchantmentLevel(Enchantment.LOOT_BONUS_BLOCKS.id, entityliving.bA()); + } + + public static int g(EntityLiving entityliving) { + return getEnchantmentLevel(Enchantment.LUCK.id, entityliving.bA()); + } + + public static int h(EntityLiving entityliving) { + return getEnchantmentLevel(Enchantment.LURE.id, entityliving.bA()); + } + + public static int getBonusMonsterLootEnchantmentLevel(EntityLiving entityliving) { + return getEnchantmentLevel(Enchantment.LOOT_BONUS_MOBS.id, entityliving.bA()); + } + + public static boolean j(EntityLiving entityliving) { + return a(Enchantment.WATER_WORKER.id, entityliving.getEquipment()) > 0; + } + + public static ItemStack a(Enchantment enchantment, EntityLiving entityliving) { + for (ItemStack itemstack : entityliving.getEquipment()) { + if (itemstack != null && getEnchantmentLevel(enchantment.id, itemstack) > 0) { + return itemstack; + } + } + + return null; + } + + public static int a(Random random, int i, int j, ItemStack itemstack) { + Item item = itemstack.getItem(); + int k = item.b(); + + if (k <= 0) { + return 0; + } else { + if (j > 15) { + j = 15; + } + + int l = random.nextInt(8) + 1 + (j >> 1) + random.nextInt(j + 1); + + return i == 0 ? Math.max(l / 3, 1) : (i == 1 ? l * 2 / 3 + 1 : Math.max(l, j * 2)); + } + } + + public static ItemStack a(Random random, ItemStack itemstack, int i) { + List list = b(random, itemstack, i); + boolean flag = itemstack.getItem() == Items.BOOK; + + if (flag) { + itemstack.setItem(Items.ENCHANTED_BOOK); + } + + if (list != null) { + + for (WeightedRandomEnchant weightedrandomenchant : list) { + if (flag) { + Items.ENCHANTED_BOOK.a(itemstack, weightedrandomenchant); + } else { + itemstack.addEnchantment(weightedrandomenchant.enchantment, weightedrandomenchant.level); + } + } + } + + return itemstack; + } + + public static List b(Random random, ItemStack itemstack, int i) { + Item item = itemstack.getItem(); + int j = item.b(); + + if (j <= 0) { + return null; + } else { + j /= 2; + j = 1 + random.nextInt((j >> 1) + 1) + random.nextInt((j >> 1) + 1); + int k = j + i; + float f = (random.nextFloat() + random.nextFloat() - 1.0F) * 0.15F; + int l = (int) ((float) k * (1.0F + f) + 0.5F); + + if (l < 1) { + l = 1; + } + + ArrayList arraylist = null; + Map map = b(l, itemstack); + + if (map != null && !map.isEmpty()) { + WeightedRandomEnchant weightedrandomenchant = WeightedRandom.a(random, map.values()); + + if (weightedrandomenchant != null) { + arraylist = Lists.newArrayList(); + arraylist.add(weightedrandomenchant); + + for (int i1 = l; random.nextInt(50) <= i1; i1 >>= 1) { + Iterator iterator = map.keySet().iterator(); + + while (iterator.hasNext()) { + Integer integer = iterator.next(); + boolean flag = true; + Iterator iterator1 = arraylist.iterator(); + + while (true) { + if (iterator1.hasNext()) { + WeightedRandomEnchant weightedrandomenchant1 = iterator1.next(); + + if (weightedrandomenchant1.enchantment.a(Enchantment.getById(integer))) { + continue; + } + + flag = false; + } + + if (!flag) { + iterator.remove(); + } + break; + } + } + + if (!map.isEmpty()) { + arraylist.add(WeightedRandom.a(random, map.values())); + } + } + } + } + + return arraylist; + } + } + + public static Map b(int i, ItemStack itemstack) { + Item item = itemstack.getItem(); + HashMap hashmap = null; + boolean flag = itemstack.getItem() == Items.BOOK; + + for (Enchantment enchantment : Enchantment.b) { + if (enchantment != null && (enchantment.slot.canEnchant(item) || flag)) { + int limit = enchantment.getEnchantLimit(); + int maxLevel = enchantment.getMaxLevel(); + + if (limit == 0) continue; // Azurite - Don't even consider the enchantment + + for (int l = enchantment.getStartLevel(); l <= (Math.min(maxLevel, limit)); ++l) { + if (i >= enchantment.a(l) && i <= enchantment.b(l)) { + if (hashmap == null) { + hashmap = Maps.newHashMap(); + } + + hashmap.put(enchantment.id, new WeightedRandomEnchant(enchantment, l)); + } + } + } + } + + return hashmap; + } + + static class SyntheticClass_1 { + } + + static final class EnchantmentModifierArthropods implements EnchantmentModifier { + + public EntityLiving a; + public Entity b; + + private EnchantmentModifierArthropods() { + } + + public void a(Enchantment enchantment, int i) { + enchantment.a(this.a, this.b, i); + } + + EnchantmentModifierArthropods(SyntheticClass_1 enchantmentmanager_syntheticclass_1) { + this(); + } + } + + static final class EnchantmentModifierThorns implements EnchantmentModifier { + + public EntityLiving a; + public Entity b; + + private EnchantmentModifierThorns() { + } + + public void a(Enchantment enchantment, int i) { + enchantment.b(this.a, this.b, i); + } + + EnchantmentModifierThorns(SyntheticClass_1 enchantmentmanager_syntheticclass_1) { + this(); + } + } + + static final class EnchantmentModifierDamage implements EnchantmentModifier { + + public float a; + public EnumMonsterType b; + + private EnchantmentModifierDamage() { + } + + public void a(Enchantment enchantment, int i) { + this.a += enchantment.a(i, this.b); + } + + EnchantmentModifierDamage(SyntheticClass_1 enchantmentmanager_syntheticclass_1) { + this(); + } + } + + static final class EnchantmentModifierProtection implements EnchantmentModifier { + + public int a; + public DamageSource b; + + private EnchantmentModifierProtection() { + } + + public void a(Enchantment enchantment, int i) { + this.a += enchantment.a(i, this.b); + } + + EnchantmentModifierProtection(SyntheticClass_1 enchantmentmanager_syntheticclass_1) { + this(); + } + } + + interface EnchantmentModifier { + + void a(Enchantment enchantment, int i); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EnchantmentOxygen.java b/azurite-server/src/main/java/net/minecraft/server/EnchantmentOxygen.java new file mode 100644 index 0000000..542151e --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EnchantmentOxygen.java @@ -0,0 +1,29 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.EnchantConfig; + +public class EnchantmentOxygen extends Enchantment { + + public EnchantmentOxygen(int var1, MinecraftKey var2, int var3) { + super(var1, var2, var3, EnchantmentSlotType.ARMOR_HEAD); + this.c("oxygen"); + } + + public int a(int var1) { + return 10 * var1; + } + + public int b(int var1) { + return this.a(var1) + 30; + } + + @Override + public int getMaxLevel() { + return Math.max(3, getEnchantLimit()); + } + + @Override + public int getEnchantLimit() { + return EnchantConfig.waterBreathing.getValue(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EnchantmentProtection.java b/azurite-server/src/main/java/net/minecraft/server/EnchantmentProtection.java new file mode 100644 index 0000000..9de5fe9 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EnchantmentProtection.java @@ -0,0 +1,93 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.EnchantConfig; + +public class EnchantmentProtection extends Enchantment { + + private static final String[] E = {"all", "fire", "fall", "explosion", "projectile"}; + private static final int[] F = {1, 10, 5, 5, 3}; + private static final int[] G = {11, 8, 6, 8, 6}; + private static final int[] H = {20, 12, 10, 12, 15}; + public final int a; + + public EnchantmentProtection(int paramInt1, MinecraftKey paramMinecraftKey, int paramInt2, int paramInt3) { + super(paramInt1, paramMinecraftKey, paramInt2, EnchantmentSlotType.ARMOR); + this.a = paramInt3; + if (paramInt3 == 2) + this.slot = EnchantmentSlotType.ARMOR_FEET; + } + + public int a(int paramInt) { + return F[this.a] + (paramInt - 1) * G[this.a]; + } + + public int b(int paramInt) { + return a(paramInt) + H[this.a]; + } + + public int getMaxLevel() { + return Math.max(4, getEnchantLimit()); + } + + @Override + public int getEnchantLimit() { + switch (a) { + case 0: + return EnchantConfig.protectionAll.getValue(); + case 1: + return EnchantConfig.protectionFire.getValue(); + case 2: + return EnchantConfig.protectionFall.getValue(); + case 3: + return EnchantConfig.protectionExplosion.getValue(); + case 4: + return EnchantConfig.protectionProjectile.getValue(); + } + return -1; + } + + public int a(int paramInt, DamageSource paramDamageSource) { + if (paramDamageSource.ignoresInvulnerability()) + return 0; + float f = (6 + paramInt * paramInt) / 3.0F; + if (this.a == 0) + return MathHelper.d(f * 0.75F); + if (this.a == 1 && paramDamageSource.o()) + return MathHelper.d(f * 1.25F); + if (this.a == 2 && paramDamageSource == DamageSource.FALL) + return MathHelper.d(f * 2.5F); + if (this.a == 3 && paramDamageSource.isExplosion()) + return MathHelper.d(f * 1.5F); + if (this.a == 4 && paramDamageSource.a()) + return MathHelper.d(f * 1.5F); + return 0; + } + + public String a() { + return "enchantment.protect." + E[this.a]; + } + + public boolean a(Enchantment paramEnchantment) { + if (paramEnchantment instanceof EnchantmentProtection) { + EnchantmentProtection enchantmentProtection = (EnchantmentProtection) paramEnchantment; + if (enchantmentProtection.a == this.a) + return false; + return this.a == 2 || enchantmentProtection.a == 2; + } + return super.a(paramEnchantment); + } + + public static int a(Entity paramEntity, int paramInt) { + int i = EnchantmentManager.a(Enchantment.PROTECTION_FIRE.id, paramEntity.getEquipment()); + if (i > 0) + paramInt -= MathHelper.d(paramInt * i * 0.15F); + return paramInt; + } + + public static double a(Entity paramEntity, double paramDouble) { + int i = EnchantmentManager.a(Enchantment.PROTECTION_EXPLOSIONS.id, paramEntity.getEquipment()); + if (i > 0) + paramDouble -= MathHelper.floor(paramDouble * (i * 0.15F)); + return paramDouble; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EnchantmentSilkTouch.java b/azurite-server/src/main/java/net/minecraft/server/EnchantmentSilkTouch.java new file mode 100644 index 0000000..677c149 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EnchantmentSilkTouch.java @@ -0,0 +1,32 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.EnchantConfig; + +public class EnchantmentSilkTouch extends Enchantment { + + protected EnchantmentSilkTouch(int var1, MinecraftKey var2, int var3) { + super(var1, var2, var3, EnchantmentSlotType.DIGGER); + this.c("untouching"); + } + + public int a(int var1) { + return 15; + } + + public int b(int var1) { + return super.a(var1) + 50; + } + + public boolean a(Enchantment var1) { + return super.a(var1) && var1.id != LOOT_BONUS_BLOCKS.id; + } + + public boolean canEnchant(ItemStack var1) { + return var1.getItem() == Items.SHEARS || super.canEnchant(var1); + } + + @Override + public int getEnchantLimit() { + return EnchantConfig.silkTouch.getValue(); + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/net/minecraft/server/EnchantmentSlotType.java b/azurite-server/src/main/java/net/minecraft/server/EnchantmentSlotType.java new file mode 100644 index 0000000..d552656 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EnchantmentSlotType.java @@ -0,0 +1,26 @@ +package net.minecraft.server; + +public enum EnchantmentSlotType { + + ALL, ARMOR, ARMOR_FEET, ARMOR_LEGS, ARMOR_TORSO, ARMOR_HEAD, WEAPON, DIGGER, FISHING_ROD, BREAKABLE, BOW; + + private EnchantmentSlotType() {} + + public boolean canEnchant(Item item) { + if (this == EnchantmentSlotType.ALL) { + return true; + } else if (this == EnchantmentSlotType.BREAKABLE && item.usesDurability()) { + return true; + } else if (item instanceof ItemArmor) { + if (this == EnchantmentSlotType.ARMOR) { + return true; + } else { + ItemArmor itemarmor = (ItemArmor) item; + + return itemarmor.b == 0 ? this == EnchantmentSlotType.ARMOR_HEAD : (itemarmor.b == 2 ? this == EnchantmentSlotType.ARMOR_LEGS : (itemarmor.b == 1 ? this == EnchantmentSlotType.ARMOR_TORSO : (itemarmor.b == 3 ? this == EnchantmentSlotType.ARMOR_FEET : false))); + } + } else { + return item instanceof ItemSword ? this == EnchantmentSlotType.WEAPON : (item instanceof ItemTool ? this == EnchantmentSlotType.DIGGER : (item instanceof ItemBow ? this == EnchantmentSlotType.BOW : (item instanceof ItemFishingRod ? this == EnchantmentSlotType.FISHING_ROD : false))); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EnchantmentThorns.java b/azurite-server/src/main/java/net/minecraft/server/EnchantmentThorns.java new file mode 100644 index 0000000..fb0f52c --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EnchantmentThorns.java @@ -0,0 +1,59 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.EnchantConfig; + +import java.util.Random; + +public class EnchantmentThorns extends Enchantment { + + public EnchantmentThorns(int i, MinecraftKey minecraftkey, int j) { + super(i, minecraftkey, j, EnchantmentSlotType.ARMOR_TORSO); + this.c("thorns"); + } + + public int a(int i) { + return 10 + 20 * (i - 1); + } + + public int b(int i) { + return super.a(i) + 50; + } + + @Override + public int getMaxLevel() { + return Math.max(3, getEnchantLimit()); + } + + @Override + public int getEnchantLimit() { + return EnchantConfig.thorns.getValue(); + } + + public boolean canEnchant(ItemStack itemstack) { + return itemstack.getItem() instanceof ItemArmor || super.canEnchant(itemstack); + } + + public void b(EntityLiving entityliving, Entity entity, int i) { + Random random = entityliving.bc(); + ItemStack itemstack = EnchantmentManager.a(Enchantment.THORNS, entityliving); + + if (entity != null && a(i, random)) { // CraftBukkit + entity.damageEntity(DamageSource.a(entityliving), (float) b(i, random)); + entity.makeSound("damage.thorns", 0.5F, 1.0F); + + if (itemstack != null) { + itemstack.damage(3, entityliving); + } + } else if (itemstack != null) { + itemstack.damage(1, entityliving); + } + } + + public static boolean a(int i, Random random) { + return i > 0 && random.nextFloat() < 0.15F * (float) i; + } + + public static int b(int i, Random random) { + return i > 10 ? i - 10 : 1 + random.nextInt(4); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EnchantmentWaterWorker.java b/azurite-server/src/main/java/net/minecraft/server/EnchantmentWaterWorker.java new file mode 100644 index 0000000..84d13be --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EnchantmentWaterWorker.java @@ -0,0 +1,24 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.EnchantConfig; + +public class EnchantmentWaterWorker extends Enchantment { + + public EnchantmentWaterWorker(int var1, MinecraftKey var2, int var3) { + super(var1, var2, var3, EnchantmentSlotType.ARMOR_HEAD); + this.c("waterWorker"); + } + + public int a(int var1) { + return 1; + } + + public int b(int var1) { + return this.a(var1) + 40; + } + + @Override + public int getEnchantLimit() { + return EnchantConfig.aquaAffinity.getValue(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EnchantmentWeaponDamage.java b/azurite-server/src/main/java/net/minecraft/server/EnchantmentWeaponDamage.java new file mode 100644 index 0000000..dfa80a9 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EnchantmentWeaponDamage.java @@ -0,0 +1,76 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.EnchantConfig; + +public class EnchantmentWeaponDamage extends Enchantment { + + private static final String[] E = new String[]{"all", "undead", "arthropods"}; + private static final int[] F = new int[]{1, 5, 5}; + private static final int[] G = new int[]{11, 8, 8}; + private static final int[] H = new int[]{20, 20, 20}; + public final int a; + + public EnchantmentWeaponDamage(int var1, MinecraftKey var2, int var3, int var4) { + super(var1, var2, var3, EnchantmentSlotType.WEAPON); + this.a = var4; + } + + public int a(int var1) { + return F[this.a] + (var1 - 1) * G[this.a]; + } + + public int b(int var1) { + return this.a(var1) + H[this.a]; + } + + @Override + public int getMaxLevel() { + return Math.max(5, getEnchantLimit()); + } + + @Override + public int getEnchantLimit() { + switch (E[this.a]) { + case "all": + return EnchantConfig.sharpness.getValue(); + case "undead": + return EnchantConfig.smite.getValue(); + case "arthropods": + return EnchantConfig.baneOfArthropods.getValue(); + } + + return -1; + } + + public float a(int var1, EnumMonsterType var2) { + if (this.a == 0) { + return (float) var1 * 1.25F; + } else if (this.a == 1 && var2 == EnumMonsterType.UNDEAD) { + return (float) var1 * 2.5F; + } else { + return this.a == 2 && var2 == EnumMonsterType.ARTHROPOD ? (float) var1 * 2.5F : 0.0F; + } + } + + public String a() { + return "enchantment.damage." + E[this.a]; + } + + public boolean a(Enchantment var1) { + return !(var1 instanceof EnchantmentWeaponDamage); + } + + public boolean canEnchant(ItemStack var1) { + return var1.getItem() instanceof ItemAxe || super.canEnchant(var1); + } + + public void a(EntityLiving var1, Entity var2, int var3) { + if (var2 instanceof EntityLiving) { + EntityLiving var4 = (EntityLiving) var2; + if (this.a == 2 && var4.getMonsterType() == EnumMonsterType.ARTHROPOD) { + int var5 = 20 + var1.bc().nextInt(10 * var3); + var4.addEffect(new MobEffect(MobEffectList.SLOWER_MOVEMENT.id, var5, 3)); + } + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/Entity.java b/azurite-server/src/main/java/net/minecraft/server/Entity.java new file mode 100644 index 0000000..3674261 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/Entity.java @@ -0,0 +1,2348 @@ +package net.minecraft.server; + +import com.eatthepath.uuid.FastUUID; +import dev.azurite.spigot.Azurite; +import dev.azurite.spigot.configs.AzuriteConfig; +import dev.azurite.spigot.knockback.Knockback; +import org.apache.logging.log4j.LogManager; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Server; +import org.bukkit.TravelAgent; +import org.bukkit.block.BlockFace; +import org.bukkit.craftbukkit.CraftWorld; +import org.bukkit.craftbukkit.entity.CraftEntity; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.craftbukkit.event.CraftEventFactory; +import org.bukkit.entity.Hanging; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Painting; +import org.bukkit.entity.Vehicle; +import org.bukkit.event.entity.CreatureSpawnEvent; +import org.bukkit.event.entity.EntityCombustByEntityEvent; +import org.bukkit.event.entity.EntityCombustEvent; +import org.bukkit.event.entity.EntityPortalEvent; +import org.bukkit.event.hanging.HangingBreakByEntityEvent; +import org.bukkit.event.painting.PaintingBreakByEntityEvent; +import org.bukkit.event.vehicle.VehicleBlockCollisionEvent; +import org.bukkit.event.vehicle.VehicleEnterEvent; +import org.bukkit.event.vehicle.VehicleExitEvent; +import org.bukkit.plugin.PluginManager; +import org.spigotmc.event.entity.EntityDismountEvent; + +import java.util.Iterator; +import java.util.List; +import java.util.Random; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; + +public abstract class Entity implements ICommandListener { + + public static int lastChunkX = Integer.MAX_VALUE, lastChunkZ = Integer.MAX_VALUE; + public static Chunk lastChunk = null; + + // CraftBukkit start + private static final int CURRENT_LEVEL = 2; + private static final AxisAlignedBB a = new AxisAlignedBB(0.0D, 0.0D, 0.0D, 0.0D, 0.0D, 0.0D); + // CraftBukikt end + public static int entityCount = 1; + public final byte activationType = org.spigotmc.ActivationRange.initializeEntityActivationType(this); + public final boolean defaultActivationState; + private final CommandObjectiveExecutor au; + public double j; + public boolean k; + public Entity passenger; + public Entity vehicle; + public boolean attachedToPlayer; + public World world; + public double lastX; + public double lastY; + public double lastZ; + public boolean forceExplosionKnockback; + public double lastMotX; + public double lastMotY; + public double lastMotZ; + public double locX; + public double locY; + public double locZ; + public double spawnX; + public double spawnY; + public double spawnZ; + public double motX; + public double motY; + public double motZ; + public float yaw; + public float pitch; + public float lastYaw; + public float lastPitch; + public int lastLavaTick, lastCollisionTick; // Vortex + public AxisAlignedBB boundingBox; // Vortex + public boolean onGround; + public boolean positionChanged; + public boolean E; + public boolean F; + public boolean velocityChanged; + public boolean dead; + public float width; + public float length; + public float L; + public float M; + public float N; + public float fallDistance; + public double P; + public double Q; + public double R; + public float S; + public boolean noclip; + public float U; + public int ticksLived; + public int maxFireTicks; + public int fireTicks; + public boolean inWater, inLava; // Spigot - protected -> public // PAIL + public boolean hasBeenCounted = false; // Paper + public CreatureSpawnEvent.SpawnReason spawnReason; + public int noDamageTicks; + public int noDamageTicksArrow; // Azurite + // Beanes - no damage time + public long noDamageTime; + public long noDamageTimeArrow; + public boolean ad; + public int ae; + public int af; + public int ag; + // PaperSpigot end + public boolean ah; + public boolean ai; + public int portalCooldown; + public int dimension; + public boolean valid; // CraftBukkit + public org.bukkit.projectiles.ProjectileSource projectileSource; // CraftBukkit - For projectiles only + public boolean inUnloadedChunk = false; // PaperSpigot - Remove entities in unloaded chunks + public boolean loadChunks = false; // PaperSpigot - Entities can load chunks they move through and keep them loaded + // Vortex End + // Spigot start + public long activatedTick = Integer.MIN_VALUE; + public boolean fromMobSpawner; + protected boolean H; + protected boolean justCreated; + protected boolean fireProof; + protected DataWatcher datawatcher; + protected boolean ak; + protected int al; + protected BlockPosition an; + protected Vec3D ao; + protected EnumDirection ap; + protected UUID uniqueID; + // CraftBukkit start + protected CraftEntity bukkitEntity; + protected int potential = 1; + int numCollisions = 0; // Spigot + private int id; + private boolean g; + private int h; + private double ar; + private double as; + private boolean invulnerable; + protected boolean sendKnockbackRespawn; // Azurite + public final Random random; + + // Beanes - toggleable collision + public boolean collidable = true; + public boolean disableKnockback = false; + public boolean disableWaterMovement = false; + + // PandaSpigot start - Use shared random for entities + public static final Random SHARED_RANDOM = new Random() { + private boolean locked = false; + + @Override + public synchronized void setSeed(long seed) { + if (locked) { + MinecraftServer.LOGGER.error("Ignoring setSeed on Entity.SHARED_RANDOM", new Throwable()); + } else { + super.setSeed(seed); + locked = true; + } + } + }; + // PandaSpigot end + + public Entity(World world) { + this.id = Entity.entityCount++; + this.j = 1.0D; + this.boundingBox = Entity.a; + this.width = 0.6F; + this.length = 1.8F; + this.h = 1; + this.maxFireTicks = 1; + this.justCreated = true; + this.random = SHARED_RANDOM; + this.uniqueID = MathHelper.a(random); + this.au = new CommandObjectiveExecutor(); + this.world = world; + this.setPosition(0.0D, 0.0D, 0.0D); + if (world != null) { + this.dimension = world.worldProvider.getDimension(); + // Spigot start + this.defaultActivationState = org.spigotmc.ActivationRange.initializeEntityActivationState(this, world.spigotConfig); + } else { + this.defaultActivationState = false; + } + // Spigot end + + this.datawatcher = new DataWatcher(this); + this.datawatcher.a(0, (byte) 0); + this.datawatcher.a(1, (short) 300); + this.datawatcher.a(3, (byte) 0); + this.datawatcher.a(2, ""); + this.datawatcher.a(4, (byte) 0); + this.h(); + } + + static boolean isLevelAtLeast(NBTTagCompound tag, int level) { + return tag.hasKey("Bukkit.updateLevel") && tag.getInt("Bukkit.updateLevel") >= level; + } + + public int getH() { + return h; + } + + public void setH(int h) { + this.h = h; + } + + public boolean merge(Entity entity) { + return false; + } + + protected void respawn() { + } + + // PaperSpigot start - EAR: Fix bug with teleporting entities + public boolean isAddedToChunk() { + int chunkX = MathHelper.floor(locX / 16.0D); + int chunkY = MathHelper.floor(locY / 16.0D); + int chunkZ = MathHelper.floor(locZ / 16.0D); + + return ad && getChunkX() == chunkX && getChunkY() == chunkY || getChunkZ() == chunkZ; + } + + public int getChunkX() { + return ae; + } // PAIL + // Spigot end + + public int getChunkY() { + return af; + } // PAIL + + public int getChunkZ() { + return ag; + } // PAIL + + public void inactiveTick() { + } + + public int getId() { + return this.id; + } + + public void d(int i) { + this.id = i; + } + + public void G() { + this.die(); + } + + protected abstract void h(); + + public DataWatcher getDataWatcher() { + return this.datawatcher; + } + + public boolean equals(Object object) { + return object instanceof Entity && ((Entity) object).id == this.id; + } + + public int hashCode() { + return this.id; + } + + public void die() { + dead = true; + } + + public void setSize(float f, float f1) { + if (f != width || f1 != length) { + float f2 = width; + width = f; + length = f1; + a(new AxisAlignedBB(boundingBox.a, boundingBox.b, boundingBox.c, boundingBox.a + width, boundingBox.b + length, boundingBox.c + width)); + if (width > f2 && !justCreated) { + move((f2 - width), 0, (f2 - width)); + } + } + } + + protected void setYawPitch(float f, float f1) { + // CraftBukkit start - yaw was sometimes set to NaN, so we need to set it back to 0 + if (Float.isNaN(f)) { + f = 0; + } + + if (f == Float.POSITIVE_INFINITY || f == Float.NEGATIVE_INFINITY) { + if (this instanceof EntityPlayer) { + this.world.getServer().getLogger().warning(this.getName() + " was caught trying to crash the server with an invalid yaw"); + ((CraftPlayer) this.getBukkitEntity()).kickPlayer("Infinite yaw (Hacking?)"); //Spigot "Nope" -> Descriptive reason + } + f = 0; + } + + // pitch was sometimes set to NaN, so we need to set it back to 0 + if (Float.isNaN(f1)) { + f1 = 0; + } + + if (f1 == Float.POSITIVE_INFINITY || f1 == Float.NEGATIVE_INFINITY) { + if (this instanceof EntityPlayer) { + this.world.getServer().getLogger().warning(this.getName() + " was caught trying to crash the server with an invalid pitch"); + ((CraftPlayer) this.getBukkitEntity()).kickPlayer("Infinite pitch (Hacking?)"); //Spigot "Nope" -> Descriptive reason + } + f1 = 0; + } + // CraftBukkit end + + this.yaw = f % 360.0F; + this.pitch = f1 % 360.0F; + } + + public void setPosition(double d0, double d1, double d2) { + locX = d0; + locY = d1; + locZ = d2; + float f = width / 2.0F; + a(new AxisAlignedBB(d0 - f, d1, d2 - f, d0 + f, d1 + length, d2 + f)); + } + + public void t_() { + K(); + } + + /** + * PaperSpigot - Checks if the feature is enabled and the entity is above the nether world bedrock height + */ + private boolean paperNetherCheck() { + return this.world.paperSpigotConfig.netherVoidTopDamage && this.world.getWorld().getEnvironment() == org.bukkit.World.Environment.NETHER && this.locY >= 128.0D; + } + + public void K() { + if (vehicle != null && vehicle.dead) { + vehicle = null; + } + + L = M; + lastX = locX; + lastY = locY; + lastZ = locZ; + lastPitch = pitch; + lastYaw = yaw; + if (world instanceof WorldServer && !(this instanceof EntityProjectile || this instanceof EntityArrow)) { + if (ak) { + int i = L(); + + if (vehicle == null && al++ >= i) { + + al = i; + portalCooldown = aq(); + byte b0; + + if (this.world.worldProvider.getDimension() == -1) { + b0 = 0; + } else { + b0 = -1; + } + + c(b0); + } + + ak = false; + } else { + if (al > 0) { + al -= 4; + } + + if (al < 0) { + al = 0; + } + } + + if (portalCooldown > 0) { + --portalCooldown; + } + + } + Y(); + W(); + if (fireTicks > 0) { + if (fireProof) { + fireTicks -= 4; + if (fireTicks < 0) { + fireTicks = 0; + } + } else { + if (fireTicks % 20 == 0) { + damageEntity(DamageSource.BURN, 1.0F); + } + + --fireTicks; + } + } + + if (ab()) { + burnFromLava(); + fallDistance *= 0.5F; + } + + if (locY < -64.0D || paperNetherCheck()) { // PaperSpigot - Configurable top-of-nether void damage + O(); + } + + b(0, fireTicks > 0); + + justCreated = false; + + if (!(this instanceof EntityPlayer)) { + if (onGround || this.inLava || this.inWater) { + this.airTicks = 0; + } else { + this.airTicks++; + } + } + } + + public int L() { + return 0; + } + + protected void burnFromLava() { + if (!this.fireProof) { + this.damageEntity(DamageSource.LAVA, 4.0F); + + // CraftBukkit start - Fallen in lava TODO: this event spams! + if (this instanceof EntityLiving) { + if (fireTicks <= 0) { + // not on fire yet + org.bukkit.entity.Entity damagee = this.getBukkitEntity(); + EntityCombustEvent combustEvent = new org.bukkit.event.entity.EntityCombustByBlockEvent(null, damagee, 15); + this.world.getServer().getPluginManager().callEvent(combustEvent); + + if (!combustEvent.isCancelled()) { + this.setOnFire(combustEvent.getDuration()); + } + } else { + // This will be called every single tick the entity is in lava, so don't throw an event + this.setOnFire(15); + } + return; + } + // CraftBukkit end - we also don't throw an event unless the object in lava is living, to save on some event calls + this.setOnFire(15); + } + } + + public void setOnFire(int i) { + int j = i * 20; + + j = EnchantmentProtection.a(this, j); + if (fireTicks < j) { + fireTicks = j; + } + } + + public void extinguish() { + this.fireTicks = 0; + } + + protected void O() { + this.die(); + } + + public boolean c(double d0, double d1, double d2) { + return this.b(boundingBox.c(d0, d1, d2)); + } + + private boolean b(AxisAlignedBB axisalignedbb) { + return world.getCubes(this, axisalignedbb).isEmpty() && !this.world.containsLiquid(axisalignedbb); + } + + /** + * PaperSpigot - Load surrounding chunks the entity is moving through + */ + public void loadChunks() { + int chunkX = MathHelper.floor(locX) >> 4, chunkZ = MathHelper.floor(locZ) >> 4; + if (lastChunkX == chunkX && lastChunkZ == chunkZ) + return; + Chunk chunk; + if (this instanceof EntityTNTPrimed || this instanceof EntityFallingBlock) { + chunk = ((ChunkProviderServer) world.chunkProvider).getChunkAtWithoutCreation(chunkX, chunkZ); + } else { + chunk = ((ChunkProviderServer) world.chunkProvider).getChunkAt(chunkX, chunkZ); + } + lastChunk = chunk; + lastChunkX = chunkX; + lastChunkZ = chunkZ; + } + + public void move(double d0, double d1, double d2) { + if (loadChunks) + loadChunks(); + if (noclip) { + a(getBoundingBox().c(d0, d1, d2)); + recalcPosition(); + } else { + try { + checkBlockCollisions(); + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.a(throwable, "Checking entity block collision"); + CrashReportSystemDetails crashreportsystemdetails = crashreport.a("Entity being checked for collision"); + appendEntityCrashDetails(crashreportsystemdetails); + throw new ReportedException(crashreport); + } + + if (d0 == 0.0D && d1 == 0.0D && d2 == 0.0D && vehicle == null && passenger == null) + return; + + double d3 = locX; + double d4 = locY; + double d5 = locZ; + + if (H) { + H = false; + d0 *= 0.25D; + d1 *= 0.05000000074505806D; + d2 *= 0.25D; + motX = 0.0D; + motY = 0.0D; + motZ = 0.0D; + } + + double d6 = d0; + double d7 = d1; + double d8 = d2; + + boolean flag = onGround && isSneaking() && this instanceof EntityHuman; + if (flag) { + double d9; + for (d9 = 0.05D; d0 != 0.0D && world.isEmpty(this, getBoundingBox().c(d0, -1.0D, 0.0D)); d6 = d0) { + if (d0 < d9 && d0 >= -d9) { + d0 = 0.0D; + } else if (d0 > 0.0D) { + d0 -= d9; + } else { + d0 += d9; + } + } + for (; d2 != 0.0D && world.isEmpty(this, getBoundingBox().c(0.0D, -1.0D, d2)); d8 = d2) { + if (d2 < d9 && d2 >= -d9) { + d2 = 0.0D; + } else if (d2 > 0.0D) { + d2 -= d9; + } else { + d2 += d9; + } + } + for (; d0 != 0.0D && d2 != 0.0D && world.isEmpty(this, getBoundingBox().c(d0, -1.0D, d2)); d8 = d2) { + if (d0 < d9 && d0 >= -d9) { + d0 = 0.0D; + } else if (d0 > 0.0D) { + d0 -= d9; + } else { + d0 += d9; + } + d6 = d0; + if (d2 < d9 && d2 >= -d9) { + d2 = 0.0D; + } else if (d2 > 0.0D) { + d2 -= d9; + } else { + d2 += d9; + } + } + } + + List list = world.getCubes(this, getBoundingBox().a(d0, d1, d2)); + + AxisAlignedBB axisalignedbb = getBoundingBox(); + + AxisAlignedBB axisalignedbb2; + for (Iterator iterator = list.iterator(); iterator.hasNext(); d1 = axisalignedbb2.b(getBoundingBox(), d1)) + axisalignedbb2 = iterator.next(); + a(getBoundingBox().c(0.0D, d1, 0.0D)); + + boolean flag1 = !(!onGround && (d7 == d1 || d7 >= 0.0D)); + + Iterator iterator1; + for (iterator1 = list.iterator(); iterator1.hasNext(); d0 = axisalignedbb2.a(getBoundingBox(), d0)) + axisalignedbb2 = iterator1.next(); + a(getBoundingBox().c(d0, 0.0D, 0.0D)); + + for (iterator1 = list.iterator(); iterator1.hasNext(); d2 = axisalignedbb2.c(getBoundingBox(), d2)) + axisalignedbb2 = iterator1.next(); + a(getBoundingBox().c(0.0D, 0.0D, d2)); + + if (S > 0.0F && flag1 && (d6 != d0 || d8 != d2)) { + double d10 = d0; + double d11 = d1; + double d12 = d2; + AxisAlignedBB axisalignedbb3 = getBoundingBox(); + + a(axisalignedbb); + d1 = S; + List list1 = world.getCubes(this, getBoundingBox().a(d6, d1, d8)); + + AxisAlignedBB axisalignedbb4 = getBoundingBox(); + AxisAlignedBB axisalignedbb5 = axisalignedbb4.a(d6, 0.0D, d8); + + double d13 = d1; + AxisAlignedBB axisalignedbb6; + for (Iterator iterator2 = list1.iterator(); iterator2.hasNext(); d13 = axisalignedbb6.b(axisalignedbb5, d13)) + axisalignedbb6 = iterator2.next(); + axisalignedbb4 = axisalignedbb4.c(0.0D, d13, 0.0D); + + double d14 = d6; + AxisAlignedBB axisalignedbb7; + for (Iterator iterator3 = list1.iterator(); iterator3.hasNext(); d14 = axisalignedbb7.a(axisalignedbb4, d14)) + axisalignedbb7 = iterator3.next(); + axisalignedbb4 = axisalignedbb4.c(d14, 0.0D, 0.0D); + + double d15 = d8; + AxisAlignedBB axisalignedbb8; + for (Iterator iterator4 = list1.iterator(); iterator4.hasNext(); d15 = axisalignedbb8.c(axisalignedbb4, d15)) + axisalignedbb8 = iterator4.next(); + axisalignedbb4 = axisalignedbb4.c(0.0D, 0.0D, d15); + AxisAlignedBB axisalignedbb9 = getBoundingBox(); + + double d16 = d1; + AxisAlignedBB axisalignedbb10; + for (Iterator iterator5 = list1.iterator(); iterator5.hasNext(); d16 = axisalignedbb10.b(axisalignedbb9, d16)) + axisalignedbb10 = iterator5.next(); + axisalignedbb9 = axisalignedbb9.c(0.0D, d16, 0.0D); + + double d17 = d6; + AxisAlignedBB axisalignedbb11; + for (Iterator iterator6 = list1.iterator(); iterator6.hasNext(); d17 = axisalignedbb11.a(axisalignedbb9, d17)) + axisalignedbb11 = iterator6.next(); + axisalignedbb9 = axisalignedbb9.c(d17, 0.0D, 0.0D); + + double d18 = d8; + AxisAlignedBB axisalignedbb12; + for (Iterator iterator7 = list1.iterator(); iterator7.hasNext(); d18 = axisalignedbb12.c(axisalignedbb9, d18)) + axisalignedbb12 = iterator7.next(); + axisalignedbb9 = axisalignedbb9.c(0.0D, 0.0D, d18); + + if (d14 * d14 + d15 * d15 > d17 * d17 + d18 * d18) { + d0 = d14; + d2 = d15; + d1 = -d13; + a(axisalignedbb4); + } else { + d0 = d17; + d2 = d18; + d1 = -d16; + a(axisalignedbb9); + } + + AxisAlignedBB axisalignedbb13; + for (Iterator iterator8 = list1.iterator(); iterator8.hasNext(); d1 = axisalignedbb13.b(getBoundingBox(), d1)) + axisalignedbb13 = iterator8.next(); + a(getBoundingBox().c(0.0D, d1, 0.0D)); + + if (d10 * d10 + d12 * d12 >= d0 * d0 + d2 * d2) { + d0 = d10; + d1 = d11; + d2 = d12; + a(axisalignedbb3); + } + } + + recalcPosition(); + positionChanged = !(d6 == d0 && d8 == d2); + E = (d7 != d1); + onGround = (E && d7 < 0.0D); + F = !(!positionChanged && !E); + + BlockPosition blockposition = new BlockPosition(MathHelper.floor(locX), MathHelper.floor(locY - 0.20000000298023224D), MathHelper.floor(locZ)); + Block block = world.getType(blockposition).getBlock(); + if (block.getMaterial() == Material.AIR) { + Block block1 = world.getType(blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()).getBlock(); + if (block1 instanceof BlockFence || block1 instanceof BlockCobbleWall || block1 instanceof BlockFenceGate) { + block = block1; + blockposition.setY(blockposition.getY() - 1); + } + } + + a(d1, onGround, block, blockposition); + if (d6 != d0) + motX = 0.0D; + if (d8 != d2) + motZ = 0.0D; + if (d7 != d1) + block.a(world, this); + + if (positionChanged && getBukkitEntity() instanceof Vehicle) { + org.bukkit.block.Block bl = world.getWorld().getBlockAt(MathHelper.floor(locX), MathHelper.floor(locY), MathHelper.floor(locZ)); + if (d6 > d0) { + bl = bl.getRelative(BlockFace.EAST); + } else if (d6 < d0) { + bl = bl.getRelative(BlockFace.WEST); + } else if (d8 > d2) { + bl = bl.getRelative(BlockFace.SOUTH); + } else if (d8 < d2) { + bl = bl.getRelative(BlockFace.NORTH); + } + VehicleBlockCollisionEvent event = new VehicleBlockCollisionEvent((Vehicle) getBukkitEntity(), bl); + world.getServer().getPluginManager().callEvent(event); + } + + // Beanes - don't send footstep sounds if player on move() because we emulate it ourselves in packet handling which is more "true" state + if (s_() && !flag && vehicle == null && !(this instanceof EntityPlayer)) { + double d21 = locX - d3; + double d22 = locY - d4; + double d23 = locZ - d5; + + if (block != Blocks.LADDER) + d22 = 0.0D; + + M = (float) (M + MathHelper.sqrt(d21 * d21 + d23 * d23) * 0.6D); + N = (float) (N + MathHelper.sqrt(d21 * d21 + d22 * d22 + d23 * d23) * 0.6D); + if (N > h && block.getMaterial() != Material.AIR) { + h = (int) N + 1; + + if (V()) { + float f = MathHelper.sqrt(motX * motX * 0.20000000298023224D + motY * motY + motZ * motZ * 0.20000000298023224D) * 0.35F; + if (f > 1.0F) + f = 1.0F; + makeSound(P(), f, 1.0F + (random.nextFloat() - random.nextFloat()) * 0.4F); + } + + a(blockposition, block); + + block.a(world, blockposition, this); + } + } + + boolean flag2 = U(); + if (world.e(getBoundingBox().shrink(0.001D, 0.001D, 0.001D))) { + burn(1.0F); + if (!flag2) { + fireTicks++; + if (fireTicks <= 0) { + EntityCombustEvent event = new EntityCombustEvent(getBukkitEntity(), 8); + world.getServer().getPluginManager().callEvent(event); + if (!event.isCancelled()) + setOnFire(event.getDuration()); + } else { + setOnFire(8); + } + } + } else if (fireTicks <= 0) { + fireTicks = -maxFireTicks; + } + + if (flag2 && fireTicks > 0) { + makeSound("random.fizz", 0.7F, 1.6F + (random.nextFloat() - random.nextFloat()) * 0.4F); + fireTicks = -maxFireTicks; + } + + } + } + + protected void recalcPosition() { + locX = (boundingBox.a + boundingBox.d) / 2.0D; + locY = boundingBox.b; + locZ = (boundingBox.c + boundingBox.f) / 2.0D; + } + + protected String P() { + return "game.neutral.swim"; + } + + protected void checkBlockCollisions() { + // Vortex - prevent tries of blocks colliding under 0 and 256 height + int startX = MathHelper.floor(boundingBox.a + 0.001), + startY = Math.max(Math.min(MathHelper.floor(boundingBox.b + 0.001), 256), 0), + startZ = MathHelper.floor(boundingBox.c + 0.001), + endX = MathHelper.floor(boundingBox.d - 0.001), + endY = Math.max(Math.min(MathHelper.floor(boundingBox.e - 0.001), 256), 0), + endZ = MathHelper.floor(boundingBox.f - 0.001); + + double currentX = locX, currentY = locY, currentZ = locZ; + World currentWorld = world; + + // Vortex - fixed chunk loading + if (loadChunks || world.areChunksLoadedBetween(startX, startY, startZ, endX, endY, endZ)) { + for (int x = startX; x <= endX; ++x) { + for (int y = startY; y <= endY; ++y) { + for (int z = startZ; z <= endZ; ++z) { + + // Vortex - cache chunks + int chunkX = x >> 4, chunkZ = z >> 4; + if (lastChunkX != chunkX || lastChunkZ != chunkZ || lastChunk == null || lastCollisionTick != MinecraftServer.currentTick) { + lastCollisionTick = MinecraftServer.currentTick; + lastChunkX = chunkX; + lastChunkZ = chunkZ; + lastChunk = loadChunks ? world.getChunkAt(lastChunkX, lastChunkZ) : world.getChunkIfLoaded(lastChunkX, lastChunkZ); + } + + IBlockData iblockdata = lastChunk.getBlockData(x, y, z); + try { + iblockdata.getBlock().a(world, new BlockPosition(x, y, z), iblockdata, this); + + // Vortex - prevent colliding other blocks if entity has teleported to different location + if (currentWorld != world || currentX != locX || currentY != locY || currentZ != locZ) + return; + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.a(throwable, "Colliding entity with block"); + CrashReportSystemDetails crashreportsystemdetails = crashreport.a("Block being collided with"); + CrashReportSystemDetails.a(crashreportsystemdetails, null, iblockdata); + throw new ReportedException(crashreport); + } + } + } + } + } + } + + protected void a(BlockPosition blockposition, Block block) { + a(blockposition.getX(), blockposition.getY(), blockposition.getZ(), block); + } + + protected void a(int x, int y, int z, Block block) { + if (!AzuriteConfig.footstepSounds.getValue()) return; + Block.StepSound block_stepsound = block.stepSound; + if (world.getType(x, y + 1, z).getBlock() == Blocks.SNOW_LAYER) { + block_stepsound = Blocks.SNOW_LAYER.stepSound; + makeSound(block_stepsound.getStepSound(), block_stepsound.getVolume1() * 0.15F, block_stepsound.getVolume2()); + } else if (!block.getMaterial().isLiquid()) { + makeSound(block_stepsound.getStepSound(), block_stepsound.getVolume1() * 0.15F, block_stepsound.getVolume2()); + } + } + + public void makeSound(String s, float f, float f1) { + this.makeSound(s, f, f1, false); + } + + public void makeSound(String s, float f, float f1, boolean self) { + if (!this.R()) { + this.world.makeSound(this, s, f, f1, self); + } + } + + public boolean R() { + return this.datawatcher.getByte(4) == 1; + } + + public void b(boolean flag) { + this.datawatcher.watch(4, (byte) (flag ? 1 : 0)); + } + + protected boolean s_() { + return true; + } + + protected void a(double d0, boolean flag, Block block, BlockPosition blockposition) { + if (flag) { + if (this.fallDistance > 0.0F) { + if (block != null) { + block.fallOn(this.world, blockposition, this, this.fallDistance); + } else { + this.e(this.fallDistance, 1.0F); + } + + this.fallDistance = 0.0F; + } + } else if (d0 < 0.0D) { + this.fallDistance = (float) ((double) this.fallDistance - d0); + } + + } + + public AxisAlignedBB S() { + return null; + } + + protected void burn(float i) { // CraftBukkit - int -> float + if (!this.fireProof) { + this.damageEntity(DamageSource.FIRE, i); + } + } + + public final boolean isFireProof() { + return this.fireProof; + } + + public void e(float f, float f1) { + if (this.passenger != null) { + this.passenger.e(f, f1); + } + } + + public boolean U() { + int x = MathHelper.floor(locX), y = MathHelper.floor(locY), z = MathHelper.floor(locZ); + return inWater || world.isRainingAt(x, y, z) || world.isRainingAt(x, MathHelper.floor(y + length), z); + } + + public boolean V() { + return inWater; + } + + public boolean W() { + if (!disableWaterMovement && world.a(boundingBox.grow(0.0D, -0.4000000059604645D, 0.0D).shrink(0.001D, 0.001D, 0.001D), Material.WATER, this)) { + fallDistance = 0.0F; + inWater = true; + fireTicks = 0; + } else { + inWater = false; + } + return inWater; + } + + protected void X() { + float f = MathHelper.sqrt(this.motX * this.motX * 0.20000000298023224D + this.motY * this.motY + this.motZ * this.motZ * 0.20000000298023224D) * 0.2F; + + if (f > 1.0F) { + f = 1.0F; + } + + this.makeSound(this.aa(), f, 1.0F + (random.nextFloat() - random.nextFloat()) * 0.4F); + float f1 = (float) MathHelper.floor(this.boundingBox.b); + + int i; + float f2; + float f3; + + for (i = 0; (float) i < 1.0F + this.width * 20.0F; ++i) { + f2 = (random.nextFloat() * 2.0F - 1.0F) * this.width; + f3 = (random.nextFloat() * 2.0F - 1.0F) * this.width; + this.world.addParticle(EnumParticle.WATER_BUBBLE, this.locX + f2, (f1 + 1.0F), this.locZ + f3, this.motX, this.motY - (double) (random.nextFloat() * 0.2F), this.motZ, EnumParticle.EMPTY_ARRAY); + } + + for (i = 0; (float) i < 1.0F + this.width * 20.0F; ++i) { + f2 = (random.nextFloat() * 2.0F - 1.0F) * this.width; + f3 = (random.nextFloat() * 2.0F - 1.0F) * this.width; + this.world.addParticle(EnumParticle.WATER_SPLASH, this.locX + f2, (f1 + 1.0F), this.locZ + f3, this.motX, this.motY, this.motZ, EnumParticle.EMPTY_ARRAY); + } + + } + + public void Y() { + if (AzuriteConfig.footstepParticles.getValue() && isSprinting() && !V()) { + Z(); + } + } + + protected void Z() { + int i = MathHelper.floor(this.locX); + int j = MathHelper.floor(this.locY - 0.20000000298023224D); + int k = MathHelper.floor(this.locZ); + IBlockData iblockdata = this.world.getType(i, j, k); + Block block = iblockdata.getBlock(); + + if (block.b() != -1) { + this.world.addParticle(EnumParticle.BLOCK_CRACK, this.locX + (random.nextFloat() - 0.5D) * this.width, this.boundingBox.b + 0.1D, this.locZ + (random.nextFloat() - 0.5D) * this.width, -this.motX * 4.0D, 1.5D, -this.motZ * 4.0D, Block.getCombinedId(iblockdata)); + } + } + + protected String aa() { + return "game.neutral.swim.splash"; + } + + public boolean a(Material material) { + double d0 = locY + getHeadHeight(); + IBlockData iblockdata = this.world.getType(MathHelper.floor(locX), MathHelper.floor(d0), MathHelper.floor(locZ)); + if (iblockdata.getBlock().getMaterial() == material) { + return (d0 < (MathHelper.floor(d0) + 1) - (BlockFluids.b(iblockdata.getBlock().toLegacyData(iblockdata)) - 0.11111111F)); + } + return false; + } + + public boolean ab() { + return ab(this.world); + } + + public boolean ab(IBlockAccess iblockaccess) { + int currentTick = MinecraftServer.currentTick; + if (lastLavaTick != currentTick) { + lastLavaTick = currentTick; + inLava = this.world.a(iblockaccess, this.getBoundingBox().grow(-0.10000000149011612D, -0.4000000059604645D, -0.10000000149011612D), Material.LAVA); + } + return inLava; + } + + public void a(float f, float f1, float f2) { + float f3 = f * f + f1 * f1; + + if (f3 >= 1.0E-4F) { + f3 = MathHelper.c(f3); + if (f3 < 1.0F) { + f3 = 1.0F; + } + + f3 = f2 / f3; + f *= f3; + f1 *= f3; + float f4 = MathHelper.sin(this.yaw * 3.1415927F / 180.0F); + float f5 = MathHelper.cos(this.yaw * 3.1415927F / 180.0F); + + this.motX += f * f5 - f1 * f4; + this.motZ += (f1 * f5 + f * f4); + } + } + + public float c(float f) { + int x = MathHelper.floor(locX), y = MathHelper.floor(locY + getHeadHeight()), z = MathHelper.floor(locZ); + + return this.world.isLoaded(x, y, z) ? this.world.o(x, y, z) : 0.0F; + } + + public void spawnIn(World world) { + // CraftBukkit start + if (world == null) { + die(); + this.world = ((CraftWorld) Bukkit.getServer().getWorlds().get(0)).getHandle(); + return; + } + // CraftBukkit end + this.world = world; + } + + public void setLocation(double d0, double d1, double d2, float f, float f1) { + this.lastX = this.locX = d0; + this.lastY = this.locY = d1; + this.lastZ = this.locZ = d2; + this.lastYaw = this.yaw = f; + this.lastPitch = this.pitch = f1; + double d3 = (this.lastYaw - f); + + if (d3 < -180.0D) { + this.lastYaw += 360.0F; + } + + if (d3 >= 180.0D) { + this.lastYaw -= 360.0F; + } + + setPosition(locX, locY, locZ); + setYawPitch(f, f1); + } + + public void setPositionRotation(BlockPosition blockposition, float f, float f1) { + this.setPositionRotation(blockposition.getX() + 0.5D, blockposition.getY(), blockposition.getZ() + 0.5D, f, f1); + } + + public void setPositionRotation(double d0, double d1, double d2, float f, float f1) { + this.P = this.lastX = this.locX = d0; + this.Q = this.lastY = this.locY = d1; + this.R = this.lastZ = this.locZ = d2; + this.yaw = f; + this.pitch = f1; + this.setPosition(this.locX, this.locY, this.locZ); + } + + public float g(Entity entity) { + float f = (float) (this.locX - entity.locX); + float f1 = (float) (this.locY - entity.locY); + float f2 = (float) (this.locZ - entity.locZ); + + return MathHelper.c(f * f + f1 * f1 + f2 * f2); + } + + public double e(double d0, double d1, double d2) { + double d3 = this.locX - d0; + double d4 = this.locY - d1; + double d5 = this.locZ - d2; + + return d3 * d3 + d4 * d4 + d5 * d5; + } + + public double b(BlockPosition blockposition) { + return blockposition.c(this.locX, this.locY, this.locZ); + } + + public double c(BlockPosition blockposition) { + return blockposition.d(this.locX, this.locY, this.locZ); + } + + public double f(double d0, double d1, double d2) { + double d3 = this.locX - d0; + double d4 = this.locY - d1; + double d5 = this.locZ - d2; + + return MathHelper.sqrt(d3 * d3 + d4 * d4 + d5 * d5); + } + + public double h(Entity entity) { + double d0 = this.locX - entity.locX; + double d1 = this.locY - entity.locY; + double d2 = this.locZ - entity.locZ; + + return d0 * d0 + d1 * d1 + d2 * d2; + } + + public void d(EntityHuman entityhuman) { + } + + public void collide(Entity entity) { + // Beanes - toggleable collisions + if (!collidable) { + return; + } + + if (entity.passenger != this && entity.vehicle != this) { + if (!entity.noclip && !this.noclip) { + double d0 = entity.locX - this.locX; + double d1 = entity.locZ - this.locZ; + double d2 = MathHelper.a(d0, d1); + + if (d2 >= 0.009999999776482582D) { + d2 = MathHelper.sqrt(d2); + d0 /= d2; + d1 /= d2; + double d3 = 1.0D / d2; + + if (d3 > 1.0D) { + d3 = 1.0D; + } + + d0 *= d3; + d1 *= d3; + d0 *= 0.05000000074505806D; + d1 *= 0.05000000074505806D; + d0 *= (1.0F - this.U); + d1 *= (1.0F - this.U); + if (this.passenger == null) { + this.g(-d0, 0.0D, -d1); + } + + if (entity.passenger == null) { + entity.g(d0, 0.0D, d1); + } + } + + } + } + } + + public void g(double d0, double d1, double d2) { + if (disableKnockback) // Rivals + return; + motX += d0; + motY += d1; + motZ += d2; + ai = true; + } + + protected void ac() { + velocityChanged = true; + } + + public boolean damageEntity(DamageSource damagesource, float f) { + if (!isInvulnerable(damagesource)) + ac(); + return false; + } + + public Vec3D d(float f) { + if (f == 1.0F) { + return this.f(this.pitch, this.yaw); + } else { + float f1 = this.lastPitch + (this.pitch - this.lastPitch) * f; + float f2 = this.lastYaw + (this.yaw - this.lastYaw) * f; + + return this.f(f1, f2); + } + } + + protected final Vec3D f(float f, float f1) { + float f2 = MathHelper.cos(-f1 * 0.017453292F - 3.1415927F); + float f3 = MathHelper.sin(-f1 * 0.017453292F - 3.1415927F); + float f4 = -MathHelper.cos(-f * 0.017453292F); + float f5 = MathHelper.sin(-f * 0.017453292F); + + return new Vec3D((f3 * f4), f5, (f2 * f4)); + } + + public boolean ad() { + return false; + } + + public boolean ae() { + return false; + } + + public void b(Entity entity, int i) { + } + + public boolean c(NBTTagCompound nbttagcompound) { + String s = this.ag(); + + if (!this.dead && s != null) { + nbttagcompound.setString("id", s); + this.e(nbttagcompound); + return true; + } else { + return false; + } + } + + public boolean d(NBTTagCompound nbttagcompound) { + String s = this.ag(); + + if (!this.dead && s != null && this.passenger == null) { + nbttagcompound.setString("id", s); + this.e(nbttagcompound); + return true; + } else { + return false; + } + } + + public void e(NBTTagCompound nbttagcompound) { + try { + nbttagcompound.set("Pos", this.a(this.locX, this.locY, this.locZ)); + nbttagcompound.set("Motion", this.a(this.motX, this.motY, this.motZ)); + nbttagcompound.set("Spawn", this.a(this.spawnX, this.spawnY, this.spawnZ)); + // CraftBukkit start - Checking for NaN pitch/yaw and resetting to zero + // TODO: make sure this is the best way to address this. + if (Float.isNaN(this.yaw)) { + this.yaw = 0; + } + + if (Float.isNaN(this.pitch)) { + this.pitch = 0; + } + // CraftBukkit end + + nbttagcompound.set("Rotation", this.a(this.yaw, this.pitch)); + nbttagcompound.setFloat("FallDistance", this.fallDistance); + nbttagcompound.setShort("Fire", (short) this.fireTicks); + nbttagcompound.setShort("Air", (short) this.getAirTicks()); + nbttagcompound.setBoolean("OnGround", this.onGround); + nbttagcompound.setInt("Dimension", this.dimension); + nbttagcompound.setBoolean("Invulnerable", this.invulnerable); + nbttagcompound.setInt("PortalCooldown", this.portalCooldown); + nbttagcompound.setLong("UUIDMost", this.getUniqueID().getMostSignificantBits()); + nbttagcompound.setLong("UUIDLeast", this.getUniqueID().getLeastSignificantBits()); + // CraftBukkit start + nbttagcompound.setLong("WorldUUIDLeast", this.world.getDataManager().getUUID().getLeastSignificantBits()); + nbttagcompound.setLong("WorldUUIDMost", this.world.getDataManager().getUUID().getMostSignificantBits()); + nbttagcompound.setInt("Bukkit.updateLevel", CURRENT_LEVEL); + nbttagcompound.setInt("Spigot.ticksLived", this.ticksLived); + // CraftBukkit end + if (this.getCustomName() != null && !this.getCustomName().isEmpty()) { + nbttagcompound.setString("CustomName", this.getCustomName()); + nbttagcompound.setBoolean("CustomNameVisible", this.getCustomNameVisible()); + } + + this.au.b(nbttagcompound); + if (this.R()) { + nbttagcompound.setBoolean("Silent", this.R()); + } + + this.b(nbttagcompound); + if (this.vehicle != null) { + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + + if (this.vehicle.c(nbttagcompound1)) { + nbttagcompound.set("Riding", nbttagcompound1); + } + } + + if (spawnReason != null) { + nbttagcompound.setString("Paper.SpawnReason", spawnReason.name()); + } + + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.a(throwable, "Saving entity NBT"); + CrashReportSystemDetails crashreportsystemdetails = crashreport.a("Entity being saved"); + + this.appendEntityCrashDetails(crashreportsystemdetails); + throw new ReportedException(crashreport); + } + } + + public void f(NBTTagCompound nbttagcompound) { + try { + NBTTagList nbttaglist = nbttagcompound.getList("Pos", 6); + NBTTagList nbttaglist1 = nbttagcompound.getList("Motion", 6); + NBTTagList nbttaglist2 = nbttagcompound.getList("Rotation", 5); + NBTTagList nbttaglist3 = nbttagcompound.getList("Spawn", 6); + + this.spawnX = nbttaglist3.d(0); + this.spawnY = nbttaglist3.d(1); + this.spawnZ = nbttaglist3.d(2); + + this.motX = nbttaglist1.d(0); + this.motY = nbttaglist1.d(1); + this.motZ = nbttaglist1.d(2); + + this.lastX = this.P = this.locX = nbttaglist.d(0); + this.lastY = this.Q = this.locY = nbttaglist.d(1); + this.lastZ = this.R = this.locZ = nbttaglist.d(2); + this.lastYaw = this.yaw = nbttaglist2.e(0); + this.lastPitch = this.pitch = nbttaglist2.e(1); + this.f(this.yaw); + this.g(this.yaw); + this.fallDistance = nbttagcompound.getFloat("FallDistance"); + this.fireTicks = nbttagcompound.getShort("Fire"); + this.setAirTicks(nbttagcompound.getShort("Air")); + this.onGround = nbttagcompound.getBoolean("OnGround"); + this.dimension = nbttagcompound.getInt("Dimension"); + this.invulnerable = nbttagcompound.getBoolean("Invulnerable"); + this.portalCooldown = nbttagcompound.getInt("PortalCooldown"); + if (nbttagcompound.hasKeyOfType("UUIDMost", 4) && nbttagcompound.hasKeyOfType("UUIDLeast", 4)) { + this.uniqueID = new UUID(nbttagcompound.getLong("UUIDMost"), nbttagcompound.getLong("UUIDLeast")); + } else if (nbttagcompound.hasKeyOfType("UUID", 8)) { + this.uniqueID = FastUUID.parseUUID(nbttagcompound.getString("UUID")); + } + + this.setPosition(this.locX, this.locY, this.locZ); + this.setYawPitch(this.yaw, this.pitch); + if (nbttagcompound.hasKeyOfType("CustomName", 8) && !nbttagcompound.getString("CustomName").isEmpty()) { + this.setCustomName(nbttagcompound.getString("CustomName")); + } + + this.setCustomNameVisible(nbttagcompound.getBoolean("CustomNameVisible")); + this.au.a(nbttagcompound); + this.b(nbttagcompound.getBoolean("Silent")); + this.a(nbttagcompound); + if (this.af()) { + this.setPosition(this.locX, this.locY, this.locZ); + } + + // CraftBukkit start + if (this instanceof EntityLiving) { + EntityLiving entity = (EntityLiving) this; + + this.ticksLived = nbttagcompound.getInt("Spigot.ticksLived"); + + // Reset the persistence for tamed animals + if (entity instanceof EntityTameableAnimal && !isLevelAtLeast(nbttagcompound, 2) && !nbttagcompound.getBoolean("PersistenceRequired")) { + EntityInsentient entityinsentient = (EntityInsentient) entity; + entityinsentient.persistent = !entityinsentient.isTypeNotPersistent(); + } + } + // CraftBukkit end + + // CraftBukkit start - Exempt Vehicles from notch's sanity check + if (!(getBukkitEntity() instanceof Vehicle)) { + if (Math.abs(this.motX) > 10.0D) { + this.motX = 0.0D; + } + + if (Math.abs(this.motY) > 10.0D) { + this.motY = 0.0D; + } + + if (Math.abs(this.motZ) > 10.0D) { + this.motZ = 0.0D; + } + } + // CraftBukkit end + + // CraftBukkit start - Reset world + if (this instanceof EntityPlayer) { + Server server = Bukkit.getServer(); + org.bukkit.World bworld; + + // TODO: Remove World related checks, replaced with WorldUID + String worldName = nbttagcompound.getString("world"); + + if (nbttagcompound.hasKey("WorldUUIDMost") && nbttagcompound.hasKey("WorldUUIDLeast")) { + UUID uid = new UUID(nbttagcompound.getLong("WorldUUIDMost"), nbttagcompound.getLong("WorldUUIDLeast")); + bworld = server.getWorld(uid); + } else { + bworld = server.getWorld(worldName); + } + + if (bworld == null) { + EntityPlayer entityPlayer = (EntityPlayer) this; + bworld = ((org.bukkit.craftbukkit.CraftServer) server).getServer().getWorldServer(entityPlayer.dimension).getWorld(); + } + + spawnIn(bworld == null ? null : ((CraftWorld) bworld).getHandle()); + } + // CraftBukkit end + + // Azurite - Backport paper world entity list + if (nbttagcompound.hasKey("Paper.SpawnReason")) { + String spawnReasonName = nbttagcompound.getString("Paper.SpawnReason"); + try { + spawnReason = org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.valueOf(spawnReasonName); + } catch (Exception ignored) { + LogManager.getLogger().error("Unknown SpawnReason {} for {}", spawnReasonName, this); + } + } + if (spawnReason == null) { + if (this instanceof EntityInsentient && this instanceof IAnimal && !((EntityInsentient) this).isTypeNotPersistent()) { + if (!nbttagcompound.getBoolean("PersistenceRequired")) { + spawnReason = org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.NATURAL; + } + } + } + if (spawnReason == null) { + spawnReason = org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.DEFAULT; + } + + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.a(throwable, "Loading entity NBT"); + CrashReportSystemDetails crashreportsystemdetails = crashreport.a("Entity being loaded"); + + this.appendEntityCrashDetails(crashreportsystemdetails); + throw new ReportedException(crashreport); + } + } + + protected boolean af() { + return true; + } + + protected final String ag() { + return EntityTypes.b(this); + } + + protected abstract void a(NBTTagCompound nbttagcompound); + + protected abstract void b(NBTTagCompound nbttagcompound); + + public void ah() { + } + + protected NBTTagList a(double... adouble) { + NBTTagList nbttaglist = new NBTTagList(); + for (double d0 : adouble) { + nbttaglist.add(new NBTTagDouble(d0)); + } + return nbttaglist; + } + + protected NBTTagList a(float... afloat) { + NBTTagList nbttaglist = new NBTTagList(); + + for (float d0 : afloat) { + nbttaglist.add(new NBTTagFloat(d0)); + } + return nbttaglist; + } + + public EntityItem a(Item item, int i) { + return this.a(item, i, 0.0F); + } + + public EntityItem a(Item item, int i, float f) { + return this.a(new ItemStack(item, i, 0), f); + } + + public EntityItem a(ItemStack itemstack, float f) { + if (itemstack.count != 0 && itemstack.getItem() != null) { + // CraftBukkit start - Capture drops for death event + if (this instanceof EntityLiving && ((EntityLiving) this).drops != null) { + ((EntityLiving) this).drops.add(org.bukkit.craftbukkit.inventory.CraftItemStack.asBukkitCopy(itemstack)); + return null; + } + // CraftBukkit end + EntityItem entityitem = new EntityItem(this.world, this.locX, this.locY + (double) f, this.locZ, itemstack); + + entityitem.p(); + this.world.addEntity(entityitem); + return entityitem; + } else { + return null; + } + } + + public boolean isAlive() { + return !this.dead; + } + + public boolean inBlock() { + if (!this.noclip) { + BlockPosition.MutableBlockPosition blockposition_mutableblockposition = new BlockPosition.MutableBlockPosition(Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE); + + for (int i = 0; i < 8; ++i) { + int j = MathHelper.floor(this.locY + (double) (((float) ((i) % 2) - 0.5F) * 0.1F) + (double) this.getHeadHeight()); + int k = MathHelper.floor(this.locX + (double) (((float) ((i >> 1) % 2) - 0.5F) * this.width * 0.8F)); + int l = MathHelper.floor(this.locZ + (double) (((float) ((i >> 2) % 2) - 0.5F) * this.width * 0.8F)); + + if (blockposition_mutableblockposition.getX() != k || blockposition_mutableblockposition.getY() != j || blockposition_mutableblockposition.getZ() != l) { + blockposition_mutableblockposition.c(k, j, l); + if (this.world.getType(blockposition_mutableblockposition).getBlock().w()) { + return true; + } + } + } + + } + return false; + } + + public boolean e(EntityHuman entityhuman) { + return false; + } + + public AxisAlignedBB j(Entity entity) { + return null; + } + + public void ak() { + if (this.vehicle.dead) { + this.vehicle = null; + } else { + this.motX = 0.0D; + this.motY = 0.0D; + this.motZ = 0.0D; + this.t_(); + if (this.vehicle != null) { + this.vehicle.al(); + this.as += (this.vehicle.yaw - this.vehicle.lastYaw); + + for (this.ar += (this.vehicle.pitch - this.vehicle.lastPitch); this.as >= 180.0D; this.as -= 360.0D) { + + } + + while (this.as < -180.0D) { + this.as += 360.0D; + } + + while (this.ar >= 180.0D) { + this.ar -= 360.0D; + } + + while (this.ar < -180.0D) { + this.ar += 360.0D; + } + + double d0 = this.as * 0.5D; + double d1 = this.ar * 0.5D; + float f = 10.0F; + + if (d0 > f) { + d0 = f; + } + + if (d0 < -f) { + d0 = (-f); + } + + if (d1 > f) { + d1 = f; + } + + if (d1 < -f) { + d1 = -f; + } + + this.as -= d0; + this.ar -= d1; + } + } + } + + public void al() { + if (this.passenger != null) { + this.passenger.setPosition(this.locX, this.locY + this.an() + this.passenger.am(), this.locZ); + } + } + + public double am() { + return 0.0D; + } + + public double an() { + return (double) this.length * 0.75D; + } + + public CraftEntity getBukkitEntity() { + if (bukkitEntity == null) { + bukkitEntity = CraftEntity.getEntity(world.getServer(), this); + } + return bukkitEntity; + } + + public void mount(Entity entity) { + Entity originalVehicle = this.vehicle; + Entity originalPassenger = this.vehicle == null ? null : this.vehicle.passenger; + PluginManager pluginManager = Bukkit.getPluginManager(); + getBukkitEntity(); // make sure bukkitEntity is initialised + // CraftBukkit end + this.ar = 0.0D; + this.as = 0.0D; + if (entity == null) { + if (this.vehicle != null) { + // CraftBukkit start + if ((this.bukkitEntity instanceof LivingEntity) && (this.vehicle.getBukkitEntity() instanceof Vehicle)) { + VehicleExitEvent event = new VehicleExitEvent((Vehicle) this.vehicle.getBukkitEntity(), (LivingEntity) this.bukkitEntity); + pluginManager.callEvent(event); + + if (event.isCancelled() || vehicle != originalVehicle) { + return; + } + } + // CraftBukkit end + // PaperSpigot start - make EntityDismountEvent cancellable + EntityDismountEvent dismountEvent = new EntityDismountEvent(this.getBukkitEntity(), this.vehicle.getBukkitEntity()); // Spigot + pluginManager.callEvent(dismountEvent); + if (dismountEvent.isCancelled()) return; + // PaperSpigot end + this.setPositionRotation(this.vehicle.locX, this.vehicle.boundingBox.b + (double) this.vehicle.length, this.vehicle.locZ, this.yaw, this.pitch); + this.vehicle.passenger = null; + } + + this.vehicle = null; + } else { + // CraftBukkit start + if ((this.bukkitEntity instanceof LivingEntity) && (entity.getBukkitEntity() instanceof Vehicle) && entity.world.isChunkLoaded(MathHelper.floor(entity.locX) >> 4, MathHelper.floor(entity.locZ) >> 4, true)) { + // It's possible to move from one vehicle to another. We need to check if they're already in a vehicle, and fire an exit event if they are. + VehicleExitEvent exitEvent = null; + if (this.vehicle != null && this.vehicle.getBukkitEntity() instanceof Vehicle) { + exitEvent = new VehicleExitEvent((Vehicle) this.vehicle.getBukkitEntity(), (LivingEntity) this.bukkitEntity); + pluginManager.callEvent(exitEvent); + + if (exitEvent.isCancelled() || this.vehicle != originalVehicle || (this.vehicle != null && this.vehicle.passenger != originalPassenger)) { + return; + } + } + + VehicleEnterEvent event = new VehicleEnterEvent((Vehicle) entity.getBukkitEntity(), this.bukkitEntity); + pluginManager.callEvent(event); + + // If a plugin messes with the vehicle or the vehicle's passenger + if (event.isCancelled() || this.vehicle != originalVehicle || (this.vehicle != null && this.vehicle.passenger != originalPassenger)) { + // If we only cancelled the enterevent then we need to put the player in a decent position. + if (exitEvent != null && this.vehicle == originalVehicle && this.vehicle != null && this.vehicle.passenger == originalPassenger) { + this.setPositionRotation(this.vehicle.locX, this.vehicle.boundingBox.b + (double) this.vehicle.length, this.vehicle.locZ, this.yaw, this.pitch); + this.vehicle.passenger = null; + this.vehicle = null; + } + return; + } + } + // CraftBukkit end + // Spigot Start + if (entity.world.isChunkLoaded(MathHelper.floor(entity.locX) >> 4, MathHelper.floor(entity.locZ) >> 4, true)) { + org.spigotmc.event.entity.EntityMountEvent event = new org.spigotmc.event.entity.EntityMountEvent(this.getBukkitEntity(), entity.getBukkitEntity()); + pluginManager.callEvent(event); + if (event.isCancelled()) { + return; + } + } + // Spigot End + + if (this.vehicle != null) { + this.vehicle.passenger = null; + } + + for (Entity entity1 = entity.vehicle; entity1 != null; entity1 = entity1.vehicle) { + if (entity1 == this) { + return; + } + } + + this.vehicle = entity; + entity.passenger = this; + } + } + + public float ao() { + return 0.1F; + } + + public Vec3D ap() { + return null; + } + + public void d(BlockPosition blockposition) { + if (this.portalCooldown > 0) { + this.portalCooldown = this.aq(); + } else { + if (!blockposition.equals(this.an)) { + this.an = blockposition; + ShapeDetector.ShapeDetectorCollection shapedetector_shapedetectorcollection = Blocks.PORTAL.f(this.world, blockposition); + double d0 = shapedetector_shapedetectorcollection.b().k() == EnumDirection.EnumAxis.X ? (double) shapedetector_shapedetectorcollection.a().getZ() : (double) shapedetector_shapedetectorcollection.a().getX(); + double d1 = shapedetector_shapedetectorcollection.b().k() == EnumDirection.EnumAxis.X ? this.locZ : this.locX; + + d1 = Math.abs(MathHelper.c(d1 - (shapedetector_shapedetectorcollection.b().e().c() == EnumDirection.EnumAxisDirection.NEGATIVE ? 1 : 0), d0, d0 - (double) shapedetector_shapedetectorcollection.d())); + double d2 = MathHelper.c(this.locY - 1.0D, shapedetector_shapedetectorcollection.a().getY(), (shapedetector_shapedetectorcollection.a().getY() - shapedetector_shapedetectorcollection.e())); + + this.ao = new Vec3D(d1, d2, 0.0D); + this.ap = shapedetector_shapedetectorcollection.b(); + } + + this.ak = true; + } + } + + public int aq() { + return 300; + } + + public ItemStack[] getEquipment() { + return null; + } + + public void setEquipment(int i, ItemStack itemstack) { + } + + public boolean isBurning() { + return !this.fireProof && this.fireTicks > 0; + } + + public boolean au() { + return this.vehicle != null; + } + + public boolean isSneaking() { + return this.g(1); + } + + public void setSneaking(boolean flag) { + this.b(1, flag); + } + + public boolean isSprinting() { + return this.g(3); + } + + public void setSprinting(boolean flag) { + this.b(3, flag); + } + + public boolean isInvisible() { + return this.g(5); + } + + public void setInvisible(boolean flag) { + this.b(5, flag); + } + + public void f(boolean flag) { + this.b(4, flag); + } + + protected boolean g(int i) { + return (this.datawatcher.getByte(0) & 1 << i) != 0; + } + + protected void b(int i, boolean flag) { + byte b0 = this.datawatcher.getByte(0); + + if (flag) { + this.datawatcher.watch(0, (byte) (b0 | 1 << i)); + } else { + this.datawatcher.watch(0, (byte) (b0 & ~(1 << i))); + } + + } + + public int getAirTicks() { + return this.datawatcher.getShort(1); + } + + public void setAirTicks(int i) { + this.datawatcher.watch(1, (short) i); + } + + public void onLightningStrike(EntityLightning entitylightning) { + // CraftBukkit start + final org.bukkit.entity.Entity thisBukkitEntity = this.getBukkitEntity(); + final org.bukkit.entity.Entity stormBukkitEntity = entitylightning.getBukkitEntity(); + final PluginManager pluginManager = Bukkit.getPluginManager(); + + if (thisBukkitEntity instanceof Hanging) { + HangingBreakByEntityEvent hangingEvent = new HangingBreakByEntityEvent((Hanging) thisBukkitEntity, stormBukkitEntity); + PaintingBreakByEntityEvent paintingEvent = null; + + if (thisBukkitEntity instanceof Painting) { + paintingEvent = new PaintingBreakByEntityEvent((Painting) thisBukkitEntity, stormBukkitEntity); + } + + pluginManager.callEvent(hangingEvent); + + if (paintingEvent != null) { + paintingEvent.setCancelled(hangingEvent.isCancelled()); + pluginManager.callEvent(paintingEvent); + } + + if (hangingEvent.isCancelled() || (paintingEvent != null && paintingEvent.isCancelled())) { + return; + } + } + + if (this.fireProof) { + return; + } + CraftEventFactory.entityDamage = entitylightning; + if (!this.damageEntity(DamageSource.LIGHTNING, 5.0F)) { + CraftEventFactory.entityDamage = null; + return; + } + // CraftBukkit end + ++this.fireTicks; + if (this.fireTicks == 0) { + // CraftBukkit start - Call a combust event when lightning strikes + EntityCombustByEntityEvent entityCombustEvent = new EntityCombustByEntityEvent(stormBukkitEntity, thisBukkitEntity, 8); + pluginManager.callEvent(entityCombustEvent); + if (!entityCombustEvent.isCancelled()) { + this.setOnFire(entityCombustEvent.getDuration()); + } + // CraftBukkit end + } + + } + + public void a(EntityLiving entityliving) { + } + + protected boolean j(double d0, double d1, double d2) { + BlockPosition blockposition = new BlockPosition(d0, d1, d2); + double d3 = d0 - (double) blockposition.getX(); + double d4 = d1 - (double) blockposition.getY(); + double d5 = d2 - (double) blockposition.getZ(); + List list = this.world.a(this.boundingBox); + + if (list.isEmpty() && !this.world.u(blockposition)) { + return false; + } else { + byte b0 = 3; + double d6 = 9999.0D; + + if (!this.world.u(blockposition.west()) && d3 < d6) { + d6 = d3; + b0 = 0; + } + + if (!this.world.u(blockposition.east()) && 1.0D - d3 < d6) { + d6 = 1.0D - d3; + b0 = 1; + } + + if (!this.world.u(blockposition.up()) && 1.0D - d4 < d6) { + d6 = 1.0D - d4; + b0 = 3; + } + + if (!this.world.u(blockposition.north()) && d5 < d6) { + d6 = d5; + b0 = 4; + } + + if (!this.world.u(blockposition.south()) && 1.0D - d5 < d6) { + b0 = 5; + } + + float f = random.nextFloat() * 0.2F + 0.1F; + + if (b0 == 0) { + this.motX = -f; + } + + if (b0 == 1) { + this.motX = f; + } + + if (b0 == 3) { + this.motY = f; + } + + if (b0 == 4) { + this.motZ = -f; + } + + if (b0 == 5) { + this.motZ = f; + } + + return true; + } + } + + public void aA() { + H = true; + fallDistance = 0.0F; + } + + public String getName() { + if (this.hasCustomName()) { + return this.getCustomName(); + } else { + String s = EntityTypes.b(this); + + if (s == null) { + s = "generic"; + } + + return LocaleI18n.get("entity." + s + ".name"); + } + } + + public Entity[] aB() { + return null; + } + + public boolean k(Entity entity) { + return this == entity; + } + + public float getHeadRotation() { + return 0.0F; + } + + public void f(float f) { + } + + public void g(float f) { + } + + public boolean aD() { + return true; + } + + public boolean l(Entity entity) { + return false; + } + + public String toString() { + return String.format("%s['%s'/%d, l='%s', x=%.2f, y=%.2f, z=%.2f]", this.getClass().getSimpleName(), this.getName(), this.id, this.world == null ? "~NULL~" : this.world.getWorldData().getName(), this.locX, this.locY, this.locZ); + } + + public boolean isInvulnerable(DamageSource damagesource) { + return invulnerable && damagesource != DamageSource.OUT_OF_WORLD && !damagesource.u(); + } + + public void m(Entity entity) { + this.setPositionRotation(entity.locX, entity.locY, entity.locZ, entity.yaw, entity.pitch); + } + + public void n(Entity entity) { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + + entity.e(nbttagcompound); + this.f(nbttagcompound); + this.portalCooldown = entity.portalCooldown; + this.an = entity.an; + this.ao = entity.ao; + this.ap = entity.ap; + } + + public void legacyDimensionChange(int dim) { + if (!this.dead) { + MinecraftServer minecraftserver = MinecraftServer.getServer(); + // CraftBukkit start - Move logic into new function "teleportToLocation" + WorldServer exitWorld = null; + if (this.dimension < CraftWorld.CUSTOM_DIMENSION_OFFSET) { // Plugins must specify exit from custom Bukkit worlds + // Only target existing worlds (compensate for allow-nether/allow-end as false) + for (WorldServer world : minecraftserver.worlds) { + if (world.dimension == dim) { + exitWorld = world; + } + } + } + + Location enter = this.getBukkitEntity().getLocation(); + Location exit = exitWorld != null ? minecraftserver.getPlayerList().calculateTarget(enter, minecraftserver.getWorldServer(dim)) : null; + boolean useTravelAgent = exitWorld != null && !(this.dimension == 1 && exitWorld.dimension == 1); // don't use agent for custom worlds or return from THE_END + + TravelAgent agent = exit != null ? (TravelAgent) ((CraftWorld) exit.getWorld()).getHandle().getTravelAgent() : org.bukkit.craftbukkit.CraftTravelAgent.DEFAULT; // return arbitrary TA to compensate for implementation dependent plugins + EntityPortalEvent event = new EntityPortalEvent(this.getBukkitEntity(), enter, exit, agent); + event.useTravelAgent(useTravelAgent); + event.getEntity().getServer().getPluginManager().callEvent(event); + if (event.isCancelled() || event.getTo() == null || event.getTo().getWorld() == null || !this.isAlive()) { + return; + } + exit = event.useTravelAgent() ? event.getPortalTravelAgent().findOrCreate(event.getTo()) : event.getTo(); + this.teleportTo(exit, true); + } + } + + public void c(int i) { + if (AzuriteConfig.preloadChunksOnDimensionChange.getValue()) { + this.betterDimensionChange(i); + } else { + this.legacyDimensionChange(i); + } + } + + // Beanes - optimized portals + // This preloads the chunks asynchronously to the target traveling location + // Should optimize the portal search by a lot + public void betterDimensionChange(int dim) { + if (this.dead) { + return; + } + + MinecraftServer minecraftserver = MinecraftServer.getServer(); + // CraftBukkit start - Move logic into new function "teleportToLocation" + WorldServer exitWorld = null; + if (this.dimension < CraftWorld.CUSTOM_DIMENSION_OFFSET) { // Plugins must specify exit from custom Bukkit worlds + // Only target existing worlds (compensate for allow-nether/allow-end as false) + for (WorldServer world : minecraftserver.worlds) { + if (world.dimension == dim) { + exitWorld = world; + } + } + } + + Location enter = this.getBukkitEntity().getLocation(); + Location exit = exitWorld != null ? minecraftserver.getPlayerList().calculateTarget(enter, minecraftserver.getWorldServer(dim)) : null; + boolean useTravelAgent = exitWorld != null && !(this.dimension == 1 && exitWorld.dimension == 1); // don't use agent for custom worlds or return from THE_END + + TravelAgent agent = exit != null ? (TravelAgent) ((CraftWorld) exit.getWorld()).getHandle().getTravelAgent() : org.bukkit.craftbukkit.CraftTravelAgent.DEFAULT; // return arbitrary TA to compensate for implementation dependent plugins + EntityPortalEvent event = new EntityPortalEvent(this.getBukkitEntity(), enter, exit, agent); + event.useTravelAgent(useTravelAgent); + event.getEntity().getServer().getPluginManager().callEvent(event); + if (event.isCancelled() || event.getTo() == null || event.getTo().getWorld() == null || !this.isAlive()) { + return; + } + exitWorld = ((CraftWorld) event.getTo().getWorld()).getHandle(); + + int chunkX = (MathHelper.floor(event.getTo().getX()) >> 4); + int chunkZ = (MathHelper.floor(event.getTo().getZ()) >> 4); + + int preLoadChunks = (int) Math.ceil(exitWorld.paperSpigotConfig.portalSearchRadius / 16.0D) + 1; + + AtomicInteger chunksRemainingForDimensionChange = new AtomicInteger((preLoadChunks + preLoadChunks) * (preLoadChunks + preLoadChunks)); + for (int addX = -preLoadChunks; addX < preLoadChunks; addX++) { + for (int addZ = -preLoadChunks; addZ < preLoadChunks; addZ++) { + int finalX = chunkX + addX; + int finalZ = chunkZ + addZ; + + exitWorld.chunkProviderServer.getChunkAt(finalX, finalZ, () -> { + // All requested chunks have been loaded, now we can do the portal search + if (chunksRemainingForDimensionChange.decrementAndGet() <= 0) { + Location teleportExit = event.useTravelAgent() ? event.getPortalTravelAgent().findOrCreate(event.getTo()) : event.getTo(); + this.teleportTo(teleportExit, true); + } + }); + } + } + } + + public void teleportTo(Location exit, boolean portal) { + WorldServer worldserver1 = ((CraftWorld) exit.getWorld()).getHandle(); + + this.dimension = worldserver1.dimension; + this.world.kill(this); + this.dead = false; + boolean before = worldserver1.chunkProviderServer.forceChunkLoad; + worldserver1.chunkProviderServer.forceChunkLoad = true; + worldserver1.getMinecraftServer().getPlayerList().repositionEntity(this, exit, portal); + worldserver1.chunkProviderServer.forceChunkLoad = before; + // CraftBukkit end + Entity entity = EntityTypes.createEntityByName(EntityTypes.b(this), worldserver1); + + if (entity != null) { + entity.n(this); + worldserver1.addEntity(entity); + // CraftBukkit start - Forward the CraftEntity to the new entity + this.getBukkitEntity().setHandle(entity); + entity.bukkitEntity = this.getBukkitEntity(); + + if (this instanceof EntityInsentient) { + ((EntityInsentient) this).unleash(true, false); // Unleash to prevent duping of leads. + } + // CraftBukkit end + } + + this.dead = true; + } + + public float a(Explosion explosion, World world, BlockPosition blockposition, IBlockData iblockdata) { + return iblockdata.getBlock().a(this); + } + + public boolean a(Explosion explosion, World world, BlockPosition blockposition, IBlockData iblockdata, float f) { + return true; + } + + public int aE() { + return 3; + } + + public Vec3D aG() { + return this.ao; + } + + public EnumDirection aH() { + return this.ap; + } + + public boolean aI() { + return false; + } + + public void appendEntityCrashDetails(CrashReportSystemDetails crashreportsystemdetails) { + crashreportsystemdetails.a("Entity Type", () -> EntityTypes.b(Entity.this) + " (" + Entity.this.getClass().getCanonicalName() + ")"); + crashreportsystemdetails.a("Entity ID", this.id); + crashreportsystemdetails.a("Entity Name", Entity.this::getName); + crashreportsystemdetails.a("Entity's Exact location", String.format("%.2f, %.2f, %.2f", this.locX, this.locY, this.locZ)); + crashreportsystemdetails.a("Entity's Block location", CrashReportSystemDetails.a(MathHelper.floor(this.locX), MathHelper.floor(this.locY), MathHelper.floor(this.locZ))); + crashreportsystemdetails.a("Entity's Momentum", String.format("%.2f, %.2f, %.2f", this.motX, this.motY, this.motZ)); + crashreportsystemdetails.a("Entity's Rider", () -> Entity.this.passenger.toString()); + crashreportsystemdetails.a("Entity's Vehicle", () -> Entity.this.vehicle.toString()); + } + + public UUID getUniqueID() { + return this.uniqueID; + } + + public boolean aL() { + return true; + } + + public IChatBaseComponent getScoreboardDisplayName() { + ChatComponentText chatcomponenttext = new ChatComponentText(this.getName()); + + chatcomponenttext.getChatModifier().setChatHoverable(this.aQ()); + chatcomponenttext.getChatModifier().setInsertion(this.getUniqueID().toString()); + return chatcomponenttext; + } + + public String getCustomName() { + return this.datawatcher.getString(2); + } + + public void setCustomName(String s) { + // CraftBukkit start - Add a sane limit for name length + if (s.length() > 256) { + s = s.substring(0, 256); + } + // CraftBukkit end + this.datawatcher.watch(2, s); + } + + public boolean hasCustomName() { + return !this.datawatcher.getString(2).isEmpty(); + } + + public boolean getCustomNameVisible() { + return this.datawatcher.getByte(3) == 1; + } + + public void setCustomNameVisible(boolean flag) { + this.datawatcher.watch(3, (byte) (flag ? 1 : 0)); + } + + public void enderTeleportTo(double d0, double d1, double d2) { + this.setPositionRotation(d0, d1, d2, this.yaw, this.pitch); + } + + public void i(int i) { + } + + public EnumDirection getDirection() { + return EnumDirection.fromType2(MathHelper.floor((double) (this.yaw * 4.0F / 360.0F) + 0.5D) & 3); + } + + protected ChatHoverable aQ() { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + String s = EntityTypes.b(this); + + nbttagcompound.setString("id", this.getUniqueID().toString()); + if (s != null) { + nbttagcompound.setString("type", s); + } + + nbttagcompound.setString("name", this.getName()); + return new ChatHoverable(ChatHoverable.EnumHoverAction.SHOW_ENTITY, new ChatComponentText(nbttagcompound.toString())); + } + + public boolean a(EntityPlayer entityplayer) { + return true; + } + + public AxisAlignedBB getBoundingBox() { + return this.boundingBox; + } + + public void a(AxisAlignedBB axisalignedbb) { + double a = axisalignedbb.a; + double b = axisalignedbb.b; + double c = axisalignedbb.c; + double d = axisalignedbb.d; + double e = axisalignedbb.e; + double f = axisalignedbb.f; + double len = axisalignedbb.d - axisalignedbb.a; + if (len < 0.0D) + d = a; + if (len > 64.0D) + d = a + 64.0D; + len = axisalignedbb.e - axisalignedbb.b; + if (len < 0.0D) + e = b; + if (len > 64.0D) + e = b + 64.0D; + len = axisalignedbb.f - axisalignedbb.c; + if (len < 0.0D) + f = c; + if (len > 64.0D) + f = c + 64.0D; + this.boundingBox = new AxisAlignedBB(a, b, c, d, e, f); + } + + public float getHeadHeight() { + return this.length * 0.85F; + } + + public boolean aT() { + return this.g; + } + + public void h(boolean flag) { + this.g = flag; + } + + public boolean d(int i, ItemStack itemstack) { + return false; + } + + public void sendMessage(IChatBaseComponent ichatbasecomponent) { + } + + public EntityTrackerEntry getEntry(int b, int c, boolean flag) { + return new EntityTrackerEntry(this, b, c, flag); + } + + public boolean a(int i, String s) { + return true; + } + + public BlockPosition getChunkCoordinates() { + return new BlockPosition(this.locX, this.locY + 0.5D, this.locZ); + } + + public Vec3D d() { + return new Vec3D(this.locX, this.locY, this.locZ); + } + + public World getWorld() { + return this.world; + } + + public Entity f() { + return this; + } + + public boolean getSendCommandFeedback() { + return false; + } + + public void a(CommandObjectiveExecutor.EnumCommandResult commandobjectiveexecutor_enumcommandresult, int i) { + this.au.a(this, commandobjectiveexecutor_enumcommandresult, i); + } + + public CommandObjectiveExecutor aU() { + return this.au; + } + + public void o(Entity entity) { + this.au.a(entity.aU()); + } + + public NBTTagCompound getNBTTag() { + return null; + } + + public boolean a(EntityHuman entityhuman, Vec3D vec3d) { + return false; + } + + public boolean aW() { + return false; + } + + public double getX() { + return locX; + } + + public double getY() { + return locY; + } + + public double getZ() { + return locZ; + } + + protected void a(EntityLiving entityliving, Entity entity) { + if (entity instanceof EntityLiving) { + EnchantmentManager.a((EntityLiving) entity, entityliving); + } + + EnchantmentManager.b(entityliving, entity); + } + + // Beanes - method to help sync server / client position more accurately by running location + motion through encode / decode + public void reEncodeByServerValues() { + // Re-encode the values for position + int encodedX = (int) Math.round(this.locX * 32.0D); + int encodedY = (int) Math.round(this.locY * 32.0D); + int encodedZ = (int) Math.round(this.locZ * 32.0D); + double decodedX = (double) encodedX / 32.0D; + double decodedY = (double) encodedY / 32.0D; + double decodedZ = (double) encodedZ / 32.0D; + this.setPosition(decodedX, decodedY, decodedZ); + + // Re-encode the values for yaw / pitch + int encodedYaw = (byte) Math.round(this.yaw * 256.0F / 360.0F); + int encodedPitch = (byte) Math.round(this.pitch * 256.0F / 360.0F); + float decodedYaw = (float) (encodedYaw * 360) / 256.0F; + float decodedPitch = (float) (encodedPitch * 360) / 256.0F; + + this.yaw = decodedYaw; + this.pitch = decodedPitch; + + // Re-encode the values for motion + double motionX = this.motX; + double motionY = this.motY; + double motionZ = this.motZ; + double limit = 3.9D; + if (motionX < -limit) + motionX = -limit; + if (motionY < -limit) + motionY = -limit; + if (motionZ < -limit) + motionZ = -limit; + if (motionX > limit) + motionX = limit; + if (motionY > limit) + motionY = limit; + if (motionZ > limit) + motionZ = limit; + + int encodedMotionX = (int) Math.round(motionX * 8000.0D); + int encodedMotionY = (int) Math.round(motionY * 8000.0D); + int encodedMotionZ = (int) Math.round(motionZ * 8000.0D); + + double decodedMotionX = (double) encodedMotionX / 8000.0D; + double decodedMotionY = (double) encodedMotionY / 8000.0D; + double decodedMotionZ = (double) encodedMotionZ / 8000.0D; + + this.motX = decodedMotionX; + this.motY = decodedMotionY; + this.motZ = decodedMotionZ; + } + + + // Azurite - knockback profiles + public Knockback knockbackProfile; + public Knockback getKnockbackProfile() { + return knockbackProfile == null ? (Knockback) Azurite.getInstance().getKnockbackManager().getActiveProfile() : knockbackProfile; + } + + public void setKnockbackProfile(Knockback profile) { + this.knockbackProfile = profile; + } + + // Azurite - kb air ticks + public int airTicks = 0; +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityAIBodyControl.java b/azurite-server/src/main/java/net/minecraft/server/EntityAIBodyControl.java new file mode 100644 index 0000000..6b5bf82 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityAIBodyControl.java @@ -0,0 +1,53 @@ +package net.minecraft.server; + +public class EntityAIBodyControl { + + private final EntityLiving a; + private int b; + private float c; + + public EntityAIBodyControl(EntityLiving entityliving) { + this.a = entityliving; + } + + public void a() { + double d0 = this.a.locX - this.a.lastX; + double d1 = this.a.locZ - this.a.lastZ; + + if (d0 * d0 + d1 * d1 > 2.500000277905201E-7D) { + this.a.aI = this.a.yaw; + this.a.aK = this.a(this.a.aI, this.a.aK, 75.0F); + this.c = this.a.aK; + this.b = 0; + } else { + float f = 75.0F; + + if (Math.abs(this.a.aK - this.c) > 15.0F) { + this.b = 0; + this.c = this.a.aK; + } else { + ++this.b; + + if (this.b > 10) { + f = Math.max(1.0F - (float) (this.b - 10) / 10.0F, 0.0F) * 75.0F; + } + } + + this.a.aI = this.a(this.a.aK, this.a.aI, f); + } + } + + private float a(float f, float f1, float f2) { + float f3 = MathHelper.g(f - f1); + + if (f3 < -f2) { + f3 = -f2; + } + + if (f3 >= f2) { + f3 = f2; + } + + return f - f3; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityAgeable.java b/azurite-server/src/main/java/net/minecraft/server/EntityAgeable.java new file mode 100644 index 0000000..e77042a --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityAgeable.java @@ -0,0 +1,188 @@ +package net.minecraft.server; + +public abstract class EntityAgeable extends EntityCreature { + + protected int a; + protected int b; + protected int c; + private float bm = -1.0F; + private float bn; + public boolean ageLocked = false; // CraftBukkit + + // Spigot start + @Override + public void inactiveTick() + { + super.inactiveTick(); + if (this.ageLocked ) { // CraftBukkit + this.a( this.isBaby() ); + } else { + int i = this.getAge(); + + if ( i < 0 ) + { + ++i; + this.setAgeRaw( i ); + } else if ( i > 0 ) + { + --i; + this.setAgeRaw( i ); + } + } + } + // Spigot end + + public EntityAgeable(World world) { + super(world); + } + + public abstract EntityAgeable createChild(EntityAgeable entityageable); + + public boolean a(EntityHuman entityhuman) { + ItemStack itemstack = entityhuman.inventory.getItemInHand(); + + if (itemstack != null && itemstack.getItem() == Items.SPAWN_EGG) { + + Class oclass = EntityTypes.a(itemstack.getData()); + + if (oclass != null && this.getClass() == oclass) { + EntityAgeable entityageable = this.createChild(this); + + if (entityageable != null) { + entityageable.setAgeRaw(-24000); + entityageable.setPositionRotation(this.locX, this.locY, this.locZ, 0.0F, 0.0F); + this.world.addEntity(entityageable, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.SPAWNER_EGG); // CraftBukkit + if (itemstack.hasName()) { + entityageable.setCustomName(itemstack.getName()); + } + + if (!entityhuman.abilities.canInstantlyBuild) { + --itemstack.count; + if (itemstack.count == 0) { // CraftBukkit - allow less than 0 stacks as "infinite" + entityhuman.inventory.setItem(entityhuman.inventory.itemInHandIndex, null); + } + } + } + } + + return true; + } else { + return false; + } + } + + protected void h() { + super.h(); + this.datawatcher.a(12, (byte) 0); + } + + public int getAge() { + return this.a; + } + + public void setAge(int i, boolean flag) { + int j = this.getAge(); + int k = j; + + j += i * 20; + if (j > 0) { + j = 0; + if (k < 0) { + this.n(); + } + } + + int l = j - k; + + this.setAgeRaw(j); + if (flag) { + this.b += l; + if (this.c == 0) { + this.c = 40; + } + } + + if (this.getAge() == 0) { + this.setAgeRaw(this.b); + } + + } + + public void setAge(int i) { + this.setAge(i, false); + } + + public void setAgeRaw(int i) { + this.datawatcher.watch(12, (byte) MathHelper.clamp(i, -1, 1)); + this.a = i; + this.a(this.isBaby()); + } + + public void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + nbttagcompound.setInt("Age", this.getAge()); + nbttagcompound.setInt("ForcedAge", this.b); + nbttagcompound.setBoolean("AgeLocked", this.ageLocked); // CraftBukkit + } + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + this.setAgeRaw(nbttagcompound.getInt("Age")); + this.b = nbttagcompound.getInt("ForcedAge"); + this.ageLocked = nbttagcompound.getBoolean("AgeLocked"); // CraftBukkit + } + + public void m() { + super.m(); + if (ageLocked) { // CraftBukkit + if (this.c > 0) { + if (this.c % 4 == 0) { + this.world.addParticle(EnumParticle.VILLAGER_HAPPY, this.locX + (double) (random.nextFloat() * this.width * 2.0F) - (double) this.width, this.locY + 0.5D + (double) (random.nextFloat() * this.length), this.locZ + (double) (random.nextFloat() * this.width * 2.0F) - (double) this.width, 0.0D, 0.0D, 0.0D, EnumParticle.EMPTY_ARRAY); + } + + --this.c; + } + + this.a(this.isBaby()); + } else { + int i = this.getAge(); + + if (i < 0) { + ++i; + this.setAgeRaw(i); + if (i == 0) { + this.n(); + } + } else if (i > 0) { + --i; + this.setAgeRaw(i); + } + } + + } + + protected void n() {} + + public boolean isBaby() { + return this.getAge() < 0; + } + + public void a(boolean flag) { + this.a(flag ? 0.5F : 1.0F); + } + + public final void setSize(float f, float f1) { // CraftBukkit - protected to public + boolean flag = this.bm > 0.0F; + + this.bm = f; + this.bn = f1; + if (!flag) { + this.a(1.0F); + } + + } + + protected final void a(float f) { + super.setSize(this.bm * f, this.bn * f); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityAmbient.java b/azurite-server/src/main/java/net/minecraft/server/EntityAmbient.java new file mode 100644 index 0000000..df1e00d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityAmbient.java @@ -0,0 +1,16 @@ +package net.minecraft.server; + +public abstract class EntityAmbient extends EntityInsentient implements IAnimal { + + public EntityAmbient(World world) { + super(world); + } + + public boolean cb() { + return false; + } + + protected boolean a(EntityHuman entityhuman) { + return false; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityAnimal.java b/azurite-server/src/main/java/net/minecraft/server/EntityAnimal.java new file mode 100644 index 0000000..edb6dad --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityAnimal.java @@ -0,0 +1,120 @@ +package net.minecraft.server; + +public abstract class EntityAnimal extends EntityAgeable implements IAnimal { + + protected Block bn; + private int bm; + private EntityHuman bo; + + public EntityAnimal(World world) { + super(world); + this.bn = Blocks.GRASS; + } + + protected void E() { + if (this.getAge() != 0) { + this.bm = 0; + } + + super.E(); + } + + public void m() { + super.m(); + if (this.getAge() != 0) { + this.bm = 0; + } + + if (this.bm > 0) { + --this.bm; + } + + } + + public float a(BlockPosition blockposition) { + return this.world.getType(blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()).getBlock() == Blocks.GRASS ? 10.0F : this.world.o(blockposition) - 0.5F; + } + + public void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + nbttagcompound.setInt("InLove", this.bm); + } + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + this.bm = nbttagcompound.getInt("InLove"); + } + + public boolean bR() { + int i = MathHelper.floor(locX), j = MathHelper.floor(boundingBox.b), k = MathHelper.floor(locZ); + return this.world.getType(i, j - 1, k).getBlock() == this.bn && this.world.k(i, j, k) > 8 && super.bR(); + } + + public int w() { + return 120; + } + + public boolean isTypeNotPersistent() { + return false; + } + + protected int getExpValue(EntityHuman entityhuman) { + return 1 + this.world.random.nextInt(3); + } + + public boolean d(ItemStack itemstack) { + return itemstack != null && itemstack.getItem() == Items.WHEAT; + } + + public boolean a(EntityHuman entityhuman) { + ItemStack itemstack = entityhuman.inventory.getItemInHand(); + + if (itemstack != null) { + if (this.d(itemstack) && this.getAge() == 0 && this.bm <= 0) { + this.a(entityhuman, itemstack); + this.c(entityhuman); + return true; + } + + if (this.isBaby() && this.d(itemstack)) { + this.a(entityhuman, itemstack); + this.setAge((int) ((float) (-this.getAge() / 20) * 0.1F), true); + return true; + } + } + + return super.a(entityhuman); + } + + protected void a(EntityHuman entityhuman, ItemStack itemstack) { + if (!entityhuman.abilities.canInstantlyBuild) { + --itemstack.count; + if (itemstack.count <= 0) { + entityhuman.inventory.setItem(entityhuman.inventory.itemInHandIndex, null); + } + } + + } + + public void c(EntityHuman entityhuman) { + this.bm = 600; + this.bo = entityhuman; + this.world.broadcastEntityEffect(this, (byte) 18); + } + + public EntityHuman cq() { + return this.bo; + } + + public boolean isInLove() { + return this.bm > 0; + } + + public void cs() { + this.bm = 0; + } + + public boolean mate(EntityAnimal entityanimal) { + return entityanimal != this && (entityanimal.getClass() == this.getClass() && this.isInLove() && entityanimal.isInLove()); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityArmorStand.java b/azurite-server/src/main/java/net/minecraft/server/EntityArmorStand.java new file mode 100644 index 0000000..f667dc3 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityArmorStand.java @@ -0,0 +1,700 @@ +package net.minecraft.server; + +import org.bukkit.craftbukkit.CraftEquipmentSlot; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.entity.ArmorStand; +import org.bukkit.entity.Player; +import org.bukkit.event.player.PlayerArmorStandManipulateEvent; +import org.bukkit.inventory.EquipmentSlot; + +import java.util.List; + +public class EntityArmorStand extends EntityLiving { + + private static final Vector3f a = new Vector3f(0.0F, 0.0F, 0.0F); + private static final Vector3f b = new Vector3f(0.0F, 0.0F, 0.0F); + private static final Vector3f c = new Vector3f(-10.0F, 0.0F, -10.0F); + private static final Vector3f d = new Vector3f(-15.0F, 0.0F, 10.0F); + private static final Vector3f e = new Vector3f(-1.0F, 0.0F, -1.0F); + private static final Vector3f f = new Vector3f(1.0F, 0.0F, 1.0F); + private final ItemStack[] items; + private boolean h; + private long i; + private int bi; + private boolean bj; + public Vector3f headPose; + public Vector3f bodyPose; + public Vector3f leftArmPose; + public Vector3f rightArmPose; + public Vector3f leftLegPose; + public Vector3f rightLegPose; + + public EntityArmorStand(World world) { + super(world); + this.items = new ItemStack[5]; + this.headPose = EntityArmorStand.a; + this.bodyPose = EntityArmorStand.b; + this.leftArmPose = EntityArmorStand.c; + this.rightArmPose = EntityArmorStand.d; + this.leftLegPose = EntityArmorStand.e; + this.rightLegPose = EntityArmorStand.f; + this.b(true); + this.noclip = this.hasGravity(); + this.setSize(0.5F, 1.975F); + } + + public EntityArmorStand(World world, double d0, double d1, double d2) { + this(world); + this.setPosition(d0, d1, d2); + } + + public boolean bM() { + return super.bM() && !this.hasGravity(); + } + + protected void h() { + super.h(); + this.datawatcher.a(10, (byte) 0); + this.datawatcher.a(11, EntityArmorStand.a); + this.datawatcher.a(12, EntityArmorStand.b); + this.datawatcher.a(13, EntityArmorStand.c); + this.datawatcher.a(14, EntityArmorStand.d); + this.datawatcher.a(15, EntityArmorStand.e); + this.datawatcher.a(16, EntityArmorStand.f); + } + + public ItemStack bA() { + return this.items[0]; + } + + public ItemStack getEquipment(int i) { + return this.items[i]; + } + + public void setEquipment(int i, ItemStack itemstack) { + this.items[i] = itemstack; + } + + public ItemStack[] getEquipment() { + return this.items; + } + + public boolean d(int i, ItemStack itemstack) { + int j; + + if (i == 99) { + j = 0; + } else { + j = i - 100 + 1; + if (j < 0 || j >= this.items.length) { + return false; + } + } + + if (itemstack != null && EntityInsentient.c(itemstack) != j && (j != 4 || !(itemstack.getItem() instanceof ItemBlock))) { + return false; + } else { + this.setEquipment(j, itemstack); + return true; + } + } + + public void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + NBTTagList nbttaglist = new NBTTagList(); + + for (ItemStack item : this.items) { + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + + if (item != null) { + item.save(nbttagcompound1); + } + + nbttaglist.add(nbttagcompound1); + } + + nbttagcompound.set("Equipment", nbttaglist); + if (this.getCustomNameVisible() && (this.getCustomName() == null || this.getCustomName().isEmpty())) { + nbttagcompound.setBoolean("CustomNameVisible", this.getCustomNameVisible()); + } + + nbttagcompound.setBoolean("Invisible", this.isInvisible()); + nbttagcompound.setBoolean("Small", this.isSmall()); + nbttagcompound.setBoolean("ShowArms", this.hasArms()); + nbttagcompound.setInt("DisabledSlots", this.bi); + nbttagcompound.setBoolean("NoGravity", this.hasGravity()); + nbttagcompound.setBoolean("NoBasePlate", this.hasBasePlate()); + if (this.s()) { + nbttagcompound.setBoolean("Marker", this.s()); + } + + nbttagcompound.set("Pose", this.z()); + } + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + if (nbttagcompound.hasKeyOfType("Equipment", 9)) { + NBTTagList nbttaglist = nbttagcompound.getList("Equipment", 10); + + for (int i = 0; i < this.items.length; ++i) { + this.items[i] = ItemStack.createStack(nbttaglist.get(i)); + } + } + + this.setInvisible(nbttagcompound.getBoolean("Invisible")); + this.setSmall(nbttagcompound.getBoolean("Small")); + this.setArms(nbttagcompound.getBoolean("ShowArms")); + this.bi = nbttagcompound.getInt("DisabledSlots"); + this.setGravity(nbttagcompound.getBoolean("NoGravity")); + this.setBasePlate(nbttagcompound.getBoolean("NoBasePlate")); + this.n(nbttagcompound.getBoolean("Marker")); + this.bj = !this.s(); + this.noclip = this.hasGravity(); + NBTTagCompound nbttagcompound1 = nbttagcompound.getCompound("Pose"); + + this.h(nbttagcompound1); + } + + private void h(NBTTagCompound nbttagcompound) { + NBTTagList nbttaglist = nbttagcompound.getList("Head", 5); + + if (!nbttaglist.isEmpty()) { + this.setHeadPose(new Vector3f(nbttaglist)); + } else { + this.setHeadPose(EntityArmorStand.a); + } + + NBTTagList nbttaglist1 = nbttagcompound.getList("Body", 5); + + if (!nbttaglist1.isEmpty()) { + this.setBodyPose(new Vector3f(nbttaglist1)); + } else { + this.setBodyPose(EntityArmorStand.b); + } + + NBTTagList nbttaglist2 = nbttagcompound.getList("LeftArm", 5); + + if (!nbttaglist2.isEmpty()) { + this.setLeftArmPose(new Vector3f(nbttaglist2)); + } else { + this.setLeftArmPose(EntityArmorStand.c); + } + + NBTTagList nbttaglist3 = nbttagcompound.getList("RightArm", 5); + + if (!nbttaglist3.isEmpty()) { + this.setRightArmPose(new Vector3f(nbttaglist3)); + } else { + this.setRightArmPose(EntityArmorStand.d); + } + + NBTTagList nbttaglist4 = nbttagcompound.getList("LeftLeg", 5); + + if (!nbttaglist4.isEmpty()) { + this.setLeftLegPose(new Vector3f(nbttaglist4)); + } else { + this.setLeftLegPose(EntityArmorStand.e); + } + + NBTTagList nbttaglist5 = nbttagcompound.getList("RightLeg", 5); + + if (!nbttaglist5.isEmpty()) { + this.setRightLegPose(new Vector3f(nbttaglist5)); + } else { + this.setRightLegPose(EntityArmorStand.f); + } + } + + private NBTTagCompound z() { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + + if (!EntityArmorStand.a.equals(this.headPose)) { + nbttagcompound.set("Head", this.headPose.a()); + } + + if (!EntityArmorStand.b.equals(this.bodyPose)) { + nbttagcompound.set("Body", this.bodyPose.a()); + } + + if (!EntityArmorStand.c.equals(this.leftArmPose)) { + nbttagcompound.set("LeftArm", this.leftArmPose.a()); + } + + if (!EntityArmorStand.d.equals(this.rightArmPose)) { + nbttagcompound.set("RightArm", this.rightArmPose.a()); + } + + if (!EntityArmorStand.e.equals(this.leftLegPose)) { + nbttagcompound.set("LeftLeg", this.leftLegPose.a()); + } + + if (!EntityArmorStand.f.equals(this.rightLegPose)) { + nbttagcompound.set("RightLeg", this.rightLegPose.a()); + } + + return nbttagcompound; + } + + public boolean ae() { + return false; + } + + protected void s(Entity entity) { + } + + protected void bL() { + List list = this.world.getEntities(this, this.getBoundingBox()); + + if (list != null && !list.isEmpty()) { + for (Entity entity : list) { + if (entity instanceof EntityMinecartAbstract && ((EntityMinecartAbstract) entity).s() == EntityMinecartAbstract.EnumMinecartType.RIDEABLE && this.h(entity) <= 0.2D) { + entity.collide(this); + } + } + } + + } + + public boolean a(EntityHuman entityhuman, Vec3D vec3d) { + if (this.s()) { + return false; + } else if (!entityhuman.isSpectator()) { + byte b0 = 0; + ItemStack itemstack = entityhuman.bZ(); + boolean flag = itemstack != null; + + if (flag && itemstack.getItem() instanceof ItemArmor) { + ItemArmor itemarmor = (ItemArmor) itemstack.getItem(); + + if (itemarmor.b == 3) { + b0 = 1; + } else if (itemarmor.b == 2) { + b0 = 2; + } else if (itemarmor.b == 1) { + b0 = 3; + } else if (itemarmor.b == 0) { + b0 = 4; + } + } + + if (flag && (itemstack.getItem() == Items.SKULL || itemstack.getItem() == Item.getItemOf(Blocks.PUMPKIN))) { + b0 = 4; + } + + byte b1 = 0; + boolean flag1 = this.isSmall(); + double d4 = flag1 ? vec3d.b * 2.0D : vec3d.b; + + if (d4 >= 0.1D && d4 < 0.1D + (flag1 ? 0.8D : 0.45D) && this.items[1] != null) { + b1 = 1; + } else if (d4 >= 0.9D + (flag1 ? 0.3D : 0.0D) && d4 < 0.9D + (flag1 ? 1.0D : 0.7D) && this.items[3] != null) { + b1 = 3; + } else if (d4 >= 0.4D && d4 < 0.4D + (flag1 ? 1.0D : 0.8D) && this.items[2] != null) { + b1 = 2; + } else if (d4 >= 1.6D && this.items[4] != null) { + b1 = 4; + } + + boolean flag2 = this.items[b1] != null; + + if ((this.bi & 1 << b1) != 0 || (this.bi & 1 << b0) != 0) { + b1 = b0; + if ((this.bi & 1 << b0) != 0) { + if ((this.bi & 1) != 0) { + return true; + } + + b1 = 0; + } + } + + if (!flag || b0 != 0 || this.hasArms()) { + if (flag) { + this.a(entityhuman, b0); + } else if (flag2) { + this.a(entityhuman, b1); + } + + } + return true; + } else { + return true; + } + } + + private void a(EntityHuman entityhuman, int i) { + ItemStack itemstack = this.items[i]; + + if (itemstack == null || (this.bi & 1 << i + 8) == 0) { + if (itemstack != null || (this.bi & 1 << i + 16) == 0) { + int j = entityhuman.inventory.itemInHandIndex; + ItemStack itemstack1 = entityhuman.inventory.getItem(j); + ItemStack itemstack2; + + // CraftBukkit start + org.bukkit.inventory.ItemStack armorStandItem = CraftItemStack.asCraftMirror(itemstack); + org.bukkit.inventory.ItemStack playerHeldItem = CraftItemStack.asCraftMirror(itemstack1); + + Player player = (Player) entityhuman.getBukkitEntity(); + ArmorStand self = (ArmorStand) this.getBukkitEntity(); + + EquipmentSlot slot = CraftEquipmentSlot.getSlot(i); + PlayerArmorStandManipulateEvent armorStandManipulateEvent = new PlayerArmorStandManipulateEvent(player, self, playerHeldItem, armorStandItem, slot); + this.world.getServer().getPluginManager().callEvent(armorStandManipulateEvent); + + if (armorStandManipulateEvent.isCancelled()) { + return; + } + // CraftBukkit end + + if (entityhuman.abilities.canInstantlyBuild && (itemstack == null || itemstack.getItem() == Item.getItemOf(Blocks.AIR)) && itemstack1 != null) { + itemstack2 = itemstack1.cloneItemStack(); + itemstack2.count = 1; + this.setEquipment(i, itemstack2); + } else if (itemstack1 != null && itemstack1.count > 1) { + if (itemstack == null) { + itemstack2 = itemstack1.cloneItemStack(); + itemstack2.count = 1; + this.setEquipment(i, itemstack2); + --itemstack1.count; + } + } else { + this.setEquipment(i, itemstack1); + entityhuman.inventory.setItem(j, itemstack); + } + } + } + } + + public boolean damageEntity(DamageSource damagesource, float f) { + // CraftBukkit start + if (org.bukkit.craftbukkit.event.CraftEventFactory.handleNonLivingEntityDamageEvent(this, damagesource, f)) { + return false; + } + // CraftBukkit end + if (this.dead) { + return false; + } else if (DamageSource.OUT_OF_WORLD.equals(damagesource)) { // PaperSpigot + this.die(); + return false; + } else if (!this.isInvulnerable(damagesource) && !this.h && !this.s()) { + if (damagesource.isExplosion()) { + this.D(); + this.die(); + return false; + } else if (DamageSource.FIRE.equals(damagesource)) { + if (!this.isBurning()) { + this.setOnFire(5); + } else { + this.a(0.15F); + } + + return false; + } else if (DamageSource.BURN.equals(damagesource) && this.getHealth() > 0.5F) { + this.a(4.0F); + return false; + } else { + boolean flag = "arrow".equals(damagesource.p()); + boolean flag1 = "player".equals(damagesource.p()); + + if (!flag1 && !flag) { + return false; + } else { + if (damagesource.i() instanceof EntityArrow) { + damagesource.i().die(); + } + + if (damagesource.getEntity() instanceof EntityHuman && !((EntityHuman) damagesource.getEntity()).abilities.mayBuild) { + return false; + } else if (damagesource.u()) { + this.A(); + this.die(); + return false; + } else { + long i = this.world.getTime(); + + if (i - this.i > 5L && !flag) { + this.i = i; + } else { + this.C(); + this.A(); + this.die(); + } + + return false; + } + } + } + } else { + return false; + } + } + + private void A() { + if (this.world instanceof WorldServer) { + ((WorldServer) this.world).a(EnumParticle.BLOCK_DUST, this.locX, this.locY + (double) this.length / 1.5D, this.locZ, 10, (this.width / 4.0F), this.length / 4.0F, this.width / 4.0F, 0.05D, Block.getCombinedId(Blocks.PLANKS.getBlockData())); + } + + } + + private void a(float f) { + float f1 = this.getHealth(); + + f1 -= f; + if (f1 <= 0.5F) { + this.D(); + this.die(); + } else { + this.setHealth(f1); + } + + } + + private void C() { + Block.dropItem(this.world, MathHelper.floor(locX), MathHelper.floor(locY), MathHelper.floor(locZ), new ItemStack(Items.ARMOR_STAND)); + this.D(); + } + + private void D() { + for (int i = 0; i < this.items.length; ++i) { + if (this.items[i] != null && this.items[i].count > 0) { + Block.dropItem(this.world, MathHelper.floor(locX), MathHelper.floor(locY) + 1, MathHelper.floor(locZ), this.items[i]); + this.items[i] = null; + } + } + } + + protected float h(float f, float f1) { + this.aJ = this.lastYaw; + this.aI = this.yaw; + return 0.0F; + } + + public float getHeadHeight() { + return this.isBaby() ? this.length * 0.5F : this.length * 0.9F; + } + + public void g(float f, float f1) { + if (!this.hasGravity()) { + super.g(f, f1); + } + } + + public void t_() { + super.t_(); + Vector3f vector3f = this.datawatcher.h(11); + + if (!this.headPose.equals(vector3f)) { + this.setHeadPose(vector3f); + } + + Vector3f vector3f1 = this.datawatcher.h(12); + + if (!this.bodyPose.equals(vector3f1)) { + this.setBodyPose(vector3f1); + } + + Vector3f vector3f2 = this.datawatcher.h(13); + + if (!this.leftArmPose.equals(vector3f2)) { + this.setLeftArmPose(vector3f2); + } + + Vector3f vector3f3 = this.datawatcher.h(14); + + if (!this.rightArmPose.equals(vector3f3)) { + this.setRightArmPose(vector3f3); + } + + Vector3f vector3f4 = this.datawatcher.h(15); + + if (!this.leftLegPose.equals(vector3f4)) { + this.setLeftLegPose(vector3f4); + } + + Vector3f vector3f5 = this.datawatcher.h(16); + + if (!this.rightLegPose.equals(vector3f5)) { + this.setRightLegPose(vector3f5); + } + + boolean flag = this.s(); + + if (!this.bj && flag) { + this.a(false); + } else { + if (!this.bj || flag) { + return; + } + + this.a(true); + } + + this.bj = flag; + } + + private void a(boolean flag) { + double d0 = this.locX; + double d1 = this.locY; + double d2 = this.locZ; + + if (flag) { + this.setSize(0.5F, 1.975F); + } else { + this.setSize(0.0F, 0.0F); + } + + this.setPosition(d0, d1, d2); + } + + protected void B() { + this.setInvisible(this.h); + } + + public void setInvisible(boolean flag) { + this.h = flag; + super.setInvisible(flag); + } + + public boolean isBaby() { + return this.isSmall(); + } + + public void G() { + this.die(); + } + + public boolean aW() { + return this.isInvisible(); + } + + public void setSmall(boolean flag) { + byte b0 = this.datawatcher.getByte(10); + + if (flag) { + b0 = (byte) (b0 | 1); + } else { + b0 &= -2; + } + + this.datawatcher.watch(10, b0); + } + + public boolean isSmall() { + return (this.datawatcher.getByte(10) & 1) != 0; + } + + public void setGravity(boolean flag) { + byte b0 = this.datawatcher.getByte(10); + + if (flag) { + b0 = (byte) (b0 | 2); + } else { + b0 &= -3; + } + + this.datawatcher.watch(10, b0); + } + + public boolean hasGravity() { + return (this.datawatcher.getByte(10) & 2) != 0; + } + + public void setArms(boolean flag) { + byte b0 = this.datawatcher.getByte(10); + + if (flag) { + b0 = (byte) (b0 | 4); + } else { + b0 &= -5; + } + + this.datawatcher.watch(10, b0); + } + + public boolean hasArms() { + return (this.datawatcher.getByte(10) & 4) != 0; + } + + public void setBasePlate(boolean flag) { + byte b0 = this.datawatcher.getByte(10); + + if (flag) { + b0 = (byte) (b0 | 8); + } else { + b0 &= -9; + } + + this.datawatcher.watch(10, b0); + } + + public boolean hasBasePlate() { + return (this.datawatcher.getByte(10) & 8) != 0; + } + + // PAIL + public void n(boolean flag) { // CraftBukkit - public + byte b0 = this.datawatcher.getByte(10); + + if (flag) { + b0 = (byte) (b0 | 16); + } else { + b0 &= -17; + } + + this.datawatcher.watch(10, b0); + } + + // PAIL + public boolean s() { + return (this.datawatcher.getByte(10) & 16) != 0; + } + + public void setHeadPose(Vector3f vector3f) { + this.headPose = vector3f; + this.datawatcher.watch(11, vector3f); + } + + public void setBodyPose(Vector3f vector3f) { + this.bodyPose = vector3f; + this.datawatcher.watch(12, vector3f); + } + + public void setLeftArmPose(Vector3f vector3f) { + this.leftArmPose = vector3f; + this.datawatcher.watch(13, vector3f); + } + + public void setRightArmPose(Vector3f vector3f) { + this.rightArmPose = vector3f; + this.datawatcher.watch(14, vector3f); + } + + public void setLeftLegPose(Vector3f vector3f) { + this.leftLegPose = vector3f; + this.datawatcher.watch(15, vector3f); + } + + public void setRightLegPose(Vector3f vector3f) { + this.rightLegPose = vector3f; + this.datawatcher.watch(16, vector3f); + } + + public Vector3f t() { + return this.headPose; + } + + public Vector3f u() { + return this.bodyPose; + } + + public boolean ad() { + return super.ad() && !this.s(); + } + + // TacoSpigot start - add an option to make armor stands not move + @Override + public void move(double motX, double motY, double motZ) { + } + // TacoSpigot end +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityArrow.java b/azurite-server/src/main/java/net/minecraft/server/EntityArrow.java new file mode 100644 index 0000000..5ad05f6 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityArrow.java @@ -0,0 +1,610 @@ +package net.minecraft.server; + +// CraftBukkit start + +import dev.azurite.spigot.configs.AzuriteConfig; +import dev.azurite.spigot.knockback.Knockback; +import org.bukkit.Bukkit; +import org.bukkit.entity.LivingEntity; +import org.bukkit.event.entity.EntityCombustByEntityEvent; +import org.bukkit.event.player.PlayerPickupItemEvent; +import org.bukkit.metadata.MetadataValue; +import org.bukkit.plugin.Plugin; +import org.bukkit.util.Vector; + +import java.util.*; + +public class EntityArrow extends Entity implements IProjectile { + + public boolean inGround = false; // Spigot - private -> public + public int fromPlayer; + public int shake; + public Entity shooter; + private float shooterYaw; // Azurite + public int knockbackStrength; + private int d = -1; + private int e = -1; + private int f = -1; + private Block g; + private int h; + private int ar; + private int as; + private double damage = 2.0D; + + public EntityArrow(World world) { + super(world); + this.j = 10.0D; + this.setSize(0.5F, 0.5F); + } + + public EntityArrow(World world, double d0, double d1, double d2) { + super(world); + this.j = 10.0D; + this.setSize(0.5F, 0.5F); + this.setPosition(d0, d1, d2); + } + + public EntityArrow(World world, EntityLiving entityliving, EntityLiving entityliving1, float f, float f1) { + super(world); + this.j = 10.0D; + this.shooter = entityliving; + this.shooterYaw = shooter.yaw; + this.projectileSource = (LivingEntity) entityliving.getBukkitEntity(); // CraftBukkit + if (entityliving instanceof EntityPlayer) { + this.fromPlayer = 1; + } + + this.locY = entityliving.locY + (double) entityliving.getHeadHeight() - 0.10000000149011612D; + double d0 = entityliving1.locX - entityliving.locX; + double d1 = entityliving1.boundingBox.b + (double) (entityliving1.length / 3.0F) - this.locY; + double d2 = entityliving1.locZ - entityliving.locZ; + double d3 = MathHelper.sqrt(d0 * d0 + d2 * d2); + + if (d3 >= 1.0E-7D) { + float f2 = (float) (MathHelper.b(d2, d0) * 180.0D / 3.1415927410125732D) - 90.0F; + float f3 = (float) (-(MathHelper.b(d1, d3) * 180.0D / 3.1415927410125732D)); + setPositionRotation(entityliving.locX + d0 / d3, locY, entityliving.locZ + d2 / d3, f2, f3); + + shoot(d0, d1 + d3 * 0.20000000298023224D, d2, f, f1); + } + } + // Vortex End + + public EntityArrow(World world, EntityLiving entityliving, float f) { + super(world); + this.j = 10.0D; + this.shooter = entityliving; + this.shooterYaw = shooter.yaw; + this.projectileSource = (LivingEntity) entityliving.getBukkitEntity(); // CraftBukkit + if (entityliving instanceof EntityPlayer) { + this.fromPlayer = 1; + } + + this.setSize(0.5F, 0.5F); + this.setPositionRotation(entityliving.locX, entityliving.locY + (double) entityliving.getHeadHeight(), entityliving.locZ, entityliving.yaw, entityliving.pitch); + if (!AzuriteConfig.patchProjectileOffset.getValue()) { + this.locX -= (MathHelper.cos(this.yaw / 180.0F * 3.1415927F) * 0.16F); + this.locZ -= (MathHelper.sin(this.yaw / 180.0F * 3.1415927F) * 0.16F); + } + + this.locY -= 0.10000000149011612D; + this.setPosition(this.locX, this.locY, this.locZ); + this.motX = (-MathHelper.sin(this.yaw / 180.0F * 3.1415927F) * MathHelper.cos(this.pitch / 180.0F * 3.1415927F)); + this.motZ = (MathHelper.cos(this.yaw / 180.0F * 3.1415927F) * MathHelper.cos(this.pitch / 180.0F * 3.1415927F)); + this.motY = (-MathHelper.sin(this.pitch / 180.0F * 3.1415927F)); + this.shoot(this.motX, this.motY, this.motZ, f * 1.5F, AzuriteConfig.arrowTrajectoryRandomness.getValue()); + } + // Spigot End + + + + // Spigot Start + @Override + public void inactiveTick() { + if (this.inGround) { + this.ar += 1; // Despawn counter. First int after shooter + } + super.inactiveTick(); + } + + protected void h() { + this.datawatcher.a(16, (byte) 0); + } + + public void shoot(double x, double y, double z, float strength, float randomness) { + float f2 = MathHelper.sqrt(x * x + y * y + z * z); + + x /= f2; + y /= f2; + z /= f2; + x += random.nextGaussian() * (random.nextBoolean() ? -1 : 1) * 0.007499999832361937D * randomness; + y += random.nextGaussian() * (random.nextBoolean() ? -1 : 1) * 0.007499999832361937D * randomness; + z += random.nextGaussian() * (random.nextBoolean() ? -1 : 1) * 0.007499999832361937D * randomness; + x *= strength; + y *= strength; + z *= strength; + this.motX = x; + this.motY = y; + this.motZ = z; + + float f3 = MathHelper.sqrt(x * x + z * z); + + this.lastYaw = this.yaw = (float) (MathHelper.b(x, z) * 180.0D / 3.1415927410125732D); + this.lastPitch = this.pitch = (float) (MathHelper.b(y, f3) * 180.0D / 3.1415927410125732D); + this.ar = 0; + + // Beanes - sync server & client values + this.reEncodeByServerValues(); + } + + public void t_() { + super.t_(); + if (this.lastPitch == 0.0F && this.lastYaw == 0.0F) { + this.lastYaw = this.yaw = (float) (MathHelper.b(this.motX, this.motZ) * 180.0D / 3.1415927410125732D); + this.lastPitch = this.pitch = (float) (MathHelper.b(this.motY, MathHelper.sqrt(this.motX * this.motX + this.motZ * this.motZ)) * 180.0D / 3.1415927410125732D); + } + + IBlockData iblockdata = this.world.getType(d, e, f); + Block block = iblockdata.getBlock(); + + if (block.getMaterial() != Material.AIR) { + BlockPosition blockposition = new BlockPosition(this.d, this.e, this.f); + block.updateShape(this.world, blockposition); + AxisAlignedBB axisalignedbb = block.a(this.world, blockposition, iblockdata); + + if (axisalignedbb != null && axisalignedbb.a(new Vec3D(this.locX, this.locY, this.locZ))) { + this.inGround = true; + } + } + + if (this.shake > 0) { + --this.shake; + } + + if (this.inGround) { + int i = block.toLegacyData(iblockdata); + + if (block == this.g && i == this.h) { + ++this.ar; + if (this.ar >= world.spigotConfig.arrowDespawnRate) { // Spigot - First int after shooter + this.die(); + } + } else { + this.inGround = false; + this.motX *= random.nextFloat() * 0.2F; + this.motY *= random.nextFloat() * 0.2F; + this.motZ *= random.nextFloat() * 0.2F; + this.ar = 0; + this.as = 0; + } + + } else { + ++this.as; + Vec3D startingPoint = new Vec3D(this.locX, this.locY, this.locZ); + Vec3D endingPoint = new Vec3D(this.locX + this.motX, this.locY + this.motY, this.locZ + this.motZ); + MovingObjectPosition movingobjectposition = this.world.rayTrace(startingPoint, endingPoint, false, true, false); + + startingPoint = new Vec3D(this.locX, this.locY, this.locZ); + endingPoint = new Vec3D(this.locX + this.motX, this.locY + this.motY, this.locZ + this.motZ); + if (movingobjectposition != null) { + endingPoint = new Vec3D(movingobjectposition.pos.a, movingobjectposition.pos.b, movingobjectposition.pos.c); + } + + Entity bestEntity = null; + double bestDistance = 0.0D; + + int j; + + // Beanes - system for bigger arrow bounding box + double baseArrowBoundingBox = 0.3D; + Collection noBoxExpand = new HashSet<>(); + + if (getBukkitEntity().hasMetadata("noBoxExpand")) { + List values = getBukkitEntity().getMetadata("noBoxExpand"); + + for (MetadataValue value : values) { + if (value.value() instanceof Collection) { + Collection collection = (Collection) value.value(); + + for (Object element : collection) { + if (element instanceof UUID) { + noBoxExpand.add((UUID) element); + } + } + } else if (value.value() instanceof UUID[]) { + UUID[] uuidArray = (UUID[]) value.value(); + noBoxExpand.addAll(Arrays.asList(uuidArray)); + } + } + } + + // Beanes - grow way bigger as we don't track interpolation positions + double growFactor = AzuriteConfig.arrowInterpolationRegistration.getValue() ? 5.0D : 1.0D; + + boolean easyArrows = (shooter instanceof EntityPlayer && ((EntityPlayer) shooter).easierArrows); + + for (Entity entity1 : world.getEntities(this, this.boundingBox.a(this.motX, this.motY, this.motZ).grow(growFactor, growFactor, growFactor))) { + if (entity1.ad() && (entity1 != this.shooter || this.as >= 5)) { + boolean interpolationArrows = AzuriteConfig.arrowInterpolationRegistration.getValue() && entity1 instanceof EntityPlayer && easyArrows; + boolean onlyInterpolation = interpolationArrows && AzuriteConfig.arrowInterpolationRegistrationOnly.getValue(); + + double arrowBox = baseArrowBoundingBox; + + if (easyArrows && entity1 instanceof EntityPlayer && !noBoxExpand.contains(entity1.getUniqueID())) { + arrowBox += AzuriteConfig.expandArrowBoundingBox.getValue(); + } + + AxisAlignedBB entityBox = entity1.boundingBox.grow(arrowBox, arrowBox, arrowBox); + + if (entityBox.a(startingPoint) && AzuriteConfig.checkStartOfRay.getValue() && !onlyInterpolation) { // Beanes - make arrows more accurate by checking if the starting point is inside the box (credits to stratus for this patch) + bestEntity = entity1; + break; + } else { + if (!onlyInterpolation) { + MovingObjectPosition rayResult = entityBox.a(startingPoint, endingPoint); + if (rayResult != null) { + double distance = startingPoint.distanceSquared(rayResult.pos); + + if (distance < bestDistance || bestDistance == 0.0D) { + bestEntity = entity1; + bestDistance = distance; + } + } + } + + // Beanes - improved projectile registration + if (interpolationArrows) { + EntityPlayer player = (EntityPlayer) entity1; + + double dist = player.interpolationData.attemptCollision(startingPoint, endingPoint, arrowBox); + + if (dist == Double.MIN_VALUE) { + bestEntity = entity1; + break; + } else if (dist < Double.MAX_VALUE && (dist < bestDistance || bestDistance == 0.0D)) { + bestEntity = entity1; + bestDistance = dist; + } + } + } + } + } + + if (bestEntity != null) { + movingobjectposition = new MovingObjectPosition(bestEntity); + } + + float f2; + float f3; + + // PaperSpigot start - Allow arrows to fly through vanished players the shooter can't see + if (movingobjectposition != null && bestEntity instanceof EntityPlayer && shooter != null) { + EntityHuman entityhuman = (EntityHuman) bestEntity; + if (entityhuman.abilities.isInvulnerable || this.shooter instanceof EntityPlayer && !((EntityHuman) this.shooter).a(entityhuman)) { + movingobjectposition = null; + } else if (shooter instanceof EntityPlayer && !((EntityPlayer) shooter).getBukkitEntity().canSee(((EntityPlayer) bestEntity).getBukkitEntity())) { + movingobjectposition = null; + } + } + + if (movingobjectposition != null) { + org.bukkit.craftbukkit.event.CraftEventFactory.callProjectileHitEvent(this); // CraftBukkit - Call event + Entity entity = movingobjectposition.entity; + if (entity != null) { + f2 = MathHelper.sqrt(this.motX * this.motX + this.motY * this.motY + this.motZ * this.motZ); + int k = MathHelper.f(f2 * this.damage); + + if (this.isCritical()) { + if (AzuriteConfig.arrowCriticalDamage.getValue()) { + k += random.nextInt(k / 2 + 2); + } else if (AzuriteConfig.arrowCriticalDamageMedian.getValue()) { + k += (k / 2 + 2) / 2; + } + } + + DamageSource damagesource; + + if (shooter == null) { + damagesource = DamageSource.arrow(this, this); + } else { + damagesource = DamageSource.arrow(this, shooter); + } + + double victimMotX = entity.motX, victimMotY = entity.motY, victimMotZ = entity.motZ; + // CraftBukkit start - Moved damage call + if (entity.damageEntity(damagesource, k)) { + if (isBurning() && !(entity instanceof EntityEnderman) && (!(entity instanceof EntityPlayer) || !(shooter instanceof EntityPlayer) || this.world.pvpMode)) { // CraftBukkit - abide by pvp setting if destination is a player + EntityCombustByEntityEvent combustEvent = new EntityCombustByEntityEvent(this.getBukkitEntity(), entity.getBukkitEntity(), 5); + org.bukkit.Bukkit.getPluginManager().callEvent(combustEvent); + if (!combustEvent.isCancelled()) { + entity.setOnFire(combustEvent.getDuration()); + } + // CraftBukkit end + } + + if (entity instanceof EntityLiving) { + EntityLiving entityliving = (EntityLiving) entity; + entityliving.o(entityliving.bv() + 1); + + boolean overrided = false; + if (shooter instanceof EntityPlayer) { + EntityPlayer player = (EntityPlayer) shooter; + Knockback profile = player.getKnockbackProfile(); + overrided = AzuriteConfig.overrideArrowKnockback.getValue(); + if (overrided) { + boolean bowBoost = knockbackStrength > 0 && profile.bowBoostDirectional.getValue(); + double punchMod = (knockbackStrength * profile.bowPunchMultiplier.getValue()) + 1; + + if (bowBoost && (!profile.bowBoostKbOnlyShooter.getValue() || shooter == entity)) { + entity.motX = (-MathHelper.sin(this.shooterYaw * 3.1415927F / 180.0F) * (float) punchMod) * profile.bowBoostHorizontal.getValue(); + entity.motY = profile.bowBoostVertical.getValue(); + entity.motZ = (MathHelper.cos(this.shooterYaw * 3.1415927F / 180.0F) * (float) punchMod) * profile.bowBoostHorizontal.getValue(); + + } else { + Vector unitVector = new Vector(motX, motY, motZ).normalize(); + double velX = (unitVector.getX() / 1.6D) * profile.bowHorizontal.getValue(); + double velZ = (unitVector.getZ() / 1.6D) * profile.bowHorizontal.getValue(); + + if (knockbackStrength > 0) { + velX *= punchMod; + velZ *= punchMod; + } + + entity.motX = velX; + entity.motY = 0.36D * profile.bowVertical.getValue(); + entity.motZ = velZ; + } + + // Immediately send the packet to the players to prevent delayed knockback + if (entity instanceof EntityPlayer && entity.velocityChanged) { + ((EntityPlayer) entity).sendVelocityPacket(victimMotX, victimMotY, victimMotZ, bowBoost); // Azurite - only reset fall distance if bow boosting. + } + } + } + + if (!overrided) { + f3 = MathHelper.sqrt(motX * motX + motZ * motZ); + if (f3 > 0.0F) { + if (knockbackStrength > 0) { + entity.g(motX * knockbackStrength * 0.6000000238418579 / f3, 0.1, motZ * knockbackStrength * 0.6000000238418579 / f3); + } + } + } + + if (shooter instanceof EntityLiving) { + EnchantmentManager.a(entityliving, shooter); + EnchantmentManager.b((EntityLiving) shooter, entityliving); + } + + if (entity != shooter && entity instanceof EntityHuman && shooter instanceof EntityPlayer) { + ((EntityPlayer) shooter).playerConnection.sendPacket(new PacketPlayOutGameStateChange(6, 0.0F)); + } + } + + this.makeSound("random.bowhit", 1.0F, 1.2F / (random.nextFloat() * 0.2F + 0.9F)); + if (!(entity instanceof EntityEnderman)) + this.die(); + this.stripNoBoxMetadata(); // Beanes - strip metadata when hit + + } else { + this.motX *= -0.10000000149011612D; + this.motY *= -0.10000000149011612D; + this.motZ *= -0.10000000149011612D; + this.yaw += 180.0F; + this.lastYaw += 180.0F; + this.as = 0; + } + } else { + BlockPosition blockposition1 = movingobjectposition.a(); + + this.d = blockposition1.getX(); + this.e = blockposition1.getY(); + this.f = blockposition1.getZ(); + IBlockData iblockdata1 = this.world.getType(d, e, f); + + this.g = iblockdata1.getBlock(); + this.h = this.g.toLegacyData(iblockdata1); + this.motX = ((float) (movingobjectposition.pos.a - this.locX)); + this.motY = ((float) (movingobjectposition.pos.b - this.locY)); + this.motZ = ((float) (movingobjectposition.pos.c - this.locZ)); + double f1 = MathHelper.sqrt(this.motX * this.motX + this.motY * this.motY + this.motZ * this.motZ); + this.locX -= this.motX / f1 * 0.05000000074505806D; + this.locY -= this.motY / f1 * 0.05000000074505806D; + this.locZ -= this.motZ / f1 * 0.05000000074505806D; + this.makeSound("random.bowhit", 1.0F, 1.2F / (random.nextFloat() * 0.2F + 0.9F)); + this.inGround = true; + this.stripNoBoxMetadata(); // Beanes - strip metadata when hit + this.shake = 7; + this.setCritical(false); + if (this.g.getMaterial() != Material.AIR) { + this.g.a(this.world, blockposition1, iblockdata1, this); + } + } + } + + if (this.isCritical()) { + for (j = 0; j < 4; ++j) { + this.world.addParticle(EnumParticle.CRIT, this.locX + this.motX * j / 4.0D, this.locY + this.motY * j / 4.0D, this.locZ + this.motZ * j / 4.0D, -this.motX, -this.motY + 0.2D, -this.motZ, EnumParticle.EMPTY_ARRAY); + } + } + + this.locX += this.motX; + this.locY += this.motY; + this.locZ += this.motZ; + f2 = MathHelper.sqrt(this.motX * this.motX + this.motZ * this.motZ); + this.yaw = (float) (MathHelper.b(this.motX, this.motZ) * 180.0D / 3.1415927410125732D); + + for (this.pitch = (float) (MathHelper.b(this.motY, f2) * 180.0D / 3.1415927410125732D); this.pitch - this.lastPitch < -180.0F; this.lastPitch -= 360.0F) { + } + + while (this.pitch - this.lastPitch >= 180.0F) { + this.lastPitch += 360.0F; + } + + while (this.yaw - this.lastYaw < -180.0F) { + this.lastYaw -= 360.0F; + } + + while (this.yaw - this.lastYaw >= 180.0F) { + this.lastYaw += 360.0F; + } + + this.pitch = this.lastPitch + (this.pitch - this.lastPitch) * 0.2F; + this.yaw = this.lastYaw + (this.yaw - this.lastYaw) * 0.2F; + float f4 = 0.99F; + if (this.V()) { + for (int l = 0; l < 4; ++l) + this.world.addParticle(EnumParticle.WATER_BUBBLE, this.locX - this.motX * 0.25F, this.locY - this.motY * 0.25F, this.locZ - this.motZ * 0.25F, this.motX, this.motY, this.motZ, EnumParticle.EMPTY_ARRAY); + f4 = 0.6F; + } + + if (this.U()) { + this.extinguish(); + } + + this.motX *= f4; + this.motY *= f4; + this.motZ *= f4; + this.motY -= 0.05; + this.setPosition(this.locX, this.locY, this.locZ); + this.checkBlockCollisions(); + } + } + + @Override + public void die() { + this.stripNoBoxMetadata(); + super.die(); + } + + private void stripNoBoxMetadata() { + if (getBukkitEntity().hasMetadata("noBoxExpand")) { + for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) { + getBukkitEntity().removeMetadata("noBoxExpand", plugin); + } + } + } + + public void b(NBTTagCompound nbttagcompound) { + nbttagcompound.setShort("xTile", (short) this.d); + nbttagcompound.setShort("yTile", (short) this.e); + nbttagcompound.setShort("zTile", (short) this.f); + nbttagcompound.setShort("life", (short) this.ar); + MinecraftKey minecraftkey = Block.REGISTRY.c(this.g); + + nbttagcompound.setString("inTile", minecraftkey == null ? "" : minecraftkey.toString()); + nbttagcompound.setByte("inData", (byte) this.h); + nbttagcompound.setByte("shake", (byte) this.shake); + nbttagcompound.setByte("inGround", (byte) (this.inGround ? 1 : 0)); + nbttagcompound.setByte("pickup", (byte) this.fromPlayer); + nbttagcompound.setDouble("damage", this.damage); + } + + public void a(NBTTagCompound nbttagcompound) { + this.d = nbttagcompound.getShort("xTile"); + this.e = nbttagcompound.getShort("yTile"); + this.f = nbttagcompound.getShort("zTile"); + this.ar = nbttagcompound.getShort("life"); + if (nbttagcompound.hasKeyOfType("inTile", 8)) { + this.g = Block.getByName(nbttagcompound.getString("inTile")); + } else { + this.g = Block.getById(nbttagcompound.getByte("inTile") & 255); + } + + this.h = nbttagcompound.getByte("inData") & 255; + this.shake = nbttagcompound.getByte("shake") & 255; + this.inGround = nbttagcompound.getByte("inGround") == 1; + if (nbttagcompound.hasKeyOfType("damage", 99)) { + this.damage = nbttagcompound.getDouble("damage"); + } + + if (nbttagcompound.hasKeyOfType("pickup", 99)) { + this.fromPlayer = nbttagcompound.getByte("pickup"); + } else if (nbttagcompound.hasKeyOfType("player", 99)) { + this.fromPlayer = nbttagcompound.getBoolean("player") ? 1 : 0; + } + + } + + public void d(EntityHuman entityhuman) { + if (this.inGround && this.shake <= 0) { + if (!((EntityPlayer) entityhuman).canSee(this)) + return; + + // CraftBukkit start + ItemStack itemstack = new ItemStack(Items.ARROW); + if (this.fromPlayer == 1 && entityhuman.inventory.canHold(itemstack) > 0) { + EntityItem item = new EntityItem(this.world, this.locX, this.locY, this.locZ, itemstack); + + PlayerPickupItemEvent event = new PlayerPickupItemEvent((org.bukkit.entity.Player) entityhuman.getBukkitEntity(), new org.bukkit.craftbukkit.entity.CraftItem(this.world.getServer(), this, item), 0); + // event.setCancelled(!entityhuman.canPickUpLoot); TODO + this.world.getServer().getPluginManager().callEvent(event); + + if (event.isCancelled()) { + return; + } + } + // CraftBukkit end + boolean flag = this.fromPlayer == 1 || this.fromPlayer == 2 && entityhuman.abilities.canInstantlyBuild; + + if (this.fromPlayer == 1 && !entityhuman.inventory.pickup(new ItemStack(Items.ARROW, 1))) { + flag = false; + } + + if (flag) { + this.makeSound("random.pop", 0.2F, ((random.nextFloat() - random.nextFloat()) * 0.7F + 1.0F) * 2.0F); + entityhuman.receive(this, 1); + this.die(); + } + + } + } + + protected boolean s_() { + return false; + } + + public void b(double d0) { + this.damage = d0; + } + + public double j() { + return this.damage; + } + + public void setKnockbackStrength(int i) { + this.knockbackStrength = i; + } + + public boolean aD() { + return false; + } + + public float getHeadHeight() { + return 0.0F; + } + + public boolean isCritical() { + byte b0 = this.datawatcher.getByte(16); + + return (b0 & 1) != 0; + } + + public void setCritical(boolean flag) { + byte b0 = this.datawatcher.getByte(16); + + if (flag) { + this.datawatcher.watch(16, (byte) (b0 | 1)); + } else { + this.datawatcher.watch(16, (byte) (b0 & -2)); + } + + } + + // CraftBukkit start + public boolean isInGround() { + return inGround; + } + + // CraftBukkit end +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityBat.java b/azurite-server/src/main/java/net/minecraft/server/EntityBat.java new file mode 100644 index 0000000..4cbd2f1 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityBat.java @@ -0,0 +1,189 @@ +package net.minecraft.server; + +import java.util.Calendar; + +public class EntityBat extends EntityAmbient { + + private BlockPosition a; + + public EntityBat(World world) { + super(world); + this.setSize(0.5F, 0.9F); + this.setAsleep(true); + } + + protected void h() { + super.h(); + this.datawatcher.a(16, (byte) 0); + } + + protected float bB() { + return 0.1F; + } + + protected float bC() { + return super.bC() * 0.95F; + } + + protected String z() { + return this.isAsleep() && random.nextInt(4) != 0 ? null : "mob.bat.idle"; + } + + protected String bo() { + return "mob.bat.hurt"; + } + + protected String bp() { + return "mob.bat.death"; + } + + public boolean ae() { + return false; + } + + protected void s(Entity entity) { + } + + protected void bL() { + } + + protected void initAttributes() { + super.initAttributes(); + this.getAttributeInstance(GenericAttributes.maxHealth).setValue(6.0D); + } + + public boolean isAsleep() { + return (this.datawatcher.getByte(16) & 1) != 0; + } + + public void setAsleep(boolean flag) { + byte b0 = this.datawatcher.getByte(16); + + if (flag) { + this.datawatcher.watch(16, (byte) (b0 | 1)); + } else { + this.datawatcher.watch(16, (byte) (b0 & -2)); + } + + } + + public void t_() { + super.t_(); + if (this.isAsleep()) { + this.motX = this.motY = this.motZ = 0.0D; + this.locY = (double) MathHelper.floor(this.locY) + 1.0D - (double) this.length; + } else { + this.motY *= 0.6000000238418579D; + } + + } + + protected void E() { + super.E(); + BlockPosition blockposition = new BlockPosition(this); + + if (this.isAsleep()) { + if (!this.world.getType(MathHelper.floor(locX), MathHelper.floor(locY) + 1, MathHelper.floor(locZ)).getBlock().isOccluding()) { + this.setAsleep(false); + this.world.a(null, 1015, blockposition, 0); + } else { + if (random.nextInt(200) == 0) { + this.aK = (float) random.nextInt(360); + } + + if (this.world.findNearbyPlayer(this, 4.0D) != null) { + this.setAsleep(false); + this.world.a(null, 1015, blockposition, 0); + } + } + } else { + if (this.a != null && (!this.world.isEmpty(this.a) || this.a.getY() < 1)) { + this.a = null; + } + + if (this.a == null || random.nextInt(30) == 0 || this.a.c(this.locX,this.locY, this.locZ) < 4.0D) { + this.a = new BlockPosition((int) this.locX + random.nextInt(7) - random.nextInt(7), (int) this.locY + random.nextInt(6) - 2, (int) this.locZ + random.nextInt(7) - random.nextInt(7)); + } + + double d0 = (double) this.a.getX() + 0.5D - this.locX; + double d1 = (double) this.a.getY() + 0.1D - this.locY; + double d2 = (double) this.a.getZ() + 0.5D - this.locZ; + + this.motX += (Math.signum(d0) * 0.5D - this.motX) * 0.10000000149011612D; + this.motY += (Math.signum(d1) * 0.699999988079071D - this.motY) * 0.10000000149011612D; + this.motZ += (Math.signum(d2) * 0.5D - this.motZ) * 0.10000000149011612D; + float f = (float) (MathHelper.b(this.motZ, this.motX) * 180.0D / 3.1415927410125732D) - 90.0F; + float f1 = MathHelper.g(f - this.yaw); + + this.ba = 0.5F; + this.yaw += f1; + if (random.nextInt(100) == 0 && this.world.getType(MathHelper.floor(locX), MathHelper.floor(locY) + 1, MathHelper.floor(locZ)).getBlock().isOccluding()) { + this.setAsleep(true); + } + } + + } + + protected boolean s_() { + return false; + } + + public void e(float f, float f1) { + } + + protected void a(double d0, boolean flag, Block block, BlockPosition blockposition) { + } + + public boolean aI() { + return true; + } + + public boolean damageEntity(DamageSource damagesource, float f) { + if (this.isInvulnerable(damagesource)) { + return false; + } else { + if (this.isAsleep()) { + this.setAsleep(false); + } + + return super.damageEntity(damagesource, f); + } + } + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + this.datawatcher.watch(16, nbttagcompound.getByte("BatFlags")); + } + + public void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + nbttagcompound.setByte("BatFlags", this.datawatcher.getByte(16)); + } + + public boolean bR() { + BlockPosition blockposition = new BlockPosition(this.locX, this.getBoundingBox().b, this.locZ); + + if (blockposition.getY() >= this.world.F()) { + return false; + } else { + int i = this.world.getLightLevel(blockposition); + byte b0 = 4; + + if (this.a(this.world.Y())) { + b0 = 7; + } else if (random.nextBoolean()) { + return false; + } + + return i <= random.nextInt(b0) && super.bR(); + } + } + + private boolean a(Calendar calendar) { + return calendar.get(Calendar.MONTH) + 1 == 10 && calendar.get(Calendar.DATE) >= 20 || calendar.get(Calendar.MONTH) + 1 == 11 && calendar.get(Calendar.DATE) <= 3; + } + + public float getHeadHeight() { + return this.length / 2.0F; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityBlaze.java b/azurite-server/src/main/java/net/minecraft/server/EntityBlaze.java new file mode 100644 index 0000000..bc1bb21 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityBlaze.java @@ -0,0 +1,198 @@ +package net.minecraft.server; + +public class EntityBlaze extends EntityMonster { + + private float a = 0.5F; + private int b; + + public EntityBlaze(World world) { + super(world); + this.fireProof = true; + this.b_ = 10; + this.goalSelector.a(4, new EntityBlaze.PathfinderGoalBlazeFireball(this)); + this.goalSelector.a(5, new PathfinderGoalMoveTowardsRestriction(this, 1.0D)); + this.goalSelector.a(7, new PathfinderGoalRandomStroll(this, 1.0D)); + this.goalSelector.a(8, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 8.0F)); + this.goalSelector.a(8, new PathfinderGoalRandomLookaround(this)); + this.targetSelector.a(1, new PathfinderGoalHurtByTarget(this, true)); + this.targetSelector.a(2, new PathfinderGoalNearestAttackableTarget<>(this, EntityHuman.class, true)); + } + + protected void initAttributes() { + super.initAttributes(); + this.getAttributeInstance(GenericAttributes.ATTACK_DAMAGE).setValue(6.0D); + this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.23000000417232513D); + this.getAttributeInstance(GenericAttributes.FOLLOW_RANGE).setValue(48.0D); + } + + protected void h() { + super.h(); + this.datawatcher.a(16, (byte) 0); + } + + protected String z() { + return "mob.blaze.breathe"; + } + + protected String bo() { + return "mob.blaze.hit"; + } + + protected String bp() { + return "mob.blaze.death"; + } + + public float c(float f) { + return 1.0F; + } + + public void m() { + if (!this.onGround && this.motY < 0.0D) { + this.motY *= 0.6D; + } + + super.m(); + } + + protected void E() { + if (this.U()) { + this.damageEntity(DamageSource.DROWN, 1.0F); + } + + --this.b; + if (this.b <= 0) { + this.b = 100; + this.a = 0.5F + (float) random.nextGaussian() * 3.0F; + } + + EntityLiving entityliving = this.getGoalTarget(); + + if (entityliving != null && entityliving.locY + (double) entityliving.getHeadHeight() > this.locY + (double) this.getHeadHeight() + (double) this.a) { + this.motY += (0.30000001192092896D - this.motY) * 0.30000001192092896D; + this.ai = true; + } + + super.E(); + } + + public void e(float f, float f1) { + } + + protected Item getLoot() { + return Items.BLAZE_ROD; + } + + public boolean isBurning() { + return this.n(); + } + + protected void dropDeathLoot(boolean flag, int i) { + if (flag) { + int j = random.nextInt(2 + i); + + for (int k = 0; k < j; ++k) { + this.a(Items.BLAZE_ROD, 1); + } + } + + } + + public boolean n() { + return (this.datawatcher.getByte(16) & 1) != 0; + } + + public void a(boolean flag) { + byte b0 = this.datawatcher.getByte(16); + + if (flag) { + b0 = (byte) (b0 | 1); + } else { + b0 &= -2; + } + + this.datawatcher.watch(16, b0); + } + + protected boolean n_() { + return true; + } + + static class PathfinderGoalBlazeFireball extends PathfinderGoal { + + private final EntityBlaze a; + private int b; + private int c; + + public PathfinderGoalBlazeFireball(EntityBlaze entityblaze) { + this.a = entityblaze; + this.a(3); + } + + public boolean a() { + EntityLiving entityliving = this.a.getGoalTarget(); + + return entityliving != null && entityliving.isAlive(); + } + + public void c() { + this.b = 0; + } + + public void d() { + this.a.a(false); + } + + public void e() { + --this.c; + EntityLiving entityliving = this.a.getGoalTarget(); + double d0 = this.a.h(entityliving); + + if (d0 < 4.0D) { + if (this.c <= 0) { + this.c = 20; + this.a.r(entityliving); + } + + this.a.getControllerMove().a(entityliving.locX, entityliving.locY, entityliving.locZ, 1.0D); + } else if (d0 < 256.0D) { + double d1 = entityliving.locX - this.a.locX; + double d2 = entityliving.getBoundingBox().b + (double) (entityliving.length / 2.0F) - (this.a.locY + (double) (this.a.length / 2.0F)); + double d3 = entityliving.locZ - this.a.locZ; + + if (this.c <= 0) { + ++this.b; + if (this.b == 1) { + this.c = 60; + this.a.a(true); + } else if (this.b <= 4) { + this.c = 6; + } else { + this.c = 100; + this.b = 0; + this.a.a(false); + } + + if (this.b > 1) { + float f = MathHelper.c(MathHelper.sqrt(d0)) * 0.5F; + + this.a.world.a(null, 1009, new BlockPosition((int) this.a.locX, (int) this.a.locY, (int) this.a.locZ), 0); + + for (int i = 0; i < 1; ++i) { + EntitySmallFireball entitysmallfireball = new EntitySmallFireball(this.a.world, this.a, d1 + this.a.bc().nextGaussian() * (double) f, d2, d3 + this.a.bc().nextGaussian() * (double) f); + + entitysmallfireball.locY = this.a.locY + (double) (this.a.length / 2.0F) + 0.5D; + this.a.world.addEntity(entitysmallfireball); + } + } + } + + this.a.getControllerLook().a(entityliving, 10.0F, 10.0F); + } else { + this.a.getNavigation().n(); + this.a.getControllerMove().a(entityliving.locX, entityliving.locY, entityliving.locZ, 1.0D); + } + + super.e(); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityBoat.java b/azurite-server/src/main/java/net/minecraft/server/EntityBoat.java new file mode 100644 index 0000000..2ad6b4f --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityBoat.java @@ -0,0 +1,480 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.AzuriteConfig; +import org.bukkit.Location; +import org.bukkit.craftbukkit.event.CraftEventFactory; +import org.bukkit.entity.Vehicle; +import org.bukkit.event.vehicle.VehicleDamageEvent; +import org.bukkit.event.vehicle.VehicleDestroyEvent; +import org.bukkit.event.vehicle.VehicleEntityCollisionEvent; +import org.bukkit.event.vehicle.VehicleMoveEvent; + +import java.util.List; +// CraftBukkit end + +public class EntityBoat extends Entity { + + private double b; + + // CraftBukkit start + public double maxSpeed = 0.4D; + public double occupiedDeceleration = 0.2D; + public double unoccupiedDeceleration = -1; + public boolean landBoats = false; + private boolean collidedWithAnyone = false; // Rivals + protected int ticksExisted = 0; // Rivals + + @Override + public void collide(Entity entity) { + // Beanes - only call if there is a listener + if (VehicleEntityCollisionEvent.getHandlerList().getRegisteredListeners().length > 0) { + org.bukkit.entity.Entity hitEntity = (entity == null) ? null : entity.getBukkitEntity(); + + VehicleEntityCollisionEvent event = new VehicleEntityCollisionEvent((Vehicle) this.getBukkitEntity(), hitEntity); + this.world.getServer().getPluginManager().callEvent(event); + + if (event.isCancelled()) { + return; + } + } + + super.collide(entity); + this.collidedWithAnyone = true; // Rivals + } + // CraftBukkit end + + public EntityBoat(World world) { + super(world); + this.b = 0.07D; + this.k = true; + this.setSize(1.5F, 0.6F); + } + + protected boolean s_() { + return false; + } + + protected void h() { + this.datawatcher.a(17, 0); + this.datawatcher.a(18, 1); + this.datawatcher.a(19, 0.0F); + } + + public AxisAlignedBB j(Entity entity) { + return entity.getBoundingBox(); + } + + public AxisAlignedBB S() { + return boundingBox; + } + + public boolean ae() { + return true; + } + + public EntityBoat(World world, double d0, double d1, double d2) { + this(world); + this.setPosition(d0, d1 + (AzuriteConfig.oldBoats.getValue() ? (double) 0.3F : 0.0F), d2); // Rivals - 1.7 Boats + this.motX = 0.0D; + this.motY = 0.0D; + this.motZ = 0.0D; + this.lastX = d0; + this.lastY = d1; + this.lastZ = d2; + + this.world.getServer().getPluginManager().callEvent(new org.bukkit.event.vehicle.VehicleCreateEvent((Vehicle) this.getBukkitEntity())); // CraftBukkit + } + + public double an() { + return -0.3D; + } + + public boolean damageEntity(DamageSource damagesource, float f) { + if (this.isInvulnerable(damagesource)) { + return false; + } else if (!this.dead) { + if (this.passenger != null && this.passenger == damagesource.getEntity() && damagesource instanceof EntityDamageSourceIndirect) { + return false; + } else { + // CraftBukkit start + Vehicle vehicle = (Vehicle) this.getBukkitEntity(); + org.bukkit.entity.Entity attacker = (damagesource.getEntity() == null) ? null : damagesource.getEntity().getBukkitEntity(); + + VehicleDamageEvent event = new VehicleDamageEvent(vehicle, attacker, f); + this.world.getServer().getPluginManager().callEvent(event); + + if (event.isCancelled()) { + return false; + } + // f = event.getDamage(); // TODO Why don't we do this? + // CraftBukkit end + + this.b(-this.m()); + this.a(10); + this.setDamage(this.j() + f * 10.0F); + this.ac(); + boolean flag = damagesource.getEntity() instanceof EntityHuman && ((EntityHuman) damagesource.getEntity()).abilities.canInstantlyBuild; + + if (flag || this.j() > 40.0F) { + // CraftBukkit start + VehicleDestroyEvent destroyEvent = new VehicleDestroyEvent(vehicle, attacker); + this.world.getServer().getPluginManager().callEvent(destroyEvent); + + if (destroyEvent.isCancelled()) { + this.setDamage(40F); // Maximize damage so this doesn't get triggered again right away + return true; + } + // CraftBukkit end + if (this.passenger != null) { + this.passenger.mount(this); + } + + if (!flag && this.world.getGameRules().getBoolean("doEntityDrops")) { + this.a(Items.BOAT, 1, 0.0F); + } + + this.die(); + } + + return true; + } + } else { + return true; + } + } + + public boolean ad() { + return !this.dead; + } + + public void t_() { + this.ticksExisted++; + // CraftBukkit start + double prevX = this.locX; + double prevY = this.locY; + double prevZ = this.locZ; + float prevYaw = this.yaw; + float prevPitch = this.pitch; + // CraftBukkit end + super.t_(); + if (this.l() > 0) { + this.a(this.l() - 1); + } + + if (this.j() > 0.0F) { + this.setDamage(this.j() - 1.0F); + } + + this.lastX = this.locX; + this.lastY = this.locY; + this.lastZ = this.locZ; + byte b0 = 5; + double d0 = 0.0D; + + for (int i = 0; i < b0; ++i) { + double d1 = boundingBox.b + (boundingBox.e - boundingBox.b) * i / b0 - 0.125D; + double d2 = boundingBox.b + (boundingBox.e - boundingBox.b) * (i + 1) / b0 - 0.125D; + AxisAlignedBB axisalignedbb = new AxisAlignedBB(boundingBox.a, d1, boundingBox.c, boundingBox.d, d2, boundingBox.f); + + if (this.world.b(axisalignedbb, Material.WATER)) { + d0 += 1.0D / (double) b0; + } + } + + double d3 = Math.sqrt(this.motX * this.motX + this.motZ * this.motZ); + double d4; + double d5; + int j; + + if (d3 > 0.2975D) { + d4 = Math.cos(this.yaw * 3.141592653589793D / 180.0D); + d5 = Math.sin(this.yaw * 3.141592653589793D / 180.0D); + + for (j = 0; (double) j < 1.0D + d3 * 60.0D; ++j) { + double d6 = (random.nextFloat() * 2.0F - 1.0F); + double d7 = (random.nextInt(2) * 2 - 1) * 0.7D; + double d8; + double d9; + + if (random.nextBoolean()) { + d8 = this.locX - d4 * d6 * 0.8D + d5 * d7; + d9 = this.locZ - d5 * d6 * 0.8D - d4 * d7; + this.world.addParticle(EnumParticle.WATER_SPLASH, d8, this.locY - 0.125D, d9, this.motX, this.motY, this.motZ, EnumParticle.EMPTY_ARRAY); + } else { + d8 = this.locX + d4 + d5 * d6 * 0.7D; + d9 = this.locZ + d5 - d4 * d6 * 0.7D; + this.world.addParticle(EnumParticle.WATER_SPLASH, d8, this.locY - 0.125D, d9, this.motX, this.motY, this.motZ, EnumParticle.EMPTY_ARRAY); + } + } + } + + double d10; + double d11; + + if (d0 < 1.0D) { + // Rivals start - 1.7 Boats don't start moving until you interact with them if they're on a source block. + if (!AzuriteConfig.oldBoats.getValue() || checkOldBoats()) { + d4 = d0 * 2.0D - 1.0D; + this.motY += 0.03999999910593033D * d4; + } + // Rivals end + } else { + if (this.motY < 0.0D) { + this.motY /= 2.0D; + } + + this.motY += 0.007000000216066837D; + } + + if (this.passenger instanceof EntityLiving) { + EntityLiving entityliving = (EntityLiving) this.passenger; + float f = this.passenger.yaw + -entityliving.aZ * 90.0F; + + this.motX += -Math.sin((f * 3.1415927F / 180.0F)) * this.b * entityliving.ba * 0.05000000074505806D; + this.motZ += Math.cos((f * 3.1415927F / 180.0F)) * this.b * entityliving.ba * 0.05000000074505806D; + } + // CraftBukkit start - Support unoccupied deceleration + else if (unoccupiedDeceleration >= 0) { + this.motX *= unoccupiedDeceleration; + this.motZ *= unoccupiedDeceleration; + // Kill lingering speed + if (motX <= 0.00001) { + motX = 0; + } + if (motZ <= 0.00001) { + motZ = 0; + } + } + // CraftBukkit end + + d4 = Math.sqrt(this.motX * this.motX + this.motZ * this.motZ); + if (d4 > 0.35D) { + d5 = 0.35D / d4; + this.motX *= d5; + this.motZ *= d5; + d4 = 0.35D; + } + + if (d4 > d3 && this.b < 0.35D) { + this.b += (0.35D - this.b) / 35.0D; + if (this.b > 0.35D) { + this.b = 0.35D; + } + } else { + this.b -= (this.b - 0.07D) / 35.0D; + if (this.b < 0.07D) { + this.b = 0.07D; + } + } + + int k; + + BlockPosition.MutableBlockPosition pos = new BlockPosition.MutableBlockPosition(); + for (k = 0; k < 4; ++k) { + int l = MathHelper.floor(this.locX + ((double) (k % 2) - 0.5D) * 0.8D); + + j = MathHelper.floor(this.locZ + ((double) (k / 2) - 0.5D) * 0.8D); + + for (int i1 = 0; i1 < 2; ++i1) { + int j1 = MathHelper.floor(this.locY) + i1; + Block block = this.world.getType(l, j1, j).getBlock(); + + if (block == Blocks.SNOW_LAYER) { + // CraftBukkit start + if (CraftEventFactory.callEntityChangeBlockEvent(this, l, j1, j, Blocks.AIR, 0).isCancelled()) { + continue; + } + // CraftBukkit end + this.world.setAir(pos.c(l, j1, j)); + this.positionChanged = false; + } else if (block == Blocks.WATERLILY) { + // CraftBukkit start + if (CraftEventFactory.callEntityChangeBlockEvent(this, l, j1, j, Blocks.AIR, 0).isCancelled()) { + continue; + } + // CraftBukkit end + this.world.setAir(pos.c(l, j1, j), true); + this.positionChanged = false; + } + } + } + + if (this.onGround && !this.landBoats) { // CraftBukkit + this.motX *= 0.5D; + this.motY *= 0.5D; + this.motZ *= 0.5D; + } + + this.move(this.motX, this.motY, this.motZ); + if (this.positionChanged && d3 > (AzuriteConfig.oldBoats.getValue() ? 0.2975D : 0.2D)) { // Rivals - 1.7 Boats + if (!this.dead) { + // CraftBukkit start + Vehicle vehicle = (Vehicle) this.getBukkitEntity(); + VehicleDestroyEvent destroyEvent = new VehicleDestroyEvent(vehicle, null); + this.world.getServer().getPluginManager().callEvent(destroyEvent); + if (!destroyEvent.isCancelled()) { + this.die(); + if (this.world.getGameRules().getBoolean("doEntityDrops")) { + breakNaturally(); // PaperSpigot + } + } // CraftBukkit end + } + } else { + this.motX *= 0.9900000095367432D; + this.motY *= 0.949999988079071D; + this.motZ *= 0.9900000095367432D; + } + + this.pitch = 0.0F; + d5 = this.yaw; + d10 = this.lastX - this.locX; + d11 = this.lastZ - this.locZ; + if (d10 * d10 + d11 * d11 > 0.001D) { + d5 = (float) (MathHelper.b(d11, d10) * 180.0D / 3.141592653589793D); + } + + double d12 = MathHelper.g(d5 - (double) this.yaw); + + if (d12 > 20.0D) { + d12 = 20.0D; + } + + if (d12 < -20.0D) { + d12 = -20.0D; + } + + this.yaw = (float) ((double) this.yaw + d12); + this.setYawPitch(this.yaw, this.pitch); + + // CraftBukkit start + org.bukkit.Server server = this.world.getServer(); + org.bukkit.World bworld = this.world.getWorld(); + + Location from = new Location(bworld, prevX, prevY, prevZ, prevYaw, prevPitch); + Location to = new Location(bworld, this.locX, this.locY, this.locZ, this.yaw, this.pitch); + Vehicle vehicle = (Vehicle) this.getBukkitEntity(); + + server.getPluginManager().callEvent(new org.bukkit.event.vehicle.VehicleUpdateEvent(vehicle)); + + if (!from.equals(to)) { + VehicleMoveEvent event = new VehicleMoveEvent(vehicle, from, to); + server.getPluginManager().callEvent(event); + } + // CraftBukkit end + + List list = this.world.getEntities(this, boundingBox.grow(0.20000000298023224D, 0.0D, 0.20000000298023224D)); + + if (list != null && !list.isEmpty()) { + for (Entity entity : list) { + if (entity != this.passenger && entity.ae() && entity instanceof EntityBoat) { + entity.collide(this); + } + } + } + + if (this.passenger != null && this.passenger.dead) { + this.passenger.vehicle = null; // CraftBukkit + this.passenger = null; + } + + } + + public void al() { + if (this.passenger != null) { + this.passenger.setPosition(this.locX + Math.cos(this.yaw * 3.141592653589793D / 180.0D) * 0.4, this.locY + this.an() + this.passenger.am(), this.locZ + Math.sin(this.yaw * 3.141592653589793D / 180.0D) * 0.4); + } + } + + protected void b(NBTTagCompound nbttagcompound) { + } + + protected void a(NBTTagCompound nbttagcompound) { + } + + public boolean e(EntityHuman entityhuman) { + if (this.passenger == null || !(this.passenger instanceof EntityPlayer) || this.passenger == entityhuman) { + entityhuman.mount(this); + } + return true; + } + + protected void a(double d0, boolean flag, Block block, BlockPosition blockposition) { + if (flag) { + if (this.fallDistance > 3.0F) { + this.e(this.fallDistance, 1.0F); + if (!this.dead) { + // CraftBukkit start + Vehicle vehicle = (Vehicle) this.getBukkitEntity(); + VehicleDestroyEvent destroyEvent = new VehicleDestroyEvent(vehicle, null); + this.world.getServer().getPluginManager().callEvent(destroyEvent); + if (!destroyEvent.isCancelled()) { + this.die(); + if (this.world.getGameRules().getBoolean("doEntityDrops")) { + breakNaturally(); // PaperSpigot + } + } // CraftBukkit end + } + + this.fallDistance = 0.0F; + } + } else if (this.world.getType(MathHelper.floor(locX), MathHelper.floor(locY) - 1, MathHelper.floor(locZ)).getBlock().getMaterial() != Material.WATER && d0 < 0.0D) { + this.fallDistance = (float) (this.fallDistance - d0); + } + + } + + public void setDamage(float f) { + this.datawatcher.watch(19, f); + } + + public float j() { + return this.datawatcher.getFloat(19); + } + + public void a(int i) { + this.datawatcher.watch(17, i); + } + + public int l() { + return this.datawatcher.getInt(17); + } + + public void b(int i) { + this.datawatcher.watch(18, i); + } + + public int m() { + return this.datawatcher.getInt(18); + } + + /** + * PaperSpigot - Handles boat drops depending on the user's config setting + */ + public void breakNaturally() { + if (this.world.paperSpigotConfig.boatsDropBoats) { + this.a(Items.BOAT, 1, 0.0F); + } else { + for (int k = 0; k < 3; ++k) { + this.a(Item.getItemOf(Blocks.PLANKS), 1, 0.0F); + } + + for (int k = 0; k < 2; ++k) { + this.a(Items.STICK, 1, 0.0F); + } + } + } + + // Rivals start - 1.7 Boats don't start moving until you interact with them if they're on a source block. + private boolean checkOldBoats() { + IBlockData blockData = this.getWorld().getType(new BlockPosition(this).down()); + // Allow physics if they're not on a source block or not on water at all. + if (blockData.getBlock() instanceof BlockFluids && blockData.get(BlockFluids.LEVEL) != 0) { + return true; + } else if (!(blockData.getBlock() instanceof BlockFluids)) { + return true; + } + + return (this.ticksExisted >= 5 && collidedWithAnyone) || passenger != null; + } + // Rivals end +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityCaveSpider.java b/azurite-server/src/main/java/net/minecraft/server/EntityCaveSpider.java new file mode 100644 index 0000000..f26d52a --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityCaveSpider.java @@ -0,0 +1,44 @@ +package net.minecraft.server; + +public class EntityCaveSpider extends EntitySpider { + + public EntityCaveSpider(World world) { + super(world); + this.setSize(0.7F, 0.5F); + } + + protected void initAttributes() { + super.initAttributes(); + this.getAttributeInstance(GenericAttributes.maxHealth).setValue(12.0D); + } + + public boolean r(Entity entity) { + if (super.r(entity)) { + if (entity instanceof EntityLiving) { + byte b0 = 0; + + if (this.world.getDifficulty() == EnumDifficulty.NORMAL) { + b0 = 7; + } else if (this.world.getDifficulty() == EnumDifficulty.HARD) { + b0 = 15; + } + + if (b0 > 0) { + ((EntityLiving) entity).addEffect(new MobEffect(MobEffectList.POISON.id, b0 * 20, 0)); + } + } + + return true; + } else { + return false; + } + } + + public GroupDataEntity prepare(DifficultyDamageScaler difficultydamagescaler, GroupDataEntity groupdataentity) { + return groupdataentity; + } + + public float getHeadHeight() { + return 0.45F; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityChicken.java b/azurite-server/src/main/java/net/minecraft/server/EntityChicken.java new file mode 100644 index 0000000..d11eb35 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityChicken.java @@ -0,0 +1,154 @@ +package net.minecraft.server; + +public class EntityChicken extends EntityAnimal { + + public float bm; + public float bo; + public float bp; + public float bq; + public float br = 1.0F; + public int bs; + public boolean bt; + + public EntityChicken(World world) { + super(world); + this.setSize(0.4F, 0.7F); + this.bs = random.nextInt(6000) + 6000; + this.goalSelector.a(0, new PathfinderGoalFloat(this)); + this.goalSelector.a(1, new PathfinderGoalPanic(this, 1.4D)); + this.goalSelector.a(2, new PathfinderGoalBreed(this, 1.0D)); + this.goalSelector.a(3, new PathfinderGoalTempt(this, 1.0D, Items.WHEAT_SEEDS, false)); + this.goalSelector.a(4, new PathfinderGoalFollowParent(this, 1.1D)); + this.goalSelector.a(5, new PathfinderGoalRandomStroll(this, 1.0D)); + this.goalSelector.a(6, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 6.0F)); + this.goalSelector.a(7, new PathfinderGoalRandomLookaround(this)); + } + + public float getHeadHeight() { + return this.length; + } + + protected void initAttributes() { + super.initAttributes(); + this.getAttributeInstance(GenericAttributes.maxHealth).setValue(4.0D); + this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.25D); + } + + public void m() { + // CraftBukkit start + if (this.isChickenJockey()) { + this.persistent = !this.isTypeNotPersistent(); + } + // CraftBukkit end + super.m(); + this.bq = this.bm; + this.bp = this.bo; + this.bo = (float) (this.bo + (this.onGround ? -1 : 4) * 0.3D); + this.bo = MathHelper.a(this.bo, 0.0F, 1.0F); + if (!this.onGround && this.br < 1.0F) { + this.br = 1.0F; + } + + this.br = (float) (this.br * 0.9D); + if (!this.onGround && this.motY < 0.0D) { + this.motY *= 0.6D; + } + + this.bm += this.br * 2.0F; + if (!this.isBaby() && !this.isChickenJockey() && --this.bs <= 0) { + this.makeSound("mob.chicken.plop", 1.0F, (random.nextFloat() - random.nextFloat()) * 0.2F + 1.0F); + this.a(Items.EGG, 1); + this.bs = random.nextInt(6000) + 6000; + } + + } + + public void e(float f, float f1) {} + + protected String z() { + return "mob.chicken.say"; + } + + protected String bo() { + return "mob.chicken.hurt"; + } + + protected String bp() { + return "mob.chicken.hurt"; + } + + protected void a(BlockPosition blockposition, Block block) { + this.makeSound("mob.chicken.step", 0.15F, 1.0F); + } + + protected Item getLoot() { + return Items.FEATHER; + } + + protected void dropDeathLoot(boolean flag, int i) { + int j = random.nextInt(3) + random.nextInt(1 + i); + + for (int k = 0; k < j; ++k) { + this.a(Items.FEATHER, 1); + } + + if (this.isBurning()) { + this.a(Items.COOKED_CHICKEN, 1); + } else { + this.a(Items.CHICKEN, 1); + } + + } + + public EntityChicken b(EntityAgeable entityageable) { + return new EntityChicken(this.world); + } + + public boolean d(ItemStack itemstack) { + return itemstack != null && itemstack.getItem() == Items.WHEAT_SEEDS; + } + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + this.bt = nbttagcompound.getBoolean("IsChickenJockey"); + if (nbttagcompound.hasKey("EggLayTime")) { + this.bs = nbttagcompound.getInt("EggLayTime"); + } + + } + + protected int getExpValue(EntityHuman entityhuman) { + return this.isChickenJockey() ? 10 : super.getExpValue(entityhuman); + } + + public void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + nbttagcompound.setBoolean("IsChickenJockey", this.bt); + nbttagcompound.setInt("EggLayTime", this.bs); + } + + public boolean isTypeNotPersistent() { + return this.isChickenJockey() && this.passenger == null; + } + + public void al() { + super.al(); + this.passenger.setPosition(this.locX + (0.1 * MathHelper.sin(this.aI * 3.1415927F / 180.0F)), this.locY + (this.length * 0.5F) + this.passenger.am() + 0.0, this.locZ - (0.1 * MathHelper.cos(this.aI * 3.1415927F / 180.0F))); + if (this.passenger instanceof EntityLiving) { + ((EntityLiving) this.passenger).aI = this.aI; + } + + } + + public boolean isChickenJockey() { + return this.bt; + } + + public void l(boolean flag) { + this.bt = flag; + } + + public EntityAgeable createChild(EntityAgeable entityageable) { + return this.b(entityageable); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityComplexPart.java b/azurite-server/src/main/java/net/minecraft/server/EntityComplexPart.java new file mode 100644 index 0000000..42d5358 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityComplexPart.java @@ -0,0 +1,35 @@ +package net.minecraft.server; + +public class EntityComplexPart extends Entity { + + public final IComplex owner; + public final String b; + + public EntityComplexPart(IComplex icomplex, String s, float f, float f1) { + super(icomplex.a()); + this.setSize(f, f1); + this.owner = icomplex; + this.b = s; + } + + protected void h() { + } + + protected void a(NBTTagCompound nbttagcompound) { + } + + protected void b(NBTTagCompound nbttagcompound) { + } + + public boolean ad() { + return true; + } + + public boolean damageEntity(DamageSource damagesource, float f) { + return !this.isInvulnerable(damagesource) && this.owner.a(this, damagesource, f); + } + + public boolean k(Entity entity) { + return this == entity || this.owner == entity; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityCow.java b/azurite-server/src/main/java/net/minecraft/server/EntityCow.java new file mode 100644 index 0000000..0abf54b --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityCow.java @@ -0,0 +1,112 @@ +package net.minecraft.server; + +// CraftBukkit start +import org.bukkit.craftbukkit.event.CraftEventFactory; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +// CraftBukkit end + +public class EntityCow extends EntityAnimal { + + public EntityCow(World world) { + super(world); + this.setSize(0.9F, 1.3F); + ((Navigation) this.getNavigation()).a(true); + this.goalSelector.a(0, new PathfinderGoalFloat(this)); + this.goalSelector.a(1, new PathfinderGoalPanic(this, 2.0D)); + this.goalSelector.a(2, new PathfinderGoalBreed(this, 1.0D)); + this.goalSelector.a(3, new PathfinderGoalTempt(this, 1.25D, Items.WHEAT, false)); + this.goalSelector.a(4, new PathfinderGoalFollowParent(this, 1.25D)); + this.goalSelector.a(5, new PathfinderGoalRandomStroll(this, 1.0D)); + this.goalSelector.a(6, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 6.0F)); + this.goalSelector.a(7, new PathfinderGoalRandomLookaround(this)); + } + + protected void initAttributes() { + super.initAttributes(); + this.getAttributeInstance(GenericAttributes.maxHealth).setValue(10.0D); + this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.20000000298023224D); + } + + protected String z() { + return "mob.cow.say"; + } + + protected String bo() { + return "mob.cow.hurt"; + } + + protected String bp() { + return "mob.cow.hurt"; + } + + protected void a(BlockPosition blockposition, Block block) { + this.makeSound("mob.cow.step", 0.15F, 1.0F); + } + + protected float bB() { + return 0.4F; + } + + protected Item getLoot() { + return Items.LEATHER; + } + + protected void dropDeathLoot(boolean flag, int i) { + int j = random.nextInt(3) + random.nextInt(1 + i); + + int k; + + for (k = 0; k < j; ++k) { + this.a(Items.LEATHER, 1); + } + + j = random.nextInt(3) + 1 + random.nextInt(1 + i); + + for (k = 0; k < j; ++k) { + if (this.isBurning()) { + this.a(Items.COOKED_BEEF, 1); + } else { + this.a(Items.BEEF, 1); + } + } + + } + + public boolean a(EntityHuman entityhuman) { + ItemStack itemstack = entityhuman.inventory.getItemInHand(); + + if (itemstack != null && itemstack.getItem() == Items.BUCKET && !entityhuman.abilities.canInstantlyBuild && !this.isBaby()) { + // CraftBukkit start - Got milk? + org.bukkit.Location loc = this.getBukkitEntity().getLocation(); + org.bukkit.event.player.PlayerBucketFillEvent event = CraftEventFactory.callPlayerBucketFillEvent(entityhuman, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), null, itemstack, Items.MILK_BUCKET); + + if (event.isCancelled()) { + return false; + } + + ItemStack result = CraftItemStack.asNMSCopy(event.getItemStack()); + if (--itemstack.count <= 0) { + entityhuman.inventory.setItem(entityhuman.inventory.itemInHandIndex, result); + } else if (!entityhuman.inventory.pickup(result)) { + entityhuman.drop(result, false); + } + // CraftBukkit end + + return true; + } else { + return super.a(entityhuman); + } + } + + public EntityCow b(EntityAgeable entityageable) { + return new EntityCow(this.world); + } + + public float getHeadHeight() { + return this.length; + } + + public EntityAgeable createChild(EntityAgeable entityageable) { + return this.b(entityageable); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityCreature.java b/azurite-server/src/main/java/net/minecraft/server/EntityCreature.java new file mode 100644 index 0000000..3e7bffc --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityCreature.java @@ -0,0 +1,123 @@ +package net.minecraft.server; + +import com.eatthepath.uuid.FastUUID; +import org.bukkit.event.entity.EntityUnleashEvent; + +import java.util.UUID; + +public abstract class EntityCreature extends EntityInsentient { + + public static final UUID bk = FastUUID.parseUUID("E199AD21-BA8A-4C53-8D13-6182D5C69D3A"); + public static final AttributeModifier bl = (new AttributeModifier(EntityCreature.bk, "Fleeing speed bonus", 2.0D, 2)).a(false); + private BlockPosition a; + private float b; + private final PathfinderGoal c; + private boolean bm; + + public EntityCreature(World world) { + super(world); + this.a = BlockPosition.ZERO; + this.b = -1.0F; + this.c = new PathfinderGoalMoveTowardsRestriction(this, 1.0D); + } + + public float a(BlockPosition blockposition) { + return 0.0F; + } + + public boolean bR() { + return super.bR() && this.a(new BlockPosition(this.locX, this.getBoundingBox().b, this.locZ)) >= 0.0F; + } + + public boolean cf() { + return !this.navigation.m(); + } + + public boolean cg() { + return this.e(new BlockPosition(this)); + } + + public boolean e(BlockPosition blockposition) { + return this.b == -1.0F || this.a.i(blockposition) < (double) (this.b * this.b); + } + + public void a(BlockPosition blockposition, int i) { + this.a = blockposition; + this.b = (float) i; + } + + public BlockPosition ch() { + return this.a; + } + + public float ci() { + return this.b; + } + + public void cj() { + this.b = -1.0F; + } + + public boolean ck() { + return this.b != -1.0F; + } + + protected void ca() { + super.ca(); + if (this.cc() && this.getLeashHolder() != null && this.getLeashHolder().world == this.world) { + Entity entity = this.getLeashHolder(); + + this.a(new BlockPosition((int) entity.locX, (int) entity.locY, (int) entity.locZ), 5); + float f = this.g(entity); + + if (this instanceof EntityTameableAnimal && ((EntityTameableAnimal) this).isSitting()) { + if (f > 10.0F) { + this.world.getServer().getPluginManager().callEvent(new EntityUnleashEvent(this.getBukkitEntity(), EntityUnleashEvent.UnleashReason.DISTANCE)); // CraftBukkit + this.unleash(true, true); + } + + return; + } + + if (!this.bm) { + this.goalSelector.a(2, this.c); + if (this.getNavigation() instanceof Navigation) { + ((Navigation) this.getNavigation()).a(false); + } + + this.bm = true; + } + + this.o(f); + if (f > 4.0F) { + this.getNavigation().a(entity, 1.0D); + } + + if (f > 6.0F) { + double d0 = (entity.locX - this.locX) / (double) f; + double d1 = (entity.locY - this.locY) / (double) f; + double d2 = (entity.locZ - this.locZ) / (double) f; + + this.motX += d0 * Math.abs(d0) * 0.4D; + this.motY += d1 * Math.abs(d1) * 0.4D; + this.motZ += d2 * Math.abs(d2) * 0.4D; + } + + if (f > 10.0F) { + this.world.getServer().getPluginManager().callEvent(new EntityUnleashEvent(this.getBukkitEntity(), EntityUnleashEvent.UnleashReason.DISTANCE)); // CraftBukkit + this.unleash(true, true); + } + } else if (!this.cc() && this.bm) { + this.bm = false; + this.goalSelector.a(this.c); + if (this.getNavigation() instanceof Navigation) { + ((Navigation) this.getNavigation()).a(true); + } + + this.cj(); + } + + } + + protected void o(float f) {} +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityCreeper.java b/azurite-server/src/main/java/net/minecraft/server/EntityCreeper.java new file mode 100644 index 0000000..bc42176 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityCreeper.java @@ -0,0 +1,236 @@ +package net.minecraft.server; + +// CraftBukkit start + +import org.bukkit.craftbukkit.event.CraftEventFactory; +import org.bukkit.event.entity.ExplosionPrimeEvent; +// CraftBukkit end + +public class EntityCreeper extends EntityMonster { + + private int fuseTicks; + private int maxFuseTicks = 30; + private int explosionRadius = 3; + private int bn = 0; + private int record = -1; // CraftBukkit + + public EntityCreeper(World world) { + super(world); + this.goalSelector.a(1, new PathfinderGoalFloat(this)); + this.goalSelector.a(2, new PathfinderGoalSwell(this)); + this.goalSelector.a(3, new PathfinderGoalAvoidTarget<>(this, EntityOcelot.class, 6.0F, 1.0D, 1.2D)); + this.goalSelector.a(4, new PathfinderGoalMeleeAttack(this, 1.0D, false)); + this.goalSelector.a(5, new PathfinderGoalRandomStroll(this, 0.8D)); + this.goalSelector.a(6, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 8.0F)); + this.goalSelector.a(6, new PathfinderGoalRandomLookaround(this)); + this.targetSelector.a(1, new PathfinderGoalNearestAttackableTarget<>(this, EntityHuman.class, true)); + this.targetSelector.a(2, new PathfinderGoalHurtByTarget(this, false)); + } + + protected void initAttributes() { + super.initAttributes(); + this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.25D); + } + + public int aE() { + return this.getGoalTarget() == null ? 3 : 3 + (int) (this.getHealth() - 1.0F); + } + + public void e(float f, float f1) { + super.e(f, f1); + this.fuseTicks = (int) ((float) this.fuseTicks + f * 1.5F); + if (this.fuseTicks > this.maxFuseTicks - 5) { + this.fuseTicks = this.maxFuseTicks - 5; + } + + } + + protected void h() { + super.h(); + this.datawatcher.a(16, (byte) -1); + this.datawatcher.a(17, (byte) 0); + this.datawatcher.a(18, (byte) 0); + } + + public void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + if (this.datawatcher.getByte(17) == 1) { + nbttagcompound.setBoolean("powered", true); + } + + nbttagcompound.setShort("Fuse", (short) this.maxFuseTicks); + nbttagcompound.setByte("ExplosionRadius", (byte) this.explosionRadius); + nbttagcompound.setBoolean("ignited", this.cn()); + } + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + this.datawatcher.watch(17, (byte) (nbttagcompound.getBoolean("powered") ? 1 : 0)); + if (nbttagcompound.hasKeyOfType("Fuse", 99)) { + this.maxFuseTicks = nbttagcompound.getShort("Fuse"); + } + + if (nbttagcompound.hasKeyOfType("ExplosionRadius", 99)) { + this.explosionRadius = nbttagcompound.getByte("ExplosionRadius"); + } + + if (nbttagcompound.getBoolean("ignited")) { + this.co(); + } + + } + + public void t_() { + if (this.isAlive()) { + if (this.cn()) { + this.a(1); + } + + int i = this.cm(); + + if (i > 0 && this.fuseTicks == 0) { + this.makeSound("creeper.primed", 1.0F, 0.5F); + } + + this.fuseTicks += i; + if (this.fuseTicks < 0) { + this.fuseTicks = 0; + } + + if (this.fuseTicks >= this.maxFuseTicks) { + this.fuseTicks = this.maxFuseTicks; + this.cr(); + } + } + + super.t_(); + } + + protected String bo() { + return "mob.creeper.say"; + } + + protected String bp() { + return "mob.creeper.death"; + } + + public void die(DamageSource damagesource) { + // super.die(damagesource); // CraftBukkit - Moved to end + if (damagesource.getEntity() instanceof EntitySkeleton) { + int i = Item.getId(Items.RECORD_13); + int j = Item.getId(Items.RECORD_WAIT); + + // CraftBukkit start - Store record for now, drop in dropDeathLoot + // this.a(Item.getById(k), 1); + this.record = i + random.nextInt(j - i + 1); + // CraftBukkit end + } else if (damagesource.getEntity() instanceof EntityCreeper && damagesource.getEntity() != this && ((EntityCreeper) damagesource.getEntity()).isPowered() && ((EntityCreeper) damagesource.getEntity()).cp()) { + ((EntityCreeper) damagesource.getEntity()).cq(); + // CraftBukkit start + // this.a(new ItemStack(Items.SKULL, 1, 4), 0.0F); + headDrop = new ItemStack(Items.SKULL, 1, 4); + // CraftBukkit end + } + + super.die(damagesource); // CraftBukkit - Moved from above + } + + // CraftBukkit start - Whole method + @Override + protected void dropDeathLoot(boolean flag, int i) { + super.dropDeathLoot(flag, i); + + // Drop a music disc? + if (this.record != -1) { + this.a(Item.getById(this.record), 1); + this.record = -1; + } + } + // CraftBukkit end + + public boolean r(Entity entity) { + return true; + } + + public boolean isPowered() { + return this.datawatcher.getByte(17) == 1; + } + + public void setPowered(boolean powered) { + if (!powered) { + this.datawatcher.watch(17, (byte) 0); + } else { + this.datawatcher.watch(17, (byte) 1); + } + // CraftBukkit end + } + + protected Item getLoot() { + return Items.GUNPOWDER; + } + + public int cm() { + return this.datawatcher.getByte(16); + } + + public void a(int i) { + this.datawatcher.watch(16,(byte) i); + } + + public void onLightningStrike(EntityLightning entitylightning) { + super.onLightningStrike(entitylightning); + // CraftBukkit start + if (CraftEventFactory.callCreeperPowerEvent(this, entitylightning, org.bukkit.event.entity.CreeperPowerEvent.PowerCause.LIGHTNING).isCancelled()) { + return; + } + + this.setPowered(true); + } + + protected boolean a(EntityHuman entityhuman) { + ItemStack itemstack = entityhuman.inventory.getItemInHand(); + + if (itemstack != null && itemstack.getItem() == Items.FLINT_AND_STEEL) { + this.world.makeSound(this.locX + 0.5D, this.locY + 0.5D, this.locZ + 0.5D, "fire.ignite", 1.0F, random.nextFloat() * 0.4F + 0.8F); + entityhuman.bw(); + this.co(); + itemstack.damage(1, entityhuman); + return true; + } + + return super.a(entityhuman); + } + + private void cr() { + + boolean flag = this.world.getGameRules().getBoolean("mobGriefing"); + float f = this.isPowered() ? 2.0F : 1.0F; + + ExplosionPrimeEvent event = new ExplosionPrimeEvent(this.getBukkitEntity(), this.explosionRadius * f, false); + this.world.getServer().getPluginManager().callEvent(event); + if (!event.isCancelled()) { + this.world.createExplosion(this, this.locX, this.locY, this.locZ, event.getRadius(), event.getFire(), flag); + this.die(); + } else { + fuseTicks = 0; + } + // CraftBukkit end + + } + + public boolean cn() { + return this.datawatcher.getByte(18) != 0; + } + + public void co() { + this.datawatcher.watch(18, (byte) 1); + } + + public boolean cp() { + return this.bn < 1 && this.world.getGameRules().getBoolean("doMobLoot"); + } + + public void cq() { + ++this.bn; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityDamageSource.java b/azurite-server/src/main/java/net/minecraft/server/EntityDamageSource.java new file mode 100644 index 0000000..58756f2 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityDamageSource.java @@ -0,0 +1,49 @@ +package net.minecraft.server; + +public class EntityDamageSource extends DamageSource { + + protected Entity q; + private boolean r = false; + private boolean isCrit = false; // Rivals + + public EntityDamageSource(String s, Entity entity) { + super(s); + this.q = entity; + } + + public EntityDamageSource v() { + this.r = true; + return this; + } + + // Rivals start + public boolean isCrit() { + return this.isCrit; + } + + public EntityDamageSource setCrit(boolean crit) { + this.isCrit = crit; + return this; + } + // Rivals end + + public boolean w() { + return this.r; + } + + public Entity getEntity() { + return this.q; + } + + public IChatBaseComponent getLocalizedDeathMessage(EntityLiving entityliving) { + ItemStack itemstack = this.q instanceof EntityLiving ? ((EntityLiving) this.q).bA() : null; + String s = "death.attack." + this.translationIndex; + String s1 = s + ".item"; + + return itemstack != null && itemstack.hasName() && LocaleI18n.c(s1) ? new ChatMessage(s1, new Object[] { entityliving.getScoreboardDisplayName(), this.q.getScoreboardDisplayName(), itemstack.C()}) : new ChatMessage(s, new Object[] { entityliving.getScoreboardDisplayName(), this.q.getScoreboardDisplayName()}); + } + + public boolean r() { + return this.q != null && this.q instanceof EntityLiving && !(this.q instanceof EntityHuman); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityDamageSourceIndirect.java b/azurite-server/src/main/java/net/minecraft/server/EntityDamageSourceIndirect.java new file mode 100644 index 0000000..10eaa1f --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityDamageSourceIndirect.java @@ -0,0 +1,34 @@ +package net.minecraft.server; + +public class EntityDamageSourceIndirect extends EntityDamageSource { + + private final Entity owner; + + public EntityDamageSourceIndirect(String s, Entity entity, Entity entity1) { + super(s, entity); + this.owner = entity1; + } + + public Entity i() { + return this.q; + } + + public Entity getEntity() { + return this.owner; + } + + public IChatBaseComponent getLocalizedDeathMessage(EntityLiving entityliving) { + IChatBaseComponent ichatbasecomponent = this.owner == null ? this.q.getScoreboardDisplayName() : this.owner.getScoreboardDisplayName(); + ItemStack itemstack = this.owner instanceof EntityLiving ? ((EntityLiving) this.owner).bA() : null; + String s = "death.attack." + this.translationIndex; + String s1 = s + ".item"; + + return itemstack != null && itemstack.hasName() && LocaleI18n.c(s1) ? new ChatMessage(s1, entityliving.getScoreboardDisplayName(), ichatbasecomponent, itemstack.C()) : new ChatMessage(s, entityliving.getScoreboardDisplayName(), ichatbasecomponent); + } + + // CraftBukkit start + public Entity getProximateDamageSource() { + return super.getEntity(); + } + // CraftBukkit end +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityEgg.java b/azurite-server/src/main/java/net/minecraft/server/EntityEgg.java new file mode 100644 index 0000000..59a4ac8 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityEgg.java @@ -0,0 +1,75 @@ +package net.minecraft.server; + +// CraftBukkit start + +import dev.azurite.spigot.configs.AzuriteConfig; +import org.bukkit.entity.Ageable; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import org.bukkit.event.player.PlayerEggThrowEvent; +// CraftBukkit end + +public class EntityEgg extends EntityProjectile { + + public EntityEgg(World world) { + super(world); + } + + public EntityEgg(World world, EntityLiving entityliving) { + super(world, entityliving); + } + + public EntityEgg(World world, double d0, double d1, double d2) { + super(world, d0, d1, d2); + } + + @Override + public float getRandomness() { + return AzuriteConfig.eggTrajectoryRandomness.getValue(); + } + + protected void a(MovingObjectPosition movingobjectposition) { + if (movingobjectposition.entity != null) { + movingobjectposition.entity.damageEntity(DamageSource.projectile(this, this.getShooter()), 0.0F); + } + + // CraftBukkit start - Fire PlayerEggThrowEvent + boolean hatching = random.nextInt(8) == 0; + int numHatching = (random.nextInt(32) == 0) ? 4 : 1; + if (!hatching) { + numHatching = 0; + } + + EntityType hatchingType = EntityType.CHICKEN; + + Entity shooter = this.getShooter(); + if (shooter instanceof EntityPlayer) { + Player player = (Player) shooter.getBukkitEntity(); + + PlayerEggThrowEvent event = new PlayerEggThrowEvent(player, (org.bukkit.entity.Egg) this.getBukkitEntity(), hatching, (byte) numHatching, hatchingType); + this.world.getServer().getPluginManager().callEvent(event); + + hatching = event.isHatching(); + numHatching = event.getNumHatches(); + hatchingType = event.getHatchingType(); + } + + if (hatching) { + for (int k = 0; k < numHatching; k++) { + Entity entity = world.getWorld().createEntity(new org.bukkit.Location(world.getWorld(), this.locX, this.locY, this.locZ, this.yaw, 0.0F), hatchingType.getEntityClass()); + if (entity.getBukkitEntity() instanceof Ageable) { + ((Ageable) entity.getBukkitEntity()).setBaby(); + } + world.getWorld().addEntity(entity, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.EGG); + } + } + // CraftBukkit end + + for (int j = 0; j < 8; ++j) { + this.world.addParticle(EnumParticle.ITEM_CRACK, this.locX, this.locY, this.locZ, ((double) random.nextFloat() - 0.5D) * 0.08D, ((double) random.nextFloat() - 0.5D) * 0.08D, ((double) random.nextFloat() - 0.5D) * 0.08D, Item.getId(Items.EGG)); + } + + this.die(); + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityEnderCrystal.java b/azurite-server/src/main/java/net/minecraft/server/EntityEnderCrystal.java new file mode 100644 index 0000000..c5fd40c --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityEnderCrystal.java @@ -0,0 +1,86 @@ +package net.minecraft.server; + +// CraftBukkit start + +import org.bukkit.craftbukkit.event.CraftEventFactory; +import org.bukkit.event.entity.ExplosionPrimeEvent; +// CraftBukkit end + +public class EntityEnderCrystal extends Entity { + + public int a; + public int b; + + public EntityEnderCrystal(World world) { + super(world); + this.k = true; + this.setSize(2.0F, 2.0F); + this.b = 5; + this.a = random.nextInt(100000); + } + + protected boolean s_() { + return false; + } + + protected void h() { + this.datawatcher.a(8, this.b); + } + + public void t_() { + this.lastX = this.locX; + this.lastY = this.locY; + this.lastZ = this.locZ; + ++this.a; + this.datawatcher.watch(8, this.b); + int i = MathHelper.floor(this.locX); + int j = MathHelper.floor(this.locY); + int k = MathHelper.floor(this.locZ); + + if (this.world.worldProvider instanceof WorldProviderTheEnd && this.world.getType(i, j, k).getBlock() != Blocks.FIRE) { + // CraftBukkit start + if (!CraftEventFactory.callBlockIgniteEvent(this.world, i, j, k, this).isCancelled()) { + this.world.setTypeUpdate(new BlockPosition(i, j, k), Blocks.FIRE.getBlockData()); + } + // CraftBukkit end + } + + } + + protected void b(NBTTagCompound nbttagcompound) { + } + + protected void a(NBTTagCompound nbttagcompound) { + } + + public boolean ad() { + return true; + } + + public boolean damageEntity(DamageSource damagesource, float f) { + if (this.isInvulnerable(damagesource)) { + return false; + } else { + if (!this.dead) { + // CraftBukkit start - All non-living entities need this + if (CraftEventFactory.handleNonLivingEntityDamageEvent(this, damagesource, f)) { + return false; + } + // CraftBukkit end + this.b = 0; + this.die(); + // CraftBukkit start + ExplosionPrimeEvent event = new ExplosionPrimeEvent(this.getBukkitEntity(), 6.0F, false); + this.world.getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { + this.dead = false; + return false; + } + this.world.createExplosion(this, this.locX, this.locY, this.locZ, event.getRadius(), event.getFire(), true); + // CraftBukkit end + } + + return true; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityEnderDragon.java b/azurite-server/src/main/java/net/minecraft/server/EntityEnderDragon.java new file mode 100644 index 0000000..3068a7b --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityEnderDragon.java @@ -0,0 +1,661 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; +import org.bukkit.Bukkit; +import org.bukkit.block.BlockState; +import org.bukkit.craftbukkit.event.CraftEventFactory; +import org.bukkit.craftbukkit.util.BlockStateListPopulator; +import org.bukkit.event.entity.EntityCreatePortalEvent; +import org.bukkit.event.entity.EntityExplodeEvent; +import org.bukkit.event.entity.EntityRegainHealthEvent; +import org.bukkit.event.entity.EntityTargetEvent; + +import java.util.ArrayList; +import java.util.List; + +public class EntityEnderDragon extends EntityInsentient implements IComplex, IMonster { + + public double a; + public double b; + public double c; + public double[][] bk = new double[64][3]; + public int bl = -1; + public EntityComplexPart[] children; + public EntityComplexPart bn; + public EntityComplexPart bo; + public EntityComplexPart bp; + public EntityComplexPart bq; + public EntityComplexPart br; + public EntityComplexPart bs; + public EntityComplexPart bt; + public float bu; + public float bv; + public boolean bw; + public boolean bx; + public Entity target; + public int by; + public EntityEnderCrystal bz; + private final Explosion explosionSource = new Explosion(null, this, Double.NaN, Double.NaN, Double.NaN, Float.NaN, true, true); // CraftBukkit - reusable source for CraftTNTPrimed.getSource() + + public EntityEnderDragon(World world) { + super(world); + this.children = new EntityComplexPart[] { this.bn = new EntityComplexPart(this, "head", 6.0F, 6.0F), this.bo = new EntityComplexPart(this, "body", 8.0F, 8.0F), this.bp = new EntityComplexPart(this, "tail", 4.0F, 4.0F), this.bq = new EntityComplexPart(this, "tail", 4.0F, 4.0F), this.br = new EntityComplexPart(this, "tail", 4.0F, 4.0F), this.bs = new EntityComplexPart(this, "wing", 4.0F, 4.0F), this.bt = new EntityComplexPart(this, "wing", 4.0F, 4.0F)}; + this.setHealth(this.getMaxHealth()); + this.setSize(16.0F, 8.0F); + this.noclip = true; + this.fireProof = true; + this.b = 100.0D; + this.ah = true; + } + + protected void initAttributes() { + super.initAttributes(); + this.getAttributeInstance(GenericAttributes.maxHealth).setValue(200.0D); + } + + protected void h() { + super.h(); + } + + public double[] b(int i, float f) { + if (this.getHealth() <= 0.0F) { + f = 0.0F; + } + + f = 1.0F - f; + int j = this.bl - i & 63; + int k = this.bl - i - 1 & 63; + double[] adouble = new double[3]; + double d0 = this.bk[j][0]; + double d1 = MathHelper.g(this.bk[k][0] - d0); + + adouble[0] = d0 + d1 * (double) f; + d0 = this.bk[j][1]; + d1 = this.bk[k][1] - d0; + adouble[1] = d0 + d1 * (double) f; + adouble[2] = this.bk[j][2] + (this.bk[k][2] - this.bk[j][2]) * (double) f; + return adouble; + } + + public void m() { + float f; + float f1; + + this.bu = this.bv; + float f2; + + if (this.getHealth() <= 0.0F) { + f = (random.nextFloat() - 0.5F) * 8.0F; + f1 = (random.nextFloat() - 0.5F) * 4.0F; + f2 = (random.nextFloat() - 0.5F) * 8.0F; + this.world.addParticle(EnumParticle.EXPLOSION_LARGE, this.locX + (double) f, this.locY + 2.0D + (double) f1, this.locZ + (double) f2, 0.0D, 0.0D, 0.0D, EnumParticle.EMPTY_ARRAY); + } else { + this.n(); + f = 0.2F / (MathHelper.sqrt(this.motX * this.motX + this.motZ * this.motZ) * 10.0F + 1.0F); + f *= (float) Math.pow(2.0D, this.motY); + if (this.bx) { + this.bv += f * 0.5F; + } else { + this.bv += f; + } + + this.yaw = MathHelper.g(this.yaw); + if (this.ce()) { + this.bv = 0.5F; + } else { + if (this.bl < 0) { + for (int i = 0; i < this.bk.length; ++i) { + this.bk[i][0] = this.yaw; + this.bk[i][1] = this.locY; + } + } + + if (++this.bl == this.bk.length) { + this.bl = 0; + } + + this.bk[this.bl][0] = this.yaw; + this.bk[this.bl][1] = this.locY; + double d0 = this.b - this.locY; + double d1 = this.c - this.locZ; + double d3 = this.a - this.locX; + double d2 = d3 * d3 + d0 * d0 + d1 * d1; + float f3; + + double d4; + + if (this.target != null) { + this.a = this.target.locX; + this.c = this.target.locZ; + double d5 = this.a - this.locX; + double d6 = this.c - this.locZ; + double d7 = Math.sqrt(d5 * d5 + d6 * d6); + + d4 = 0.4000000059604645D + d7 / 80.0D - 1.0D; + if (d4 > 10.0D) { + d4 = 10.0D; + } + + this.b = this.target.boundingBox.b + d4; + } else { + this.a += random.nextGaussian() * 2.0D; + this.c += random.nextGaussian() * 2.0D; + } + + if (this.bw || d2 < 100.0D || d2 > 22500.0D || this.positionChanged || this.E) { + this.cf(); + } + + d0 /= MathHelper.sqrt(d3 * d3 + d1 * d1); + f3 = 0.6F; + d0 = MathHelper.a(d0, -f3, f3); + this.motY += d0 * 0.10000000149011612D; + this.yaw = MathHelper.g(this.yaw); + double d8 = 180.0D - MathHelper.b(d3, d1) * 180.0D / 3.1415927410125732D; + double d9 = MathHelper.g(d8 - (double) this.yaw); + + if (d9 > 50.0D) { + d9 = 50.0D; + } + + if (d9 < -50.0D) { + d9 = -50.0D; + } + + Vec3D vec3d = (new Vec3D(this.a - this.locX, this.b - this.locY, this.c - this.locZ)).a(); + + d4 = -MathHelper.cos(this.yaw * 3.1415927F / 180.0F); + Vec3D vec3d1 = (new Vec3D(MathHelper.sin(this.yaw * 3.1415927F / 180.0F), this.motY, d4)).a(); + float f4 = ((float) vec3d1.b(vec3d) + 0.5F) / 1.5F; + + if (f4 < 0.0F) { + f4 = 0.0F; + } + + this.bb *= 0.8F; + float f5 = MathHelper.sqrt(this.motX * this.motX + this.motZ * this.motZ) + 1.0F; + double d10 = Math.sqrt(this.motX * this.motX + this.motZ * this.motZ) + 1.0D; + + if (d10 > 40.0D) { + d10 = 40.0D; + } + + this.bb = (float) ((double) this.bb + d9 * (0.699999988079071D / d10 / (double) f5)); + this.yaw += this.bb * 0.1F; + float f6 = (float) (2.0D / (d10 + 1.0D)); + float f7 = 0.06F; + + this.a(0.0F, -1.0F, f7 * (f4 * f6 + (1.0F - f6))); + if (this.bx) { + this.move(this.motX * 0.800000011920929D, this.motY * 0.800000011920929D, this.motZ * 0.800000011920929D); + } else { + this.move(this.motX, this.motY, this.motZ); + } + + Vec3D vec3d2 = (new Vec3D(this.motX, this.motY, this.motZ)).a(); + float f8 = ((float) vec3d2.b(vec3d1) + 1.0F) / 2.0F; + + f8 = 0.8F + 0.15F * f8; + this.motX *= f8; + this.motZ *= f8; + this.motY *= 0.9100000262260437D; + + this.aI = this.yaw; + this.bn.width = this.bn.length = 3.0F; + this.bp.width = this.bp.length = 2.0F; + this.bq.width = this.bq.length = 2.0F; + this.br.width = this.br.length = 2.0F; + this.bo.length = 3.0F; + this.bo.width = 5.0F; + this.bs.length = 2.0F; + this.bs.width = 4.0F; + this.bt.length = 3.0F; + this.bt.width = 4.0F; + f1 = (float) (this.b(5, 1.0F)[1] - this.b(10, 1.0F)[1]) * 10.0F / 180.0F * 3.1415927F; + f2 = MathHelper.cos(f1); + float f9 = -MathHelper.sin(f1); + float f10 = this.yaw * 3.1415927F / 180.0F; + float f11 = MathHelper.sin(f10); + float f12 = MathHelper.cos(f10); + + this.bo.t_(); + this.bo.setPositionRotation(this.locX + (double) (f11 * 0.5F), this.locY, this.locZ - (double) (f12 * 0.5F), 0.0F, 0.0F); + this.bs.t_(); + this.bs.setPositionRotation(this.locX + (double) (f12 * 4.5F), this.locY + 2.0D, this.locZ + (double) (f11 * 4.5F), 0.0F, 0.0F); + this.bt.t_(); + this.bt.setPositionRotation(this.locX - (double) (f12 * 4.5F), this.locY + 2.0D, this.locZ - (double) (f11 * 4.5F), 0.0F, 0.0F); + if (this.hurtTicks == 0) { + this.a(this.world.getEntities(this, this.bs.boundingBox.grow(4.0D, 2.0D, 4.0D).c(0.0D, -2.0D, 0.0D))); + this.a(this.world.getEntities(this, this.bt.boundingBox.grow(4.0D, 2.0D, 4.0D).c(0.0D, -2.0D, 0.0D))); + this.b(this.world.getEntities(this, this.bn.boundingBox.grow(1.0D, 1.0D, 1.0D))); + } + + double[] adouble = this.b(5, 1.0F); + double[] adouble1 = this.b(0, 1.0F); + + f3 = MathHelper.sin(this.yaw * 3.1415927F / 180.0F - this.bb * 0.01F); + float f13 = MathHelper.cos(this.yaw * 3.1415927F / 180.0F - this.bb * 0.01F); + + this.bn.t_(); + this.bn.setPositionRotation(this.locX + (double) (f3 * 5.5F * f2), this.locY + (adouble1[1] - adouble[1]) + (double) (f9 * 5.5F), this.locZ - (double) (f13 * 5.5F * f2), 0.0F, 0.0F); + + for (int j = 0; j < 3; ++j) { + EntityComplexPart entitycomplexpart = null; + + if (j == 0) { + entitycomplexpart = this.bp; + } + + if (j == 1) { + entitycomplexpart = this.bq; + } + + if (j == 2) { + entitycomplexpart = this.br; + } + + double[] adouble2 = this.b(12 + j * 2, 1.0F); + float f14 = this.yaw * 3.1415927F / 180.0F + this.b(adouble2[0] - adouble[0]) * 3.1415927F / 180.0F; + float f15 = MathHelper.sin(f14); + float f16 = MathHelper.cos(f14); + float f17 = 1.5F; + float f18 = (float) (j + 1) * 2.0F; + + entitycomplexpart.t_(); + entitycomplexpart.setPositionRotation(this.locX - (double) ((f11 * f17 + f15 * f18) * f2), this.locY + (adouble2[1] - adouble[1]) - (double) ((f18 + f17) * f9) + 1.5D, this.locZ + (double) ((f12 * f17 + f16 * f18) * f2), 0.0F, 0.0F); + } + + this.bx = this.b(this.bn.boundingBox) | this.b(this.bo.boundingBox); + + + } + } + } + + private void n() { + if (this.bz != null) { + if (this.bz.dead) { + + CraftEventFactory.entityDamage = this.bz; // CraftBukkit + this.a(this.bn, DamageSource.explosion(null), 10.0F); + CraftEventFactory.entityDamage = null; // CraftBukkit + + this.bz = null; + } else if (this.ticksLived % 10 == 0 && this.getHealth() < this.getMaxHealth()) { + // CraftBukkit start + EntityRegainHealthEvent event = new EntityRegainHealthEvent(this.getBukkitEntity(), 1.0D, EntityRegainHealthEvent.RegainReason.ENDER_CRYSTAL); + this.world.getServer().getPluginManager().callEvent(event); + + if (!event.isCancelled()) { + this.setHealth((float) (this.getHealth() + event.getAmount())); + } + // CraftBukkit end + } + } + + if (random.nextInt(10) == 0) { + float f = 32.0F; + List list = this.world.a(EntityEnderCrystal.class, this.boundingBox.grow(f, f, f)); + EntityEnderCrystal entityendercrystal = null; + double d0 = Double.MAX_VALUE; + + for (EntityEnderCrystal entityendercrystal1 : list) { + double d1 = entityendercrystal1.h(this); + + if (d1 < d0) { + d0 = d1; + entityendercrystal = entityendercrystal1; + } + } + + this.bz = entityendercrystal; + } + + } + + private void a(List list) { + double d0 = (this.bo.boundingBox.a + this.bo.boundingBox.d) / 2.0D; + double d1 = (this.bo.boundingBox.c + this.bo.boundingBox.f) / 2.0D; + + for (Entity entity : list) { + if (entity instanceof EntityLiving) { + double d2 = entity.locX - d0; + double d3 = entity.locZ - d1; + double d4 = d2 * d2 + d3 * d3; + + entity.g(d2 / d4 * 4.0D, 0.20000000298023224D, d3 / d4 * 4.0D); + } + } + + } + + private void b(List list) { + for (Entity entity : list) { + if (entity instanceof EntityLiving) { + entity.damageEntity(DamageSource.mobAttack(this), 10.0F); + this.a(this, entity); + } + } + + } + + private void cf() { + this.bw = false; + ArrayList arraylist = Lists.newArrayList(this.world.players); + + arraylist.removeIf(EntityHuman::isSpectator); + + if (random.nextInt(2) == 0 && !arraylist.isEmpty()) { + // CraftBukkit start + Entity target = this.world.players.get(random.nextInt(this.world.players.size())); + EntityTargetEvent event = new EntityTargetEvent(this.getBukkitEntity(), target.getBukkitEntity(), EntityTargetEvent.TargetReason.RANDOM_TARGET); + this.world.getServer().getPluginManager().callEvent(event); + + if (!event.isCancelled()) { + if (event.getTarget() == null) { + this.target = null; + } else { + this.target = ((org.bukkit.craftbukkit.entity.CraftEntity) event.getTarget()).getHandle(); + } + } + // CraftBukkit end + } else { + boolean flag; + + do { + this.a = 0.0D; + this.b = 70.0F + random.nextFloat() * 50.0F; + this.c = 0.0D; + this.a += random.nextFloat() * 120.0F - 60.0F; + this.c += random.nextFloat() * 120.0F - 60.0F; + double d0 = this.locX - this.a; + double d1 = this.locY - this.b; + double d2 = this.locZ - this.c; + + flag = d0 * d0 + d1 * d1 + d2 * d2 > 100.0D; + } while (!flag); + + this.target = null; + } + + } + + private float b(double d0) { + return (float) MathHelper.g(d0); + } + + private boolean b(AxisAlignedBB axisalignedbb) { + int i = MathHelper.floor(axisalignedbb.a); + int j = MathHelper.floor(axisalignedbb.b); + int k = MathHelper.floor(axisalignedbb.c); + int l = MathHelper.floor(axisalignedbb.d); + int i1 = MathHelper.floor(axisalignedbb.e); + int j1 = MathHelper.floor(axisalignedbb.f); + boolean flag = false; + boolean flag1 = false; + + // CraftBukkit start - Create a list to hold all the destroyed blocks + List destroyedBlocks = new ArrayList<>(); + org.bukkit.craftbukkit.CraftWorld craftWorld = this.world.getWorld(); + // CraftBukkit end + + for (int k1 = i; k1 <= l; ++k1) { + for (int l1 = j; l1 <= i1; ++l1) { + for (int i2 = k; i2 <= j1; ++i2) { + Block block = this.world.getType(k1, l1, i2).getBlock(); + + if (block.getMaterial() != Material.AIR) { + if (block != Blocks.BARRIER && block != Blocks.OBSIDIAN && block != Blocks.END_STONE && block != Blocks.BEDROCK && block != Blocks.COMMAND_BLOCK && this.world.getGameRules().getBoolean("mobGriefing")) { + // CraftBukkit start - Add blocks to list rather than destroying them + // flag1 = this.world.setAir(new BlockPosition(blockposition)) || flag1; + flag1 = true; + destroyedBlocks.add(craftWorld.getBlockAt(k1, l1, i2)); + // CraftBukkit end + } else { + flag = true; + } + } + } + } + } + + if (flag1) { + // CraftBukkit start - Set off an EntityExplodeEvent for the dragon exploding all these blocks + org.bukkit.entity.Entity bukkitEntity = this.getBukkitEntity(); + EntityExplodeEvent event = new EntityExplodeEvent(bukkitEntity, bukkitEntity.getLocation(), destroyedBlocks, 0F); + Bukkit.getPluginManager().callEvent(event); + if (event.isCancelled()) { + // This flag literally means 'Dragon hit something hard' (Obsidian, White Stone or Bedrock) and will cause the dragon to slow down. + // We should consider adding an event extension for it, or perhaps returning true if the event is cancelled. + return flag; + } else if (event.getYield() == 0F) { + // Yield zero ==> no drops + for (org.bukkit.block.Block block : event.blockList()) { + this.world.setAir(new BlockPosition(block.getX(), block.getY(), block.getZ())); + } + } else { + for (org.bukkit.block.Block block : event.blockList()) { + org.bukkit.Material blockId = block.getType(); + if (blockId == org.bukkit.Material.AIR) { + continue; + } + + Block nmsBlock = org.bukkit.craftbukkit.util.CraftMagicNumbers.getBlock(blockId); + + BlockPosition pos = new BlockPosition(block.getX(), block.getY(), block.getZ()); + if (nmsBlock.a(explosionSource)) { + nmsBlock.dropNaturally(this.world, pos, nmsBlock.fromLegacyData(block.getData()), event.getYield(), 0); + } + + nmsBlock.wasExploded(world, pos, explosionSource); + + this.world.setAir(pos); + } + } + // CraftBukkit end + double d0 = axisalignedbb.a + (axisalignedbb.d - axisalignedbb.a) * random.nextFloat(); + double d1 = axisalignedbb.b + (axisalignedbb.e - axisalignedbb.b) * random.nextFloat(); + double d2 = axisalignedbb.c + (axisalignedbb.f - axisalignedbb.c) * random.nextFloat(); + + this.world.addParticle(EnumParticle.EXPLOSION_LARGE, d0, d1, d2, 0.0D, 0.0D, 0.0D, EnumParticle.EMPTY_ARRAY); + } + + return flag; + } + + public boolean a(EntityComplexPart entitycomplexpart, DamageSource damagesource, float f) { + if (entitycomplexpart != this.bn) { + f = f / 4.0F + 1.0F; + } + + float f1 = this.yaw * 3.1415927F / 180.0F; + float f2 = MathHelper.sin(f1); + float f3 = MathHelper.cos(f1); + + this.a = this.locX + (double) (f2 * 5.0F) + (double) ((random.nextFloat() - 0.5F) * 2.0F); + this.b = this.locY + (double) (random.nextFloat() * 3.0F) + 1.0D; + this.c = this.locZ - (double) (f3 * 5.0F) + (double) ((random.nextFloat() - 0.5F) * 2.0F); + this.target = null; + if (damagesource.getEntity() instanceof EntityHuman || damagesource.isExplosion()) { + this.dealDamage(damagesource, f); + } + + return true; + } + + public boolean damageEntity(DamageSource damagesource, float f) { + if (damagesource instanceof EntityDamageSource && ((EntityDamageSource) damagesource).w()) { + this.dealDamage(damagesource, f); + } + + return false; + } + + protected boolean dealDamage(DamageSource damagesource, float f) { + return super.damageEntity(damagesource, f); + } + + public void G() { + this.die(); + } + + protected void aZ() { + if (this.dead) return; // CraftBukkit - can't kill what's already dead + ++this.by; + if (this.by >= 180 && this.by <= 200) { + float f = (random.nextFloat() - 0.5F) * 8.0F; + float f1 = (random.nextFloat() - 0.5F) * 4.0F; + float f2 = (random.nextFloat() - 0.5F) * 8.0F; + + this.world.addParticle(EnumParticle.EXPLOSION_HUGE, this.locX + (double) f, this.locY + 2.0D + (double) f1, this.locZ + (double) f2, 0.0D, 0.0D, 0.0D, EnumParticle.EMPTY_ARRAY); + } + + boolean flag = this.world.getGameRules().getBoolean("doMobLoot"); + int i; + int j; + + if (this.by > 150 && this.by % 5 == 0 && flag) { + i = this.expToDrop / 12; // CraftBukkit - drop experience as dragon falls from sky. use experience drop from death event. This is now set in getExpReward() + + while (i > 0) { + j = EntityExperienceOrb.getOrbValue(i); + i -= j; + this.world.addEntity(new EntityExperienceOrb(this.world, this.locX, this.locY, this.locZ, j)); + } + } + + if (this.by == 1) { + // CraftBukkit start - Use relative location for far away sounds + // this.world.a(1018, new BlockPosition(this), 0); + int viewDistance = this.world.getServer().getViewDistance() * 16; + for (EntityPlayer player : MinecraftServer.getServer().getPlayerList().players) { + double deltaX = this.locX - player.locX; + double deltaZ = this.locZ - player.locZ; + double distanceSquared = deltaX * deltaX + deltaZ * deltaZ; + if ( world.spigotConfig.dragonDeathSoundRadius > 0 && distanceSquared > world.spigotConfig.dragonDeathSoundRadius * world.spigotConfig.dragonDeathSoundRadius ) continue; // Spigot + if (distanceSquared > viewDistance * viewDistance) { + double deltaLength = Math.sqrt(distanceSquared); + double relativeX = player.locX + (deltaX / deltaLength) * viewDistance; + double relativeZ = player.locZ + (deltaZ / deltaLength) * viewDistance; + player.playerConnection.sendPacket(new PacketPlayOutWorldEvent(1018, new BlockPosition(relativeX, this.locY, relativeZ), 0, true)); + } else { + player.playerConnection.sendPacket(new PacketPlayOutWorldEvent(1018, new BlockPosition(this.locX, this.locY, this.locZ), 0, true)); + } + } + // CraftBukkit end + } + + this.move(0.0D, 0.10000000149011612D, 0.0D); + this.aI = this.yaw += 20.0F; + if (this.by == 200) { + if (flag) { + i = this.expToDrop - (10 * this.expToDrop / 12); // CraftBukkit - drop the remaining experience + + while (i > 0) { + j = EntityExperienceOrb.getOrbValue(i); + i -= j; + this.world.addEntity(new EntityExperienceOrb(this.world, this.locX, this.locY, this.locZ, j)); + } + } + + this.a(new BlockPosition(this.locX, 64.0D, this.locZ)); + this.die(); + } + + } + + private void a(BlockPosition blockposition) { + + // CraftBukkit start - Replace any "this.world" in the following with just "world"! + BlockStateListPopulator world = new BlockStateListPopulator(this.world.getWorld()); + + for (int i = -1; i <= 32; ++i) { + for (int j = -4; j <= 4; ++j) { + for (int k = -4; k <= 4; ++k) { + double d2 = j * j + k * k; + + if (d2 <= 12.25D) { + BlockPosition blockposition1 = blockposition.a(j, i, k); + + if (i < 0) { + if (d2 <= 6.25D) { + world.setTypeUpdate(blockposition1, Blocks.BEDROCK.getBlockData()); + } + } else if (i > 0) { + world.setTypeUpdate(blockposition1, Blocks.AIR.getBlockData()); + } else if (d2 > 6.25D) { + world.setTypeUpdate(blockposition1, Blocks.BEDROCK.getBlockData()); + } else { + world.setTypeUpdate(blockposition1, Blocks.END_PORTAL.getBlockData()); + } + } + } + } + } + + world.setTypeUpdate(blockposition, Blocks.BEDROCK.getBlockData()); + world.setTypeUpdate(blockposition.up(), Blocks.BEDROCK.getBlockData()); + BlockPosition blockposition2 = blockposition.up(2); + + world.setTypeUpdate(blockposition2, Blocks.BEDROCK.getBlockData()); + world.setTypeUpdate(blockposition2.west(), Blocks.TORCH.getBlockData().set(BlockTorch.FACING, EnumDirection.EAST)); + world.setTypeUpdate(blockposition2.east(), Blocks.TORCH.getBlockData().set(BlockTorch.FACING, EnumDirection.WEST)); + world.setTypeUpdate(blockposition2.north(), Blocks.TORCH.getBlockData().set(BlockTorch.FACING, EnumDirection.SOUTH)); + world.setTypeUpdate(blockposition2.south(), Blocks.TORCH.getBlockData().set(BlockTorch.FACING, EnumDirection.NORTH)); + world.setTypeUpdate(blockposition.up(3), Blocks.BEDROCK.getBlockData()); + world.setTypeUpdate(blockposition.up(4), Blocks.DRAGON_EGG.getBlockData()); + + EntityCreatePortalEvent event = new EntityCreatePortalEvent((org.bukkit.entity.LivingEntity) this.getBukkitEntity(), java.util.Collections.unmodifiableList(world.getList()), org.bukkit.PortalType.ENDER); + this.world.getServer().getPluginManager().callEvent(event); + + if (!event.isCancelled()) { + for (BlockState state : event.getBlocks()) { + state.update(true); + } + } else { + for (BlockState state : event.getBlocks()) { + PacketPlayOutBlockChange packet = new PacketPlayOutBlockChange(this.world, new BlockPosition(state.getX(), state.getY(), state.getZ())); + for (EntityHuman entity : this.world.players) { + if (entity instanceof EntityPlayer) { + ((EntityPlayer) entity).playerConnection.sendPacket(packet); + } + } + } + } + // CraftBukkit end + } + + protected void D() {} + + public Entity[] aB() { + return this.children; + } + + public boolean ad() { + return false; + } + + public World a() { + return this.world; + } + + protected String z() { + return "mob.enderdragon.growl"; + } + + protected String bo() { + return "mob.enderdragon.hit"; + } + + protected float bB() { + return 5.0F; + } + + // CraftBukkit start + public int getExpReward() { + // This value is equal to the amount of experience dropped while falling from the sky (10 * 1000) + // plus what is dropped when the dragon hits the ground (2000) + return 12000; + } + // CraftBukkit end +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityEnderPearl.java b/azurite-server/src/main/java/net/minecraft/server/EntityEnderPearl.java new file mode 100644 index 0000000..461ccb7 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityEnderPearl.java @@ -0,0 +1,1026 @@ +package net.minecraft.server; + +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Sets; +import dev.azurite.spigot.configs.AzuriteConfig; +import dev.azurite.spigot.configs.PearlConfig; +import dev.azurite.spigot.utils.PearlUtil; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.BlockFace; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.craftbukkit.event.CraftEventFactory; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.player.PlayerPearlRefundEvent; +import org.bukkit.event.player.PlayerTeleportEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.material.Gate; +import org.bukkit.material.Stairs; +import org.bukkit.material.TrapDoor; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import java.util.Set; + +public class EntityEnderPearl extends EntityProjectile { + private final ImmutableSet blocked = Sets.immutableEnumSet(org.bukkit.Material.THIN_GLASS, Material.GLASS, org.bukkit.Material.STAINED_GLASS_PANE, org.bukkit.Material.STAINED_GLASS); + private final Random random = new Random(); + private EntityLiving c; + private boolean isEdited; + private boolean crosspearl; + private boolean ar; + private boolean a; + + public EntityEnderPearl(World world) { + super(world); + loadChunks = world.paperSpigotConfig.loadUnloadedEnderPearls; + } + + public EntityEnderPearl(World world, EntityLiving entityliving) { + super(world, entityliving); + c = entityliving; + loadChunks = world.paperSpigotConfig.loadUnloadedEnderPearls; + } + + @Override + public float getRandomness() { + return AzuriteConfig.pearlTrajectoryRandomness.getValue(); + } + + @Override + protected void a(MovingObjectPosition moving) { + double pearlDamage = PearlConfig.pearlDamage.getValue(); + EntityLiving entityliving = this.getShooter(); + Entity bukkitEntity = getBukkitEntity(); + org.bukkit.World bukkitWorld = bukkitEntity.getWorld(); + BlockPosition pos = moving.a(); + org.bukkit.block.Block block = (pos != null ? bukkitWorld.getBlockAt(pos.getX(), pos.getY(), pos.getZ()) : null); + + if (moving.entity != null && moving.entity == c) { + return; + } + + if (this.inUnloadedChunk && this.world.paperSpigotConfig.removeUnloadedEnderPearls) { + this.die(); + } + + if (entityliving instanceof EntityPlayer) { + EntityPlayer entityplayer = (EntityPlayer) entityliving; + CraftPlayer player = entityplayer.getBukkitEntity(); + if (entityplayer.playerConnection.a().g() && entityplayer.world == this.world && !entityplayer.isSleeping()) { + Location pl = player.getLocation(); + Location location = bukkitEntity.getLocation(); + location.setPitch(pl.getPitch()); + location.setYaw(pl.getYaw()); + org.bukkit.block.Block block2 = location.getBlock(); + org.bukkit.Material mat = block2.getType(); + String t = mat.toString(); + + if (this.checkForEntity(location, player, moving)) { + return; + } + org.bukkit.block.Block b = block2.getRelative(BlockFace.UP); + if (t.contains("CHEST") && b.getType().toString().contains("FENCE_GATE") && this.distance(b, pl, 2.0)) { + refundPearl(player); + this.die(); + return; + } + if (!PearlUtil.thruEnabled(mat) && PearlUtil.isApplicable(mat)) { + refundPearl(player); + this.die(); + return; + } + if (t.equals("IRON_TRAPDOOR") || t.equals("TRAP_DOOR") && (pl.getBlock().getRelative(BlockFace.UP).getType() == org.bukkit.Material.TRAP_DOOR || pl.getBlock().getRelative(BlockFace.UP).getType().toString().equals("IRON_TRAPDOOR"))) { + refundPearl(player); + this.die(); + return; + } + if (!this.checkPearlThru(location, player)) { + refundPearl(player); + this.die(); + return; + } + if (this.checkForTrapDoor(location)) { + this.isEdited = true; + this.setToBlock(location); + } + if (!this.isEdited) { + if (PearlConfig.refundRiskyPearl.getValue() && !this.a && !this.checkRisky(location, player, moving)) { + refundPearl(player); + this.die(); + return; + } + if (PearlConfig.refundCloseDistance.getValue() > 0.0D && !this.checkClose(location, player, moving)) { + refundPearl(player); + this.die(); + return; + } + if (PearlConfig.refundSuffocation.getValue() && PearlUtil.customTransparent(block2)) { + refundPearl(player); + this.die(); + return; + } + } + if (PearlConfig.fixBlockGlitch.getValue()) { + if (!this.isEdited) { + this.setToBlock(location); + + } else if (this.blocked.contains(mat)) { + refundPearl(player); + this.die(); + return; + } + if (block != null && block2.getRelative(BlockFace.DOWN).getType() == Material.AIR + && (blocked.contains(block.getType()) || block.getType() == Material.GLASS)) { + location.setY(location.getY() - 0.5D); + } + } + if (PearlConfig.fixFenceGlitch.getValue() && !this.a && !this.checkFenceGate(location)) { + refundPearl(player); + this.die(); + return; + } + + PlayerTeleportEvent playerTeleportEvent = new PlayerTeleportEvent(player, player.getLocation(), location, PlayerTeleportEvent.TeleportCause.ENDER_PEARL); + Bukkit.getPluginManager().callEvent(playerTeleportEvent); + + if (!playerTeleportEvent.isCancelled() && !entityplayer.playerConnection.isDisconnected()) { + if (PearlConfig.spawnEndermite.getValue() && random.nextFloat() < 0.05F && world.getGameRules().getBoolean("doMobSpawning")) { + EntityEndermite entityendermite = new EntityEndermite(world); + entityendermite.a(true); + entityendermite.setPositionRotation(entityliving.locX, entityliving.locY, entityliving.locZ, entityliving.yaw, entityliving.pitch); + world.addEntity(entityendermite); + } + + if (entityplayer.au()) { + entityplayer.mount(null); + } + + // Azurite - make pearls smoother + entityplayer.playerConnection.teleport(playerTeleportEvent.getTo(), false); + entityplayer.fallDistance = 0.0f; + + if (pearlDamage > 0.0) { + // Beanes - reset motion values if player takes damage to fix "boosting" downwards (fixes stuff like getting boosted downwards in pearl fight) + entityplayer.motX = 0.0D; + entityplayer.motY = 0.0D; + entityplayer.motZ = 0.0D; + + CraftEventFactory.entityDamage = this; + entityplayer.damageEntity(DamageSource.FALL, (float) pearlDamage); + CraftEventFactory.entityDamage = null; + } + } + } + } + if (PearlConfig.pearlParticlesEnabled.getValue()) { + for (int i = 0; i < PearlConfig.pearlParticleCount.getValue(); ++i) { + this.world.addParticle(EnumParticle.PORTAL, this.locX, this.locY + this.random.nextDouble() * 2.0, this.locZ, this.random.nextGaussian(), 0.0, this.random.nextGaussian()); + } + } + this.die(); + } + + protected boolean checkForEntity(Location location, Player player, MovingObjectPosition moving) { + if (moving.entity != null) { + double pearlDamage = PearlConfig.pearlDamage.getValue(); + if (moving.entity == this.c || location.getBlock().getType().toString().contains("FENCE_GATE")) { + return false; + } + if (pearlDamage > 0.0 && moving.entity != null) { + if (moving.entity != this.c) { + moving.entity.damageEntity(DamageSource.projectile(this, getShooter()), (float) pearlDamage); + } + } + + if (PearlConfig.entityTpHitDetection.getValue()) { + if (PearlConfig.practicePearls.getValue()) { // Beanes - teleport "halfly" in the player + // Get the positions + double victimX = moving.entity.locX; + double victimZ = moving.entity.locZ; + double pearlX = this.locX; + double pearlZ = this.locZ; + + // Calculate the direction vector from player to hit player + double dirX = pearlX - victimX; + double dirZ = pearlZ - victimZ; + + // Normalize the horizontal direction vector + double distance = Math.sqrt(dirX * dirX + dirZ * dirZ); + if (distance > 0) { + dirX /= distance; + dirZ /= distance; + } + + double reverseStrength = 0.3D; + + location.setX(moving.entity.locX + dirX * reverseStrength); + location.setY(moving.entity.locY); + location.setZ(moving.entity.locZ + dirZ * reverseStrength); + } else { + String direction = PearlUtil.direction(location); + org.bukkit.block.Block block = location.getBlock(); + List blockface = this.getBFByDirection(direction); + Entity bukkitEntity = moving.entity.getBukkitEntity(); + Location a = bukkitEntity.getLocation(); + + if (a.getBlock().getType() == Material.AIR) { // Azurite - Patch teleporting to entity while they're in a block. + if (!this.isntDiagonal(direction)) { + if (this.isGood(block.getRelative(blockface.get(0))) && this.isGood(block.getRelative(blockface.get(1)))) { + location.setX(moving.entity.locX); + location.setZ(moving.entity.locZ); + } + } else { + org.bukkit.block.Block next = block.getRelative(blockface.get(0)); + org.bukkit.block.Block nextnext = next.getRelative(blockface.get(0)); + if (a.distance(player.getLocation()) <= 2.1 && !PearlUtil.customTransparent(block) && this.isGood(next) && this.isGood(nextnext)) { + location.setX(moving.entity.locX); + location.setZ(moving.entity.locZ); + } + if (a.distance(location) <= 2.05 && !PearlUtil.customTransparent(block) && this.isGood(next)) { + location.setX(moving.entity.locX); + location.setZ(moving.entity.locZ); + } + } + } + } + } + } + return false; + } + + protected boolean isGood(org.bukkit.block.Block block) { + return !PearlUtil.customTransparent(block) && !block.getType().toString().contains("FENCE_GATE"); + } + + protected boolean checkClose(Location location, Player player, MovingObjectPosition mov) { + if (mov.entity != null) { + return true; + } + org.bukkit.block.Block tBlock = player.getTargetBlock((Set) null, 1); + org.bukkit.block.Block block = location.getBlock(); + String dr = PearlUtil.direction(player.getLocation()); + org.bukkit.block.Block west = block.getRelative(BlockFace.WEST); + org.bukkit.block.Block east = block.getRelative(BlockFace.EAST); + org.bukkit.block.Block north = block.getRelative(BlockFace.NORTH); + org.bukkit.block.Block south = block.getRelative(BlockFace.SOUTH); + if (location.distance(player.getLocation()) <= 1.75 && player.getLocation().distance(tBlock.getLocation().clone().add(0.5, 0.0, 0.5)) <= 1.75) { + if (PearlUtil.thruEnabled(block.getType()) || PearlUtil.thruEnabled(tBlock.getRelative(BlockFace.DOWN).getType())) { + return true; + } + if (PearlUtil.customTransparent(tBlock)) { + return false; + } + } + if (!PearlUtil.customTransparent(block)) { + Location pLocation = player.getLocation(); + double d = PearlConfig.refundCloseDistance.getValue(); + return dr.contains("N") ? !PearlUtil.customTransparent(north) || !this.distance(north, pLocation, d) : (dr.contains("S") ? !PearlUtil.customTransparent(south) || !this.distance(south, pLocation, d) : (dr.contains("W") ? !PearlUtil.customTransparent(west) || !this.distance(west, pLocation, d) : !dr.contains("E") || !PearlUtil.customTransparent(east) || !this.distance(east, pLocation, d))); + } + return true; + } + + protected boolean checkRisky(Location location, Player player, MovingObjectPosition mov) { + org.bukkit.block.Block block = location.getBlock(); + org.bukkit.block.Block west = block.getRelative(BlockFace.WEST); + org.bukkit.block.Block east = block.getRelative(BlockFace.EAST); + org.bukkit.block.Block north = block.getRelative(BlockFace.NORTH); + org.bukkit.block.Block south = block.getRelative(BlockFace.SOUTH); + if (!PearlUtil.customTransparent(block) && !block.getType().toString().contains("CHEST") && !block.getType().toString().contains("SIGN") && PearlUtil.isRiskyBlock(block.getRelative(BlockFace.DOWN)) && PearlUtil.isRiskyBlock(block.getRelative(BlockFace.UP)) && mov.entity == null) { + String direction = PearlUtil.direction(player.getLocation()); + if (!(!direction.contains("E") || PearlUtil.customTransparent(east) || east.getType().toString().contains("CHEST") || east.getType().toString().contains("SIGN") || PearlUtil.customTransparent(east.getRelative(BlockFace.UP)))) { + return true; + } + if (!(!direction.contains("W") || PearlUtil.customTransparent(west) || west.getType().toString().contains("CHEST") || west.getType().toString().contains("SIGN") || PearlUtil.customTransparent(west.getRelative(BlockFace.UP)))) { + return true; + } + if (!(!direction.contains("N") || PearlUtil.customTransparent(north) || north.getType().toString().contains("CHEST") || north.getType().toString().contains("SIGN") || PearlUtil.customTransparent(north.getRelative(BlockFace.UP)))) { + return true; + } + return direction.contains("S") && !PearlUtil.customTransparent(south) && !south.getType().toString().contains("CHEST") && !south.getType().toString().contains("SIGN") && !PearlUtil.customTransparent(south.getRelative(BlockFace.UP)); + } + return true; + } + + protected boolean checkFenceGate(Location location) { + org.bukkit.block.Block block = location.getBlock(); + org.bukkit.block.Block down = block.getRelative(BlockFace.DOWN); + org.bukkit.Material mat = block.getType(); + if (mat.toString().contains("FENCE_GATE")) { + if (down.getType().toString().contains("CHEST") && PearlConfig.pearlChestUnderFence.getValue()) { + return true; + } + if (down.getType() == org.bukkit.Material.HOPPER && PearlConfig.pearlHopperUnderFence.getValue()) { + return true; + } + if (!((Gate) block.getState().getData()).isOpen()) { + return down.getType().toString().contains("FENCE_GATE") && ((Gate) down.getState().getData()).isOpen(); + } + this.isEdited = true; + location.setX((double) location.getBlockX() + 0.5); + location.setY(location.getBlockY()); + location.setZ((double) location.getBlockZ() + 0.5); + return true; + } + return true; + } + + protected boolean checkForTrapDoor(Location location) { + org.bukkit.block.Block a = location.getBlock(); + String d = PearlUtil.direction(location); + if (!PearlUtil.customTransparent(a) && this.isntDiagonal(d)) { + org.bukkit.block.Block e = a.getRelative(this.getBFByDirection(d).get(0)); + org.bukkit.block.Block k = e.getRelative(BlockFace.UP); + if ((e.getType().toString().contains("FENCE_GATE") && k.getType().toString().equals("TRAP_DOOR") || k.getType().toString().equals("IRON_TRAPDOOR")) && ((TrapDoor) k.getState().getData()).isOpen()) { + this.addToLocation(d, location); + this.a = true; + return true; + } + } + return false; + } + + protected boolean checkPearlThru(Location location, Player player) { + Location plocation = player.getLocation(); + String direction = PearlUtil.direction(plocation); + org.bukkit.block.Block block = this.getThruBlock(location, player); + if (block != null) { + org.bukkit.Material mat = block.getType(); + BlockFace blockface = null; + boolean stairFacing = PearlUtil.isStairs(mat); + + if (stairFacing) { + Stairs stairs = (Stairs) block.getState().getData(); + blockface = stairs.getFacing(); + } + + if (this.crosspearl) { + return true; + } + + boolean b = !PearlConfig.refundOnCritblock.getValue(); + boolean i = PearlConfig.instantlyTaliTeleport.getValue(); + Location loc = block.getLocation().clone(); + boolean diagonal = PearlUtil.diagonalPearl(mat); + org.bukkit.block.Block west = block.getRelative(BlockFace.WEST); + org.bukkit.block.Block east = block.getRelative(BlockFace.EAST); + org.bukkit.block.Block north = block.getRelative(BlockFace.NORTH); + org.bukkit.block.Block south = block.getRelative(BlockFace.SOUTH); + if (direction.contains("E")) { + if (direction.equals("E")) { + org.bukkit.block.Block abc; + if (stairFacing && blockface != null && blockface != BlockFace.SOUTH && blockface != BlockFace.NORTH && blockface != BlockFace.WEST) { + return false; + } + boolean qe = false; + if (!PearlUtil.thruEnabled(east.getType()) && (PearlUtil.customTransparent(east) || !this.ar && PearlUtil.customTransparent(east.getRelative(BlockFace.DOWN)))) { + if (i) { + location.add(1.0, 0.0, 0.0); + } + qe = true; + } + if (!qe) { + for (int ia = 0; ia < PearlConfig.maxTeleportBlocks.getValue(); ++ia) { + org.bukkit.block.Block nextcurrent = block.getRelative(BlockFace.EAST); + if (!PearlUtil.thruEnabled(nextcurrent.getType())) continue; + org.bukkit.block.Block l = nextcurrent.getRelative(BlockFace.EAST); + if (!PearlUtil.thruEnabled(l.getType())) { + if (PearlUtil.customTransparent(l) || !this.ar && l.getRelative(BlockFace.UP).getType().isSolid() && PearlUtil.customTransparent(l.getRelative(BlockFace.DOWN))) { + return false; + } + if (this.isStairBad(nextcurrent, direction)) { + return false; + } + location.add(1.0, 0.0, 0.0); + break; + } + if (this.isStairBad(nextcurrent, direction)) { + return false; + } + block = nextcurrent; + location.add(1.0, 0.0, 0.0); + } + } + if (this.isClosed(abc = block.getRelative(BlockFace.EAST).getRelative(BlockFace.UP)) || PearlUtil.isCritBlock(abc)) { + if (!PearlUtil.isCritblock(block.getType()) || qe) { + return b; + } + location.add(1.5, -0.5, 0.0); + this.setToBlock(location); + } + } + if (direction.equals("SE") && PearlUtil.customTransparent(east) && PearlUtil.customTransparent(south)) { + return false; + } + if (direction.equals("NE") && PearlUtil.customTransparent(east) && PearlUtil.customTransparent(north)) { + return false; + } + if (direction.equals("NE") && diagonal) { + if (PearlUtil.diagonalPearl(south.getType()) || PearlUtil.diagonalPearl(west.getType())) { + if (!PearlUtil.customTransparent(north)) { + location.setZ(loc.add(0.0, 0.0, -1.0).getZ()); + location.setX(loc.getX() + 0.5); + location.setZ(loc.getZ() + 0.5); + this.isEdited = true; + return true; + } + location.setX(loc.add(1.0, 0.0, 0.0).getX()); + location.setX(loc.getX() + 0.5); + location.setZ(loc.getZ() + 0.5); + this.isEdited = true; + return true; + } + } else if (direction.equals("SE") && diagonal && (PearlUtil.diagonalPearl(north.getType()) || PearlUtil.diagonalPearl(west.getType()))) { + if (!PearlUtil.customTransparent(south)) { + location.setZ(loc.add(0.0, 0.0, 1.0).getZ()); + location.setX(loc.getX() + 0.5); + location.setZ(loc.getZ() + 0.5); + this.isEdited = true; + return true; + } + location.setX(loc.add(1.0, 0.0, 0.0).getX()); + location.setX(loc.getX() + 0.5); + location.setZ(loc.getZ() + 0.5); + this.isEdited = true; + return true; + } + if (!this.isEdited) { + location.setX((double) location.getBlockX() + 0.5); + location.setZ((double) location.getBlockZ() + 0.5); + this.isEdited = true; + } + return true; + } + if (direction.contains("W")) { + if (direction.equals("W")) { + org.bukkit.block.Block abc; + if (stairFacing && blockface != null && blockface != BlockFace.SOUTH && blockface != BlockFace.NORTH && blockface != BlockFace.EAST) { + return false; + } + boolean qe = false; + if (!PearlUtil.thruEnabled(west.getType()) && (PearlUtil.customTransparent(west) || !this.ar && PearlUtil.customTransparent(west.getRelative(BlockFace.DOWN)))) { + if (i) { + location.add(-1.0, 0.0, 0.0); + } + qe = true; + } + if (!qe) { + for (int ia = 0; ia < PearlConfig.maxTeleportBlocks.getValue(); ++ia) { + org.bukkit.block.Block nextcurrent = block.getRelative(BlockFace.WEST); + if (!PearlUtil.thruEnabled(nextcurrent.getType())) continue; + org.bukkit.block.Block l = nextcurrent.getRelative(BlockFace.WEST); + if (!PearlUtil.thruEnabled(l.getType())) { + if (PearlUtil.customTransparent(l) || !this.ar && l.getRelative(BlockFace.UP).getType().isSolid() && PearlUtil.customTransparent(l.getRelative(BlockFace.DOWN))) { + return false; + } + if (this.isStairBad(nextcurrent, direction)) { + return false; + } + location.add(-1.0, 0.0, 0.0); + break; + } + if (this.isStairBad(nextcurrent, direction)) { + return false; + } + block = nextcurrent; + location.add(-1.0, 0.0, 0.0); + } + } + if (this.isClosed(abc = block.getRelative(BlockFace.WEST).getRelative(BlockFace.UP)) || PearlUtil.isCritBlock(abc)) { + if (!PearlUtil.isCritblock(block.getType()) || qe) { + return b; + } + location.add(-1.5, -0.5, 0.0); + this.setToBlock(location); + } + } + if (direction.equals("SW") ? PearlUtil.customTransparent(west) && PearlUtil.customTransparent(south) : direction.equals("NW") && PearlUtil.customTransparent(west) && PearlUtil.customTransparent(north)) { + return false; + } + if (direction.equals("NW") && diagonal) { + if (PearlUtil.diagonalPearl(east.getType()) || PearlUtil.diagonalPearl(south.getType())) { + if (!PearlUtil.customTransparent(north)) { + location.setZ(loc.add(0.0, 0.0, -1.0).getZ()); + location.setX(loc.getX() + 0.5); + location.setZ(loc.getZ() + 0.5); + this.isEdited = true; + return true; + } + location.setX(loc.add(-1.0, 0.0, 0.0).getX()); + location.setX(loc.getX() + 0.5); + location.setZ(loc.getZ() + 0.5); + this.isEdited = true; + return true; + } + } else if (direction.equals("SW") && diagonal && (PearlUtil.diagonalPearl(north.getType()) || PearlUtil.diagonalPearl(east.getType()))) { + if (!PearlUtil.customTransparent(south)) { + location.setZ(loc.add(0.0, 0.0, 1.0).getZ()); + location.setX(loc.getX() + 0.5); + location.setZ(loc.getZ() + 0.5); + this.isEdited = true; + return true; + } + location.setX(loc.add(-1.0, 0.0, 0.0).getX()); + location.setX(loc.getX() + 0.5); + location.setZ(loc.getZ() + 0.5); + this.isEdited = true; + return true; + } + if (!this.isEdited) { + location.setX((double) location.getBlockX() + 0.5); + location.setZ((double) location.getBlockZ() + 0.5); + this.isEdited = true; + } + return true; + } + if (direction.equals("N")) { + org.bukkit.block.Block abc; + if (stairFacing && blockface != null && blockface != BlockFace.EAST && blockface != BlockFace.WEST && blockface != BlockFace.SOUTH) { + return false; + } + boolean qe = false; + if (!PearlUtil.thruEnabled(north.getType()) && (PearlUtil.customTransparent(north) || !this.ar && PearlUtil.customTransparent(north.getRelative(BlockFace.DOWN)))) { + if (i) { + location.add(0.0, 0.0, -1.0); + } + qe = true; + } + if (!qe) { + for (int ia = 0; ia < PearlConfig.maxTeleportBlocks.getValue(); ++ia) { + org.bukkit.block.Block nextcurrent = block.getRelative(BlockFace.NORTH); + if (!PearlUtil.thruEnabled(nextcurrent.getType())) continue; + org.bukkit.block.Block l = nextcurrent.getRelative(BlockFace.NORTH); + if (!PearlUtil.thruEnabled(l.getType())) { + if (PearlUtil.customTransparent(l) || !this.ar && l.getRelative(BlockFace.UP).getType().isSolid() && PearlUtil.customTransparent(l.getRelative(BlockFace.DOWN))) { + return false; + } + if (this.isStairBad(nextcurrent, direction)) { + return false; + } + location.add(0.0, 0.0, -1.0); + break; + } + if (this.isStairBad(nextcurrent, direction)) { + return false; + } + block = nextcurrent; + location.add(0.0, 0.0, -1.0); + } + } + if (this.isClosed(abc = block.getRelative(BlockFace.NORTH).getRelative(BlockFace.UP)) || PearlUtil.isCritBlock(abc)) { + if (!PearlUtil.isCritblock(block.getType()) || qe) { + return b; + } + location.add(0.0, -0.5, -1.5); + this.setToBlock(location); + } + if (!this.isEdited) { + location.setX((double) location.getBlockX() + 0.5); + location.setZ((double) location.getBlockZ() + 0.5); + this.isEdited = true; + } + return true; + } + if (direction.equals("S")) { + if (stairFacing && blockface != null && blockface != BlockFace.EAST && blockface != BlockFace.WEST) { + return false; + } + boolean qe = false; + if (!PearlUtil.thruEnabled(south.getType()) && (PearlUtil.customTransparent(south) || !this.ar && PearlUtil.customTransparent(south.getRelative(BlockFace.DOWN)))) { + if (i) { + location.add(0.0, 0.0, 1.0); + } + qe = true; + } + for (int ia = 0; ia < PearlConfig.maxTeleportBlocks.getValue(); ++ia) { + org.bukkit.block.Block nextcurrent = block.getRelative(BlockFace.SOUTH); + if (!PearlUtil.thruEnabled(nextcurrent.getType())) continue; + org.bukkit.block.Block l = nextcurrent.getRelative(BlockFace.SOUTH); + if (!PearlUtil.thruEnabled(l.getType())) { + if (PearlUtil.customTransparent(l) || !this.ar && l.getRelative(BlockFace.UP).getType().isSolid() && PearlUtil.customTransparent(l.getRelative(BlockFace.DOWN))) { + return false; + } + if (this.isStairBad(nextcurrent, direction)) { + return false; + } + location.add(0.0, 0.0, 1.0); + break; + } + if (this.isStairBad(nextcurrent, direction)) { + return false; + } + block = nextcurrent; + location.add(0.0, 0.0, 1.0); + } + org.bukkit.block.Block abc = block.getRelative(BlockFace.SOUTH).getRelative(BlockFace.UP); + if (this.isClosed(abc) || PearlUtil.isCritBlock(abc)) { + if (!PearlUtil.isCritblock(block.getType()) || qe) { + return b; + } + location.add(0.0, -0.5, 1.5); + this.setToBlock(location); + } + if (!this.isEdited) { + location.setX((double) location.getBlockX() + 0.5); + location.setZ((double) location.getBlockZ() + 0.5); + this.isEdited = true; + } + return true; + } + } + return true; + } + + private boolean isClosed(org.bukkit.block.Block b) { + String t = b.getType().toString(); + return (t.equals("IRON_TRAPDOOR") || t.equals("TRAP_DOOR")) && ((TrapDoor) b.getState().getData()).isOpen(); + } + + protected org.bukkit.block.Block getThruBlock(Location location, Player player) { + block89: + { + org.bukkit.block.Block block = location.getBlock(); + Location pLoc = player.getLocation(); + String dr = PearlUtil.direction(pLoc); + org.bukkit.Material mat = block.getType(); + org.bukkit.block.Block down = block.getRelative(BlockFace.DOWN); + org.bukkit.block.Block west = block.getRelative(BlockFace.WEST); + org.bukkit.block.Block east = block.getRelative(BlockFace.EAST); + org.bukkit.block.Block north = block.getRelative(BlockFace.NORTH); + org.bukkit.block.Block south = block.getRelative(BlockFace.SOUTH); + org.bukkit.Material eastType = east.getType(); + org.bukkit.Material westType = west.getType(); + org.bukkit.Material northType = north.getType(); + org.bukkit.Material southType = south.getType(); + if (!this.distance(block, pLoc, 6.0)) break block89; + if (PearlUtil.thruEnabled(mat)) { + switch (dr) { + case "SE": + if (PearlUtil.thruEnabled(eastType)) { + return east; + } + if (PearlUtil.thruEnabled(southType)) { + return south; + } + break; + case "NE": + if (PearlUtil.thruEnabled(eastType)) { + return east; + } + if (PearlUtil.thruEnabled(northType)) { + return north; + } + break; + case "SW": + if (PearlUtil.thruEnabled(westType)) { + return west; + } + if (PearlUtil.thruEnabled(southType)) { + return south; + } + break; + case "NW": + if (PearlUtil.thruEnabled(westType)) { + return west; + } + if (PearlUtil.thruEnabled(northType)) { + return north; + } + break; + } + return block; + } + if (PearlUtil.customTransparent(block)) break block89; + org.bukkit.block.Block q = player.getTargetBlock((Set) null, 4); + if (!PearlUtil.customTransparent(down)) { + org.bukkit.block.Block tBlock = player.getTargetBlock((Set) null, 1); + if (PearlConfig.hitBlockTeleport.getValue()) { + org.bukkit.block.Block a; + if (dr.equals("E")) { + org.bukkit.block.Block a2 = down.getRelative(BlockFace.EAST); + if (PearlUtil.thruEnabled(a2.getType()) && tBlock.getType() == a2.getType()) { + if (this.isStairBad(a2, dr)) { + return null; + } + location.add(0.5, 0.0, 0.0); + location.setY(a2.getY()); + return a2; + } + } else if (dr.equals("W")) { + org.bukkit.block.Block a3 = down.getRelative(BlockFace.WEST); + if (PearlUtil.thruEnabled(a3.getType()) && tBlock.getType() == a3.getType()) { + if (this.isStairBad(a3, dr)) { + return null; + } + location.add(-0.5, 0.0, 0.0); + location.setY(a3.getY()); + return a3; + } + } else if (dr.equals("N")) { + org.bukkit.block.Block a4 = down.getRelative(BlockFace.NORTH); + if (PearlUtil.thruEnabled(a4.getType()) && tBlock.getType() == a4.getType()) { + if (this.isStairBad(a4, dr)) { + return null; + } + location.setY(a4.getY()); + location.add(0.0, 0.0, -0.5); + return a4; + } + } else if (dr.equals("S") && PearlUtil.thruEnabled((a = down.getRelative(BlockFace.SOUTH)).getType()) && tBlock.getType() == a.getType()) { + if (this.isStairBad(a, dr)) { + return null; + } + location.add(0.0, 0.0, 0.5); + location.setY(a.getY()); + return a; + } + } + } + if ((q.getType().toString().contains("WALL") || q.getType().toString().equals("IRON_TRAPDOOR") || q.getType().toString().equals("TRAP_DOOR")) && !PearlUtil.customTransparent(q.getRelative(BlockFace.UP)) && PearlUtil.getBehind(dr) != null && !PearlUtil.customTransparent(q.getRelative(PearlUtil.getBehind(dr)).getRelative(BlockFace.UP)) && q.getRelative(PearlUtil.getBehind(dr)).getRelative(BlockFace.UP).getLocation().add(0.5, 0.0, 0.5).distance(pLoc) <= 2.0) { + if (dr.equals("W") || dr.equals("E")) { + this.ar = true; + if (dr.equals("E")) { + location.setX(location.getX() + 0.7); + } else { + location.setX(location.getX() - 0.7); + } + return q; + } + this.ar = true; + if (dr.equals("N")) { + location.setZ(location.getZ() - 0.7); + } else { + location.setZ(location.getZ() + 0.7); + } + return q; + } + if (down.getType() == Material.AIR) break block89; + switch (dr) { + case "SE": { + double d = PearlConfig.crossPearlMoveHelper.getValue(); + if (this.isCannable(east, location)) { + if (!PearlUtil.thruEnabled(block.getRelative(BlockFace.SOUTH_EAST).getType()) && PearlUtil.crossPearl(east.getType()) && !south.getType().toString().contains("FENCE_GATE")) { + location.setZ(location.getZ() + d); + location.setX(location.getX() + d); + this.crosspearl = true; + this.isEdited = true; + return east; + } + return block.getRelative(BlockFace.SOUTH_EAST); + } + if (this.isCannable(south, location)) { + if (!PearlUtil.thruEnabled(block.getRelative(BlockFace.SOUTH_EAST).getType()) && PearlUtil.crossPearl(south.getType()) && !east.getType().toString().contains("FENCE_GATE")) { + location.setZ(location.getZ() + d); + location.setX(location.getX() + d); + this.crosspearl = true; + this.isEdited = true; + return south; + } + return block.getRelative(BlockFace.SOUTH_EAST); + } + break; + } + case "NE": { + double d = PearlConfig.crossPearlMoveHelper.getValue(); + if (this.isCannable(north, location)) { + if (!PearlUtil.thruEnabled(block.getRelative(BlockFace.NORTH_EAST).getType()) && PearlUtil.crossPearl(north.getType()) && !east.getType().toString().contains("FENCE_GATE")) { + location.setZ(location.getZ() - d); + location.setX(location.getX() + d); + this.crosspearl = true; + this.isEdited = true; + return north; + } + return block.getRelative(BlockFace.NORTH_EAST); + } + if (this.isCannable(east, location)) { + if (!PearlUtil.thruEnabled(block.getRelative(BlockFace.NORTH_EAST).getType()) && PearlUtil.crossPearl(east.getType()) && !north.getType().toString().contains("FENCE_GATE")) { + location.setZ(location.getZ() - d); + location.setX(location.getX() + d); + this.crosspearl = true; + this.isEdited = true; + return east; + } + return block.getRelative(BlockFace.NORTH_EAST); + } + break; + } + case "NW": { + double d = PearlConfig.crossPearlMoveHelper.getValue(); + if (this.isCannable(west, location)) { + if (!PearlUtil.thruEnabled(block.getRelative(BlockFace.NORTH_WEST).getType()) && PearlUtil.crossPearl(west.getType()) && !north.getType().toString().contains("FENCE_GATE")) { + location.setZ(location.getZ() - d); + location.setX(location.getX() - d); + this.crosspearl = true; + this.isEdited = true; + return west; + } + return block.getRelative(BlockFace.NORTH_WEST); + } + if (this.isCannable(north, location)) { + if (!PearlUtil.thruEnabled(block.getRelative(BlockFace.NORTH_WEST).getType()) && PearlUtil.crossPearl(north.getType()) && !west.getType().toString().contains("FENCE_GATE")) { + location.setZ(location.getZ() - d); + location.setX(location.getX() - d); + this.crosspearl = true; + this.isEdited = true; + return north; + } + return block.getRelative(BlockFace.NORTH_WEST); + } + break; + } + case "SW": { + double d = PearlConfig.crossPearlMoveHelper.getValue(); + if (this.isCannable(south, location)) { + if (!PearlUtil.thruEnabled(block.getRelative(BlockFace.SOUTH_WEST).getType()) && PearlUtil.crossPearl(south.getType()) && !west.getType().toString().contains("FENCE_GATE")) { + location.setZ(location.getZ() + d); + location.setX(location.getX() - d); + this.crosspearl = true; + this.isEdited = true; + return south; + } + return block.getRelative(BlockFace.SOUTH_WEST); + } + if (this.isCannable(west, location)) { + if (!PearlUtil.thruEnabled(block.getRelative(BlockFace.SOUTH_WEST).getType()) && PearlUtil.crossPearl(west.getType()) && !south.getType().toString().contains("FENCE_GATE")) { + location.setZ(location.getZ() + d); + location.setX(location.getX() - d); + this.crosspearl = true; + this.isEdited = true; + return west; + } + return block.getRelative(BlockFace.SOUTH_WEST); + } + break; + } + } + if (!PearlConfig.beforeBlockTeleport.getValue()) break block89; + switch (dr) { + case "E": { + if (!PearlUtil.thruEnabled(eastType) || !this.distance(east, location, 0.8)) break; + if (this.isStairBad(east, dr)) { + return null; + } + if (!PearlUtil.customTransparent(east.getRelative(BlockFace.DOWN))) break; + location.setX(location.getX() + 0.3); + return east; + } + case "W": { + if (!PearlUtil.thruEnabled(westType) || !this.distance(west, location, 0.8)) break; + if (this.isStairBad(west, dr)) { + return null; + } + if (!PearlUtil.customTransparent(west.getRelative(BlockFace.DOWN))) break; + location.setX(location.getX() - 0.3); + return west; + } + case "N": { + if (!PearlUtil.thruEnabled(northType) || !this.distance(north, location, 0.8)) break; + if (this.isStairBad(north, dr)) { + return null; + } + if (!PearlUtil.customTransparent(north.getRelative(BlockFace.DOWN))) break; + location.setZ(location.getZ() - 0.3); + return north; + } + case "S": { + if (!PearlUtil.thruEnabled(southType) || !this.distance(south, location, 0.8)) break; + if (this.isStairBad(south, dr)) { + return null; + } + if (!PearlUtil.customTransparent(south.getRelative(BlockFace.DOWN))) break; + location.setZ(location.getZ() + 0.3); + return south; + } + } + } + return null; + } + + private List getBFByDirection(String d) { + ArrayList l = new ArrayList<>(); + switch (d) { + case "E": + l.add(BlockFace.EAST); + return l; + case "N": + l.add(BlockFace.NORTH); + return l; + case "W": + l.add(BlockFace.WEST); + return l; + case "S": + l.add(BlockFace.SOUTH); + return l; + case "NW": + l.add(BlockFace.NORTH); + l.add(BlockFace.WEST); + return l; + case "SW": + l.add(BlockFace.SOUTH); + l.add(BlockFace.WEST); + return l; + case "NE": + l.add(BlockFace.NORTH); + l.add(BlockFace.EAST); + return l; + case "SE": + l.add(BlockFace.SOUTH); + l.add(BlockFace.EAST); + return l; + } + return l; + } + + public void refundPearl(Player player) { + if (PearlConfig.glitchReturnPearl.getValue()) { + player.getInventory().addItem(new ItemStack(Material.ENDER_PEARL)); + player.updateInventory(); + } + + String message = PearlConfig.glitchReturnMessage.getValue(), consoleCommand = PearlConfig.glitchReturnCommand.getValue(); + + if (message != null && !message.isEmpty()) { + player.sendMessage(message); + } + + if (consoleCommand != null && !consoleCommand.isEmpty()) { + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), consoleCommand.replace("%player%", player.getName())); + } + + if (PlayerPearlRefundEvent.getHandlerList().getRegisteredListeners().length != 0) { + Bukkit.getPluginManager().callEvent(new PlayerPearlRefundEvent(player)); + } + } + + private boolean isntDiagonal(String d) { + return d.equals("W") || d.equals("S") || d.equals("E") || d.equals("N"); + } + + private boolean isStairBad(org.bukkit.block.Block block, String dr) { + boolean u = PearlUtil.isStairs(block.getType()); + BlockFace m = null; + if (u) { + Stairs t = (Stairs) block.getState().getData(); + m = t.getFacing(); + } + if (u && m != null) { + if (dr.equals("E") && (m == BlockFace.WEST || m == BlockFace.EAST)) { + this.isEdited = true; + return true; + } + if (dr.equals("W") && (m == BlockFace.WEST || m == BlockFace.EAST)) { + this.isEdited = true; + return true; + } + if (dr.equals("N") && (m == BlockFace.NORTH || m == BlockFace.SOUTH)) { + this.isEdited = true; + return true; + } + if (dr.equals("S") && (m == BlockFace.NORTH || m == BlockFace.SOUTH)) { + this.isEdited = true; + return true; + } + } + return false; + } + + private boolean isCannable(org.bukkit.block.Block b, Location l) { + if (this.distance(b, l, 1.0)) { + return PearlUtil.thruEnabled(b.getType()); + } + return false; + } + + private void setToBlock(Location l) { + l.setX((double) l.getBlockX() + 0.5); + l.setY(l.getBlockY()); + l.setZ((double) l.getBlockZ() + 0.5); + } + + protected void addToLocation(String d, Location location) { + switch (d) { + case "E": { + location.setX(location.getX() + 1.0); + break; + } + case "W": { + location.setX(location.getX() - 1.0); + break; + } + case "N": { + location.setZ(location.getZ() - 1.0); + break; + } + case "S": { + location.setZ(location.getZ() + 1.0); + } + } + } + + private boolean distance(org.bukkit.block.Block b, Location l, double d) { + return b.getLocation().clone().add(0.5, 0.0, 0.5).distance(l) <= d; + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityEnderSignal.java b/azurite-server/src/main/java/net/minecraft/server/EntityEnderSignal.java new file mode 100644 index 0000000..f4705f5 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityEnderSignal.java @@ -0,0 +1,132 @@ +package net.minecraft.server; + +public class EntityEnderSignal extends Entity { + + private double a; + private double b; + private double c; + private int d; + private boolean e; + + public EntityEnderSignal(World world) { + super(world); + this.setSize(0.25F, 0.25F); + } + + protected void h() { + } + + public EntityEnderSignal(World world, double d0, double d1, double d2) { + super(world); + this.d = 0; + this.setSize(0.25F, 0.25F); + this.setPosition(d0, d1, d2); + } + + public void a(BlockPosition blockposition) { + double d0 = blockposition.getX(); + int i = blockposition.getY(); + double d1 = blockposition.getZ(); + double d2 = d0 - this.locX; + double d3 = d1 - this.locZ; + float f = MathHelper.sqrt(d2 * d2 + d3 * d3); + + if (f > 12.0F) { + this.a = this.locX + d2 / (double) f * 12.0D; + this.c = this.locZ + d3 / (double) f * 12.0D; + this.b = this.locY + 8.0D; + } else { + this.a = d0; + this.b = i; + this.c = d1; + } + + this.d = 0; + this.e = random.nextInt(5) > 0; + } + + public void t_() { + this.P = this.locX; + this.Q = this.locY; + this.R = this.locZ; + super.t_(); + this.locX += this.motX; + this.locY += this.motY; + this.locZ += this.motZ; + float f = MathHelper.sqrt(this.motX * this.motX + this.motZ * this.motZ); + + this.yaw = (float) (MathHelper.b(this.motX, this.motZ) * 180.0D / 3.1415927410125732D); + + for (this.pitch = (float) (MathHelper.b(this.motY, f) * 180.0D / 3.1415927410125732D); this.pitch - this.lastPitch < -180.0F; this.lastPitch -= 360.0F) { + } + + while (this.pitch - this.lastPitch >= 180.0F) { + this.lastPitch += 360.0F; + } + + while (this.yaw - this.lastYaw < -180.0F) { + this.lastYaw -= 360.0F; + } + + while (this.yaw - this.lastYaw >= 180.0F) { + this.lastYaw += 360.0F; + } + + this.pitch = this.lastPitch + (this.pitch - this.lastPitch) * 0.2F; + this.yaw = this.lastYaw + (this.yaw - this.lastYaw) * 0.2F; + double d0 = this.a - this.locX; + double d1 = this.c - this.locZ; + float f1 = (float) Math.sqrt(d0 * d0 + d1 * d1); + float f2 = (float) MathHelper.b(d1, d0); + double d2 = (double) f + (double) (f1 - f) * 0.0025D; + + if (f1 < 1.0F) { + d2 *= 0.8D; + this.motY *= 0.8D; + } + + this.motX = Math.cos(f2) * d2; + this.motZ = Math.sin(f2) * d2; + if (this.locY < this.b) { + this.motY += (1.0D - this.motY) * 0.014999999664723873D; + } else { + this.motY += (-1.0D - this.motY) * 0.014999999664723873D; + } + + float f3 = 0.25F; + + if (this.V()) { + for (int i = 0; i < 4; ++i) { + this.world.addParticle(EnumParticle.WATER_BUBBLE, this.locX - this.motX * (double) f3, this.locY - this.motY * (double) f3, this.locZ - this.motZ * (double) f3, this.motX, this.motY, this.motZ); + } + } else { + this.world.addParticle(EnumParticle.PORTAL, this.locX - this.motX * (double) f3 + random.nextDouble() * 0.6D - 0.3D, this.locY - this.motY * (double) f3 - 0.5D, this.locZ - this.motZ * (double) f3 + random.nextDouble() * 0.6D - 0.3D, this.motX, this.motY, this.motZ); + } + + this.setPosition(this.locX, this.locY, this.locZ); + ++this.d; + if (this.d > 80) { + this.die(); + if (this.e) { + this.world.addEntity(new EntityItem(this.world, this.locX, this.locY, this.locZ, new ItemStack(Items.ENDER_EYE))); + } else { + this.world.triggerEffect(2003, new BlockPosition(this), 0); + } + } + + } + + public void b(NBTTagCompound nbttagcompound) { + } + + public void a(NBTTagCompound nbttagcompound) { + } + + public float c(float f) { + return 1.0F; + } + + public boolean aD() { + return false; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityEnderman.java b/azurite-server/src/main/java/net/minecraft/server/EntityEnderman.java new file mode 100644 index 0000000..c3e6d81 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityEnderman.java @@ -0,0 +1,472 @@ +package net.minecraft.server; + +import com.eatthepath.uuid.FastUUID; +import com.google.common.base.Predicate; +import com.google.common.collect.Sets; +import dev.azurite.spigot.configs.AzuriteConfig; +import org.bukkit.Location; +import org.bukkit.event.entity.EntityTeleportEvent; + +import java.util.*; + +public class EntityEnderman extends EntityMonster { + + private static final UUID a = FastUUID.parseUUID("020E0DFB-87AE-4653-9556-831010E291A0"); + private static final AttributeModifier b = (new AttributeModifier(EntityEnderman.a, "Attacking speed boost", 0.15000000596046448D, 0)).a(false); + private static final Set c = Sets.newIdentityHashSet(); + private boolean bm; + + public EntityEnderman(World world) { + super(world); + this.setSize(0.6F, 2.9F); + this.S = 1.0F; + this.goalSelector.a(0, new PathfinderGoalFloat(this)); + this.goalSelector.a(2, new PathfinderGoalMeleeAttack(this, 1.0D, false)); + this.goalSelector.a(7, new PathfinderGoalRandomStroll(this, 1.0D)); + this.goalSelector.a(8, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 8.0F)); + this.goalSelector.a(8, new PathfinderGoalRandomLookaround(this)); + this.goalSelector.a(10, new PathfinderGoalEndermanPlaceBlock(this)); + this.goalSelector.a(11, new PathfinderGoalEndermanPickupBlock(this)); + this.targetSelector.a(1, new PathfinderGoalHurtByTarget(this, false)); + this.targetSelector.a(2, new PathfinderGoalPlayerWhoLookedAtTarget(this)); + this.targetSelector.a(3, new PathfinderGoalNearestAttackableTarget(this, EntityEndermite.class, 10, true, false, new Predicate() { + public boolean a(EntityEndermite entityendermite) { + return entityendermite.n(); + } + + public boolean apply(Object object) { + return this.a((EntityEndermite) object); + } + })); + } + + protected void initAttributes() { + super.initAttributes(); + this.getAttributeInstance(GenericAttributes.maxHealth).setValue(40.0D); + this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.30000001192092896D); + this.getAttributeInstance(GenericAttributes.ATTACK_DAMAGE).setValue(7.0D); + this.getAttributeInstance(GenericAttributes.FOLLOW_RANGE).setValue(64.0D); + } + + protected void h() { + super.h(); + this.datawatcher.a(16, (short) 0); + this.datawatcher.a(17, (byte) 0); + this.datawatcher.a(18, (byte) 0); + } + + public void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + IBlockData iblockdata = this.getCarried(); + + nbttagcompound.setShort("carried", (short) Block.getId(iblockdata.getBlock())); + nbttagcompound.setShort("carriedData", (short) iblockdata.getBlock().toLegacyData(iblockdata)); + } + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + IBlockData iblockdata; + + if (nbttagcompound.hasKeyOfType("carried", 8)) { + iblockdata = Block.getByName(nbttagcompound.getString("carried")).fromLegacyData(nbttagcompound.getShort("carriedData") & '\uffff'); + } else { + iblockdata = Block.getById(nbttagcompound.getShort("carried")).fromLegacyData(nbttagcompound.getShort("carriedData") & '\uffff'); + } + + this.setCarried(iblockdata); + } + + private boolean c(EntityHuman entityhuman) { + ItemStack itemstack = entityhuman.inventory.armor[3]; + + if (itemstack != null && itemstack.getItem() == Item.getItemOf(Blocks.PUMPKIN)) { + return false; + } else { + Vec3D vec3d = entityhuman.d(1.0F).a(); + Vec3D vec3d1 = new Vec3D(this.locX - entityhuman.locX, (this.locY + (double) this.getHeadHeight()) - (entityhuman.locY + (double) entityhuman.getHeadHeight()), this.locZ - entityhuman.locZ); + double d0 = vec3d1.b(); + + vec3d1 = vec3d1.a(); + double d1 = vec3d.b(vec3d1); + + return d1 > 1.0D - 0.025D / d0 && entityhuman.hasLineOfSight(this); + } + } + + public float getHeadHeight() { + return 2.55F; + } + + public void m() { + this.aY = false; + super.m(); + } + + protected void E() { + if (this.U()) { + this.damageEntity(DamageSource.DROWN, 1.0F); + } + + if (this.co() && !this.bm && random.nextInt(100) == 0) { + this.a(false); + } + + if (this.world.w()) { + float f = this.c(1.0F); + + if (f > 0.5F && this.world.i(MathHelper.floor(locX), MathHelper.floor(locY), MathHelper.floor(locZ)) && random.nextFloat() * 30.0F < (f - 0.4F) * 2.0F) { + this.setGoalTarget(null); + this.a(false); + this.bm = false; + this.n(); + } + } + + super.E(); + } + + protected boolean n() { + double d0 = this.locX + (random.nextDouble() - 0.5D) * 64.0D; + double d1 = this.locY + (double) (random.nextInt(64) - 32); + double d2 = this.locZ + (random.nextDouble() - 0.5D) * 64.0D; + + return this.k(d0, d1, d2); + } + + protected boolean b(Entity entity) { + Vec3D vec3d = new Vec3D(this.locX - entity.locX, this.locY + (double) this.getHeadHeight() - entity.locY + (double) entity.getHeadHeight(), this.locZ - entity.locZ); + vec3d = vec3d.a(); + double d0 = 16.0D; + double d1 = this.locX + (random.nextDouble() - 0.5D) * 8.0D - vec3d.a * d0; + double d2 = this.locY + (double) (random.nextInt(16) - 8) - vec3d.b * d0; + double d3 = this.locZ + (random.nextDouble() - 0.5D) * 8.0D - vec3d.c * d0; + + return this.k(d1, d2, d3); + } + + protected boolean k(double d0, double d1, double d2) { + if (!intelligence) + return false; + + double d3 = this.locX; + double d4 = this.locY; + double d5 = this.locZ; + + this.locX = d0; + this.locY = d1; + this.locZ = d2; + boolean flag = false; + int x = MathHelper.floor(locX), y = MathHelper.floor(locY), z = MathHelper.floor(locZ); + + if (this.world.isLoaded(x,y,z)) { + boolean flag1 = false; + + while (!flag1 && y > 0) { + Block block = this.world.getType(x,y-1,z).getBlock(); + + if (block.getMaterial().isSolid()) { + flag1 = true; + } else { + --this.locY; + y--; + } + } + + if (flag1) { + // CraftBukkit start - Teleport event + // super.enderTeleportTo(this.locX, this.locY, this.locZ); + EntityTeleportEvent teleport = new EntityTeleportEvent(this.getBukkitEntity(), new Location(this.world.getWorld(), d3, d4, d5), new Location(this.world.getWorld(), this.locX, this.locY, this.locZ)); + this.world.getServer().getPluginManager().callEvent(teleport); + if (teleport.isCancelled()) { + return false; + } + + Location to = teleport.getTo(); + this.enderTeleportTo(to.getX(), to.getY(), to.getZ()); + // CraftBukkit end + if (this.world.getCubes(this, this.boundingBox).isEmpty() && !this.world.containsLiquid(this.boundingBox)) { + flag = true; + } + } + } + + if (!flag) { + this.setPosition(d3, d4, d5); + return false; + } else { + short short0 = 128; + + for (int i = 0; i < short0; ++i) { + double d6 = (double) i / ((double) short0 - 1.0D); + float f = (random.nextFloat() - 0.5F) * 0.2F; + float f1 = (random.nextFloat() - 0.5F) * 0.2F; + float f2 = (random.nextFloat() - 0.5F) * 0.2F; + double d7 = d3 + (this.locX - d3) * d6 + (random.nextDouble() - 0.5D) * this.width * 2.0D; + double d8 = d4 + (this.locY - d4) * d6 + random.nextDouble() * (double) this.length; + double d9 = d5 + (this.locZ - d5) * d6 + (random.nextDouble() - 0.5D) * this.width * 2.0D; + + this.world.addParticle(EnumParticle.PORTAL, d7, d8, d9, f, f1, f2, EnumParticle.EMPTY_ARRAY); + } + + this.world.makeSound(d3, d4, d5, "mob.endermen.portal", 1.0F, 1.0F); + this.makeSound("mob.endermen.portal", 1.0F, 1.0F); + return true; + } + } + + protected String z() { + return this.co() ? "mob.endermen.scream" : "mob.endermen.idle"; + } + + protected String bo() { + return "mob.endermen.hit"; + } + + protected String bp() { + return "mob.endermen.death"; + } + + protected Item getLoot() { + return Items.ENDER_PEARL; + } + + protected void dropDeathLoot(boolean flag, int i) { + Item item = this.getLoot(); + + if (item != null) { + int j = random.nextInt(2 + i); + + for (int k = 0; k < j; ++k) { + this.a(item, 1); + } + } + + // PaperSpigot start - Drop the block the entity is holding when it dies + Item carriedItem = Item.getItemOf(getCarried().getBlock()); + if (carriedItem != null) { + this.a(carriedItem, 1); + } + // PaperSpigot end + + } + + public void setCarried(IBlockData iblockdata) { + this.datawatcher.watch(16, (short) (Block.getCombinedId(iblockdata) & '\uffff')); + } + + public IBlockData getCarried() { + return Block.getByCombinedId(this.datawatcher.getShort(16) & '\uffff'); + } + + public boolean damageEntity(DamageSource damagesource, float f) { + if (this.isInvulnerable(damagesource)) { + return false; + } else { + if (damagesource.getEntity() == null || !(damagesource.getEntity() instanceof EntityEndermite)) { + this.a(true); + if (damagesource instanceof EntityDamageSource && damagesource.getEntity() instanceof EntityHuman) { + if (((EntityPlayer) damagesource.getEntity()).playerInteractManager.isCreative()) { + this.a(false); + } else { + this.bm = true; + } + } + + if (damagesource instanceof EntityDamageSourceIndirect) { + this.bm = false; + + for (int i = 0; i < 64; ++i) { + if (this.n()) { + return true; + } + } + + return false; + } + } + + boolean flag = super.damageEntity(damagesource, f); + + if (damagesource.ignoresArmor() && random.nextInt(10) != 0) { + this.n(); + } + + return flag; + } + } + + public boolean co() { + return this.datawatcher.getByte(18) > 0; + } + + public void a(boolean flag) { + this.datawatcher.watch(18, (byte) (flag ? 1 : 0)); + } + + static { + EntityEnderman.c.add(Blocks.GRASS); + EntityEnderman.c.add(Blocks.DIRT); + EntityEnderman.c.add(Blocks.SAND); + EntityEnderman.c.add(Blocks.GRAVEL); + EntityEnderman.c.add(Blocks.YELLOW_FLOWER); + EntityEnderman.c.add(Blocks.RED_FLOWER); + EntityEnderman.c.add(Blocks.BROWN_MUSHROOM); + EntityEnderman.c.add(Blocks.RED_MUSHROOM); + EntityEnderman.c.add(Blocks.TNT); + EntityEnderman.c.add(Blocks.CACTUS); + EntityEnderman.c.add(Blocks.CLAY); + EntityEnderman.c.add(Blocks.PUMPKIN); + EntityEnderman.c.add(Blocks.MELON_BLOCK); + EntityEnderman.c.add(Blocks.MYCELIUM); + } + + static class PathfinderGoalEndermanPickupBlock extends PathfinderGoal { + + private final EntityEnderman enderman; + + public PathfinderGoalEndermanPickupBlock(EntityEnderman entityenderman) { + this.enderman = entityenderman; + } + + public boolean a() { + return this.enderman.world.getGameRules().getBoolean("mobGriefing") && (this.enderman.getCarried().getBlock().getMaterial() == Material.AIR && this.enderman.bc().nextInt(20) == 0); + } + + public void e() { + Random random = this.enderman.bc(); + World world = this.enderman.world; + int i = MathHelper.floor(this.enderman.locX - 2.0D + random.nextDouble() * 4.0D); + int j = MathHelper.floor(this.enderman.locY + random.nextDouble() * 3.0D); + int k = MathHelper.floor(this.enderman.locZ - 2.0D + random.nextDouble() * 4.0D); + IBlockData iblockdata = world.getType(i, j, k); + Block block = iblockdata.getBlock(); + + if (EntityEnderman.c.contains(block)) { + // CraftBukkit start - Pickup event + if (!org.bukkit.craftbukkit.event.CraftEventFactory.callEntityChangeBlockEvent(this.enderman, this.enderman.world.getWorld().getBlockAt(i, j, k), org.bukkit.Material.AIR).isCancelled()) { + this.enderman.setCarried(iblockdata); + world.setTypeUpdate(new BlockPosition(i, j, k), Blocks.AIR.getBlockData()); + } + // CraftBukkit end + } + + } + } + + static class PathfinderGoalEndermanPlaceBlock extends PathfinderGoal { + + private final EntityEnderman a; + + public PathfinderGoalEndermanPlaceBlock(EntityEnderman entityenderman) { + this.a = entityenderman; + } + + public boolean a() { + return this.a.world.getGameRules().getBoolean("mobGriefing") && (this.a.getCarried().getBlock().getMaterial() != Material.AIR && this.a.bc().nextInt(2000) == 0); + } + + public void e() { + Random random = this.a.bc(); + World world = this.a.world; + int i = MathHelper.floor(this.a.locX - 1.0D + random.nextDouble() * 2.0D); + int j = MathHelper.floor(this.a.locY + random.nextDouble() * 2.0D); + int k = MathHelper.floor(this.a.locZ - 1.0D + random.nextDouble() * 2.0D); + BlockPosition blockposition = new BlockPosition(i, j, k); + Block block = world.getType(i, j, k).getBlock(); + + if (this.a(world, blockposition, this.a.getCarried().getBlock(), block, world.getType(i, j - 1, k).getBlock())) { + // CraftBukkit start - Place event + if (!org.bukkit.craftbukkit.event.CraftEventFactory.callEntityChangeBlockEvent(this.a,i,j,k, this.a.getCarried().getBlock(), this.a.getCarried().getBlock().toLegacyData(this.a.getCarried())).isCancelled()) { + world.setTypeAndData(new BlockPosition(i, j, k), this.a.getCarried(), 3); + this.a.setCarried(Blocks.AIR.getBlockData()); + } + // CraftBukkit end + } + + } + + private boolean a(World world, BlockPosition blockposition, Block block, Block block1, Block block2) { + return block.canPlace(world, blockposition) && (block1.getMaterial() == Material.AIR && (block2.getMaterial() != Material.AIR && block2.d())); + } + } + + static class PathfinderGoalPlayerWhoLookedAtTarget extends PathfinderGoalNearestAttackableTarget { + + private EntityHuman g; + private int h; + private int i; + private final EntityEnderman j; + + public PathfinderGoalPlayerWhoLookedAtTarget(EntityEnderman entityenderman) { + super(entityenderman, EntityHuman.class, true); + this.j = entityenderman; + } + + public boolean a() { + double d0 = this.f(); + List list = this.e.world.a(EntityHuman.class, this.e.boundingBox.grow(d0, 4.0D, d0), this.c); + + Collections.sort(list, this.b); + if (list.isEmpty()) { + return false; + } else { + this.g = (EntityHuman) list.get(0); + return true; + } + } + + public void c() { + this.h = 5; + this.i = 0; + } + + public void d() { + this.g = null; + this.j.a(false); + this.j.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).c(EntityEnderman.b); + super.d(); + } + + public boolean b() { + if (this.g != null) { + if (!this.j.c(this.g)) { + return false; + } else { + this.j.bm = true; + this.j.a(this.g, 10.0F, 10.0F); + return true; + } + } else { + return super.b(); + } + } + + public void e() { + if (this.g != null) { + if (--this.h <= 0) { + this.d = this.g; + this.g = null; + super.c(); + this.j.makeSound("mob.endermen.stare", 1.0F, 1.0F); + this.j.a(true); + j.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).b(EntityEnderman.b); + } + } else { + if (this.d != null) { + if (this.d instanceof EntityHuman && this.j.c((EntityHuman) this.d)) { + if (this.d.h(this.j) < 16.0D) { + this.j.n(); + } + + this.i = 0; + } else if (this.d.h(this.j) > 256.0D && this.i++ >= 30 && this.j.b((Entity) this.d)) { + this.i = 0; + } + } + + super.e(); + } + + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityEndermite.java b/azurite-server/src/main/java/net/minecraft/server/EntityEndermite.java new file mode 100644 index 0000000..a1c5ea9 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityEndermite.java @@ -0,0 +1,105 @@ +package net.minecraft.server; + +public class EntityEndermite extends EntityMonster { + + private int a = 0; + private boolean b = false; + + public EntityEndermite(World world) { + super(world); + this.b_ = 3; + this.setSize(0.4F, 0.3F); + this.goalSelector.a(1, new PathfinderGoalFloat(this)); + this.goalSelector.a(2, new PathfinderGoalMeleeAttack(this, EntityHuman.class, 1.0D, false)); + this.goalSelector.a(3, new PathfinderGoalRandomStroll(this, 1.0D)); + this.goalSelector.a(7, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 8.0F)); + this.goalSelector.a(8, new PathfinderGoalRandomLookaround(this)); + this.targetSelector.a(1, new PathfinderGoalHurtByTarget(this, true)); + this.targetSelector.a(2, new PathfinderGoalNearestAttackableTarget<>(this, EntityHuman.class, true)); + } + + public float getHeadHeight() { + return 0.1F; + } + + protected void initAttributes() { + super.initAttributes(); + this.getAttributeInstance(GenericAttributes.maxHealth).setValue(8.0D); + this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.25D); + this.getAttributeInstance(GenericAttributes.ATTACK_DAMAGE).setValue(2.0D); + } + + protected boolean s_() { + return false; + } + + protected String z() { + return "mob.silverfish.say"; + } + + protected String bo() { + return "mob.silverfish.hit"; + } + + protected String bp() { + return "mob.silverfish.kill"; + } + + protected void a(BlockPosition blockposition, Block block) { + this.makeSound("mob.silverfish.step", 0.15F, 1.0F); + } + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + this.a = nbttagcompound.getInt("Lifetime"); + this.b = nbttagcompound.getBoolean("PlayerSpawned"); + } + + public void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + nbttagcompound.setInt("Lifetime", this.a); + nbttagcompound.setBoolean("PlayerSpawned", this.b); + } + + public void t_() { + this.aI = this.yaw; + super.t_(); + } + + public boolean n() { + return this.b; + } + + public void a(boolean flag) { + this.b = flag; + } + + public void m() { + super.m(); + if (!this.isPersistent()) { + ++this.a; + } + + if (this.a >= 2400) { + this.die(); + } + } + + protected boolean n_() { + return true; + } + + public boolean bR() { + if (super.bR()) { + EntityHuman entityhuman = this.world.findNearbyPlayer(this, 5.0D); + + return entityhuman == null; + } else { + return false; + } + } + + public EnumMonsterType getMonsterType() { + return EnumMonsterType.ARTHROPOD; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityExperienceOrb.java b/azurite-server/src/main/java/net/minecraft/server/EntityExperienceOrb.java new file mode 100644 index 0000000..44e80e0 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityExperienceOrb.java @@ -0,0 +1,198 @@ +package net.minecraft.server; + +// CraftBukkit start + +import org.bukkit.craftbukkit.event.CraftEventFactory; +import org.bukkit.event.entity.EntityTargetEvent; +import org.bukkit.event.entity.EntityTargetLivingEntityEvent; +// CraftBukkit end + +public class EntityExperienceOrb extends Entity { + + public int a; + public int b; + public int c; + public int value; + private int d = 5; + private EntityHuman targetPlayer; + private int targetTime; + + public EntityExperienceOrb(World world, double d0, double d1, double d2, int i) { + super(world); + this.setSize(0.5F, 0.5F); + this.setPosition(d0, d1, d2); + this.yaw = (float) (Math.random() * 360.0D); + this.motX = ((float) (Math.random() * 0.20000000298023224D - 0.10000000149011612D) * 2.0F); + this.motY = ((float) (Math.random() * 0.2D) * 2.0F); + this.motZ = ((float) (Math.random() * 0.20000000298023224D - 0.10000000149011612D) * 2.0F); + this.value = i; + } + + public EntityExperienceOrb(World world) { + super(world); + this.setSize(0.25F, 0.25F); + } + + public static int getOrbValue(int i) { + // CraftBukkit start + if (i > 162670129) return i - 100000; + if (i > 81335063) return 81335063; + if (i > 40667527) return 40667527; + if (i > 20333759) return 20333759; + if (i > 10166857) return 10166857; + if (i > 5083423) return 5083423; + if (i > 2541701) return 2541701; + if (i > 1270849) return 1270849; + if (i > 635413) return 635413; + if (i > 317701) return 317701; + if (i > 158849) return 158849; + if (i > 79423) return 79423; + if (i > 39709) return 39709; + if (i > 19853) return 19853; + if (i > 9923) return 9923; + if (i > 4957) return 4957; + // CraftBukkit end + return i >= 2477 ? 2477 : (i >= 1237 ? 1237 : (i >= 617 ? 617 : (i >= 307 ? 307 : (i >= 149 ? 149 : (i >= 73 ? 73 : (i >= 37 ? 37 : (i >= 17 ? 17 : (i >= 7 ? 7 : (i >= 3 ? 3 : 1))))))))); + } + + protected boolean s_() { + return false; + } + + protected void h() { + } + + public void t_() { + super.t_(); + EntityHuman prevTarget = this.targetPlayer;// CraftBukkit - store old target + if (this.c > 0) { + --this.c; + } + + this.lastX = this.locX; + this.lastY = this.locY; + this.lastZ = this.locZ; + this.motY -= 0.029999999329447746D; + if (this.world.getType(MathHelper.floor(locX), MathHelper.floor(locY), MathHelper.floor(locZ)).getBlock().getMaterial() == Material.LAVA) { + this.motY = 0.20000000298023224D; + this.motX = ((random.nextFloat() - random.nextFloat()) * 0.2F); + this.motZ = ((random.nextFloat() - random.nextFloat()) * 0.2F); + this.makeSound("random.fizz", 0.4F, 2.0F + random.nextFloat() * 0.4F); + } + + this.j(this.locX, (this.getBoundingBox().b + this.getBoundingBox().e) / 2.0D, this.locZ); + double d0 = 8.0D; + + if (this.targetTime < this.a - 20 + this.getId() % 100) { + if (this.targetPlayer == null || this.targetPlayer.h(this) > d0 * d0) { + this.targetPlayer = this.world.findNearbyPlayer(this, d0); + } + + this.targetTime = this.a; + } + + if (this.targetPlayer != null && this.targetPlayer.isSpectator()) { + this.targetPlayer = null; + } + + if (this.targetPlayer != null) { + // CraftBukkit start + boolean cancelled = false; + if (this.targetPlayer != prevTarget) { + EntityTargetLivingEntityEvent event = CraftEventFactory.callEntityTargetLivingEvent(this, targetPlayer, EntityTargetEvent.TargetReason.CLOSEST_PLAYER); + EntityLiving target = event.getTarget() == null ? null : ((org.bukkit.craftbukkit.entity.CraftLivingEntity) event.getTarget()).getHandle(); + targetPlayer = target instanceof EntityHuman ? (EntityHuman) target : null; + cancelled = event.isCancelled(); + } + + if (!cancelled && targetPlayer != null) { + double d1 = (this.targetPlayer.locX - this.locX) / d0; + double d2 = (this.targetPlayer.locY + (double) this.targetPlayer.getHeadHeight() - this.locY) / d0; + double d3 = (this.targetPlayer.locZ - this.locZ) / d0; + double d4 = Math.sqrt(d1 * d1 + d2 * d2 + d3 * d3); + double d5 = 1.0D - d4; + + if (d5 > 0.0D) { + d5 *= d5; + this.motX += d1 / d4 * d5 * 0.1D; + this.motY += d2 / d4 * d5 * 0.1D; + this.motZ += d3 / d4 * d5 * 0.1D; + } + } + // CraftBukkit end + } + + this.move(this.motX, this.motY, this.motZ); + float f = 0.98F; + + if (this.onGround) { + f = this.world.getType(MathHelper.floor(this.locX), MathHelper.floor(this.getBoundingBox().b) - 1, MathHelper.floor(this.locZ)).getBlock().frictionFactor * 0.98F; + } + + this.motX *= f; + this.motY *= 0.9800000190734863D; + this.motZ *= f; + if (this.onGround) { + this.motY *= -0.8999999761581421D; + } + + ++this.a; + ++this.b; + if (this.b >= 6000) { + this.die(); + } + + } + + public boolean W() { + return this.world.a(this.getBoundingBox(), Material.WATER, this); + } + + protected void burn(int i) { + this.damageEntity(DamageSource.FIRE, (float) i); + } + + public boolean damageEntity(DamageSource damagesource, float f) { + if (!this.isInvulnerable(damagesource)) { + this.ac(); + this.d = (int) ((float) this.d - f); + if (this.d <= 0) { + this.die(); + } + + } + return false; + } + + public void b(NBTTagCompound nbttagcompound) { + nbttagcompound.setShort("Health", (byte) this.d); + nbttagcompound.setShort("Age", (short) this.b); + nbttagcompound.setInt("Value", this.value); + } + + public void a(NBTTagCompound nbttagcompound) { + this.d = nbttagcompound.getShort("Health") & 255; + this.b = nbttagcompound.getShort("Age"); + this.value = nbttagcompound.getInt("Value"); + } + + public void d(EntityHuman entityhuman) { + + if (this.c == 0 && entityhuman.bp == 0) { + entityhuman.bp = 2; + this.world.makeSound(entityhuman, "random.orb", 0.1F, 0.5F * ((random.nextFloat() - random.nextFloat()) * 0.7F + 1.8F)); + entityhuman.receive(this, 1); + entityhuman.giveExp(CraftEventFactory.callPlayerExpChangeEvent(entityhuman, this.value).getAmount()); // CraftBukkit - this.value -> event.getAmount() + this.die(); + } + + } + + public int j() { + return this.value; + } + + public boolean aD() { + return false; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityFallingBlock.java b/azurite-server/src/main/java/net/minecraft/server/EntityFallingBlock.java new file mode 100644 index 0000000..5a6c87a --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityFallingBlock.java @@ -0,0 +1,410 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.AzuriteConfig; +import org.bukkit.craftbukkit.event.CraftEventFactory; + +import java.util.Iterator; +import java.util.List; + +public class EntityFallingBlock extends Entity { + + public int ticksLived; + public boolean dropItem = true; + public boolean hurtEntities; // PAIL: private -> public + public NBTTagCompound tileEntityData; + public org.bukkit.Location sourceLoc; // PaperSpigot + private IBlockData block; + private boolean e; + private int fallHurtMax = 40; + private float fallHurtAmount = 2.0F; + + // PaperSpigot start - Add FallingBlock source location API + public EntityFallingBlock(World world) { + this(null, world); + } + + public EntityFallingBlock(org.bukkit.Location loc, World world) { + super(world); + sourceLoc = loc; + loadChunks = world.paperSpigotConfig.loadUnloadedFallingBlocks; // PaperSpigot + } + + public EntityFallingBlock(World world, double d0, double d1, double d2, IBlockData iblockdata) { + this(null, world, d0, d1, d2, iblockdata); + } + + public EntityFallingBlock(org.bukkit.Location loc, World world, double d0, double d1, double d2, IBlockData iblockdata) { + super(world); + sourceLoc = loc; + this.block = iblockdata; + this.k = true; + this.setSize(0.98F, 0.98F); + this.setPosition(d0, d1, d2); + this.motX = 0.0D; + this.motY = 0.0D; + this.motZ = 0.0D; + this.lastX = d0; + this.lastY = d1; + this.lastZ = d2; + this.loadChunks = world.paperSpigotConfig.loadUnloadedFallingBlocks; // PaperSpigot + } + + protected boolean s_() { + return false; + } + + protected void h() { + } + + public boolean ad() { + return !dead; + } + + public void t_() { + Block block = this.block.getBlock(); + if (block.getMaterial() == Material.AIR) { + die(); + } else { + lastX = locX; + lastY = locY; + lastZ = locZ; + + if (ticksLived++ == 0) { + int x = MathHelper.floor(locX), y = MathHelper.floor(locY), z = MathHelper.floor(locZ); + if (world.getType(x, y, z).getBlock() == block && !CraftEventFactory.callEntityChangeBlockEvent(this, x, y, z, Blocks.AIR, 0).isCancelled()) { + world.setTypeAndData(new BlockPosition(x, y, z), Blocks.AIR.getBlockData(), 3, false, true); + } else { + die(); + return; + } + } + + motY -= 0.03999999910593033D; + move(motX, motY, motZ); + + if (world.paperSpigotConfig.fallingBlockHeightNerf != 0 && locY > world.paperSpigotConfig.fallingBlockHeightNerf || + inUnloadedChunk && world.paperSpigotConfig.removeUnloadedFallingBlocks) { + die(); + if (dropItem && world.getGameRules().getBoolean("doEntityDrops")) + a(new ItemStack(block, 1, block.getDropData(this.block)), 0.0F); + return; + } + + motX *= 0.9800000190734863D; + motY *= 0.9800000190734863D; + motZ *= 0.9800000190734863D; + + BlockPosition blockposition = new BlockPosition(this); + if (onGround) { + motX *= 0.699999988079071D; + motZ *= 0.699999988079071D; + motY *= -0.5D; + + IBlockData currentBlock = world.getType(blockposition); + if (currentBlock.getBlock() != Blocks.PISTON_EXTENSION) { + die(); + if (!e) { + if (world.a(block, blockposition, true, EnumDirection.UP, null, null) && !BlockFalling.canFall(world, blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()) && blockposition.getX() >= -30000000 && blockposition.getZ() >= -30000000 && blockposition.getX() < 30000000 && blockposition.getZ() < 30000000 && blockposition.getY() >= 0 && blockposition.getY() < 256 && currentBlock != this.block) { + if (AzuriteConfig.fireSandBlockChangeEvent.getValue() && CraftEventFactory.callEntityChangeBlockEvent(this, blockposition, this.block.getBlock(), this.block.getBlock().toLegacyData(this.block)).isCancelled()) + return; + + world.setTypeAndData(blockposition, this.block, 3, false, AzuriteConfig.optimizeSandMovement.getValue()); + respawn(); + + if (block instanceof BlockFalling) + ((BlockFalling) block).a_(this.world, blockposition); + + if (this.tileEntityData != null && block instanceof IContainer) { + TileEntity tileentity = this.world.getTileEntity(blockposition); + if (tileentity != null) { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + tileentity.b(nbttagcompound); + for (String s : this.tileEntityData.c()) { + NBTBase nbtbase = this.tileEntityData.get(s); + if (!s.equals("x") && !s.equals("y") && !s.equals("z")) + nbttagcompound.set(s, nbtbase.clone()); + } + tileentity.a(nbttagcompound); + tileentity.update(); + } + } + } else if (dropItem && world.getGameRules().getBoolean("doEntityDrops")) { + a(new ItemStack(block, 1, block.getDropData(this.block)), 0.0F); + } + } + } + + } else if ((ticksLived > 100 && (blockposition.getY() < 1 || blockposition.getY() > 256)) || ticksLived > 600) { + if (dropItem && world.getGameRules().getBoolean("doEntityDrops")) + a(new ItemStack(block, 1, block.getDropData(this.block)), 0.0F); + die(); + } + } + + } + + public void e(float f, float f1) { + if (this.hurtEntities) { + int i = MathHelper.f(f - 1.0F); + + if (i > 0) { + boolean flag = this.block.getBlock() == Blocks.ANVIL; + DamageSource damagesource = flag ? DamageSource.ANVIL : DamageSource.FALLING_BLOCK; + for (Entity en : world.getEntities(this, boundingBox)) { + CraftEventFactory.entityDamage = this; // CraftBukkit + en.damageEntity(damagesource, Math.min(MathHelper.d(i * this.fallHurtAmount), this.fallHurtMax)); + CraftEventFactory.entityDamage = null; // CraftBukkit + } + + if (flag && random.nextFloat() < 0.05000000074505806D + i * 0.05D) { + int j = this.block.get(BlockAnvil.DAMAGE); + ++j; + if (j > 2) { + this.e = true; + } else { + this.block = this.block.set(BlockAnvil.DAMAGE, j); + } + } + } + } + + } + + public boolean merge(Entity entity) { + return AzuriteConfig.sandMerging.getValue() && + entity.ticksLived == ticksLived + 1 && + entity.lastX == locX && + entity.lastY == locY && + entity.lastZ == locZ && + entity.lastMotX == motX && + entity.lastMotY == motY - 0.03999999910593033D && + entity.lastMotZ == motZ && + entity.getClass() == getClass() && + ((EntityFallingBlock) entity).getBlock() == getBlock(); + } + + protected void respawn() { + if (potential <= 1) + return; + int amount = potential; + for (int i = 1; i < amount; i++) { + setPosition(lastX, lastY, lastZ); + motX = lastMotX; + motY = lastMotY + 0.03999999910593033D; + motZ = lastMotZ; + potential = 1; + t_(); + } + } + + protected void b(NBTTagCompound nbttagcompound) { + Block block = this.block != null ? this.block.getBlock() : Blocks.AIR; + MinecraftKey minecraftkey = Block.REGISTRY.c(block); + + nbttagcompound.setString("Block", minecraftkey == null ? "" : minecraftkey.toString()); + nbttagcompound.setByte("Data", (byte) block.toLegacyData(this.block)); + nbttagcompound.setByte("Time", (byte) this.ticksLived); + nbttagcompound.setBoolean("DropItem", this.dropItem); + nbttagcompound.setBoolean("HurtEntities", this.hurtEntities); + nbttagcompound.setFloat("FallHurtAmount", this.fallHurtAmount); + nbttagcompound.setInt("FallHurtMax", this.fallHurtMax); + if (this.tileEntityData != null) { + nbttagcompound.set("TileEntityData", this.tileEntityData); + } + // PaperSpigot start - Add FallingBlock source location API + if (sourceLoc != null) { + nbttagcompound.setInt("SourceLoc_x", sourceLoc.getBlockX()); + nbttagcompound.setInt("SourceLoc_y", sourceLoc.getBlockY()); + nbttagcompound.setInt("SourceLoc_z", sourceLoc.getBlockZ()); + } + // PaperSpigot end + } + + protected void a(NBTTagCompound nbttagcompound) { + int i = nbttagcompound.getByte("Data") & 255; + + if (nbttagcompound.hasKeyOfType("Block", 8)) { + this.block = Block.getByName(nbttagcompound.getString("Block")).fromLegacyData(i); + } else if (nbttagcompound.hasKeyOfType("TileID", 99)) { + this.block = Block.getById(nbttagcompound.getInt("TileID")).fromLegacyData(i); + } else { + this.block = Block.getById(nbttagcompound.getByte("Tile") & 255).fromLegacyData(i); + } + + this.ticksLived = nbttagcompound.getByte("Time") & 255; + Block block = this.block.getBlock(); + + if (nbttagcompound.hasKeyOfType("HurtEntities", 99)) { + this.hurtEntities = nbttagcompound.getBoolean("HurtEntities"); + this.fallHurtAmount = nbttagcompound.getFloat("FallHurtAmount"); + this.fallHurtMax = nbttagcompound.getInt("FallHurtMax"); + } else if (block == Blocks.ANVIL) { + this.hurtEntities = true; + } + + if (nbttagcompound.hasKeyOfType("DropItem", 99)) { + this.dropItem = nbttagcompound.getBoolean("DropItem"); + } + + if (nbttagcompound.hasKeyOfType("TileEntityData", 10)) { + this.tileEntityData = nbttagcompound.getCompound("TileEntityData"); + } + + if (block == null || block.getMaterial() == Material.AIR) { + this.block = Blocks.SAND.getBlockData(); + } + // PaperSpigot start - Add FallingBlock source location API + if (nbttagcompound.hasKey("SourceLoc_x")) { + int srcX = nbttagcompound.getInt("SourceLoc_x"); + int srcY = nbttagcompound.getInt("SourceLoc_y"); + int srcZ = nbttagcompound.getInt("SourceLoc_z"); + sourceLoc = new org.bukkit.Location(world.getWorld(), srcX, srcY, srcZ); + } + // PaperSpigot end + } + + public void a(boolean flag) { + this.hurtEntities = flag; + } + + public void appendEntityCrashDetails(CrashReportSystemDetails crashreportsystemdetails) { + super.appendEntityCrashDetails(crashreportsystemdetails); + if (this.block != null) { + Block block = this.block.getBlock(); + + crashreportsystemdetails.a("Immitating block ID", Block.getId(block)); + crashreportsystemdetails.a("Immitating block data", block.toLegacyData(this.block)); + } + + } + + public IBlockData getBlock() { + return this.block; + } + + public double f(double d0, double d1, double d2) { + if (!world.paperSpigotConfig.fixCannons) + return super.f(d0, d1, d2); + double d3 = locX - d0; + double d4 = locY + getHeadHeight() - d1; + double d5 = locZ - d2; + return MathHelper.sqrt(d3 * d3 + d4 * d4 + d5 * d5); + } + + public float getHeadHeight() { + return world.paperSpigotConfig.fixCannons ? (length / 2.0F) : super.getHeadHeight(); + } + + @Override + public void move(double d0, double d1, double d2) { + if (loadChunks) + loadChunks(); + if (noclip) { + a(boundingBox.c(d0, d1, d2)); + recalcPosition(); + } else { + lastMotX = motX; + lastMotY = motY; + lastMotZ = motZ; + if (world.movementCache.move(this)) + return; + + try { + checkBlockCollisions(); + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.a(throwable, "Checking entity block collision"); + CrashReportSystemDetails crashreportsystemdetails = crashreport.a("Entity being checked for collision"); + appendEntityCrashDetails(crashreportsystemdetails); + throw new ReportedException(crashreport); + } + + if (d0 == 0.0D && d1 == 0.0D && d2 == 0.0D && vehicle == null && passenger == null) + return; + + if (H) { + H = false; + d0 *= 0.25D; + d1 *= 0.05000000074505806D; + d2 *= 0.25D; + motX = 0.0D; + motY = 0.0D; + motZ = 0.0D; + } + + double d6 = d0; + double d7 = d1; + double d8 = d2; + + AxisAlignedBB totalArea = boundingBox.a(d0, d1, d2); + double xLength = totalArea.d - totalArea.a; + double yLength = totalArea.e - totalArea.b; + double zLength = totalArea.f - totalArea.c; + boolean axisScan = AzuriteConfig.optimizeTNTMovement.getValue() && (xLength * yLength * zLength > 10.0D); + List list = world.getCubes(this, axisScan ? boundingBox.a(0.0D, d1, 0.0D) : totalArea); + + AxisAlignedBB axisalignedbb1; + for (Iterator iterator = list.iterator(); iterator.hasNext(); d1 = axisalignedbb1.b(boundingBox, d1)) + axisalignedbb1 = iterator.next(); + a(boundingBox.c(0.0D, d1, 0.0D)); + + AxisAlignedBB axisalignedbb2; + if (AzuriteConfig.fixEastWestCannon.getValue() && Math.abs(d0) > Math.abs(d2)) { + if (axisScan) + list = world.getCubes(this, boundingBox.a(0.0D, 0.0D, d2)); + + Iterator iterator1; + for (iterator1 = list.iterator(); iterator1.hasNext(); d2 = axisalignedbb2.c(boundingBox, d2)) + axisalignedbb2 = iterator1.next(); + a(boundingBox.c(0.0D, 0.0D, d2)); + + if (axisScan) + list = world.getCubes(this, boundingBox.a(d0, 0.0D, 0.0D)); + + for (iterator1 = list.iterator(); iterator1.hasNext(); d0 = axisalignedbb2.a(boundingBox, d0)) + axisalignedbb2 = iterator1.next(); + a(boundingBox.c(d0, 0.0D, 0.0D)); + } else { + if (axisScan) + list = world.getCubes(this, boundingBox.a(d0, 0.0D, 0.0D)); + + Iterator iterator1; + for (iterator1 = list.iterator(); iterator1.hasNext(); d0 = axisalignedbb2.a(boundingBox, d0)) + axisalignedbb2 = iterator1.next(); + a(boundingBox.c(d0, 0.0D, 0.0D)); + + if (axisScan) + list = world.getCubes(this, boundingBox.a(0.0D, 0.0D, d2)); + + for (iterator1 = list.iterator(); iterator1.hasNext(); d2 = axisalignedbb2.c(boundingBox, d2)) + axisalignedbb2 = iterator1.next(); + a(boundingBox.c(0.0D, 0.0D, d2)); + } + + recalcPosition(); + positionChanged = !(d6 == d0 && d8 == d2); + E = (d7 != d1); + onGround = (E && d7 < 0.0D); + F = !(!positionChanged && !E); + + BlockPosition blockposition = new BlockPosition(MathHelper.floor(locX), MathHelper.floor(locY - 0.20000000298023224D), MathHelper.floor(locZ)); + Block block = world.getType(blockposition).getBlock(); + if (block.getMaterial() == Material.AIR) { + Block block1 = world.getType(blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()).getBlock(); + if (block1 instanceof BlockFence || block1 instanceof BlockCobbleWall || block1 instanceof BlockFenceGate) { + block = block1; + blockposition.setY(blockposition.getY() - 1); + } + } + + a(d1, onGround, block, blockposition); + if (d6 != d0) + motX = 0.0D; + if (d8 != d2) + motZ = 0.0D; + if (d7 != d1) + block.a(world, this); + + world.movementCache.cache(this); + } + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityFireball.java b/azurite-server/src/main/java/net/minecraft/server/EntityFireball.java new file mode 100644 index 0000000..41a282b --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityFireball.java @@ -0,0 +1,279 @@ +package net.minecraft.server; + +import org.bukkit.craftbukkit.event.CraftEventFactory; + +import java.util.List; + +public abstract class EntityFireball extends Entity { + + public EntityLiving shooter; + public double dirX; + public double dirY; + public double dirZ; + public float bukkitYield = 1; // CraftBukkit + public boolean isIncendiary = true; // CraftBukkit + private int e = -1; + private int f = -1; + private int g = -1; + private Block h; + private boolean i; + private int ar; + private int as; + + public EntityFireball(World world) { + super(world); + this.setSize(1.0F, 1.0F); + } + + public EntityFireball(World world, double d0, double d1, double d2, double d3, double d4, double d5) { + super(world); + this.setSize(1.0F, 1.0F); + this.setPositionRotation(d0, d1, d2, this.yaw, this.pitch); + this.setPosition(d0, d1, d2); + double d6 = MathHelper.sqrt(d3 * d3 + d4 * d4 + d5 * d5); + + this.dirX = d3 / d6 * 0.1D; + this.dirY = d4 / d6 * 0.1D; + this.dirZ = d5 / d6 * 0.1D; + } + + public EntityFireball(World world, EntityLiving entityliving, double d0, double d1, double d2) { + super(world); + this.shooter = entityliving; + this.projectileSource = (org.bukkit.entity.LivingEntity) entityliving.getBukkitEntity(); // CraftBukkit + this.setSize(1.0F, 1.0F); + this.setPositionRotation(entityliving.locX, entityliving.locY, entityliving.locZ, entityliving.yaw, entityliving.pitch); + this.setPosition(this.locX, this.locY, this.locZ); + this.motX = this.motY = this.motZ = 0.0D; + // CraftBukkit start - Added setDirection method + this.setDirection(d0, d1, d2); + } + + protected void h() { + } + + public void setDirection(double d0, double d1, double d2) { + // CraftBukkit end + d0 += random.nextGaussian() * 0.4D; + d1 += random.nextGaussian() * 0.4D; + d2 += random.nextGaussian() * 0.4D; + double d3 = MathHelper.sqrt(d0 * d0 + d1 * d1 + d2 * d2); + + this.dirX = d0 / d3 * 0.1D; + this.dirY = d1 / d3 * 0.1D; + this.dirZ = d2 / d3 * 0.1D; + } + + public void t_() { + if ((this.shooter != null && this.shooter.dead || !this.world.isLoaded(MathHelper.floor(this.locX), MathHelper.floor(this.locY), MathHelper.floor(this.locZ)))) { + this.die(); + } else { + super.t_(); + this.setOnFire(1); + if (this.i) { + if (this.world.getType(this.e, this.f, this.g).getBlock() == this.h) { + ++this.ar; + if (this.ar == 600) { + this.die(); + } + + return; + } + + this.i = false; + this.motX *= (random.nextFloat() * 0.2F); + this.motY *= (random.nextFloat() * 0.2F); + this.motZ *= (random.nextFloat() * 0.2F); + this.ar = 0; + this.as = 0; + } else { + ++this.as; + } + + Vec3D vec3d = new Vec3D(this.locX, this.locY, this.locZ); + Vec3D vec3d1 = new Vec3D(this.locX + this.motX, this.locY + this.motY, this.locZ + this.motZ); + MovingObjectPosition movingobjectposition = this.world.rayTrace(vec3d, vec3d1); + + vec3d = new Vec3D(this.locX, this.locY, this.locZ); + vec3d1 = new Vec3D(this.locX + this.motX, this.locY + this.motY, this.locZ + this.motZ); + if (movingobjectposition != null) { + vec3d1 = new Vec3D(movingobjectposition.pos.a, movingobjectposition.pos.b, movingobjectposition.pos.c); + } + + Entity entity = null; + List list = this.world.getEntities(this, this.getBoundingBox().a(this.motX, this.motY, this.motZ).grow(1.0D, 1.0D, 1.0D)); + double d0 = 0.0D; + + for (Entity entity1 : list) { + if (entity1.ad() && (!entity1.k(this.shooter) || this.as >= 25)) { + float f = 0.3F; + AxisAlignedBB axisalignedbb = entity1.getBoundingBox().grow(f, f, f); + MovingObjectPosition movingobjectposition1 = axisalignedbb.a(vec3d, vec3d1); + + if (movingobjectposition1 != null) { + double d1 = vec3d.distanceSquared(movingobjectposition1.pos); + + if (d1 < d0 || d0 == 0.0D) { + entity = entity1; + d0 = d1; + } + } + } + } + + if (entity != null) { + movingobjectposition = new MovingObjectPosition(entity); + } + + if (movingobjectposition != null) { + this.a(movingobjectposition); + + // CraftBukkit start - Fire ProjectileHitEvent + if (this.dead) { + CraftEventFactory.callProjectileHitEvent(this); + } + // CraftBukkit end + } + + this.locX += this.motX; + this.locY += this.motY; + this.locZ += this.motZ; + float f1 = MathHelper.sqrt(this.motX * this.motX + this.motZ * this.motZ); + + this.yaw = (float) (MathHelper.b(this.motZ, this.motX) * 180.0D / 3.1415927410125732D) + 90.0F; + + for (this.pitch = (float) (MathHelper.b(f1, this.motY) * 180.0D / 3.1415927410125732D) - 90.0F; this.pitch - this.lastPitch < -180.0F; this.lastPitch -= 360.0F) { + } + + while (this.pitch - this.lastPitch >= 180.0F) { + this.lastPitch += 360.0F; + } + + while (this.yaw - this.lastYaw < -180.0F) { + this.lastYaw -= 360.0F; + } + + while (this.yaw - this.lastYaw >= 180.0F) { + this.lastYaw += 360.0F; + } + + this.pitch = this.lastPitch + (this.pitch - this.lastPitch) * 0.2F; + this.yaw = this.lastYaw + (this.yaw - this.lastYaw) * 0.2F; + float f2 = this.j(); + + if (this.V()) { + for (int j = 0; j < 4; ++j) { + float f3 = 0.25F; + this.world.addParticle(EnumParticle.WATER_BUBBLE, this.locX - this.motX * f3, this.locY - this.motY * (double) f3, this.locZ - this.motZ * (double) f3, this.motX, this.motY, this.motZ, EnumParticle.EMPTY_ARRAY); + } + + f2 = 0.8F; + } + + this.motX += this.dirX; + this.motY += this.dirY; + this.motZ += this.dirZ; + this.motX *= f2; + this.motY *= f2; + this.motZ *= f2; + this.world.addParticle(EnumParticle.SMOKE_NORMAL, this.locX, this.locY + 0.5D, this.locZ, 0.0D, 0.0D, 0.0D, EnumParticle.EMPTY_ARRAY); + this.setPosition(this.locX, this.locY, this.locZ); + } + } + + protected float j() { + return 0.95F; + } + + protected abstract void a(MovingObjectPosition movingobjectposition); + + public void b(NBTTagCompound nbttagcompound) { + nbttagcompound.setShort("xTile", (short) this.e); + nbttagcompound.setShort("yTile", (short) this.f); + nbttagcompound.setShort("zTile", (short) this.g); + MinecraftKey minecraftkey = Block.REGISTRY.c(this.h); + + nbttagcompound.setString("inTile", minecraftkey == null ? "" : minecraftkey.toString()); + nbttagcompound.setByte("inGround", (byte) (this.i ? 1 : 0)); + // CraftBukkit - Fix direction being mismapped to invalid variables + nbttagcompound.set("power", this.a(this.dirX, this.dirY, this.dirZ)); + nbttagcompound.set("direction", this.a(this.motX, this.motY, this.motZ)); + } + + public void a(NBTTagCompound nbttagcompound) { + this.e = nbttagcompound.getShort("xTile"); + this.f = nbttagcompound.getShort("yTile"); + this.g = nbttagcompound.getShort("zTile"); + if (nbttagcompound.hasKeyOfType("inTile", 8)) { + this.h = Block.getByName(nbttagcompound.getString("inTile")); + } else { + this.h = Block.getById(nbttagcompound.getByte("inTile") & 255); + } + + this.i = nbttagcompound.getByte("inGround") == 1; + // CraftBukkit start - direction -> power + if (nbttagcompound.hasKeyOfType("power", 9)) { + NBTTagList nbttaglist = nbttagcompound.getList("power", 6); + + this.dirX = nbttaglist.d(0); + this.dirY = nbttaglist.d(1); + this.dirZ = nbttaglist.d(2); + } else if (nbttagcompound.hasKeyOfType("direction", 9)) { + NBTTagList nbttaglist = nbttagcompound.getList("direction", 6); + + this.motX = nbttaglist.d(0); + this.motY = nbttaglist.d(1); + this.motZ = nbttaglist.d(2); + // CraftBukkit end + } else { + this.die(); + } + + } + + public boolean ad() { + return true; + } + + public float ao() { + return 1.0F; + } + + public boolean damageEntity(DamageSource damagesource, float f) { + if (this.isInvulnerable(damagesource)) { + return false; + } else { + this.ac(); + if (damagesource.getEntity() != null) { + // CraftBukkit start + if (CraftEventFactory.handleNonLivingEntityDamageEvent(this, damagesource, f)) { + return false; + } + // CraftBukkit end + Vec3D vec3d = damagesource.getEntity().ap(); + + if (vec3d != null) { + this.motX = vec3d.a; + this.motY = vec3d.b; + this.motZ = vec3d.c; + this.dirX = this.motX * 0.1D; + this.dirY = this.motY * 0.1D; + this.dirZ = this.motZ * 0.1D; + } + + if (damagesource.getEntity() instanceof EntityLiving) { + this.shooter = (EntityLiving) damagesource.getEntity(); + this.projectileSource = (org.bukkit.projectiles.ProjectileSource) this.shooter.getBukkitEntity(); + } + + return true; + } else { + return false; + } + } + } + + public float c(float f) { + return 1.0F; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityFireworks.java b/azurite-server/src/main/java/net/minecraft/server/EntityFireworks.java new file mode 100644 index 0000000..a2eeaae --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityFireworks.java @@ -0,0 +1,129 @@ +package net.minecraft.server; + +public class EntityFireworks extends Entity { + + private int ticksFlown; + public int expectedLifespan; + + // Spigot Start + @Override + public void inactiveTick() + { + this.ticksFlown += 1; + super.inactiveTick(); + } + // Spigot End + + public EntityFireworks(World world) { + super(world); + this.setSize(0.25F, 0.25F); + } + + protected void h() { + this.datawatcher.add(8, 5); + } + + public EntityFireworks(World world, double d0, double d1, double d2, ItemStack itemstack) { + super(world); + this.ticksFlown = 0; + this.setSize(0.25F, 0.25F); + this.setPosition(d0, d1, d2); + int i = 1; + + if (itemstack != null && itemstack.hasTag()) { + this.datawatcher.watch(8, itemstack); + NBTTagCompound nbttagcompound = itemstack.getTag(); + NBTTagCompound nbttagcompound1 = nbttagcompound.getCompound("Fireworks"); + + if (nbttagcompound1 != null) { + i += nbttagcompound1.getByte("Flight"); + } + } + + this.motX = random.nextGaussian() * 0.001D; + this.motZ = random.nextGaussian() * 0.001D; + this.motY = 0.05D; + this.expectedLifespan = 10 * i + random.nextInt(6) + random.nextInt(7); + } + + public void t_() { + this.P = this.locX; + this.Q = this.locY; + this.R = this.locZ; + super.t_(); + this.motX *= 1.15D; + this.motZ *= 1.15D; + this.motY += 0.04D; + this.move(this.motX, this.motY, this.motZ); + float f = MathHelper.sqrt(this.motX * this.motX + this.motZ * this.motZ); + + this.yaw = (float) (MathHelper.b(this.motX, this.motZ) * 180.0D / 3.1415927410125732D); + + for (this.pitch = (float) (MathHelper.b(this.motY, f) * 180.0D / 3.1415927410125732D); this.pitch - this.lastPitch < -180.0F; this.lastPitch -= 360.0F) { + + } + + while (this.pitch - this.lastPitch >= 180.0F) { + this.lastPitch += 360.0F; + } + + while (this.yaw - this.lastYaw < -180.0F) { + this.lastYaw -= 360.0F; + } + + while (this.yaw - this.lastYaw >= 180.0F) { + this.lastYaw += 360.0F; + } + + this.pitch = this.lastPitch + (this.pitch - this.lastPitch) * 0.2F; + this.yaw = this.lastYaw + (this.yaw - this.lastYaw) * 0.2F; + if (this.ticksFlown == 0 && !this.R()) { + this.world.makeSound(this, "fireworks.launch", 3.0F, 1.0F); + } + + ++this.ticksFlown; + + if (this.ticksFlown > this.expectedLifespan) { + if (!org.bukkit.craftbukkit.event.CraftEventFactory.callFireworkExplodeEvent(this).isCancelled()) this.world.broadcastEntityEffect(this, (byte) 17); + this.die(); + } + + } + + public void b(NBTTagCompound nbttagcompound) { + nbttagcompound.setInt("Life", this.ticksFlown); + nbttagcompound.setInt("LifeTime", this.expectedLifespan); + ItemStack itemstack = this.datawatcher.getItemStack(8); + + if (itemstack != null) { + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + + itemstack.save(nbttagcompound1); + nbttagcompound.set("FireworksItem", nbttagcompound1); + } + + } + + public void a(NBTTagCompound nbttagcompound) { + this.ticksFlown = nbttagcompound.getInt("Life"); + this.expectedLifespan = nbttagcompound.getInt("LifeTime"); + NBTTagCompound nbttagcompound1 = nbttagcompound.getCompound("FireworksItem"); + + if (nbttagcompound1 != null) { + ItemStack itemstack = ItemStack.createStack(nbttagcompound1); + + if (itemstack != null) { + this.datawatcher.watch(8, itemstack); + } + } + + } + + public float c(float f) { + return super.c(f); + } + + public boolean aD() { + return false; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityFishingHook.java b/azurite-server/src/main/java/net/minecraft/server/EntityFishingHook.java new file mode 100644 index 0000000..58a974e --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityFishingHook.java @@ -0,0 +1,624 @@ +package net.minecraft.server; + +import dev.azurite.spigot.Azurite; +import dev.azurite.spigot.configs.AzuriteConfig; +import dev.azurite.spigot.knockback.Knockback; +import org.bukkit.entity.Fish; +import org.bukkit.entity.Player; +import org.bukkit.event.player.PlayerFishEvent; +import org.bukkit.util.Vector; + +import java.util.Arrays; +import java.util.List; + +public class EntityFishingHook extends Entity { + + private static final List d = Arrays.asList( + (new PossibleFishingResult(new ItemStack(Items.LEATHER_BOOTS), 10)).a(0.9F), + new PossibleFishingResult(new ItemStack(Items.LEATHER), 10), + new PossibleFishingResult(new ItemStack(Items.BONE), 10), + new PossibleFishingResult(new ItemStack(Items.POTION), 10), + new PossibleFishingResult(new ItemStack(Items.STRING), 5), + (new PossibleFishingResult(new ItemStack(Items.FISHING_ROD), 2)).a(0.9F), + new PossibleFishingResult(new ItemStack(Items.BOWL), 10), + new PossibleFishingResult(new ItemStack(Items.STICK), 5), + new PossibleFishingResult(new ItemStack(Items.DYE, 10, EnumColor.BLACK.getInvColorIndex()), 1), + new PossibleFishingResult(new ItemStack(Blocks.TRIPWIRE_HOOK), 10), + new PossibleFishingResult(new ItemStack(Items.ROTTEN_FLESH), 10)); + private static final List e = Arrays + .asList(new PossibleFishingResult(new ItemStack(Blocks.WATERLILY), 1), + new PossibleFishingResult(new ItemStack(Items.NAME_TAG), 1), + new PossibleFishingResult(new ItemStack(Items.SADDLE), 1), + (new PossibleFishingResult(new ItemStack(Items.BOW), 1)).a(0.25F).a(), + (new PossibleFishingResult(new ItemStack(Items.FISHING_ROD), 1)).a(0.25F).a(), + (new PossibleFishingResult(new ItemStack(Items.BOOK), 1)).a()); + private static final List f = Arrays.asList(new PossibleFishingResult(new ItemStack(Items.FISH, 1, ItemFish.EnumFish.COD.a()), 60), + new PossibleFishingResult(new ItemStack(Items.FISH, 1, ItemFish.EnumFish.SALMON.a()), 25), + new PossibleFishingResult(new ItemStack(Items.FISH, 1, ItemFish.EnumFish.CLOWNFISH.a()), 2), + new PossibleFishingResult(new ItemStack(Items.FISH, 1, ItemFish.EnumFish.PUFFERFISH.a()), 13)); + public int a; + public EntityHuman owner; + public Entity hooked; + private int g = -1; + private int h = -1; + private int i = -1; + private Block ar; + private boolean as; + private int at; + private int au; + private int av; + private int aw; + private int ax; + private float ay; + private int az; + + public EntityFishingHook(World world) { + super(world); + this.setSize(0.25F, 0.25F); + this.ah = true; + } + + public EntityFishingHook(World world, EntityHuman entityhuman) { + super(world); + this.ah = true; + this.owner = entityhuman; + this.owner.hookedFish = this; + this.setSize(0.25F, 0.25F); + this.setPositionRotation(entityhuman.locX, entityhuman.locY + entityhuman.getHeadHeight(), entityhuman.locZ, + entityhuman.yaw, entityhuman.pitch); + this.locY -= 0.10000000149011612D; + + // Beanes - remove projectile offset + if (!AzuriteConfig.patchProjectileOffset.getValue()) { + this.locX -= (MathHelper.cos(this.yaw / 180.0F * 3.1415927F) * 0.16F); + this.locZ -= (MathHelper.sin(this.yaw / 180.0F * 3.1415927F) * 0.16F); + } + + this.setPosition(this.locX, this.locY, this.locZ); + + this.motX = (-MathHelper.sin(this.yaw / 180.0F * 3.1415927F) * MathHelper.cos(this.pitch / 180.0F * 3.1415927F) + * 0.4F); + this.motZ = (MathHelper.cos(this.yaw / 180.0F * 3.1415927F) * MathHelper.cos(this.pitch / 180.0F * 3.1415927F) + * 0.4F); + this.motY = (-MathHelper.sin(this.pitch / 180.0F * 3.1415927F) * 0.4F); + this.c(this.motX, this.motY, this.motZ, 1.5F, AzuriteConfig.rodTrajectoryRandomness.getValue()); + + // Beanes - sync server & client values + this.reEncodeByServerValues(); + } + + public static List j() { + return EntityFishingHook.f; + } + + protected void h() { + } + + public void c(double d0, double d1, double d2, float f, float f1) { + f *= (float) (owner != null ? owner.getKnockbackProfile() : Azurite.getInstance().getKnockbackManager().getActiveProfile()).getRodSpeed(); + + float f2 = MathHelper.sqrt(d0 * d0 + d1 * d1 + d2 * d2); + + d0 /= f2; + d1 /= f2; + d2 /= f2; + d0 += random.nextGaussian() * 0.007499999832361937D * f1; + d1 += random.nextGaussian() * 0.007499999832361937D * f1; + d2 += random.nextGaussian() * 0.007499999832361937D * f1; + d0 *= f; + d1 *= f; + d2 *= f; + this.motX = d0; + this.motY = d1; + this.motZ = d2; + float f3 = MathHelper.sqrt(d0 * d0 + d2 * d2); + + this.lastYaw = this.yaw = (float) (MathHelper.b(d0, d2) * 180.0D / 3.1415927410125732D); + this.lastPitch = this.pitch = (float) (MathHelper.b(d1, f3) * 180.0D / 3.1415927410125732D); + this.at = 0; + } + + @Override + public void t_() { + super.t_(); + if (this.az > 0) { + this.yaw = (this.yaw + MathHelper.g(0 - this.yaw) / this.az); + this.pitch = (this.pitch + (0 - this.pitch) / this.az); + --this.az; + this.setPosition(this.locX + (0 - this.locX) / this.az, this.locY + (0 - this.locY) / this.az, this.locZ + (0 - this.locZ) / this.az); + this.setYawPitch(this.yaw, this.pitch); + } else { + ItemStack itemstack = this.owner.bZ(); + + if (this.owner.dead || !this.owner.isAlive() || itemstack == null || itemstack.getItem() != Items.FISHING_ROD || this.h(this.owner) > 1024.0D) { + this.die(); + this.owner.hookedFish = null; + return; + } + + if (this.hooked != null) { + if (!this.hooked.dead) { + this.motX = 0; + this.motY = 0; + this.motZ = 0; + + this.locX = this.hooked.locX; + double d4 = this.hooked.length; + + this.locY = this.hooked.boundingBox.b + d4 * 0.55D; + this.locZ = this.hooked.locZ; + return; + } + + this.hooked = null; + + // Beanes - smoother rods + // Whoever was hooked is no longer hooked, the entity tracker can stop tracking the rod + if (AzuriteConfig.rodTrackedToCenterOfHooked.getValue()) { + WorldServer worldServer = (WorldServer) world; + EntityTrackerEntry entry = worldServer.tracker.trackedEntities.get(getId()); + entry.c = Integer.MAX_VALUE; + } + } + + if (this.a > 0) { + --this.a; + } + + if (this.as) { + if (this.world.getType(this.g, this.h, this.i).getBlock() == this.ar) { + ++this.at; + if (this.at == 1200) { + this.die(); + } + + return; + } + + this.as = false; + this.motX *= (random.nextFloat() * 0.2F); + this.motY *= (random.nextFloat() * 0.2F); + this.motZ *= (random.nextFloat() * 0.2F); + this.at = 0; + this.au = 0; + } else { + ++this.au; + } + + Vec3D startingPoint = new Vec3D(this.locX, this.locY, this.locZ); + Vec3D endingPoint = new Vec3D(this.locX + this.motX, this.locY + this.motY, this.locZ + this.motZ); + MovingObjectPosition movingobjectposition = this.world.rayTrace(startingPoint, endingPoint); + + startingPoint = new Vec3D(this.locX, this.locY, this.locZ); + endingPoint = new Vec3D(this.locX + this.motX, this.locY + this.motY, this.locZ + this.motZ); + if (movingobjectposition != null) { + endingPoint = new Vec3D(movingobjectposition.pos.a, movingobjectposition.pos.b, movingobjectposition.pos.c); + } + + Entity bestEntity = null; + double bestDistance = Double.MAX_VALUE; + + double d6; + + // Beanes - grow way bigger as we don't track interpolation positions + double growFactor = AzuriteConfig.rodInterpolationRegistration.getValue() ? 5.0D : 1.0D; + + for (Entity possibleEntity : world.getEntities(this, boundingBox.a(motX, motY, motZ).grow(growFactor, growFactor, growFactor))) { + if (possibleEntity.ad() && (possibleEntity != owner || au >= 5)) { + boolean interpolationRods = AzuriteConfig.rodInterpolationRegistration.getValue() && possibleEntity instanceof EntityPlayer; + boolean onlyInterpolationRods = interpolationRods && AzuriteConfig.rodInterpolationRegistrationOnly.getValue(); + + double rodBox = 0.3; + + AxisAlignedBB axisalignedbb = possibleEntity.boundingBox.grow(rodBox, rodBox, rodBox); + + // Beanes - make rods smoother by checking if the start of the ray is inside the box + if (!this.as && axisalignedbb.a(startingPoint) && AzuriteConfig.checkStartOfRay.getValue() && !onlyInterpolationRods) { + d6 = 0.0D; + bestEntity = possibleEntity; + break; + } else { + if (!onlyInterpolationRods) { + MovingObjectPosition movingobjectposition1 = axisalignedbb.a(startingPoint, endingPoint); + + if (movingobjectposition1 != null) { + d6 = startingPoint.distanceSquared(movingobjectposition1.pos); + if (d6 < bestDistance) { + bestEntity = possibleEntity; + bestDistance = d6; + } + } + } + + // Beanes - improved projectile registration + if (interpolationRods) { + EntityPlayer player = (EntityPlayer) possibleEntity; + + double dist = player.interpolationData.attemptCollision(startingPoint, endingPoint, rodBox); + + if (dist == Double.MIN_VALUE) { + bestEntity = possibleEntity; + break; + } else if (dist < bestDistance) { + bestEntity = possibleEntity; + bestDistance = dist; + } + } + } + } + } + + if (bestEntity != null) { + movingobjectposition = new MovingObjectPosition(bestEntity); + } + + // PaperSpigot start - Allow fishing hooks to fly through vanished players the + // shooter can't see + if (movingobjectposition != null && bestEntity instanceof EntityPlayer && owner instanceof EntityPlayer) { + if (!((EntityPlayer) owner).getBukkitEntity().canSee(((EntityPlayer) bestEntity).getBukkitEntity())) { + movingobjectposition = null; + bestEntity = null; + } + } + // PaperSpigot end + + if (movingobjectposition != null) { + org.bukkit.craftbukkit.event.CraftEventFactory.callProjectileHitEvent(this); // Craftbukkit - Call event + + if (bestEntity != null) { + if (owner != null) { + double victimMotX = bestEntity.motX, victimMotY = bestEntity.motY, victimMotZ = bestEntity.motZ; + if (bestEntity.damageEntity(DamageSource.projectile(this, this.owner), 0.0F)) { + Knockback profile = owner.getKnockbackProfile(); + if (AzuriteConfig.overrideRodKnockback.getValue()) { + Vector unitVector = new Vector(motX, motY, motZ).normalize(); + double horizontal = profile.rodHorizontal.getValue(); + bestEntity.motX = (unitVector.getX() / 1.6D) * horizontal; + bestEntity.motY = 0.36D * profile.rodVertical.getValue(); + bestEntity.motZ = (unitVector.getZ() / 1.6D) * horizontal; + + // Immediately send the packet for players to prevent delayed knockback + if (bestEntity instanceof EntityPlayer && bestEntity.velocityChanged) { + ((EntityPlayer) bestEntity).sendVelocityPacket(victimMotX, victimMotY, victimMotZ, false); + } + } + hooked = bestEntity; + + // Beanes - smooth rods + // Someone is hooked so now we have to make the entity tracker update + // Reset motion values because the rod is hooked + if (AzuriteConfig.rodTrackedToCenterOfHooked.getValue()) { + this.motX = 0; + this.motY = 0; + this.motZ = 0; + + WorldServer worldServer = (WorldServer) world; + EntityTrackerEntry entry = worldServer.tracker.trackedEntities.get(getId()); + entry.c = 1; + } + } + } + } else if (movingobjectposition.direction == EnumDirection.UP) { + this.as = true; + + // Beanes - fix inGround + g = movingobjectposition.a().getX(); + h = movingobjectposition.a().getY(); + i = movingobjectposition.a().getZ(); + this.ar = this.world.getType(new BlockPosition(this.g, this.h, this.i)).getBlock(); + } + } + + if (!this.as) { + this.move(this.motX, this.motY, this.motZ); + float f1 = MathHelper.sqrt(this.motX * this.motX + this.motZ * this.motZ); + + this.yaw = (float) (MathHelper.b(this.motX, this.motZ) * 180.0D / 3.1415927410125732D); + + for (this.pitch = (float) (MathHelper.b(this.motY, f1) * 180.0D / 3.1415927410125732D); this.pitch + - this.lastPitch < -180.0F; this.lastPitch -= 360.0F) { + } + + while (this.pitch - this.lastPitch >= 180.0F) { + this.lastPitch += 360.0F; + } + + while (this.yaw - this.lastYaw < -180.0F) { + this.lastYaw -= 360.0F; + } + + while (this.yaw - this.lastYaw >= 180.0F) { + this.lastYaw += 360.0F; + } + + this.pitch = this.lastPitch + (this.pitch - this.lastPitch) * 0.2F; + this.yaw = this.lastYaw + (this.yaw - this.lastYaw) * 0.2F; + float f2 = 0.92F; + + if (this.onGround || this.positionChanged) { + f2 = 0.5F; + } + + byte b0 = 5; + double d7 = 0.0D; + + double d8; + + for (int j = 0; j < b0; ++j) { + AxisAlignedBB axisalignedbb1 = this.boundingBox; + double d9 = axisalignedbb1.e - axisalignedbb1.b; + double d10 = axisalignedbb1.b + d9 * j / b0; + + d8 = axisalignedbb1.b + d9 * (j + 1) / b0; + AxisAlignedBB axisalignedbb2 = new AxisAlignedBB(axisalignedbb1.a, d10, axisalignedbb1.c, + axisalignedbb1.d, d8, axisalignedbb1.f); + + if (this.world.b(axisalignedbb2, Material.WATER)) { + d7 += 1.0D / (double) b0; + // Update entity hook if we are in water + WorldServer worldServer = (WorldServer) world; + EntityTrackerEntry entry = worldServer.tracker.trackedEntities.get(getId()); + entry.c = 1; + } + } + + if (d7 > 0.0D) { + WorldServer worldserver = (WorldServer) this.world; + int k = 1; + + int x = MathHelper.floor(locX), y = MathHelper.floor(locY + 1), z = MathHelper.floor(locZ); + + if (random.nextFloat() < 0.25F && this.world.isRainingAt(x, y, z)) { + k = 2; + } + + if (random.nextFloat() < 0.5F && !this.world.i(x, y, z)) { + --k; + } + + if (this.av > 0) { + --this.av; + if (this.av <= 0) { + this.aw = 0; + this.ax = 0; + } + } else { + float f3; + float f4; + double d11; + Block block; + float f5; + double d12; + + if (this.ax > 0) { + this.ax -= k; + if (this.ax <= 0) { + this.motY -= 0.20000000298023224D; + + this.makeSound("random.splash", 0.25F, 1.0F + (random.nextFloat() - random.nextFloat()) * 0.4F); + f3 = (float) MathHelper.floor(this.boundingBox.b); + worldserver.a(EnumParticle.WATER_BUBBLE, this.locX, f3 + 1.0F, this.locZ, (int) (1.0F + this.width * 20.0F), this.width, 0.0D, this.width, 0.20000000298023224D); + worldserver.a(EnumParticle.WATER_WAKE, this.locX, f3 + 1.0F, this.locZ, (int) (1.0F + this.width * 20.0F), this.width, 0.0D, this.width, 0.20000000298023224D); + + this.av = MathHelper.nextInt(random, 10, 30); + } else { + this.ay = (float) (this.ay + random.nextGaussian() * 4.0D); + f3 = this.ay * 0.017453292F; + f5 = MathHelper.sin(f3); + f4 = MathHelper.cos(f3); + d8 = this.locX + (f5 * this.ax * 0.1F); + d12 = (float) MathHelper.floor(this.boundingBox.b) + 1.0F; + d11 = this.locZ + (f4 * this.ax * 0.1F); + block = worldserver.getType((int) d8, (int) d12 - 1, (int) d11).getBlock(); + if (block == Blocks.WATER || block == Blocks.FLOWING_WATER) { + if (random.nextFloat() < 0.15F) { + worldserver.a(EnumParticle.WATER_BUBBLE, d8, d12 - 0.10000000149011612D, d11, 1, + f5, 0.1D, f4, 0.0D); + } + + float f6 = f5 * 0.04F; + float f7 = f4 * 0.04F; + + worldserver.a(EnumParticle.WATER_WAKE, d8, d12, d11, 0, f7, 0.01D, -f6, 1.0D); + worldserver.a(EnumParticle.WATER_WAKE, d8, d12, d11, 0, -f7, 0.01D, f6, 1.0D); + } + } + } else if (this.aw > 0) { + this.aw -= k; + f3 = 0.15F; + if (this.aw < 20) { + f3 = (float) (f3 + (20 - this.aw) * 0.05D); + } else if (this.aw < 40) { + f3 = (float) (f3 + (40 - this.aw) * 0.02D); + } else if (this.aw < 60) { + f3 = (float) (f3 + (60 - this.aw) * 0.01D); + } + + if (random.nextFloat() < f3) { + f5 = MathHelper.a(random, 0.0F, 360.0F) * 0.017453292F; + f4 = MathHelper.a(random, 25.0F, 60.0F); + d8 = this.locX + (MathHelper.sin(f5) * f4 * 0.1F); + d12 = (float) MathHelper.floor(this.boundingBox.b) + 1.0F; + d11 = this.locZ + (MathHelper.cos(f5) * f4 * 0.1F); + block = worldserver.getType((int) d8, (int) d12 - 1, (int) d11).getBlock(); + if (block == Blocks.WATER || block == Blocks.FLOWING_WATER) { + worldserver.a(EnumParticle.WATER_SPLASH, d8, d12, d11, 2 + random.nextInt(2), + 0.10000000149011612D, 0.0D, 0.10000000149011612D, 0.0D, EnumParticle.EMPTY_ARRAY); + } + } + + if (this.aw <= 0) { + this.ay = MathHelper.a(random, 0.0F, 360.0F); + this.ax = MathHelper.nextInt(random, 20, 80); + } + } else { + this.aw = MathHelper.nextInt(random, this.world.paperSpigotConfig.fishingMinTicks, + this.world.paperSpigotConfig.fishingMaxTicks); // PaperSpigot - Configurable fishing + // tick range + this.aw -= EnchantmentManager.h(this.owner) * 20 * 5; + } + } + + if (this.av > 0) { + this.motY -= (double) (random.nextFloat() * random.nextFloat() + * random.nextFloat()) * 0.2D; + } + } + + d6 = d7 * 2.0D - 1.0D; + this.motY += 0.03999999910593033D * d6; + if (d7 > 0.0D) { + f2 = (float) ((double) f2 * 0.9D); + this.motY *= 0.8D; + } + + this.motX *= f2; + this.motY *= f2; + this.motZ *= f2; + this.setPosition(this.locX, this.locY, this.locZ); + if (this.ak) this.die(); // PandaSpigot - Prevent going through portals + } + } + } + + public void b(NBTTagCompound nbttagcompound) { + nbttagcompound.setShort("xTile", (short) this.g); + nbttagcompound.setShort("yTile", (short) this.h); + nbttagcompound.setShort("zTile", (short) this.i); + MinecraftKey minecraftkey = Block.REGISTRY.c(this.ar); + + nbttagcompound.setString("inTile", minecraftkey == null ? "" : minecraftkey.toString()); + nbttagcompound.setByte("shake", (byte) this.a); + nbttagcompound.setByte("inGround", (byte) (this.as ? 1 : 0)); + } + + public void a(NBTTagCompound nbttagcompound) { + this.g = nbttagcompound.getShort("xTile"); + this.h = nbttagcompound.getShort("yTile"); + this.i = nbttagcompound.getShort("zTile"); + if (nbttagcompound.hasKeyOfType("inTile", 8)) { + this.ar = Block.getByName(nbttagcompound.getString("inTile")); + } else { + this.ar = Block.getById(nbttagcompound.getByte("inTile") & 255); + } + + this.a = nbttagcompound.getByte("shake") & 255; + this.as = nbttagcompound.getByte("inGround") == 1; + } + + public int l() { + byte b0 = 0; + + if (this.hooked != null) { + // CraftBukkit start + PlayerFishEvent playerFishEvent = new PlayerFishEvent((Player) this.owner.getBukkitEntity(), + this.hooked.getBukkitEntity(), (Fish) this.getBukkitEntity(), PlayerFishEvent.State.CAUGHT_ENTITY); + this.world.getServer().getPluginManager().callEvent(playerFishEvent); + + if (playerFishEvent.isCancelled()) { + return 0; + } + // CraftBukkit end + + double d0 = this.owner.locX - this.locX; + double d1 = this.owner.locY - this.locY; + double d2 = this.owner.locZ - this.locZ; + double d3 = MathHelper.sqrt(d0 * d0 + d1 * d1 + d2 * d2); + + this.hooked.motX += d0 * 0.1; + this.hooked.motY += d1 * 0.1 + MathHelper.sqrt(d3) * 0.08D; + this.hooked.motZ += d2 * 0.1; + b0 = 3; + } else if (this.av > 0) { + EntityItem entityitem = new EntityItem(this.world, this.locX, this.locY, this.locZ, this.m()); + // CraftBukkit start + PlayerFishEvent playerFishEvent = new PlayerFishEvent((Player) this.owner.getBukkitEntity(), + entityitem.getBukkitEntity(), (Fish) this.getBukkitEntity(), PlayerFishEvent.State.CAUGHT_FISH); + playerFishEvent.setExpToDrop(random.nextInt(6) + 1); + this.world.getServer().getPluginManager().callEvent(playerFishEvent); + + if (playerFishEvent.isCancelled()) { + return 0; + } + // CraftBukkit end + double d5 = this.owner.locX - this.locX; + double d6 = this.owner.locY - this.locY; + double d7 = this.owner.locZ - this.locZ; + double d8 = MathHelper.sqrt(d5 * d5 + d6 * d6 + d7 * d7); + + entityitem.motX = d5 * 0.1; + entityitem.motY = d6 * 0.1 + MathHelper.sqrt(d8) * 0.08D; + entityitem.motZ = d7 * 0.1; + this.world.addEntity(entityitem); + // CraftBukkit start - random.nextInt(6) + 1 -> + // playerFishEvent.getExpToDrop() + if (playerFishEvent.getExpToDrop() > 0) { + this.owner.world.addEntity(new EntityExperienceOrb(this.owner.world, this.owner.locX, + this.owner.locY + 0.5D, this.owner.locZ + 0.5D, playerFishEvent.getExpToDrop())); + } // CraftBukkit end + b0 = 1; + } + + if (this.as) { + // CraftBukkit start + PlayerFishEvent playerFishEvent = new PlayerFishEvent((Player) this.owner.getBukkitEntity(), null, + (Fish) this.getBukkitEntity(), PlayerFishEvent.State.IN_GROUND); + this.world.getServer().getPluginManager().callEvent(playerFishEvent); + + if (playerFishEvent.isCancelled()) { + return 0; + } + // CraftBukkit end + b0 = 2; + } + + // CraftBukkit start + if (b0 == 0) { + PlayerFishEvent playerFishEvent = new PlayerFishEvent((Player) this.owner.getBukkitEntity(), null, + (Fish) this.getBukkitEntity(), PlayerFishEvent.State.FAILED_ATTEMPT); + this.world.getServer().getPluginManager().callEvent(playerFishEvent); + + if (playerFishEvent.isCancelled()) { + return 0; + } + } + // CraftBukkit end + + this.die(); + this.owner.hookedFish = null; + return b0; + + } + + private ItemStack m() { + float f = this.world.random.nextFloat(); + int i = EnchantmentManager.g(this.owner); + int j = EnchantmentManager.h(this.owner); + float f1 = 0.1F - (float) i * 0.025F - (float) j * 0.01F; + float f2 = 0.05F + (float) i * 0.01F - (float) j * 0.01F; + + f1 = MathHelper.a(f1, 0.0F, 1.0F); + f2 = MathHelper.a(f2, 0.0F, 1.0F); + if (f < f1) { + this.owner.b(StatisticList.D); + return (WeightedRandom.a(this.random, EntityFishingHook.d)).a(this.random); + } else { + f -= f1; + if (f < f2) { + this.owner.b(StatisticList.E); + return (WeightedRandom.a(this.random, EntityFishingHook.e)).a(this.random); + } else { + this.owner.b(StatisticList.C); + return (WeightedRandom.a(this.random, EntityFishingHook.f)).a(this.random); + } + } + } + + public void die() { + super.die(); + if (this.owner != null) { + this.owner.hookedFish = null; + } + } + +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityFlying.java b/azurite-server/src/main/java/net/minecraft/server/EntityFlying.java new file mode 100644 index 0000000..f579ae6 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityFlying.java @@ -0,0 +1,53 @@ +package net.minecraft.server; + +public abstract class EntityFlying extends EntityInsentient { + + public EntityFlying(World world) { + super(world); + } + + public void e(float f, float f1) { + } + + protected void a(double d0, boolean flag, Block block, BlockPosition blockposition) { + } + + public void g(float f, float f1) { + if (this.V()) { + this.a(f, f1, 0.02F); + this.move(this.motX, this.motY, this.motZ); + this.motX *= 0.800000011920929D; + this.motY *= 0.800000011920929D; + this.motZ *= 0.800000011920929D; + } else if (this.ab()) { + this.a(f, f1, 0.02F); + this.move(this.motX, this.motY, this.motZ); + this.motX *= 0.5D; + this.motY *= 0.5D; + this.motZ *= 0.5D; + } else { + float f2 = 0.91F; + + if (this.onGround) { + f2 = this.world.getType(MathHelper.floor(this.locX), MathHelper.floor(this.boundingBox.b) - 1, MathHelper.floor(this.locZ)).getBlock().frictionFactor * 0.91F; + } + + float f3 = 0.16277136F / (f2 * f2 * f2); + + this.a(f, f1, this.onGround ? 0.1F * f3 : 0.02F); + f2 = 0.91F; + if (this.onGround) { + f2 = this.world.getType(MathHelper.floor(this.locX), MathHelper.floor(this.boundingBox.b) - 1, MathHelper.floor(this.locZ)).getBlock().frictionFactor * 0.91F; + } + + this.move(this.motX, this.motY, this.motZ); + this.motX *= f2; + this.motY *= f2; + this.motZ *= f2; + } + } + + public boolean k_() { + return false; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityGhast.java b/azurite-server/src/main/java/net/minecraft/server/EntityGhast.java new file mode 100644 index 0000000..c6bf89c --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityGhast.java @@ -0,0 +1,296 @@ +package net.minecraft.server; + +import java.util.Random; + +public class EntityGhast extends EntityFlying implements IMonster { + + private int a = 1; + + public EntityGhast(World world) { + super(world); + this.setSize(4.0F, 4.0F); + this.fireProof = true; + this.b_ = 5; + this.moveController = new ControllerGhast(this); + this.goalSelector.a(5, new PathfinderGoalGhastIdleMove(this)); + this.goalSelector.a(7, new PathfinderGoalGhastMoveTowardsTarget(this)); + this.goalSelector.a(7, new PathfinderGoalGhastAttackTarget(this)); + this.targetSelector.a(1, new PathfinderGoalTargetNearestPlayer(this)); + } + + public void a(boolean flag) { + this.datawatcher.watch(16, (byte) (flag ? 1 : 0)); + } + + public int cf() { + return this.a; + } + + public void t_() { + super.t_(); + if (this.world.getDifficulty() == EnumDifficulty.PEACEFUL) { + this.die(); + } + + } + + public boolean damageEntity(DamageSource damagesource, float f) { + if (this.isInvulnerable(damagesource)) { + return false; + } else if ("fireball".equals(damagesource.p()) && damagesource.getEntity() instanceof EntityHuman) { + super.damageEntity(damagesource, 1000.0F); + ((EntityHuman) damagesource.getEntity()).b(AchievementList.z); + return true; + } else { + return super.damageEntity(damagesource, f); + } + } + + protected void h() { + super.h(); + this.datawatcher.a(16, (byte) 0); + } + + protected void initAttributes() { + super.initAttributes(); + this.getAttributeInstance(GenericAttributes.maxHealth).setValue(10.0D); + this.getAttributeInstance(GenericAttributes.FOLLOW_RANGE).setValue(100.0D); + } + + protected String z() { + return "mob.ghast.moan"; + } + + protected String bo() { + return "mob.ghast.scream"; + } + + protected String bp() { + return "mob.ghast.death"; + } + + protected Item getLoot() { + return Items.GUNPOWDER; + } + + protected void dropDeathLoot(boolean flag, int i) { + int j = random.nextInt(2) + random.nextInt(1 + i); + + int k; + + for (k = 0; k < j; ++k) { + this.a(Items.GHAST_TEAR, 1); + } + + j = random.nextInt(3) + random.nextInt(1 + i); + + for (k = 0; k < j; ++k) { + this.a(Items.GUNPOWDER, 1); + } + + } + + protected float bB() { + return 10.0F; + } + + public boolean bR() { + return random.nextInt(20) == 0 && super.bR() && this.world.getDifficulty() != EnumDifficulty.PEACEFUL; + } + + public int bV() { + return 1; + } + + public void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + nbttagcompound.setInt("ExplosionPower", this.a); + } + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + if (nbttagcompound.hasKeyOfType("ExplosionPower", 99)) { + this.a = nbttagcompound.getInt("ExplosionPower"); + } + + } + + public float getHeadHeight() { + return 2.6F; + } + + static class PathfinderGoalGhastAttackTarget extends PathfinderGoal { + + private final EntityGhast b; + public int a; + + public PathfinderGoalGhastAttackTarget(EntityGhast entityghast) { + this.b = entityghast; + } + + public boolean a() { + return this.b.getGoalTarget() != null; + } + + public void c() { + this.a = 0; + } + + public void d() { + this.b.a(false); + } + + public void e() { + EntityLiving entityliving = this.b.getGoalTarget(); + double d0 = 64.0D; + + if (entityliving.h(this.b) < d0 * d0 && this.b.hasLineOfSight(entityliving)) { + World world = this.b.world; + + ++this.a; + if (this.a == 10) { + world.a(null, 1007, new BlockPosition(this.b), 0); + } + + if (this.a == 20) { + double d1 = 4.0D; + Vec3D vec3d = this.b.d(1.0F); + double d2 = entityliving.locX - (this.b.locX + vec3d.a * d1); + double d3 = entityliving.getBoundingBox().b + (double) (entityliving.length / 2.0F) - (0.5D + this.b.locY + (double) (this.b.length / 2.0F)); + double d4 = entityliving.locZ - (this.b.locZ + vec3d.c * d1); + + world.a(null, 1008, new BlockPosition(this.b), 0); + EntityLargeFireball entitylargefireball = new EntityLargeFireball(world, this.b, d2, d3, d4); + + + // CraftBukkit - set bukkitYield when setting explosionpower + entitylargefireball.bukkitYield = entitylargefireball.yield = this.b.cf(); + entitylargefireball.locX = this.b.locX + vec3d.a * d1; + entitylargefireball.locY = this.b.locY + (double) (this.b.length / 2.0F) + 0.5D; + entitylargefireball.locZ = this.b.locZ + vec3d.c * d1; + world.addEntity(entitylargefireball); + this.a = -40; + } + } else if (this.a > 0) { + --this.a; + } + + this.b.a(this.a > 10); + } + } + + static class PathfinderGoalGhastMoveTowardsTarget extends PathfinderGoal { + + private final EntityGhast a; + + public PathfinderGoalGhastMoveTowardsTarget(EntityGhast entityghast) { + this.a = entityghast; + this.a(2); + } + + public boolean a() { + return true; + } + + public void e() { + if (this.a.getGoalTarget() == null) { + this.a.aI = this.a.yaw = -((float) MathHelper.b(this.a.motX, this.a.motZ)) * 180.0F / 3.1415927F; + } else { + EntityLiving entityliving = this.a.getGoalTarget(); + double d0 = 64.0D; + + if (entityliving.h(this.a) < d0 * d0) { + this.a.aI = this.a.yaw = -((float) MathHelper.b(entityliving.locX - this.a.locX, entityliving.locZ - this.a.locZ)) * 180.0F / 3.1415927F; + } + } + + } + } + + static class PathfinderGoalGhastIdleMove extends PathfinderGoal { + + private final EntityGhast a; + + public PathfinderGoalGhastIdleMove(EntityGhast entityghast) { + this.a = entityghast; + this.a(1); + } + + public boolean a() { + ControllerMove controllermove = this.a.getControllerMove(); + + if (!controllermove.a()) { + return true; + } else { + double d0 = controllermove.d() - this.a.locX; + double d1 = controllermove.e() - this.a.locY; + double d2 = controllermove.f() - this.a.locZ; + double d3 = d0 * d0 + d1 * d1 + d2 * d2; + + return d3 < 1.0D || d3 > 3600.0D; + } + } + + public boolean b() { + return false; + } + + public void c() { + Random random = this.a.bc(); + double d0 = this.a.locX + (double) ((random.nextFloat() * 2.0F - 1.0F) * 16.0F); + double d1 = this.a.locY + (double) ((random.nextFloat() * 2.0F - 1.0F) * 16.0F); + double d2 = this.a.locZ + (double) ((random.nextFloat() * 2.0F - 1.0F) * 16.0F); + + this.a.getControllerMove().a(d0, d1, d2, 1.0D); + } + } + + static class ControllerGhast extends ControllerMove { + + private final EntityGhast g; + private int h; + + public ControllerGhast(EntityGhast entityghast) { + super(entityghast); + this.g = entityghast; + } + + public void c() { + if (this.f) { + double d0 = this.b - this.g.locX; + double d1 = this.c - this.g.locY; + double d2 = this.d - this.g.locZ; + double d3 = d0 * d0 + d1 * d1 + d2 * d2; + + if (this.h-- <= 0) { + this.h += this.g.bc().nextInt(5) + 2; + d3 = MathHelper.sqrt(d3); + if (this.b(this.b, this.c, this.d, d3)) { + this.g.motX += d0 / d3 * 0.1D; + this.g.motY += d1 / d3 * 0.1D; + this.g.motZ += d2 / d3 * 0.1D; + } else { + this.f = false; + } + } + + } + } + + private boolean b(double d0, double d1, double d2, double d3) { + double d4 = (d0 - this.g.locX) / d3; + double d5 = (d1 - this.g.locY) / d3; + double d6 = (d2 - this.g.locZ) / d3; + AxisAlignedBB axisalignedbb = this.g.getBoundingBox(); + + for (int i = 1; (double) i < d3; ++i) { + axisalignedbb = axisalignedbb.c(d4, d5, d6); + if (!this.g.world.getCubes(this.g, axisalignedbb).isEmpty()) { + return false; + } + } + + return true; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityGiantZombie.java b/azurite-server/src/main/java/net/minecraft/server/EntityGiantZombie.java new file mode 100644 index 0000000..558b3a6 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityGiantZombie.java @@ -0,0 +1,24 @@ +package net.minecraft.server; + +public class EntityGiantZombie extends EntityMonster { + + public EntityGiantZombie(World world) { + super(world); + this.setSize(this.width * 6.0F, this.length * 6.0F); + } + + public float getHeadHeight() { + return 10.440001F; + } + + protected void initAttributes() { + super.initAttributes(); + this.getAttributeInstance(GenericAttributes.maxHealth).setValue(100.0D); + this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.5D); + this.getAttributeInstance(GenericAttributes.ATTACK_DAMAGE).setValue(50.0D); + } + + public float a(BlockPosition blockposition) { + return this.world.o(blockposition) - 0.5F; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityGolem.java b/azurite-server/src/main/java/net/minecraft/server/EntityGolem.java new file mode 100644 index 0000000..34f376c --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityGolem.java @@ -0,0 +1,27 @@ +package net.minecraft.server; + +public abstract class EntityGolem extends EntityCreature implements IAnimal { + public EntityGolem(World var1) { + super(var1); + } + + protected String z() { + return "none"; + } + + protected String bo() { + return "none"; + } + + protected String bp() { + return "none"; + } + + public int w() { + return 120; + } + + public boolean isTypeNotPersistent() { + return false; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityGuardian.java b/azurite-server/src/main/java/net/minecraft/server/EntityGuardian.java new file mode 100644 index 0000000..aeb391a --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityGuardian.java @@ -0,0 +1,426 @@ +package net.minecraft.server; + +import com.google.common.base.Predicate; + +import java.util.List; + +public class EntityGuardian extends EntityMonster { + + private int bp; + public PathfinderGoalRandomStroll goalRandomStroll; + + public EntityGuardian(World world) { + super(world); + this.b_ = 10; + this.setSize(0.85F, 0.85F); + this.goalSelector.a(4, new PathfinderGoalGuardianAttack(this)); + PathfinderGoalMoveTowardsRestriction pathfindergoalmovetowardsrestriction; + + this.goalSelector.a(5, pathfindergoalmovetowardsrestriction = new PathfinderGoalMoveTowardsRestriction(this, 1.0D)); + this.goalSelector.a(7, this.goalRandomStroll = new PathfinderGoalRandomStroll(this, 1.0D, 80)); + this.goalSelector.a(8, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 8.0F)); + this.goalSelector.a(8, new PathfinderGoalLookAtPlayer(this, EntityGuardian.class, 12.0F, 0.01F)); + this.goalSelector.a(9, new PathfinderGoalRandomLookaround(this)); + this.goalRandomStroll.a(3); + pathfindergoalmovetowardsrestriction.a(3); + this.targetSelector.a(1, new PathfinderGoalNearestAttackableTarget(this, EntityLiving.class, 10, true, false, new EntitySelectorGuardianTargetHumanSquid(this))); + this.moveController = new ControllerMoveGuardian(this); + + } + + public void initAttributes() { + super.initAttributes(); + this.getAttributeInstance(GenericAttributes.ATTACK_DAMAGE).setValue(6.0D); + this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.5D); + this.getAttributeInstance(GenericAttributes.FOLLOW_RANGE).setValue(16.0D); + this.getAttributeInstance(GenericAttributes.maxHealth).setValue(30.0D); + } + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + this.setElder(nbttagcompound.getBoolean("Elder")); + } + + public void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + nbttagcompound.setBoolean("Elder", this.isElder()); + } + + protected NavigationAbstract b(World world) { + return new NavigationGuardian(this, world); + } + + protected void h() { + super.h(); + this.datawatcher.a(16, 0); + this.datawatcher.a(17, 0); + } + + private boolean a(int i) { + return (this.datawatcher.getInt(16) & i) != 0; + } + + private void a(int i, boolean flag) { + int j = this.datawatcher.getInt(16); + + if (flag) { + this.datawatcher.watch(16, j | i); + } else { + this.datawatcher.watch(16, j & ~i); + } + + } + + public boolean n() { + return this.a(2); + } + + private void l(boolean flag) { + this.a(2, flag); + } + + public int cm() { + return this.isElder() ? 60 : 80; + } + + public boolean isElder() { + return this.a(4); + } + + public void setElder(boolean flag) { + this.a(4, flag); + if (flag) { + this.setSize(1.9975F, 1.9975F); + this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.30000001192092896D); + this.getAttributeInstance(GenericAttributes.ATTACK_DAMAGE).setValue(8.0D); + this.getAttributeInstance(GenericAttributes.maxHealth).setValue(80.0D); + this.bX(); + this.goalRandomStroll.setTimeBetweenMovement(400); + } + + } + + private void b(int i) { + this.datawatcher.watch(17, i); + } + + public boolean cp() { + return this.datawatcher.getInt(17) != 0; + } + + public EntityLiving cq() { + if (!this.cp()) { + return null; + } else { + return this.getGoalTarget(); + } + } + + public void i(int i) { + super.i(i); + if (i == 16) { + if (this.isElder() && this.width < 1.0F) { + this.setSize(1.9975F, 1.9975F); + } + } else if (i == 17) { + this.bp = 0; + } + + } + + public int w() { + return 160; + } + + protected String z() { + return !this.V() ? "mob.guardian.land.idle" : (this.isElder() ? "mob.guardian.elder.idle" : "mob.guardian.idle"); + } + + protected String bo() { + return !this.V() ? "mob.guardian.land.hit" : (this.isElder() ? "mob.guardian.elder.hit" : "mob.guardian.hit"); + } + + protected String bp() { + return !this.V() ? "mob.guardian.land.death" : (this.isElder() ? "mob.guardian.elder.death" : "mob.guardian.death"); + } + + protected boolean s_() { + return false; + } + + public float getHeadHeight() { + return this.length * 0.5F; + } + + public float a(BlockPosition blockposition) { + return this.world.getType(blockposition).getBlock().getMaterial() == Material.WATER ? 10.0F + this.world.o(blockposition) - 0.5F : super.a(blockposition); + } + + public void m() { + + if (this.inWater) { + this.setAirTicks(300); + } else if (this.onGround) { + this.motY += 0.5D; + this.motX += ((random.nextFloat() * 2.0F - 1.0F) * 0.4F); + this.motZ += ((random.nextFloat() * 2.0F - 1.0F) * 0.4F); + this.yaw = random.nextFloat() * 360.0F; + this.onGround = false; + this.ai = true; + } + + if (this.cp()) { + this.yaw = this.aK; + } + + super.m(); + } + + public float q(float f) { + return ((float) this.bp + f) / (float) this.cm(); + } + + protected void E() { + super.E(); + if (this.isElder()) { + if ((this.ticksLived + this.getId()) % 1200 == 0) { + MobEffectList mobeffectlist = MobEffectList.SLOWER_DIG; + List list = this.world.b(EntityPlayer.class, new Predicate() { + public boolean a(EntityPlayer entityplayer) { + return EntityGuardian.this.h(entityplayer) < 2500.0D && entityplayer.playerInteractManager.c(); + } + + public boolean apply(Object object) { + return this.a((EntityPlayer) object); + } + }); + + for (EntityPlayer entityplayer : list) { + if (!entityplayer.hasEffect(mobeffectlist) || entityplayer.getEffect(mobeffectlist).getAmplifier() < 2 || entityplayer.getEffect(mobeffectlist).getDuration() < 1200) { + entityplayer.playerConnection.sendPacket(new PacketPlayOutGameStateChange(10, 0.0F)); + entityplayer.addEffect(new MobEffect(mobeffectlist.id, 6000, 2)); + } + } + } + + if (!this.ck()) { + this.a(new BlockPosition(this), 16); + } + } + + } + + protected void dropDeathLoot(boolean flag, int i) { + int j = random.nextInt(3) + random.nextInt(i + 1); + + if (j > 0) { + this.a(new ItemStack(Items.PRISMARINE_SHARD, j, 0), 1.0F); + } + + if (random.nextInt(3 + i) > 1) { + this.a(new ItemStack(Items.FISH, 1, ItemFish.EnumFish.COD.a()), 1.0F); + } else if (random.nextInt(3 + i) > 1) { + this.a(new ItemStack(Items.PRISMARINE_CRYSTALS, 1, 0), 1.0F); + } + + if (flag && this.isElder()) { + this.a(new ItemStack(Blocks.SPONGE, 1, 1), 1.0F); + } + + } + + protected void getRareDrop() { + ItemStack itemstack = WeightedRandom.a(random, EntityFishingHook.j()).a(random); + + this.a(itemstack, 1.0F); + } + + protected boolean n_() { + return true; + } + + public boolean canSpawn() { + return this.world.a(this.getBoundingBox(), this) && this.world.getCubes(this, this.getBoundingBox()).isEmpty(); + } + + public boolean bR() { + return (random.nextInt(20) == 0 || !this.world.j(new BlockPosition(this))) && super.bR(); + } + + public boolean damageEntity(DamageSource damagesource, float f) { + if (!this.n() && !damagesource.isMagic() && damagesource.i() instanceof EntityLiving) { + EntityLiving entityliving = (EntityLiving) damagesource.i(); + + if (!damagesource.isExplosion()) { + entityliving.damageEntity(DamageSource.a(this), 2.0F); + entityliving.makeSound("damage.thorns", 0.5F, 1.0F); + } + } + + this.goalRandomStroll.f(); + return super.damageEntity(damagesource, f); + } + + public int bQ() { + return 180; + } + + public void g(float f, float f1) { + if (this.bM()) { + if (this.V()) { + this.a(f, f1, 0.1F); + this.move(this.motX, this.motY, this.motZ); + this.motX *= 0.8999999761581421D; + this.motY *= 0.8999999761581421D; + this.motZ *= 0.8999999761581421D; + if (!this.n() && this.getGoalTarget() == null) { + this.motY -= 0.005D; + } + } else { + super.g(f, f1); + } + } else { + super.g(f, f1); + } + + } + + static class ControllerMoveGuardian extends ControllerMove { + + private final EntityGuardian g; + + public ControllerMoveGuardian(EntityGuardian entityguardian) { + super(entityguardian); + this.g = entityguardian; + } + + public void c() { + if (this.f && !this.g.getNavigation().m()) { + double d0 = this.b - this.g.locX; + double d1 = this.c - this.g.locY; + double d2 = this.d - this.g.locZ; + double d3 = d0 * d0 + d1 * d1 + d2 * d2; + + d3 = MathHelper.sqrt(d3); + d1 /= d3; + float f = (float) (MathHelper.b(d2, d0) * 180.0D / 3.1415927410125732D) - 90.0F; + + this.g.yaw = this.a(this.g.yaw, f, 30.0F); + this.g.aI = this.g.yaw; + float f1 = (float) (this.e * this.g.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).getValue()); + + this.g.k(this.g.bI() + (f1 - this.g.bI()) * 0.125F); + double d4 = Math.sin((double) (this.g.ticksLived + this.g.getId()) * 0.5D) * 0.05D; + double d5 = Math.cos((this.g.yaw * 3.1415927F / 180.0F)); + double d6 = Math.sin(this.g.yaw * 3.1415927F / 180.0F); + + this.g.motX += d4 * d5; + this.g.motZ += d4 * d6; + d4 = Math.sin((double) (this.g.ticksLived + this.g.getId()) * 0.75D) * 0.05D; + this.g.motY += d4 * (d6 + d5) * 0.25D; + this.g.motY += (double) this.g.bI() * d1 * 0.1D; + ControllerLook controllerlook = this.g.getControllerLook(); + double d7 = this.g.locX + d0 / d3 * 2.0D; + double d8 = (double) this.g.getHeadHeight() + this.g.locY + d1 / d3; + double d9 = this.g.locZ + d2 / d3 * 2.0D; + double d10 = controllerlook.e(); + double d11 = controllerlook.f(); + double d12 = controllerlook.g(); + + if (!controllerlook.b()) { + d10 = d7; + d11 = d8; + d12 = d9; + } + + this.g.getControllerLook().a(d10 + (d7 - d10) * 0.125D, d11 + (d8 - d11) * 0.125D, d12 + (d9 - d12) * 0.125D, 10.0F, 40.0F); + this.g.l(true); + } else { + this.g.k(0.0F); + this.g.l(false); + } + } + } + + static class PathfinderGoalGuardianAttack extends PathfinderGoal { + + private final EntityGuardian a; + private int b; + + public PathfinderGoalGuardianAttack(EntityGuardian entityguardian) { + this.a = entityguardian; + this.a(3); + } + + public boolean a() { + EntityLiving entityliving = this.a.getGoalTarget(); + + return entityliving != null && entityliving.isAlive(); + } + + public boolean b() { + return super.b() && (this.a.isElder() || this.a.h(this.a.getGoalTarget()) > 9.0D); + } + + public void c() { + this.b = -10; + this.a.getNavigation().n(); + this.a.getControllerLook().a(this.a.getGoalTarget(), 90.0F, 90.0F); + this.a.ai = true; + } + + public void d() { + this.a.b(0); + this.a.setGoalTarget(null); + this.a.goalRandomStroll.f(); + } + + public void e() { + EntityLiving entityliving = this.a.getGoalTarget(); + + this.a.getNavigation().n(); + this.a.getControllerLook().a(entityliving, 90.0F, 90.0F); + if (!this.a.hasLineOfSight(entityliving)) { + this.a.setGoalTarget(null); + } else { + ++this.b; + if (this.b == 0) { + this.a.b(this.a.getGoalTarget().getId()); + this.a.world.broadcastEntityEffect(this.a, (byte) 21); + } else if (this.b >= this.a.cm()) { + float f = 1.0F; + + if (this.a.world.getDifficulty() == EnumDifficulty.HARD) { + f += 2.0F; + } + + if (this.a.isElder()) { + f += 2.0F; + } + + entityliving.damageEntity(DamageSource.b(this.a, this.a), f); + entityliving.damageEntity(DamageSource.mobAttack(this.a), (float) this.a.getAttributeInstance(GenericAttributes.ATTACK_DAMAGE).getValue()); + this.a.setGoalTarget(null); + } + super.e(); + } + } + } + + static class EntitySelectorGuardianTargetHumanSquid implements Predicate { + + private final EntityGuardian a; + + public EntitySelectorGuardianTargetHumanSquid(EntityGuardian entityguardian) { + this.a = entityguardian; + } + + public boolean a(EntityLiving entityliving) { + return (entityliving instanceof EntityHuman || entityliving instanceof EntitySquid) && entityliving.h(this.a) > 9.0D; + } + + public boolean apply(EntityLiving object) { + return this.a(object); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityHanging.java b/azurite-server/src/main/java/net/minecraft/server/EntityHanging.java new file mode 100644 index 0000000..056a049 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityHanging.java @@ -0,0 +1,289 @@ +package net.minecraft.server; + +import org.apache.commons.lang3.Validate; +import org.bukkit.entity.Hanging; +import org.bukkit.entity.Painting; +import org.bukkit.event.hanging.HangingBreakEvent; +import org.bukkit.event.painting.PaintingBreakEvent; + +import java.util.Iterator; +import java.util.List; +// CraftBukkit end + +public abstract class EntityHanging extends Entity { + + private int c; + public BlockPosition blockPosition; + public EnumDirection direction; + + public EntityHanging(World world) { + super(world); + this.setSize(0.5F, 0.5F); + } + + public EntityHanging(World world, BlockPosition blockposition) { + this(world); + this.blockPosition = blockposition; + } + + protected void h() {} + + public void setDirection(EnumDirection enumdirection) { + Validate.notNull(enumdirection); + Validate.isTrue(enumdirection.k().c()); + this.direction = enumdirection; + this.lastYaw = this.yaw = (float) (this.direction.b() * 90); + this.updateBoundingBox(); + } + + /* CraftBukkit start - bounding box calculation made static (for spawn usage) + + l is from function l() + m is from function m() + + Placing here as it's more likely to be noticed as something which needs to be updated + then something in a CraftBukkit file. + */ + public static AxisAlignedBB calculateBoundingBox(BlockPosition blockPosition, EnumDirection direction, int width, int height) { + double d0 = blockPosition.getX() + 0.5D; + double d1 = blockPosition.getY() + 0.5D; + double d2 = blockPosition.getZ() + 0.5D; + + double d4 = width % 32 == 0 ? 0.5D : 0.0D; + double d5 = height % 32 == 0 ? 0.5D : 0.0D; + + d0 -= (double) direction.getAdjacentX() * 0.111146875D; + d2 -= (double) direction.getAdjacentZ() * 0.111146875D; + d1 += d5; + EnumDirection enumdirection = direction.f(); + + d0 += d4 * enumdirection.getAdjacentX(); + d2 += d4 * enumdirection.getAdjacentZ(); + double d6 = width; + double d7 = height; + double d8 = width; + + if (direction.k() == EnumDirection.EnumAxis.Z) { + d8 = 1.0D; + } else { + d6 = 1.0D; + } + + d6 /= 32.0D; + d7 /= 32.0D; + d8 /= 32.0D; + return new AxisAlignedBB(d0 - d6, d1 - d7, d2 - d8, d0 + d6, d1 + d7, d2 + d8); + } + + private void updateBoundingBox() { + if (this.direction != null) { + // CraftBukkit start code moved in to calculateBoundingBox + AxisAlignedBB bb = calculateBoundingBox(this.blockPosition, this.direction, this.l(), this.m()); + this.locX = (bb.a + bb.d) / 2.0D; + this.locY = (bb.b + bb.e) / 2.0D; + this.locZ = (bb.c + bb.f) / 2.0D; + this.a(bb); + // CraftBukkit end + } + } + + public void t_() { + this.lastX = this.locX; + this.lastY = this.locY; + this.lastZ = this.locZ; + if (this.c++ == this.world.spigotConfig.hangingTickFrequency) { + this.c = 0; + if (!this.dead && !this.survives()) { + // CraftBukkit start - fire break events + Material material = this.world.getType(MathHelper.floor(locX), MathHelper.floor(locY),MathHelper.floor(locZ)).getBlock().getMaterial(); + HangingBreakEvent.RemoveCause cause; + + if (!material.equals(Material.AIR)) { + // TODO: This feels insufficient to catch 100% of suffocation cases + cause = HangingBreakEvent.RemoveCause.OBSTRUCTION; + } else { + cause = HangingBreakEvent.RemoveCause.PHYSICS; + } + + HangingBreakEvent event = new HangingBreakEvent((Hanging) this.getBukkitEntity(), cause); + this.world.getServer().getPluginManager().callEvent(event); + + PaintingBreakEvent paintingEvent = null; + if (this instanceof EntityPainting) { + // Fire old painting event until it can be removed + paintingEvent = new PaintingBreakEvent((Painting) this.getBukkitEntity(), PaintingBreakEvent.RemoveCause.valueOf(cause.name())); + paintingEvent.setCancelled(event.isCancelled()); + this.world.getServer().getPluginManager().callEvent(paintingEvent); + } + + if (dead || event.isCancelled() || (paintingEvent != null && paintingEvent.isCancelled())) { + return; + } + // CraftBukkit end + this.die(); + this.b((Entity) null); + } + } + + } + + public boolean survives() { + if (this.world.getCubes(this, this.getBoundingBox()).isEmpty()) { + int i = Math.max(1, this.l() / 16); + int j = Math.max(1, this.m() / 16); + BlockPosition blockposition = this.blockPosition.shift(this.direction.opposite()); + EnumDirection enumdirection = this.direction.f(); + + for (int k = 0; k < i; ++k) { + for (int l = 0; l < j; ++l) { + BlockPosition blockposition1 = blockposition.shift(enumdirection, k).up(l); + Block block = this.world.getType(blockposition1).getBlock(); + + if (!block.getMaterial().isBuildable() && !BlockDiodeAbstract.d(block)) { + return false; + } + } + } + + List list = this.world.getEntities(this, this.getBoundingBox()); + Iterator iterator = list.iterator(); + + Entity entity; + + do { + if (!iterator.hasNext()) { + return true; + } + + entity = iterator.next(); + } while (!(entity instanceof EntityHanging)); + + } + return false; + } + + public boolean ad() { + return true; + } + + public boolean l(Entity entity) { + return entity instanceof EntityHuman && this.damageEntity(DamageSource.playerAttack((EntityHuman) entity), 0.0F); + } + + public EnumDirection getDirection() { + return this.direction; + } + + public boolean damageEntity(DamageSource damagesource, float f) { + if (this.isInvulnerable(damagesource)) { + return false; + } else { + if (!this.dead) { + // CraftBukkit start - fire break events + HangingBreakEvent event = new HangingBreakEvent((Hanging) this.getBukkitEntity(), HangingBreakEvent.RemoveCause.DEFAULT); + PaintingBreakEvent paintingEvent = null; + if (damagesource.getEntity() != null) { + event = new org.bukkit.event.hanging.HangingBreakByEntityEvent((Hanging) this.getBukkitEntity(), damagesource.getEntity() == null ? null : damagesource.getEntity().getBukkitEntity()); + + if (this instanceof EntityPainting) { + // Fire old painting event until it can be removed + paintingEvent = new org.bukkit.event.painting.PaintingBreakByEntityEvent((Painting) this.getBukkitEntity(), damagesource.getEntity() == null ? null : damagesource.getEntity().getBukkitEntity()); + } + } else if (damagesource.isExplosion()) { + event = new HangingBreakEvent((Hanging) this.getBukkitEntity(), HangingBreakEvent.RemoveCause.EXPLOSION); + } + + this.world.getServer().getPluginManager().callEvent(event); + + if (paintingEvent != null) { + paintingEvent.setCancelled(event.isCancelled()); + this.world.getServer().getPluginManager().callEvent(paintingEvent); + } + + if (this.dead || event.isCancelled() || (paintingEvent != null && paintingEvent.isCancelled())) { + return true; + } + // CraftBukkit end + + this.die(); + this.ac(); + this.b(damagesource.getEntity()); + } + + return true; + } + } + + public void move(double d0, double d1, double d2) { + if (!this.dead && d0 * d0 + d1 * d1 + d2 * d2 > 0.0D) { + + // CraftBukkit start - fire break events + // TODO - Does this need its own cause? Seems to only be triggered by pistons + HangingBreakEvent event = new HangingBreakEvent((Hanging) this.getBukkitEntity(), HangingBreakEvent.RemoveCause.PHYSICS); + this.world.getServer().getPluginManager().callEvent(event); + + if (event.isCancelled()) { + return; + } + // CraftBukkit end + + this.die(); + this.b((Entity)null); + } + + } + + public void g(double d0, double d1, double d2) { + } + + public void b(NBTTagCompound nbttagcompound) { + nbttagcompound.setByte("Facing", (byte) this.direction.b()); + nbttagcompound.setInt("TileX", this.getBlockPosition().getX()); + nbttagcompound.setInt("TileY", this.getBlockPosition().getY()); + nbttagcompound.setInt("TileZ", this.getBlockPosition().getZ()); + } + + public void a(NBTTagCompound nbttagcompound) { + this.blockPosition = new BlockPosition(nbttagcompound.getInt("TileX"), nbttagcompound.getInt("TileY"), nbttagcompound.getInt("TileZ")); + EnumDirection enumdirection; + + if (nbttagcompound.hasKeyOfType("Direction", 99)) { + enumdirection = EnumDirection.fromType2(nbttagcompound.getByte("Direction")); + this.blockPosition = this.blockPosition.shift(enumdirection); + } else if (nbttagcompound.hasKeyOfType("Facing", 99)) { + enumdirection = EnumDirection.fromType2(nbttagcompound.getByte("Facing")); + } else { + enumdirection = EnumDirection.fromType2(nbttagcompound.getByte("Dir")); + } + + this.setDirection(enumdirection); + } + + public abstract int l(); + + public abstract int m(); + + public abstract void b(Entity entity); + + protected boolean af() { + return false; + } + + public void setPosition(double d0, double d1, double d2) { + this.locX = d0; + this.locY = d1; + this.locZ = d2; + BlockPosition blockposition = this.blockPosition; + + this.blockPosition = new BlockPosition(d0, d1, d2); + if (!this.blockPosition.equals(blockposition)) { + this.updateBoundingBox(); + this.ai = true; + } + + } + + public BlockPosition getBlockPosition() { + return this.blockPosition; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityHorse.java b/azurite-server/src/main/java/net/minecraft/server/EntityHorse.java new file mode 100644 index 0000000..3ccef1b --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityHorse.java @@ -0,0 +1,1274 @@ +package net.minecraft.server; + +import com.eatthepath.uuid.FastUUID; +import com.google.common.base.Predicate; +import dev.azurite.spigot.configs.AzuriteConfig; +import org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason; + +public class EntityHorse extends EntityAnimal implements IInventoryListener { + + public static final IAttribute attributeJumpStrength = (new AttributeRanged(null, "horse.jumpStrength", 0.7D, 0.0D, 2.0D)).a("Jump Strength").a(true); + private static final Predicate bs = entity -> entity instanceof EntityHorse && ((EntityHorse) entity).cA(); + private static final int[] bw = {0, 5, 7, 11}; + public int bm; + public int bo; + public InventoryHorseChest inventoryChest; + public int maxDomestication = 100; // CraftBukkit - store max domestication value + protected boolean bp; + protected int bq; + protected float br; + private int bB; + private int bC; + private int bD; + private boolean bF; + private boolean bG; + private float bH; + private float bJ; + private float bK; + private float bL; + private int bN; + + public EntityHorse(World world) { + super(world); + this.setSize(1.4F, 1.6F); + this.fireProof = false; + this.setHasChest(false); + ((Navigation) this.getNavigation()).a(true); + this.goalSelector.a(0, new PathfinderGoalFloat(this)); + this.goalSelector.a(1, new PathfinderGoalPanic(this, 1.2D)); + this.goalSelector.a(1, new PathfinderGoalTame(this, 1.2D)); + this.goalSelector.a(2, new PathfinderGoalBreed(this, 1.0D)); + this.goalSelector.a(4, new PathfinderGoalFollowParent(this, 1.0D)); + this.goalSelector.a(6, new PathfinderGoalRandomStroll(this, 0.7D)); + this.goalSelector.a(7, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 6.0F)); + this.goalSelector.a(8, new PathfinderGoalRandomLookaround(this)); + this.loadChest(); + } + + public static boolean a(Item item) { + return item == Items.IRON_HORSE_ARMOR || item == Items.GOLDEN_HORSE_ARMOR || item == Items.DIAMOND_HORSE_ARMOR; + } + + protected void h() { + super.h(); + this.datawatcher.a(16, 0); + this.datawatcher.a(19, (byte) 0); + this.datawatcher.a(20, 0); + this.datawatcher.a(21, ""); + this.datawatcher.a(22, 0); + } + + public int getType() { + return this.datawatcher.getByte(19); + } + + public void setType(int i) { + this.datawatcher.watch(19, (byte) i); + + } + + public int getVariant() { + return this.datawatcher.getInt(20); + } + + public void setVariant(int i) { + this.datawatcher.watch(20, i); + + } + + public String getName() { + if (this.hasCustomName()) { + return this.getCustomName(); + } else { + int i = this.getType(); + + switch (i) { + case 0: + default: + return LocaleI18n.get("entity.horse.name"); + + case 1: + return LocaleI18n.get("entity.donkey.name"); + + case 2: + return LocaleI18n.get("entity.mule.name"); + + case 3: + return LocaleI18n.get("entity.zombiehorse.name"); + + case 4: + return LocaleI18n.get("entity.skeletonhorse.name"); + } + } + } + + private boolean w(int i) { + return (this.datawatcher.getInt(16) & i) != 0; + } + + private void c(int i, boolean flag) { + int j = this.datawatcher.getInt(16); + + if (flag) { + this.datawatcher.watch(16, j | i); + } else { + this.datawatcher.watch(16, j & ~i); + } + + } + + public boolean cn() { + return !this.isBaby(); + } + + public boolean isTame() { + return this.w(2); + } + + public void setTame(boolean flag) { + this.c(2, flag); + } + + public boolean cp() { + return this.cn(); + } + + public String getOwnerUUID() { + return this.datawatcher.getString(21); + } + + public void setOwnerUUID(String s) { + this.datawatcher.watch(21, s); + } + + public float cu() { + return 0.5F; + } + + public void a(boolean flag) { + if (flag) { + this.a(this.cu()); + } else { + this.a(1.0F); + } + + } + + public boolean cv() { + return this.bp; + } + + public void m(boolean flag) { + this.bp = flag; + } + + public boolean cb() { + // PaperSpigot start - Configurable undead horse leashing + if (this.world.paperSpigotConfig.allowUndeadHorseLeashing) { + return super.cb(); + } + // PaperSpigot end + return !this.cR() && super.cb(); + } + + protected void o(float f) { + if (f > 6.0F && this.cy()) { + this.r(false); + } + + } + + public boolean hasChest() { + return this.w(8); + } + + public int cx() { + return this.datawatcher.getInt(22); + } + + private int f(ItemStack itemstack) { + if (itemstack == null) { + return 0; + } else { + Item item = itemstack.getItem(); + + return item == Items.IRON_HORSE_ARMOR ? 1 : (item == Items.GOLDEN_HORSE_ARMOR ? 2 : (item == Items.DIAMOND_HORSE_ARMOR ? 3 : 0)); + } + } + + public boolean cy() { + return this.w(32); + } + + public boolean cz() { + return this.w(64); + } + + public boolean cA() { + return this.w(16); + } + + public boolean cB() { + return this.bF; + } + + public void e(ItemStack itemstack) { + this.datawatcher.watch(22, this.f(itemstack)); + + } + + public void n(boolean flag) { + this.c(16, flag); + } + + public void setHasChest(boolean flag) { + this.c(8, flag); + } + + public void p(boolean flag) { + this.bF = flag; + } + + public void q(boolean flag) { + this.c(4, flag); + } + + public int getTemper() { + return this.bq; + } + + public void setTemper(int i) { + this.bq = i; + } + + public int u(int i) { + int j = MathHelper.clamp(this.getTemper() + i, 0, this.getMaxDomestication()); + + this.setTemper(j); + return j; + } + + public boolean damageEntity(DamageSource damagesource, float f) { + Entity entity = damagesource.getEntity(); + + return (this.passenger == null || !this.passenger.equals(entity)) && super.damageEntity(damagesource, f); + } + + public int br() { + return EntityHorse.bw[this.cx()]; + } + + public boolean ae() { + return this.passenger == null; + } + + public boolean cD() { + this.world.getBiome(MathHelper.floor(this.locX), 0, MathHelper.floor(this.locZ)); + return true; + } + + public void cE() { + if (this.hasChest()) { + this.a(Item.getItemOf(Blocks.CHEST), 1); + this.setHasChest(false); + } + } + + private void cY() { + this.df(); + if (!this.R()) { + this.world.makeSound(this, "eating", 1.0F, 1.0F + (random.nextFloat() - random.nextFloat()) * 0.2F); + } + + } + + public void e(float f, float f1) { + if (f > 1.0F) { + this.makeSound("mob.horse.land", 0.4F, 1.0F); + } + + int i = MathHelper.f((f * 0.5F - 3.0F) * f1); + + if (i > 0) { + this.damageEntity(DamageSource.FALL, (float) i); + if (this.passenger != null) { + this.passenger.damageEntity(DamageSource.FALL, (float) i); + } + + if (AzuriteConfig.footstepSounds.getValue()) { + Block block = this.world.getType(MathHelper.floor(this.locX), MathHelper.floor(this.locY - 0.2D - (double) this.lastYaw), MathHelper.floor(this.locZ)).getBlock(); + if (block.getMaterial() != Material.AIR && !this.R()) { + Block.StepSound block_stepsound = block.stepSound; + this.world.makeSound(this, block_stepsound.getStepSound(), block_stepsound.getVolume1() * 0.5F, block_stepsound.getVolume2() * 0.75F); + } + } + } + } + + private int cZ() { + return this.hasChest() /* && (i == 1 || i == 2) */ ? 17 : 2; // CraftBukkit - Remove type check + } + + public void loadChest() { + InventoryHorseChest inventoryhorsechest = this.inventoryChest; + + this.inventoryChest = new InventoryHorseChest("HorseChest", this.cZ(), this); // CraftBukkit - add this horse + this.inventoryChest.a(this.getName()); + if (inventoryhorsechest != null) { + inventoryhorsechest.b(this); + int i = Math.min(inventoryhorsechest.getSize(), this.inventoryChest.getSize()); + + for (int j = 0; j < i; ++j) { + ItemStack itemstack = inventoryhorsechest.getItem(j); + + if (itemstack != null) { + this.inventoryChest.setItem(j, itemstack.cloneItemStack()); + } + } + } + + this.inventoryChest.a(this); + this.db(); + } + + private void db() { + + this.q(this.inventoryChest.getItem(0) != null); + if (this.cO()) { + this.e(this.inventoryChest.getItem(1)); + } + + } + + public void a(InventorySubcontainer inventorysubcontainer) { + int i = this.cx(); + boolean flag = this.cG(); + + this.db(); + if (this.ticksLived > 20) { + if (i == 0 && i != this.cx()) { + this.makeSound("mob.horse.armor", 0.5F, 1.0F); + } else if (i != this.cx()) { + this.makeSound("mob.horse.armor", 0.5F, 1.0F); + } + + if (!flag && this.cG()) { + this.makeSound("mob.horse.leather", 0.5F, 1.0F); + } + } + + } + + public boolean bR() { + this.cD(); + return super.bR(); + } + + protected EntityHorse a(Entity entity, double d0) { + double d1 = Double.MAX_VALUE; + Entity entity1 = null; + + for (Entity entity2 : world.a(entity, entity.boundingBox.a(d0, d0, d0), EntityHorse.bs)) { + double d2 = entity2.e(entity.locX, entity.locY, entity.locZ); + + if (d2 < d1) { + entity1 = entity2; + d1 = d2; + } + } + + return (EntityHorse) entity1; + } + + public double getJumpStrength() { + return this.getAttributeInstance(EntityHorse.attributeJumpStrength).getValue(); + } + + protected String bp() { + this.df(); + int i = this.getType(); + + return i == 3 ? "mob.horse.zombie.death" : (i == 4 ? "mob.horse.skeleton.death" : (i != 1 && i != 2 ? "mob.horse.death" : "mob.horse.donkey.death")); + } + + protected Item getLoot() { + boolean flag = random.nextInt(4) == 0; + int i = this.getType(); + + return i == 4 ? Items.BONE : (i == 3 ? (flag ? null : Items.ROTTEN_FLESH) : Items.LEATHER); + } + + protected String bo() { + this.df(); + if (random.nextInt(3) == 0) { + this.dh(); + } + + int i = this.getType(); + + return i == 3 ? "mob.horse.zombie.hit" : (i == 4 ? "mob.horse.skeleton.hit" : (i != 1 && i != 2 ? "mob.horse.hit" : "mob.horse.donkey.hit")); + } + + public boolean cG() { + return this.w(4); + } + + protected String z() { + this.df(); + if (random.nextInt(10) == 0 && !this.bD()) { + this.dh(); + } + + int i = this.getType(); + + return i == 3 ? "mob.horse.zombie.idle" : (i == 4 ? "mob.horse.skeleton.idle" : (i != 1 && i != 2 ? "mob.horse.idle" : "mob.horse.donkey.idle")); + } + + protected String cH() { + this.df(); + this.dh(); + int i = this.getType(); + + return i != 3 && i != 4 ? (i != 1 && i != 2 ? "mob.horse.angry" : "mob.horse.donkey.angry") : null; + } + + protected void a(BlockPosition blockposition, Block block) { + Block.StepSound block_stepsound = block.stepSound; + + if (this.world.getType(blockposition.getX(), blockposition.getY() + 1, blockposition.getZ()).getBlock() == Blocks.SNOW_LAYER) { + block_stepsound = Blocks.SNOW_LAYER.stepSound; + } + + if (!block.getMaterial().isLiquid()) { + int i = this.getType(); + + if (this.passenger != null && i != 1 && i != 2) { + ++this.bN; + if (this.bN > 5 && this.bN % 3 == 0) { + this.makeSound("mob.horse.gallop", block_stepsound.getVolume1() * 0.15F, block_stepsound.getVolume2()); + if (i == 0 && random.nextInt(10) == 0) { + this.makeSound("mob.horse.breathe", block_stepsound.getVolume1() * 0.6F, block_stepsound.getVolume2()); + } + } else if (this.bN <= 5) { + this.makeSound("mob.horse.wood", block_stepsound.getVolume1() * 0.15F, block_stepsound.getVolume2()); + } + } else if (block_stepsound == Block.f) { + this.makeSound("mob.horse.wood", block_stepsound.getVolume1() * 0.15F, block_stepsound.getVolume2()); + } else { + this.makeSound("mob.horse.soft", block_stepsound.getVolume1() * 0.15F, block_stepsound.getVolume2()); + } + } + + } + + protected void initAttributes() { + super.initAttributes(); + this.getAttributeMap().b(EntityHorse.attributeJumpStrength); + this.getAttributeInstance(GenericAttributes.maxHealth).setValue(53.0D); + this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.22499999403953552D); + } + + public int bV() { + return 6; + } + + public int getMaxDomestication() { + return this.maxDomestication; // CraftBukkit - return stored max domestication instead of 100 + } + + protected float bB() { + return 0.8F; + } + + public int w() { + return 400; + } + + public void g(EntityHuman entityhuman) { + if ((this.passenger == null || this.passenger == entityhuman) && this.isTame()) { + this.inventoryChest.a(this.getName()); + entityhuman.openHorseInventory(this, this.inventoryChest); + } + + } + + public boolean a(EntityHuman entityhuman) { + ItemStack itemstack = entityhuman.inventory.getItemInHand(); + + if (itemstack != null && itemstack.getItem() == Items.SPAWN_EGG) { + return super.a(entityhuman); + } else if (!this.isTame() && this.cR()) { + return false; + } else if (this.isTame() && this.cn() && entityhuman.isSneaking()) { + this.g(entityhuman); + return true; + } else if (this.cp() && this.passenger != null) { + return super.a(entityhuman); + } else { + if (itemstack != null) { + boolean flag = false; + + if (this.cO()) { // Can wear armor + byte b0 = -1; + + if (itemstack.getItem() == Items.IRON_HORSE_ARMOR) { + b0 = 1; + } else if (itemstack.getItem() == Items.GOLDEN_HORSE_ARMOR) { + b0 = 2; + } else if (itemstack.getItem() == Items.DIAMOND_HORSE_ARMOR) { + b0 = 3; + } + + if (b0 >= 0) { + if (!this.isTame()) { + this.cW(); + return true; + } + + this.g(entityhuman); + return true; + } + } + + if (!this.cR()) { // Not undead + float f = 0.0F; + short short0 = 0; + byte b1 = 0; + + if (itemstack.getItem() == Items.WHEAT) { + f = 2.0F; + short0 = 20; + b1 = 3; + } else if (itemstack.getItem() == Items.SUGAR) { + f = 1.0F; + short0 = 30; + b1 = 3; + } else if (Block.asBlock(itemstack.getItem()) == Blocks.HAY_BLOCK) { + f = 20.0F; + short0 = 180; + } else if (itemstack.getItem() == Items.APPLE) { + f = 3.0F; + short0 = 60; + b1 = 3; + } else if (itemstack.getItem() == Items.GOLDEN_CARROT) { + f = 4.0F; + short0 = 60; + b1 = 5; + if (this.isTame() && this.getAge() == 0) { + flag = true; + this.c(entityhuman); + } + } else if (itemstack.getItem() == Items.GOLDEN_APPLE) { + f = 10.0F; + short0 = 240; + b1 = 10; + if (this.isTame() && this.getAge() == 0) { + flag = true; + this.c(entityhuman); + } + } + + if (this.getHealth() < this.getMaxHealth() && f > 0.0F) { + this.heal(f, RegainReason.EATING); // CraftBukkit + flag = true; + } + + if (!this.cn() && short0 > 0) { + this.setAge(short0); + flag = true; + } + + if (b1 > 0 && (flag || !this.isTame()) && b1 < this.getMaxDomestication()) { + flag = true; + this.u(b1); + } + + if (flag) { + this.cY(); + } + } + + if (!this.isTame() && !flag) { + if (itemstack.a(entityhuman, this)) { + return true; + } + + this.cW(); + return true; + } + + if (!flag && this.cP() && !this.hasChest() && itemstack.getItem() == Item.getItemOf(Blocks.CHEST)) { + this.setHasChest(true); + this.makeSound("mob.chickenplop", 1.0F, (random.nextFloat() - random.nextFloat()) * 0.2F + 1.0F); + flag = true; + this.loadChest(); + } + + if (!flag && this.cp() && !this.cG() && itemstack.getItem() == Items.SADDLE) { + this.g(entityhuman); + return true; + } + + if (flag) { + if (!entityhuman.abilities.canInstantlyBuild && --itemstack.count == 0) { + entityhuman.inventory.setItem(entityhuman.inventory.itemInHandIndex, null); + } + + return true; + } + } + + if (this.cp() && this.passenger == null) { + if (itemstack == null || !itemstack.a(entityhuman, this)) { + this.i(entityhuman); + } + return true; + } else { + return super.a(entityhuman); + } + } + } + + private void i(EntityHuman entityhuman) { + entityhuman.yaw = this.yaw; + entityhuman.pitch = this.pitch; + this.r(false); + this.s(false); + + entityhuman.mount(this); + + } + + public boolean cO() { + return this.getType() == 0; + } + + public boolean cP() { + int i = this.getType(); + + return i == 2 || i == 1; + } + + protected boolean bD() { + return this.passenger != null && this.cG() || this.cy() || this.cz(); + } + + public boolean cR() { + int i = this.getType(); + + return i == 3 || i == 4; + } + + public boolean cS() { + return this.cR() || this.getType() == 2; + } + + public boolean d(ItemStack itemstack) { + return false; + } + + private void de() { + this.bm = 1; + } + + public void die(DamageSource damagesource) { + super.die(damagesource); + /* CraftBukkit start - Handle chest dropping in dropDeathLoot below + if (!this.world.isClientSide) { + this.dropChest(); + } + // CraftBukkit end */ + } + // CraftBukkit end + + // CraftBukkit start - Add method + @Override + protected void dropDeathLoot(boolean flag, int i) { + super.dropDeathLoot(flag, i); + + // Moved from die method above + this.dropChest(); + } + + public void m() { + if (random.nextInt(200) == 0) { + this.de(); + } + + super.m(); + + if (random.nextInt(900) == 0 && this.deathTicks == 0) { + this.heal(1.0F, RegainReason.REGEN); // CraftBukkit + } + + if (!this.cy() && this.passenger == null && random.nextInt(300) == 0 && this.world.getType(MathHelper.floor(this.locX), MathHelper.floor(this.locY) - 1, MathHelper.floor(this.locZ)).getBlock() == Blocks.GRASS) { + this.r(true); + } + + if (this.cy() && ++this.bB > 50) { + this.bB = 0; + this.r(false); + } + + if (this.cA() && !this.cn() && !this.cy()) { + EntityHorse entityhorse = this.a(this, 16.0D); + + if (entityhorse != null && this.h(entityhorse) > 4.0D) { + this.navigation.a(entityhorse); + } + } + + } + + public void t_() { + super.t_(); + + if (this.bC > 0 && ++this.bC > 30) { + this.bC = 0; + this.c(128, false); + } + + if (this.bD > 0 && ++this.bD > 20) { + this.bD = 0; + this.s(false); + } + + if (this.bm > 0 && ++this.bm > 8) { + this.bm = 0; + } + + if (this.bo > 0) { + ++this.bo; + if (this.bo > 300) { + this.bo = 0; + } + } + + if (this.cy()) { + this.bH += (1.0F - this.bH) * 0.4F + 0.05F; + if (this.bH > 1.0F) { + this.bH = 1.0F; + } + } else { + this.bH += (0.0F - this.bH) * 0.4F - 0.05F; + if (this.bH < 0.0F) { + this.bH = 0.0F; + } + } + + this.bK = this.bJ; + if (this.cz()) { + + this.bJ += (1.0F - this.bJ) * 0.4F + 0.05F; + if (this.bJ > 1.0F) { + this.bJ = 1.0F; + } + } else { + this.bG = false; + this.bJ += (0.8F * this.bJ * this.bJ * this.bJ - this.bJ) * 0.6F - 0.05F; + if (this.bJ < 0.0F) { + this.bJ = 0.0F; + } + } + + if (this.w(128)) { + this.bL += (1.0F - this.bL) * 0.7F + 0.05F; + if (this.bL > 1.0F) { + this.bL = 1.0F; + } + } else { + this.bL += (0.0F - this.bL) * 0.7F - 0.05F; + if (this.bL < 0.0F) { + this.bL = 0.0F; + } + } + + } + + private void df() { + + this.bC = 1; + this.c(128, true); + + } + + private boolean dg() { + return this.passenger == null && this.vehicle == null && this.isTame() && this.cn() && !this.cS() && this.getHealth() >= this.getMaxHealth() && this.isInLove(); + } + + public void f(boolean flag) { + this.c(32, flag); + } + + public void r(boolean flag) { + this.f(flag); + } + + public void s(boolean flag) { + if (flag) { + this.r(false); + } + + this.c(64, flag); + } + + private void dh() { + this.bD = 1; + this.s(true); + + } + + public void cW() { + this.dh(); + String s = this.cH(); + + if (s != null) { + this.makeSound(s, this.bB(), this.bC()); + } + + } + + public void dropChest() { + this.a(this, this.inventoryChest); + this.cE(); + } + + private void a(Entity entity, InventoryHorseChest inventoryhorsechest) { + if (inventoryhorsechest != null) { + for (int i = 0; i < inventoryhorsechest.getSize(); ++i) { + ItemStack itemstack = inventoryhorsechest.getItem(i); + + if (itemstack != null) { + this.a(itemstack, 0.0F); + } + } + + } + } + + public boolean h(EntityHuman entityhuman) { + this.setOwnerUUID(FastUUID.toString(entityhuman.getUniqueID())); + this.setTame(true); + return true; + } + + public void g(float f, float f1) { + if (this.passenger != null && this.passenger instanceof EntityLiving && this.cG()) { + this.lastYaw = this.yaw = this.passenger.yaw; + this.pitch = this.passenger.pitch * 0.5F; + this.setYawPitch(this.yaw, this.pitch); + this.aK = this.aI = this.yaw; + f = ((EntityLiving) this.passenger).aZ * 0.5F; + f1 = ((EntityLiving) this.passenger).ba; + if (f1 <= 0.0F) { + f1 *= 0.25F; + this.bN = 0; + } + + if (this.onGround && this.br == 0.0F && this.cz() && !this.bG) { + f = 0.0F; + f1 = 0.0F; + } + + if (this.br > 0.0F && !this.cv() && this.onGround) { + this.motY = this.getJumpStrength() * (double) this.br; + if (this.hasEffect(MobEffectList.JUMP)) { + this.motY += ((float) (this.getEffect(MobEffectList.JUMP).getAmplifier() + 1) * 0.1F); + } + + this.m(true); + this.ai = true; + if (f1 > 0.0F) { + float f2 = MathHelper.sin(this.yaw * 3.1415927F / 180.0F); + float f3 = MathHelper.cos(this.yaw * 3.1415927F / 180.0F); + + this.motX += (-0.4F * f2 * this.br); + this.motZ += (0.4F * f3 * this.br); + this.makeSound("mob.horse.jump", 0.4F, 1.0F); + } + + this.br = 0.0F; + } + + this.S = 1.0F; + this.aM = this.bI() * 0.1F; + + this.k((float) this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).getValue()); + super.g(f, f1); + + if (this.onGround) { + this.br = 0.0F; + this.m(false); + } + + this.aA = this.aB; + double d0 = this.locX - this.lastX; + double d1 = this.locZ - this.lastZ; + float f4 = MathHelper.sqrt(d0 * d0 + d1 * d1) * 4.0F; + + if (f4 > 1.0F) { + f4 = 1.0F; + } + + this.aB += (f4 - this.aB) * 0.4F; + this.aC += this.aB; + } else { + this.S = 0.5F; + this.aM = 0.02F; + super.g(f, f1); + } + } + + public void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + nbttagcompound.setBoolean("EatingHaystack", this.cy()); + nbttagcompound.setBoolean("ChestedHorse", this.hasChest()); + nbttagcompound.setBoolean("HasReproduced", this.cB()); + nbttagcompound.setBoolean("Bred", this.cA()); + nbttagcompound.setInt("Type", this.getType()); + nbttagcompound.setInt("Variant", this.getVariant()); + nbttagcompound.setInt("Temper", this.getTemper()); + nbttagcompound.setBoolean("Tame", this.isTame()); + nbttagcompound.setString("OwnerUUID", this.getOwnerUUID()); + nbttagcompound.setInt("Bukkit.MaxDomestication", this.maxDomestication); // CraftBukkit + if (this.hasChest()) { + NBTTagList nbttaglist = new NBTTagList(); + + for (int i = 2; i < this.inventoryChest.getSize(); ++i) { + ItemStack itemstack = this.inventoryChest.getItem(i); + + if (itemstack != null) { + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + + nbttagcompound1.setByte("Slot", (byte) i); + itemstack.save(nbttagcompound1); + nbttaglist.add(nbttagcompound1); + } + } + + nbttagcompound.set("Items", nbttaglist); + } + + if (this.inventoryChest.getItem(1) != null) { + nbttagcompound.set("ArmorItem", this.inventoryChest.getItem(1).save(new NBTTagCompound())); + } + + if (this.inventoryChest.getItem(0) != null) { + nbttagcompound.set("SaddleItem", this.inventoryChest.getItem(0).save(new NBTTagCompound())); + } + + } + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + this.r(nbttagcompound.getBoolean("EatingHaystack")); + this.n(nbttagcompound.getBoolean("Bred")); + this.setHasChest(nbttagcompound.getBoolean("ChestedHorse")); + this.p(nbttagcompound.getBoolean("HasReproduced")); + this.setType(nbttagcompound.getInt("Type")); + this.setVariant(nbttagcompound.getInt("Variant")); + this.setTemper(nbttagcompound.getInt("Temper")); + this.setTame(nbttagcompound.getBoolean("Tame")); + String s; + + if (nbttagcompound.hasKeyOfType("OwnerUUID", 8)) { + s = nbttagcompound.getString("OwnerUUID"); + } else { + String s1 = nbttagcompound.getString("Owner"); + // Spigot start + if (s1 == null || s1.isEmpty()) { + if (nbttagcompound.hasKey("OwnerName")) { + String owner = nbttagcompound.getString("OwnerName"); + if (owner != null && !owner.isEmpty()) { + s1 = owner; + } + } + } + // Spigot end + + s = NameReferencingFileConverter.a(s1); + } + + if (s.length() > 0) { + this.setOwnerUUID(s); + } + + // CraftBukkit start + if (nbttagcompound.hasKey("Bukkit.MaxDomestication")) { + this.maxDomestication = nbttagcompound.getInt("Bukkit.MaxDomestication"); + } + // CraftBukkit end + + AttributeInstance attributeinstance = this.getAttributeMap().a("Speed"); + + if (attributeinstance != null) { + this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(attributeinstance.b() * 0.25D); + } + + if (this.hasChest()) { + NBTTagList nbttaglist = nbttagcompound.getList("Items", 10); + + this.loadChest(); + + for (int i = 0; i < nbttaglist.size(); ++i) { + NBTTagCompound nbttagcompound1 = nbttaglist.get(i); + int j = nbttagcompound1.getByte("Slot") & 255; + + if (j >= 2 && j < this.inventoryChest.getSize()) { + this.inventoryChest.setItem(j, ItemStack.createStack(nbttagcompound1)); + } + } + } + + ItemStack itemstack; + + if (nbttagcompound.hasKeyOfType("ArmorItem", 10)) { + itemstack = ItemStack.createStack(nbttagcompound.getCompound("ArmorItem")); + if (itemstack != null && a(itemstack.getItem())) { + this.inventoryChest.setItem(1, itemstack); + } + } + + if (nbttagcompound.hasKeyOfType("SaddleItem", 10)) { + itemstack = ItemStack.createStack(nbttagcompound.getCompound("SaddleItem")); + if (itemstack != null && itemstack.getItem() == Items.SADDLE) { + this.inventoryChest.setItem(0, itemstack); + } + } else if (nbttagcompound.getBoolean("Saddle")) { + this.inventoryChest.setItem(0, new ItemStack(Items.SADDLE)); + } + + this.db(); + } + + public boolean mate(EntityAnimal entityanimal) { + if (entityanimal == this) { + return false; + } else if (entityanimal.getClass() != this.getClass()) { + return false; + } else { + EntityHorse entityhorse = (EntityHorse) entityanimal; + + if (this.dg() && entityhorse.dg()) { + int i = this.getType(); + int j = entityhorse.getType(); + + return i == j || i == 0 && j == 1 || i == 1 && j == 0; + } else { + return false; + } + } + } + + public EntityAgeable createChild(EntityAgeable entityageable) { + EntityHorse entityhorse = (EntityHorse) entityageable; + EntityHorse entityhorse1 = new EntityHorse(this.world); + int i = this.getType(); + int j = entityhorse.getType(); + int k = 0; + + if (i == j) { + k = i; + } else if (i == 0 && j == 1 || i == 1 && j == 0) { + k = 2; + } + + if (k == 0) { + int l = random.nextInt(9); + int i1; + + if (l < 4) { + i1 = this.getVariant() & 255; + } else if (l < 8) { + i1 = entityhorse.getVariant() & 255; + } else { + i1 = random.nextInt(7); + } + + int j1 = random.nextInt(5); + + if (j1 < 2) { + i1 |= this.getVariant() & '\uff00'; + } else if (j1 < 4) { + i1 |= entityhorse.getVariant() & '\uff00'; + } else { + i1 |= random.nextInt(5) << 8 & '\uff00'; + } + + entityhorse1.setVariant(i1); + } + + entityhorse1.setType(k); + double d0 = this.getAttributeInstance(GenericAttributes.maxHealth).b() + entityageable.getAttributeInstance(GenericAttributes.maxHealth).b() + (double) this.di(); + + entityhorse1.getAttributeInstance(GenericAttributes.maxHealth).setValue(d0 / 3.0D); + double d1 = this.getAttributeInstance(EntityHorse.attributeJumpStrength).b() + entityageable.getAttributeInstance(EntityHorse.attributeJumpStrength).b() + this.dj(); + + entityhorse1.getAttributeInstance(EntityHorse.attributeJumpStrength).setValue(d1 / 3.0D); + double d2 = this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).b() + entityageable.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).b() + this.dk(); + + entityhorse1.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(d2 / 3.0D); + return entityhorse1; + } + + public GroupDataEntity prepare(DifficultyDamageScaler difficultydamagescaler, GroupDataEntity groupdataentity) { + GroupDataEntity object = super.prepare(difficultydamagescaler, groupdataentity); + int i = 0; + int j; + + if (object instanceof GroupDataHorse) { + j = ((GroupDataHorse) object).a; + i = ((GroupDataHorse) object).b & 255 | random.nextInt(5) << 8; + } else { + if (random.nextInt(10) == 0) { + j = 1; + } else { + int k = random.nextInt(7); + int l = random.nextInt(5); + + j = 0; + i = k | l << 8; + } + + object = new GroupDataHorse(j, i); + } + + this.setType(j); + this.setVariant(i); + if (random.nextInt(5) == 0) { + this.setAgeRaw(-24000); + } + + if (j != 4 && j != 3) { + this.getAttributeInstance(GenericAttributes.maxHealth).setValue(this.di()); + if (j == 0) { + this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(this.dk()); + } else { + this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.17499999701976776D); + } + } else { + this.getAttributeInstance(GenericAttributes.maxHealth).setValue(15.0D); + this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.20000000298023224D); + } + + if (j != 2 && j != 1) { + this.getAttributeInstance(EntityHorse.attributeJumpStrength).setValue(this.dj()); + } else { + this.getAttributeInstance(EntityHorse.attributeJumpStrength).setValue(0.5D); + } + + this.setHealth(this.getMaxHealth()); + return object; + } + + public void v(int i) { + if (this.cG()) { + // CraftBukkit start - fire HorseJumpEvent, use event power + if (i < 0) { + i = 0; + } + + float power; + if (i >= 90) { + power = 1.0F; + } else { + power = 0.4F + 0.4F * (float) i / 90.0F; + } + + org.bukkit.event.entity.HorseJumpEvent event = org.bukkit.craftbukkit.event.CraftEventFactory.callHorseJumpEvent(this, power); + if (!event.isCancelled()) { + this.bG = true; + this.dh(); + this.br = power; + } + // CraftBukkit end + } + + } + + public void al() { + super.al(); + if (this.bK > 0.0F) { + float f = MathHelper.sin(this.aI * 3.1415927F / 180.0F); + float f1 = MathHelper.cos(this.aI * 3.1415927F / 180.0F); + float f2 = 0.7F * this.bK; + float f3 = 0.15F * this.bK; + + this.passenger.setPosition(this.locX + (double) (f2 * f), this.locY + this.an() + this.passenger.am() + (double) f3, this.locZ - (double) (f2 * f1)); + if (this.passenger instanceof EntityLiving) { + ((EntityLiving) this.passenger).aI = this.aI; + } + } + + } + + private float di() { + return 15.0F + (float) random.nextInt(8) + (float) random.nextInt(9); + } + + private double dj() { + return 0.4000000059604645D + random.nextDouble() * 0.2D + random.nextDouble() * 0.2D + random.nextDouble() * 0.2D; + } + + private double dk() { + return (0.44999998807907104D + random.nextDouble() * 0.3D + random.nextDouble() * 0.3D + random.nextDouble() * 0.3D) * 0.25D; + } + + public boolean k_() { + return false; + } + + public float getHeadHeight() { + return this.length; + } + + public boolean d(int i, ItemStack itemstack) { + if (i == 499 && this.cP()) { + if (itemstack == null && this.hasChest()) { + this.setHasChest(false); + this.loadChest(); + return true; + } + + if (itemstack != null && itemstack.getItem() == Item.getItemOf(Blocks.CHEST) && !this.hasChest()) { + this.setHasChest(true); + this.loadChest(); + return true; + } + } + + int j = i - 400; + + if (j >= 0 && j < 2 && j < this.inventoryChest.getSize()) { + if (j == 0 && itemstack != null && itemstack.getItem() != Items.SADDLE) { + return false; + } else if (j == 1 && (itemstack != null && !a(itemstack.getItem()) || !this.cO())) { + return false; + } else { + this.inventoryChest.setItem(j, itemstack); + this.db(); + return true; + } + } else { + int k = i - 500 + 2; + + if (k >= 2 && k < this.inventoryChest.getSize()) { + this.inventoryChest.setItem(k, itemstack); + return true; + } else { + return false; + } + } + } + + public static class GroupDataHorse implements GroupDataEntity { + + public int a; + public int b; + + public GroupDataHorse(int i, int j) { + this.a = i; + this.b = j; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityHuman.java b/azurite-server/src/main/java/net/minecraft/server/EntityHuman.java new file mode 100644 index 0000000..94e87a8 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityHuman.java @@ -0,0 +1,2103 @@ +package net.minecraft.server; + +import com.google.common.base.Charsets; +import com.google.common.collect.Lists; +import com.mojang.authlib.GameProfile; +import dev.azurite.spigot.configs.AzuriteConfig; +import dev.azurite.spigot.knockback.Knockback; +import dev.azurite.spigot.knockback.KnockbackType; +import dev.azurite.spigot.knockback.types.AdvancedKnockback; +import dev.azurite.spigot.knockback.types.ConstantKnockback; +import dev.azurite.spigot.knockback.types.SimpleKnockback; +import org.bukkit.Bukkit; +import org.bukkit.craftbukkit.entity.CraftHumanEntity; +import org.bukkit.craftbukkit.entity.CraftItem; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityCombustByEntityEvent; +import org.bukkit.event.inventory.EquipmentSetEvent; +import org.bukkit.event.player.*; +import org.bukkit.util.Vector; + +import java.util.Collection; +import java.util.List; +import java.util.Objects; +import java.util.UUID; + +public abstract class EntityHuman extends EntityLiving { + + public PlayerInventory inventory = new PlayerInventory(this); + private InventoryEnderChest enderChest = new InventoryEnderChest(); + public Container defaultContainer; + public Container activeContainer; + protected FoodMetaData foodData = new FoodMetaData(this); // CraftBukkit - add "this" to constructor + protected int bm; + public float bn; + public float bo; + public int bp; + public double bq; + public double br; + public double bs; + public double bt; + public double bu; + public double bv; + public boolean sleeping; + public BlockPosition bx; + public int sleepTicks; + public float by; + public float bz; + private BlockPosition c; + private boolean d; + private BlockPosition e; + public PlayerAbilities abilities = new PlayerAbilities(); + public int expLevel; + public int expTotal; + public float exp; + private int f; + public ItemStack g; + private int h; + protected float bE = 0.1F; + protected float bF = 0.02F; + private int i; + private final GameProfile bH; + private boolean bI = false; + public EntityFishingHook hookedFish; + public boolean affectsSpawning = true; // PaperSpigot + // CraftBukkit start + public boolean fauxSleeping; + public String spawnWorld = ""; + public int oldLevel = -1; + public boolean shouldDealSprintKnockback = false; + public boolean shouldDealSprintKnockbackForConstantKnockback = false; // Beanes - constant kb more accurate + public int ticksDown; + + public EntityHuman(World world, GameProfile gameprofile) { + super(world); + uniqueID = a(gameprofile); + bH = gameprofile; + defaultContainer = new ContainerPlayer(inventory, true, this); + activeContainer = defaultContainer; + + BlockPosition blockposition = world.getSpawn(); + setPositionRotation(blockposition.getX() + 0.5D, blockposition.getY() + 1, blockposition.getZ() + 0.5D, 0.0F, 0.0F); + + aV = 180.0F; + maxFireTicks = 20; + } + // CraftBukkit end + + // PaperSpigot start - SPIGOT-1387: Resolve bed issues on unloaded chunks + public static BlockPosition getBed(World world, BlockPosition blockposition, boolean flag) { + boolean before = ((WorldServer) world).chunkProviderServer.forceChunkLoad; + ((WorldServer) world).chunkProviderServer.forceChunkLoad = true; + final BlockPosition result = getBed0(world, blockposition, flag); + ((WorldServer) world).chunkProviderServer.forceChunkLoad = before; + return result; + } + + private static BlockPosition getBed0(World world, BlockPosition blockposition, boolean flag) { + // PaperSpigot end + ((ChunkProviderServer) world.chunkProvider).getChunkAt(blockposition.getX() >> 4, blockposition.getZ() >> 4); // CraftBukkit + Block block = world.getType(blockposition).getBlock(); + + if (block != Blocks.BED) { + if (!flag) { + return null; + } else { + return block.g() && world.getType(blockposition.getX(), blockposition.getY() + 1, blockposition.getZ()).getBlock().g() ? blockposition : null; + } + } else { + return BlockBed.a(world, blockposition, 0); + } + } + + public static UUID a(GameProfile gameprofile) { + UUID uuid = gameprofile.getId(); + + if (uuid == null) { + uuid = b(gameprofile.getName()); + } + + return uuid; + } + + public static UUID b(String s) { + return UUID.nameUUIDFromBytes(("OfflinePlayer:" + s).getBytes(Charsets.UTF_8)); + } + + @Override + public EntityTrackerEntry getEntry(int i, int j, boolean flag) { + return new EntityTrackerPlayerEntry(this, i, j, flag); + } + + @Override + public CraftHumanEntity getBukkitEntity() { + return (CraftHumanEntity) super.getBukkitEntity(); + } + + protected void initAttributes() { + super.initAttributes(); + this.getAttributeMap().b(GenericAttributes.ATTACK_DAMAGE).setValue(1.0D); + this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.10000000149011612D); + } + + protected void h() { + super.h(); + this.datawatcher.a(16, (byte) 0); + this.datawatcher.a(17, 0.0F); + this.datawatcher.a(18, 0); + this.datawatcher.a(10, (byte) 0); + } + + public boolean bS() { + return this.g != null; + } + + public void bU() { + if (g != null) { + g.b(this.world, this, this.h); + } + + bV(); + } + + public void bV() { + g = null; //usingItem + h = 0; //left using ticks + f(false); + } + + public boolean isBlocking() { + return this.bS() && this.g.getItem().e(this.g) == EnumAnimation.BLOCK; + } + + public boolean isAnimating() { + return this.bS() && this.g.getItem().e(this.g) != EnumAnimation.NONE; + } + + public boolean isEating() { + return this.bS() && this.g.getItem().e(this.g) == EnumAnimation.EAT; + } + + // Beanes - add bow check + public boolean isBowing() { + return this.bS() && this.g.getItem().e(this.g) == EnumAnimation.BOW; + } + + public void t_() { + noclip = isSpectator(); + if (isSpectator()) { + this.onGround = false; + } + + if (g != null) { + ItemStack itemstack = inventory.getItemInHand(); + + if (itemstack == g) { + if (h <= 25 && h % 4 == 0) { + b(itemstack, 5); // sendParticles + } + + if (--h == 0) { // finish + s(); + } + } else { + bV(); // cleanup + } + } + + if (this.bp > 0) { + --this.bp; + } + + if (this.isSleeping()) { + if (++this.sleepTicks > 100) { + this.sleepTicks = 100; + } + if (!this.p()) { + this.a(true, true, false); + } else if (this.world.w()) { + this.a(false, true, true); + } + } else if (this.sleepTicks > 0) { + if (++sleepTicks >= 110) { + this.sleepTicks = 0; + } + } + + super.t_(); + if (this.activeContainer != null && !this.activeContainer.a(this)) { + this.closeInventory(); + this.activeContainer = this.defaultContainer; + } + + if (this.isBurning() && this.abilities.isInvulnerable) { + this.extinguish(); + } + + this.bq = this.bt; + this.br = this.bu; + this.bs = this.bv; + double d0 = this.locX - this.bt; + double d1 = this.locY - this.bu; + double d2 = this.locZ - this.bv; + if (d0 > 10.0) { + this.bq = this.bt = this.locX; + } + + if (d2 > 10.0) { + this.bs = this.bv = this.locZ; + } + + if (d1 > 10.0) { + this.br = this.bu = this.locY; + } + + if (d0 < -10.0) { + this.bq = this.bt = this.locX; + } + + if (d2 < -10.0) { + this.bs = this.bv = this.locZ; + } + + if (d1 < -10.0) { + this.br = this.bu = this.locY; + } + + this.bt += d0 * 0.25D; + this.bv += d2 * 0.25D; + this.bu += d1 * 0.25D; + if (this.vehicle == null) { + this.e = null; + } + + foodData.a(this); + this.b(StatisticList.g); + if (this.isAlive()) { + this.b(StatisticList.h); + } + + double d4 = MathHelper.a(this.locX, -2.9999999E7D, 2.9999999E7D); + double d5 = MathHelper.a(this.locZ, -2.9999999E7D, 2.9999999E7D); + if (d4 != this.locX || d5 != this.locZ) + setPosition(d4, this.locY, d5); + } + + public int L() { + return this.abilities.isInvulnerable ? 0 : 80; + } + + protected String P() { + return "game.player.swim"; + } + + protected String aa() { + return "game.player.swim.splash"; + } + + @Override + public void collide(Entity entity) { + // Beanes - toggleable collisions movement for players + if (AzuriteConfig.playerCollisions.getValue()) { + super.collide(entity); + } + } + + public int aq() { + return 10; + } + + public void makeSound(String s, float f, float f1) { + this.world.a(this, s, f, f1); + } + + protected void b(ItemStack itemstack, int i) { + switch (itemstack.m()) { // Vortex - use switch case + case DRINK: { + makeSound("random.drink", 0.5F, this.world.random.nextFloat() * 0.1F + 0.9F); + break; + } + case EAT: { + for (int j = 0; j < i; ++j) { + Vec3D vec3d = new Vec3D((random.nextFloat() - 0.5D) * 0.1D, Math.random() * 0.1D + 0.1D, 0.0D); + + vec3d = vec3d.a(-this.pitch * 3.1415927F / 180.0F); + vec3d = vec3d.b(-this.yaw * 3.1415927F / 180.0F); + double d0 = (-random.nextFloat()) * 0.6D - 0.3D; + Vec3D vec3d1 = new Vec3D((random.nextFloat() - 0.5D) * 0.3D, d0, 0.6D); + + vec3d1 = vec3d1.a(-this.pitch * 3.1415927F / 180.0F); + vec3d1 = vec3d1.b(-this.yaw * 3.1415927F / 180.0F); + vec3d1 = vec3d1.add(this.locX, this.locY + this.getHeadHeight(), this.locZ); + if (itemstack.usesData()) { + world.addParticle(EnumParticle.ITEM_CRACK, vec3d1.a, vec3d1.b, vec3d1.c, vec3d.a, vec3d.b + 0.05D, vec3d.c, Item.getId(itemstack.getItem()), itemstack.getData()); + } else { + world.addParticle(EnumParticle.ITEM_CRACK, vec3d1.a, vec3d1.b, vec3d1.c, vec3d.a, vec3d.b + 0.05D, vec3d.c, Item.getId(itemstack.getItem())); + } + } + + this.makeSound("random.eat", 0.5F + 0.5F * random.nextInt(2), (random.nextFloat() - random.nextFloat()) * 0.2F + 1.0F); + break; + } + default: + break; + } + } + + // Beanes - don't send finish using as we replace the item anyways instantly + protected boolean cancelFinishPacket() { + return this.g != null && this.g.getItem() instanceof ItemPotion && !this.abilities.canInstantlyBuild; + } + + protected void s() { + if (this.g != null) { + this.b(this.g, 16); + int i = this.g.count; + + // CraftBukkit start - fire PlayerItemConsumeEvent + org.bukkit.inventory.ItemStack craftItem = CraftItemStack.asBukkitCopy(this.g); + PlayerItemConsumeEvent event = new PlayerItemConsumeEvent((Player) this.getBukkitEntity(), craftItem); + world.getServer().getPluginManager().callEvent(event); + + if (event.isCancelled()) { + // Update client + EntityPlayer pl = (EntityPlayer) this; + pl.playerConnection.sendPacket(new PacketPlayOutSetSlot((byte) 0, + activeContainer.getSlot(this.inventory, this.inventory.itemInHandIndex).index, + this.g)); + // Spigot Start + pl.getBukkitEntity().updateInventory(); + pl.getBukkitEntity().updateScaledHealth(); + // Spigot End + return; + } + + // Plugin modified the item, process it but don't remove it + if (!craftItem.equals(event.getItem())) { + CraftItemStack.asNMSCopy(event.getItem()).b(this.world, this); + + // Update client + sendPacket(new PacketPlayOutSetSlot((byte) 0, activeContainer.getSlot(this.inventory, this.inventory.itemInHandIndex).index, this.g)); + return; + } + // CraftBukkit end + + ItemStack itemstack = this.g.b(this.world, this); + + if ((itemstack != this.g) || ((itemstack != null) && (itemstack.count != i))) { + this.inventory.items[this.inventory.itemInHandIndex] = itemstack; + if (itemstack.count == 0) { + this.inventory.items[this.inventory.itemInHandIndex] = null; + } + } + + this.bV(); + } + + } + + protected boolean bD() { + return this.getHealth() <= 0.0F || this.isSleeping(); + } + + public void closeInventory() { + this.activeContainer = this.defaultContainer; + } + + public void ak() { + if (this.isSneaking()) { + this.mount(null); + this.setSneaking(false); + } else { + double d0 = this.locX; + double d1 = this.locY; + double d2 = this.locZ; + float f = this.yaw; + float f1 = this.pitch; + + super.ak(); + this.bn = this.bo; + this.bo = 0.0F; + this.l(this.locX - d0, this.locY - d1, this.locZ - d2); + if (this.vehicle instanceof EntityPig) { + this.pitch = f1; + this.yaw = f; + this.aI = ((EntityPig) this.vehicle).aI; + } + + } + } + + protected void doTick() { + super.doTick(); + this.bx(); + this.aK = this.yaw; + } + + public void m() { + if (this.bm > 0) { + --this.bm; + } + + if (this.world.getDifficulty() == EnumDifficulty.PEACEFUL && this.world.getGameRules().getBoolean("naturalRegeneration")) { + if (this.getHealth() < this.getMaxHealth() && this.ticksLived % 20 == 0) { + // CraftBukkit - added regain reason of "REGEN" for filtering purposes. + this.heal(1.0F, org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason.REGEN); + } + + if (this.foodData.c() && this.ticksLived % 10 == 0) { + this.foodData.a(this.foodData.getFoodLevel() + 1); + } + } + + this.inventory.k(); + this.bn = this.bo; + super.m(); + AttributeInstance attributeinstance = this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED); + + attributeinstance.setValue(this.abilities.b()); + this.aM = this.bF; + if (this.isSprinting()) { + this.aM = (float) (this.aM + this.bF * 0.3D); + } + + this.k((float) attributeinstance.getValue()); + float f = MathHelper.sqrt(this.motX * this.motX + this.motZ * this.motZ); + float f1 = (float) (org.bukkit.craftbukkit.TrigMath.atan(-this.motY * 0.20000000298023224D) * 15.0D); // CraftBukkit + + if (f > 0.1F) { + f = 0.1F; + } + + if (!this.onGround || this.getHealth() <= 0.0F) { + f = 0.0F; + } + + if (this.onGround || this.getHealth() <= 0.0F) { + f1 = 0.0F; + } + + this.bo += (f - this.bo) * 0.4F; + this.aF += (f1 - this.aF) * 0.8F; + if (getHealth() > 0.0F && !isSpectator() && ae()) { // Vortex + AxisAlignedBB axisalignedbb; + + if (vehicle != null && !vehicle.dead) { + axisalignedbb = boundingBox.a(vehicle.boundingBox).grow(1.0D, 0.0D, 1.0D); + } else { + axisalignedbb = boundingBox.grow(1.0D, 0.5D, 1.0D); + } + + for (Entity entity : world.getEntities(this, axisalignedbb)) { + if (!entity.dead) { + d(entity); + } + } + } + + } + + private void d(Entity entity) { + entity.d(this); + } + + public int getScore() { + return this.datawatcher.getInt(18); + } + + public void setScore(int i) { + this.datawatcher.watch(18, i); + } + + public void addScore(int i) { + this.datawatcher.watch(18, getScore() + i); + } + + public void die(DamageSource damagesource) { + super.die(damagesource); + setSize(0.2F, 0.2F); + setPosition(locX, locY, locZ); + motY = 0.10000000149011612D; + + if (!world.getGameRules().getBoolean("keepInventory")) { + inventory.n(); + } + + motX = (-MathHelper.cos((aw + yaw) * 3.1415927F / 180.0F) * 0.1F); + motZ = (-MathHelper.sin((aw + yaw) * 3.1415927F / 180.0F) * 0.1F); + + this.b(StatisticList.y); + this.a(StatisticList.h); + } + + protected String bo() { + return "game.player.hurt"; + } + + protected String bp() { + return "game.player.die"; + } + + public void b(Entity entity, int i) { + this.addScore(i); + // CraftBukkit - Get our scores instead + Collection collection = this.world.getServer().getScoreboardManager() + .getScoreboardScores(IScoreboardCriteria.f, this.getName(), new java.util.ArrayList<>()); + + if (entity instanceof EntityHuman) { + b(StatisticList.B); + // CraftBukkit - Get our scores instead + this.world.getServer().getScoreboardManager().getScoreboardScores(IScoreboardCriteria.e, this.getName(), + collection); + collection.addAll(this.e(entity)); + } else { + b(StatisticList.z); + } + + for (ScoreboardScore scoreboardScore : collection) { + scoreboardScore.incrementScore(); + } + + } + + private Collection e(Entity entity) { + ScoreboardTeam scoreboardteam = this.getScoreboard().getPlayerTeam(this.getName()); + + if (scoreboardteam != null) { + int i = scoreboardteam.l().b(); + + if (i >= 0 && i < IScoreboardCriteria.i.length) { + + for (ScoreboardObjective scoreboardobjective : this.getScoreboard().getObjectivesForCriteria(IScoreboardCriteria.i[i])) { + ScoreboardScore scoreboardscore = this.getScoreboard().getPlayerScoreForObjective(entity.getName(), + scoreboardobjective); + + scoreboardscore.incrementScore(); + } + } + } + + ScoreboardTeam scoreboardteam1 = this.getScoreboard().getPlayerTeam(entity.getName()); + + if (scoreboardteam1 != null) { + int j = scoreboardteam1.l().b(); + + if (j >= 0 && j < IScoreboardCriteria.h.length) { + return this.getScoreboard().getObjectivesForCriteria(IScoreboardCriteria.h[j]); + } + } + + return Lists.newArrayList(); + } + + public EntityItem a(boolean dropAllItems) { + // Called only when dropped by Q or CTRL-Q + return this.dropWithContext(this.inventory.getItemInHand(), false, true, dropAllItems); + } + + public EntityItem drop(ItemStack itemstack, boolean flag) { + return this.a(itemstack, false, false); + } + + public EntityItem a(ItemStack itemstack, boolean flag, boolean flag1) { + return this.dropWithContext(itemstack, flag, flag1, false); // Necrozma - Don't send item updates for cancelled drops + } + + public EntityItem dropWithContext(ItemStack originalItemStack, boolean flag, boolean flag1, boolean dropAll) { // Necrozma - Don't send item updates for cancelled drops + if (originalItemStack == null) { + return null; + } + + // Necrozma start - Don't send item updates for cancelled drops + ItemStack itemstack = originalItemStack.cloneItemStack(); + if (flag1 && !dropAll) { + itemstack.count = 1; + } + // Necrozma end + + if (itemstack.count == 0) { + return null; + } + + double d0 = this.locY - 0.30000001192092896D + (double) this.getHeadHeight(); + EntityItem entityitem = new EntityItem(this.world, this.locX, d0, this.locZ, itemstack); + entityitem.owner = this; + entityitem.a(40); + if (flag1) { + entityitem.c(this.getName()); + } + + float f; + float f1; + + if (flag) { + f = random.nextFloat() * 0.5F; + f1 = random.nextFloat() * 3.1415927F * 2.0F; + entityitem.motX = (-MathHelper.sin(f1) * f); + entityitem.motZ = (MathHelper.cos(f1) * f); + entityitem.motY = 0.20000000298023224D; + } else { + f = 0.3F; + entityitem.motX = (-MathHelper.sin(this.yaw / 180.0F * 3.1415927F) + * MathHelper.cos(this.pitch / 180.0F * 3.1415927F) * f); + entityitem.motZ = (MathHelper.cos(this.yaw / 180.0F * 3.1415927F) + * MathHelper.cos(this.pitch / 180.0F * 3.1415927F) * f); + entityitem.motY = (-MathHelper.sin(this.pitch / 180.0F * 3.1415927F) * f + 0.1F); + f1 = random.nextFloat() * 3.1415927F * 2.0F; + f = 0.02F * random.nextFloat(); + entityitem.motX += Math.cos(f1) * (double) f; + entityitem.motY += ((random.nextFloat() - random.nextFloat()) * 0.1F); + entityitem.motZ += Math.sin(f1) * (double) f; + } + + // CraftBukkit start - fire PlayerDropItemEvent + Player player = (Player) this.getBukkitEntity(); + org.bukkit.entity.Item drop = (org.bukkit.entity.Item) entityitem.getBukkitEntity(); // Rivals fix - strong reference + + PlayerDropItemEvent event = new PlayerDropItemEvent(player, drop); + this.world.getServer().getPluginManager().callEvent(event); + + // Necrozma start - Don't send item updates for cancelled drops + if (event.isCancelled()) { + if (!flag1) { + player.getInventory().addItem(drop.getItemStack()); + } + return null; + } else if (flag1) { + this.inventory.splitStack(this.inventory.itemInHandIndex, dropAll && this.inventory.getItemInHand() != null ? this.inventory.getItemInHand().count : 1); + } + // Necrozma end + // CraftBukkit end + + this.a(entityitem); + if (flag1) { + this.b(StatisticList.v); + } + return entityitem; + + } + + protected void a(EntityItem entityitem) { + this.world.addEntity(entityitem); + } + + public float a(Block block) { + float f = this.inventory.a(block); + + if (f > 1.0F) { + int i = EnchantmentManager.getDigSpeedEnchantmentLevel(this); + ItemStack itemstack = this.inventory.getItemInHand(); + + if (i > 0 && itemstack != null) { + f += (float) (i * i + 1); + } + } + + if (this.hasEffect(MobEffectList.FASTER_DIG)) { + f *= 1.0F + (float) (this.getEffect(MobEffectList.FASTER_DIG).getAmplifier() + 1) * 0.2F; + } + + if (this.hasEffect(MobEffectList.SLOWER_DIG)) { + float f1; + + switch (this.getEffect(MobEffectList.SLOWER_DIG).getAmplifier()) { + case 0: + f1 = 0.3F; + break; + + case 1: + f1 = 0.09F; + break; + + case 2: + f1 = 0.0027F; + break; + + case 3: + default: + f1 = 8.1E-4F; + } + + f *= f1; + } + + if (this.a(Material.WATER) && !EnchantmentManager.j(this)) { + f /= 5.0F; + } + + if (!this.onGround) { + f /= 5.0F; + } + + return f; + } + + public boolean b(Block block) { + return this.inventory.b(block); + } + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + this.uniqueID = a(this.bH); + + NBTTagList nbttaglist = nbttagcompound.getList("Inventory", 10); + inventory.b(nbttaglist); + inventory.itemInHandIndex = nbttagcompound.getInt("SelectedItemSlot"); + + sleeping = nbttagcompound.getBoolean("Sleeping"); + sleepTicks = nbttagcompound.getShort("SleepTimer"); + exp = nbttagcompound.getFloat("XpP"); + expLevel = nbttagcompound.getInt("XpLevel"); + expTotal = nbttagcompound.getInt("XpTotal"); + f = nbttagcompound.getInt("XpSeed"); + if (f == 0) { + f = random.nextInt(); + } + + setScore(nbttagcompound.getInt("Score")); + if (sleeping) { + bx = new BlockPosition(this); + a(true, true, false); + } + + // CraftBukkit start + spawnWorld = nbttagcompound.getString("SpawnWorld"); + if ("".equals(spawnWorld)) { + spawnWorld = world.getServer().getWorlds().get(0).getName(); + } + // CraftBukkit end + + if (nbttagcompound.hasKeyOfType("SpawnX", 99) && nbttagcompound.hasKeyOfType("SpawnY", 99) + && nbttagcompound.hasKeyOfType("SpawnZ", 99)) { + c = new BlockPosition(nbttagcompound.getInt("SpawnX"), nbttagcompound.getInt("SpawnY"), + nbttagcompound.getInt("SpawnZ")); + d = nbttagcompound.getBoolean("SpawnForced"); + } + + foodData.a(nbttagcompound); + abilities.b(nbttagcompound); + if (nbttagcompound.hasKeyOfType("EnderItems", 9)) { + enderChest.a(nbttagcompound.getList("EnderItems", 10)); + } + + } + + public void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + nbttagcompound.set("Inventory", this.inventory.a(new NBTTagList())); + nbttagcompound.setInt("SelectedItemSlot", this.inventory.itemInHandIndex); + nbttagcompound.setBoolean("Sleeping", this.sleeping); + nbttagcompound.setShort("SleepTimer", (short) this.sleepTicks); + nbttagcompound.setFloat("XpP", this.exp); + nbttagcompound.setInt("XpLevel", this.expLevel); + nbttagcompound.setInt("XpTotal", this.expTotal); + nbttagcompound.setInt("XpSeed", this.f); + nbttagcompound.setInt("Score", this.getScore()); + if (this.c != null) { + nbttagcompound.setInt("SpawnX", this.c.getX()); + nbttagcompound.setInt("SpawnY", this.c.getY()); + nbttagcompound.setInt("SpawnZ", this.c.getZ()); + nbttagcompound.setBoolean("SpawnForced", this.d); + } + + this.foodData.b(nbttagcompound); + this.abilities.a(nbttagcompound); + nbttagcompound.set("EnderItems", this.enderChest.h()); + ItemStack itemstack = this.inventory.getItemInHand(); + + if (itemstack != null && itemstack.getItem() != null) { + nbttagcompound.set("SelectedItem", itemstack.save(new NBTTagCompound())); + } + nbttagcompound.setString("SpawnWorld", spawnWorld); // CraftBukkit - fixes bed spawns for multiworld worlds + + } + + public boolean damageEntity(DamageSource damagesource, float f) { + if (isInvulnerable(damagesource) || abilities.isInvulnerable && !damagesource.ignoresInvulnerability()) + return false; + ticksFarFromPlayer = 0; + if (getHealth() <= 0.0F) + return false; + if (isSleeping()) + a(true, true, false); + if (damagesource.r()) { + if (world.getDifficulty() == EnumDifficulty.PEACEFUL) + return false; + else if (world.getDifficulty() == EnumDifficulty.EASY) + f = f / 2.0F + 1.0F; + else if (world.getDifficulty() == EnumDifficulty.HARD) + f = f * 3.0F / 2.0F; + } + return super.damageEntity(damagesource, f); + } + + public boolean a(EntityHuman entityhuman) { + // CraftBukkit start - Change to check OTHER player's scoreboard team according + // to API + // To summarize this method's logic, it's "Can parameter hurt this" + org.bukkit.scoreboard.Team team; + if (entityhuman instanceof EntityPlayer) { + EntityPlayer thatPlayer = (EntityPlayer) entityhuman; + team = thatPlayer.getBukkitEntity().getScoreboard().getPlayerTeam(thatPlayer.getBukkitEntity()); + } else { + // This should never be called, but is implemented anyway + org.bukkit.OfflinePlayer thisPlayer = entityhuman.world.getServer().getOfflinePlayer(entityhuman.getName()); + team = entityhuman.world.getServer().getScoreboardManager().getMainScoreboard().getPlayerTeam(thisPlayer); + } + if (team == null || team.allowFriendlyFire()) { + return true; + } + + if (this instanceof EntityPlayer) { + return !team.hasPlayer(((EntityPlayer) this).getBukkitEntity()); + } + return !team.hasPlayer(this.world.getServer().getOfflinePlayer(this.getName())); + // CraftBukkit end + } + + protected void damageArmor(float f) { + this.inventory.a(f); + } + + public int br() { + return this.inventory.m(); + } + + public float bY() { + int i = 0; + for (ItemStack itemstack : inventory.armor) { + if (itemstack != null) { + ++i; + } + } + + return (float) i / (float) this.inventory.armor.length; + } + + public void openSign(TileEntitySign tileentitysign) { + } + + public void a(CommandBlockListenerAbstract commandblocklistenerabstract) { + } + + public void openTrade(IMerchant imerchant) { + } + + public void openContainer(IInventory iinventory) { + } + + public void openHorseInventory(EntityHorse entityhorse, IInventory iinventory) { + } + + public void openTileEntity(ITileEntityContainer itileentitycontainer) { + } + + public void openBook(ItemStack itemstack) { + } + + public boolean u(Entity entity) { + if (this.isSpectator()) { + if (entity instanceof IInventory) { + this.openContainer((IInventory) entity); + } + + return false; + } else { + ItemStack itemstack = this.bZ(); + ItemStack itemstack1 = itemstack != null ? itemstack.cloneItemStack() : null; + + if (!entity.e(this)) { + if (itemstack != null && entity instanceof EntityLiving) { + if (this.abilities.canInstantlyBuild) { + itemstack = itemstack1; + } + + if (itemstack.a(this, (EntityLiving) entity)) { + // CraftBukkit - bypass infinite items; <= 0 -> == 0 + if (itemstack.count == 0 && !this.abilities.canInstantlyBuild) { + this.ca(); + } + + return true; + } + } + + return false; + } else { + if (itemstack != null && itemstack == this.bZ()) { + if (itemstack.count <= 0 && !this.abilities.canInstantlyBuild) { + this.ca(); + } else if (itemstack.count < itemstack1.count && this.abilities.canInstantlyBuild) { + itemstack.count = itemstack1.count; + } + } + + return true; + } + } + } + + public ItemStack bZ() { + return this.inventory.getItemInHand(); + } + + public void ca() { + this.inventory.setItem(this.inventory.itemInHandIndex, null); + } + + public double am() { + return -0.35D; + } + + + // Rivals - block check event + protected boolean checkBlock() { + if (this instanceof EntityPlayer) { + PlayerCanBlockEvent event = new PlayerCanBlockEvent(((EntityPlayer) this).getBukkitEntity()); + Bukkit.getPluginManager().callEvent(event); + return !event.isCancelled(); + } else { + return true; + } + } + + // Rivals - block check event + private boolean checkCrit() { + if (this instanceof EntityPlayer) { + PlayerCanCritEvent event = new PlayerCanCritEvent(((EntityPlayer) this).getBukkitEntity()); + Bukkit.getPluginManager().callEvent(event); + return !event.isCancelled(); + } else { + return true; + } + } + + public void attack(Entity entity) { + if (!entity.aD()) { + return; + } + + if (entity.l(this)) { + return; + } + + + float baseAttackDamage = (float) this.getAttributeInstance(GenericAttributes.ATTACK_DAMAGE).getValue(); + float additionalEnchantmentDamage; + + if (entity instanceof EntityLiving) { + additionalEnchantmentDamage = EnchantmentManager.a(this.bA(), ((EntityLiving) entity).getMonsterType()); + } else { + additionalEnchantmentDamage = EnchantmentManager.a(this.bA(), EnumMonsterType.UNDEFINED); + } + + if (!(baseAttackDamage > 0.0F) && !(additionalEnchantmentDamage > 0.0F)) { + return; + } + + boolean isCrit = !world.paperSpigotConfig.disablePlayerCrits && this.fallDistance > 0.0F && !this.onGround && !this.k_() && !this.V() && !this.hasEffect(MobEffectList.BLINDNESS) && this.vehicle == null && entity instanceof EntityLiving; // PaperSpigot + + if (isCrit && baseAttackDamage > 0.0F && checkCrit()) { // Rivals bukkit event check + baseAttackDamage *= AzuriteConfig.critDamageModifier.getValue(); + } + + baseAttackDamage += additionalEnchantmentDamage; + boolean wasPutOnFire = false; + int fireAspectEnchantmentLevel = EnchantmentManager.getFireAspectEnchantmentLevel(this); + + if (entity instanceof EntityLiving && fireAspectEnchantmentLevel > 0 && !entity.isBurning()) { + // CraftBukkit start - Call a combust event when somebody hits with a fire enchanted item + EntityCombustByEntityEvent combustEvent = new EntityCombustByEntityEvent(this.getBukkitEntity(), entity.getBukkitEntity(), 1); + org.bukkit.Bukkit.getPluginManager().callEvent(combustEvent); + + if (!combustEvent.isCancelled()) { + wasPutOnFire = true; + entity.setOnFire(combustEvent.getDuration()); + } + // CraftBukkit end + } + + double victimMotX = entity.motX; + double victimMotY = entity.motY; + double victimMotZ = entity.motZ; + boolean damageSuccess = entity.damageEntity(DamageSource.playerAttack(this).setCrit(isCrit), baseAttackDamage); + + if (damageSuccess) { + if (!entity.disableKnockback) { // Rivals + if (AzuriteConfig.overrideDefaultKnockback.getValue() && (AzuriteConfig.nonPlayerEntitiesOverrideDefaultKnockback.getValue() || entity instanceof EntityPlayer)) { + if (entity.velocityChanged) { + Knockback profile = entity.getKnockbackProfile(); + KnockbackType type = profile.getKnockbackType(); + + // Azurite - When auto respawn is enabled we need to make sure the last velocity the player receives is 0 + if (entity.sendKnockbackRespawn && entity instanceof EntityPlayer) { + EntityPlayer victimPlayer = (EntityPlayer) entity; + Vector vector = new Vector(0, 0, 0); + PlayerVelocityEvent event = new PlayerVelocityEvent(victimPlayer.getBukkitEntity(), vector); + this.world.getServer().getPluginManager().callEvent(event); + if (!event.isCancelled()) { + victimPlayer.getBukkitEntity().setVelocityDirect(event.getVelocity()); + victimPlayer.playerConnection.sendPacket(new PacketPlayOutEntityVelocity(entity)); + entity.velocityChanged = false; + } + entity.motX = victimMotX; + entity.motY = victimMotY; + entity.motZ = victimMotZ; + entity.sendKnockbackRespawn = false; + + } else { + if (type == KnockbackType.ADVANCED) { + AdvancedKnockback knockback = profile.advancedKnockback; + + if (knockback.horizontalInherit.getValue()) { + double entityVelX = entity.motX * knockback.horizontalFriction.getValue(); + double entityVelZ = entity.motZ * knockback.horizontalFriction.getValue(); + entity.motX = entityVelX + Math.sin(Math.toRadians(yaw)) * -1.0F; + entity.motZ = entityVelZ + Math.cos(Math.toRadians(yaw)); + + } else { + entity.motX = Math.sin(Math.toRadians(getHeadRotation())) * -1.0F; + entity.motZ = Math.cos(Math.toRadians(getHeadRotation())); + } + + boolean onePointSeven = knockback.enableOnePointSeven.getValue() && + getBukkitEntity().getLocation().getDirection().dot(entity.getBukkitEntity().getLocation().getDirection()) > 0.1 && + entity.isSprinting(); // Azurite - Improve 1.7 KB + + entity.motX *= (onePointSeven ? knockback.onePointSevenHorizontal.getValue() : knockback.horizontal.getValue()); + entity.motZ *= (onePointSeven ? knockback.onePointSevenHorizontal.getValue() : knockback.horizontal.getValue()); + + if (knockback.verticalInherit.getValue()) { + double entityVelY = entity.motY * knockback.verticalFriction.getValue(); + entity.motY = entityVelY + knockback.vertical.getValue(); + + } else { + entity.motY = knockback.vertical.getValue(); + } + + if (entity.onGround) { + entity.motX *= knockback.horizontalOnGround.getValue(); + entity.motY *= knockback.verticalOnGround.getValue(); + entity.motZ *= knockback.horizontalOnGround.getValue(); + + } else { + entity.motY *= knockback.verticalInAir.getValue(); + } + + int enchLvl = EnchantmentManager.getEnchantmentLevel(Enchantment.KNOCKBACK.id, this.inventory.getItemInHand()) + 1; + if (enchLvl > 0) { + entity.motX *= enchLvl; + entity.motZ *= enchLvl; + entity.motX /= knockback.horizontalKnockbackDeduction.getValue(); + entity.motZ /= knockback.horizontalKnockbackDeduction.getValue(); + } + + if (shouldDealSprintKnockback) { + entity.motX *= knockback.horizontalSprinting.getValue(); + entity.motY *= knockback.verticalSprinting.getValue(); + entity.motZ *= knockback.horizontalSprinting.getValue(); + shouldDealSprintKnockback = false; + } + + if (isSprinting()) { + motX *= knockback.slowdown.getValue(); + motZ *= knockback.slowdown.getValue(); + shouldDealSprintKnockback = false; + + if (knockback.cancelSprint.getValue()) { + setSprinting(false); + } + } + + if (profile.comboMode.getValue()) { + double yOff = entity.locY - locY; + + if (yOff > profile.comboHeight.getValue()) + ticksDown = MinecraftServer.currentTick; + + if (yOff > profile.comboHeight.getValue() || MinecraftServer.currentTick - ticksDown < profile.comboTicks.getValue()) { + entity.motY = profile.comboVelocity.getValue(); + } + } + + double yOff = entity.locY - locY; + + if (knockback.enableVerticalLimit.getValue()) { + if (yOff > knockback.verticalLimit.getValue()) { + entity.motY = 0; + } + } + + if (entity instanceof EntityPlayer) { + EntityPlayer victimPlayer = (EntityPlayer) entity; + PlayerVelocityEvent event = new PlayerVelocityEvent(victimPlayer.getBukkitEntity(), entity.getBukkitEntity().getVelocity()); + this.world.getServer().getPluginManager().callEvent(event); + if (!event.isCancelled()) { + victimPlayer.getBukkitEntity().setVelocityDirect(event.getVelocity()); + ((EntityPlayer) entity).playerConnection.sendPacket(new PacketPlayOutEntityVelocity(entity)); + } + entity.velocityChanged = false; + } + + entity.motX = victimMotX; + entity.motY = victimMotY; + entity.motZ = victimMotZ; + + } else if (type == KnockbackType.SIMPLE) { // Always true if not advanced, but can be false when we add more types + SimpleKnockback knockback = profile.simpleKnockback; + int enchLvl = EnchantmentManager.a(this) + 1; + boolean onePointSeven = knockback.enableOnePointSeven.getValue() && + getBukkitEntity().getLocation().getDirection().dot(entity.getBukkitEntity().getLocation().getDirection()) > 0.1 && + entity.isSprinting(); + + entity.g( + -MathHelper.sin(this.yaw * 3.1415927F / 180.0F) * (float) enchLvl * knockback.extraHorizontal.getValue(), + knockback.extraVertical.getValue(), + MathHelper.cos(this.yaw * 3.1415927F / 180.0F) * (float) enchLvl * knockback.extraHorizontal.getValue() + ); + + if (isSprinting()) { + motX *= knockback.slowdown.getValue(); + motZ *= knockback.slowdown.getValue(); + setSprinting(false); + } + + if (onePointSeven) { + entity.motX *= knockback.onePointSevenMultiplier.getValue(); + entity.motZ *= knockback.onePointSevenMultiplier.getValue(); + } + + if (entity.velocityChanged) { + if (entity instanceof EntityPlayer) { + EntityPlayer victimPlayer = (EntityPlayer) entity; + PlayerVelocityEvent event = new PlayerVelocityEvent(victimPlayer.getBukkitEntity(), entity.getBukkitEntity().getVelocity()); + this.world.getServer().getPluginManager().callEvent(event); + if (!event.isCancelled()) { + victimPlayer.getBukkitEntity().setVelocityDirect(event.getVelocity()); + ((EntityPlayer) entity).playerConnection.sendPacket(new PacketPlayOutEntityVelocity(entity)); + } + entity.velocityChanged = false; + } + + entity.motX = victimMotX; + entity.motY = victimMotY; + entity.motZ = victimMotZ; + } + } else if (type == KnockbackType.CONSTANT) { + entity.velocityChanged = false; + + ConstantKnockback knockback = profile.constantKnockback; + + // Get the positions + double victimX = entity.locX; + double victimZ = entity.locZ; + + double playerX = this.locX; + double playerZ = this.locZ; + + // Calculate the direction vector from player to victim + double dirX = victimX - playerX; + double dirZ = victimZ - playerZ; + + // Normalize the horizontal direction vector + double distance = Math.sqrt(dirX * dirX + dirZ * dirZ); + if (distance > 0) { + dirX /= distance; + dirZ /= distance; + } + + double strengthModifier = knockback.getHorizontal(); + + if (shouldDealSprintKnockbackForConstantKnockback) { + shouldDealSprintKnockbackForConstantKnockback = false; + strengthModifier = knockback.getHorizontalSprintReset(); + } + + dirX *= strengthModifier; + dirZ *= strengthModifier; + + if (knockback.getYawModifier() > 0) { + double addX = (-MathHelper.sin(this.yaw * (float) Math.PI / 180.0F)) * knockback.getYawModifier(); + double addZ = MathHelper.cos(this.yaw * (float) Math.PI / 180.0F) * knockback.getYawModifier(); + + dirX += addX; + dirZ += addZ; + } + + // Calculate vertical + int longAirTicks; // Add compensation ticks :P + + if (entity instanceof EntityPlayer) { + EntityPlayer victimPlayer = (EntityPlayer) entity; + longAirTicks = victimPlayer.airTicks + victimPlayer.getEatCompensationTicks(); + } else { + longAirTicks = entity.airTicks; // No calculation for non player entiites yet + } + double vertical = longAirTicks >= 20 && !this.inLava && !this.inWater ? knockback.getVerticalLongAir() : knockback.getVertical(); + + // Reset motion values as we always send the same constant kb + entity.motX = 0.0D; + entity.motY = 0.0D; + entity.motZ = 0.0D; + + // Beanes - remove 1 from fall distance to fix high ping players taking fall dmg + entity.fallDistance = Math.max(0.0F, entity.fallDistance - 1.0F); + + if (entity instanceof EntityPlayer) { + EntityPlayer victimPlayer = (EntityPlayer) entity; + PlayerVelocityEvent event = new PlayerVelocityEvent(victimPlayer.getBukkitEntity(), entity.getBukkitEntity().getVelocity()); + this.world.getServer().getPluginManager().callEvent(event); + if (!event.isCancelled()) { + victimPlayer.getBukkitEntity().setVelocityDirect(event.getVelocity()); + ((EntityPlayer) entity).playerConnection.sendPacket(new PacketPlayOutEntityVelocity(entity.getId(), dirX, vertical, dirZ)); + } + entity.velocityChanged = false; + } + } + } + } + } else { + // Mojang sprint extra kb + int kbLevel = EnchantmentManager.a(this); + + if (isSprinting()) + kbLevel++; + if (kbLevel > 0) { + entity.g( + -MathHelper.sin(this.yaw * (float) Math.PI / 180.0F) * (float) kbLevel * 0.5F, + 0.1D, + MathHelper.cos(this.yaw * (float) Math.PI / 180.0F) * (float) kbLevel * 0.5F + ); + + motX *= 0.6D; + motZ *= 0.6D; + setSprinting(false); + } + + if (entity instanceof EntityPlayer) { + EntityPlayer victim = (EntityPlayer) entity; + if (victim.velocityChanged) { + PlayerVelocityEvent event = new PlayerVelocityEvent(victim.getBukkitEntity(), victim.getBukkitEntity().getVelocity()); + this.world.getServer().getPluginManager().callEvent(event); + if (!event.isCancelled()) { + victim.getBukkitEntity().setVelocityDirect(event.getVelocity()); + victim.playerConnection.sendPacket(new PacketPlayOutEntityVelocity(victim)); + } + victim.velocityChanged = false; + victim.motX = victimMotX; + victim.motY = victimMotY; + victim.motZ = victimMotZ; + } + } + } + } + + if (isCrit) { + this.b(entity, this); // Send critical animation, Beanes: pretty sure clientside this is already handled, not sure if the server should send this too + } + + if (additionalEnchantmentDamage > 0.0F) { + this.c(entity, this); // Send enchantment particle + } + + if (baseAttackDamage >= 18.0F) { + this.b(AchievementList.F); // Give overkill achievement + } + + this.p(entity); // Set last attacker + if (entity instanceof EntityLiving) { + EnchantmentManager.a((EntityLiving) entity, this); // Apply thorn + } + + EnchantmentManager.b(this, entity); + ItemStack itemstack = this.bZ(); + Object object = entity; + + if (entity instanceof EntityComplexPart) { + IComplex icomplex = ((EntityComplexPart) entity).owner; + + if (icomplex instanceof EntityLiving) { + object = icomplex; + } + } + + if (itemstack != null && object instanceof EntityLiving) { + itemstack.a((EntityLiving) object, this); + // CraftBukkit - bypass infinite items; <= 0 -> == 0 + if (itemstack.count == 0) { + this.ca(); + } + } + + if (entity instanceof EntityLiving) { + this.a(StatisticList.w, Math.round(baseAttackDamage * 10.0F)); + if (fireAspectEnchantmentLevel > 0) { + // CraftBukkit start - Call a combust event when somebody hits with a fire enchanted item + EntityCombustByEntityEvent combustEvent = new EntityCombustByEntityEvent(this.getBukkitEntity(), entity.getBukkitEntity(), fireAspectEnchantmentLevel * 4); + org.bukkit.Bukkit.getPluginManager().callEvent(combustEvent); + + if (!combustEvent.isCancelled()) { + entity.setOnFire(combustEvent.getDuration()); + } + // CraftBukkit end + } + } + + this.applyExhaustion(world.spigotConfig.combatExhaustion); // Spigot - Change to use configurable value + } else if (wasPutOnFire) { + entity.extinguish(); + } + } + + public void sendVelocityPacket(double victimMotX, double victimMotY, double victimMotZ, boolean resetFallDistance) { + EntityPlayer player = (EntityPlayer) this; + PlayerVelocityEvent event = new PlayerVelocityEvent(player.getBukkitEntity(), player.getBukkitEntity().getVelocity()); + world.getServer().getPluginManager().callEvent(event); + + if (!event.isCancelled()) { + player.getBukkitEntity().setVelocityDirect(event.getVelocity(), resetFallDistance); + player.playerConnection.sendPacket(new PacketPlayOutEntityVelocity(this)); + } + + velocityChanged = false; + motX = victimMotX; + motY = victimMotY; + motZ = victimMotZ; + } + + public void b(Entity entity) { + } + + public void b(Entity entity, EntityHuman attacker) { + } + + public void c(Entity entity) { + } + + public void c(Entity entity, EntityHuman attacker) { + } + + public void setSprinting(boolean flag) { + if (flag) { + if (!isSprinting()) + shouldDealSprintKnockback = true; + } else { + shouldDealSprintKnockback = false; + } + + super.setSprinting(flag); + } + + public void die() { + super.die(); + this.defaultContainer.b(this); + + if (this.activeContainer != null) { + this.activeContainer.b(this); + } + } + + public boolean inBlock() { + return !this.sleeping && super.inBlock(); + } + + public GameProfile getProfile() { + return this.bH; + } + + public EntityHuman.EnumBedResult a(BlockPosition blockposition) { + if (this.isSleeping() || !this.isAlive()) { + return EntityHuman.EnumBedResult.OTHER_PROBLEM; + } + + if (!this.world.worldProvider.d()) { + return EntityHuman.EnumBedResult.NOT_POSSIBLE_HERE; + } + + if (this.world.w()) { + return EntityHuman.EnumBedResult.NOT_POSSIBLE_NOW; + } + + if (Math.abs(this.locX - blockposition.getX()) > 3.0D + || Math.abs(this.locY - blockposition.getY()) > 2.0D + || Math.abs(this.locZ - blockposition.getZ()) > 3.0D) { + return EntityHuman.EnumBedResult.TOO_FAR_AWAY; + } + + double d0 = 8.0D; + double d1 = 5.0D; + List list = this.world.a(EntityMonster.class, + new AxisAlignedBB(blockposition.getX() - d0, blockposition.getY() - d1, + blockposition.getZ() - d0, blockposition.getX() + d0, + blockposition.getY() + d1, blockposition.getZ() + d0)); + + if (!list.isEmpty()) { + return EntityHuman.EnumBedResult.NOT_SAFE; + } + + if (this.au()) { + this.mount(null); + } + + // CraftBukkit start - fire PlayerBedEnterEvent + if (this.getBukkitEntity() instanceof Player) { + Player player = (Player) this.getBukkitEntity(); + org.bukkit.block.Block bed = this.world.getWorld().getBlockAt(blockposition.getX(), blockposition.getY(), + blockposition.getZ()); + + PlayerBedEnterEvent event = new PlayerBedEnterEvent(player, bed); + this.world.getServer().getPluginManager().callEvent(event); + + if (event.isCancelled()) { + return EnumBedResult.OTHER_PROBLEM; + } + } + // CraftBukkit end + + this.setSize(0.2F, 0.2F); + if (this.world.isLoaded(blockposition)) { + EnumDirection enumdirection = this.world.getType(blockposition) + .get(BlockDirectional.FACING); + float f = 0.5F; + float f1 = 0.5F; + + switch (EntityHuman.SyntheticClass_1.a[enumdirection.ordinal()]) { + case 1: + f1 = 0.9F; + break; + + case 2: + f1 = 0.1F; + break; + + case 3: + f = 0.1F; + break; + + case 4: + f = 0.9F; + } + + this.a(enumdirection); + this.setPosition(((float) blockposition.getX() + f), + ((float) blockposition.getY() + 0.6875F), ((float) blockposition.getZ() + f1)); + } else { + this.setPosition(((float) blockposition.getX() + 0.5F), + ((float) blockposition.getY() + 0.6875F), ((float) blockposition.getZ() + 0.5F)); + } + + this.sleeping = true; + this.sleepTicks = 0; + this.bx = blockposition; + this.motX = this.motZ = this.motY = 0.0D; + this.world.everyoneSleeping(); + return EntityHuman.EnumBedResult.OK; + } + + private void a(EnumDirection enumdirection) { + this.by = 0.0F; + this.bz = 0.0F; + switch (EntityHuman.SyntheticClass_1.a[enumdirection.ordinal()]) { + case 1: + this.bz = -1.8F; + break; + + case 2: + this.bz = 1.8F; + break; + + case 3: + this.by = 1.8F; + break; + + case 4: + this.by = -1.8F; + } + + } + + public void a(boolean flag, boolean flag1, boolean flag2) { + this.setSize(0.6F, 1.8F); + IBlockData iblockdata = this.world.getType(this.bx); + + if (this.bx != null && iblockdata.getBlock() == Blocks.BED) { + this.world.setTypeAndData(this.bx, iblockdata.set(BlockBed.OCCUPIED, false), 4); + BlockPosition blockposition = BlockBed.a(this.world, this.bx, 0); + + if (blockposition == null) { + blockposition = this.bx.up(); + } + + this.setPosition(((float) blockposition.getX() + 0.5F), + ((float) blockposition.getY() + 0.1F), ((float) blockposition.getZ() + 0.5F)); + } + + this.sleeping = false; + if (flag1) { + this.world.everyoneSleeping(); + } + + // CraftBukkit start - fire PlayerBedLeaveEvent + if (this.getBukkitEntity() instanceof Player) { + Player player = (Player) this.getBukkitEntity(); + + org.bukkit.block.Block bed; + BlockPosition blockposition = this.bx; + if (blockposition != null) { + bed = this.world.getWorld().getBlockAt(blockposition.getX(), blockposition.getY(), + blockposition.getZ()); + } else { + bed = this.world.getWorld().getBlockAt(player.getLocation()); + } + + PlayerBedLeaveEvent event = new PlayerBedLeaveEvent(player, bed); + this.world.getServer().getPluginManager().callEvent(event); + } + // CraftBukkit end + + this.sleepTicks = flag ? 0 : 100; + if (flag2) { + this.setRespawnPosition(this.bx, false); + } + + } + + private boolean p() { + return this.world.getType(this.bx).getBlock() == Blocks.BED; + } + + public boolean isSleeping() { + return this.sleeping; + } + + public boolean isDeeplySleeping() { + return this.sleeping && this.sleepTicks >= 100; + } + + public void b(IChatBaseComponent ichatbasecomponent) { + } + + public BlockPosition getBed() { + return this.c; + } + + public boolean isRespawnForced() { + return this.d; + } + + public void setRespawnPosition(BlockPosition blockposition, boolean flag) { + if (blockposition != null) { + this.c = blockposition; + this.d = flag; + this.spawnWorld = this.world.worldData.getName(); // CraftBukkit + } else { + this.c = null; + this.d = false; + this.spawnWorld = ""; // CraftBukkit + } + } + + public void b(Statistic statistic) { + this.a(statistic, 1); + } + + public void a(Statistic statistic, int i) { + } + + public void a(Statistic statistic) { + } + + public void bF() { + super.bF(); + this.b(StatisticList.u); + if (this.isSprinting()) { + this.applyExhaustion(world.spigotConfig.sprintExhaustion); // Spigot - Change to use configurable value + } else { + this.applyExhaustion(world.spigotConfig.walkExhaustion); // Spigot - Change to use configurable value + } + + } + + public void g(float f, float f1) { + double d0 = this.locX; + double d1 = this.locY; + double d2 = this.locZ; + + if (this.abilities.isFlying && this.vehicle == null) { + double d3 = this.motY; + float f2 = this.aM; + + this.aM = this.abilities.a() * (float) (this.isSprinting() ? 2 : 1); + super.g(f, f1); + this.motY = d3 * 0.6D; + this.aM = f2; + } else { + super.g(f, f1); + } + + this.checkMovement(this.locX - d0, this.locY - d1, this.locZ - d2); + } + + public float bI() { + return (float) this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).getValue(); + } + + public void sendPacket(Packet packet) { + PlayerConnection connection = ((EntityPlayer) this).playerConnection; + if (connection != null) + connection.sendPacket(packet); + } + + public void checkMovement(double d0, double d1, double d2) { + if (this.vehicle == null) { + int i; + + if (this.a(Material.WATER)) { + i = Math.round(MathHelper.sqrt(d0 * d0 + d1 * d1 + d2 * d2) * 100.0F); + if (i > 0) { + this.a(StatisticList.p, i); + this.applyExhaustion(world.paperSpigotConfig.playerSwimmingExhaustion * (float) i * 0.01F); + } + } else if (this.V()) { + i = Math.round(MathHelper.sqrt(d0 * d0 + d2 * d2) * 100.0F); + if (i > 0) { + this.a(StatisticList.l, i); + this.applyExhaustion(world.paperSpigotConfig.playerSwimmingExhaustion * (float) i * 0.01F); + } + } else if (this.k_()) { + if (d1 > 0.0D) { + this.a(StatisticList.n, (int) Math.round(d1 * 100.0D)); + } + } else if (this.onGround) { + i = Math.round(MathHelper.sqrt(d0 * d0 + d2 * d2) * 100.0F); + if (i > 0) { + this.a(StatisticList.i, i); + if (this.isSprinting()) { + this.a(StatisticList.k, i); + this.applyExhaustion(0.099999994F * (float) i * 0.01F); + } else { + if (this.isSneaking()) { + this.a(StatisticList.j, i); + } + this.applyExhaustion(0.01F * (float) i * 0.01F); + } + } + } else { + i = Math.round(MathHelper.sqrt(d0 * d0 + d2 * d2) * 100.0F); + if (i > 25) { + this.a(StatisticList.o, i); + } + } + } + } + + private void l(double d0, double d1, double d2) { + if (this.vehicle != null) { + int i = Math.round(MathHelper.sqrt(d0 * d0 + d1 * d1 + d2 * d2) * 100.0F); + + if (i > 0) { + if (this.vehicle instanceof EntityMinecartAbstract) { + this.a(StatisticList.q, i); + if (this.e == null) { + this.e = new BlockPosition(this); + } else if (this.e.c(MathHelper.floor(this.locX), MathHelper.floor(this.locY), MathHelper.floor(this.locZ)) >= 1000000.0D) { + this.b(AchievementList.q); + } + } else if (this.vehicle instanceof EntityBoat) { + this.a(StatisticList.r, i); + } else if (this.vehicle instanceof EntityPig) { + this.a(StatisticList.s, i); + } else if (this.vehicle instanceof EntityHorse) { + this.a(StatisticList.t, i); + } + } + } + } + + public void e(float f, float f1) { + if (!this.abilities.canFly) { + if (f >= 2.0F) { + this.a(StatisticList.m, (int) Math.round((double) f * 100.0D)); + } + super.e(f, f1); + } + } + + protected void X() { + if (!this.isSpectator()) { + super.X(); + } + + } + + protected String n(int i) { + return i > 4 ? "game.player.hurt.fall.big" : "game.player.hurt.fall.small"; + } + + public void a(EntityLiving entityliving) { + if (entityliving instanceof IMonster) { + this.b(AchievementList.s); + } + + EntityTypes.MonsterEggInfo entitytypes_monsteregginfo = EntityTypes.eggInfo.get(EntityTypes.a(entityliving)); + + if (entitytypes_monsteregginfo != null) { + this.b(entitytypes_monsteregginfo.killEntityStatistic); + } + } + + public void aA() { + if (!this.abilities.isFlying) { + super.aA(); + } + } + + public ItemStack q(int i) { + return this.inventory.e(i); + } + + public void giveExp(int i) { + this.addScore(i); + int j = Integer.MAX_VALUE - this.expTotal; + + if (i > j) { + i = j; + } + + this.exp += (float) i / (float) this.getExpToLevel(); + + for (this.expTotal += i; this.exp >= 1.0F; this.exp /= (float) this.getExpToLevel()) { + this.exp = (this.exp - 1.0F) * (float) this.getExpToLevel(); + this.levelDown(1); + } + + } + + public int cj() { + return this.f; + } + + public void enchantDone(int i) { + this.expLevel -= i; + if (this.expLevel < 0) { + this.expLevel = 0; + this.exp = 0.0F; + this.expTotal = 0; + } + + this.f = random.nextInt(); + } + + public void levelDown(int i) { + this.expLevel += i; + if (this.expLevel < 0) { + this.expLevel = 0; + this.exp = 0.0F; + this.expTotal = 0; + } + + if (i > 0 && this.expLevel % 5 == 0 && (float) this.i < (float) this.ticksLived - 100.0F) { + float f = this.expLevel > 30 ? 1.0F : (float) this.expLevel / 30.0F; + + this.world.makeSound(this, "random.levelup", f * 0.75F, 1.0F); + this.i = this.ticksLived; + } + + } + + public int getExpToLevel() { + // Rivals start - 1.7 exp leveling + if (AzuriteConfig.oldExpLeveling.getValue()) { + return this.expLevel >= 30 ? 62 + (this.expLevel - 30) * 7 : (this.expLevel >= 15 ? 17 + (this.expLevel - 15) * 3 : 17); + } + // Rivals end + return this.expLevel >= 30 ? 112 + (this.expLevel - 30) * 9 + : (this.expLevel >= 15 ? 37 + (this.expLevel - 15) * 5 : 7 + this.expLevel * 2); + } + + public void applyExhaustion(float f) { + if (!this.abilities.isInvulnerable) { + this.foodData.a(f); + } + } + + public FoodMetaData getFoodData() { + return this.foodData; + } + + public boolean j(boolean flag) { + return (flag || this.foodData.c()) && !this.abilities.isInvulnerable; + } + + public boolean cm() { + return this.getHealth() > 0.0F && this.getHealth() < this.getMaxHealth(); + } + + public void a(ItemStack itemstack, int i) { + if (itemstack != g) { + g = itemstack; + h = i; + f(true); + } + } + + public boolean cn() { + return this.abilities.mayBuild; + } + + public boolean a(BlockPosition blockposition, EnumDirection enumdirection, ItemStack itemstack) { + if (this.abilities.mayBuild) { + return true; + } else if (itemstack == null) { + return false; + } else { + enumdirection = enumdirection.opposite(); + + return itemstack.d(world.getType(blockposition.getX() + enumdirection.getAdjacentX(), blockposition.getY() + enumdirection.getAdjacentY(), blockposition.getZ() + enumdirection.getAdjacentZ()).getBlock()) + || itemstack.x(); + } + } + + protected int getExpValue(EntityHuman entityhuman) { + if (this.world.getGameRules().getBoolean("keepInventory")) { + return 0; + } else { + return Math.min(expLevel * 7, 100); + } + } + + protected boolean alwaysGivesExp() { + return true; + } + + public void copyTo(EntityHuman entityhuman, boolean flag) { + if (flag) { + this.inventory.b(entityhuman.inventory); + this.setHealth(entityhuman.getHealth()); + this.foodData = entityhuman.foodData; + this.expLevel = entityhuman.expLevel; + this.expTotal = entityhuman.expTotal; + this.exp = entityhuman.exp; + this.setScore(entityhuman.getScore()); + this.an = entityhuman.an; + this.ao = entityhuman.ao; + this.ap = entityhuman.ap; + } else if (this.world.getGameRules().getBoolean("keepInventory")) { + this.inventory.b(entityhuman.inventory); + this.expLevel = entityhuman.expLevel; + this.expTotal = entityhuman.expTotal; + this.exp = entityhuman.exp; + this.setScore(entityhuman.getScore()); + } + + this.f = entityhuman.f; + this.enderChest = entityhuman.enderChest; + this.getDataWatcher().watch(10, entityhuman.getDataWatcher().getByte(10)); + } + + protected boolean s_() { + return !this.abilities.isFlying; + } + + public void updateAbilities() { + } + + public void a(WorldSettings.EnumGamemode worldsettings_enumgamemode) { + } + + public String getName() { + return this.bH.getName(); + } + + public InventoryEnderChest getEnderChest() { + return this.enderChest; + } + + public ItemStack getEquipment(int i) { + return i == 0 ? inventory.getItemInHand() : inventory.armor[i - 1]; + } + + public ItemStack bA() { + return this.inventory.getItemInHand(); + } + + public void setEquipment(int i, ItemStack itemstack) { + ItemStack previous = this.inventory.armor[i]; + if (!Objects.equals(itemstack, previous)) { + if (previous != null && (EquipmentSetEvent.getHandlerList().getRegisteredListeners()).length > 0) + previous = previous.cloneItemStack(); + this.inventory.armor[i] = itemstack; + Bukkit.getPluginManager().callEvent(new EquipmentSetEvent(getBukkitEntity(), i, CraftItemStack.asBukkitCopy(previous), CraftItemStack.asBukkitCopy(itemstack))); + } + } + + public abstract boolean isSpectator(); + + public ItemStack[] getEquipment() { + return this.inventory.armor; + } + + public boolean aL() { + return !this.abilities.isFlying; + } + + public Scoreboard getScoreboard() { + return this.world.getScoreboard(); + } + + public ScoreboardTeamBase getScoreboardTeam() { + return this.getScoreboard().getPlayerTeam(this.getName()); + } + + public IChatBaseComponent getScoreboardDisplayName() { + // CraftBukkit - todo: fun + ChatComponentText chatcomponenttext = new ChatComponentText( + ScoreboardTeam.getPlayerDisplayName(this.getScoreboardTeam(), this.getName())); + + chatcomponenttext.getChatModifier().setChatClickable( + new ChatClickable(ChatClickable.EnumClickAction.SUGGEST_COMMAND, "/msg " + this.getName() + " ")); + chatcomponenttext.getChatModifier().setChatHoverable(this.aQ()); + chatcomponenttext.getChatModifier().setInsertion(this.getName()); + return chatcomponenttext; + } + + public float getHeadHeight() { + float f = 1.62F; + + if (this.isSleeping()) { + f = 0.2F; + } + + if (this.isSneaking()) { + f -= 0.08F; // from 0.08F to 0.19F + } + + return f; + } + + public float getAbsorptionHearts() { + return this.getDataWatcher().getFloat(17); + } + + public void setAbsorptionHearts(float f) { + if (f < 0.0F) + f = 0.0F; + getDataWatcher().watch(17, f); + } + + public boolean a(ChestLock chestlock) { + if (chestlock.a()) { + return true; + } else { + ItemStack itemstack = this.bZ(); + + return itemstack != null && itemstack.hasName() && itemstack.getName().equals(chestlock.b()); + } + } + + public boolean getSendCommandFeedback() { + return MinecraftServer.getServer().worldServer[0].getGameRules().getBoolean("sendCommandFeedback"); + } + + public boolean d(int i, ItemStack itemstack) { + if (i >= 0 && i < this.inventory.items.length) { + this.inventory.setItem(i, itemstack); + return true; + } else { + int j = i - 100; + int k; + + if (j >= 0 && j < this.inventory.armor.length) { + k = j + 1; + if (itemstack != null && itemstack.getItem() != null) { + if (itemstack.getItem() instanceof ItemArmor) { + if (EntityInsentient.c(itemstack) != k) { + return false; + } + } else if (k != 4 + || itemstack.getItem() != Items.SKULL && !(itemstack.getItem() instanceof ItemBlock)) { + return false; + } + } + + this.inventory.setItem(j + this.inventory.items.length, itemstack); + return true; + } else { + k = i - 200; + if (k >= 0 && k < this.enderChest.getSize()) { + this.enderChest.setItem(k, itemstack); + return true; + } else { + return false; + } + } + } + } + + public enum EnumBedResult { + + OK, NOT_POSSIBLE_HERE, NOT_POSSIBLE_NOW, TOO_FAR_AWAY, OTHER_PROBLEM, NOT_SAFE; + + EnumBedResult() { + } + } + + public enum EnumChatVisibility { + + FULL(0, "options.chat.visibility.full"), SYSTEM(1, "options.chat.visibility.system"), + HIDDEN(2, "options.chat.visibility.hidden"); + + private static final EntityHuman.EnumChatVisibility[] d = new EntityHuman.EnumChatVisibility[values().length]; + + static { + for (EnumChatVisibility entityhuman_enumchatvisibility : values()) { + EnumChatVisibility.d[entityhuman_enumchatvisibility.e] = entityhuman_enumchatvisibility; + } + + } + + private final int e; + + EnumChatVisibility(int i, String s) { + this.e = i; + } + + public static EntityHuman.EnumChatVisibility a(int i) { + return EntityHuman.EnumChatVisibility.d[i % EntityHuman.EnumChatVisibility.d.length]; + } + + public int a() { + return this.e; + } + } + + static class SyntheticClass_1 { + + static final int[] a = new int[EnumDirection.values().length]; + + static { + try { + EntityHuman.SyntheticClass_1.a[EnumDirection.SOUTH.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + } + + try { + EntityHuman.SyntheticClass_1.a[EnumDirection.NORTH.ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + } + + try { + EntityHuman.SyntheticClass_1.a[EnumDirection.WEST.ordinal()] = 3; + } catch (NoSuchFieldError ignored) { + } + + try { + EntityHuman.SyntheticClass_1.a[EnumDirection.EAST.ordinal()] = 4; + } catch (NoSuchFieldError ignored) { + } + + } + } + +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityInsentient.java b/azurite-server/src/main/java/net/minecraft/server/EntityInsentient.java new file mode 100644 index 0000000..eb650e3 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityInsentient.java @@ -0,0 +1,937 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.AzuriteConfig; +import dev.azurite.spigot.pathsearch.AzuriteNavigation; +import org.bukkit.craftbukkit.entity.CraftLivingEntity; +import org.bukkit.craftbukkit.event.CraftEventFactory; +import org.bukkit.entity.LivingEntity; +import org.bukkit.event.entity.EntityPickupItemEvent; +import org.bukkit.event.entity.EntityTargetEvent; +import org.bukkit.event.entity.EntityTargetLivingEntityEvent; +import org.bukkit.event.entity.EntityUnleashEvent; +import org.bukkit.event.entity.EntityUnleashEvent.UnleashReason; + +import java.lang.ref.WeakReference; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; + +public abstract class EntityInsentient extends EntityLiving { + + private final ControllerLook lookController; + private final EntityAIBodyControl b; + private final EntitySenses bk; + private final ItemStack[] equipment = new ItemStack[5]; + public int a_; + public PathfinderGoalSelector goalSelector; + public PathfinderGoalSelector targetSelector; + public float[] dropChances = new float[5]; + public boolean canPickUpLoot; + public boolean persistent; + public PathfinderGoalFloat goalFloat; // PaperSpigot + protected int b_; + protected ControllerMove moveController; + protected ControllerJump g; + protected NavigationAbstract navigation; + protected ItemStack headDrop = null; // CraftBukkit + //private EntityLiving goalTarget; + private WeakReference goalTarget = new WeakReference<>(null); + private boolean bo; + private Entity bp; + private NBTTagCompound bq; + public boolean intelligence = AzuriteConfig.mobAI.getValue() || (AzuriteConfig.mobAIHorses.getValue() && this instanceof EntityHorse); + + public EntityInsentient(World world) { + super(world); + this.goalSelector = new PathfinderGoalSelector(); + this.targetSelector = new PathfinderGoalSelector(); + this.lookController = new ControllerLook(this); + this.moveController = new ControllerMove(this); + this.g = new ControllerJump(this); + this.b = new EntityAIBodyControl(this); + this.navigation = this.b(world); + this.bk = new EntitySenses(this); + + Arrays.fill(this.dropChances, 0.085F); + + // CraftBukkit start - default persistance to type's persistance value + this.persistent = !isTypeNotPersistent(); + // CraftBukkit end + } + + public static int c(ItemStack itemstack) { + if (itemstack.getItem() != Item.getItemOf(Blocks.PUMPKIN) && itemstack.getItem() != Items.SKULL) { + if (itemstack.getItem() instanceof ItemArmor) { + switch (((ItemArmor) itemstack.getItem()).b) { + case 0: + return 4; + + case 1: + return 3; + + case 2: + return 2; + + case 3: + return 1; + } + } + + return 0; + } else { + return 4; + } + } + + public static Item a(int i, int j) { + switch (i) { + case 4: + if (j == 0) { + return Items.LEATHER_HELMET; + } else if (j == 1) { + return Items.GOLDEN_HELMET; + } else if (j == 2) { + return Items.CHAINMAIL_HELMET; + } else if (j == 3) { + return Items.IRON_HELMET; + } else if (j == 4) { + return Items.DIAMOND_HELMET; + } + + case 3: + if (j == 0) { + return Items.LEATHER_CHESTPLATE; + } else if (j == 1) { + return Items.GOLDEN_CHESTPLATE; + } else if (j == 2) { + return Items.CHAINMAIL_CHESTPLATE; + } else if (j == 3) { + return Items.IRON_CHESTPLATE; + } else if (j == 4) { + return Items.DIAMOND_CHESTPLATE; + } + + case 2: + if (j == 0) { + return Items.LEATHER_LEGGINGS; + } else if (j == 1) { + return Items.GOLDEN_LEGGINGS; + } else if (j == 2) { + return Items.CHAINMAIL_LEGGINGS; + } else if (j == 3) { + return Items.IRON_LEGGINGS; + } else if (j == 4) { + return Items.DIAMOND_LEGGINGS; + } + + case 1: + if (j == 0) { + return Items.LEATHER_BOOTS; + } else if (j == 1) { + return Items.GOLDEN_BOOTS; + } else if (j == 2) { + return Items.CHAINMAIL_BOOTS; + } else if (j == 3) { + return Items.IRON_BOOTS; + } else if (j == 4) { + return Items.DIAMOND_BOOTS; + } + + default: + return null; + } + } + + protected void initAttributes() { + super.initAttributes(); + this.getAttributeMap().b(GenericAttributes.FOLLOW_RANGE).setValue(16.0D); + } + + protected NavigationAbstract b(World world) { + return new AzuriteNavigation(this, world); // Migot + } + + public ControllerLook getControllerLook() { + return this.lookController; + } + + public ControllerMove getControllerMove() { + return this.moveController; + } + + public ControllerJump getControllerJump() { + return this.g; + } + + public NavigationAbstract getNavigation() { + return this.navigation; + } + + public EntitySenses getEntitySenses() { + return this.bk; + } + + public EntityLiving getGoalTarget() { + return this.goalTarget.get(); // Changed to weak reference. + } + + public void setGoalTarget(EntityLiving entityliving) { + // CraftBukkit start - fire event + setGoalTarget(entityliving, EntityTargetEvent.TargetReason.UNKNOWN, true); + + } + + public void setGoalTarget(EntityLiving entityliving, EntityTargetEvent.TargetReason reason, boolean fireEvent) { + if (getGoalTarget() == entityliving) return; + if (fireEvent) { + if (reason == EntityTargetEvent.TargetReason.UNKNOWN && getGoalTarget() != null && entityliving == null) { + reason = getGoalTarget().isAlive() ? EntityTargetEvent.TargetReason.FORGOT_TARGET : EntityTargetEvent.TargetReason.TARGET_DIED; + } + if (reason == EntityTargetEvent.TargetReason.UNKNOWN) { + world.getServer().getLogger().log(java.util.logging.Level.WARNING, "Unknown target reason, please report on the issue tracker", new Exception()); + } + CraftLivingEntity ctarget = null; + if (entityliving != null) { + ctarget = (CraftLivingEntity) entityliving.getBukkitEntity(); + } + EntityTargetLivingEntityEvent event = new EntityTargetLivingEntityEvent(this.getBukkitEntity(), ctarget, reason); + world.getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { + return; + } + + if (event.getTarget() != null) { + entityliving = ((CraftLivingEntity) event.getTarget()).getHandle(); + } else { + entityliving = null; + } + } + //this.goalTarget = entityliving; + this.goalTarget = new WeakReference<>(entityliving); + // CraftBukkit end + } + + public boolean a(Class oclass) { + return oclass != EntityGhast.class; + } + + public void v() { + } + + protected void h() { + super.h(); + this.datawatcher.a(15, (byte) 0); + } + + public int w() { + return 80; + } + + public void x() { + String s = this.z(); + + if (s != null) { + this.makeSound(s, this.bB(), this.bC()); + } + + } + + public void K() { + super.K(); + + if (AzuriteConfig.mobRandomSounds.getValue() && isAlive() && random.nextInt(1000) < this.a_++) { + this.a_ = -this.w(); + this.x(); + } + } + + protected int getExpValue(EntityHuman entityhuman) { + if (this.b_ > 0) { + int i = this.b_; + ItemStack[] aitemstack = this.getEquipment(); + + for (int j = 0; j < aitemstack.length; ++j) { + if (aitemstack[j] != null && this.dropChances[j] <= 1.0F) { + i += 1 + random.nextInt(3); + } + } + + return i; + } else { + return this.b_; + } + } + + public void y() { + this.world.broadcastEntityEffect(this, (byte) 20); + } + + public void t_() { + super.t_(); + + this.ca(); + + } + + protected float h(float f, float f1) { + this.b.a(); + return f1; + } + + protected String z() { + return null; + } + + protected Item getLoot() { + return null; + } + + protected void dropDeathLoot(boolean flag, int i) { + Item item = this.getLoot(); + + if (item != null) { + int j = random.nextInt(3); + + if (i > 0) { + j += random.nextInt(i + 1); + } + + for (int k = 0; k < j; ++k) { + this.a(item, 1); + } + } + + // CraftBukkit start + if (headDrop != null) { + this.a(headDrop, 0.0F); + headDrop = null; + } + // CraftBukkit end + } + + public void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + nbttagcompound.setBoolean("CanPickUpLoot", this.bY()); + nbttagcompound.setBoolean("PersistenceRequired", this.persistent); + NBTTagList nbttaglist = new NBTTagList(); + + NBTTagCompound nbttagcompound1; + + for (ItemStack itemStack : this.equipment) { + nbttagcompound1 = new NBTTagCompound(); + if (itemStack != null) { + itemStack.save(nbttagcompound1); + } + + nbttaglist.add(nbttagcompound1); + } + + nbttagcompound.set("Equipment", nbttaglist); + NBTTagList nbttaglist1 = new NBTTagList(); + + for (float dropChance : this.dropChances) { + nbttaglist1.add(new NBTTagFloat(dropChance)); + } + + nbttagcompound.set("DropChances", nbttaglist1); + nbttagcompound.setBoolean("Leashed", this.bo); + if (this.bp != null) { + nbttagcompound1 = new NBTTagCompound(); + if (this.bp instanceof EntityLiving) { + nbttagcompound1.setLong("UUIDMost", this.bp.getUniqueID().getMostSignificantBits()); + nbttagcompound1.setLong("UUIDLeast", this.bp.getUniqueID().getLeastSignificantBits()); + } else if (this.bp instanceof EntityHanging) { + BlockPosition blockposition = ((EntityHanging) this.bp).getBlockPosition(); + + nbttagcompound1.setInt("X", blockposition.getX()); + nbttagcompound1.setInt("Y", blockposition.getY()); + nbttagcompound1.setInt("Z", blockposition.getZ()); + } + + nbttagcompound.set("Leash", nbttagcompound1); + } else if (this.bq != null) { + nbttagcompound.set("Leash", this.bq); + } + + if (this.ce()) { + nbttagcompound.setBoolean("NoAI", this.ce()); + } + + } + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + + // CraftBukkit start - If looting or persistence is false only use it if it was set after we started using it + if (nbttagcompound.hasKeyOfType("CanPickUpLoot", 1)) { + boolean data = nbttagcompound.getBoolean("CanPickUpLoot"); + if (isLevelAtLeast(nbttagcompound, 1) || data) { + this.j(data); + } + } + + boolean data = nbttagcompound.getBoolean("PersistenceRequired"); + if (isLevelAtLeast(nbttagcompound, 1) || data) { + this.persistent = data; + } + // CraftBukkit end + NBTTagList nbttaglist; + int i; + + if (nbttagcompound.hasKeyOfType("Equipment", 9)) { + nbttaglist = nbttagcompound.getList("Equipment", 10); + + for (i = 0; i < this.equipment.length; ++i) { + this.equipment[i] = ItemStack.createStack(nbttaglist.get(i)); + } + } + + if (nbttagcompound.hasKeyOfType("DropChances", 9)) { + nbttaglist = nbttagcompound.getList("DropChances", 5); + + for (i = 0; i < nbttaglist.size(); ++i) { + this.dropChances[i] = nbttaglist.e(i); + } + } + + this.bo = nbttagcompound.getBoolean("Leashed"); + if (this.bo && nbttagcompound.hasKeyOfType("Leash", 10)) { + this.bq = nbttagcompound.getCompound("Leash"); + } + + this.k(nbttagcompound.getBoolean("NoAI")); + } + + public void n(float f) { + this.ba = f; + } + + public void k(float f) { + super.k(f); + this.n(f); + } + + public void m() { + super.m(); + + if (this.bY() && !this.aP && this.world.getGameRules().getBoolean("mobGriefing")) { + List list = this.world.a(EntityItem.class, this.getBoundingBox().grow(1.0D, 0.0D, 1.0D)); + + for (EntityItem entityitem : list) { + if (!entityitem.dead && entityitem.getItemStack() != null && !entityitem.s()) { + this.a(entityitem); + } + } + } + + } + + protected void a(EntityItem entityitem) { + ItemStack itemstack = entityitem.getItemStack(); + int i = c(itemstack); + + if (i > -1) { + boolean flag = true; + ItemStack itemstack1 = this.getEquipment(i); + + if (itemstack1 != null) { + if (i == 0) { + if (itemstack.getItem() instanceof ItemSword && itemstack1.getItem() instanceof ItemSword) { + ItemSword itemsword = (ItemSword) itemstack.getItem(); + ItemSword itemsword1 = (ItemSword) itemstack1.getItem(); + + if (itemsword.g() == itemsword1.g()) { + flag = itemstack.getData() > itemstack1.getData() || itemstack.hasTag() && !itemstack1.hasTag(); + } else { + flag = itemsword.g() > itemsword1.g(); + } + } else if (itemstack.getItem() instanceof ItemBow && itemstack1.getItem() instanceof ItemBow) { + flag = itemstack.hasTag() && !itemstack1.hasTag(); + } else { + flag = false; + } + } else if (itemstack.getItem() instanceof ItemArmor && itemstack1.getItem() instanceof ItemArmor) { + ItemArmor itemarmor = (ItemArmor) itemstack.getItem(); + ItemArmor itemarmor1 = (ItemArmor) itemstack1.getItem(); + + if (itemarmor.c == itemarmor1.c) { + flag = itemstack.getData() > itemstack1.getData() || itemstack.hasTag() && !itemstack1.hasTag(); + } else { + flag = itemarmor.c > itemarmor1.c; + } + } else { + flag = false; + } + } + + boolean canPickup = flag && this.a(itemstack); + EntityPickupItemEvent entityEvent = new EntityPickupItemEvent((LivingEntity) getBukkitEntity(), (org.bukkit.entity.Item) entityitem.getBukkitEntity(), 0); + entityEvent.setCancelled(!canPickup); + this.world.getServer().getPluginManager().callEvent(entityEvent); + canPickup = !entityEvent.isCancelled(); + + if (canPickup) { + if (itemstack1 != null && random.nextFloat() - 0.1F < this.dropChances[i]) { + this.a(itemstack1, 0.0F); + } + + if (itemstack.getItem() == Items.DIAMOND && entityitem.n() != null) { + EntityHuman entityhuman = this.world.a(entityitem.n()); + + if (entityhuman != null) { + entityhuman.b(AchievementList.x); + } + } + + this.setEquipment(i, itemstack); + this.dropChances[i] = 2.0F; + this.persistent = true; + this.receive(entityitem, 1); + entityitem.die(); + } + } + } + + protected boolean a(ItemStack itemstack) { + return true; + } + + public boolean isTypeNotPersistent() { + return true; + } + + protected void D() { + if (this.persistent) { + this.ticksFarFromPlayer = 0; + } else { + EntityHuman entityhuman = this.world.findNearbyPlayerWhoAffectsSpawning(this, -1.0D); // PaperSpigot - Affects Spawning API + + if (entityhuman != null) { + double d0 = entityhuman.locX - this.locX; + double d1 = entityhuman.locY - this.locY; + double d2 = entityhuman.locZ - this.locZ; + double d3 = d0 * d0 + d1 * d1 + d2 * d2; + + if (d3 > this.world.paperSpigotConfig.hardDespawnDistance) { // CraftBukkit - remove isTypeNotPersistent() check // PaperSpigot - custom despawn distances + this.die(); + } + + if (this.ticksFarFromPlayer > 600 && random.nextInt(800) == 0 && d3 > this.world.paperSpigotConfig.softDespawnDistance) { // CraftBukkit - remove isTypeNotPersistent() check // PaperSpigot - custom despawn distance + this.die(); + } else if (d3 < this.world.paperSpigotConfig.softDespawnDistance) { // PaperSpigot - custom despawn distances + this.ticksFarFromPlayer = 0; + } + } + } + } + + @Override + public void inactiveTick() { + super.inactiveTick(); + + // MineHQ - only check despawns on inactive tick + if (this.ticksLived % 50 == 0) { + this.D(); + } + } + + protected final void doTick() { + ++this.ticksFarFromPlayer; + this.navigation.cleanUpExpiredSearches(); // Migot + // Spigot Start + if (world.spigotConfig.nerfSpawnerMobs && this.fromMobSpawner) { + // PaperSpigot start - Allow nerfed mobs to jump + if (goalFloat != null) { + if (goalFloat.a()) goalFloat.e(); + this.g.b(); + } + // PaperSpigot end + return; + } + // Spigot End + if (intelligence) { + this.bk.a(); + this.targetSelector.a(); + this.goalSelector.a(); + this.navigation.k(); + } + this.E(); + if (intelligence) { + this.moveController.c(); + this.lookController.a(); + this.g.b(); + } + } + + protected void E() { + } + + public int bQ() { + return 40; + } + + public void a(Entity entity, float f, float f1) { + double d0 = entity.locX - this.locX; + double d1 = entity.locZ - this.locZ; + double d2; + + if (entity instanceof EntityLiving) { + EntityLiving entityliving = (EntityLiving) entity; + + d2 = entityliving.locY + (double) entityliving.getHeadHeight() - (this.locY + (double) this.getHeadHeight()); + } else { + d2 = (entity.boundingBox.b + entity.boundingBox.e) / 2.0D - (this.locY + (double) this.getHeadHeight()); + } + + double d3 = MathHelper.sqrt(d0 * d0 + d1 * d1); + float f2 = (float) (MathHelper.b(d1, d0) * 180.0D / 3.1415927410125732D) - 90.0F; + float f3 = (float) (-(MathHelper.b(d2, d3) * 180.0D / 3.1415927410125732D)); + + this.pitch = this.b(this.pitch, f3, f1); + this.yaw = this.b(this.yaw, f2, f); + } + + private float b(float f, float f1, float f2) { + float f3 = MathHelper.g(f1 - f); + + if (f3 > f2) { + f3 = f2; + } + + if (f3 < -f2) { + f3 = -f2; + } + + return f + f3; + } + + public boolean bR() { + return true; + } + + public boolean canSpawn() { + return world.a(boundingBox, this) && world.getCubes(this, boundingBox).isEmpty() && !world.containsLiquid(boundingBox); + } + + public int bV() { + return 4; + } + + public int aE() { + if (this.getGoalTarget() == null) { + return 3; + } else { + int i = (int) (this.getHealth() - this.getMaxHealth() * 0.33F); + + i -= (3 - this.world.getDifficulty().a()) * 4; + if (i < 0) { + i = 0; + } + + return i + 3; + } + } + + public ItemStack bA() { + return this.equipment[0]; + } + + public ItemStack getEquipment(int i) { + return this.equipment[i]; + } + + public ItemStack q(int i) { + return this.equipment[i + 1]; + } + + public void setEquipment(int i, ItemStack itemstack) { + this.equipment[i] = itemstack; + } + + public ItemStack[] getEquipment() { + return this.equipment; + } + + protected void dropEquipment(boolean flag, int i) { + for (int j = 0; j < this.getEquipment().length; ++j) { + ItemStack itemstack = this.getEquipment(j); + boolean flag1 = this.dropChances[j] > 1.0F; + + if (itemstack != null && (flag || flag1) && random.nextFloat() - (float) i * 0.01F < this.dropChances[j]) { + if (!flag1 && itemstack.e()) { + int k = Math.max(itemstack.j() - 25, 1); + int l = itemstack.j() - random.nextInt(random.nextInt(k) + 1); + + if (l > k) { + l = k; + } + + if (l < 1) { + l = 1; + } + + itemstack.setData(l); + } + + this.a(itemstack, 0.0F); + } + } + + } + + protected void a(DifficultyDamageScaler difficultydamagescaler) { + if (random.nextFloat() < 0.15F * difficultydamagescaler.c()) { + int i = random.nextInt(2); + float f = this.world.getDifficulty() == EnumDifficulty.HARD ? 0.1F : 0.25F; + + if (random.nextFloat() < 0.095F) { + ++i; + } + + if (random.nextFloat() < 0.095F) { + ++i; + } + + if (random.nextFloat() < 0.095F) { + ++i; + } + + for (int j = 3; j >= 0; --j) { + ItemStack itemstack = this.q(j); + + if (j < 3 && random.nextFloat() < f) { + break; + } + + if (itemstack == null) { + Item item = a(j + 1, i); + + if (item != null) { + this.setEquipment(j + 1, new ItemStack(item)); + } + } + } + } + + } + + protected void b(DifficultyDamageScaler difficultydamagescaler) { + float f = difficultydamagescaler.c(); + + if (this.bA() != null && random.nextFloat() < 0.25F * f) { + EnchantmentManager.a(random, this.bA(), (int) (5.0F + f * (float) random.nextInt(18))); + } + + for (int i = 0; i < 4; ++i) { + ItemStack itemstack = this.q(i); + + if (itemstack != null && random.nextFloat() < 0.5F * f) { + EnchantmentManager.a(random, itemstack, (int) (5.0F + f * (float) random.nextInt(18))); + } + } + + } + + public GroupDataEntity prepare(DifficultyDamageScaler difficultydamagescaler, GroupDataEntity groupdataentity) { + this.getAttributeInstance(GenericAttributes.FOLLOW_RANGE).b(new AttributeModifier("Random spawn bonus", random.nextGaussian() * 0.05D, 1)); + return groupdataentity; + } + + public boolean bW() { + return false; + } + + public void bX() { + this.persistent = true; + } + + public void a(int i, float f) { + this.dropChances[i] = f; + } + + public boolean bY() { + return this.canPickUpLoot; + } + + public void j(boolean flag) { + this.canPickUpLoot = flag; + } + + public boolean isPersistent() { + return this.persistent; + } + + public final boolean e(EntityHuman entityhuman) { + if (this.cc() && this.getLeashHolder() == entityhuman) { + // CraftBukkit start - fire PlayerUnleashEntityEvent + if (CraftEventFactory.callPlayerUnleashEntityEvent(this, entityhuman).isCancelled()) { + entityhuman.sendPacket(new PacketPlayOutAttachEntity(1, this, this.getLeashHolder())); + return false; + } + // CraftBukkit end + this.unleash(true, !entityhuman.abilities.canInstantlyBuild); + return true; + } else { + ItemStack itemstack = entityhuman.inventory.getItemInHand(); + + if (itemstack != null && itemstack.getItem() == Items.LEAD && this.cb()) { + if (!(this instanceof EntityTameableAnimal) || !((EntityTameableAnimal) this).isTamed()) { + // CraftBukkit start - fire PlayerLeashEntityEvent + if (CraftEventFactory.callPlayerLeashEntityEvent(this, entityhuman, entityhuman).isCancelled()) { + entityhuman.sendPacket(new PacketPlayOutAttachEntity(1, this, this.getLeashHolder())); + return false; + } + // CraftBukkit end + this.setLeashHolder(entityhuman, true); + --itemstack.count; + return true; + } + + if (((EntityTameableAnimal) this).e((EntityLiving) entityhuman)) { + // CraftBukkit start - fire PlayerLeashEntityEvent + if (CraftEventFactory.callPlayerLeashEntityEvent(this, entityhuman, entityhuman).isCancelled()) { + entityhuman.sendPacket(new PacketPlayOutAttachEntity(1, this, this.getLeashHolder())); + return false; + } + // CraftBukkit end + this.setLeashHolder(entityhuman, true); + --itemstack.count; + return true; + } + } + + return this.a(entityhuman) || super.e(entityhuman); + } + } + + protected boolean a(EntityHuman entityhuman) { + return false; + } + + protected void ca() { + if (this.bq != null) { + this.n(); + } + + if (this.bo) { + if (!this.isAlive()) { + this.world.getServer().getPluginManager().callEvent(new EntityUnleashEvent(this.getBukkitEntity(), UnleashReason.PLAYER_UNLEASH)); // CraftBukkit + this.unleash(true, true); + } + + if (this.bp == null || this.bp.dead) { + this.world.getServer().getPluginManager().callEvent(new EntityUnleashEvent(this.getBukkitEntity(), UnleashReason.HOLDER_GONE)); // CraftBukkit + this.unleash(true, true); + } + } + } + + public void unleash(boolean flag, boolean flag1) { + if (this.bo) { + this.bo = false; + this.bp = null; + if (flag1) { + this.a(Items.LEAD, 1); + } + + if (flag && this.world instanceof WorldServer) { + ((WorldServer) this.world).getTracker().a(this, new PacketPlayOutAttachEntity(1, this, null)); + } + } + + } + + public boolean cb() { + return !this.cc() && !(this instanceof IMonster); + } + + public boolean cc() { + return this.bo; + } + + public Entity getLeashHolder() { + return this.bp; + } + + public void setLeashHolder(Entity entity, boolean flag) { + this.bo = true; + this.bp = entity; + if (flag && this.world instanceof WorldServer) { + ((WorldServer) this.world).getTracker().a(this, new PacketPlayOutAttachEntity(1, this, this.bp)); + } + + } + + private void n() { + if (this.bo && this.bq != null) { + if (this.bq.hasKeyOfType("UUIDMost", 4) && this.bq.hasKeyOfType("UUIDLeast", 4)) { + UUID uuid = new UUID(this.bq.getLong("UUIDMost"), this.bq.getLong("UUIDLeast")); + List list = this.world.a(EntityLiving.class, this.getBoundingBox().grow(10.0D, 10.0D, 10.0D)); + + for (EntityLiving entityliving : list) { + if (entityliving.getUniqueID().equals(uuid)) { + this.setLeashHolder(entityliving, true); + break; + } + } + } + if (this.bp == null && this.bq.hasKeyOfType("X", 99) && this.bq.hasKeyOfType("Y", 99) && this.bq.hasKeyOfType("Z", 99)) { + BlockPosition blockposition = new BlockPosition(this.bq.getInt("X"), this.bq.getInt("Y"), this.bq.getInt("Z")); + EntityLeash entityleash = EntityLeash.b(this.world, blockposition); + + if (entityleash == null) { + entityleash = EntityLeash.a(this.world, blockposition); + } + this.setLeashHolder(entityleash, true); + } + if (this.bp == null) { // MinetickMod + this.world.getServer().getPluginManager().callEvent(new EntityUnleashEvent(this.getBukkitEntity(), UnleashReason.UNKNOWN)); // CraftBukkit + this.unleash(false, true); + } + + + } + + this.bq = null; + } + + public boolean d(int i, ItemStack itemstack) { + int j; + + if (i == 99) { + j = 0; + } else { + j = i - 100 + 1; + if (j < 0 || j >= this.equipment.length) { + return false; + } + } + + if (itemstack != null && c(itemstack) != j && (j != 4 || !(itemstack.getItem() instanceof ItemBlock))) { + return false; + } else { + this.setEquipment(j, itemstack); + return true; + } + } + + public boolean bM() { + return super.bM() && !this.ce(); + } + + public void k(boolean flag) { + this.datawatcher.watch(15, (byte) (flag ? 1 : 0)); + } + + public boolean ce() { + return this.datawatcher.getByte(15) != 0; + } + + public enum EnumEntityPositionType { + + ON_GROUND, IN_AIR, IN_WATER; + + EnumEntityPositionType() { + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityIronGolem.java b/azurite-server/src/main/java/net/minecraft/server/EntityIronGolem.java new file mode 100644 index 0000000..bfd53ee --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityIronGolem.java @@ -0,0 +1,234 @@ +package net.minecraft.server; + +import com.google.common.base.Predicate; +import dev.azurite.spigot.configs.AzuriteConfig; + +public class EntityIronGolem extends EntityGolem { + + private int b; + Village a; + private int c; + private int bm; + + public EntityIronGolem(World world) { + super(world); + this.setSize(1.4F, 2.9F); + ((Navigation) this.getNavigation()).a(true); + this.goalSelector.a(1, new PathfinderGoalMeleeAttack(this, 1.0D, true)); + this.goalSelector.a(2, new PathfinderGoalMoveTowardsTarget(this, 0.9D, 32.0F)); + this.goalSelector.a(3, new PathfinderGoalMoveThroughVillage(this, 0.6D, true)); + this.goalSelector.a(4, new PathfinderGoalMoveTowardsRestriction(this, 1.0D)); + this.goalSelector.a(5, new PathfinderGoalOfferFlower(this)); + this.goalSelector.a(6, new PathfinderGoalRandomStroll(this, 0.6D)); + this.goalSelector.a(7, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 6.0F)); + this.goalSelector.a(8, new PathfinderGoalRandomLookaround(this)); + this.targetSelector.a(1, new PathfinderGoalDefendVillage(this)); + this.targetSelector.a(2, new PathfinderGoalHurtByTarget(this, false)); + this.targetSelector.a(3, new EntityIronGolem.PathfinderGoalNearestGolemTarget<>(this, EntityInsentient.class, 10, false, true, IMonster.e)); + } + + @Override + public void e(float f, float f1) { + if (AzuriteConfig.ironGolemFallDamage.getValue()) { + super.e(f, f1); + } + } + + protected void h() { + super.h(); + this.datawatcher.a(16, (byte) 0); + } + + protected void E() { + if (--this.b <= 0) { + this.b = 70 + random.nextInt(50); + this.a = this.world.ae().getClosestVillage(MathHelper.floor(locX), MathHelper.floor(locY), MathHelper.floor(locZ), 32); + if (this.a == null) { + this.cj(); + } else { + this.a(a.a(), (int) ((float) this.a.b() * 0.6F)); + } + } + + super.E(); + } + + protected void initAttributes() { + super.initAttributes(); + this.getAttributeInstance(GenericAttributes.maxHealth).setValue(100.0D); + this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.25D); + } + + protected int j(int i) { + return i; + } + + protected void s(Entity entity) { + if (entity instanceof IMonster && !(entity instanceof EntityCreeper) && this.bc().nextInt(20) == 0) { + this.setGoalTarget((EntityLiving) entity, org.bukkit.event.entity.EntityTargetLivingEntityEvent.TargetReason.COLLISION, true); // CraftBukkit - set reason + } + + super.s(entity); + } + + public void m() { + super.m(); + if (this.c > 0) { + --this.c; + } + + if (this.bm > 0) { + --this.bm; + } + + if (this.motX * this.motX + this.motZ * this.motZ > 2.500000277905201E-7D && random.nextInt(5) == 0) { + int i = MathHelper.floor(this.locX); + int j = MathHelper.floor(this.locY - 0.20000000298023224D); + int k = MathHelper.floor(this.locZ); + IBlockData iblockdata = this.world.getType(i, j, k); + Block block = iblockdata.getBlock(); + + if (block.getMaterial() != Material.AIR) { + this.world.addParticle(EnumParticle.BLOCK_CRACK, this.locX + (random.nextFloat() - 0.5D) * this.width, this.getBoundingBox().b + 0.1D, this.locZ + (random.nextFloat() - 0.5D) * this.width, 4.0D * (random.nextFloat() - 0.5D), 0.5D, (random.nextFloat() - 0.5D) * 4.0D, Block.getCombinedId(iblockdata)); + } + } + + } + + public boolean a(Class oclass) { + return (!this.isPlayerCreated() || !EntityHuman.class.isAssignableFrom(oclass)) && (oclass != EntityCreeper.class && super.a(oclass)); + } + + public void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + nbttagcompound.setBoolean("PlayerCreated", this.isPlayerCreated()); + } + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + this.setPlayerCreated(nbttagcompound.getBoolean("PlayerCreated")); + } + + public boolean r(Entity entity) { + this.c = 10; + this.world.broadcastEntityEffect(this, (byte) 4); + boolean flag = entity.damageEntity(DamageSource.mobAttack(this), (float) (7 + random.nextInt(15))); + + if (flag) { + entity.motY += 0.4000000059604645D; + this.a(this, entity); + } + + this.makeSound("mob.irongolem.throw", 1.0F, 1.0F); + return flag; + } + + public Village n() { + return this.a; + } + + public void a(boolean flag) { + this.bm = flag ? 400 : 0; + this.world.broadcastEntityEffect(this, (byte) 11); + } + + protected String bo() { + return "mob.irongolem.hit"; + } + + protected String bp() { + return "mob.irongolem.death"; + } + + protected void a(BlockPosition blockposition, Block block) { + this.makeSound("mob.irongolem.walk", 1.0F, 1.0F); + } + + protected void dropDeathLoot(boolean flag, int i) { + int j = random.nextInt(3); + + int k; + + for (k = 0; k < j; ++k) { + this.a(Item.getItemOf(Blocks.RED_FLOWER), 1, (float) BlockFlowers.EnumFlowerVarient.POPPY.b()); + } + + k = 3 + random.nextInt(3); + + for (int l = 0; l < k; ++l) { + this.a(Items.IRON_INGOT, 1); + } + + } + + public int cm() { + return this.bm; + } + + public boolean isPlayerCreated() { + return (this.datawatcher.getByte(16) & 1) != 0; + } + + public void setPlayerCreated(boolean flag) { + byte b0 = this.datawatcher.getByte(16); + + if (flag) { + this.datawatcher.watch(16, (byte) (b0 | 1)); + } else { + this.datawatcher.watch(16, (byte) (b0 & -2)); + } + + } + + public void die(DamageSource damagesource) { + if (!this.isPlayerCreated() && this.killer != null && this.a != null) { + this.a.a(this.killer.getName(), -5); + } + + super.die(damagesource); + } + + static class PathfinderGoalNearestGolemTarget extends PathfinderGoalNearestAttackableTarget { + + public PathfinderGoalNearestGolemTarget(final EntityCreature entitycreature, Class oclass, int i, boolean flag, boolean flag1, final Predicate predicate) { + super(entitycreature, oclass, i, flag, flag1, predicate); + this.c = new Predicate() { + public boolean a(T t0) { + if (predicate != null && !predicate.apply(t0)) { + return false; + } else if (t0 instanceof EntityCreeper) { + return false; + } else { + if (t0 instanceof EntityHuman) { + double d0 = PathfinderGoalNearestGolemTarget.this.f(); + + if (t0.isSneaking()) { + d0 *= 0.800000011920929D; + } + + if (t0.isInvisible()) { + float f = ((EntityHuman) t0).bY(); + + if (f < 0.1F) { + f = 0.1F; + } + + d0 *= 0.7F * f; + } + + if ((double) t0.g(entitycreature) > d0) { + return false; + } + } + + return PathfinderGoalNearestGolemTarget.this.a(t0, false); + } + } + + public boolean apply(Object object) { + return this.a((T) object); // CraftBukkit - fix decompiler error + } + }; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityItem.java b/azurite-server/src/main/java/net/minecraft/server/EntityItem.java new file mode 100644 index 0000000..7851b03 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityItem.java @@ -0,0 +1,476 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.AzuriteConfig; +import net.techcable.tacospigot.HopperPusher; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.bukkit.event.entity.EntityPickupItemEvent; +import org.bukkit.event.player.PlayerPickupItemEvent; + +import java.util.*; + +// TacoSpigot start - implement HopperPusher +public class EntityItem extends Entity implements HopperPusher { + private static final Logger b = LogManager.getLogger(); + + public int pickupDelay; + public float a; + public Entity owner; + private int age; + private int e; + private String f; + private String g; + private int lastTick = MinecraftServer.currentTick; // CraftBukkit + + public EntityItem(World world, double d0, double d1, double d2) { + super(world); + this.e = 5; + this.a = (float) (Math.random() * 3.141592653589793D * 2.0D); + this.setSize(0.25F, 0.25F); + this.setPosition(d0, d1, d2); + this.yaw = (float) (Math.random() * 360.0D); + this.motX = ((float) (Math.random() * 0.20000000298023224D - 0.10000000149011612D)); + this.motY = 0.20000000298023224D; + this.motZ = ((float) (Math.random() * 0.20000000298023224D - 0.10000000149011612D)); + } + + public EntityItem(World world, double d0, double d1, double d2, ItemStack itemstack) { + this(world, d0, d1, d2); + // CraftBukkit start - Can't set null items in the datawatcher + if (itemstack == null || itemstack.getItem() == null) { + return; + } + // CraftBukkit end + this.setItemStack(itemstack); + } + + public EntityItem(World world) { + super(world); + this.e = 5; + this.a = (float) (Math.random() * 3.141592653589793D * 2.0D); + this.setSize(0.25F, 0.25F); + this.setItemStack(new ItemStack(Blocks.AIR, 0)); + } + + @Override + public boolean acceptItem(TileEntityHopper hopper) { + return TileEntityHopper.a(hopper, this); + } + + protected boolean s_() { + return false; + } + + protected void h() { + this.getDataWatcher().add(10, 5); + } + + public void t_() { + ItemStack itemStack = this.getItemStack(); + if (itemStack == null) { + this.die(); + } else { + // Beanes - option to randomize item pickup + if (!possiblePickup.isEmpty()) { + Collections.shuffle(possiblePickup); + } + + while (!possiblePickup.isEmpty() && !this.dead) { + EntityHuman possible = possiblePickup.remove(0); + + // Beanes - ensure player is still online & not dead (as it's a tick delayed) + if (!possible.dead && ((org.bukkit.entity.Player) possible.getBukkitEntity()).isOnline()) { + tryPickup(possible); + } + } + + // Dead because of pickup + if (this.dead) { + return; + } + + + super.t_(); + if (ticksLived % 15 == 0 && tryPutInHopper()) // Vortex - optimized ticking + return; + + // CraftBukkit start - Use wall time for pickup and despawn timers + int elapsedTicks = MinecraftServer.currentTick - this.lastTick; + if (this.pickupDelay != 32767) this.pickupDelay -= elapsedTicks; + if (this.age != -32768) this.age += elapsedTicks; + this.lastTick = MinecraftServer.currentTick; + // CraftBukkit end + + this.lastX = this.locX; + this.lastY = this.locY; + this.lastZ = this.locZ; + this.motY -= 0.03999999910593033D; + this.noclip = this.j(this.locX, (boundingBox.b + boundingBox.e) / 2.0D, this.locZ); + this.move(this.motX, this.motY, this.motZ); + + // Vortex - optimized ticking while entity doesnt change location + if ((int) this.lastX != (int) this.locX || (int) this.lastY != (int) this.locY || (int) this.lastZ != (int) this.locZ || this.ticksLived % 25 == 0) { + if (world.getType(MathHelper.floor(locX), MathHelper.floor(locY), MathHelper.floor(locZ)).getBlock().getMaterial() == Material.LAVA) { + this.motY = 0.20000000298023224D; + this.motX = ((random.nextFloat() - random.nextFloat()) * 0.2F); + this.motZ = ((random.nextFloat() - random.nextFloat()) * 0.2F); + if (AzuriteConfig.itemFizzSounds.getValue()) + this.makeSound("random.fizz", 0.4F, 2.0F + random.nextFloat() * 0.4F); + } + this.w(itemStack); + } + + float f = 0.98F; + + if (this.onGround) { + f = this.world.getType(MathHelper.floor(this.locX), MathHelper.floor(boundingBox.b) - 1, MathHelper.floor(this.locZ)).getBlock().frictionFactor * 0.98F; + } + + this.motX *= f; + this.motY *= 0.9800000190734863D; + this.motZ *= f; + if (this.onGround) { + this.motY *= -0.5D; + } + + if (this.age >= world.spigotConfig.itemDespawnRate) { // Spigot + // CraftBukkit start - fire ItemDespawnEvent + if (org.bukkit.craftbukkit.event.CraftEventFactory.callItemDespawnEvent(this).isCancelled()) { + this.age = 0; + return; + } + // CraftBukkit end + this.die(); + } + + // Beanes - Re-encode by server values if item didn't move, so when the next forced teleport happens client is 1:1 w/ server to prevent desyncs + if (this.lastX == this.locX && this.lastY == this.locY && this.lastZ == this.locZ) { + this.reEncodeByServerValues(); + } + } + } + + // Spigot start - copied from above + @Override + public void inactiveTick() { + if (ticksLived % 15 == 0 && tryPutInHopper()) // Vortex - optimized inactive ticking + return; + // CraftBukkit start - Use wall time for pickup and despawn timers + int elapsedTicks = MinecraftServer.currentTick - this.lastTick; + if (this.pickupDelay != 32767) this.pickupDelay -= elapsedTicks; + if (this.age != -32768) this.age += elapsedTicks; + this.lastTick = MinecraftServer.currentTick; + // CraftBukkit end + + if (this.age >= world.spigotConfig.itemDespawnRate) { // Spigot + // CraftBukkit start - fire ItemDespawnEvent + if (org.bukkit.craftbukkit.event.CraftEventFactory.callItemDespawnEvent(this).isCancelled()) { + this.age = 0; + return; + } + // CraftBukkit end + this.die(); + } + } + // Spigot end + + private void w(ItemStack itemStack) { + if (itemStack.count >= itemStack.getMaxStackSize()) { //Vortex - dont merge items + return; + } + // Spigot start + double radius = world.spigotConfig.itemMerge; + // Spigot end + + for (EntityItem entityItem : this.world.a(EntityItem.class, boundingBox.grow(radius, radius, radius))) { + this.a(entityItem); + } + + } + + private boolean a(EntityItem entityitem) { + if (entityitem == this) { + return false; + } else if (entityitem.isAlive() && this.isAlive()) { + ItemStack itemstack = this.getItemStack(); + ItemStack itemstack1 = entityitem.getItemStack(); + + if (this.pickupDelay != 32767 && entityitem.pickupDelay != 32767) { + if (this.age != -32768 && entityitem.age != -32768) { + if (itemstack1.getItem() != itemstack.getItem()) { + return false; + } else if (itemstack1.hasTag() ^ itemstack.hasTag()) { + return false; + } else if (itemstack1.hasTag() && !itemstack1.getTag().equals(itemstack.getTag())) { + return false; + } else if (itemstack1.getItem() == null) { + return false; + } else if (itemstack1.getItem().k() && itemstack1.getData() != itemstack.getData()) { + return false; + } else if (itemstack1.count < itemstack.count) { + return entityitem.a(this); + } else if (itemstack1.count + itemstack.count > itemstack1.getMaxStackSize()) { + return false; + } else { + // Spigot start + if (org.bukkit.craftbukkit.event.CraftEventFactory.callItemMergeEvent(entityitem, this).isCancelled()) + return false; // CraftBukkit + itemstack.count += itemstack1.count; + this.pickupDelay = Math.max(entityitem.pickupDelay, this.pickupDelay); + this.age = Math.min(entityitem.age, this.age); + this.setItemStack(itemstack); + entityitem.die(); + // Spigot end + return true; + } + } else { + return false; + } + } else { + return false; + } + } else { + return false; + } + } + + public void j() { + this.age = 4800; + } + + public boolean W() { + this.inWater = this.world.a(boundingBox, Material.WATER, this); + return this.inWater; + } + + protected void burn(int i) { + this.damageEntity(DamageSource.FIRE, (float) i); + } + + public boolean damageEntity(DamageSource damagesource, float f) { + if (this.isInvulnerable(damagesource)) { + return false; + } else if (this.getItemStack() != null && this.getItemStack().getItem() == Items.NETHER_STAR && damagesource.isExplosion()) { + return false; + } else { + // CraftBukkit start + if (org.bukkit.craftbukkit.event.CraftEventFactory.handleNonLivingEntityDamageEvent(this, damagesource, f)) { + return false; + } + // CraftBukkit end + this.ac(); + this.e = (int) ((float) this.e - f); + if (this.e <= 0) { + this.die(); + } + + return false; + } + } + + public void b(NBTTagCompound nbttagcompound) { + nbttagcompound.setShort("Health", (short) this.e); + nbttagcompound.setShort("Age", (short) this.age); + nbttagcompound.setShort("PickupDelay", (short) this.pickupDelay); + if (this.n() != null) { + nbttagcompound.setString("Thrower", this.f); + } + + if (this.m() != null) { + nbttagcompound.setString("Owner", this.g); + } + + if (this.getItemStack() != null) { + nbttagcompound.set("Item", this.getItemStack().save(new NBTTagCompound())); + } + + } + + public void a(NBTTagCompound nbttagcompound) { + this.e = nbttagcompound.getShort("Health") & 255; + this.age = nbttagcompound.getShort("Age"); + if (nbttagcompound.hasKey("PickupDelay")) { + this.pickupDelay = nbttagcompound.getShort("PickupDelay"); + } + + if (nbttagcompound.hasKey("Owner")) { + this.g = nbttagcompound.getString("Owner"); + } + + if (nbttagcompound.hasKey("Thrower")) { + this.f = nbttagcompound.getString("Thrower"); + } + + NBTTagCompound nbttagcompound1 = nbttagcompound.getCompound("Item"); + + // CraftBukkit start - Handle missing "Item" compounds + if (nbttagcompound1 != null) { + ItemStack itemstack = ItemStack.createStack(nbttagcompound1); + if (itemstack != null) { + this.setItemStack(itemstack); + } else { + this.die(); + } + } else { + this.die(); + } + // CraftBukkit end + if (this.getItemStack() == null) { + this.die(); + } + + } + + // Beanes - option to randomize item pickup + private final List possiblePickup = new ArrayList<>(5); + + public void d(EntityHuman entityhuman) { + if (!((EntityPlayer) entityhuman).canSee(this)) + return; + + // Beanes - option to randomize item pickup + if (AzuriteConfig.randomizeItemPickup.getValue()) { + possiblePickup.add(entityhuman); + } else { + tryPickup(entityhuman); + } + } + + public void tryPickup(EntityHuman entityhuman) { + ItemStack itemstack = this.getItemStack(); + int i = itemstack.count; + + // CraftBukkit start - fire PlayerPickupItemEvent + int canHold = entityhuman.inventory.canHold(itemstack); + int remaining = itemstack.count - canHold; + + if (this.pickupDelay <= 0 && canHold > 0) { + itemstack.count = canHold; + PlayerPickupItemEvent event = new PlayerPickupItemEvent((org.bukkit.entity.Player) entityhuman.getBukkitEntity(), (org.bukkit.entity.Item) this.getBukkitEntity(), remaining); + this.world.getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { + return; + } + + EntityPickupItemEvent entityEvent = new EntityPickupItemEvent(entityhuman.getBukkitEntity(), (org.bukkit.entity.Item) this.getBukkitEntity(), remaining); + this.world.getServer().getPluginManager().callEvent(entityEvent); + if (entityEvent.isCancelled()) { + return; + } + itemstack.count = canHold + remaining; + // Possibly < 0; fix here so we do not have to modify code below + this.pickupDelay = 0; + } + // CraftBukkit end + + if (this.pickupDelay == 0 && (this.g == null || 6000 - this.age <= 200 || this.g.equals(entityhuman.getName())) && entityhuman.inventory.pickup(itemstack)) { + if (itemstack.getItem() == Item.getItemOf(Blocks.LOG)) { + entityhuman.b(AchievementList.g); + } else if (itemstack.getItem() == Item.getItemOf(Blocks.LOG2)) { + entityhuman.b(AchievementList.g); + } else if (itemstack.getItem() == Items.LEATHER) { + entityhuman.b(AchievementList.t); + } else if (itemstack.getItem() == Items.DIAMOND) { + entityhuman.b(AchievementList.w); + } else if (itemstack.getItem() == Items.BLAZE_ROD) { + entityhuman.b(AchievementList.A); + } + + if (itemstack.getItem() == Items.DIAMOND && this.n() != null) { + EntityHuman entityhuman1 = this.world.a(this.n()); + + if (entityhuman1 != null && entityhuman1 != entityhuman) { + entityhuman1.b(AchievementList.x); + } + } + + if (!this.R()) { + this.world.makeSound(entityhuman, "random.pop", 0.2F, ((random.nextFloat() - random.nextFloat()) * 0.7F + 1.0F) * 2.0F); + } + + entityhuman.receive(this, i); + if (itemstack.count <= 0) { + this.die(); + } + } + } + + public String getName() { + return this.hasCustomName() ? this.getCustomName() : LocaleI18n.get("item." + this.getItemStack().a()); + } + + public boolean aD() { + return false; + } + + public void c(int i) { + super.c(i); + ItemStack itemStack = this.getItemStack(); + if (itemStack != null) + this.w(itemStack); + } + + public ItemStack getItemStack() { + ItemStack itemstack = this.getDataWatcher().getItemStack(10); + + if (itemstack == null) { + if (this.world != null) { + EntityItem.b.error("Item entity {} has no item?!", this.getId()); + } + + return new ItemStack(Blocks.STONE); + } else { + return itemstack; + } + } + + public void setItemStack(ItemStack itemstack) { + this.getDataWatcher().watch(10, itemstack); + this.getDataWatcher().update(10); + } + + public String m() { + return this.g; + } + + public void b(String s) { + this.g = s; + } + + public String n() { + return this.f; + } + + public void c(String s) { + this.f = s; + } + + public void p() { + this.pickupDelay = 10; + } + + public void q() { + this.pickupDelay = 0; + } + + public void r() { + this.pickupDelay = 32767; + } + + public void a(int i) { + this.pickupDelay = i; + } + + public boolean s() { + return this.pickupDelay > 0; + } + + public void u() { + this.age = -6000; + } + + public void v() { + this.r(); + this.age = 5999; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityItemFrame.java b/azurite-server/src/main/java/net/minecraft/server/EntityItemFrame.java new file mode 100644 index 0000000..bff1b34 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityItemFrame.java @@ -0,0 +1,183 @@ +package net.minecraft.server; + +import org.apache.commons.codec.Charsets; + +import java.util.UUID; + +public class EntityItemFrame extends EntityHanging { + + private float c = 1.0F; + + public EntityItemFrame(World world) { + super(world); + } + + public EntityItemFrame(World world, BlockPosition blockposition, EnumDirection enumdirection) { + super(world, blockposition); + this.setDirection(enumdirection); + } + + protected void h() { + this.getDataWatcher().add(8, 5); + this.getDataWatcher().a(9, (byte) 0); + } + + public float ao() { + return 0.0F; + } + + public boolean damageEntity(DamageSource damagesource, float f) { + if (this.isInvulnerable(damagesource)) { + return false; + } else if (!damagesource.isExplosion() && this.getItem() != null) { + // CraftBukkit start - fire EntityDamageEvent + if (org.bukkit.craftbukkit.event.CraftEventFactory.handleNonLivingEntityDamageEvent(this, damagesource, f, false) || this.dead) { + return true; + } + // CraftBukkit end + this.a(damagesource.getEntity(), false); + this.setItem(null); + return true; + } else { + return super.damageEntity(damagesource, f); + } + } + + public int l() { + return 12; + } + + public int m() { + return 12; + } + + public void b(Entity entity) { + this.a(entity, true); + } + + public void a(Entity entity, boolean flag) { + if (this.world.getGameRules().getBoolean("doEntityDrops")) { + ItemStack itemstack = this.getItem(); + + if (entity instanceof EntityHuman) { + EntityHuman entityhuman = (EntityHuman) entity; + + if (entityhuman.abilities.canInstantlyBuild) { + this.b(itemstack); + return; + } + } + + if (flag) { + this.a(new ItemStack(Items.ITEM_FRAME), 0.0F); + } + + if (itemstack != null && random.nextFloat() < this.c) { + itemstack = itemstack.cloneItemStack(); + this.b(itemstack); + this.a(itemstack, 0.0F); + } + + } + } + + private void b(ItemStack itemstack) { + if (itemstack != null) { + if (itemstack.getItem() == Items.FILLED_MAP) { + WorldMap worldmap = ((ItemWorldMap) itemstack.getItem()).getSavedMap(itemstack, this.world); + + worldmap.decorations.remove(UUID.nameUUIDFromBytes(("frame-" + this.getId()).getBytes(Charsets.US_ASCII))); // Spigot + } + + itemstack.a((EntityItemFrame) null); + } + } + + public ItemStack getItem() { + return this.getDataWatcher().getItemStack(8); + } + + public void setItem(ItemStack itemstack) { + this.setItem(itemstack, true); + } + + private void setItem(ItemStack itemstack, boolean flag) { + if (itemstack != null) { + itemstack = itemstack.cloneItemStack(); + itemstack.count = 1; + itemstack.a(this); + } + + this.getDataWatcher().watch(8, itemstack); + this.getDataWatcher().update(8); + if (flag && this.blockPosition != null) { + world.updateAdjacentComparators(blockPosition, Blocks.AIR); + } + + } + + public int getRotation() { + return this.getDataWatcher().getByte(9); + } + + public void setRotation(int i) { + this.setRotation(i, true); + } + + private void setRotation(int i, boolean flag) { + this.getDataWatcher().watch(9, (byte) (i % 8)); + if (flag && this.blockPosition != null) { + world.updateAdjacentComparators(blockPosition, Blocks.AIR); + } + + } + + public void b(NBTTagCompound nbttagcompound) { + if (this.getItem() != null) { + nbttagcompound.set("Item", this.getItem().save(new NBTTagCompound())); + nbttagcompound.setByte("ItemRotation", (byte) this.getRotation()); + nbttagcompound.setFloat("ItemDropChance", this.c); + } + + super.b(nbttagcompound); + } + + public void a(NBTTagCompound nbttagcompound) { + NBTTagCompound nbttagcompound1 = nbttagcompound.getCompound("Item"); + + if (nbttagcompound1 != null && !nbttagcompound1.isEmpty()) { + this.setItem(ItemStack.createStack(nbttagcompound1), false); + this.setRotation(nbttagcompound.getByte("ItemRotation"), false); + if (nbttagcompound.hasKeyOfType("ItemDropChance", 99)) { + this.c = nbttagcompound.getFloat("ItemDropChance"); + } + + if (nbttagcompound.hasKey("Direction")) { + this.setRotation(this.getRotation() * 2, false); + } + } + + super.a(nbttagcompound); + } + + public boolean e(EntityHuman entityhuman) { + if (this.getItem() == null) { + ItemStack itemstack = entityhuman.bA(); + + if (itemstack != null) { + this.setItem(itemstack); + if (!entityhuman.abilities.canInstantlyBuild && --itemstack.count <= 0) { + entityhuman.inventory.setItem(entityhuman.inventory.itemInHandIndex, null); + } + } + } else { + this.setRotation(this.getRotation() + 1); + } + + return true; + } + + public int q() { + return this.getItem() == null ? 0 : this.getRotation() % 8 + 1; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityLargeFireball.java b/azurite-server/src/main/java/net/minecraft/server/EntityLargeFireball.java new file mode 100644 index 0000000..8a00604 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityLargeFireball.java @@ -0,0 +1,52 @@ +package net.minecraft.server; + +import org.bukkit.event.entity.ExplosionPrimeEvent; + +public class EntityLargeFireball extends EntityFireball { + + public int yield = 1; + + public EntityLargeFireball(World world) { + super(world); + } + + public EntityLargeFireball(World world, EntityLiving entityliving, double d0, double d1, double d2) { + super(world, entityliving, d0, d1, d2); + } + + protected void a(MovingObjectPosition movingobjectposition) { + + if (movingobjectposition.entity != null) { + movingobjectposition.entity.damageEntity(DamageSource.fireball(this, this.shooter), 6.0F); + this.a(this.shooter, movingobjectposition.entity); + } + + boolean flag = this.world.getGameRules().getBoolean("mobGriefing"); + + // CraftBukkit start - fire ExplosionPrimeEvent + ExplosionPrimeEvent event = new ExplosionPrimeEvent((org.bukkit.entity.Explosive) org.bukkit.craftbukkit.entity.CraftEntity.getEntity(this.world.getServer(), this)); + this.world.getServer().getPluginManager().callEvent(event); + + if (!event.isCancelled()) { + // give 'this' instead of (Entity) null so we know what causes the damage + this.world.createExplosion(this, this.locX, this.locY, this.locZ, event.getRadius(), event.getFire(), flag); + } + // CraftBukkit end + this.die(); + + } + + public void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + nbttagcompound.setInt("ExplosionPower", this.yield); + } + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + if (nbttagcompound.hasKeyOfType("ExplosionPower", 99)) { + // CraftBukkit - set bukkitYield when setting explosionpower + bukkitYield = this.yield = nbttagcompound.getInt("ExplosionPower"); + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityLeash.java b/azurite-server/src/main/java/net/minecraft/server/EntityLeash.java new file mode 100644 index 0000000..424a5e0 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityLeash.java @@ -0,0 +1,139 @@ +package net.minecraft.server; + +import org.bukkit.craftbukkit.event.CraftEventFactory; + +import java.util.Iterator; +import java.util.List; + +public class EntityLeash extends EntityHanging { + + public EntityLeash(World world) { + super(world); + } + + public EntityLeash(World world, BlockPosition blockposition) { + super(world, blockposition); + this.setPosition((double) blockposition.getX() + 0.5D, (double) blockposition.getY() + 0.5D, (double) blockposition.getZ() + 0.5D); + this.a(new AxisAlignedBB(this.locX - 0.1875D, this.locY - 0.25D + 0.125D, this.locZ - 0.1875D, this.locX + 0.1875D, this.locY + 0.25D + 0.125D, this.locZ + 0.1875D)); + } + + protected void h() { + super.h(); + } + + public void setDirection(EnumDirection enumdirection) {} + + public int l() { + return 9; + } + + public int m() { + return 9; + } + + public float getHeadHeight() { + return -0.0625F; + } + + public void b(Entity entity) {} + + public boolean d(NBTTagCompound nbttagcompound) { + return false; + } + + public void b(NBTTagCompound nbttagcompound) {} + + public void a(NBTTagCompound nbttagcompound) {} + + public boolean e(EntityHuman entityhuman) { + ItemStack itemstack = entityhuman.bA(); + boolean flag = false; + double d0; + List list; + Iterator iterator; + EntityInsentient entityinsentient; + + if (itemstack != null && itemstack.getItem() == Items.LEAD) { + d0 = 7.0D; + list = this.world.a(EntityInsentient.class, new AxisAlignedBB(this.locX - d0, this.locY - d0, this.locZ - d0, this.locX + d0, this.locY + d0, this.locZ + d0)); + iterator = list.iterator(); + + while (iterator.hasNext()) { + entityinsentient = iterator.next(); + if (entityinsentient.cc() && entityinsentient.getLeashHolder() == entityhuman) { + // CraftBukkit start + if (CraftEventFactory.callPlayerLeashEntityEvent(entityinsentient, this, entityhuman).isCancelled()) { + entityhuman.sendPacket(new PacketPlayOutAttachEntity(1, entityinsentient, entityinsentient.getLeashHolder())); + continue; + } + // CraftBukkit end + entityinsentient.setLeashHolder(this, true); + flag = true; + } + } + } + + if (!flag) { + // CraftBukkit start - Move below + // this.die(); + boolean die = true; + // CraftBukkit end + // CraftBukkit - Process for non-creative as well + d0 = 7.0D; + list = this.world.a(EntityInsentient.class, new AxisAlignedBB(this.locX - d0, this.locY - d0, this.locZ - d0, this.locX + d0, this.locY + d0, this.locZ + d0)); + iterator = list.iterator(); + + while (iterator.hasNext()) { + entityinsentient = iterator.next(); + if (entityinsentient.cc() && entityinsentient.getLeashHolder() == this) { + // CraftBukkit start + if (CraftEventFactory.callPlayerUnleashEntityEvent(entityinsentient, entityhuman).isCancelled()) { + die = false; + continue; + } + entityinsentient.unleash(true, !entityhuman.abilities.canInstantlyBuild); // false -> survival mode boolean + // CraftBukkit end + } + } + // CraftBukkit start + if (die) { + this.die(); + } + // CraftBukkit end + } + + return true; + } + + public boolean survives() { + return this.world.getType(this.blockPosition).getBlock() instanceof BlockFence; + } + + public static EntityLeash a(World world, BlockPosition blockposition) { + EntityLeash entityleash = new EntityLeash(world, blockposition); + + entityleash.attachedToPlayer = true; + world.addEntity(entityleash); + return entityleash; + } + + public static EntityLeash b(World world, BlockPosition blockposition) { + int i = blockposition.getX(); + int j = blockposition.getY(); + int k = blockposition.getZ(); + List list = world.a(EntityLeash.class, new AxisAlignedBB((double) i - 1.0D, (double) j - 1.0D, (double) k - 1.0D, (double) i + 1.0D, (double) j + 1.0D, (double) k + 1.0D)); + Iterator iterator = list.iterator(); + + EntityLeash entityleash; + + do { + if (!iterator.hasNext()) { + return null; + } + + entityleash = iterator.next(); + } while (!entityleash.getBlockPosition().equals(blockposition)); + + return entityleash; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityLightning.java b/azurite-server/src/main/java/net/minecraft/server/EntityLightning.java new file mode 100644 index 0000000..700b51f --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityLightning.java @@ -0,0 +1,132 @@ +package net.minecraft.server; + +import org.bukkit.craftbukkit.event.CraftEventFactory; + +import java.util.List; + +public class EntityLightning extends EntityWeather { + + public long a; + // CraftBukkit start + public boolean isEffect; + public boolean isSilent = false; // Spigot + private int lifeTicks; + private int c; + + public EntityLightning(World world, double d0, double d1, double d2) { + this(world, d0, d1, d2, false); + } + + public EntityLightning(World world, double d0, double d1, double d2, boolean isEffect) { + // CraftBukkit end + super(world); + + // CraftBukkit - Set isEffect + this.isEffect = isEffect; + + this.setPositionRotation(d0, d1, d2, 0.0F, 0.0F); + this.lifeTicks = 2; + this.a = random.nextLong(); + this.c = random.nextInt(3) + 1; + BlockPosition blockposition = new BlockPosition(this); + + // CraftBukkit - add "!isEffect" + if (!isEffect && world.getGameRules().getBoolean("doFireTick") && (world.getDifficulty() == EnumDifficulty.NORMAL || world.getDifficulty() == EnumDifficulty.HARD) && world.areChunksLoaded(blockposition, 10)) { + if (world.getType(blockposition).getBlock().getMaterial() == Material.AIR && Blocks.FIRE.canPlace(world, blockposition)) { + // CraftBukkit start + if (!CraftEventFactory.callBlockIgniteEvent(world, blockposition.getX(), blockposition.getY(), blockposition.getZ(), this).isCancelled()) { + world.setTypeUpdate(blockposition, Blocks.FIRE.getBlockData()); + } + // CraftBukkit end + } + + for (int i = 0; i < 4; ++i) { + int x = blockposition.getX() + random.nextInt(3) - 1; + int y = blockposition.getY() + random.nextInt(3) - 1; + int z = blockposition.getZ() + random.nextInt(3) - 1; + + if (world.getType(x, y, z).getBlock().getMaterial() == Material.AIR && Blocks.FIRE.canPlace(world, x, y, z)) { + // CraftBukkit start + if (!CraftEventFactory.callBlockIgniteEvent(world, x, y, z, this).isCancelled()) { + world.setTypeUpdate(new BlockPosition(x, y, z), Blocks.FIRE.getBlockData()); + } + // CraftBukkit end + } + } + } + } + + // Spigot start + public EntityLightning(World world, double d0, double d1, double d2, boolean isEffect, boolean isSilent) { + this(world, d0, d1, d2, isEffect); + this.isSilent = isSilent; + } + // Spigot end + + public void t_() { + super.t_(); + if (!isSilent && this.lifeTicks == 2) { // Spigot + // CraftBukkit start - Use relative location for far away sounds + //this.world.makeSound(this.locX, this.locY, this.locZ, "ambient.weather.thunder", 10000.0F, 0.8F + random.nextFloat() * 0.2F); + float pitch = 0.8F + random.nextFloat() * 0.2F; + int viewDistance = this.world.getServer().getViewDistance() * 16; + int squaredDistance = viewDistance * viewDistance; + for (EntityHuman human : this.world.players) { + EntityPlayer player = (EntityPlayer) human; + double deltaX = this.locX - player.locX; + double deltaZ = this.locZ - player.locZ; + double distanceSquared = deltaX * deltaX + deltaZ * deltaZ; + if (distanceSquared > squaredDistance) { + double deltaLength = Math.sqrt(distanceSquared); + double relativeX = player.locX + (deltaX / deltaLength) * viewDistance; + double relativeZ = player.locZ + (deltaZ / deltaLength) * viewDistance; + player.playerConnection.sendPacket(new PacketPlayOutNamedSoundEffect("ambient.weather.thunder", relativeX, this.locY, relativeZ, 10000.0F, pitch)); + } else { + player.playerConnection.sendPacket(new PacketPlayOutNamedSoundEffect("ambient.weather.thunder", this.locX, this.locY, this.locZ, 10000.0F, pitch)); + } + } + // CraftBukkit end + this.world.makeSound(this.locX, this.locY, this.locZ, "random.explode", 2.0F, 0.5F + random.nextFloat() * 0.2F); + } + + --this.lifeTicks; + if (this.lifeTicks < 0) { + if (this.c == 0) { + this.die(); + } else if (this.lifeTicks < -random.nextInt(10)) { + --this.c; + this.lifeTicks = 1; + this.a = random.nextLong(); + BlockPosition blockposition = new BlockPosition(this); + + // CraftBukkit - add "!isEffect" + if (world.getGameRules().getBoolean("doFireTick") && this.world.areChunksLoaded(blockposition, 10) && this.world.getType(blockposition).getBlock().getMaterial() == Material.AIR && Blocks.FIRE.canPlace(this.world, blockposition)) { + // CraftBukkit start + if (!isEffect && !CraftEventFactory.callBlockIgniteEvent(world, blockposition.getX(), blockposition.getY(), blockposition.getZ(), this).isCancelled()) { + this.world.setTypeUpdate(blockposition, Blocks.FIRE.getBlockData()); + } + // CraftBukkit end + } + } + } + + if (this.lifeTicks >= 0 && !this.isEffect) { // CraftBukkit - add !this.isEffect + double d0 = 3.0D; + List list = this.world.getEntities(this, new AxisAlignedBB(this.locX - d0, this.locY - d0, this.locZ - d0, this.locX + d0, this.locY + 6.0D + d0, this.locZ + d0)); + + for (Entity entity : list) { + entity.onLightningStrike(this); + } + } + + } + + protected void h() { + } + + protected void a(NBTTagCompound nbttagcompound) { + } + + protected void b(NBTTagCompound nbttagcompound) { + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityLiving.java b/azurite-server/src/main/java/net/minecraft/server/EntityLiving.java new file mode 100644 index 0000000..1f62b76 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityLiving.java @@ -0,0 +1,1803 @@ +package net.minecraft.server; + +// CraftBukkit start + +import com.eatthepath.uuid.FastUUID; +import com.google.common.base.Function; +import com.google.common.base.Predicates; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Multimap; +import dev.azurite.spigot.Azurite; +import dev.azurite.spigot.configs.AzuriteConfig; +import dev.azurite.spigot.knockback.Knockback; +import dev.azurite.spigot.knockback.KnockbackType; +import dev.azurite.spigot.knockback.event.ArrowBypassNoDamageTicksEvent; +import dev.azurite.spigot.knockback.types.SimpleKnockback; +import dev.azurite.spigot.utils.CraftPotionUtils; +import org.bukkit.Bukkit; +import org.bukkit.craftbukkit.event.CraftEventFactory; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Vehicle; +import org.bukkit.event.entity.*; +import org.bukkit.event.vehicle.VehicleExitEvent; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; +import org.spigotmc.event.entity.EntityDismountEvent; + +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; + +public abstract class EntityLiving extends Entity { + + private static final UUID a = FastUUID.parseUUID("662A6B8D-DA3E-4C1C-8813-96EA6097278D"); + private static final AttributeModifier b = (new AttributeModifier(EntityLiving.a, "Sprinting speed boost", + 0.30000001192092896D, 2)).a(false); + public final Map effects = new ConcurrentHashMap<>(); + public final ItemStack[] h = new ItemStack[5]; + // Spigot endCombatTracker + + public CombatTracker combatTracker = new CombatTracker(this); + public boolean ar; + public int as; + public int at; + public int hurtTicks; + public int av; + public float aw; + public int deathTicks; + public float ay; + public float az; + public float aA; + public float aB; + public float aC; + public int maxNoDamageTicks = 20; + public float aE; + public float aF; + public float aG; + public float aH; + public float aI; + public float aJ; + public float aK; + public float aL; + public float aM = 0.02F; + public EntityHuman killer; + public float lastDamage; + public float aZ; + public float ba; + public boolean updateEffects = true; + public EntityLiving lastDamager; + public int hurtTimestamp; + // CraftBukkit start + public int expToDrop; + public int maxAirTicks = 300; + protected int lastDamageByPlayerTime; + protected boolean aP; + protected int ticksFarFromPlayer; + protected float aR; + protected float aS; + protected float aT; + protected float aU; + protected float aV; + protected int aW; + protected boolean aY; + protected float bb; + protected int bc; + protected double bd; + protected double be; + protected double bf; + protected double bg; + protected double bh; + ArrayList drops = null; + private AttributeMapBase c; + private EntityLiving bk; + private int bl; + private float bm; + private int bn; + private float bo; + + public EntityLiving(World world) { + super(world); + this.initAttributes(); + // CraftBukkit - setHealth(getMaxHealth()) inlined and simplified to skip the + // instanceof check for EntityPlayer, as getBukkitEntity() is not initialized in + // constructor + // Beanes - reduce packets + float hp = (float) this.getAttributeInstance(GenericAttributes.maxHealth).getValue(); + if (hp > 0.0F) { + this.datawatcher.setWithoutUpdate(6, hp); + } else { + this.datawatcher.watch(6, hp); + } + + this.k = true; + this.aH = (float) ((Math.random() + 1.0D) * 0.009999999776482582D); + this.setPosition(this.locX, this.locY, this.locZ); + this.aG = (float) Math.random() * 12398.0F; + this.yaw = (float) (Math.random() * 3.1415927410125732D * 2.0D); + this.aK = this.yaw; + this.S = 0.6F; + } + + // CraftBukkit end + // Spigot start + public void inactiveTick() { + super.inactiveTick(); + ++this.ticksFarFromPlayer; // Above all the floats + } + + public void G() { + this.damageEntity(DamageSource.OUT_OF_WORLD, Float.MAX_VALUE); + } + + protected void h() { + this.datawatcher.a(7, 0); + this.datawatcher.a(8, (byte) 0); + this.datawatcher.a(9, (byte) 0); + this.datawatcher.a(6, 1.0F); + } + + protected void initAttributes() { + this.getAttributeMap().b(GenericAttributes.maxHealth); + this.getAttributeMap().b(GenericAttributes.c); + this.getAttributeMap().b(GenericAttributes.MOVEMENT_SPEED); + } + + protected void a(double d0, boolean flag, Block block, BlockPosition blockposition) { + if (!this.V()) { + this.W(); + } + super.a(d0, flag, block, blockposition); + } + + public boolean aY() { + return false; + } + // CraftBukkit end + + public void K() { + ay = az; + super.K(); + + boolean flag = this instanceof EntityHuman; + + if (isAlive()) { + if (inBlock()) { // Vortex - Don't check inBlock if entity is undamageable + this.damageEntity(DamageSource.STUCK, 1.0F); + } else if (AzuriteConfig.playerBorderDamage.getValue() && flag && !world.getWorldBorder().a(boundingBox)) { + double d0 = world.getWorldBorder().a(this) + world.getWorldBorder().getDamageBuffer(); + if (d0 < 0.0D) + damageEntity(DamageSource.STUCK, Math.max(1, MathHelper.floor(-d0 * world.getWorldBorder().getDamageAmount()))); + } + } + + if (isFireProof()) { + extinguish(); + } + + boolean flag1 = flag && ((EntityHuman) this).abilities.isInvulnerable; + + if (isAlive()) { + if (a(Material.WATER)) { + if (!aY() && !hasEffect(MobEffectList.WATER_BREATHING.id) && !flag1) { + setAirTicks(j(getAirTicks())); + if (getAirTicks() == -20) { + setAirTicks(0); + damageEntity(DamageSource.DROWN, 2.0F); + } + } + if (au() && vehicle instanceof EntityLiving) + mount(null); + } else if (getAirTicks() != 300) { + setAirTicks(maxAirTicks); + } + } + + if (isAlive() && U()) + extinguish(); + + aE = aF; + + if (hurtTicks > 0) { + --hurtTicks; + } + + if (noDamageTicks > 0 && !(this instanceof EntityPlayer)) { + --noDamageTicks; + } + + // Azurite start - Arrow bounce off fix + if (noDamageTicksArrow > 0 && !(this instanceof EntityPlayer)) { + --noDamageTicksArrow; + } + // Azurite end + + if (getHealth() <= 0.0F) + aZ(); + + if (lastDamageByPlayerTime > 0) { + --lastDamageByPlayerTime; + } else { + killer = null; + } + + if (bk != null && !bk.isAlive()) { + bk = null; + } + + if (lastDamager != null) { + if (!lastDamager.isAlive()) { + b((EntityLiving) null); + } else if (ticksLived - hurtTimestamp > 100) { + b((EntityLiving) null); + } + } + + bi(); + aU = aT; + aJ = aI; + aL = aK; + lastYaw = yaw; + lastPitch = pitch; + } + + // CraftBukkit start + public int getExpReward() { + int exp = this.getExpValue(this.killer); + + if ((this.lastDamageByPlayerTime > 0 || this.alwaysGivesExp()) && this.ba() && this.world.getGameRules().getBoolean("doMobLoot")) { + return exp; + } else { + return 0; + } + } + + public boolean isBaby() { + return false; + } + + protected void aZ() { + ++this.deathTicks; + if (this.deathTicks >= 20 && !this.dead) { // CraftBukkit - (this.deathTicks == 20) -> (this.deathTicks >= 20 && + // !this.dead) + int i; + + // CraftBukkit start - Update getExpReward() above if the removed if() changes! + i = this.expToDrop; + while (i > 0) { + int j = EntityExperienceOrb.getOrbValue(i); + i -= j; + this.world.addEntity(new EntityExperienceOrb(this.world, this.locX, this.locY, this.locZ, j)); + } + this.expToDrop = 0; + // CraftBukkit end + + this.die(); + + for (i = 0; i < 20; ++i) + this.world.addParticle(EnumParticle.EXPLOSION_NORMAL, + this.locX + (random.nextFloat() * this.width * 2.0F) - this.width, + this.locY + (random.nextFloat() * this.length), + this.locZ + (random.nextFloat() * this.width * 2.0F) - this.width, + random.nextGaussian() * 0.02D, random.nextGaussian() * 0.02D, + random.nextGaussian() * 0.02D, EnumParticle.EMPTY_ARRAY); + } + + } + + protected boolean ba() { + return !this.isBaby(); + } + + protected int j(int i) { + int j = EnchantmentManager.getOxygenEnchantmentLevel(this); + + return j > 0 && random.nextInt(j + 1) > 0 ? i : i - 1; + } + + protected int getExpValue(EntityHuman entityhuman) { + return 0; + } + + protected boolean alwaysGivesExp() { + return false; + } + + public Random bc() { + return random; + } + + public EntityLiving getLastDamager() { + return this.lastDamager; + } + + public int be() { + return this.hurtTimestamp; + } + + public void b(EntityLiving entityliving) { + this.lastDamager = entityliving; + this.hurtTimestamp = this.ticksLived; + } + + public EntityLiving bf() { + return this.bk; + } + + public int bg() { + return this.bl; + } + + public void p(Entity entity) { + if (entity instanceof EntityLiving) { + this.bk = (EntityLiving) entity; + } else { + this.bk = null; + } + + this.bl = this.ticksLived; + } + + public int bh() { + return this.ticksFarFromPlayer; + } + + public void b(NBTTagCompound nbttagcompound) { + nbttagcompound.setFloat("HealF", this.getHealth()); + nbttagcompound.setShort("Health", (short) ((int) Math.ceil(this.getHealth()))); + nbttagcompound.setShort("HurtTime", (short) this.hurtTicks); + nbttagcompound.setInt("HurtByTimestamp", this.hurtTimestamp); + nbttagcompound.setShort("DeathTime", (short) this.deathTicks); + nbttagcompound.setFloat("AbsorptionAmount", this.getAbsorptionHearts()); + + for (ItemStack itemstack : getEquipment()) { + if (itemstack != null) { + Multimap tag = itemstack.B(); + this.c.a(tag); + this.c.b(tag); + } + } + + nbttagcompound.set("Attributes", GenericAttributes.a(this.getAttributeMap())); + + if (!this.effects.isEmpty()) { + NBTTagList nbttaglist = new NBTTagList(); + + for (MobEffect mobEffect : this.effects.values()) { + nbttaglist.add(mobEffect.a(new NBTTagCompound())); + } + + nbttagcompound.set("ActiveEffects", nbttaglist); + } + + } + + public void a(NBTTagCompound nbttagcompound) { + this.setAbsorptionHearts(nbttagcompound.getFloat("AbsorptionAmount")); + if (nbttagcompound.hasKeyOfType("Attributes", 9) && this.world != null) { + GenericAttributes.a(this.getAttributeMap(), nbttagcompound.getList("Attributes", 10)); + } + + if (nbttagcompound.hasKeyOfType("ActiveEffects", 9)) { + NBTTagList nbttaglist = nbttagcompound.getList("ActiveEffects", 10); + + for (int i = 0; i < nbttaglist.size(); ++i) { + NBTTagCompound nbttagcompound1 = nbttaglist.get(i); + MobEffect mobeffect = MobEffect.b(nbttagcompound1); + + if (mobeffect != null) { + this.effects.put(mobeffect.getEffectId(), mobeffect); + } + } + } + + // CraftBukkit start + if (nbttagcompound.hasKey("Bukkit.MaxHealth")) { + NBTBase nbtbase = nbttagcompound.get("Bukkit.MaxHealth"); + if (nbtbase.getTypeId() == 5) { + this.getAttributeInstance(GenericAttributes.maxHealth).setValue((double) ((NBTTagFloat) nbtbase).c()); + } else if (nbtbase.getTypeId() == 3) { + this.getAttributeInstance(GenericAttributes.maxHealth).setValue(((NBTTagInt) nbtbase).d()); + } + } + // CraftBukkit end + + if (nbttagcompound.hasKeyOfType("HealF", 99)) { + this.setHealth(nbttagcompound.getFloat("HealF")); + } else { + NBTBase nbtbase = nbttagcompound.get("Health"); + + if (nbtbase == null) { + this.setHealth(this.getMaxHealth()); + } else if (nbtbase.getTypeId() == 5) { + this.setHealth(((NBTTagFloat) nbtbase).h()); + } else if (nbtbase.getTypeId() == 2) { + this.setHealth(((NBTTagShort) nbtbase).e()); + } + } + + this.hurtTicks = nbttagcompound.getShort("HurtTime"); + this.deathTicks = nbttagcompound.getShort("DeathTime"); + this.hurtTimestamp = nbttagcompound.getInt("HurtByTimestamp"); + } + // CraftBukkit end + + public void bi() { + Iterator iterator = this.effects.keySet().iterator(); + + while (iterator.hasNext()) { + Integer integer = iterator.next(); + MobEffect mobeffect = this.effects.get(integer); + if (!mobeffect.tick(this)) { + PotionEffectExpireEvent event = new PotionEffectExpireEvent((LivingEntity) getBukkitEntity(), new PotionEffect(PotionEffectType.getById(mobeffect.getEffectId()), mobeffect.getDuration(), mobeffect.getAmplifier(), mobeffect.isAmbient())); + this.world.getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { + CraftPotionUtils.extendDuration(mobeffect, event.getDuration()); + continue; + } + iterator.remove(); + b(mobeffect); + continue; + } + if (mobeffect.getDuration() % 600 == 0) + a(mobeffect, false); + } + + if (this.updateEffects) { + B(); + this.updateEffects = false; + } + + int i = this.datawatcher.getInt(7); + boolean flag = this.datawatcher.getByte(8) > 0; + + if (i > 0) { + boolean flag1; + + if (!this.isInvisible()) { + flag1 = random.nextBoolean(); + } else { + flag1 = random.nextInt(15) == 0; + } + + if (flag) { + flag1 &= random.nextInt(5) == 0; + } + + if (flag1) { + this.world.addParticle(flag ? EnumParticle.SPELL_MOB_AMBIENT : EnumParticle.SPELL_MOB, + this.locX + (random.nextDouble() - 0.5D) * this.width, + this.locY + random.nextDouble() * (double) this.length, + this.locZ + (random.nextDouble() - 0.5D) * this.width, (i >> 16 & 255) / 255.0D, + (i >> 8 & 255) / 255.0D, (i & 255) / 255.0D, EnumParticle.EMPTY_ARRAY); + } + } + + } + + protected void B() { + if (this.effects.isEmpty()) { + bj(); + setInvisible(false); + } else { + int i = PotionBrewer.a(effects.values()); + datawatcher.watch(8, (byte) (PotionBrewer.b(effects.values()) ? 1 : 0)); + datawatcher.watch(7, i); + setInvisible(hasEffect(MobEffectList.INVISIBILITY.id)); + } + } + + protected void bj() { + datawatcher.watch(8, (byte) 0); + datawatcher.watch(7, 0); + } + + public void removeAllEffects() { + Iterator iterator = this.effects.keySet().iterator(); + while (iterator.hasNext()) { + Integer integer = iterator.next(); + MobEffect mobeffect = this.effects.get(integer); + PotionEffectRemoveEvent event = new PotionEffectRemoveEvent((LivingEntity) getBukkitEntity(), new PotionEffect(PotionEffectType.getById(mobeffect.getEffectId()), mobeffect.getDuration(), mobeffect.getAmplifier(), mobeffect.isAmbient())); + this.world.getServer().getPluginManager().callEvent(event); + iterator.remove(); + b(mobeffect); + } + } + + // Beanes - make an option for milk to only remove bad effects + private static final Set BAD_EFFECTS = ImmutableSet.of( + MobEffectList.SLOWER_MOVEMENT.getId(), + MobEffectList.POISON.getId(), + MobEffectList.BLINDNESS.getId(), + MobEffectList.WEAKNESS.getId(), + MobEffectList.WITHER.getId(), + MobEffectList.CONFUSION.getId(), + MobEffectList.HUNGER.getId(), + MobEffectList.SLOWER_DIG.getId() + ); + + public void removeBadEffects() { + Iterator iterator = this.effects.keySet().iterator(); + + while (iterator.hasNext()) { + Integer integer = iterator.next(); + MobEffect mobeffect = this.effects.get(integer); + + if (BAD_EFFECTS.contains(mobeffect.getEffectId())) { + PotionEffectRemoveEvent event = new PotionEffectRemoveEvent((LivingEntity) getBukkitEntity(), new PotionEffect(PotionEffectType.getById(mobeffect.getEffectId()), mobeffect.getDuration(), mobeffect.getAmplifier(), mobeffect.isAmbient())); + this.world.getServer().getPluginManager().callEvent(event); + iterator.remove(); + b(mobeffect); + } + } + } + + + public Collection getEffects() { + return this.effects.values(); + } + + public boolean hasEffect(int i) { + return !this.effects.isEmpty() && this.effects.containsKey(i); + } + + public boolean hasEffect(MobEffectList mobeffectlist) { + return this.effects.containsKey(mobeffectlist.id); + } + + public MobEffect getEffect(MobEffectList mobeffectlist) { + return this.effects.get(mobeffectlist.id); + } + + public void addEffect(MobEffect mobeffect) { + addEffect(mobeffect, PotionEffectAddEvent.EffectCause.UNKNOWN); + } + + public void addEffect(MobEffect mobeffect, PotionEffectAddEvent.EffectCause cause) { + if (d(mobeffect)) { + MobEffect current = this.effects.get(mobeffect.getEffectId()); + + if (current != null) { + PotionEffectExtendEvent event = new PotionEffectExtendEvent((LivingEntity) this.getBukkitEntity(), + CraftPotionUtils.toBukkit(mobeffect), + CraftPotionUtils.toBukkit(current), cause); + + this.world.getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) return; + + current.a(mobeffect); + a(current, true); + + } else { + PotionEffectAddEvent event = new PotionEffectAddEvent((LivingEntity) this.getBukkitEntity(), + CraftPotionUtils.toBukkit(mobeffect), cause); + this.world.getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) return; + this.effects.put(mobeffect.getEffectId(), mobeffect); + a(mobeffect); + } + } + } + + public boolean d(MobEffect mobeffect) { + if (getMonsterType() == EnumMonsterType.UNDEAD) { + int i = mobeffect.getEffectId(); + return i != MobEffectList.REGENERATION.id && i != MobEffectList.POISON.id; + } + return true; + } + + public boolean bm() { + return (getMonsterType() == EnumMonsterType.UNDEAD); + } + + public void removeEffect(int i) { + MobEffect mobeffect = this.effects.remove(i); + if (mobeffect != null) { + PotionEffectRemoveEvent event = new PotionEffectRemoveEvent((LivingEntity) getBukkitEntity(), CraftPotionUtils.toBukkit(mobeffect)); + this.world.getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { + this.effects.put(i, mobeffect); + return; + } + b(mobeffect); + } + } + + protected void a(MobEffect mobeffect) { + this.updateEffects = true; + MobEffectList.byId[mobeffect.getEffectId()].b(this, getAttributeMap(), mobeffect.getAmplifier()); + } + + protected void a(MobEffect mobeffect, boolean flag) { + this.updateEffects = true; + if (flag) { + MobEffectList.byId[mobeffect.getEffectId()].a(this, getAttributeMap(), mobeffect.getAmplifier()); + MobEffectList.byId[mobeffect.getEffectId()].b(this, getAttributeMap(), mobeffect.getAmplifier()); + } + } + + protected void b(MobEffect mobeffect) { + this.updateEffects = true; + MobEffectList.byId[mobeffect.getEffectId()].a(this, getAttributeMap(), mobeffect.getAmplifier()); + } + + // CraftBukkit start - Delegate so we can handle providing a reason for health + // being regained + public void heal(float f) { + heal(f, EntityRegainHealthEvent.RegainReason.CUSTOM); + } + + public void heal(float f, EntityRegainHealthEvent.RegainReason regainReason) { + float f1 = this.getHealth(); + + if (f1 > 0.0F) { + EntityRegainHealthEvent event = new EntityRegainHealthEvent(this.getBukkitEntity(), f, regainReason); + this.world.getServer().getPluginManager().callEvent(event); + + if (!event.isCancelled()) { + this.setHealth((float) (this.getHealth() + event.getAmount())); + } + // CraftBukkit end + } + + } + + public final float getHealth() { + if (this instanceof EntityPlayer) + return (float) ((EntityPlayer) this).getBukkitEntity().getHealth(); + return datawatcher.getFloat(6); + } + + public void setHealth(float f) { + if (this instanceof EntityPlayer) { + org.bukkit.craftbukkit.entity.CraftPlayer player = ((EntityPlayer) this).getBukkitEntity(); + + if (f < 0.0F) { + player.setRealHealth(0.0D); + } else if (f > player.getMaxHealth()) { + player.setRealHealth(player.getMaxHealth()); + } else { + player.setRealHealth(f); + } + if (player.getHealth() != 0.0D || !AzuriteConfig.autoRespawnPlayer.getValue()) { + // Beanes - reduce packets + float hp = player.getScaledHealth(); + if (hp > 0.0F) { + this.datawatcher.setWithoutUpdate(6, hp); + } else { + this.datawatcher.watch(6, hp); + } + } + return; + } + + // Beanes - reduce packets + float hp = MathHelper.a(f, 0.0F, this.getMaxHealth()); + if (hp > 0.0F && (!(this instanceof EntityHorse) || !AzuriteConfig.horseHealthUpdates.getValue())) { + this.datawatcher.setWithoutUpdate(6, hp); + } else { + this.datawatcher.watch(6, hp); + } + } + + public boolean damageEntity(DamageSource damagesource, float amountOfDamage) { + if (isInvulnerable(damagesource)) + return false; + ticksFarFromPlayer = 0; + if (getHealth() <= 0.0F || damagesource.o() && hasEffect(MobEffectList.FIRE_RESISTANCE)) + return false; + + this.aB = 1.5F; + boolean shouldDealVelocity = true; + + // Azurite - Patch arrow bounce bug properly + boolean shouldUseArrowDamageTicks = AzuriteConfig.patchArrowBounceBug.getValue() && damagesource.translationIndex.equals("arrow"); + int customMaxNoDamageTicks = maxNoDamageTicks; + Knockback knockback = null; + + if (this instanceof EntityPlayer) { + EntityPlayer entityPlayer = (EntityPlayer) this; + knockback = entityPlayer.getKnockbackProfile(); + + // Beanes - plugin can cancel the arrow no damage ticks bypass + if (shouldUseArrowDamageTicks) { + ArrowBypassNoDamageTicksEvent event = new ArrowBypassNoDamageTicksEvent(entityPlayer.getBukkitEntity(), damagesource.getEntity().getBukkitEntity()); + event.callEvent(); + + if (event.isCancelled()) { + shouldUseArrowDamageTicks = false; + } + } + + customMaxNoDamageTicks = (shouldUseArrowDamageTicks ? knockback.hitDelayArrow.getValue() : knockback.hitDelay.getValue()); + } + + int currentTicks = (shouldUseArrowDamageTicks ? noDamageTicksArrow : noDamageTicks); + + // Beanes - no damage timee + long currentDamageTime = (shouldUseArrowDamageTicks ? noDamageTimeArrow : noDamageTime); + boolean isTime = AzuriteConfig.useSystemTimeForNoDamageTicks.getValue(); + boolean hitCooldown = isTime ? System.currentTimeMillis() < currentDamageTime : currentTicks > customMaxNoDamageTicks / 2.0F; + + if (customMaxNoDamageTicks > 0 && hitCooldown) { + // If damage is less or "patchDoubleHitBug (should be toggleDamageUpgrades)" is enabled don't damage upgrade + if (amountOfDamage <= this.lastDamage || (AzuriteConfig.patchDoubleHitBug.getValue() && damagesource.translationIndex.equals("player"))) { + forceExplosionKnockback = true; + return false; + } + + float damage = amountOfDamage - this.lastDamage; + + if (!d(damagesource, damage, true)) { + forceExplosionKnockback = true; + return false; + } + lastDamage = amountOfDamage; + shouldDealVelocity = false; + } else { + if (!d(damagesource, amountOfDamage, false)) + return false; + + lastDamage = amountOfDamage; + noDamageTicks = (knockback != null ? knockback.hitDelay.getValue() : maxNoDamageTicks); + noDamageTime = System.currentTimeMillis() + Math.round(noDamageTicks / 2.0D) * 50L; // Beanes - no damage time + hurtTicks = av = 10; + + // Only set noDamageTicksArrow if they were hit by an arrow + if (shouldUseArrowDamageTicks && knockback != null) { + noDamageTicksArrow = knockback.hitDelayArrow.getValue(); + noDamageTimeArrow = System.currentTimeMillis() + Math.round(noDamageTicksArrow / 2.0D) * 50L; // Beanes - no damage time + } + } + + if (this instanceof EntityAnimal) { + ((EntityAnimal) this).cq(); + if (this instanceof EntityTameableAnimal) + ((EntityTameableAnimal) this).getGoalSit().setSitting(false); + } + + aw = 0.0F; + Entity entity = damagesource.getEntity(); + if (entity != null) { + if (entity instanceof EntityLiving) + b((EntityLiving) entity); + if (entity instanceof EntityHuman) { + lastDamageByPlayerTime = 100; + killer = (EntityHuman) entity; + } else if (entity instanceof EntityWolf) { + EntityWolf entitywolf = (EntityWolf) entity; + if (entitywolf.isTamed()) { + lastDamageByPlayerTime = 100; + killer = null; + } + } + } + + boolean knockbackCancelled = false; + if (shouldDealVelocity) + if (!(knockbackCancelled = (world.paperSpigotConfig.disableExplosionKnockback && damagesource.isExplosion() && this instanceof EntityHuman))) { + world.broadcastEntityEffect(this, (byte) 2); + if (damagesource != DamageSource.DROWN) + ac(); + if (entity != null) { + double d0 = entity.locX - this.locX; + double d1; + for (d1 = entity.locZ - this.locZ; d0 * d0 + d1 * d1 < 1.0E-4D; d1 = (Math.random() - Math.random()) * 0.01D) + d0 = (Math.random() - Math.random()) * 0.01D; + this.aw = (float) (MathHelper.b(d1, d0) * 180.0D / 3.1415927410125732D - this.yaw); + a(entity, amountOfDamage, d0, d1); + } else { + this.aw = ((int) (Math.random() * 2.0D) * 180); + } + } + if (knockbackCancelled) + world.broadcastEntityEffect(this, (byte) 2); + + if (getHealth() <= 0.0F) { + String s = bp(); + if (shouldDealVelocity && s != null) + makeSound(s, bB(), bC()); + die(damagesource); + + if (AzuriteConfig.autoRespawnPlayer.getValue()) { + sendKnockbackRespawn = true; + } + + } else { + String s = bo(); + if (shouldDealVelocity && s != null) + makeSound(s, bB(), bC()); + } + return true; + } + + public void b(ItemStack itemstack) { + // Beanes - add option to hear own item break sound + this.makeSound("random.break", 0.8F, 0.8F + this.world.random.nextFloat() * 0.4F, AzuriteConfig.itemBreakSoundSelf.getValue()); + + for (int i = 0; i < 5; ++i) { + Vec3D vec3d = new Vec3D((random.nextFloat() - 0.5D) * 0.1D, Math.random() * 0.1D + 0.1D, + 0.0D); + + vec3d = vec3d.a(-this.pitch * 3.1415927F / 180.0F); + vec3d = vec3d.b(-this.yaw * 3.1415927F / 180.0F); + Vec3D vec3d1 = new Vec3D((random.nextFloat() - 0.5D) * 0.3D, -random.nextFloat() * 0.6D - 0.3D, 0.6D); + + vec3d1 = vec3d1.a(-this.pitch * 3.1415927F / 180.0F); + vec3d1 = vec3d1.b(-this.yaw * 3.1415927F / 180.0F); + vec3d1 = vec3d1.add(this.locX, this.locY + this.getHeadHeight(), this.locZ); + this.world.addParticle(EnumParticle.ITEM_CRACK, vec3d1.a, vec3d1.b, vec3d1.c, vec3d.a, vec3d.b + 0.05D, + vec3d.c, Item.getId(itemstack.getItem())); + } + } + + public void die(DamageSource damagesource) { + Entity entity = damagesource.getEntity(); + EntityLiving entityliving = bt(); + if (this.aW >= 0 && entityliving != null) + entityliving.b(this, this.aW); + if (entity != null) + entity.a(this); + this.aP = true; + bs().g(); + int i = 0; + if (entity instanceof EntityHuman) + i = EnchantmentManager.getBonusMonsterLootEnchantmentLevel((EntityLiving) entity); + if (ba() && this.world.getGameRules().getBoolean("doMobLoot")) { + this.drops = new ArrayList<>(); + dropDeathLoot((this.lastDamageByPlayerTime > 0), i); + dropEquipment((this.lastDamageByPlayerTime > 0), i); + if (this.lastDamageByPlayerTime > 0 && random.nextFloat() < 0.025F + i * 0.01F) + getRareDrop(); + CraftEventFactory.callEntityDeathEvent(this, this.drops); + this.drops = null; + } else { + CraftEventFactory.callEntityDeathEvent(this); + } + this.world.broadcastEntityEffect(this, (byte) 3); + } + + protected void dropEquipment(boolean flag, int i) { + } + + public void a(Entity attacker, float dmg, double diffX, double diffZ) { + if (disableKnockback) // Rivals + return; + + if (random.nextDouble() >= this.getAttributeInstance(GenericAttributes.c).getValue()) { + this.ai = true; + float magnitude = MathHelper.sqrt(diffX * diffX + diffZ * diffZ); + + if (AzuriteConfig.overrideDefaultKnockback.getValue() && this instanceof EntityHuman) { + Knockback profile = ((EntityHuman) this).getKnockbackProfile(); + + if (profile.getKnockbackType() == KnockbackType.SIMPLE) { + SimpleKnockback knockback = profile.simpleKnockback; + + this.motX /= knockback.friction.getValue(); + this.motY /= knockback.friction.getValue(); + this.motZ /= knockback.friction.getValue(); + + this.motX -= diffX / magnitude * knockback.horizontal.getValue(); + this.motY += knockback.vertical.getValue(); + this.motZ -= diffZ / magnitude * knockback.horizontal.getValue(); + + double verticalLimit = knockback.verticalLimit.getValue(); + + if (this.motY > verticalLimit) { + this.motY = verticalLimit; + } + return; + } + } + + this.motX /= 2.0D; + this.motY /= 2.0D; + this.motZ /= 2.0D; + this.motX -= diffX / (double) magnitude * (double) 0.4F; + this.motY += 0.4F; + this.motZ -= diffZ / (double) magnitude * (double) 0.4F; + if (this.motY > 0.4000000059604645D) { + this.motY = 0.4000000059604645D; + } + } + } + + protected String bo() { + return "game.neutral.hurt"; + } + + protected String bp() { + return "game.neutral.die"; + } + + protected void getRareDrop() { + } + + protected void dropDeathLoot(boolean flag, int i) { + } + + public boolean k_() { + if (!(this instanceof EntityHuman) || !((EntityHuman) this).isSpectator()) { + Block block = world.getType(MathHelper.floor(locX), MathHelper.floor(boundingBox.b), MathHelper.floor(locZ)).getBlock(); + return block == Blocks.LADDER || block == Blocks.VINE; + } + return false; + } + + public boolean isAlive() { + return !this.dead && this.getHealth() > 0.0F; + } + + public void e(float f, float f1) { + super.e(f, f1); + MobEffect mobeffect = this.getEffect(MobEffectList.JUMP); + float f2 = mobeffect != null ? (float) (mobeffect.getAmplifier() + 1) : 0.0F; + int i = MathHelper.f((f - 3.0F - f2) * f1); + + if (i > 0) { + // CraftBukkit start + if (!damageEntity(DamageSource.FALL, (float) (i * AzuriteConfig.fallDamageModifier.getValue()))) { + return; + } + // CraftBukkit end + this.makeSound(this.n(i), 1.0F, 1.0F); + + if (AzuriteConfig.footstepSounds.getValue()) { + Block block = world.getType(MathHelper.floor(locX), MathHelper.floor(locY - 0.20000000298023224D), MathHelper.floor(locZ)).getBlock(); + if (block.getMaterial() != Material.AIR) { + Block.StepSound block_stepsound = block.stepSound; + makeSound(block_stepsound.getStepSound(), block_stepsound.getVolume1() * 0.5F, block_stepsound.getVolume2() * 0.75F); + } + } + } + + } + + protected String n(int i) { + return i > 4 ? "game.neutral.hurt.fall.big" : "game.neutral.hurt.fall.small"; + } + + public int br() { + int i = 0; + for (ItemStack itemstack : getEquipment()) { + if (itemstack != null && itemstack.getItem() instanceof ItemArmor) { + i += ((ItemArmor) itemstack.getItem()).c; + } + } + + return i; + } + + protected void damageArmor(float f) { + } + + protected float applyArmorModifier(DamageSource damagesource, float f) { + if (!damagesource.ignoresArmor()) { + int i = 25 - br(); + float f1 = f * i; + + f = f1 / 25.0F; + } + + return f; + } + + protected float applyMagicModifier(DamageSource damagesource, float f) { + if (damagesource.isStarvation()) + return f; + if (f <= 0.0F) + return 0.0F; + int i = EnchantmentManager.a(getEquipment(), damagesource); + if (i > 20) + i = 20; + if (i > 0) { + int j = 25 - i; + float f1 = f * j; + f = f1 / AzuriteConfig.protectionModifier.getValue().floatValue(); + } + return f; + } + + protected boolean d(final DamageSource damagesource, float f) { + return this.d(damagesource, f, false); + } + + // Beanes - add damage upgrade to event + protected boolean d(final DamageSource damagesource, float f, boolean damageUpgrade) { + if (!isInvulnerable(damagesource)) { + boolean human = this instanceof EntityHuman; + float originalDamage = f; + ItemStack helmet = damagesource == DamageSource.ANVIL || damagesource == DamageSource.FALLING_BLOCK ? getEquipment(4) : null; + + Function hardHat = f12 -> helmet != null ? -(f12 - f12 * 0.75D) : -0.0D; + float hardHatModifier = hardHat.apply((double) f).floatValue(); + f += hardHatModifier; + + Function blocking = f13 -> { + if (human && !damagesource.ignoresArmor() && ((EntityHuman) this).isBlocking() && f13 > 0.0D && ((EntityHuman) this).checkBlock()) + return -(f13 - (1.0D + f13) * world.paperSpigotConfig.playerBlockingDamageMultiplier); + return -0.0D; + }; + float blockingModifier = blocking.apply((double) f).floatValue(); + f += blockingModifier; + + Function armor = f17 -> -(f17 - applyArmorModifier(damagesource, f17.floatValue())); + float armorModifier = armor.apply((double) f).floatValue(); + f += armorModifier; + + Function resistance = f16 -> { + if (!damagesource.isStarvation() && hasEffect(MobEffectList.RESISTANCE) && damagesource != DamageSource.OUT_OF_WORLD) { + int i = (getEffect(MobEffectList.RESISTANCE).getAmplifier() + 1) * 5; + int j = 25 - i; + float f1 = f16.floatValue() * j; + return -(f16 - (f1 / 25.0F)); + } + return -0.0D; + }; + float resistanceModifier = resistance.apply((double) f).floatValue(); + f += resistanceModifier; + + Function magic = f15 -> -(f15 - applyMagicModifier(damagesource, f15.floatValue())); + float magicModifier = magic.apply((double) f).floatValue(); + f += magicModifier; + + Function absorption = f14 -> -Math.max(f14 - Math.max(f14 - getAbsorptionHearts(), 0.0D), 0.0D); + float absorptionModifier = absorption.apply((double) f).floatValue(); + + EntityDamageEvent event = CraftEventFactory.handleLivingEntityDamageEvent(this, damagesource, originalDamage, hardHatModifier, blockingModifier, armorModifier, resistanceModifier, magicModifier, absorptionModifier, hardHat, blocking, armor, resistance, magic, absorption, damageUpgrade); + if (event.isCancelled()) + return false; + f = (float) event.getFinalDamage(); + + if (helmet != null) + helmet.damage((int) (event.getDamage() * 4.0D + random.nextFloat() * event.getDamage() * 2.0D), this); + + if (!damagesource.ignoresArmor()) { + float armorDamage = (float) (event.getDamage() + event.getDamage(EntityDamageEvent.DamageModifier.BLOCKING) + event.getDamage(EntityDamageEvent.DamageModifier.HARD_HAT)); + damageArmor(armorDamage); + } + + absorptionModifier = (float) -event.getDamage(EntityDamageEvent.DamageModifier.ABSORPTION); + setAbsorptionHearts(Math.max(getAbsorptionHearts() - absorptionModifier, 0.0F)); + + if (f != 0.0F) { + if (human) { + ((EntityHuman) this).applyExhaustion(damagesource.getExhaustionCost()); + if (f < 3.4028235E37F) { + ((EntityHuman) this).a(StatisticList.x, Math.round(f * 10.0F)); + } + } + float f2 = getHealth(); + setHealth(f2 - f); + bs().a(damagesource, f2, f); + if (human) + return true; + setAbsorptionHearts(getAbsorptionHearts() - f); + } + + return true; + } + return false; + } + + public CombatTracker bs() { + return this.combatTracker; + } + + public EntityLiving bt() { + return (this.combatTracker.c() != null ? this.combatTracker.c() + : (this.killer != null ? this.killer : (this.lastDamager != null ? this.lastDamager : null))); + } + + public final float getMaxHealth() { + return (float) this.getAttributeInstance(GenericAttributes.maxHealth).getValue(); + } + + public final int bv() { + return datawatcher.getByte(9); + } + + public final void o(int i) { + datawatcher.watch(9, AzuriteConfig.disableStuckArrows.getValue() ? 0 : (byte) i); + } + + private int n() { + return this.hasEffect(MobEffectList.FASTER_DIG) + ? 6 - (1 + getEffect(MobEffectList.FASTER_DIG).getAmplifier()) + : (hasEffect(MobEffectList.SLOWER_DIG) + ? 6 + (1 + getEffect(MobEffectList.SLOWER_DIG).getAmplifier()) * 2 + : 6); + } + + public void bw() { + if (!ar || as >= n() / 2 || as < 0) { + as = -1; + ar = true; + if (world instanceof WorldServer) { + // Azurite - Queue arm animations + EntityTrackerEntry entry = ((WorldServer) world).getTracker().trackedEntities.get(getId()); + + if (entry != null) { + entry.queueBroadcastTracked(new PacketPlayOutAnimation(this, 0), 3); + } + } + } + } + + // Beanes - Don't care about the client code. + public void justSwing() { + EntityTrackerEntry entry = ((WorldServer) world).getTracker().trackedEntities.get(getId()); + + if (entry != null) { + entry.queueBroadcastTracked(new PacketPlayOutAnimation(this, 0), 3); + } + } + + protected void O() { + damageEntity(DamageSource.OUT_OF_WORLD, 4.0F); + } + + protected void bx() { + int i = this.n(); + + if (this.ar) { + ++this.as; + if (this.as >= i) { + this.as = 0; + this.ar = false; + } + } else { + this.as = 0; + } + + this.az = (float) this.as / (float) i; + } + + public AttributeInstance getAttributeInstance(IAttribute iattribute) { + return this.getAttributeMap().a(iattribute); + } + + public AttributeMapBase getAttributeMap() { + if (this.c == null) { + this.c = new AttributeMapServer(); + } + + return this.c; + } + + public EnumMonsterType getMonsterType() { + return EnumMonsterType.UNDEFINED; + } + + public abstract ItemStack bA(); + + public abstract ItemStack getEquipment(int i); + + public abstract void setEquipment(int i, ItemStack itemstack); + + public void setSprinting(boolean flag) { + super.setSprinting(flag); + AttributeInstance attributeinstance = this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED); + + // Beanes - only remove sprint modifier when it is present + if (!flag && attributeinstance.a(EntityLiving.a) != null) { + attributeinstance.c(EntityLiving.b); + } + + // Beanes - only add sprint modifier when it is not present + if (flag && attributeinstance.a(EntityLiving.a) == null) { + attributeinstance.b(EntityLiving.b); + } + + } + + public abstract ItemStack[] getEquipment(); + + protected float bB() { + return 1.0F; + } + + protected float bC() { + return this.isBaby() ? (random.nextFloat() - random.nextFloat()) * 0.2F + 1.5F + : (random.nextFloat() - random.nextFloat()) * 0.2F + 1.0F; + } + + protected boolean bD() { + return this.getHealth() <= 0.0F; + } + + public void q(Entity entity) { + double d0 = entity.locX; + double d1 = entity.boundingBox.b + (double) entity.length; + double d2 = entity.locZ; + byte b0 = 1; + + for (int i = -b0; i <= b0; ++i) { + for (int j = -b0; j < b0; ++j) { + if (i != 0 || j != 0) { + int k = (int) (this.locX + (double) i); + int l = (int) (this.locZ + (double) j); + AxisAlignedBB axisalignedbb = this.boundingBox.c(i, 1.0D, j); + + if (this.world.a(axisalignedbb).isEmpty()) { + if (World.a(this.world, k, (int) this.locY, l)) { + this.enderTeleportTo(this.locX + (double) i, this.locY + 1.0D, this.locZ + (double) j); + return; + } + + if (World.a(this.world, k, (int) this.locY - 1, l) || this.world.getType(k, (int) this.locY - 1, l).getBlock().getMaterial() == Material.WATER) { + d0 = this.locX + (double) i; + d1 = this.locY + 1.0D; + d2 = this.locZ + (double) j; + } + } + } + } + } + + this.enderTeleportTo(d0, d1, d2); + } + + protected float bE() { + return 0.42F; + } + + protected void bF() { + this.motY = this.bE(); + if (this.hasEffect(MobEffectList.JUMP)) { + this.motY += (this.getEffect(MobEffectList.JUMP).getAmplifier() + 1) * 0.1F; + } + + if (this.isSprinting()) { + float f = this.yaw * 0.017453292F; + + this.motX -= MathHelper.sin(f) * 0.2; + this.motZ += MathHelper.cos(f) * 0.2; + } + + this.ai = true; + } + + protected void bG() { + this.motY += 0.03999999910593033D; + } + + protected void bH() { + this.motY += 0.03999999910593033D; + } + + public void g(float f, float f1) { + double d0; + float f2; + + if (this.bM()) { + float f3; + float f4; + if (this.V() && (!(this instanceof EntityHuman) || !((EntityHuman) this).abilities.isFlying)) { + d0 = this.locY; + f3 = 0.8F; + f4 = 0.02F; + f2 = (float) EnchantmentManager.b(this); + if (f2 > 3.0F) { + f2 = 3.0F; + } + + if (!this.onGround) { + f2 *= 0.5F; + } + + if (f2 > 0.0F) { + f3 += (0.54600006F - f3) * f2 / 3.0F; + f4 += (this.bI() - f4) * f2 / 3.0F; + } + + this.a(f, f1, f4); + this.move(this.motX, this.motY, this.motZ); + this.motX *= f3; + this.motY *= 0.800000011920929D; + this.motZ *= f3; + this.motY -= 0.02D; + if (this.positionChanged && this.c(this.motX, this.motY + 0.6000000238418579D - this.locY + d0, this.motZ)) { + this.motY = 0.30000001192092896D; + } + } else if (this.ab() && (!(this instanceof EntityHuman) || !((EntityHuman) this).abilities.isFlying)) { + d0 = this.locY; + this.a(f, f1, 0.02F); + this.move(this.motX, this.motY, this.motZ); + this.motX *= 0.5D; + this.motY *= 0.5D; + this.motZ *= 0.5D; + this.motY -= 0.02D; + if (this.positionChanged && this.c(this.motX, this.motY + 0.6000000238418579D - this.locY + d0, this.motZ)) { + this.motY = 0.30000001192092896D; + } + } else { + float f5 = 0.91F; + + if (this.onGround) { + f5 = this.world.getType(MathHelper.floor(this.locX), MathHelper.floor(this.boundingBox.b) - 1, MathHelper.floor(this.locZ)).getBlock().frictionFactor * 0.91F; + } + + float f6 = 0.16277136F / (f5 * f5 * f5); + + if (this.onGround) { + f3 = this.bI() * f6; + } else { + f3 = this.aM; + } + + this.a(f, f1, f3); + f5 = 0.91F; + if (this.onGround) { + f5 = this.world.getType(MathHelper.floor(this.locX), MathHelper.floor(this.boundingBox.b) - 1, MathHelper.floor(this.locZ)).getBlock().frictionFactor * 0.91F; + } + + if (this.k_()) { + f4 = 0.15F; + this.motX = MathHelper.a(this.motX, -f4, f4); + this.motZ = MathHelper.a(this.motZ, -f4, f4); + this.fallDistance = 0.0F; + if (this.motY < -0.15D) { + this.motY = -0.15D; + } + if (isSneaking() && this instanceof EntityHuman && this.motY < 0.0D) { + this.motY = 0.0D; + } + } + + move(this.motX, this.motY, this.motZ); + if (this.positionChanged && this.k_()) { + this.motY = 0.2D; + } + + this.motY -= 0.08D; + + this.motY *= 0.9800000190734863D; + this.motX *= f5; + this.motZ *= f5; + } + } + this.aA = this.aB; + d0 = this.locX - this.lastX; + double d1 = this.locZ - this.lastZ; + + f2 = MathHelper.sqrt(d0 * d0 + d1 * d1) * 4.0F; + if (f2 > 1.0F) { + f2 = 1.0F; + } + + this.aB += (f2 - this.aB) * 0.4F; + this.aC += this.aB; + } + + public float bI() { + return this.bm; + } + + public void k(float f) { + this.bm = f; + } + + public boolean r(Entity entity) { + this.p(entity); + return false; + } + + public boolean isSleeping() { + return false; + } + + public void t_() { + super.t_(); + int i = this.bv(); + + if (i > 0) { + if (this.at <= 0) { + this.at = 20 * (30 - i); + } + + --this.at; + if (this.at <= 0) { + this.o(i - 1); + } + } + + // Beanes - check for hand attributes + if (this instanceof EntityPlayer) { + ((EntityPlayer) this).checkHandAttributes(); + } + + for (int j = 0; j < 5; ++j) { + ItemStack previousItem = h[j]; + ItemStack currentItem = getEquipment(j); + + // Beanes - dont check durability to update item + if (!ItemStack.matchesWithoutDurability(currentItem, previousItem)) { // Spigot + // Beanes - don't update attributes for player hand here + if (j != 0 || !(this instanceof EntityPlayer)) { + if (previousItem != null) { + this.c.a(previousItem.B()); + } + + if (currentItem != null) { + this.c.b(currentItem.B()); + } + } + + this.h[j] = currentItem == null ? null : currentItem.cloneItemStack(); + ((WorldServer) this.world).getTracker().a(this, new PacketPlayOutEntityEquipment(getId(), j, currentItem, AzuriteConfig.obfuscateEntityEquipment.getValue())); + + // Beanes - item use desync fix (pvpgym updated ver) + if (currentItem != null && this instanceof EntityHuman && j == 0 && ((EntityHuman) this).bS() && !sentFakeMetadata) { + this.resolveDesync(); + } + } + } + + if (ticksLived % 20 == 0) { + bs().g(); + } + + this.m(); + double d0 = this.locX - this.lastX; + double d1 = this.locZ - this.lastZ; + float f = (float) (d0 * d0 + d1 * d1); + float f1 = this.aI; + float f2 = 0.0F; + + this.aR = this.aS; + float f3 = 0.0F; + + if (f > 0.0025000002F) { + f3 = 1.0F; + f2 = (float) Math.sqrt(f) * 3.0F; + // CraftBukkit - Math -> TrigMath + f1 = (float) org.bukkit.craftbukkit.TrigMath.atan2(d1, d0) * 180.0F / 3.1415927F - 90.0F; + } + + if (this.az > 0.0F) { + f1 = this.yaw; + } + + if (!this.onGround) { + f3 = 0.0F; + } + + this.aS += (f3 - this.aS) * 0.3F; + + f2 = this.h(f1, f2); + + while (this.yaw - this.lastYaw < -180.0F) { + this.lastYaw -= 360.0F; + } + + while (this.yaw - this.lastYaw >= 180.0F) { + this.lastYaw += 360.0F; + } + + while (this.aI - this.aJ < -180.0F) { + this.aJ -= 360.0F; + } + + while (this.aI - this.aJ >= 180.0F) { + this.aJ += 360.0F; + } + + while (this.pitch - this.lastPitch < -180.0F) { + this.lastPitch -= 360.0F; + } + + while (this.pitch - this.lastPitch >= 180.0F) { + this.lastPitch += 360.0F; + } + + while (this.aK - this.aL < -180.0F) { + this.aL -= 360.0F; + } + + while (this.aK - this.aL >= 180.0F) { + this.aL += 360.0F; + } + + this.aT += f2; + } + + protected float h(float f, float f1) { + float f2 = MathHelper.g(f - this.aI); + + this.aI += f2 * 0.3F; + float f3 = MathHelper.g(this.yaw - this.aI); + boolean flag = f3 < -90.0F || f3 >= 90.0F; + + if (f3 < -75.0F) { + f3 = -75.0F; + } + + if (f3 >= 75.0F) { + f3 = 75.0F; + } + + this.aI = this.yaw - f3; + if (f3 * f3 > 2500.0F) { + this.aI += f3 * 0.2F; + } + + if (flag) { + f1 *= -1.0F; + } + + return f1; + } + + public void m() { + if (this.bn > 0) { + --this.bn; + } + + if (this.bc > 0) { + double d0 = this.locX + (this.bd - this.locX) / this.bc; + double d1 = this.locY + (this.be - this.locY) / this.bc; + double d2 = this.locZ + (this.bf - this.locZ) / this.bc; + double d3 = MathHelper.g(this.bg - this.yaw); + + this.yaw = (float) (this.yaw + d3 / this.bc); + this.pitch = (float) (this.pitch + (this.bh - this.pitch) / this.bc); + --this.bc; + this.setPosition(d0, d1, d2); + this.setYawPitch(this.yaw, this.pitch); + } else if (!this.bM()) { + this.motX *= 0.98D; + this.motY *= 0.98D; + this.motZ *= 0.98D; + } + + if (Math.abs(this.motX) < 0.005D) { + this.motX = 0.0D; + } + + if (Math.abs(this.motY) < 0.005D) { + this.motY = 0.0D; + } + + if (Math.abs(this.motZ) < 0.005D) { + this.motZ = 0.0D; + } + + if (this.bD()) { + this.aY = false; + this.aZ = 0.0F; + this.ba = 0.0F; + this.bb = 0.0F; + } else if (this.bM()) { + this.doTick(); + } + + if (this.aY) { + if (this.V()) { + this.bG(); + } else if (this.ab()) { + this.bH(); + } else if (this.onGround && this.bn == 0) { + this.bF(); + this.bn = 10; + } + } else { + this.bn = 0; + } + + this.aZ *= 0.98F; + this.ba *= 0.98F; + this.bb *= 0.9F; + this.g(this.aZ, this.ba); + + // Azurite - Remove vortex breaking entity collisions completely. + if (AzuriteConfig.entityCollisions.getValue() && ticksLived % AzuriteConfig.entityCollisionsDelay.getValue() == 0) { // Vortex - optimized collisions + this.bL(); + } + } + + protected void doTick() { + } + + protected void bL() { + List list = this.world.a(this, this.boundingBox.grow(0.20000000298023224D, 0.0D, 0.20000000298023224D), Predicates.and(IEntitySelector.d, Entity::ae)); + + if (this.ad() && !list.isEmpty()) { // Spigot: Add this.ad() condition + numCollisions -= world.spigotConfig.maxCollisionsPerEntity; // Spigot + + for (Entity value : list) { + if (numCollisions > world.spigotConfig.maxCollisionsPerEntity) { + break; + } // Spigot + + // TODO better check now? + // CraftBukkit start - Only handle mob (non-player) collisions every other tick + if (value instanceof EntityLiving && !(this instanceof EntityPlayer) && this.ticksLived % 2 == 0) { + continue; + } + // CraftBukkit end + + value.numCollisions++; // Spigot + numCollisions++; // Spigot + this.s(value); + } + numCollisions = 0; // Spigot + } + } + + protected void s(Entity entity) { + entity.collide(this); + } + + public void mount(Entity entity) { + if (this.vehicle != null && entity == null) { + // CraftBukkit start + Entity originalVehicle = this.vehicle; + if ((this.bukkitEntity instanceof LivingEntity) && (this.vehicle.getBukkitEntity() instanceof Vehicle)) { + VehicleExitEvent event = new VehicleExitEvent((Vehicle) this.vehicle.getBukkitEntity(), + (LivingEntity) this.bukkitEntity); + getBukkitEntity().getServer().getPluginManager().callEvent(event); + + if (event.isCancelled() || vehicle != originalVehicle) { + return; + } + } + // CraftBukkit end + // PaperSpigot start - make dismountEvent cancellable + EntityDismountEvent dismountEvent = new EntityDismountEvent(this.getBukkitEntity(), + this.vehicle.getBukkitEntity()); // Spigot + Bukkit.getPluginManager().callEvent(dismountEvent); + if (dismountEvent.isCancelled()) + return; + // PaperSpigot end + + this.q(this.vehicle); + + if (this.vehicle != null) { + this.vehicle.passenger = null; + } + + this.vehicle = null; + } else { + super.mount(entity); + } + } + + public void ak() { + super.ak(); + this.aR = this.aS; + this.aS = 0.0F; + this.fallDistance = 0.0F; + } + + public void i(boolean flag) { + this.aY = flag; + } + + public void receive(Entity entity, int i) { + if (!entity.dead) { + EntityTracker entitytracker = ((WorldServer) this.world).getTracker(); + + if (EntityCollectEvent.getHandlerList().getRegisteredListeners().length > 0) { + new EntityCollectEvent(entity.getBukkitEntity(), (LivingEntity) this.getBukkitEntity()).callEvent(); + } + + if (entity instanceof EntityItem) { + entitytracker.a(entity, new PacketPlayOutCollect(entity.getId(), this.getId())); + } else if (entity instanceof EntityArrow) { + entitytracker.a(entity, new PacketPlayOutCollect(entity.getId(), this.getId())); + } else if (entity instanceof EntityExperienceOrb) { + entitytracker.a(entity, new PacketPlayOutCollect(entity.getId(), this.getId())); + } + } + + } + + public boolean hasLineOfSight(Entity entity) { + return this.world.rayTrace(new Vec3D(this.locX, this.locY + (double) this.getHeadHeight(), this.locZ), + new Vec3D(entity.locX, entity.locY + (double) entity.getHeadHeight(), entity.locZ)) == null; + } + + public Vec3D ap() { + return this.d(1.0F); + } + + public Vec3D d(float f) { + if (f == 1.0F) { + return this.f(this.pitch, this.aK); + } else { + float f1 = this.lastPitch + (this.pitch - this.lastPitch) * f; + float f2 = this.aL + (this.aK - this.aL) * f; + + return this.f(f1, f2); + } + } + + public boolean bM() { + return true; + } + + public boolean ad() { + return !this.dead; + } + + public boolean ae() { + return !this.dead; + } + + protected void ac() { + this.velocityChanged = random.nextDouble() >= this.getAttributeInstance(GenericAttributes.c).getValue(); + } + + public float getHeadRotation() { + return this.aK; + } + + public void f(float f) { + this.aK = f; + } + + public void g(float f) { + this.aI = f; + } + + public float getAbsorptionHearts() { + return this.bo; + } + + public void setAbsorptionHearts(float f) { + if (f < 0.0F) { + f = 0.0F; + } + + this.bo = f; + } + + public ScoreboardTeamBase getScoreboardTeam() { + return this.world.getScoreboard().getPlayerTeam(FastUUID.toString(this.getUniqueID())); + } + + public boolean c(EntityLiving entityliving) { + return this.a(entityliving.getScoreboardTeam()); + } + + public boolean a(ScoreboardTeamBase scoreboardteambase) { + ScoreboardTeamBase team = getScoreboardTeam(); + return team != null && team.isAlly(scoreboardteambase); + } + + public void enterCombat() { + } + + public void exitCombat() { + } + + protected void bP() { + this.updateEffects = true; + } + + // Beanes - item desync resolve (updated ver by pvpgym) + private boolean sentFakeMetadata; + + private void resolveDesync() { + DataWatcher.WatchableObject object = this.datawatcher.cloneById(0); + List list = new java.util.ArrayList<>(); + list.add(object); + + // Disable bit 4 + byte current = this.datawatcher.getByte(0); + object.a(Byte.valueOf((byte) (current & ~(1 << 4)))); + + // Only send to watchers not self + PacketPlayOutEntityMetadata packet = new PacketPlayOutEntityMetadata(this.getId(), list); + ((WorldServer) this.world).getTracker().a(this, packet); + sentFakeMetadata = true; + + Bukkit.getScheduler().runTaskLater(Azurite.getPluginInstance(), () -> { + byte latest = this.datawatcher.getByte(0); + object.a(Byte.valueOf(latest)); // Set bit 4 on latest value + ((WorldServer) this.world).getTracker().a(this, packet); + sentFakeMetadata = false; + }, 3L); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityMagmaCube.java b/azurite-server/src/main/java/net/minecraft/server/EntityMagmaCube.java new file mode 100644 index 0000000..8250cc6 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityMagmaCube.java @@ -0,0 +1,100 @@ +package net.minecraft.server; + +public class EntityMagmaCube extends EntitySlime { + + public EntityMagmaCube(World world) { + super(world); + this.fireProof = true; + } + + protected void initAttributes() { + super.initAttributes(); + this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.20000000298023224D); + } + + public boolean bR() { + return this.world.getDifficulty() != EnumDifficulty.PEACEFUL; + } + + public boolean canSpawn() { + return this.world.a(this.getBoundingBox(), this) && this.world.getCubes(this, this.getBoundingBox()).isEmpty() && !this.world.containsLiquid(this.getBoundingBox()); + } + + public int br() { + return this.getSize() * 3; + } + + public float c(float f) { + return 1.0F; + } + + protected EnumParticle n() { + return EnumParticle.FLAME; + } + + protected EntitySlime cf() { + return new EntityMagmaCube(this.world); + } + + protected Item getLoot() { + return Items.MAGMA_CREAM; + } + + protected void dropDeathLoot(boolean flag, int i) { + Item item = this.getLoot(); + + if (item != null && this.getSize() > 1) { + int j = random.nextInt(4) - 2; + + if (i > 0) { + j += random.nextInt(i + 1); + } + + for (int k = 0; k < j; ++k) { + this.a(item, 1); + } + } + + } + + public boolean isBurning() { + return false; + } + + protected int cg() { + return super.cg() * 4; + } + + protected void ch() { + this.a *= 0.9F; + } + + protected void bF() { + this.motY = 0.42F + (float) this.getSize() * 0.1F; + this.ai = true; + } + + protected void bH() { + this.motY = 0.22F + (float) this.getSize() * 0.05F; + this.ai = true; + } + + public void e(float f, float f1) { + } + + protected boolean ci() { + return true; + } + + protected int cj() { + return super.cj() + 2; + } + + protected String ck() { + return this.getSize() > 1 ? "mob.magmacube.big" : "mob.magmacube.small"; + } + + protected boolean cl() { + return true; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityMinecartAbstract.java b/azurite-server/src/main/java/net/minecraft/server/EntityMinecartAbstract.java new file mode 100644 index 0000000..7962fca --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityMinecartAbstract.java @@ -0,0 +1,942 @@ +package net.minecraft.server; + +import com.google.common.collect.Maps; +import org.bukkit.Location; +import org.bukkit.entity.Vehicle; +import org.bukkit.event.vehicle.VehicleDamageEvent; +import org.bukkit.event.vehicle.VehicleDestroyEvent; +import org.bukkit.event.vehicle.VehicleEntityCollisionEvent; +import org.bukkit.util.Vector; + +import java.util.Map; +// CraftBukkit end + +public abstract class EntityMinecartAbstract extends Entity implements INamableTileEntity { + + private boolean a; + private String b; + private static final int[][][] matrix = { { { 0, 0, -1}, { 0, 0, 1}}, { { -1, 0, 0}, { 1, 0, 0}}, { { -1, -1, 0}, { 1, 0, 0}}, { { -1, 0, 0}, { 1, -1, 0}}, { { 0, 0, -1}, { 0, -1, 1}}, { { 0, -1, -1}, { 0, 0, 1}}, { { 0, 0, 1}, { 1, 0, 0}}, { { 0, 0, 1}, { -1, 0, 0}}, { { 0, 0, -1}, { -1, 0, 0}}, { { 0, 0, -1}, { 1, 0, 0}}}; + + // CraftBukkit start + public boolean slowWhenEmpty = true; + private double derailedX = 0.5; + private double derailedY = 0.5; + private double derailedZ = 0.5; + private double flyingX = 0.95; + private double flyingY = 0.95; + private double flyingZ = 0.95; + public double maxSpeed = 0.4D; + // CraftBukkit end + + public EntityMinecartAbstract(World world) { + super(world); + this.k = true; + this.setSize(0.98F, 0.7F); + } + + public static EntityMinecartAbstract a(World world, double d0, double d1, double d2, EnumMinecartType entityminecartabstract_enumminecarttype) { + switch (SyntheticClass_1.a[entityminecartabstract_enumminecarttype.ordinal()]) { + case 1: + return new EntityMinecartChest(world, d0, d1, d2); + + case 2: + return new EntityMinecartFurnace(world, d0, d1, d2); + + case 3: + return new EntityMinecartTNT(world, d0, d1, d2); + + case 4: + return new EntityMinecartMobSpawner(world, d0, d1, d2); + + case 5: + return new EntityMinecartHopper(world, d0, d1, d2); + + case 6: + return new EntityMinecartCommandBlock(world, d0, d1, d2); + + default: + return new EntityMinecartRideable(world, d0, d1, d2); + } + } + + protected boolean s_() { + return false; + } + + protected void h() { + this.datawatcher.a(17, 0); + this.datawatcher.a(18, 1); + this.datawatcher.a(19, 0.0F); + this.datawatcher.a(20, 0); + this.datawatcher.a(21, 6); + this.datawatcher.a(22, (byte) 0); + } + + public AxisAlignedBB j(Entity entity) { + return entity.ae() ? entity.getBoundingBox() : null; + } + + public AxisAlignedBB S() { + return null; + } + + public boolean ae() { + return true; + } + + public EntityMinecartAbstract(World world, double d0, double d1, double d2) { + this(world); + this.setPosition(d0, d1, d2); + this.motX = 0.0D; + this.motY = 0.0D; + this.motZ = 0.0D; + this.lastX = d0; + this.lastY = d1; + this.lastZ = d2; + + this.world.getServer().getPluginManager().callEvent(new org.bukkit.event.vehicle.VehicleCreateEvent((Vehicle) this.getBukkitEntity())); // CraftBukkit + } + + public double an() { + return 0.0D; + } + + public boolean damageEntity(DamageSource damagesource, float f) { + if (!this.dead) { + if (this.isInvulnerable(damagesource)) { + return false; + } else { + // CraftBukkit start - fire VehicleDamageEvent + Vehicle vehicle = (Vehicle) this.getBukkitEntity(); + org.bukkit.entity.Entity passenger = (damagesource.getEntity() == null) ? null : damagesource.getEntity().getBukkitEntity(); + + VehicleDamageEvent event = new VehicleDamageEvent(vehicle, passenger, f); + this.world.getServer().getPluginManager().callEvent(event); + + if (event.isCancelled()) { + return false; + } + + f = (float) event.getDamage(); + // CraftBukkit end + this.k(-this.r()); + this.j(10); + this.ac(); + this.setDamage(this.getDamage() + f * 10.0F); + boolean flag = damagesource.getEntity() instanceof EntityHuman && ((EntityHuman) damagesource.getEntity()).abilities.canInstantlyBuild; + + if (flag || this.getDamage() > 40.0F) { + // CraftBukkit start + VehicleDestroyEvent destroyEvent = new VehicleDestroyEvent(vehicle, passenger); + this.world.getServer().getPluginManager().callEvent(destroyEvent); + + if (destroyEvent.isCancelled()) { + this.setDamage(40); // Maximize damage so this doesn't get triggered again right away + return true; + } + // CraftBukkit end + if (this.passenger != null) { + this.passenger.mount(null); + } + + if (flag && !this.hasCustomName()) { + this.die(); + } else { + this.a(damagesource); + } + } + + return true; + } + } else { + return true; + } + } + + public void a(DamageSource damagesource) { + this.die(); + if (this.world.getGameRules().getBoolean("doEntityDrops")) { + ItemStack itemstack = new ItemStack(Items.MINECART, 1); + + if (this.b != null) { + itemstack.c(this.b); + } + + this.a(itemstack, 0.0F); + } + + } + + public boolean ad() { + return !this.dead; + } + + public void die() { + super.die(); + } + + public void t_() { + // CraftBukkit start + double prevX = this.locX; + double prevY = this.locY; + double prevZ = this.locZ; + float prevYaw = this.yaw; + float prevPitch = this.pitch; + // CraftBukkit end + + if (this.getType() > 0) { + this.j(this.getType() - 1); + } + + if (this.getDamage() > 0.0F) { + this.setDamage(this.getDamage() - 1.0F); + } + + if (this.locY < -64.0D) { + this.O(); + } + + int i; + + if (this.world instanceof WorldServer) { + + MinecraftServer minecraftserver = ((WorldServer) this.world).getMinecraftServer(); + + i = this.L(); + if (this.ak) { + if (minecraftserver.getAllowNether()) { // CraftBukkit - multi-world should still allow teleport even if default vanilla nether disabled + if (this.vehicle == null && this.al++ >= i) { + this.al = i; + this.portalCooldown = this.aq(); + byte b0; + + if (this.world.worldProvider.getDimension() == -1) { + b0 = 0; + } else { + b0 = -1; + } + + this.c(b0); + } + + this.ak = false; + } + } else { + if (this.al > 0) { + this.al -= 4; + } + + if (this.al < 0) { + this.al = 0; + } + } + + if (this.portalCooldown > 0) { + --this.portalCooldown; + } + + } + + this.lastX = this.locX; + this.lastY = this.locY; + this.lastZ = this.locZ; + this.motY -= 0.03999999910593033D; + int j = MathHelper.floor(this.locX); + + i = MathHelper.floor(this.locY); + int k = MathHelper.floor(this.locZ); + + if (BlockMinecartTrackAbstract.e(this.world, j, i - 1, k)) { + --i; + } + + IBlockData iblockdata = this.world.getType(j, i, k); + if (BlockMinecartTrackAbstract.d(iblockdata)) { + this.a(j, i, k, iblockdata); + if (iblockdata.getBlock() == Blocks.ACTIVATOR_RAIL) { + this.a(j, i, k, iblockdata.get(BlockPoweredRail.POWERED)); + } + } else { + this.n(); + } + + this.checkBlockCollisions(); + this.pitch = 0.0F; + double d4 = this.lastX - this.locX; + double d5 = this.lastZ - this.locZ; + + if (d4 * d4 + d5 * d5 > 0.001D) { + this.yaw = (float) (MathHelper.b(d5, d4) * 180.0D / 3.141592653589793D); + if (this.a) { + this.yaw += 180.0F; + } + } + + double d6 = MathHelper.g(this.yaw - this.lastYaw); + + if (d6 < -170.0D || d6 >= 170.0D) { + this.yaw += 180.0F; + this.a = !this.a; + } + + this.setYawPitch(this.yaw, this.pitch); + + // CraftBukkit start + org.bukkit.World bworld = this.world.getWorld(); + Location from = new Location(bworld, prevX, prevY, prevZ, prevYaw, prevPitch); + Location to = new Location(bworld, this.locX, this.locY, this.locZ, this.yaw, this.pitch); + Vehicle vehicle = (Vehicle) this.getBukkitEntity(); + + this.world.getServer().getPluginManager().callEvent(new org.bukkit.event.vehicle.VehicleUpdateEvent(vehicle)); + + if (!from.equals(to)) { + this.world.getServer().getPluginManager().callEvent(new org.bukkit.event.vehicle.VehicleMoveEvent(vehicle, from, to)); + } + // CraftBukkit end + + for (Entity entity : this.world.getEntities(this, this.getBoundingBox().grow(0.20000000298023224D, 0.0D, 0.20000000298023224D))) { + if (entity != this.passenger && entity.ae() && entity instanceof EntityMinecartAbstract) { + entity.collide(this); + } + } + + if (this.passenger != null && this.passenger.dead) { + if (this.passenger.vehicle == this) { + this.passenger.vehicle = null; + } + + this.passenger = null; + } + + this.W(); + + } + + protected double m() { + return this.maxSpeed; // CraftBukkit + } + + public void a(int i, int j, int k, boolean flag) {} + + protected void n() { + double d0 = this.m(); + + this.motX = MathHelper.a(this.motX, -d0, d0); + this.motZ = MathHelper.a(this.motZ, -d0, d0); + if (this.onGround) { + // CraftBukkit start - replace magic numbers with our variables + this.motX *= this.derailedX; + this.motY *= this.derailedY; + this.motZ *= this.derailedZ; + // CraftBukkit end + } + + this.move(this.motX, this.motY, this.motZ); + if (!this.onGround) { + // CraftBukkit start - replace magic numbers with our variables + this.motX *= this.flyingX; + this.motY *= this.flyingY; + this.motZ *= this.flyingZ; + // CraftBukkit end + } + + } + protected void a(int x, int y, int z, IBlockData iblockdata) { + this.fallDistance = 0.0F; + Vec3D vec3d = this.k(this.locX, this.locY, this.locZ); + + this.locY = y; + boolean flag = false; + boolean flag1 = false; + BlockMinecartTrackAbstract blockminecarttrackabstract = (BlockMinecartTrackAbstract) iblockdata.getBlock(); + + if (blockminecarttrackabstract == Blocks.GOLDEN_RAIL) { + flag = iblockdata.get(BlockPoweredRail.POWERED); + flag1 = !flag; + } + + BlockMinecartTrackAbstract.EnumTrackPosition blockminecarttrackabstract_enumtrackposition = iblockdata.get(blockminecarttrackabstract.n()); + + switch (SyntheticClass_1.b[blockminecarttrackabstract_enumtrackposition.ordinal()]) { + case 1: + this.motX -= 0.0078125D; + ++this.locY; + break; + + case 2: + this.motX += 0.0078125D; + ++this.locY; + break; + + case 3: + this.motZ += 0.0078125D; + ++this.locY; + break; + + case 4: + this.motZ -= 0.0078125D; + ++this.locY; + } + + int[][] aint = EntityMinecartAbstract.matrix[blockminecarttrackabstract_enumtrackposition.a()]; + double d1 = aint[1][0] - aint[0][0]; + double d2 = aint[1][2] - aint[0][2]; + double d3 = Math.sqrt(d1 * d1 + d2 * d2); + double d4 = this.motX * d1 + this.motZ * d2; + + if (d4 < 0.0D) { + d1 = -d1; + d2 = -d2; + } + + double d5 = Math.sqrt(this.motX * this.motX + this.motZ * this.motZ); + + if (d5 > 2.0D) { + d5 = 2.0D; + } + + this.motX = d5 * d1 / d3; + this.motZ = d5 * d2 / d3; + double d6; + double d7; + double d8; + double d9; + + if (this.passenger instanceof EntityLiving) { + d6 = ((EntityLiving) this.passenger).ba; + if (d6 > 0.0D) { + d7 = -Math.sin(this.passenger.yaw * 3.1415927F / 180.0F); + d8 = Math.cos(this.passenger.yaw * 3.1415927F / 180.0F); + d9 = this.motX * this.motX + this.motZ * this.motZ; + if (d9 < 0.01D) { + this.motX += d7 * 0.1D; + this.motZ += d8 * 0.1D; + flag1 = false; + } + } + } + + if (flag1) { + d6 = Math.sqrt(this.motX * this.motX + this.motZ * this.motZ); + if (d6 < 0.03D) { + this.motX *= 0.0D; + this.motY *= 0.0D; + this.motZ *= 0.0D; + } else { + this.motX *= 0.5D; + this.motY *= 0.0D; + this.motZ *= 0.5D; + } + } + + d7 = (double) x + 0.5D + (double) aint[0][0] * 0.5D; + d8 = (double) z + 0.5D + (double) aint[0][2] * 0.5D; + d9 = (double) x + 0.5D + (double) aint[1][0] * 0.5D; + double d10 = (double) z + 0.5D + (double) aint[1][2] * 0.5D; + + d1 = d9 - d7; + d2 = d10 - d8; + double d11; + double d12; + + if (d1 == 0.0D) { + d6 = this.locZ - (double) z; + } else if (d2 == 0.0D) { + d6 = this.locX - (double) x; + } else { + d11 = this.locX - d7; + d12 = this.locZ - d8; + d6 = (d11 * d1 + d12 * d2) * 2.0D; + } + + this.locX = d7 + d1 * d6; + this.locZ = d8 + d2 * d6; + this.setPosition(this.locX, this.locY, this.locZ); + d11 = this.motX; + d12 = this.motZ; + if (this.passenger != null) { + d11 *= 0.75D; + d12 *= 0.75D; + } + + double d13 = this.m(); + + d11 = MathHelper.a(d11, -d13, d13); + d12 = MathHelper.a(d12, -d13, d13); + this.move(d11, 0.0D, d12); + if (aint[0][1] != 0 && MathHelper.floor(this.locX) - x == aint[0][0] && MathHelper.floor(this.locZ) - z == aint[0][2]) { + this.setPosition(this.locX, this.locY + (double) aint[0][1], this.locZ); + } else if (aint[1][1] != 0 && MathHelper.floor(this.locX) - x == aint[1][0] && MathHelper.floor(this.locZ) - z == aint[1][2]) { + this.setPosition(this.locX, this.locY + (double) aint[1][1], this.locZ); + } + + this.o(); + Vec3D vec3d1 = this.k(this.locX, this.locY, this.locZ); + + if (vec3d1 != null && vec3d != null) { + double d14 = (vec3d.b - vec3d1.b) * 0.05D; + + d5 = Math.sqrt(this.motX * this.motX + this.motZ * this.motZ); + if (d5 > 0.0D) { + this.motX = this.motX / d5 * (d5 + d14); + this.motZ = this.motZ / d5 * (d5 + d14); + } + + this.setPosition(this.locX, vec3d1.b, this.locZ); + } + + int i = MathHelper.floor(this.locX); + int j = MathHelper.floor(this.locZ); + + if (i != x || j != z) { + d5 = Math.sqrt(this.motX * this.motX + this.motZ * this.motZ); + this.motX = d5 * (double) (i - x); + this.motZ = d5 * (double) (j - z); + } + + if (flag) { + double d15 = Math.sqrt(this.motX * this.motX + this.motZ * this.motZ); + + if (d15 > 0.01D) { + double d16 = 0.06D; + + this.motX += this.motX / d15 * d16; + this.motZ += this.motZ / d15 * d16; + } else if (blockminecarttrackabstract_enumtrackposition == BlockMinecartTrackAbstract.EnumTrackPosition.EAST_WEST) { + final EnumDirection w = EnumDirection.WEST; + final EnumDirection e = EnumDirection.EAST; + if (this.world.getType(x + w.getAdjacentX() * i, y + w.getAdjacentY() * i, z + w.getAdjacentZ()).getBlock().isOccluding()) { + this.motX = 0.02D; + } else if (this.world.getType(x + e.getAdjacentX() * i, y + e.getAdjacentY() * i, z + e.getAdjacentZ()).getBlock().isOccluding()) { + this.motX = -0.02D; + } + } else if (blockminecarttrackabstract_enumtrackposition == BlockMinecartTrackAbstract.EnumTrackPosition.NORTH_SOUTH) { + final EnumDirection w = EnumDirection.NORTH; + final EnumDirection e = EnumDirection.SOUTH; + if (this.world.getType(x + w.getAdjacentX() * i, y + w.getAdjacentY() * i, z + w.getAdjacentZ()).getBlock().isOccluding()) { + this.motX = 0.02D; + } else if (this.world.getType(x + e.getAdjacentX() * i, y + e.getAdjacentY() * i, z + e.getAdjacentZ()).getBlock().isOccluding()) { + this.motX = -0.02D; + } + } + } + + } + + protected void o() { + if (this.passenger != null || !this.slowWhenEmpty) { // CraftBukkit - add !this.slowWhenEmpty + this.motX *= 0.996999979019165D; + this.motY *= 0.0D; + this.motZ *= 0.996999979019165D; + } else { + this.motX *= 0.9599999785423279D; + this.motY *= 0.0D; + this.motZ *= 0.9599999785423279D; + } + + } + + public void setPosition(double d0, double d1, double d2) { + this.locX = d0; + this.locY = d1; + this.locZ = d2; + float f = this.width / 2.0F; + float f1 = this.length; + + this.a(new AxisAlignedBB(d0 - (double) f, d1, d2 - (double) f, d0 + (double) f, d1 + (double) f1, d2 + (double) f)); + } + + public Vec3D k(double d0, double d1, double d2) { + int i = MathHelper.floor(d0); + int j = MathHelper.floor(d1); + int k = MathHelper.floor(d2); + + if (BlockMinecartTrackAbstract.e(this.world, i, j - 1, k)) { + --j; + } + + IBlockData iblockdata = this.world.getType(i, j, k); + + if (BlockMinecartTrackAbstract.d(iblockdata)) { + BlockMinecartTrackAbstract.EnumTrackPosition blockminecarttrackabstract_enumtrackposition = iblockdata.get(((BlockMinecartTrackAbstract) iblockdata.getBlock()).n()); + int[][] aint = EntityMinecartAbstract.matrix[blockminecarttrackabstract_enumtrackposition.a()]; + double d3; + double d4 = (double) i + 0.5D + (double) aint[0][0] * 0.5D; + double d5 = (double) j + 0.0625D + (double) aint[0][1] * 0.5D; + double d6 = (double) k + 0.5D + (double) aint[0][2] * 0.5D; + double d7 = (double) i + 0.5D + (double) aint[1][0] * 0.5D; + double d8 = (double) j + 0.0625D + (double) aint[1][1] * 0.5D; + double d9 = (double) k + 0.5D + (double) aint[1][2] * 0.5D; + double d10 = d7 - d4; + double d11 = (d8 - d5) * 2.0D; + double d12 = d9 - d6; + + if (d10 == 0.0D) { + d3 = d2 - (double) k; + } else if (d12 == 0.0D) { + d3 = d0 - (double) i; + } else { + double d13 = d0 - d4; + double d14 = d2 - d6; + + d3 = (d13 * d10 + d14 * d12) * 2.0D; + } + + d0 = d4 + d10 * d3; + d1 = d5 + d11 * d3; + d2 = d6 + d12 * d3; + if (d11 < 0.0D) { + ++d1; + } + + if (d11 > 0.0D) { + d1 += 0.5D; + } + + return new Vec3D(d0, d1, d2); + } else { + return null; + } + } + + protected void a(NBTTagCompound nbttagcompound) { + if (nbttagcompound.getBoolean("CustomDisplayTile")) { + int i = nbttagcompound.getInt("DisplayData"); + Block block; + + if (nbttagcompound.hasKeyOfType("DisplayTile", 8)) { + block = Block.getByName(nbttagcompound.getString("DisplayTile")); + } else { + block = Block.getById(nbttagcompound.getInt("DisplayTile")); + } + if (block == null) { + this.setDisplayBlock(Blocks.AIR.getBlockData()); + } else { + this.setDisplayBlock(block.fromLegacyData(i)); + } + + this.SetDisplayBlockOffset(nbttagcompound.getInt("DisplayOffset")); + } + + if (nbttagcompound.hasKeyOfType("CustomName", 8) && nbttagcompound.getString("CustomName").length() > 0) { + this.b = nbttagcompound.getString("CustomName"); + } + + } + + protected void b(NBTTagCompound nbttagcompound) { + if (this.x()) { + nbttagcompound.setBoolean("CustomDisplayTile", true); + IBlockData iblockdata = this.getDisplayBlock(); + MinecraftKey minecraftkey = Block.REGISTRY.c(iblockdata.getBlock()); + + nbttagcompound.setString("DisplayTile", minecraftkey == null ? "" : minecraftkey.toString()); + nbttagcompound.setInt("DisplayData", iblockdata.getBlock().toLegacyData(iblockdata)); + nbttagcompound.setInt("DisplayOffset", this.getDisplayBlockOffset()); + } + + if (this.b != null && this.b.length() > 0) { + nbttagcompound.setString("CustomName", this.b); + } + + } + + public void collide(Entity entity) { + + if (!entity.noclip && !this.noclip) { + if (entity != this.passenger) { + // CraftBukkit start + Vehicle vehicle = (Vehicle) this.getBukkitEntity(); + org.bukkit.entity.Entity hitEntity = entity.getBukkitEntity(); + + VehicleEntityCollisionEvent collisionEvent = new VehicleEntityCollisionEvent(vehicle, hitEntity); + this.world.getServer().getPluginManager().callEvent(collisionEvent); + + if (collisionEvent.isCancelled()) { + return; + } + // CraftBukkit end + if (entity instanceof EntityLiving && !(entity instanceof EntityHuman) && !(entity instanceof EntityIronGolem) && this.s() == EnumMinecartType.RIDEABLE && this.motX * this.motX + this.motZ * this.motZ > 0.01D && this.passenger == null && entity.vehicle == null) { + entity.mount(this); + } + + double d0 = entity.locX - this.locX; + double d1 = entity.locZ - this.locZ; + double d2 = d0 * d0 + d1 * d1; + + // CraftBukkit - collision + if (d2 >= 9.999999747378752E-5D && !collisionEvent.isCollisionCancelled()) { + d2 = MathHelper.sqrt(d2); + d0 /= d2; + d1 /= d2; + double d3 = 1.0D / d2; + + if (d3 > 1.0D) { + d3 = 1.0D; + } + + d0 *= d3; + d1 *= d3; + d0 *= 0.10000000149011612D; + d1 *= 0.10000000149011612D; + d0 *= 1.0F - this.U; + d1 *= 1.0F - this.U; + d0 *= 0.5D; + d1 *= 0.5D; + if (entity instanceof EntityMinecartAbstract) { + double d4 = entity.locX - this.locX; + double d5 = entity.locZ - this.locZ; + Vec3D vec3d = (new Vec3D(d4, 0.0D, d5)).a(); + Vec3D vec3d1 = (new Vec3D(MathHelper.cos(this.yaw * 3.1415927F / 180.0F), 0.0D, MathHelper.sin(this.yaw * 3.1415927F / 180.0F))).a(); + double d6 = Math.abs(vec3d.b(vec3d1)); + + if (d6 < 0.800000011920929D) { + return; + } + + double d7 = entity.motX + this.motX; + double d8 = entity.motZ + this.motZ; + + if (((EntityMinecartAbstract) entity).s() == EnumMinecartType.FURNACE && this.s() != EnumMinecartType.FURNACE) { + this.motX *= 0.20000000298023224D; + this.motZ *= 0.20000000298023224D; + this.g(entity.motX - d0, 0.0D, entity.motZ - d1); + entity.motX *= 0.949999988079071D; + entity.motZ *= 0.949999988079071D; + } else if (((EntityMinecartAbstract) entity).s() != EnumMinecartType.FURNACE && this.s() == EnumMinecartType.FURNACE) { + entity.motX *= 0.20000000298023224D; + entity.motZ *= 0.20000000298023224D; + entity.g(this.motX + d0, 0.0D, this.motZ + d1); + this.motX *= 0.949999988079071D; + this.motZ *= 0.949999988079071D; + } else { + d7 /= 2.0D; + d8 /= 2.0D; + this.motX *= 0.20000000298023224D; + this.motZ *= 0.20000000298023224D; + this.g(d7 - d0, 0.0D, d8 - d1); + entity.motX *= 0.20000000298023224D; + entity.motZ *= 0.20000000298023224D; + entity.g(d7 + d0, 0.0D, d8 + d1); + } + } else { + this.g(-d0, 0.0D, -d1); + entity.g(d0 / 4.0D, 0.0D, d1 / 4.0D); + } + } + + } + } + } + + public void setDamage(float f) { + this.datawatcher.watch(19, f); + } + + public float getDamage() { + return this.datawatcher.getFloat(19); + } + + public void j(int i) { + this.datawatcher.watch(17, i); + } + + public int getType() { + return this.datawatcher.getInt(17); + } + + public void k(int i) { + this.datawatcher.watch(18, i); + } + + public int r() { + return this.datawatcher.getInt(18); + } + + public abstract EnumMinecartType s(); + + public IBlockData getDisplayBlock() { + return !this.x() ? this.u() : Block.getByCombinedId(this.getDataWatcher().getInt(20)); + } + + public IBlockData u() { + return Blocks.AIR.getBlockData(); + } + + public int getDisplayBlockOffset() { + return !this.x() ? this.w() : this.getDataWatcher().getInt(21); + } + + public int w() { + return 6; + } + + public void setDisplayBlock(IBlockData iblockdata) { + this.getDataWatcher().watch(20, Block.getCombinedId(iblockdata)); + this.a(true); + } + + public void SetDisplayBlockOffset(int i) { + this.getDataWatcher().watch(21, i); + this.a(true); + } + + public boolean x() { + return this.getDataWatcher().getByte(22) == 1; + } + + public void a(boolean flag) { + this.getDataWatcher().watch(22, (byte) (flag ? 1 : 0)); + } + + public void setCustomName(String s) { + this.b = s; + } + + public String getName() { + return this.b != null ? this.b : super.getName(); + } + + public boolean hasCustomName() { + return this.b != null; + } + + public String getCustomName() { + return this.b; + } + + public IChatBaseComponent getScoreboardDisplayName() { + if (this.hasCustomName()) { + ChatComponentText chatcomponenttext = new ChatComponentText(this.b); + + chatcomponenttext.getChatModifier().setChatHoverable(this.aQ()); + chatcomponenttext.getChatModifier().setInsertion(this.getUniqueID().toString()); + return chatcomponenttext; + } else { + ChatMessage chatmessage = new ChatMessage(this.getName()); + + chatmessage.getChatModifier().setChatHoverable(this.aQ()); + chatmessage.getChatModifier().setInsertion(this.getUniqueID().toString()); + return chatmessage; + } + } + + static class SyntheticClass_1 { + + static final int[] a; + static final int[] b = new int[BlockMinecartTrackAbstract.EnumTrackPosition.values().length]; + + static { + try { + SyntheticClass_1.b[BlockMinecartTrackAbstract.EnumTrackPosition.ASCENDING_EAST.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.b[BlockMinecartTrackAbstract.EnumTrackPosition.ASCENDING_WEST.ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.b[BlockMinecartTrackAbstract.EnumTrackPosition.ASCENDING_NORTH.ordinal()] = 3; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.b[BlockMinecartTrackAbstract.EnumTrackPosition.ASCENDING_SOUTH.ordinal()] = 4; + } catch (NoSuchFieldError ignored) { + } + + a = new int[EnumMinecartType.values().length]; + + try { + SyntheticClass_1.a[EnumMinecartType.CHEST.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.a[EnumMinecartType.FURNACE.ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.a[EnumMinecartType.TNT.ordinal()] = 3; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.a[EnumMinecartType.SPAWNER.ordinal()] = 4; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.a[EnumMinecartType.HOPPER.ordinal()] = 5; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.a[EnumMinecartType.COMMAND_BLOCK.ordinal()] = 6; + } catch (NoSuchFieldError ignored) { + } + + } + } + + public enum EnumMinecartType { + + RIDEABLE(0, "MinecartRideable"), CHEST(1, "MinecartChest"), FURNACE(2, "MinecartFurnace"), TNT(3, "MinecartTNT"), SPAWNER(4, "MinecartSpawner"), HOPPER(5, "MinecartHopper"), COMMAND_BLOCK(6, "MinecartCommandBlock"); + + private static final Map h = Maps.newHashMap(); + private final int i; + private final String j; + + EnumMinecartType(int i, String s) { + this.i = i; + this.j = s; + } + + public int a() { + return this.i; + } + + public String b() { + return this.j; + } + + public static EnumMinecartType a(int i) { + EnumMinecartType entityminecartabstract_enumminecarttype = EnumMinecartType.h.get(i); + + return entityminecartabstract_enumminecarttype == null ? EnumMinecartType.RIDEABLE : entityminecartabstract_enumminecarttype; + } + + static { + + for (EnumMinecartType entityminecartabstract_enumminecarttype : values()) { + EnumMinecartType.h.put(entityminecartabstract_enumminecarttype.a(), entityminecartabstract_enumminecarttype); + } + + } + } + + // CraftBukkit start - Methods for getting and setting flying and derailed velocity modifiers + public Vector getFlyingVelocityMod() { + return new Vector(flyingX, flyingY, flyingZ); + } + + public void setFlyingVelocityMod(Vector flying) { + flyingX = flying.getX(); + flyingY = flying.getY(); + flyingZ = flying.getZ(); + } + + public Vector getDerailedVelocityMod() { + return new Vector(derailedX, derailedY, derailedZ); + } + + public void setDerailedVelocityMod(Vector derailed) { + derailedX = derailed.getX(); + derailedY = derailed.getY(); + derailedZ = derailed.getZ(); + } + // CraftBukkit end +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityMinecartChest.java b/azurite-server/src/main/java/net/minecraft/server/EntityMinecartChest.java new file mode 100644 index 0000000..dcee0df --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityMinecartChest.java @@ -0,0 +1,44 @@ +package net.minecraft.server; + +public class EntityMinecartChest extends EntityMinecartContainer { + + public EntityMinecartChest(World world) { + super(world); + } + + public EntityMinecartChest(World world, double d0, double d1, double d2) { + super(world, d0, d1, d2); + } + + public void a(DamageSource damagesource) { + super.a(damagesource); + if (this.world.getGameRules().getBoolean("doEntityDrops")) { + this.a(Item.getItemOf(Blocks.CHEST), 1, 0.0F); + } + + } + + public int getSize() { + return 27; + } + + public EntityMinecartAbstract.EnumMinecartType s() { + return EntityMinecartAbstract.EnumMinecartType.CHEST; + } + + public IBlockData u() { + return Blocks.CHEST.getBlockData().set(BlockChest.FACING, EnumDirection.NORTH); + } + + public int w() { + return 8; + } + + public String getContainerName() { + return "minecraft:chest"; + } + + public Container createContainer(PlayerInventory playerinventory, EntityHuman entityhuman) { + return new ContainerChest(playerinventory, this, entityhuman); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityMinecartCommandBlock.java b/azurite-server/src/main/java/net/minecraft/server/EntityMinecartCommandBlock.java new file mode 100644 index 0000000..21d0f5f --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityMinecartCommandBlock.java @@ -0,0 +1,95 @@ +package net.minecraft.server; + +public class EntityMinecartCommandBlock extends EntityMinecartAbstract { + + private final CommandBlockListenerAbstract a = new CommandBlockListenerAbstract() { + { + this.sender = EntityMinecartCommandBlock.this.getBukkitEntity(); // CraftBukkit - Set the sender + } + public void h() { + EntityMinecartCommandBlock.this.getDataWatcher().watch(23, this.getCommand()); + EntityMinecartCommandBlock.this.getDataWatcher().watch(24, IChatBaseComponent.ChatSerializer.a(this.k())); + } + + public BlockPosition getChunkCoordinates() { + return new BlockPosition(EntityMinecartCommandBlock.this.locX, EntityMinecartCommandBlock.this.locY + 0.5D, EntityMinecartCommandBlock.this.locZ); + } + + public Vec3D d() { + return new Vec3D(EntityMinecartCommandBlock.this.locX, EntityMinecartCommandBlock.this.locY, EntityMinecartCommandBlock.this.locZ); + } + + public World getWorld() { + return EntityMinecartCommandBlock.this.world; + } + + public Entity f() { + return EntityMinecartCommandBlock.this; + } + }; + private int b = 0; + + public EntityMinecartCommandBlock(World world) { + super(world); + } + + public EntityMinecartCommandBlock(World world, double d0, double d1, double d2) { + super(world, d0, d1, d2); + } + + protected void h() { + super.h(); + this.getDataWatcher().a(23, ""); + this.getDataWatcher().a(24, ""); + } + + protected void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + this.a.b(nbttagcompound); + this.getDataWatcher().watch(23, this.getCommandBlock().getCommand()); + this.getDataWatcher().watch(24, IChatBaseComponent.ChatSerializer.a(this.getCommandBlock().k())); + } + + protected void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + this.a.a(nbttagcompound); + } + + public EnumMinecartType s() { + return EnumMinecartType.COMMAND_BLOCK; + } + + public IBlockData u() { + return Blocks.COMMAND_BLOCK.getBlockData(); + } + + public CommandBlockListenerAbstract getCommandBlock() { + return this.a; + } + + public void a(int i, int j, int k, boolean flag) { + if (flag && this.ticksLived - this.b >= 4) { + this.getCommandBlock().a(this.world); + this.b = this.ticksLived; + } + + } + + public boolean e(EntityHuman entityhuman) { + this.a.a(entityhuman); + return false; + } + + public void i(int i) { + super.i(i); + if (i == 24) { + try { + this.a.b(IChatBaseComponent.ChatSerializer.a(this.getDataWatcher().getString(24))); + } catch (Throwable ignored) { + } + } else if (i == 23) { + this.a.setCommand(this.getDataWatcher().getString(23)); + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityMinecartContainer.java b/azurite-server/src/main/java/net/minecraft/server/EntityMinecartContainer.java new file mode 100644 index 0000000..5027ca6 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityMinecartContainer.java @@ -0,0 +1,246 @@ +package net.minecraft.server; + +// CraftBukkit start + +import net.techcable.tacospigot.HopperPusher; +import org.bukkit.craftbukkit.entity.CraftHumanEntity; +import org.bukkit.entity.HumanEntity; +import org.bukkit.inventory.InventoryHolder; + +import java.util.Arrays; +import java.util.List; + +// TacoSpigot start - HopperPusher +public abstract class EntityMinecartContainer extends EntityMinecartAbstract implements ITileInventory, HopperPusher { + + @Override + public boolean acceptItem(TileEntityHopper hopper) { + return TileEntityHopper.acceptItem(hopper, this); + } + // TacoSpigot end + + private ItemStack[] items = new ItemStack[27]; // CraftBukkit - 36 -> 27 + private boolean b = true; + + // CraftBukkit start + public List transaction = new java.util.ArrayList<>(); + private int maxStack = MAX_STACK; + + public ItemStack[] getContents() { + return this.items; + } + + public void onOpen(CraftHumanEntity who) { + transaction.add(who); + } + + public void onClose(CraftHumanEntity who) { + transaction.remove(who); + } + + public List getViewers() { + return transaction; + } + + public InventoryHolder getOwner() { + org.bukkit.entity.Entity cart = getBukkitEntity(); + if(cart instanceof InventoryHolder) return (InventoryHolder) cart; + return null; + } + + public void setMaxStackSize(int size) { + maxStack = size; + } + // CraftBukkit end + + public EntityMinecartContainer(World world) { + super(world); + } + + public EntityMinecartContainer(World world, double d0, double d1, double d2) { + super(world, d0, d1, d2); + } + + public void a(DamageSource damagesource) { + super.a(damagesource); + if (this.world.getGameRules().getBoolean("doEntityDrops")) { + InventoryUtils.dropEntity(this.world, this, this); + } + + } + + // TacoSpigot start + @Override + public void t_() { + super.t_(); + if (ticksLived % 6 == 0) // no need to do this every single tick. + tryPutInHopper(); + } + + @Override + public void inactiveTick() { + super.inactiveTick(); + if (ticksLived % 6 == 0) // no need to do this every tick. + tryPutInHopper(); + } + // TacoSpigot end + + public ItemStack getItem(int i) { + return this.items[i]; + } + + public ItemStack splitStack(int i, int j) { + if (this.items[i] != null) { + ItemStack itemstack; + + if (this.items[i].count <= j) { + itemstack = this.items[i]; + this.items[i] = null; + } else { + itemstack = this.items[i].cloneAndSubtract(j); + if (this.items[i].count == 0) { + this.items[i] = null; + } + + } + return itemstack; + } else { + return null; + } + } + + public ItemStack splitWithoutUpdate(int i) { + if (this.items[i] != null) { + ItemStack itemstack = this.items[i]; + + this.items[i] = null; + return itemstack; + } else { + return null; + } + } + + public void setItem(int i, ItemStack itemstack) { + this.items[i] = itemstack; + if (itemstack != null && itemstack.count > this.getMaxStackSize()) { + itemstack.count = this.getMaxStackSize(); + } + + } + + public void update() {} + + public boolean a(EntityHuman entityhuman) { + return !this.dead && entityhuman.h(this) <= 64.0D; + } + + public void startOpen(EntityHuman entityhuman) {} + + public void closeContainer(EntityHuman entityhuman) {} + + public boolean b(int i, ItemStack itemstack) { + return true; + } + + public String getName() { + return this.hasCustomName() ? this.getCustomName() : "container.minecart"; + } + + public int getMaxStackSize() { + return maxStack; // CraftBukkit + } + + public void c(int i) { + // Spigot Start + for ( HumanEntity human : new java.util.ArrayList<>(transaction) ) + { + human.closeInventory(); + } + // Spigot End + this.b = false; + super.c(i); + } + + public void die() { + if (this.b) { + InventoryUtils.dropEntity(this.world, this, this); + } + + super.die(); + } + + protected void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + NBTTagList nbttaglist = new NBTTagList(); + + for (int i = 0; i < this.items.length; ++i) { + if (this.items[i] != null) { + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + + nbttagcompound1.setByte("Slot", (byte) i); + this.items[i].save(nbttagcompound1); + nbttaglist.add(nbttagcompound1); + } + } + + nbttagcompound.set("Items", nbttaglist); + } + + protected void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + NBTTagList nbttaglist = nbttagcompound.getList("Items", 10); + + this.items = new ItemStack[this.getSize()]; + + for (int i = 0; i < nbttaglist.size(); ++i) { + NBTTagCompound nbttagcompound1 = nbttaglist.get(i); + int j = nbttagcompound1.getByte("Slot") & 255; + + if (j < this.items.length) { + this.items[j] = ItemStack.createStack(nbttagcompound1); + } + } + + } + + public boolean e(EntityHuman entityhuman) { + + entityhuman.openContainer(this); + + return true; + } + + protected void o() { + int i = 15 - Container.b(this); + float f = 0.98F + (float) i * 0.001F; + + this.motX *= f; + this.motY *= 0.0D; + this.motZ *= f; + } + + public int getProperty(int i) { + return 0; + } + + public void b(int i, int j) {} + + public int g() { + return 0; + } + + public boolean r_() { + return false; + } + + public void a(ChestLock chestlock) {} + + public ChestLock i() { + return ChestLock.a; + } + + public void l() { + Arrays.fill(this.items, null); + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityMinecartFurnace.java b/azurite-server/src/main/java/net/minecraft/server/EntityMinecartFurnace.java new file mode 100644 index 0000000..35720ab --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityMinecartFurnace.java @@ -0,0 +1,139 @@ +package net.minecraft.server; + +public class EntityMinecartFurnace extends EntityMinecartAbstract { + + private int c; + public double a; + public double b; + + public EntityMinecartFurnace(World world) { + super(world); + } + + public EntityMinecartFurnace(World world, double d0, double d1, double d2) { + super(world, d0, d1, d2); + } + + public EnumMinecartType s() { + return EnumMinecartType.FURNACE; + } + + protected void h() { + super.h(); + this.datawatcher.a(16, (byte) 0); + } + + public void t_() { + super.t_(); + if (this.c > 0) { + --this.c; + } + + if (this.c <= 0) { + this.a = this.b = 0.0D; + } + + this.i(this.c > 0); + if (this.j() && random.nextInt(4) == 0) { + this.world.addParticle(EnumParticle.SMOKE_LARGE, this.locX, this.locY + 0.8D, this.locZ, 0.0D, 0.0D, 0.0D, EnumParticle.EMPTY_ARRAY); + } + + } + + protected double m() { + return 0.2D; + } + + public void a(DamageSource damagesource) { + super.a(damagesource); + if (!damagesource.isExplosion() && this.world.getGameRules().getBoolean("doEntityDrops")) { + this.a(new ItemStack(Blocks.FURNACE, 1), 0.0F); + } + + } + + protected void a(final int x, final int y, final int z, IBlockData iblockdata) { + super.a(x,y,z, iblockdata); + double d0 = this.a * this.a + this.b * this.b; + + if (d0 > 1.0E-4D && this.motX * this.motX + this.motZ * this.motZ > 0.001D) { + d0 = MathHelper.sqrt(d0); + // PaperSpigot - Don't lose all your velocity on corners + // https://bugs.mojang.com/browse/MC-51053?focusedCommentId=223854 + double d1 = MathHelper.sqrt(this.motX * this.motX + this.motZ * this.motZ); + this.a = (motX / d1) * d0; + this.b = (motZ / d1) * d0; + // PaperSpigot end + } + + } + + protected void o() { + double d0 = this.a * this.a + this.b * this.b; + + if (d0 > 1.0E-4D) { + d0 = MathHelper.sqrt(d0); + this.a /= d0; + this.b /= d0; + double d1 = 1.0D; + + this.motX *= 0.800000011920929D; + this.motY *= 0.0D; + this.motZ *= 0.800000011920929D; + this.motX += this.a * d1; + this.motZ += this.b * d1; + } else { + this.motX *= 0.9800000190734863D; + this.motY *= 0.0D; + this.motZ *= 0.9800000190734863D; + } + + super.o(); + } + + public boolean e(EntityHuman entityhuman) { + ItemStack itemstack = entityhuman.inventory.getItemInHand(); + + if (itemstack != null && itemstack.getItem() == Items.COAL) { + if (!entityhuman.abilities.canInstantlyBuild && --itemstack.count == 0) { + entityhuman.inventory.setItem(entityhuman.inventory.itemInHandIndex, null); + } + + this.c += 3600; + } + + this.a = this.locX - entityhuman.locX; + this.b = this.locZ - entityhuman.locZ; + return true; + } + + protected void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + nbttagcompound.setDouble("PushX", this.a); + nbttagcompound.setDouble("PushZ", this.b); + nbttagcompound.setShort("Fuel", (short) this.c); + } + + protected void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + this.a = nbttagcompound.getDouble("PushX"); + this.b = nbttagcompound.getDouble("PushZ"); + this.c = nbttagcompound.getShort("Fuel"); + } + + protected boolean j() { + return (this.datawatcher.getByte(16) & 1) != 0; + } + + protected void i(boolean flag) { + if (flag) { + this.datawatcher.watch(16, (byte) (this.datawatcher.getByte(16) | 1)); + } else { + this.datawatcher.watch(16, (byte) (this.datawatcher.getByte(16) & -2)); + } + } + + public IBlockData u() { + return (this.j() ? Blocks.LIT_FURNACE : Blocks.FURNACE).getBlockData().set(BlockFurnace.FACING, EnumDirection.NORTH); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityMinecartHopper.java b/azurite-server/src/main/java/net/minecraft/server/EntityMinecartHopper.java new file mode 100644 index 0000000..3cd2e62 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityMinecartHopper.java @@ -0,0 +1,145 @@ +package net.minecraft.server; + +import java.util.List; + +public class EntityMinecartHopper extends EntityMinecartContainer implements IHopper { + + private boolean a = true; + private int b = -1; + private final BlockPosition c; + + public EntityMinecartHopper(World world) { + super(world); + this.c = BlockPosition.ZERO; + } + + public EntityMinecartHopper(World world, double d0, double d1, double d2) { + super(world, d0, d1, d2); + this.c = BlockPosition.ZERO; + } + + public EnumMinecartType s() { + return EnumMinecartType.HOPPER; + } + + public IBlockData u() { + return Blocks.HOPPER.getBlockData(); + } + + public int w() { + return 1; + } + + public int getSize() { + return 5; + } + + public boolean e(EntityHuman entityhuman) { + entityhuman.openContainer(this); + + return true; + } + + public void a(int i, int j, int k, boolean flag) { + boolean flag1 = !flag; + + if (flag1 != this.y()) { + this.i(flag1); + } + + } + + public boolean y() { + return this.a; + } + + public void i(boolean flag) { + this.a = flag; + } + + public World getWorld() { + return this.world; + } + + public double A() { + return this.locX; + } + + public double B() { + return this.locY + 0.5D; + } + + public double C() { + return this.locZ; + } + + public void t_() { + super.t_(); + if (this.isAlive() && this.y()) { + BlockPosition blockposition = new BlockPosition(this); + + if (blockposition.equals(this.c)) { + --this.b; + } else { + this.m(0); + } + + if (!this.E()) { + this.m(0); + if (this.D()) { + this.m(4); + this.update(); + } + } + } + + } + + public boolean D() { + if (TileEntityHopper.a(this)) { + return true; + } else { + List list = this.world.a(EntityItem.class, this.getBoundingBox().grow(0.25D, 0.0D, 0.25D), IEntitySelector.a); + + if (list.size() > 0) { + TileEntityHopper.a(this, list.get(0)); + } + + return false; + } + } + + public void a(DamageSource damagesource) { + super.a(damagesource); + if (this.world.getGameRules().getBoolean("doEntityDrops")) { + this.a(Item.getItemOf(Blocks.HOPPER), 1, 0.0F); + } + + } + + protected void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + nbttagcompound.setInt("TransferCooldown", this.b); + } + + protected void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + this.b = nbttagcompound.getInt("TransferCooldown"); + } + + public void m(int i) { + this.b = i; + } + + public boolean E() { + return this.b > 0; + } + + public String getContainerName() { + return "minecraft:hopper"; + } + + public Container createContainer(PlayerInventory playerinventory, EntityHuman entityhuman) { + return new ContainerHopper(playerinventory, this, entityhuman); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityMinecartMobSpawner.java b/azurite-server/src/main/java/net/minecraft/server/EntityMinecartMobSpawner.java new file mode 100644 index 0000000..1a8dc6b --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityMinecartMobSpawner.java @@ -0,0 +1,49 @@ +package net.minecraft.server; + +public class EntityMinecartMobSpawner extends EntityMinecartAbstract { + + private final MobSpawnerAbstract a = new MobSpawnerAbstract() { + public void a(int i) { + EntityMinecartMobSpawner.this.world.broadcastEntityEffect(EntityMinecartMobSpawner.this, (byte) i); + } + + public World a() { + return EntityMinecartMobSpawner.this.world; + } + + public BlockPosition b() { + return new BlockPosition(EntityMinecartMobSpawner.this); + } + }; + + public EntityMinecartMobSpawner(World world) { + super(world); + } + + public EntityMinecartMobSpawner(World world, double d0, double d1, double d2) { + super(world, d0, d1, d2); + } + + public EntityMinecartAbstract.EnumMinecartType s() { + return EntityMinecartAbstract.EnumMinecartType.SPAWNER; + } + + public IBlockData u() { + return Blocks.MOB_SPAWNER.getBlockData(); + } + + protected void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + this.a.a(nbttagcompound); + } + + protected void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + this.a.b(nbttagcompound); + } + + public void t_() { + super.t_(); + this.a.c(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityMinecartRideable.java b/azurite-server/src/main/java/net/minecraft/server/EntityMinecartRideable.java new file mode 100644 index 0000000..bcd9f62 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityMinecartRideable.java @@ -0,0 +1,46 @@ +package net.minecraft.server; + +public class EntityMinecartRideable extends EntityMinecartAbstract { + + public EntityMinecartRideable(World world) { + super(world); + } + + public EntityMinecartRideable(World world, double d0, double d1, double d2) { + super(world, d0, d1, d2); + } + + public boolean e(EntityHuman entityhuman) { + if (this.passenger != null && this.passenger instanceof EntityHuman && this.passenger != entityhuman) { + return true; + } else if (this.passenger != null && this.passenger != entityhuman) { + return false; + } else { + if (!this.world.isClientSide) { + entityhuman.mount(this); + } + + return true; + } + } + + public void a(int i, int j, int k, boolean flag) { + if (flag) { + if (this.passenger != null) { + this.passenger.mount((Entity) null); + } + + if (this.getType() == 0) { + this.k(-this.r()); + this.j(10); + this.setDamage(50.0F); + this.ac(); + } + } + + } + + public EntityMinecartAbstract.EnumMinecartType s() { + return EntityMinecartAbstract.EnumMinecartType.RIDEABLE; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityMinecartTNT.java b/azurite-server/src/main/java/net/minecraft/server/EntityMinecartTNT.java new file mode 100644 index 0000000..b4335d8 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityMinecartTNT.java @@ -0,0 +1,125 @@ +package net.minecraft.server; + +public class EntityMinecartTNT extends EntityMinecartAbstract { + private int a = -1; + + public EntityMinecartTNT(World var1) { + super(var1); + } + + public EntityMinecartTNT(World var1, double var2, double var4, double var6) { + super(var1, var2, var4, var6); + } + + public EntityMinecartAbstract.EnumMinecartType s() { + return EnumMinecartType.TNT; + } + + public IBlockData u() { + return Blocks.TNT.getBlockData(); + } + + public void t_() { + super.t_(); + if (this.a > 0) { + --this.a; + this.world.addParticle(EnumParticle.SMOKE_NORMAL, this.locX, this.locY + 0.5, this.locZ, 0.0, 0.0, 0.0, EnumParticle.EMPTY_ARRAY); + } else if (this.a == 0) { + this.b(this.motX * this.motX + this.motZ * this.motZ); + } + + if (this.positionChanged) { + double var1 = this.motX * this.motX + this.motZ * this.motZ; + if (var1 >= 0.009999999776482582) { + this.b(var1); + } + } + + } + + public boolean damageEntity(DamageSource var1, float var2) { + Entity var3 = var1.i(); + if (var3 instanceof EntityArrow) { + EntityArrow var4 = (EntityArrow) var3; + if (var4.isBurning()) { + this.b(var4.motX * var4.motX + var4.motY * var4.motY + var4.motZ * var4.motZ); + } + } + + return super.damageEntity(var1, var2); + } + + public void a(DamageSource var1) { + super.a(var1); + double var2 = this.motX * this.motX + this.motZ * this.motZ; + if (!var1.isExplosion() && this.world.getGameRules().getBoolean("doEntityDrops")) { + this.a(new ItemStack(Blocks.TNT, 1), 0.0F); + } + + if (var1.o() || var1.isExplosion() || var2 >= 0.009999999776482582) { + this.b(var2); + } + + } + + protected void b(double var1) { + double var3 = Math.sqrt(var1); + if (var3 > 5.0) { + var3 = 5.0; + } + + this.world.explode(this, this.locX, this.locY, this.locZ, (float) (4.0 + random.nextDouble() * 1.5 * var3), true); + this.die(); + + } + + public void e(float var1, float var2) { + if (var1 >= 3.0F) { + float var3 = var1 / 10.0F; + this.b(var3 * var3); + } + + super.e(var1, var2); + } + + public void a(int var1, int var2, int var3, boolean var4) { + if (var4 && this.a < 0) { + this.j(); + } + + } + + public void j() { + this.a = 80; + this.world.broadcastEntityEffect(this, (byte) 10); + if (!this.R()) { + this.world.makeSound(this, "game.tnt.primed", 1.0F, 1.0F); + } + + } + + public boolean y() { + return this.a > -1; + } + + public float a(Explosion var1, World var2, BlockPosition var3, IBlockData var4) { + return !this.y() || !BlockMinecartTrackAbstract.d(var4) && !BlockMinecartTrackAbstract.e(var2, var3.up()) ? super.a(var1, var2, var3, var4) : 0.0F; + } + + public boolean a(Explosion var1, World var2, BlockPosition var3, IBlockData var4, float var5) { + return (!this.y() || !BlockMinecartTrackAbstract.d(var4) && !BlockMinecartTrackAbstract.e(var2, var3.up())) && super.a(var1, var2, var3, var4, var5); + } + + protected void a(NBTTagCompound var1) { + super.a(var1); + if (var1.hasKeyOfType("TNTFuse", 99)) { + this.a = var1.getInt("TNTFuse"); + } + + } + + protected void b(NBTTagCompound var1) { + super.b(var1); + var1.setInt("TNTFuse", this.a); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityMonster.java b/azurite-server/src/main/java/net/minecraft/server/EntityMonster.java new file mode 100644 index 0000000..503dbd9 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityMonster.java @@ -0,0 +1,136 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.AzuriteConfig; +import org.bukkit.event.entity.EntityCombustByEntityEvent; + +public abstract class EntityMonster extends EntityCreature implements IMonster { + + public EntityMonster(World world) { + super(world); + this.b_ = 5; + } + + public void m() { + this.bx(); + float f = this.c(1.0F); + + if (f > 0.5F) { + this.ticksFarFromPlayer += 2; + } + + super.m(); + } + + public void t_() { + super.t_(); + if (this.world.getDifficulty() == EnumDifficulty.PEACEFUL) { + this.die(); + } + + } + + protected String P() { + return "game.hostile.swim"; + } + + protected String aa() { + return "game.hostile.swim.splash"; + } + + public boolean damageEntity(DamageSource damagesource, float f) { + if (this.isInvulnerable(damagesource)) { + return false; + } else return super.damageEntity(damagesource, f); + } + + protected String bo() { + return "game.hostile.hurt"; + } + + protected String bp() { + return "game.hostile.die"; + } + + protected String n(int i) { + return i > 4 ? "game.hostile.hurt.fall.big" : "game.hostile.hurt.fall.small"; + } + + public boolean r(Entity entity) { + float f = (float) this.getAttributeInstance(GenericAttributes.ATTACK_DAMAGE).getValue(); + int i = 0; + + if (entity instanceof EntityLiving) { + f += EnchantmentManager.a(this.bA(), ((EntityLiving) entity).getMonsterType()); + i += EnchantmentManager.a(this); + } + + boolean flag = entity.damageEntity(DamageSource.mobAttack(this), f); + + if (flag) { + if (i > 0) { + entity.g(-MathHelper.sin(this.yaw * 3.1415927F / 180.0F) * (float) i * 0.5F, 0.1D, MathHelper.cos(this.yaw * 3.1415927F / 180.0F) * (float) i * 0.5F); + this.motX *= 0.6D; + this.motZ *= 0.6D; + } + + int j = EnchantmentManager.getFireAspectEnchantmentLevel(this); + + if (j > 0) { + // CraftBukkit start - Call a combust event when somebody hits with a fire enchanted item + EntityCombustByEntityEvent combustEvent = new EntityCombustByEntityEvent(this.getBukkitEntity(), entity.getBukkitEntity(), j * 4); + org.bukkit.Bukkit.getPluginManager().callEvent(combustEvent); + + if (!combustEvent.isCancelled()) { + entity.setOnFire(combustEvent.getDuration()); + } + // CraftBukkit end + } + + this.a(this, entity); + } + + return flag; + } + + public float a(BlockPosition blockposition) { + return 0.5F - this.world.o(blockposition); + } + + protected boolean n_() { + if (AzuriteConfig.disableBlockLighting.getValue()) + return true; + int x = MathHelper.floor(locX), y = MathHelper.floor(boundingBox.b), z = MathHelper.floor(locZ); + + if (this.world.b(EnumSkyBlock.SKY, x, y, z) > random.nextInt(32)) { + return false; + } else { + // PandaSpigot start + // int i = this.world.getLightLevel(blockposition); + boolean passes; + // PandaSpigot end + + if (this.world.R()) { + int j = this.world.ab(); + + this.world.c(10); + passes = !this.world.isLightLevel(x, y, z, this.random.nextInt(8)); // PandaSpigot + this.world.c(j); + } else { passes = !this.world.isLightLevel(x, y, z, this.random.nextInt(8)); } // PandaSpigot + + return passes; // PandaSpigot + } + } + + public boolean bR() { + return this.world.getDifficulty() != EnumDifficulty.PEACEFUL && this.n_() && super.bR(); + } + + protected void initAttributes() { + super.initAttributes(); + this.getAttributeMap().b(GenericAttributes.ATTACK_DAMAGE); + } + + protected boolean ba() { + return true; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityMushroomCow.java b/azurite-server/src/main/java/net/minecraft/server/EntityMushroomCow.java new file mode 100644 index 0000000..adc9d20 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityMushroomCow.java @@ -0,0 +1,75 @@ +package net.minecraft.server; + +import org.bukkit.event.player.PlayerShearEntityEvent; + +public class EntityMushroomCow extends EntityCow { + + public EntityMushroomCow(World world) { + super(world); + this.setSize(0.9F, 1.3F); + this.bn = Blocks.MYCELIUM; + } + + public boolean a(EntityHuman entityhuman) { + ItemStack itemstack = entityhuman.inventory.getItemInHand(); + + if (itemstack != null && itemstack.getItem() == Items.BOWL && this.getAge() >= 0) { + if (itemstack.count == 1) { + entityhuman.inventory.setItem(entityhuman.inventory.itemInHandIndex, new ItemStack(Items.MUSHROOM_STEW)); + return true; + } + + if (entityhuman.inventory.pickup(new ItemStack(Items.MUSHROOM_STEW)) && !entityhuman.abilities.canInstantlyBuild) { + entityhuman.inventory.splitStack(entityhuman.inventory.itemInHandIndex, 1); + return true; + } + } + + if (itemstack != null && itemstack.getItem() == Items.SHEARS && this.getAge() >= 0) { + // CraftBukkit start + PlayerShearEntityEvent event = new PlayerShearEntityEvent((org.bukkit.entity.Player) entityhuman.getBukkitEntity(), this.getBukkitEntity()); + this.world.getServer().getPluginManager().callEvent(event); + + if (event.isCancelled()) { + return false; + } + // CraftBukkit end + this.die(); + this.world.addParticle(EnumParticle.EXPLOSION_LARGE, this.locX, this.locY + (this.length / 2.0F), this.locZ, 0.0D, 0.0D, 0.0D, EnumParticle.EMPTY_ARRAY); + + EntityCow entitycow = new EntityCow(this.world); + + entitycow.setPositionRotation(this.locX, this.locY, this.locZ, this.yaw, this.pitch); + entitycow.setHealth(this.getHealth()); + entitycow.aI = this.aI; + if (this.hasCustomName()) { + entitycow.setCustomName(this.getCustomName()); + } + + this.world.addEntity(entitycow); + + for (int i = 0; i < 5; ++i) { + this.world.addEntity(new EntityItem(this.world, this.locX, this.locY + (double) this.length, this.locZ, new ItemStack(Blocks.RED_MUSHROOM))); + } + + itemstack.damage(1, entityhuman); + this.makeSound("mob.sheep.shear", 1.0F, 1.0F); + + return true; + } else { + return super.a(entityhuman); + } + } + + public EntityMushroomCow c(EntityAgeable entityageable) { + return new EntityMushroomCow(this.world); + } + + public EntityCow b(EntityAgeable entityageable) { + return this.c(entityageable); + } + + public EntityAgeable createChild(EntityAgeable entityageable) { + return this.c(entityageable); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityOcelot.java b/azurite-server/src/main/java/net/minecraft/server/EntityOcelot.java new file mode 100644 index 0000000..e2a655e --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityOcelot.java @@ -0,0 +1,233 @@ +package net.minecraft.server; + +public class EntityOcelot extends EntityTameableAnimal { + + public boolean spawnBonus = true; // Spigot + private PathfinderGoalAvoidTarget bo; + private final PathfinderGoalTempt bp; + + public EntityOcelot(World world) { + super(world); + this.setSize(0.6F, 0.7F); + ((Navigation) this.getNavigation()).a(true); + this.goalSelector.a(1, new PathfinderGoalFloat(this)); + this.goalSelector.a(2, this.bm); + this.goalSelector.a(3, this.bp = new PathfinderGoalTempt(this, 0.6D, Items.FISH, true)); + this.goalSelector.a(5, new PathfinderGoalFollowOwner(this, 1.0D, 10.0F, 5.0F)); + this.goalSelector.a(6, new PathfinderGoalJumpOnBlock(this, 0.8D)); + this.goalSelector.a(7, new PathfinderGoalLeapAtTarget(this, 0.3F)); + this.goalSelector.a(8, new PathfinderGoalOcelotAttack(this)); + this.goalSelector.a(9, new PathfinderGoalBreed(this, 0.8D)); + this.goalSelector.a(10, new PathfinderGoalRandomStroll(this, 0.8D)); + this.goalSelector.a(11, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 10.0F)); + this.targetSelector.a(1, new PathfinderGoalRandomTargetNonTamed<>(this, EntityChicken.class, false, null)); + } + + protected void h() { + super.h(); + this.datawatcher.a(18, (byte) 0); + } + + public void E() { + if (this.getControllerMove().a()) { + double d0 = this.getControllerMove().b(); + + if (d0 == 0.6D) { + this.setSneaking(true); + this.setSprinting(false); + } else if (d0 == 1.33D) { + this.setSneaking(false); + this.setSprinting(true); + } else { + this.setSneaking(false); + this.setSprinting(false); + } + } else { + this.setSneaking(false); + this.setSprinting(false); + } + + } + + public boolean isTypeNotPersistent() { + return !this.isTamed() /*&& this.ticksLived > 2400*/; // CraftBukkit + } + + protected void initAttributes() { + super.initAttributes(); + this.getAttributeInstance(GenericAttributes.maxHealth).setValue(10.0D); + this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.30000001192092896D); + } + + public void e(float f, float f1) { + } + + public void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + nbttagcompound.setInt("CatType", this.getCatType()); + } + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + this.setCatType(nbttagcompound.getInt("CatType")); + } + + protected String z() { + return this.isTamed() ? (this.isInLove() ? "mob.cat.purr" : (random.nextInt(4) == 0 ? "mob.cat.purreow" : "mob.cat.meow")) : ""; + } + + protected String bo() { + return "mob.cat.hitt"; + } + + protected String bp() { + return "mob.cat.hitt"; + } + + protected float bB() { + return 0.4F; + } + + protected Item getLoot() { + return Items.LEATHER; + } + + public boolean r(Entity entity) { + return entity.damageEntity(DamageSource.mobAttack(this), 3.0F); + } + + protected void dropDeathLoot(boolean flag, int i) { + } + + public boolean a(EntityHuman entityhuman) { + ItemStack itemstack = entityhuman.inventory.getItemInHand(); + + if (this.isTamed()) { + if (this.e((EntityLiving) entityhuman) && !this.d(itemstack)) { + this.bm.setSitting(!this.isSitting()); + } + } else if (this.bp.f() && itemstack != null && itemstack.getItem() == Items.FISH && entityhuman.h(this) < 9.0D) { + if (!entityhuman.abilities.canInstantlyBuild) { + --itemstack.count; + } + + if (itemstack.count <= 0) { + entityhuman.inventory.setItem(entityhuman.inventory.itemInHandIndex, null); + } + + // CraftBukkit - added event call and isCancelled check + if (random.nextInt(3) == 0 && !org.bukkit.craftbukkit.event.CraftEventFactory.callEntityTameEvent(this, entityhuman).isCancelled()) { + this.setTamed(true); + this.setCatType(1 + this.world.random.nextInt(3)); + this.setOwnerUUID(entityhuman.getUniqueID().toString()); + this.l(true); + this.bm.setSitting(true); + this.world.broadcastEntityEffect(this, (byte) 7); + } else { + this.l(false); + this.world.broadcastEntityEffect(this, (byte) 6); + } + + return true; + } + + return super.a(entityhuman); + } + + public EntityOcelot b(EntityAgeable entityageable) { + EntityOcelot entityocelot = new EntityOcelot(this.world); + + if (this.isTamed()) { + entityocelot.setOwnerUUID(this.getOwnerUUID()); + entityocelot.setTamed(true); + entityocelot.setCatType(this.getCatType()); + } + + return entityocelot; + } + + public boolean d(ItemStack itemstack) { + return itemstack != null && itemstack.getItem() == Items.FISH; + } + + public boolean mate(EntityAnimal entityanimal) { + if (entityanimal == this) { + return false; + } else if (!this.isTamed()) { + return false; + } else if (!(entityanimal instanceof EntityOcelot)) { + return false; + } else { + EntityOcelot entityocelot = (EntityOcelot) entityanimal; + + return entityocelot.isTamed() && this.isInLove() && entityocelot.isInLove(); + } + } + + public int getCatType() { + return this.datawatcher.getByte(18); + } + + public void setCatType(int i) { + this.datawatcher.watch(18, (byte) i); + } + + public boolean bR() { + return this.world.random.nextInt(3) != 0; + } + + public boolean canSpawn() { + if (this.world.a(this.getBoundingBox(), this) && this.world.getCubes(this, this.getBoundingBox()).isEmpty() && !this.world.containsLiquid(this.getBoundingBox())) { + BlockPosition blockposition = new BlockPosition(this.locX, this.getBoundingBox().b, this.locZ); + + if (blockposition.getY() < this.world.F()) { + return false; + } + + Block block = this.world.getType(blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()).getBlock(); + + return block == Blocks.GRASS || block.getMaterial() == Material.LEAVES; + } + + return false; + } + + public String getName() { + return this.hasCustomName() ? this.getCustomName() : (this.isTamed() ? LocaleI18n.get("entity.Cat.name") : super.getName()); + } + + public void setTamed(boolean flag) { + super.setTamed(flag); + } + + protected void cm() { + if (this.bo == null) { + this.bo = new PathfinderGoalAvoidTarget<>(this, EntityHuman.class, 16.0F, 0.8D, 1.33D); + } + + this.goalSelector.a(this.bo); + if (!this.isTamed()) { + this.goalSelector.a(4, this.bo); + } + + } + + public GroupDataEntity prepare(DifficultyDamageScaler difficultydamagescaler, GroupDataEntity groupdataentity) { + groupdataentity = super.prepare(difficultydamagescaler, groupdataentity); + if (spawnBonus && this.world.random.nextInt(7) == 0) { // Spigot + for (int i = 0; i < 2; ++i) { + EntityOcelot entityocelot = new EntityOcelot(this.world); + + entityocelot.setPositionRotation(this.locX, this.locY, this.locZ, this.yaw, 0.0F); + entityocelot.setAgeRaw(-24000); + this.world.addEntity(entityocelot, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.OCELOT_BABY); // CraftBukkit - add SpawnReason + } + } + + return groupdataentity; + } + + public EntityAgeable createChild(EntityAgeable entityageable) { + return this.b(entityageable); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityOwnable.java b/azurite-server/src/main/java/net/minecraft/server/EntityOwnable.java new file mode 100644 index 0000000..c5d6620 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityOwnable.java @@ -0,0 +1,8 @@ +package net.minecraft.server; + +public interface EntityOwnable { + + String getOwnerUUID(); + + Entity getOwner(); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityPainting.java b/azurite-server/src/main/java/net/minecraft/server/EntityPainting.java new file mode 100644 index 0000000..ab36795 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityPainting.java @@ -0,0 +1,103 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; + +import java.util.ArrayList; + +public class EntityPainting extends EntityHanging { + + public EntityPainting.EnumArt art; + + public EntityPainting(World world) { + super(world); + this.art = EnumArt.values()[random.nextInt(EnumArt.values().length)]; // CraftBukkit - generate a non-null painting + } + + public EntityPainting(World world, BlockPosition blockposition, EnumDirection enumdirection) { + super(world, blockposition); + ArrayList arraylist = Lists.newArrayList(); + + for (EnumArt entitypainting_enumart : EntityPainting.EnumArt.values()) { + this.art = entitypainting_enumart; + this.setDirection(enumdirection); + if (this.survives()) { + arraylist.add(entitypainting_enumart); + } + } + + if (!arraylist.isEmpty()) { + this.art = arraylist.get(random.nextInt(arraylist.size())); + } + + this.setDirection(enumdirection); + } + + public void b(NBTTagCompound nbttagcompound) { + nbttagcompound.setString("Motive", this.art.B); + super.b(nbttagcompound); + } + + public void a(NBTTagCompound nbttagcompound) { + String s = nbttagcompound.getString("Motive"); + + for (EnumArt entitypainting_enumart : EntityPainting.EnumArt.values()) { + if (entitypainting_enumart.B.equals(s)) { + this.art = entitypainting_enumart; + } + } + + if (this.art == null) { + this.art = EntityPainting.EnumArt.KEBAB; + } + + super.a(nbttagcompound); + } + + public int l() { + return this.art.C; + } + + public int m() { + return this.art.D; + } + + public void b(Entity entity) { + if (this.world.getGameRules().getBoolean("doEntityDrops")) { + if (entity instanceof EntityHuman) { + EntityHuman entityhuman = (EntityHuman) entity; + + if (entityhuman.abilities.canInstantlyBuild) { + return; + } + } + + this.a(new ItemStack(Items.PAINTING), 0.0F); + } + } + + public void setPositionRotation(double d0, double d1, double d2, float f, float f1) { + BlockPosition blockposition = this.blockPosition.a(d0 - this.locX, d1 - this.locY, d2 - this.locZ); + + this.setPosition(blockposition.getX(), blockposition.getY(), blockposition.getZ()); + } + + public enum EnumArt { + + KEBAB("Kebab", 16, 16, 0, 0), AZTEC("Aztec", 16, 16, 16, 0), ALBAN("Alban", 16, 16, 32, 0), AZTEC_2("Aztec2", 16, 16, 48, 0), BOMB("Bomb", 16, 16, 64, 0), PLANT("Plant", 16, 16, 80, 0), WASTELAND("Wasteland", 16, 16, 96, 0), POOL("Pool", 32, 16, 0, 32), COURBET("Courbet", 32, 16, 32, 32), SEA("Sea", 32, 16, 64, 32), SUNSET("Sunset", 32, 16, 96, 32), CREEBET("Creebet", 32, 16, 128, 32), WANDERER("Wanderer", 16, 32, 0, 64), GRAHAM("Graham", 16, 32, 16, 64), MATCH("Match", 32, 32, 0, 128), BUST("Bust", 32, 32, 32, 128), STAGE("Stage", 32, 32, 64, 128), VOID("Void", 32, 32, 96, 128), SKULL_AND_ROSES("SkullAndRoses", 32, 32, 128, 128), WITHER("Wither", 32, 32, 160, 128), FIGHTERS("Fighters", 64, 32, 0, 96), POINTER("Pointer", 64, 64, 0, 192), PIGSCENE("Pigscene", 64, 64, 64, 192), BURNING_SKULL("BurningSkull", 64, 64, 128, 192), SKELETON("Skeleton", 64, 48, 192, 64), DONKEY_KONG("DonkeyKong", 64, 48, 192, 112); + + public static final int A = "SkullAndRoses".length(); + public final String B; + public final int C; + public final int D; + public final int E; + public final int F; + + EnumArt(String s, int i, int j, int k, int l) { + this.B = s; + this.C = i; + this.D = j; + this.E = k; + this.F = l; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityPig.java b/azurite-server/src/main/java/net/minecraft/server/EntityPig.java new file mode 100644 index 0000000..6680fc9 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityPig.java @@ -0,0 +1,160 @@ +package net.minecraft.server; + +import org.bukkit.craftbukkit.event.CraftEventFactory; + +public class EntityPig extends EntityAnimal { + + private final PathfinderGoalPassengerCarrotStick bm; + + public EntityPig(World world) { + super(world); + this.setSize(0.9F, 0.9F); + ((Navigation) this.getNavigation()).a(true); + this.goalSelector.a(0, new PathfinderGoalFloat(this)); + this.goalSelector.a(1, new PathfinderGoalPanic(this, 1.25D)); + this.goalSelector.a(2, this.bm = new PathfinderGoalPassengerCarrotStick(this, 0.3F)); + this.goalSelector.a(3, new PathfinderGoalBreed(this, 1.0D)); + this.goalSelector.a(4, new PathfinderGoalTempt(this, 1.2D, Items.CARROT_ON_A_STICK, false)); + this.goalSelector.a(4, new PathfinderGoalTempt(this, 1.2D, Items.CARROT, false)); + this.goalSelector.a(5, new PathfinderGoalFollowParent(this, 1.1D)); + this.goalSelector.a(6, new PathfinderGoalRandomStroll(this, 1.0D)); + this.goalSelector.a(7, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 6.0F)); + this.goalSelector.a(8, new PathfinderGoalRandomLookaround(this)); + } + + protected void initAttributes() { + super.initAttributes(); + this.getAttributeInstance(GenericAttributes.maxHealth).setValue(10.0D); + this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.25D); + } + + public boolean bW() { + ItemStack itemstack = ((EntityHuman) this.passenger).bA(); + + return itemstack != null && itemstack.getItem() == Items.CARROT_ON_A_STICK; + } + + protected void h() { + super.h(); + this.datawatcher.a(16, (byte) 0); + } + + public void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + nbttagcompound.setBoolean("Saddle", this.hasSaddle()); + } + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + this.setSaddle(nbttagcompound.getBoolean("Saddle")); + } + + protected String z() { + return "mob.pig.say"; + } + + protected String bo() { + return "mob.pig.say"; + } + + protected String bp() { + return "mob.pig.death"; + } + + protected void a(BlockPosition blockposition, Block block) { + this.makeSound("mob.pig.step", 0.15F, 1.0F); + } + + public boolean a(EntityHuman entityhuman) { + if (super.a(entityhuman)) { + return true; + } else if (this.hasSaddle() && (this.passenger == null || this.passenger == entityhuman)) { + entityhuman.mount(this); + return true; + } else { + return false; + } + } + + protected Item getLoot() { + return this.isBurning() ? Items.COOKED_PORKCHOP : Items.PORKCHOP; + } + + protected void dropDeathLoot(boolean flag, int i) { + int j = random.nextInt(3) + 1 + random.nextInt(1 + i); + + for (int k = 0; k < j; ++k) { + if (this.isBurning()) { + this.a(Items.COOKED_PORKCHOP, 1); + } else { + this.a(Items.PORKCHOP, 1); + } + } + + if (this.hasSaddle()) { + this.a(Items.SADDLE, 1); + } + + } + + public boolean hasSaddle() { + return (this.datawatcher.getByte(16) & 1) != 0; + } + + public void setSaddle(boolean flag) { + if (flag) { + this.datawatcher.watch(16, (byte) 1); + } else { + this.datawatcher.watch(16, (byte) 0); + } + + } + + public void onLightningStrike(EntityLightning entitylightning) { + if (!this.dead) { + EntityPigZombie entitypigzombie = new EntityPigZombie(this.world); + + // CraftBukkit start + if (CraftEventFactory.callPigZapEvent(this, entitylightning, entitypigzombie).isCancelled()) { + return; + } + // CraftBukkit end + + entitypigzombie.setEquipment(0, new ItemStack(Items.GOLDEN_SWORD)); + entitypigzombie.setPositionRotation(this.locX, this.locY, this.locZ, this.yaw, this.pitch); + entitypigzombie.k(this.ce()); + if (this.hasCustomName()) { + entitypigzombie.setCustomName(this.getCustomName()); + entitypigzombie.setCustomNameVisible(this.getCustomNameVisible()); + } + + // CraftBukkit - added a reason for spawning this creature + this.world.addEntity(entitypigzombie, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.LIGHTNING); + this.die(); + } + } + + public void e(float f, float f1) { + super.e(f, f1); + + if (f > 5.0F && this.passenger instanceof EntityHuman) { + ((EntityHuman) this.passenger).b(AchievementList.u); + } + } + + public EntityPig b(EntityAgeable entityageable) { + return new EntityPig(this.world); + } + + public boolean d(ItemStack itemstack) { + return itemstack != null && itemstack.getItem() == Items.CARROT; + } + + public PathfinderGoalPassengerCarrotStick cm() { + return this.bm; + } + + public EntityAgeable createChild(EntityAgeable entityageable) { + return this.b(entityageable); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityPigZombie.java b/azurite-server/src/main/java/net/minecraft/server/EntityPigZombie.java new file mode 100644 index 0000000..b63c4c0 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityPigZombie.java @@ -0,0 +1,208 @@ +package net.minecraft.server; + +import com.eatthepath.uuid.FastUUID; + +import java.util.UUID; + +public class EntityPigZombie extends EntityZombie { + + private static final UUID b = FastUUID.parseUUID("49455A49-7EC5-45BA-B886-3B90B23A1718"); + private static final AttributeModifier c = (new AttributeModifier(EntityPigZombie.b, "Attacking speed boost", 0.05D, 0)).a(false); + public int angerLevel; + private int soundDelay; + private UUID hurtBy; + + public EntityPigZombie(World world) { + super(world); + this.fireProof = true; + } + + public void b(EntityLiving entityliving) { + super.b(entityliving); + if (entityliving != null) { + this.hurtBy = entityliving.getUniqueID(); + } + + } + + protected void n() { + this.targetSelector.a(1, new EntityPigZombie.PathfinderGoalAngerOther(this)); + this.targetSelector.a(2, new EntityPigZombie.PathfinderGoalAnger(this)); + } + + protected void initAttributes() { + super.initAttributes(); + this.getAttributeInstance(EntityPigZombie.a).setValue(0.0D); + this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.23000000417232513D); + this.getAttributeInstance(GenericAttributes.ATTACK_DAMAGE).setValue(5.0D); + } + + public void t_() { + super.t_(); + } + + protected void E() { + AttributeInstance attributeinstance = this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED); + + if (this.cm()) { + if (!this.isBaby() && !attributeinstance.a(EntityPigZombie.c)) { + attributeinstance.b(EntityPigZombie.c); + } + + --this.angerLevel; + } else if (attributeinstance.a(EntityPigZombie.c)) { + attributeinstance.c(EntityPigZombie.c); + } + + if (this.soundDelay > 0 && --this.soundDelay == 0) { + this.makeSound("mob.zombiepig.zpigangry", this.bB() * 2.0F, ((random.nextFloat() - random.nextFloat()) * 0.2F + 1.0F) * 1.8F); + } + + if (this.angerLevel > 0 && this.hurtBy != null && this.getLastDamager() == null) { + EntityHuman entityhuman = this.world.b(this.hurtBy); + + this.b(entityhuman); + this.killer = entityhuman; + this.lastDamageByPlayerTime = this.be(); + } + + super.E(); + } + + public boolean bR() { + return this.world.getDifficulty() != EnumDifficulty.PEACEFUL; + } + + public boolean canSpawn() { + return this.world.a(this.getBoundingBox(), this) && this.world.getCubes(this, this.getBoundingBox()).isEmpty() && !this.world.containsLiquid(this.getBoundingBox()); + } + + public void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + nbttagcompound.setShort("Anger", (short) this.angerLevel); + if (this.hurtBy != null) { + nbttagcompound.setString("HurtBy", this.hurtBy.toString()); + } else { + nbttagcompound.setString("HurtBy", ""); + } + + } + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + this.angerLevel = nbttagcompound.getShort("Anger"); + String s = nbttagcompound.getString("HurtBy"); + + if (s.length() > 0) { + this.hurtBy = FastUUID.parseUUID(s); + EntityHuman entityhuman = this.world.b(this.hurtBy); + + this.b(entityhuman); + if (entityhuman != null) { + this.killer = entityhuman; + this.lastDamageByPlayerTime = this.be(); + } + } + + } + + public boolean damageEntity(DamageSource damagesource, float f) { + if (this.isInvulnerable(damagesource)) { + return false; + } else { + Entity entity = damagesource.getEntity(); + + if (entity instanceof EntityHuman) { + this.b(entity); + } + + return super.damageEntity(damagesource, f); + } + } + + private void b(Entity entity) { + this.angerLevel = 400 + random.nextInt(400); + this.soundDelay = random.nextInt(40); + if (entity instanceof EntityLiving) { + this.b((EntityLiving) entity); + } + + } + + public boolean cm() { + return this.angerLevel > 0; + } + + protected String z() { + return "mob.zombiepig.zpig"; + } + + protected String bo() { + return "mob.zombiepig.zpighurt"; + } + + protected String bp() { + return "mob.zombiepig.zpigdeath"; + } + + protected void dropDeathLoot(boolean flag, int i) { + int j = random.nextInt(2 + i); + + int k; + + for (k = 0; k < j; ++k) { + this.a(Items.ROTTEN_FLESH, 1); + } + + j = random.nextInt(2 + i); + + for (k = 0; k < j; ++k) { + this.a(Items.GOLD_NUGGET, 1); + } + + } + + public boolean a(EntityHuman entityhuman) { + return false; + } + + protected void getRareDrop() { + this.a(Items.GOLD_INGOT, 1); + } + + protected void a(DifficultyDamageScaler difficultydamagescaler) { + this.setEquipment(0, new ItemStack(Items.GOLDEN_SWORD)); + } + + public GroupDataEntity prepare(DifficultyDamageScaler difficultydamagescaler, GroupDataEntity groupdataentity) { + super.prepare(difficultydamagescaler, groupdataentity); + this.setVillager(false); + return groupdataentity; + } + + static class PathfinderGoalAnger extends PathfinderGoalNearestAttackableTarget { + + public PathfinderGoalAnger(EntityPigZombie entitypigzombie) { + super(entitypigzombie, EntityHuman.class, true); + } + + public boolean a() { + return ((EntityPigZombie) this.e).cm() && super.a(); + } + } + + static class PathfinderGoalAngerOther extends PathfinderGoalHurtByTarget { + + public PathfinderGoalAngerOther(EntityPigZombie entitypigzombie) { + super(entitypigzombie, true); + } + + protected void a(EntityCreature entitycreature, EntityLiving entityliving) { + super.a(entitycreature, entityliving); + if (entitycreature instanceof EntityPigZombie) { + ((EntityPigZombie) entitycreature).b((Entity) entityliving); + } + + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityPlayer.java b/azurite-server/src/main/java/net/minecraft/server/EntityPlayer.java new file mode 100644 index 0000000..72d2cbd --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityPlayer.java @@ -0,0 +1,1516 @@ +package net.minecraft.server; + +import com.google.common.collect.Sets; +import com.mojang.authlib.GameProfile; +import dev.azurite.spigot.configs.AzuriteConfig; +import dev.azurite.spigot.optimizations.EntityTrackerLinkedList; +import dev.azurite.spigot.utils.CC; +import dev.azurite.spigot.utils.FixHealth; +import dev.azurite.spigot.utils.InterpolationData; +import io.netty.buffer.Unpooled; +import org.bukkit.Bukkit; +import org.bukkit.WeatherType; +import org.bukkit.craftbukkit.CraftWorld; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.craftbukkit.event.CraftEventFactory; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.craftbukkit.util.CraftChatMessage; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityAnimationEvent; +import org.bukkit.event.entity.PlayerDeathEvent; +import org.bukkit.event.inventory.InventoryType; +import org.bukkit.event.player.PlayerTeleportEvent; + +import java.util.*; + +public class EntityPlayer extends EntityHuman implements ICrafting { + + // Beanes - compensated ticks + private static final int MAXIMUM_COMPENSATED_TICKS = 3; // To prevent abuse, only allow compensation for 3 ticks + private static final int PING_COMPENSATION_LENIENCY = 25; + public final MinecraftServer server; + public final PlayerInteractManager playerInteractManager; + public final List chunkCoordIntPairQueue = new ArrayList<>(); + //public final List removeQueue = Lists.newLinkedList(); Vortex - Useless + private final ServerStatisticManager bK; + // Azurite - Fix ghost items + private final Deque useItemQueue = new ArrayDeque<>(); + public String locale = "en_US"; // Spigot + public PlayerConnection playerConnection; + public double d; + public double e; + public int lastSentExp = -99999999; + public int invulnerableTicks = AzuriteConfig.invulnerableTicks.getValue(); + public boolean g; + public int ping; + public boolean viewingCredits; + public String displayName; + public IChatBaseComponent listName; + public org.bukkit.Location compassTarget; + public int newExp = 0; + public int newLevel = 0; + public int newTotalExp = 0; + public boolean keepLevel = false; + public double maxHealthCache; + public boolean joining = true; + // CraftBukkit end + // Spigot start + public boolean collidesWithEntities = true; + public int viewDistance; // PaperSpigot - Player view distance API + public transient long lastActivity = System.currentTimeMillis(); + // CraftBukkit start - Add per-player time and weather. + public long timeOffset = 0; + public boolean relativeTime = true; + public WeatherType weather = null; + public int playerMapX; + public int playerMapZ; + // Azurite - backpack fix + public boolean inventoryOpen; + // Beanes - drop item fix + public int expectingItemUseTicksExpire; + public boolean expectingItemUse; + // Beanes - don't send useless time updates + public long lastSentPlayerTime = Long.MIN_VALUE; + // Beanes - since liquid ticks + public int sinceLiquidTicks = 0; + // Beanes - toggleable magic crits & normal crits for players + public boolean serverCriticalSelf = true; + public boolean serverCriticalEnemy = true; + public boolean serverCriticalOther = true; + public boolean serverMagicCriticalSelf = true; + public boolean serverMagicCriticalEnemy = true; + public boolean serverMagicCriticalOther = true; + // Beanes - interpolation data + public InterpolationData interpolationData; + // CraftBukkit start + private boolean bS = true; + private float bL = Float.MIN_VALUE; + private float lastHealth = -1.0E8F; + private int lastFood = -99999999; + private float lastSaturation = -1.0E8F; + private EntityHuman.EnumChatVisibility bR; + private long bT = System.currentTimeMillis(); + // CraftBukkit end + private Entity bU = null; + private int containerCounter; + private int containerUpdateDelay; // PaperSpigot + // Vortex End + private float pluginRainPosition; + // Spigot end + private float pluginRainPositionPrevious; + private boolean queuedRelease = false; + // Beanes - cps penalty cap + private int swings = 0; + private int attacks = 0; + private int ticks = 0; + private int penaltyTicks = 0; + // Beanes - creation time + public long createdAt = MinecraftServer.currentTick; + // Beanes - ping balance to use compensated potions + private int fiftyPingBalance = 0; + // Beanes - instant reference to tracker queue + public EntityTrackerLinkedList[] trackerQueueRef = null; + // Beanes - toggle for easier arrows + public boolean easierArrows = true; + + public EntityPlayer(MinecraftServer minecraftserver, WorldServer worldserver, GameProfile gameprofile, PlayerInteractManager playerinteractmanager) { + super(worldserver, gameprofile); + viewDistance = world.spigotConfig.viewDistance; // PaperSpigot - Player view distance API + playerinteractmanager.player = this; + playerInteractManager = playerinteractmanager; + + BlockPosition blockposition = worldserver.getSpawn(); + if (!worldserver.worldProvider.o() && worldserver.getWorldData().getGameType() != WorldSettings.EnumGamemode.ADVENTURE) { + int i = Math.max(5, minecraftserver.getSpawnProtection() - 6); + int j = MathHelper.floor(worldserver.getWorldBorder().b(blockposition.getX(), blockposition.getZ())); + if (j < i) + i = j; + if (j <= 1) + i = 1; + blockposition = worldserver.r(blockposition.a(random.nextInt(i * 2) - i, 0, random.nextInt(i * 2) - i)); + } + + server = minecraftserver; + bK = minecraftserver.getPlayerList().a((EntityHuman) this); + S = 0.0F; + + setPositionRotation(blockposition, 0.0F, 0.0F); + while (!worldserver.getCubes(this, getBoundingBox()).isEmpty() && locY < 255.0D) + setPosition(locX, locY + 1.0D, locZ); + + displayName = getName(); + maxHealthCache = getMaxHealth(); + + this.interpolationData = new InterpolationData(this.locX, this.locY, this.locZ); + } + + @Override + public boolean ad() { + return this.collidesWithEntities && super.ad(); // (first !this.isDead near bottom of EntityLiving) + } + + public int getPing() { + return ping; + } + + @Override + public boolean ae() { + return this.collidesWithEntities && super.ae(); // (second !this.isDead near bottom of EntityLiving) + } + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + if (nbttagcompound.hasKeyOfType("playerGameType", 99)) { + if (MinecraftServer.getServer().getForceGamemode()) { + this.playerInteractManager.setGameMode(MinecraftServer.getServer().getGamemode()); + } else { + this.playerInteractManager.setGameMode(WorldSettings.EnumGamemode.getById(nbttagcompound.getInt("playerGameType"))); + } + } + + this.getBukkitEntity().readExtraData(nbttagcompound); // CraftBukkit + } + + public void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + nbttagcompound.setInt("playerGameType", this.playerInteractManager.getGameMode().getId()); + + this.getBukkitEntity().setExtraData(nbttagcompound); // CraftBukkit + } + + // CraftBukkit start - World fallback code, either respawn location or global spawn + public void spawnIn(World world) { + super.spawnIn(world); + if (world == null) { + this.dead = false; + BlockPosition position = null; + if (this.spawnWorld != null && !this.spawnWorld.isEmpty()) { + CraftWorld cworld = (CraftWorld) Bukkit.getServer().getWorld(this.spawnWorld); + if (cworld != null && getBed() != null) { + world = cworld.getHandle(); + position = EntityHuman.getBed(cworld.getHandle(), getBed(), false); + } + } + if (world == null || position == null) { + world = ((CraftWorld) Bukkit.getServer().getWorlds().get(0)).getHandle(); + position = world.getSpawn(); + } + this.world = world; + setPosition(position.getX() + 0.5D, position.getY(), position.getZ() + 0.5D); + } + this.dimension = ((WorldServer) this.world).dimension; + this.playerInteractManager.a((WorldServer) world); + } + + public void levelDown(int i) { + super.levelDown(i); + this.lastSentExp = -1; + } + + public void enchantDone(int i) { + super.enchantDone(i); + this.lastSentExp = -1; + } + + public void syncInventory() { + this.activeContainer.addSlotListener(this); + } + + public void t_() { + // CraftBukkit start + if (this.joining) { + this.joining = false; + } + + // CraftBukkit end + this.playerInteractManager.a(); + --this.invulnerableTicks; + + if (this.noDamageTicks > 0) { + --this.noDamageTicks; + } + + if (this.noDamageTicksArrow > 0) { + --this.noDamageTicksArrow; // Azurite + } + + // PaperSpigot start - Configurable container update tick rate + if (--containerUpdateDelay <= 0) { + this.activeContainer.b(); + containerUpdateDelay = world.paperSpigotConfig.containerUpdateTickRate; + } + // PaperSpigot end + if (!this.activeContainer.a(this)) { + this.closeInventory(); + this.activeContainer = this.defaultContainer; + } + + if (!this.chunkCoordIntPairQueue.isEmpty()) { + int limit = Math.min(this.chunkCoordIntPairQueue.size(), world.spigotConfig.maxBulkChunk); + + if (limit > 0) { + List chunksToSend = new ArrayList<>(limit); + Iterator chunkQueueIterator = this.chunkCoordIntPairQueue.iterator(); + + while (chunkQueueIterator.hasNext() && chunksToSend.size() <= limit) { // Spigot + ChunkCoordIntPair chunkcoordintpair = chunkQueueIterator.next(); + + if (chunkcoordintpair != null) { + if (world.isValidLocation(chunkcoordintpair.x << 4, chunkcoordintpair.z << 4)) { + Chunk chunk = world.getChunkIfLoaded(chunkcoordintpair.x, chunkcoordintpair.z); + + if (chunk != null && chunk.isReady()) { + chunksToSend.add(chunk); + chunkQueueIterator.remove(); + } + } + } else { + chunkQueueIterator.remove(); + } + } + + if (!chunksToSend.isEmpty()) { + if (chunksToSend.size() == 1) { + this.playerConnection.sendPacket(new PacketPlayOutMapChunk(chunksToSend.get(0), true, '\uffff')); + } else { + this.playerConnection.sendPacket(new PacketPlayOutMapChunkBulk(chunksToSend)); + } + + for (Chunk c : chunksToSend) { + for (TileEntity tile : c.tileEntities.values()) { + this.a(tile); + } + } + } + } + } + + Entity entity = this.C(); + + if (entity != this) { + if (!entity.isAlive()) { + this.setSpectatorTarget(this); + } else { + this.setLocation(entity.locX, entity.locY, entity.locZ, entity.yaw, entity.pitch); + this.server.getPlayerList().d(this); + if (this.isSneaking()) { + this.setSpectatorTarget(this); + } + } + } + + // Beanes - lava ticks + if (this.inLava || this.inWater) { + this.sinceLiquidTicks = 0; + } else { + this.sinceLiquidTicks++; + } + + // Beanes - interpolation + this.interpolationData.tick(); + } + + public void l() { + try { + super.t_(); + + for (int i = 0; i < this.inventory.getSize(); ++i) { + ItemStack itemstack = this.inventory.getItem(i); + + if (itemstack != null && itemstack.getItem().f()) { + Packet packet = ((ItemWorldMapBase) itemstack.getItem()).c(itemstack, this.world, this); + + if (packet != null) { + this.playerConnection.sendPacket(packet); + } + } + } + + // Beanes - packet reduce + this.updateHealthAndFood(); + + if (this.getHealth() + this.getAbsorptionHearts() != this.bL) { + this.bL = this.getHealth() + this.getAbsorptionHearts(); + for (ScoreboardObjective scoreboardObjective : getScoreboard().getObjectivesForCriteria(IScoreboardCriteria.g)) { + this.getScoreboard().getPlayerScoreForObjective(this.getName(), scoreboardObjective).updateForList(Arrays.asList(new EntityHuman[]{this})); + } + // CraftBukkit - Update ALL the scores! + this.world.getServer().getScoreboardManager().updateAllScoresForList(IScoreboardCriteria.g, this.getName(), com.google.common.collect.ImmutableList.of(this)); + } + // CraftBukkit start - Force max health updates + if (this.maxHealthCache != this.getMaxHealth()) { + this.getBukkitEntity().updateScaledHealth(); + } + // CraftBukkit end + + if (this.expTotal != this.lastSentExp) { + this.lastSentExp = this.expTotal; + this.playerConnection.sendPacket(new PacketPlayOutExperience(this.exp, this.expTotal, this.expLevel)); + } + + if (AzuriteConfig.trackPlayerStatistics.getValue() && this.ticksLived % 20 * 5 == 0 && !this.getStatisticManager().hasAchievement(AchievementList.L)) { + this.i_(); + } + + // CraftBukkit start - initialize oldLevel and fire PlayerLevelChangeEvent + if (this.oldLevel == -1) { + this.oldLevel = this.expLevel; + } + + if (this.oldLevel != this.expLevel) { + CraftEventFactory.callPlayerLevelChangeEvent(this.world.getServer().getPlayer(this), this.oldLevel, this.expLevel); + this.oldLevel = this.expLevel; + } + // CraftBukkit end + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.a(throwable, "Ticking player"); + CrashReportSystemDetails crashreportsystemdetails = crashreport.a("Player being ticked"); + + this.appendEntityCrashDetails(crashreportsystemdetails); + throw new ReportedException(crashreport); + } + } + + protected void i_() { + BiomeBase biomebase = this.world.getBiome(new BlockPosition(MathHelper.floor(this.locX), 0, MathHelper.floor(this.locZ))); + String s = biomebase.ah; + AchievementSet achievementset = this.getStatisticManager().b((Statistic) AchievementList.L); + + if (achievementset == null) { + achievementset = this.getStatisticManager().a(AchievementList.L, new AchievementSet()); + } + + achievementset.add(s); + if (this.getStatisticManager().b(AchievementList.L) && achievementset.size() >= BiomeBase.n.size()) { + Set hashset = Sets.newHashSet(BiomeBase.n); + + for (String s1 : achievementset) { + hashset.removeIf(biomebase1 -> biomebase1.ah.equals(s1)); + + if (hashset.isEmpty()) { + break; + } + } + + if (hashset.isEmpty()) { + this.b(AchievementList.L); + } + } + } + + public void die(DamageSource damagesource) { + if (this.dead) + return; + + List loot = new ArrayList<>(); + boolean keepInventory = this.world.getGameRules().getBoolean("keepInventory"); + if (!keepInventory) { + int i; + for (i = 0; i < this.inventory.items.length; i++) { + if (this.inventory.items[i] != null) + loot.add(CraftItemStack.asCraftMirror(this.inventory.items[i])); + } + for (i = 0; i < this.inventory.armor.length; i++) { + if (this.inventory.armor[i] != null) + loot.add(CraftItemStack.asCraftMirror(this.inventory.armor[i])); + } + } + + IChatBaseComponent chatmessage = damagesource == DamageSource.GENERIC ? damagesource.getLocalizedDeathMessage(this) : this.bs().b(); // CraftBukkit + String deathmessage = chatmessage.c(); + PlayerDeathEvent event = CraftEventFactory.callPlayerDeathEvent(this, loot, deathmessage, keepInventory); + + closeInventory(); + bs().g(); + this.b(StatisticList.y); + this.a(StatisticList.h); + + String deathMessage = event.getDeathMessage(); + if (deathMessage != null && !deathMessage.isEmpty() && this.world.getGameRules().getBoolean("showDeathMessages")) + if (deathMessage.equals(deathmessage)) { + this.server.getPlayerList().sendMessage(chatmessage); + } else { + this.server.getPlayerList().sendMessage(CraftChatMessage.fromString(deathMessage)); + } + + if (!event.getKeepInventory()) { + int i; + for (i = 0; i < this.inventory.items.length; i++) + this.inventory.setItem(i, null); + for (i = 0; i < this.inventory.armor.length; i++) + this.inventory.player.setEquipment(i, null); + } + + setSpectatorTarget(this); + + for (ScoreboardScore scoreboardScore : this.world.getServer().getScoreboardManager().getScoreboardScores(IScoreboardCriteria.d, getName(), new ArrayList<>())) + scoreboardScore.incrementScore(); + + EntityLiving entityliving = bt(); + if (entityliving != null) { + EntityTypes.MonsterEggInfo entitytypes_monsteregginfo = EntityTypes.eggInfo.get(EntityTypes.a(entityliving)); + if (entitytypes_monsteregginfo != null) { + this.b(entitytypes_monsteregginfo.e); + } + entityliving.b(this, this.aW); + } + + CraftPlayer entity = getBukkitEntity(); + + if (entity.isOnline() && AzuriteConfig.autoRespawnPlayer.getValue()) { + this.playerConnection.forceRespawn(this); + } + } + + public boolean damageEntity(DamageSource damagesource, float f) { + if (isInvulnerable(damagesource)) + return false; + boolean flag = cr() && "fall".equals(damagesource.translationIndex); + if (!flag && invulnerableTicks > 0 && damagesource != DamageSource.OUT_OF_WORLD) + return false; + if (damagesource instanceof EntityDamageSource && !damagesource.isExplosion()) { // Vortex - optimize explosion player damage + Entity entity = damagesource.getEntity(); + if (entity instanceof EntityHuman && !a((EntityHuman) entity)) + return false; + if (entity instanceof EntityArrow) { + EntityArrow entityarrow = (EntityArrow) entity; + if (entityarrow.shooter instanceof EntityHuman && !a((EntityHuman) entityarrow.shooter)) + return false; + } + } + return super.damageEntity(damagesource, f); + } + + public boolean a(EntityHuman entityhuman) { + return this.cr() && super.a(entityhuman); + } + + private boolean cr() { + // CraftBukkit - this.server.getPvP() -> this.world.pvpMode + return this.world.pvpMode; + } + + public void c(int i) { + boolean endPortal = (this.dimension == 1 && i == 1); + if (endPortal) { + this.b(AchievementList.D); + if (!world.paperSpigotConfig.disableEndCredits) { + world.kill(this); + viewingCredits = true; + playerConnection.sendPacket(new PacketPlayOutGameStateChange(4, 0.0F)); + } + } else { + if (this.dimension == 0 && i == 1) { + this.b(AchievementList.C); + } else { + this.b(AchievementList.y); + } + } + if (!endPortal || world.paperSpigotConfig.disableEndCredits) { + PlayerTeleportEvent.TeleportCause cause = (endPortal || this.dimension == 1 || i == 1) ? PlayerTeleportEvent.TeleportCause.END_PORTAL : PlayerTeleportEvent.TeleportCause.NETHER_PORTAL; + server.getPlayerList().changeDimension(this, i, cause); + lastSentExp = -1; + lastHealth = -1.0F; + lastFood = -1; + } + } + + public boolean a(EntityPlayer entityplayer) { + return entityplayer.isSpectator() ? this.C() == this : (!this.isSpectator() && super.a(entityplayer)); + } + + public void a(TileEntity tileentity) { + if (tileentity != null) { + Packet packet = tileentity.getUpdatePacket(); + + if (packet != null) { + this.playerConnection.sendPacket(packet); + } + } + + } + + public void receive(Entity entity, int i) { + super.receive(entity, i); + this.activeContainer.b(); + } + + public EntityHuman.EnumBedResult a(BlockPosition blockposition) { + EntityHuman.EnumBedResult entityhuman_enumbedresult = super.a(blockposition); + + if (entityhuman_enumbedresult == EntityHuman.EnumBedResult.OK) { + PacketPlayOutBed packetplayoutbed = new PacketPlayOutBed(this, blockposition); + + this.u().getTracker().a(this, packetplayoutbed); + this.playerConnection.a(this.locX, this.locY, this.locZ, this.yaw, this.pitch); + this.playerConnection.sendPacket(packetplayoutbed); + } + + return entityhuman_enumbedresult; + } + + public void a(boolean flag, boolean flag1, boolean flag2) { + if (!this.sleeping) return; // CraftBukkit - Can't leave bed if not in one! + if (this.isSleeping()) { + // Wake-up animation + this.u().getTracker().sendPacketToEntity(this, new PacketPlayOutAnimation(this, 2)); + } + + super.a(flag, flag1, flag2); + if (this.playerConnection != null) { + this.playerConnection.a(this.locX, this.locY, this.locZ, this.yaw, this.pitch); + } + + } + + public void mount(Entity entity) { + Entity entity1 = this.vehicle; + + super.mount(entity); + if (this.vehicle != entity1) { // CraftBukkit + this.playerConnection.sendPacket(new PacketPlayOutAttachEntity(0, this, this.vehicle)); + this.playerConnection.a(this.locX, this.locY, this.locZ, this.yaw, this.pitch); + // MineHQ start - Beanes - this only sends attributes when needed (when you mount the entity) + if (this.vehicle instanceof EntityLiving) { + AttributeMapServer attributemapserver = (AttributeMapServer) ((EntityLiving) this.vehicle).getAttributeMap(); + Collection collection = attributemapserver.getUsefulAttributes(this.vehicle instanceof EntityHorse); + if (!collection.isEmpty()) { + if (!AzuriteConfig.horseHealthUpdates.getValue() || !(vehicle instanceof EntityHorse)) { + PacketPlayOutEntityMetadata metadata = new PacketPlayOutEntityMetadata(); + metadata.a = this.vehicle.getId(); + List objects = new ArrayList<>(1); + objects.add(new DataWatcher.WatchableObject(3, 6, ((EntityLiving) vehicle).getHealth())); + + metadata.b = objects; + + this.playerConnection.sendPacket(metadata); + } + + this.playerConnection.sendPacket(new PacketPlayOutUpdateAttributes(this.vehicle.getId(), collection)); + } + } + // MineHQ end + } + + } + + protected void a(double d0, boolean flag, Block block, BlockPosition blockposition) { + } + + public void a(double d0, boolean flag) { + int i = MathHelper.floor(locX), j = MathHelper.floor(locY - 0.20000000298023224D), k = MathHelper.floor(locZ); + + IBlockData iblockdata = world.getType(i, j, k); + + if (iblockdata.getBlock().getMaterial() == Material.AIR) { + IBlockData down = world.getType(i, j - 1, k); + Block block = down.getBlock(); + if (block instanceof BlockFence || block instanceof BlockCobbleWall || block instanceof BlockFenceGate) { + j--; + iblockdata = down; + } + } + + Block block = iblockdata.getBlock(); + + if (AzuriteConfig.footstepParticles.getValue() && fallDistance > 3.0F && flag) { + float f = MathHelper.f(fallDistance - 3.0F); + if (block.getMaterial() != Material.AIR) { + double d1 = Math.min(0.2F + f / 15.0F, 10.0F); + if (d1 > 2.5D) + d1 = 2.5D; + ((WorldServer) world).sendParticles(this, EnumParticle.BLOCK_DUST, false, locX, locY, locZ, (int) (150D * d1), 0, 0, 0, 0.15000000596046448D, Block.getCombinedId(iblockdata)); + } + } + + super.a(d0, flag, block, new BlockPosition(i, j, k)); + } + + public void openSign(TileEntitySign tileentitysign) { + tileentitysign.a(this); + this.playerConnection.sendPacket(new PacketPlayOutOpenSignEditor(tileentitysign.getPosition())); + } + + public int nextContainerCounter() { // CraftBukkit - private void -> public int + this.containerCounter = this.containerCounter % 100 + 1; + return containerCounter; // CraftBukkit + } + + public void openTileEntity(ITileEntityContainer itileentitycontainer) { + // CraftBukkit start - Inventory open hook + Container container = CraftEventFactory.callInventoryOpenEvent(this, itileentitycontainer.createContainer(this.inventory, this)); + if (container == null) { + return; + } + // CraftBukkit end + this.nextContainerCounter(); + this.playerConnection.sendPacket(new PacketPlayOutOpenWindow(this.containerCounter, itileentitycontainer.getContainerName(), itileentitycontainer.getScoreboardDisplayName())); + this.activeContainer = container; // CraftBukkit + this.activeContainer.windowId = this.containerCounter; + this.activeContainer.addSlotListener(this); + } + + public void openContainer(IInventory iinventory) { + // CraftBukkit start - Inventory open hook + // Copied from below + boolean cancelled = false; + if (iinventory instanceof ITileInventory) { + ITileInventory itileinventory = (ITileInventory) iinventory; + cancelled = itileinventory.r_() && !this.a(itileinventory.i()) && !this.isSpectator(); + } + + Container container; + if (iinventory instanceof ITileEntityContainer) { + container = ((ITileEntityContainer) iinventory).createContainer(this.inventory, this); + } else { + container = new ContainerChest(this.inventory, iinventory, this); + } + container = CraftEventFactory.callInventoryOpenEvent(this, container, cancelled); + if (container == null && !cancelled) { // Let pre-cancelled events fall through + iinventory.closeContainer(this); + return; + } + // CraftBukkit end + + + if (this.activeContainer != this.defaultContainer) { + this.closeInventory(); + } + + if (iinventory instanceof ITileInventory) { + ITileInventory itileinventory = (ITileInventory) iinventory; + + if (itileinventory.r_() && !this.a(itileinventory.i()) && !this.isSpectator() && container == null) { // CraftBukkit - allow plugins to uncancel the lock + this.playerConnection.sendPacket(new PacketPlayOutChat(new ChatMessage("container.isLocked", iinventory.getScoreboardDisplayName()), (byte) 2)); + this.playerConnection.sendPacket(new PacketPlayOutNamedSoundEffect("random.door_close", this.locX, this.locY, this.locZ, 1.0F, 1.0F)); + + iinventory.closeContainer(this); // CraftBukkit + return; + } + } + + // Beanes - update slots to latest + // Without this you get + // - Window items + // - Set slot (removed with this patch) + // even though the window items cover everything + if (container != null) { + container.updateSlotsToLatest(); + } + + this.nextContainerCounter(); + // CraftBukkit + if (iinventory instanceof ITileEntityContainer) { + this.playerConnection.sendPacket(new PacketPlayOutOpenWindow(this.containerCounter, ((ITileEntityContainer) iinventory).getContainerName(), iinventory.getScoreboardDisplayName(), iinventory.getSize())); + } else { + this.playerConnection.sendPacket(new PacketPlayOutOpenWindow(this.containerCounter, "minecraft:container", iinventory.getScoreboardDisplayName(), iinventory.getSize())); + } + this.activeContainer = container; // CraftBukkit + + if (activeContainer != null) { + this.activeContainer.windowId = this.containerCounter; + this.activeContainer.addSlotListener(this); + } + } + // CraftBukkit end + + public void openTrade(IMerchant imerchant) { + // CraftBukkit start - Inventory open hook + Container container = CraftEventFactory.callInventoryOpenEvent(this, new ContainerMerchant(this.inventory, imerchant, this.world)); + if (container == null) { + return; + } + // CraftBukkit end + this.nextContainerCounter(); + this.activeContainer = container; // CraftBukkit + this.activeContainer.windowId = this.containerCounter; + this.activeContainer.addSlotListener(this); + InventoryMerchant inventorymerchant = ((ContainerMerchant) this.activeContainer).e(); + IChatBaseComponent ichatbasecomponent = imerchant.getScoreboardDisplayName(); + + this.playerConnection.sendPacket(new PacketPlayOutOpenWindow(this.containerCounter, "minecraft:villager", ichatbasecomponent, inventorymerchant.getSize())); + MerchantRecipeList merchantrecipelist = imerchant.getOffers(this); + + if (merchantrecipelist != null) { + PacketDataSerializer packetdataserializer = new PacketDataSerializer(Unpooled.buffer()); + + packetdataserializer.writeInt(this.containerCounter); + merchantrecipelist.a(packetdataserializer); + this.playerConnection.sendPacket(new PacketPlayOutCustomPayload("MC|TrList", packetdataserializer)); + } + + } + + public void openHorseInventory(EntityHorse entityhorse, IInventory iinventory) { + // CraftBukkit start - Inventory open hook + Container container = CraftEventFactory.callInventoryOpenEvent(this, new ContainerHorse(this.inventory, iinventory, entityhorse, this)); + if (container == null) { + iinventory.closeContainer(this); + return; + } + // CraftBukkit end + if (this.activeContainer != this.defaultContainer) { + this.closeInventory(); + } + + this.nextContainerCounter(); + this.playerConnection.sendPacket(new PacketPlayOutOpenWindow(this.containerCounter, "EntityHorse", iinventory.getScoreboardDisplayName(), iinventory.getSize(), entityhorse.getId())); + this.activeContainer = container; + this.activeContainer.windowId = this.containerCounter; + this.activeContainer.addSlotListener(this); + } + + public void openBook(ItemStack itemstack) { + Item item = itemstack.getItem(); + + if (item == Items.WRITTEN_BOOK) { + this.playerConnection.sendPacket(new PacketPlayOutCustomPayload("MC|BOpen", new PacketDataSerializer(Unpooled.buffer()))); + } + + } + + public void a(Container container, int i, ItemStack itemstack) { + if (!(container.getSlot(i) instanceof SlotResult)) { + if (!this.g) { + this.playerConnection.sendPacket(new PacketPlayOutSetSlot(container.windowId, i, itemstack)); + } + } + } + + public void updateInventory(Container container) { + this.a(container, container.a()); + } + + public void a(Container container, List list) { + playerConnection.sendPacket(new PacketPlayOutWindowItems(container.windowId, list)); + playerConnection.sendPacket(new PacketPlayOutSetSlot(-1, -1, inventory.getCarried())); + + // CraftBukkit start - Send a Set Slot to update the crafting result slot + InventoryType type = container.getBukkitView().getType(); // Vortex - less object creation + if (type == InventoryType.CRAFTING || type == InventoryType.WORKBENCH) { + playerConnection.sendPacket(new PacketPlayOutSetSlot(container.windowId, 0, container.getSlot(0).getItem())); + } + // CraftBukkit end + } + + public boolean canSee(Entity entity) { + if (!AzuriteConfig.hideEntitiesThrownHidden.getValue()) + return true; + + Player bukkit = getBukkitEntity(), target = null; + if (entity instanceof EntityProjectile) { + EntityProjectile projectile = (EntityProjectile) entity; + if (projectile.shooter instanceof EntityPlayer) + target = ((EntityPlayer) projectile.shooter).getBukkitEntity(); + } else if (entity instanceof EntityItem) { + EntityItem item = (EntityItem) entity; + if (item.owner instanceof EntityPlayer) + target = ((EntityPlayer) item.owner).getBukkitEntity(); + } else if (entity instanceof EntityArrow) { + EntityArrow arrow = (EntityArrow) entity; + if (arrow.shooter instanceof EntityPlayer) + target = ((EntityPlayer) arrow.shooter).getBukkitEntity(); + } else if (entity instanceof EntityFishingHook) { + EntityFishingHook hook = (EntityFishingHook) entity; + if (hook.owner instanceof EntityPlayer) + target = ((EntityPlayer) hook.owner).getBukkitEntity(); + } + + if (target == null && entity instanceof EntityPlayer) + target = ((EntityPlayer) entity).getBukkitEntity(); + + return target == null || bukkit.equals(target) || bukkit.canSee(target); + } + + public void setContainerData(Container container, int i, int j) { + this.playerConnection.sendPacket(new PacketPlayOutWindowData(container.windowId, i, j)); + } + + public void setContainerData(Container container, IInventory iinventory) { + for (int i = 0; i < iinventory.g(); ++i) { + this.playerConnection.sendPacket(new PacketPlayOutWindowData(container.windowId, i, iinventory.getProperty(i))); + } + } + + public void closeInventory() { + CraftEventFactory.handleInventoryCloseEvent(this); // CraftBukkit + this.playerConnection.sendPacket(new PacketPlayOutCloseWindow(this.activeContainer.windowId)); + this.inventoryOpen = false; // Beanes - fix backpacking + this.p(); + } + + public void broadcastCarriedItem() { + if (!this.g) + this.playerConnection.sendPacket(new PacketPlayOutSetSlot(-1, -1, this.inventory.getCarried())); + } + + public void p() { + this.activeContainer.b(this); + this.activeContainer = this.defaultContainer; + } + + public void a(float f, float f1, boolean flag, boolean flag1) { + if (this.vehicle != null) { + if (f >= -1.0F && f <= 1.0F) { + this.aZ = f; + } + + if (f1 >= -1.0F && f1 <= 1.0F) { + this.ba = f1; + } + + this.aY = flag; + this.setSneaking(flag1); + } + + } + + public void a(Statistic statistic, int i) { + if (!AzuriteConfig.trackPlayerStatistics.getValue()) { + return; + } + + if (statistic != null) { + this.bK.b(this, statistic, i); + + for (ScoreboardObjective scoreboardObjective : this.getScoreboard().getObjectivesForCriteria(statistic.k())) { + this.getScoreboard().getPlayerScoreForObjective(this.getName(), scoreboardObjective).addScore(i); + } + + if (this.bK.e()) { + this.bK.a(this); + } + } + } + + public void a(Statistic statistic) { + if (!AzuriteConfig.trackPlayerStatistics.getValue()) { + return; + } + + if (statistic != null) { + this.bK.setStatistic(this, statistic, 0); + + for (ScoreboardObjective scoreboardObjective : this.getScoreboard().getObjectivesForCriteria(statistic.k())) { + this.getScoreboard().getPlayerScoreForObjective(this.getName(), scoreboardObjective).setScore(0); + } + + if (this.bK.e()) { + this.bK.a(this); + } + } + } + + public void q() { + if (this.passenger != null) { + this.passenger.mount(this); + } + + if (this.sleeping) { + this.a(true, false, false); + } + + } + + public void triggerHealthUpdate() { + this.lastHealth = -1.0E8F; + this.lastSentExp = -1; // CraftBukkit - Added to reset + } + + // CraftBukkit start - Support multi-line messages + public void sendMessage(IChatBaseComponent[] ichatbasecomponent) { + for (IChatBaseComponent component : ichatbasecomponent) { + this.sendMessage(component); + } + } + + public void b(IChatBaseComponent ichatbasecomponent) { + this.playerConnection.sendPacket(new PacketPlayOutChat(ichatbasecomponent)); + } + + protected void s() { + if (!cancelFinishPacket()) { + this.playerConnection.sendPacket(new PacketPlayOutEntityStatus(this, (byte) 9)); + } + super.s(); + } + + public void a(ItemStack itemstack, int i) { + super.a(itemstack, i); + if (itemstack != null && itemstack.getItem() != null && itemstack.getItem().e(itemstack) == EnumAnimation.EAT) { + this.u().getTracker().a(this, new PacketPlayOutAnimation(this, 3)); // Beanes - don't broadcast eating to self + } + } + + public void copyTo(EntityHuman entityhuman, boolean flag) { + super.copyTo(entityhuman, flag); + this.lastSentExp = -1; + this.lastHealth = -1.0F; + this.lastFood = -1; + //this.removeQueue.addAll(((EntityPlayer)entityhuman).removeQueue); + } + + protected void a(MobEffect mobeffect) { + super.a(mobeffect); + this.playerConnection.sendPacket(new PacketPlayOutEntityEffect(getId(), mobeffect)); + } + + protected void a(MobEffect mobeffect, boolean flag) { + super.a(mobeffect, flag); + this.playerConnection.sendPacket(new PacketPlayOutEntityEffect(getId(), mobeffect)); + } + + protected void b(MobEffect mobeffect) { + super.b(mobeffect); + this.playerConnection.sendPacket(new PacketPlayOutRemoveEntityEffect(getId(), mobeffect)); + } + + public void enderTeleportTo(double d0, double d1, double d2) { + this.playerConnection.a(d0, d1, d2, this.yaw, this.pitch); + } + + public void b(Entity entity) { + this.u().getTracker().sendPacketToEntity(this, new PacketPlayOutAnimation(entity, 4)); + } + + // Beanes - particle settings + public void b(Entity entity, EntityHuman attacker) { + new EntityAnimationEvent(entity.getBukkitEntity(), EntityAnimationEvent.Animation.CRITICAL).callEvent(); + this.u().getTracker().broadcastWithPredicate(this, new PacketPlayOutAnimation(entity, 4), p -> { + if (p == entity) { + return p.serverCriticalSelf; + } else if (p == attacker) { + return p.serverCriticalEnemy; + } else { + return p.serverCriticalOther; + } + }); + } + + public void c(Entity entity) { + this.u().getTracker().sendPacketToEntity(this, new PacketPlayOutAnimation(entity, 5)); + } + + // Beanes - particle settings + public void c(Entity entity, EntityHuman attacker) { + new EntityAnimationEvent(entity.getBukkitEntity(), EntityAnimationEvent.Animation.SHARPNESS).callEvent(); + this.u().getTracker().broadcastWithPredicate(this, new PacketPlayOutAnimation(entity, 5), p -> { + if (p == entity) { + return p.serverMagicCriticalSelf; + } else if (p == attacker) { + return p.serverMagicCriticalEnemy; + } else { + return p.serverMagicCriticalOther; + } + }); + } + + public void updateAbilities() { + if (this.playerConnection != null) { + this.playerConnection.sendPacket(new PacketPlayOutAbilities(this.abilities)); + this.B(); + } + } + + public WorldServer u() { + return (WorldServer) this.world; + } + + public void a(WorldSettings.EnumGamemode worldsettings_enumgamemode) { + getBukkitEntity().setGameMode(org.bukkit.GameMode.getByValue(worldsettings_enumgamemode.getId())); + + } + + public boolean isSpectator() { + return this.playerInteractManager.getGameMode().equals(WorldSettings.EnumGamemode.SPECTATOR); + } + + public void sendMessage(IChatBaseComponent ichatbasecomponent) { + this.playerConnection.sendPacket(new PacketPlayOutChat(ichatbasecomponent)); + } + + public boolean a(int i, String s) { + if ("@".equals(s)) { + return getBukkitEntity().hasPermission("minecraft.command.selector"); + } + return true; + } + + public String w() { + String s = this.playerConnection.networkManager.getSocketAddress().toString(); + + s = s.substring(s.indexOf("/") + 1); + s = s.substring(0, s.indexOf(":")); + return s; + } + + public void a(PacketPlayInSettings packetplayinsettings) { + // PaperSpigot start - Add PlayerLocaleChangeEvent + String oldLocale = this.locale; + this.locale = packetplayinsettings.a(); + if (!this.locale.equals(oldLocale)) { + CraftEventFactory.callPlayerLocaleChangeEvent(this, oldLocale, this.locale); + } + // PaperSpigot end + this.bR = packetplayinsettings.c(); + this.bS = packetplayinsettings.d(); + this.getDataWatcher().watch(10, (byte) packetplayinsettings.e()); + } + + public EntityHuman.EnumChatVisibility getChatFlags() { + return this.bR; + } + + public void setResourcePack(String s, String s1) { + this.playerConnection.sendPacket(new PacketPlayOutResourcePackSend(s, s1)); + } + + public void resetIdleTimer() { + if (AzuriteConfig.playerIdleTimer.getValue()) + this.bT = MinecraftServer.az(); + } + + public ServerStatisticManager getStatisticManager() { + return this.bK; + } + + public void d(Entity entity) { + playerConnection.writePacketLazily(new PacketPlayOutEntityDestroy(entity.getId())); // Azurite - Write lazily to keep order of packets + } + + protected void B() { + if (this.isSpectator()) { + this.bj(); + this.setInvisible(true); + } else { + super.B(); + } + } + + public Entity C() { + return (this.bU == null ? this : this.bU); + } + // CraftBukkit end + + public void setSpectatorTarget(Entity entity) { + Entity entity1 = this.C(); + + this.bU = (entity == null ? this : entity); + if (entity1 != this.bU) { + this.playerConnection.sendPacket(new PacketPlayOutCamera(this.bU)); + this.enderTeleportTo(this.bU.locX, this.bU.locY, this.bU.locZ); + } + + } + + public void attack(Entity entity) { + if (this.penaltyTicks > 0) { // Beanes - cancel any attack while the player is cps cap penalized + return; + } + + if (this.playerInteractManager.getGameMode() == WorldSettings.EnumGamemode.SPECTATOR) { + this.setSpectatorTarget(entity); + } else { + super.attack(entity); + } + } + + public long D() { + return this.bT; + } + + public IChatBaseComponent getPlayerListName() { + return listName; // CraftBukkit + } + + public long getPlayerTime() { + if (this.relativeTime) { + // Adds timeOffset to the current server time. + return this.world.getDayTime() + this.timeOffset; + } else { + // Adds timeOffset to the beginning of this day. + return this.world.getDayTime() - (this.world.getDayTime() % 24000) + this.timeOffset; + } + } + + public WeatherType getPlayerWeather() { + return this.weather; + } + + public void setPlayerWeather(WeatherType type, boolean plugin) { + if (!plugin && this.weather != null) { + return; + } + + if (plugin) { + this.weather = type; + } + + if (type == WeatherType.DOWNFALL) { + this.playerConnection.sendPacket(new PacketPlayOutGameStateChange(2, 0)); + } else { + this.playerConnection.sendPacket(new PacketPlayOutGameStateChange(1, 0)); + } + } + + public void updateWeather(float oldRain, float newRain, float oldThunder, float newThunder) { + if (this.weather == null) { + // Vanilla + if (oldRain != newRain) { + this.playerConnection.sendPacket(new PacketPlayOutGameStateChange(7, newRain)); + } + } else { + // Plugin + if (pluginRainPositionPrevious != pluginRainPosition) { + this.playerConnection.sendPacket(new PacketPlayOutGameStateChange(7, pluginRainPosition)); + } + } + + if (oldThunder != newThunder) { + if (weather == WeatherType.DOWNFALL || weather == null) { + this.playerConnection.sendPacket(new PacketPlayOutGameStateChange(8, newThunder)); + } else { + this.playerConnection.sendPacket(new PacketPlayOutGameStateChange(8, 0)); + } + } + } + + public void tickWeather() { + if (this.weather == null) return; + + pluginRainPositionPrevious = pluginRainPosition; + if (weather == WeatherType.DOWNFALL) { + pluginRainPosition += 0.01F; + } else { + pluginRainPosition -= 0.01F; + } + + pluginRainPosition = MathHelper.a(pluginRainPosition, 0.0F, 1.0F); + } + + public void resetPlayerWeather() { + this.weather = null; + this.setPlayerWeather(this.world.getWorldData().hasStorm() ? WeatherType.DOWNFALL : WeatherType.CLEAR, false); + } + + @Override + public String toString() { + return super.toString() + "(" + this.getName() + " at " + this.locX + "," + this.locY + "," + this.locZ + ")"; + } + + public void reset() { + float exp = 0; + boolean keepInventory = this.world.getGameRules().getBoolean("keepInventory"); + + if (this.keepLevel || keepInventory) { + exp = this.exp; + this.newTotalExp = this.expTotal; + this.newLevel = this.expLevel; + } + + this.setHealth(this.getMaxHealth()); + this.fireTicks = 0; + this.fallDistance = 0; + this.foodData = new FoodMetaData(this); + this.expLevel = this.newLevel; + this.expTotal = this.newTotalExp; + this.exp = 0; + this.deathTicks = 0; + this.removeAllEffects(); + this.updateEffects = true; + this.activeContainer = this.defaultContainer; + this.killer = null; + this.lastDamager = null; + this.combatTracker = new CombatTracker(this); + this.lastSentExp = -1; + if (this.keepLevel || keepInventory) { + this.exp = exp; + } else { + this.giveExp(this.newExp); + } + this.keepLevel = false; + } + + @Override + public CraftPlayer getBukkitEntity() { + return (CraftPlayer) super.getBukkitEntity(); + } + + // Azurite - a more optimal move entity with heading, the idea is that forward & strafe are always 0, so why waste our time using moveFlying? + @Override + public void g(float f, float f1) { + // Copied from EntityHuman + double d0 = this.locX; + double d1 = this.locY; + double d2 = this.locZ; + + if (this.abilities.isFlying && this.vehicle == null) { + double d3 = this.motY; + float f2 = this.aM; + + this.aM = this.abilities.a() * (float) (this.isSprinting() ? 2 : 1); + this.moveEntityWithNoHeading(); // Replaced to faster method + this.motY = d3 * 0.6D; + this.aM = f2; + } else { + this.moveEntityWithNoHeading(); // Replaced to faster method + } + + this.checkMovement(this.locX - d0, this.locY - d1, this.locZ - d2); + } + + public void moveEntityWithNoHeading() { // Theres no forward / strafe on mc servers, its both zero! + if (this.bM()) { + if (this.V() && !this.abilities.isFlying) { + double d0 = this.locY; + float waterFriction = 0.8F; + float depthStriderMultiplier = (float) EnchantmentManager.b(this); + if (depthStriderMultiplier > 3.0F) { + depthStriderMultiplier = 3.0F; + } + + if (!this.onGround) { + depthStriderMultiplier *= 0.5F; + } + + if (depthStriderMultiplier > 0.0F) { + waterFriction += (0.54600006F - waterFriction) * depthStriderMultiplier / 3.0F; + } + + this.move(this.motX, this.motY, this.motZ); + this.motX *= waterFriction; + this.motY *= 0.800000011920929D; + this.motZ *= waterFriction; + this.motY -= 0.02D; + if (this.positionChanged && this.c(this.motX, this.motY + 0.6000000238418579D - this.locY + d0, this.motZ)) { + this.motY = 0.30000001192092896D; + } + } else if (this.ab() && !this.abilities.isFlying) { + double d0 = this.locY; + this.move(this.motX, this.motY, this.motZ); + this.motX *= 0.5D; + this.motY *= 0.5D; + this.motZ *= 0.5D; + this.motY -= 0.02D; + if (this.positionChanged && this.c(this.motX, this.motY + 0.6000000238418579D - this.locY + d0, this.motZ)) { + this.motY = 0.30000001192092896D; + } + } else { + float blockFriction = 0.91F; + if (this.onGround) { + blockFriction = this.world.getType(MathHelper.floor(this.locX), MathHelper.floor(this.boundingBox.b) - 1, MathHelper.floor(this.locZ)).getBlock().frictionFactor * 0.91F; + } + + if (this.k_()) { // onLadder check + this.motX = MathHelper.a(this.motX, -0.15F, 0.15F); + this.motZ = MathHelper.a(this.motZ, -0.15F, 0.15F); + this.fallDistance = 0.0F; + if (this.motY < -0.15D) { + this.motY = -0.15D; + } + if (isSneaking() && this.motY < 0.0D) { + this.motY = 0.0D; + } + } + + move(this.motX, this.motY, this.motZ); + if (this.positionChanged && this.k_()) { + this.motY = 0.2D; + } + + this.motY -= 0.08D; + + this.motY *= 0.9800000190734863D; + this.motX *= blockFriction; + this.motZ *= blockFriction; + } + } + } + + // Azurite - item queue + public void addToUseItemQueue(ItemStack itemStack) { + this.useItemQueue.add(itemStack); + } + + public void queueItemRelease() { + this.queuedRelease = true; + } + + public void processItemQueue(PacketPlayInFlying packet) { + // Save the player coordinates + float savedYaw = this.yaw; + float savedPitch = this.pitch; + + if (packet.hasLook) { + this.yaw = packet.yaw; + this.pitch = packet.pitch; + } + + // Process the items at the set place + ItemStack networkItem; + + while ((networkItem = useItemQueue.poll()) != null) { + // Just copied nms code + ItemStack inHand = inventory.getItemInHand(); // Beanes - Shouldnt have changed (I think) + + if (inHand != null) + this.playerInteractManager.useItem(this, this.world, inHand); + + inHand = this.inventory.getItemInHand(); + if (inHand != null && inHand.count == 0) { + this.inventory.items[this.inventory.itemInHandIndex] = null; + inHand = null; + } + + if (inHand == null || inHand.l() == 0) { + this.g = true; + this.inventory.items[this.inventory.itemInHandIndex] = ItemStack.b(this.inventory.items[this.inventory.itemInHandIndex]); + Slot slot = this.activeContainer.getSlot(this.inventory, this.inventory.itemInHandIndex); + + this.activeContainer.b(); + this.g = false; + // CraftBukkit - TODO CHECK IF NEEDED -- new if structure might not need + // 'always'. Kept it in for now, but may be able to remove in future + + if (!ItemStack.matches(this.inventory.getItemInHand(), networkItem)) + sendPacket(new PacketPlayOutSetSlot(this.activeContainer.windowId, slot.rawSlotIndex, this.inventory.getItemInHand())); + } + } + + // Process a possible queued item release; + if (this.queuedRelease) { + this.queuedRelease = false; + this.bU(); + } + + // Restore the player position + this.yaw = savedYaw; + this.pitch = savedPitch; + } + + // Beanes - Fix backpacking + public void checkBackpacking() { + if (this.inventoryOpen) { + this.closeInventory(); + } + } + + public void registerSwing() { + swings++; + } + + public void registerAttack() { + attacks++; + } + + public void registerTickForCpsPenalty() { + ticks++; + + if (penaltyTicks > 0) { + penaltyTicks--; + } + + if (ticks >= 20) { + if (AzuriteConfig.cpsCapEnabled.getValue()) { + int cap = getKnockbackProfile().getCpsCapOverride() != -1 ? getKnockbackProfile().getCpsCapOverride() : AzuriteConfig.cpsCap.getValue(); + + // Give 1 cps leniency for swings as those can be inaccurate + boolean penalize = this.swings > (cap + 1) || this.attacks > cap; + + if (penalize) { + this.penaltyTicks = AzuriteConfig.cpsCapPenaltyTicks.getValue(); + + if (AzuriteConfig.cpsCapSendMessage.getValue()) { + getBukkitEntity().sendMessage(CC.t(AzuriteConfig.cpsCapMessage.getValue() + .replace("%cps%", String.valueOf(cap)) + )); + } + } + } + + this.ticks = 0; + this.swings = 0; + this.attacks = 0; + } + } + + public int getEatCompensationTicks() { + double latencyInTicks = (this.ping + PING_COMPENSATION_LENIENCY) / 50.0D; + int ticks = (int) Math.floor(latencyInTicks); + + return Math.min(ticks, MAXIMUM_COMPENSATED_TICKS); + } + + public int getPotionCompensationTicks() { + if (fiftyPingBalance >= 0) { + return 1; + } + + return 0; + } + + // Beanes - constant knockback + public void constantKnockbackTick(boolean onGround) { + if (onGround || this.inLava || this.inWater) { + this.airTicks = 0; + } else { + this.airTicks++; + } + } + + + + // Beanes - ping + public void calculatePingBalance() { + this.fiftyPingBalance += (this.ping > 50 ? 1 : -1); + } + + // Beanes - reduce packets + public void updateHealthAndFood() { + float health = FixHealth.roundHealth(this.getBukkitEntity().getScaledHealth()); + int food = this.foodData.getFoodLevel(); + float saturation = Math.round(this.foodData.getSaturationLevel()); + + if (this.lastHealth != health || this.lastFood != food || saturation != this.lastSaturation) { + // Round health & saturation -> reduces packets visually + this.playerConnection.sendPacket(new PacketPlayOutUpdateHealth(health, food, saturation)); + + this.lastHealth = health; + this.lastFood = food; + this.lastSaturation = saturation; + } + } + + // Beanes - better attribute updates + public ItemStack lastUsedHeldItemAttributes = null; + public void checkHandAttributes() { + ItemStack currentItemStack = this.inventory.getItemInHand(); + + if (!ItemStack.matches(lastUsedHeldItemAttributes, currentItemStack)) { // Spigot + if (lastUsedHeldItemAttributes != null) { + this.getAttributeMap().a(lastUsedHeldItemAttributes.B()); + } + + if (currentItemStack != null) { + this.getAttributeMap().b(currentItemStack.B()); + } + + lastUsedHeldItemAttributes = currentItemStack != null ? currentItemStack.cloneItemStack() : null; // Clone for safety never know if someone is modifying stuff :P + } + } + + // Beanes - patch drop eat run bug + public void checkDropEatRunBug() { + if (expectingItemUse) { + if (isEating()) { + // Player did not restart the eating -> release the item + if (--expectingItemUseTicksExpire == 0) { + this.bU(); + expectingItemUse = false; + } + } else { + expectingItemUse = false; + } + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityPositionTypes.java b/azurite-server/src/main/java/net/minecraft/server/EntityPositionTypes.java new file mode 100644 index 0000000..9dbc596 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityPositionTypes.java @@ -0,0 +1,48 @@ +package net.minecraft.server; + +import com.google.common.collect.Maps; +import java.util.HashMap; + +public class EntityPositionTypes { + + private static final HashMap a = Maps.newHashMap(); + + public static EntityInsentient.EnumEntityPositionType a(Class oclass) { + return (EntityInsentient.EnumEntityPositionType) EntityPositionTypes.a.get(oclass); + } + + static { + EntityPositionTypes.a.put(EntityBat.class, EntityInsentient.EnumEntityPositionType.ON_GROUND); + EntityPositionTypes.a.put(EntityChicken.class, EntityInsentient.EnumEntityPositionType.ON_GROUND); + EntityPositionTypes.a.put(EntityCow.class, EntityInsentient.EnumEntityPositionType.ON_GROUND); + EntityPositionTypes.a.put(EntityHorse.class, EntityInsentient.EnumEntityPositionType.ON_GROUND); + EntityPositionTypes.a.put(EntityMushroomCow.class, EntityInsentient.EnumEntityPositionType.ON_GROUND); + EntityPositionTypes.a.put(EntityOcelot.class, EntityInsentient.EnumEntityPositionType.ON_GROUND); + EntityPositionTypes.a.put(EntityPig.class, EntityInsentient.EnumEntityPositionType.ON_GROUND); + EntityPositionTypes.a.put(EntityRabbit.class, EntityInsentient.EnumEntityPositionType.ON_GROUND); + EntityPositionTypes.a.put(EntitySheep.class, EntityInsentient.EnumEntityPositionType.ON_GROUND); + EntityPositionTypes.a.put(EntitySnowman.class, EntityInsentient.EnumEntityPositionType.ON_GROUND); + EntityPositionTypes.a.put(EntitySquid.class, EntityInsentient.EnumEntityPositionType.IN_WATER); + EntityPositionTypes.a.put(EntityIronGolem.class, EntityInsentient.EnumEntityPositionType.ON_GROUND); + EntityPositionTypes.a.put(EntityWolf.class, EntityInsentient.EnumEntityPositionType.ON_GROUND); + EntityPositionTypes.a.put(EntityVillager.class, EntityInsentient.EnumEntityPositionType.ON_GROUND); + EntityPositionTypes.a.put(EntityEnderDragon.class, EntityInsentient.EnumEntityPositionType.ON_GROUND); + EntityPositionTypes.a.put(EntityWither.class, EntityInsentient.EnumEntityPositionType.ON_GROUND); + EntityPositionTypes.a.put(EntityBlaze.class, EntityInsentient.EnumEntityPositionType.ON_GROUND); + EntityPositionTypes.a.put(EntityCaveSpider.class, EntityInsentient.EnumEntityPositionType.ON_GROUND); + EntityPositionTypes.a.put(EntityCreeper.class, EntityInsentient.EnumEntityPositionType.ON_GROUND); + EntityPositionTypes.a.put(EntityEnderman.class, EntityInsentient.EnumEntityPositionType.ON_GROUND); + EntityPositionTypes.a.put(EntityEndermite.class, EntityInsentient.EnumEntityPositionType.ON_GROUND); + EntityPositionTypes.a.put(EntityGhast.class, EntityInsentient.EnumEntityPositionType.ON_GROUND); + EntityPositionTypes.a.put(EntityGiantZombie.class, EntityInsentient.EnumEntityPositionType.ON_GROUND); + EntityPositionTypes.a.put(EntityGuardian.class, EntityInsentient.EnumEntityPositionType.IN_WATER); + EntityPositionTypes.a.put(EntityMagmaCube.class, EntityInsentient.EnumEntityPositionType.ON_GROUND); + EntityPositionTypes.a.put(EntityPigZombie.class, EntityInsentient.EnumEntityPositionType.ON_GROUND); + EntityPositionTypes.a.put(EntitySilverfish.class, EntityInsentient.EnumEntityPositionType.ON_GROUND); + EntityPositionTypes.a.put(EntitySkeleton.class, EntityInsentient.EnumEntityPositionType.ON_GROUND); + EntityPositionTypes.a.put(EntitySlime.class, EntityInsentient.EnumEntityPositionType.ON_GROUND); + EntityPositionTypes.a.put(EntitySpider.class, EntityInsentient.EnumEntityPositionType.ON_GROUND); + EntityPositionTypes.a.put(EntityWitch.class, EntityInsentient.EnumEntityPositionType.ON_GROUND); + EntityPositionTypes.a.put(EntityZombie.class, EntityInsentient.EnumEntityPositionType.ON_GROUND); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityPotion.java b/azurite-server/src/main/java/net/minecraft/server/EntityPotion.java new file mode 100644 index 0000000..a138585 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityPotion.java @@ -0,0 +1,207 @@ +package net.minecraft.server; + +// CraftBukkit start + +import dev.azurite.spigot.configs.AzuriteConfig; +import dev.azurite.spigot.knockback.Knockback; +import org.bukkit.craftbukkit.entity.CraftLivingEntity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.event.entity.PotionEffectAddEvent; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.UUID; + +public class EntityPotion extends EntityProjectile { + public static boolean IS_HEALTH_POTION_HACK = false; // Azurite - had to do a hack here because of motion code, and cant really replace a lot of nms to keep compatibility.. + + public ItemStack item; + public UUID hitEntity = null; + + public EntityPotion(World world) { + super(world); + } + + public EntityPotion(World world, EntityLiving entityliving, int i) { + this(world, entityliving, new ItemStack(Items.POTION, 1, i)); + } + + public EntityPotion(World world, EntityLiving entityliving, ItemStack itemstack) { + super(world, entityliving); + this.item = itemstack; + } + + public EntityPotion(World world, double d0, double d1, double d2, ItemStack itemstack) { + super(world, d0, d1, d2); + this.item = itemstack; + } + + public boolean isHealPotion() { + return IS_HEALTH_POTION_HACK || (item != null && (item.getData() == 16421 || item.getData() == 16453)); + } + + protected float m() { + if (AzuriteConfig.overrideOnlyHealthPotion.getValue() && !isHealPotion()) { + return 0.05F; + } + Knockback knockback = getProfile(); + return knockback.potionFall.getValue(); + } + + protected float j() { + if (AzuriteConfig.overrideOnlyHealthPotion.getValue() && !isHealPotion()) { + return 0.5F; + } + Knockback knockback = getProfile(); + return knockback.potionSpeed.getValue(); + } + + protected float l() { + if (AzuriteConfig.overrideOnlyHealthPotion.getValue() && !isHealPotion()) { + return -20.0F; + } + Knockback knockback = getProfile(); + return knockback.potionVerticalOffset.getValue(); + } + + @Override + public float getRandomness() { + return AzuriteConfig.potionTrajectoryRandomness.getValue(); + } + + public int getPotionValue() { + if (this.item == null) { + this.item = new ItemStack(Items.POTION, 1, 0); + } + + return this.item.getData(); + } + + public void setPotionValue(int i) { + if (this.item == null) { + this.item = new ItemStack(Items.POTION, 1, 0); + } + + this.item.setData(i); + } + + protected void a(MovingObjectPosition movingobjectposition) { + hitEntity = movingobjectposition.entity != null ? movingobjectposition.entity.getUniqueID() : null; + + List list = Items.POTION.h(this.item); + AxisAlignedBB axisalignedbb = this.getBoundingBox().grow(4.0D, 2.0D, 4.0D); + List list1 = this.world.a(EntityLiving.class, axisalignedbb); + Iterator iterator = list1.iterator(); + + // CraftBukkit + HashMap affected = new HashMap<>(); + + while (iterator.hasNext()) { + EntityLiving entityliving = iterator.next(); + double d0 = this.h(entityliving); + + if (d0 < 16.0D) { + if (entityliving instanceof EntityPlayer && !((EntityPlayer) entityliving).canSee(this)) + continue; + + double d1 = 1.0D - Math.sqrt(d0) / 4.0D; + + if (entityliving == movingobjectposition.entity) { + d1 = 1.0D; + } + + // CraftBukkit start + affected.put((LivingEntity) entityliving.getBukkitEntity(), d1); + } + } + + org.bukkit.event.entity.PotionSplashEvent event = org.bukkit.craftbukkit.event.CraftEventFactory.callPotionSplashEvent(this, affected); + + EntityLiving shooter = getShooter(); + + if (!event.isCancelled() && list != null && !list.isEmpty()) { // do not process effects if there are no effects + // to process + for (LivingEntity victim : event.getAffectedEntities()) { + if (!(victim instanceof CraftLivingEntity)) { + continue; + } + + EntityLiving entityliving = ((CraftLivingEntity) victim).getHandle(); + + double d1 = event.getIntensity(victim); + // CraftBukkit end + + for (MobEffect mobeffect : list) { + int i = mobeffect.getEffectId(); + + // CraftBukkit start - Abide by PVP settings - for players only! + if (!this.world.pvpMode && shooter instanceof EntityPlayer && entityliving instanceof EntityPlayer + && entityliving != shooter) { + // Block SLOWER_MOVEMENT, SLOWER_DIG, HARM, BLINDNESS, HUNGER, WEAKNESS and + // POISON potions + if (i == 2 || i == 4 || i == 7 || i == 15 || i == 17 || i == 18 || i == 19) + continue; + } + // CraftBukkit end + + if (MobEffectList.byId[i].isInstant()) { + MobEffectList.byId[i].applyInstantEffect(this, this.getShooter(), entityliving, + mobeffect.getAmplifier(), d1); + } else { + int j = (int) (d1 * mobeffect.getDuration() + 0.5D); + + if (j > 20) { + entityliving.addEffect(new MobEffect(i, j, mobeffect.getAmplifier()), PotionEffectAddEvent.EffectCause.POTION_SPLASH); + } + } + } + } + } + + /* + Smooth Potting - Beanes + Basically often you have full intensity pots that hit your body, but it hits you when the potion is near the ground + This code offsets the potion upwards if the potion was full intensity on your player while near the ground + */ + BlockPosition blockPosition; + if (getProfile().potionBetterVisual.getValue() && movingobjectposition.entity != null) { + int entityY = MathHelper.floor(movingobjectposition.entity.locY); + int potionY = MathHelper.floor(this.locY); + int offset = potionY - entityY; + if (offset >= 2 || offset < 0) { + blockPosition = new BlockPosition((int) Math.round(this.locX), (int) Math.round(this.locY), (int) Math.round(this.locZ)); + } else { + blockPosition = new BlockPosition((int) Math.round(this.locX), entityY + 2, (int) Math.round(this.locZ)); + } + } else { + blockPosition = new BlockPosition((int) Math.round(this.locX), (int) Math.round(this.locY), (int) Math.round(this.locZ)); + } + + this.world.triggerEffect(2002, blockPosition, this.getPotionValue()); + + this.die(); + } + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + if (nbttagcompound.hasKeyOfType("Potion", 10)) { + this.item = ItemStack.createStack(nbttagcompound.getCompound("Potion")); + } else { + this.setPotionValue(nbttagcompound.getInt("potionValue")); + } + + if (this.item == null) { + this.die(); + } + + } + + public void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + if (this.item != null) { + nbttagcompound.set("Potion", this.item.save(new NBTTagCompound())); + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityProjectile.java b/azurite-server/src/main/java/net/minecraft/server/EntityProjectile.java new file mode 100644 index 0000000..3eacd12 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityProjectile.java @@ -0,0 +1,357 @@ +package net.minecraft.server; + +import com.eatthepath.uuid.FastUUID; +import dev.azurite.spigot.Azurite; +import dev.azurite.spigot.configs.AzuriteConfig; +import dev.azurite.spigot.configs.PearlConfig; +import dev.azurite.spigot.knockback.Knockback; + +import java.util.List; + +public abstract class EntityProjectile extends Entity implements IProjectile { + + public EntityLiving shooter; + public String shooterName; + protected boolean inGround; + private int blockX = -1; + private int blockY = -1; + private int blockZ = -1; + private Block inBlockId; + private int i; + private int ar; + + public EntityProjectile(World world) { + super(world); + this.setSize(0.25F, 0.25F); + } + + public EntityProjectile(World world, EntityLiving entityliving) { + super(world); + this.shooter = entityliving; + this.projectileSource = (org.bukkit.entity.LivingEntity) entityliving.getBukkitEntity(); // CraftBukkit + this.setSize(0.25F, 0.25F); + + this.setPositionRotation(entityliving.locX, entityliving.locY + entityliving.getHeadHeight(), entityliving.locZ, + entityliving.yaw, entityliving.pitch); + + // Beanes - remove projectile offset + if (!AzuriteConfig.patchProjectileOffset.getValue()) { + this.locX -= (MathHelper.cos(this.yaw / 180.0F * 3.1415927F) * 0.16F); + this.locZ -= (MathHelper.sin(this.yaw / 180.0F * 3.1415927F) * 0.16F); + } + + this.locY -= 0.10000000149011612D; + + if (this instanceof EntityPotion) { + if (((EntityPotion) this).isHealPotion()) { + Knockback knockback = getProfile(); + this.locY += knockback.potionYOffset.getValue(); + } + } + + this.setPosition(this.locX, this.locY, this.locZ); + this.motX = (-MathHelper.sin(this.yaw / 180.0F * 3.1415927F) * MathHelper.cos(this.pitch / 180.0F * 3.1415927F) + * 0.4F); + this.motZ = (MathHelper.cos(this.yaw / 180.0F * 3.1415927F) * MathHelper.cos(this.pitch / 180.0F * 3.1415927F) + * 0.4F); + this.motY = (-MathHelper.sin((this.pitch + this.l()) / 180.0F * 3.1415927F) * 0.4F); + this.shoot(this.motX, this.motY, this.motZ, this.j(), getRandomness()); + } + + public EntityProjectile(World world, double d0, double d1, double d2) { + super(world); + this.i = 0; + this.setSize(0.25F, 0.25F); + this.setPosition(d0, d1, d2); + } + + protected void h() { + } + + protected Knockback getProfile() { + Knockback knockback = (Knockback) Azurite.getInstance().getKnockbackManager().getActiveProfile(); + + if (shooter instanceof EntityHuman) { + EntityHuman entityHuman = (EntityHuman) shooter; + if (entityHuman.getKnockbackProfile() != null) knockback = entityHuman.getKnockbackProfile(); + } + + return knockback; + } + + public float getRandomness() { + return 1.0F; + } + + protected float j() { + return 1.5F; + } + + protected float l() { + return 0.0F; + } + + public void shoot(double d0, double d1, double d2, float f, float f1) { + float f2 = MathHelper.sqrt(d0 * d0 + d1 * d1 + d2 * d2); + d0 /= f2; + d1 /= f2; + d2 /= f2; + d0 += random.nextGaussian() * 0.007499999832361937D * f1; + d1 += random.nextGaussian() * 0.007499999832361937D * f1; + d2 += random.nextGaussian() * 0.007499999832361937D * f1; + d0 *= f; + d1 *= f; + d2 *= f; + this.motX = d0; + this.motY = d1; + this.motZ = d2; + this.lastYaw = this.yaw = (float) (MathHelper.b(d0, d2) * 180.0D / 3.1415927410125732D); + this.lastPitch = this.pitch = (float) (MathHelper.b(d1, MathHelper.sqrt(d0 * d0 + d2 * d2)) * 180.0D / 3.1415927410125732D); + this.i = 0; + + // Beanes - sync server & client values + this.reEncodeByServerValues(); + } + + public void t_() { + this.P = this.locX; + this.Q = this.locY; + this.R = this.locZ; + super.t_(); + + if (this.inGround) { + if (this.world.getType(this.blockX, this.blockY, this.blockZ).getBlock() == this.inBlockId) { + ++this.i; + if (this.i == 1200) { + this.die(); + } + + return; + } + + this.inGround = false; + this.motX *= random.nextFloat() * 0.2F; + this.motY *= random.nextFloat() * 0.2F; + this.motZ *= random.nextFloat() * 0.2F; + this.i = 0; + this.ar = 0; + } else { + ++this.ar; + } + Vec3D startingPoint = new Vec3D(this.locX, this.locY, this.locZ); + Vec3D endingPoint = new Vec3D(this.locX + this.motX, this.locY + this.motY, this.locZ + this.motZ); + MovingObjectPosition movingobjectposition = (this instanceof EntityEnderPearl ? + this.world.rayTracePearls(startingPoint, endingPoint) : + this.world.rayTrace(startingPoint, endingPoint)); + + // Did we hit any block? + if (movingobjectposition != null) { + // Yes we hit a block, set end to there + endingPoint = new Vec3D(movingobjectposition.pos.a, movingobjectposition.pos.b, movingobjectposition.pos.c); + } + + // Fetch entities + Entity entity = null; + + // Beanes - grow way bigger as we don't track interpolation positions + double growFactor = AzuriteConfig.projectileInterpolationRegistration.getValue() && !(this instanceof EntityPotion) && !(this instanceof EntityEnderPearl) ? 5.0D : 1.075D; + + List list = this.world.getEntities(this, this.boundingBox.a(this.motX, this.motY, this.motZ).grow(growFactor, growFactor, growFactor)); + double bestDistance = this instanceof EntityPotion ? Double.MAX_VALUE : startingPoint.distanceSquared(endingPoint); // Beanes - set best distance from start to block + EntityLiving shooter = this.getShooter(); + + int possibleSelfTicks = AzuriteConfig.minimumPotionTicksForSelfSplash.getValue(); + + if (shooter instanceof EntityPlayer + && this instanceof EntityPotion + && AzuriteConfig.compensatedPotions.getValue() + && ((EntityPlayer) shooter).sinceLiquidTicks > 10 // Beanes check no liquid (otherwise can pot downwards) + ) { + possibleSelfTicks -= ((EntityPlayer) shooter).getPotionCompensationTicks(); + } + + for (Entity possibleEntity : list) { + if (possibleEntity.ad() && (possibleEntity != shooter || ar >= possibleSelfTicks)) { + boolean interpolationProjectiles = AzuriteConfig.projectileInterpolationRegistration.getValue() && possibleEntity instanceof EntityPlayer && !(this instanceof EntityPotion); + boolean onlyInterpolationProjectiles = interpolationProjectiles && AzuriteConfig.projectileInterpolationRegistrationOnly.getValue(); + double projectileBox = 0.3D; + + AxisAlignedBB entityBox = possibleEntity.boundingBox.grow(projectileBox, projectileBox, projectileBox); + MovingObjectPosition intercept = entityBox.a(startingPoint, endingPoint); + + if (entityBox.a(startingPoint) && AzuriteConfig.checkStartOfRay.getValue() && !onlyInterpolationProjectiles) { // Beanes - make projectiles more accurate + entity = possibleEntity; + break; + } + + // Azurite/Vortex - fast pots.. + if (this instanceof EntityPotion + && ((EntityPotion) this).isHealPotion() + && getProfile().potionFast.getValue() + && intercept == null + && possibleEntity == shooter + && ticksLived % 2 == 0 + && !possibleEntity.inWater + && !possibleEntity.ab() + && !possibleEntity.isSneaking() + // Azurite - Fix vortex bug with potions when flying. + && (possibleEntity instanceof EntityHuman && !((EntityHuman) possibleEntity).abilities.isFlying)) { + intercept = new MovingObjectPosition(possibleEntity); + } + + if (intercept != null && !onlyInterpolationProjectiles) { + double d1 = startingPoint.distanceSquared(intercept.pos); + if (d1 < bestDistance) { + entity = possibleEntity; + bestDistance = d1; + } + } + + // Beanes - improved projectile registration + if (interpolationProjectiles) { + EntityPlayer player = (EntityPlayer) possibleEntity; + + double dist = player.interpolationData.attemptCollision(startingPoint, endingPoint, projectileBox); + + if (dist == Double.MIN_VALUE) { + entity = possibleEntity; + break; + } else if (dist < bestDistance) { + entity = possibleEntity; + bestDistance = dist; + } + } + } + } + + if (entity != null) { + boolean visible = true; + if (entity instanceof EntityPlayer && this.shooter instanceof EntityPlayer) { + if (!((EntityPlayer) this.shooter).getBukkitEntity().canSee(((EntityPlayer) entity).getBukkitEntity())) { + visible = false; + } + } + // Azurite - Don't return entity for tp detection if getOutByOneByOne is enabled + if (this instanceof EntityEnderPearl && PearlConfig.entityTpGetOutOneByOne.getValue() && shooter != null && + shooter.getBukkitEntity().getLocation().distance(entity.getBukkitEntity().getLocation()) <= 0.5) { + visible = false; + } + if (visible) + movingobjectposition = new MovingObjectPosition(entity); + } + + if (movingobjectposition != null) { + if (movingobjectposition.type == MovingObjectPosition.EnumMovingObjectType.BLOCK && this.world.getType(movingobjectposition.a()).getBlock() == Blocks.PORTAL) { + this.d(movingobjectposition.a()); + } else { + this.a(movingobjectposition); + // CraftBukkit start + if (this.dead) { + org.bukkit.craftbukkit.event.CraftEventFactory.callProjectileHitEvent(this); + } + // CraftBukkit end + } + } + + this.locX += motX; + this.locY += motY; + this.locZ += motZ; + float f1 = MathHelper.sqrt(this.motX * this.motX + this.motZ * this.motZ); + + this.yaw = (float) (MathHelper.b(this.motX, this.motZ) * 180.0D / 3.1415927410125732D); + + for (this.pitch = (float) (MathHelper.b(this.motY, f1) * 180.0D / 3.1415927410125732D); this.pitch + - this.lastPitch < -180.0F; this.lastPitch -= 360.0F) { + } + + while (this.pitch - this.lastPitch >= 180.0F) { + this.lastPitch += 360.0F; + } + + while (this.yaw - this.lastYaw < -180.0F) { + this.lastYaw -= 360.0F; + } + + while (this.yaw - this.lastYaw >= 180.0F) { + this.lastYaw += 360.0F; + } + + this.pitch = this.lastPitch + (this.pitch - this.lastPitch) * 0.2F; + this.yaw = this.lastYaw + (this.yaw - this.lastYaw) * 0.2F; + float f2 = 0.99F; + float f3 = this.m(); + + if (this.V()) { + for (int j = 0; j < 4; ++j) { + this.world.addParticle(EnumParticle.WATER_BUBBLE, this.locX - this.motX * 0.25F, + this.locY - this.motY * 0.25F, this.locZ - this.motZ * 0.25F, this.motX, this.motY, this.motZ, EnumParticle.EMPTY_ARRAY); + } + f2 = 0.8F; + } + this.motX *= f2; + this.motY *= f2; + this.motZ *= f2; + this.motY -= f3; + this.setPosition(this.locX, this.locY, this.locZ); + } + + protected float m() { + return 0.03F; + } + + protected abstract void a(MovingObjectPosition movingobjectposition); + + public void b(NBTTagCompound nbttagcompound) { + nbttagcompound.setShort("xTile", (short) this.blockX); + nbttagcompound.setShort("yTile", (short) this.blockY); + nbttagcompound.setShort("zTile", (short) this.blockZ); + MinecraftKey minecraftkey = Block.REGISTRY.c(this.inBlockId); + + nbttagcompound.setString("inTile", minecraftkey == null ? "" : minecraftkey.toString()); + nbttagcompound.setByte("inGround", (byte) (this.inGround ? 1 : 0)); + if ((this.shooterName == null || this.shooterName.isEmpty()) && this.shooter instanceof EntityHuman) { + this.shooterName = this.shooter.getName(); + } + + nbttagcompound.setString("ownerName", this.shooterName == null ? "" : this.shooterName); + } + + public void a(NBTTagCompound nbttagcompound) { + this.blockX = nbttagcompound.getShort("xTile"); + this.blockY = nbttagcompound.getShort("yTile"); + this.blockZ = nbttagcompound.getShort("zTile"); + if (nbttagcompound.hasKeyOfType("inTile", 8)) { + this.inBlockId = Block.getByName(nbttagcompound.getString("inTile")); + } else { + this.inBlockId = Block.getById(nbttagcompound.getByte("inTile") & 255); + } + + this.inGround = nbttagcompound.getByte("inGround") == 1; + this.shooter = null; + this.shooterName = nbttagcompound.getString("ownerName"); + if (this.shooterName != null && this.shooterName.isEmpty()) { + this.shooterName = null; + } + + this.shooter = this.getShooter(); + } + + public EntityLiving getShooter() { + if (this.shooter == null && this.shooterName != null && !this.shooterName.isEmpty()) { + this.shooter = this.world.a(this.shooterName); + if (this.shooter == null && this.world instanceof WorldServer) { + try { + Entity entity = ((WorldServer) this.world).getEntity(FastUUID.parseUUID(this.shooterName)); + + if (entity instanceof EntityLiving) { + this.shooter = (EntityLiving) entity; + } + } catch (Throwable throwable) { + this.shooter = null; + } + } + } + + return this.shooter; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityRabbit.java b/azurite-server/src/main/java/net/minecraft/server/EntityRabbit.java new file mode 100644 index 0000000..bc1f26e --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityRabbit.java @@ -0,0 +1,528 @@ +package net.minecraft.server; + +public class EntityRabbit extends EntityAnimal { + + private PathfinderGoalRabbitAvoidTarget bm; + private int bo = 0; + private int bp = 0; + private boolean bq = false; + private boolean br = false; + private int bs = 0; + private EnumRabbitState bt; + private int bu; + + public EntityRabbit(World world) { + super(world); + this.bt = EnumRabbitState.HOP; + this.bu = 0; + this.setSize(0.6F, 0.7F); + this.g = new ControllerJumpRabbit(this); + this.moveController = new ControllerMoveRabbit(this); + ((Navigation) this.getNavigation()).a(true); + this.initializePathFinderGoals(); // CraftBukkit - moved code + this.b(0.0D); + } + + // CraftBukkit start - code from constructor + public void initializePathFinderGoals(){ + this.navigation.a(2.5F); + this.goalSelector.a(1, new PathfinderGoalFloat(this)); + this.goalSelector.a(1, new PathfinderGoalRabbitPanic(this, 1.33D)); + this.goalSelector.a(2, new PathfinderGoalTempt(this, 1.0D, Items.CARROT, false)); + this.goalSelector.a(2, new PathfinderGoalTempt(this, 1.0D, Items.GOLDEN_CARROT, false)); + this.goalSelector.a(2, new PathfinderGoalTempt(this, 1.0D, Item.getItemOf(Blocks.YELLOW_FLOWER), false)); + this.goalSelector.a(3, new PathfinderGoalBreed(this, 0.8D)); + this.goalSelector.a(5, new PathfinderGoalEatCarrots(this)); + this.goalSelector.a(5, new PathfinderGoalRandomStroll(this, 0.6D)); + this.goalSelector.a(11, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 10.0F)); + this.bm = new PathfinderGoalRabbitAvoidTarget(this, EntityWolf.class, 16.0F, 1.33D, 1.33D); + this.goalSelector.a(4, this.bm); + } + // CraftBukkit end + + protected float bE() { + return this.moveController.a() && this.moveController.e() > this.locY + 0.5D ? 0.5F : this.bt.b(); + } + + public void a(EnumRabbitState entityrabbit_enumrabbitstate) { + this.bt = entityrabbit_enumrabbitstate; + } + + public void b(double d0) { + this.getNavigation().a(d0); + this.moveController.a(this.moveController.d(), this.moveController.e(), this.moveController.f(), d0); + } + + public void a(boolean flag, EnumRabbitState entityrabbit_enumrabbitstate) { + super.i(flag); + if (!flag) { + if (this.bt == EnumRabbitState.ATTACK) { + this.bt = EnumRabbitState.HOP; + } + } else { + this.b(1.5D * (double) entityrabbit_enumrabbitstate.a()); + this.makeSound(this.cm(), this.bB(), ((random.nextFloat() - random.nextFloat()) * 0.2F + 1.0F) * 0.8F); + } + + this.bq = flag; + } + + public void b(EnumRabbitState entityrabbit_enumrabbitstate) { + this.a(true, entityrabbit_enumrabbitstate); + this.bp = entityrabbit_enumrabbitstate.d(); + this.bo = 0; + } + + public boolean cl() { + return this.bq; + } + + protected void h() { + super.h(); + this.datawatcher.a(18, (byte) 0); + } + + public void E() { + if (this.moveController.b() > 0.8D) { + this.a(EnumRabbitState.SPRINT); + } else if (this.bt != EnumRabbitState.ATTACK) { + this.a(EnumRabbitState.HOP); + } + + if (this.bs > 0) { + --this.bs; + } + + if (this.bu > 0) { + this.bu -= random.nextInt(3); + if (this.bu < 0) { + this.bu = 0; + } + } + + if (this.onGround) { + if (!this.br) { + this.a(false, EnumRabbitState.NONE); + this.cw(); + } + + if (this.getRabbitType() == 99 && this.bs == 0) { + EntityLiving entityliving = this.getGoalTarget(); + + if (entityliving != null && this.h(entityliving) < 16.0D) { + this.a(entityliving.locX, entityliving.locZ); + this.moveController.a(entityliving.locX, entityliving.locY, entityliving.locZ, this.moveController.b()); + this.b(EnumRabbitState.ATTACK); + this.br = true; + } + } + + ControllerJumpRabbit entityrabbit_controllerjumprabbit = (ControllerJumpRabbit) this.g; + + if (!entityrabbit_controllerjumprabbit.c()) { + if (this.moveController.a() && this.bs == 0) { + PathEntity pathentity = this.navigation.j(); + Vec3D vec3d = new Vec3D(this.moveController.d(), this.moveController.e(), this.moveController.f()); + + if (pathentity != null && pathentity.e() < pathentity.d()) { + vec3d = pathentity.a(this); + } + + this.a(vec3d.a, vec3d.c); + this.b(this.bt); + } + } else if (!entityrabbit_controllerjumprabbit.d()) { + this.ct(); + } + } + + this.br = this.onGround; + } + + public void Y() {} + + private void a(double d0, double d1) { + this.yaw = (float) (MathHelper.b(d1 - this.locZ, d0 - this.locX) * 180.0D / 3.1415927410125732D) - 90.0F; + } + + private void ct() { + ((ControllerJumpRabbit) this.g).a(true); + } + + private void cu() { + ((ControllerJumpRabbit) this.g).a(false); + } + + private void cv() { + this.bs = this.co(); + } + + private void cw() { + this.cv(); + this.cu(); + } + + public void m() { + super.m(); + if (this.bo != this.bp) { + if (this.bo == 0) { + this.world.broadcastEntityEffect(this, (byte) 1); + } + + ++this.bo; + } else if (this.bp != 0) { + this.bo = 0; + this.bp = 0; + } + + } + + protected void initAttributes() { + super.initAttributes(); + this.getAttributeInstance(GenericAttributes.maxHealth).setValue(10.0D); + this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.30000001192092896D); + } + + public void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + nbttagcompound.setInt("RabbitType", this.getRabbitType()); + nbttagcompound.setInt("MoreCarrotTicks", this.bu); + } + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + this.setRabbitType(nbttagcompound.getInt("RabbitType")); + this.bu = nbttagcompound.getInt("MoreCarrotTicks"); + } + + protected String cm() { + return "mob.rabbit.hop"; + } + + protected String z() { + return "mob.rabbit.idle"; + } + + protected String bo() { + return "mob.rabbit.hurt"; + } + + protected String bp() { + return "mob.rabbit.death"; + } + + public boolean r(Entity entity) { + if (this.getRabbitType() == 99) { + this.makeSound("mob.attack", 1.0F, (random.nextFloat() - random.nextFloat()) * 0.2F + 1.0F); + return entity.damageEntity(DamageSource.mobAttack(this), 8.0F); + } else { + return entity.damageEntity(DamageSource.mobAttack(this), 3.0F); + } + } + + public int br() { + return this.getRabbitType() == 99 ? 8 : super.br(); + } + + public boolean damageEntity(DamageSource damagesource, float f) { + return !this.isInvulnerable(damagesource) && super.damageEntity(damagesource, f); + } + + protected void getRareDrop() { + this.a(new ItemStack(Items.RABBIT_FOOT, 1), 0.0F); + } + + protected void dropDeathLoot(boolean flag, int i) { + int j = random.nextInt(2) + random.nextInt(1 + i); + + int k; + + for (k = 0; k < j; ++k) { + this.a(Items.RABBIT_HIDE, 1); + } + + j = random.nextInt(2); + + for (k = 0; k < j; ++k) { + if (this.isBurning()) { + this.a(Items.COOKED_RABBIT, 1); + } else { + this.a(Items.RABBIT, 1); + } + } + + } + + private boolean a(Item item) { + return item == Items.CARROT || item == Items.GOLDEN_CARROT || item == Item.getItemOf(Blocks.YELLOW_FLOWER); + } + + public EntityRabbit b(EntityAgeable entityageable) { + EntityRabbit entityrabbit = new EntityRabbit(this.world); + + if (entityageable instanceof EntityRabbit) { + entityrabbit.setRabbitType(random.nextBoolean() ? this.getRabbitType() : ((EntityRabbit) entityageable).getRabbitType()); + } + + return entityrabbit; + } + + public boolean d(ItemStack itemstack) { + return itemstack != null && this.a(itemstack.getItem()); + } + + public int getRabbitType() { + return this.datawatcher.getByte(18); + } + + public void setRabbitType(int i) { + if (i == 99) { + this.goalSelector.a(this.bm); + this.goalSelector.a(4, new PathfinderGoalKillerRabbitMeleeAttack(this)); + this.targetSelector.a(1, new PathfinderGoalHurtByTarget(this, false)); + this.targetSelector.a(2, new PathfinderGoalNearestAttackableTarget<>(this, EntityHuman.class, true)); + this.targetSelector.a(2, new PathfinderGoalNearestAttackableTarget<>(this, EntityWolf.class, true)); + if (!this.hasCustomName()) { + this.setCustomName(LocaleI18n.get("entity.KillerBunny.name")); + } + } + + this.datawatcher.watch(18, (byte) i); + } + + public GroupDataEntity prepare(DifficultyDamageScaler difficultydamagescaler, GroupDataEntity groupdataentity) { + GroupDataEntity object = super.prepare(difficultydamagescaler, groupdataentity); + int i = random.nextInt(6); + boolean flag = false; + + if (object instanceof GroupDataRabbit) { + i = ((GroupDataRabbit) object).a; + flag = true; + } else { + object = new GroupDataRabbit(i); + } + + this.setRabbitType(i); + if (flag) { + this.setAgeRaw(-24000); + } + + return object; + } + + private boolean cx() { + return this.bu == 0; + } + + protected int co() { + return this.bt.c(); + } + + protected void cp() { + this.world.addParticle(EnumParticle.BLOCK_DUST, this.locX + (random.nextFloat() * this.width * 2.0F) - this.width, this.locY + 0.5D + (random.nextFloat() * this.length), this.locZ + (random.nextFloat() * this.width * 2.0F) - this.width, 0.0D, 0.0D, 0.0D, Block.getCombinedId(Blocks.CARROTS.fromLegacyData(7))); + this.bu = 100; + } + + public EntityAgeable createChild(EntityAgeable entityageable) { + return this.b(entityageable); + } + + enum EnumRabbitState { + + NONE(0.0F, 0.0F, 30, 1), HOP(0.8F, 0.2F, 20, 10), STEP(1.0F, 0.45F, 14, 14), SPRINT(1.75F, 0.4F, 1, 8), ATTACK(2.0F, 0.7F, 7, 8); + + private final float f; + private final float g; + private final int h; + private final int i; + + EnumRabbitState(float f, float f1, int i, int j) { + this.f = f; + this.g = f1; + this.h = i; + this.i = j; + } + + public float a() { + return this.f; + } + + public float b() { + return this.g; + } + + public int c() { + return this.h; + } + + public int d() { + return this.i; + } + } + + static class PathfinderGoalKillerRabbitMeleeAttack extends PathfinderGoalMeleeAttack { + + public PathfinderGoalKillerRabbitMeleeAttack(EntityRabbit entityrabbit) { + super(entityrabbit, EntityLiving.class, 1.4D, true); + } + + protected double a(EntityLiving entityliving) { + return 4.0F + entityliving.width; + } + } + + static class PathfinderGoalRabbitPanic extends PathfinderGoalPanic { + + private final EntityRabbit b; + + public PathfinderGoalRabbitPanic(EntityRabbit entityrabbit, double d0) { + super(entityrabbit, d0); + this.b = entityrabbit; + } + + public void e() { + super.e(); + this.b.b(this.a); + } + } + + static class PathfinderGoalEatCarrots extends PathfinderGoalGotoTarget { + + private final EntityRabbit c; + private boolean d; + private boolean e = false; + + public PathfinderGoalEatCarrots(EntityRabbit entityrabbit) { + super(entityrabbit, 0.699999988079071D, 16); + this.c = entityrabbit; + } + + public boolean a() { + if (this.a <= 0) { + if (!this.c.world.getGameRules().getBoolean("mobGriefing")) { + return false; + } + + this.e = false; + this.d = this.c.cx(); + } + + return super.a(); + } + + public boolean b() { + return this.e && super.b(); + } + + public void c() { + super.c(); + } + + public void d() { + super.d(); + } + + public void e() { + super.e(); + this.c.getControllerLook().a((double) this.b.getX() + 0.5D, (this.b.getY() + 1), (double) this.b.getZ() + 0.5D, 10.0F, (float) this.c.bQ()); + if (this.f()) { + World world = this.c.world; + BlockPosition blockposition = this.b.up(); + IBlockData iblockdata = world.getType(blockposition); + + if (this.e && iblockdata.getBlock() instanceof BlockCarrots && iblockdata.get(BlockCarrots.AGE) == 7) { + world.setTypeAndData(blockposition, Blocks.AIR.getBlockData(), 2); + world.setAir(blockposition, true); + this.c.cp(); + } + + this.e = false; + this.a = 10; + } + + } + + protected boolean a(World world, BlockPosition blockposition) { + Block block = world.getType(blockposition).getBlock(); + + if (block == Blocks.FARMLAND) { + blockposition = blockposition.up(); + IBlockData iblockdata = world.getType(blockposition); + + block = iblockdata.getBlock(); + if (block instanceof BlockCarrots && iblockdata.get(BlockCarrots.AGE) == 7 && this.d && !this.e) { + this.e = true; + return true; + } + } + + return false; + } + } + + static class PathfinderGoalRabbitAvoidTarget extends PathfinderGoalAvoidTarget { + + public PathfinderGoalRabbitAvoidTarget(EntityRabbit entityrabbit, Class oclass, float f, double d0, double d1) { + super(entityrabbit, oclass, f, d0, d1); + } + + } + + static class ControllerMoveRabbit extends ControllerMove { + + private final EntityRabbit g; + + public ControllerMoveRabbit(EntityRabbit entityrabbit) { + super(entityrabbit); + this.g = entityrabbit; + } + + public void c() { + if (this.g.onGround && !this.g.cl()) { + this.g.b(0.0D); + } + + super.c(); + } + } + + public static class ControllerJumpRabbit extends ControllerJump { + + private final EntityRabbit c; + private boolean d = false; + + public ControllerJumpRabbit(EntityRabbit entityrabbit) { + super(entityrabbit); + this.c = entityrabbit; + } + + public boolean c() { + return this.a; + } + + public boolean d() { + return this.d; + } + + public void a(boolean flag) { + this.d = flag; + } + + public void b() { + if (this.a) { + this.c.b(EnumRabbitState.STEP); + this.a = false; + } + + } + } + + public static class GroupDataRabbit implements GroupDataEntity { + + public int a; + + public GroupDataRabbit(int i) { + this.a = i; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntitySenses.java b/azurite-server/src/main/java/net/minecraft/server/EntitySenses.java new file mode 100644 index 0000000..825a884 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntitySenses.java @@ -0,0 +1,38 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; + +import java.util.List; + +public class EntitySenses { + + EntityInsentient a; + List b = Lists.newArrayList(); + List c = Lists.newArrayList(); + + public EntitySenses(EntityInsentient entityinsentient) { + this.a = entityinsentient; + } + + public void a() { + this.b.clear(); + this.c.clear(); + } + + public boolean a(Entity entity) { + if (this.b.contains(entity)) { + return true; + } else if (this.c.contains(entity)) { + return false; + } else { + boolean flag = this.a.hasLineOfSight(entity); + if (flag) { + this.b.add(entity); + } else { + this.c.add(entity); + } + + return flag; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntitySheep.java b/azurite-server/src/main/java/net/minecraft/server/EntitySheep.java new file mode 100644 index 0000000..53b383c --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntitySheep.java @@ -0,0 +1,248 @@ +package net.minecraft.server; + +import com.google.common.collect.Maps; +import org.bukkit.event.entity.SheepRegrowWoolEvent; +import org.bukkit.event.player.PlayerShearEntityEvent; +import org.bukkit.inventory.InventoryView; + +import java.util.Map; +import java.util.Random; + +public class EntitySheep extends EntityAnimal { + + private final InventoryCrafting bm = new InventoryCrafting(new Container() { + public boolean a(EntityHuman entityhuman) { + return false; + } + + // CraftBukkit start + @Override + public InventoryView getBukkitView() { + return null; // TODO: O.O + } + // CraftBukkit end + }, 2, 1); + private static final Map bo = Maps.newEnumMap(EnumColor.class); + + public static float[] a(EnumColor enumcolor) { + return EntitySheep.bo.get(enumcolor); + } + + public EntitySheep(World world) { + super(world); + this.setSize(0.9F, 1.3F); + ((Navigation) this.getNavigation()).a(true); + this.goalSelector.a(0, new PathfinderGoalFloat(this)); + this.goalSelector.a(1, new PathfinderGoalPanic(this, 1.25D)); + this.goalSelector.a(2, new PathfinderGoalBreed(this, 1.0D)); + this.goalSelector.a(3, new PathfinderGoalTempt(this, 1.1D, Items.WHEAT, false)); + this.goalSelector.a(4, new PathfinderGoalFollowParent(this, 1.1D)); + this.goalSelector.a(5, new PathfinderGoalEatTile(this)); + this.goalSelector.a(6, new PathfinderGoalRandomStroll(this, 1.0D)); + this.goalSelector.a(7, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 6.0F)); + this.goalSelector.a(8, new PathfinderGoalRandomLookaround(this)); + this.bm.setItem(0, new ItemStack(Items.DYE, 1, 0)); + this.bm.setItem(1, new ItemStack(Items.DYE, 1, 0)); + this.bm.resultInventory = new InventoryCraftResult(); // CraftBukkit - add result slot for event + } + + protected void E() { + super.E(); + } + + protected void initAttributes() { + super.initAttributes(); + this.getAttributeInstance(GenericAttributes.maxHealth).setValue(8.0D); + this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.23000000417232513D); + } + + protected void h() { + super.h(); + this.datawatcher.a(16, (byte) 0); + } + + protected void dropDeathLoot(boolean flag, int i) { + if (!this.isSheared()) { + this.a(new ItemStack(Item.getItemOf(Blocks.WOOL), 1, this.getColor().getColorIndex()), 0.0F); + } + + int j = random.nextInt(2) + 1 + random.nextInt(1 + i); + + for (int k = 0; k < j; ++k) { + if (this.isBurning()) { + this.a(Items.COOKED_MUTTON, 1); + } else { + this.a(Items.MUTTON, 1); + } + } + + } + + protected Item getLoot() { + return Item.getItemOf(Blocks.WOOL); + } + + public boolean a(EntityHuman entityhuman) { + ItemStack itemstack = entityhuman.inventory.getItemInHand(); + + if (itemstack != null && itemstack.getItem() == Items.SHEARS && !this.isSheared() && !this.isBaby()) { + + // CraftBukkit start + PlayerShearEntityEvent event = new PlayerShearEntityEvent((org.bukkit.entity.Player) entityhuman.getBukkitEntity(), this.getBukkitEntity()); + this.world.getServer().getPluginManager().callEvent(event); + + if (event.isCancelled()) { + return false; + } + // CraftBukkit end + + this.setSheared(true); + int i = 1 + random.nextInt(3); + + for (int j = 0; j < i; ++j) { + EntityItem entityitem = this.a(new ItemStack(Item.getItemOf(Blocks.WOOL), 1, this.getColor().getColorIndex()), 1.0F); + + entityitem.motY += (random.nextFloat() * 0.05F); + entityitem.motX += ((random.nextFloat() - random.nextFloat()) * 0.1F); + entityitem.motZ += ((random.nextFloat() - random.nextFloat()) * 0.1F); + } + + itemstack.damage(1, entityhuman); + this.makeSound("mob.sheep.shear", 1.0F, 1.0F); + } + + return super.a(entityhuman); + } + + public void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + nbttagcompound.setBoolean("Sheared", this.isSheared()); + nbttagcompound.setByte("Color", (byte) this.getColor().getColorIndex()); + } + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + this.setSheared(nbttagcompound.getBoolean("Sheared")); + this.setColor(EnumColor.fromColorIndex(nbttagcompound.getByte("Color"))); + } + + protected String z() { + return "mob.sheep.say"; + } + + protected String bo() { + return "mob.sheep.say"; + } + + protected String bp() { + return "mob.sheep.say"; + } + + protected void a(BlockPosition blockposition, Block block) { + this.makeSound("mob.sheep.step", 0.15F, 1.0F); + } + + public EnumColor getColor() { + return EnumColor.fromColorIndex(this.datawatcher.getByte(16) & 15); + } + + public void setColor(EnumColor enumcolor) { + byte b0 = this.datawatcher.getByte(16); + + this.datawatcher.watch(16, (byte) (b0 & 240 | enumcolor.getColorIndex() & 15)); + } + + public boolean isSheared() { + return (this.datawatcher.getByte(16) & 16) != 0; + } + + public void setSheared(boolean flag) { + byte b0 = this.datawatcher.getByte(16); + + if (flag) { + this.datawatcher.watch(16, (byte) (b0 | 16)); + } else { + this.datawatcher.watch(16, (byte) (b0 & -17)); + } + + } + + public static EnumColor a(Random random) { + int i = random.nextInt(100); + + return i < 5 ? EnumColor.BLACK : (i < 10 ? EnumColor.GRAY : (i < 15 ? EnumColor.SILVER : (i < 18 ? EnumColor.BROWN : (random.nextInt(500) == 0 ? EnumColor.PINK : EnumColor.WHITE)))); + } + + public EntitySheep b(EntityAgeable entityageable) { + EntitySheep entitysheep1 = new EntitySheep(this.world); + + entitysheep1.setColor(this.a(this, (EntitySheep) entityageable)); + return entitysheep1; + } + + public void v() { + // CraftBukkit start + SheepRegrowWoolEvent event = new SheepRegrowWoolEvent((org.bukkit.entity.Sheep) this.getBukkitEntity()); + this.world.getServer().getPluginManager().callEvent(event); + + if (!event.isCancelled()) { + this.setSheared(false); + } + // CraftBukkit end + if (this.isBaby()) { + this.setAge(60); + } + + } + + public GroupDataEntity prepare(DifficultyDamageScaler difficultydamagescaler, GroupDataEntity groupdataentity) { + groupdataentity = super.prepare(difficultydamagescaler, groupdataentity); + this.setColor(a(this.world.random)); + return groupdataentity; + } + + private EnumColor a(EntityAnimal entityanimal, EntityAnimal entityanimal1) { + int i = ((EntitySheep) entityanimal).getColor().getInvColorIndex(); + int j = ((EntitySheep) entityanimal1).getColor().getInvColorIndex(); + + this.bm.getItem(0).setData(i); + this.bm.getItem(1).setData(j); + ItemStack itemstack = CraftingManager.getInstance().craft(this.bm, entityanimal.world); + int k; + + if (itemstack != null && itemstack.getItem() == Items.DYE) { + k = itemstack.getData(); + } else { + k = this.world.random.nextBoolean() ? i : j; + } + + return EnumColor.fromInvColorIndex(k); + } + + public float getHeadHeight() { + return 0.95F * this.length; + } + + public EntityAgeable createChild(EntityAgeable entityageable) { + return this.b(entityageable); + } + + static { + EntitySheep.bo.put(EnumColor.WHITE, new float[] { 1.0F, 1.0F, 1.0F}); + EntitySheep.bo.put(EnumColor.ORANGE, new float[] { 0.85F, 0.5F, 0.2F}); + EntitySheep.bo.put(EnumColor.MAGENTA, new float[] { 0.7F, 0.3F, 0.85F}); + EntitySheep.bo.put(EnumColor.LIGHT_BLUE, new float[] { 0.4F, 0.6F, 0.85F}); + EntitySheep.bo.put(EnumColor.YELLOW, new float[] { 0.9F, 0.9F, 0.2F}); + EntitySheep.bo.put(EnumColor.LIME, new float[] { 0.5F, 0.8F, 0.1F}); + EntitySheep.bo.put(EnumColor.PINK, new float[] { 0.95F, 0.5F, 0.65F}); + EntitySheep.bo.put(EnumColor.GRAY, new float[] { 0.3F, 0.3F, 0.3F}); + EntitySheep.bo.put(EnumColor.SILVER, new float[] { 0.6F, 0.6F, 0.6F}); + EntitySheep.bo.put(EnumColor.CYAN, new float[] { 0.3F, 0.5F, 0.6F}); + EntitySheep.bo.put(EnumColor.PURPLE, new float[] { 0.5F, 0.25F, 0.7F}); + EntitySheep.bo.put(EnumColor.BLUE, new float[] { 0.2F, 0.3F, 0.7F}); + EntitySheep.bo.put(EnumColor.BROWN, new float[] { 0.4F, 0.3F, 0.2F}); + EntitySheep.bo.put(EnumColor.GREEN, new float[] { 0.4F, 0.5F, 0.2F}); + EntitySheep.bo.put(EnumColor.RED, new float[] { 0.6F, 0.2F, 0.2F}); + EntitySheep.bo.put(EnumColor.BLACK, new float[] { 0.1F, 0.1F, 0.1F}); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntitySilverfish.java b/azurite-server/src/main/java/net/minecraft/server/EntitySilverfish.java new file mode 100644 index 0000000..b69a4a8 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntitySilverfish.java @@ -0,0 +1,216 @@ +package net.minecraft.server; + +import java.util.Random; + +public class EntitySilverfish extends EntityMonster { + + private final PathfinderGoalSilverfishWakeOthers a; + + public EntitySilverfish(World world) { + super(world); + this.setSize(0.4F, 0.3F); + this.goalSelector.a(1, new PathfinderGoalFloat(this)); + this.goalSelector.a(3, this.a = new PathfinderGoalSilverfishWakeOthers(this)); + this.goalSelector.a(4, new PathfinderGoalMeleeAttack(this, EntityHuman.class, 1.0D, false)); + this.goalSelector.a(5, new PathfinderGoalSilverfishHideInBlock(this)); + this.targetSelector.a(1, new PathfinderGoalHurtByTarget(this, true)); + this.targetSelector.a(2, new PathfinderGoalNearestAttackableTarget(this, EntityHuman.class, true)); + } + + public double am() { + return 0.2D; + } + + public float getHeadHeight() { + return 0.1F; + } + + protected void initAttributes() { + super.initAttributes(); + this.getAttributeInstance(GenericAttributes.maxHealth).setValue(8.0D); + this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.25D); + this.getAttributeInstance(GenericAttributes.ATTACK_DAMAGE).setValue(1.0D); + } + + protected boolean s_() { + return false; + } + + protected String z() { + return "mob.silverfish.say"; + } + + protected String bo() { + return "mob.silverfish.hit"; + } + + protected String bp() { + return "mob.silverfish.kill"; + } + + public boolean damageEntity(DamageSource damagesource, float f) { + if (this.isInvulnerable(damagesource)) { + return false; + } else { + if (damagesource instanceof EntityDamageSource || damagesource == DamageSource.MAGIC) { + this.a.f(); + } + + return super.damageEntity(damagesource, f); + } + } + + protected void a(BlockPosition blockposition, Block block) { + this.makeSound("mob.silverfish.step", 0.15F, 1.0F); + } + + protected Item getLoot() { + return null; + } + + public void t_() { + this.aI = this.yaw; + super.t_(); + } + + public float a(BlockPosition blockposition) { + return this.world.getType(blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()).getBlock() == Blocks.STONE ? 10.0F : super.a(blockposition); + } + + protected boolean n_() { + return true; + } + + public boolean bR() { + if (super.bR()) { + EntityHuman entityhuman = this.world.findNearbyPlayer(this, 5.0D); + + return entityhuman == null; + } else { + return false; + } + } + + public EnumMonsterType getMonsterType() { + return EnumMonsterType.ARTHROPOD; + } + + static class PathfinderGoalSilverfishHideInBlock extends PathfinderGoalRandomStroll { + + private final EntitySilverfish silverfish; + private EnumDirection b; + private boolean c; + + public PathfinderGoalSilverfishHideInBlock(EntitySilverfish entitysilverfish) { + super(entitysilverfish, 1.0D, 10); + this.silverfish = entitysilverfish; + this.a(1); + } + + public boolean a() { + if (this.silverfish.getGoalTarget() != null) { + return false; + } else if (!this.silverfish.getNavigation().m()) { + return false; + } else { + Random random = this.silverfish.bc(); + + if (random.nextInt(10) == 0) { + this.b = EnumDirection.a(random); + IBlockData iblockdata = this.silverfish.world.getType(MathHelper.floor(this.silverfish.locX + b.getAdjacentX()), MathHelper.floor(this.silverfish.locY + 0.5D + b.getAdjacentY()), MathHelper.floor(this.silverfish.locZ + b.getAdjacentZ())); + + if (BlockMonsterEggs.d(iblockdata)) { + this.c = true; + return true; + } + } + + this.c = false; + return super.a(); + } + } + + public boolean b() { + return !this.c && super.b(); + } + + public void c() { + if (!this.c) { + super.c(); + } else { + World world = this.silverfish.world; + BlockPosition blockposition = (new BlockPosition(this.silverfish.locX, this.silverfish.locY + 0.5D, this.silverfish.locZ)).shift(this.b); + IBlockData iblockdata = world.getType(blockposition); + + if (BlockMonsterEggs.d(iblockdata)) { + // CraftBukkit start + if (org.bukkit.craftbukkit.event.CraftEventFactory.callEntityChangeBlockEvent(this.silverfish, blockposition.getX(), blockposition.getY(), blockposition.getZ(), Blocks.MONSTER_EGG, Block.getId(BlockMonsterEggs.getById(iblockdata.getBlock().toLegacyData(iblockdata)))).isCancelled()) { + return; + } + // CraftBukkit end + world.setTypeAndData(blockposition, Blocks.MONSTER_EGG.getBlockData().set(BlockMonsterEggs.VARIANT, BlockMonsterEggs.EnumMonsterEggVarient.a(iblockdata)), 3); + this.silverfish.y(); + this.silverfish.die(); + } + + } + } + } + + static class PathfinderGoalSilverfishWakeOthers extends PathfinderGoal { + + private final EntitySilverfish silverfish; + private int b; + + public PathfinderGoalSilverfishWakeOthers(EntitySilverfish entitysilverfish) { + this.silverfish = entitysilverfish; + } + + public void f() { + if (this.b == 0) { + this.b = 20; + } + + } + + public boolean a() { + return this.b > 0; + } + + public void e() { + --this.b; + if (this.b <= 0) { + World world = this.silverfish.world; + Random random = this.silverfish.bc(); + BlockPosition blockposition = new BlockPosition(this.silverfish); + + for (int i = 0; i <= 5 && i >= -5; i = i <= 0 ? 1 - i : -i) { + for (int j = 0; j <= 10 && j >= -10; j = j <= 0 ? 1 - j : -j) { + for (int k = 0; k <= 10 && k >= -10; k = k <= 0 ? 1 - k : -k) { + BlockPosition blockposition1 = blockposition.a(j, i, k); + IBlockData iblockdata = world.getType(blockposition1); + + if (iblockdata.getBlock() == Blocks.MONSTER_EGG) { + // CraftBukkit start + if (org.bukkit.craftbukkit.event.CraftEventFactory.callEntityChangeBlockEvent(this.silverfish, blockposition1.getX(), blockposition1.getY(), blockposition1.getZ(), Blocks.AIR, 0).isCancelled()) { + continue; + } + // CraftBukkit end + if (world.getGameRules().getBoolean("mobGriefing")) { + world.setAir(blockposition1, true); + } else { + world.setTypeAndData(blockposition1, iblockdata.get(BlockMonsterEggs.VARIANT).d(), 3); + } + + if (random.nextBoolean()) { + return; + } + } + } + } + } + } + + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntitySkeleton.java b/azurite-server/src/main/java/net/minecraft/server/EntitySkeleton.java new file mode 100644 index 0000000..1e5cf01 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntitySkeleton.java @@ -0,0 +1,301 @@ +package net.minecraft.server; + +import org.bukkit.event.entity.EntityCombustEvent; +import org.bukkit.event.entity.PotionEffectAddEvent; + +public class EntitySkeleton extends EntityMonster implements IRangedEntity { + + private final PathfinderGoalArrowAttack a = new PathfinderGoalArrowAttack(this, 1.0D, 20, 60, 15.0F); + private final PathfinderGoalMeleeAttack b = new PathfinderGoalMeleeAttack(this, EntityHuman.class, 1.2D, false); + + public EntitySkeleton(World world) { + super(world); + this.goalSelector.a(1, new PathfinderGoalFloat(this)); + this.goalSelector.a(2, new PathfinderGoalRestrictSun(this)); + this.goalSelector.a(3, new PathfinderGoalFleeSun(this, 1.0D)); + this.goalSelector.a(3, new PathfinderGoalAvoidTarget<>(this, EntityWolf.class, 6.0F, 1.0D, 1.2D)); + this.goalSelector.a(4, new PathfinderGoalRandomStroll(this, 1.0D)); + this.goalSelector.a(6, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 8.0F)); + this.goalSelector.a(6, new PathfinderGoalRandomLookaround(this)); + this.targetSelector.a(1, new PathfinderGoalHurtByTarget(this, false)); + this.targetSelector.a(2, new PathfinderGoalNearestAttackableTarget<>(this, EntityHuman.class, true)); + this.targetSelector.a(3, new PathfinderGoalNearestAttackableTarget<>(this, EntityIronGolem.class, true)); + if (world != null) { + this.n(); + } + + } + + protected void initAttributes() { + super.initAttributes(); + this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.25D); + } + + protected void h() { + super.h(); + this.datawatcher.a(13, (byte) 0); + } + + protected String z() { + return "mob.skeleton.say"; + } + + protected String bo() { + return "mob.skeleton.hurt"; + } + + protected String bp() { + return "mob.skeleton.death"; + } + + protected void a(BlockPosition blockposition, Block block) { + this.makeSound("mob.skeleton.step", 0.15F, 1.0F); + } + + public boolean r(Entity entity) { + if (super.r(entity)) { + if (this.getSkeletonType() == 1 && entity instanceof EntityLiving) { + ((EntityLiving) entity).addEffect(new MobEffect(MobEffectList.WITHER.id, 200), PotionEffectAddEvent.EffectCause.WITHER_SKELETON); + } + + return true; + } else { + return false; + } + } + + public EnumMonsterType getMonsterType() { + return EnumMonsterType.UNDEAD; + } + + public void m() { + if (this.world.w()) { + float f = this.c(1.0F); + + if (f > 0.5F && random.nextFloat() * 30.0F < (f - 0.4F) * 2.0F && this.world.i(MathHelper.floor(this.locX), MathHelper.floor(Math.round(this.locY)), MathHelper.floor(this.locZ))) { + boolean flag = true; + ItemStack itemstack = this.getEquipment(4); + + if (itemstack != null) { + if (itemstack.e()) { + itemstack.setData(itemstack.h() + random.nextInt(2)); + if (itemstack.h() >= itemstack.j()) { + this.b(itemstack); + this.setEquipment(4, null); + } + } + + flag = false; + } + + if (flag) { + // CraftBukkit start + EntityCombustEvent event = new EntityCombustEvent(this.getBukkitEntity(), 8); + this.world.getServer().getPluginManager().callEvent(event); + + if (!event.isCancelled()) { + this.setOnFire(event.getDuration()); + } + // CraftBukkit end + } + } + } + + super.m(); + } + + public void ak() { + super.ak(); + if (this.vehicle instanceof EntityCreature) { + EntityCreature entitycreature = (EntityCreature) this.vehicle; + + this.aI = entitycreature.aI; + } + + } + + public void die(DamageSource damagesource) { + // super.die(damagesource); // CraftBukkit + if (damagesource.i() instanceof EntityArrow && damagesource.getEntity() instanceof EntityHuman) { + EntityHuman entityhuman = (EntityHuman) damagesource.getEntity(); + double d0 = entityhuman.locX - this.locX; + double d1 = entityhuman.locZ - this.locZ; + + if (d0 * d0 + d1 * d1 >= 2500.0D) { + entityhuman.b(AchievementList.v); + } + } else if (damagesource.getEntity() instanceof EntityCreeper && ((EntityCreeper) damagesource.getEntity()).isPowered() && ((EntityCreeper) damagesource.getEntity()).cp()) { + ((EntityCreeper) damagesource.getEntity()).cq(); + // CraftBukkit start + // this.a(new ItemStack(Items.SKULL, 1, this.getSkeletonType() == 1 ? 1 : 0), 0.0F); + headDrop = new ItemStack(Items.SKULL, 1, this.getSkeletonType() == 1 ? 1 : 0); + // CraftBukkit end + } + + super.die(damagesource); // CraftBukkit - moved from above + } + + /* CraftBukkit start + protected Item getLoot() { + return Items.ARROW; + } + // CraftBukkit end */ + + protected void dropDeathLoot(boolean flag, int i) { + super.dropDeathLoot(flag, i); // CraftBukkit + int j; + int k; + + if (this.getSkeletonType() == 1) { + j = random.nextInt(3 + i) - 1; + + for (k = 0; k < j; ++k) { + this.a(Items.COAL, 1); + } + } else { + j = random.nextInt(3 + i); + + for (k = 0; k < j; ++k) { + this.a(Items.ARROW, 1); + } + } + + j = random.nextInt(3 + i); + + for (k = 0; k < j; ++k) { + this.a(Items.BONE, 1); + } + + } + + protected void getRareDrop() { + if (this.getSkeletonType() == 1) { + this.a(new ItemStack(Items.SKULL, 1, 1), 0.0F); + } + + } + + protected void a(DifficultyDamageScaler difficultydamagescaler) { + super.a(difficultydamagescaler); + this.setEquipment(0, new ItemStack(Items.BOW)); + } + + public GroupDataEntity prepare(DifficultyDamageScaler difficultydamagescaler, GroupDataEntity groupdataentity) { + groupdataentity = super.prepare(difficultydamagescaler, groupdataentity); + if (this.world.worldProvider instanceof WorldProviderHell && this.bc().nextInt(5) > 0) { + this.goalSelector.a(4, this.b); + this.setSkeletonType(1); + this.setEquipment(0, new ItemStack(Items.STONE_SWORD)); + this.getAttributeInstance(GenericAttributes.ATTACK_DAMAGE).setValue(4.0D); + } else { + this.goalSelector.a(4, this.a); + this.a(difficultydamagescaler); + this.b(difficultydamagescaler); + } + + this.j(random.nextFloat() < 0.55F * difficultydamagescaler.c()); + + return groupdataentity; + } + + public void n() { + this.goalSelector.a(this.b); + this.goalSelector.a(this.a); + ItemStack itemstack = this.bA(); + + if (itemstack != null && itemstack.getItem() == Items.BOW) { + this.goalSelector.a(4, this.a); + } else { + this.goalSelector.a(4, this.b); + } + + } + + public void a(EntityLiving entityliving, float f) { + EntityArrow entityarrow = new EntityArrow(this.world, this, entityliving, 1.6F, (float) (14 - this.world.getDifficulty().a() * 4)); + int i = EnchantmentManager.getEnchantmentLevel(Enchantment.ARROW_DAMAGE.id, this.bA()); + int j = EnchantmentManager.getEnchantmentLevel(Enchantment.ARROW_KNOCKBACK.id, this.bA()); + + entityarrow.b((double) (f * 2.0F) + random.nextGaussian() * 0.25D + (double) ((float) this.world.getDifficulty().a() * 0.11F)); + if (i > 0) { + entityarrow.b(entityarrow.j() + (double) i * 0.5D + 0.5D); + } + + if (j > 0) { + entityarrow.setKnockbackStrength(j); + } + + if (EnchantmentManager.getEnchantmentLevel(Enchantment.ARROW_FIRE.id, this.bA()) > 0 || this.getSkeletonType() == 1) { + // CraftBukkit start - call EntityCombustEvent + EntityCombustEvent event = new EntityCombustEvent(entityarrow.getBukkitEntity(), 100); + this.world.getServer().getPluginManager().callEvent(event); + + if (!event.isCancelled()) { + entityarrow.setOnFire(event.getDuration()); + } + // CraftBukkit end + } + + // CraftBukkit start + org.bukkit.event.entity.EntityShootBowEvent event = org.bukkit.craftbukkit.event.CraftEventFactory.callEntityShootBowEvent(this, this.bA(), entityarrow, 0.8F); + if (event.isCancelled()) { + event.getProjectile().remove(); + return; + } + + if (event.getProjectile() == entityarrow.getBukkitEntity()) { + world.addEntity(entityarrow); + } + // CraftBukkit end + + this.makeSound("random.bow", 1.0F, 1.0F / (this.bc().nextFloat() * 0.4F + 0.8F)); + // this.world.addEntity(entityarrow); // CraftBukkit - moved up + } + + public int getSkeletonType() { + return this.datawatcher.getByte(13); + } + + public void setSkeletonType(int i) { + this.datawatcher.watch(13, (byte) i); + this.fireProof = i == 1; + if (i == 1) { + this.setSize(0.72F, 2.535F); + } else { + this.setSize(0.6F, 1.95F); + } + + } + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + if (nbttagcompound.hasKeyOfType("SkeletonType", 99)) { + byte b0 = nbttagcompound.getByte("SkeletonType"); + + this.setSkeletonType(b0); + } + + this.n(); + } + + public void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + nbttagcompound.setByte("SkeletonType", (byte) this.getSkeletonType()); + } + + public void setEquipment(int i, ItemStack itemstack) { + super.setEquipment(i, itemstack); + if (i == 0) { + this.n(); + } + + } + + public float getHeadHeight() { + return this.getSkeletonType() == 1 ? super.getHeadHeight() : 1.74F; + } + + public double am() { + return this.isBaby() ? 0.0D : -0.35D; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntitySlice.java b/azurite-server/src/main/java/net/minecraft/server/EntitySlice.java new file mode 100644 index 0000000..26fe1d3 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntitySlice.java @@ -0,0 +1,115 @@ +package net.minecraft.server; + +import com.google.common.collect.Iterators; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import com.google.common.collect.Sets; + +import java.util.*; + +public class EntitySlice extends AbstractSet { + + private static final Set> a = Sets.newConcurrentHashSet(); // CraftBukkit + private final Map, List> b = Maps.newHashMap(); + private final Set> c = Sets.newIdentityHashSet(); + private final Class d; + private final List e = Lists.newArrayList(); + + public EntitySlice(Class oclass) { + this.d = oclass; + this.c.add(oclass); + this.b.put(oclass, this.e); + + for (Class aClass : EntitySlice.a) { + this.a(aClass); + } + + } + + protected void a(Class oclass) { + EntitySlice.a.add(oclass); + + for (T object : this.e) { + if (oclass.isAssignableFrom(object.getClass())) { + this.a(object, oclass); + } + } + + this.c.add(oclass); + } + + protected Class b(Class oclass) { + if (this.d.isAssignableFrom(oclass)) { + if (!this.c.contains(oclass)) { + this.a(oclass); + } + + return oclass; + } else { + throw new IllegalArgumentException("Don't know how to search for " + oclass); + } + } + + public boolean add(T t0) { + + for (Class aClass : this.c) { + + if (aClass.isAssignableFrom(t0.getClass())) { + this.a(t0, aClass); + } + } + + return true; + } + + private void a(T t0, Class oclass) { + List list = this.b.get(oclass); + + if (list == null) { + this.b.put(oclass, Lists.newArrayList(t0)); + } else { + list.add(t0); + } + + } + + public boolean remove(Object object) { + boolean flag = false; + + for (Class oclass : this.c) { + if (oclass.isAssignableFrom(object.getClass())) { + List list = this.b.get(oclass); + + if (list != null && list.remove(object)) { + flag = true; + } + } + } + + return flag; + } + + public boolean contains(Object object) { + return Iterators.contains(this.c(object.getClass()).iterator(), object); + } + + public Iterable c(final Class oclass) { + return () -> { + List list = EntitySlice.this.b.get(EntitySlice.this.b(oclass)); + + if (list == null) { + return Collections.emptyIterator(); + } else { + return Iterators.filter(list.iterator(), oclass); + } + }; + } + + public Iterator iterator() { + return this.e.isEmpty() ? Iterators.emptyIterator() : Iterators.unmodifiableIterator(this.e.iterator()); + } + + public int size() { + return this.e.size(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntitySlime.java b/azurite-server/src/main/java/net/minecraft/server/EntitySlime.java new file mode 100644 index 0000000..d78075a --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntitySlime.java @@ -0,0 +1,427 @@ +package net.minecraft.server; + +// CraftBukkit start +import org.bukkit.event.entity.SlimeSplitEvent; +// CraftBukkit end + +public class EntitySlime extends EntityInsentient implements IMonster { + + public float a; + public float b; + public float c; + private boolean bk; + + public EntitySlime(World world) { + super(world); + this.moveController = new EntitySlime.ControllerMoveSlime(this); + this.goalSelector.a(1, new EntitySlime.PathfinderGoalSlimeRandomJump(this)); + this.goalSelector.a(2, new EntitySlime.PathfinderGoalSlimeNearestPlayer(this)); + this.goalSelector.a(3, new EntitySlime.PathfinderGoalSlimeRandomDirection(this)); + this.goalSelector.a(5, new EntitySlime.PathfinderGoalSlimeIdle(this)); + this.targetSelector.a(1, new PathfinderGoalTargetNearestPlayer(this)); + this.targetSelector.a(3, new PathfinderGoalNearestAttackableTargetInsentient(this, EntityIronGolem.class)); + } + + protected void h() { + super.h(); + this.datawatcher.a(16, (byte) 1); + } + + public void setSize(int i) { + this.datawatcher.watch(16, (byte) i); + this.setSize(0.51000005F * (float) i, 0.51000005F * (float) i); + this.setPosition(this.locX, this.locY, this.locZ); + this.getAttributeInstance(GenericAttributes.maxHealth).setValue(i * i); + this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.2F + 0.1F * (float) i); + this.setHealth(this.getMaxHealth()); + this.b_ = i; + } + + public int getSize() { + return this.datawatcher.getByte(16); + } + + public void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + nbttagcompound.setInt("Size", this.getSize() - 1); + nbttagcompound.setBoolean("wasOnGround", this.bk); + } + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + int i = nbttagcompound.getInt("Size"); + + if (i < 0) { + i = 0; + } + + this.setSize(i + 1); + this.bk = nbttagcompound.getBoolean("wasOnGround"); + } + + protected EnumParticle n() { + return EnumParticle.SLIME; + } + + protected String ck() { + return "mob.slime." + (this.getSize() > 1 ? "big" : "small"); + } + + public void t_() { + if (this.world.getDifficulty() == EnumDifficulty.PEACEFUL && this.getSize() > 0) { + this.dead = true; + } + + this.b += (this.a - this.b) * 0.5F; + this.c = this.b; + super.t_(); + if (this.onGround && !this.bk) { + int i = this.getSize(); + + for (int j = 0; j < i * 8; ++j) { + float f = random.nextFloat() * 3.1415927F * 2.0F; + float f1 = random.nextFloat() * 0.5F + 0.5F; + float f2 = MathHelper.sin(f) * (float) i * 0.5F * f1; + float f3 = MathHelper.cos(f) * (float) i * 0.5F * f1; + + this.world.addParticle(n(), locX + f2, this.getBoundingBox().b, locZ + f3, 0.0D, 0.0D, 0.0D, EnumParticle.EMPTY_ARRAY); + } + + if (this.cl()) { + this.makeSound(this.ck(), this.bB(), ((random.nextFloat() - random.nextFloat()) * 0.2F + 1.0F) / 0.8F); + } + + this.a = -0.5F; + } else if (!this.onGround && this.bk) { + this.a = 1.0F; + } + + this.bk = this.onGround; + this.ch(); + } + + protected void ch() { + this.a *= 0.6F; + } + + protected int cg() { + return random.nextInt(20) + 10; + } + + protected EntitySlime cf() { + return new EntitySlime(this.world); + } + + public void i(int i) { + if (i == 16) { + int j = this.getSize(); + + this.setSize(0.51000005F * (float) j, 0.51000005F * (float) j); + this.yaw = this.aK; + this.aI = this.aK; + if (this.V() && random.nextInt(20) == 0) { + this.X(); + } + } + + super.i(i); + } + + public void die() { + int i = this.getSize(); + + if (i > 1 && this.getHealth() <= 0.0F) { + int j = 2 + random.nextInt(3); + + // CraftBukkit start + SlimeSplitEvent event = new SlimeSplitEvent((org.bukkit.entity.Slime) this.getBukkitEntity(), j); + this.world.getServer().getPluginManager().callEvent(event); + + if (!event.isCancelled() && event.getCount() > 0) { + j = event.getCount(); + } else { + super.die(); + return; + } + // CraftBukkit end + + for (int k = 0; k < j; ++k) { + float f = ((float) (k % 2) - 0.5F) * (float) i / 4.0F; + float f1 = ((float) (k / 2) - 0.5F) * (float) i / 4.0F; + EntitySlime entityslime = this.cf(); + + if (this.hasCustomName()) { + entityslime.setCustomName(this.getCustomName()); + } + + if (this.isPersistent()) { + entityslime.bX(); + } + + entityslime.setSize(i / 2); + entityslime.setPositionRotation(this.locX + (double) f, this.locY + 0.5D, this.locZ + (double) f1, random.nextFloat() * 360.0F, 0.0F); + this.world.addEntity(entityslime, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.SLIME_SPLIT); // CraftBukkit - SpawnReason + } + } + + super.die(); + } + + public void collide(Entity entity) { + super.collide(entity); + if (entity instanceof EntityIronGolem && this.ci()) { + this.e((EntityLiving) entity); + } + + } + + public void d(EntityHuman entityhuman) { + if (this.ci()) { + this.e((EntityLiving) entityhuman); + } + + } + + protected void e(EntityLiving entityliving) { + int i = this.getSize(); + + if (this.hasLineOfSight(entityliving) && this.h(entityliving) < 0.6D * (double) i * 0.6D * (double) i && entityliving.damageEntity(DamageSource.mobAttack(this), (float) this.cj())) { + this.makeSound("mob.attack", 1.0F, (random.nextFloat() - random.nextFloat()) * 0.2F + 1.0F); + this.a(this, entityliving); + } + + } + + public float getHeadHeight() { + return 0.625F * this.length; + } + + protected boolean ci() { + return this.getSize() > 1; + } + + protected int cj() { + return this.getSize(); + } + + protected String bo() { + return "mob.slime." + (this.getSize() > 1 ? "big" : "small"); + } + + protected String bp() { + return "mob.slime." + (this.getSize() > 1 ? "big" : "small"); + } + + protected Item getLoot() { + return this.getSize() == 1 ? Items.SLIME : null; + } + + public boolean bR() { + int x = MathHelper.floor(this.locX), z = MathHelper.floor(locZ); + Chunk chunk = this.world.getChunkAtWorldCoords(x, z); + if (this.world.getWorldData().getType() != WorldType.FLAT || random.nextInt(4) == 1) { + if (this.world.getDifficulty() != EnumDifficulty.PEACEFUL) { + BiomeBase biomebase = this.world.getBiome(x, 0, z); + + if (biomebase == BiomeBase.SWAMPLAND && this.locY > 50.0D && this.locY < 70.0D && random.nextFloat() < 0.5F && random.nextFloat() < this.world.y() && this.world.getLightLevel(MathHelper.floor(locX), MathHelper.floor(locY), MathHelper.floor(locZ)) <= random.nextInt(8)) { + return super.bR(); + } + + // PaperSpigot - Toggle to make all chunks spawn chunks + boolean isSlimeChunk = world.paperSpigotConfig.allChunksAreSlimeChunks || chunk.a(987234911L).nextInt(10) == 0; + if (random.nextInt(10) == 0 && isSlimeChunk && this.locY < 40.0D) { + return super.bR(); + } + } + + } + return false; + } + + protected float bB() { + return 0.4F * (float) this.getSize(); + } + + public int bQ() { + return 0; + } + + protected boolean cn() { + return this.getSize() > 0; + } + + protected boolean cl() { + return this.getSize() > 2; + } + + protected void bF() { + this.motY = 0.41999998688697815D; + this.ai = true; + } + + public GroupDataEntity prepare(DifficultyDamageScaler difficultydamagescaler, GroupDataEntity groupdataentity) { + int i = random.nextInt(3); + + if (i < 2 && random.nextFloat() < 0.5F * difficultydamagescaler.c()) { + ++i; + } + + int j = 1 << i; + + this.setSize(j); + return super.prepare(difficultydamagescaler, groupdataentity); + } + + static class PathfinderGoalSlimeIdle extends PathfinderGoal { + + private final EntitySlime a; + + public PathfinderGoalSlimeIdle(EntitySlime entityslime) { + this.a = entityslime; + this.a(5); + } + + public boolean a() { + return true; + } + + public void e() { + ((EntitySlime.ControllerMoveSlime) this.a.getControllerMove()).a(1.0D); + } + } + + static class PathfinderGoalSlimeRandomJump extends PathfinderGoal { + + private final EntitySlime a; + + public PathfinderGoalSlimeRandomJump(EntitySlime entityslime) { + this.a = entityslime; + this.a(5); + ((Navigation) entityslime.getNavigation()).d(true); + } + + public boolean a() { + return this.a.V() || this.a.ab(); + } + + public void e() { + if (this.a.bc().nextFloat() < 0.8F) { + this.a.getControllerJump().a(); + } + + ((EntitySlime.ControllerMoveSlime) this.a.getControllerMove()).a(1.2D); + } + } + + static class PathfinderGoalSlimeRandomDirection extends PathfinderGoal { + + private final EntitySlime a; + private float b; + private int c; + + public PathfinderGoalSlimeRandomDirection(EntitySlime entityslime) { + this.a = entityslime; + this.a(2); + } + + public boolean a() { + return this.a.getGoalTarget() == null && (this.a.onGround || this.a.V() || this.a.ab()); + } + + public void e() { + if (--this.c <= 0) { + this.c = 40 + this.a.bc().nextInt(60); + this.b = (float) this.a.bc().nextInt(360); + } + + ((EntitySlime.ControllerMoveSlime) this.a.getControllerMove()).a(this.b, false); + } + } + + static class PathfinderGoalSlimeNearestPlayer extends PathfinderGoal { + + private final EntitySlime a; + private int b; + + public PathfinderGoalSlimeNearestPlayer(EntitySlime entityslime) { + this.a = entityslime; + this.a(2); + } + + public boolean a() { + EntityLiving entityliving = this.a.getGoalTarget(); + + return entityliving != null && (entityliving.isAlive() && (!(entityliving instanceof EntityHuman) || !((EntityHuman) entityliving).abilities.isInvulnerable)); + } + + public void c() { + this.b = 300; + super.c(); + } + + public boolean b() { + EntityLiving entityliving = this.a.getGoalTarget(); + + return entityliving != null && (entityliving.isAlive() && ((!(entityliving instanceof EntityHuman) || !((EntityHuman) entityliving).abilities.isInvulnerable) && --this.b > 0)); + } + + public void e() { + this.a.a(this.a.getGoalTarget(), 10.0F, 10.0F); + ((EntitySlime.ControllerMoveSlime) this.a.getControllerMove()).a(this.a.yaw, this.a.ci()); + } + } + + static class ControllerMoveSlime extends ControllerMove { + + private float g; + private int h; + private final EntitySlime i; + private boolean j; + + public ControllerMoveSlime(EntitySlime entityslime) { + super(entityslime); + this.i = entityslime; + } + + public void a(float f, boolean flag) { + this.g = f; + this.j = flag; + } + + public void a(double d0) { + this.e = d0; + this.f = true; + } + + public void c() { + this.a.yaw = this.a(this.a.yaw, this.g, 30.0F); + this.a.aK = this.a.yaw; + this.a.aI = this.a.yaw; + if (!this.f) { + this.a.n(0.0F); + } else { + this.f = false; + if (this.a.onGround) { + this.a.k((float) (this.e * this.a.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).getValue())); + if (this.h-- <= 0) { + this.h = this.i.cg(); + if (this.j) { + this.h /= 3; + } + + this.i.getControllerJump().a(); + if (this.i.cn()) { + this.i.makeSound(this.i.ck(), this.i.bB(), ((this.i.bc().nextFloat() - this.i.bc().nextFloat()) * 0.2F + 1.0F) * 0.8F); + } + } else { + this.i.aZ = this.i.ba = 0.0F; + this.a.k(0.0F); + } + } else { + this.a.k((float) (this.e * this.a.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).getValue())); + } + + } + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntitySmallFireball.java b/azurite-server/src/main/java/net/minecraft/server/EntitySmallFireball.java new file mode 100644 index 0000000..5f67a4a --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntitySmallFireball.java @@ -0,0 +1,70 @@ +package net.minecraft.server; + +import org.bukkit.event.entity.EntityCombustByEntityEvent; + +public class EntitySmallFireball extends EntityFireball { + + public EntitySmallFireball(World world) { + super(world); + this.setSize(0.3125F, 0.3125F); + } + + public EntitySmallFireball(World world, EntityLiving entityliving, double d0, double d1, double d2) { + super(world, entityliving, d0, d1, d2); + this.setSize(0.3125F, 0.3125F); + } + + public EntitySmallFireball(World world, double d0, double d1, double d2, double d3, double d4, double d5) { + super(world, d0, d1, d2, d3, d4, d5); + this.setSize(0.3125F, 0.3125F); + } + + protected void a(MovingObjectPosition movingobjectposition) { + boolean flag; + + if (movingobjectposition.entity != null) { + flag = movingobjectposition.entity.damageEntity(DamageSource.fireball(this, this.shooter), 5.0F); + if (flag) { + this.a(this.shooter, movingobjectposition.entity); + if (!movingobjectposition.entity.isFireProof()) { + // CraftBukkit start - Entity damage by entity event + combust event + EntityCombustByEntityEvent event = new EntityCombustByEntityEvent(this.getBukkitEntity(), movingobjectposition.entity.getBukkitEntity(), 5); + movingobjectposition.entity.world.getServer().getPluginManager().callEvent(event); + + if (!event.isCancelled()) { + movingobjectposition.entity.setOnFire(event.getDuration()); + } + // CraftBukkit end + } + } + } else { + flag = true; + if (this.shooter != null && this.shooter instanceof EntityInsentient) { + flag = this.world.getGameRules().getBoolean("mobGriefing"); + } + + if (flag) { + BlockPosition blockposition = movingobjectposition.a().shift(movingobjectposition.direction); + + if (this.world.isEmpty(blockposition)) { + // CraftBukkit start + if (isIncendiary && !org.bukkit.craftbukkit.event.CraftEventFactory.callBlockIgniteEvent(world, blockposition.getX(), blockposition.getY(), blockposition.getZ(), this).isCancelled()) { + this.world.setTypeUpdate(blockposition, Blocks.FIRE.getBlockData()); + } + // CraftBukkit end + } + } + } + + this.die(); + + } + + public boolean ad() { + return false; + } + + public boolean damageEntity(DamageSource damagesource, float f) { + return false; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntitySnowball.java b/azurite-server/src/main/java/net/minecraft/server/EntitySnowball.java new file mode 100644 index 0000000..34da3ee --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntitySnowball.java @@ -0,0 +1,40 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.AzuriteConfig; + +public class EntitySnowball extends EntityProjectile { + + public EntitySnowball(World world) { + super(world); + } + + public EntitySnowball(World world, EntityLiving entityliving) { + super(world, entityliving); + } + + public EntitySnowball(World world, double d0, double d1, double d2) { + super(world, d0, d1, d2); + } + + @Override + public float getRandomness() { + return AzuriteConfig.snowballTrajectoryRandomness.getValue(); + } + + protected void a(MovingObjectPosition movingobjectposition) { + if (movingobjectposition.entity != null) { + byte b0 = 0; + if (movingobjectposition.entity instanceof EntityBlaze) { + b0 = 3; + } + + movingobjectposition.entity.damageEntity(DamageSource.projectile(this, this.getShooter()), (float) b0); + } + + for (int i = 0; i < 8; ++i) { + this.world.addParticle(EnumParticle.SNOWBALL, this.locX, this.locY, this.locZ, 0.0D, 0.0D, 0.0D, EnumParticle.EMPTY_ARRAY); + } + + this.die(); + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/net/minecraft/server/EntitySnowman.java b/azurite-server/src/main/java/net/minecraft/server/EntitySnowman.java new file mode 100644 index 0000000..d00bb3e --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntitySnowman.java @@ -0,0 +1,103 @@ +package net.minecraft.server; + +// CraftBukkit start + +import dev.azurite.spigot.configs.AzuriteConfig; +import org.bukkit.craftbukkit.event.CraftEventFactory; +import org.bukkit.craftbukkit.util.CraftMagicNumbers; +import org.bukkit.event.block.EntityBlockFormEvent; +// CraftBukkit end + +public class EntitySnowman extends EntityGolem implements IRangedEntity { + + public EntitySnowman(World world) { + super(world); + this.setSize(0.7F, 1.9F); + ((Navigation) this.getNavigation()).a(true); + this.goalSelector.a(1, new PathfinderGoalArrowAttack(this, 1.25D, 20, 10.0F)); + this.goalSelector.a(2, new PathfinderGoalRandomStroll(this, 1.0D)); + this.goalSelector.a(3, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 6.0F)); + this.goalSelector.a(4, new PathfinderGoalRandomLookaround(this)); + this.targetSelector.a(1, new PathfinderGoalNearestAttackableTarget<>(this, EntityInsentient.class, 10, true, false, IMonster.d)); + } + + protected void initAttributes() { + super.initAttributes(); + this.getAttributeInstance(GenericAttributes.maxHealth).setValue(4.0D); + this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.20000000298023224D); + } + + + @Override + public void e(float f, float f1) { + if (AzuriteConfig.snowGolemFallDamage.getValue()) + super.e(f, f1); + } + + public void m() { + super.m(); + int i = MathHelper.floor(this.locX); + int j = MathHelper.floor(this.locY); + int k = MathHelper.floor(this.locZ); + + if (this.U()) { + this.damageEntity(DamageSource.DROWN, 1.0F); + } + + if (this.world.getBiome(i, 0, k).aV(i, j, k) > 1.0F) { + this.damageEntity(CraftEventFactory.MELTING, 1.0F); // CraftBukkit - DamageSource.BURN -> CraftEventFactory.MELTING + } + + for (int l = 0; l < 4; ++l) { + i = MathHelper.floor(this.locX + (double) ((float) (l % 2 * 2 - 1) * 0.25F)); + j = MathHelper.floor(this.locY); + k = MathHelper.floor(this.locZ + (double) ((float) (l / 2 % 2 * 2 - 1) * 0.25F)); + BlockPosition blockposition = new BlockPosition(i, j, k); + + if (this.world.getType(blockposition).getBlock().getMaterial() == Material.AIR && this.world.getBiome(i, 0, k).a(blockposition) < 0.8F && Blocks.SNOW_LAYER.canPlace(this.world, blockposition)) { + // CraftBukkit start + org.bukkit.block.BlockState blockState = this.world.getWorld().getBlockAt(i, j, k).getState(); + blockState.setType(CraftMagicNumbers.getMaterial(Blocks.SNOW_LAYER)); + + EntityBlockFormEvent event = new EntityBlockFormEvent(this.getBukkitEntity(), blockState.getBlock(), blockState); + this.world.getServer().getPluginManager().callEvent(event); + + if (!event.isCancelled()) { + blockState.update(true); + } + // CraftBukkit end + } + } + + } + + protected Item getLoot() { + return Items.SNOWBALL; + } + + protected void dropDeathLoot(boolean flag, int i) { + int j = random.nextInt(16); + + for (int k = 0; k < j; ++k) { + this.a(Items.SNOWBALL, 1); + } + + } + + public void a(EntityLiving entityliving, float f) { + EntitySnowball entitysnowball = new EntitySnowball(this.world, this); + double d0 = entityliving.locY + (double) entityliving.getHeadHeight() - 1.100000023841858D; + double d1 = entityliving.locX - this.locX; + double d2 = d0 - entitysnowball.locY; + double d3 = entityliving.locZ - this.locZ; + float f1 = MathHelper.sqrt(d1 * d1 + d3 * d3) * 0.2F; + + entitysnowball.shoot(d1, d2 + (double) f1, d3, 1.6F, 12.0F); + this.makeSound("random.bow", 1.0F, 1.0F / (this.bc().nextFloat() * 0.4F + 0.8F)); + this.world.addEntity(entitysnowball); + } + + public float getHeadHeight() { + return 1.7F; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntitySpider.java b/azurite-server/src/main/java/net/minecraft/server/EntitySpider.java new file mode 100644 index 0000000..65a9cdc --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntitySpider.java @@ -0,0 +1,198 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.AzuriteConfig; + +import java.util.Random; + +public class EntitySpider extends EntityMonster { + + public EntitySpider(World world) { + super(world); + this.setSize(1.4F, 0.9F); + this.goalSelector.a(1, new PathfinderGoalFloat(this)); + this.goalSelector.a(3, new PathfinderGoalLeapAtTarget(this, 0.4F)); + this.goalSelector.a(4, new EntitySpider.PathfinderGoalSpiderMeleeAttack(this, EntityHuman.class)); + this.goalSelector.a(4, new EntitySpider.PathfinderGoalSpiderMeleeAttack(this, EntityIronGolem.class)); + this.goalSelector.a(5, new PathfinderGoalRandomStroll(this, 0.8D)); + this.goalSelector.a(6, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 8.0F)); + this.goalSelector.a(6, new PathfinderGoalRandomLookaround(this)); + this.targetSelector.a(1, new PathfinderGoalHurtByTarget(this, false)); + this.targetSelector.a(2, new EntitySpider.PathfinderGoalSpiderNearestAttackableTarget<>(this, EntityHuman.class)); + this.targetSelector.a(3, new EntitySpider.PathfinderGoalSpiderNearestAttackableTarget<>(this, EntityIronGolem.class)); + } + + public double an() { + return this.length * 0.5F; + } + + protected NavigationAbstract b(World world) { + return new NavigationSpider(this, world); + } + + protected void h() { + super.h(); + this.datawatcher.a(16, (byte) 0); + } + + public void t_() { + super.t_(); + + this.a(this.positionChanged); + + } + + protected void initAttributes() { + super.initAttributes(); + this.getAttributeInstance(GenericAttributes.maxHealth).setValue(16.0D); + this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.30000001192092896D); + } + + protected String z() { + return "mob.spider.say"; + } + + protected String bo() { + return "mob.spider.say"; + } + + protected String bp() { + return "mob.spider.death"; + } + + protected void a(BlockPosition blockposition, Block block) { + this.makeSound("mob.spider.step", 0.15F, 1.0F); + } + + protected Item getLoot() { + return Items.STRING; + } + + protected void dropDeathLoot(boolean flag, int i) { + super.dropDeathLoot(flag, i); + if (flag && (random.nextInt(3) == 0 || random.nextInt(1 + i) > 0)) { + this.a(Items.SPIDER_EYE, 1); + } + + } + + public boolean k_() { + return this.n(); + } + + public void aA() { + } + + public EnumMonsterType getMonsterType() { + return EnumMonsterType.ARTHROPOD; + } + + public boolean d(MobEffect mobeffect) { + return mobeffect.getEffectId() != MobEffectList.POISON.id && super.d(mobeffect); + } + + public boolean n() { + return (this.datawatcher.getByte(16) & 1) != 0; + } + + public void a(boolean flag) { + byte b0 = this.datawatcher.getByte(16); + + if (flag) { + b0 = (byte) (b0 | 1); + } else { + b0 &= -2; + } + + this.datawatcher.watch(16, b0); + } + + public GroupDataEntity prepare(DifficultyDamageScaler difficultydamagescaler, GroupDataEntity groupdataentity) { + GroupDataEntity object = super.prepare(difficultydamagescaler, groupdataentity); + + if (AzuriteConfig.skeletonOnSpiderSpawning.getValue() && this.world.random.nextInt(100) == 0) { + EntitySkeleton entityskeleton = new EntitySkeleton(this.world); + entityskeleton.setPositionRotation(this.locX, this.locY, this.locZ, this.yaw, 0.0F); + entityskeleton.prepare(difficultydamagescaler, null); + this.world.addEntity(entityskeleton, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.JOCKEY); // CraftBukkit - add SpawnReason + entityskeleton.mount(this); + } + + if (object == null) { + object = new EntitySpider.GroupDataSpider(); + if (this.world.getDifficulty() == EnumDifficulty.HARD && this.world.random.nextFloat() < 0.1F * difficultydamagescaler.c()) { + ((EntitySpider.GroupDataSpider) object).a(this.world.random); + } + } + + if (object instanceof EntitySpider.GroupDataSpider) { + int i = ((EntitySpider.GroupDataSpider) object).a; + + if (i > 0 && MobEffectList.byId[i] != null) { + this.addEffect(new MobEffect(i, Integer.MAX_VALUE)); + } + } + + return object; + } + + public float getHeadHeight() { + return 0.65F; + } + + static class PathfinderGoalSpiderNearestAttackableTarget extends PathfinderGoalNearestAttackableTarget { + + public PathfinderGoalSpiderNearestAttackableTarget(EntitySpider entityspider, Class oclass) { + super(entityspider, oclass, true); + } + + public boolean a() { + float f = this.e.c(1.0F); + + return !(f >= 0.5F) && super.a(); + } + } + + static class PathfinderGoalSpiderMeleeAttack extends PathfinderGoalMeleeAttack { + + public PathfinderGoalSpiderMeleeAttack(EntitySpider entityspider, Class oclass) { + super(entityspider, oclass, 1.0D, true); + } + + public boolean b() { + float f = this.b.c(1.0F); + + if (f >= 0.5F && this.b.bc().nextInt(100) == 0) { + this.b.setGoalTarget(null); + return false; + } else { + return super.b(); + } + } + + protected double a(EntityLiving entityliving) { + return 4.0F + entityliving.width; + } + } + + public static class GroupDataSpider implements GroupDataEntity { + + public int a; + + public GroupDataSpider() { + } + + public void a(Random random) { + int i = random.nextInt(5); + + if (i <= 1) { + this.a = MobEffectList.FASTER_MOVEMENT.id; + } else if (i == 2) { + this.a = MobEffectList.INCREASE_DAMAGE.id; + } else if (i == 3) { + this.a = MobEffectList.REGENERATION.id; + } else { + this.a = MobEffectList.INVISIBILITY.id; + } + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntitySquid.java b/azurite-server/src/main/java/net/minecraft/server/EntitySquid.java new file mode 100644 index 0000000..3b87d56 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntitySquid.java @@ -0,0 +1,182 @@ +package net.minecraft.server; + +import java.util.Random; + +public class EntitySquid extends EntityWaterAnimal { + + private final Random random = new Random(); // Vortex - local random + public float a; + public float b; + public float c; + public float bk; + public float bl; + public float bm; + public float bn; + public float bo; + private float bp; + private float bq; + private float br; + private float bs; + private float bt; + private float bu; + + public EntitySquid(World world) { + super(world); + this.setSize(0.95F, 0.95F); + //this.random.setSeed((long) (1 + this.getId())); // PandaSpigot - shared random + this.bq = 1.0F / (random.nextFloat() + 1.0F) * 0.2F; + this.goalSelector.a(0, new EntitySquid.PathfinderGoalSquid(this)); + } + + protected void initAttributes() { + super.initAttributes(); + this.getAttributeInstance(GenericAttributes.maxHealth).setValue(10.0D); + } + + public float getHeadHeight() { + return this.length * 0.5F; + } + + protected String z() { + return null; + } + + protected String bo() { + return null; + } + + protected String bp() { + return null; + } + + protected float bB() { + return 0.4F; + } + + protected Item getLoot() { + return null; + } + + protected boolean s_() { + return false; + } + + protected void dropDeathLoot(boolean flag, int i) { + int j = random.nextInt(3 + i) + 1; + + for (int k = 0; k < j; ++k) { + this.a(new ItemStack(Items.DYE, 1, EnumColor.BLACK.getInvColorIndex()), 0.0F); + } + + } + + /* CraftBukkit start - Delegate to Entity to use existing inWater value + public boolean V() { + return this.world.a(this.getBoundingBox().grow(0.0D, -0.6000000238418579D, 0.0D), Material.WATER, (Entity) this); + } + // CraftBukkit end */ + + public void m() { + super.m(); + this.b = this.a; + this.bk = this.c; + this.bm = this.bl; + this.bo = this.bn; + this.bl += this.bq; + if ((double) this.bl > 6.283185307179586D) { + this.bl = (float) ((double) this.bl - 6.283185307179586D); + if (random.nextInt(10) == 0) { + this.bq = 1.0F / (random.nextFloat() + 1.0F) * 0.2F; + } + + this.world.broadcastEntityEffect(this, (byte) 19); + } + + if (this.inWater) { + float f; + + if (this.bl < 3.1415927F) { + f = this.bl / 3.1415927F; + this.bn = MathHelper.sin(f * f * 3.1415927F) * 3.1415927F * 0.25F; + if ((double) f > 0.75D) { + this.bp = 1.0F; + this.br = 1.0F; + } else { + this.br *= 0.8F; + } + } else { + this.bn = 0.0F; + this.bp *= 0.9F; + this.br *= 0.99F; + } + + this.motX = this.bs * this.bp; + this.motY = this.bt * this.bp; + this.motZ = this.bu * this.bp; + + f = MathHelper.sqrt(this.motX * this.motX + this.motZ * this.motZ); + this.aI += (-((float) MathHelper.b(this.motX, this.motZ)) * 180.0F / 3.1415927F - this.aI) * 0.1F; + this.yaw = this.aI; + this.c = (float) ((double) this.c + 3.141592653589793D * (double) this.br * 1.5D); + this.a += (-((float) MathHelper.b(f, this.motY)) * 180.0F / 3.1415927F - this.a) * 0.1F; + } else { + this.bn = MathHelper.e(MathHelper.sin(this.bl)) * 3.1415927F * 0.25F; + + this.motX = 0.0D; + this.motY -= 0.08D; + this.motY *= 0.9800000190734863D; + this.motZ = 0.0D; + + this.a = (float) ((double) this.a + (double) (-90.0F - this.a) * 0.02D); + } + + } + + public void g(float f, float f1) { + this.move(this.motX, this.motY, this.motZ); + } + + public boolean bR() { + // PaperSpigot - Configurable squid spawn range + return this.locY > this.world.paperSpigotConfig.squidMinSpawnHeight && this.locY < this.world.paperSpigotConfig.squidMaxSpawnHeight && super.bR(); + } + + public void b(float f, float f1, float f2) { + this.bs = f; + this.bt = f1; + this.bu = f2; + } + + public boolean n() { + return this.bs != 0.0F || this.bt != 0.0F || this.bu != 0.0F; + } + + static class PathfinderGoalSquid extends PathfinderGoal { + + private final EntitySquid a; + + public PathfinderGoalSquid(EntitySquid entitysquid) { + this.a = entitysquid; + } + + public boolean a() { + return true; + } + + public void e() { + int i = this.a.bh(); + + if (i > 100) { + this.a.b(0.0F, 0.0F, 0.0F); + } else if (this.a.bc().nextInt(50) == 0 || !this.a.inWater || !this.a.n()) { + float f = this.a.bc().nextFloat() * 3.1415927F * 2.0F; + float f1 = MathHelper.cos(f) * 0.2F; + float f2 = -0.1F + this.a.bc().nextFloat() * 0.2F; + float f3 = MathHelper.sin(f) * 0.2F; + + this.a.b(f1, f2, f3); + } + + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityTNTPrimed.java b/azurite-server/src/main/java/net/minecraft/server/EntityTNTPrimed.java new file mode 100644 index 0000000..13e1dd5 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityTNTPrimed.java @@ -0,0 +1,315 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.AzuriteConfig; +import org.bukkit.Location; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.entity.CraftEntity; +import org.bukkit.entity.Explosive; +import org.bukkit.event.entity.ExplosionPrimeEvent; + +import java.util.Iterator; +import java.util.List; + +public class EntityTNTPrimed extends Entity { + public int fuseTicks; + public float yield = 4.0F; + public boolean isIncendiary = false; + public Location sourceLoc; + private EntityLiving source; + + public EntityTNTPrimed(World world) { + this(null, world); + } + + public EntityTNTPrimed(Location loc, World world) { + super(world); + sourceLoc = loc; + k = true; + setSize(0.98F, 0.98F); + loadChunks = world.paperSpigotConfig.loadUnloadedTNTEntities; + } + + public EntityTNTPrimed(Location loc, World world, double d0, double d1, double d2, EntityLiving entityliving) { + this(loc, world); + setPosition(d0, d1, d2); + if (world.paperSpigotConfig.fixCannons) { + motX = motZ = 0.0D; + } else { + float f = (float) (Math.random() * 3.1415927410125732D * 2.0D); + motX = (-((float) Math.sin(f)) * 0.02F); + motZ = (-((float) Math.cos(f)) * 0.02F); + } + motY = 0.20000000298023224D; + fuseTicks = 80; + lastX = d0; + lastY = d1; + lastZ = d2; + source = entityliving; + } + + protected void h() { + } + + protected boolean s_() { + return false; + } + + public boolean ad() { + return !dead; + } + + public void t_() { + lastX = locX; + lastY = locY; + lastZ = locZ; + + motY -= 0.03999999910593033D; + + move(motX, motY, motZ); + + if (world.paperSpigotConfig.tntEntityHeightNerf != 0 && locY > world.paperSpigotConfig.tntEntityHeightNerf) { + die(); + } + + if (inUnloadedChunk && world.paperSpigotConfig.removeUnloadedTNTEntities) { + die(); + fuseTicks = 2; + } + + motX *= 0.9800000190734863D; + motY *= 0.9800000190734863D; + motZ *= 0.9800000190734863D; + + if (onGround) { + motX *= 0.699999988079071D; + motY *= -0.5D; + motZ *= 0.699999988079071D; + } + + if (fuseTicks-- <= 0) { + respawn(); + explode(); + die(); + } else { + W(); + if (AzuriteConfig.tntParticles.getValue()) + world.addParticle(EnumParticle.SMOKE_NORMAL, locX, locY + 0.5D, locZ, 0.0D, 0.0D, 0.0D, EnumParticle.EMPTY_ARRAY); + } + } + + public boolean merge(Entity entity) { + return AzuriteConfig.tntMerging.getValue() && + entity.ticksLived == ticksLived + 1 && + entity.lastX == locX && + entity.lastY == locY && + entity.lastZ == locZ && + entity.lastMotX == motX && + entity.lastMotY == motY - 0.03999999910593033D && + entity.lastMotZ == motZ && + entity.getClass() == getClass() && + ((EntityTNTPrimed) entity).fuseTicks == fuseTicks - 1 && fuseTicks > 0; + } + + protected void respawn() { + if (potential <= 1) + return; + EntityTNTPrimed temp = new EntityTNTPrimed(new Location( + world.getWorld(), + lastX, lastY, lastZ), + world, lastX, lastY, lastZ, source); + temp.motX = lastMotX; + temp.motY = lastMotY + 0.03999999910593033D; + temp.motZ = lastMotZ; + temp.recalcPosition(); + Chunk chunk = world.getChunkAtWorldCoords(MathHelper.floor(temp.locX), MathHelper.floor(temp.locZ)); + chunk.addCannonEntity(temp); + for (int i = 1; i < potential; i++) { + explode(); + locX = lastX; + locY = lastY; + locZ = lastZ; + motX = temp.motX; + motY = temp.motY; + motZ = temp.motZ; + a(temp.boundingBox); + fuseTicks = 1; + t_(); + } + chunk.removeCannonEntity(temp, temp.af); + } + + private void explode() { + ChunkProviderServer chunkProviderServer = (ChunkProviderServer) world.chunkProvider; + + boolean forceChunkLoad = chunkProviderServer.forceChunkLoad; + if (world.paperSpigotConfig.loadUnloadedTNTEntities) { + chunkProviderServer.forceChunkLoad = true; + } + + CraftServer server = world.getServer(); + ExplosionPrimeEvent event = new ExplosionPrimeEvent((Explosive) CraftEntity.getEntity(server, this)); + server.getPluginManager().callEvent(event); + + if (!event.isCancelled()) + world.createExplosion(this, locX, locY + (length / 2.0F), locZ, event.getRadius(), event.getFire(), true); + + if (world.paperSpigotConfig.loadUnloadedTNTEntities) + chunkProviderServer.forceChunkLoad = forceChunkLoad; + } + + protected void b(NBTTagCompound nbttagcompound) { + nbttagcompound.setByte("Fuse", (byte) fuseTicks); + if (sourceLoc != null) { + nbttagcompound.setInt("SourceLoc_x", sourceLoc.getBlockX()); + nbttagcompound.setInt("SourceLoc_y", sourceLoc.getBlockY()); + nbttagcompound.setInt("SourceLoc_z", sourceLoc.getBlockZ()); + } + } + + protected void a(NBTTagCompound nbttagcompound) { + fuseTicks = nbttagcompound.getByte("Fuse"); + if (nbttagcompound.hasKey("SourceLoc_x")) { + sourceLoc = new Location(world.getWorld(), nbttagcompound.getInt("SourceLoc_x"), nbttagcompound.getInt("SourceLoc_y"), nbttagcompound.getInt("SourceLoc_z")); + } + } + + public EntityLiving getSource() { + return source; + } + + @Override + public double f(double d0, double d1, double d2) { + double d3 = locX - d0; + double d4 = locY + getHeadHeight() - d1; + double d5 = locZ - d2; + return MathHelper.sqrt(d3 * d3 + d4 * d4 + d5 * d5); + } + + @Override + public boolean aL() { + return !world.paperSpigotConfig.fixCannons && super.aL(); + } + + @Override + public float getHeadHeight() { + return world.paperSpigotConfig.fixCannons ? (length / 2.0F) : 0.0F; + } + + @Override + public boolean W() { + return world.paperSpigotConfig.fixCannons ? inWater : super.W(); + } + + @Override + public void move(double d0, double d1, double d2) { + if (loadChunks) + loadChunks(); + if (noclip) { + a(boundingBox.c(d0, d1, d2)); + recalcPosition(); + } else { + lastMotX = motX; + lastMotY = motY; + lastMotZ = motZ; + if (world.movementCache.move(this)) + return; + + try { + checkBlockCollisions(); + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.a(throwable, "Checking entity block collision"); + CrashReportSystemDetails crashreportsystemdetails = crashreport.a("Entity being checked for collision"); + appendEntityCrashDetails(crashreportsystemdetails); + throw new ReportedException(crashreport); + } + + if (d0 == 0.0D && d1 == 0.0D && d2 == 0.0D && vehicle == null && passenger == null) + return; + + if (H) { + H = false; + d0 *= 0.25D; + d1 *= 0.05000000074505806D; + d2 *= 0.25D; + motX = 0.0D; + motY = 0.0D; + motZ = 0.0D; + } + + double d6 = d0; + double d7 = d1; + double d8 = d2; + + AxisAlignedBB totalArea = boundingBox.a(d0, d1, d2); + double xLength = totalArea.d - totalArea.a; + double yLength = totalArea.e - totalArea.b; + double zLength = totalArea.f - totalArea.c; + boolean axisScan = AzuriteConfig.optimizeTNTMovement.getValue() && (xLength * yLength * zLength > 10.0D); + List list = world.getCubes(this, axisScan ? boundingBox.a(0.0D, d1, 0.0D) : totalArea); + + AxisAlignedBB axisalignedbb1; + for (Iterator iterator = list.iterator(); iterator.hasNext(); d1 = axisalignedbb1.b(boundingBox, d1)) + axisalignedbb1 = iterator.next(); + a(boundingBox.c(0.0D, d1, 0.0D)); + + AxisAlignedBB axisalignedbb2; + if (AzuriteConfig.fixEastWestCannon.getValue() && Math.abs(d0) > Math.abs(d2)) { + if (axisScan) + list = world.getCubes(this, boundingBox.a(0.0D, 0.0D, d2)); + + Iterator iterator1; + for (iterator1 = list.iterator(); iterator1.hasNext(); d2 = axisalignedbb2.c(boundingBox, d2)) + axisalignedbb2 = iterator1.next(); + a(boundingBox.c(0.0D, 0.0D, d2)); + + if (axisScan) + list = world.getCubes(this, boundingBox.a(d0, 0.0D, 0.0D)); + + for (iterator1 = list.iterator(); iterator1.hasNext(); d0 = axisalignedbb2.a(boundingBox, d0)) + axisalignedbb2 = iterator1.next(); + a(boundingBox.c(d0, 0.0D, 0.0D)); + } else { + if (axisScan) + list = world.getCubes(this, boundingBox.a(d0, 0.0D, 0.0D)); + + Iterator iterator1; + for (iterator1 = list.iterator(); iterator1.hasNext(); d0 = axisalignedbb2.a(boundingBox, d0)) + axisalignedbb2 = iterator1.next(); + a(boundingBox.c(d0, 0.0D, 0.0D)); + + if (axisScan) + list = world.getCubes(this, boundingBox.a(0.0D, 0.0D, d2)); + + for (iterator1 = list.iterator(); iterator1.hasNext(); d2 = axisalignedbb2.c(boundingBox, d2)) + axisalignedbb2 = iterator1.next(); + a(boundingBox.c(0.0D, 0.0D, d2)); + } + + recalcPosition(); + positionChanged = !(d6 == d0 && d8 == d2); + E = (d7 != d1); + onGround = (E && d7 < 0.0D); + F = !(!positionChanged && !E); + + BlockPosition blockposition = new BlockPosition(MathHelper.floor(locX), MathHelper.floor(locY - 0.20000000298023224D), MathHelper.floor(locZ)); + Block block = world.getType(blockposition).getBlock(); + if (block.getMaterial() == Material.AIR) { + Block block1 = world.getType(blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()).getBlock(); + if (block1 instanceof BlockFence || block1 instanceof BlockCobbleWall || block1 instanceof BlockFenceGate) { + block = block1; + blockposition.setY(blockposition.getY() - 1); + } + } + + a(d1, onGround, block, blockposition); + if (d6 != d0) + motX = 0.0D; + if (d8 != d2) + motZ = 0.0D; + if (d7 != d1) + block.a(world, this); + + world.movementCache.cache(this); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityTameableAnimal.java b/azurite-server/src/main/java/net/minecraft/server/EntityTameableAnimal.java new file mode 100644 index 0000000..22efa11 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityTameableAnimal.java @@ -0,0 +1,169 @@ +package net.minecraft.server; + +import com.eatthepath.uuid.FastUUID; + +import java.util.UUID; + +public abstract class EntityTameableAnimal extends EntityAnimal implements EntityOwnable { + + protected PathfinderGoalSit bm = new PathfinderGoalSit(this); + + public EntityTameableAnimal(World world) { + super(world); + this.cm(); + } + + protected void h() { + super.h(); + this.datawatcher.a(16, Byte.valueOf((byte) 0)); + this.datawatcher.a(17, ""); + } + + public void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + if (this.getOwnerUUID() == null) { + nbttagcompound.setString("OwnerUUID", ""); + } else { + nbttagcompound.setString("OwnerUUID", this.getOwnerUUID()); + } + + nbttagcompound.setBoolean("Sitting", this.isSitting()); + } + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + String s = ""; + + if (nbttagcompound.hasKeyOfType("OwnerUUID", 8)) { + s = nbttagcompound.getString("OwnerUUID"); + } else { + String s1 = nbttagcompound.getString("Owner"); + + s = NameReferencingFileConverter.a(s1); + } + + if (s.length() > 0) { + this.setOwnerUUID(s); + this.setTamed(true); + } + + this.bm.setSitting(nbttagcompound.getBoolean("Sitting")); + this.setSitting(nbttagcompound.getBoolean("Sitting")); + } + + protected void l(boolean flag) { + EnumParticle enumparticle = EnumParticle.HEART; + + if (!flag) { + enumparticle = EnumParticle.SMOKE_NORMAL; + } + + for (int i = 0; i < 7; ++i) { + double d0 = this.random.nextGaussian() * 0.02D; + double d1 = this.random.nextGaussian() * 0.02D; + double d2 = this.random.nextGaussian() * 0.02D; + + this.world.addParticle(enumparticle, this.locX + (double) (this.random.nextFloat() * this.width * 2.0F) - (double) this.width, this.locY + 0.5D + (double) (this.random.nextFloat() * this.length), this.locZ + (double) (this.random.nextFloat() * this.width * 2.0F) - (double) this.width, d0, d1, d2, new int[0]); + } + + } + + public boolean isTamed() { + return (this.datawatcher.getByte(16) & 4) != 0; + } + + public void setTamed(boolean flag) { + byte b0 = this.datawatcher.getByte(16); + + if (flag) { + this.datawatcher.watch(16, Byte.valueOf((byte) (b0 | 4))); + } else { + this.datawatcher.watch(16, Byte.valueOf((byte) (b0 & -5))); + } + + this.cm(); + } + + protected void cm() {} + + public boolean isSitting() { + return (this.datawatcher.getByte(16) & 1) != 0; + } + + public void setSitting(boolean flag) { + byte b0 = this.datawatcher.getByte(16); + + if (flag) { + this.datawatcher.watch(16, Byte.valueOf((byte) (b0 | 1))); + } else { + this.datawatcher.watch(16, Byte.valueOf((byte) (b0 & -2))); + } + + } + + public String getOwnerUUID() { + return this.datawatcher.getString(17); + } + + public void setOwnerUUID(String s) { + this.datawatcher.watch(17, s); + } + + public EntityLiving getOwner() { + try { + UUID uuid = FastUUID.parseUUID(this.getOwnerUUID()); + + return uuid == null ? null : this.world.b(uuid); + } catch (IllegalArgumentException illegalargumentexception) { + return null; + } + } + + public boolean e(EntityLiving entityliving) { + return entityliving == this.getOwner(); + } + + public PathfinderGoalSit getGoalSit() { + return this.bm; + } + + public boolean a(EntityLiving entityliving, EntityLiving entityliving1) { + return true; + } + + public ScoreboardTeamBase getScoreboardTeam() { + if (this.isTamed()) { + EntityLiving entityliving = this.getOwner(); + + if (entityliving != null) { + return entityliving.getScoreboardTeam(); + } + } + + return super.getScoreboardTeam(); + } + + public boolean c(EntityLiving entityliving) { + if (this.isTamed()) { + EntityLiving entityliving1 = this.getOwner(); + + if (entityliving == entityliving1) { + return true; + } + + if (entityliving1 != null) { + return entityliving1.c(entityliving); + } + } + + return super.c(entityliving); + } + + public void die(DamageSource damagesource) { + if (!this.world.isClientSide && this.world.getGameRules().getBoolean("showDeathMessages") && this.hasCustomName() && this.getOwner() instanceof EntityPlayer) { + ((EntityPlayer) this.getOwner()).sendMessage(this.bs().b()); + } + + super.die(damagesource); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityThrownExpBottle.java b/azurite-server/src/main/java/net/minecraft/server/EntityThrownExpBottle.java new file mode 100644 index 0000000..1b5cfc1 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityThrownExpBottle.java @@ -0,0 +1,53 @@ +package net.minecraft.server; + +public class EntityThrownExpBottle extends EntityProjectile { + + public EntityThrownExpBottle(World world) { + super(world); + } + + public EntityThrownExpBottle(World world, EntityLiving entityliving) { + super(world, entityliving); + } + + public EntityThrownExpBottle(World world, double d0, double d1, double d2) { + super(world, d0, d1, d2); + } + + protected float m() { + return 0.07F; + } + + protected float j() { + return 0.7F; + } + + protected float l() { + return -20.0F; + } + + protected void a(MovingObjectPosition movingobjectposition) { + + // CraftBukkit - moved to after event + // this.world.triggerEffect(2002, new BlockPosition(this), 0); + int i = 3 + this.world.random.nextInt(5) + this.world.random.nextInt(5); + + // CraftBukkit start + org.bukkit.event.entity.ExpBottleEvent event = org.bukkit.craftbukkit.event.CraftEventFactory.callExpBottleEvent(this, i); + i = event.getExperience(); + if (event.getShowEffect()) { + this.world.triggerEffect(2002, new BlockPosition(this), 0); + } + // CraftBukkit end + + while (i > 0) { + int j = EntityExperienceOrb.getOrbValue(i); + + i -= j; + this.world.addEntity(new EntityExperienceOrb(this.world, this.locX, this.locY, this.locZ, j)); + } + + this.die(); + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityTracker.java b/azurite-server/src/main/java/net/minecraft/server/EntityTracker.java new file mode 100644 index 0000000..62c30e4 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityTracker.java @@ -0,0 +1,179 @@ +package net.minecraft.server; + +import dev.azurite.spigot.Azurite; +import dev.azurite.spigot.configs.AzuriteConfig; +import dev.azurite.spigot.optimizations.ObjectMapList; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.spigotmc.AsyncCatcher; +import org.spigotmc.TrackingRange; + +import java.util.function.Predicate; + +public class EntityTracker { + private static final Logger a = LogManager.getLogger(); + + private final ObjectMapList c = new ObjectMapList<>(EntityTrackerEntry.class); + public final IntHashMap trackedEntities = new IntHashMap<>(); + private final WorldServer world; // Vortex - obf helper + private final int e; + + public EntityTracker(WorldServer worldserver) { + this.world = worldserver; + this.e = 128; + } + + public void track(Entity entity) { + if (entity instanceof EntityPlayer) { + addEntity(entity, 512, AzuriteConfig.trackerTicks.getValue()); + } else if (entity instanceof EntityFishingHook) { + addEntity(entity, 64, Integer.MAX_VALUE, false); // Beanes - smooth rods + } else if (entity instanceof EntityPotion) { + addEntity(entity, 64, Integer.MAX_VALUE, false); // Azurite - don't update short-lived projectiles as it only makes them look worse + } else if (entity instanceof EntityEnderPearl) { + addEntity(entity, 64, Integer.MAX_VALUE, false); // Azurite - don't update short-lived projectiles as it only makes them look worse + } else if (entity instanceof EntityArrow) { + addEntity(entity, 64, Integer.MAX_VALUE, false); // Azurite - don't update short-lived projectiles as it only makes them look worse + } else if (entity instanceof EntitySmallFireball) { + addEntity(entity, 64, 10, false); + } else if (entity instanceof EntityFireball) { + addEntity(entity, 64, 10, false); + } else if (entity instanceof EntitySnowball) { + addEntity(entity, 64, Integer.MAX_VALUE, false); // Azurite - don't update short-lived projectiles as it only makes them look worse + } else if (entity instanceof EntityEnderSignal) { + addEntity(entity, 64, 4, true); + } else if (entity instanceof EntityEgg) { + addEntity(entity, 64, Integer.MAX_VALUE, false); // Azurite - don't update short-lived projectiles as it only makes them look worse + } else if (entity instanceof EntityThrownExpBottle) { + addEntity(entity, 64, 10, true); + } else if (entity instanceof EntityFireworks) { + addEntity(entity, 64, 10, true); + } else if (entity instanceof EntityItem) { + addEntity(entity, 64, 20, true); + } else if (entity instanceof EntityMinecartAbstract) { + addEntity(entity, 80, 3, true); + } else if (entity instanceof EntityBoat) { + addEntity(entity, 80, 3, true); + } else if (entity instanceof EntitySquid) { + addEntity(entity, 64, 3, true); + } else if (entity instanceof EntityWither) { + addEntity(entity, 80, 3, false); + } else if (entity instanceof EntityBat) { + addEntity(entity, 80, 3, false); + } else if (entity instanceof EntityEnderDragon) { + addEntity(entity, 160, 3, true); + } else if (entity instanceof IAnimal) { + addEntity(entity, 80, 3, true); + } else if (entity instanceof EntityTNTPrimed) { + addEntity(entity, 160, 10, true); + } else if (entity instanceof EntityFallingBlock) { + addEntity(entity, 160, 20, true); + } else if (entity instanceof EntityHanging) { + addEntity(entity, 160, Integer.MAX_VALUE, false); + } else if (entity instanceof EntityArmorStand) { + addEntity(entity, 160, 3, true); + } else if (entity instanceof EntityExperienceOrb) { + addEntity(entity, 160, 20, true); + } else if (entity instanceof EntityEnderCrystal) { + addEntity(entity, 256, Integer.MAX_VALUE, false); + } + } + + public void addEntity(Entity entity, int trackingRange, int updateFrequency) { + addEntity(entity, trackingRange, updateFrequency, false); + } + + public void addEntity(Entity entity, int trackingRange, int trackingFrequency, boolean flag) { + if (AzuriteConfig.hideSandEntity.getValue() && entity instanceof EntityFallingBlock || AzuriteConfig.hideTntEntity.getValue() && entity instanceof EntityTNTPrimed) { + return; + } + + AsyncCatcher.catchOp("entity track"); + trackingRange = TrackingRange.getEntityTrackingRange(entity, trackingRange); + if (trackingRange > e) + trackingRange = e; + + try { + if (trackedEntities.b(entity.getId())) + throw new IllegalStateException("Entity is already tracked!"); + + EntityTrackerEntry entitytrackerentry = entity.getEntry(trackingRange, trackingFrequency, flag); + trackedEntities.a(entity.getId(), entitytrackerentry); + c.add(entitytrackerentry); + entitytrackerentry.addNearPlayers(-1, true); // Azurite + + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.a(throwable, "Adding entity to track"); + CrashReportSystemDetails crashreportsystemdetails = crashreport.a("Entity To Track"); + crashreportsystemdetails.a("Tracking range", trackingRange + " blocks"); + final int finalI = trackingRange; + crashreportsystemdetails.a("Update interval", () -> { + String s = "Once per " + finalI + " ticks"; + if (finalI == Integer.MAX_VALUE) + s = "Maximum (" + s + ")"; + return s; + }); + entity.appendEntityCrashDetails(crashreportsystemdetails); + CrashReportSystemDetails crashreportsystemdetails1 = crashreport.a("Entity That Is Already Tracked"); + trackedEntities.get(entity.getId()).tracker.appendEntityCrashDetails(crashreportsystemdetails1); + try { + throw new ReportedException(crashreport); + } catch (ReportedException reportedexception) { + a.error("\"Silently\" catching entity tracking error.", reportedexception); + } + } + } + + public void untrackEntity(Entity entity) { + AsyncCatcher.catchOp("entity untrack"); + if (entity instanceof EntityPlayer) { + EntityPlayer entityplayer = (EntityPlayer) entity; + for (EntityTrackerEntry entitytrackerentry : c) { + entitytrackerentry.clear(entityplayer); + } + } + EntityTrackerEntry entitytrackerentry1 = trackedEntities.d(entity.getId()); + if (entitytrackerentry1 != null) { + c.remove(entitytrackerentry1); + entitytrackerentry1.a(); + } + } + + public void updatePlayers() { + Azurite.getInstance().getThreadingManager().getTrackerExecutor().updatePlayers(c); // Azurite + } + + public void a(EntityPlayer entityplayer) { // void B() EntityPlayer + } + + public void a(EntityPlayer entityplayer, Chunk chunk) { + for (EntityTrackerEntry entitytrackerentry : this.c) { + if (entitytrackerentry.tracker != entityplayer && entitytrackerentry.tracker.ae == chunk.locX && entitytrackerentry.tracker.ag == chunk.locZ) + entitytrackerentry.updatePlayer(entityplayer); + } + } + + public void a(Entity entity, Packet packet) { + EntityTrackerEntry entitytrackerentry = trackedEntities.get(entity.getId()); + if (entitytrackerentry != null) + entitytrackerentry.broadcast(packet); + } + + public void sendPacketToEntity(Entity entity, Packet packet) { + EntityTrackerEntry entitytrackerentry = trackedEntities.get(entity.getId()); + if (entitytrackerentry != null) + entitytrackerentry.broadcastIncludingSelf(packet); + } + + public void broadcastWithPredicate(Entity entity, Packet packet, Predicate predicate) { + EntityTrackerEntry entitytrackerentry = trackedEntities.get(entity.getId()); + if (entitytrackerentry != null) + entitytrackerentry.broadcastWithPredicate(packet, predicate); + } + + public void untrackPlayer(EntityPlayer entityplayer) { + for (EntityTrackerEntry entitytrackerentry : this.c) { + entitytrackerentry.clear(entityplayer); + } + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityTrackerEntry.java b/azurite-server/src/main/java/net/minecraft/server/EntityTrackerEntry.java new file mode 100644 index 0000000..9e2c9c1 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityTrackerEntry.java @@ -0,0 +1,610 @@ +package net.minecraft.server; + +import dev.azurite.spigot.Azurite; +import dev.azurite.spigot.configs.AzuriteConfig; +import dev.azurite.spigot.optimizations.ObjectMapList; +import dev.azurite.spigot.optimizations.PlayerMap; +import org.bukkit.Bukkit; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.function.Predicate; + +public class EntityTrackerEntry { + + public final Entity tracker; + public final Set trackedPlayers = new ObjectMapList<>(EntityPlayer.class); // Azurite - Object Map List faster iteration + public final ObjectMapList trackedPlayersMapList = (ObjectMapList) trackedPlayers; // Renaming above to object map list breaks compat with many plugins + protected final boolean u; // Send velocity updates + private final int addRemoveRate; + public int b; // Range + public int c; // Update frequency + public int xLoc; + public int yLoc; + public int zLoc; + public int yRot; + public int xRot; + public int i; // Head yaw + public double j; // motX + public double k; // motY + public double l; // motZ + public int m; // tracked ticks + public boolean n; + public int addRemoveCooldown; // Azurite -> public + protected double q; // x + protected double r; // y + protected double s; // z + protected boolean isMoving; + protected int v; // Ticks since last forced teleport + protected Entity w; // Vehicle + protected boolean x; // Is riding in vehicle + protected boolean y; // onGround + protected boolean npcEntity; // Whether the tracker entry is a npc + + public EntityTrackerEntry(Entity entity, int b, int c, boolean flag) { + tracker = entity; + this.b = b; + this.c = c; + this.u = flag; + this.xLoc = (int) Math.round(entity.locX * 32.0D); + this.yLoc = (int) Math.round(entity.locY * 32.0D); + this.zLoc = (int) Math.round(entity.locZ * 32.0D); + this.yRot = Math.round(entity.yaw * 256.0F / 360.0F); + this.xRot = Math.round(entity.pitch * 256.0F / 360.0F); + this.i = Math.round(entity.getHeadRotation() * 256.0F / 360.0F); + + if (this.tracker instanceof EntityArrow || this.tracker instanceof EntityProjectile) { + this.addRemoveRate = 5; // projectile things + } else if (this.tracker instanceof EntityPlayer) { + this.addRemoveRate = 5; // players + } else { + this.addRemoveRate = 10; // default + } + this.addRemoveCooldown = this.tracker.getId() % addRemoveRate; + this.npcEntity = Bukkit.getPlayer(entity.getUniqueID()) == null; + } + + @Override + public boolean equals(Object object) { + return object instanceof EntityTrackerEntry && ((EntityTrackerEntry) object).tracker.getId() == this.tracker.getId(); + } + + @Override + public int hashCode() { + return this.tracker.getId(); + } + + public void update(int trackerThread) { + if (--this.addRemoveCooldown <= 0) { + this.removeFarPlayers(); + this.addNearPlayers(trackerThread, false); + this.addRemoveCooldown = this.addRemoveRate; + } + + this.track(null, trackerThread); + } + + private void removeFarPlayers() { + if (withinNoTrack()) { + for (int index = 0; index < trackedPlayersMapList.count; index++) { + EntityPlayer player = trackedPlayersMapList.elements[index]; + + if (player != tracker) { + player.playerConnection.writePacketLazily(new PacketPlayOutEntityDestroy(tracker.getId())); + } + } + trackedPlayers.clear(); + } else { + for (int index = trackedPlayersMapList.count - 1; index >= 0; index--) { + EntityPlayer player = trackedPlayersMapList.elements[index]; + + if (!c(player)) { + trackedPlayersMapList.remove(index); + player.playerConnection.writePacketLazily(new PacketPlayOutEntityDestroy(tracker.getId())); // Azurite - Write lazily to keep order of packets + } + } + } + } + + public void addNearPlayers(int trackerThread, boolean immediate) { + if (withinNoTrack()) { + return; + } + + double distance = this.getRange(); + + for (int chunkX = MathHelper.floor(this.tracker.locX - distance) >> PlayerMap.CHUNK_BITS; chunkX <= MathHelper.floor(this.tracker.locX + distance) >> PlayerMap.CHUNK_BITS; chunkX++) { + for (int chunkZ = MathHelper.floor(this.tracker.locZ - distance) >> PlayerMap.CHUNK_BITS; chunkZ <= MathHelper.floor(this.tracker.locZ + distance) >> PlayerMap.CHUNK_BITS; chunkZ++) { + ObjectMapList players = this.tracker.world.playerMap.map.get(PlayerMap.xzToKey(chunkX, chunkZ)); + + if (players != null) { + for (int index = 0; index < players.count; index++) { + EntityPlayer player = players.elements[index]; + + if (player != tracker) { + updatePlayer(player, trackerThread, immediate); + } + } + } + } + } + } + + private boolean withinNoTrack() { + if (!(tracker instanceof EntityPlayer)) return false; // ensure all non-players are always tracked + if (npcEntity) return false; // Ensure NPC entities are tracked. + + int noTrack = Azurite.getInstance().getNoTrackRange(); + if (noTrack == 0) { + return false; + } + + double xDist = tracker.locX * tracker.locX; + double zDist = tracker.locZ * tracker.locZ; + int noTrackDist = noTrack * noTrack; + return xDist <= noTrackDist && zDist <= noTrackDist; + } + + public void track(List list, int trackerThread) { + Packet vehicleUpdate = null; + Packet movementPacketUpdate = null; + Packet velocityPacketUpdate = null; + Packet dataUpdate = null; + Packet headYawUpdate = null; + + this.n = false; + + if (!this.isMoving || this.tracker.e(this.q, this.r, this.s) > 16.0D) { + this.q = this.tracker.locX; + this.r = this.tracker.locY; + this.s = this.tracker.locZ; + this.isMoving = true; + this.n = true; + } + + if (this.w != this.tracker.vehicle || this.tracker.vehicle != null && this.m % 60 == 0) { + this.w = this.tracker.vehicle; + vehicleUpdate = new PacketPlayOutAttachEntity(0, tracker, tracker.vehicle); + } + + if (this.tracker instanceof EntityItemFrame /*&& this.m % 10 == 0*/) { // CraftBukkit - Moved below, should always enter this block + EntityItemFrame entityitemframe = (EntityItemFrame) this.tracker; + ItemStack itemstack = entityitemframe.getItem(); + + if (this.m % 10 == 0 && itemstack != null && itemstack.getItem() instanceof ItemWorldMap) { // CraftBukkit - Moved this.m % 10 logic here so item frames do not enter the other blocks + WorldMap worldmap = Items.FILLED_MAP.getSavedMap(itemstack, this.tracker.world); + // CraftBukkit + + for (EntityPlayer entityplayer : this.trackedPlayers) { + worldmap.a(entityplayer, itemstack); + Packet packet = Items.FILLED_MAP.c(itemstack, this.tracker.world, entityplayer); + + if (packet != null) { + entityplayer.playerConnection.queueEntityTrackerPacket(packet, trackerThread); + } + } + } + } + + boolean projectile = this.tracker instanceof EntityArrow || (this.tracker instanceof EntityFishingHook && this.c == Integer.MAX_VALUE) || this.tracker instanceof EntityProjectile; + if (this.m % this.c == 0 || this.tracker.ai || projectile) { + int newEncodedX = (int) Math.round(tracker.locX * 32.0D); + int newEncodedY = (int) Math.round(tracker.locY * 32.0D); + int newEncodedZ = (int) Math.round(tracker.locZ * 32.0D); + + if (this.tracker.vehicle == null) { + ++this.v; + int newEncodedYaw = Math.round(tracker.yaw * 256.0F / 360.0F); + int newEncodedPitch = Math.round(tracker.pitch * 256.0F / 360.0F); + int encodedDeltaX = newEncodedX - this.xLoc; + int encodedDeltaY = newEncodedY - this.yLoc; + int encodedDeltaZ = newEncodedZ - this.zLoc; + + int trackerAccuracy = Math.min(Math.max(AzuriteConfig.trackerDeltaAccuracy.getValue(), 1), 4); + boolean posChanged = Math.abs(encodedDeltaX) >= trackerAccuracy || Math.abs(encodedDeltaY) >= trackerAccuracy || Math.abs(encodedDeltaZ) >= trackerAccuracy || (tracker instanceof EntityItem && this.m % 60 == 0); + boolean rotChanged = Math.abs(newEncodedYaw - this.yRot) >= trackerAccuracy || Math.abs(newEncodedPitch - this.xRot) >= trackerAccuracy; + + if (this.m > 0 && !(projectile)) { + if (posChanged) { + this.xLoc = newEncodedX; + this.yLoc = newEncodedY; + this.zLoc = newEncodedZ; + } + + if (rotChanged) { + this.yRot = newEncodedYaw; + this.xRot = newEncodedPitch; + } + + if (encodedDeltaX >= -128 && encodedDeltaX < 128 && encodedDeltaY >= -128 && encodedDeltaY < 128 && encodedDeltaZ >= -128 && encodedDeltaZ < 128 && this.v <= 400 && !this.x && this.y == this.tracker.onGround && !(this.tracker instanceof EntityFishingHook)) { + if (!posChanged || !rotChanged) { + if (posChanged) { + movementPacketUpdate = new PacketPlayOutEntity.PacketPlayOutRelEntityMove(this.tracker.getId(), (byte) encodedDeltaX, (byte) encodedDeltaY, (byte) encodedDeltaZ, this.tracker.onGround); + } else if (rotChanged) { + movementPacketUpdate = new PacketPlayOutEntity.PacketPlayOutEntityLook(this.tracker.getId(), (byte) newEncodedYaw, (byte) newEncodedPitch, this.tracker.onGround); + } + } else { + movementPacketUpdate = new PacketPlayOutEntity.PacketPlayOutRelEntityMoveLook(this.tracker.getId(), (byte) encodedDeltaX, (byte) encodedDeltaY, (byte) encodedDeltaZ, (byte) newEncodedYaw, (byte) newEncodedPitch, this.tracker.onGround); + } + } else { + this.y = this.tracker.onGround; + this.v = 0; + movementPacketUpdate = new PacketPlayOutEntityTeleport(this.tracker.getId(), newEncodedX, newEncodedY, newEncodedZ, (byte) newEncodedYaw, (byte) newEncodedPitch, this.tracker.onGround); + } + } else if (projectile) { + if (posChanged) { + this.xLoc = newEncodedX; + this.yLoc = newEncodedY; + this.zLoc = newEncodedZ; + } + + if (rotChanged) { + this.yRot = newEncodedYaw; + this.xRot = newEncodedPitch; + } + } + + if (this.u) { + double d0 = this.tracker.motX - this.j; + double d1 = this.tracker.motY - this.k; + double d2 = this.tracker.motZ - this.l; + double d3 = 0.02D; + double d4 = d0 * d0 + d1 * d1 + d2 * d2; + + if (d4 > d3 * d3 || d4 > 0.0D && this.tracker.motX == 0.0D && this.tracker.motY == 0.0D && this.tracker.motZ == 0.0D) { + this.j = this.tracker.motX; + this.k = this.tracker.motY; + this.l = this.tracker.motZ; + velocityPacketUpdate = new PacketPlayOutEntityVelocity(this.tracker.getId(), this.j, this.k, this.l); + } + } + this.x = false; + + } else { + // We have a vehicle only send yaw & pitch + int encodedYaw = Math.round(tracker.yaw * 256.0F / 360.0F); + int encodedPitch = Math.round(tracker.pitch * 256.0F / 360.0F); + if (Math.abs(encodedYaw - this.yRot) >= 4 || Math.abs(encodedPitch - this.xRot) >= 4) { + movementPacketUpdate = new PacketPlayOutEntity.PacketPlayOutEntityLook(tracker.getId(), (byte) encodedYaw, (byte) encodedPitch, tracker.onGround); + this.yRot = encodedYaw; + this.xRot = encodedPitch; + } + + this.xLoc = newEncodedX; + this.yLoc = newEncodedY; + this.zLoc = newEncodedZ; + this.x = true; + } + + int encodedHeadRotation = Math.round(this.tracker.getHeadRotation() * 256.0F / 360.0F); + if (Math.abs(encodedHeadRotation - this.i) >= 1 && !projectile) { + headYawUpdate = new PacketPlayOutEntityHeadRotation(tracker, (byte) encodedHeadRotation); + this.i = encodedHeadRotation; + } + + tracker.ai = false; + } + + ++this.m; + + DataWatcher datawatcher = tracker.getDataWatcher(); + + // If metadata is changed, broadcast it + if (datawatcher.a()) { + dataUpdate = new PacketPlayOutEntityMetadata(tracker.getId(), datawatcher.b()); + } + + if (tracker instanceof EntityLiving) { + // Azurite - only send useful attributes + AttributeMapServer attributemapserver = (AttributeMapServer) ((EntityLiving) this.tracker).getAttributeMap(); + Set updatedAttributes = attributemapserver.getAttributes(); + + // Only send attributes if the player is riding + if (this.tracker.passenger instanceof EntityPlayer) { + List usefulAttributes = new ArrayList<>(); + + for (AttributeInstance updatedAttribute : updatedAttributes) { + // Azurite - Movement speed is only useful for horses + if (updatedAttribute.getAttribute() == GenericAttributes.MOVEMENT_SPEED && !(this.tracker instanceof EntityHorse)) { + continue; + } + + usefulAttributes.add(updatedAttribute); + } + + if (!updatedAttributes.isEmpty()) { + // MineHQ - Beanes - only send attribute changes to passenger + ((EntityPlayer) this.tracker.passenger).playerConnection.queueEntityTrackerPacket(new PacketPlayOutUpdateAttributes(this.tracker.getId(), usefulAttributes), trackerThread); + } + } + updatedAttributes.clear(); + } + + if (this.tracker.velocityChanged) { + velocityPacketUpdate = new PacketPlayOutEntityVelocity(this.tracker); + this.tracker.velocityChanged = false; + } + + if (vehicleUpdate != null || movementPacketUpdate != null || velocityPacketUpdate != null || dataUpdate != null || headYawUpdate != null) { + this.queueToWatchers(trackerThread, vehicleUpdate, movementPacketUpdate, velocityPacketUpdate, dataUpdate, headYawUpdate); + } + } + + public void broadcast(Packet packet) { + for (EntityPlayer p : trackedPlayers) { + p.playerConnection.sendPacket(packet); + } + } + + // Beanes - optimized way to queue packets + private void queueToWatchers(int trackerThread, Packet a, Packet b, Packet c, Packet d, Packet e) { + for (int i = 0; i < trackedPlayersMapList.count; i++) { + List> queue = trackedPlayersMapList.elements[i].trackerQueueRef[trackerThread]; + + if (a != null) { + queue.add(a); + } + + if (b != null) { + queue.add(b); + } + + if (c != null) { + queue.add(c); + } + + if (d != null) { + queue.add(d); + } + + if (e != null) { + queue.add(e); + } + } + } + + public void queueBroadcastTracked(Packet packet, int trackerThread) { + for (int index = 0; index < trackedPlayersMapList.count; index++) { + EntityPlayer player = trackedPlayersMapList.elements[index]; + player.playerConnection.queueEntityTrackerPacket(packet, trackerThread); + } + } + + public void broadcastIncludingSelf(Packet packet) { + this.broadcast(packet); + } + + public void broadcastWithPredicate(Packet packet, Predicate predicate) { + for (EntityPlayer p : trackedPlayers) { + if (predicate.test(p)) { + p.playerConnection.sendPacket(packet); + } + } + } + + public void a() { + for (EntityPlayer p : trackedPlayers) { + p.d(tracker); + } + } + + public void updatePlayer(EntityPlayer entityplayer, int trackerThread, boolean immediate) { + if (!c(entityplayer)) { + if (trackedPlayers.remove(entityplayer)) entityplayer.d(tracker); + return; + } + + if (!trackedPlayers.contains(entityplayer) && (e(entityplayer) || tracker.attachedToPlayer)) { + if (!entityplayer.canSee(tracker)) + return; + + trackedPlayers.add(entityplayer); + + Packet packet = getSpawnPacketFixed(this.xLoc, this.yLoc, this.zLoc, this.yRot, this.xRot); // Beanes - better spawn packet + + if (packet == null) // Vortex - Don't send packet if the entity is died + return; + + List> queue = immediate ? new ArrayList<>(10) : entityplayer.trackerQueueRef[trackerThread]; + queue.add(packet); + int id = tracker.getId(); + + if (!tracker.getDataWatcher().d()) + queue.add(new PacketPlayOutEntityMetadata(id, tracker.getDataWatcher(), true)); + + j = tracker.motX; + k = tracker.motY; + l = tracker.motZ; + + // Beanes - only send these motions one time + boolean oneTimeMotion = this.tracker instanceof EntityFishingHook + || this.tracker instanceof EntityPotion + || this.tracker instanceof EntityEnderPearl + || this.tracker instanceof EntitySnowball + || this.tracker instanceof EntityEgg; + + if ((u && !(packet instanceof PacketPlayOutSpawnEntityLiving)) || oneTimeMotion) + queue.add(new PacketPlayOutEntityVelocity(id, tracker.motX, tracker.motY, tracker.motZ)); + + if (tracker instanceof EntityLiving) { + EntityLiving entityliving = (EntityLiving) tracker; + + for (int i = 0; i < 5; i++) { + ItemStack itemstack = entityliving.getEquipment(i); + if (itemstack != null) + queue.add(new PacketPlayOutEntityEquipment(id, i, itemstack, AzuriteConfig.obfuscateEntityEquipment.getValue())); + } + + if (tracker instanceof EntityInsentient && ((EntityInsentient) tracker).getLeashHolder() != null) + queue.add(new PacketPlayOutAttachEntity(1, tracker, ((EntityInsentient) tracker).getLeashHolder())); + + queue.add(new PacketPlayOutEntityHeadRotation(tracker, (byte) (this.i = Math.round(tracker.getHeadRotation() * 256.0F / 360.0F)))); // Beanes - round + } + + if (tracker.vehicle != null) + queue.add(new PacketPlayOutAttachEntity(0, tracker, tracker.vehicle)); + + if (immediate) { + entityplayer.playerConnection.sendPackets(queue); + } + } + } + + protected boolean e(EntityPlayer entityplayer) { + return entityplayer.u().getPlayerChunkMap().a(entityplayer, tracker.ae, tracker.ag); + } + + protected Packet c() { + int encodedX = (int) Math.round(tracker.locX * 32.0D); + int encodedY = (int) Math.round(tracker.locY * 32.0D); + int encodedZ = (int) Math.round(tracker.locZ * 32.0D); + int encodedYaw = Math.round(tracker.yaw * 256.0F / 360.0F); + int encodedPitch = Math.round(tracker.pitch * 256.0F / 360.0F); + return getSpawnPacketFixed(encodedX, encodedY, encodedZ, encodedYaw, encodedPitch); + } + + // Beanes - a method that return s spawn packet with the tracker last used position + // If we used the actual entity position then the next tracker update would be out of sync as we don't know how much "delta" movement has already been sent + // Paper fixes this by sending an absolute teleport but that adds an extra performance cost, this is faster + // Also player check is removed here as that is not used + protected Packet getSpawnPacketFixed(int xLoc, int yLoc, int zLoc, int yRot, int xRot) { + if (tracker.dead) { + return null; + } else if (tracker instanceof EntityPlayer) { + return new PacketPlayOutNamedEntitySpawn((EntityHuman) tracker, xLoc, yLoc, zLoc, yRot, xRot); + } else if (tracker instanceof EntityItem) { + return new PacketPlayOutSpawnEntity(tracker, 2, 1, xLoc, yLoc, zLoc, yRot, xRot); + } else if (tracker instanceof EntityPotion) { + return new PacketPlayOutSpawnEntity(tracker, 73, ((EntityPotion) tracker).getPotionValue(), xLoc, yLoc, zLoc, yRot, xRot); + } else if (tracker instanceof EntityArrow) { + Entity entity = ((EntityArrow) tracker).shooter; + return new PacketPlayOutSpawnEntity(tracker, 60, entity != null ? entity.getId() : tracker.getId(), xLoc, yLoc, zLoc, yRot, xRot); + } else if (tracker instanceof EntityFishingHook) { + EntityHuman entityhuman = ((EntityFishingHook) tracker).owner; + return new PacketPlayOutSpawnEntity(tracker, 90, entityhuman != null ? entityhuman.getId() : tracker.getId(), xLoc, yLoc, zLoc, yRot, xRot); + } else if (tracker instanceof EntityEnderPearl) { + return new PacketPlayOutSpawnEntity(tracker, 65, 0, xLoc, yLoc, zLoc, yRot, xRot); + } else if (tracker instanceof EntityMinecartAbstract) { + EntityMinecartAbstract entityminecartabstract = (EntityMinecartAbstract) tracker; + return new PacketPlayOutSpawnEntity(tracker, 10, entityminecartabstract.s().a(), xLoc, yLoc, zLoc, yRot, xRot); + } else if (tracker instanceof EntityBoat) { + return new PacketPlayOutSpawnEntity(tracker, 1, 0, xLoc, yLoc, zLoc, yRot, xRot); + } else if (tracker instanceof IAnimal) { + return new PacketPlayOutSpawnEntityLiving((EntityLiving) tracker, xLoc, yLoc, zLoc, yRot, xRot, this.i); + } else if (tracker instanceof EntitySnowball) { + return new PacketPlayOutSpawnEntity(tracker, 61, 0, xLoc, yLoc, zLoc, yRot, xRot); + } else if (tracker instanceof EntityThrownExpBottle) { + return new PacketPlayOutSpawnEntity(tracker, 75, 0, xLoc, yLoc, zLoc, yRot, xRot); + } else if (tracker instanceof EntityEnderSignal) { + return new PacketPlayOutSpawnEntity(tracker, 72, 0, xLoc, yLoc, zLoc, yRot, xRot); + } else if (tracker instanceof EntityTNTPrimed) { + return new PacketPlayOutSpawnEntity(tracker, 50, 0, xLoc, yLoc, zLoc, yRot, xRot); + } else if (tracker instanceof EntityFallingBlock) { + EntityFallingBlock entityfallingblock = (EntityFallingBlock) tracker; + return new PacketPlayOutSpawnEntity(tracker, 70, Block.getCombinedId(entityfallingblock.getBlock()), xLoc, yLoc, zLoc, yRot, xRot); + } else if (tracker instanceof EntityFireworks) { + return new PacketPlayOutSpawnEntity(tracker, 76, 0, xLoc, yLoc, zLoc, yRot, xRot); + } else { + PacketPlayOutSpawnEntity packetplayoutspawnentity; + + if (tracker instanceof EntityFireball) { + EntityFireball entityfireball = (EntityFireball) tracker; + + int type = 63; + + if (tracker instanceof EntitySmallFireball) { + type = 64; + } else if (tracker instanceof EntityWitherSkull) { + type = 66; + } + + if (entityfireball.shooter != null) { + packetplayoutspawnentity = new PacketPlayOutSpawnEntity(tracker, type, ((EntityFireball) tracker).shooter.getId(), xLoc, yLoc, zLoc, yRot, xRot); + } else { + packetplayoutspawnentity = new PacketPlayOutSpawnEntity(tracker, type, 0, xLoc, yLoc, zLoc, yRot, xRot); + } + + // Beanes - round + packetplayoutspawnentity.d((int) Math.round(entityfireball.dirX * 8000.0D)); + packetplayoutspawnentity.e((int) Math.round(entityfireball.dirY * 8000.0D)); + packetplayoutspawnentity.f((int) Math.round(entityfireball.dirZ * 8000.0D)); + return packetplayoutspawnentity; + } else if (tracker instanceof EntityEgg) { + return new PacketPlayOutSpawnEntity(tracker, 62, 0, xLoc, yLoc, zLoc, yRot, xRot); + } else if (tracker instanceof EntityEnderCrystal) { + return new PacketPlayOutSpawnEntity(tracker, 51, 0, xLoc, yLoc, zLoc, yRot, xRot); + } else if (tracker instanceof EntityArmorStand) { + return new PacketPlayOutSpawnEntity(tracker, 78, 0, xLoc, yLoc, zLoc, yRot, xRot); + } else if (tracker instanceof EntityPainting) { + return new PacketPlayOutSpawnEntityPainting((EntityPainting) tracker); + } else { + if (tracker instanceof EntityItemFrame) { + EntityItemFrame frame = (EntityItemFrame) tracker; + BlockPosition blockposition = frame.getBlockPosition(); + packetplayoutspawnentity = new PacketPlayOutSpawnEntity(tracker, 71, frame.direction.b(), + MathHelper.d((float) (blockposition.getX() * 32)), + MathHelper.d((float) (blockposition.getY() * 32)), + MathHelper.d((float) (blockposition.getZ() * 32)), + Math.round(tracker.pitch * 256.0F / 360.0F), + Math.round(tracker.yaw * 256.0F / 360.0F) + ); + + return packetplayoutspawnentity; + } else if (tracker instanceof EntityLeash) { + EntityLeash leash = (EntityLeash) tracker; + BlockPosition blockposition = leash.getBlockPosition(); + packetplayoutspawnentity = new PacketPlayOutSpawnEntity(tracker, 77, 0, + MathHelper.d((float) (blockposition.getX() * 32)), + MathHelper.d((float) (blockposition.getY() * 32)), + MathHelper.d((float) (blockposition.getZ() * 32)), + Math.round(tracker.pitch * 256.0F / 360.0F), + Math.round(tracker.yaw * 256.0F / 360.0F) + ); + return packetplayoutspawnentity; + } else if (tracker instanceof EntityExperienceOrb) { + return new PacketPlayOutSpawnEntityExperienceOrb((EntityExperienceOrb) tracker, xLoc, yLoc, zLoc); + } else { + throw new IllegalArgumentException("Don't know how to add " + tracker.getClass() + "!"); + } + } + } + } + + public boolean c(EntityPlayer entityplayer) { + double d0 = entityplayer.locX - tracker.locX; + double d1 = entityplayer.locZ - tracker.locZ; + return d0 >= -b && d0 <= b && d1 >= -b && d1 <= b; + } + + public void clear(EntityPlayer entityplayer) { + if (trackedPlayers.remove(entityplayer)) { + entityplayer.d(tracker); + } + } + + // Vortex - obf helper + @SuppressWarnings("unused") + public void scanPlayers(List playerList) { + } + + // Azurite start - obf helpers + public void updatePlayer(EntityPlayer entityPlayer) { + if (entityPlayer != this.tracker) { + this.updatePlayer(entityPlayer, 3, true); + } + } + + @SuppressWarnings("unused") + public void track(List list) { + this.track(list, 3); + } + // Azurite end + + public int getRange() { + if (this.tracker.passenger == null) { + return this.b; + } + return Math.max(this.b, org.spigotmc.TrackingRange.getEntityTrackingRange(this.tracker.passenger, 0)); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityTrackerPlayerEntry.java b/azurite-server/src/main/java/net/minecraft/server/EntityTrackerPlayerEntry.java new file mode 100644 index 0000000..21c9ab8 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityTrackerPlayerEntry.java @@ -0,0 +1,286 @@ +package net.minecraft.server; + +import dev.azurite.spigot.Azurite; +import dev.azurite.spigot.configs.AzuriteConfig; +import org.bukkit.entity.Player; +import org.bukkit.event.player.PlayerVelocityEvent; +import org.bukkit.util.Vector; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.function.Predicate; + +public class EntityTrackerPlayerEntry extends EntityTrackerEntry { + + public EntityTrackerPlayerEntry(Entity entity, int b, int c, boolean flag) { + super(entity, b, c, flag); + } + + @Override + public void track(List list, int trackerThread) { + Packet vehicleUpdate = null; + Packet movementPacketUpdate = null; + Packet dataUpdate = null; + Packet headYawUpdate = null; + + // --- Check for vehicle updates --- + if (this.w != tracker.vehicle || tracker.vehicle != null && this.m % 60 == 0) { + this.w = tracker.vehicle; + vehicleUpdate = new PacketPlayOutAttachEntity(0, tracker, tracker.vehicle); + } + + // --- Check for movement updates --- + if (this.m % this.c == 0 || tracker.ai) { + int newEncodedX = (int) Math.round(tracker.locX * 32.0D); + int newEncodedY = (int) Math.round(tracker.locY * 32.0D); + int newEncodedZ = (int) Math.round(tracker.locZ * 32.0D); + + if (tracker.vehicle == null) { + ++this.v; + int newEncodedYaw = Math.round(tracker.yaw * 256.0F / 360.0F); + int newEncodedPitch = Math.round(tracker.pitch * 256.0F / 360.0F); + int encodedDeltaX = newEncodedX - this.xLoc; + int encodedDeltaY = newEncodedY - this.yLoc; + int encodedDeltaZ = newEncodedZ - this.zLoc; + + int trackerAccuracy = Math.min(Math.max(AzuriteConfig.trackerDeltaAccuracy.getValue(), 1), 4); + boolean posChanged = Math.abs(encodedDeltaX) >= trackerAccuracy || Math.abs(encodedDeltaY) >= trackerAccuracy || Math.abs(encodedDeltaZ) >= trackerAccuracy; + boolean rotChanged = Math.abs(newEncodedYaw - this.yRot) >= trackerAccuracy || Math.abs(newEncodedPitch - this.xRot) >= trackerAccuracy; + + if (this.m > 0) { // PaperSpigot - Moved up + if (posChanged) { + this.xLoc = newEncodedX; + this.yLoc = newEncodedY; + this.zLoc = newEncodedZ; + ((EntityPlayer) tracker).interpolationData.setNewTarget((double) newEncodedX / 32.0D, (double) newEncodedY / 32.0D, (double) newEncodedZ / 32.0D); + } + + if (rotChanged) { + this.yRot = newEncodedYaw; + this.xRot = newEncodedPitch; + } + + if (encodedDeltaX >= -128 && encodedDeltaX < 128 && encodedDeltaY >= -128 && encodedDeltaY < 128 && encodedDeltaZ >= -128 && encodedDeltaZ < 128 && this.v <= 150 && !this.x) { + if (posChanged && rotChanged) { + movementPacketUpdate = new PacketPlayOutEntity.PacketPlayOutRelEntityMoveLook(tracker.getId(), (byte) encodedDeltaX, (byte) encodedDeltaY, (byte) encodedDeltaZ, (byte) newEncodedYaw, (byte) newEncodedPitch, tracker.onGround); + } else { + if (posChanged) { + movementPacketUpdate = new PacketPlayOutEntity.PacketPlayOutRelEntityMove(tracker.getId(), (byte) encodedDeltaX, (byte) encodedDeltaY, (byte) encodedDeltaZ, tracker.onGround); + } else if (rotChanged) { + movementPacketUpdate = new PacketPlayOutEntity.PacketPlayOutEntityLook(tracker.getId(), (byte) newEncodedYaw, (byte) newEncodedPitch, tracker.onGround); + } + } + } else { + this.y = tracker.onGround; + this.v = 0; + movementPacketUpdate = new PacketPlayOutEntityTeleport(tracker.getId(), newEncodedX, newEncodedY, newEncodedZ, (byte) newEncodedYaw, (byte) newEncodedPitch, tracker.onGround); + } + } + + this.x = false; + } else { + // We have a vehicle only send yaw & pitch + int encodedYaw = Math.round(tracker.yaw * 256.0F / 360.0F); + int encodedPitch = Math.round(tracker.pitch * 256.0F / 360.0F); + if (Math.abs(encodedYaw - this.yRot) >= 4 || Math.abs(encodedPitch - this.xRot) >= 4) { + movementPacketUpdate = new PacketPlayOutEntity.PacketPlayOutEntityLook(tracker.getId(), (byte) encodedYaw, (byte) encodedPitch, tracker.onGround); + this.yRot = encodedYaw; + this.xRot = encodedPitch; + } + + this.xLoc = newEncodedX; + this.yLoc = newEncodedY; + this.zLoc = newEncodedZ; + this.x = true; + } + + int encodedHeadRotation = Math.round(this.tracker.getHeadRotation() * 256.0F / 360.0F); + if (Math.abs(encodedHeadRotation - this.i) >= 1) { + headYawUpdate = new PacketPlayOutEntityHeadRotation(tracker, (byte) encodedHeadRotation); + this.i = encodedHeadRotation; + } + + tracker.ai = false; + } + + ++this.m; + + // --- Check for datawatcher updates --- + if (tracker.getDataWatcher().a()) { + // We create 2 packets + // A normal packet: + // A modified packet: stripped health metadata so that people don't abuse health name tags + List changedMetadata = tracker.getDataWatcher().b(); + PacketPlayOutEntityMetadata selfPacket = new PacketPlayOutEntityMetadata(this.tracker.getId(), new ArrayList<>(changedMetadata)); + selfPacket.fixHealth(); + if (!AzuriteConfig.selfPotionParticles.getValue()) { + selfPacket.removePotionParticles(); + } + + if (Azurite.getInstance().getBetterSlowdown().handleEntityMetadata(tracker.getUniqueID(), selfPacket)) { + // Only send if needed + ((EntityPlayer) this.tracker).playerConnection.queueEntityTrackerPacket(selfPacket, trackerThread); + } + + + changedMetadata.removeIf(watchable -> watchable.a() == 6 && (float) watchable.b() > 0); + if (!changedMetadata.isEmpty()) { + dataUpdate = new PacketPlayOutEntityMetadata(this.tracker.getId(), changedMetadata); + } + } + + + // --- Check for attributes updates (only for self) --- + EntityPlayer entityPlayer = ((EntityPlayer) this.tracker); + Set changedAttributes = ((AttributeMapServer) entityPlayer.getAttributeMap()).getAttributes(); + if (!changedAttributes.isEmpty()) { + // CraftBukkit start - Send scaled max health + entityPlayer.getBukkitEntity().injectScaledMaxHealth(changedAttributes, false); + // CraftBukkit end + + // Azurite - only send player attributes to yourself + // Beanes - better slowdown + PacketPlayOutUpdateAttributes packet = new PacketPlayOutUpdateAttributes(tracker.getId(), changedAttributes); + if (Azurite.getInstance().getBetterSlowdown().handleAttributes(tracker.getUniqueID(), packet)) { + entityPlayer.playerConnection.queueEntityTrackerPacket(packet, trackerThread); + } + + changedAttributes.clear(); + } + + // --- Check for velocity updates (only for self) --- + if (tracker.velocityChanged) { + boolean cancelled = false; + + Player bukkitPlayer = (Player) tracker.getBukkitEntity(); + Vector velocity = bukkitPlayer.getVelocity(); + + PlayerVelocityEvent event = new PlayerVelocityEvent(bukkitPlayer, velocity); + tracker.world.getServer().getPluginManager().callEvent(event); + + if (event.isCancelled()) { + cancelled = true; + } else if (!velocity.equals(event.getVelocity())) { + bukkitPlayer.setVelocity(velocity); + } + + if (!cancelled) { + entityPlayer.playerConnection.queueEntityTrackerPacket(new PacketPlayOutEntityVelocity(tracker), trackerThread); + } + + tracker.velocityChanged = false; + } + + if (vehicleUpdate != null || movementPacketUpdate != null || dataUpdate != null || headYawUpdate != null) { + this.queueToWatchersPlayer(trackerThread, vehicleUpdate, movementPacketUpdate, dataUpdate, headYawUpdate); + } + } + + @Override + public void updatePlayer(EntityPlayer watcher, int trackerThread, boolean immediate) { + if (c(watcher)) { + if (!trackedPlayers.contains(watcher) && e(watcher)) { + EntityPlayer player = (EntityPlayer) tracker; + if (!watcher.getBukkitEntity().canSee(player.getBukkitEntity())) { + return; + } + + trackedPlayers.add(watcher); + + if (tracker.dead) { // Vortex - Don't send packet if the entity is died + return; + } + + List> queue = immediate ? new ArrayList<>(10) : watcher.trackerQueueRef[trackerThread]; + + // Beanes + // We need to set the spawn positions to the tracker last recorded position + // If we used the actual entity position then the next tracker update would be out of sync as we don't know how much "delta" movement has already been sent + // Paper fixes this by sending an absolute teleport but that adds an extra performance cost, this is faster + Packet packet = new PacketPlayOutNamedEntitySpawn(player, this.xLoc, this.yLoc, this.zLoc, this.yRot, this.xRot); + queue.add(packet); + + if (player.isSleeping()) { + queue.add(new PacketPlayOutBed(player, new BlockPosition(tracker))); + } + + int id = tracker.getId(); + + if (!tracker.getDataWatcher().d()) { + PacketPlayOutEntityMetadata meta = new PacketPlayOutEntityMetadata(id, tracker.getDataWatcher(), true); + if (tracker.isAlive()) meta.obfuscateHealth(); + queue.add(meta); + } + + EntityLiving livingEntity = (EntityLiving) tracker; + + for (int i = 0; i < 5; i++) { + ItemStack equipment = livingEntity.getEquipment(i); + if (equipment != null) { + queue.add(new PacketPlayOutEntityEquipment(id, i, equipment, AzuriteConfig.obfuscateEntityEquipment.getValue())); + } + } + + queue.add(new PacketPlayOutEntityHeadRotation(tracker, (byte) Math.round(tracker.getHeadRotation() * 256.0F / 360.0F))); + + if (tracker.vehicle != null) { + queue.add(new PacketPlayOutAttachEntity(0, tracker, tracker.vehicle)); + } + + if (immediate) { + watcher.playerConnection.sendPackets(queue); + } + } + } else if (trackedPlayers.remove(watcher)) { + watcher.d(tracker); + } + } + + @Override + public boolean c(EntityPlayer entityplayer) { + return super.c(entityplayer) && tracker.a(entityplayer); + } + + @Override + public void broadcastIncludingSelf(Packet packet) { + broadcast(packet); + ((EntityPlayer) tracker).playerConnection.sendPacket(packet); + } + + @Override + public void broadcastWithPredicate(Packet packet, Predicate predicate) { + if (predicate.test(((EntityPlayer) tracker))) { + ((EntityPlayer) tracker).playerConnection.sendPacket(packet); + } + + super.broadcastWithPredicate(packet, predicate); + } + + @Override + protected Packet c() { + return tracker.dead ? null : new PacketPlayOutNamedEntitySpawn((EntityHuman) tracker); + } + + private void queueToWatchersPlayer(int trackerThread, Packet a, Packet b, Packet c, Packet d) { + for (int i = 0; i < trackedPlayersMapList.count; i++) { + List> queue = trackedPlayersMapList.elements[i].trackerQueueRef[trackerThread]; + + if (a != null) { + queue.add(a); + } + + if (b != null) { + queue.add(b); + } + + if (c != null) { + queue.add(c); + } + + if (d != null) { + queue.add(d); + } + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityTypes.java b/azurite-server/src/main/java/net/minecraft/server/EntityTypes.java new file mode 100644 index 0000000..a65615a --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityTypes.java @@ -0,0 +1,241 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class EntityTypes { + + private static final Logger b = LogManager.getLogger(); + private static final Map> c = Maps.newHashMap(); + private static final Map, String> d = Maps.newHashMap(); + private static final Map> e = Maps.newHashMap(); + private static final Map, Integer> f = Maps.newHashMap(); + private static final Map g = Maps.newHashMap(); + public static final Map eggInfo = Maps.newLinkedHashMap(); + + private static void a(Class oclass, String s, int i) { + if (EntityTypes.c.containsKey(s)) { + throw new IllegalArgumentException("ID is already registered: " + s); + } else if (EntityTypes.e.containsKey(i)) { + throw new IllegalArgumentException("ID is already registered: " + i); + } else if (i == 0) { + throw new IllegalArgumentException("Cannot register to reserved id: " + i); + } else if (oclass == null) { + throw new IllegalArgumentException("Cannot register null clazz for id: " + i); + } else { + EntityTypes.c.put(s, oclass); + EntityTypes.d.put(oclass, s); + EntityTypes.e.put(i, oclass); + EntityTypes.f.put(oclass, i); + EntityTypes.g.put(s, i); + } + } + + private static void a(Class oclass, String s, int i, int j, int k) { + a(oclass, s, i); + EntityTypes.eggInfo.put(i, new EntityTypes.MonsterEggInfo(i, j, k)); + } + + public static Entity createEntityByName(String s, World world) { + Entity entity = null; + + try { + Class oclass = EntityTypes.c.get(s); + + if (oclass != null) { + entity = oclass.getConstructor(World.class).newInstance(world); + } + } catch (Exception exception) { + exception.printStackTrace(); + } + + return entity; + } + + public static Entity a(NBTTagCompound nbttagcompound, World world) { + Entity entity = null; + + if ("Minecart".equals(nbttagcompound.getString("id"))) { + nbttagcompound.setString("id", EntityMinecartAbstract.EnumMinecartType.a(nbttagcompound.getInt("Type")).b()); + nbttagcompound.remove("Type"); + } + + try { + Class oclass = EntityTypes.c.get(nbttagcompound.getString("id")); + + if (oclass != null) { + entity = oclass.getConstructor(new Class[]{World.class}).newInstance(world); + } + } catch (Exception exception) { + exception.printStackTrace(); + } + + if (entity != null) { + entity.f(nbttagcompound); + } else { + EntityTypes.b.warn("Skipping Entity with id " + nbttagcompound.getString("id")); + } + + return entity; + } + + public static Entity a(int i, World world) { + Entity entity = null; + + try { + Class oclass = a(i); + + if (oclass != null) { + entity = oclass.getConstructor(World.class).newInstance(world); + } + } catch (Exception exception) { + exception.printStackTrace(); + } + + if (entity == null) { + EntityTypes.b.warn("Skipping Entity with id " + i); + } + + return entity; + } + + public static int a(Entity entity) { + Integer integer = EntityTypes.f.get(entity.getClass()); + + return integer == null ? 0 : integer; + } + + public static Class a(int i) { + return EntityTypes.e.get(i); + } + + public static String b(Entity entity) { + return EntityTypes.d.get(entity.getClass()); + } + + public static String b(int i) { + return EntityTypes.d.get(a(i)); + } + + public static void a() { + } + + public static List b() { + ArrayList arraylist = Lists.newArrayList(); + + for (String s : EntityTypes.c.keySet()) { + Class oclass = EntityTypes.c.get(s); + + if ((oclass.getModifiers() & 1024) != 1024) { + arraylist.add(s); + } + } + + arraylist.add("LightningBolt"); + return arraylist; + } + + public static boolean a(Entity entity, String s) { + String s1 = b(entity); + + if (s1 == null && entity instanceof EntityHuman) { + s1 = "Player"; + } else if (s1 == null && entity instanceof EntityLightning) { + s1 = "LightningBolt"; + } + + return s.equals(s1); + } + + public static boolean b(String s) { + return "Player".equals(s) || b().contains(s); + } + + static { + a(EntityItem.class, "Item", 1); + a(EntityExperienceOrb.class, "XPOrb", 2); + a(EntityEgg.class, "ThrownEgg", 7); + a(EntityLeash.class, "LeashKnot", 8); + a(EntityPainting.class, "Painting", 9); + a(EntityArrow.class, "Arrow", 10); + a(EntitySnowball.class, "Snowball", 11); + a(EntityLargeFireball.class, "Fireball", 12); + a(EntitySmallFireball.class, "SmallFireball", 13); + a(EntityEnderPearl.class, "ThrownEnderpearl", 14); + a(EntityEnderSignal.class, "EyeOfEnderSignal", 15); + a(EntityPotion.class, "ThrownPotion", 16); + a(EntityThrownExpBottle.class, "ThrownExpBottle", 17); + a(EntityItemFrame.class, "ItemFrame", 18); + a(EntityWitherSkull.class, "WitherSkull", 19); + a(EntityTNTPrimed.class, "PrimedTnt", 20); + a(EntityFallingBlock.class, "FallingSand", 21); + a(EntityFireworks.class, "FireworksRocketEntity", 22); + a(EntityArmorStand.class, "ArmorStand", 30); + a(EntityBoat.class, "Boat", 41); + a(EntityMinecartRideable.class, EntityMinecartAbstract.EnumMinecartType.RIDEABLE.b(), 42); + a(EntityMinecartChest.class, EntityMinecartAbstract.EnumMinecartType.CHEST.b(), 43); + a(EntityMinecartFurnace.class, EntityMinecartAbstract.EnumMinecartType.FURNACE.b(), 44); + a(EntityMinecartTNT.class, EntityMinecartAbstract.EnumMinecartType.TNT.b(), 45); + a(EntityMinecartHopper.class, EntityMinecartAbstract.EnumMinecartType.HOPPER.b(), 46); + a(EntityMinecartMobSpawner.class, EntityMinecartAbstract.EnumMinecartType.SPAWNER.b(), 47); + a(EntityMinecartCommandBlock.class, EntityMinecartAbstract.EnumMinecartType.COMMAND_BLOCK.b(), 40); + a(EntityInsentient.class, "Mob", 48); + a(EntityMonster.class, "Monster", 49); + a(EntityCreeper.class, "Creeper", 50, 894731, 0); + a(EntitySkeleton.class, "Skeleton", 51, 12698049, 4802889); + a(EntitySpider.class, "Spider", 52, 3419431, 11013646); + a(EntityGiantZombie.class, "Giant", 53); + a(EntityZombie.class, "Zombie", 54, '\uafaf', 7969893); + a(EntitySlime.class, "Slime", 55, 5349438, 8306542); + a(EntityGhast.class, "Ghast", 56, 16382457, 12369084); + a(EntityPigZombie.class, "PigZombie", 57, 15373203, 5009705); + a(EntityEnderman.class, "Enderman", 58, 1447446, 0); + a(EntityCaveSpider.class, "CaveSpider", 59, 803406, 11013646); + a(EntitySilverfish.class, "Silverfish", 60, 7237230, 3158064); + a(EntityBlaze.class, "Blaze", 61, 16167425, 16775294); + a(EntityMagmaCube.class, "LavaSlime", 62, 3407872, 16579584); + a(EntityEnderDragon.class, "EnderDragon", 63); + a(EntityWither.class, "WitherBoss", 64); + a(EntityBat.class, "Bat", 65, 4996656, 986895); + a(EntityWitch.class, "Witch", 66, 3407872, 5349438); + a(EntityEndermite.class, "Endermite", 67, 1447446, 7237230); + a(EntityGuardian.class, "Guardian", 68, 5931634, 15826224); + a(EntityPig.class, "Pig", 90, 15771042, 14377823); + a(EntitySheep.class, "Sheep", 91, 15198183, 16758197); + a(EntityCow.class, "Cow", 92, 4470310, 10592673); + a(EntityChicken.class, "Chicken", 93, 10592673, 16711680); + a(EntitySquid.class, "Squid", 94, 2243405, 7375001); + a(EntityWolf.class, "Wolf", 95, 14144467, 13545366); + a(EntityMushroomCow.class, "MushroomCow", 96, 10489616, 12040119); + a(EntitySnowman.class, "SnowMan", 97); + a(EntityOcelot.class, "Ozelot", 98, 15720061, 5653556); + a(EntityIronGolem.class, "VillagerGolem", 99); + a(EntityHorse.class, "EntityHorse", 100, 12623485, 15656192); + a(EntityRabbit.class, "Rabbit", 101, 10051392, 7555121); + a(EntityVillager.class, "Villager", 120, 5651507, 12422002); + a(EntityEnderCrystal.class, "EnderCrystal", 200); + } + + public static class MonsterEggInfo { + + public final int a; + public final int b; + public final int c; + public final Statistic killEntityStatistic; + public final Statistic e; + + public MonsterEggInfo(int i, int j, int k) { + this.a = i; + this.b = j; + this.c = k; + this.killEntityStatistic = StatisticList.a(this); + this.e = StatisticList.b(this); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityVillager.java b/azurite-server/src/main/java/net/minecraft/server/EntityVillager.java new file mode 100644 index 0000000..80cd6b8 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityVillager.java @@ -0,0 +1,754 @@ +package net.minecraft.server; + +import org.bukkit.craftbukkit.entity.CraftVillager; + +import java.util.Random; + +public class EntityVillager extends EntityAgeable implements IMerchant, NPC { + + private int profession; + private boolean bo; + private boolean bp; + Village village; + private EntityHuman tradingPlayer; + private MerchantRecipeList br; + private int bs; + private boolean bt; + private boolean bu; + private int riches; + private String bw; + private int bx; + private int by; + private boolean bz; + private boolean bA; + public InventorySubcontainer inventory; + private static final EntityVillager.IMerchantRecipeOption[][][][] bC = new EntityVillager.IMerchantRecipeOption[][][][]{{{{new EntityVillager.MerchantRecipeOptionBuy(Items.WHEAT, new EntityVillager.MerchantOptionRandomRange(18, 22)), new EntityVillager.MerchantRecipeOptionBuy(Items.POTATO, new EntityVillager.MerchantOptionRandomRange(15, 19)), new EntityVillager.MerchantRecipeOptionBuy(Items.CARROT, new EntityVillager.MerchantOptionRandomRange(15, 19)), new EntityVillager.MerchantRecipeOptionSell(Items.BREAD, new EntityVillager.MerchantOptionRandomRange(-4, -2))}, {new EntityVillager.MerchantRecipeOptionBuy(Item.getItemOf(Blocks.PUMPKIN), new EntityVillager.MerchantOptionRandomRange(8, 13)), new EntityVillager.MerchantRecipeOptionSell(Items.PUMPKIN_PIE, new EntityVillager.MerchantOptionRandomRange(-3, -2))}, {new EntityVillager.MerchantRecipeOptionBuy(Item.getItemOf(Blocks.MELON_BLOCK), new EntityVillager.MerchantOptionRandomRange(7, 12)), new EntityVillager.MerchantRecipeOptionSell(Items.APPLE, new EntityVillager.MerchantOptionRandomRange(-5, -7))}, {new EntityVillager.MerchantRecipeOptionSell(Items.COOKIE, new EntityVillager.MerchantOptionRandomRange(-6, -10)), new EntityVillager.MerchantRecipeOptionSell(Items.CAKE, new EntityVillager.MerchantOptionRandomRange(1, 1))}}, {{new EntityVillager.MerchantRecipeOptionBuy(Items.STRING, new EntityVillager.MerchantOptionRandomRange(15, 20)), new EntityVillager.MerchantRecipeOptionBuy(Items.COAL, new EntityVillager.MerchantOptionRandomRange(16, 24)), new EntityVillager.MerchantRecipeOptionProcess(Items.FISH, new EntityVillager.MerchantOptionRandomRange(6, 6), Items.COOKED_FISH, new EntityVillager.MerchantOptionRandomRange(6, 6))}, {new EntityVillager.MerchantRecipeOptionEnchant(Items.FISHING_ROD, new EntityVillager.MerchantOptionRandomRange(7, 8))}}, {{new EntityVillager.MerchantRecipeOptionBuy(Item.getItemOf(Blocks.WOOL), new EntityVillager.MerchantOptionRandomRange(16, 22)), new EntityVillager.MerchantRecipeOptionSell(Items.SHEARS, new EntityVillager.MerchantOptionRandomRange(3, 4))}, {new EntityVillager.MerchantRecipeOptionSell(new ItemStack(Item.getItemOf(Blocks.WOOL), 1, 0), new EntityVillager.MerchantOptionRandomRange(1, 2)), new EntityVillager.MerchantRecipeOptionSell(new ItemStack(Item.getItemOf(Blocks.WOOL), 1, 1), new EntityVillager.MerchantOptionRandomRange(1, 2)), new EntityVillager.MerchantRecipeOptionSell(new ItemStack(Item.getItemOf(Blocks.WOOL), 1, 2), new EntityVillager.MerchantOptionRandomRange(1, 2)), new EntityVillager.MerchantRecipeOptionSell(new ItemStack(Item.getItemOf(Blocks.WOOL), 1, 3), new EntityVillager.MerchantOptionRandomRange(1, 2)), new EntityVillager.MerchantRecipeOptionSell(new ItemStack(Item.getItemOf(Blocks.WOOL), 1, 4), new EntityVillager.MerchantOptionRandomRange(1, 2)), new EntityVillager.MerchantRecipeOptionSell(new ItemStack(Item.getItemOf(Blocks.WOOL), 1, 5), new EntityVillager.MerchantOptionRandomRange(1, 2)), new EntityVillager.MerchantRecipeOptionSell(new ItemStack(Item.getItemOf(Blocks.WOOL), 1, 6), new EntityVillager.MerchantOptionRandomRange(1, 2)), new EntityVillager.MerchantRecipeOptionSell(new ItemStack(Item.getItemOf(Blocks.WOOL), 1, 7), new EntityVillager.MerchantOptionRandomRange(1, 2)), new EntityVillager.MerchantRecipeOptionSell(new ItemStack(Item.getItemOf(Blocks.WOOL), 1, 8), new EntityVillager.MerchantOptionRandomRange(1, 2)), new EntityVillager.MerchantRecipeOptionSell(new ItemStack(Item.getItemOf(Blocks.WOOL), 1, 9), new EntityVillager.MerchantOptionRandomRange(1, 2)), new EntityVillager.MerchantRecipeOptionSell(new ItemStack(Item.getItemOf(Blocks.WOOL), 1, 10), new EntityVillager.MerchantOptionRandomRange(1, 2)), new EntityVillager.MerchantRecipeOptionSell(new ItemStack(Item.getItemOf(Blocks.WOOL), 1, 11), new EntityVillager.MerchantOptionRandomRange(1, 2)), new EntityVillager.MerchantRecipeOptionSell(new ItemStack(Item.getItemOf(Blocks.WOOL), 1, 12), new EntityVillager.MerchantOptionRandomRange(1, 2)), new EntityVillager.MerchantRecipeOptionSell(new ItemStack(Item.getItemOf(Blocks.WOOL), 1, 13), new EntityVillager.MerchantOptionRandomRange(1, 2)), new EntityVillager.MerchantRecipeOptionSell(new ItemStack(Item.getItemOf(Blocks.WOOL), 1, 14), new EntityVillager.MerchantOptionRandomRange(1, 2)), new EntityVillager.MerchantRecipeOptionSell(new ItemStack(Item.getItemOf(Blocks.WOOL), 1, 15), new EntityVillager.MerchantOptionRandomRange(1, 2))}}, {{new EntityVillager.MerchantRecipeOptionBuy(Items.STRING, new EntityVillager.MerchantOptionRandomRange(15, 20)), new EntityVillager.MerchantRecipeOptionSell(Items.ARROW, new EntityVillager.MerchantOptionRandomRange(-12, -8))}, {new EntityVillager.MerchantRecipeOptionSell(Items.BOW, new EntityVillager.MerchantOptionRandomRange(2, 3)), new EntityVillager.MerchantRecipeOptionProcess(Item.getItemOf(Blocks.GRAVEL), new EntityVillager.MerchantOptionRandomRange(10, 10), Items.FLINT, new EntityVillager.MerchantOptionRandomRange(6, 10))}}}, {{{new EntityVillager.MerchantRecipeOptionBuy(Items.PAPER, new EntityVillager.MerchantOptionRandomRange(24, 36)), new EntityVillager.MerchantRecipeOptionBook()}, {new EntityVillager.MerchantRecipeOptionBuy(Items.BOOK, new EntityVillager.MerchantOptionRandomRange(8, 10)), new EntityVillager.MerchantRecipeOptionSell(Items.COMPASS, new EntityVillager.MerchantOptionRandomRange(10, 12)), new EntityVillager.MerchantRecipeOptionSell(Item.getItemOf(Blocks.BOOKSHELF), new EntityVillager.MerchantOptionRandomRange(3, 4))}, {new EntityVillager.MerchantRecipeOptionBuy(Items.WRITTEN_BOOK, new EntityVillager.MerchantOptionRandomRange(2, 2)), new EntityVillager.MerchantRecipeOptionSell(Items.CLOCK, new EntityVillager.MerchantOptionRandomRange(10, 12)), new EntityVillager.MerchantRecipeOptionSell(Item.getItemOf(Blocks.GLASS), new EntityVillager.MerchantOptionRandomRange(-5, -3))}, {new EntityVillager.MerchantRecipeOptionBook()}, {new EntityVillager.MerchantRecipeOptionBook()}, {new EntityVillager.MerchantRecipeOptionSell(Items.NAME_TAG, new EntityVillager.MerchantOptionRandomRange(20, 22))}}}, {{{new EntityVillager.MerchantRecipeOptionBuy(Items.ROTTEN_FLESH, new EntityVillager.MerchantOptionRandomRange(36, 40)), new EntityVillager.MerchantRecipeOptionBuy(Items.GOLD_INGOT, new EntityVillager.MerchantOptionRandomRange(8, 10))}, {new EntityVillager.MerchantRecipeOptionSell(Items.REDSTONE, new EntityVillager.MerchantOptionRandomRange(-4, -1)), new EntityVillager.MerchantRecipeOptionSell(new ItemStack(Items.DYE, 1, EnumColor.BLUE.getInvColorIndex()), new EntityVillager.MerchantOptionRandomRange(-2, -1))}, {new EntityVillager.MerchantRecipeOptionSell(Items.ENDER_EYE, new EntityVillager.MerchantOptionRandomRange(7, 11)), new EntityVillager.MerchantRecipeOptionSell(Item.getItemOf(Blocks.GLOWSTONE), new EntityVillager.MerchantOptionRandomRange(-3, -1))}, {new EntityVillager.MerchantRecipeOptionSell(Items.EXPERIENCE_BOTTLE, new EntityVillager.MerchantOptionRandomRange(3, 11))}}}, {{{new EntityVillager.MerchantRecipeOptionBuy(Items.COAL, new EntityVillager.MerchantOptionRandomRange(16, 24)), new EntityVillager.MerchantRecipeOptionSell(Items.IRON_HELMET, new EntityVillager.MerchantOptionRandomRange(4, 6))}, {new EntityVillager.MerchantRecipeOptionBuy(Items.IRON_INGOT, new EntityVillager.MerchantOptionRandomRange(7, 9)), new EntityVillager.MerchantRecipeOptionSell(Items.IRON_CHESTPLATE, new EntityVillager.MerchantOptionRandomRange(10, 14))}, {new EntityVillager.MerchantRecipeOptionBuy(Items.DIAMOND, new EntityVillager.MerchantOptionRandomRange(3, 4)), new EntityVillager.MerchantRecipeOptionEnchant(Items.DIAMOND_CHESTPLATE, new EntityVillager.MerchantOptionRandomRange(16, 19))}, {new EntityVillager.MerchantRecipeOptionSell(Items.CHAINMAIL_BOOTS, new EntityVillager.MerchantOptionRandomRange(5, 7)), new EntityVillager.MerchantRecipeOptionSell(Items.CHAINMAIL_LEGGINGS, new EntityVillager.MerchantOptionRandomRange(9, 11)), new EntityVillager.MerchantRecipeOptionSell(Items.CHAINMAIL_HELMET, new EntityVillager.MerchantOptionRandomRange(5, 7)), new EntityVillager.MerchantRecipeOptionSell(Items.CHAINMAIL_CHESTPLATE, new EntityVillager.MerchantOptionRandomRange(11, 15))}}, {{new EntityVillager.MerchantRecipeOptionBuy(Items.COAL, new EntityVillager.MerchantOptionRandomRange(16, 24)), new EntityVillager.MerchantRecipeOptionSell(Items.IRON_AXE, new EntityVillager.MerchantOptionRandomRange(6, 8))}, {new EntityVillager.MerchantRecipeOptionBuy(Items.IRON_INGOT, new EntityVillager.MerchantOptionRandomRange(7, 9)), new EntityVillager.MerchantRecipeOptionEnchant(Items.IRON_SWORD, new EntityVillager.MerchantOptionRandomRange(9, 10))}, {new EntityVillager.MerchantRecipeOptionBuy(Items.DIAMOND, new EntityVillager.MerchantOptionRandomRange(3, 4)), new EntityVillager.MerchantRecipeOptionEnchant(Items.DIAMOND_SWORD, new EntityVillager.MerchantOptionRandomRange(12, 15)), new EntityVillager.MerchantRecipeOptionEnchant(Items.DIAMOND_AXE, new EntityVillager.MerchantOptionRandomRange(9, 12))}}, {{new EntityVillager.MerchantRecipeOptionBuy(Items.COAL, new EntityVillager.MerchantOptionRandomRange(16, 24)), new EntityVillager.MerchantRecipeOptionEnchant(Items.IRON_SHOVEL, new EntityVillager.MerchantOptionRandomRange(5, 7))}, {new EntityVillager.MerchantRecipeOptionBuy(Items.IRON_INGOT, new EntityVillager.MerchantOptionRandomRange(7, 9)), new EntityVillager.MerchantRecipeOptionEnchant(Items.IRON_PICKAXE, new EntityVillager.MerchantOptionRandomRange(9, 11))}, {new EntityVillager.MerchantRecipeOptionBuy(Items.DIAMOND, new EntityVillager.MerchantOptionRandomRange(3, 4)), new EntityVillager.MerchantRecipeOptionEnchant(Items.DIAMOND_PICKAXE, new EntityVillager.MerchantOptionRandomRange(12, 15))}}}, {{{new EntityVillager.MerchantRecipeOptionBuy(Items.PORKCHOP, new EntityVillager.MerchantOptionRandomRange(14, 18)), new EntityVillager.MerchantRecipeOptionBuy(Items.CHICKEN, new EntityVillager.MerchantOptionRandomRange(14, 18))}, {new EntityVillager.MerchantRecipeOptionBuy(Items.COAL, new EntityVillager.MerchantOptionRandomRange(16, 24)), new EntityVillager.MerchantRecipeOptionSell(Items.COOKED_PORKCHOP, new EntityVillager.MerchantOptionRandomRange(-7, -5)), new EntityVillager.MerchantRecipeOptionSell(Items.COOKED_CHICKEN, new EntityVillager.MerchantOptionRandomRange(-8, -6))}}, {{new EntityVillager.MerchantRecipeOptionBuy(Items.LEATHER, new EntityVillager.MerchantOptionRandomRange(9, 12)), new EntityVillager.MerchantRecipeOptionSell(Items.LEATHER_LEGGINGS, new EntityVillager.MerchantOptionRandomRange(2, 4))}, {new EntityVillager.MerchantRecipeOptionEnchant(Items.LEATHER_CHESTPLATE, new EntityVillager.MerchantOptionRandomRange(7, 12))}, {new EntityVillager.MerchantRecipeOptionSell(Items.SADDLE, new EntityVillager.MerchantOptionRandomRange(8, 10))}}}}; + + public EntityVillager(World world) { + this(world, 0); + } + + public EntityVillager(World world, int i) { + super(world); + this.inventory = new InventorySubcontainer("Items", false, 8, (CraftVillager) this.getBukkitEntity()); // CraftBukkit add argument + this.setProfession(i); + this.setSize(0.6F, 1.8F); + ((Navigation) this.getNavigation()).b(true); + ((Navigation) this.getNavigation()).a(true); + this.goalSelector.a(0, new PathfinderGoalFloat(this)); + this.goalSelector.a(1, new PathfinderGoalAvoidTarget<>(this, EntityZombie.class, 8.0F, 0.6D, 0.6D)); + this.goalSelector.a(1, new PathfinderGoalTradeWithPlayer(this)); + this.goalSelector.a(1, new PathfinderGoalLookAtTradingPlayer(this)); + this.goalSelector.a(2, new PathfinderGoalMoveIndoors(this)); + this.goalSelector.a(3, new PathfinderGoalRestrictOpenDoor(this)); + this.goalSelector.a(4, new PathfinderGoalOpenDoor(this, true)); + this.goalSelector.a(5, new PathfinderGoalMoveTowardsRestriction(this, 0.6D)); + this.goalSelector.a(6, new PathfinderGoalMakeLove(this)); + this.goalSelector.a(7, new PathfinderGoalTakeFlower(this)); + this.goalSelector.a(9, new PathfinderGoalInteract(this, EntityHuman.class, 3.0F, 1.0F)); + this.goalSelector.a(9, new PathfinderGoalInteractVillagers(this)); + this.goalSelector.a(9, new PathfinderGoalRandomStroll(this, 0.6D)); + this.goalSelector.a(10, new PathfinderGoalLookAtPlayer(this, EntityInsentient.class, 8.0F)); + this.j(true); + } + + private void cv() { + if (!this.bA) { + this.bA = true; + if (this.isBaby()) { + this.goalSelector.a(8, new PathfinderGoalPlay(this, 0.32D)); + } else if (this.getProfession() == 0) { + this.goalSelector.a(6, new PathfinderGoalVillagerFarm(this, 0.6D)); + } + + } + } + + protected void n() { + if (this.getProfession() == 0) { + this.goalSelector.a(8, new PathfinderGoalVillagerFarm(this, 0.6D)); + } + + super.n(); + } + + protected void initAttributes() { + super.initAttributes(); + this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.5D); + } + + protected void E() { + if (--this.profession <= 0) { + BlockPosition blockposition = new BlockPosition(this); + + this.world.ae().a(blockposition); + this.profession = 70 + random.nextInt(50); + this.village = this.world.ae().getClosestVillage(blockposition, 32); + if (this.village == null) { + this.cj(); + } else { + BlockPosition blockposition1 = this.village.a(); + + this.a(blockposition1, (int) ((float) this.village.b())); + if (this.bz) { + this.bz = false; + this.village.b(5); + } + } + } + + if (!this.co() && this.bs > 0) { + --this.bs; + if (this.bs <= 0) { + if (this.bt) { + + for (MerchantRecipe merchantrecipe : this.br) { + if (merchantrecipe.h()) { + merchantrecipe.a(random.nextInt(6) + random.nextInt(6) + 2); + } + } + + this.cw(); + this.bt = false; + if (this.village != null && this.bw != null) { + this.world.broadcastEntityEffect(this, (byte) 14); + this.village.a(this.bw, 1); + } + } + + this.addEffect(new MobEffect(MobEffectList.REGENERATION.id, 200, 0)); + } + } + + super.E(); + } + + public boolean a(EntityHuman entityhuman) { + ItemStack itemstack = entityhuman.inventory.getItemInHand(); + boolean flag = itemstack != null && itemstack.getItem() == Items.SPAWN_EGG; + + if (!flag && this.isAlive() && !this.co() && !this.isBaby()) { + if ((this.br == null || !this.br.isEmpty())) { + this.a_(entityhuman); + entityhuman.openTrade(this); + } + + entityhuman.b(StatisticList.F); + return true; + } else { + return super.a(entityhuman); + } + } + + protected void h() { + super.h(); + this.datawatcher.a(16, 0); + } + + public void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + nbttagcompound.setInt("Profession", this.getProfession()); + nbttagcompound.setInt("Riches", this.riches); + nbttagcompound.setInt("Career", this.bx); + nbttagcompound.setInt("CareerLevel", this.by); + nbttagcompound.setBoolean("Willing", this.bu); + if (this.br != null) { + nbttagcompound.set("Offers", this.br.a()); + } + + NBTTagList nbttaglist = new NBTTagList(); + + for (int i = 0; i < this.inventory.getSize(); ++i) { + ItemStack itemstack = this.inventory.getItem(i); + + if (itemstack != null) { + nbttaglist.add(itemstack.save(new NBTTagCompound())); + } + } + + nbttagcompound.set("Inventory", nbttaglist); + } + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + this.setProfession(nbttagcompound.getInt("Profession")); + this.riches = nbttagcompound.getInt("Riches"); + this.bx = nbttagcompound.getInt("Career"); + this.by = nbttagcompound.getInt("CareerLevel"); + this.bu = nbttagcompound.getBoolean("Willing"); + if (nbttagcompound.hasKeyOfType("Offers", 10)) { + NBTTagCompound nbttagcompound1 = nbttagcompound.getCompound("Offers"); + + this.br = new MerchantRecipeList(nbttagcompound1); + } + + NBTTagList nbttaglist = nbttagcompound.getList("Inventory", 10); + + for (int i = 0; i < nbttaglist.size(); ++i) { + ItemStack itemstack = ItemStack.createStack(nbttaglist.get(i)); + + if (itemstack != null) { + this.inventory.a(itemstack); + } + } + + this.j(true); + this.cv(); + } + + public boolean isTypeNotPersistent() { + return false; + } + + protected String z() { + return this.co() ? "mob.villager.haggle" : "mob.villager.idle"; + } + + protected String bo() { + return "mob.villager.hit"; + } + + protected String bp() { + return "mob.villager.death"; + } + + public void setProfession(int i) { + this.datawatcher.watch(16, i); + } + + public int getProfession() { + return Math.max(this.datawatcher.getInt(16) % 5, 0); + } + + public boolean cm() { + return this.bo; + } + + public void l(boolean flag) { + this.bo = flag; + } + + public void m(boolean flag) { + this.bp = flag; + } + + public boolean cn() { + return this.bp; + } + + public void b(EntityLiving entityliving) { + super.b(entityliving); + if (this.village != null && entityliving != null) { + this.village.a(entityliving); + if (entityliving instanceof EntityHuman) { + byte b0 = -1; + + if (this.isBaby()) { + b0 = -3; + } + + this.village.a(entityliving.getName(), b0); + if (this.isAlive()) { + this.world.broadcastEntityEffect(this, (byte) 13); + } + } + } + + } + + public void die(DamageSource damagesource) { + if (this.village != null) { + Entity entity = damagesource.getEntity(); + + if (entity != null) { + if (entity instanceof EntityHuman) { + this.village.a(entity.getName(), -2); + } else if (entity instanceof IMonster) { + this.village.h(); + } + } else { + EntityHuman entityhuman = this.world.findNearbyPlayer(this, 16.0D); + + if (entityhuman != null) { + this.village.h(); + } + } + } + + super.die(damagesource); + } + + public void a_(EntityHuman entityhuman) { + this.tradingPlayer = entityhuman; + } + + public EntityHuman v_() { + return this.tradingPlayer; + } + + public boolean co() { + return this.tradingPlayer != null; + } + + public boolean n(boolean flag) { + if (!this.bu && flag && this.cr()) { + boolean flag1 = false; + + for (int i = 0; i < this.inventory.getSize(); ++i) { + ItemStack itemstack = this.inventory.getItem(i); + + if (itemstack != null) { + if (itemstack.getItem() == Items.BREAD && itemstack.count >= 3) { + flag1 = true; + this.inventory.splitStack(i, 3); + } else if ((itemstack.getItem() == Items.POTATO || itemstack.getItem() == Items.CARROT) && itemstack.count >= 12) { + flag1 = true; + this.inventory.splitStack(i, 12); + } + } + + if (flag1) { + this.world.broadcastEntityEffect(this, (byte) 18); + this.bu = true; + break; + } + } + } + + return this.bu; + } + + public void o(boolean flag) { + this.bu = flag; + } + + public void a(MerchantRecipe merchantrecipe) { + merchantrecipe.g(); + this.a_ = -this.w(); + this.makeSound("mob.villager.yes", this.bB(), this.bC()); + int i = 3 + random.nextInt(4); + + if (merchantrecipe.e() == 1 || random.nextInt(5) == 0) { + this.bs = 40; + this.bt = true; + this.bu = true; + if (this.tradingPlayer != null) { + this.bw = this.tradingPlayer.getName(); + } else { + this.bw = null; + } + + i += 5; + } + + if (merchantrecipe.getBuyItem1().getItem() == Items.EMERALD) { + this.riches += merchantrecipe.getBuyItem1().count; + } + + if (merchantrecipe.j()) { + this.world.addEntity(new EntityExperienceOrb(this.world, this.locX, this.locY + 0.5D, this.locZ, i)); + } + + } + + public void a_(ItemStack itemstack) { + if (this.a_ > -this.w() + 20) { + this.a_ = -this.w(); + if (itemstack != null) { + this.makeSound("mob.villager.yes", this.bB(), this.bC()); + } else { + this.makeSound("mob.villager.no", this.bB(), this.bC()); + } + } + + } + + public MerchantRecipeList getOffers(EntityHuman entityhuman) { + if (this.br == null) { + this.cw(); + } + + return this.br; + } + + private void cw() { + EntityVillager.IMerchantRecipeOption[][][] aentityvillager_imerchantrecipeoption = EntityVillager.bC[this.getProfession()]; + + if (this.bx != 0 && this.by != 0) { + ++this.by; + } else { + this.bx = random.nextInt(aentityvillager_imerchantrecipeoption.length) + 1; + this.by = 1; + } + + if (this.br == null) { + this.br = new MerchantRecipeList(); + } + + int i = this.bx - 1; + int j = this.by - 1; + EntityVillager.IMerchantRecipeOption[][] aentityvillager_imerchantrecipeoption1 = aentityvillager_imerchantrecipeoption[i]; + + if (j >= 0 && j < aentityvillager_imerchantrecipeoption1.length) { + + for (IMerchantRecipeOption entityvillager_imerchantrecipeoption : aentityvillager_imerchantrecipeoption1[j]) { + entityvillager_imerchantrecipeoption.a(this.br, random); + } + } + + } + + public IChatBaseComponent getScoreboardDisplayName() { + String s = this.getCustomName(); + + if (s != null && !s.isEmpty()) { + ChatComponentText chatcomponenttext = new ChatComponentText(s); + + chatcomponenttext.getChatModifier().setChatHoverable(this.aQ()); + chatcomponenttext.getChatModifier().setInsertion(this.getUniqueID().toString()); + return chatcomponenttext; + } else { + if (this.br == null) { + this.cw(); + } + + String s1 = null; + + switch (this.getProfession()) { + case 0: + if (this.bx == 1) { + s1 = "farmer"; + } else if (this.bx == 2) { + s1 = "fisherman"; + } else if (this.bx == 3) { + s1 = "shepherd"; + } else if (this.bx == 4) { + s1 = "fletcher"; + } + break; + + case 1: + s1 = "librarian"; + break; + + case 2: + s1 = "cleric"; + break; + + case 3: + if (this.bx == 1) { + s1 = "armor"; + } else if (this.bx == 2) { + s1 = "weapon"; + } else if (this.bx == 3) { + s1 = "tool"; + } + break; + + case 4: + if (this.bx == 1) { + s1 = "butcher"; + } else if (this.bx == 2) { + s1 = "leather"; + } + } + + if (s1 != null) { + ChatMessage chatmessage = new ChatMessage("entity.Villager." + s1); + + chatmessage.getChatModifier().setChatHoverable(this.aQ()); + chatmessage.getChatModifier().setInsertion(this.getUniqueID().toString()); + return chatmessage; + } else { + return super.getScoreboardDisplayName(); + } + } + } + + public float getHeadHeight() { + float f = 1.62F; + + if (this.isBaby()) { + f = (float) ((double) f - 0.81D); + } + + return f; + } + + public GroupDataEntity prepare(DifficultyDamageScaler difficultydamagescaler, GroupDataEntity groupdataentity) { + groupdataentity = super.prepare(difficultydamagescaler, groupdataentity); + this.setProfession(this.world.random.nextInt(5)); + this.cv(); + return groupdataentity; + } + + public void cp() { + this.bz = true; + } + + public EntityVillager b(EntityAgeable entityageable) { + EntityVillager entityvillager = new EntityVillager(this.world); + + entityvillager.prepare(this.world.E(MathHelper.floor(entityvillager.locX), MathHelper.floor(entityvillager.locY), MathHelper.floor(entityvillager.locZ)), null); + return entityvillager; + } + + public boolean cb() { + return false; + } + + public void onLightningStrike(EntityLightning entitylightning) { + if (!this.dead) { + EntityWitch entitywitch = new EntityWitch(this.world); + + entitywitch.setPositionRotation(this.locX, this.locY, this.locZ, this.yaw, this.pitch); + entitywitch.prepare(this.world.E(MathHelper.floor(entitywitch.locX), MathHelper.floor(entitywitch.locY), MathHelper.floor(entitywitch.locZ)), null); + entitywitch.k(this.ce()); + if (this.hasCustomName()) { + entitywitch.setCustomName(this.getCustomName()); + entitywitch.setCustomNameVisible(this.getCustomNameVisible()); + } + + this.world.addEntity(entitywitch); + this.die(); + } + } + + public InventorySubcontainer cq() { + return this.inventory; + } + + protected void a(EntityItem entityitem) { + ItemStack itemstack = entityitem.getItemStack(); + Item item = itemstack.getItem(); + + if (this.a(item)) { + ItemStack itemstack1 = this.inventory.a(itemstack); + + if (itemstack1 == null) { + entityitem.die(); + } else { + itemstack.count = itemstack1.count; + } + } + + } + + private boolean a(Item item) { + return item == Items.BREAD || item == Items.POTATO || item == Items.CARROT || item == Items.WHEAT || item == Items.WHEAT_SEEDS; + } + + public boolean cr() { + return this.s(1); + } + + public boolean cs() { + return this.s(2); + } + + public boolean ct() { + boolean flag = this.getProfession() == 0; + + return flag ? !this.s(5) : !this.s(1); + } + + private boolean s(int i) { + boolean flag = this.getProfession() == 0; + + for (int j = 0; j < this.inventory.getSize(); ++j) { + ItemStack itemstack = this.inventory.getItem(j); + + if (itemstack != null) { + if (itemstack.getItem() == Items.BREAD && itemstack.count >= 3 * i || itemstack.getItem() == Items.POTATO && itemstack.count >= 12 * i || itemstack.getItem() == Items.CARROT && itemstack.count >= 12 * i) { + return true; + } + + if (flag && itemstack.getItem() == Items.WHEAT && itemstack.count >= 9 * i) { + return true; + } + } + } + + return false; + } + + public boolean cu() { + for (int i = 0; i < this.inventory.getSize(); ++i) { + ItemStack itemstack = this.inventory.getItem(i); + + if (itemstack != null && (itemstack.getItem() == Items.WHEAT_SEEDS || itemstack.getItem() == Items.POTATO || itemstack.getItem() == Items.CARROT)) { + return true; + } + } + + return false; + } + + public boolean d(int i, ItemStack itemstack) { + if (super.d(i, itemstack)) { + return true; + } else { + int j = i - 300; + + if (j >= 0 && j < this.inventory.getSize()) { + this.inventory.setItem(j, itemstack); + return true; + } else { + return false; + } + } + } + + public EntityAgeable createChild(EntityAgeable entityageable) { + return this.b(entityageable); + } + + static class MerchantRecipeOptionProcess implements EntityVillager.IMerchantRecipeOption { + + public ItemStack a; + public EntityVillager.MerchantOptionRandomRange b; + public ItemStack c; + public EntityVillager.MerchantOptionRandomRange d; + + public MerchantRecipeOptionProcess(Item item, EntityVillager.MerchantOptionRandomRange entityvillager_merchantoptionrandomrange, Item item1, EntityVillager.MerchantOptionRandomRange entityvillager_merchantoptionrandomrange1) { + this.a = new ItemStack(item); + this.b = entityvillager_merchantoptionrandomrange; + this.c = new ItemStack(item1); + this.d = entityvillager_merchantoptionrandomrange1; + } + + public void a(MerchantRecipeList merchantrecipelist, Random random) { + int i = 1; + + if (this.b != null) { + i = this.b.a(random); + } + + int j = 1; + + if (this.d != null) { + j = this.d.a(random); + } + + merchantrecipelist.add(new MerchantRecipe(new ItemStack(this.a.getItem(), i, this.a.getData()), new ItemStack(Items.EMERALD), new ItemStack(this.c.getItem(), j, this.c.getData()))); + } + } + + static class MerchantRecipeOptionBook implements EntityVillager.IMerchantRecipeOption { + + public MerchantRecipeOptionBook() { + } + + public void a(MerchantRecipeList merchantrecipelist, Random random) { + Enchantment enchantment = Enchantment.b[random.nextInt(Enchantment.b.length)]; + int i = MathHelper.nextInt(random, enchantment.getStartLevel(), Math.min(enchantment.getMaxLevel(), enchantment.getEnchantLimit())); + ItemStack itemstack = Items.ENCHANTED_BOOK.a(new WeightedRandomEnchant(enchantment, i)); + int j = 2 + random.nextInt(5 + i * 10) + 3 * i; + + if (j > 64) { + j = 64; + } + + merchantrecipelist.add(new MerchantRecipe(new ItemStack(Items.BOOK), new ItemStack(Items.EMERALD, j), itemstack)); + } + } + + static class MerchantRecipeOptionEnchant implements EntityVillager.IMerchantRecipeOption { + + public ItemStack a; + public EntityVillager.MerchantOptionRandomRange b; + + public MerchantRecipeOptionEnchant(Item item, EntityVillager.MerchantOptionRandomRange entityvillager_merchantoptionrandomrange) { + this.a = new ItemStack(item); + this.b = entityvillager_merchantoptionrandomrange; + } + + public void a(MerchantRecipeList merchantrecipelist, Random random) { + int i = 1; + + if (this.b != null) { + i = this.b.a(random); + } + + ItemStack itemstack = new ItemStack(Items.EMERALD, i, 0); + ItemStack itemstack1 = new ItemStack(this.a.getItem(), 1, this.a.getData()); + + EnchantmentManager.a(random, itemstack1, 5 + random.nextInt(15)); + merchantrecipelist.add(new MerchantRecipe(itemstack, itemstack1)); + } + } + + static class MerchantRecipeOptionSell implements EntityVillager.IMerchantRecipeOption { + + public ItemStack a; + public EntityVillager.MerchantOptionRandomRange b; + + public MerchantRecipeOptionSell(Item item, EntityVillager.MerchantOptionRandomRange entityvillager_merchantoptionrandomrange) { + this.a = new ItemStack(item); + this.b = entityvillager_merchantoptionrandomrange; + } + + public MerchantRecipeOptionSell(ItemStack itemstack, EntityVillager.MerchantOptionRandomRange entityvillager_merchantoptionrandomrange) { + this.a = itemstack; + this.b = entityvillager_merchantoptionrandomrange; + } + + public void a(MerchantRecipeList merchantrecipelist, Random random) { + int i = 1; + + if (this.b != null) { + i = this.b.a(random); + } + + ItemStack itemstack; + ItemStack itemstack1; + + if (i < 0) { + itemstack = new ItemStack(Items.EMERALD, 1, 0); + itemstack1 = new ItemStack(this.a.getItem(), -i, this.a.getData()); + } else { + itemstack = new ItemStack(Items.EMERALD, i, 0); + itemstack1 = new ItemStack(this.a.getItem(), 1, this.a.getData()); + } + + merchantrecipelist.add(new MerchantRecipe(itemstack, itemstack1)); + } + } + + static class MerchantRecipeOptionBuy implements EntityVillager.IMerchantRecipeOption { + + public Item a; + public EntityVillager.MerchantOptionRandomRange b; + + public MerchantRecipeOptionBuy(Item item, EntityVillager.MerchantOptionRandomRange entityvillager_merchantoptionrandomrange) { + this.a = item; + this.b = entityvillager_merchantoptionrandomrange; + } + + public void a(MerchantRecipeList merchantrecipelist, Random random) { + int i = 1; + + if (this.b != null) { + i = this.b.a(random); + } + + merchantrecipelist.add(new MerchantRecipe(new ItemStack(this.a, i, 0), Items.EMERALD)); + } + } + + interface IMerchantRecipeOption { + + void a(MerchantRecipeList merchantrecipelist, Random random); + } + + static class MerchantOptionRandomRange extends Tuple { + + public MerchantOptionRandomRange(int i, int j) { + super(i, j); + } + + public int a(Random random) { + return this.a() >= this.b() ? this.a() : this.a() + random.nextInt(this.b() - this.a() + 1); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityWaterAnimal.java b/azurite-server/src/main/java/net/minecraft/server/EntityWaterAnimal.java new file mode 100644 index 0000000..8140d93 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityWaterAnimal.java @@ -0,0 +1,53 @@ +package net.minecraft.server; + +public abstract class EntityWaterAnimal extends EntityInsentient implements IAnimal { + + public EntityWaterAnimal(World world) { + super(world); + } + + public boolean aY() { + return true; + } + + public boolean bR() { + return true; + } + + public boolean canSpawn() { + return this.world.a(this.getBoundingBox(), (Entity) this); + } + + public int w() { + return 120; + } + + public boolean isTypeNotPersistent() { + return true; + } + + protected int getExpValue(EntityHuman entityhuman) { + return 1 + this.world.random.nextInt(3); + } + + public void K() { + int i = this.getAirTicks(); + + super.K(); + if (this.isAlive() && !this.V()) { + --i; + this.setAirTicks(i); + if (this.getAirTicks() == -20) { + this.setAirTicks(0); + this.damageEntity(DamageSource.DROWN, 2.0F); + } + } else { + this.setAirTicks(300); + } + + } + + public boolean aL() { + return false; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityWeather.java b/azurite-server/src/main/java/net/minecraft/server/EntityWeather.java new file mode 100644 index 0000000..03ff54c --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityWeather.java @@ -0,0 +1,8 @@ +package net.minecraft.server; + +public abstract class EntityWeather extends Entity { + + public EntityWeather(World world) { + super(world); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityWitch.java b/azurite-server/src/main/java/net/minecraft/server/EntityWitch.java new file mode 100644 index 0000000..05c173a --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityWitch.java @@ -0,0 +1,169 @@ +package net.minecraft.server; + +import com.eatthepath.uuid.FastUUID; + +import java.util.List; +import java.util.UUID; + +public class EntityWitch extends EntityMonster implements IRangedEntity { + + private static final UUID a = FastUUID.parseUUID("5CD17E52-A79A-43D3-A529-90FDE04B181E"); + private static final AttributeModifier b = (new AttributeModifier(EntityWitch.a, "Drinking speed penalty", -0.25D, 0)).a(false); + private static final Item[] c = {Items.GLOWSTONE_DUST, Items.SUGAR, Items.REDSTONE, Items.SPIDER_EYE, Items.GLASS_BOTTLE, Items.GUNPOWDER, Items.STICK, Items.STICK}; + private int bm; + + public EntityWitch(World world) { + super(world); + this.setSize(0.6F, 1.95F); + this.goalSelector.a(1, new PathfinderGoalFloat(this)); + this.goalSelector.a(2, new PathfinderGoalArrowAttack(this, 1.0D, 60, 10.0F)); + this.goalSelector.a(2, new PathfinderGoalRandomStroll(this, 1.0D)); + this.goalSelector.a(3, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 8.0F)); + this.goalSelector.a(3, new PathfinderGoalRandomLookaround(this)); + this.targetSelector.a(1, new PathfinderGoalHurtByTarget(this, false)); + this.targetSelector.a(2, new PathfinderGoalNearestAttackableTarget<>(this, EntityHuman.class, true)); + } + + protected void h() { + super.h(); + this.getDataWatcher().a(21, (byte) 0); + } + + protected String z() { + return null; + } + + protected String bo() { + return null; + } + + protected String bp() { + return null; + } + + public void a(boolean flag) { + this.getDataWatcher().watch(21, (byte) (flag ? 1 : 0)); + } + + public boolean n() { + return this.getDataWatcher().getByte(21) == 1; + } + + protected void initAttributes() { + super.initAttributes(); + this.getAttributeInstance(GenericAttributes.maxHealth).setValue(26.0D); + this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.25D); + } + + public void m() { + if (this.n()) { + if (this.bm-- <= 0) { + this.a(false); + ItemStack itemstack = this.bA(); + + this.setEquipment(0, null); + if (itemstack != null && itemstack.getItem() == Items.POTION) { + List list = Items.POTION.h(itemstack); + + if (list != null) { + + for (MobEffect mobeffect : list) { + this.addEffect(new MobEffect(mobeffect)); + } + } + } + + this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).c(EntityWitch.b); + } + } else { + short short0 = -1; + + if (random.nextFloat() < 0.15F && this.a(Material.WATER) && !this.hasEffect(MobEffectList.WATER_BREATHING)) { + short0 = 8237; + } else if (random.nextFloat() < 0.15F && this.isBurning() && !this.hasEffect(MobEffectList.FIRE_RESISTANCE)) { + short0 = 16307; + } else if (random.nextFloat() < 0.05F && this.getHealth() < this.getMaxHealth()) { + short0 = 16341; + } else if (random.nextFloat() < 0.25F && this.getGoalTarget() != null && !this.hasEffect(MobEffectList.FASTER_MOVEMENT) && this.getGoalTarget().h(this) > 121.0D) { + short0 = 16274; + } else if (random.nextFloat() < 0.25F && this.getGoalTarget() != null && !this.hasEffect(MobEffectList.FASTER_MOVEMENT) && this.getGoalTarget().h(this) > 121.0D) { + short0 = 16274; + } + + if (short0 > -1) { + this.setEquipment(0, new ItemStack(Items.POTION, 1, short0)); + this.bm = this.bA().l(); + this.a(true); + AttributeInstance attributeinstance = this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED); + + attributeinstance.c(EntityWitch.b); + attributeinstance.b(EntityWitch.b); + } + } + + if (random.nextFloat() < 7.5E-4F) { + this.world.broadcastEntityEffect(this, (byte) 15); + } + + super.m(); + } + + protected float applyMagicModifier(DamageSource damagesource, float f) { + f = super.applyMagicModifier(damagesource, f); + if (damagesource.getEntity() == this) { + f = 0.0F; + } + + if (damagesource.isMagic()) { + f = (float) ((double) f * 0.15D); + } + + return f; + } + + protected void dropDeathLoot(boolean flag, int i) { + int j = random.nextInt(3) + 1; + + for (int k = 0; k < j; ++k) { + int l = random.nextInt(3); + Item item = EntityWitch.c[random.nextInt(EntityWitch.c.length)]; + + if (i > 0) { + l += random.nextInt(i + 1); + } + + for (int i1 = 0; i1 < l; ++i1) { + this.a(item, 1); + } + } + + } + + public void a(EntityLiving entityliving, float f) { + if (!this.n()) { + EntityPotion entitypotion = new EntityPotion(this.world, this, 32732); + double d0 = entityliving.locY + (double) entityliving.getHeadHeight() - 1.100000023841858D; + + entitypotion.pitch -= -20.0F; + double d1 = entityliving.locX + entityliving.motX - this.locX; + double d2 = d0 - this.locY; + double d3 = entityliving.locZ + entityliving.motZ - this.locZ; + float f1 = MathHelper.sqrt(d1 * d1 + d3 * d3); + + if (f1 >= 8.0F && !entityliving.hasEffect(MobEffectList.SLOWER_MOVEMENT)) { + entitypotion.setPotionValue(32698); + } else if (entityliving.getHealth() >= 8.0F && !entityliving.hasEffect(MobEffectList.POISON)) { + entitypotion.setPotionValue(32660); + } else if (f1 <= 3.0F && !entityliving.hasEffect(MobEffectList.WEAKNESS) && random.nextFloat() < 0.25F) { + entitypotion.setPotionValue(32696); + } + + entitypotion.shoot(d1, d2 + (double) (f1 * 0.2F), d3, 0.75F, 8.0F); + this.world.addEntity(entitypotion); + } + } + + public float getHeadHeight() { + return 1.62F; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityWither.java b/azurite-server/src/main/java/net/minecraft/server/EntityWither.java new file mode 100644 index 0000000..6f2037d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityWither.java @@ -0,0 +1,494 @@ +package net.minecraft.server; + +import com.google.common.base.Predicate; +import com.google.common.base.Predicates; +import org.bukkit.craftbukkit.event.CraftEventFactory; +import org.bukkit.event.entity.EntityRegainHealthEvent; +import org.bukkit.event.entity.ExplosionPrimeEvent; + +import java.util.List; +// CraftBukkit end + +public class EntityWither extends EntityMonster implements IRangedEntity { + + private static final Predicate bq = new Predicate() { + public boolean a(Entity entity) { + return entity instanceof EntityLiving && ((EntityLiving) entity).getMonsterType() != EnumMonsterType.UNDEAD; + } + + public boolean apply(Object object) { + return this.a((Entity) object); + } + }; + private final float[] a = new float[2]; + private final float[] b = new float[2]; + + private final int[] bn = new int[2]; + private final int[] bo = new int[2]; + private int bp; + + public EntityWither(World world) { + super(world); + this.setHealth(this.getMaxHealth()); + this.setSize(0.9F, 3.5F); + this.fireProof = true; + ((Navigation) this.getNavigation()).d(true); + this.goalSelector.a(0, new PathfinderGoalFloat(this)); + this.goalSelector.a(2, new PathfinderGoalArrowAttack(this, 1.0D, 40, 20.0F)); + this.goalSelector.a(5, new PathfinderGoalRandomStroll(this, 1.0D)); + this.goalSelector.a(6, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 8.0F)); + this.goalSelector.a(7, new PathfinderGoalRandomLookaround(this)); + this.targetSelector.a(1, new PathfinderGoalHurtByTarget(this, false)); + this.targetSelector.a(2, new PathfinderGoalNearestAttackableTarget(this, EntityInsentient.class, 0, false, false, EntityWither.bq)); + this.b_ = 50; + } + + public static boolean a(Block block) { + return block != Blocks.BEDROCK && block != Blocks.END_PORTAL && block != Blocks.END_PORTAL_FRAME && block != Blocks.COMMAND_BLOCK && block != Blocks.BARRIER; + } + + protected void h() { + super.h(); + this.datawatcher.a(17, 0); + this.datawatcher.a(18, 0); + this.datawatcher.a(19, 0); + this.datawatcher.a(20, 0); + } + + public void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + nbttagcompound.setInt("Invul", this.cl()); + } + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + this.r(nbttagcompound.getInt("Invul")); + } + + protected String z() { + return "mob.wither.idle"; + } + + protected String bo() { + return "mob.wither.hurt"; + } + + protected String bp() { + return "mob.wither.death"; + } + + public void m() { + this.motY *= 0.6000000238418579D; + double d0; + double d1; + double d2; + + if (this.s(0) > 0) { + Entity entity = this.world.a(this.s(0)); + + if (entity != null) { + if (this.locY < entity.locY || !this.cm() && this.locY < entity.locY + 5.0D) { + if (this.motY < 0.0D) { + this.motY = 0.0D; + } + + this.motY += (0.5D - this.motY) * 0.6000000238418579D; + } + + double d3 = entity.locX - this.locX; + + d0 = entity.locZ - this.locZ; + d1 = d3 * d3 + d0 * d0; + if (d1 > 9.0D) { + d2 = MathHelper.sqrt(d1); + this.motX += (d3 / d2 * 0.5D - this.motX) * 0.6000000238418579D; + this.motZ += (d0 / d2 * 0.5D - this.motZ) * 0.6000000238418579D; + } + } + } + + if (this.motX * this.motX + this.motZ * this.motZ > 0.05000000074505806D) { + this.yaw = (float) MathHelper.b(this.motZ, this.motX) * 57.295776F - 90.0F; + } + + super.m(); + + int i; + + int j; + + for (i = 0; i < 2; ++i) { + j = this.s(i + 1); + Entity entity1 = null; + + if (j > 0) { + entity1 = this.world.a(j); + } + + if (entity1 != null) { + d0 = this.t(i + 1); + d1 = this.u(i + 1); + d2 = this.v(i + 1); + double d4 = entity1.locX - d0; + double d5 = entity1.locY + (double) entity1.getHeadHeight() - d1; + double d6 = entity1.locZ - d2; + double d7 = MathHelper.sqrt(d4 * d4 + d6 * d6); + float f = (float) (MathHelper.b(d6, d4) * 180.0D / 3.1415927410125732D) - 90.0F; + float f1 = (float) (-(MathHelper.b(d5, d7) * 180.0D / 3.1415927410125732D)); + + this.a[i] = this.b(this.a[i], f1, 40.0F); + this.b[i] = this.b(this.b[i], f, 10.0F); + } else { + this.b[i] = this.b(this.b[i], this.aI, 10.0F); + } + } + + boolean flag = this.cm(); + + for (j = 0; j < 3; ++j) { + double d8 = this.t(j); + double d9 = this.u(j); + double d10 = this.v(j); + + this.world.addParticle(EnumParticle.SMOKE_NORMAL, d8 + random.nextGaussian() * 0.30000001192092896D, d9 + random.nextGaussian() * 0.30000001192092896D, d10 + random.nextGaussian() * 0.30000001192092896D, 0.0D, 0.0D, 0.0D, EnumParticle.EMPTY_ARRAY); + if (flag && this.world.random.nextInt(4) == 0) { + this.world.addParticle(EnumParticle.SPELL_MOB, d8 + random.nextGaussian() * 0.30000001192092896D, d9 + random.nextGaussian() * 0.30000001192092896D, d10 + random.nextGaussian() * 0.30000001192092896D, 0.699999988079071D, 0.699999988079071D, 0.5D, EnumParticle.EMPTY_ARRAY); + } + } + + if (this.cl() > 0) { + for (j = 0; j < 3; ++j) { + this.world.addParticle(EnumParticle.SPELL_MOB, this.locX + random.nextGaussian(), this.locY + (double) (random.nextFloat() * 3.3F), this.locZ + random.nextGaussian(), 0.699999988079071D, 0.699999988079071D, 0.8999999761581421D, EnumParticle.EMPTY_ARRAY); + } + } + + } + + protected void E() { + int i; + + if (this.cl() > 0) { + i = this.cl() - 1; + if (i <= 0) { + // CraftBukkit start + // this.world.createExplosion(this, this.locX, this.locY + (double) this.getHeadHeight(), this.locZ, 7.0F, false, this.world.getGameRules().getBoolean("mobGriefing")); + ExplosionPrimeEvent event = new ExplosionPrimeEvent(this.getBukkitEntity(), 7.0F, false); + this.world.getServer().getPluginManager().callEvent(event); + + if (!event.isCancelled()) { + this.world.createExplosion(this, this.locX, this.locY + (double) this.getHeadHeight(), this.locZ, event.getRadius(), event.getFire(), this.world.getGameRules().getBoolean("mobGriefing")); + } + // CraftBukkit end + + // CraftBukkit start - Use relative location for far away sounds + // this.world.a(1013, new BlockPosition(this), 0); + int viewDistance = this.world.getServer().getViewDistance() * 16; + for (EntityPlayer player : MinecraftServer.getServer().getPlayerList().players) { + double deltaX = this.locX - player.locX; + double deltaZ = this.locZ - player.locZ; + double distanceSquared = deltaX * deltaX + deltaZ * deltaZ; + if (world.spigotConfig.witherSpawnSoundRadius > 0 && distanceSquared > world.spigotConfig.witherSpawnSoundRadius * world.spigotConfig.witherSpawnSoundRadius) + continue; // Spigot + if (distanceSquared > viewDistance * viewDistance) { + double deltaLength = Math.sqrt(distanceSquared); + double relativeX = player.locX + (deltaX / deltaLength) * viewDistance; + double relativeZ = player.locZ + (deltaZ / deltaLength) * viewDistance; + player.playerConnection.sendPacket(new PacketPlayOutWorldEvent(1013, new BlockPosition((int) relativeX, (int) this.locY, (int) relativeZ), 0, true)); + } else { + player.playerConnection.sendPacket(new PacketPlayOutWorldEvent(1013, new BlockPosition((int) this.locX, (int) this.locY, (int) this.locZ), 0, true)); + } + } + // CraftBukkit end + } + + this.r(i); + if (this.ticksLived % 10 == 0) { + this.heal(10.0F, EntityRegainHealthEvent.RegainReason.WITHER_SPAWN); // CraftBukkit + } + + } else { + super.E(); + + int j; + + for (i = 1; i < 3; ++i) { + if (this.ticksLived >= this.bn[i - 1]) { + this.bn[i - 1] = this.ticksLived + 10 + random.nextInt(10); + if (this.world.getDifficulty() == EnumDifficulty.NORMAL || this.world.getDifficulty() == EnumDifficulty.HARD) { + int k = i - 1; + int l = this.bo[i - 1]; + + this.bo[k] = this.bo[i - 1] + 1; + if (l > 15) { + float f = 10.0F; + float f1 = 5.0F; + double d0 = MathHelper.a(random, this.locX - (double) f, this.locX + (double) f); + double d1 = MathHelper.a(random, this.locY - (double) f1, this.locY + (double) f1); + double d2 = MathHelper.a(random, this.locZ - (double) f, this.locZ + (double) f); + + this.a(i + 1, d0, d1, d2, true); + this.bo[i - 1] = 0; + } + } + + j = this.s(i); + if (j > 0) { + Entity entity = this.world.a(j); + + if (entity != null && entity.isAlive() && this.h(entity) <= 900.0D && this.hasLineOfSight(entity)) { + if (entity instanceof EntityHuman && ((EntityHuman) entity).abilities.isInvulnerable) { + this.b(i, 0); + } else { + this.a(i + 1, (EntityLiving) entity); + this.bn[i - 1] = this.ticksLived + 40 + random.nextInt(20); + this.bo[i - 1] = 0; + } + } else { + this.b(i, 0); + } + } else { + List list = this.world.a(EntityLiving.class, this.getBoundingBox().grow(20.0D, 8.0D, 20.0D), Predicates.and(EntityWither.bq, IEntitySelector.d)); + + for (int i1 = 0; i1 < 10 && !list.isEmpty(); ++i1) { + EntityLiving entityliving = list.get(random.nextInt(list.size())); + + if (entityliving != this && entityliving.isAlive() && this.hasLineOfSight(entityliving)) { + if (entityliving instanceof EntityHuman) { + if (!((EntityHuman) entityliving).abilities.isInvulnerable) { + this.b(i, entityliving.getId()); + } + } else { + this.b(i, entityliving.getId()); + } + break; + } + + list.remove(entityliving); + } + } + } + } + + if (this.getGoalTarget() != null) { + this.b(0, this.getGoalTarget().getId()); + } else { + this.b(0, 0); + } + + if (this.bp > 0) { + --this.bp; + if (this.bp == 0 && this.world.getGameRules().getBoolean("mobGriefing")) { + i = MathHelper.floor(this.locY); + j = MathHelper.floor(this.locX); + int j1 = MathHelper.floor(this.locZ); + boolean flag = false; + + for (int k1 = -1; k1 <= 1; ++k1) { + for (int l1 = -1; l1 <= 1; ++l1) { + for (int i2 = 0; i2 <= 3; ++i2) { + int j2 = j + k1; + int k2 = i + i2; + int l2 = j1 + l1; + BlockPosition blockposition = new BlockPosition(j2, k2, l2); + Block block = this.world.getType(blockposition).getBlock(); + + if (block.getMaterial() != Material.AIR && a(block)) { + // CraftBukkit start + if (CraftEventFactory.callEntityChangeBlockEvent(this, j2, k2, l2, Blocks.AIR, 0).isCancelled()) { + continue; + } + // CraftBukkit end + flag = this.world.setAir(blockposition, true) || flag; + } + } + } + } + + if (flag) { + this.world.a(null, 1012, new BlockPosition(this), 0); + } + } + } + + if (this.ticksLived % 20 == 0) { + this.heal(1.0F, EntityRegainHealthEvent.RegainReason.REGEN); // CraftBukkit + } + + } + } + + public void n() { + this.r(220); + this.setHealth(this.getMaxHealth() / 3.0F); + } + + public void aA() { + } + + public int br() { + return 4; + } + + private double t(int i) { + if (i <= 0) { + return this.locX; + } else { + float f = (this.aI + (float) (180 * (i - 1))) / 180.0F * 3.1415927F; + float f1 = MathHelper.cos(f); + + return this.locX + (double) f1 * 1.3D; + } + } + + private double u(int i) { + return i <= 0 ? this.locY + 3.0D : this.locY + 2.2D; + } + + private double v(int i) { + if (i <= 0) { + return this.locZ; + } else { + float f = (this.aI + (float) (180 * (i - 1))) / 180.0F * 3.1415927F; + float f1 = MathHelper.sin(f); + + return this.locZ + (double) f1 * 1.3D; + } + } + + private float b(float f, float f1, float f2) { + float f3 = MathHelper.g(f1 - f); + + if (f3 > f2) { + f3 = f2; + } + + if (f3 < -f2) { + f3 = -f2; + } + + return f + f3; + } + + private void a(int i, EntityLiving entityliving) { + this.a(i, entityliving.locX, entityliving.locY + (double) entityliving.getHeadHeight() * 0.5D, entityliving.locZ, i == 0 && random.nextFloat() < 0.001F); + } + + private void a(int i, double d0, double d1, double d2, boolean flag) { + this.world.a(null, 1014, new BlockPosition(this), 0); + double d3 = this.t(i); + double d4 = this.u(i); + double d5 = this.v(i); + double d6 = d0 - d3; + double d7 = d1 - d4; + double d8 = d2 - d5; + EntityWitherSkull entitywitherskull = new EntityWitherSkull(this.world, this, d6, d7, d8); + + if (flag) { + entitywitherskull.setCharged(true); + } + + entitywitherskull.locY = d4; + entitywitherskull.locX = d3; + entitywitherskull.locZ = d5; + this.world.addEntity(entitywitherskull); + } + + public void a(EntityLiving entityliving, float f) { + this.a(0, entityliving); + } + + public boolean damageEntity(DamageSource damagesource, float f) { + if (this.isInvulnerable(damagesource)) { + return false; + } else if (damagesource != DamageSource.DROWN && !(damagesource.getEntity() instanceof EntityWither)) { + if (this.cl() > 0 && damagesource != DamageSource.OUT_OF_WORLD) { + return false; + } else { + Entity entity; + + if (this.cm()) { + entity = damagesource.i(); + if (entity instanceof EntityArrow) { + return false; + } + } + + entity = damagesource.getEntity(); + if (!(entity instanceof EntityHuman) && entity instanceof EntityLiving && ((EntityLiving) entity).getMonsterType() == this.getMonsterType()) { + return false; + } else { + if (this.bp <= 0) { + this.bp = 20; + } + + for (int i = 0; i < this.bo.length; ++i) { + this.bo[i] += 3; + } + + return super.damageEntity(damagesource, f); + } + } + } else { + return false; + } + } + + protected void dropDeathLoot(boolean flag, int i) { + EntityItem entityitem = this.a(Items.NETHER_STAR, 1); + + if (entityitem != null) { + entityitem.u(); + } + + if (!this.world.isClientSide) { + for (EntityHuman entityhuman : this.world.a(EntityHuman.class, this.getBoundingBox().grow(50.0D, 100.0D, 50.0D))) { + entityhuman.b(AchievementList.J); + } + } + } + + protected void D() { + this.ticksFarFromPlayer = 0; + } + + public void e(float f, float f1) { + } + + public void addEffect(MobEffect mobeffect) { + } + + protected void initAttributes() { + super.initAttributes(); + this.getAttributeInstance(GenericAttributes.maxHealth).setValue(300.0D); + this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.6000000238418579D); + this.getAttributeInstance(GenericAttributes.FOLLOW_RANGE).setValue(40.0D); + } + + public int cl() { + return this.datawatcher.getInt(20); + } + + public void r(int i) { + this.datawatcher.watch(20, i); + } + + public int s(int i) { + return this.datawatcher.getInt(17 + i); + } + + public void b(int i, int j) { + this.datawatcher.watch(17 + i, j); + } + + public boolean cm() { + return this.getHealth() <= this.getMaxHealth() / 2.0F; + } + + public EnumMonsterType getMonsterType() { + return EnumMonsterType.UNDEAD; + } + + public void mount(Entity entity) { + this.vehicle = null; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityWitherSkull.java b/azurite-server/src/main/java/net/minecraft/server/EntityWitherSkull.java new file mode 100644 index 0000000..fc97274 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityWitherSkull.java @@ -0,0 +1,103 @@ +package net.minecraft.server; + +import org.bukkit.event.entity.ExplosionPrimeEvent; +import org.bukkit.event.entity.PotionEffectAddEvent; + +public class EntityWitherSkull extends EntityFireball { + + public EntityWitherSkull(World world) { + super(world); + this.setSize(0.3125F, 0.3125F); + } + + public EntityWitherSkull(World world, EntityLiving entityliving, double d0, double d1, double d2) { + super(world, entityliving, d0, d1, d2); + this.setSize(0.3125F, 0.3125F); + } + + protected float j() { + return this.isCharged() ? 0.73F : super.j(); + } + + public boolean isBurning() { + return false; + } + + public float a(Explosion explosion, World world, BlockPosition blockposition, IBlockData iblockdata) { + float f = super.a(explosion, world, blockposition, iblockdata); + Block block = iblockdata.getBlock(); + + if (this.isCharged() && EntityWither.a(block)) { + f = Math.min(0.8F, f); + } + + return f; + } + + protected void a(MovingObjectPosition movingobjectposition) { + + if (movingobjectposition.entity != null) { + // Spigot start + boolean didDamage; + if (this.shooter != null) { + didDamage = movingobjectposition.entity.damageEntity(DamageSource.projectile(this, shooter), 8.0F); + if (didDamage) { + if (!movingobjectposition.entity.isAlive()) { + this.shooter.heal(5.0F, org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason.WITHER); // CraftBukkit + } else { + this.a(this.shooter, movingobjectposition.entity); + } + } + } else { + didDamage = movingobjectposition.entity.damageEntity(DamageSource.MAGIC, 5.0F); + } + + if (didDamage && movingobjectposition.entity instanceof EntityLiving) { + // Spigot end + byte b0 = 0; + + if (this.world.getDifficulty() == EnumDifficulty.NORMAL) { + b0 = 10; + } else if (this.world.getDifficulty() == EnumDifficulty.HARD) { + b0 = 40; + } + + if (b0 > 0) { + ((EntityLiving) movingobjectposition.entity).addEffect(new MobEffect(MobEffectList.WITHER.id, 20 * b0, 1), PotionEffectAddEvent.EffectCause.WITHER_SKULL); + } + } + } + + // CraftBukkit start + // this.world.createExplosion(this, this.locX, this.locY, this.locZ, 1.0F, false, this.world.getGameRules().getBoolean("mobGriefing")); + ExplosionPrimeEvent event = new ExplosionPrimeEvent(this.getBukkitEntity(), 1.0F, false); + this.world.getServer().getPluginManager().callEvent(event); + + if (!event.isCancelled()) { + this.world.createExplosion(this, this.locX, this.locY, this.locZ, event.getRadius(), event.getFire(), this.world.getGameRules().getBoolean("mobGriefing")); + } + // CraftBukkit end + this.die(); + + } + + public boolean ad() { + return false; + } + + public boolean damageEntity(DamageSource damagesource, float f) { + return false; + } + + protected void h() { + this.datawatcher.a(10, (byte) 0); + } + + public boolean isCharged() { + return this.datawatcher.getByte(10) == 1; + } + + public void setCharged(boolean flag) { + this.datawatcher.watch(10, (byte) (flag ? 1 : 0)); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityWolf.java b/azurite-server/src/main/java/net/minecraft/server/EntityWolf.java new file mode 100644 index 0000000..5ffcca9 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityWolf.java @@ -0,0 +1,402 @@ +package net.minecraft.server; + +import com.google.common.base.Predicate; +import org.bukkit.craftbukkit.event.CraftEventFactory; +import org.bukkit.event.entity.EntityTargetEvent.TargetReason; +// CraftBukkit end + +public class EntityWolf extends EntityTameableAnimal { + + private float bo; + private boolean bq; + private boolean br; + private float bs; + private float bt; + + public EntityWolf(World world) { + super(world); + this.setSize(0.6F, 0.8F); + ((Navigation) this.getNavigation()).a(true); + this.goalSelector.a(1, new PathfinderGoalFloat(this)); + this.goalSelector.a(2, this.bm); + this.goalSelector.a(3, new PathfinderGoalLeapAtTarget(this, 0.4F)); + this.goalSelector.a(4, new PathfinderGoalMeleeAttack(this, 1.0D, true)); + this.goalSelector.a(5, new PathfinderGoalFollowOwner(this, 1.0D, 10.0F, 2.0F)); + this.goalSelector.a(6, new PathfinderGoalBreed(this, 1.0D)); + this.goalSelector.a(7, new PathfinderGoalRandomStroll(this, 1.0D)); + this.goalSelector.a(8, new PathfinderGoalBeg(this, 8.0F)); + this.goalSelector.a(9, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 8.0F)); + this.goalSelector.a(9, new PathfinderGoalRandomLookaround(this)); + this.targetSelector.a(1, new PathfinderGoalOwnerHurtByTarget(this)); + this.targetSelector.a(2, new PathfinderGoalOwnerHurtTarget(this)); + this.targetSelector.a(3, new PathfinderGoalHurtByTarget(this, true)); + this.targetSelector.a(4, new PathfinderGoalRandomTargetNonTamed<>(this, EntityAnimal.class, false, new Predicate() { + public boolean a(Entity entity) { + return entity instanceof EntitySheep || entity instanceof EntityRabbit; + } + + public boolean apply(Object object) { + return this.a((Entity) object); + } + })); + this.targetSelector.a(5, new PathfinderGoalNearestAttackableTarget<>(this, EntitySkeleton.class, false)); + this.setTamed(false); + } + + protected void initAttributes() { + super.initAttributes(); + this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.30000001192092896D); + if (this.isTamed()) { + this.getAttributeInstance(GenericAttributes.maxHealth).setValue(20.0D); + } else { + this.getAttributeInstance(GenericAttributes.maxHealth).setValue(8.0D); + } + + this.getAttributeMap().b(GenericAttributes.ATTACK_DAMAGE); + this.getAttributeInstance(GenericAttributes.ATTACK_DAMAGE).setValue(2.0D); + } + + public void setGoalTarget(EntityLiving entityliving) { + super.setGoalTarget(entityliving); + if (entityliving == null) { + this.setAngry(false); + } else if (!this.isTamed()) { + this.setAngry(true); + } + + } + + // CraftBukkit - add overriden version + @Override + public void setGoalTarget(EntityLiving entityliving, org.bukkit.event.entity.EntityTargetEvent.TargetReason reason, boolean fire) { + super.setGoalTarget(entityliving, reason, fire); + if (entityliving == null) { + this.setAngry(false); + } else if (!this.isTamed()) { + this.setAngry(true); + } + } + // CraftBukkit end + + protected void E() { + this.datawatcher.watch(18, this.getHealth()); + } + + protected void h() { + super.h(); + this.datawatcher.a(18, this.getHealth()); + this.datawatcher.a(19, (byte) 0); + this.datawatcher.a(20, (byte) EnumColor.RED.getColorIndex()); + } + + protected void a(BlockPosition blockposition, Block block) { + this.makeSound("mob.wolf.step", 0.15F, 1.0F); + } + + public void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + nbttagcompound.setBoolean("Angry", this.isAngry()); + nbttagcompound.setByte("CollarColor", (byte) this.getCollarColor().getInvColorIndex()); + } + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + this.setAngry(nbttagcompound.getBoolean("Angry")); + if (nbttagcompound.hasKeyOfType("CollarColor", 99)) { + this.setCollarColor(EnumColor.fromInvColorIndex(nbttagcompound.getByte("CollarColor"))); + } + + } + + protected String z() { + // CraftBukkit - (getFloat(18) < 10) -> (getFloat(18) < this.getMaxHealth() / 2) + return this.isAngry() ? "mob.wolf.growl" : (random.nextInt(3) == 0 ? (this.isTamed() && this.datawatcher.getFloat(18) < this.getMaxHealth() / 2 ? "mob.wolf.whine" : "mob.wolf.panting") : "mob.wolf.bark"); + } + + protected String bo() { + return "mob.wolf.hurt"; + } + + protected String bp() { + return "mob.wolf.death"; + } + + protected float bB() { + return 0.4F; + } + + protected Item getLoot() { + return Item.getById(-1); + } + + public void m() { + super.m(); + if (this.bq && !this.br && !this.cf() && this.onGround) { + this.br = true; + this.bs = 0.0F; + this.bt = 0.0F; + this.world.broadcastEntityEffect(this, (byte) 8); + } + + if (this.getGoalTarget() == null && this.isAngry()) { + this.setAngry(false); + } + + } + + public void t_() { + super.t_(); + + if (this.cx()) { + this.bo += (1.0F - this.bo) * 0.4F; + } else { + this.bo += (0.0F - this.bo) * 0.4F; + } + + if (this.U()) { + this.bq = true; + this.br = false; + this.bs = 0.0F; + this.bt = 0.0F; + } else if ((this.bq || this.br) && this.br) { + if (this.bs == 0.0F) { + this.makeSound("mob.wolf.shake", this.bB(), (random.nextFloat() - random.nextFloat()) * 0.2F + 1.0F); + } + + this.bt = this.bs; + this.bs += 0.05F; + if (this.bt >= 2.0F) { + this.bq = false; + this.br = false; + this.bt = 0.0F; + this.bs = 0.0F; + } + + if (this.bs > 0.4F) { + float f = (float) this.getBoundingBox().b; + int i = (int) (MathHelper.sin((this.bs - 0.4F) * 3.1415927F) * 7.0F); + + for (int j = 0; j < i; ++j) { + float f1 = (random.nextFloat() * 2.0F - 1.0F) * this.width * 0.5F; + float f2 = (random.nextFloat() * 2.0F - 1.0F) * this.width * 0.5F; + + this.world.addParticle(EnumParticle.WATER_SPLASH, this.locX + f1, (f + 0.8F), this.locZ + f2, this.motX, this.motY, this.motZ, EnumParticle.EMPTY_ARRAY); + } + } + } + + } + + public float getHeadHeight() { + return this.length * 0.8F; + } + + public int bQ() { + return this.isSitting() ? 20 : super.bQ(); + } + + public boolean damageEntity(DamageSource damagesource, float f) { + if (this.isInvulnerable(damagesource)) { + return false; + } else { + Entity entity = damagesource.getEntity(); + + // CraftBukkit - moved into EntityLiving.d(DamageSource, float) + // this.bm.setSitting(false); + if (entity != null && !(entity instanceof EntityHuman) && !(entity instanceof EntityArrow)) { + f = (f + 1.0F) / 2.0F; + } + + return super.damageEntity(damagesource, f); + } + } + + public boolean r(Entity entity) { + boolean flag = entity.damageEntity(DamageSource.mobAttack(this), (float) ((int) this.getAttributeInstance(GenericAttributes.ATTACK_DAMAGE).getValue())); + + if (flag) { + this.a(this, entity); + } + + return flag; + } + + public void setTamed(boolean flag) { + super.setTamed(flag); + if (flag) { + this.getAttributeInstance(GenericAttributes.maxHealth).setValue(20.0D); + } else { + this.getAttributeInstance(GenericAttributes.maxHealth).setValue(8.0D); + } + + this.getAttributeInstance(GenericAttributes.ATTACK_DAMAGE).setValue(4.0D); + } + + public boolean a(EntityHuman entityhuman) { + ItemStack itemstack = entityhuman.inventory.getItemInHand(); + + if (this.isTamed()) { + if (itemstack != null) { + if (itemstack.getItem() instanceof ItemFood) { + ItemFood itemfood = (ItemFood) itemstack.getItem(); + + if (itemfood.g() && this.datawatcher.getFloat(18) < 20.0F) { + if (!entityhuman.abilities.canInstantlyBuild) { + --itemstack.count; + } + + this.heal((float) itemfood.getNutrition(itemstack), org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason.EATING); // CraftBukkit + if (itemstack.count <= 0) { + entityhuman.inventory.setItem(entityhuman.inventory.itemInHandIndex, null); + } + + return true; + } + } else if (itemstack.getItem() == Items.DYE) { + EnumColor enumcolor = EnumColor.fromInvColorIndex(itemstack.getData()); + + if (enumcolor != this.getCollarColor()) { + this.setCollarColor(enumcolor); + if (!entityhuman.abilities.canInstantlyBuild && --itemstack.count <= 0) { + entityhuman.inventory.setItem(entityhuman.inventory.itemInHandIndex, null); + } + + return true; + } + } + } + + if (this.e((EntityLiving) entityhuman) && !this.d(itemstack)) { + this.bm.setSitting(!this.isSitting()); + this.aY = false; + this.navigation.n(); + this.setGoalTarget(null, TargetReason.FORGOT_TARGET, true); // CraftBukkit - reason + } + } else if (itemstack != null && itemstack.getItem() == Items.BONE && !this.isAngry()) { + if (!entityhuman.abilities.canInstantlyBuild) { + --itemstack.count; + } + + if (itemstack.count <= 0) { + entityhuman.inventory.setItem(entityhuman.inventory.itemInHandIndex, null); + } + + // CraftBukkit - added event call and isCancelled check. + if (random.nextInt(3) == 0 && !CraftEventFactory.callEntityTameEvent(this, entityhuman).isCancelled()) { + this.setTamed(true); + this.navigation.n(); + this.setGoalTarget(null, TargetReason.FORGOT_TARGET, true); + this.bm.setSitting(true); + this.setHealth(this.getMaxHealth()); // CraftBukkit - 20.0 -> getMaxHealth() + this.setOwnerUUID(entityhuman.getUniqueID().toString()); + this.l(true); + this.world.broadcastEntityEffect(this, (byte) 7); + } else { + this.l(false); + this.world.broadcastEntityEffect(this, (byte) 6); + } + + return true; + } + + return super.a(entityhuman); + } + + public boolean d(ItemStack itemstack) { + return itemstack != null && (itemstack.getItem() instanceof ItemFood && ((ItemFood) itemstack.getItem()).g()); + } + + public int bV() { + return 8; + } + + public boolean isAngry() { + return (this.datawatcher.getByte(16) & 2) != 0; + } + + public void setAngry(boolean flag) { + byte b0 = this.datawatcher.getByte(16); + + if (flag) { + this.datawatcher.watch(16, (byte) (b0 | 2)); + } else { + this.datawatcher.watch(16, (byte) (b0 & -3)); + } + + } + + public EnumColor getCollarColor() { + return EnumColor.fromInvColorIndex(this.datawatcher.getByte(20) & 15); + } + + public void setCollarColor(EnumColor enumcolor) { + this.datawatcher.watch(20, (byte) (enumcolor.getInvColorIndex() & 15)); + } + + public EntityWolf b(EntityAgeable entityageable) { + EntityWolf entitywolf = new EntityWolf(this.world); + String s = this.getOwnerUUID(); + + if (s != null && !s.trim().isEmpty()) { + entitywolf.setOwnerUUID(s); + entitywolf.setTamed(true); + } + + return entitywolf; + } + + public void p(boolean flag) { + if (flag) { + this.datawatcher.watch(19, (byte) 1); + } else { + this.datawatcher.watch(19, (byte) 0); + } + + } + + public boolean mate(EntityAnimal entityanimal) { + if (entityanimal == this) { + return false; + } else if (!this.isTamed()) { + return false; + } else if (!(entityanimal instanceof EntityWolf)) { + return false; + } else { + EntityWolf entitywolf = (EntityWolf) entityanimal; + + return entitywolf.isTamed() && (!entitywolf.isSitting() && this.isInLove() && entitywolf.isInLove()); + } + } + + public boolean cx() { + return this.datawatcher.getByte(19) == 1; + } + + public boolean isTypeNotPersistent() { + return !this.isTamed() /*&& this.ticksLived > 2400*/; // CraftBukkit + } + + public boolean a(EntityLiving entityliving, EntityLiving entityliving1) { + if (!(entityliving instanceof EntityCreeper) && !(entityliving instanceof EntityGhast)) { + if (entityliving instanceof EntityWolf) { + EntityWolf entitywolf = (EntityWolf) entityliving; + + if (entitywolf.isTamed() && entitywolf.getOwner() == entityliving1) { + return false; + } + } + + return (!(entityliving instanceof EntityHuman) || !(entityliving1 instanceof EntityHuman) || ((EntityHuman) entityliving1).a((EntityHuman) entityliving)) && (!(entityliving instanceof EntityHorse) || !((EntityHorse) entityliving).isTame()); + } else { + return false; + } + } + + public boolean cb() { + return !this.isAngry() && super.cb(); + } + + public EntityAgeable createChild(EntityAgeable entityageable) { + return this.b(entityageable); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EntityZombie.java b/azurite-server/src/main/java/net/minecraft/server/EntityZombie.java new file mode 100644 index 0000000..6e5deb6 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EntityZombie.java @@ -0,0 +1,567 @@ +package net.minecraft.server; + +import com.eatthepath.uuid.FastUUID; +import dev.azurite.spigot.configs.AzuriteConfig; +import org.bukkit.event.entity.CreatureSpawnEvent; +import org.bukkit.event.entity.EntityCombustByEntityEvent; +import org.bukkit.event.entity.EntityCombustEvent; +import org.bukkit.event.entity.EntityTargetEvent; + +import java.util.List; +import java.util.UUID; + +public class EntityZombie extends EntityMonster { + + protected static final IAttribute a = (new AttributeRanged(null, "zombie.spawnReinforcements", 0.0D, 0.0D, 1.0D)).a("Spawn Reinforcements Chance"); + private static final UUID b = FastUUID.parseUUID("B9766B59-9566-4402-BC1F-2EE2A276D836"); + private static final AttributeModifier c = new AttributeModifier(EntityZombie.b, "Baby speed boost", org.github.paperspigot.PaperSpigotConfig.babyZombieMovementSpeed, 1); // PaperSpigot - Configurable baby zombie movement speed + private final PathfinderGoalBreakDoor bm = new PathfinderGoalBreakDoor(this); + private int bn; + private boolean bo = false; + private float bp = -1.0F; + private float bq; + private int lastTick = MinecraftServer.currentTick; // CraftBukkit - add field + + public EntityZombie(World world) { + super(world); + ((Navigation) this.getNavigation()).b(true); + this.goalSelector.a(0, new PathfinderGoalFloat(this)); + this.goalSelector.a(2, new PathfinderGoalMeleeAttack(this, EntityHuman.class, 1.0D, false)); + this.goalSelector.a(5, new PathfinderGoalMoveTowardsRestriction(this, 1.0D)); + this.goalSelector.a(7, new PathfinderGoalRandomStroll(this, 1.0D)); + this.goalSelector.a(8, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 8.0F)); + this.goalSelector.a(8, new PathfinderGoalRandomLookaround(this)); + this.n(); + this.setSize(0.6F, 1.95F); + } + + protected void n() { + if (world.spigotConfig.zombieAggressiveTowardsVillager) + this.goalSelector.a(4, new PathfinderGoalMeleeAttack(this, EntityVillager.class, 1.0D, true)); // Spigot + this.goalSelector.a(4, new PathfinderGoalMeleeAttack(this, EntityIronGolem.class, 1.0D, true)); + this.goalSelector.a(6, new PathfinderGoalMoveThroughVillage(this, 1.0D, false)); + this.targetSelector.a(1, new PathfinderGoalHurtByTarget(this, true, EntityPigZombie.class)); + this.targetSelector.a(2, new PathfinderGoalNearestAttackableTarget<>(this, EntityHuman.class, true)); + if (world.spigotConfig.zombieAggressiveTowardsVillager) + this.targetSelector.a(2, new PathfinderGoalNearestAttackableTarget<>(this, EntityVillager.class, false)); // Spigot + this.targetSelector.a(2, new PathfinderGoalNearestAttackableTarget<>(this, EntityIronGolem.class, true)); + } + + protected void initAttributes() { + super.initAttributes(); + this.getAttributeInstance(GenericAttributes.FOLLOW_RANGE).setValue(16.0D); + this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.23000000417232513D); + this.getAttributeInstance(GenericAttributes.ATTACK_DAMAGE).setValue(3.0D); + this.getAttributeMap().b(EntityZombie.a).setValue(random.nextDouble() * 0.10000000149011612D); + } + + protected void h() { + super.h(); + this.getDataWatcher().a(12, (byte) 0); + this.getDataWatcher().a(13, (byte) 0); + this.getDataWatcher().a(14, (byte) 0); + } + + public int br() { + int i = super.br() + 2; + + if (i > 20) { + i = 20; + } + + return i; + } + + public boolean cn() { + return this.bo; + } + + public void a(boolean flag) { + if (this.bo != flag) { + this.bo = flag; + if (flag) { + this.goalSelector.a(1, this.bm); + } else { + this.goalSelector.a(this.bm); + } + } + + } + + public boolean isBaby() { + return this.getDataWatcher().getByte(12) == 1; + } + + protected int getExpValue(EntityHuman entityhuman) { + + return super.getExpValue(entityhuman); + } + + public void setBaby(boolean flag) { + this.getDataWatcher().watch(12, (byte) (flag ? 1 : 0)); + if (this.world != null) { + AttributeInstance attributeinstance = this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED); + + attributeinstance.c(EntityZombie.c); + if (flag) { + attributeinstance.b(EntityZombie.c); + } + } + + this.n(flag); + } + + public boolean isVillager() { + return this.getDataWatcher().getByte(13) == 1; + } + + public void setVillager(boolean flag) { + this.getDataWatcher().watch(13, (byte) (flag ? 1 : 0)); + } + + public void m() { + if (this.world.w() && !this.isBaby()) { + float f = this.c(1.0F); + if (f > 0.5F && random.nextFloat() * 30.0F < (f - 0.4F) * 2.0F && this.world.i(MathHelper.floor(this.locX), MathHelper.floor(Math.round(this.locY)), MathHelper.floor(this.locZ))) { + boolean flag = true; + ItemStack itemstack = this.getEquipment(4); + + if (itemstack != null) { + if (itemstack.e()) { + itemstack.setData(itemstack.h() + random.nextInt(2)); + if (itemstack.h() >= itemstack.j()) { + this.b(itemstack); + this.setEquipment(4, null); + } + } + + flag = false; + } + + if (flag) { + // CraftBukkit start + EntityCombustEvent event = new EntityCombustEvent(this.getBukkitEntity(), 8); + this.world.getServer().getPluginManager().callEvent(event); + + if (!event.isCancelled()) { + this.setOnFire(event.getDuration()); + } + // CraftBukkit end + } + } + } + + if (this.au() && this.getGoalTarget() != null && this.vehicle instanceof EntityChicken) { + ((EntityInsentient) this.vehicle).getNavigation().a(this.getNavigation().j(), 1.5D); + } + + super.m(); + } + + public boolean damageEntity(DamageSource damagesource, float f) { + if (super.damageEntity(damagesource, f)) { + EntityLiving entityliving = this.getGoalTarget(); + + if (entityliving == null && damagesource.getEntity() instanceof EntityLiving) { + entityliving = (EntityLiving) damagesource.getEntity(); + } + + if (entityliving != null && this.world.getDifficulty() == EnumDifficulty.HARD && (double) random.nextFloat() < this.getAttributeInstance(EntityZombie.a).getValue()) { + int i = MathHelper.floor(this.locX); + int j = MathHelper.floor(this.locY); + int k = MathHelper.floor(this.locZ); + EntityZombie entityzombie = new EntityZombie(this.world); + + for (int l = 0; l < 50; ++l) { + int i1 = i + MathHelper.nextInt(random, 7, 40) * MathHelper.nextInt(random, -1, 1); + int j1 = j + MathHelper.nextInt(random, 7, 40) * MathHelper.nextInt(random, -1, 1); + int k1 = k + MathHelper.nextInt(random, 7, 40) * MathHelper.nextInt(random, -1, 1); + + if (World.a(this.world, i1, j1 - 1, k1) && !this.world.isLightLevel(i1, j1, k1, 10)) { + entityzombie.setPosition(i1, 1, k1); + if (!this.world.isPlayerNearby(i1, j1, k1, 7.0D) && this.world.a(entityzombie.getBoundingBox(), entityzombie) && this.world.getCubes(entityzombie, entityzombie.getBoundingBox()).isEmpty() && !this.world.containsLiquid(entityzombie.getBoundingBox())) { + this.world.addEntity(entityzombie, CreatureSpawnEvent.SpawnReason.REINFORCEMENTS); // CraftBukkit + entityzombie.setGoalTarget(entityliving, EntityTargetEvent.TargetReason.REINFORCEMENT_TARGET, true); + entityzombie.prepare(this.world.E(MathHelper.floor(entityzombie.locX), MathHelper.floor(entityzombie.locY), MathHelper.floor(entityzombie.locZ)), null); + this.getAttributeInstance(EntityZombie.a).b(new AttributeModifier("Zombie reinforcement caller charge", -0.05000000074505806D, 0)); + entityzombie.getAttributeInstance(EntityZombie.a).b(new AttributeModifier("Zombie reinforcement callee charge", -0.05000000074505806D, 0)); + break; + } + } + } + } + + return true; + } else { + return false; + } + } + + public void t_() { + if (this.cp()) { + int i = this.cr(); + + // CraftBukkit start - Use wall time instead of ticks for villager conversion + int elapsedTicks = MinecraftServer.currentTick - this.lastTick; + this.lastTick = MinecraftServer.currentTick; + i *= elapsedTicks; + // CraftBukkit end + + this.bn -= i; + if (this.bn <= 0) { + this.cq(); + } + } + + super.t_(); + } + + public boolean r(Entity entity) { + boolean flag = super.r(entity); + + if (flag) { + int i = this.world.getDifficulty().a(); + + if (this.bA() == null && this.isBurning() && random.nextFloat() < (float) i * 0.3F) { + // CraftBukkit start + EntityCombustByEntityEvent event = new EntityCombustByEntityEvent(this.getBukkitEntity(), entity.getBukkitEntity(), 2 * i); + this.world.getServer().getPluginManager().callEvent(event); + + if (!event.isCancelled()) { + entity.setOnFire(event.getDuration()); + } + // CraftBukkit end + } + } + + return flag; + } + + protected String z() { + return "mob.zombie.say"; + } + + protected String bo() { + return "mob.zombie.hurt"; + } + + protected String bp() { + return "mob.zombie.death"; + } + + protected void a(BlockPosition blockposition, Block block) { + this.makeSound("mob.zombie.step", 0.15F, 1.0F); + } + + protected Item getLoot() { + return Items.ROTTEN_FLESH; + } + + public EnumMonsterType getMonsterType() { + return EnumMonsterType.UNDEAD; + } + + protected void getRareDrop() { + switch (random.nextInt(3)) { + case 0: + this.a(Items.IRON_INGOT, 1); + break; + + case 1: + this.a(Items.CARROT, 1); + break; + + case 2: + this.a(Items.POTATO, 1); + } + + } + + protected void a(DifficultyDamageScaler difficultydamagescaler) { + super.a(difficultydamagescaler); + if (random.nextFloat() < (this.world.getDifficulty() == EnumDifficulty.HARD ? 0.05F : 0.01F)) { + int i = random.nextInt(3); + + if (i == 0) { + this.setEquipment(0, new ItemStack(Items.IRON_SWORD)); + } else { + this.setEquipment(0, new ItemStack(Items.IRON_SHOVEL)); + } + } + + } + + public void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + if (this.isBaby()) { + nbttagcompound.setBoolean("IsBaby", true); + } + + if (this.isVillager()) { + nbttagcompound.setBoolean("IsVillager", true); + } + + nbttagcompound.setInt("ConversionTime", this.cp() ? this.bn : -1); + nbttagcompound.setBoolean("CanBreakDoors", this.cn()); + } + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + if (nbttagcompound.getBoolean("IsBaby")) { + this.setBaby(true); + } + + if (nbttagcompound.getBoolean("IsVillager")) { + this.setVillager(true); + } + + if (nbttagcompound.hasKeyOfType("ConversionTime", 99) && nbttagcompound.getInt("ConversionTime") > -1) { + this.a(nbttagcompound.getInt("ConversionTime")); + } + + this.a(nbttagcompound.getBoolean("CanBreakDoors")); + } + + public void a(EntityLiving entityliving) { + super.a(entityliving); + if ((this.world.getDifficulty() == EnumDifficulty.NORMAL || this.world.getDifficulty() == EnumDifficulty.HARD) && entityliving instanceof EntityVillager) { + if (this.world.getDifficulty() != EnumDifficulty.HARD && random.nextBoolean()) { + return; + } + + EntityInsentient entityinsentient = (EntityInsentient) entityliving; + EntityZombie entityzombie = new EntityZombie(this.world); + + entityzombie.m(entityliving); + this.world.kill(entityliving); + entityzombie.prepare(this.world.E(MathHelper.floor(entityzombie.locX), MathHelper.floor(entityzombie.locY), MathHelper.floor(entityzombie.locZ)), null); + entityzombie.setVillager(true); + if (entityliving.isBaby()) { + entityzombie.setBaby(true); + } + + entityzombie.k(entityinsentient.ce()); + if (entityinsentient.hasCustomName()) { + entityzombie.setCustomName(entityinsentient.getCustomName()); + entityzombie.setCustomNameVisible(entityinsentient.getCustomNameVisible()); + } + + this.world.addEntity(entityzombie, CreatureSpawnEvent.SpawnReason.INFECTION); // CraftBukkit - add SpawnReason + this.world.a(null, 1016, new BlockPosition((int) this.locX, (int) this.locY, (int) this.locZ), 0); + } + + } + + public float getHeadHeight() { + float f = 1.74F; + + if (this.isBaby()) { + f = (float) ((double) f - 0.81D); + } + + return f; + } + + protected boolean a(ItemStack itemstack) { + return (itemstack.getItem() != Items.EGG || !this.isBaby() || !this.au()) && super.a(itemstack); + } + + public GroupDataEntity prepare(DifficultyDamageScaler difficultydamagescaler, GroupDataEntity groupdataentity) { + GroupDataEntity object = super.prepare(difficultydamagescaler, groupdataentity); + float f = difficultydamagescaler.c(); + + this.j(random.nextFloat() < 0.55F * f); + if (object == null) { + object = new GroupDataZombie(this.world.random.nextFloat() < 0.05F, this.world.random.nextFloat() < 0.05F, null); + } + + if (object instanceof GroupDataZombie) { + GroupDataZombie entityzombie_groupdatazombie = (GroupDataZombie) object; + + if (entityzombie_groupdatazombie.b && AzuriteConfig.villagerZombieSpawning.getValue()) { + this.setVillager(true); + } + + if (entityzombie_groupdatazombie.a && AzuriteConfig.babyZombieSpawning.getValue()) { + this.setBaby(true); + if (AzuriteConfig.zombieOnChickenSpawning.getValue()) { + if (world.random.nextFloat() < 0.05D) { + List list = world.a(EntityChicken.class, this.getBoundingBox().grow(5.0D, 3.0D, 5.0D), IEntitySelector.b); + + if (!list.isEmpty()) { + EntityChicken entitychicken = list.get(0); + + entitychicken.l(true); + this.mount(entitychicken); + } + } else if (world.random.nextFloat() < 0.05D) { + EntityChicken entitychicken1 = new EntityChicken(this.world); + + entitychicken1.setPositionRotation(this.locX, this.locY, this.locZ, this.yaw, 0.0F); + entitychicken1.prepare(difficultydamagescaler, null); + entitychicken1.l(true); + this.world.addEntity(entitychicken1, CreatureSpawnEvent.SpawnReason.MOUNT); + this.mount(entitychicken1); + } + } + } + } + + this.a(random.nextFloat() < f * 0.1F); + this.a(difficultydamagescaler); + this.b(difficultydamagescaler); + + this.getAttributeInstance(GenericAttributes.c).b(new AttributeModifier("Random spawn bonus", random.nextDouble() * 0.05000000074505806D, 0)); + double d0 = random.nextDouble() * 1.5D * (double) f; + + if (d0 > 1.0D) { + this.getAttributeInstance(GenericAttributes.FOLLOW_RANGE).b(new AttributeModifier("Random zombie-spawn bonus", d0, 2)); + } + + if (random.nextFloat() < f * 0.05F) { + this.getAttributeInstance(EntityZombie.a).b(new AttributeModifier("Leader zombie bonus", random.nextDouble() * 0.25D + 0.5D, 0)); + this.getAttributeInstance(GenericAttributes.maxHealth).b(new AttributeModifier("Leader zombie bonus", random.nextDouble() * 3.0D + 1.0D, 2)); + this.a(true); + } + + return object; + } + + public boolean a(EntityHuman entityhuman) { + ItemStack itemstack = entityhuman.bZ(); + + if (itemstack != null && itemstack.getItem() == Items.GOLDEN_APPLE && itemstack.getData() == 0 && this.isVillager() && this.hasEffect(MobEffectList.WEAKNESS)) { + if (!entityhuman.abilities.canInstantlyBuild) { + --itemstack.count; + } + + if (itemstack.count <= 0) { + entityhuman.inventory.setItem(entityhuman.inventory.itemInHandIndex, null); + } + + this.a(random.nextInt(2401) + 3600); + + return true; + } else { + return false; + } + } + + protected void a(int i) { + this.bn = i; + this.getDataWatcher().watch(14, (byte) 1); + this.removeEffect(MobEffectList.WEAKNESS.id); + this.addEffect(new MobEffect(MobEffectList.INCREASE_DAMAGE.id, i, Math.min(this.world.getDifficulty().a() - 1, 0))); + this.world.broadcastEntityEffect(this, (byte) 16); + } + + public boolean isTypeNotPersistent() { + return !this.cp(); + } + + public boolean cp() { + return this.getDataWatcher().getByte(14) == 1; + } + + protected void cq() { + EntityVillager entityvillager = new EntityVillager(this.world); + + entityvillager.m(this); + entityvillager.prepare(this.world.E(MathHelper.floor(entityvillager.locX), MathHelper.floor(entityvillager.locY), MathHelper.floor(entityvillager.locZ)), null); + entityvillager.cp(); + if (this.isBaby()) { + entityvillager.setAgeRaw(-24000); + } + + this.world.kill(this); + entityvillager.k(this.ce()); + if (this.hasCustomName()) { + entityvillager.setCustomName(this.getCustomName()); + entityvillager.setCustomNameVisible(this.getCustomNameVisible()); + } + + this.world.addEntity(entityvillager, CreatureSpawnEvent.SpawnReason.CURED); // CraftBukkit - add SpawnReason + entityvillager.addEffect(new MobEffect(MobEffectList.CONFUSION.id, 200, 0)); + this.world.a(null, 1017, new BlockPosition((int) this.locX, (int) this.locY, (int) this.locZ), 0); + } + + protected int cr() { + int i = 1; + + if (random.nextFloat() < 0.01F) { + int j = 0; + + for (int k = (int) this.locX - 4; k < (int) this.locX + 4 && j < 14; ++k) { + for (int l = (int) this.locY - 4; l < (int) this.locY + 4 && j < 14; ++l) { + for (int i1 = (int) this.locZ - 4; i1 < (int) this.locZ + 4 && j < 14; ++i1) { + Block block = this.world.getType(k, l, i1).getBlock(); + + if (block == Blocks.IRON_BARS || block == Blocks.BED) { + if (random.nextFloat() < 0.3F) { + ++i; + } + + ++j; + } + } + } + } + } + + return i; + } + + public void n(boolean flag) { + this.a(flag ? 0.5F : 1.0F); + } + + public final void setSize(float f, float f1) { // CraftBukkit - public + boolean flag = this.bp > 0.0F && this.bq > 0.0F; + + this.bp = f; + this.bq = f1; + if (!flag) { + this.a(1.0F); + } + + } + + protected final void a(float f) { + super.setSize(this.bp * f, this.bq * f); + } + + public double am() { + return this.isBaby() ? 0.0D : -0.35D; + } + + public void die(DamageSource damagesource) { + // super.die(damagesource); // CraftBukkit + if (damagesource.getEntity() instanceof EntityCreeper && !(this instanceof EntityPigZombie) && ((EntityCreeper) damagesource.getEntity()).isPowered() && ((EntityCreeper) damagesource.getEntity()).cp()) { + ((EntityCreeper) damagesource.getEntity()).cq(); + // CraftBukkit start + // this.a(new ItemStack(Items.SKULL, 1, 2), 0.0F); + headDrop = new ItemStack(Items.SKULL, 1, 2); + // CraftBukkit end + } + + super.die(damagesource); // CraftBukkit - moved from above + } + + static class SyntheticClass_1 { + } + + static class GroupDataZombie implements GroupDataEntity { + + public boolean a; + public boolean b; + + private GroupDataZombie(boolean flag, boolean flag1) { + this.a = flag; + this.b = flag1; + } + + GroupDataZombie(boolean flag, boolean flag1, SyntheticClass_1 entityzombie_syntheticclass_1) { + this(flag, flag1); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EnumAnimation.java b/azurite-server/src/main/java/net/minecraft/server/EnumAnimation.java new file mode 100644 index 0000000..8c0088a --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EnumAnimation.java @@ -0,0 +1,8 @@ +package net.minecraft.server; + +public enum EnumAnimation { + + NONE, EAT, DRINK, BLOCK, BOW; + + private EnumAnimation() {} +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EnumChatFormat.java b/azurite-server/src/main/java/net/minecraft/server/EnumChatFormat.java new file mode 100644 index 0000000..f0382a5 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EnumChatFormat.java @@ -0,0 +1,116 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Map; +import java.util.regex.Pattern; + +public enum EnumChatFormat { + + BLACK("BLACK", '0', 0), DARK_BLUE("DARK_BLUE", '1', 1), DARK_GREEN("DARK_GREEN", '2', 2), DARK_AQUA("DARK_AQUA", '3', 3), DARK_RED("DARK_RED", '4', 4), DARK_PURPLE("DARK_PURPLE", '5', 5), GOLD("GOLD", '6', 6), GRAY("GRAY", '7', 7), DARK_GRAY("DARK_GRAY", '8', 8), BLUE("BLUE", '9', 9), GREEN("GREEN", 'a', 10), AQUA("AQUA", 'b', 11), RED("RED", 'c', 12), LIGHT_PURPLE("LIGHT_PURPLE", 'd', 13), YELLOW("YELLOW", 'e', 14), WHITE("WHITE", 'f', 15), OBFUSCATED("OBFUSCATED", 'k', true), BOLD("BOLD", 'l', true), STRIKETHROUGH("STRIKETHROUGH", 'm', true), UNDERLINE("UNDERLINE", 'n', true), ITALIC("ITALIC", 'o', true), RESET("RESET", 'r', -1); + + private static final Map w = Maps.newHashMap(); + private static final Pattern x = Pattern.compile("(?i)" + String.valueOf('\u00a7') + "[0-9A-FK-OR]"); + private final String y; + private final char z; + private final boolean A; + private final String B; + private final int C; + + private static String c(String s) { + return s.toLowerCase().replaceAll("[^a-z]", ""); + } + + private EnumChatFormat(String s, char c0, int i) { + this(s, c0, false, i); + } + + private EnumChatFormat(String s, char c0, boolean flag) { + this(s, c0, flag, -1); + } + + private EnumChatFormat(String s, char c0, boolean flag, int i) { + this.y = s; + this.z = c0; + this.A = flag; + this.C = i; + this.B = "\u00a7" + c0; + } + + public int b() { + return this.C; + } + + public boolean isFormat() { + return this.A; + } + + public boolean d() { + return !this.A && this != EnumChatFormat.RESET; + } + + public String e() { + return this.name().toLowerCase(); + } + + public String toString() { + return this.B; + } + + public static String a(String s) { + return s == null ? null : EnumChatFormat.x.matcher(s).replaceAll(""); + } + + public static EnumChatFormat b(String s) { + return s == null ? null : (EnumChatFormat) EnumChatFormat.w.get(c(s)); + } + + public static EnumChatFormat a(int i) { + if (i < 0) { + return EnumChatFormat.RESET; + } else { + EnumChatFormat[] aenumchatformat = values(); + int j = aenumchatformat.length; + + for (int k = 0; k < j; ++k) { + EnumChatFormat enumchatformat = aenumchatformat[k]; + + if (enumchatformat.b() == i) { + return enumchatformat; + } + } + + return null; + } + } + + public static Collection a(boolean flag, boolean flag1) { + ArrayList arraylist = Lists.newArrayList(); + EnumChatFormat[] aenumchatformat = values(); + int i = aenumchatformat.length; + + for (int j = 0; j < i; ++j) { + EnumChatFormat enumchatformat = aenumchatformat[j]; + + if ((!enumchatformat.d() || flag) && (!enumchatformat.isFormat() || flag1)) { + arraylist.add(enumchatformat.e()); + } + } + + return arraylist; + } + + static { + EnumChatFormat[] aenumchatformat = values(); + int i = aenumchatformat.length; + + for (int j = 0; j < i; ++j) { + EnumChatFormat enumchatformat = aenumchatformat[j]; + + EnumChatFormat.w.put(c(enumchatformat.y), enumchatformat); + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EnumColor.java b/azurite-server/src/main/java/net/minecraft/server/EnumColor.java new file mode 100644 index 0000000..2bdaa0b --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EnumColor.java @@ -0,0 +1,77 @@ +package net.minecraft.server; + +public enum EnumColor implements INamable { + + WHITE(0, 15, "white", "white", MaterialMapColor.j, EnumChatFormat.WHITE), ORANGE(1, 14, "orange", "orange", MaterialMapColor.q, EnumChatFormat.GOLD), MAGENTA(2, 13, "magenta", "magenta", MaterialMapColor.r, EnumChatFormat.AQUA), LIGHT_BLUE(3, 12, "light_blue", "lightBlue", MaterialMapColor.s, EnumChatFormat.BLUE), YELLOW(4, 11, "yellow", "yellow", MaterialMapColor.t, EnumChatFormat.YELLOW), LIME(5, 10, "lime", "lime", MaterialMapColor.u, EnumChatFormat.GREEN), PINK(6, 9, "pink", "pink", MaterialMapColor.v, EnumChatFormat.LIGHT_PURPLE), GRAY(7, 8, "gray", "gray", MaterialMapColor.w, EnumChatFormat.DARK_GRAY), SILVER(8, 7, "silver", "silver", MaterialMapColor.x, EnumChatFormat.GRAY), CYAN(9, 6, "cyan", "cyan", MaterialMapColor.y, EnumChatFormat.DARK_AQUA), PURPLE(10, 5, "purple", "purple", MaterialMapColor.z, EnumChatFormat.DARK_PURPLE), BLUE(11, 4, "blue", "blue", MaterialMapColor.A, EnumChatFormat.DARK_BLUE), BROWN(12, 3, "brown", "brown", MaterialMapColor.B, EnumChatFormat.GOLD), GREEN(13, 2, "green", "green", MaterialMapColor.C, EnumChatFormat.DARK_GREEN), RED(14, 1, "red", "red", MaterialMapColor.D, EnumChatFormat.DARK_RED), BLACK(15, 0, "black", "black", MaterialMapColor.E, EnumChatFormat.BLACK); + + private static final EnumColor[] q = new EnumColor[values().length]; + private static final EnumColor[] r = new EnumColor[values().length]; + private final int s; + private final int t; + private final String u; + private final String v; + private final MaterialMapColor w; + private final EnumChatFormat x; + + private EnumColor(int i, int j, String s, String s1, MaterialMapColor materialmapcolor, EnumChatFormat enumchatformat) { + this.s = i; + this.t = j; + this.u = s; + this.v = s1; + this.w = materialmapcolor; + this.x = enumchatformat; + } + + public int getColorIndex() { + return this.s; + } + + public int getInvColorIndex() { + return this.t; + } + + public String d() { + return this.v; + } + + public MaterialMapColor e() { + return this.w; + } + + public static EnumColor fromInvColorIndex(int i) { + if (i < 0 || i >= EnumColor.r.length) { + i = 0; + } + + return EnumColor.r[i]; + } + + public static EnumColor fromColorIndex(int i) { + if (i < 0 || i >= EnumColor.q.length) { + i = 0; + } + + return EnumColor.q[i]; + } + + public String toString() { + return this.v; + } + + public String getName() { + return this.u; + } + + static { + EnumColor[] aenumcolor = values(); + int i = aenumcolor.length; + + for (int j = 0; j < i; ++j) { + EnumColor enumcolor = aenumcolor[j]; + + EnumColor.q[enumcolor.getColorIndex()] = enumcolor; + EnumColor.r[enumcolor.getInvColorIndex()] = enumcolor; + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EnumCreatureType.java b/azurite-server/src/main/java/net/minecraft/server/EnumCreatureType.java new file mode 100644 index 0000000..4ff3a93 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EnumCreatureType.java @@ -0,0 +1,42 @@ +package net.minecraft.server; + +public enum EnumCreatureType { + MONSTER(IMonster.class, 70, Material.AIR, false, false), + CREATURE(EntityAnimal.class, 10, Material.AIR, true, true), + AMBIENT(EntityAmbient.class, 15, Material.AIR, true, false), + WATER_CREATURE(EntityWaterAnimal.class, 5, Material.WATER, true, false); + + private final Class e; + private final int f; + private final Material g; + private final boolean h; + private final boolean i; + + EnumCreatureType(Class var3, int var4, Material var5, boolean var6, boolean var7) { + this.e = var3; + this.f = var4; + this.g = var5; + this.h = var6; + this.i = var7; + } + + public boolean matches(Entity entity) { + return a().isAssignableFrom(entity.getClass()); + } + + public Class a() { + return this.e; + } + + public int b() { + return this.f; + } + + public boolean d() { + return this.h; + } + + public boolean e() { + return this.i; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EnumDifficulty.java b/azurite-server/src/main/java/net/minecraft/server/EnumDifficulty.java new file mode 100644 index 0000000..7671000 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EnumDifficulty.java @@ -0,0 +1,39 @@ +package net.minecraft.server; + +public enum EnumDifficulty { + + PEACEFUL(0, "options.difficulty.peaceful"), EASY(1, "options.difficulty.easy"), NORMAL(2, "options.difficulty.normal"), HARD(3, "options.difficulty.hard"); + + private static final EnumDifficulty[] e = new EnumDifficulty[values().length]; + private final int f; + private final String g; + + private EnumDifficulty(int i, String s) { + this.f = i; + this.g = s; + } + + public int a() { + return this.f; + } + + public static EnumDifficulty getById(int i) { + return EnumDifficulty.e[i % EnumDifficulty.e.length]; + } + + public String b() { + return this.g; + } + + static { + EnumDifficulty[] aenumdifficulty = values(); + int i = aenumdifficulty.length; + + for (int j = 0; j < i; ++j) { + EnumDifficulty enumdifficulty = aenumdifficulty[j]; + + EnumDifficulty.e[enumdifficulty.f] = enumdifficulty; + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EnumDirection.java b/azurite-server/src/main/java/net/minecraft/server/EnumDirection.java new file mode 100644 index 0000000..a1a7b5a --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EnumDirection.java @@ -0,0 +1,343 @@ +package net.minecraft.server; + +import com.google.common.base.Predicate; +import com.google.common.collect.Iterators; +import com.google.common.collect.Maps; + +import java.util.Iterator; +import java.util.Map; +import java.util.Random; + +public enum EnumDirection implements INamable { + + DOWN(0, 1, -1, "down", EnumAxisDirection.NEGATIVE, EnumAxis.Y, new BaseBlockPosition(0, -1, 0)), + UP(1, 0, -1, "up", EnumAxisDirection.POSITIVE, EnumAxis.Y, new BaseBlockPosition(0, 1, 0)), + NORTH(2, 3, 2, "north", EnumAxisDirection.NEGATIVE, EnumAxis.Z, new BaseBlockPosition(0, 0, -1)), + SOUTH(3, 2, 0, "south", EnumAxisDirection.POSITIVE, EnumAxis.Z, new BaseBlockPosition(0, 0, 1)), + WEST(4, 5, 1, "west", EnumAxisDirection.NEGATIVE, EnumAxis.X, new BaseBlockPosition(-1, 0, 0)), + EAST(5, 4, 3, "east", EnumAxisDirection.POSITIVE, EnumAxis.X, new BaseBlockPosition(1, 0, 0)); + + private final int g; + private final int h; + private final int i; + private final String j; + private final EnumAxis k; + private final EnumAxisDirection l; + private final BaseBlockPosition m; + private static final EnumDirection[] n = new EnumDirection[6]; + private static final EnumDirection[] o = new EnumDirection[4]; + + EnumDirection(int i, int j, int k, String s, EnumAxisDirection enumdirection_enumaxisdirection, EnumAxis enumdirection_enumaxis, BaseBlockPosition baseblockposition) { + this.g = i; + this.i = k; + this.h = j; + this.j = s; + this.k = enumdirection_enumaxis; + this.l = enumdirection_enumaxisdirection; + this.m = baseblockposition; + } + + public int a() { + return this.g; + } + + public int b() { + return this.i; + } + + public EnumAxisDirection c() { + return this.l; + } + + public EnumDirection opposite() { + return fromType1(this.h); + } + + public EnumDirection e() { + switch (SyntheticClass_1.b[this.ordinal()]) { + case 1: + return EnumDirection.EAST; + + case 2: + return EnumDirection.SOUTH; + + case 3: + return EnumDirection.WEST; + + case 4: + return EnumDirection.NORTH; + + default: + throw new IllegalStateException("Unable to get Y-rotated facing of " + this); + } + } + + public EnumDirection f() { + switch (SyntheticClass_1.b[this.ordinal()]) { + case 1: + return EnumDirection.WEST; + + case 2: + return EnumDirection.NORTH; + + case 3: + return EnumDirection.EAST; + + case 4: + return EnumDirection.SOUTH; + + default: + throw new IllegalStateException("Unable to get CCW facing of " + this); + } + } + + public int getAdjacentX() { + return this.k == EnumAxis.X ? this.l.a() : 0; + } + + public int getAdjacentY() { + return this.k == EnumAxis.Y ? this.l.a() : 0; + } + + public int getAdjacentZ() { + return this.k == EnumAxis.Z ? this.l.a() : 0; + } + + public String j() { + return this.j; + } + + public EnumAxis k() { + return this.k; + } + + public static EnumDirection fromType1(int i) { + return EnumDirection.n[MathHelper.a(i % EnumDirection.n.length)]; + } + + public static EnumDirection fromType2(int i) { + return EnumDirection.o[MathHelper.a(i % EnumDirection.o.length)]; + } + + public static EnumDirection fromAngle(double d0) { + return fromType2(MathHelper.floor(d0 / 90.0D + 0.5D) & 3); + } + + public static EnumDirection a(Random random) { + return values()[random.nextInt(values().length)]; + } + + public String toString() { + return this.j; + } + + public String getName() { + return this.j; + } + + public static EnumDirection a(EnumAxisDirection enumdirection_enumaxisdirection, EnumAxis enumdirection_enumaxis) { + for (EnumDirection enumdirection : values()) { + if (enumdirection.c() == enumdirection_enumaxisdirection && enumdirection.k() == enumdirection_enumaxis) { + return enumdirection; + } + } + + throw new IllegalArgumentException("No such direction: " + enumdirection_enumaxisdirection + " " + enumdirection_enumaxis); + } + + static { + for (EnumDirection enumdirection : values()) { + EnumDirection.n[enumdirection.g] = enumdirection; + if (enumdirection.k().c()) { + EnumDirection.o[enumdirection.i] = enumdirection; + } + } + + } + + static class SyntheticClass_1 { + + static final int[] a; + static final int[] b; + static final int[] c = new int[EnumDirectionLimit.values().length]; + + static { + try { + SyntheticClass_1.c[EnumDirectionLimit.HORIZONTAL.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.c[EnumDirectionLimit.VERTICAL.ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + } + + b = new int[EnumDirection.values().length]; + + try { + SyntheticClass_1.b[EnumDirection.NORTH.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.b[EnumDirection.EAST.ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.b[EnumDirection.SOUTH.ordinal()] = 3; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.b[EnumDirection.WEST.ordinal()] = 4; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.b[EnumDirection.UP.ordinal()] = 5; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.b[EnumDirection.DOWN.ordinal()] = 6; + } catch (NoSuchFieldError ignored) { + } + + a = new int[EnumAxis.values().length]; + + try { + SyntheticClass_1.a[EnumAxis.X.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.a[EnumAxis.Y.ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.a[EnumAxis.Z.ordinal()] = 3; + } catch (NoSuchFieldError ignored) { + } + + } + } + + public BaseBlockPosition getBaseBlockPosition() + { + return m; + } + + public enum EnumDirectionLimit implements Predicate, Iterable { + + HORIZONTAL, VERTICAL; + + EnumDirectionLimit() {} + + public EnumDirection[] a() { + switch (SyntheticClass_1.c[this.ordinal()]) { + case 1: + return new EnumDirection[] { EnumDirection.NORTH, EnumDirection.EAST, EnumDirection.SOUTH, EnumDirection.WEST}; + + case 2: + return new EnumDirection[] { EnumDirection.UP, EnumDirection.DOWN}; + + default: + throw new Error("Someone's been tampering with the universe!"); + } + } + + public EnumDirection a(Random random) { + EnumDirection[] aenumdirection = this.a(); + + return aenumdirection[random.nextInt(aenumdirection.length)]; + } + + public boolean a(EnumDirection enumdirection) { + return enumdirection != null && enumdirection.k().d() == this; + } + + public Iterator iterator() { + return Iterators.forArray(this.a()); + } + + public boolean apply(EnumDirection object) { + return this.a(object); + } + } + + public enum EnumAxisDirection { + + POSITIVE(1, "Towards positive"), NEGATIVE(-1, "Towards negative"); + + private final int c; + private final String d; + + EnumAxisDirection(int i, String s) { + this.c = i; + this.d = s; + } + + public int a() { + return this.c; + } + + public String toString() { + return this.d; + } + } + + public enum EnumAxis implements Predicate, INamable { + + X("x", EnumDirectionLimit.HORIZONTAL), Y("y", EnumDirectionLimit.VERTICAL), Z("z", EnumDirectionLimit.HORIZONTAL); + + private static final Map d = Maps.newHashMap(); + private final String e; + private final EnumDirectionLimit f; + + EnumAxis(String s, EnumDirectionLimit enumdirection_enumdirectionlimit) { + this.e = s; + this.f = enumdirection_enumdirectionlimit; + } + + public String a() { + return this.e; + } + + public boolean b() { + return this.f == EnumDirectionLimit.VERTICAL; + } + + public boolean c() { + return this.f == EnumDirectionLimit.HORIZONTAL; + } + + public String toString() { + return this.e; + } + + public boolean a(EnumDirection enumdirection) { + return enumdirection != null && enumdirection.k() == this; + } + + public EnumDirectionLimit d() { + return this.f; + } + + public String getName() { + return this.e; + } + + public boolean apply(EnumDirection object) { + return this.a(object); + } + + static { + for (EnumAxis enumdirection_enumaxis : values()) { + EnumAxis.d.put(enumdirection_enumaxis.a().toLowerCase(), enumdirection_enumaxis); + } + + } + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/net/minecraft/server/EnumItemRarity.java b/azurite-server/src/main/java/net/minecraft/server/EnumItemRarity.java new file mode 100644 index 0000000..85a1753 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EnumItemRarity.java @@ -0,0 +1,14 @@ +package net.minecraft.server; + +public enum EnumItemRarity { + + COMMON(EnumChatFormat.WHITE, "Common"), UNCOMMON(EnumChatFormat.YELLOW, "Uncommon"), RARE(EnumChatFormat.AQUA, "Rare"), EPIC(EnumChatFormat.LIGHT_PURPLE, "Epic"); + + public final EnumChatFormat e; + public final String f; + + private EnumItemRarity(EnumChatFormat enumchatformat, String s) { + this.e = enumchatformat; + this.f = s; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EnumMonsterType.java b/azurite-server/src/main/java/net/minecraft/server/EnumMonsterType.java new file mode 100644 index 0000000..25aa9c0 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EnumMonsterType.java @@ -0,0 +1,8 @@ +package net.minecraft.server; + +public enum EnumMonsterType { + + UNDEFINED, UNDEAD, ARTHROPOD; + + private EnumMonsterType() {} +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EnumParticle.java b/azurite-server/src/main/java/net/minecraft/server/EnumParticle.java new file mode 100644 index 0000000..480c282 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EnumParticle.java @@ -0,0 +1,86 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import org.bukkit.Effect; + +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.Map; + +public enum EnumParticle { + + EXPLOSION_NORMAL("explode", 0, true), EXPLOSION_LARGE("largeexplode", 1, true), EXPLOSION_HUGE("hugeexplosion", 2, true), FIREWORKS_SPARK("fireworksSpark", 3, false), WATER_BUBBLE("bubble", 4, false), WATER_SPLASH("splash", 5, false), WATER_WAKE("wake", 6, false), SUSPENDED("suspended", 7, false), SUSPENDED_DEPTH("depthsuspend", 8, false), CRIT("crit", 9, false), CRIT_MAGIC("magicCrit", 10, false), SMOKE_NORMAL("smoke", 11, false), SMOKE_LARGE("largesmoke", 12, false), SPELL("spell", 13, false), SPELL_INSTANT("instantSpell", 14, false), SPELL_MOB("mobSpell", 15, false), SPELL_MOB_AMBIENT("mobSpellAmbient", 16, false), SPELL_WITCH("witchMagic", 17, false), DRIP_WATER("dripWater", 18, false), DRIP_LAVA("dripLava", 19, false), VILLAGER_ANGRY("angryVillager", 20, false), VILLAGER_HAPPY("happyVillager", 21, false), TOWN_AURA("townaura", 22, false), NOTE("note", 23, false), PORTAL("portal", 24, false), ENCHANTMENT_TABLE("enchantmenttable", 25, false), FLAME("flame", 26, false), LAVA("lava", 27, false), FOOTSTEP("footstep", 28, false), CLOUD("cloud", 29, false), REDSTONE("reddust", 30, false), SNOWBALL("snowballpoof", 31, false), SNOW_SHOVEL("snowshovel", 32, false), SLIME("slime", 33, false), HEART("heart", 34, false), BARRIER("barrier", 35, false), ITEM_CRACK("iconcrack_", 36, false, 2), BLOCK_CRACK("blockcrack_", 37, false, 1), BLOCK_DUST("blockdust_", 38, false, 1), WATER_DROP("droplet", 39, false), ITEM_TAKE("take", 40, false), MOB_APPEARANCE("mobappearance", 41, true); + + public static final int[] EMPTY_ARRAY = new int[0]; + public static final EnumMap EFFECT_TO_PARTICLE = new EnumMap<>(Effect.class); + static { + for (EnumParticle p : values()) { + String tmp = p.b().replace("_", ""); + for (Effect e : Effect.values()) { + if (e.getName() != null && e.getName().startsWith(tmp)) { + EFFECT_TO_PARTICLE.put(e, p); + break; + } + } + } + } + + private final String Q; + private final int R; + private final boolean S; + private final int T; + private static final Map U = Maps.newHashMap(); + private static final String[] V; + + EnumParticle(String s, int i, boolean flag, int j) { + this.Q = s; + this.R = i; + this.S = flag; + this.T = j; + } + + EnumParticle(String s, int i, boolean flag) { + this(s, i, flag, 0); + } + + public static String[] a() { + return EnumParticle.V; + } + + public String b() { + return this.Q; + } + + public int c() { + return this.R; + } + + public int d() { + return this.T; + } + + public boolean e() { + return this.S; + } + + public boolean f() { + return this.T > 0; + } + + public static EnumParticle a(int i) { + return EnumParticle.U.get(i); + } + + static { + ArrayList arraylist = Lists.newArrayList(); + for(EnumParticle enumparticle : values()) { + EnumParticle.U.put(enumparticle.c(), enumparticle); + if (!enumparticle.b().endsWith("_")) { + arraylist.add(enumparticle.b()); + } + } + + V = arraylist.toArray(new String[0]); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EnumProtocol.java b/azurite-server/src/main/java/net/minecraft/server/EnumProtocol.java new file mode 100644 index 0000000..e3d506a --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EnumProtocol.java @@ -0,0 +1,247 @@ +package net.minecraft.server; + +import com.google.common.collect.BiMap; +import com.google.common.collect.HashBiMap; +import com.google.common.collect.Maps; +import dev.azurite.spigot.optimizations.FastEnumProtocol; +import org.apache.logging.log4j.LogManager; + +import java.util.Iterator; +import java.util.Map; +import java.util.function.Supplier; + +public enum EnumProtocol { + + HANDSHAKING(-1, PacketHandshakingInSetProtocol::new) { + { + a(EnumProtocolDirection.SERVERBOUND, PacketHandshakingInSetProtocol.class); + } + }, PLAY(0, PacketPlayInKeepAlive::new, + PacketPlayInChat::new, + PacketPlayInUseEntity::new, + PacketPlayInFlying::new, + PacketPlayInFlying.PacketPlayInPosition::new, + PacketPlayInFlying.PacketPlayInLook::new, + PacketPlayInFlying.PacketPlayInPositionLook::new, + PacketPlayInBlockDig::new, + PacketPlayInBlockPlace::new, + PacketPlayInHeldItemSlot::new, + PacketPlayInArmAnimation::new, + PacketPlayInEntityAction::new, + PacketPlayInSteerVehicle::new, + PacketPlayInCloseWindow::new, + PacketPlayInWindowClick::new, + PacketPlayInTransaction::new, + PacketPlayInSetCreativeSlot::new, + PacketPlayInEnchantItem::new, + PacketPlayInUpdateSign::new, + PacketPlayInAbilities::new, + PacketPlayInTabComplete::new, + PacketPlayInSettings::new, + PacketPlayInClientCommand::new, + PacketPlayInCustomPayload::new, + PacketPlayInSpectate::new, + PacketPlayInResourcePackStatus::new) { + { + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutKeepAlive.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutLogin.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutChat.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutUpdateTime.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutEntityEquipment.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutSpawnPosition.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutUpdateHealth.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutRespawn.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutPosition.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutHeldItemSlot.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutBed.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutAnimation.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutNamedEntitySpawn.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutCollect.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutSpawnEntity.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutSpawnEntityLiving.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutSpawnEntityPainting.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutSpawnEntityExperienceOrb.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutEntityVelocity.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutEntityDestroy.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutEntity.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutEntity.PacketPlayOutRelEntityMove.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutEntity.PacketPlayOutEntityLook.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutEntity.PacketPlayOutRelEntityMoveLook.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutEntityTeleport.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutEntityHeadRotation.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutEntityStatus.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutAttachEntity.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutEntityMetadata.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutEntityEffect.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutRemoveEntityEffect.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutExperience.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutUpdateAttributes.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutMapChunk.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutMultiBlockChange.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutBlockChange.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutBlockAction.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutBlockBreakAnimation.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutMapChunkBulk.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutExplosion.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutWorldEvent.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutNamedSoundEffect.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutWorldParticles.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutGameStateChange.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutSpawnEntityWeather.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutOpenWindow.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutCloseWindow.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutSetSlot.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutWindowItems.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutWindowData.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutTransaction.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutUpdateSign.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutMap.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutTileEntityData.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutOpenSignEditor.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutStatistic.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutPlayerInfo.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutAbilities.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutTabComplete.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutScoreboardObjective.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutScoreboardScore.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutScoreboardDisplayObjective.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutScoreboardTeam.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutCustomPayload.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutKickDisconnect.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutServerDifficulty.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutCombatEvent.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutCamera.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutWorldBorder.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutTitle.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutSetCompression.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutPlayerListHeaderFooter.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutResourcePackSend.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketPlayOutUpdateEntityNBT.class); + a(EnumProtocolDirection.SERVERBOUND, PacketPlayInKeepAlive.class); + a(EnumProtocolDirection.SERVERBOUND, PacketPlayInChat.class); + a(EnumProtocolDirection.SERVERBOUND, PacketPlayInUseEntity.class); + a(EnumProtocolDirection.SERVERBOUND, PacketPlayInFlying.class); + a(EnumProtocolDirection.SERVERBOUND, PacketPlayInFlying.PacketPlayInPosition.class); + a(EnumProtocolDirection.SERVERBOUND, PacketPlayInFlying.PacketPlayInLook.class); + a(EnumProtocolDirection.SERVERBOUND, PacketPlayInFlying.PacketPlayInPositionLook.class); + a(EnumProtocolDirection.SERVERBOUND, PacketPlayInBlockDig.class); + a(EnumProtocolDirection.SERVERBOUND, PacketPlayInBlockPlace.class); + a(EnumProtocolDirection.SERVERBOUND, PacketPlayInHeldItemSlot.class); + a(EnumProtocolDirection.SERVERBOUND, PacketPlayInArmAnimation.class); + a(EnumProtocolDirection.SERVERBOUND, PacketPlayInEntityAction.class); + a(EnumProtocolDirection.SERVERBOUND, PacketPlayInSteerVehicle.class); + a(EnumProtocolDirection.SERVERBOUND, PacketPlayInCloseWindow.class); + a(EnumProtocolDirection.SERVERBOUND, PacketPlayInWindowClick.class); + a(EnumProtocolDirection.SERVERBOUND, PacketPlayInTransaction.class); + a(EnumProtocolDirection.SERVERBOUND, PacketPlayInSetCreativeSlot.class); + a(EnumProtocolDirection.SERVERBOUND, PacketPlayInEnchantItem.class); + a(EnumProtocolDirection.SERVERBOUND, PacketPlayInUpdateSign.class); + a(EnumProtocolDirection.SERVERBOUND, PacketPlayInAbilities.class); + a(EnumProtocolDirection.SERVERBOUND, PacketPlayInTabComplete.class); + a(EnumProtocolDirection.SERVERBOUND, PacketPlayInSettings.class); + a(EnumProtocolDirection.SERVERBOUND, PacketPlayInClientCommand.class); + a(EnumProtocolDirection.SERVERBOUND, PacketPlayInCustomPayload.class); + a(EnumProtocolDirection.SERVERBOUND, PacketPlayInSpectate.class); + a(EnumProtocolDirection.SERVERBOUND, PacketPlayInResourcePackStatus.class); + } + }, STATUS(1, PacketStatusInStart::new, + PacketStatusInPing::new) { + { + a(EnumProtocolDirection.SERVERBOUND, PacketStatusInStart.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketStatusOutServerInfo.class); + a(EnumProtocolDirection.SERVERBOUND, PacketStatusInPing.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketStatusOutPong.class); + } + }, LOGIN(2, PacketLoginInStart::new, + PacketLoginInEncryptionBegin::new) { + { + a(EnumProtocolDirection.CLIENTBOUND, PacketLoginOutDisconnect.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketLoginOutEncryptionBegin.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketLoginOutSuccess.class); + a(EnumProtocolDirection.CLIENTBOUND, PacketLoginOutSetCompression.class); + a(EnumProtocolDirection.SERVERBOUND, PacketLoginInStart.class); + a(EnumProtocolDirection.SERVERBOUND, PacketLoginInEncryptionBegin.class); + } + }; + + private static int e = -1; + private static final int f = 2; + private static final EnumProtocol[] g = new EnumProtocol[EnumProtocol.f - EnumProtocol.e + 1]; + private static final Map>, EnumProtocol> h = Maps.newHashMap(); + private final int i; + private final Map>>> j = Maps.newEnumMap(EnumProtocolDirection.class); + public final FastEnumProtocol fastEnumProtocol; + + EnumProtocol(int i, Object object) { + this(i); + } + + @SafeVarargs + EnumProtocol(int i, Supplier>... suppliers) { + this.i = i; + this.fastEnumProtocol = new FastEnumProtocol(suppliers); + } + + protected EnumProtocol a(EnumProtocolDirection enumprotocoldirection, Class> oclass) { + BiMap>> object = j.computeIfAbsent(enumprotocoldirection, k -> HashBiMap.create()); + + if (object.containsValue(oclass)) { + String s = enumprotocoldirection + " packet " + oclass + " is already known to ID " + object.inverse().get(oclass); + LogManager.getLogger().fatal(s); + throw new IllegalArgumentException(s); + } else { + object.put(object.size(), oclass); + return this; + } + } + + public Integer a(EnumProtocolDirection enumprotocoldirection, Packet packet) { + return j.get(enumprotocoldirection).inverse().get(packet.getClass()); + } + + public Packet a(EnumProtocolDirection enumprotocoldirection, int i) throws IllegalAccessException, InstantiationException { + Class> oclass = j.get(enumprotocoldirection).get(i); + return oclass == null ? null : oclass.newInstance(); + } + + public int a() { + return i; + } + + public static EnumProtocol a(int i) { + return i >= e && i <= f ? g[i - e] : null; + } + + public static EnumProtocol a(Packet packet) { + return h.get(packet.getClass()); + } + + static { + for (EnumProtocol enumprotocol : values()) { + int k = enumprotocol.a(); + + if (k < e || k > f) { + throw new Error("Invalid protocol ID " + k); + } + + g[k - e] = enumprotocol; + + for (EnumProtocolDirection direction : enumprotocol.j.keySet()) { + Class> oclass; + + for (Iterator>> iterator1 = enumprotocol.j.get(direction).values().iterator(); iterator1.hasNext(); h.put(oclass, enumprotocol)) { + oclass = iterator1.next(); + if (h.containsKey(oclass) && h.get(oclass) != enumprotocol) { + throw new Error("Packet " + oclass + " is already assigned to protocol " + h.get(oclass) + " - can't reassign to " + enumprotocol); + } + + try { + oclass.newInstance(); + } catch (Throwable throwable) { + throw new Error("Packet " + oclass + " fails instantiation checks! " + oclass); + } + } + } + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EnumProtocolDirection.java b/azurite-server/src/main/java/net/minecraft/server/EnumProtocolDirection.java new file mode 100644 index 0000000..c525fad --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EnumProtocolDirection.java @@ -0,0 +1,8 @@ +package net.minecraft.server; + +public enum EnumProtocolDirection { + + SERVERBOUND, CLIENTBOUND; + + private EnumProtocolDirection() {} +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EnumSkyBlock.java b/azurite-server/src/main/java/net/minecraft/server/EnumSkyBlock.java new file mode 100644 index 0000000..5880922 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EnumSkyBlock.java @@ -0,0 +1,12 @@ +package net.minecraft.server; + +public enum EnumSkyBlock { + + SKY(15), BLOCK(0); + + public final int c; + + private EnumSkyBlock(int i) { + this.c = i; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/EnumWorldBorderState.java b/azurite-server/src/main/java/net/minecraft/server/EnumWorldBorderState.java new file mode 100644 index 0000000..32664e6 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/EnumWorldBorderState.java @@ -0,0 +1,12 @@ +package net.minecraft.server; + +public enum EnumWorldBorderState { + + GROWING(4259712), SHRINKING(16724016), STATIONARY(2138367); + + private final int d; + + private EnumWorldBorderState(int i) { + this.d = i; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ExceptionEntityNotFound.java b/azurite-server/src/main/java/net/minecraft/server/ExceptionEntityNotFound.java new file mode 100644 index 0000000..d01a15f --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ExceptionEntityNotFound.java @@ -0,0 +1,12 @@ +package net.minecraft.server; + +public class ExceptionEntityNotFound extends CommandException { + + public ExceptionEntityNotFound() { + this("commands.generic.entity.notFound", new Object[0]); + } + + public ExceptionEntityNotFound(String s, Object... aobject) { + super(s, aobject); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ExceptionInvalidNumber.java b/azurite-server/src/main/java/net/minecraft/server/ExceptionInvalidNumber.java new file mode 100644 index 0000000..b66af35 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ExceptionInvalidNumber.java @@ -0,0 +1,12 @@ +package net.minecraft.server; + +public class ExceptionInvalidNumber extends CommandException { + + public ExceptionInvalidNumber() { + this("commands.generic.num.invalid", new Object[0]); + } + + public ExceptionInvalidNumber(String s, Object... aobject) { + super(s, aobject); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ExceptionInvalidSyntax.java b/azurite-server/src/main/java/net/minecraft/server/ExceptionInvalidSyntax.java new file mode 100644 index 0000000..8f47be8 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ExceptionInvalidSyntax.java @@ -0,0 +1,12 @@ +package net.minecraft.server; + +public class ExceptionInvalidSyntax extends CommandException { + + public ExceptionInvalidSyntax() { + this("commands.generic.snytax", new Object[0]); + } + + public ExceptionInvalidSyntax(String s, Object... aobject) { + super(s, aobject); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ExceptionPlayerNotFound.java b/azurite-server/src/main/java/net/minecraft/server/ExceptionPlayerNotFound.java new file mode 100644 index 0000000..76b2c68 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ExceptionPlayerNotFound.java @@ -0,0 +1,12 @@ +package net.minecraft.server; + +public class ExceptionPlayerNotFound extends CommandException { + + public ExceptionPlayerNotFound() { + this("commands.generic.player.notFound", new Object[0]); + } + + public ExceptionPlayerNotFound(String s, Object... aobject) { + super(s, aobject); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ExceptionUnknownCommand.java b/azurite-server/src/main/java/net/minecraft/server/ExceptionUnknownCommand.java new file mode 100644 index 0000000..ed9a83a --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ExceptionUnknownCommand.java @@ -0,0 +1,12 @@ +package net.minecraft.server; + +public class ExceptionUnknownCommand extends CommandException { + + public ExceptionUnknownCommand() { + this("commands.generic.notFound", new Object[0]); + } + + public ExceptionUnknownCommand(String s, Object... aobject) { + super(s, aobject); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ExceptionUsage.java b/azurite-server/src/main/java/net/minecraft/server/ExceptionUsage.java new file mode 100644 index 0000000..0f2606a --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ExceptionUsage.java @@ -0,0 +1,8 @@ +package net.minecraft.server; + +public class ExceptionUsage extends ExceptionInvalidSyntax { + + public ExceptionUsage(String s, Object... aobject) { + super(s, aobject); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ExceptionWorldConflict.java b/azurite-server/src/main/java/net/minecraft/server/ExceptionWorldConflict.java new file mode 100644 index 0000000..11de72a --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ExceptionWorldConflict.java @@ -0,0 +1,8 @@ +package net.minecraft.server; + +public class ExceptionWorldConflict extends Exception { + + public ExceptionWorldConflict(String s) { + super(s); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ExpirableListEntry.java b/azurite-server/src/main/java/net/minecraft/server/ExpirableListEntry.java new file mode 100644 index 0000000..692203b --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ExpirableListEntry.java @@ -0,0 +1,95 @@ +package net.minecraft.server; + +import com.google.gson.JsonObject; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; + +public abstract class ExpirableListEntry extends JsonListEntry { + + public static final SimpleDateFormat a = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z"); + protected final Date b; + protected final String c; + protected final Date d; + protected final String e; + + public ExpirableListEntry(T t0, Date date, String s, Date date1, String s1) { + super(t0); + this.b = date == null ? new Date() : date; + this.c = s == null ? "(Unknown)" : s; + this.d = date1; + this.e = s1 == null ? "Banned by an operator." : s1; + } + + protected ExpirableListEntry(T t0, JsonObject jsonobject) { + super(checkExpiry(t0, jsonobject), jsonobject); + + Date date; + + try { + date = jsonobject.has("created") ? ExpirableListEntry.a.parse(jsonobject.get("created").getAsString()) : new Date(); + } catch (ParseException parseexception) { + date = new Date(); + } + + this.b = date; + this.c = jsonobject.has("source") ? jsonobject.get("source").getAsString() : "(Unknown)"; + + Date date1; + + try { + date1 = jsonobject.has("expires") ? ExpirableListEntry.a.parse(jsonobject.get("expires").getAsString()) : null; + } catch (ParseException parseexception1) { + date1 = null; + } + + this.d = date1; + this.e = jsonobject.has("reason") ? jsonobject.get("reason").getAsString() : "Banned by an operator."; + } + + public Date getExpires() { + return this.d; + } + + public String getReason() { + return this.e; + } + + boolean hasExpired() { + return this.d != null && this.d.before(new Date()); + } + + protected void a(JsonObject jsonobject) { + jsonobject.addProperty("created", ExpirableListEntry.a.format(this.b)); + jsonobject.addProperty("source", this.c); + jsonobject.addProperty("expires", this.d == null ? "forever" : ExpirableListEntry.a.format(this.d)); + jsonobject.addProperty("reason", this.e); + } + + // CraftBukkit start + public String getSource() { + return this.c; + } + + public Date getCreated() { + return this.b; + } + + private static T checkExpiry(T object, JsonObject jsonobject) { + Date expires = null; + + try { + expires = jsonobject.has("expires") ? a.parse(jsonobject.get("expires").getAsString()) : null; + } catch (ParseException ex) { + // Guess we don't have a date + } + + if (expires == null || expires.after(new Date())) { + return object; + } else { + return null; + } + } + // CraftBukkit end +} diff --git a/azurite-server/src/main/java/net/minecraft/server/Explosion.java b/azurite-server/src/main/java/net/minecraft/server/Explosion.java new file mode 100644 index 0000000..c49fcfa --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/Explosion.java @@ -0,0 +1,387 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import dev.azurite.spigot.configs.AzuriteConfig; +import dev.azurite.spigot.utils.Utils; +import it.unimi.dsi.fastutil.doubles.DoubleArrayList; +import it.unimi.dsi.fastutil.longs.LongArrayList; +import it.unimi.dsi.fastutil.longs.LongListIterator; +import org.bukkit.Location; +import org.bukkit.craftbukkit.CraftWorld; +import org.bukkit.craftbukkit.entity.CraftEntity; +import org.bukkit.craftbukkit.event.CraftEventFactory; +import org.bukkit.event.block.BlockExplodeEvent; +import org.bukkit.event.entity.EntityExplodeEvent; +import org.bukkit.util.NumberConversions; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class Explosion { + + public static double[] densityVectors; + public static double[] blockVectors; + + static { + final DoubleArrayList coords = new DoubleArrayList(); + float f = 0.0f; + while (f <= 1.0f) { + float f1 = 0.0f; + while (f1 <= 1.0f) { + float f2 = 0.0f; + while (f2 <= 1.0f) { + coords.add(f); + coords.add(f1); + coords.add(f2); + f2 += 0.3378378334839559F; + } + f1 += 0.3378378334839559F; + } + f += 0.3378378334839559F; + } + densityVectors = coords.toDoubleArray(); + } + + static { + final DoubleArrayList coords = new DoubleArrayList(); + for (int k = 0; k < 16; k++) { + for (int i = 0; i < 16; i++) { + for (int j = 0; j < 16; j++) { + if (k == 0 || k == 15 || i == 0 || i == 15 || j == 0 || j == 15) { + double d0 = (k / 15.0F * 2.0F - 1.0F); + double d1 = (i / 15.0F * 2.0F - 1.0F); + double d2 = (j / 15.0F * 2.0F - 1.0F); + double d3 = Math.sqrt(d0 * d0 + d1 * d1 + d2 * d2); + coords.add(d0 / d3 * 0.30000001192092896D); + coords.add(d1 / d3 * 0.30000001192092896D); + coords.add(d2 / d3 * 0.30000001192092896D); + } + } + } + } + blockVectors = coords.toDoubleArray(); + } + + public final Entity source; + private final boolean a; + private final boolean b; + private final World world; + private final double posX; + private final double posY; + private final double posZ; + private final float size; + private final LongArrayList blocks = new LongArrayList(); // Azurite - Store the position in long value instead of block position allocations + private final Map k = Maps.newHashMap(); + public boolean wasCanceled; + + public Explosion(World world, Entity entity, double d0, double d1, double d2, float f, boolean flag, boolean flag1) { + this.world = world; + this.source = entity; + this.size = (float) Math.max(f, 0.0); + this.posX = d0; + this.posY = d1; + this.posZ = d2; + this.a = flag; + this.b = flag1; + } + + public void a() { + if (size < 0.1f) + return; + + int floorPosX = MathHelper.floor(posX), floorPosY = MathHelper.floor(posY), floorPosZ = MathHelper.floor(posZ); + Chunk chunk = world.getChunkAt(floorPosX >> 4, floorPosZ >> 4); + + if (!chunk.getBlockData(floorPosX, floorPosY, floorPosZ).getBlock().getMaterial().isLiquid()) { + handleBlocks(chunk); + } + + float strength = size * AzuriteConfig.explosionEntityPower.getValue().floatValue(); + Vec3D vec3d = new Vec3D(posX, posY, posZ); + + int minX = MathHelper.floor(posX - strength - 1.0D) >> 4; + int maxX = MathHelper.floor(posX + strength + 1.0D) >> 4; + + int minY = MathHelper.clamp(MathHelper.floor(posY - strength - 1.0D) >> 4, 0, 15); + int maxY = MathHelper.clamp(MathHelper.floor(posY + strength + 1.0D) >> 4, 0, 15); + + int minZ = MathHelper.floor(posZ - strength - 1.0D) >> 4; + int maxZ = MathHelper.floor(posZ + strength + 1.0D) >> 4; + + for (int chunkX = minX; chunkX <= maxX; chunkX++) { + for (int chunkZ = minZ; chunkZ <= maxZ; chunkZ++) { + if (Utils.isInvalidChunk(chunk, chunkX, chunkZ)) + chunk = world.getChunkIfLoaded(chunkX, chunkZ); + + if (chunk != null) + for (int chunkY = minY; chunkY <= maxY; chunkY++) + handleEntities(new ArrayList<>(chunk.entitySlices[chunkY]), vec3d, strength); + } + } + } + + public void a(boolean flag) { + if (AzuriteConfig.explosionSounds.getValue()) + world.makeSound(posX, posY, posZ, "random.explode", source instanceof EntityTNTPrimed ? world.paperSpigotConfig.tntExplosionVolume : 4.0f, (1.0f + (world.random.nextFloat() - world.random.nextFloat()) * 0.2f) * 0.7f); + + if (AzuriteConfig.explosionParticles.getValue()) { + if (size >= 2.0f && b) { + world.addParticle(EnumParticle.EXPLOSION_HUGE, posX, posY, posZ, 1.0, 0.0, 0.0, EnumParticle.EMPTY_ARRAY); + } else { + world.addParticle(EnumParticle.EXPLOSION_LARGE, posX, posY, posZ, 1.0, 0.0, 0.0, EnumParticle.EMPTY_ARRAY); + } + } + + Chunk chunk = null; + if (b) { + List bukkitBlocks; + boolean cancelled; + + CraftWorld bworld = world.getWorld(); + CraftEntity explode = source == null ? null : source.getBukkitEntity(); + Location location = new Location(bworld, posX, posY, posZ); + float yield; + + List blockList = Lists.newArrayList(); + for (int i = blocks.size() - 1; i >= 0; i--) { + long cpos = blocks.getLong(i); // Azurite + org.bukkit.block.Block bblock = bworld.getBlockAt(BlockPosition.getXFromLong(cpos), BlockPosition.getYFromLong(cpos), BlockPosition.getZFromLong(cpos)); + if (bblock.getType() != org.bukkit.Material.AIR) + blockList.add(bblock); + } + + if (explode != null) { + EntityExplodeEvent event = new EntityExplodeEvent(explode, location, blockList, 0.3F); + world.getServer().getPluginManager().callEvent(event); + cancelled = event.isCancelled(); + bukkitBlocks = event.blockList(); + yield = event.getYield(); + } else { + BlockExplodeEvent event = new BlockExplodeEvent(location.getBlock(), blockList, 0.3F); + world.getServer().getPluginManager().callEvent(event); + cancelled = event.isCancelled(); + bukkitBlocks = event.blockList(); + yield = event.getYield(); + } + + blocks.clear(); + + for (org.bukkit.block.Block bblock : bukkitBlocks) { + blocks.add(BlockPosition.asLong(bblock.getX(), bblock.getY(), bblock.getZ())); // Azurite + } + + if (cancelled) { + wasCanceled = true; + return; + } + + LongListIterator iterator = blocks.iterator(); + + while (iterator.hasNext()) { + long position = iterator.nextLong(); + BlockPosition blockPosition = BlockPosition.fromLong(position); + int x = blockPosition.getX(), y = blockPosition.getY(), z = blockPosition.getZ(); + int chunkX = x >> 4, chunkZ = z >> 4; + + if (Utils.isInvalidChunk(chunk, chunkX, chunkZ)) + chunk = world.getChunkAt(chunkX, chunkZ); + + IBlockData iblockdata = world.getType(chunk, x, y, z, true); + Block block = iblockdata.getBlock(); + if (block.getMaterial() != Material.AIR) { + if (block.explosionDurability > 0) { + int durability = world.getDurability(chunk, x, y, z) - 1; + + if (durability > 0) { + world.setDurability(chunk, x, y, z, durability); + iterator.remove(); + continue; + } + } + + if (AzuriteConfig.dropExplosionBlocks.getValue() && block.a(this)) + block.dropNaturally(world, blockPosition, iblockdata, yield, 0); + + world.setTypeAndData(chunk, blockPosition, Blocks.AIR.getBlockData(), 3, true, false); + block.wasExploded(world, blockPosition, this); + + } else { + if (a) { + if (world.random.nextInt(3) == 0 && world.getType(chunk, x, y - 1, z, true).getBlock().o() + && !CraftEventFactory.callBlockIgniteEvent(world, chunk, x, y, z, this).isCancelled()) { + world.setTypeAndData(chunk, blockPosition, Blocks.FIRE.getBlockData(), 3, true, false); + } + } + } + } + } + } + + public void handleEntities(List list, Vec3D vec3d, float strength) { + double lastX = Integer.MAX_VALUE, // always cache first iteration + lastY = 0, + lastZ = 0, + density = 0, + distance = 0; + + for (Entity entity : list) { + if (!entity.aW() && !entity.dead) { + double distX = entity.locX - posX, + distY = (entity.locY + entity.getHeadHeight()) - posY, + distZ = entity.locZ - posZ; + if (lastX != entity.locX || lastY != entity.locY || lastZ != entity.locZ) { + + // If distance is higher than 8 or equal 0 we skip the entity + double distSquared = distX * distX + distY * distY + distZ * distZ; + if (distSquared > 64 || distSquared == 0) + continue; + + lastX = entity.locX; + lastY = entity.locY; + lastZ = entity.locZ; + + distance = Math.sqrt(distSquared); // get the real distance + density = (1.0D - distance / strength) * getBlockDensity(vec3d, entity.boundingBox); + } + + distX /= distance; + distY /= distance; + distZ /= distance; + + if (entity instanceof EntityTNTPrimed || entity instanceof EntityFallingBlock) { + entity.g(distX * density, distY * density, distZ * density); + continue; + } + + CraftEventFactory.entityDamage = this.source; + entity.forceExplosionKnockback = false; + boolean wasDamaged = entity.damageEntity(DamageSource.explosion(this), (int) ((density * density + density) / 2 * 8 * strength + 1)); + CraftEventFactory.entityDamage = null; + + if (wasDamaged || entity.forceExplosionKnockback) { + double multiplier = (entity instanceof EntityPlayer && world.paperSpigotConfig.disableExplosionKnockback) ? 0 : EnchantmentProtection.a(entity, density); + entity.g(distX * multiplier, distY * multiplier * AzuriteConfig.tntYVelocityMultiplier.getValue(), distZ * multiplier); + if (entity instanceof EntityHuman && !((EntityHuman) entity).abilities.isInvulnerable && !world.paperSpigotConfig.disableExplosionKnockback) + k.put((EntityHuman) entity, new Vec3D(distX * density, distY * density, distZ * density)); + } + } + } + world.rayTraceCache.clear(); + } + + private void handleBlocks(Chunk chunk) { + int lastX = 0, lastY = 0, lastZ = 0; + + float explosionPower = AzuriteConfig.explosionBlockPower.getValue().floatValue(); + for (int i = 0, length = blockVectors.length; i < length;) { + float power = size * explosionPower, resistance = 0.0F; + double stepX = posX, stepY = posY, stepZ = posZ; + double x = blockVectors[i], y = blockVectors[i + 1], z = blockVectors[i + 2]; + i += 3; + + for (; power > 0.0F; power -= 0.22500001F) { + int floorX = NumberConversions.floor(stepX), floorY = NumberConversions.floor(stepY), floorZ = NumberConversions.floor(stepZ); + if (lastX != floorX || lastY != floorY || lastZ != floorZ) { + lastX = floorX; + lastY = floorY; + lastZ = floorZ; + + int chunkX = floorX >> 4, chunkZ = floorZ >> 4; + if (Utils.isInvalidChunk(chunk, chunkX, chunkZ)) + chunk = world.getChunkAt(chunkX, chunkZ); + + Block block = chunk.getBlockData(floorX, floorY, floorZ).getBlock(); + if (block.getMaterial().isLiquid()) + break; + + if (block != Blocks.AIR && floorY < 256 && floorY >= 0) { + if (block.explosionDurability > 0) { + if (AzuriteConfig.damageOnlyByTNT.getValue() && !(source instanceof EntityTNTPrimed)) + break; + + int durability = world.getDurability(chunk, floorX, floorY, floorZ); + if (durability < 0) // skip block with invalid durability + break; + + // if the time is to break the block, we just set this, + // otherwise we skip the block + if (durability <= 1) + resistance = block.explosionResistance; + } else { + resistance = block.explosionResistance; + } + power -= resistance; + if (power > 0.0F) { + long position = BlockPosition.asLong(floorX, floorY, floorZ); // Azurite + + if (!blocks.contains(position)) { + blocks.add(position); + } + } + } + } else { + power -= resistance; + } + stepX += x; + stepY += y; + stepZ += z; + } + } + } + + public Map b() { + return this.k; + } + + public LongArrayList getBlocks() { + return this.blocks; + } + + private float getBlockDensity(Vec3D vec3d, AxisAlignedBB aabb) { + int key = genKey(this, aabb); + float blockDensity = world.explosionDensityCache.get(key); + if (blockDensity == -1.0F) { + blockDensity = world.getExplosionDensity(vec3d, aabb); + world.explosionDensityCache.put(key, blockDensity); + } + return blockDensity; + } + + private int genKey(Explosion explosion, AxisAlignedBB aabb) { + int result = explosion.world.hashCode(); + long temp = Double.doubleToLongBits(explosion.posX); + result = 31 * result + (int) (temp ^ temp >>> 32L); + temp = Double.doubleToLongBits(explosion.posY); + result = 31 * result + (int) (temp ^ temp >>> 32L); + temp = Double.doubleToLongBits(explosion.posZ); + result = 31 * result + (int) (temp ^ temp >>> 32L); + temp = Double.doubleToLongBits(aabb.a); + result = 31 * result + (int) (temp ^ temp >>> 32L); + temp = Double.doubleToLongBits(aabb.b); + result = 31 * result + (int) (temp ^ temp >>> 32L); + temp = Double.doubleToLongBits(aabb.c); + result = 31 * result + (int) (temp ^ temp >>> 32L); + temp = Double.doubleToLongBits(aabb.d); + result = 31 * result + (int) (temp ^ temp >>> 32L); + temp = Double.doubleToLongBits(aabb.e); + result = 31 * result + (int) (temp ^ temp >>> 32L); + temp = Double.doubleToLongBits(aabb.f); + result = 31 * result + (int) (temp ^ temp >>> 32L); + return result; + } + + public EntityLiving getSource() { + return this.source == null ? null : (this.source instanceof EntityTNTPrimed ? ((EntityTNTPrimed) this.source).getSource() : (this.source instanceof EntityLiving ? (EntityLiving) this.source : (this.source instanceof EntityFireball ? ((EntityFireball) this.source).shooter : null))); + } + + public Explosion cancel() { + wasCanceled = true; + return this; + } + + public void clearBlocks() { + this.blocks.clear(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/FileIOThread.java b/azurite-server/src/main/java/net/minecraft/server/FileIOThread.java new file mode 100644 index 0000000..ee4c85e --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/FileIOThread.java @@ -0,0 +1,74 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; +import java.util.Collections; +import java.util.List; + +public class FileIOThread implements Runnable { + + private static final FileIOThread a = new FileIOThread(); + private final List b = Collections.synchronizedList(Lists.newArrayList()); + private volatile long c; + private volatile long d; + private volatile boolean e; + + private FileIOThread() { + Thread thread = new Thread(this, "File IO Thread"); + thread.setPriority(1); + thread.start(); + } + + public static FileIOThread a() { + return FileIOThread.a; + } + + public void run() { + while (true) { + this.c(); + } + } + + private void c() { + for (int i = 0; i < this.b.size(); ++i) { + IAsyncChunkSaver iasyncchunksaver = this.b.get(i); + boolean flag = iasyncchunksaver.c(); + + if (!flag) { + this.b.remove(i--); + ++this.d; + } + } + if (this.b.isEmpty()) { + try { + Thread.sleep(25L); + } catch (InterruptedException interruptedexception1) { + interruptedexception1.printStackTrace(); + } + } + } + + public void a(IAsyncChunkSaver iasyncchunksaver) { + if (!this.b.contains(iasyncchunksaver)) { + ++this.c; + this.b.add(iasyncchunksaver); + } + } + + public void b() throws InterruptedException { + this.e = true; + while (this.c != this.d) { + Thread.sleep(10L); + } + this.e = false; + } + + // Migot start + public boolean isDone() { + return this.c == this.d; + } + + public void setNoDelay(boolean active) { + this.e = active; + } + // Migot end +} diff --git a/azurite-server/src/main/java/net/minecraft/server/FoodMetaData.java b/azurite-server/src/main/java/net/minecraft/server/FoodMetaData.java new file mode 100644 index 0000000..d7f085a --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/FoodMetaData.java @@ -0,0 +1,120 @@ +package net.minecraft.server; + +public class FoodMetaData { + + public int foodLevel = 20; + public float saturationLevel = 5.0F; + public float exhaustionLevel; + private int foodTickTimer; + private final EntityHuman entityhuman; // CraftBukkit + + public FoodMetaData() { throw new AssertionError("Whoopsie, we missed the bukkit."); } // CraftBukkit start - throw an error + + // CraftBukkit start - added EntityHuman constructor + public FoodMetaData(EntityHuman entityhuman) { + org.apache.commons.lang.Validate.notNull(entityhuman); + this.entityhuman = entityhuman; + } + // CraftBukkit end + + public void eat(int i, float f) { + this.foodLevel = Math.min(i + this.foodLevel, 20); + this.saturationLevel = Math.min(this.saturationLevel + (float) i * f * 2.0F, (float) this.foodLevel); + } + + public void a(ItemFood itemfood, ItemStack itemstack) { + // CraftBukkit start + int oldFoodLevel = foodLevel; + + org.bukkit.event.entity.FoodLevelChangeEvent event = org.bukkit.craftbukkit.event.CraftEventFactory.callFoodLevelChangeEvent(entityhuman, itemfood.getNutrition(itemstack) + oldFoodLevel); + + if (!event.isCancelled()) { + this.eat(event.getFoodLevel() - oldFoodLevel, itemfood.getSaturationModifier(itemstack)); + } + + // Beanes - reduce packets + ((EntityPlayer) entityhuman).updateHealthAndFood(); + // CraftBukkit end + } + + public void a(EntityHuman entityhuman) { + EnumDifficulty enumdifficulty = entityhuman.world.getDifficulty(); + + if (this.exhaustionLevel > 4.0F) { + this.exhaustionLevel -= 4.0F; + if (this.saturationLevel > 0.0F) { + this.saturationLevel = Math.max(this.saturationLevel - 1.0F, 0.0F); + } else if (enumdifficulty != EnumDifficulty.PEACEFUL) { + // CraftBukkit start + org.bukkit.event.entity.FoodLevelChangeEvent event = org.bukkit.craftbukkit.event.CraftEventFactory.callFoodLevelChangeEvent(entityhuman, Math.max(this.foodLevel - 1, 0)); + + if (!event.isCancelled()) { + this.foodLevel = event.getFoodLevel(); + } + + // Beanes - reduce packets + ((EntityPlayer) entityhuman).updateHealthAndFood(); + // CraftBukkit end + } + } + + if (entityhuman.world.getGameRules().getBoolean("naturalRegeneration") && this.foodLevel >= 18 && entityhuman.cm()) { + ++this.foodTickTimer; + if (this.foodTickTimer >= 80) { + // CraftBukkit - added RegainReason + entityhuman.heal(1.0F, org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason.SATIATED); + this.a(entityhuman.world.spigotConfig.regenExhaustion); // Spigot - Change to use configurable value + this.foodTickTimer = 0; + } + } else if (this.foodLevel <= 0) { + ++this.foodTickTimer; + if (this.foodTickTimer >= 80) { + if (entityhuman.getHealth() > 10.0F || enumdifficulty == EnumDifficulty.HARD || entityhuman.getHealth() > 1.0F && enumdifficulty == EnumDifficulty.NORMAL) { + entityhuman.damageEntity(DamageSource.STARVE, 1.0F); + } + + this.foodTickTimer = 0; + } + } else { + this.foodTickTimer = 0; + } + + } + + public void a(NBTTagCompound nbttagcompound) { + if (nbttagcompound.hasKeyOfType("foodLevel", 99)) { + this.foodLevel = nbttagcompound.getInt("foodLevel"); + this.foodTickTimer = nbttagcompound.getInt("foodTickTimer"); + this.saturationLevel = nbttagcompound.getFloat("foodSaturationLevel"); + this.exhaustionLevel = nbttagcompound.getFloat("foodExhaustionLevel"); + } + + } + + public void b(NBTTagCompound nbttagcompound) { + nbttagcompound.setInt("foodLevel", this.foodLevel); + nbttagcompound.setInt("foodTickTimer", this.foodTickTimer); + nbttagcompound.setFloat("foodSaturationLevel", this.saturationLevel); + nbttagcompound.setFloat("foodExhaustionLevel", this.exhaustionLevel); + } + + public int getFoodLevel() { + return this.foodLevel; + } + + public boolean c() { + return this.foodLevel < 20; + } + + public void a(float f) { + this.exhaustionLevel = Math.min(this.exhaustionLevel + f, 40.0F); + } + + public float getSaturationLevel() { + return this.saturationLevel; + } + + public void a(int i) { + this.foodLevel = i; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/GameProfileBanEntry.java b/azurite-server/src/main/java/net/minecraft/server/GameProfileBanEntry.java new file mode 100644 index 0000000..6a7de8e --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/GameProfileBanEntry.java @@ -0,0 +1,58 @@ +package net.minecraft.server; + +import com.eatthepath.uuid.FastUUID; +import com.google.gson.JsonObject; +import com.mojang.authlib.GameProfile; + +import java.util.Date; +import java.util.UUID; + +public class GameProfileBanEntry extends ExpirableListEntry { + + public GameProfileBanEntry(GameProfile gameprofile) { + this(gameprofile, null, null, null, null); + } + + public GameProfileBanEntry(GameProfile gameprofile, Date date, String s, Date date1, String s1) { + super(gameprofile, date, s, date1, s1); // Spigot + } + + public GameProfileBanEntry(JsonObject jsonobject) { + super(b(jsonobject), jsonobject); + } + + protected void a(JsonObject jsonobject) { + if (this.getKey() != null) { + jsonobject.addProperty("uuid", getKey().getId() == null ? "" : FastUUID.toString(getKey().getId())); + jsonobject.addProperty("name", getKey().getName()); + super.a(jsonobject); + } + } + + private static GameProfile b(JsonObject jsonobject) { + // Spigot start + // this whole method has to be reworked to account for the fact Bukkit only accepts UUID bans and gives no way for usernames to be stored! + UUID uuid = null; + String name = null; + if (jsonobject.has("uuid")) { + String s = jsonobject.get("uuid").getAsString(); + + try { + uuid = FastUUID.parseUUID(s); + } catch (Throwable ignored) { + } + + } + if ( jsonobject.has("name")) + { + name = jsonobject.get("name").getAsString(); + } + if ( uuid != null || name != null ) + { + return new GameProfile( uuid, name ); + } else { + return null; + } + // Spigot End + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/GameProfileBanList.java b/azurite-server/src/main/java/net/minecraft/server/GameProfileBanList.java new file mode 100644 index 0000000..477cccd --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/GameProfileBanList.java @@ -0,0 +1,60 @@ +package net.minecraft.server; + +import com.eatthepath.uuid.FastUUID; +import com.google.gson.JsonObject; +import com.mojang.authlib.GameProfile; + +import java.io.File; +import java.util.Iterator; + +public class GameProfileBanList extends JsonList { + + public GameProfileBanList(File file) { + super(file); + } + + protected JsonListEntry a(JsonObject jsonobject) { + return new GameProfileBanEntry(jsonobject); + } + + public boolean isBanned(GameProfile gameprofile) { + return this.d(gameprofile); + } + + public String[] getEntries() { + String[] astring = new String[this.e().size()]; + int i = 0; + + GameProfileBanEntry gameprofilebanentry; + + for (Iterator iterator = this.e().values().iterator(); iterator.hasNext(); astring[i++] = gameprofilebanentry.getKey().getName()) { + gameprofilebanentry = iterator.next(); + } + + return astring; + } + + protected String b(GameProfile gameprofile) { + return FastUUID.toString(gameprofile.getId()); + } + + public GameProfile a(String s) { + Iterator iterator = this.e().values().iterator(); + + GameProfileBanEntry gameprofilebanentry; + + do { + if (!iterator.hasNext()) { + return null; + } + + gameprofilebanentry = iterator.next(); + } while (!s.equalsIgnoreCase(gameprofilebanentry.getKey().getName())); + + return gameprofilebanentry.getKey(); + } + + protected String a(GameProfile object) { + return this.b(object); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/GameProfileSerializer.java b/azurite-server/src/main/java/net/minecraft/server/GameProfileSerializer.java new file mode 100644 index 0000000..f22d2e5 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/GameProfileSerializer.java @@ -0,0 +1,163 @@ +package net.minecraft.server; + +import com.eatthepath.uuid.FastUUID; +import com.mojang.authlib.GameProfile; +import com.mojang.authlib.properties.Property; +import org.apache.commons.lang3.StringUtils; + +import java.util.Iterator; +import java.util.UUID; + +public final class GameProfileSerializer { + + public static GameProfile deserialize(NBTTagCompound nbttagcompound) { + String s = null; + String s1 = null; + + if (nbttagcompound.hasKeyOfType("Name", 8)) { + s = nbttagcompound.getString("Name"); + } + + if (nbttagcompound.hasKeyOfType("Id", 8)) { + s1 = nbttagcompound.getString("Id"); + } + + if (StringUtils.isEmpty(s) && StringUtils.isEmpty(s1)) { + return null; + } else { + UUID uuid; + + try { + uuid = FastUUID.parseUUID(s1); + } catch (Throwable throwable) { + uuid = null; + } + + GameProfile gameprofile = new GameProfile(uuid, s); + + if (nbttagcompound.hasKeyOfType("Properties", 10)) { + NBTTagCompound nbttagcompound1 = nbttagcompound.getCompound("Properties"); + + for (String s2 : nbttagcompound1.c()) { + NBTTagList nbttaglist = nbttagcompound1.getList(s2, 10); + + for (int i = 0; i < nbttaglist.size(); ++i) { + NBTTagCompound nbttagcompound2 = nbttaglist.get(i); + String s3 = nbttagcompound2.getString("Value"); + + if (nbttagcompound2.hasKeyOfType("Signature", 8)) { + gameprofile.getProperties().put(s2, new Property(s2, s3, nbttagcompound2.getString("Signature"))); + } else { + gameprofile.getProperties().put(s2, new Property(s2, s3)); + } + } + } + } + + return gameprofile; + } + } + + public static NBTTagCompound serialize(NBTTagCompound nbttagcompound, GameProfile gameprofile) { + if (!StringUtils.isEmpty(gameprofile.getName())) { + nbttagcompound.setString("Name", gameprofile.getName()); + } + + if (gameprofile.getId() != null) { + nbttagcompound.setString("Id", FastUUID.toString(gameprofile.getId())); + } + + if (!gameprofile.getProperties().isEmpty()) { + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + + for (String s : gameprofile.getProperties().keySet()) { + NBTTagList nbttaglist = new NBTTagList(); + + NBTTagCompound nbttagcompound2; + + for (Iterator iterator1 = gameprofile.getProperties().get(s).iterator(); iterator1.hasNext(); nbttaglist.add(nbttagcompound2)) { + Property property = iterator1.next(); + + nbttagcompound2 = new NBTTagCompound(); + nbttagcompound2.setString("Value", property.getValue()); + if (property.hasSignature()) { + nbttagcompound2.setString("Signature", property.getSignature()); + } + } + + nbttagcompound1.set(s, nbttaglist); + } + + nbttagcompound.set("Properties", nbttagcompound1); + } + + return nbttagcompound; + } + + public static boolean a(NBTBase nbtbase, NBTBase nbtbase1, boolean flag) { + if (nbtbase == nbtbase1) { + return true; + } else if (nbtbase == null) { + return true; + } else if (nbtbase1 == null) { + return false; + } else if (!nbtbase.getClass().equals(nbtbase1.getClass())) { + return false; + } else if (nbtbase instanceof NBTTagCompound) { + NBTTagCompound nbttagcompound = (NBTTagCompound) nbtbase; + NBTTagCompound nbttagcompound1 = (NBTTagCompound) nbtbase1; + Iterator iterator = nbttagcompound.c().iterator(); + + String s; + NBTBase nbtbase2; + + do { + if (!iterator.hasNext()) { + return true; + } + + s = iterator.next(); + nbtbase2 = nbttagcompound.get(s); + } while (a(nbtbase2, nbttagcompound1.get(s), flag)); + + return false; + } else if (nbtbase instanceof NBTTagList && flag) { + NBTTagList nbttaglist = (NBTTagList) nbtbase; + NBTTagList nbttaglist1 = (NBTTagList) nbtbase1; + + if (nbttaglist.size() == 0) { + return nbttaglist1.size() == 0; + } else { + int i = 0; + + while (i < nbttaglist.size()) { + NBTBase nbtbase3 = nbttaglist.g(i); + boolean flag1 = false; + int j = 0; + + while (true) { + if (j < nbttaglist1.size()) { + if (!a(nbtbase3, nbttaglist1.g(j), true)) { + ++j; + continue; + } + + flag1 = true; + } + + if (!flag1) { + return false; + } + + ++i; + break; + } + } + + return true; + } + } else { + return nbtbase.equals(nbtbase1); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/GameRules.java b/azurite-server/src/main/java/net/minecraft/server/GameRules.java new file mode 100644 index 0000000..822903f --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/GameRules.java @@ -0,0 +1,130 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.AzuriteConfig; + +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; + + +public class GameRules { + private final Map values = new LinkedHashMap<>(); // Azurite - Use LinkedHashMap + + public GameRules() { + a("doFireTick", "true", EnumGameRuleType.BOOLEAN_VALUE); + a("mobGriefing", "true", EnumGameRuleType.BOOLEAN_VALUE); + a("keepInventory", "false", EnumGameRuleType.BOOLEAN_VALUE); + a("doMobSpawning", AzuriteConfig.naturalMobSpawn.getValue().toString(), EnumGameRuleType.BOOLEAN_VALUE); + a("doMobLoot", "true", EnumGameRuleType.BOOLEAN_VALUE); + a("doTileDrops", "true", EnumGameRuleType.BOOLEAN_VALUE); + a("doEntityDrops", "true", EnumGameRuleType.BOOLEAN_VALUE); + a("commandBlockOutput", "true", EnumGameRuleType.BOOLEAN_VALUE); + a("naturalRegeneration", "true", EnumGameRuleType.BOOLEAN_VALUE); + a("doDaylightCycle", "true", EnumGameRuleType.BOOLEAN_VALUE); + a("logAdminCommands", "true", EnumGameRuleType.BOOLEAN_VALUE); + a("showDeathMessages", "true", EnumGameRuleType.BOOLEAN_VALUE); + a("randomTickSpeed", "3", EnumGameRuleType.NUMERICAL_VALUE); + a("sendCommandFeedback", "true", EnumGameRuleType.BOOLEAN_VALUE); + a("reducedDebugInfo", "false", EnumGameRuleType.BOOLEAN_VALUE); + a("doWeatherCycle", "true", EnumGameRuleType.BOOLEAN_VALUE); + } + + public void a(String name, String value, EnumGameRuleType type) { + this.values.put(name, new GameRuleValue(value, type)); + } + + public void set(String name, String defaultValue) { + GameRuleValue value = this.values.get(name); + if (value != null) { + value.a(defaultValue); + } else { + a(name, defaultValue, EnumGameRuleType.ANY_VALUE); + } + } + + public String get(String name) { + GameRuleValue value = this.values.get(name); + return (value != null) ? value.a() : ""; + } + + public boolean getBoolean(String name) { + GameRuleValue value = this.values.get(name); + return value != null && value.b(); + } + + public int c(String name) { + GameRuleValue gameRuleValue = this.values.get(name); + if (gameRuleValue != null) + return gameRuleValue.c(); + return 0; + } + + public NBTTagCompound a() { + NBTTagCompound compound = new NBTTagCompound(); + for (String name : this.values.keySet()) + compound.setString(name, this.values.get(name).a()); + return compound; + } + + public void a(NBTTagCompound compound) { + for (String str1 : compound.c()) + set(str1, compound.getString(str1)); + } + + public String[] getGameRules() { + Set set = this.values.keySet(); + return set.toArray(new String[0]); + } + + public boolean contains(String name) { + return this.values.containsKey(name); + } + + public boolean a(String name, EnumGameRuleType type) { + GameRuleValue value = this.values.get(name); + return (value != null && (value.e() == type || type == EnumGameRuleType.ANY_VALUE)); + } + + public enum EnumGameRuleType { + ANY_VALUE, BOOLEAN_VALUE, NUMERICAL_VALUE + } + + static class GameRuleValue { + private final GameRules.EnumGameRuleType e; + private String a; + private boolean b; + + private int c; + + public GameRuleValue(String value, GameRules.EnumGameRuleType type) { + this.e = type; + a(value); + } + + public void a(String value) { + this.a = value; + this.b = Boolean.parseBoolean(value); + this.c = this.b ? 1 : 0; + try { + this.c = Integer.parseInt(value); + } catch (NumberFormatException ignored) { + } + } + + public String a() { + return this.a; + } + + public boolean b() { + return this.b; + } + + public int c() { + return this.c; + } + + public GameRules.EnumGameRuleType e() { + return this.e; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/GenLayer.java b/azurite-server/src/main/java/net/minecraft/server/GenLayer.java new file mode 100644 index 0000000..0dc845b --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/GenLayer.java @@ -0,0 +1,206 @@ +package net.minecraft.server; + +import dev.azurite.spigot.generator.layer.GenLayerSpawnBiome; +import dev.azurite.spigot.generator.layer.GenLayerSpawnRiver; +import net.minecraft.server.CustomWorldSettingsFinal.CustomWorldSettings; +import net.minecraft.server.GenLayerSpecial.EnumGenLayerSpecial; + +public abstract class GenLayer { + private long c; + protected GenLayer a; + private long d; + protected long b; + + public static GenLayer[] a(long var0, WorldType var2, String var3, World world) { + GenLayer var30 = getGenLayer(world); + int var6 = 4; + int var7 = var6; + + if (var2 == WorldType.CUSTOMIZED && !var3.isEmpty()) { + CustomWorldSettingsFinal var31 = CustomWorldSettings.a(var3).b(); + var6 = var31.G; + var7 = var31.H; + } + + if (var2 == WorldType.LARGE_BIOMES) { + var6 = 6; + } + + GenLayer var8 = GenLayerZoom.b(1000L, var30, 0); + GenLayerCleaner var32 = new GenLayerCleaner(100L, var8); + GenLayerBiome var9 = new GenLayerBiome(200L, var30, var2, var3, world); + GenLayer var37 = GenLayerZoom.b(1000L, var9, 2); + GenLayerDesert var38 = new GenLayerDesert(1000L, var37); + GenLayer var10 = GenLayerZoom.b(1000L, var32, 2); + GenLayerRegionHills var39 = new GenLayerRegionHills(1000L, var38, var10, world); + GenLayer var33 = GenLayerZoom.b(1000L, var32, 2); + var33 = GenLayerZoom.b(1000L, var33, var7); + GenLayerRiverMix var42 = getGenLayerRiverMix(var33, var39, var6, world); + GenLayerZoomVoronoi var12 = new GenLayerZoomVoronoi(10L, var42); + (var42).a(var0); + (var12).a(var0); + return new GenLayer[]{var42, var12, var42}; + } + + private static GenLayerRiverMix getGenLayerRiverMix(GenLayer var33, GenLayerRegionHills var39, int var6, World world) { + GenLayer var35 = new GenLayerRiver(1L, var33); + + if (world.generatorConfig.spawnBiomeRadius.getValue() > 0 && !world.generatorConfig.spawnBiomeRivers.getValue()) { + var35 = new GenLayerSpawnRiver(1L, var33, world); + } + + GenLayerSmooth var36 = new GenLayerSmooth(1000L, var35); + GenLayer var40 = getGenLayer(var39, var6, world); + GenLayerSmooth var41 = new GenLayerSmooth(1000L, var40); + return new GenLayerRiverMix(100L, var41, var36); + } + + private static GenLayer getGenLayer(GenLayerRegionHills var39, int var6, World world) { + GenLayer var40 = new GenLayerPlains(1001L, var39); + + if (world.generatorConfig.spawnBiomeRadius.getValue() > 0) { + var40 = new GenLayerSpawnBiome(var40, var6, world); + } + + for (int var11 = 0; var11 < var6; ++var11) { + var40 = new GenLayerZoom((1000 + var11), var40); + if (var11 == 0) { + var40 = new GenLayerIsland(3L, var40); + } + + if (var11 == 1 || var6 == 1) { + var40 = new GenLayerMushroomShore(1000L, var40); + } + } + return var40; + } + + private static GenLayer getGenLayer(World world) { + GenLayerSpecial var22 = getGenLayerSpecial(world); + var22 = new GenLayerSpecial(2L, var22, EnumGenLayerSpecial.HEAT_ICE); + var22 = new GenLayerSpecial(3L, var22, EnumGenLayerSpecial.SPECIAL); + GenLayerZoom var25 = new GenLayerZoom(2002L, var22); + var25 = new GenLayerZoom(2003L, var25); + GenLayerIsland var27 = new GenLayerIsland(4L, var25); + GenLayerMushroomIsland var28 = new GenLayerMushroomIsland(5L, var27, world); + GenLayerDeepOcean var29 = new GenLayerDeepOcean(4L, var28); + return GenLayerZoom.b(1000L, var29, 0); + } + + private static GenLayerSpecial getGenLayerSpecial(World world) { + LayerIsland var4 = new LayerIsland(1L, world); + GenLayerZoomFuzzy var13 = new GenLayerZoomFuzzy(2000L, var4); + GenLayerIsland var14 = new GenLayerIsland(1L, var13); + GenLayerZoom var15 = new GenLayerZoom(2001L, var14); + GenLayerIsland var16 = new GenLayerIsland(2L, var15); + var16 = new GenLayerIsland(50L, var16); + var16 = new GenLayerIsland(70L, var16); + GenLayerIcePlains var19 = new GenLayerIcePlains(2L, var16); + GenLayerTopSoil var20 = new GenLayerTopSoil(2L, var19); + GenLayerIsland var21 = new GenLayerIsland(3L, var20); + return new GenLayerSpecial(2L, var21, EnumGenLayerSpecial.COOL_WARM); + } + + public GenLayer(long var1) { + this.b = var1; + this.b *= this.b * 6364136223846793005L + 1442695040888963407L; + this.b += var1; + this.b *= this.b * 6364136223846793005L + 1442695040888963407L; + this.b += var1; + this.b *= this.b * 6364136223846793005L + 1442695040888963407L; + this.b += var1; + } + + public void a(long var1) { + this.c = var1; + if (this.a != null) { + this.a.a(var1); + } + + this.c *= this.c * 6364136223846793005L + 1442695040888963407L; + this.c += this.b; + this.c *= this.c * 6364136223846793005L + 1442695040888963407L; + this.c += this.b; + this.c *= this.c * 6364136223846793005L + 1442695040888963407L; + this.c += this.b; + } + + public void a(long var1, long var3) { + this.d = this.c; + this.d *= this.d * 6364136223846793005L + 1442695040888963407L; + this.d += var1; + this.d *= this.d * 6364136223846793005L + 1442695040888963407L; + this.d += var3; + this.d *= this.d * 6364136223846793005L + 1442695040888963407L; + this.d += var1; + this.d *= this.d * 6364136223846793005L + 1442695040888963407L; + this.d += var3; + } + + protected int a(int var1) { + int var2 = (int) ((this.d >> 24) % (long) var1); + if (var2 < 0) { + var2 += var1; + } + + this.d *= this.d * 6364136223846793005L + 1442695040888963407L; + this.d += this.c; + return var2; + } + + public abstract int[] a(int var1, int var2, int var3, int var4); + + protected static boolean a(int var0, int var1) { + if (var0 == var1) { + return true; + } else if (var0 != BiomeBase.MESA_PLATEAU_F.id && var0 != BiomeBase.MESA_PLATEAU.id) { + final BiomeBase var2 = BiomeBase.getBiome(var0); + final BiomeBase var3 = BiomeBase.getBiome(var1); + try { + return var2 != null && var3 != null && var2.a(var3); + } catch (Throwable var7) { + CrashReport var5 = CrashReport.a(var7, "Comparing biomes"); + CrashReportSystemDetails var6 = var5.a("Biomes being compared"); + var6.a("Biome A ID", var0); + var6.a("Biome B ID", var1); + var6.a("Biome A", () -> String.valueOf(var2)); + var6.a("Biome B", () -> String.valueOf(var3)); + throw new ReportedException(var5); + } + } else { + return var1 == BiomeBase.MESA_PLATEAU_F.id || var1 == BiomeBase.MESA_PLATEAU.id; + } + } + + protected static boolean b(int var0) { + return var0 == BiomeBase.OCEAN.id || var0 == BiomeBase.DEEP_OCEAN.id || var0 == BiomeBase.FROZEN_OCEAN.id; + } + + protected int a(int... var1) { + return var1[this.a(var1.length)]; + } + + protected int b(int var1, int var2, int var3, int var4) { + if (var2 == var3 && var3 == var4) { + return var2; + } else if (var1 == var2 && var1 == var3) { + return var1; + } else if (var1 == var2 && var1 == var4) { + return var1; + } else if (var1 == var3 && var1 == var4) { + return var1; + } else if (var1 == var2 && var3 != var4) { + return var1; + } else if (var1 == var3 && var2 != var4) { + return var1; + } else if (var1 == var4 && var2 != var3) { + return var1; + } else if (var2 == var3 && var1 != var4) { + return var2; + } else if (var2 == var4 && var1 != var3) { + return var2; + } else { + return var3 == var4 && var1 != var2 ? var3 : this.a(new int[]{var1, var2, var3, var4}); + } + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/net/minecraft/server/GenLayerBiome.java b/azurite-server/src/main/java/net/minecraft/server/GenLayerBiome.java new file mode 100644 index 0000000..30da23b --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/GenLayerBiome.java @@ -0,0 +1,157 @@ +package net.minecraft.server; + +import java.util.ArrayList; +import java.util.List; + +public class GenLayerBiome extends GenLayer { + + private BiomeBase[] c; + private final BiomeBase[] d, e, f; + private final CustomWorldSettingsFinal g; + private final World world; + + public GenLayerBiome(long i, GenLayer genlayer, WorldType worldtype, String s, World world) { + super(i); + List list = new ArrayList<>(); + if (world.generatorConfig.biomeDesert.getValue()) { + list.add(BiomeBase.DESERT); + list.add(BiomeBase.DESERT); + list.add(BiomeBase.DESERT); + } + if (world.generatorConfig.biomeSavanna.getValue()) { + list.add(BiomeBase.SAVANNA); + list.add(BiomeBase.SAVANNA); + } + if (world.generatorConfig.biomePlains.getValue()) { + list.add(BiomeBase.PLAINS); + } + this.c = list.toArray(new BiomeBase[0]); + list.clear(); + + if (world.generatorConfig.biomeForest.getValue()) { + list.add(BiomeBase.FOREST); + } + if (world.generatorConfig.biomeRoofedForest.getValue()) { + list.add(BiomeBase.ROOFED_FOREST); + } + if (world.generatorConfig.biomeExtremeHills.getValue()) { + list.add(BiomeBase.EXTREME_HILLS); + } + if (world.generatorConfig.biomePlains.getValue()) { + list.add(BiomeBase.PLAINS); + } + if (world.generatorConfig.biomeBirchForest.getValue()) { + list.add(BiomeBase.BIRCH_FOREST); + } + if (world.generatorConfig.biomeSwampland.getValue()) { + list.add(BiomeBase.SWAMPLAND); + } + if (list.isEmpty() && world.generatorConfig.biomeJungle.getValue()) { + list.add(BiomeBase.JUNGLE); + } + this.d = list.toArray(new BiomeBase[0]); + list.clear(); + + if (world.generatorConfig.biomeForest.getValue()) { + list.add(BiomeBase.FOREST); + } + if (world.generatorConfig.biomeExtremeHills.getValue()) { + list.add(BiomeBase.EXTREME_HILLS); + } + if (world.generatorConfig.biomeTaiga.getValue()) { + list.add(BiomeBase.TAIGA); + } + if (world.generatorConfig.biomePlains.getValue()) { + list.add(BiomeBase.PLAINS); + } + this.e = list.toArray(new BiomeBase[0]); + list.clear(); + + if (world.generatorConfig.biomeIcePlains.getValue()) { + list.add(BiomeBase.ICE_PLAINS); + list.add(BiomeBase.ICE_PLAINS); + list.add(BiomeBase.ICE_PLAINS); + } + if (world.generatorConfig.biomeColdTaiga.getValue()) { + list.add(BiomeBase.COLD_TAIGA); + } + this.f = list.toArray(new BiomeBase[0]); + this.a = genlayer; + this.world = world; + if (worldtype == WorldType.NORMAL_1_1) { + this.c = new BiomeBase[]{BiomeBase.DESERT, BiomeBase.FOREST, BiomeBase.EXTREME_HILLS, BiomeBase.SWAMPLAND, BiomeBase.PLAINS, BiomeBase.TAIGA}; + this.g = null; + } else if (worldtype == WorldType.CUSTOMIZED) { + this.g = CustomWorldSettingsFinal.CustomWorldSettings.a(s).b(); + } else { + this.g = null; + } + } + + public int[] a(int i, int j, int k, int l) { + int[] aint = this.a.a(i, j, k, l); + int[] aint1 = IntCache.a(k * l); + + for (int i1 = 0; i1 < l; ++i1) { + for (int j1 = 0; j1 < k; ++j1) { + this.a(j1 + i, (long) (i1 + j)); + int k1 = aint[j1 + i1 * k]; + int l1 = (k1 & 3840) >> 8; + + k1 &= -3841; + if (this.g != null && this.g.F >= 0) { + aint1[j1 + i1 * k] = this.g.F; + } else if (b(k1)) { + aint1[j1 + i1 * k] = k1; + } else if (k1 == BiomeBase.MUSHROOM_ISLAND.id) { + aint1[j1 + i1 * k] = k1; + } else if (k1 == 1) { + BiomeBase[] biomes = this.firstNonEmpty(this.c, this.d, this.e, this.f); + if (l1 > 0) { + if (this.a(3) == 0 && this.world.generatorConfig.biomeMesaPlateau.getValue()) { + aint1[j1 + i1 * k] = BiomeBase.MESA_PLATEAU.id; + } else if (this.world.generatorConfig.biomeMesaPlateauF.getValue()) { + aint1[j1 + i1 * k] = BiomeBase.MESA_PLATEAU_F.id; + } else if (this.world.generatorConfig.biomeMesa.getValue()) { + aint1[j1 + i1 * k] = BiomeBase.MESA.id; + } else { + aint1[j1 + i1 * k] = biomes[this.a(biomes.length)].id; + } + } else { + aint1[j1 + i1 * k] = biomes[this.a(biomes.length)].id; + } + } else if (k1 == 2) { + BiomeBase[] biomes = this.firstNonEmpty(this.d, this.e, this.f, this.c); + if (l1 > 0 && this.world.generatorConfig.biomeJungle.getValue()) { + aint1[j1 + i1 * k] = BiomeBase.JUNGLE.id; + } else { + aint1[j1 + i1 * k] = biomes[this.a(biomes.length)].id; + } + } else if (k1 == 3) { + BiomeBase[] biomes = this.firstNonEmpty(this.e, this.f, this.c, this.d); + if (l1 > 0 && this.world.generatorConfig.biomeMegaTaiga.getValue()) { + aint1[j1 + i1 * k] = BiomeBase.MEGA_TAIGA.id; + } else { + aint1[j1 + i1 * k] = biomes[this.a(biomes.length)].id; + } + } else if (k1 == 4) { + BiomeBase[] biomes = this.firstNonEmpty(this.f, this.c, this.d, this.e); + aint1[j1 + i1 * k] = biomes[this.a(biomes.length)].id; + } else { + aint1[j1 + i1 * k] = BiomeBase.MUSHROOM_ISLAND.id; + } + } + } + + return aint1; + } + + private BiomeBase[] firstNonEmpty(BiomeBase[]... options) { + for (BiomeBase[] option : options) { + if (option.length > 0) { + return option; + } + } + return new BiomeBase[]{BiomeBase.PLAINS}; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/GenLayerCleaner.java b/azurite-server/src/main/java/net/minecraft/server/GenLayerCleaner.java new file mode 100644 index 0000000..4522236 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/GenLayerCleaner.java @@ -0,0 +1,23 @@ +package net.minecraft.server; + +public class GenLayerCleaner extends GenLayer { + + public GenLayerCleaner(long i, GenLayer genlayer) { + super(i); + this.a = genlayer; + } + + public int[] a(int i, int j, int k, int l) { + int[] aint = this.a.a(i, j, k, l); + int[] aint1 = IntCache.a(k * l); + + for (int i1 = 0; i1 < l; ++i1) { + for (int j1 = 0; j1 < k; ++j1) { + this.a((long) (j1 + i), (long) (i1 + j)); + aint1[j1 + i1 * k] = aint[j1 + i1 * k] > 0 ? this.a(299999) + 2 : 0; + } + } + + return aint1; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/GenLayerDeepOcean.java b/azurite-server/src/main/java/net/minecraft/server/GenLayerDeepOcean.java new file mode 100644 index 0000000..71d1df7 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/GenLayerDeepOcean.java @@ -0,0 +1,53 @@ +package net.minecraft.server; + +public class GenLayerDeepOcean extends GenLayer { + + public GenLayerDeepOcean(long i, GenLayer genlayer) { + super(i); + this.a = genlayer; + } + + public int[] a(int i, int j, int k, int l) { + int i1 = i - 1; + int j1 = j - 1; + int k1 = k + 2; + int l1 = l + 2; + int[] aint = this.a.a(i1, j1, k1, l1); + int[] aint1 = IntCache.a(k * l); + + for (int i2 = 0; i2 < l; ++i2) { + for (int j2 = 0; j2 < k; ++j2) { + int k2 = aint[j2 + 1 + (i2 + 1 - 1) * (k + 2)]; + int l2 = aint[j2 + 1 + 1 + (i2 + 1) * (k + 2)]; + int i3 = aint[j2 + 1 - 1 + (i2 + 1) * (k + 2)]; + int j3 = aint[j2 + 1 + (i2 + 1 + 1) * (k + 2)]; + int k3 = aint[j2 + 1 + (i2 + 1) * k1]; + int l3 = 0; + + if (k2 == 0) { + ++l3; + } + + if (l2 == 0) { + ++l3; + } + + if (i3 == 0) { + ++l3; + } + + if (j3 == 0) { + ++l3; + } + + if (k3 == 0 && l3 > 3) { + aint1[j2 + i2 * k] = BiomeBase.DEEP_OCEAN.id; + } else { + aint1[j2 + i2 * k] = k3; + } + } + } + + return aint1; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/GenLayerDesert.java b/azurite-server/src/main/java/net/minecraft/server/GenLayerDesert.java new file mode 100644 index 0000000..901beae --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/GenLayerDesert.java @@ -0,0 +1,114 @@ +package net.minecraft.server; + +public class GenLayerDesert extends GenLayer { + + public GenLayerDesert(long i, GenLayer genlayer) { + super(i); + this.a = genlayer; + } + + public int[] a(int i, int j, int k, int l) { + int[] aint = this.a.a(i - 1, j - 1, k + 2, l + 2); + int[] aint1 = IntCache.a(k * l); + + for (int i1 = 0; i1 < l; ++i1) { + for (int j1 = 0; j1 < k; ++j1) { + this.a((long) (j1 + i), (long) (i1 + j)); + int k1 = aint[j1 + 1 + (i1 + 1) * (k + 2)]; + + if (!this.a(aint, aint1, j1, i1, k, k1, BiomeBase.EXTREME_HILLS.id, BiomeBase.SMALL_MOUNTAINS.id) && !this.b(aint, aint1, j1, i1, k, k1, BiomeBase.MESA_PLATEAU_F.id, BiomeBase.MESA.id) && !this.b(aint, aint1, j1, i1, k, k1, BiomeBase.MESA_PLATEAU.id, BiomeBase.MESA.id) && !this.b(aint, aint1, j1, i1, k, k1, BiomeBase.MEGA_TAIGA.id, BiomeBase.TAIGA.id)) { + int l1; + int i2; + int j2; + int k2; + + if (k1 == BiomeBase.DESERT.id) { + l1 = aint[j1 + 1 + (i1 + 1 - 1) * (k + 2)]; + i2 = aint[j1 + 1 + 1 + (i1 + 1) * (k + 2)]; + j2 = aint[j1 + 1 - 1 + (i1 + 1) * (k + 2)]; + k2 = aint[j1 + 1 + (i1 + 1 + 1) * (k + 2)]; + if (l1 != BiomeBase.ICE_PLAINS.id && i2 != BiomeBase.ICE_PLAINS.id && j2 != BiomeBase.ICE_PLAINS.id && k2 != BiomeBase.ICE_PLAINS.id) { + aint1[j1 + i1 * k] = k1; + } else { + aint1[j1 + i1 * k] = BiomeBase.EXTREME_HILLS_PLUS.id; + } + } else if (k1 == BiomeBase.SWAMPLAND.id) { + l1 = aint[j1 + 1 + (i1 + 1 - 1) * (k + 2)]; + i2 = aint[j1 + 1 + 1 + (i1 + 1) * (k + 2)]; + j2 = aint[j1 + 1 - 1 + (i1 + 1) * (k + 2)]; + k2 = aint[j1 + 1 + (i1 + 1 + 1) * (k + 2)]; + if (l1 != BiomeBase.DESERT.id && i2 != BiomeBase.DESERT.id && j2 != BiomeBase.DESERT.id && k2 != BiomeBase.DESERT.id && l1 != BiomeBase.COLD_TAIGA.id && i2 != BiomeBase.COLD_TAIGA.id && j2 != BiomeBase.COLD_TAIGA.id && k2 != BiomeBase.COLD_TAIGA.id && l1 != BiomeBase.ICE_PLAINS.id && i2 != BiomeBase.ICE_PLAINS.id && j2 != BiomeBase.ICE_PLAINS.id && k2 != BiomeBase.ICE_PLAINS.id) { + if (l1 != BiomeBase.JUNGLE.id && k2 != BiomeBase.JUNGLE.id && i2 != BiomeBase.JUNGLE.id && j2 != BiomeBase.JUNGLE.id) { + aint1[j1 + i1 * k] = k1; + } else { + aint1[j1 + i1 * k] = BiomeBase.JUNGLE_EDGE.id; + } + } else { + aint1[j1 + i1 * k] = BiomeBase.PLAINS.id; + } + } else { + aint1[j1 + i1 * k] = k1; + } + } + } + } + + return aint1; + } + + private boolean a(int[] aint, int[] aint1, int i, int j, int k, int l, int i1, int j1) { + if (!a(l, i1)) { + return false; + } else { + int k1 = aint[i + 1 + (j + 1 - 1) * (k + 2)]; + int l1 = aint[i + 1 + 1 + (j + 1) * (k + 2)]; + int i2 = aint[i + 1 - 1 + (j + 1) * (k + 2)]; + int j2 = aint[i + 1 + (j + 1 + 1) * (k + 2)]; + + if (this.b(k1, i1) && this.b(l1, i1) && this.b(i2, i1) && this.b(j2, i1)) { + aint1[i + j * k] = l; + } else { + aint1[i + j * k] = j1; + } + + return true; + } + } + + private boolean b(int[] aint, int[] aint1, int i, int j, int k, int l, int i1, int j1) { + if (l != i1) { + return false; + } else { + int k1 = aint[i + 1 + (j + 1 - 1) * (k + 2)]; + int l1 = aint[i + 1 + 1 + (j + 1) * (k + 2)]; + int i2 = aint[i + 1 - 1 + (j + 1) * (k + 2)]; + int j2 = aint[i + 1 + (j + 1 + 1) * (k + 2)]; + + if (a(k1, i1) && a(l1, i1) && a(i2, i1) && a(j2, i1)) { + aint1[i + j * k] = l; + } else { + aint1[i + j * k] = j1; + } + + return true; + } + } + + private boolean b(int i, int j) { + if (a(i, j)) { + return true; + } else { + BiomeBase biomebase = BiomeBase.getBiome(i); + BiomeBase biomebase1 = BiomeBase.getBiome(j); + + if (biomebase != null && biomebase1 != null) { + BiomeBase.EnumTemperature biomebase_enumtemperature = biomebase.m(); + BiomeBase.EnumTemperature biomebase_enumtemperature1 = biomebase1.m(); + + return biomebase_enumtemperature == biomebase_enumtemperature1 || biomebase_enumtemperature == BiomeBase.EnumTemperature.MEDIUM || biomebase_enumtemperature1 == BiomeBase.EnumTemperature.MEDIUM; + } else { + return false; + } + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/GenLayerIcePlains.java b/azurite-server/src/main/java/net/minecraft/server/GenLayerIcePlains.java new file mode 100644 index 0000000..993f058 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/GenLayerIcePlains.java @@ -0,0 +1,36 @@ +package net.minecraft.server; + +public class GenLayerIcePlains extends GenLayer { + + public GenLayerIcePlains(long i, GenLayer genlayer) { + super(i); + this.a = genlayer; + } + + public int[] a(int i, int j, int k, int l) { + int i1 = i - 1; + int j1 = j - 1; + int k1 = k + 2; + int l1 = l + 2; + int[] aint = this.a.a(i1, j1, k1, l1); + int[] aint1 = IntCache.a(k * l); + + for (int i2 = 0; i2 < l; ++i2) { + for (int j2 = 0; j2 < k; ++j2) { + int k2 = aint[j2 + 1 + (i2 + 1 - 1) * (k + 2)]; + int l2 = aint[j2 + 1 + 1 + (i2 + 1) * (k + 2)]; + int i3 = aint[j2 + 1 - 1 + (i2 + 1) * (k + 2)]; + int j3 = aint[j2 + 1 + (i2 + 1 + 1) * (k + 2)]; + int k3 = aint[j2 + 1 + (i2 + 1) * k1]; + + aint1[j2 + i2 * k] = k3; + this.a((long) (j2 + i), (long) (i2 + j)); + if (k3 == 0 && k2 == 0 && l2 == 0 && i3 == 0 && j3 == 0 && this.a(2) == 0) { + aint1[j2 + i2 * k] = 1; + } + } + } + + return aint1; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/GenLayerIsland.java b/azurite-server/src/main/java/net/minecraft/server/GenLayerIsland.java new file mode 100644 index 0000000..ff8c936 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/GenLayerIsland.java @@ -0,0 +1,72 @@ +package net.minecraft.server; + +public class GenLayerIsland extends GenLayer { + + public GenLayerIsland(long i, GenLayer genlayer) { + super(i); + this.a = genlayer; + } + + public int[] a(int i, int j, int k, int l) { + int i1 = i - 1; + int j1 = j - 1; + int k1 = k + 2; + int l1 = l + 2; + int[] aint = this.a.a(i1, j1, k1, l1); + int[] aint1 = IntCache.a(k * l); + + for (int i2 = 0; i2 < l; ++i2) { + for (int j2 = 0; j2 < k; ++j2) { + int k2 = aint[j2 + 0 + (i2 + 0) * k1]; + int l2 = aint[j2 + 2 + (i2 + 0) * k1]; + int i3 = aint[j2 + 0 + (i2 + 2) * k1]; + int j3 = aint[j2 + 2 + (i2 + 2) * k1]; + int k3 = aint[j2 + 1 + (i2 + 1) * k1]; + + this.a((long) (j2 + i), (long) (i2 + j)); + if (k3 == 0 && (k2 != 0 || l2 != 0 || i3 != 0 || j3 != 0)) { + int l3 = 1; + int i4 = 1; + + if (k2 != 0 && this.a(l3++) == 0) { + i4 = k2; + } + + if (l2 != 0 && this.a(l3++) == 0) { + i4 = l2; + } + + if (i3 != 0 && this.a(l3++) == 0) { + i4 = i3; + } + + if (j3 != 0 && this.a(l3++) == 0) { + i4 = j3; + } + + if (this.a(3) == 0) { + aint1[j2 + i2 * k] = i4; + } else if (i4 == 4) { + aint1[j2 + i2 * k] = 4; + } else { + aint1[j2 + i2 * k] = 0; + } + } else if (k3 > 0 && (k2 == 0 || l2 == 0 || i3 == 0 || j3 == 0)) { + if (this.a(5) == 0) { + if (k3 == 4) { + aint1[j2 + i2 * k] = 4; + } else { + aint1[j2 + i2 * k] = 0; + } + } else { + aint1[j2 + i2 * k] = k3; + } + } else { + aint1[j2 + i2 * k] = k3; + } + } + } + + return aint1; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/GenLayerMushroomIsland.java b/azurite-server/src/main/java/net/minecraft/server/GenLayerMushroomIsland.java new file mode 100644 index 0000000..93e442b --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/GenLayerMushroomIsland.java @@ -0,0 +1,40 @@ +package net.minecraft.server; + +public class GenLayerMushroomIsland extends GenLayer { + + private final World world; + + public GenLayerMushroomIsland(long var1, GenLayer var3, World world) { + super(var1); + this.a = var3; + this.world = world; + } + + public int[] a(int var1, int var2, int var3, int var4) { + int var5 = var1 - 1; + int var6 = var2 - 1; + int var7 = var3 + 2; + int var8 = var4 + 2; + int[] var9 = this.a.a(var5, var6, var7, var8); + int[] var10 = IntCache.a(var3 * var4); + + for (int var11 = 0; var11 < var4; ++var11) { + for (int var12 = 0; var12 < var3; ++var12) { + int var13 = var9[var12 + (var11) * var7]; + int var14 = var9[var12 + 2 + (var11) * var7]; + int var15 = var9[var12 + (var11 + 2) * var7]; + int var16 = var9[var12 + 2 + (var11 + 2) * var7]; + int var17 = var9[var12 + 1 + (var11 + 1) * var7]; + this.a(var12 + var1, (long) (var11 + var2)); + + if (var17 == 0 && var13 == 0 && var14 == 0 && var15 == 0 && var16 == 0 && this.a(100) == 0 && world.generatorConfig.biomeMushroomIsland.getValue()) { + var10[var12 + var11 * var3] = BiomeBase.MUSHROOM_ISLAND.id; + } else { + var10[var12 + var11 * var3] = var17; + } + } + } + + return var10; + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/net/minecraft/server/GenLayerMushroomShore.java b/azurite-server/src/main/java/net/minecraft/server/GenLayerMushroomShore.java new file mode 100644 index 0000000..96e2c31 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/GenLayerMushroomShore.java @@ -0,0 +1,114 @@ +package net.minecraft.server; + +public class GenLayerMushroomShore extends GenLayer { + + public GenLayerMushroomShore(long i, GenLayer genlayer) { + super(i); + this.a = genlayer; + } + + public int[] a(int i, int j, int k, int l) { + int[] aint = this.a.a(i - 1, j - 1, k + 2, l + 2); + int[] aint1 = IntCache.a(k * l); + + for (int i1 = 0; i1 < l; ++i1) { + for (int j1 = 0; j1 < k; ++j1) { + this.a((long) (j1 + i), (long) (i1 + j)); + int k1 = aint[j1 + 1 + (i1 + 1) * (k + 2)]; + BiomeBase biomebase = BiomeBase.getBiome(k1); + int l1; + int i2; + int j2; + int k2; + + if (k1 == BiomeBase.MUSHROOM_ISLAND.id) { + l1 = aint[j1 + 1 + (i1 + 1 - 1) * (k + 2)]; + i2 = aint[j1 + 1 + 1 + (i1 + 1) * (k + 2)]; + j2 = aint[j1 + 1 - 1 + (i1 + 1) * (k + 2)]; + k2 = aint[j1 + 1 + (i1 + 1 + 1) * (k + 2)]; + if (l1 != BiomeBase.OCEAN.id && i2 != BiomeBase.OCEAN.id && j2 != BiomeBase.OCEAN.id && k2 != BiomeBase.OCEAN.id) { + aint1[j1 + i1 * k] = k1; + } else { + aint1[j1 + i1 * k] = BiomeBase.MUSHROOM_SHORE.id; + } + } else if (biomebase != null && biomebase.l() == BiomeJungle.class) { + l1 = aint[j1 + 1 + (i1 + 1 - 1) * (k + 2)]; + i2 = aint[j1 + 1 + 1 + (i1 + 1) * (k + 2)]; + j2 = aint[j1 + 1 - 1 + (i1 + 1) * (k + 2)]; + k2 = aint[j1 + 1 + (i1 + 1 + 1) * (k + 2)]; + if (this.c(l1) && this.c(i2) && this.c(j2) && this.c(k2)) { + if (!b(l1) && !b(i2) && !b(j2) && !b(k2)) { + aint1[j1 + i1 * k] = k1; + } else { + aint1[j1 + i1 * k] = BiomeBase.BEACH.id; + } + } else { + aint1[j1 + i1 * k] = BiomeBase.JUNGLE_EDGE.id; + } + } else if (k1 != BiomeBase.EXTREME_HILLS.id && k1 != BiomeBase.EXTREME_HILLS_PLUS.id && k1 != BiomeBase.SMALL_MOUNTAINS.id) { + if (biomebase != null && biomebase.j()) { + this.a(aint, aint1, j1, i1, k, k1, BiomeBase.COLD_BEACH.id); + } else if (k1 != BiomeBase.MESA.id && k1 != BiomeBase.MESA_PLATEAU_F.id) { + if (k1 != BiomeBase.OCEAN.id && k1 != BiomeBase.DEEP_OCEAN.id && k1 != BiomeBase.RIVER.id && k1 != BiomeBase.SWAMPLAND.id) { + l1 = aint[j1 + 1 + (i1 + 1 - 1) * (k + 2)]; + i2 = aint[j1 + 1 + 1 + (i1 + 1) * (k + 2)]; + j2 = aint[j1 + 1 - 1 + (i1 + 1) * (k + 2)]; + k2 = aint[j1 + 1 + (i1 + 1 + 1) * (k + 2)]; + if (!b(l1) && !b(i2) && !b(j2) && !b(k2)) { + aint1[j1 + i1 * k] = k1; + } else { + aint1[j1 + i1 * k] = BiomeBase.BEACH.id; + } + } else { + aint1[j1 + i1 * k] = k1; + } + } else { + l1 = aint[j1 + 1 + (i1 + 1 - 1) * (k + 2)]; + i2 = aint[j1 + 1 + 1 + (i1 + 1) * (k + 2)]; + j2 = aint[j1 + 1 - 1 + (i1 + 1) * (k + 2)]; + k2 = aint[j1 + 1 + (i1 + 1 + 1) * (k + 2)]; + if (!b(l1) && !b(i2) && !b(j2) && !b(k2)) { + if (this.d(l1) && this.d(i2) && this.d(j2) && this.d(k2)) { + aint1[j1 + i1 * k] = k1; + } else { + aint1[j1 + i1 * k] = BiomeBase.DESERT.id; + } + } else { + aint1[j1 + i1 * k] = k1; + } + } + } else { + this.a(aint, aint1, j1, i1, k, k1, BiomeBase.STONE_BEACH.id); + } + } + } + + return aint1; + } + + private void a(int[] aint, int[] aint1, int i, int j, int k, int l, int i1) { + if (b(l)) { + aint1[i + j * k] = l; + } else { + int j1 = aint[i + 1 + (j + 1 - 1) * (k + 2)]; + int k1 = aint[i + 1 + 1 + (j + 1) * (k + 2)]; + int l1 = aint[i + 1 - 1 + (j + 1) * (k + 2)]; + int i2 = aint[i + 1 + (j + 1 + 1) * (k + 2)]; + + if (!b(j1) && !b(k1) && !b(l1) && !b(i2)) { + aint1[i + j * k] = l; + } else { + aint1[i + j * k] = i1; + } + + } + } + + private boolean c(int i) { + return BiomeBase.getBiome(i) != null && BiomeBase.getBiome(i).l() == BiomeJungle.class ? true : i == BiomeBase.JUNGLE_EDGE.id || i == BiomeBase.JUNGLE.id || i == BiomeBase.JUNGLE_HILLS.id || i == BiomeBase.FOREST.id || i == BiomeBase.TAIGA.id || b(i); + } + + private boolean d(int i) { + return BiomeBase.getBiome(i) instanceof BiomeMesa; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/GenLayerPlains.java b/azurite-server/src/main/java/net/minecraft/server/GenLayerPlains.java new file mode 100644 index 0000000..2a8a99f --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/GenLayerPlains.java @@ -0,0 +1,33 @@ +package net.minecraft.server; + +public class GenLayerPlains extends GenLayer { + + public GenLayerPlains(long i, GenLayer genlayer) { + super(i); + this.a = genlayer; + } + + public int[] a(int i, int j, int k, int l) { + int[] aint = this.a.a(i - 1, j - 1, k + 2, l + 2); + int[] aint1 = IntCache.a(k * l); + + for (int i1 = 0; i1 < l; ++i1) { + for (int j1 = 0; j1 < k; ++j1) { + this.a((long) (j1 + i), (long) (i1 + j)); + int k1 = aint[j1 + 1 + (i1 + 1) * (k + 2)]; + + if (this.a(57) == 0) { + if (k1 == BiomeBase.PLAINS.id) { + aint1[j1 + i1 * k] = BiomeBase.PLAINS.id + 128; + } else { + aint1[j1 + i1 * k] = k1; + } + } else { + aint1[j1 + i1 * k] = k1; + } + } + } + + return aint1; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/GenLayerRegionHills.java b/azurite-server/src/main/java/net/minecraft/server/GenLayerRegionHills.java new file mode 100644 index 0000000..d874a72 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/GenLayerRegionHills.java @@ -0,0 +1,125 @@ +package net.minecraft.server; + +public class GenLayerRegionHills extends GenLayer { + + private final GenLayer d; + private final World world; + + public GenLayerRegionHills(long i, GenLayer genlayer, GenLayer genlayer1, World world) { + super(i); + this.a = genlayer; + this.d = genlayer1; + this.world = world; + } + + public int[] a(int i, int j, int k, int l) { + int[] aint = this.a.a(i - 1, j - 1, k + 2, l + 2); + int[] aint1 = this.d.a(i - 1, j - 1, k + 2, l + 2); + int[] aint2 = IntCache.a(k * l); + + for (int i1 = 0; i1 < l; ++i1) { + for (int j1 = 0; j1 < k; ++j1) { + this.a((j1 + i), (long) (i1 + j)); + int k1 = aint[j1 + 1 + (i1 + 1) * (k + 2)]; + int l1 = aint1[j1 + 1 + (i1 + 1) * (k + 2)]; + boolean flag = (l1 - 2) % 29 == 0; + + if (k1 != 0 && l1 >= 2 && (l1 - 2) % 29 == 1 && k1 < 128) { + if (BiomeBase.getBiome(k1 + 128) != null) { + aint2[j1 + i1 * k] = k1 + 128; + } else { + aint2[j1 + i1 * k] = k1; + } + } else if (this.a(3) != 0 && !flag) { + aint2[j1 + i1 * k] = k1; + } else { + int i2 = k1; + int j2; + + if (k1 == BiomeBase.DESERT.id && this.world.generatorConfig.biomeDesertHills.getValue()) { + i2 = BiomeBase.DESERT_HILLS.id; + } else if (k1 == BiomeBase.FOREST.id && this.world.generatorConfig.biomeForestHills.getValue()) { + i2 = BiomeBase.FOREST_HILLS.id; + } else if (k1 == BiomeBase.BIRCH_FOREST.id && this.world.generatorConfig.biomeBirchForestHills.getValue()) { + i2 = BiomeBase.BIRCH_FOREST_HILLS.id; + } else if (k1 == BiomeBase.ROOFED_FOREST.id && this.world.generatorConfig.biomePlains.getValue()) { + i2 = BiomeBase.PLAINS.id; + } else if (k1 == BiomeBase.TAIGA.id && this.world.generatorConfig.biomeTaigaHills.getValue()) { + i2 = BiomeBase.TAIGA_HILLS.id; + } else if (k1 == BiomeBase.MEGA_TAIGA.id && this.world.generatorConfig.biomeMegaTaigaHills.getValue()) { + i2 = BiomeBase.MEGA_TAIGA_HILLS.id; + } else if (k1 == BiomeBase.COLD_TAIGA.id && this.world.generatorConfig.biomeColdTaigaHills.getValue()) { + i2 = BiomeBase.COLD_TAIGA_HILLS.id; + } else if (k1 == BiomeBase.PLAINS.id) { + if (this.a(3) == 0 && this.world.generatorConfig.biomeForestHills.getValue()) { + i2 = BiomeBase.FOREST_HILLS.id; + } else if (this.world.generatorConfig.biomeForest.getValue()) { + i2 = BiomeBase.FOREST.id; + } + } else if (k1 == BiomeBase.ICE_PLAINS.id && this.world.generatorConfig.biomeIceMountains.getValue()) { + i2 = BiomeBase.ICE_MOUNTAINS.id; + } else if (k1 == BiomeBase.JUNGLE.id && this.world.generatorConfig.biomeJungleHills.getValue()) { + i2 = BiomeBase.JUNGLE_HILLS.id; + } else if (k1 == BiomeBase.OCEAN.id) { + i2 = BiomeBase.DEEP_OCEAN.id; + } else if (k1 == BiomeBase.EXTREME_HILLS.id && this.world.generatorConfig.biomeExtremeHillsPlus.getValue()) { + i2 = BiomeBase.EXTREME_HILLS_PLUS.id; + } else if (k1 == BiomeBase.SAVANNA.id && this.world.generatorConfig.biomeSavannaPlateau.getValue()) { + i2 = BiomeBase.SAVANNA_PLATEAU.id; + } else if (a(k1, BiomeBase.MESA_PLATEAU_F.id) && this.world.generatorConfig.biomeMesa.getValue()) { + i2 = BiomeBase.MESA.id; + } else if (k1 == BiomeBase.DEEP_OCEAN.id && this.a(3) == 0) { + j2 = this.a(2); + if (j2 == 0 && this.world.generatorConfig.biomePlains.getValue()) { + i2 = BiomeBase.PLAINS.id; + } else if (this.world.generatorConfig.biomeForest.getValue()) { + i2 = BiomeBase.FOREST.id; + } + } + + if (flag && i2 != k1) { + if (BiomeBase.getBiome(i2 + 128) != null) { + i2 += 128; + } else { + i2 = k1; + } + } + + if (i2 == k1) { + aint2[j1 + i1 * k] = k1; + } else { + j2 = aint[j1 + 1 + (i1 + 1 - 1) * (k + 2)]; + int k2 = aint[j1 + 1 + 1 + (i1 + 1) * (k + 2)]; + int l2 = aint[j1 + 1 - 1 + (i1 + 1) * (k + 2)]; + int i3 = aint[j1 + 1 + (i1 + 1 + 1) * (k + 2)]; + int j3 = 0; + + if (a(j2, k1)) { + ++j3; + } + + if (a(k2, k1)) { + ++j3; + } + + if (a(l2, k1)) { + ++j3; + } + + if (a(i3, k1)) { + ++j3; + } + + if (j3 >= 3) { + aint2[j1 + i1 * k] = i2; + } else { + aint2[j1 + i1 * k] = k1; + } + } + } + } + } + + return aint2; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/GenLayerRiver.java b/azurite-server/src/main/java/net/minecraft/server/GenLayerRiver.java new file mode 100644 index 0000000..d461683 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/GenLayerRiver.java @@ -0,0 +1,40 @@ +package net.minecraft.server; + +public class GenLayerRiver extends GenLayer { + + public GenLayerRiver(long i, GenLayer genlayer) { + super(i); + super.a = genlayer; + } + + public int[] a(int i, int j, int k, int l) { + int i1 = i - 1; + int j1 = j - 1; + int k1 = k + 2; + int l1 = l + 2; + int[] aint = this.a.a(i1, j1, k1, l1); + int[] aint1 = IntCache.a(k * l); + + for (int i2 = 0; i2 < l; ++i2) { + for (int j2 = 0; j2 < k; ++j2) { + int k2 = this.c(aint[j2 + 0 + (i2 + 1) * k1]); + int l2 = this.c(aint[j2 + 2 + (i2 + 1) * k1]); + int i3 = this.c(aint[j2 + 1 + (i2 + 0) * k1]); + int j3 = this.c(aint[j2 + 1 + (i2 + 2) * k1]); + int k3 = this.c(aint[j2 + 1 + (i2 + 1) * k1]); + + if (k3 == k2 && k3 == i3 && k3 == l2 && k3 == j3) { + aint1[j2 + i2 * k] = -1; + } else { + aint1[j2 + i2 * k] = BiomeBase.RIVER.id; + } + } + } + + return aint1; + } + + private int c(int i) { + return i >= 2 ? 2 + (i & 1) : i; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/GenLayerRiverMix.java b/azurite-server/src/main/java/net/minecraft/server/GenLayerRiverMix.java new file mode 100644 index 0000000..9f02d40 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/GenLayerRiverMix.java @@ -0,0 +1,45 @@ +package net.minecraft.server; + +public class GenLayerRiverMix extends GenLayer { + + private GenLayer c; + private GenLayer d; + + public GenLayerRiverMix(long i, GenLayer genlayer, GenLayer genlayer1) { + super(i); + this.c = genlayer; + this.d = genlayer1; + } + + public void a(long i) { + this.c.a(i); + this.d.a(i); + super.a(i); + } + + public int[] a(int i, int j, int k, int l) { + int[] aint = this.c.a(i, j, k, l); + int[] aint1 = this.d.a(i, j, k, l); + int[] aint2 = IntCache.a(k * l); + + for (int i1 = 0; i1 < k * l; ++i1) { + if (aint[i1] != BiomeBase.OCEAN.id && aint[i1] != BiomeBase.DEEP_OCEAN.id) { + if (aint1[i1] == BiomeBase.RIVER.id) { + if (aint[i1] == BiomeBase.ICE_PLAINS.id) { + aint2[i1] = BiomeBase.FROZEN_RIVER.id; + } else if (aint[i1] != BiomeBase.MUSHROOM_ISLAND.id && aint[i1] != BiomeBase.MUSHROOM_SHORE.id) { + aint2[i1] = aint1[i1] & 255; + } else { + aint2[i1] = BiomeBase.MUSHROOM_SHORE.id; + } + } else { + aint2[i1] = aint[i1]; + } + } else { + aint2[i1] = aint[i1]; + } + } + + return aint2; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/GenLayerSmooth.java b/azurite-server/src/main/java/net/minecraft/server/GenLayerSmooth.java new file mode 100644 index 0000000..6dd1163 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/GenLayerSmooth.java @@ -0,0 +1,49 @@ +package net.minecraft.server; + +public class GenLayerSmooth extends GenLayer { + + public GenLayerSmooth(long i, GenLayer genlayer) { + super(i); + super.a = genlayer; + } + + public int[] a(int i, int j, int k, int l) { + int i1 = i - 1; + int j1 = j - 1; + int k1 = k + 2; + int l1 = l + 2; + int[] aint = this.a.a(i1, j1, k1, l1); + int[] aint1 = IntCache.a(k * l); + + for (int i2 = 0; i2 < l; ++i2) { + for (int j2 = 0; j2 < k; ++j2) { + int k2 = aint[j2 + 0 + (i2 + 1) * k1]; + int l2 = aint[j2 + 2 + (i2 + 1) * k1]; + int i3 = aint[j2 + 1 + (i2 + 0) * k1]; + int j3 = aint[j2 + 1 + (i2 + 2) * k1]; + int k3 = aint[j2 + 1 + (i2 + 1) * k1]; + + if (k2 == l2 && i3 == j3) { + this.a((long) (j2 + i), (long) (i2 + j)); + if (this.a(2) == 0) { + k3 = k2; + } else { + k3 = i3; + } + } else { + if (k2 == l2) { + k3 = k2; + } + + if (i3 == j3) { + k3 = i3; + } + } + + aint1[j2 + i2 * k] = k3; + } + } + + return aint1; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/GenLayerSpecial.java b/azurite-server/src/main/java/net/minecraft/server/GenLayerSpecial.java new file mode 100644 index 0000000..33b4cfb --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/GenLayerSpecial.java @@ -0,0 +1,144 @@ +package net.minecraft.server; + +public class GenLayerSpecial extends GenLayer { + + private final GenLayerSpecial.EnumGenLayerSpecial c; + + public GenLayerSpecial(long i, GenLayer genlayer, GenLayerSpecial.EnumGenLayerSpecial genlayerspecial_enumgenlayerspecial) { + super(i); + this.a = genlayer; + this.c = genlayerspecial_enumgenlayerspecial; + } + + public int[] a(int i, int j, int k, int l) { + switch (GenLayerSpecial.SyntheticClass_1.a[this.c.ordinal()]) { + case 1: + default: + return this.c(i, j, k, l); + + case 2: + return this.d(i, j, k, l); + + case 3: + return this.e(i, j, k, l); + } + } + + private int[] c(int i, int j, int k, int l) { + int i1 = i - 1; + int j1 = j - 1; + int k1 = 1 + k + 1; + int l1 = 1 + l + 1; + int[] aint = this.a.a(i1, j1, k1, l1); + int[] aint1 = IntCache.a(k * l); + + for (int i2 = 0; i2 < l; ++i2) { + for (int j2 = 0; j2 < k; ++j2) { + this.a((long) (j2 + i), (long) (i2 + j)); + int k2 = aint[j2 + 1 + (i2 + 1) * k1]; + + if (k2 == 1) { + int l2 = aint[j2 + 1 + (i2 + 1 - 1) * k1]; + int i3 = aint[j2 + 1 + 1 + (i2 + 1) * k1]; + int j3 = aint[j2 + 1 - 1 + (i2 + 1) * k1]; + int k3 = aint[j2 + 1 + (i2 + 1 + 1) * k1]; + boolean flag = l2 == 3 || i3 == 3 || j3 == 3 || k3 == 3; + boolean flag1 = l2 == 4 || i3 == 4 || j3 == 4 || k3 == 4; + + if (flag || flag1) { + k2 = 2; + } + } + + aint1[j2 + i2 * k] = k2; + } + } + + return aint1; + } + + private int[] d(int i, int j, int k, int l) { + int i1 = i - 1; + int j1 = j - 1; + int k1 = 1 + k + 1; + int l1 = 1 + l + 1; + int[] aint = this.a.a(i1, j1, k1, l1); + int[] aint1 = IntCache.a(k * l); + + for (int i2 = 0; i2 < l; ++i2) { + for (int j2 = 0; j2 < k; ++j2) { + int k2 = aint[j2 + 1 + (i2 + 1) * k1]; + + if (k2 == 4) { + int l2 = aint[j2 + 1 + (i2 + 1 - 1) * k1]; + int i3 = aint[j2 + 1 + 1 + (i2 + 1) * k1]; + int j3 = aint[j2 + 1 - 1 + (i2 + 1) * k1]; + int k3 = aint[j2 + 1 + (i2 + 1 + 1) * k1]; + boolean flag = l2 == 2 || i3 == 2 || j3 == 2 || k3 == 2; + boolean flag1 = l2 == 1 || i3 == 1 || j3 == 1 || k3 == 1; + + if (flag1 || flag) { + k2 = 3; + } + } + + aint1[j2 + i2 * k] = k2; + } + } + + return aint1; + } + + private int[] e(int i, int j, int k, int l) { + int[] aint = this.a.a(i, j, k, l); + int[] aint1 = IntCache.a(k * l); + + for (int i1 = 0; i1 < l; ++i1) { + for (int j1 = 0; j1 < k; ++j1) { + this.a((long) (j1 + i), (long) (i1 + j)); + int k1 = aint[j1 + i1 * k]; + + if (k1 != 0 && this.a(13) == 0) { + k1 |= 1 + this.a(15) << 8 & 3840; + } + + aint1[j1 + i1 * k] = k1; + } + } + + return aint1; + } + + static class SyntheticClass_1 { + + static final int[] a = new int[GenLayerSpecial.EnumGenLayerSpecial.values().length]; + + static { + try { + GenLayerSpecial.SyntheticClass_1.a[GenLayerSpecial.EnumGenLayerSpecial.COOL_WARM.ordinal()] = 1; + } catch (NoSuchFieldError nosuchfielderror) { + ; + } + + try { + GenLayerSpecial.SyntheticClass_1.a[GenLayerSpecial.EnumGenLayerSpecial.HEAT_ICE.ordinal()] = 2; + } catch (NoSuchFieldError nosuchfielderror1) { + ; + } + + try { + GenLayerSpecial.SyntheticClass_1.a[GenLayerSpecial.EnumGenLayerSpecial.SPECIAL.ordinal()] = 3; + } catch (NoSuchFieldError nosuchfielderror2) { + ; + } + + } + } + + public static enum EnumGenLayerSpecial { + + COOL_WARM, HEAT_ICE, SPECIAL; + + private EnumGenLayerSpecial() {} + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/GenLayerTopSoil.java b/azurite-server/src/main/java/net/minecraft/server/GenLayerTopSoil.java new file mode 100644 index 0000000..9e26498 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/GenLayerTopSoil.java @@ -0,0 +1,44 @@ +package net.minecraft.server; + +public class GenLayerTopSoil extends GenLayer { + + public GenLayerTopSoil(long i, GenLayer genlayer) { + super(i); + this.a = genlayer; + } + + public int[] a(int i, int j, int k, int l) { + int i1 = i - 1; + int j1 = j - 1; + int k1 = k + 2; + int l1 = l + 2; + int[] aint = this.a.a(i1, j1, k1, l1); + int[] aint1 = IntCache.a(k * l); + + for (int i2 = 0; i2 < l; ++i2) { + for (int j2 = 0; j2 < k; ++j2) { + int k2 = aint[j2 + 1 + (i2 + 1) * k1]; + + this.a((long) (j2 + i), (long) (i2 + j)); + if (k2 == 0) { + aint1[j2 + i2 * k] = 0; + } else { + int l2 = this.a(6); + byte b0; + + if (l2 == 0) { + b0 = 4; + } else if (l2 <= 1) { + b0 = 3; + } else { + b0 = 1; + } + + aint1[j2 + i2 * k] = b0; + } + } + } + + return aint1; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/GenLayerZoom.java b/azurite-server/src/main/java/net/minecraft/server/GenLayerZoom.java new file mode 100644 index 0000000..9bb3731 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/GenLayerZoom.java @@ -0,0 +1,59 @@ +package net.minecraft.server; + +public class GenLayerZoom extends GenLayer { + + public GenLayerZoom(long i, GenLayer genlayer) { + super(i); + super.a = genlayer; + } + + public int[] a(int i, int j, int k, int l) { + int i1 = i >> 1; + int j1 = j >> 1; + int k1 = (k >> 1) + 2; + int l1 = (l >> 1) + 2; + int[] aint = this.a.a(i1, j1, k1, l1); + int i2 = k1 - 1 << 1; + int j2 = l1 - 1 << 1; + int[] aint1 = IntCache.a(i2 * j2); + + int k2; + + for (int l2 = 0; l2 < l1 - 1; ++l2) { + k2 = (l2 << 1) * i2; + int i3 = 0; + int j3 = aint[i3 + 0 + (l2 + 0) * k1]; + + for (int k3 = aint[i3 + 0 + (l2 + 1) * k1]; i3 < k1 - 1; ++i3) { + this.a((long) (i3 + i1 << 1), (long) (l2 + j1 << 1)); + int l3 = aint[i3 + 1 + (l2 + 0) * k1]; + int i4 = aint[i3 + 1 + (l2 + 1) * k1]; + + aint1[k2] = j3; + aint1[k2++ + i2] = this.a(new int[] { j3, k3}); + aint1[k2] = this.a(new int[] { j3, l3}); + aint1[k2++ + i2] = this.b(j3, l3, k3, i4); + j3 = l3; + k3 = i4; + } + } + + int[] aint2 = IntCache.a(k * l); + + for (k2 = 0; k2 < l; ++k2) { + System.arraycopy(aint1, (k2 + (j & 1)) * i2 + (i & 1), aint2, k2 * k, k); + } + + return aint2; + } + + public static GenLayer b(long i, GenLayer genlayer, int j) { + Object object = genlayer; + + for (int k = 0; k < j; ++k) { + object = new GenLayerZoom(i + (long) k, (GenLayer) object); + } + + return (GenLayer) object; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/GenLayerZoomFuzzy.java b/azurite-server/src/main/java/net/minecraft/server/GenLayerZoomFuzzy.java new file mode 100644 index 0000000..b139208 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/GenLayerZoomFuzzy.java @@ -0,0 +1,12 @@ +package net.minecraft.server; + +public class GenLayerZoomFuzzy extends GenLayerZoom { + + public GenLayerZoomFuzzy(long i, GenLayer genlayer) { + super(i, genlayer); + } + + protected int b(int i, int j, int k, int l) { + return this.a(new int[] { i, j, k, l}); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/GenLayerZoomVoronoi.java b/azurite-server/src/main/java/net/minecraft/server/GenLayerZoomVoronoi.java new file mode 100644 index 0000000..4b71fcd --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/GenLayerZoomVoronoi.java @@ -0,0 +1,83 @@ +package net.minecraft.server; + +public class GenLayerZoomVoronoi extends GenLayer { + + public GenLayerZoomVoronoi(long i, GenLayer genlayer) { + super(i); + super.a = genlayer; + } + + public int[] a(int i, int j, int k, int l) { + i -= 2; + j -= 2; + int i1 = i >> 2; + int j1 = j >> 2; + int k1 = (k >> 2) + 2; + int l1 = (l >> 2) + 2; + int[] aint = this.a.a(i1, j1, k1, l1); + int i2 = k1 - 1 << 2; + int j2 = l1 - 1 << 2; + int[] aint1 = IntCache.a(i2 * j2); + + int k2; + + for (int l2 = 0; l2 < l1 - 1; ++l2) { + k2 = 0; + int i3 = aint[k2 + 0 + (l2 + 0) * k1]; + + for (int j3 = aint[k2 + 0 + (l2 + 1) * k1]; k2 < k1 - 1; ++k2) { + double d0 = 3.6D; + + this.a((long) (k2 + i1 << 2), (long) (l2 + j1 << 2)); + double d1 = ((double) this.a(1024) / 1024.0D - 0.5D) * 3.6D; + double d2 = ((double) this.a(1024) / 1024.0D - 0.5D) * 3.6D; + + this.a((long) (k2 + i1 + 1 << 2), (long) (l2 + j1 << 2)); + double d3 = ((double) this.a(1024) / 1024.0D - 0.5D) * 3.6D + 4.0D; + double d4 = ((double) this.a(1024) / 1024.0D - 0.5D) * 3.6D; + + this.a((long) (k2 + i1 << 2), (long) (l2 + j1 + 1 << 2)); + double d5 = ((double) this.a(1024) / 1024.0D - 0.5D) * 3.6D; + double d6 = ((double) this.a(1024) / 1024.0D - 0.5D) * 3.6D + 4.0D; + + this.a((long) (k2 + i1 + 1 << 2), (long) (l2 + j1 + 1 << 2)); + double d7 = ((double) this.a(1024) / 1024.0D - 0.5D) * 3.6D + 4.0D; + double d8 = ((double) this.a(1024) / 1024.0D - 0.5D) * 3.6D + 4.0D; + int k3 = aint[k2 + 1 + (l2 + 0) * k1] & 255; + int l3 = aint[k2 + 1 + (l2 + 1) * k1] & 255; + + for (int i4 = 0; i4 < 4; ++i4) { + int j4 = ((l2 << 2) + i4) * i2 + (k2 << 2); + + for (int k4 = 0; k4 < 4; ++k4) { + double d9 = ((double) i4 - d2) * ((double) i4 - d2) + ((double) k4 - d1) * ((double) k4 - d1); + double d10 = ((double) i4 - d4) * ((double) i4 - d4) + ((double) k4 - d3) * ((double) k4 - d3); + double d11 = ((double) i4 - d6) * ((double) i4 - d6) + ((double) k4 - d5) * ((double) k4 - d5); + double d12 = ((double) i4 - d8) * ((double) i4 - d8) + ((double) k4 - d7) * ((double) k4 - d7); + + if (d9 < d10 && d9 < d11 && d9 < d12) { + aint1[j4++] = i3; + } else if (d10 < d9 && d10 < d11 && d10 < d12) { + aint1[j4++] = k3; + } else if (d11 < d9 && d11 < d10 && d11 < d12) { + aint1[j4++] = j3; + } else { + aint1[j4++] = l3; + } + } + } + + i3 = k3; + j3 = l3; + } + } + + int[] aint2 = IntCache.a(k * l); + + for (k2 = 0; k2 < l; ++k2) { + System.arraycopy(aint1, (k2 + (j & 3)) * i2 + (i & 3), aint2, k2 * k, k); + } + + return aint2; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/GenericAttributes.java b/azurite-server/src/main/java/net/minecraft/server/GenericAttributes.java new file mode 100644 index 0000000..fc40bf3 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/GenericAttributes.java @@ -0,0 +1,110 @@ +package net.minecraft.server; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.util.Collection; +import java.util.UUID; + +public class GenericAttributes { + + private static final Logger f = LogManager.getLogger(); + // Spigot start + public static final IAttribute maxHealth = (new AttributeRanged(null, "generic.maxHealth", 20.0D, 0.1D, org.spigotmc.SpigotConfig.maxHealth)).a("Max Health").a(true); + public static final IAttribute FOLLOW_RANGE = (new AttributeRanged(null, "generic.followRange", 32.0D, 0.0D, 2048.0D)).a("Follow Range"); + public static final IAttribute c = (new AttributeRanged(null, "generic.knockbackResistance", 0.0D, 0.0D, 1.0D)).a("Knockback Resistance"); + public static final IAttribute MOVEMENT_SPEED = (new AttributeRanged(null, "generic.movementSpeed", 0.699999988079071D, 0.0D, org.spigotmc.SpigotConfig.movementSpeed)).a("Movement Speed").a(true); + public static final IAttribute ATTACK_DAMAGE = new AttributeRanged(null, "generic.attackDamage", 2.0D, 0.0D, org.spigotmc.SpigotConfig.attackDamage); + // Spigot end + + public static NBTTagList a(AttributeMapBase attributemapbase) { + NBTTagList nbttaglist = new NBTTagList(); + + for (AttributeInstance attributeinstance : attributemapbase.a()) { + nbttaglist.add(a(attributeinstance)); + } + + return nbttaglist; + } + + private static NBTTagCompound a(AttributeInstance attributeinstance) { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + IAttribute iattribute = attributeinstance.getAttribute(); + + nbttagcompound.setString("Name", iattribute.getName()); + nbttagcompound.setDouble("Base", attributeinstance.b()); + Collection collection = attributeinstance.c(); + + if (collection != null && !collection.isEmpty()) { + NBTTagList nbttaglist = new NBTTagList(); + + for (AttributeModifier attributemodifier : collection) { + if (attributemodifier.e()) { + nbttaglist.add(a(attributemodifier)); + } + } + + nbttagcompound.set("Modifiers", nbttaglist); + } + + return nbttagcompound; + } + + private static NBTTagCompound a(AttributeModifier attributemodifier) { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + + nbttagcompound.setString("Name", attributemodifier.b()); + nbttagcompound.setDouble("Amount", attributemodifier.d()); + nbttagcompound.setInt("Operation", attributemodifier.c()); + nbttagcompound.setLong("UUIDMost", attributemodifier.a().getMostSignificantBits()); + nbttagcompound.setLong("UUIDLeast", attributemodifier.a().getLeastSignificantBits()); + return nbttagcompound; + } + + public static void a(AttributeMapBase attributemapbase, NBTTagList nbttaglist) { + for (int i = 0; i < nbttaglist.size(); ++i) { + NBTTagCompound nbttagcompound = nbttaglist.get(i); + AttributeInstance attributeinstance = attributemapbase.a(nbttagcompound.getString("Name")); + + if (attributeinstance != null) { + a(attributeinstance, nbttagcompound); + } else { + GenericAttributes.f.warn("Ignoring unknown attribute '" + nbttagcompound.getString("Name") + "'"); + } + } + + } + + private static void a(AttributeInstance attributeinstance, NBTTagCompound nbttagcompound) { + attributeinstance.setValue(nbttagcompound.getDouble("Base")); + if (nbttagcompound.hasKeyOfType("Modifiers", 9)) { + NBTTagList nbttaglist = nbttagcompound.getList("Modifiers", 10); + + for (int i = 0; i < nbttaglist.size(); ++i) { + AttributeModifier attributemodifier = a(nbttaglist.get(i)); + + if (attributemodifier != null) { + AttributeModifier attributemodifier1 = attributeinstance.a(attributemodifier.a()); + + if (attributemodifier1 != null) { + attributeinstance.c(attributemodifier1); + } + + attributeinstance.b(attributemodifier); + } + } + } + + } + + public static AttributeModifier a(NBTTagCompound nbttagcompound) { + UUID uuid = new UUID(nbttagcompound.getLong("UUIDMost"), nbttagcompound.getLong("UUIDLeast")); + + try { + return new AttributeModifier(uuid, nbttagcompound.getString("Name"), nbttagcompound.getDouble("Amount"), nbttagcompound.getInt("Operation")); + } catch (Exception exception) { + GenericAttributes.f.warn("Unable to create attribute: " + exception.getMessage()); + return null; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/GroupDataEntity.java b/azurite-server/src/main/java/net/minecraft/server/GroupDataEntity.java new file mode 100644 index 0000000..9bfebc3 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/GroupDataEntity.java @@ -0,0 +1,4 @@ +package net.minecraft.server; + +public interface GroupDataEntity { +} diff --git a/azurite-server/src/main/java/net/minecraft/server/GuiStatsComponent.java b/azurite-server/src/main/java/net/minecraft/server/GuiStatsComponent.java new file mode 100644 index 0000000..62937c8 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/GuiStatsComponent.java @@ -0,0 +1,76 @@ +package net.minecraft.server; + +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Graphics; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.text.DecimalFormat; +import javax.swing.JComponent; +import javax.swing.Timer; + +public class GuiStatsComponent extends JComponent { + + private static final DecimalFormat a = new DecimalFormat("########0.000"); + private int[] b = new int[256]; + private int c; + private String[] d = new String[11]; + private final MinecraftServer e; + + public GuiStatsComponent(MinecraftServer minecraftserver) { + this.e = minecraftserver; + this.setPreferredSize(new Dimension(456, 246)); + this.setMinimumSize(new Dimension(456, 246)); + this.setMaximumSize(new Dimension(456, 246)); + (new Timer(500, new ActionListener() { + public void actionPerformed(ActionEvent actionevent) { + GuiStatsComponent.this.a(); + } + })).start(); + this.setBackground(Color.BLACK); + } + + private void a() { + long i = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); + + System.gc(); + this.d[0] = "Memory use: " + i / 1024L / 1024L + " mb (" + Runtime.getRuntime().freeMemory() * 100L / Runtime.getRuntime().maxMemory() + "% free)"; + this.d[1] = "Avg tick: " + " ms"; + this.repaint(); + } + + private double a(long[] along) { + long i = 0L; + + for (int j = 0; j < along.length; ++j) { + i += along[j]; + } + + return (double) i / (double) along.length; + } + + public void paint(Graphics graphics) { + graphics.setColor(new Color(16777215)); + graphics.fillRect(0, 0, 456, 246); + + int i; + + for (i = 0; i < 256; ++i) { + int j = this.b[i + this.c & 255]; + + graphics.setColor(new Color(j + 28 << 16)); + graphics.fillRect(i, 100 - j, 1, j); + } + + graphics.setColor(Color.BLACK); + + for (i = 0; i < this.d.length; ++i) { + String s = this.d[i]; + + if (s != null) { + graphics.drawString(s, 32, 116 + i * 16); + } + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/HandshakeListener.java b/azurite-server/src/main/java/net/minecraft/server/HandshakeListener.java new file mode 100644 index 0000000..fdaca20 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/HandshakeListener.java @@ -0,0 +1,126 @@ +package net.minecraft.server; + +// CraftBukkit start + +import com.mojang.util.UUIDTypeAdapter; +import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap; + +import java.net.InetAddress; +import java.net.InetSocketAddress; + +public class HandshakeListener implements PacketHandshakingInListener { + + private static final com.google.gson.Gson gson = new com.google.gson.Gson(); // Spigot + // CraftBukkit start - add fields + private static final Object2LongOpenHashMap throttleTracker = new Object2LongOpenHashMap<>(); // Vortex + private static int throttleCounter = 0; + // CraftBukkit end + + private final MinecraftServer a; + private final NetworkManager b; + + public HandshakeListener(MinecraftServer minecraftserver, NetworkManager networkmanager) { + this.a = minecraftserver; + this.b = networkmanager; + } + + public void a(PacketHandshakingInSetProtocol packethandshakinginsetprotocol) { + switch (SyntheticClass_1.a[packethandshakinginsetprotocol.a().ordinal()]) { + case 1: + this.b.a(EnumProtocol.LOGIN); + + ChatComponentText chatcomponenttext; + + // CraftBukkit start - Connection throttle + try { + long currentTime = System.currentTimeMillis(); + long connectionThrottle = MinecraftServer.getServer().server.getConnectionThrottle(); + InetAddress address = ((java.net.InetSocketAddress) this.b.getSocketAddress()).getAddress(); + + if (throttleTracker.containsKey(address) && !"127.0.0.1".equals(address.getHostAddress()) && currentTime - throttleTracker.getLong(address) < connectionThrottle) { + throttleTracker.put(address, currentTime); + chatcomponenttext = new ChatComponentText("Connection throttled! Please wait before reconnecting."); + this.b.handle(new PacketLoginOutDisconnect(chatcomponenttext)); + this.b.close(chatcomponenttext); + return; + } + + throttleTracker.put(address, currentTime); + throttleCounter++; + if (throttleCounter > 200) { + throttleCounter = 0; + + // Cleanup stale entries + throttleTracker.entrySet().removeIf(inetAddressLongEntry -> inetAddressLongEntry.getValue() > connectionThrottle); + } + + } catch (Throwable t) { + org.apache.logging.log4j.LogManager.getLogger().debug("Failed to check connection throttle", t); + } + // CraftBukkit end + int ver = packethandshakinginsetprotocol.b(); + if (ver > 47) { + chatcomponenttext = new ChatComponentText( java.text.MessageFormat.format( org.spigotmc.SpigotConfig.outdatedServerMessage, "1.8.8" ) ); // Spigot + this.b.handle(new PacketLoginOutDisconnect(chatcomponenttext)); + this.b.close(chatcomponenttext); + } else if (ver < 47) { + chatcomponenttext = new ChatComponentText( java.text.MessageFormat.format( org.spigotmc.SpigotConfig.outdatedClientMessage, "1.8.8" ) ); // Spigot + this.b.handle(new PacketLoginOutDisconnect(chatcomponenttext)); + this.b.close(chatcomponenttext); + } else { + this.b.a(new LoginListener(this.a, this.b)); + // Spigot Start + if (org.spigotmc.SpigotConfig.bungee) { + String[] split = packethandshakinginsetprotocol.hostname.split("\00"); + if ( split.length == 3 || split.length == 4 ) { + packethandshakinginsetprotocol.hostname = split[0]; + b.l = new InetSocketAddress(split[1], ((java.net.InetSocketAddress) b.getSocketAddress()).getPort()); + b.spoofedUUID = UUIDTypeAdapter.fromString( split[2] ); + } else + { + chatcomponenttext = new ChatComponentText("If you wish to use IP forwarding, please enable it in your BungeeCord config as well!"); + this.b.handle(new PacketLoginOutDisconnect(chatcomponenttext)); + this.b.close(chatcomponenttext); + return; + } + if ( split.length == 4 ) + { + b.spoofedProfile = gson.fromJson(split[3], com.mojang.authlib.properties.Property[].class); + } + } + // Spigot End + ((LoginListener) b.getPacketListener()).hostname = packethandshakinginsetprotocol.hostname + ":" + packethandshakinginsetprotocol.port; // CraftBukkit - set hostname + } + break; + + case 2: + this.b.a(EnumProtocol.STATUS); + this.b.a(new PacketStatusListener(this.a, this.b)); + break; + + default: + throw new UnsupportedOperationException("Invalid intention " + packethandshakinginsetprotocol.a()); + } + + } + + public void a(IChatBaseComponent ichatbasecomponent) {} + + static class SyntheticClass_1 { + + static final int[] a = new int[EnumProtocol.values().length]; + + static { + try { + SyntheticClass_1.a[EnumProtocol.LOGIN.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.a[EnumProtocol.STATUS.ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + } + + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/HttpUtilities.java b/azurite-server/src/main/java/net/minecraft/server/HttpUtilities.java new file mode 100644 index 0000000..4132d8b --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/HttpUtilities.java @@ -0,0 +1,105 @@ +package net.minecraft.server; + +import com.google.common.util.concurrent.ListeningExecutorService; +import com.google.common.util.concurrent.MoreExecutors; +import com.google.common.util.concurrent.ThreadFactoryBuilder; +import java.io.BufferedReader; +import java.io.DataOutputStream; +import java.io.InputStreamReader; +import java.io.UnsupportedEncodingException; +import java.net.HttpURLConnection; +import java.net.Proxy; +import java.net.URL; +import java.net.URLEncoder; +import java.util.Iterator; +import java.util.Map; +import java.util.Map.Entry; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicInteger; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +public class HttpUtilities { + + public static final ListeningExecutorService a = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool((new ThreadFactoryBuilder()).setDaemon(true).setNameFormat("Downloader %d").build())); + private static final AtomicInteger b = new AtomicInteger(0); + private static final Logger c = LogManager.getLogger(); + + public static String a(Map map) { + StringBuilder stringbuilder = new StringBuilder(); + Iterator iterator = map.entrySet().iterator(); + + while (iterator.hasNext()) { + Entry entry = (Entry) iterator.next(); + + if (stringbuilder.length() > 0) { + stringbuilder.append('&'); + } + + try { + stringbuilder.append(URLEncoder.encode((String) entry.getKey(), "UTF-8")); + } catch (UnsupportedEncodingException unsupportedencodingexception) { + unsupportedencodingexception.printStackTrace(); + } + + if (entry.getValue() != null) { + stringbuilder.append('='); + + try { + stringbuilder.append(URLEncoder.encode(entry.getValue().toString(), "UTF-8")); + } catch (UnsupportedEncodingException unsupportedencodingexception1) { + unsupportedencodingexception1.printStackTrace(); + } + } + } + + return stringbuilder.toString(); + } + + public static String a(URL url, Map map, boolean flag) { + return a(url, a(map), flag); + } + + private static String a(URL url, String s, boolean flag) { + try { + Proxy proxy = MinecraftServer.getServer() == null ? null : MinecraftServer.getServer().ay(); + + if (proxy == null) { + proxy = Proxy.NO_PROXY; + } + + HttpURLConnection httpurlconnection = (HttpURLConnection) url.openConnection(proxy); + + httpurlconnection.setRequestMethod("POST"); + httpurlconnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); + httpurlconnection.setRequestProperty("Content-Length", "" + s.getBytes().length); + httpurlconnection.setRequestProperty("Content-Language", "en-US"); + httpurlconnection.setUseCaches(false); + httpurlconnection.setDoInput(true); + httpurlconnection.setDoOutput(true); + DataOutputStream dataoutputstream = new DataOutputStream(httpurlconnection.getOutputStream()); + + dataoutputstream.writeBytes(s); + dataoutputstream.flush(); + dataoutputstream.close(); + BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(httpurlconnection.getInputStream())); + StringBuffer stringbuffer = new StringBuffer(); + + String s1; + + while ((s1 = bufferedreader.readLine()) != null) { + stringbuffer.append(s1); + stringbuffer.append('\r'); + } + + bufferedreader.close(); + return stringbuffer.toString(); + } catch (Exception exception) { + if (!flag) { + HttpUtilities.c.error("Could not post to " + url, exception); + } + + return ""; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/IAnimal.java b/azurite-server/src/main/java/net/minecraft/server/IAnimal.java new file mode 100644 index 0000000..78d3914 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/IAnimal.java @@ -0,0 +1,3 @@ +package net.minecraft.server; + +public interface IAnimal {} diff --git a/azurite-server/src/main/java/net/minecraft/server/IAsyncChunkSaver.java b/azurite-server/src/main/java/net/minecraft/server/IAsyncChunkSaver.java new file mode 100644 index 0000000..dde4c47 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/IAsyncChunkSaver.java @@ -0,0 +1,6 @@ +package net.minecraft.server; + +public interface IAsyncChunkSaver { + + boolean c(); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/IAsyncTaskHandler.java b/azurite-server/src/main/java/net/minecraft/server/IAsyncTaskHandler.java new file mode 100644 index 0000000..5cba626 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/IAsyncTaskHandler.java @@ -0,0 +1,13 @@ +package net.minecraft.server; + +import com.google.common.util.concurrent.ListenableFuture; + +public interface IAsyncTaskHandler { + ListenableFuture postToMainThread(Runnable paramRunnable); + + default void postToMainThreadRunnable(Runnable runnable) { + postToMainThread(runnable); + } + + boolean isMainThread(); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/IAttribute.java b/azurite-server/src/main/java/net/minecraft/server/IAttribute.java new file mode 100644 index 0000000..e76405d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/IAttribute.java @@ -0,0 +1,14 @@ +package net.minecraft.server; + +public interface IAttribute { + + String getName(); + + double a(double d0); + + double b(); + + boolean c(); + + IAttribute d(); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/IBlockAccess.java b/azurite-server/src/main/java/net/minecraft/server/IBlockAccess.java new file mode 100644 index 0000000..f24c8a3 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/IBlockAccess.java @@ -0,0 +1,16 @@ +package net.minecraft.server; + +public interface IBlockAccess { + + TileEntity getTileEntity(BlockPosition blockposition); + + IBlockData getType(BlockPosition blockposition); + + default IBlockData getType(int x, int y, int z) { + return getType(new BlockPosition(x, y, z)); + } + + boolean isEmpty(BlockPosition blockposition); + + int getBlockPower(BlockPosition blockposition, EnumDirection enumdirection); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/IBlockData.java b/azurite-server/src/main/java/net/minecraft/server/IBlockData.java new file mode 100644 index 0000000..3c3ab0c --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/IBlockData.java @@ -0,0 +1,19 @@ +package net.minecraft.server; + +import com.google.common.collect.ImmutableMap; +import java.util.Collection; + +public interface IBlockData { + + Collection a(); + + > T get(IBlockState iblockstate); + + , V extends T> IBlockData set(IBlockState iblockstate, V v0); + + > IBlockData a(IBlockState iblockstate); + + ImmutableMap b(); + + Block getBlock(); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/IBlockFragilePlantElement.java b/azurite-server/src/main/java/net/minecraft/server/IBlockFragilePlantElement.java new file mode 100644 index 0000000..2df9744 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/IBlockFragilePlantElement.java @@ -0,0 +1,12 @@ +package net.minecraft.server; + +import java.util.Random; + +public interface IBlockFragilePlantElement { + + boolean a(World world, BlockPosition blockposition, IBlockData iblockdata, boolean flag); + + boolean a(World world, Random random, BlockPosition blockposition, IBlockData iblockdata); + + void b(World world, Random random, BlockPosition blockposition, IBlockData iblockdata); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/IBlockState.java b/azurite-server/src/main/java/net/minecraft/server/IBlockState.java new file mode 100644 index 0000000..620eee3 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/IBlockState.java @@ -0,0 +1,34 @@ +package net.minecraft.server; + +import net.techcable.tacospigot.Indexer; + +import java.util.Collection; + +// TacoSpigot start +// TacoSpigot end + +public interface IBlockState> { + + String a(); + + Collection c(); + + Class b(); + + String a(T t0); + + // TacoSpigot start + @SuppressWarnings("Convert2Lambda") + // We have to use anon for performance reasons :/ + Indexer INDEXER = IBlockState::getId; + + default void tryInitId() { + } + + int getId(); + + int getValueId(T value); + + T getByValueId(int id); + // TacoSpigot end +} diff --git a/azurite-server/src/main/java/net/minecraft/server/IChatBaseComponent.java b/azurite-server/src/main/java/net/minecraft/server/IChatBaseComponent.java new file mode 100644 index 0000000..52324ad --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/IChatBaseComponent.java @@ -0,0 +1,285 @@ +package net.minecraft.server; + +import java.lang.reflect.Type; +import java.util.List; +import java.util.Map.Entry; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; + +public interface IChatBaseComponent extends Iterable { + + IChatBaseComponent setChatModifier(ChatModifier chatmodifier); + + ChatModifier getChatModifier(); + + IChatBaseComponent a(String s); + + IChatBaseComponent addSibling(IChatBaseComponent ichatbasecomponent); + + String getText(); + + String c(); + + List a(); + + IChatBaseComponent f(); + + class ChatSerializer implements JsonDeserializer, JsonSerializer { + + private static final int CHATCOMPONENT_LIMIT = 128; + private static final Gson a; + + public ChatSerializer() { + } + + public IChatBaseComponent a(int extraCount, String lastElement, JsonElement jsonelement, Type type, JsonDeserializationContext jsondeserializationcontext) throws JsonParseException { + if (jsonelement.isJsonPrimitive()) { + return new ChatComponentText(jsonelement.getAsString()); + } else if (!jsonelement.isJsonObject()) { + if (jsonelement.isJsonArray()) { + JsonArray jsonarray = jsonelement.getAsJsonArray(); + + // FlamePaper start - Limit ChatComponents + if (jsonarray.size() > CHATCOMPONENT_LIMIT) { + throw new JsonParseException("Too many ChatComponent array elements"); + } + // FlamePaper end - Limit Chatcomponents + + IChatBaseComponent ichatbasecomponent = null; + + for (JsonElement jsonelement1 : jsonarray) { + // FlamePaper start - Limit ChatComponents + if (jsonelement1.isJsonArray()) { + throw new JsonParseException("Stacked ChatComponent array"); + } + // FlamePaper end - Limit Chatcomponents + + IChatBaseComponent ichatbasecomponent1 = this.a(jsonelement1, jsonelement1.getClass(), jsondeserializationcontext); + + if (ichatbasecomponent == null) { + ichatbasecomponent = ichatbasecomponent1; + } else { + ichatbasecomponent.addSibling(ichatbasecomponent1); + } + } + + return ichatbasecomponent; + } else { + throw new JsonParseException("Don't know how to turn " + jsonelement + " into a Component"); + } + } else { + JsonObject jsonobject = jsonelement.getAsJsonObject(); + IChatBaseComponent object; + + if (jsonobject.has("text")) { + object = new ChatComponentText(jsonobject.get("text").getAsString()); + } else if (jsonobject.has("translate")) { + String s = jsonobject.get("translate").getAsString(); + + if (jsonobject.has("with")) { + JsonArray jsonarray1 = jsonobject.getAsJsonArray("with"); + + // FlamePaper start - Limit ChatComponents + if (jsonarray1.size() > CHATCOMPONENT_LIMIT) { + throw new JsonParseException("Too many ChatComponent array elements in with"); + } + // FlamePaper end - Limit Chatcomponents + + // FlamePaper start - Limit ChatComponents + if (lastElement != null && lastElement.equals("with")) { + throw new JsonParseException("Stacked with ChatComponent elements"); + } + // FlamePaper end - Limit Chatcomponents + + Object[] aobject = new Object[jsonarray1.size()]; + + for (int i = 0; i < aobject.length; ++i) { + // FlamePaper start - Limit ChatComponents + if (jsonarray1.get(i).isJsonArray()) { + throw new JsonParseException("Stacked ChatComponent array in with element"); + } + // FlamePaper end - Limit Chatcomponents + + aobject[i] = this.a(extraCount, "with", jsonarray1.get(i), type, jsondeserializationcontext); + if (aobject[i] instanceof ChatComponentText) { + ChatComponentText chatcomponenttext = (ChatComponentText) aobject[i]; + + if (chatcomponenttext.getChatModifier().g() && chatcomponenttext.a().isEmpty()) { + aobject[i] = chatcomponenttext.g(); + } + } + } + + object = new ChatMessage(s, aobject); + } else { + object = new ChatMessage(s); + } + } else if (jsonobject.has("score")) { + JsonObject jsonobject1 = jsonobject.getAsJsonObject("score"); + + if (!jsonobject1.has("name") || !jsonobject1.has("objective")) { + throw new JsonParseException("A score component needs a least a name and an objective"); + } + + object = new ChatComponentScore(ChatDeserializer.h(jsonobject1, "name"), ChatDeserializer.h(jsonobject1, "objective")); + if (jsonobject1.has("value")) { + ((ChatComponentScore) object).b(ChatDeserializer.h(jsonobject1, "value")); + } + } else { + if (!jsonobject.has("selector")) { + throw new JsonParseException("Don't know how to turn " + jsonelement + " into a Component"); + } + + object = new ChatComponentSelector(ChatDeserializer.h(jsonobject, "selector")); + } + + if (jsonobject.has("extra")) { + JsonArray jsonarray2 = jsonobject.getAsJsonArray("extra"); + + // FlamePaper start - Limit ChatComponents + if (jsonarray2.size() > CHATCOMPONENT_LIMIT) { + throw new JsonParseException("Too many ChatComponent array elements in extra"); + } + // FlamePaper end - Limit Chatcomponents + + // FlamePaper start - Limit ChatComponents + if (extraCount > CHATCOMPONENT_LIMIT) { + throw new JsonParseException("Too many stacked extra ChatComponent elements"); + } + // FlamePaper end - Limit Chatcomponents + + if (jsonarray2.size() <= 0) { + throw new JsonParseException("Unexpected empty array of components"); + } + + for (int j = 0; j < jsonarray2.size(); ++j) { + // FlamePaper start - Limit ChatComponents + if (jsonarray2.get(j).isJsonArray()) { + throw new JsonParseException("Stacked ChatComponent array in extra element"); + } + // FlamePaper end - Limit Chatcomponents + + object.addSibling(this.a(++extraCount, "extra", jsonarray2.get(j), type, jsondeserializationcontext)); + } + } + + object.setChatModifier(jsondeserializationcontext.deserialize(jsonelement, ChatModifier.class)); + return object; + } + } + + public IChatBaseComponent a(JsonElement jsonelement, Type type, JsonDeserializationContext jsondeserializationcontext) throws JsonParseException { + return a(0, null, jsonelement, type, jsondeserializationcontext); + } + + private void a(ChatModifier chatmodifier, JsonObject jsonobject, JsonSerializationContext jsonserializationcontext) { + JsonElement jsonelement = jsonserializationcontext.serialize(chatmodifier); + + if (jsonelement.isJsonObject()) { + JsonObject jsonobject1 = (JsonObject) jsonelement; + + for (Entry entry : jsonobject1.entrySet()) { + jsonobject.add(entry.getKey(), entry.getValue()); + } + } + + } + + public JsonElement a(IChatBaseComponent ichatbasecomponent, Type type, JsonSerializationContext jsonserializationcontext) { + if (ichatbasecomponent instanceof ChatComponentText && ichatbasecomponent.getChatModifier().g() && ichatbasecomponent.a().isEmpty()) { + return new JsonPrimitive(((ChatComponentText) ichatbasecomponent).g()); + } else { + JsonObject jsonobject = new JsonObject(); + + if (!ichatbasecomponent.getChatModifier().g()) { + this.a(ichatbasecomponent.getChatModifier(), jsonobject, jsonserializationcontext); + } + + if (!ichatbasecomponent.a().isEmpty()) { + JsonArray jsonarray = new JsonArray(); + + for (IChatBaseComponent ichatbasecomponent1 : ichatbasecomponent.a()) { + jsonarray.add(this.a(ichatbasecomponent1, ichatbasecomponent1.getClass(), jsonserializationcontext)); + } + + jsonobject.add("extra", jsonarray); + } + + if (ichatbasecomponent instanceof ChatComponentText) { + jsonobject.addProperty("text", ((ChatComponentText) ichatbasecomponent).g()); + } else if (ichatbasecomponent instanceof ChatMessage) { + ChatMessage chatmessage = (ChatMessage) ichatbasecomponent; + + jsonobject.addProperty("translate", chatmessage.i()); + if (chatmessage.j() != null && chatmessage.j().length > 0) { + JsonArray jsonarray1 = new JsonArray(); + + for (Object object : chatmessage.j()) { + if (object instanceof IChatBaseComponent) { + jsonarray1.add(this.a((IChatBaseComponent) object, object.getClass(), jsonserializationcontext)); + } else { + jsonarray1.add(new JsonPrimitive(String.valueOf(object))); + } + } + + jsonobject.add("with", jsonarray1); + } + } else if (ichatbasecomponent instanceof ChatComponentScore) { + ChatComponentScore chatcomponentscore = (ChatComponentScore) ichatbasecomponent; + JsonObject jsonobject1 = new JsonObject(); + + jsonobject1.addProperty("name", chatcomponentscore.g()); + jsonobject1.addProperty("objective", chatcomponentscore.h()); + jsonobject1.addProperty("value", chatcomponentscore.getText()); + jsonobject.add("score", jsonobject1); + } else { + if (!(ichatbasecomponent instanceof ChatComponentSelector)) { + throw new IllegalArgumentException("Don't know how to serialize " + ichatbasecomponent + " as a Component"); + } + + ChatComponentSelector chatcomponentselector = (ChatComponentSelector) ichatbasecomponent; + + jsonobject.addProperty("selector", chatcomponentselector.g()); + } + + return jsonobject; + } + } + + public static String a(IChatBaseComponent ichatbasecomponent) { + return IChatBaseComponent.ChatSerializer.a.toJson(ichatbasecomponent); + } + + public static IChatBaseComponent a(String s) { + return ChatSerializer.a.fromJson(s, IChatBaseComponent.class); + } + + @Override + public JsonElement serialize(IChatBaseComponent iChatBaseComponent, Type type, JsonSerializationContext jsonSerializationContext) { + return this.a(iChatBaseComponent, type, jsonSerializationContext); + } + + public IChatBaseComponent deserialize(JsonElement jsonelement, Type type, JsonDeserializationContext jsondeserializationcontext) throws JsonParseException { + return this.a(jsonelement, type, jsondeserializationcontext); + } + + static { + GsonBuilder gsonbuilder = new GsonBuilder(); + + gsonbuilder.registerTypeHierarchyAdapter(IChatBaseComponent.class, new IChatBaseComponent.ChatSerializer()); + gsonbuilder.registerTypeHierarchyAdapter(ChatModifier.class, new ChatModifier.ChatModifierSerializer()); + gsonbuilder.registerTypeAdapterFactory(new ChatTypeAdapterFactory()); + a = gsonbuilder.create(); + } + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/net/minecraft/server/IChunkLoader.java b/azurite-server/src/main/java/net/minecraft/server/IChunkLoader.java new file mode 100644 index 0000000..df4c1e0 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/IChunkLoader.java @@ -0,0 +1,16 @@ +package net.minecraft.server; + +import java.io.IOException; + +public interface IChunkLoader { + + Chunk a(World world, int i, int j) throws IOException; + + void a(World world, Chunk chunk) throws IOException, ExceptionWorldConflict; + + void b(World world, Chunk chunk) throws IOException; + + void a(); + + void b(); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/IChunkProvider.java b/azurite-server/src/main/java/net/minecraft/server/IChunkProvider.java new file mode 100644 index 0000000..1b1b204 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/IChunkProvider.java @@ -0,0 +1,37 @@ +package net.minecraft.server; + +import java.util.List; + +public interface IChunkProvider { + boolean isChunkLoaded(int paramInt1, int paramInt2); + + Chunk getOrCreateChunk(int paramInt1, int paramInt2); + + default Chunk getOrCreateChunk(long hash, int i, int j) { + return getOrCreateChunk(i, j); + } + + Chunk getChunkAt(BlockPosition paramBlockPosition); + + void getChunkAt(IChunkProvider paramIChunkProvider, int paramInt1, int paramInt2); + + boolean a(IChunkProvider paramIChunkProvider, Chunk paramChunk, int paramInt1, int paramInt2); + + boolean saveChunks(boolean paramBoolean, IProgressUpdate paramIProgressUpdate); + + boolean unloadChunks(); + + boolean canSave(); + + String getName(); + + List getMobsFor(EnumCreatureType paramEnumCreatureType, BlockPosition paramBlockPosition); + + BlockPosition findNearestMapFeature(World paramWorld, String paramString, BlockPosition paramBlockPosition); + + int getLoadedChunks(); + + void recreateStructures(Chunk paramChunk, int paramInt1, int paramInt2); + + void c(); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ICommand.java b/azurite-server/src/main/java/net/minecraft/server/ICommand.java new file mode 100644 index 0000000..7c87a09 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ICommand.java @@ -0,0 +1,20 @@ +package net.minecraft.server; + +import java.util.List; + +public interface ICommand extends Comparable { + + String getCommand(); + + String getUsage(ICommandListener icommandlistener); + + List b(); + + void execute(ICommandListener icommandlistener, String[] astring) throws CommandException; + + boolean canUse(ICommandListener icommandlistener); + + List tabComplete(ICommandListener icommandlistener, String[] astring, BlockPosition blockposition); + + boolean isListStart(String[] astring, int i); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ICommandDispatcher.java b/azurite-server/src/main/java/net/minecraft/server/ICommandDispatcher.java new file mode 100644 index 0000000..6fe2bba --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ICommandDispatcher.java @@ -0,0 +1,6 @@ +package net.minecraft.server; + +public interface ICommandDispatcher { + + void a(ICommandListener icommandlistener, ICommand icommand, int i, String s, Object... aobject); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ICommandHandler.java b/azurite-server/src/main/java/net/minecraft/server/ICommandHandler.java new file mode 100644 index 0000000..1cc3bc0 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ICommandHandler.java @@ -0,0 +1,15 @@ +package net.minecraft.server; + +import java.util.List; +import java.util.Map; + +public interface ICommandHandler { + + int a(ICommandListener icommandlistener, String s); + + List a(ICommandListener icommandlistener, String s, BlockPosition blockposition); + + List a(ICommandListener icommandlistener); + + Map getCommands(); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ICommandListener.java b/azurite-server/src/main/java/net/minecraft/server/ICommandListener.java new file mode 100644 index 0000000..443e967 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ICommandListener.java @@ -0,0 +1,24 @@ +package net.minecraft.server; + +public interface ICommandListener { + + String getName(); + + IChatBaseComponent getScoreboardDisplayName(); + + void sendMessage(IChatBaseComponent ichatbasecomponent); + + boolean a(int i, String s); + + BlockPosition getChunkCoordinates(); + + Vec3D d(); + + World getWorld(); + + Entity f(); + + boolean getSendCommandFeedback(); + + void a(CommandObjectiveExecutor.EnumCommandResult commandobjectiveexecutor_enumcommandresult, int i); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/IComplex.java b/azurite-server/src/main/java/net/minecraft/server/IComplex.java new file mode 100644 index 0000000..b92a1f9 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/IComplex.java @@ -0,0 +1,8 @@ +package net.minecraft.server; + +public interface IComplex { + + World a(); + + boolean a(EntityComplexPart entitycomplexpart, DamageSource damagesource, float f); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/IContainer.java b/azurite-server/src/main/java/net/minecraft/server/IContainer.java new file mode 100644 index 0000000..873c7a2 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/IContainer.java @@ -0,0 +1,6 @@ +package net.minecraft.server; + +public interface IContainer { + + TileEntity a(World world, int i); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ICrafting.java b/azurite-server/src/main/java/net/minecraft/server/ICrafting.java new file mode 100644 index 0000000..f528e95 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ICrafting.java @@ -0,0 +1,14 @@ +package net.minecraft.server; + +import java.util.List; + +public interface ICrafting { + + void a(Container container, List list); + + void a(Container container, int i, ItemStack itemstack); + + void setContainerData(Container container, int i, int j); + + void setContainerData(Container container, IInventory iinventory); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/IDataManager.java b/azurite-server/src/main/java/net/minecraft/server/IDataManager.java new file mode 100644 index 0000000..09597aa --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/IDataManager.java @@ -0,0 +1,28 @@ +package net.minecraft.server; + +import java.io.File; + +public interface IDataManager { + + WorldData getWorldData(); + + void checkSession() throws ExceptionWorldConflict; + + IChunkLoader createChunkLoader(WorldProvider worldprovider); + + void saveWorldData(WorldData worlddata, NBTTagCompound nbttagcompound); + + void saveWorldData(WorldData worlddata); + + IPlayerFileData getPlayerFileData(); + + void a(); + + File getDirectory(); + + File getDataFile(String s); + + String g(); + + java.util.UUID getUUID(); // CraftBukkit +} diff --git a/azurite-server/src/main/java/net/minecraft/server/IDispenseBehavior.java b/azurite-server/src/main/java/net/minecraft/server/IDispenseBehavior.java new file mode 100644 index 0000000..f045a6e --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/IDispenseBehavior.java @@ -0,0 +1,12 @@ +package net.minecraft.server; + +public interface IDispenseBehavior { + + IDispenseBehavior NONE = new IDispenseBehavior() { + public ItemStack a(ISourceBlock isourceblock, ItemStack itemstack) { + return itemstack; + } + }; + + ItemStack a(ISourceBlock isourceblock, ItemStack itemstack); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/IEntitySelector.java b/azurite-server/src/main/java/net/minecraft/server/IEntitySelector.java new file mode 100644 index 0000000..1dd636d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/IEntitySelector.java @@ -0,0 +1,68 @@ +package net.minecraft.server; + +import com.google.common.base.Predicate; + +public final class IEntitySelector { + + public static final Predicate a = new Predicate() { + public boolean a(Entity entity) { + return entity.isAlive(); + } + + public boolean apply(Object object) { + return this.a((Entity) object); + } + }; + public static final Predicate b = new Predicate() { + public boolean a(Entity entity) { + return entity.isAlive() && entity.passenger == null && entity.vehicle == null; + } + + public boolean apply(Object object) { + return this.a((Entity) object); + } + }; + public static final Predicate c = new Predicate() { + public boolean a(Entity entity) { + return entity instanceof IInventory && entity.isAlive(); + } + + public boolean apply(Object object) { + return this.a((Entity) object); + } + }; + public static final Predicate d = new Predicate() { + public boolean a(Entity entity) { + return !(entity instanceof EntityHuman) || !((EntityHuman) entity).isSpectator(); + } + + public boolean apply(Object object) { + return this.a((Entity) object); + } + }; + + public static class EntitySelectorEquipable implements Predicate { + + private final ItemStack a; + + public EntitySelectorEquipable(ItemStack itemstack) { + this.a = itemstack; + } + + public boolean a(Entity entity) { + if (!entity.isAlive()) { + return false; + } else if (!(entity instanceof EntityLiving)) { + return false; + } else { + EntityLiving entityliving = (EntityLiving) entity; + + return entityliving.getEquipment(EntityInsentient.c(this.a)) != null ? false : (entityliving instanceof EntityInsentient ? ((EntityInsentient) entityliving).bY() : (entityliving instanceof EntityArmorStand ? true : entityliving instanceof EntityHuman)); + } + } + + public boolean apply(Entity object) { + return this.a(object); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/IHopper.java b/azurite-server/src/main/java/net/minecraft/server/IHopper.java new file mode 100644 index 0000000..58ebe50 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/IHopper.java @@ -0,0 +1,12 @@ +package net.minecraft.server; + +public interface IHopper extends IInventory { + + World getWorld(); + + double A(); + + double B(); + + double C(); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/IInventory.java b/azurite-server/src/main/java/net/minecraft/server/IInventory.java new file mode 100644 index 0000000..53ed0d3 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/IInventory.java @@ -0,0 +1,52 @@ +package net.minecraft.server; + +import org.bukkit.craftbukkit.entity.CraftHumanEntity; + +public interface IInventory extends INamableTileEntity { + + int getSize(); + + ItemStack getItem(int i); + + ItemStack splitStack(int i, int j); + + ItemStack splitWithoutUpdate(int i); + + void setItem(int i, ItemStack itemstack); + + int getMaxStackSize(); + + void update(); + + boolean a(EntityHuman entityhuman); + + void startOpen(EntityHuman entityhuman); + + void closeContainer(EntityHuman entityhuman); + + boolean b(int i, ItemStack itemstack); + + int getProperty(int i); + + void b(int i, int j); + + int g(); + + void l(); + + // CraftBukkit start + ItemStack[] getContents(); + + void onOpen(CraftHumanEntity who); + + void onClose(CraftHumanEntity who); + + java.util.List getViewers(); + + org.bukkit.inventory.InventoryHolder getOwner(); + + void setMaxStackSize(int size); + + int MAX_STACK = 64; + // CraftBukkit end +} diff --git a/azurite-server/src/main/java/net/minecraft/server/IInventoryListener.java b/azurite-server/src/main/java/net/minecraft/server/IInventoryListener.java new file mode 100644 index 0000000..9950b76 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/IInventoryListener.java @@ -0,0 +1,6 @@ +package net.minecraft.server; + +public interface IInventoryListener { + + void a(InventorySubcontainer inventorysubcontainer); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/IJsonStatistic.java b/azurite-server/src/main/java/net/minecraft/server/IJsonStatistic.java new file mode 100644 index 0000000..5df213b --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/IJsonStatistic.java @@ -0,0 +1,10 @@ +package net.minecraft.server; + +import com.google.gson.JsonElement; + +public interface IJsonStatistic { + + void a(JsonElement jsonelement); + + JsonElement a(); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ILocationSource.java b/azurite-server/src/main/java/net/minecraft/server/ILocationSource.java new file mode 100644 index 0000000..21f31dd --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ILocationSource.java @@ -0,0 +1,3 @@ +package net.minecraft.server; + +public interface ILocationSource extends ISource {} diff --git a/azurite-server/src/main/java/net/minecraft/server/IMerchant.java b/azurite-server/src/main/java/net/minecraft/server/IMerchant.java new file mode 100644 index 0000000..07a68e3 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/IMerchant.java @@ -0,0 +1,16 @@ +package net.minecraft.server; + +public interface IMerchant { + + void a_(EntityHuman entityhuman); + + EntityHuman v_(); + + MerchantRecipeList getOffers(EntityHuman entityhuman); + + void a(MerchantRecipe merchantrecipe); + + void a_(ItemStack itemstack); + + IChatBaseComponent getScoreboardDisplayName(); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/IMinecraftServer.java b/azurite-server/src/main/java/net/minecraft/server/IMinecraftServer.java new file mode 100644 index 0000000..5692a46 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/IMinecraftServer.java @@ -0,0 +1,44 @@ +package net.minecraft.server; + +public interface IMinecraftServer { + + int a(String s, int i); + + String a(String s, String s1); + + void a(String s, Object object); + + void a(); + + String b(); + + String E(); + + int F(); + + String G(); + + String getVersion(); + + int I(); + + int J(); + + String[] getPlayers(); + + String U(); + + String getPlugins(); + + String executeRemoteCommand(String s); + + boolean isDebugging(); + + void info(String s); + + void warning(String s); + + void g(String s); + + void h(String s); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/IMojangStatistics.java b/azurite-server/src/main/java/net/minecraft/server/IMojangStatistics.java new file mode 100644 index 0000000..d906c9c --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/IMojangStatistics.java @@ -0,0 +1,10 @@ +package net.minecraft.server; + +public interface IMojangStatistics { + + void a(MojangStatisticsGenerator mojangstatisticsgenerator); + + void b(MojangStatisticsGenerator mojangstatisticsgenerator); + + boolean getSnooperEnabled(); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/IMonster.java b/azurite-server/src/main/java/net/minecraft/server/IMonster.java new file mode 100644 index 0000000..8076121 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/IMonster.java @@ -0,0 +1,25 @@ +package net.minecraft.server; + +import com.google.common.base.Predicate; + +public interface IMonster extends IAnimal { + + Predicate d = new Predicate() { + public boolean a(Entity entity) { + return entity instanceof IMonster; + } + + public boolean apply(Object object) { + return this.a((Entity) object); + } + }; + Predicate e = new Predicate() { + public boolean a(Entity entity) { + return entity instanceof IMonster && !entity.isInvisible(); + } + + public boolean apply(Object object) { + return this.a((Entity) object); + } + }; +} diff --git a/azurite-server/src/main/java/net/minecraft/server/INamable.java b/azurite-server/src/main/java/net/minecraft/server/INamable.java new file mode 100644 index 0000000..c957511 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/INamable.java @@ -0,0 +1,6 @@ +package net.minecraft.server; + +public interface INamable { + + String getName(); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/INamableTileEntity.java b/azurite-server/src/main/java/net/minecraft/server/INamableTileEntity.java new file mode 100644 index 0000000..e82245d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/INamableTileEntity.java @@ -0,0 +1,10 @@ +package net.minecraft.server; + +public interface INamableTileEntity { + + String getName(); + + boolean hasCustomName(); + + IChatBaseComponent getScoreboardDisplayName(); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/IPlayerFileData.java b/azurite-server/src/main/java/net/minecraft/server/IPlayerFileData.java new file mode 100644 index 0000000..8b2d910 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/IPlayerFileData.java @@ -0,0 +1,10 @@ +package net.minecraft.server; + +public interface IPlayerFileData { + + void save(EntityHuman entityhuman); + + NBTTagCompound load(EntityHuman entityhuman); + + String[] getSeenPlayers(); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/IPosition.java b/azurite-server/src/main/java/net/minecraft/server/IPosition.java new file mode 100644 index 0000000..b883ec9 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/IPosition.java @@ -0,0 +1,10 @@ +package net.minecraft.server; + +public interface IPosition { + + double getX(); + + double getY(); + + double getZ(); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/IProgressUpdate.java b/azurite-server/src/main/java/net/minecraft/server/IProgressUpdate.java new file mode 100644 index 0000000..3ac3db1 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/IProgressUpdate.java @@ -0,0 +1,10 @@ +package net.minecraft.server; + +public interface IProgressUpdate { + + void a(String s); + + void c(String s); + + void a(int i); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/IProjectile.java b/azurite-server/src/main/java/net/minecraft/server/IProjectile.java new file mode 100644 index 0000000..c043481 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/IProjectile.java @@ -0,0 +1,6 @@ +package net.minecraft.server; + +public interface IProjectile { + + void shoot(double d0, double d1, double d2, float f, float f1); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/IRangedEntity.java b/azurite-server/src/main/java/net/minecraft/server/IRangedEntity.java new file mode 100644 index 0000000..b4178ce --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/IRangedEntity.java @@ -0,0 +1,6 @@ +package net.minecraft.server; + +public interface IRangedEntity { + + void a(EntityLiving entityliving, float f); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/IRecipe.java b/azurite-server/src/main/java/net/minecraft/server/IRecipe.java new file mode 100644 index 0000000..ffc65a2 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/IRecipe.java @@ -0,0 +1,18 @@ +package net.minecraft.server; + +public interface IRecipe { + + boolean a(InventoryCrafting inventorycrafting, World world); + + ItemStack craftItem(InventoryCrafting inventorycrafting); + + int a(); + + ItemStack b(); + + ItemStack[] b(InventoryCrafting inventorycrafting); + + org.bukkit.inventory.Recipe toBukkitRecipe(); // CraftBukkit + + java.util.List getIngredients(); // Spigot +} diff --git a/azurite-server/src/main/java/net/minecraft/server/IRegistry.java b/azurite-server/src/main/java/net/minecraft/server/IRegistry.java new file mode 100644 index 0000000..fb8e5cc --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/IRegistry.java @@ -0,0 +1,3 @@ +package net.minecraft.server; + +public interface IRegistry extends Iterable {} diff --git a/azurite-server/src/main/java/net/minecraft/server/IScoreboardCriteria.java b/azurite-server/src/main/java/net/minecraft/server/IScoreboardCriteria.java new file mode 100644 index 0000000..5c9fd9a --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/IScoreboardCriteria.java @@ -0,0 +1,60 @@ +package net.minecraft.server; + +import com.google.common.collect.Maps; +import java.util.List; +import java.util.Map; + +public interface IScoreboardCriteria { + + Map criteria = Maps.newHashMap(); + IScoreboardCriteria b = new ScoreboardBaseCriteria("dummy"); + IScoreboardCriteria c = new ScoreboardBaseCriteria("trigger"); + IScoreboardCriteria d = new ScoreboardBaseCriteria("deathCount"); + IScoreboardCriteria e = new ScoreboardBaseCriteria("playerKillCount"); + IScoreboardCriteria f = new ScoreboardBaseCriteria("totalKillCount"); + IScoreboardCriteria g = new ScoreboardHealthCriteria("health"); + IScoreboardCriteria[] h = new IScoreboardCriteria[] { new ScoreboardCriteriaInteger("teamkill.", EnumChatFormat.BLACK), new ScoreboardCriteriaInteger("teamkill.", EnumChatFormat.DARK_BLUE), new ScoreboardCriteriaInteger("teamkill.", EnumChatFormat.DARK_GREEN), new ScoreboardCriteriaInteger("teamkill.", EnumChatFormat.DARK_AQUA), new ScoreboardCriteriaInteger("teamkill.", EnumChatFormat.DARK_RED), new ScoreboardCriteriaInteger("teamkill.", EnumChatFormat.DARK_PURPLE), new ScoreboardCriteriaInteger("teamkill.", EnumChatFormat.GOLD), new ScoreboardCriteriaInteger("teamkill.", EnumChatFormat.GRAY), new ScoreboardCriteriaInteger("teamkill.", EnumChatFormat.DARK_GRAY), new ScoreboardCriteriaInteger("teamkill.", EnumChatFormat.BLUE), new ScoreboardCriteriaInteger("teamkill.", EnumChatFormat.GREEN), new ScoreboardCriteriaInteger("teamkill.", EnumChatFormat.AQUA), new ScoreboardCriteriaInteger("teamkill.", EnumChatFormat.RED), new ScoreboardCriteriaInteger("teamkill.", EnumChatFormat.LIGHT_PURPLE), new ScoreboardCriteriaInteger("teamkill.", EnumChatFormat.YELLOW), new ScoreboardCriteriaInteger("teamkill.", EnumChatFormat.WHITE)}; + IScoreboardCriteria[] i = new IScoreboardCriteria[] { new ScoreboardCriteriaInteger("killedByTeam.", EnumChatFormat.BLACK), new ScoreboardCriteriaInteger("killedByTeam.", EnumChatFormat.DARK_BLUE), new ScoreboardCriteriaInteger("killedByTeam.", EnumChatFormat.DARK_GREEN), new ScoreboardCriteriaInteger("killedByTeam.", EnumChatFormat.DARK_AQUA), new ScoreboardCriteriaInteger("killedByTeam.", EnumChatFormat.DARK_RED), new ScoreboardCriteriaInteger("killedByTeam.", EnumChatFormat.DARK_PURPLE), new ScoreboardCriteriaInteger("killedByTeam.", EnumChatFormat.GOLD), new ScoreboardCriteriaInteger("killedByTeam.", EnumChatFormat.GRAY), new ScoreboardCriteriaInteger("killedByTeam.", EnumChatFormat.DARK_GRAY), new ScoreboardCriteriaInteger("killedByTeam.", EnumChatFormat.BLUE), new ScoreboardCriteriaInteger("killedByTeam.", EnumChatFormat.GREEN), new ScoreboardCriteriaInteger("killedByTeam.", EnumChatFormat.AQUA), new ScoreboardCriteriaInteger("killedByTeam.", EnumChatFormat.RED), new ScoreboardCriteriaInteger("killedByTeam.", EnumChatFormat.LIGHT_PURPLE), new ScoreboardCriteriaInteger("killedByTeam.", EnumChatFormat.YELLOW), new ScoreboardCriteriaInteger("killedByTeam.", EnumChatFormat.WHITE)}; + + String getName(); + + int getScoreModifier(List list); + + boolean isReadOnly(); + + IScoreboardCriteria.EnumScoreboardHealthDisplay c(); + + public static enum EnumScoreboardHealthDisplay { + + INTEGER("integer"), HEARTS("hearts"); + + private static final Map c = Maps.newHashMap(); + private final String d; + + private EnumScoreboardHealthDisplay(String s) { + this.d = s; + } + + public String a() { + return this.d; + } + + public static IScoreboardCriteria.EnumScoreboardHealthDisplay a(String s) { + IScoreboardCriteria.EnumScoreboardHealthDisplay iscoreboardcriteria_enumscoreboardhealthdisplay = (IScoreboardCriteria.EnumScoreboardHealthDisplay) IScoreboardCriteria.EnumScoreboardHealthDisplay.c.get(s); + + return iscoreboardcriteria_enumscoreboardhealthdisplay == null ? IScoreboardCriteria.EnumScoreboardHealthDisplay.INTEGER : iscoreboardcriteria_enumscoreboardhealthdisplay; + } + + static { + IScoreboardCriteria.EnumScoreboardHealthDisplay[] aiscoreboardcriteria_enumscoreboardhealthdisplay = values(); + int i = aiscoreboardcriteria_enumscoreboardhealthdisplay.length; + + for (int j = 0; j < i; ++j) { + IScoreboardCriteria.EnumScoreboardHealthDisplay iscoreboardcriteria_enumscoreboardhealthdisplay = aiscoreboardcriteria_enumscoreboardhealthdisplay[j]; + + IScoreboardCriteria.EnumScoreboardHealthDisplay.c.put(iscoreboardcriteria_enumscoreboardhealthdisplay.a(), iscoreboardcriteria_enumscoreboardhealthdisplay); + } + + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ISource.java b/azurite-server/src/main/java/net/minecraft/server/ISource.java new file mode 100644 index 0000000..9424003 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ISource.java @@ -0,0 +1,6 @@ +package net.minecraft.server; + +public interface ISource extends IPosition { + + World getWorld(); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ISourceBlock.java b/azurite-server/src/main/java/net/minecraft/server/ISourceBlock.java new file mode 100644 index 0000000..a028295 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ISourceBlock.java @@ -0,0 +1,16 @@ +package net.minecraft.server; + +public interface ISourceBlock extends ILocationSource { + + double getX(); + + double getY(); + + double getZ(); + + BlockPosition getBlockPosition(); + + int f(); + + T getTileEntity(); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ITileEntityContainer.java b/azurite-server/src/main/java/net/minecraft/server/ITileEntityContainer.java new file mode 100644 index 0000000..4da4298 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ITileEntityContainer.java @@ -0,0 +1,8 @@ +package net.minecraft.server; + +public interface ITileEntityContainer extends INamableTileEntity { + + Container createContainer(PlayerInventory playerinventory, EntityHuman entityhuman); + + String getContainerName(); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ITileInventory.java b/azurite-server/src/main/java/net/minecraft/server/ITileInventory.java new file mode 100644 index 0000000..6dc5cbc --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ITileInventory.java @@ -0,0 +1,10 @@ +package net.minecraft.server; + +public interface ITileInventory extends IInventory, ITileEntityContainer { + + boolean r_(); + + void a(ChestLock chestlock); + + ChestLock i(); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/IUpdatePlayerListBox.java b/azurite-server/src/main/java/net/minecraft/server/IUpdatePlayerListBox.java new file mode 100644 index 0000000..63e38c9 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/IUpdatePlayerListBox.java @@ -0,0 +1,6 @@ +package net.minecraft.server; + +public interface IUpdatePlayerListBox { + + void c(); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/IWorldAccess.java b/azurite-server/src/main/java/net/minecraft/server/IWorldAccess.java new file mode 100644 index 0000000..251cc29 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/IWorldAccess.java @@ -0,0 +1,38 @@ +package net.minecraft.server; + +public interface IWorldAccess { + + // Azurite + default void a(int x, int y, int z) { + this.a(new BlockPosition(x, y, z)); // Some plugins override IWorldAccess and don't have this method so default back to this + } + + void a(BlockPosition var1); + + void b(BlockPosition var1); + + void a(int var1, int var2, int var3, int var4, int var5, int var6); + + void a(String var1, double var2, double var4, double var6, float var8, float var9); + + // Beanes - add self variable + void a(String var1, double var2, double var4, double var6, float var8, float var9, boolean self); + + void a(EntityHuman var1, String var2, double var3, double var5, double var7, float var9, float var10); + + void a(EntityHuman var1, String var2, double var3, double var5, double var7, float var9, float var10, boolean self); + + void a(int var1, boolean var2, double var3, double var5, double var7, double var9, double var11, double var13, int... var15); + + void a(Entity var1); + + void b(Entity var1); + + void a(String var1, BlockPosition var2); + + void a(int var1, BlockPosition var2, int var3); + + void a(EntityHuman var1, int var2, BlockPosition var3, int var4); + + void b(int var1, BlockPosition var2, int var3); +} \ No newline at end of file diff --git a/azurite-server/src/main/java/net/minecraft/server/IWorldBorderListener.java b/azurite-server/src/main/java/net/minecraft/server/IWorldBorderListener.java new file mode 100644 index 0000000..4552acd --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/IWorldBorderListener.java @@ -0,0 +1,18 @@ +package net.minecraft.server; + +public interface IWorldBorderListener { + + void a(WorldBorder worldborder, double d0); + + void a(WorldBorder worldborder, double d0, double d1, long i); + + void a(WorldBorder worldborder, double d0, double d1); + + void a(WorldBorder worldborder, int i); + + void b(WorldBorder worldborder, int i); + + void b(WorldBorder worldborder, double d0); + + void c(WorldBorder worldborder, double d0); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/IWorldInventory.java b/azurite-server/src/main/java/net/minecraft/server/IWorldInventory.java new file mode 100644 index 0000000..8df2f60 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/IWorldInventory.java @@ -0,0 +1,10 @@ +package net.minecraft.server; + +public interface IWorldInventory extends IInventory { + int[] getSlotsForFace(EnumDirection var1); + int[] getSlotsForDownFace(); // Beanes - optimized hoppers + + boolean canPlaceItemThroughFace(int var1, ItemStack var2, EnumDirection var3); + + boolean canTakeItemThroughFace(int var1, ItemStack var2, EnumDirection var3); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/InsensitiveStringMap.java b/azurite-server/src/main/java/net/minecraft/server/InsensitiveStringMap.java new file mode 100644 index 0000000..1d67b28 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/InsensitiveStringMap.java @@ -0,0 +1,74 @@ +package net.minecraft.server; + +import com.google.common.collect.Maps; +import java.util.Collection; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; +import java.util.Map.Entry; + +public class InsensitiveStringMap implements Map { + + private final Map a = Maps.newLinkedHashMap(); + + public InsensitiveStringMap() {} + + public int size() { + return this.a.size(); + } + + public boolean isEmpty() { + return this.a.isEmpty(); + } + + public boolean containsKey(Object object) { + return this.a.containsKey(object.toString().toLowerCase()); + } + + public boolean containsValue(Object object) { + return this.a.containsKey(object); + } + + public V get(Object object) { + return this.a.get(object.toString().toLowerCase()); + } + + public V a(String s, V v0) { + return this.a.put(s.toLowerCase(), v0); + } + + public V remove(Object object) { + return this.a.remove(object.toString().toLowerCase()); + } + + public void putAll(Map map) { + Iterator iterator = map.entrySet().iterator(); + + while (iterator.hasNext()) { + Entry entry = (Entry) iterator.next(); + + this.a((String) entry.getKey(), (V) entry.getValue()); + } + + } + + public void clear() { + this.a.clear(); + } + + public Set keySet() { + return this.a.keySet(); + } + + public Collection values() { + return this.a.values(); + } + + public Set> entrySet() { + return this.a.entrySet(); + } + + public V put(String object, V object1) { + return this.a(object, object1); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/InstantMobEffect.java b/azurite-server/src/main/java/net/minecraft/server/InstantMobEffect.java new file mode 100644 index 0000000..50a5124 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/InstantMobEffect.java @@ -0,0 +1,16 @@ +package net.minecraft.server; + +public class InstantMobEffect extends MobEffectList { + + public InstantMobEffect(int i, MinecraftKey minecraftkey, boolean flag, int j) { + super(i, minecraftkey, flag, j); + } + + public boolean isInstant() { + return true; + } + + public boolean a(int i, int j) { + return i >= 1; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/IntCache.java b/azurite-server/src/main/java/net/minecraft/server/IntCache.java new file mode 100644 index 0000000..2856c73 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/IntCache.java @@ -0,0 +1,113 @@ +package net.minecraft.server; + +// NeonPaper start + +import it.unimi.dsi.fastutil.objects.ObjectArrayList; + +import java.lang.ref.WeakReference; +import java.util.Iterator; +import java.util.List; +// NeonPaper end + +public class IntCache { + + private static int a = 256; + // NeonPaper start - Refactored IntCache to be thread local instead of static + private static final ThreadLocal caches = new ThreadLocal() { + @Override + protected IntCache initialValue() { + IntCache cache = new IntCache(); + synchronized (ALL_CACHES) { + ALL_CACHES.add(new WeakReference<>(cache)); + } + return new IntCache(); + } + }; + + private static final List> ALL_CACHES = new ObjectArrayList<>(); + private final List b = new ObjectArrayList<>(); + private final List c = new ObjectArrayList<>(); + private final List d = new ObjectArrayList<>(); + private final List e = new ObjectArrayList<>(); + + private final int cacheLimit = org.spigotmc.SpigotConfig.intCacheLimit; + + public static int[] a(int i) { + return caches.get().aNonStatic(i); + } + + public int[] aNonStatic(int i) { + int[] aint; + + if (i <= 256) { + if (this.b.isEmpty()) { + aint = new int[256]; + } else { + aint = this.b.remove(this.b.size() - 1); + } + if (c.size() < cacheLimit) this.c.add(aint); + return aint; + } else if (i > a) { + a = i; + this.d.clear(); + this.e.clear(); + aint = new int[a]; + if (0 < cacheLimit) this.e.add(aint); + return aint; + } else if (this.d.isEmpty()) { + aint = new int[a]; + if (e.size() < cacheLimit) this.e.add(aint); + return aint; + } else { + aint = this.d.remove(this.d.size() - 1); + if (e.size() < cacheLimit) this.e.add(aint); + return aint; + } + } + + public static void a() { + caches.get().aNonStatic(); + } + + public void aNonStatic() { + if (!this.d.isEmpty()) { + this.d.remove(this.d.size() - 1); + } + + if (!this.b.isEmpty()) { + this.b.remove(this.b.size() - 1); + } + + this.d.addAll(this.e); + this.b.addAll(this.c); + this.e.clear(); + this.c.clear(); + } + + public static String b() { + int cache = 0; + int tcache = 0; + int allocated = 0; + int tallocated = 0; + int numberOfCaches; + + synchronized (ALL_CACHES) { + numberOfCaches = ALL_CACHES.size(); + Iterator> iter = ALL_CACHES.iterator(); + while (iter.hasNext()) { + WeakReference reference = iter.next(); + IntCache intcache = reference.get(); + if (intcache != null) { + cache += intcache.d.size(); + tcache += intcache.b.size(); + allocated += intcache.e.size(); + tallocated += intcache.c.size(); + } else { + iter.remove(); + } + } + } + return numberOfCaches + " IntCaches. In Total => cache: " + cache + ", tcache: " + tcache + ", allocated: " + allocated + ", tallocated: " + tallocated; + } + // NeonPaper end +} \ No newline at end of file diff --git a/azurite-server/src/main/java/net/minecraft/server/IntHashMap.java b/azurite-server/src/main/java/net/minecraft/server/IntHashMap.java new file mode 100644 index 0000000..4a71cc0 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/IntHashMap.java @@ -0,0 +1,194 @@ +package net.minecraft.server; + +import java.util.Arrays; +import java.util.Objects; + +public class IntHashMap { + + private transient IntHashMapEntry[] a = new IntHashMapEntry[16]; + private transient int b; + private int c = 12; + + public IntHashMap() { + } + + private static int g(int i) { + i ^= i >>> 20 ^ i >>> 12; + return i ^ i >>> 7 ^ i >>> 4; + } + + private static int a(int i, int j) { + return i & j - 1; + } + + public V get(int i) { + int j = g(i); + + for (IntHashMapEntry inthashmap_inthashmapentry = this.a[a(j, this.a.length)]; + inthashmap_inthashmapentry != null; inthashmap_inthashmapentry = inthashmap_inthashmapentry.c) { + if (inthashmap_inthashmapentry.a == i) { + return inthashmap_inthashmapentry.b(); + } + } + + return null; + } + + public boolean b(int i) { + return this.c(i) != null; + } + + final IntHashMapEntry c(int i) { + int j = g(i); + + for (IntHashMapEntry inthashmap_inthashmapentry = this.a[a(j, this.a.length)]; inthashmap_inthashmapentry != null; inthashmap_inthashmapentry = inthashmap_inthashmapentry.c) { + if (inthashmap_inthashmapentry.a == i) { + return inthashmap_inthashmapentry; + } + } + + return null; + } + + public void a(int i, V v0) { + int j = g(i); + int k = a(j, this.a.length); + + for (IntHashMapEntry inthashmap_inthashmapentry = this.a[k]; inthashmap_inthashmapentry != null; inthashmap_inthashmapentry = inthashmap_inthashmapentry.c) { + if (inthashmap_inthashmapentry.a == i) { + inthashmap_inthashmapentry.b = v0; + return; + } + } + + this.a(j, i, v0, k); + } + + private void h(int i) { + IntHashMapEntry[] ainthashmap_inthashmapentry = this.a; + int j = ainthashmap_inthashmapentry.length; + + if (j == 1073741824) { + this.c = Integer.MAX_VALUE; + } else { + IntHashMapEntry[] ainthashmap_inthashmapentry1 = new IntHashMapEntry[i]; + + this.a(ainthashmap_inthashmapentry1); + this.a = ainthashmap_inthashmapentry1; + this.c = (int) ((float) i * 0.75F); + } + } + + private void a(IntHashMapEntry[] ainthashmap_inthashmapentry) { + IntHashMapEntry[] ainthashmap_inthashmapentry1 = this.a; + int i = ainthashmap_inthashmapentry.length; + + for (int j = 0; j < ainthashmap_inthashmapentry1.length; ++j) { + IntHashMapEntry inthashmap_inthashmapentry = ainthashmap_inthashmapentry1[j]; + + if (inthashmap_inthashmapentry != null) { + ainthashmap_inthashmapentry1[j] = null; + + IntHashMapEntry inthashmap_inthashmapentry1; + + do { + inthashmap_inthashmapentry1 = inthashmap_inthashmapentry.c; + int k = a(inthashmap_inthashmapentry.d, i); + + inthashmap_inthashmapentry.c = ainthashmap_inthashmapentry[k]; + ainthashmap_inthashmapentry[k] = inthashmap_inthashmapentry; + inthashmap_inthashmapentry = inthashmap_inthashmapentry1; + } while (inthashmap_inthashmapentry1 != null); + } + } + + } + + public V d(int i) { + IntHashMapEntry inthashmap_inthashmapentry = this.e(i); + + return inthashmap_inthashmapentry == null ? null : inthashmap_inthashmapentry.b; + } + + final IntHashMapEntry e(int i) { + int j = g(i); + int k = a(j, this.a.length); + IntHashMapEntry inthashmap_inthashmapentry = this.a[k]; + + IntHashMapEntry inthashmap_inthashmapentry1; + IntHashMapEntry inthashmap_inthashmapentry2; + + for (inthashmap_inthashmapentry1 = inthashmap_inthashmapentry; inthashmap_inthashmapentry1 != null; inthashmap_inthashmapentry1 = inthashmap_inthashmapentry2) { + inthashmap_inthashmapentry2 = inthashmap_inthashmapentry1.c; + if (inthashmap_inthashmapentry1.a == i) { + --this.b; + if (inthashmap_inthashmapentry == inthashmap_inthashmapentry1) { + this.a[k] = inthashmap_inthashmapentry2; + } else { + inthashmap_inthashmapentry.c = inthashmap_inthashmapentry2; + } + + return inthashmap_inthashmapentry1; + } + + inthashmap_inthashmapentry = inthashmap_inthashmapentry1; + } + + return null; + } + + public void c() { + Arrays.fill(a, null); + this.b = 0; + } + + private void a(int i, int j, V v0, int k) { + IntHashMapEntry inthashmap_inthashmapentry = this.a[k]; + + this.a[k] = new IntHashMapEntry(i, j, v0, inthashmap_inthashmapentry); + if (this.b++ >= this.c) { + this.h(2 * this.a.length); + } + + } + + static class IntHashMapEntry { + + final int a; + V b; + IntHashMapEntry c; + final int d; + + IntHashMapEntry(int i, int j, V v0, IntHashMapEntry inthashmap_inthashmapentry) { + this.b = v0; + this.c = inthashmap_inthashmapentry; + this.a = j; + this.d = i; + } + + public final int a() { + return this.a; + } + + public final V b() { + return this.b; + } + + public final boolean equals(Object object) { + if (!(object instanceof IntHashMap.IntHashMapEntry)) { + return false; + } else { + IntHashMapEntry inthashmap_inthashmapentry = (IntHashMapEntry) object; + return Objects.equals(a(), inthashmap_inthashmapentry.a()) && Objects.equals(b(), inthashmap_inthashmapentry.b()); + } + } + + public final int hashCode() { + return IntHashMap.g(this.a); + } + + public final String toString() { + return this.a() + "=" + this.b(); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/InventoryCraftResult.java b/azurite-server/src/main/java/net/minecraft/server/InventoryCraftResult.java new file mode 100644 index 0000000..e22ff16 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/InventoryCraftResult.java @@ -0,0 +1,116 @@ +package net.minecraft.server; + +// CraftBukkit start +import org.bukkit.craftbukkit.entity.CraftHumanEntity; +import org.bukkit.entity.HumanEntity; + +import java.util.Arrays; +// CraftBukkit end + +public class InventoryCraftResult implements IInventory { + + public final ItemStack[] items = new ItemStack[1]; + + // CraftBukkit start + private int maxStack = MAX_STACK; + + public ItemStack[] getContents() { + return this.items; + } + + public org.bukkit.inventory.InventoryHolder getOwner() { + return null; // Result slots don't get an owner + } + + // Don't need a transaction; the InventoryCrafting keeps track of it for us + public void onOpen(CraftHumanEntity who) {} + public void onClose(CraftHumanEntity who) {} + public java.util.List getViewers() { + return new java.util.ArrayList<>(); + } + + public void setMaxStackSize(int size) { + maxStack = size; + } + // CraftBukkit end + + public InventoryCraftResult() {} + + public int getSize() { + return 1; + } + + public ItemStack getItem(int i) { + return this.items[0]; + } + + public String getName() { + return "Result"; + } + + public boolean hasCustomName() { + return false; + } + + public IChatBaseComponent getScoreboardDisplayName() { + return (this.hasCustomName() ? new ChatComponentText(this.getName()) : new ChatMessage(this.getName())); + } + + public ItemStack splitStack(int i, int j) { + ItemStack itemstack = this.items[0]; + + if (itemstack != null) { + this.items[0] = null; + return itemstack; + } else { + return null; + } + } + + public ItemStack splitWithoutUpdate(int i) { + ItemStack itemstack = this.items[0]; + + if (itemstack != null) { + this.items[0] = null; + return itemstack; + } else { + return null; + } + } + + public void setItem(int i, ItemStack itemstack) { + this.items[0] = itemstack; + } + + public int getMaxStackSize() { + return maxStack; // CraftBukkit + } + + public void update() {} + + public boolean a(EntityHuman entityhuman) { + return true; + } + + public void startOpen(EntityHuman entityhuman) {} + + public void closeContainer(EntityHuman entityhuman) {} + + public boolean b(int i, ItemStack itemstack) { + return true; + } + + public int getProperty(int i) { + return 0; + } + + public void b(int i, int j) {} + + public int g() { + return 0; + } + + public void l() { + Arrays.fill(this.items, null); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/InventoryCrafting.java b/azurite-server/src/main/java/net/minecraft/server/InventoryCrafting.java new file mode 100644 index 0000000..8abae21 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/InventoryCrafting.java @@ -0,0 +1,166 @@ +package net.minecraft.server; + +// CraftBukkit start + +import org.bukkit.craftbukkit.entity.CraftHumanEntity; +import org.bukkit.entity.HumanEntity; +import org.bukkit.event.inventory.InventoryType; + +import java.util.Arrays; +import java.util.List; +// CraftBukkit end + +public class InventoryCrafting implements IInventory { + + public final ItemStack[] items; + private final int b; + private final int c; + private final Container d; + + // CraftBukkit start - add fields + public List transaction = new java.util.ArrayList<>(); + public IRecipe currentRecipe; + public IInventory resultInventory; + private EntityHuman owner; + + public ItemStack[] getContents() { + return this.items; + } + + public void onOpen(CraftHumanEntity who) { + transaction.add(who); + } + + public InventoryType getInvType() { + return items.length == 4 ? InventoryType.CRAFTING : InventoryType.WORKBENCH; + } + + public void onClose(CraftHumanEntity who) { + transaction.remove(who); + } + + public List getViewers() { + return transaction; + } + + public org.bukkit.inventory.InventoryHolder getOwner() { + return (owner == null) ? null : owner.getBukkitEntity(); + } + + public void setMaxStackSize(int size) { + resultInventory.setMaxStackSize(size); + } + + public InventoryCrafting(Container container, int i, int j, EntityHuman player) { + this(container, i, j); + this.owner = player; + } + // CraftBukkit end + + public InventoryCrafting(Container container, int i, int j) { + int k = i * j; + + this.items = new ItemStack[k]; + this.d = container; + this.b = i; + this.c = j; + } + + public int getSize() { + return this.items.length; + } + + public ItemStack getItem(int i) { + return i >= this.getSize() ? null : this.items[i]; + } + + public ItemStack c(int i, int j) { + return i >= 0 && i < this.b && j >= 0 && j <= this.c ? this.getItem(i + j * this.b) : null; + } + + public String getName() { + return "container.crafting"; + } + + public boolean hasCustomName() { + return false; + } + + public IChatBaseComponent getScoreboardDisplayName() { + return (this.hasCustomName() ? new ChatComponentText(this.getName()) : new ChatMessage(this.getName())); + } + + public ItemStack splitWithoutUpdate(int i) { + ItemStack itemstack = items[i]; + if (itemstack != null) { + this.items[i] = null; + return itemstack; + } else { + return null; + } + } + + public ItemStack splitStack(int i, int j) { + ItemStack itemstack = items[i]; + if (itemstack != null) { + if (itemstack.count <= j) { + this.items[i] = null; + } else { + if (itemstack.count == 0) { + this.items[i] = null; + } + itemstack = itemstack.cloneAndSubtract(j); + } + this.d.a(this); + return itemstack; + } else { + return null; + } + } + + public void setItem(int i, ItemStack itemstack) { + this.items[i] = itemstack; + this.d.a(this); + } + + public int getMaxStackSize() { + return 64; + } + + public void update() {} + + public boolean a(EntityHuman entityhuman) { + return true; + } + + public void startOpen(EntityHuman entityhuman) {} + + public void closeContainer(EntityHuman entityhuman) {} + + public boolean b(int i, ItemStack itemstack) { + return true; + } + + public int getProperty(int i) { + return 0; + } + + public void b(int i, int j) {} + + public int g() { + return 0; + } + + public void l() { + Arrays.fill(this.items, null); + + } + + public int h() { + return this.c; + } + + public int i() { + return this.b; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/InventoryEnderChest.java b/azurite-server/src/main/java/net/minecraft/server/InventoryEnderChest.java new file mode 100644 index 0000000..33ed6fb --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/InventoryEnderChest.java @@ -0,0 +1,113 @@ +package net.minecraft.server; + +// CraftBukkit start + +import org.bukkit.craftbukkit.entity.CraftHumanEntity; +import org.bukkit.entity.HumanEntity; + +import java.util.List; +// CraftBukkit end + +public class InventoryEnderChest extends InventorySubcontainer { + + private TileEntityEnderChest a; + + // CraftBukkit start - add fields and methods + public List transaction = new java.util.ArrayList<>(); + public org.bukkit.entity.Player player; + private int maxStack = MAX_STACK; + + public ItemStack[] getContents() { + return this.items; + } + + public void onOpen(CraftHumanEntity who) { + transaction.add(who); + } + + public void onClose(CraftHumanEntity who) { + transaction.remove(who); + } + + public List getViewers() { + return transaction; + } + + public org.bukkit.inventory.InventoryHolder getOwner() { + return this.player; + } + + public void setMaxStackSize(int size) { + maxStack = size; + } + + public int getMaxStackSize() { + return maxStack; + } + // CraftBukkit end + + public InventoryEnderChest() { + super("container.enderchest", false, 27); + } + + public void a(TileEntityEnderChest tileentityenderchest) { + this.a = tileentityenderchest; + } + + public void a(NBTTagList nbttaglist) { + int i; + + for (i = 0; i < this.getSize(); ++i) { + this.setItem(i,null); + } + + for (i = 0; i < nbttaglist.size(); ++i) { + NBTTagCompound nbttagcompound = nbttaglist.get(i); + int j = nbttagcompound.getByte("Slot") & 255; + + if (j < this.getSize()) { + this.setItem(j, ItemStack.createStack(nbttagcompound)); + } + } + + } + + public NBTTagList h() { + NBTTagList nbttaglist = new NBTTagList(); + + for (int i = 0; i < this.getSize(); ++i) { + ItemStack itemstack = this.getItem(i); + + if (itemstack != null) { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + + nbttagcompound.setByte("Slot", (byte) i); + itemstack.save(nbttagcompound); + nbttaglist.add(nbttagcompound); + } + } + + return nbttaglist; + } + + public boolean a(EntityHuman entityhuman) { + return (this.a == null || this.a.a(entityhuman)) && super.a(entityhuman); + } + + public void startOpen(EntityHuman entityhuman) { + if (this.a != null) { + this.a.b(); + } + + super.startOpen(entityhuman); + } + + public void closeContainer(EntityHuman entityhuman) { + if (this.a != null) { + this.a.d(); + } + + super.closeContainer(entityhuman); + this.a = null; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/InventoryHorseChest.java b/azurite-server/src/main/java/net/minecraft/server/InventoryHorseChest.java new file mode 100644 index 0000000..f73c3d1 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/InventoryHorseChest.java @@ -0,0 +1,62 @@ +package net.minecraft.server; + +// CraftBukkit start + +import org.bukkit.craftbukkit.entity.CraftHumanEntity; +import org.bukkit.entity.HumanEntity; + +import java.util.List; +// CraftBukkit end + +public class InventoryHorseChest extends InventorySubcontainer { + + public InventoryHorseChest(String s, int i) { + super(s, false, i); + } + + // CraftBukkit start - add fields and methods + public List transaction = new java.util.ArrayList<>(); + private EntityHorse horse; + private int maxStack = MAX_STACK; + + public InventoryHorseChest(String s, int i, EntityHorse horse) { + super(s, false, i, (org.bukkit.craftbukkit.entity.CraftHorse) horse.getBukkitEntity()); + this.horse = horse; + } + + @Override + public ItemStack[] getContents() { + return this.items; + } + + @Override + public void onOpen(CraftHumanEntity who) { + transaction.add(who); + } + + @Override + public void onClose(CraftHumanEntity who) { + transaction.remove(who); + } + + @Override + public List getViewers() { + return transaction; + } + + @Override + public org.bukkit.inventory.InventoryHolder getOwner() { + return (org.bukkit.entity.Horse) this.horse.getBukkitEntity(); + } + + @Override + public void setMaxStackSize(int size) { + maxStack = size; + } + + @Override + public int getMaxStackSize() { + return maxStack; + } + // CraftBukkit end +} diff --git a/azurite-server/src/main/java/net/minecraft/server/InventoryLargeChest.java b/azurite-server/src/main/java/net/minecraft/server/InventoryLargeChest.java new file mode 100644 index 0000000..6eea5a2 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/InventoryLargeChest.java @@ -0,0 +1,177 @@ +package net.minecraft.server; + +// CraftBukkit start + +import org.bukkit.craftbukkit.entity.CraftHumanEntity; +import org.bukkit.entity.HumanEntity; + +import java.util.List; +// CraftBukkit end + +public class InventoryLargeChest implements ITileInventory { + + private final String a; + public ITileInventory left; + public ITileInventory right; + + // CraftBukkit start - add fields and methods + public List transaction = new java.util.ArrayList<>(); + + public ItemStack[] getContents() { + ItemStack[] result = new ItemStack[this.getSize()]; + for (int i = 0; i < result.length; i++) { + result[i] = this.getItem(i); + } + return result; + } + + public void onOpen(CraftHumanEntity who) { + this.left.onOpen(who); + this.right.onOpen(who); + transaction.add(who); + } + + public void onClose(CraftHumanEntity who) { + this.left.onClose(who); + this.right.onClose(who); + transaction.remove(who); + } + + public List getViewers() { + return transaction; + } + + public org.bukkit.inventory.InventoryHolder getOwner() { + return null; // This method won't be called since CraftInventoryDoubleChest doesn't defer to here + } + + public void setMaxStackSize(int size) { + this.left.setMaxStackSize(size); + this.right.setMaxStackSize(size); + } + // CraftBukkit end + + public InventoryLargeChest(String s, ITileInventory itileinventory, ITileInventory itileinventory1) { + this.a = s; + if (itileinventory == null) { + itileinventory = itileinventory1; + } + + if (itileinventory1 == null) { + itileinventory1 = itileinventory; + } + + this.left = itileinventory; + this.right = itileinventory1; + if (itileinventory.r_()) { + itileinventory1.a(itileinventory.i()); + } else if (itileinventory1.r_()) { + itileinventory.a(itileinventory1.i()); + } + + } + + public int getSize() { + return this.left.getSize() + this.right.getSize(); + } + + public boolean a(IInventory iinventory) { + return this.left == iinventory || this.right == iinventory; + } + + public String getName() { + return this.left.hasCustomName() ? this.left.getName() : (this.right.hasCustomName() ? this.right.getName() : this.a); + } + + public boolean hasCustomName() { + return this.left.hasCustomName() || this.right.hasCustomName(); + } + + public IChatBaseComponent getScoreboardDisplayName() { + return (this.hasCustomName() ? new ChatComponentText(this.getName()) : new ChatMessage(this.getName())); + } + + public ItemStack getItem(int i) { + return i >= this.left.getSize() ? this.right.getItem(i - this.left.getSize()) : this.left.getItem(i); + } + + public ItemStack splitStack(int i, int j) { + return i >= this.left.getSize() ? this.right.splitStack(i - this.left.getSize(), j) : this.left.splitStack(i, j); + } + + public ItemStack splitWithoutUpdate(int i) { + return i >= this.left.getSize() ? this.right.splitWithoutUpdate(i - this.left.getSize()) : this.left.splitWithoutUpdate(i); + } + + public void setItem(int i, ItemStack itemstack) { + if (i >= this.left.getSize()) { + this.right.setItem(i - this.left.getSize(), itemstack); + } else { + this.left.setItem(i, itemstack); + } + + } + + public int getMaxStackSize() { + return Math.min(this.left.getMaxStackSize(), this.right.getMaxStackSize()); // CraftBukkit - check both sides + } + + public void update() { + this.left.update(); + this.right.update(); + } + + public boolean a(EntityHuman entityhuman) { + return this.left.a(entityhuman) && this.right.a(entityhuman); + } + + public void startOpen(EntityHuman entityhuman) { + this.left.startOpen(entityhuman); + this.right.startOpen(entityhuman); + } + + public void closeContainer(EntityHuman entityhuman) { + this.left.closeContainer(entityhuman); + this.right.closeContainer(entityhuman); + } + + public boolean b(int i, ItemStack itemstack) { + return true; + } + + public int getProperty(int i) { + return 0; + } + + public void b(int i, int j) {} + + public int g() { + return 0; + } + + public boolean r_() { + return this.left.r_() || this.right.r_(); + } + + public void a(ChestLock chestlock) { + this.left.a(chestlock); + this.right.a(chestlock); + } + + public ChestLock i() { + return this.left.i(); + } + + public String getContainerName() { + return this.left.getContainerName(); + } + + public Container createContainer(PlayerInventory playerinventory, EntityHuman entityhuman) { + return new ContainerChest(playerinventory, this, entityhuman); + } + + public void l() { + this.left.l(); + this.right.l(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/InventoryMerchant.java b/azurite-server/src/main/java/net/minecraft/server/InventoryMerchant.java new file mode 100644 index 0000000..30a68b6 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/InventoryMerchant.java @@ -0,0 +1,218 @@ +package net.minecraft.server; + +// CraftBukkit start + +import org.bukkit.craftbukkit.entity.CraftHumanEntity; +import org.bukkit.entity.HumanEntity; +import org.bukkit.inventory.InventoryHolder; + +import java.util.Arrays; +import java.util.List; +// CraftBukkit end + +public class InventoryMerchant implements IInventory { + + private final IMerchant merchant; + private final ItemStack[] itemsInSlots = new ItemStack[3]; + private final EntityHuman player; + private MerchantRecipe recipe; + private int e; + + // CraftBukkit start - add fields and methods + public List transaction = new java.util.ArrayList<>(); + private int maxStack = MAX_STACK; + + public ItemStack[] getContents() { + return this.itemsInSlots; + } + + public void onOpen(CraftHumanEntity who) { + transaction.add(who); + } + + public void onClose(CraftHumanEntity who) { + transaction.remove(who); + } + + public List getViewers() { + return transaction; + } + + public void setMaxStackSize(int i) { + maxStack = i; + } + + public InventoryHolder getOwner() { + if (!(this.merchant instanceof EntityVillager)) + return this.merchant.v_().getBukkitEntity(); + return (InventoryHolder)((EntityVillager)this.merchant).getBukkitEntity(); + } + // CraftBukkit end + + public InventoryMerchant(EntityHuman entityhuman, IMerchant imerchant) { + this.player = entityhuman; + this.merchant = imerchant; + } + + public int getSize() { + return this.itemsInSlots.length; + } + + public ItemStack getItem(int i) { + return this.itemsInSlots[i]; + } + + public ItemStack splitStack(int i, int j) { + if (this.itemsInSlots[i] != null) { + ItemStack itemstack; + + if (i == 2) { + itemstack = this.itemsInSlots[i]; + this.itemsInSlots[i] = null; + return itemstack; + } else if (this.itemsInSlots[i].count <= j) { + itemstack = this.itemsInSlots[i]; + this.itemsInSlots[i] = null; + if (this.e(i)) { + this.h(); + } + + return itemstack; + } else { + itemstack = this.itemsInSlots[i].cloneAndSubtract(j); + if (this.itemsInSlots[i].count == 0) { + this.itemsInSlots[i] = null; + } + + if (this.e(i)) { + this.h(); + } + + return itemstack; + } + } else { + return null; + } + } + + private boolean e(int i) { + return i == 0 || i == 1; + } + + public ItemStack splitWithoutUpdate(int i) { + if (this.itemsInSlots[i] != null) { + ItemStack itemstack = this.itemsInSlots[i]; + + this.itemsInSlots[i] = null; + return itemstack; + } else { + return null; + } + } + + public void setItem(int i, ItemStack itemstack) { + this.itemsInSlots[i] = itemstack; + if (itemstack != null && itemstack.count > this.getMaxStackSize()) { + itemstack.count = this.getMaxStackSize(); + } + + if (this.e(i)) { + this.h(); + } + + } + + public String getName() { + return "mob.villager"; + } + + public boolean hasCustomName() { + return false; + } + + public IChatBaseComponent getScoreboardDisplayName() { + return (this.hasCustomName() ? new ChatComponentText(this.getName()) : new ChatMessage(this.getName())); + } + + public int getMaxStackSize() { + return maxStack; // CraftBukkit + } + + public boolean a(EntityHuman entityhuman) { + return this.merchant.v_() == entityhuman; + } + + public void startOpen(EntityHuman entityhuman) {} + + public void closeContainer(EntityHuman entityhuman) {} + + public boolean b(int i, ItemStack itemstack) { + return true; + } + + public void update() { + this.h(); + } + + public void h() { + this.recipe = null; + ItemStack itemstack = this.itemsInSlots[0]; + ItemStack itemstack1 = this.itemsInSlots[1]; + + if (itemstack == null) { + itemstack = itemstack1; + itemstack1 = null; + } + + if (itemstack == null) { + this.setItem(2, null); + } else { + MerchantRecipeList merchantrecipelist = this.merchant.getOffers(this.player); + + if (merchantrecipelist != null) { + MerchantRecipe merchantrecipe = merchantrecipelist.a(itemstack, itemstack1, this.e); + + if (merchantrecipe != null && !merchantrecipe.h()) { + this.recipe = merchantrecipe; + this.setItem(2, merchantrecipe.getBuyItem3().cloneItemStack()); + } else if (itemstack1 != null) { + merchantrecipe = merchantrecipelist.a(itemstack1, itemstack, this.e); + if (merchantrecipe != null && !merchantrecipe.h()) { + this.recipe = merchantrecipe; + this.setItem(2, merchantrecipe.getBuyItem3().cloneItemStack()); + } else { + this.setItem(2, null); + } + } else { + this.setItem(2, null); + } + } + } + + this.merchant.a_(this.getItem(2)); + } + + public MerchantRecipe getRecipe() { + return this.recipe; + } + + public void d(int i) { + this.e = i; + this.h(); + } + + public int getProperty(int i) { + return 0; + } + + public void b(int i, int j) {} + + public int g() { + return 0; + } + + public void l() { + Arrays.fill(this.itemsInSlots, null); + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/InventorySubcontainer.java b/azurite-server/src/main/java/net/minecraft/server/InventorySubcontainer.java new file mode 100644 index 0000000..8f5c915 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/InventorySubcontainer.java @@ -0,0 +1,207 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; +import org.bukkit.craftbukkit.entity.CraftHumanEntity; +import org.bukkit.entity.HumanEntity; + +import java.util.Arrays; +import java.util.List; +// CraftBukkit end + +public class InventorySubcontainer implements IInventory { + + private String a; + private final int b; + public ItemStack[] items; + private List d; + private boolean e; + + // CraftBukkit start - add fields and methods + public List transaction = new java.util.ArrayList<>(); + protected org.bukkit.inventory.InventoryHolder bukkitOwner; + + public ItemStack[] getContents() { + return this.items; + } + + public void onOpen(CraftHumanEntity who) { + transaction.add(who); + } + + public void onClose(CraftHumanEntity who) { + transaction.remove(who); + } + + public List getViewers() { + return transaction; + } + + public void setMaxStackSize(int i) { + } + + public org.bukkit.inventory.InventoryHolder getOwner() { + return bukkitOwner; + } + + public InventorySubcontainer(String s, boolean flag, int i) { + this(s, flag, i, null); + } + + public InventorySubcontainer(String s, boolean flag, int i, org.bukkit.inventory.InventoryHolder owner) { // Added argument + this.bukkitOwner = owner; + // CraftBukkit end + this.a = s; + this.e = flag; + this.b = i; + this.items = new ItemStack[i]; + } + + public void a(IInventoryListener iinventorylistener) { + if (this.d == null) { + this.d = Lists.newArrayList(); + } + + this.d.add(iinventorylistener); + } + + public void b(IInventoryListener iinventorylistener) { + this.d.remove(iinventorylistener); + } + + public ItemStack getItem(int i) { + return i >= 0 && i < this.items.length ? this.items[i] : null; + } + + public ItemStack splitStack(int i, int j) { + ItemStack itemstack = items[i]; + + if (itemstack != null) { + if (itemstack.count <= j) { + this.items[i] = null; + } else { + if (itemstack.count == 0) { + this.items[i] = null; + } + itemstack = itemstack.cloneAndSubtract(j); + } + this.update(); + return itemstack; + } else { + return null; + } + } + + public ItemStack a(ItemStack itemstack) { + ItemStack itemstack1 = itemstack.cloneItemStack(); + + for (int i = 0; i < this.b; ++i) { + ItemStack itemstack2 = this.getItem(i); + + if (itemstack2 == null) { + this.setItem(i, itemstack1); + this.update(); + return null; + } + + if (ItemStack.c(itemstack2, itemstack1)) { + int j = Math.min(this.getMaxStackSize(), itemstack2.getMaxStackSize()); + int k = Math.min(itemstack1.count, j - itemstack2.count); + + if (k > 0) { + itemstack2.count += k; + itemstack1.count -= k; + if (itemstack1.count <= 0) { + this.update(); + return null; + } + } + } + } + + if (itemstack1.count != itemstack.count) { + this.update(); + } + + return itemstack1; + } + + public ItemStack splitWithoutUpdate(int i) { + ItemStack itemstack = this.items[i]; + + if (itemstack != null) { + this.items[i] = null; + return itemstack; + } else { + return null; + } + } + + public void setItem(int i, ItemStack itemstack) { + this.items[i] = itemstack; + if (itemstack != null && itemstack.count > this.getMaxStackSize()) { + itemstack.count = this.getMaxStackSize(); + } + + this.update(); + } + + public int getSize() { + return this.b; + } + + public String getName() { + return this.a; + } + + public boolean hasCustomName() { + return this.e; + } + + public void a(String s) { + this.e = true; + this.a = s; + } + + public IChatBaseComponent getScoreboardDisplayName() { + return this.hasCustomName() ? new ChatComponentText(this.getName()) : new ChatMessage(this.getName()); + } + + public int getMaxStackSize() { + return 64; + } + + public void update() { + if (this.d != null) { + for (IInventoryListener iInventoryListener : this.d) { + iInventoryListener.a(this); + } + } + + } + + public boolean a(EntityHuman entityhuman) { + return true; + } + + public void startOpen(EntityHuman entityhuman) {} + + public void closeContainer(EntityHuman entityhuman) {} + + public boolean b(int i, ItemStack itemstack) { + return true; + } + + public int getProperty(int i) { + return 0; + } + + public void b(int i, int j) {} + + public int g() { + return 0; + } + + public void l() { + Arrays.fill(this.items, null); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/InventoryUtils.java b/azurite-server/src/main/java/net/minecraft/server/InventoryUtils.java new file mode 100644 index 0000000..55ab12f --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/InventoryUtils.java @@ -0,0 +1,56 @@ +package net.minecraft.server; + +import java.util.Random; + +public class InventoryUtils { + + private static final Random a = new Random(); + + public static void dropInventory(World world, BlockPosition blockposition, IInventory iinventory) { + dropInventory(world, (double) blockposition.getX(), (double) blockposition.getY(), (double) blockposition.getZ(), iinventory); + } + + public static void dropEntity(World world, Entity entity, IInventory iinventory) { + dropInventory(world, entity.locX, entity.locY, entity.locZ, iinventory); + } + + private static void dropInventory(World world, double d0, double d1, double d2, IInventory iinventory) { + for (int i = 0; i < iinventory.getSize(); ++i) { + ItemStack itemstack = iinventory.getItem(i); + + if (itemstack != null) { + dropItem(world, d0, d1, d2, itemstack); + } + } + + } + + private static void dropItem(World world, double d0, double d1, double d2, ItemStack itemstack) { + float f = InventoryUtils.a.nextFloat() * 0.8F + 0.1F; + float f1 = InventoryUtils.a.nextFloat() * 0.8F + 0.1F; + float f2 = InventoryUtils.a.nextFloat() * 0.8F + 0.1F; + + while (itemstack.count > 0) { + int i = InventoryUtils.a.nextInt(21) + 10; + + if (i > itemstack.count) { + i = itemstack.count; + } + + itemstack.count -= i; + EntityItem entityitem = new EntityItem(world, d0 + (double) f, d1 + (double) f1, d2 + (double) f2, new ItemStack(itemstack.getItem(), i, itemstack.getData())); + + if (itemstack.hasTag()) { + entityitem.getItemStack().setTag((NBTTagCompound) itemstack.getTag().clone()); + } + + float f3 = 0.05F; + + entityitem.motX = InventoryUtils.a.nextGaussian() * (double) f3; + entityitem.motY = InventoryUtils.a.nextGaussian() * (double) f3 + 0.20000000298023224D; + entityitem.motZ = InventoryUtils.a.nextGaussian() * (double) f3; + world.addEntity(entityitem); + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/IpBanEntry.java b/azurite-server/src/main/java/net/minecraft/server/IpBanEntry.java new file mode 100644 index 0000000..a9781bc --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/IpBanEntry.java @@ -0,0 +1,30 @@ +package net.minecraft.server; + +import com.google.gson.JsonObject; +import java.util.Date; + +public class IpBanEntry extends ExpirableListEntry { + + public IpBanEntry(String s) { + this(s, (Date) null, (String) null, (Date) null, (String) null); + } + + public IpBanEntry(String s, Date date, String s1, Date date1, String s2) { + super(s, date, s1, date1, s2); + } + + public IpBanEntry(JsonObject jsonobject) { + super(b(jsonobject), jsonobject); + } + + private static String b(JsonObject jsonobject) { + return jsonobject.has("ip") ? jsonobject.get("ip").getAsString() : null; + } + + protected void a(JsonObject jsonobject) { + if (this.getKey() != null) { + jsonobject.addProperty("ip", (String) this.getKey()); + super.a(jsonobject); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/IpBanList.java b/azurite-server/src/main/java/net/minecraft/server/IpBanList.java new file mode 100644 index 0000000..e91b964 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/IpBanList.java @@ -0,0 +1,42 @@ +package net.minecraft.server; + +import com.google.gson.JsonObject; +import java.io.File; +import java.net.SocketAddress; + +public class IpBanList extends JsonList { + + public IpBanList(File file) { + super(file); + } + + protected JsonListEntry a(JsonObject jsonobject) { + return new IpBanEntry(jsonobject); + } + + public boolean isBanned(SocketAddress socketaddress) { + String s = this.c(socketaddress); + + return this.d(s); + } + + public IpBanEntry get(SocketAddress socketaddress) { + String s = this.c(socketaddress); + + return this.get(s); + } + + private String c(SocketAddress socketaddress) { + String s = socketaddress.toString(); + + if (s.contains("/")) { + s = s.substring(s.indexOf(47) + 1); + } + + if (s.contains(":")) { + s = s.substring(0, s.indexOf(58)); + } + + return s; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/Item.java b/azurite-server/src/main/java/net/minecraft/server/Item.java new file mode 100644 index 0000000..b450232 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/Item.java @@ -0,0 +1,791 @@ +package net.minecraft.server; + +import com.eatthepath.uuid.FastUUID; +import com.google.common.base.Function; +import com.google.common.collect.HashMultimap; +import com.google.common.collect.Maps; +import com.google.common.collect.Multimap; +import dev.azurite.spigot.configs.AzuriteConfig; + +import java.util.Map; +import java.util.Random; +import java.util.UUID; + +public class Item { + + public static final RegistryMaterials REGISTRY = new RegistryMaterials<>(); + protected static final UUID f = FastUUID.parseUUID("CB3F55D3-645C-4F38-A497-9C13A33DB5CF"); + private static final Map a = Maps.newHashMap(); + protected static Random g = new Random(); + protected int maxStackSize = 64; + protected boolean i; + protected boolean j; + public int durability; // Beanes - make public for fake durability + private Item craftingResult; + private String k; + private String name; + + public Item() { + } + + public static int getId(Item item) { + return item == null ? 0 : Item.REGISTRY.b(item); + } + + public static Item getById(int i) { + return Item.REGISTRY.a(i); + } + + public static Item getItemOf(Block block) { + return Item.a.get(block); + } + + public static Item d(String s) { + Item item = Item.REGISTRY.get(new MinecraftKey(s)); + + if (item == null) { + try { + return getById(Integer.parseInt(s)); + } catch (NumberFormatException ignored) { + } + } + + return item; + } + + public static void t() { + a(Blocks.STONE, (new ItemMultiTexture(Blocks.STONE, Blocks.STONE, new Function() { + public String a(ItemStack itemstack) { + return BlockStone.EnumStoneVariant.a(itemstack.getData()).d(); + } + + public Object apply(Object object) { + return this.a((ItemStack) object); + } + })).b("stone")); + a(Blocks.GRASS, (new ItemWithAuxData(Blocks.GRASS, false))); + a(Blocks.DIRT, (new ItemMultiTexture(Blocks.DIRT, Blocks.DIRT, new Function() { + public String a(ItemStack itemstack) { + return BlockDirt.EnumDirtVariant.a(itemstack.getData()).c(); + } + + public Object apply(Object object) { + return this.a((ItemStack) object); + } + })).b("dirt")); + c(Blocks.COBBLESTONE); + a(Blocks.PLANKS, (new ItemMultiTexture(Blocks.PLANKS, Blocks.PLANKS, new Function() { + public String a(ItemStack itemstack) { + return BlockWood.EnumLogVariant.a(itemstack.getData()).d(); + } + + public Object apply(Object object) { + return this.a((ItemStack) object); + } + })).b("wood")); + a(Blocks.SAPLING, (new ItemMultiTexture(Blocks.SAPLING, Blocks.SAPLING, new Function() { + public String a(ItemStack itemstack) { + return BlockWood.EnumLogVariant.a(itemstack.getData()).d(); + } + + public Object apply(Object object) { + return this.a((ItemStack) object); + } + })).b("sapling")); + c(Blocks.BEDROCK); + a(Blocks.SAND, (new ItemMultiTexture(Blocks.SAND, Blocks.SAND, new Function() { + public String a(ItemStack itemstack) { + return BlockSand.EnumSandVariant.a(itemstack.getData()).d(); + } + + public Object apply(Object object) { + return this.a((ItemStack) object); + } + })).b("sand")); + c(Blocks.GRAVEL); + c(Blocks.GOLD_ORE); + c(Blocks.IRON_ORE); + c(Blocks.COAL_ORE); + a(Blocks.LOG, (new ItemMultiTexture(Blocks.LOG, Blocks.LOG, new Function() { + public String a(ItemStack itemstack) { + return BlockWood.EnumLogVariant.a(itemstack.getData()).d(); + } + + public Object apply(Object object) { + return this.a((ItemStack) object); + } + })).b("log")); + a(Blocks.LOG2, (new ItemMultiTexture(Blocks.LOG2, Blocks.LOG2, new Function() { + public String a(ItemStack itemstack) { + return BlockWood.EnumLogVariant.a(itemstack.getData() + 4).d(); + } + + public Object apply(Object object) { + return this.a((ItemStack) object); + } + })).b("log")); + a(Blocks.LEAVES, (new ItemLeaves(Blocks.LEAVES)).b("leaves")); + a(Blocks.LEAVES2, (new ItemLeaves(Blocks.LEAVES2)).b("leaves")); + a(Blocks.SPONGE, (new ItemMultiTexture(Blocks.SPONGE, Blocks.SPONGE, new Function() { + public String a(ItemStack itemstack) { + return (itemstack.getData() & 1) == 1 ? "wet" : "dry"; + } + + public Object apply(Object object) { + return this.a((ItemStack) object); + } + })).b("sponge")); + c(Blocks.GLASS); + c(Blocks.LAPIS_ORE); + c(Blocks.LAPIS_BLOCK); + c(Blocks.DISPENSER); + a(Blocks.SANDSTONE, (new ItemMultiTexture(Blocks.SANDSTONE, Blocks.SANDSTONE, new Function() { + public String a(ItemStack itemstack) { + return BlockSandStone.EnumSandstoneVariant.a(itemstack.getData()).c(); + } + + public Object apply(Object object) { + return this.a((ItemStack) object); + } + })).b("sandStone")); + c(Blocks.NOTEBLOCK); + c(Blocks.GOLDEN_RAIL); + c(Blocks.DETECTOR_RAIL); + a(Blocks.STICKY_PISTON, (new ItemPiston(Blocks.STICKY_PISTON))); + c(Blocks.WEB); + a(Blocks.TALLGRASS, (new ItemWithAuxData(Blocks.TALLGRASS, true)).a(new String[]{"shrub", "grass", "fern"})); + c(Blocks.DEADBUSH); + a(Blocks.PISTON, (new ItemPiston(Blocks.PISTON))); + a(Blocks.WOOL, (new ItemCloth(Blocks.WOOL)).b("cloth")); + a(Blocks.YELLOW_FLOWER, (new ItemMultiTexture(Blocks.YELLOW_FLOWER, Blocks.YELLOW_FLOWER, new Function() { + public String a(ItemStack itemstack) { + return BlockFlowers.EnumFlowerVarient.a(BlockFlowers.EnumFlowerType.YELLOW, itemstack.getData()).d(); + } + + public Object apply(Object object) { + return this.a((ItemStack) object); + } + })).b("flower")); + a(Blocks.RED_FLOWER, (new ItemMultiTexture(Blocks.RED_FLOWER, Blocks.RED_FLOWER, new Function() { + public String a(ItemStack itemstack) { + return BlockFlowers.EnumFlowerVarient.a(BlockFlowers.EnumFlowerType.RED, itemstack.getData()).d(); + } + + public Object apply(Object object) { + return this.a((ItemStack) object); + } + })).b("rose")); + c(Blocks.BROWN_MUSHROOM); + c(Blocks.RED_MUSHROOM); + c(Blocks.GOLD_BLOCK); + c(Blocks.IRON_BLOCK); + a(Blocks.STONE_SLAB, (new ItemStep(Blocks.STONE_SLAB, Blocks.STONE_SLAB, Blocks.DOUBLE_STONE_SLAB)).b("stoneSlab")); + c(Blocks.BRICK_BLOCK); + c(Blocks.TNT); + c(Blocks.BOOKSHELF); + c(Blocks.MOSSY_COBBLESTONE); + c(Blocks.OBSIDIAN); + c(Blocks.TORCH); + c(Blocks.MOB_SPAWNER); + c(Blocks.OAK_STAIRS); + c(Blocks.CHEST); + c(Blocks.DIAMOND_ORE); + c(Blocks.DIAMOND_BLOCK); + c(Blocks.CRAFTING_TABLE); + c(Blocks.FARMLAND); + c(Blocks.FURNACE); + c(Blocks.LIT_FURNACE); + c(Blocks.LADDER); + c(Blocks.RAIL); + c(Blocks.STONE_STAIRS); + c(Blocks.LEVER); + c(Blocks.STONE_PRESSURE_PLATE); + c(Blocks.WOODEN_PRESSURE_PLATE); + c(Blocks.REDSTONE_ORE); + c(Blocks.REDSTONE_TORCH); + c(Blocks.STONE_BUTTON); + a(Blocks.SNOW_LAYER, (new ItemSnow(Blocks.SNOW_LAYER))); + c(Blocks.ICE); + c(Blocks.SNOW); + c(Blocks.CACTUS); + c(Blocks.CLAY); + c(Blocks.JUKEBOX); + c(Blocks.FENCE); + c(Blocks.SPRUCE_FENCE); + c(Blocks.BIRCH_FENCE); + c(Blocks.JUNGLE_FENCE); + c(Blocks.DARK_OAK_FENCE); + c(Blocks.ACACIA_FENCE); + c(Blocks.PUMPKIN); + c(Blocks.NETHERRACK); + c(Blocks.SOUL_SAND); + c(Blocks.GLOWSTONE); + c(Blocks.LIT_PUMPKIN); + c(Blocks.TRAPDOOR); + a(Blocks.MONSTER_EGG, (new ItemMultiTexture(Blocks.MONSTER_EGG, Blocks.MONSTER_EGG, new Function() { + public String a(ItemStack itemstack) { + return BlockMonsterEggs.EnumMonsterEggVarient.a(itemstack.getData()).c(); + } + + public Object apply(Object object) { + return this.a((ItemStack) object); + } + })).b("monsterStoneEgg")); + a(Blocks.STONEBRICK, (new ItemMultiTexture(Blocks.STONEBRICK, Blocks.STONEBRICK, new Function() { + public String a(ItemStack itemstack) { + return BlockSmoothBrick.EnumStonebrickType.a(itemstack.getData()).c(); + } + + public Object apply(Object object) { + return this.a((ItemStack) object); + } + })).b("stonebricksmooth")); + c(Blocks.BROWN_MUSHROOM_BLOCK); + c(Blocks.RED_MUSHROOM_BLOCK); + c(Blocks.IRON_BARS); + c(Blocks.GLASS_PANE); + c(Blocks.MELON_BLOCK); + a(Blocks.VINE, (new ItemWithAuxData(Blocks.VINE, false))); + c(Blocks.FENCE_GATE); + c(Blocks.SPRUCE_FENCE_GATE); + c(Blocks.BIRCH_FENCE_GATE); + c(Blocks.JUNGLE_FENCE_GATE); + c(Blocks.DARK_OAK_FENCE_GATE); + c(Blocks.ACACIA_FENCE_GATE); + c(Blocks.BRICK_STAIRS); + c(Blocks.STONE_BRICK_STAIRS); + c(Blocks.MYCELIUM); + a(Blocks.WATERLILY, (new ItemWaterLily(Blocks.WATERLILY))); + c(Blocks.NETHER_BRICK); + c(Blocks.NETHER_BRICK_FENCE); + c(Blocks.NETHER_BRICK_STAIRS); + c(Blocks.ENCHANTING_TABLE); + c(Blocks.END_PORTAL_FRAME); + c(Blocks.END_STONE); + c(Blocks.DRAGON_EGG); + c(Blocks.REDSTONE_LAMP); + a(Blocks.WOODEN_SLAB, (new ItemStep(Blocks.WOODEN_SLAB, Blocks.WOODEN_SLAB, Blocks.DOUBLE_WOODEN_SLAB)).b("woodSlab")); + c(Blocks.SANDSTONE_STAIRS); + c(Blocks.EMERALD_ORE); + c(Blocks.ENDER_CHEST); + c(Blocks.TRIPWIRE_HOOK); + c(Blocks.EMERALD_BLOCK); + c(Blocks.SPRUCE_STAIRS); + c(Blocks.BIRCH_STAIRS); + c(Blocks.JUNGLE_STAIRS); + c(Blocks.COMMAND_BLOCK); + c(Blocks.BEACON); + a(Blocks.COBBLESTONE_WALL, (new ItemMultiTexture(Blocks.COBBLESTONE_WALL, Blocks.COBBLESTONE_WALL, new Function() { + public String a(ItemStack itemstack) { + return BlockCobbleWall.EnumCobbleVariant.a(itemstack.getData()).c(); + } + + public Object apply(Object object) { + return this.a((ItemStack) object); + } + })).b("cobbleWall")); + c(Blocks.WOODEN_BUTTON); + a(Blocks.ANVIL, (new ItemAnvil(Blocks.ANVIL)).b("anvil")); + c(Blocks.TRAPPED_CHEST); + c(Blocks.LIGHT_WEIGHTED_PRESSURE_PLATE); + c(Blocks.HEAVY_WEIGHTED_PRESSURE_PLATE); + c(Blocks.DAYLIGHT_DETECTOR); + c(Blocks.REDSTONE_BLOCK); + c(Blocks.QUARTZ_ORE); + c(Blocks.HOPPER); + a(Blocks.QUARTZ_BLOCK, (new ItemMultiTexture(Blocks.QUARTZ_BLOCK, Blocks.QUARTZ_BLOCK, new String[]{"default", "chiseled", "lines"})).b("quartzBlock")); + c(Blocks.QUARTZ_STAIRS); + c(Blocks.ACTIVATOR_RAIL); + c(Blocks.DROPPER); + a(Blocks.STAINED_HARDENED_CLAY, (new ItemCloth(Blocks.STAINED_HARDENED_CLAY)).b("clayHardenedStained")); + c(Blocks.BARRIER); + c(Blocks.IRON_TRAPDOOR); + c(Blocks.HAY_BLOCK); + a(Blocks.CARPET, (new ItemCloth(Blocks.CARPET)).b("woolCarpet")); + c(Blocks.HARDENED_CLAY); + c(Blocks.COAL_BLOCK); + c(Blocks.PACKED_ICE); + c(Blocks.ACACIA_STAIRS); + c(Blocks.DARK_OAK_STAIRS); + c(Blocks.SLIME); + a(Blocks.DOUBLE_PLANT, (new ItemTallPlant(Blocks.DOUBLE_PLANT, Blocks.DOUBLE_PLANT, new Function() { + public String a(ItemStack itemstack) { + return BlockTallPlant.EnumTallFlowerVariants.a(itemstack.getData()).c(); + } + + public Object apply(Object object) { + return this.a((ItemStack) object); + } + })).b("doublePlant")); + a(Blocks.STAINED_GLASS, (new ItemCloth(Blocks.STAINED_GLASS)).b("stainedGlass")); + a(Blocks.STAINED_GLASS_PANE, (new ItemCloth(Blocks.STAINED_GLASS_PANE)).b("stainedGlassPane")); + a(Blocks.PRISMARINE, (new ItemMultiTexture(Blocks.PRISMARINE, Blocks.PRISMARINE, new Function() { + public String a(ItemStack itemstack) { + return BlockPrismarine.EnumPrismarineVariant.a(itemstack.getData()).c(); + } + + public Object apply(Object object) { + return this.a((ItemStack) object); + } + })).b("prismarine")); + c(Blocks.SEA_LANTERN); + a(Blocks.RED_SANDSTONE, (new ItemMultiTexture(Blocks.RED_SANDSTONE, Blocks.RED_SANDSTONE, new Function() { + public String a(ItemStack itemstack) { + return BlockRedSandstone.EnumRedSandstoneVariant.a(itemstack.getData()).c(); + } + + public Object apply(Object object) { + return this.a((ItemStack) object); + } + })).b("redSandStone")); + c(Blocks.RED_SANDSTONE_STAIRS); + a(Blocks.STONE_SLAB2, (new ItemStep(Blocks.STONE_SLAB2, Blocks.STONE_SLAB2, Blocks.DOUBLE_STONE_SLAB2)).b("stoneSlab2")); + a(256, "iron_shovel", (new ItemSpade(Item.EnumToolMaterial.IRON)).c("shovelIron")); + a(257, "iron_pickaxe", (new ItemPickaxe(Item.EnumToolMaterial.IRON)).c("pickaxeIron")); + a(258, "iron_axe", (new ItemAxe(Item.EnumToolMaterial.IRON)).c("hatchetIron")); + a(259, "flint_and_steel", (new ItemFlintAndSteel()).c("flintAndSteel")); + a(260, "apple", (new ItemFood(4, 0.3F, false)).c("apple")); + a(261, "bow", (new ItemBow()).c("bow")); + a(262, "arrow", (new Item()).c("arrow").a(CreativeModeTab.j)); + a(263, "coal", (new ItemCoal()).c("coal")); + a(264, "diamond", (new Item()).c("diamond").a(CreativeModeTab.l)); + a(265, "iron_ingot", (new Item()).c("ingotIron").a(CreativeModeTab.l)); + a(266, "gold_ingot", (new Item()).c("ingotGold").a(CreativeModeTab.l)); + a(267, "iron_sword", (new ItemSword(Item.EnumToolMaterial.IRON)).c("swordIron")); + a(268, "wooden_sword", (new ItemSword(Item.EnumToolMaterial.WOOD)).c("swordWood")); + a(269, "wooden_shovel", (new ItemSpade(Item.EnumToolMaterial.WOOD)).c("shovelWood")); + a(270, "wooden_pickaxe", (new ItemPickaxe(Item.EnumToolMaterial.WOOD)).c("pickaxeWood")); + a(271, "wooden_axe", (new ItemAxe(Item.EnumToolMaterial.WOOD)).c("hatchetWood")); + a(272, "stone_sword", (new ItemSword(Item.EnumToolMaterial.STONE)).c("swordStone")); + a(273, "stone_shovel", (new ItemSpade(Item.EnumToolMaterial.STONE)).c("shovelStone")); + a(274, "stone_pickaxe", (new ItemPickaxe(Item.EnumToolMaterial.STONE)).c("pickaxeStone")); + a(275, "stone_axe", (new ItemAxe(Item.EnumToolMaterial.STONE)).c("hatchetStone")); + a(276, "diamond_sword", (new ItemSword(Item.EnumToolMaterial.EMERALD)).c("swordDiamond")); + a(277, "diamond_shovel", (new ItemSpade(Item.EnumToolMaterial.EMERALD)).c("shovelDiamond")); + a(278, "diamond_pickaxe", (new ItemPickaxe(Item.EnumToolMaterial.EMERALD)).c("pickaxeDiamond")); + a(279, "diamond_axe", (new ItemAxe(Item.EnumToolMaterial.EMERALD)).c("hatchetDiamond")); + a(280, "stick", (new Item()).n().c("stick").a(CreativeModeTab.l)); + a(281, "bowl", (new Item()).c("bowl").a(CreativeModeTab.l)); + a(282, "mushroom_stew", (new ItemSoup(6)).c("mushroomStew")); + a(283, "golden_sword", (new ItemSword(Item.EnumToolMaterial.GOLD)).c("swordGold")); + a(284, "golden_shovel", (new ItemSpade(Item.EnumToolMaterial.GOLD)).c("shovelGold")); + a(285, "golden_pickaxe", (new ItemPickaxe(Item.EnumToolMaterial.GOLD)).c("pickaxeGold")); + a(286, "golden_axe", (new ItemAxe(Item.EnumToolMaterial.GOLD)).c("hatchetGold")); + a(287, "string", (new ItemReed(Blocks.TRIPWIRE)).c("string").a(CreativeModeTab.l)); + a(288, "feather", (new Item()).c("feather").a(CreativeModeTab.l)); + a(289, "gunpowder", (new Item()).c("sulphur").e(PotionBrewer.k).a(CreativeModeTab.l)); + a(290, "wooden_hoe", (new ItemHoe(Item.EnumToolMaterial.WOOD)).c("hoeWood")); + a(291, "stone_hoe", (new ItemHoe(Item.EnumToolMaterial.STONE)).c("hoeStone")); + a(292, "iron_hoe", (new ItemHoe(Item.EnumToolMaterial.IRON)).c("hoeIron")); + a(293, "diamond_hoe", (new ItemHoe(Item.EnumToolMaterial.EMERALD)).c("hoeDiamond")); + a(294, "golden_hoe", (new ItemHoe(Item.EnumToolMaterial.GOLD)).c("hoeGold")); + a(295, "wheat_seeds", (new ItemSeeds(Blocks.WHEAT, Blocks.FARMLAND)).c("seeds")); + a(296, "wheat", (new Item()).c("wheat").a(CreativeModeTab.l)); + a(297, "bread", (new ItemFood(5, 0.6F, false)).c("bread")); + a(298, "leather_helmet", (new ItemArmor(ItemArmor.EnumArmorMaterial.LEATHER, 0, 0)).c("helmetCloth")); + a(299, "leather_chestplate", (new ItemArmor(ItemArmor.EnumArmorMaterial.LEATHER, 0, 1)).c("chestplateCloth")); + a(300, "leather_leggings", (new ItemArmor(ItemArmor.EnumArmorMaterial.LEATHER, 0, 2)).c("leggingsCloth")); + a(301, "leather_boots", (new ItemArmor(ItemArmor.EnumArmorMaterial.LEATHER, 0, 3)).c("bootsCloth")); + a(302, "chainmail_helmet", (new ItemArmor(ItemArmor.EnumArmorMaterial.CHAIN, 1, 0)).c("helmetChain")); + a(303, "chainmail_chestplate", (new ItemArmor(ItemArmor.EnumArmorMaterial.CHAIN, 1, 1)).c("chestplateChain")); + a(304, "chainmail_leggings", (new ItemArmor(ItemArmor.EnumArmorMaterial.CHAIN, 1, 2)).c("leggingsChain")); + a(305, "chainmail_boots", (new ItemArmor(ItemArmor.EnumArmorMaterial.CHAIN, 1, 3)).c("bootsChain")); + a(306, "iron_helmet", (new ItemArmor(ItemArmor.EnumArmorMaterial.IRON, 2, 0)).c("helmetIron")); + a(307, "iron_chestplate", (new ItemArmor(ItemArmor.EnumArmorMaterial.IRON, 2, 1)).c("chestplateIron")); + a(308, "iron_leggings", (new ItemArmor(ItemArmor.EnumArmorMaterial.IRON, 2, 2)).c("leggingsIron")); + a(309, "iron_boots", (new ItemArmor(ItemArmor.EnumArmorMaterial.IRON, 2, 3)).c("bootsIron")); + a(310, "diamond_helmet", (new ItemArmor(ItemArmor.EnumArmorMaterial.DIAMOND, 3, 0)).c("helmetDiamond")); + a(311, "diamond_chestplate", (new ItemArmor(ItemArmor.EnumArmorMaterial.DIAMOND, 3, 1)).c("chestplateDiamond")); + a(312, "diamond_leggings", (new ItemArmor(ItemArmor.EnumArmorMaterial.DIAMOND, 3, 2)).c("leggingsDiamond")); + a(313, "diamond_boots", (new ItemArmor(ItemArmor.EnumArmorMaterial.DIAMOND, 3, 3)).c("bootsDiamond")); + a(314, "golden_helmet", (new ItemArmor(ItemArmor.EnumArmorMaterial.GOLD, 4, 0)).c("helmetGold")); + a(315, "golden_chestplate", (new ItemArmor(ItemArmor.EnumArmorMaterial.GOLD, 4, 1)).c("chestplateGold")); + a(316, "golden_leggings", (new ItemArmor(ItemArmor.EnumArmorMaterial.GOLD, 4, 2)).c("leggingsGold")); + a(317, "golden_boots", (new ItemArmor(ItemArmor.EnumArmorMaterial.GOLD, 4, 3)).c("bootsGold")); + a(318, "flint", (new Item()).c("flint").a(CreativeModeTab.l)); + a(319, "porkchop", (new ItemFood(3, 0.3F, true)).c("porkchopRaw")); + a(320, "cooked_porkchop", (new ItemFood(8, 0.8F, true)).c("porkchopCooked")); + a(321, "painting", (new ItemHanging(EntityPainting.class)).c("painting")); + a(322, "golden_apple", (new ItemGoldenApple(4, 1.2F, false)).h().a(MobEffectList.REGENERATION.id, 5, 1, 1.0F).c("appleGold")); + a(323, "sign", (new ItemSign()).c("sign")); + a(324, "wooden_door", (new ItemDoor(Blocks.WOODEN_DOOR)).c("doorOak")); + Item item = (new ItemBucket(Blocks.AIR)).c("bucket").c(16); + + a(325, "bucket", item); + a(326, "water_bucket", (new ItemBucket(Blocks.FLOWING_WATER)).c("bucketWater").c(item)); + a(327, "lava_bucket", (new ItemBucket(Blocks.FLOWING_LAVA)).c("bucketLava").c(item)); + a(328, "minecart", (new ItemMinecart(EntityMinecartAbstract.EnumMinecartType.RIDEABLE)).c("minecart")); + a(329, "saddle", (new ItemSaddle()).c("saddle")); + a(330, "iron_door", (new ItemDoor(Blocks.IRON_DOOR)).c("doorIron")); + a(331, "redstone", (new ItemRedstone()).c("redstone").e(PotionBrewer.i)); + a(332, "snowball", (new ItemSnowball()).c("snowball")); + a(333, "boat", (new ItemBoat()).c("boat")); + a(334, "leather", (new Item()).c("leather").a(CreativeModeTab.l)); + a(335, "milk_bucket", (new ItemMilkBucket()).c("milk").c(item)); + a(336, "brick", (new Item()).c("brick").a(CreativeModeTab.l)); + a(337, "clay_ball", (new Item()).c("clay").a(CreativeModeTab.l)); + a(338, "reeds", (new ItemReed(Blocks.REEDS)).c("reeds").a(CreativeModeTab.l)); + a(339, "paper", (new Item()).c("paper").a(CreativeModeTab.f)); + a(340, "book", (new ItemBook()).c("book").a(CreativeModeTab.f)); + a(341, "slime_ball", (new Item()).c("slimeball").a(CreativeModeTab.f)); + a(342, "chest_minecart", (new ItemMinecart(EntityMinecartAbstract.EnumMinecartType.CHEST)).c("minecartChest")); + a(343, "furnace_minecart", (new ItemMinecart(EntityMinecartAbstract.EnumMinecartType.FURNACE)).c("minecartFurnace")); + a(344, "egg", (new ItemEgg()).c("egg")); + a(345, "compass", (new Item()).c("compass").a(CreativeModeTab.i)); + a(346, "fishing_rod", (new ItemFishingRod()).c("fishingRod")); + a(347, "clock", (new Item()).c("clock").a(CreativeModeTab.i)); + a(348, "glowstone_dust", (new Item()).c("yellowDust").e(PotionBrewer.j).a(CreativeModeTab.l)); + a(349, "fish", (new ItemFish(false)).c("fish").a(true)); + a(350, "cooked_fish", (new ItemFish(true)).c("fish").a(true)); + a(351, "dye", (new ItemDye()).c("dyePowder")); + a(352, "bone", (new Item()).c("bone").n().a(CreativeModeTab.f)); + a(353, "sugar", (new Item()).c("sugar").e(PotionBrewer.b).a(CreativeModeTab.l)); + a(354, "cake", (new ItemReed(Blocks.CAKE)).c(1).c("cake").a(CreativeModeTab.h)); + a(355, "bed", (new ItemBed()).c(1).c("bed")); + a(356, "repeater", (new ItemReed(Blocks.UNPOWERED_REPEATER)).c("diode").a(CreativeModeTab.d)); + a(357, "cookie", (new ItemFood(2, 0.1F, false)).c("cookie")); + a(358, "filled_map", (new ItemWorldMap()).c("map")); + a(359, "shears", (new ItemShears()).c("shears")); + a(360, "melon", (new ItemFood(2, 0.3F, false)).c("melon")); + a(361, "pumpkin_seeds", (new ItemSeeds(Blocks.PUMPKIN_STEM, Blocks.FARMLAND)).c("seeds_pumpkin")); + a(362, "melon_seeds", (new ItemSeeds(Blocks.MELON_STEM, Blocks.FARMLAND)).c("seeds_melon")); + a(363, "beef", (new ItemFood(3, 0.3F, true)).c("beefRaw")); + a(364, "cooked_beef", (new ItemFood(8, 0.8F, true)).c("beefCooked")); + a(365, "chicken", (new ItemFood(2, 0.3F, true)).a(MobEffectList.HUNGER.id, 30, 0, 0.3F).c("chickenRaw")); + a(366, "cooked_chicken", (new ItemFood(6, 0.6F, true)).c("chickenCooked")); + a(367, "rotten_flesh", (new ItemFood(4, 0.1F, true)).a(MobEffectList.HUNGER.id, 30, 0, 0.8F).c("rottenFlesh")); + a(368, "ender_pearl", (new ItemEnderPearl()).c("enderPearl")); + a(369, "blaze_rod", (new Item()).c("blazeRod").a(CreativeModeTab.l).n()); + a(370, "ghast_tear", (new Item()).c("ghastTear").e(PotionBrewer.c).a(CreativeModeTab.k)); + a(371, "gold_nugget", (new Item()).c("goldNugget").a(CreativeModeTab.l)); + a(372, "nether_wart", (new ItemSeeds(Blocks.NETHER_WART, Blocks.SOUL_SAND)).c("netherStalkSeeds").e("+4")); + a(373, "potion", (new ItemPotion()).c("potion")); + a(374, "glass_bottle", (new ItemGlassBottle()).c("glassBottle")); + a(375, "spider_eye", (new ItemFood(2, 0.8F, false)).a(MobEffectList.POISON.id, 5, 0, 1.0F).c("spiderEye").e(PotionBrewer.d)); + a(376, "fermented_spider_eye", (new Item()).c("fermentedSpiderEye").e(PotionBrewer.e).a(CreativeModeTab.k)); + a(377, "blaze_powder", (new Item()).c("blazePowder").e(PotionBrewer.g).a(CreativeModeTab.k)); + a(378, "magma_cream", (new Item()).c("magmaCream").e(PotionBrewer.h).a(CreativeModeTab.k)); + a(379, "brewing_stand", (new ItemReed(Blocks.BREWING_STAND)).c("brewingStand").a(CreativeModeTab.k)); + a(380, "cauldron", (new ItemReed(Blocks.cauldron)).c("cauldron").a(CreativeModeTab.k)); + a(381, "ender_eye", (new ItemEnderEye()).c("eyeOfEnder")); + a(382, "speckled_melon", (new Item()).c("speckledMelon").e(PotionBrewer.f).a(CreativeModeTab.k)); + a(383, "spawn_egg", (new ItemMonsterEgg()).c("monsterPlacer")); + a(384, "experience_bottle", (new ItemExpBottle()).c("expBottle")); + a(385, "fire_charge", (new ItemFireball()).c("fireball")); + a(386, "writable_book", (new ItemBookAndQuill()).c("writingBook").a(CreativeModeTab.f)); + a(387, "written_book", (new ItemWrittenBook()).c("writtenBook").c(16)); + a(388, "emerald", (new Item()).c("emerald").a(CreativeModeTab.l)); + a(389, "item_frame", (new ItemHanging(EntityItemFrame.class)).c("frame")); + a(390, "flower_pot", (new ItemReed(Blocks.FLOWER_POT)).c("flowerPot").a(CreativeModeTab.c)); + a(391, "carrot", (new ItemSeedFood(3, 0.6F, Blocks.CARROTS, Blocks.FARMLAND)).c("carrots")); + a(392, "potato", (new ItemSeedFood(1, 0.3F, Blocks.POTATOES, Blocks.FARMLAND)).c("potato")); + a(393, "baked_potato", (new ItemFood(5, 0.6F, false)).c("potatoBaked")); + a(394, "poisonous_potato", (new ItemFood(2, 0.3F, false)).a(MobEffectList.POISON.id, 5, 0, 0.6F).c("potatoPoisonous")); + a(395, "map", (new ItemMapEmpty()).c("emptyMap")); + a(396, "golden_carrot", (new ItemFood(6, 1.2F, false)).c("carrotGolden").e(PotionBrewer.l).a(CreativeModeTab.k)); + a(397, "skull", (new ItemSkull()).c("skull")); + a(398, "carrot_on_a_stick", (new ItemCarrotStick()).c("carrotOnAStick")); + a(399, "nether_star", (new ItemNetherStar()).c("netherStar").a(CreativeModeTab.l)); + a(400, "pumpkin_pie", (new ItemFood(8, 0.3F, false)).c("pumpkinPie").a(CreativeModeTab.h)); + a(401, "fireworks", (new ItemFireworks()).c("fireworks")); + a(402, "firework_charge", (new ItemFireworksCharge()).c("fireworksCharge").a(CreativeModeTab.f)); + a(403, "enchanted_book", (new ItemEnchantedBook()).c(1).c("enchantedBook")); + a(404, "comparator", (new ItemReed(Blocks.UNPOWERED_COMPARATOR)).c("comparator").a(CreativeModeTab.d)); + a(405, "netherbrick", (new Item()).c("netherbrick").a(CreativeModeTab.l)); + a(406, "quartz", (new Item()).c("netherquartz").a(CreativeModeTab.l)); + a(407, "tnt_minecart", (new ItemMinecart(EntityMinecartAbstract.EnumMinecartType.TNT)).c("minecartTnt")); + a(408, "hopper_minecart", (new ItemMinecart(EntityMinecartAbstract.EnumMinecartType.HOPPER)).c("minecartHopper")); + a(409, "prismarine_shard", (new Item()).c("prismarineShard").a(CreativeModeTab.l)); + a(410, "prismarine_crystals", (new Item()).c("prismarineCrystals").a(CreativeModeTab.l)); + a(411, "rabbit", (new ItemFood(3, 0.3F, true)).c("rabbitRaw")); + a(412, "cooked_rabbit", (new ItemFood(5, 0.6F, true)).c("rabbitCooked")); + a(413, "rabbit_stew", (new ItemSoup(10)).c("rabbitStew")); + a(414, "rabbit_foot", (new Item()).c("rabbitFoot").e(PotionBrewer.n).a(CreativeModeTab.k)); + a(415, "rabbit_hide", (new Item()).c("rabbitHide").a(CreativeModeTab.l)); + a(416, "armor_stand", (new ItemArmorStand()).c("armorStand").c(16)); + a(417, "iron_horse_armor", (new Item()).c("horsearmormetal").c(1).a(CreativeModeTab.f)); + a(418, "golden_horse_armor", (new Item()).c("horsearmorgold").c(1).a(CreativeModeTab.f)); + a(419, "diamond_horse_armor", (new Item()).c("horsearmordiamond").c(1).a(CreativeModeTab.f)); + a(420, "lead", (new ItemLeash()).c("leash")); + a(421, "name_tag", (new ItemNameTag()).c("nameTag")); + a(422, "command_block_minecart", (new ItemMinecart(EntityMinecartAbstract.EnumMinecartType.COMMAND_BLOCK)).c("minecartCommandBlock").a((CreativeModeTab) null)); + a(423, "mutton", (new ItemFood(2, 0.3F, true)).c("muttonRaw")); + a(424, "cooked_mutton", (new ItemFood(6, 0.8F, true)).c("muttonCooked")); + a(425, "banner", (new ItemBanner()).b("banner")); + a(427, "spruce_door", (new ItemDoor(Blocks.SPRUCE_DOOR)).c("doorSpruce")); + a(428, "birch_door", (new ItemDoor(Blocks.BIRCH_DOOR)).c("doorBirch")); + a(429, "jungle_door", (new ItemDoor(Blocks.JUNGLE_DOOR)).c("doorJungle")); + a(430, "acacia_door", (new ItemDoor(Blocks.ACACIA_DOOR)).c("doorAcacia")); + a(431, "dark_oak_door", (new ItemDoor(Blocks.DARK_OAK_DOOR)).c("doorDarkOak")); + a(2256, "record_13", (new ItemRecord("13")).c("record")); + a(2257, "record_cat", (new ItemRecord("cat")).c("record")); + a(2258, "record_blocks", (new ItemRecord("blocks")).c("record")); + a(2259, "record_chirp", (new ItemRecord("chirp")).c("record")); + a(2260, "record_far", (new ItemRecord("far")).c("record")); + a(2261, "record_mall", (new ItemRecord("mall")).c("record")); + a(2262, "record_mellohi", (new ItemRecord("mellohi")).c("record")); + a(2263, "record_stal", (new ItemRecord("stal")).c("record")); + a(2264, "record_strad", (new ItemRecord("strad")).c("record")); + a(2265, "record_ward", (new ItemRecord("ward")).c("record")); + a(2266, "record_11", (new ItemRecord("11")).c("record")); + a(2267, "record_wait", (new ItemRecord("wait")).c("record")); + Block.durabilityChecker = Item.d(AzuriteConfig.durabilityItemChecker.getValue().toLowerCase()); + } + + private static void c(Block block) { + a(block, (new ItemBlock(block))); + } + + protected static void a(Block block, Item item) { + a(Block.getId(block), Block.REGISTRY.c(block), item); + Item.a.put(block, item); + } + + private static void a(int i, String s, Item item) { + a(i, new MinecraftKey(s), item); + } + + private static void a(int i, MinecraftKey minecraftkey, Item item) { + Item.REGISTRY.a(i, minecraftkey, item); + } + + public boolean a(NBTTagCompound nbttagcompound) { + return false; + } + + public Item c(int i) { + this.maxStackSize = i; + return this; + } + + public boolean interactWith(ItemStack itemstack, EntityHuman entityhuman, World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2) { + return false; + } + + public float getDestroySpeed(ItemStack itemstack, Block block) { + return 1.0F; + } + + public ItemStack a(ItemStack itemstack, World world, EntityHuman entityhuman) { + return itemstack; + } + + public ItemStack b(ItemStack itemstack, World world, EntityHuman entityhuman) { + return itemstack; + } + + public int getMaxStackSize() { + return this.maxStackSize; + } + + public int filterData(int i) { + return 0; + } + + public boolean k() { + return this.j; + } + + protected Item a(boolean flag) { + this.j = flag; + return this; + } + + public int getMaxDurability() { + return this.durability; + } + + protected Item setMaxDurability(int i) { + this.durability = i; + return this; + } + + public boolean usesDurability() { + return this.durability > 0 && !this.j; + } + + public boolean a(ItemStack itemstack, EntityLiving entityliving, EntityLiving entityliving1) { + return false; + } + + public boolean a(ItemStack itemstack, World world, Block block, BlockPosition blockposition, EntityLiving entityliving) { + return false; + } + + public boolean canDestroySpecialBlock(Block block) { + return false; + } + + public boolean a(ItemStack itemstack, EntityHuman entityhuman, EntityLiving entityliving) { + return false; + } + + public Item n() { + this.i = true; + return this; + } + + public Item c(String s) { + this.name = s; + return this; + } + + public String k(ItemStack itemstack) { + String s = this.e_(itemstack); + + return s == null ? "" : LocaleI18n.get(s); + } + + public String getName() { + return "item." + this.name; + } + + public String e_(ItemStack itemstack) { + return "item." + this.name; + } + + public Item c(Item item) { + this.craftingResult = item; + return this; + } + + public boolean p() { + return true; + } + + public Item q() { + return this.craftingResult; + } + + public boolean r() { + return this.craftingResult != null; + } + + public void a(ItemStack itemstack, World world, Entity entity, int i, boolean flag) { + } + + public void d(ItemStack itemstack, World world, EntityHuman entityhuman) { + } + + public boolean f() { + return false; + } + + public EnumAnimation e(ItemStack itemstack) { + return EnumAnimation.NONE; + } + + public int d(ItemStack itemstack) { + return 0; + } + + public void a(ItemStack itemstack, World world, EntityHuman entityhuman, int i) { + } + + protected Item e(String s) { + this.k = s; + return this; + } + + public String j(ItemStack itemstack) { + return this.k; + } + + public boolean l(ItemStack itemstack) { + return this.j(itemstack) != null; + } + + public String a(ItemStack itemstack) { + return ("" + LocaleI18n.get(this.k(itemstack) + ".name")).trim(); + } + + public EnumItemRarity g(ItemStack itemstack) { + return itemstack.hasEnchantments() ? EnumItemRarity.RARE : EnumItemRarity.COMMON; + } + + public boolean f_(ItemStack itemstack) { + return this.getMaxStackSize() == 1 && this.usesDurability(); + } + + protected MovingObjectPosition a(World world, EntityHuman entityhuman, boolean flag) { + float f = entityhuman.pitch; + float f1 = entityhuman.yaw; + Vec3D vec3d = new Vec3D(entityhuman.locX, entityhuman.locY + entityhuman.getHeadHeight(), entityhuman.locZ); + float f2 = MathHelper.cos(-f1 * 0.017453292F - 3.1415927F); + float f3 = MathHelper.sin(-f1 * 0.017453292F - 3.1415927F); + float f4 = -MathHelper.cos(-f * 0.017453292F); + float f5 = MathHelper.sin(-f * 0.017453292F); + float f6 = f3 * f4; + float f7 = f2 * f4; + + return world.rayTrace(vec3d, vec3d.add(f6 * 5D, f5 * 5D, f7 * 5D), flag, !flag, false); + } + + public int b() { + return 0; + } + + public Item a(CreativeModeTab creativemodetab) { + return this; + } + + public boolean s() { + return false; + } + + public boolean a(ItemStack itemstack, ItemStack itemstack1) { + return false; + } + + public Multimap i() { + return HashMultimap.create(); + } + + public enum EnumToolMaterial { + + WOOD(0, 59, 2.0F, 0.0F, 15), STONE(1, 131, 4.0F, 1.0F, 5), IRON(2, 250, 6.0F, 2.0F, 14), EMERALD(3, 1561, 8.0F, 3.0F, 10), GOLD(0, 32, 12.0F, 0.0F, 22); + + private final int f; + private final int g; + private final float h; + private final float i; + private final int j; + + EnumToolMaterial(int i, int j, float f, float f1, int k) { + this.f = i; + this.g = j; + this.h = f; + this.i = f1; + this.j = k; + } + + public int a() { + return this.g; + } + + public float b() { + return this.h; + } + + public float c() { + return this.i; + } + + public int d() { + return this.f; + } + + public int e() { + return this.j; + } + + public Item f() { + return this == Item.EnumToolMaterial.WOOD ? Item.getItemOf(Blocks.PLANKS) : (this == Item.EnumToolMaterial.STONE ? Item.getItemOf(Blocks.COBBLESTONE) : (this == Item.EnumToolMaterial.GOLD ? Items.GOLD_INGOT : (this == Item.EnumToolMaterial.IRON ? Items.IRON_INGOT : (this == Item.EnumToolMaterial.EMERALD ? Items.DIAMOND : null)))); + } + } + + // Beanes - fake durability + public boolean hasFakeDurability() { + return false; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemAnvil.java b/azurite-server/src/main/java/net/minecraft/server/ItemAnvil.java new file mode 100644 index 0000000..f3bf808 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemAnvil.java @@ -0,0 +1,12 @@ +package net.minecraft.server; + +public class ItemAnvil extends ItemMultiTexture { + + public ItemAnvil(Block block) { + super(block, block, new String[] { "intact", "slightlyDamaged", "veryDamaged"}); + } + + public int filterData(int i) { + return i << 2; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemArmor.java b/azurite-server/src/main/java/net/minecraft/server/ItemArmor.java new file mode 100644 index 0000000..218525d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemArmor.java @@ -0,0 +1,197 @@ +package net.minecraft.server; + +import com.google.common.base.Predicates; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.event.block.BlockDispenseArmorEvent; + +import java.util.List; +// CraftBukkit end + +public class ItemArmor extends Item { + + private static final int[] k = new int[]{11, 16, 15, 13}; + public static final String[] a = new String[]{"minecraft:items/empty_armor_slot_helmet", "minecraft:items/empty_armor_slot_chestplate", "minecraft:items/empty_armor_slot_leggings", "minecraft:items/empty_armor_slot_boots"}; + private static final IDispenseBehavior l = new DispenseBehaviorItem() { + protected ItemStack b(ISourceBlock isourceblock, ItemStack itemstack) { + BlockPosition blockposition = isourceblock.getBlockPosition().shift(BlockDispenser.b(isourceblock.f())); + int i = blockposition.getX(); + int j = blockposition.getY(); + int k = blockposition.getZ(); + AxisAlignedBB axisalignedbb = new AxisAlignedBB(i, j, k, i + 1, (j + 1), (k + 1)); + List list = isourceblock.getWorld().a(EntityLiving.class, axisalignedbb, Predicates.and(IEntitySelector.d, new IEntitySelector.EntitySelectorEquipable(itemstack))); + + if (!list.isEmpty()) { + EntityLiving entityliving = list.get(0); + int l = entityliving instanceof EntityHuman ? 1 : 0; + int i1 = EntityInsentient.c(itemstack); + + // CraftBukkit start + ItemStack itemstack1 = itemstack.cloneAndSubtract(1); + World world = isourceblock.getWorld(); + org.bukkit.block.Block block = world.getWorld().getBlockAt(isourceblock.getBlockPosition().getX(), isourceblock.getBlockPosition().getY(), isourceblock.getBlockPosition().getZ()); + CraftItemStack craftItem = CraftItemStack.asCraftMirror(itemstack1); + + BlockDispenseArmorEvent event = new BlockDispenseArmorEvent(block, craftItem.clone(), (org.bukkit.craftbukkit.entity.CraftLivingEntity) entityliving.bukkitEntity); + if (!BlockDispenser.eventFired) { + world.getServer().getPluginManager().callEvent(event); + } + + if (event.isCancelled()) { + itemstack.count++; + return itemstack; + } + + if (!event.getItem().equals(craftItem)) { + itemstack.count++; + // Chain to handler for new item + ItemStack eventStack = CraftItemStack.asNMSCopy(event.getItem()); + IDispenseBehavior idispensebehavior = BlockDispenser.REGISTRY.get(eventStack.getItem()); + if (idispensebehavior != IDispenseBehavior.NONE && idispensebehavior != this) { + idispensebehavior.a(isourceblock, eventStack); + return itemstack; + } + } + // CraftBukkit end + + itemstack1.count = 1; + entityliving.setEquipment(i1 - l, itemstack1); + if (entityliving instanceof EntityInsentient) { + ((EntityInsentient) entityliving).a(i1, 2.0F); + } + + // --itemstack.count; // CraftBukkit - handled above + return itemstack; + } else { + return super.b(isourceblock, itemstack); + } + } + }; + public final int b; + public final int c; + public final int d; + private final ItemArmor.EnumArmorMaterial m; + + public ItemArmor(ItemArmor.EnumArmorMaterial itemarmor_enumarmormaterial, int i, int j) { + this.m = itemarmor_enumarmormaterial; + this.b = j; + this.d = i; + this.c = itemarmor_enumarmormaterial.b(j); + this.setMaxDurability(itemarmor_enumarmormaterial.a(j)); + this.maxStackSize = 1; + this.a(CreativeModeTab.j); + BlockDispenser.REGISTRY.a(this, ItemArmor.l); + } + + public int b() { + return this.m.a(); + } + + public ItemArmor.EnumArmorMaterial x_() { + return this.m; + } + + public boolean d_(ItemStack itemstack) { + return this.m == EnumArmorMaterial.LEATHER && (itemstack.hasTag() && (itemstack.getTag().hasKeyOfType("display", 10) && itemstack.getTag().getCompound("display").hasKeyOfType("color", 3))); + } + + public int b(ItemStack itemstack) { + if (this.m != ItemArmor.EnumArmorMaterial.LEATHER) { + return -1; + } else { + NBTTagCompound nbttagcompound = itemstack.getTag(); + + if (nbttagcompound != null) { + NBTTagCompound nbttagcompound1 = nbttagcompound.getCompound("display"); + + if (nbttagcompound1 != null && nbttagcompound1.hasKeyOfType("color", 3)) { + return nbttagcompound1.getInt("color"); + } + } + + return 10511680; + } + } + + public void c(ItemStack itemstack) { + if (this.m == ItemArmor.EnumArmorMaterial.LEATHER) { + NBTTagCompound nbttagcompound = itemstack.getTag(); + + if (nbttagcompound != null) { + NBTTagCompound nbttagcompound1 = nbttagcompound.getCompound("display"); + + if (nbttagcompound1.hasKey("color")) { + nbttagcompound1.remove("color"); + } + + } + } + } + + public void b(ItemStack itemstack, int i) { + if (this.m != ItemArmor.EnumArmorMaterial.LEATHER) { + throw new UnsupportedOperationException("Can't dye non-leather!"); + } else { + NBTTagCompound nbttagcompound = itemstack.getTag(); + + if (nbttagcompound == null) { + nbttagcompound = new NBTTagCompound(); + itemstack.setTag(nbttagcompound); + } + + NBTTagCompound nbttagcompound1 = nbttagcompound.getCompound("display"); + + if (!nbttagcompound.hasKeyOfType("display", 10)) { + nbttagcompound.set("display", nbttagcompound1); + } + + nbttagcompound1.setInt("color", i); + } + } + + public boolean a(ItemStack itemstack, ItemStack itemstack1) { + return this.m.b() == itemstack1.getItem() || super.a(itemstack, itemstack1); + } + + public ItemStack a(ItemStack itemstack, World world, EntityHuman entityhuman) { + int i = EntityInsentient.c(itemstack) - 1; + ItemStack itemstack1 = entityhuman.q(i); + + if (itemstack1 == null) { + entityhuman.setEquipment(i, itemstack.cloneItemStack()); + itemstack.count = 0; + } + + return itemstack; + } + + public enum EnumArmorMaterial { + + LEATHER("leather", 5, new int[]{1, 3, 2, 1}, 15), CHAIN("chainmail", 15, new int[]{2, 5, 4, 1}, 12), IRON("iron", 15, new int[]{2, 6, 5, 2}, 9), GOLD("gold", 7, new int[]{2, 5, 3, 1}, 25), DIAMOND("diamond", 33, new int[]{3, 8, 6, 3}, 10); + + private final int g; + private final int[] h; + private final int i; + + EnumArmorMaterial(String s, int i, int[] aint, int j) { + this.g = i; + this.h = aint; + this.i = j; + } + + public int a(int i) { + return ItemArmor.k[i] * this.g; + } + + public int b(int i) { + return this.h[i]; + } + + public int a() { + return this.i; + } + + public Item b() { + return this == ItemArmor.EnumArmorMaterial.LEATHER ? Items.LEATHER : (this == ItemArmor.EnumArmorMaterial.CHAIN ? Items.IRON_INGOT : (this == ItemArmor.EnumArmorMaterial.GOLD ? Items.GOLD_INGOT : (this == ItemArmor.EnumArmorMaterial.IRON ? Items.IRON_INGOT : (this == ItemArmor.EnumArmorMaterial.DIAMOND ? Items.DIAMOND : null)))); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemArmorStand.java b/azurite-server/src/main/java/net/minecraft/server/ItemArmorStand.java new file mode 100644 index 0000000..efb1c90 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemArmorStand.java @@ -0,0 +1,76 @@ +package net.minecraft.server; + +import java.util.List; +import java.util.Random; + +public class ItemArmorStand extends Item { + + public ItemArmorStand() { + this.a(CreativeModeTab.c); + } + + public boolean interactWith(ItemStack itemstack, EntityHuman entityhuman, World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2) { + if (enumdirection == EnumDirection.DOWN) { + return false; + } else { + boolean flag = world.getType(blockposition).getBlock().a(world, blockposition); + BlockPosition blockposition1 = flag ? blockposition : blockposition.shift(enumdirection); + + if (!entityhuman.a(blockposition1, enumdirection, itemstack)) { + return false; + } else { + BlockPosition blockposition2 = blockposition1.up(); + boolean flag1 = !world.isEmpty(blockposition1) && !world.getType(blockposition1).getBlock().a(world, blockposition1); + + flag1 |= !world.isEmpty(blockposition2) && !world.getType(blockposition2).getBlock().a(world, blockposition2); + if (flag1) { + return false; + } else { + double d0 = blockposition1.getX(); + double d1 = blockposition1.getY(); + double d2 = blockposition1.getZ(); + List list = world.getEntities(null, AxisAlignedBB.a(d0, d1, d2, d0 + 1.0D, d1 + 2.0D, d2 + 1.0D)); + + if (!list.isEmpty()) { + return false; + } else { + world.setAir(blockposition1); + world.setAir(blockposition2); + EntityArmorStand entityarmorstand = new EntityArmorStand(world, d0 + 0.5D, d1, d2 + 0.5D); + float f3 = (float) MathHelper.d((MathHelper.g(entityhuman.yaw - 180.0F) + 22.5F) / 45.0F) * 45.0F; + + entityarmorstand.setPositionRotation(d0 + 0.5D, d1, d2 + 0.5D, f3, 0.0F); + this.a(entityarmorstand, world.random); + NBTTagCompound nbttagcompound = itemstack.getTag(); + + if (nbttagcompound != null && nbttagcompound.hasKeyOfType("EntityTag", 10)) { + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + + entityarmorstand.d(nbttagcompound1); + nbttagcompound1.a(nbttagcompound.getCompound("EntityTag")); + entityarmorstand.f(nbttagcompound1); + } + + world.addEntity(entityarmorstand); + + --itemstack.count; + return true; + } + } + } + } + } + + private void a(EntityArmorStand entityarmorstand, Random random) { + Vector3f vector3f = entityarmorstand.t(); + float f = random.nextFloat() * 5.0F; + float f1 = random.nextFloat() * 20.0F - 10.0F; + Vector3f vector3f1 = new Vector3f(vector3f.getX() + f, vector3f.getY() + f1, vector3f.getZ()); + + entityarmorstand.setHeadPose(vector3f1); + vector3f = entityarmorstand.u(); + f = random.nextFloat() * 10.0F - 5.0F; + vector3f1 = new Vector3f(vector3f.getX(), vector3f.getY() + f, vector3f.getZ()); + entityarmorstand.setBodyPose(vector3f1); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemAxe.java b/azurite-server/src/main/java/net/minecraft/server/ItemAxe.java new file mode 100644 index 0000000..10d9519 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemAxe.java @@ -0,0 +1,18 @@ +package net.minecraft.server; + +import com.google.common.collect.Sets; + +import java.util.Set; + +public class ItemAxe extends ItemTool { + + private static final Set c = Sets.newHashSet(Blocks.PLANKS, Blocks.BOOKSHELF, Blocks.LOG, Blocks.LOG2, Blocks.CHEST, Blocks.PUMPKIN, Blocks.LIT_PUMPKIN, Blocks.MELON_BLOCK, Blocks.LADDER); + + protected ItemAxe(EnumToolMaterial item_enumtoolmaterial) { + super(3.0F, item_enumtoolmaterial, ItemAxe.c); + } + + public float getDestroySpeed(ItemStack itemstack, Block block) { + return block.getMaterial() != Material.WOOD && block.getMaterial() != Material.PLANT && block.getMaterial() != Material.REPLACEABLE_PLANT ? super.getDestroySpeed(itemstack, block) : this.a; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemBanner.java b/azurite-server/src/main/java/net/minecraft/server/ItemBanner.java new file mode 100644 index 0000000..52f5b8d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemBanner.java @@ -0,0 +1,65 @@ +package net.minecraft.server; + +public class ItemBanner extends ItemBlock { + + public ItemBanner() { + super(Blocks.STANDING_BANNER); + this.maxStackSize = 16; + this.a(CreativeModeTab.c); + this.a(true); + this.setMaxDurability(0); + } + + public boolean interactWith(ItemStack itemstack, EntityHuman entityhuman, World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2) { + if (enumdirection == EnumDirection.DOWN) { + return false; + } else if (!world.getType(blockposition).getBlock().getMaterial().isBuildable()) { + return false; + } else { + blockposition = blockposition.shift(enumdirection); + if (!entityhuman.a(blockposition, enumdirection, itemstack)) { + return false; + } else if (!Blocks.STANDING_BANNER.canPlace(world, blockposition)) { + return false; + } else { + if (enumdirection == EnumDirection.UP) { + int i = MathHelper.floor((double) ((entityhuman.yaw + 180.0F) * 16.0F / 360.0F) + 0.5D) & 15; + + world.setTypeAndData(blockposition, Blocks.STANDING_BANNER.getBlockData().set(BlockFloorSign.ROTATION, i), 3); + } else { + world.setTypeAndData(blockposition, Blocks.WALL_BANNER.getBlockData().set(BlockWallSign.FACING, enumdirection), 3); + } + + --itemstack.count; + TileEntity tileentity = world.getTileEntity(blockposition); + + if (tileentity instanceof TileEntityBanner) { + ((TileEntityBanner) tileentity).a(itemstack); + } + + return true; + } + } + } + + public String a(ItemStack itemstack) { + String s = "item.banner."; + EnumColor enumcolor = this.h(itemstack); + + s = s + enumcolor.d() + ".name"; + return LocaleI18n.get(s); + } + + private EnumColor h(ItemStack itemstack) { + NBTTagCompound nbttagcompound = itemstack.a("BlockEntityTag", false); + EnumColor enumcolor; + + if (nbttagcompound != null && nbttagcompound.hasKey("Base")) { + enumcolor = EnumColor.fromInvColorIndex(nbttagcompound.getInt("Base")); + } else { + enumcolor = EnumColor.fromInvColorIndex(itemstack.getData()); + } + + return enumcolor; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemBed.java b/azurite-server/src/main/java/net/minecraft/server/ItemBed.java new file mode 100644 index 0000000..be146ec --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemBed.java @@ -0,0 +1,49 @@ +package net.minecraft.server; + +public class ItemBed extends Item { + + public ItemBed() { + this.a(CreativeModeTab.c); + } + + public boolean interactWith(ItemStack itemstack, EntityHuman entityhuman, World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2) { + if (enumdirection != EnumDirection.UP) { + return false; + } else { + IBlockData iblockdata = world.getType(blockposition); + Block block = iblockdata.getBlock(); + boolean flag = block.a(world, blockposition); + + if (!flag) { + blockposition = blockposition.up(); + } + + int i = MathHelper.floor((double) (entityhuman.yaw * 4.0F / 360.0F) + 0.5D) & 3; + EnumDirection enumdirection1 = EnumDirection.fromType2(i); + BlockPosition blockposition1 = blockposition.shift(enumdirection1); + + if (entityhuman.a(blockposition, enumdirection, itemstack) && entityhuman.a(blockposition1, enumdirection, itemstack)) { + boolean flag1 = world.getType(blockposition1).getBlock().a(world, blockposition1); + boolean flag2 = flag || world.isEmpty(blockposition); + boolean flag3 = flag1 || world.isEmpty(blockposition1); + + if (flag2 && flag3 && World.a(world, blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()) && World.a(world, blockposition1.getX(), blockposition1.getY() - 1, blockposition1.getZ())) { + IBlockData iblockdata1 = Blocks.BED.getBlockData().set(BlockBed.OCCUPIED, Boolean.FALSE).set(BlockBed.FACING, enumdirection1).set(BlockBed.PART, BlockBed.EnumBedPart.FOOT); + + if (world.setTypeAndData(blockposition, iblockdata1, 3)) { + IBlockData iblockdata2 = iblockdata1.set(BlockBed.PART, BlockBed.EnumBedPart.HEAD); + + world.setTypeAndData(blockposition1, iblockdata2, 3); + } + + --itemstack.count; + return true; + } else { + return false; + } + } else { + return false; + } + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemBlock.java b/azurite-server/src/main/java/net/minecraft/server/ItemBlock.java new file mode 100644 index 0000000..a4445a1 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemBlock.java @@ -0,0 +1,98 @@ +package net.minecraft.server; + +public class ItemBlock extends Item { + + protected final Block a; + + public ItemBlock(Block block) { + this.a = block; + } + + public ItemBlock b(String s) { + super.c(s); + return this; + } + + public boolean interactWith(ItemStack itemstack, EntityHuman entityhuman, World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2) { + IBlockData iblockdata = world.getType(blockposition); + Block block = iblockdata.getBlock(); + + if (!block.a(world, blockposition)) { + blockposition = blockposition.shift(enumdirection); + } + + if (itemstack.count == 0) { + return false; + } else if (!entityhuman.a(blockposition, enumdirection, itemstack)) { + return false; + } else if (world.a(this.a, blockposition, false, enumdirection, entityhuman, itemstack)) { // PaperSpigot - Pass entityhuman instead of null + int i = this.filterData(itemstack.getData()); + IBlockData iblockdata1 = this.a.getPlacedState(world, blockposition, enumdirection, f, f1, f2, i, entityhuman); + + if (world.setTypeAndData(blockposition, iblockdata1, 3)) { + iblockdata1 = world.getType(blockposition); + if (iblockdata1.getBlock() == this.a) { + a(world, entityhuman, blockposition, itemstack); + this.a.postPlace(world, blockposition, iblockdata1, entityhuman, itemstack); + } + + world.makeSound((float) blockposition.getX() + 0.5F, (float) blockposition.getY() + 0.5F, (float) blockposition.getZ() + 0.5F, this.a.stepSound.getPlaceSound(), (this.a.stepSound.getVolume1() + 1.0F) / 2.0F, this.a.stepSound.getVolume2() * 0.8F); + --itemstack.count; + } + + return true; + } else { + return false; + } + } + + public static boolean a(World world, EntityHuman entityhuman, BlockPosition blockposition, ItemStack itemstack) { + MinecraftServer minecraftserver = MinecraftServer.getServer(); + + if (minecraftserver != null) { + if (itemstack.hasTag() && itemstack.getTag().hasKeyOfType("BlockEntityTag", 10)) { + TileEntity tileentity = world.getTileEntity(blockposition); + + if (tileentity != null) { + if (tileentity.F() && !minecraftserver.getPlayerList().isOp(entityhuman.getProfile())) { + return false; + } + + NBTTagCompound nbttagcompound = new NBTTagCompound(); + NBTTagCompound nbttagcompound1 = (NBTTagCompound) nbttagcompound.clone(); + + tileentity.b(nbttagcompound); + NBTTagCompound nbttagcompound2 = (NBTTagCompound) itemstack.getTag().get("BlockEntityTag"); + + nbttagcompound.a(nbttagcompound2); + nbttagcompound.setInt("x", blockposition.getX()); + nbttagcompound.setInt("y", blockposition.getY()); + nbttagcompound.setInt("z", blockposition.getZ()); + if (!nbttagcompound.equals(nbttagcompound1)) { + tileentity.a(nbttagcompound); + tileentity.update(); + return true; + } + } + } + + } + return false; + } + + public String e_(ItemStack itemstack) { + return this.a.a(); + } + + public String getName() { + return this.a.a(); + } + + public Block d() { + return this.a; + } + + public Item c(String s) { + return this.b(s); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemBoat.java b/azurite-server/src/main/java/net/minecraft/server/ItemBoat.java new file mode 100644 index 0000000..983a01d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemBoat.java @@ -0,0 +1,83 @@ +package net.minecraft.server; + +import java.util.List; + +public class ItemBoat extends Item { + + public ItemBoat() { + this.maxStackSize = 1; + this.a(CreativeModeTab.e); + } + + public ItemStack a(ItemStack itemstack, World world, EntityHuman entityhuman) { + float f = 1.0F; + float f1 = entityhuman.lastPitch + (entityhuman.pitch - entityhuman.lastPitch) * f; + float f2 = entityhuman.lastYaw + (entityhuman.yaw - entityhuman.lastYaw) * f; + double d0 = entityhuman.lastX + (entityhuman.locX - entityhuman.lastX) * (double) f; + double d1 = entityhuman.lastY + (entityhuman.locY - entityhuman.lastY) * (double) f + (double) entityhuman.getHeadHeight(); + double d2 = entityhuman.lastZ + (entityhuman.locZ - entityhuman.lastZ) * (double) f; + Vec3D vec3d = new Vec3D(d0, d1, d2); + float f3 = MathHelper.cos(-f2 * 0.017453292F - 3.1415927F); + float f4 = MathHelper.sin(-f2 * 0.017453292F - 3.1415927F); + float f5 = -MathHelper.cos(-f1 * 0.017453292F); + float f6 = MathHelper.sin(-f1 * 0.017453292F); + float f7 = f4 * f5; + float f8 = f3 * f5; + double d3 = 5.0D; + Vec3D vec3d1 = vec3d.add((double) f7 * d3, (double) f6 * d3, (double) f8 * d3); + //TODO: Fucking Raytrace but its a boat so who cares bro + MovingObjectPosition movingobjectposition = world.rayTrace(vec3d, vec3d1, true); + + if (movingobjectposition != null) { + Vec3D vec3d2 = entityhuman.d(f); + boolean flag = false; + float f9 = 1.0F; + List list = world.getEntities(entityhuman, entityhuman.getBoundingBox().a(vec3d2.a * d3, vec3d2.b * d3, vec3d2.c * d3).grow(f9, f9, f9)); + + for (Entity entity : list) { + if (entity.ad()) { + float f10 = entity.ao(); + AxisAlignedBB axisalignedbb = entity.getBoundingBox().grow(f10, f10, f10); + + if (axisalignedbb.a(vec3d)) { + flag = true; + } + } + } + + if (!flag) { + if (movingobjectposition.type == MovingObjectPosition.EnumMovingObjectType.BLOCK) { + BlockPosition blockposition = movingobjectposition.a(); + + // CraftBukkit start - Boat placement + org.bukkit.event.player.PlayerInteractEvent event = org.bukkit.craftbukkit.event.CraftEventFactory.callPlayerInteractEvent(entityhuman, org.bukkit.event.block.Action.RIGHT_CLICK_BLOCK, blockposition, movingobjectposition.direction, itemstack); + + if (event.isCancelled()) { + return itemstack; + } + // CraftBukkit end + + if (world.getType(blockposition).getBlock() == Blocks.SNOW_LAYER) { + blockposition = blockposition.down(); + } + + EntityBoat entityboat = new EntityBoat(world, ((float) blockposition.getX() + 0.5F), (float) blockposition.getY() + 1.0F, (float) blockposition.getZ() + 0.5F); + + entityboat.yaw = (float) (((MathHelper.floor((double) (entityhuman.yaw * 4.0F / 360.0F) + 0.5D) & 3) - 1) * 90); + if (!world.getCubes(entityboat, entityboat.getBoundingBox().grow(-0.1D, -0.1D, -0.1D)).isEmpty()) { + return itemstack; + } + + world.addEntity(entityboat); + + if (!entityhuman.abilities.canInstantlyBuild) { + --itemstack.count; + } + + entityhuman.b(StatisticList.USE_ITEM_COUNT[Item.getId(this)]); + } + } + } + return itemstack; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemBook.java b/azurite-server/src/main/java/net/minecraft/server/ItemBook.java new file mode 100644 index 0000000..24fd6dd --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemBook.java @@ -0,0 +1,14 @@ +package net.minecraft.server; + +public class ItemBook extends Item { + + public ItemBook() {} + + public boolean f_(ItemStack itemstack) { + return itemstack.count == 1; + } + + public int b() { + return 1; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemBookAndQuill.java b/azurite-server/src/main/java/net/minecraft/server/ItemBookAndQuill.java new file mode 100644 index 0000000..f4b7ad2 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemBookAndQuill.java @@ -0,0 +1,68 @@ +package net.minecraft.server; + +import java.nio.charset.StandardCharsets; + +public class ItemBookAndQuill extends Item { + public static final String[] MOJANG_CRASH_TRANSLATIONS = {"translation.test.invalid", "translation.test.invalid2"}; + + public ItemBookAndQuill() { + this.c(1); + } + + // Vortex start - Anticrash + public static boolean b(NBTTagCompound var0) { + if (var0 == null || !var0.hasKeyOfType("pages", 9)) + return false; + + NBTTagList pages = var0.getList("pages", 8); + if (pages.size() > 50) + return false; + + long byteTotal = 0L, byteAllowed = 2560L; + + for (int i = 0; i < pages.size(); ++i) { + String page = pages.getString(i); + + if (page == null || page.equals("null") || page.length() > 500) + return false; + + int byteLength = page.getBytes(StandardCharsets.UTF_8).length; + byteTotal += byteLength; + + int length = page.length(); + int multibytes = 0; + if (byteLength != length) { + for (char c : page.toCharArray()) { + if (c > '\u007f') { + ++multibytes; + } + } + } + + byteAllowed += (long) (2560 * Math.min(1.0, Math.max(0.1, length / 255.0)) * 0.98D); + if (multibytes > 1) { + byteAllowed -= multibytes; + } + + if (byteTotal > byteAllowed) + return false; + + if (page.replace(" ", "").startsWith("{\"translate\"")) { + for (String crashTranslation : ItemBookAndQuill.MOJANG_CRASH_TRANSLATIONS) { + if (page.equalsIgnoreCase(String.format("{\"translate\":\"%s\"}", crashTranslation))) { + return false; + } + } + } + } + return true; + } + // Vortex end + + @Override + public ItemStack a(ItemStack var1, World var2, EntityHuman var3) { + var3.openBook(var1); + return var1; + } + +} \ No newline at end of file diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemBow.java b/azurite-server/src/main/java/net/minecraft/server/ItemBow.java new file mode 100644 index 0000000..c629b51 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemBow.java @@ -0,0 +1,106 @@ +package net.minecraft.server; + +import org.bukkit.event.entity.EntityCombustEvent; + +public class ItemBow extends Item { + + public static final String[] a = new String[] { "pulling_0", "pulling_1", "pulling_2"}; + + public ItemBow() { + this.maxStackSize = 1; + this.setMaxDurability(384); + this.a(CreativeModeTab.j); + } + + public void a(ItemStack itemstack, World world, EntityHuman entityhuman, int i) { + boolean hasInfiniteArrows = entityhuman.abilities.canInstantlyBuild || EnchantmentManager.getEnchantmentLevel(Enchantment.ARROW_INFINITE.id, itemstack) > 0; + + if (hasInfiniteArrows || entityhuman.inventory.b(Items.ARROW)) { + int timeLeftOnBow = this.d(itemstack) - i; + float strength = (float) timeLeftOnBow / 20.0F; + + strength = (strength * strength + strength * 2.0F) / 3.0F; + if ((double) strength < 0.1D) { + return; + } + + if (strength > 1.0F) { + strength = 1.0F; + } + + EntityArrow entityarrow = new EntityArrow(world, entityhuman, strength * 2.0F); + + if (strength == 1.0F) { + entityarrow.setCritical(true); + } + + int powerEnchantmentLevel = EnchantmentManager.getEnchantmentLevel(Enchantment.ARROW_DAMAGE.id, itemstack); + + if (powerEnchantmentLevel > 0) { + entityarrow.b(entityarrow.j() + (double) powerEnchantmentLevel * 0.5D + 0.5D); + } + + int l = EnchantmentManager.getEnchantmentLevel(Enchantment.ARROW_KNOCKBACK.id, itemstack); + + if (l > 0) { + entityarrow.setKnockbackStrength(l); + } + + if (EnchantmentManager.getEnchantmentLevel(Enchantment.ARROW_FIRE.id, itemstack) > 0) { + // CraftBukkit start - call EntityCombustEvent + EntityCombustEvent event = new EntityCombustEvent(entityarrow.getBukkitEntity(), 100); + entityarrow.world.getServer().getPluginManager().callEvent(event); + + if (!event.isCancelled()) { + entityarrow.setOnFire(event.getDuration()); + } + // CraftBukkit end + } + + // CraftBukkit start + org.bukkit.event.entity.EntityShootBowEvent event = org.bukkit.craftbukkit.event.CraftEventFactory.callEntityShootBowEvent(entityhuman, itemstack, entityarrow, strength, timeLeftOnBow); + if (event.isCancelled()) { + event.getProjectile().remove(); + return; + } + + if (event.getProjectile() == entityarrow.getBukkitEntity()) { + world.addEntity(entityarrow); + } + // CraftBukkit end + + itemstack.damage(1, entityhuman); + world.makeSound(entityhuman, "random.bow", 1.0F, 1.0F / (ItemBow.g.nextFloat() * 0.4F + 1.2F) + strength * 0.5F); + if (hasInfiniteArrows) { + entityarrow.fromPlayer = 2; + } else { + entityhuman.inventory.a(Items.ARROW); + } + entityhuman.b(StatisticList.USE_ITEM_COUNT[Item.getId(this)]); + } + } + + public ItemStack b(ItemStack itemstack, World world, EntityHuman entityhuman) { + return itemstack; + } + + public int d(ItemStack itemstack) { + return 72000; + } + + public EnumAnimation e(ItemStack itemstack) { + return EnumAnimation.BOW; + } + + public ItemStack a(ItemStack itemstack, World world, EntityHuman entityhuman) { + if (entityhuman.abilities.canInstantlyBuild || entityhuman.inventory.b(Items.ARROW)) { + entityhuman.a(itemstack, this.d(itemstack)); + } + + return itemstack; + } + + public int b() { + return 1; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemBucket.java b/azurite-server/src/main/java/net/minecraft/server/ItemBucket.java new file mode 100644 index 0000000..4e8519d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemBucket.java @@ -0,0 +1,205 @@ +package net.minecraft.server; + +// CraftBukkit start + +import dev.azurite.spigot.configs.AzuriteConfig; +import dev.azurite.spigot.utils.Utils; +import org.bukkit.craftbukkit.event.CraftEventFactory; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.event.player.PlayerBucketEmptyEvent; +import org.bukkit.event.player.PlayerBucketFillEvent; +import org.github.paperspigot.PaperSpigotConfig; + +public class ItemBucket extends Item { + + private final Block a; + + public ItemBucket(Block block) { + this.maxStackSize = 1; + this.a = block; + this.a(CreativeModeTab.f); + } + + public ItemStack a(ItemStack itemstack, World world, EntityHuman entityhuman) { //useItem + boolean flag = this.a == Blocks.AIR; + MovingObjectPosition movingobjectposition = this.a(world, entityhuman, flag); + + if (movingobjectposition != null) { + if (movingobjectposition.type == MovingObjectPosition.EnumMovingObjectType.BLOCK) { + BlockPosition blockposition = movingobjectposition.a(); + + if (!world.a(entityhuman, blockposition)) { + return itemstack; + } + + if (flag) { + if (!entityhuman.a(blockposition.shift(movingobjectposition.direction), movingobjectposition.direction, itemstack)) { + return itemstack; + } + + IBlockData iblockdata = world.getType(blockposition); + Material material = iblockdata.getBlock().getMaterial(); + + if (material == Material.WATER && iblockdata.get(BlockFluids.LEVEL) == 0) { + PlayerBucketFillEvent event = CraftEventFactory.callPlayerBucketFillEvent(entityhuman, blockposition.getX(), blockposition.getY(), blockposition.getZ(), null, itemstack, Items.WATER_BUCKET); + if (event.isCancelled()) { + // Vortex - Fix lava & water desync bug + ((EntityPlayer) entityhuman).updateInventory(entityhuman.activeContainer); // Update in hand item to prevent inventory desync + entityhuman.sendPacket(new PacketPlayOutBlockChange(world, blockposition)); + return itemstack; + } + + world.setAir(blockposition); + entityhuman.b(StatisticList.USE_ITEM_COUNT[Item.getId(this)]); + ItemStack result = a(itemstack, entityhuman, Items.WATER_BUCKET, event.getItemStack()); + // CraftBukkit - added Event stack + notifyChanges(entityhuman, world, blockposition); + return result; + } + + if (material == Material.LAVA && iblockdata.get(BlockFluids.LEVEL) == 0) { + PlayerBucketFillEvent event = CraftEventFactory.callPlayerBucketFillEvent(entityhuman, blockposition.getX(), blockposition.getY(), blockposition.getZ(), null, itemstack, Items.LAVA_BUCKET); + if (event.isCancelled()) { + // Vortex - Fix lava & water desync bug + ((EntityPlayer) entityhuman).updateInventory(entityhuman.activeContainer); // Update in hand item to prevent inventory desync + entityhuman.sendPacket(new PacketPlayOutBlockChange(world, blockposition)); + return itemstack; + } + + world.setAir(blockposition); + entityhuman.b(StatisticList.USE_ITEM_COUNT[Item.getId(this)]); + ItemStack result = a(itemstack, entityhuman, Items.LAVA_BUCKET, event.getItemStack()); + // CraftBukkit - added Event stack + notifyChanges(entityhuman, world, blockposition); + return result; + } + } else { + + BlockPosition blockposition1 = blockposition.shift(movingobjectposition.direction); + + if (!entityhuman.a(blockposition1, movingobjectposition.direction, itemstack)) { + return itemstack; + } + + // CraftBukkit start + PlayerBucketEmptyEvent event = CraftEventFactory.callPlayerBucketEmptyEvent(entityhuman, blockposition.getX(), blockposition.getY(), blockposition.getZ(), movingobjectposition.direction, itemstack); + + int radius = AzuriteConfig.spongeRadius.getValue(); + if (!event.isCancelled() && radius > 0 && AzuriteConfig.spongePreventWaterFlow.getValue()) { + int x = blockposition.getX(), y = blockposition.getY(), z = blockposition.getZ(); + org.bukkit.World bukkitWorld = world.getWorld(); + + for (int searchX = -radius; searchX <= radius; searchX++) { + for (int searchY = -radius; searchY <= radius; searchY++) { + for (int searchZ = -radius; searchZ <= radius; searchZ++) { + if (bukkitWorld.getBlockAt(x + searchX, y + searchY, z + searchZ).getType() == org.bukkit.Material.SPONGE) { + event.setCancelled(true); + break; + } + } + } + } + } + + if (event.isCancelled()) { + // Vortex - Fix lava & water desync bug + ((EntityPlayer) entityhuman).updateInventory(entityhuman.activeContainer); // Update in hand item to prevent inventory desync + entityhuman.sendPacket(new PacketPlayOutBlockChange(world, blockposition1)); + return itemstack; + } + // CraftBukkit end + + if (this.a(entityhuman, world, blockposition1) && !entityhuman.abilities.canInstantlyBuild) { + entityhuman.b(StatisticList.USE_ITEM_COUNT[Item.getId(this)]); + notifyChanges(entityhuman, world, blockposition); + // PaperSpigot start - Stackable Buckets + ItemStack stack = CraftItemStack.asNMSCopy(event.getItemStack()); + if ((this == Items.LAVA_BUCKET && PaperSpigotConfig.stackableLavaBuckets) || + (this == Items.WATER_BUCKET && PaperSpigotConfig.stackableWaterBuckets)) { + if (--itemstack.count <= 0) { + return stack; + } + if (!entityhuman.inventory.pickup(stack)) { + entityhuman.drop(stack, false); + } + return itemstack; + } + // PaperSpigot end + return stack; // CraftBukkit + } + } + } + + } + return itemstack; + } + + // CraftBukkit - added ob.ItemStack result - TODO: Is this... the right way to handle this? + private ItemStack a(ItemStack itemstack, EntityHuman entityhuman, Item item, org.bukkit.inventory.ItemStack result) { + if (entityhuman.abilities.canInstantlyBuild) { + return itemstack; + } else if (--itemstack.count <= 0) { + return CraftItemStack.asNMSCopy(result); // CraftBukkit + } else { + + if (!entityhuman.inventory.pickup(CraftItemStack.asNMSCopy(result))) { + entityhuman.drop(CraftItemStack.asNMSCopy(result), false); + } + + return itemstack; + } + } + + public boolean a(EntityHuman entityhuman, World world, BlockPosition blockposition) { + if (this.a == Blocks.AIR) { + return false; + } else { + Material material = world.getType(blockposition).getBlock().getMaterial(); + boolean flag = !material.isBuildable(); + + if (!world.isEmpty(blockposition) && !flag) { + return false; + } else { + if (world.worldProvider.n() && this.a == Blocks.FLOWING_WATER) { + int i = blockposition.getX(), j = blockposition.getY(), k = blockposition.getZ(); + + world.makeSound(i + 0.5F, j + 0.5F, k + 0.5F, "random.fizz", 0.5F, 2.6F + (world.random.nextFloat() - world.random.nextFloat()) * 0.8F); + + for (int l = 0; l < 8; ++l) { + world.addParticle(EnumParticle.SMOKE_LARGE, i + Math.random(), j + Math.random(), k + Math.random(), 0.0D, 0.0D, 0.0D, EnumParticle.EMPTY_ARRAY); + } + } else { + if (flag && !material.isLiquid()) { + world.setAir(blockposition, true); + } + + world.setTypeAndData(blockposition, this.a.getBlockData(), 3); + } + + return true; + } + } + } + + // Vortex + // Fix lava & water desync bug + private void notifyChanges(EntityHuman entityhuman, World world, BlockPosition position) { + if (entityhuman != null) { + Chunk chunk = null; + for (int radiusX = -1; radiusX <= 1; radiusX++) { + for (int radiusZ = -1; radiusZ <= 1; radiusZ++) { + int locX = position.getX() + radiusX, locZ = position.getZ() + radiusZ; + + int chunkX = locX >> 4, chunkZ = locZ >> 4; + if (Utils.isInvalidChunk(chunk, chunkX, chunkZ)) // Cache chunk + chunk = world.getChunkAt(chunkX, chunkZ); + + for (int radiusY = -1; radiusY <= 1; radiusY++) { + entityhuman.sendPacket(new PacketPlayOutBlockChange(world, chunk, new BlockPosition(locX, position.getY() + radiusY, locZ))); + } + } + } + ((EntityPlayer) entityhuman).updateInventory(entityhuman.activeContainer); // Update in hand item to prevent inventory desync + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemCarrotStick.java b/azurite-server/src/main/java/net/minecraft/server/ItemCarrotStick.java new file mode 100644 index 0000000..47a2786 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemCarrotStick.java @@ -0,0 +1,30 @@ +package net.minecraft.server; + +public class ItemCarrotStick extends Item { + + public ItemCarrotStick() { + this.a(CreativeModeTab.e); + this.c(1); + this.setMaxDurability(25); + } + + public ItemStack a(ItemStack itemstack, World world, EntityHuman entityhuman) { + if (entityhuman.au() && entityhuman.vehicle instanceof EntityPig) { + EntityPig entitypig = (EntityPig) entityhuman.vehicle; + + if (entitypig.cm().h() && itemstack.j() - itemstack.getData() >= 7) { + entitypig.cm().g(); + itemstack.damage(7, entityhuman); + if (itemstack.count == 0) { + ItemStack itemstack1 = new ItemStack(Items.FISHING_ROD); + + itemstack1.setTag(itemstack.getTag()); + return itemstack1; + } + } + } + + entityhuman.b(StatisticList.USE_ITEM_COUNT[Item.getId(this)]); + return itemstack; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemCloth.java b/azurite-server/src/main/java/net/minecraft/server/ItemCloth.java new file mode 100644 index 0000000..3a89af4 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemCloth.java @@ -0,0 +1,18 @@ +package net.minecraft.server; + +public class ItemCloth extends ItemBlock { + + public ItemCloth(Block block) { + super(block); + this.setMaxDurability(0); + this.a(true); + } + + public int filterData(int i) { + return i; + } + + public String e_(ItemStack itemstack) { + return super.getName() + "." + EnumColor.fromColorIndex(itemstack.getData()).d(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemCoal.java b/azurite-server/src/main/java/net/minecraft/server/ItemCoal.java new file mode 100644 index 0000000..d398370 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemCoal.java @@ -0,0 +1,14 @@ +package net.minecraft.server; + +public class ItemCoal extends Item { + + public ItemCoal() { + this.a(true); + this.setMaxDurability(0); + this.a(CreativeModeTab.l); + } + + public String e_(ItemStack itemstack) { + return itemstack.getData() == 1 ? "item.charcoal" : "item.coal"; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemDoor.java b/azurite-server/src/main/java/net/minecraft/server/ItemDoor.java new file mode 100644 index 0000000..6857d07 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemDoor.java @@ -0,0 +1,60 @@ +package net.minecraft.server; + +public class ItemDoor extends Item { + + private Block a; + + public ItemDoor(Block block) { + this.a = block; + this.a(CreativeModeTab.d); + } + + public boolean interactWith(ItemStack itemstack, EntityHuman entityhuman, World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2) { + if (enumdirection != EnumDirection.UP) { + return false; + } else { + IBlockData iblockdata = world.getType(blockposition); + Block block = iblockdata.getBlock(); + + if (!block.a(world, blockposition)) { + blockposition = blockposition.shift(enumdirection); + } + + if (!entityhuman.a(blockposition, enumdirection, itemstack)) { + return false; + } else if (!this.a.canPlace(world, blockposition)) { + return false; + } else { + a(world, blockposition, EnumDirection.fromAngle(entityhuman.yaw), this.a); + --itemstack.count; + return true; + } + } + } + + public static void a(World world, BlockPosition blockposition, EnumDirection enumdirection, Block block) { + BlockPosition blockposition1 = blockposition.shift(enumdirection.e()); + BlockPosition blockposition2 = blockposition.shift(enumdirection.f()); + + Block block2 = world.getType(blockposition2).getBlock(); + Block block1 = world.getType(blockposition1).getBlock(); + Block block3 = world.getType(blockposition2.getX(), blockposition2.getY() + 1, blockposition2.getZ()).getBlock(); + Block block4 = world.getType(blockposition1.getX(), blockposition1.getY() + 1, blockposition1.getZ()).getBlock(); + + int i = (block2.isOccluding() ? 1 : 0) + (block3.isOccluding() ? 1 : 0); + int j = (block1.isOccluding() ? 1 : 0) + (block4.isOccluding() ? 1 : 0); + boolean flag = block2 == block || block3 == block; + boolean flag1 = block1 == block || block4 == block; + boolean flag2 = flag && !flag1 || j > i; + + BlockPosition blockposition3 = blockposition.up(); + IBlockData iblockdata = block.getBlockData().set(BlockDoor.FACING, enumdirection).set(BlockDoor.HINGE, flag2 ? BlockDoor.EnumDoorHinge.RIGHT : BlockDoor.EnumDoorHinge.LEFT); + + // Spigot start - update physics after the block multi place event + world.setTypeAndData(blockposition, iblockdata.set(BlockDoor.HALF, BlockDoor.EnumDoorHalf.LOWER), 3); + world.setTypeAndData(blockposition3, iblockdata.set(BlockDoor.HALF, BlockDoor.EnumDoorHalf.UPPER), 3); + // world.applyPhysics(blockposition, block); + // world.applyPhysics(blockposition3, block); + // Spigot end + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemDye.java b/azurite-server/src/main/java/net/minecraft/server/ItemDye.java new file mode 100644 index 0000000..67fb9ef --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemDye.java @@ -0,0 +1,108 @@ +package net.minecraft.server; + +import org.bukkit.event.entity.SheepDyeWoolEvent; + +public class ItemDye extends Item { + + public static final int[] a = new int[]{1973019, 11743532, 3887386, 5320730, 2437522, 8073150, 2651799, 11250603, 4408131, 14188952, 4312372, 14602026, 6719955, 12801229, 15435844, 15790320}; + + public ItemDye() { + this.a(true); + this.setMaxDurability(0); + this.a(CreativeModeTab.l); + } + + public static boolean a(ItemStack itemstack, World world, BlockPosition blockposition) { + IBlockData iblockdata = world.getType(blockposition); + + if (iblockdata.getBlock() instanceof IBlockFragilePlantElement) { + IBlockFragilePlantElement iblockfragileplantelement = (IBlockFragilePlantElement) iblockdata.getBlock(); + + if (iblockfragileplantelement.a(world, blockposition, iblockdata, false)) { + if (iblockfragileplantelement.a(world, world.random, blockposition, iblockdata)) { + iblockfragileplantelement.b(world, world.random, blockposition, iblockdata); + } + + --itemstack.count; + + return true; + } + } + + return false; + } + + public String e_(ItemStack itemstack) { + int i = itemstack.getData(); + + return super.getName() + "." + EnumColor.fromInvColorIndex(i).d(); + } + + public boolean interactWith(ItemStack itemstack, EntityHuman entityhuman, World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2) { + if (entityhuman.a(blockposition.shift(enumdirection), enumdirection, itemstack)) { + EnumColor enumcolor = EnumColor.fromInvColorIndex(itemstack.getData()); + + if (enumcolor == EnumColor.WHITE) { + if (a(itemstack, world, blockposition)) { + world.triggerEffect(2005, blockposition, 0); + + return true; + } + } else if (enumcolor == EnumColor.BROWN) { + IBlockData iblockdata = world.getType(blockposition); + Block block = iblockdata.getBlock(); + + if (block == Blocks.LOG && iblockdata.get(BlockWood.VARIANT) == BlockWood.EnumLogVariant.JUNGLE) { + if (enumdirection == EnumDirection.DOWN) { + return false; + } + + if (enumdirection == EnumDirection.UP) { + return false; + } + + blockposition = blockposition.shift(enumdirection); + if (world.isEmpty(blockposition)) { + IBlockData iblockdata1 = Blocks.COCOA.getPlacedState(world, blockposition, enumdirection, f, f1, f2, 0, entityhuman); + + world.setTypeAndData(blockposition, iblockdata1, 2); + if (!entityhuman.abilities.canInstantlyBuild) { + --itemstack.count; + } + } + + return true; + } + } + + } + return false; + } + + public boolean a(ItemStack itemstack, EntityHuman entityhuman, EntityLiving entityliving) { + if (entityliving instanceof EntitySheep) { + EntitySheep entitysheep = (EntitySheep) entityliving; + EnumColor enumcolor = EnumColor.fromInvColorIndex(itemstack.getData()); + + if (!entitysheep.isSheared() && entitysheep.getColor() != enumcolor) { + // CraftBukkit start + byte bColor = (byte) enumcolor.getColorIndex(); + SheepDyeWoolEvent event = new SheepDyeWoolEvent((org.bukkit.entity.Sheep) entitysheep.getBukkitEntity(), org.bukkit.DyeColor.getByData(bColor)); + entitysheep.world.getServer().getPluginManager().callEvent(event); + + if (event.isCancelled()) { + return false; + } + + enumcolor = EnumColor.fromColorIndex(event.getColor().getWoolData()); + // CraftBukkit end + entitysheep.setColor(enumcolor); + --itemstack.count; + } + + return true; + } else { + return false; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemEgg.java b/azurite-server/src/main/java/net/minecraft/server/ItemEgg.java new file mode 100644 index 0000000..fcc3ec2 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemEgg.java @@ -0,0 +1,19 @@ +package net.minecraft.server; + +public class ItemEgg extends Item { + + public ItemEgg() { + this.maxStackSize = 16; + this.a(CreativeModeTab.l); + } + + public ItemStack a(ItemStack itemstack, World world, EntityHuman entityhuman) { + if (!entityhuman.abilities.canInstantlyBuild) { + --itemstack.count; + } + + world.makeSound(entityhuman, "random.bow", 0.5F, 0.4F / (ItemEgg.g.nextFloat() * 0.4F + 0.8F)); + world.addEntity(new EntityEgg(world, entityhuman)); + return itemstack; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemEnchantedBook.java b/azurite-server/src/main/java/net/minecraft/server/ItemEnchantedBook.java new file mode 100644 index 0000000..ef9d422 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemEnchantedBook.java @@ -0,0 +1,85 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.AzuriteConfig; + +import java.util.Random; + +public class ItemEnchantedBook extends Item { + + public ItemEnchantedBook() {} + + public boolean f_(ItemStack itemstack) { + return false; + } + + public EnumItemRarity g(ItemStack itemstack) { + return this.h(itemstack).size() > 0 ? EnumItemRarity.UNCOMMON : super.g(itemstack); + } + + public NBTTagList h(ItemStack itemstack) { + NBTTagCompound nbttagcompound = itemstack.getTag(); + + return nbttagcompound != null && nbttagcompound.hasKeyOfType("StoredEnchantments", 9) ? (NBTTagList) nbttagcompound.get("StoredEnchantments") : new NBTTagList(); + } + + public void a(ItemStack itemstack, WeightedRandomEnchant weightedrandomenchant) { + NBTTagList nbttaglist = this.h(itemstack); + boolean flag = true; + + for (int i = 0; i < nbttaglist.size(); ++i) { + NBTTagCompound nbttagcompound = nbttaglist.get(i); + + if (nbttagcompound.getShort("id") == weightedrandomenchant.enchantment.id) { + if (nbttagcompound.getShort("lvl") < weightedrandomenchant.level) { + nbttagcompound.setShort("lvl", (short) weightedrandomenchant.level); + } + + flag = false; + break; + } + } + + if (flag) { + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + + nbttagcompound1.setShort("id", (short) weightedrandomenchant.enchantment.id); + nbttagcompound1.setShort("lvl", (short) weightedrandomenchant.level); + nbttaglist.add(nbttagcompound1); + } + + if (!itemstack.hasTag()) { + itemstack.setTag(new NBTTagCompound()); + } + + itemstack.getTag().set("StoredEnchantments", nbttaglist); + } + + public ItemStack a(WeightedRandomEnchant weightedrandomenchant) { + ItemStack itemstack = new ItemStack(this); + + this.a(itemstack, weightedrandomenchant); + return itemstack; + } + + public StructurePieceTreasure b(Random random) { + return this.a(random, 1, 1, 1); + } + + public StructurePieceTreasure a(Random random, int i, int j, int k) { + ItemStack itemstack = new ItemStack(Items.BOOK, 1, 0); + + EnchantmentManager.a(random, itemstack, 30); + + // Rivals start + if (AzuriteConfig.structureBookNerf.getValue()) { + boolean flame = EnchantmentManager.getEnchantmentLevel(Enchantment.ARROW_FIRE.id, itemstack) > 0; + boolean infinity = EnchantmentManager.getEnchantmentLevel(Enchantment.ARROW_INFINITE.id, itemstack) > 0; + if (flame || infinity) { + return b(random); + } + } + // Rivals end + + return new StructurePieceTreasure(itemstack, i, j, k); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemEnderEye.java b/azurite-server/src/main/java/net/minecraft/server/ItemEnderEye.java new file mode 100644 index 0000000..c12fda1 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemEnderEye.java @@ -0,0 +1,117 @@ +package net.minecraft.server; + +public class ItemEnderEye extends Item { + + public ItemEnderEye() { + this.a(CreativeModeTab.f); + } + + public boolean interactWith(ItemStack itemstack, EntityHuman entityhuman, World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2) { + IBlockData iblockdata = world.getType(blockposition); + + if (entityhuman.a(blockposition.shift(enumdirection), enumdirection, itemstack) && iblockdata.getBlock() == Blocks.END_PORTAL_FRAME && !iblockdata.get(BlockEnderPortalFrame.EYE)) { + world.setTypeAndData(blockposition, iblockdata.set(BlockEnderPortalFrame.EYE, Boolean.TRUE), 2); + world.updateAdjacentComparators(blockposition, Blocks.END_PORTAL_FRAME); + --itemstack.count; + + for (int i = 0; i < 16; ++i) { + world.addParticle(EnumParticle.SMOKE_NORMAL, blockposition.getX() + (5.0F + ItemEnderEye.g.nextFloat() * 6.0F) / 16.0F, blockposition.getY() + 0.8125F, blockposition.getZ() + (5.0F + ItemEnderEye.g.nextFloat() * 6.0F) / 16.0F, 0, 0, 0, EnumParticle.EMPTY_ARRAY); + } + + EnumDirection enumdirection1 = iblockdata.get(BlockEnderPortalFrame.FACING); + int j = 0; + int k = 0; + boolean flag = false; + boolean flag1 = true; + EnumDirection enumdirection2 = enumdirection1.e(); + + for (int l = -2; l <= 2; ++l) { + BlockPosition blockposition1 = blockposition.shift(enumdirection2, l); + IBlockData iblockdata1 = world.getType(blockposition1); + + if (iblockdata1.getBlock() == Blocks.END_PORTAL_FRAME) { + if (!iblockdata1.get(BlockEnderPortalFrame.EYE)) { + flag1 = false; + break; + } + + k = l; + if (!flag) { + j = l; + flag = true; + } + } + } + + if (flag1 && k == j + 2) { + BlockPosition blockposition2 = blockposition.shift(enumdirection1, 4); + + int i1; + + for (i1 = j; i1 <= k; ++i1) { + BlockPosition blockposition3 = blockposition2.shift(enumdirection2, i1); + IBlockData iblockdata2 = world.getType(blockposition3); + + if (iblockdata2.getBlock() != Blocks.END_PORTAL_FRAME || !iblockdata2.get(BlockEnderPortalFrame.EYE)) { + flag1 = false; + break; + } + } + + int j1; + BlockPosition blockposition4; + + for (i1 = j - 1; i1 <= k + 1; i1 += 4) { + blockposition2 = blockposition.shift(enumdirection2, i1); + + for (j1 = 1; j1 <= 3; ++j1) { + blockposition4 = blockposition2.shift(enumdirection1, j1); + IBlockData iblockdata3 = world.getType(blockposition4); + + if (iblockdata3.getBlock() != Blocks.END_PORTAL_FRAME || !iblockdata3.get(BlockEnderPortalFrame.EYE)) { + flag1 = false; + break; + } + } + } + + if (flag1) { + for (i1 = j; i1 <= k; ++i1) { + blockposition2 = blockposition.shift(enumdirection2, i1); + + for (j1 = 1; j1 <= 3; ++j1) { + blockposition4 = blockposition2.shift(enumdirection1, j1); + world.setTypeAndData(blockposition4, Blocks.END_PORTAL.getBlockData(), 2); + } + } + } + } + + return true; + } else { + return false; + } + } + + public ItemStack a(ItemStack itemstack, World world, EntityHuman entityhuman) { + MovingObjectPosition movingobjectposition = this.a(world, entityhuman, false); + + if (movingobjectposition == null || movingobjectposition.type != MovingObjectPosition.EnumMovingObjectType.BLOCK || world.getType(movingobjectposition.a()).getBlock() != Blocks.END_PORTAL_FRAME) { + BlockPosition blockposition = world.a("Stronghold", new BlockPosition(entityhuman)); + + if (blockposition != null) { + EntityEnderSignal entityendersignal = new EntityEnderSignal(world, entityhuman.locX, entityhuman.locY, entityhuman.locZ); + + entityendersignal.a(blockposition); + world.addEntity(entityendersignal); + world.makeSound(entityhuman, "random.bow", 0.5F, 0.4F / (ItemEnderEye.g.nextFloat() * 0.4F + 0.8F)); + world.a(null, 1002, new BlockPosition(entityhuman), 0); + if (!entityhuman.abilities.canInstantlyBuild) { + --itemstack.count; + } + } + + } + return itemstack; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemEnderPearl.java b/azurite-server/src/main/java/net/minecraft/server/ItemEnderPearl.java new file mode 100644 index 0000000..b6da3d8 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemEnderPearl.java @@ -0,0 +1,30 @@ +package net.minecraft.server; + +import org.bukkit.Bukkit; +import org.bukkit.entity.Projectile; +import org.bukkit.event.entity.PrePearlLaunchEvent; + +public class ItemEnderPearl extends Item { + + public ItemEnderPearl() { + this.maxStackSize = 16; + this.a(CreativeModeTab.f); + } + + public ItemStack a(ItemStack itemstack, World world, EntityHuman entityhuman) { + if (entityhuman.abilities.canInstantlyBuild) + return itemstack; + Entity en = new EntityEnderPearl(world, entityhuman); + if (PrePearlLaunchEvent.getHandlerList().getRegisteredListeners().length != 0) { + Projectile projectile = (Projectile) en.getBukkitEntity(); + PrePearlLaunchEvent event = new PrePearlLaunchEvent(projectile); + Bukkit.getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) + return itemstack; + } + itemstack.count--; + world.makeSound(entityhuman, "random.bow", 0.5F, 0.4F / (g.nextFloat() * 0.4F + 0.8F)); + world.addEntity(en); + return itemstack; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemExpBottle.java b/azurite-server/src/main/java/net/minecraft/server/ItemExpBottle.java new file mode 100644 index 0000000..0c5ce6e --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemExpBottle.java @@ -0,0 +1,18 @@ +package net.minecraft.server; + +public class ItemExpBottle extends Item { + + public ItemExpBottle() { + this.a(CreativeModeTab.f); + } + + public ItemStack a(ItemStack itemstack, World world, EntityHuman entityhuman) { + if (!entityhuman.abilities.canInstantlyBuild) { + --itemstack.count; + } + + world.makeSound(entityhuman, "random.bow", 0.5F, 0.4F / (ItemExpBottle.g.nextFloat() * 0.4F + 0.8F)); + world.addEntity(new EntityThrownExpBottle(world, entityhuman)); + return itemstack; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemFireball.java b/azurite-server/src/main/java/net/minecraft/server/ItemFireball.java new file mode 100644 index 0000000..6b6a7fc --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemFireball.java @@ -0,0 +1,41 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.AzuriteConfig; + +public class ItemFireball extends Item { + + public ItemFireball() { + this.a(CreativeModeTab.f); + } + + public boolean interactWith(ItemStack itemstack, EntityHuman entityhuman, World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2) { + // Rivals start - Prevent fire on dead bushes + if (!AzuriteConfig.allowOnFireOnDeadBush.getValue() && world.getType(blockposition).getBlock() instanceof BlockDeadBush && enumdirection == EnumDirection.UP) { + return false; + } + + blockposition = blockposition.shift(enumdirection); + if (!entityhuman.a(blockposition, enumdirection, itemstack)) { + return false; + } else { + if (world.getType(blockposition).getBlock().getMaterial() == Material.AIR) { + // CraftBukkit start - fire BlockIgniteEvent + if (org.bukkit.craftbukkit.event.CraftEventFactory.callBlockIgniteEvent(world, blockposition.getX(), blockposition.getY(), blockposition.getZ(), org.bukkit.event.block.BlockIgniteEvent.IgniteCause.FIREBALL, entityhuman).isCancelled()) { + if (!entityhuman.abilities.canInstantlyBuild) { + --itemstack.count; + } + return false; + } + // CraftBukkit end + world.makeSound((double) blockposition.getX() + 0.5D, (double) blockposition.getY() + 0.5D, (double) blockposition.getZ() + 0.5D, "item.fireCharge.use", 1.0F, (ItemFireball.g.nextFloat() - ItemFireball.g.nextFloat()) * 0.2F + 1.0F); + world.setTypeUpdate(blockposition, Blocks.FIRE.getBlockData()); + } + + if (!entityhuman.abilities.canInstantlyBuild) { + --itemstack.count; + } + + return true; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemFireworks.java b/azurite-server/src/main/java/net/minecraft/server/ItemFireworks.java new file mode 100644 index 0000000..cdb71a7 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemFireworks.java @@ -0,0 +1,18 @@ +package net.minecraft.server; + +public class ItemFireworks extends Item { + + public ItemFireworks() { + } + + public boolean interactWith(ItemStack itemstack, EntityHuman entityhuman, World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2) { + EntityFireworks entityfireworks = new EntityFireworks(world, (float) blockposition.getX() + f, (float) blockposition.getY() + f1, (float) blockposition.getZ() + f2, itemstack); + + world.addEntity(entityfireworks); + if (!entityhuman.abilities.canInstantlyBuild) { + --itemstack.count; + } + + return true; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemFireworksCharge.java b/azurite-server/src/main/java/net/minecraft/server/ItemFireworksCharge.java new file mode 100644 index 0000000..e7ca932 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemFireworksCharge.java @@ -0,0 +1,6 @@ +package net.minecraft.server; + +public class ItemFireworksCharge extends Item { + + public ItemFireworksCharge() {} +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemFish.java b/azurite-server/src/main/java/net/minecraft/server/ItemFish.java new file mode 100644 index 0000000..aecd8a5 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemFish.java @@ -0,0 +1,127 @@ +package net.minecraft.server; + +import com.google.common.collect.Maps; + +import java.util.Map; + +public class ItemFish extends ItemFood { + + private final boolean b; + + public ItemFish(boolean flag) { + super(0, 0.0F, false); + this.b = flag; + } + + public int getNutrition(ItemStack itemstack) { + EnumFish itemfish_enumfish = EnumFish.a(itemstack); + + return this.b && itemfish_enumfish.g() ? itemfish_enumfish.e() : itemfish_enumfish.c(); + } + + public float getSaturationModifier(ItemStack itemstack) { + EnumFish itemfish_enumfish = EnumFish.a(itemstack); + + return this.b && itemfish_enumfish.g() ? itemfish_enumfish.f() : itemfish_enumfish.d(); + } + + public String j(ItemStack itemstack) { + return EnumFish.a(itemstack) == EnumFish.PUFFERFISH ? PotionBrewer.m : null; + } + + protected void c(ItemStack itemstack, World world, EntityHuman entityhuman) { + EnumFish itemfish_enumfish = EnumFish.a(itemstack); + + if (itemfish_enumfish == EnumFish.PUFFERFISH) { + entityhuman.addEffect(new MobEffect(MobEffectList.POISON.id, 1200, 3)); + entityhuman.addEffect(new MobEffect(MobEffectList.HUNGER.id, 300, 2)); + entityhuman.addEffect(new MobEffect(MobEffectList.CONFUSION.id, 300, 1)); + } + + super.c(itemstack, world, entityhuman); + } + + public String e_(ItemStack itemstack) { + EnumFish itemfish_enumfish = EnumFish.a(itemstack); + + return this.getName() + "." + itemfish_enumfish.b() + "." + (this.b && itemfish_enumfish.g() ? "cooked" : "raw"); + } + + public enum EnumFish { + + COD(0, "cod", 2, 0.1F, 5, 0.6F), SALMON(1, "salmon", 2, 0.1F, 6, 0.8F), CLOWNFISH(2, "clownfish", 1, 0.1F), PUFFERFISH(3, "pufferfish", 1, 0.1F); + + private static final Map e = Maps.newHashMap(); + private final int f; + private final String g; + private final int h; + private final float i; + private final int j; + private final float k; + private final boolean l; + + EnumFish(int i, String s, int j, float f, int k, float f1) { + this.f = i; + this.g = s; + this.h = j; + this.i = f; + this.j = k; + this.k = f1; + this.l = true; + } + + EnumFish(int i, String s, int j, float f) { + this.f = i; + this.g = s; + this.h = j; + this.i = f; + this.j = 0; + this.k = 0.0F; + this.l = false; + } + + public int a() { + return this.f; + } + + public String b() { + return this.g; + } + + public int c() { + return this.h; + } + + public float d() { + return this.i; + } + + public int e() { + return this.j; + } + + public float f() { + return this.k; + } + + public boolean g() { + return this.l; + } + + public static EnumFish a(int i) { + EnumFish itemfish_enumfish = (EnumFish) EnumFish.e.get(i); + + return itemfish_enumfish == null ? EnumFish.COD : itemfish_enumfish; + } + + public static EnumFish a(ItemStack itemstack) { + return itemstack.getItem() instanceof ItemFish ? a(itemstack.getData()) : EnumFish.COD; + } + + static { + for (EnumFish itemfish_enumfish : values()) { + EnumFish.e.put(itemfish_enumfish.a(), itemfish_enumfish); + } + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemFishingRod.java b/azurite-server/src/main/java/net/minecraft/server/ItemFishingRod.java new file mode 100644 index 0000000..1f7ec6d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemFishingRod.java @@ -0,0 +1,45 @@ +package net.minecraft.server; + +import org.bukkit.event.player.PlayerFishEvent; + +public class ItemFishingRod extends Item { + + public ItemFishingRod() { + this.setMaxDurability(64); + this.c(1); + this.a(CreativeModeTab.i); + } + + public ItemStack a(ItemStack itemstack, World world, EntityHuman entityhuman) { + if (entityhuman.hookedFish != null) { + int i = entityhuman.hookedFish.l(); + itemstack.damage(i, entityhuman); + + } else { + // CraftBukkit start + EntityFishingHook hook = new EntityFishingHook(world, entityhuman); + PlayerFishEvent playerFishEvent = new PlayerFishEvent((org.bukkit.entity.Player) entityhuman.getBukkitEntity(), null, (org.bukkit.entity.Fish) hook.getBukkitEntity(), PlayerFishEvent.State.FISHING); + world.getServer().getPluginManager().callEvent(playerFishEvent); + + if (playerFishEvent.isCancelled()) { + entityhuman.hookedFish = null; + return itemstack; + } + // CraftBukkit end + world.makeSound(entityhuman, "random.bow", 0.5F, 0.4F / (ItemFishingRod.g.nextFloat() * 0.4F + 0.8F)); + world.addEntity(hook); // CraftBukkit - moved creation up + } + + entityhuman.bw(); + entityhuman.b(StatisticList.USE_ITEM_COUNT[Item.getId(this)]); + return itemstack; + } + + public boolean f_(ItemStack itemstack) { + return super.f_(itemstack); + } + + public int b() { + return 1; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemFlintAndSteel.java b/azurite-server/src/main/java/net/minecraft/server/ItemFlintAndSteel.java new file mode 100644 index 0000000..31eeb1b --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemFlintAndSteel.java @@ -0,0 +1,66 @@ +package net.minecraft.server; + +// CraftBukkit start +import dev.azurite.spigot.configs.AzuriteConfig; +import org.bukkit.craftbukkit.block.CraftBlockState; +import org.bukkit.craftbukkit.event.CraftEventFactory; +// CraftBukkit end + +public class ItemFlintAndSteel extends Item { + + public ItemFlintAndSteel() { + this.maxStackSize = 1; + this.setMaxDurability(64); + this.a(CreativeModeTab.i); + } + + public boolean interactWith(ItemStack itemstack, EntityHuman entityhuman, World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2) { + BlockPosition clicked = blockposition; // CraftBukkit + // Rivals start - Prevent fire on dead bushes + if (!AzuriteConfig.allowOnFireOnDeadBush.getValue() && world.getType(blockposition).getBlock() instanceof BlockDeadBush && enumdirection == EnumDirection.UP) { + return false; + } + // Rivals end - Prevent fire on dead bushes + blockposition = blockposition.shift(enumdirection); + if (!entityhuman.a(blockposition, enumdirection, itemstack)) { + return false; + } else { + if (world.getType(blockposition).getBlock().getMaterial() == Material.AIR) { + // Rivals start + if (!Blocks.FIRE.canPlace(world, blockposition)) { + return false; + } + // Rivals end + + // CraftBukkit start - Store the clicked block + if (CraftEventFactory.callBlockIgniteEvent(world, blockposition.getX(), blockposition.getY(), blockposition.getZ(), org.bukkit.event.block.BlockIgniteEvent.IgniteCause.FLINT_AND_STEEL, entityhuman).isCancelled()) { + itemstack.damage(1, entityhuman); + return false; + } + + CraftBlockState blockState = CraftBlockState.getBlockState(world, blockposition.getX(), blockposition.getY(), blockposition.getZ()); + // CraftBukkit end + world.makeSound((double) blockposition.getX() + 0.5D, (double) blockposition.getY() + 0.5D, (double) blockposition.getZ() + 0.5D, "fire.ignite", 1.0F, ItemFlintAndSteel.g.nextFloat() * 0.4F + 0.8F); + // Rivals start + if (!world.setTypeUpdate(blockposition, Blocks.FIRE.getBlockData())) { + return false; + } + // Rivals end + + // CraftBukkit start + org.bukkit.event.block.BlockPlaceEvent placeEvent = CraftEventFactory.callBlockPlaceEvent(world, entityhuman, blockState, clicked.getX(), clicked.getY(), clicked.getZ()); + + if (placeEvent.isCancelled() || !placeEvent.canBuild()) { + placeEvent.getBlockPlaced().setTypeIdAndData(0, (byte) 0, false); + return false; + } + // CraftBukkit end + itemstack.damage(1, entityhuman); + + return true; + } else { + return false; + } + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemFood.java b/azurite-server/src/main/java/net/minecraft/server/ItemFood.java new file mode 100644 index 0000000..3f78702 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemFood.java @@ -0,0 +1,106 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.AzuriteConfig; + +public class ItemFood extends Item { + public final int a = 32; + + private final int b; + + private final float c; + + private final boolean d; + + private boolean k; + + private int l; + + private int m; + + private int n; + + private float o; + + public ItemFood(int paramInt, float paramFloat, boolean paramBoolean) { + this.b = paramInt; + this.d = paramBoolean; + this.c = paramFloat; + a(CreativeModeTab.h); + } + + public ItemFood(int paramInt, boolean paramBoolean) { + this(paramInt, 0.6F, paramBoolean); + } + + public ItemStack b(ItemStack paramItemStack, World paramWorld, EntityHuman paramEntityHuman) { + paramItemStack.count--; + paramEntityHuman.getFoodData().a(this, paramItemStack); + paramWorld.makeSound(paramEntityHuman, "random.burp", 0.5F, paramWorld.random.nextFloat() * 0.1F + 0.9F); + c(paramItemStack, paramWorld, paramEntityHuman); + return paramItemStack; + } + + protected void c(ItemStack paramItemStack, World paramWorld, EntityHuman paramEntityHuman) { + if (this.l > 0 && paramWorld.random.nextFloat() < this.o) + paramEntityHuman.addEffect(new MobEffect(this.l, this.m * 20, this.n)); + } + + public int d(ItemStack paramItemStack) { + return 32; + } + + public EnumAnimation e(ItemStack paramItemStack) { + return EnumAnimation.EAT; + } + + public ItemStack a(ItemStack paramItemStack, World paramWorld, EntityHuman paramEntityHuman) { + if (paramEntityHuman.j(k)) { + if (paramEntityHuman instanceof EntityPlayer) { + EntityPlayer player = (EntityPlayer) paramEntityHuman; + + if (!AzuriteConfig.patchDropEatRunBug.getValue() && AzuriteConfig.patchDropEatBug.getValue()) { + PlayerConnection playerConnection = player.playerConnection; + if (playerConnection != null && playerConnection.lastDropTick != 0 && MinecraftServer.currentTick - playerConnection.lastDropTick <= 5) { + return paramItemStack; + } + } + + // Beanes - compensation ticks for eating, we remove the compensated ticks from the ticks needed to eat food + if (AzuriteConfig.compensatedEating.getValue()) { + int ticksNeeded = d(paramItemStack) - player.getEatCompensationTicks(); + paramEntityHuman.a(paramItemStack, ticksNeeded); + return paramItemStack; + } + } + + + paramEntityHuman.a(paramItemStack, d(paramItemStack)); + } + return paramItemStack; + } + + public int getNutrition(ItemStack paramItemStack) { + return this.b; + } + + public float getSaturationModifier(ItemStack paramItemStack) { + return this.c; + } + + public boolean g() { + return this.d; + } + + public ItemFood a(int paramInt1, int paramInt2, int paramInt3, float paramFloat) { + this.l = paramInt1; + this.m = paramInt2; + this.n = paramInt3; + this.o = paramFloat; + return this; + } + + public ItemFood h() { + this.k = true; + return this; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemGlassBottle.java b/azurite-server/src/main/java/net/minecraft/server/ItemGlassBottle.java new file mode 100644 index 0000000..26989fb --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemGlassBottle.java @@ -0,0 +1,37 @@ +package net.minecraft.server; + +public class ItemGlassBottle extends Item { + + public ItemGlassBottle() { + this.a(CreativeModeTab.k); + } + + public ItemStack a(ItemStack itemstack, World world, EntityHuman entityhuman) { + MovingObjectPosition movingobjectposition = this.a(world, entityhuman, true); + + if (movingobjectposition != null && movingobjectposition.type == MovingObjectPosition.EnumMovingObjectType.BLOCK) { + BlockPosition blockposition = movingobjectposition.a(); + + if (!world.a(entityhuman, blockposition)) { + return itemstack; + } + + if (!entityhuman.a(blockposition.shift(movingobjectposition.direction), movingobjectposition.direction, itemstack)) { + return itemstack; + } + + if (world.getType(blockposition).getBlock().getMaterial() == Material.WATER) { + --itemstack.count; + if (itemstack.count <= 0) { + return new ItemStack(Items.POTION); + } + + if (!entityhuman.inventory.pickup(new ItemStack(Items.POTION))) { + entityhuman.drop(new ItemStack(Items.POTION, 1, 0), false); + } + } + + } + return itemstack; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemGoldenApple.java b/azurite-server/src/main/java/net/minecraft/server/ItemGoldenApple.java new file mode 100644 index 0000000..db4134a --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemGoldenApple.java @@ -0,0 +1,25 @@ +package net.minecraft.server; + +public class ItemGoldenApple extends ItemFood { + public ItemGoldenApple(int paramInt, float paramFloat, boolean paramBoolean) { + super(paramInt, paramFloat, paramBoolean); + a(true); + } + + public EnumItemRarity g(ItemStack paramItemStack) { + if (paramItemStack.getData() == 0) + return EnumItemRarity.RARE; + return EnumItemRarity.EPIC; + } + + protected void c(ItemStack paramItemStack, World paramWorld, EntityHuman paramEntityHuman) { + paramEntityHuman.addEffect(new MobEffect(MobEffectList.ABSORBTION.id, 2400, 0)); + if (paramItemStack.getData() > 0) { + paramEntityHuman.addEffect(new MobEffect(MobEffectList.REGENERATION.id, 600, 4)); + paramEntityHuman.addEffect(new MobEffect(MobEffectList.RESISTANCE.id, 6000, 0)); + paramEntityHuman.addEffect(new MobEffect(MobEffectList.FIRE_RESISTANCE.id, 6000, 0)); + } else { + super.c(paramItemStack, paramWorld, paramEntityHuman); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemHanging.java b/azurite-server/src/main/java/net/minecraft/server/ItemHanging.java new file mode 100644 index 0000000..4331f8b --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemHanging.java @@ -0,0 +1,67 @@ +package net.minecraft.server; + +// CraftBukkit start + +import org.bukkit.entity.Player; +import org.bukkit.event.hanging.HangingPlaceEvent; +import org.bukkit.event.painting.PaintingPlaceEvent; +// CraftBukkit end + +public class ItemHanging extends Item { + + private final Class a; + + public ItemHanging(Class oclass) { + this.a = oclass; + this.a(CreativeModeTab.c); + } + + public boolean interactWith(ItemStack itemstack, EntityHuman entityhuman, World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2) { + if (enumdirection == EnumDirection.DOWN) { + return false; + } else if (enumdirection == EnumDirection.UP) { + return false; + } else { + BlockPosition blockposition1 = blockposition.shift(enumdirection); + + if (!entityhuman.a(blockposition1, enumdirection, itemstack)) { + return false; + } else { + EntityHanging entityhanging = this.a(world, blockposition1, enumdirection); + + if (entityhanging != null && entityhanging.survives()) { + + // CraftBukkit start - fire HangingPlaceEvent + Player who = (Player) entityhuman.getBukkitEntity(); + org.bukkit.block.Block blockClicked = world.getWorld().getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()); + org.bukkit.block.BlockFace blockFace = org.bukkit.craftbukkit.block.CraftBlock.notchToBlockFace(enumdirection); + + HangingPlaceEvent event = new HangingPlaceEvent((org.bukkit.entity.Hanging) entityhanging.getBukkitEntity(), who, blockClicked, blockFace); + world.getServer().getPluginManager().callEvent(event); + + PaintingPlaceEvent paintingEvent = null; + if (entityhanging instanceof EntityPainting) { + // Fire old painting event until it can be removed + paintingEvent = new PaintingPlaceEvent((org.bukkit.entity.Painting) entityhanging.getBukkitEntity(), who, blockClicked, blockFace); + paintingEvent.setCancelled(event.isCancelled()); + world.getServer().getPluginManager().callEvent(paintingEvent); + } + + if (event.isCancelled() || (paintingEvent != null && paintingEvent.isCancelled())) { + return false; + } + // CraftBukkit end + world.addEntity(entityhanging); + + --itemstack.count; + } + + return true; + } + } + } + + private EntityHanging a(World world, BlockPosition blockposition, EnumDirection enumdirection) { + return this.a == EntityPainting.class ? new EntityPainting(world, blockposition, enumdirection) : (this.a == EntityItemFrame.class ? new EntityItemFrame(world, blockposition, enumdirection) : null); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemHoe.java b/azurite-server/src/main/java/net/minecraft/server/ItemHoe.java new file mode 100644 index 0000000..fe7f5e3 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemHoe.java @@ -0,0 +1,67 @@ +package net.minecraft.server; + +public class ItemHoe extends Item { + + protected EnumToolMaterial a; + + public ItemHoe(EnumToolMaterial item_enumtoolmaterial) { + this.a = item_enumtoolmaterial; + this.maxStackSize = 1; + this.setMaxDurability(item_enumtoolmaterial.a()); + this.a(CreativeModeTab.i); + } + + public boolean interactWith(ItemStack itemstack, EntityHuman entityhuman, World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2) { + if (entityhuman.a(blockposition.shift(enumdirection), enumdirection, itemstack)) { + IBlockData iblockdata = world.getType(blockposition); + Block block = iblockdata.getBlock(); + + if (enumdirection != EnumDirection.DOWN && world.getType(blockposition.up()).getBlock().getMaterial() == Material.AIR) { + if (block == Blocks.GRASS) { + return this.a(itemstack, entityhuman, world, blockposition, Blocks.FARMLAND.getBlockData()); + } + + if (block == Blocks.DIRT) { + switch (SyntheticClass_1.a[iblockdata.get(BlockDirt.VARIANT).ordinal()]) { + case 1: + return this.a(itemstack, entityhuman, world, blockposition, Blocks.FARMLAND.getBlockData()); + + case 2: + return this.a(itemstack, entityhuman, world, blockposition, Blocks.DIRT.getBlockData().set(BlockDirt.VARIANT, BlockDirt.EnumDirtVariant.DIRT)); + } + } + } + + } + return false; + } + + protected boolean a(ItemStack itemstack, EntityHuman entityhuman, World world, BlockPosition blockposition, IBlockData iblockdata) { + world.makeSound((float) blockposition.getX() + 0.5F, (float) blockposition.getY() + 0.5F, (float) blockposition.getZ() + 0.5F, iblockdata.getBlock().stepSound.getStepSound(), (iblockdata.getBlock().stepSound.getVolume1() + 1.0F) / 2.0F, iblockdata.getBlock().stepSound.getVolume2() * 0.8F); + world.setTypeUpdate(blockposition, iblockdata); + itemstack.damage(1, entityhuman); + return true; + } + + public String g() { + return this.a.toString(); + } + + static class SyntheticClass_1 { + + static final int[] a = new int[BlockDirt.EnumDirtVariant.values().length]; + + static { + try { + SyntheticClass_1.a[BlockDirt.EnumDirtVariant.DIRT.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.a[BlockDirt.EnumDirtVariant.COARSE_DIRT.ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + } + + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemLeash.java b/azurite-server/src/main/java/net/minecraft/server/ItemLeash.java new file mode 100644 index 0000000..e686127 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemLeash.java @@ -0,0 +1,60 @@ +package net.minecraft.server; + +import org.bukkit.event.hanging.HangingPlaceEvent; + +import java.util.List; + +public class ItemLeash extends Item { + + public ItemLeash() { + this.a(CreativeModeTab.i); + } + + public static boolean a(EntityHuman entityhuman, World world, BlockPosition blockposition) { + EntityLeash entityleash = EntityLeash.b(world, blockposition); + boolean flag = false; + double d0 = 7.0D; + int i = blockposition.getX(); + int j = blockposition.getY(); + int k = blockposition.getZ(); + List list = world.a(EntityInsentient.class, new AxisAlignedBB((double) i - d0, (double) j - d0, (double) k - d0, (double) i + d0, (double) j + d0, (double) k + d0)); + + for (EntityInsentient entityinsentient : list) { + if (entityinsentient.cc() && entityinsentient.getLeashHolder() == entityhuman) { + if (entityleash == null) { + entityleash = EntityLeash.a(world, blockposition); + + // CraftBukkit start - fire HangingPlaceEvent + HangingPlaceEvent event = new HangingPlaceEvent((org.bukkit.entity.Hanging) entityleash.getBukkitEntity(), entityhuman != null ? (org.bukkit.entity.Player) entityhuman.getBukkitEntity() : null, world.getWorld().getBlockAt(i, j, k), org.bukkit.block.BlockFace.SELF); + world.getServer().getPluginManager().callEvent(event); + + if (event.isCancelled()) { + entityleash.die(); + return false; + } + // CraftBukkit end + } + + // CraftBukkit start + if (org.bukkit.craftbukkit.event.CraftEventFactory.callPlayerLeashEntityEvent(entityinsentient, entityleash, entityhuman).isCancelled()) { + continue; + } + // CraftBukkit end + + entityinsentient.setLeashHolder(entityleash, true); + flag = true; + } + } + + return flag; + } + + public boolean interactWith(ItemStack itemstack, EntityHuman entityhuman, World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2) { + if (world.getType(blockposition).getBlock() instanceof BlockFence) { + a(entityhuman, world, blockposition); + return true; + } else { + return false; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemLeaves.java b/azurite-server/src/main/java/net/minecraft/server/ItemLeaves.java new file mode 100644 index 0000000..31bb831 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemLeaves.java @@ -0,0 +1,21 @@ +package net.minecraft.server; + +public class ItemLeaves extends ItemBlock { + + private final BlockLeaves b; + + public ItemLeaves(BlockLeaves blockleaves) { + super(blockleaves); + this.b = blockleaves; + this.setMaxDurability(0); + this.a(true); + } + + public int filterData(int i) { + return i | 4; + } + + public String e_(ItemStack itemstack) { + return super.getName() + "." + this.b.b(itemstack.getData()).d(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemMapEmpty.java b/azurite-server/src/main/java/net/minecraft/server/ItemMapEmpty.java new file mode 100644 index 0000000..f341d45 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemMapEmpty.java @@ -0,0 +1,34 @@ +package net.minecraft.server; + +public class ItemMapEmpty extends ItemWorldMapBase { + + protected ItemMapEmpty() { + this.a(CreativeModeTab.f); + } + + public ItemStack a(ItemStack itemstack, World world, EntityHuman entityhuman) { + World worldMain = world.getServer().getServer().worlds.get(0); // CraftBukkit - store reference to primary world + ItemStack itemstack1 = new ItemStack(Items.FILLED_MAP, 1, worldMain.b("map")); // CraftBukkit - use primary world for maps + String s = "map_" + itemstack1.getData(); + WorldMap worldmap = new WorldMap(s); + + worldMain.a(s, worldmap); // CraftBukkit + worldmap.scale = 0; + worldmap.a(entityhuman.locX, entityhuman.locZ, worldmap.scale); + worldmap.map = (byte) ((WorldServer) world).dimension; // CraftBukkit - use bukkit dimension + worldmap.c(); + + org.bukkit.craftbukkit.event.CraftEventFactory.callEvent(new org.bukkit.event.server.MapInitializeEvent(worldmap.mapView)); // CraftBukkit + + --itemstack.count; + if (itemstack.count <= 0) { + return itemstack1; + } else { + if (!entityhuman.inventory.pickup(itemstack1.cloneItemStack())) { + entityhuman.drop(itemstack1, false); + } + entityhuman.b(StatisticList.USE_ITEM_COUNT[Item.getId(this)]); + return itemstack; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemMilkBucket.java b/azurite-server/src/main/java/net/minecraft/server/ItemMilkBucket.java new file mode 100644 index 0000000..957dd31 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemMilkBucket.java @@ -0,0 +1,61 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.AzuriteConfig; +import org.github.paperspigot.PaperSpigotConfig; + +public class ItemMilkBucket extends Item { + + public ItemMilkBucket() { + this.c(1); + this.a(CreativeModeTab.f); + } + + public ItemStack b(ItemStack itemstack, World world, EntityHuman entityhuman) { + if (!entityhuman.abilities.canInstantlyBuild) { + --itemstack.count; + } + + // Beanes - make an option for milk to only remove bad effects + if (AzuriteConfig.milkOnlyRemovesBadEffects.getValue()) { + entityhuman.removeBadEffects(); + } else { + entityhuman.removeAllEffects(); + } + + entityhuman.b(StatisticList.USE_ITEM_COUNT[Item.getId(this)]); + // PaperSpigot start - Stackable Buckets + if (PaperSpigotConfig.stackableMilkBuckets) { + if (itemstack.count <= 0) { + return new ItemStack(Items.BUCKET); + } else if (!entityhuman.inventory.pickup(new ItemStack(Items.BUCKET))) { + entityhuman.drop(new ItemStack(Items.BUCKET), false); + } + } + // PaperSpigot end + return itemstack.count <= 0 ? new ItemStack(Items.BUCKET) : itemstack; + } + + public int d(ItemStack itemstack) { + return 32; + } + + public EnumAnimation e(ItemStack itemstack) { + return EnumAnimation.DRINK; + } + + public ItemStack a(ItemStack itemstack, World world, EntityHuman entityhuman) { + if (entityhuman instanceof EntityPlayer) { + EntityPlayer player = (EntityPlayer) entityhuman; + + // Beanes - compensation ticks for drinking potions, we remove the compensated ticks from the ticks needed to drink + if (AzuriteConfig.compensatedEating.getValue()) { + int ticksNeeded = d(itemstack) - player.getEatCompensationTicks(); + entityhuman.a(itemstack, ticksNeeded); + return itemstack; + } + } + + entityhuman.a(itemstack, this.d(itemstack)); + return itemstack; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemMinecart.java b/azurite-server/src/main/java/net/minecraft/server/ItemMinecart.java new file mode 100644 index 0000000..008e274 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemMinecart.java @@ -0,0 +1,133 @@ +package net.minecraft.server; + +// CraftBukkit start + +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.event.block.BlockDispenseEvent; +// CraftBukkit end + +public class ItemMinecart extends Item { + + private static final IDispenseBehavior a = new DispenseBehaviorItem() { + private final DispenseBehaviorItem b = new DispenseBehaviorItem(); + + public ItemStack b(ISourceBlock isourceblock, ItemStack itemstack) { + EnumDirection enumdirection = BlockDispenser.b(isourceblock.f()); + World world = isourceblock.getWorld(); + double d0 = isourceblock.getX() + (double) enumdirection.getAdjacentX() * 1.125D; + double d1 = Math.floor(isourceblock.getY()) + (double) enumdirection.getAdjacentY(); + double d2 = isourceblock.getZ() + (double) enumdirection.getAdjacentZ() * 1.125D; + BlockPosition blockposition = isourceblock.getBlockPosition().shift(enumdirection); + IBlockData iblockdata = world.getType(blockposition); + BlockMinecartTrackAbstract.EnumTrackPosition blockminecarttrackabstract_enumtrackposition = iblockdata.getBlock() instanceof BlockMinecartTrackAbstract ? iblockdata.get(((BlockMinecartTrackAbstract) iblockdata.getBlock()).n()) : BlockMinecartTrackAbstract.EnumTrackPosition.NORTH_SOUTH; + double d3; + + if (BlockMinecartTrackAbstract.d(iblockdata)) { + if (blockminecarttrackabstract_enumtrackposition.c()) { + d3 = 0.6D; + } else { + d3 = 0.1D; + } + } else { + if (iblockdata.getBlock().getMaterial() != Material.AIR || !BlockMinecartTrackAbstract.d(world.getType(blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()))) { + return this.b.a(isourceblock, itemstack); + } + + IBlockData iblockdata1 = world.getType(blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()); + BlockMinecartTrackAbstract.EnumTrackPosition blockminecarttrackabstract_enumtrackposition1 = iblockdata1.getBlock() instanceof BlockMinecartTrackAbstract ? iblockdata1.get(((BlockMinecartTrackAbstract) iblockdata1.getBlock()).n()) : BlockMinecartTrackAbstract.EnumTrackPosition.NORTH_SOUTH; + + if (enumdirection != EnumDirection.DOWN && blockminecarttrackabstract_enumtrackposition1.c()) { + d3 = -0.4D; + } else { + d3 = -0.9D; + } + } + + // CraftBukkit start + // EntityMinecartAbstract entityminecartabstract = EntityMinecartAbstract.a(world, d0, d1 + d3, d2, ((ItemMinecart) itemstack.getItem()).b); + ItemStack itemstack1 = itemstack.cloneAndSubtract(1); + org.bukkit.block.Block block2 = world.getWorld().getBlockAt(isourceblock.getBlockPosition().getX(), isourceblock.getBlockPosition().getY(), isourceblock.getBlockPosition().getZ()); + CraftItemStack craftItem = CraftItemStack.asCraftMirror(itemstack1); + + BlockDispenseEvent event = new BlockDispenseEvent(block2, craftItem.clone(), new org.bukkit.util.Vector(d0, d1 + d3, d2)); + if (!BlockDispenser.eventFired) { + world.getServer().getPluginManager().callEvent(event); + } + + if (event.isCancelled()) { + itemstack.count++; + return itemstack; + } + + if (!event.getItem().equals(craftItem)) { + itemstack.count++; + // Chain to handler for new item + ItemStack eventStack = CraftItemStack.asNMSCopy(event.getItem()); + IDispenseBehavior idispensebehavior = BlockDispenser.REGISTRY.get(eventStack.getItem()); + if (idispensebehavior != IDispenseBehavior.NONE && idispensebehavior != this) { + idispensebehavior.a(isourceblock, eventStack); + return itemstack; + } + } + + itemstack1 = CraftItemStack.asNMSCopy(event.getItem()); + EntityMinecartAbstract entityminecartabstract = EntityMinecartAbstract.a(world, event.getVelocity().getX(), event.getVelocity().getY(), event.getVelocity().getZ(), ((ItemMinecart) itemstack1.getItem()).b); + + if (itemstack.hasName()) { + entityminecartabstract.setCustomName(itemstack.getName()); + } + + world.addEntity(entityminecartabstract); + // itemstack.a(1); // CraftBukkit - handled during event processing + // CraftBukkit end + return itemstack; + } + + protected void a(ISourceBlock isourceblock) { + isourceblock.getWorld().triggerEffect(1000, isourceblock.getBlockPosition(), 0); + } + }; + private final EntityMinecartAbstract.EnumMinecartType b; + + public ItemMinecart(EntityMinecartAbstract.EnumMinecartType entityminecartabstract_enumminecarttype) { + this.maxStackSize = 1; + this.b = entityminecartabstract_enumminecarttype; + this.a(CreativeModeTab.e); + BlockDispenser.REGISTRY.a(this, ItemMinecart.a); + } + + public boolean interactWith(ItemStack itemstack, EntityHuman entityhuman, World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2) { + IBlockData iblockdata = world.getType(blockposition); + + if (BlockMinecartTrackAbstract.d(iblockdata)) { + + BlockMinecartTrackAbstract.EnumTrackPosition blockminecarttrackabstract_enumtrackposition = iblockdata.getBlock() instanceof BlockMinecartTrackAbstract ? iblockdata.get(((BlockMinecartTrackAbstract) iblockdata.getBlock()).n()) : BlockMinecartTrackAbstract.EnumTrackPosition.NORTH_SOUTH; + double d0 = 0.0D; + + if (blockminecarttrackabstract_enumtrackposition.c()) { + d0 = 0.5D; + } + + // CraftBukkit start - Minecarts + org.bukkit.event.player.PlayerInteractEvent event = org.bukkit.craftbukkit.event.CraftEventFactory.callPlayerInteractEvent(entityhuman, org.bukkit.event.block.Action.RIGHT_CLICK_BLOCK, blockposition, enumdirection, itemstack); + + if (event.isCancelled()) { + return false; + } + // CraftBukkit end + + EntityMinecartAbstract entityminecartabstract = EntityMinecartAbstract.a(world, (double) blockposition.getX() + 0.5D, (double) blockposition.getY() + 0.0625D + d0, (double) blockposition.getZ() + 0.5D, this.b); + + if (itemstack.hasName()) { + entityminecartabstract.setCustomName(itemstack.getName()); + } + + world.addEntity(entityminecartabstract); + + --itemstack.count; + return true; + } else { + return false; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemMonsterEgg.java b/azurite-server/src/main/java/net/minecraft/server/ItemMonsterEgg.java new file mode 100644 index 0000000..f1ed7d2 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemMonsterEgg.java @@ -0,0 +1,138 @@ +package net.minecraft.server; + +public class ItemMonsterEgg extends Item { + + public ItemMonsterEgg() { + this.a(true); + this.a(CreativeModeTab.f); + } + + public static Entity a(World world, int i, double d0, double d1, double d2) { + // CraftBukkit start - delegate to spawnCreature + return spawnCreature(world, i, d0, d1, d2, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.SPAWNER_EGG); + } + + public static Entity spawnCreature(World world, int i, double d0, double d1, double d2, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason spawnReason) { + // CraftBukkit end + if (!EntityTypes.eggInfo.containsKey(i)) { + return null; + } else { + Entity entity = null; + + for (int j = 0; j < 1; ++j) { + entity = EntityTypes.a(i, world); + if (entity instanceof EntityLiving) { + EntityInsentient entityinsentient = (EntityInsentient) entity; + + entity.setPositionRotation(d0, d1, d2, MathHelper.g(world.random.nextFloat() * 360.0F), 0.0F); + entityinsentient.aK = entityinsentient.yaw; + entityinsentient.aI = entityinsentient.yaw; + entityinsentient.prepare(world.E(MathHelper.floor(entityinsentient.locX), MathHelper.floor(entityinsentient.locY), MathHelper.floor(entityinsentient.locZ)), null); + // CraftBukkit start - don't return an entity when CreatureSpawnEvent is canceled + if (!world.addEntity(entity, spawnReason)) { + entity = null; + } else { + entityinsentient.x(); + } + // CraftBukkit end + } + } + + return entity; + } + } + + public String a(ItemStack itemstack) { + String s = ("" + LocaleI18n.get(this.getName() + ".name")).trim(); + String s1 = EntityTypes.b(itemstack.getData()); + + if (s1 != null) { + s = s + " " + LocaleI18n.get("entity." + s1 + ".name"); + } + + return s; + } + + public boolean interactWith(ItemStack itemstack, EntityHuman entityhuman, World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2) { + if (!entityhuman.a(blockposition.shift(enumdirection), enumdirection, itemstack)) { + return false; + } else { + IBlockData iblockdata = world.getType(blockposition); + + if (iblockdata.getBlock() == Blocks.MOB_SPAWNER) { + TileEntity tileentity = world.getTileEntity(blockposition); + + if (tileentity instanceof TileEntityMobSpawner) { + MobSpawnerAbstract mobspawnerabstract = ((TileEntityMobSpawner) tileentity).getSpawner(); + + mobspawnerabstract.setMobName(EntityTypes.b(itemstack.getData())); + tileentity.update(); + world.notify(blockposition); + if (!entityhuman.abilities.canInstantlyBuild) { + --itemstack.count; + } + + return true; + } + } + + blockposition = blockposition.shift(enumdirection); + double d0 = 0.0D; + + if (enumdirection == EnumDirection.UP && iblockdata instanceof BlockFence) { + d0 = 0.5D; + } + + Entity entity = a(world, itemstack.getData(), (double) blockposition.getX() + 0.5D, (double) blockposition.getY() + d0, (double) blockposition.getZ() + 0.5D); + + if (entity != null) { + if (entity instanceof EntityLiving && itemstack.hasName()) { + entity.setCustomName(itemstack.getName()); + } + + if (!entityhuman.abilities.canInstantlyBuild) { + --itemstack.count; + } + + entityhuman.b(StatisticList.USE_ITEM_COUNT[Item.getId(this)]); + } + + return true; + } + } + + public ItemStack a(ItemStack itemstack, World world, EntityHuman entityhuman) { + MovingObjectPosition movingobjectposition = this.a(world, entityhuman, true); + + if (movingobjectposition != null) { + if (movingobjectposition.type == MovingObjectPosition.EnumMovingObjectType.BLOCK) { + BlockPosition blockposition = movingobjectposition.a(); + + if (!world.a(entityhuman, blockposition)) { + return itemstack; + } + + if (!entityhuman.a(blockposition, movingobjectposition.direction, itemstack)) { + return itemstack; + } + + if (world.getType(blockposition).getBlock() instanceof BlockFluids) { + Entity entity = a(world, itemstack.getData(), (double) blockposition.getX() + 0.5D, (double) blockposition.getY() + 0.5D, (double) blockposition.getZ() + 0.5D); + + if (entity != null) { + if (entity instanceof EntityLiving && itemstack.hasName()) { + entity.setCustomName(itemstack.getName()); + } + + if (!entityhuman.abilities.canInstantlyBuild) { + --itemstack.count; + } + + } + } + } + + } + return itemstack; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemMultiTexture.java b/azurite-server/src/main/java/net/minecraft/server/ItemMultiTexture.java new file mode 100644 index 0000000..ae9c604 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemMultiTexture.java @@ -0,0 +1,43 @@ +package net.minecraft.server; + +import com.google.common.base.Function; + +public class ItemMultiTexture extends ItemBlock { + + protected final Block b; + protected final Function c; + + public ItemMultiTexture(Block block, Block block1, Function function) { + super(block); + this.b = block1; + this.c = function; + this.setMaxDurability(0); + this.a(true); + } + + public ItemMultiTexture(Block block, Block block1, final String[] astring) { + this(block, block1, new Function() { + public String a(ItemStack itemstack) { + int i = itemstack.getData(); + + if (i < 0 || i >= astring.length) { + i = 0; + } + + return astring[i]; + } + + public Object apply(Object object) { + return this.a((ItemStack) object); + } + }); + } + + public int filterData(int i) { + return i; + } + + public String e_(ItemStack itemstack) { + return super.getName() + "." + this.c.apply(itemstack); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemNameTag.java b/azurite-server/src/main/java/net/minecraft/server/ItemNameTag.java new file mode 100644 index 0000000..9c3b3c5 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemNameTag.java @@ -0,0 +1,23 @@ +package net.minecraft.server; + +public class ItemNameTag extends Item { + + public ItemNameTag() { + this.a(CreativeModeTab.i); + } + + public boolean a(ItemStack itemstack, EntityHuman entityhuman, EntityLiving entityliving) { + if (!itemstack.hasName()) { + return false; + } else if (entityliving instanceof EntityInsentient) { + EntityInsentient entityinsentient = (EntityInsentient) entityliving; + + entityinsentient.setCustomName(itemstack.getName()); + entityinsentient.bX(); + --itemstack.count; + return true; + } else { + return super.a(itemstack, entityhuman, entityliving); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemNetherStar.java b/azurite-server/src/main/java/net/minecraft/server/ItemNetherStar.java new file mode 100644 index 0000000..86319b7 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemNetherStar.java @@ -0,0 +1,6 @@ +package net.minecraft.server; + +public class ItemNetherStar extends Item { + + public ItemNetherStar() {} +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemPickaxe.java b/azurite-server/src/main/java/net/minecraft/server/ItemPickaxe.java new file mode 100644 index 0000000..c4c78eb --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemPickaxe.java @@ -0,0 +1,22 @@ +package net.minecraft.server; + +import com.google.common.collect.Sets; + +import java.util.Set; + +public class ItemPickaxe extends ItemTool { + + private static final Set c = Sets.newHashSet(Blocks.ACTIVATOR_RAIL, Blocks.COAL_ORE, Blocks.COBBLESTONE, Blocks.DETECTOR_RAIL, Blocks.DIAMOND_BLOCK, Blocks.DIAMOND_ORE, Blocks.DOUBLE_STONE_SLAB, Blocks.GOLDEN_RAIL, Blocks.GOLD_BLOCK, Blocks.GOLD_ORE, Blocks.ICE, Blocks.IRON_BLOCK, Blocks.IRON_ORE, Blocks.LAPIS_BLOCK, Blocks.LAPIS_ORE, Blocks.LIT_REDSTONE_ORE, Blocks.MOSSY_COBBLESTONE, Blocks.NETHERRACK, Blocks.PACKED_ICE, Blocks.RAIL, Blocks.REDSTONE_ORE, Blocks.SANDSTONE, Blocks.RED_SANDSTONE, Blocks.STONE, Blocks.STONE_SLAB); + + protected ItemPickaxe(EnumToolMaterial item_enumtoolmaterial) { + super(2.0F, item_enumtoolmaterial, ItemPickaxe.c); + } + + public boolean canDestroySpecialBlock(Block block) { + return block == Blocks.OBSIDIAN ? this.b.d() == 3 : (block != Blocks.DIAMOND_BLOCK && block != Blocks.DIAMOND_ORE ? (block != Blocks.EMERALD_ORE && block != Blocks.EMERALD_BLOCK ? (block != Blocks.GOLD_BLOCK && block != Blocks.GOLD_ORE ? (block != Blocks.IRON_BLOCK && block != Blocks.IRON_ORE ? (block != Blocks.LAPIS_BLOCK && block != Blocks.LAPIS_ORE ? (block != Blocks.REDSTONE_ORE && block != Blocks.LIT_REDSTONE_ORE ? (block.getMaterial() == Material.STONE || (block.getMaterial() == Material.ORE || block.getMaterial() == Material.HEAVY)) : this.b.d() >= 2) : this.b.d() >= 1) : this.b.d() >= 1) : this.b.d() >= 2) : this.b.d() >= 2) : this.b.d() >= 2); + } + + public float getDestroySpeed(ItemStack itemstack, Block block) { + return block.getMaterial() != Material.ORE && block.getMaterial() != Material.HEAVY && block.getMaterial() != Material.STONE ? super.getDestroySpeed(itemstack, block) : this.a; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemPiston.java b/azurite-server/src/main/java/net/minecraft/server/ItemPiston.java new file mode 100644 index 0000000..85ff125 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemPiston.java @@ -0,0 +1,12 @@ +package net.minecraft.server; + +public class ItemPiston extends ItemBlock { + + public ItemPiston(Block block) { + super(block); + } + + public int filterData(int i) { + return 7; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemPotion.java b/azurite-server/src/main/java/net/minecraft/server/ItemPotion.java new file mode 100644 index 0000000..74e5ea1 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemPotion.java @@ -0,0 +1,158 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import dev.azurite.spigot.configs.AzuriteConfig; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class ItemPotion extends Item { + + private final Map> a = Maps.newHashMap(); + + public ItemPotion() { + this.c(1); + this.a(true); + this.setMaxDurability(0); + this.a(CreativeModeTab.k); + } + + public static boolean f(int i) { + return (i & 16384) != 0; + } + + public List h(ItemStack itemstack) { + if (itemstack.hasTag() && itemstack.getTag().hasKeyOfType("CustomPotionEffects", 9)) { + ArrayList arraylist = Lists.newArrayList(); + NBTTagList nbttaglist = itemstack.getTag().getList("CustomPotionEffects", 10); + + for (int i = 0; i < nbttaglist.size(); ++i) { + NBTTagCompound nbttagcompound = nbttaglist.get(i); + MobEffect mobeffect = MobEffect.b(nbttagcompound); + + if (mobeffect != null) { + arraylist.add(mobeffect); + } + } + + return arraylist; + } else { + List list = this.a.get(itemstack.getData()); + + if (list == null) { + list = PotionBrewer.getEffects(itemstack.getData(), false); + this.a.put(itemstack.getData(), list); + } + + return list; + } + } + + public List e(int i) { + List list = this.a.get(i); + + if (list == null) { + list = PotionBrewer.getEffects(i, false); + this.a.put(i, list); + } + + return list; + } + + public ItemStack b(ItemStack itemstack, World world, EntityHuman entityhuman) { + if (!entityhuman.abilities.canInstantlyBuild) { + --itemstack.count; + } + + List list = this.h(itemstack); + + if (list != null) { + for (MobEffect mobeffect : list) { + // Beanes - make drinkable potion effect particles toggleable + MobEffect effect = new MobEffect(mobeffect); + + if (AzuriteConfig.drinkablePotionsNoParticles.getValue()) { + effect.particles = false; + } + + entityhuman.addEffect(effect); + } + } + + if (!entityhuman.abilities.canInstantlyBuild) { + if (AzuriteConfig.autoRemovePotionAfterDrink.getValue()) { + return itemstack; + } + + if (itemstack.count <= 0) { + return new ItemStack(Items.GLASS_BOTTLE); + } + + entityhuman.inventory.pickup(new ItemStack(Items.GLASS_BOTTLE)); + } + + return itemstack; + } + + public int d(ItemStack itemstack) { + return 32; + } + + public EnumAnimation e(ItemStack itemstack) { + return EnumAnimation.DRINK; + } + + public ItemStack a(ItemStack itemstack, World world, EntityHuman entityhuman) { + if (f(itemstack.getData())) { + if (!entityhuman.abilities.canInstantlyBuild) { + --itemstack.count; + } + + world.makeSound(entityhuman, "random.bow", 0.5F, 0.4F / (ItemPotion.g.nextFloat() * 0.4F + 0.8F)); + // Azurite - hacky... + EntityPotion.IS_HEALTH_POTION_HACK = (itemstack.getData() == 16421 || itemstack.getData() == 16453); + world.addEntity(new EntityPotion(world, entityhuman, itemstack)); + EntityPotion.IS_HEALTH_POTION_HACK = false; + } else { + if (entityhuman instanceof EntityPlayer) { + EntityPlayer player = (EntityPlayer) entityhuman; + + // Beanes - compensation ticks for drinking potions, we remove the compensated ticks from the ticks needed to drink + if (AzuriteConfig.compensatedEating.getValue()) { + int ticksNeeded = d(itemstack) - player.getEatCompensationTicks(); + entityhuman.a(itemstack, ticksNeeded); + return itemstack; + } + } + + entityhuman.a(itemstack, this.d(itemstack)); + } + return itemstack; + } + + public String a(ItemStack itemstack) { + if (itemstack.getData() == 0) { + return LocaleI18n.get("item.emptyPotion.name").trim(); + } else { + String s = ""; + + if (f(itemstack.getData())) { + s = LocaleI18n.get("potion.prefix.grenade").trim() + " "; + } + + List list = Items.POTION.h(itemstack); + String s1; + + if (list != null && !list.isEmpty()) { + s1 = list.get(0).g(); + s1 = s1 + ".postfix"; + return s + LocaleI18n.get(s1).trim(); + } else { + s1 = PotionBrewer.c(itemstack.getData()); + return LocaleI18n.get(s1).trim() + " " + super.a(itemstack); + } + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemRecord.java b/azurite-server/src/main/java/net/minecraft/server/ItemRecord.java new file mode 100644 index 0000000..a8a1161 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemRecord.java @@ -0,0 +1,27 @@ +package net.minecraft.server; + +import com.google.common.collect.Maps; + +import java.util.Map; + +public class ItemRecord extends Item { + + private static final Map b = Maps.newHashMap(); + public final String a; + + protected ItemRecord(String s) { + this.a = s; + this.maxStackSize = 1; + this.a(CreativeModeTab.f); + ItemRecord.b.put("records." + s, this); + } + + public boolean interactWith(ItemStack itemstack, EntityHuman entityhuman, World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2) { + IBlockData iblockdata = world.getType(blockposition); + return iblockdata.getBlock() == Blocks.JUKEBOX && !iblockdata.get(BlockJukeBox.HAS_RECORD); + } + + public EnumItemRarity g(ItemStack itemstack) { + return EnumItemRarity.RARE; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemRedstone.java b/azurite-server/src/main/java/net/minecraft/server/ItemRedstone.java new file mode 100644 index 0000000..b7e8a7e --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemRedstone.java @@ -0,0 +1,29 @@ +package net.minecraft.server; + +public class ItemRedstone extends Item { + + public ItemRedstone() { + this.a(CreativeModeTab.d); + } + + public boolean interactWith(ItemStack itemstack, EntityHuman entityhuman, World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2) { + boolean flag = world.getType(blockposition).getBlock().a(world, blockposition); + BlockPosition blockposition1 = flag ? blockposition : blockposition.shift(enumdirection); + + if (!entityhuman.a(blockposition1, enumdirection, itemstack)) { + return false; + } else { + Block block = world.getType(blockposition1).getBlock(); + + if (!world.a(block, blockposition1, false, enumdirection, null, itemstack)) { + return false; + } else if (Blocks.REDSTONE_WIRE.canPlace(world, blockposition1)) { + --itemstack.count; + world.setTypeUpdate(blockposition1, Blocks.REDSTONE_WIRE.getBlockData()); + return true; + } else { + return false; + } + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemReed.java b/azurite-server/src/main/java/net/minecraft/server/ItemReed.java new file mode 100644 index 0000000..98b4d78 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemReed.java @@ -0,0 +1,45 @@ +package net.minecraft.server; + +public class ItemReed extends Item { + + private final Block a; + + public ItemReed(Block block) { + this.a = block; + } + + public boolean interactWith(ItemStack itemstack, EntityHuman entityhuman, World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2) { + IBlockData iblockdata = world.getType(blockposition); + Block block = iblockdata.getBlock(); + + if (block == Blocks.SNOW_LAYER && iblockdata.get(BlockSnow.LAYERS) < 1) { + enumdirection = EnumDirection.UP; + } else if (!block.a(world, blockposition)) { + blockposition = blockposition.shift(enumdirection); + } + + if (!entityhuman.a(blockposition, enumdirection, itemstack)) { + return false; + } else if (itemstack.count == 0) { + return false; + } else { + if (world.a(this.a, blockposition, false, enumdirection, null, itemstack)) { + IBlockData iblockdata1 = this.a.getPlacedState(world, blockposition, enumdirection, f, f1, f2, 0, entityhuman); + + if (world.setTypeAndData(blockposition, iblockdata1, 3)) { + iblockdata1 = world.getType(blockposition); + if (iblockdata1.getBlock() == this.a) { + ItemBlock.a(world, entityhuman, blockposition, itemstack); + iblockdata1.getBlock().postPlace(world, blockposition, iblockdata1, entityhuman, itemstack); + } + + world.makeSound((float) blockposition.getX() + 0.5F, (float) blockposition.getY() + 0.5F, (float) blockposition.getZ() + 0.5F, this.a.stepSound.getPlaceSound(), (this.a.stepSound.getVolume1() + 1.0F) / 2.0F, this.a.stepSound.getVolume2() * 0.8F); + --itemstack.count; + return true; + } + } + + return false; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemSaddle.java b/azurite-server/src/main/java/net/minecraft/server/ItemSaddle.java new file mode 100644 index 0000000..9228ed7 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemSaddle.java @@ -0,0 +1,30 @@ +package net.minecraft.server; + +public class ItemSaddle extends Item { + + public ItemSaddle() { + this.maxStackSize = 1; + this.a(CreativeModeTab.e); + } + + public boolean a(ItemStack itemstack, EntityHuman entityhuman, EntityLiving entityliving) { + if (entityliving instanceof EntityPig) { + EntityPig entitypig = (EntityPig) entityliving; + + if (!entitypig.hasSaddle() && !entitypig.isBaby()) { + entitypig.setSaddle(true); + entitypig.world.makeSound(entitypig, "mob.horse.leather", 0.5F, 1.0F); + --itemstack.count; + } + + return true; + } else { + return false; + } + } + + public boolean a(ItemStack itemstack, EntityLiving entityliving, EntityLiving entityliving1) { + this.a(itemstack, null, entityliving); + return true; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemSeedFood.java b/azurite-server/src/main/java/net/minecraft/server/ItemSeedFood.java new file mode 100644 index 0000000..1e5558a --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemSeedFood.java @@ -0,0 +1,27 @@ +package net.minecraft.server; + +public class ItemSeedFood extends ItemFood { + + private final Block b; + private final Block c; + + public ItemSeedFood(int i, float f, Block block, Block block1) { + super(i, f, false); + this.b = block; + this.c = block1; + } + + public boolean interactWith(ItemStack itemstack, EntityHuman entityhuman, World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2) { + if (enumdirection != EnumDirection.UP) { + return false; + } else if (!entityhuman.a(blockposition.shift(enumdirection), enumdirection, itemstack)) { + return false; + } else if (world.getType(blockposition).getBlock() == this.c && world.isEmpty(blockposition.up())) { + world.setTypeUpdate(blockposition.up(), this.b.getBlockData()); + --itemstack.count; + return true; + } else { + return false; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemSeeds.java b/azurite-server/src/main/java/net/minecraft/server/ItemSeeds.java new file mode 100644 index 0000000..4819e99 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemSeeds.java @@ -0,0 +1,27 @@ +package net.minecraft.server; + +public class ItemSeeds extends Item { + + private final Block a; + private final Block b; + + public ItemSeeds(Block block, Block block1) { + this.a = block; + this.b = block1; + this.a(CreativeModeTab.l); + } + + public boolean interactWith(ItemStack itemstack, EntityHuman entityhuman, World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2) { + if (enumdirection != EnumDirection.UP) { + return false; + } else if (!entityhuman.a(blockposition.shift(enumdirection), enumdirection, itemstack)) { + return false; + } else if (world.getType(blockposition).getBlock() == this.b && world.isEmpty(blockposition.up())) { + world.setTypeUpdate(blockposition.up(), this.a.getBlockData()); + --itemstack.count; + return true; + } else { + return false; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemShears.java b/azurite-server/src/main/java/net/minecraft/server/ItemShears.java new file mode 100644 index 0000000..d6effdf --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemShears.java @@ -0,0 +1,27 @@ +package net.minecraft.server; + +public class ItemShears extends Item { + + public ItemShears() { + this.c(1); + this.setMaxDurability(238); + this.a(CreativeModeTab.i); + } + + public boolean a(ItemStack itemstack, World world, Block block, BlockPosition blockposition, EntityLiving entityliving) { + if (block.getMaterial() != Material.LEAVES && block != Blocks.WEB && block != Blocks.TALLGRASS && block != Blocks.VINE && block != Blocks.TRIPWIRE && block != Blocks.WOOL) { + return super.a(itemstack, world, block, blockposition, entityliving); + } else { + itemstack.damage(1, entityliving); + return true; + } + } + + public boolean canDestroySpecialBlock(Block block) { + return block == Blocks.WEB || block == Blocks.REDSTONE_WIRE || block == Blocks.TRIPWIRE; + } + + public float getDestroySpeed(ItemStack itemstack, Block block) { + return block != Blocks.WEB && block.getMaterial() != Material.LEAVES ? (block == Blocks.WOOL ? 5.0F : super.getDestroySpeed(itemstack, block)) : 15.0F; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemSign.java b/azurite-server/src/main/java/net/minecraft/server/ItemSign.java new file mode 100644 index 0000000..60cb24f --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemSign.java @@ -0,0 +1,41 @@ +package net.minecraft.server; + +public class ItemSign extends Item { + + public ItemSign() { + this.maxStackSize = 16; + this.a(CreativeModeTab.c); + } + + public boolean interactWith(ItemStack itemstack, EntityHuman entityhuman, World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2) { + if (enumdirection == EnumDirection.DOWN) { + return false; + } else if (!world.getType(blockposition).getBlock().getMaterial().isBuildable()) { + return false; + } else { + blockposition = blockposition.shift(enumdirection); + if (!entityhuman.a(blockposition, enumdirection, itemstack)) { + return false; + } else if (!Blocks.STANDING_SIGN.canPlace(world, blockposition)) { + return false; + } else { + if (enumdirection == EnumDirection.UP) { + int i = MathHelper.floor((double) ((entityhuman.yaw + 180.0F) * 16.0F / 360.0F) + 0.5D) & 15; + + world.setTypeAndData(blockposition, Blocks.STANDING_SIGN.getBlockData().set(BlockFloorSign.ROTATION, i), 3); + } else { + world.setTypeAndData(blockposition, Blocks.WALL_SIGN.getBlockData().set(BlockWallSign.FACING, enumdirection), 3); + } + + --itemstack.count; + TileEntity tileentity = world.getTileEntity(blockposition); + + if (tileentity instanceof TileEntitySign && !ItemBlock.a(world, entityhuman, blockposition, itemstack)) { + entityhuman.openSign((TileEntitySign) tileentity); + } + + return true; + } + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemSkull.java b/azurite-server/src/main/java/net/minecraft/server/ItemSkull.java new file mode 100644 index 0000000..888ae4b --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemSkull.java @@ -0,0 +1,131 @@ +package net.minecraft.server; + +import com.mojang.authlib.GameProfile; + +public class ItemSkull extends Item { + + private static final String[] a = new String[] { "skeleton", "wither", "zombie", "char", "creeper"}; + + public ItemSkull() { + this.a(CreativeModeTab.c); + this.setMaxDurability(0); + this.a(true); + } + + public boolean interactWith(ItemStack itemstack, EntityHuman entityhuman, World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2) { + if (enumdirection == EnumDirection.DOWN) { + return false; + } else { + IBlockData iblockdata = world.getType(blockposition); + Block block = iblockdata.getBlock(); + boolean flag = block.a(world, blockposition); + + if (!flag) { + if (!world.getType(blockposition).getBlock().getMaterial().isBuildable()) { + return false; + } + + blockposition = blockposition.shift(enumdirection); + } + + if (!entityhuman.a(blockposition, enumdirection, itemstack)) { + return false; + } else if (!Blocks.SKULL.canPlace(world, blockposition)) { + return false; + } else { + // Spigot Start + if ( !Blocks.SKULL.canPlace( world, blockposition ) ) + { + return false; + } + // Spigot End + world.setTypeAndData(blockposition, Blocks.SKULL.getBlockData().set(BlockSkull.FACING, enumdirection), 3); + int i = 0; + + if (enumdirection == EnumDirection.UP) { + i = MathHelper.floor((double) (entityhuman.yaw * 16.0F / 360.0F) + 0.5D) & 15; + } + + TileEntity tileentity = world.getTileEntity(blockposition); + + if (tileentity instanceof TileEntitySkull) { + TileEntitySkull tileentityskull = (TileEntitySkull) tileentity; + + if (itemstack.getData() == 3) { + GameProfile gameprofile = null; + + if (itemstack.hasTag()) { + NBTTagCompound nbttagcompound = itemstack.getTag(); + + if (nbttagcompound.hasKeyOfType("SkullOwner", 10)) { + gameprofile = GameProfileSerializer.deserialize(nbttagcompound.getCompound("SkullOwner")); + } else if (nbttagcompound.hasKeyOfType("SkullOwner", 8) && nbttagcompound.getString("SkullOwner").length() > 0) { + gameprofile = new GameProfile(null, nbttagcompound.getString("SkullOwner")); + } + } + + tileentityskull.setGameProfile(gameprofile); + } else { + tileentityskull.setSkullType(itemstack.getData()); + } + + tileentityskull.setRotation(i); + Blocks.SKULL.a(world, blockposition, tileentityskull); + } + + --itemstack.count; + + return true; + } + } + } + + public int filterData(int i) { + return i; + } + + public String e_(ItemStack itemstack) { + int i = itemstack.getData(); + + if (i < 0 || i >= ItemSkull.a.length) { + i = 0; + } + + return super.getName() + "." + ItemSkull.a[i]; + } + + public String a(ItemStack itemstack) { + if (itemstack.getData() == 3 && itemstack.hasTag()) { + if (itemstack.getTag().hasKeyOfType("SkullOwner", 8)) { + return LocaleI18n.a("item.skull.player.name", itemstack.getTag().getString("SkullOwner")); + } + + if (itemstack.getTag().hasKeyOfType("SkullOwner", 10)) { + NBTTagCompound nbttagcompound = itemstack.getTag().getCompound("SkullOwner"); + + if (nbttagcompound.hasKeyOfType("Name", 8)) { + return LocaleI18n.a("item.skull.player.name", nbttagcompound.getString("Name")); + } + } + } + + return super.a(itemstack); + } + + public boolean a(final NBTTagCompound nbttagcompound) { // Spigot - make final + super.a(nbttagcompound); + if (nbttagcompound.hasKeyOfType("SkullOwner", 8) && nbttagcompound.getString("SkullOwner").length() > 0) { + GameProfile gameprofile = new GameProfile(null, nbttagcompound.getString("SkullOwner")); + + // Spigot start + TileEntitySkull.b(gameprofile, gameprofile1 -> { + nbttagcompound.set("SkullOwner", GameProfileSerializer.serialize(new NBTTagCompound(), gameprofile1)); + return false; + }); + // Spigot end + return true; + } else { + return false; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemSnow.java b/azurite-server/src/main/java/net/minecraft/server/ItemSnow.java new file mode 100644 index 0000000..7b74931 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemSnow.java @@ -0,0 +1,49 @@ +package net.minecraft.server; + +public class ItemSnow extends ItemBlock { + + public ItemSnow(Block block) { + super(block); + this.setMaxDurability(0); + this.a(true); + } + + public boolean interactWith(ItemStack itemstack, EntityHuman entityhuman, World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2) { + if (itemstack.count == 0) { + return false; + } else if (!entityhuman.a(blockposition, enumdirection, itemstack)) { + return false; + } else { + IBlockData iblockdata = world.getType(blockposition); + Block block = iblockdata.getBlock(); + BlockPosition blockposition1 = blockposition; + + if ((enumdirection != EnumDirection.UP || block != this.a) && !block.a(world, blockposition)) { + blockposition1 = blockposition.shift(enumdirection); + iblockdata = world.getType(blockposition1); + block = iblockdata.getBlock(); + } + + if (block == this.a) { + int i = iblockdata.get(BlockSnow.LAYERS); + + if (i <= 7) { + IBlockData iblockdata1 = iblockdata.set(BlockSnow.LAYERS, i + 1); + AxisAlignedBB axisalignedbb = this.a.a(world, blockposition1, iblockdata1); + + if (axisalignedbb != null && world.b(axisalignedbb) && world.setTypeAndData(blockposition1, iblockdata1, 2)) { + world.makeSound((float) blockposition1.getX() + 0.5F, (float) blockposition1.getY() + 0.5F, (float) blockposition1.getZ() + 0.5F, this.a.stepSound.getPlaceSound(), (this.a.stepSound.getVolume1() + 1.0F) / 2.0F, this.a.stepSound.getVolume2() * 0.8F); + --itemstack.count; + return true; + } + } + } + + return super.interactWith(itemstack, entityhuman, world, blockposition1, enumdirection, f, f1, f2); + } + } + + public int filterData(int i) { + return i; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemSnowball.java b/azurite-server/src/main/java/net/minecraft/server/ItemSnowball.java new file mode 100644 index 0000000..c0e7cf3 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemSnowball.java @@ -0,0 +1,19 @@ +package net.minecraft.server; + +public class ItemSnowball extends Item { + + public ItemSnowball() { + this.maxStackSize = 16; + this.a(CreativeModeTab.f); + } + + public ItemStack a(ItemStack itemstack, World world, EntityHuman entityhuman) { + if (!entityhuman.abilities.canInstantlyBuild) { + --itemstack.count; + } + + world.makeSound(entityhuman, "random.bow", 0.5F, 0.4F / (ItemSnowball.g.nextFloat() * 0.4F + 0.8F)); + world.addEntity(new EntitySnowball(world, entityhuman)); + return itemstack; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemSoup.java b/azurite-server/src/main/java/net/minecraft/server/ItemSoup.java new file mode 100644 index 0000000..de3023c --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemSoup.java @@ -0,0 +1,14 @@ +package net.minecraft.server; + +public class ItemSoup extends ItemFood { + + public ItemSoup(int i) { + super(i, false); + this.c(1); + } + + public ItemStack b(ItemStack itemstack, World world, EntityHuman entityhuman) { + super.b(itemstack, world, entityhuman); + return new ItemStack(Items.BOWL); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemSpade.java b/azurite-server/src/main/java/net/minecraft/server/ItemSpade.java new file mode 100644 index 0000000..5918691 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemSpade.java @@ -0,0 +1,18 @@ +package net.minecraft.server; + +import com.google.common.collect.Sets; + +import java.util.Set; + +public class ItemSpade extends ItemTool { + + private static final Set c = Sets.newHashSet(Blocks.CLAY, Blocks.DIRT, Blocks.FARMLAND, Blocks.GRASS, Blocks.GRAVEL, Blocks.MYCELIUM, Blocks.SAND, Blocks.SNOW, Blocks.SNOW_LAYER, Blocks.SOUL_SAND); + + public ItemSpade(EnumToolMaterial item_enumtoolmaterial) { + super(1.0F, item_enumtoolmaterial, ItemSpade.c); + } + + public boolean canDestroySpecialBlock(Block block) { + return block == Blocks.SNOW_LAYER || block == Blocks.SNOW; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemStack.java b/azurite-server/src/main/java/net/minecraft/server/ItemStack.java new file mode 100644 index 0000000..33bfe88 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemStack.java @@ -0,0 +1,777 @@ +package net.minecraft.server; + +import com.google.common.collect.HashMultimap; +import com.google.common.collect.Multimap; +import org.bukkit.Location; +import org.bukkit.TreeType; +import org.bukkit.block.BlockState; +import org.bukkit.craftbukkit.block.CraftBlockState; +import org.bukkit.craftbukkit.util.CraftMagicNumbers; +import org.bukkit.entity.Player; +import org.bukkit.event.world.StructureGrowEvent; +import org.github.paperspigot.PaperSpigotConfig; + +import java.text.DecimalFormat; +import java.util.List; +import java.util.Map; +import java.util.Random; + +public final class ItemStack { + + public static final DecimalFormat a = new DecimalFormat("#.###"); + public int count; + public int c; + private Item item; + private NBTTagCompound tag; + private int damage; + private EntityItemFrame g; + private Block h; + private boolean i; + private Block j; + private boolean k; + + public ItemStack(Block block) { + this(block, 1); + } + + public ItemStack(Block block, int i) { + this(block, i, 0); + } + + public ItemStack(Block block, int i, int j) { + this(Item.getItemOf(block), i, j); + } + + public ItemStack(Item item) { + this(item, 1); + } + + public ItemStack(Item item, int i) { + this(item, i, 0); + } + + public ItemStack(Item item, int i, int j) { + this.h = null; + this.i = false; + this.j = null; + this.k = false; + this.item = item; + this.count = i; + + // CraftBukkit start - Pass to setData to do filtering + this.setData(j); + //this.damage = j; + //if (this.damage < 0) { + // this.damage = 0; + //} + // CraftBukkit end + + } + + public static ItemStack createStack(NBTTagCompound nbttagcompound) { + ItemStack itemstack = new ItemStack(); + + itemstack.c(nbttagcompound); + return itemstack.getItem() != null ? itemstack : null; + } + + private ItemStack() { + this.h = null; + this.i = false; + this.j = null; + this.k = false; + } + + public ItemStack cloneAndSubtract(int i) { + ItemStack itemstack = new ItemStack(this.item, i, this.damage); + + if (this.tag != null) { + itemstack.tag = (NBTTagCompound) this.tag.clone(); + } + + this.count -= i; + return itemstack; + } + + public Item getItem() { + return this.item; + } + + public boolean placeItem(EntityHuman entityhuman, World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2) { + // CraftBukkit start - handle all block place event logic here + int data = this.getData(); + int count = this.count; + + if (!(this.getItem() instanceof ItemBucket)) { // if not bucket + world.captureBlockStates = true; + // special case bonemeal + if (this.getItem() instanceof ItemDye && this.getData() == 15) { + Block block = world.getType(blockposition).getBlock(); + if (block == Blocks.SAPLING || block instanceof BlockMushroom) { + world.captureTreeGeneration = true; + } + } + } + boolean flag = this.getItem().interactWith(this, entityhuman, world, blockposition, enumdirection, f, f1, f2); + int newData = this.getData(); + int newCount = this.count; + this.count = count; + this.setData(data); + world.captureBlockStates = false; + if (flag && world.captureTreeGeneration && !world.capturedBlockStates.isEmpty()) { + world.captureTreeGeneration = false; + Location location = new Location(world.getWorld(), blockposition.getX(), blockposition.getY(), blockposition.getZ()); + TreeType treeType = BlockSapling.treeType; + BlockSapling.treeType = null; + List blocks = (List) world.capturedBlockStates.clone(); + world.capturedBlockStates.clear(); + StructureGrowEvent event = null; + if (treeType != null) { + boolean isBonemeal = getItem() == Items.DYE && data == 15; + event = new StructureGrowEvent(location, treeType, isBonemeal, (Player) entityhuman.getBukkitEntity(), blocks); + org.bukkit.Bukkit.getPluginManager().callEvent(event); + } + if (event == null || !event.isCancelled()) { + // Change the stack to its new contents if it hasn't been tampered with. + if (this.count == count && this.getData() == data) { + this.setData(newData); + this.count = newCount; + } + for (BlockState blockstate : blocks) { + blockstate.update(true); + } + } + + return true; + } + world.captureTreeGeneration = false; + + if (flag) { + org.bukkit.event.block.BlockPlaceEvent placeEvent = null; + List blocks = (List) world.capturedBlockStates.clone(); + world.capturedBlockStates.clear(); + if (blocks.size() > 1) { + placeEvent = org.bukkit.craftbukkit.event.CraftEventFactory.callBlockMultiPlaceEvent(world, entityhuman, blocks, blockposition.getX(), blockposition.getY(), blockposition.getZ()); + } else if (blocks.size() == 1) { + placeEvent = org.bukkit.craftbukkit.event.CraftEventFactory.callBlockPlaceEvent(world, entityhuman, blocks.get(0), blockposition.getX(), blockposition.getY(), blockposition.getZ()); + } + + if (placeEvent != null && (placeEvent.isCancelled() || !placeEvent.canBuild())) { + flag = false; // cancel placement + // revert back all captured blocks + for (BlockState blockstate : blocks) { + blockstate.update(true, false); + } + } else { + // Change the stack to its new contents if it hasn't been tampered with. + if (this.count == count && this.getData() == data) { + this.setData(newData); + this.count = newCount; + } + for (BlockState blockstate : blocks) { + int x = blockstate.getX(); + int y = blockstate.getY(); + int z = blockstate.getZ(); + int updateFlag = ((CraftBlockState) blockstate).getFlag(); + org.bukkit.Material mat = blockstate.getType(); + Block oldBlock = CraftMagicNumbers.getBlock(mat); + BlockPosition newblockposition = new BlockPosition(x, y, z); + IBlockData block = world.getType(newblockposition); + + if (!(block instanceof BlockContainer)) { // Containers get placed automatically + block.getBlock().onPlace(world, newblockposition, block); + } + + world.notifyAndUpdatePhysics(newblockposition, null, oldBlock, block.getBlock(), updateFlag); // send null chunk as chunk.k() returns false by this point + } + + for (Map.Entry e : world.capturedTileEntities.entrySet()) { + world.setTileEntity(e.getKey(), e.getValue()); + } + + // Special case juke boxes as they update their tile entity. Copied from ItemRecord. + if (this.getItem() instanceof ItemRecord) { + ((BlockJukeBox) Blocks.JUKEBOX).a(world, blockposition, world.getType(blockposition), this); + world.a(null, 1005, blockposition, Item.getId(this.getItem())); + --this.count; + entityhuman.b(StatisticList.X); + } + + if (this.getItem() == Items.SKULL) { // Special case skulls to allow wither spawns to be cancelled + BlockPosition bp = blockposition; + if (!world.getType(blockposition).getBlock().a(world, blockposition)) { + if (!world.getType(blockposition).getBlock().getMaterial().isBuildable()) { + bp = null; + } else { + bp = bp.shift(enumdirection); + } + } + if (bp != null) { + TileEntity te = world.getTileEntity(bp); + if (te instanceof TileEntitySkull) { + Blocks.SKULL.a(world, bp, (TileEntitySkull) te); + } + } + } + + entityhuman.b(StatisticList.USE_ITEM_COUNT[Item.getId(this.item)]); + } + } + world.capturedTileEntities.clear(); + world.capturedBlockStates.clear(); + // CraftBukkit end + + return flag; + } + + public float a(Block block) { + return this.getItem().getDestroySpeed(this, block); + } + + public ItemStack a(World world, EntityHuman entityhuman) { + return this.getItem().a(this, world, entityhuman); + } + + public ItemStack b(World world, EntityHuman entityhuman) { + return this.getItem().b(this, world, entityhuman); + } + + public NBTTagCompound save(NBTTagCompound nbttagcompound) { + MinecraftKey minecraftkey = Item.REGISTRY.c(this.item); + + nbttagcompound.setString("id", minecraftkey == null ? "minecraft:air" : minecraftkey.toString()); + nbttagcompound.setByte("Count", (byte) this.count); + nbttagcompound.setShort("Damage", (short) this.damage); + if (this.tag != null) { + nbttagcompound.set("tag", this.tag.clone()); // CraftBukkit - make defensive copy, data is going to another thread + } + + return nbttagcompound; + } + + public void c(NBTTagCompound nbttagcompound) { + if (nbttagcompound.hasKeyOfType("id", 8)) { + this.item = Item.d(nbttagcompound.getString("id")); + } else { + this.item = Item.getById(nbttagcompound.getShort("id")); + } + + this.count = nbttagcompound.getByte("Count"); + /* CraftBukkit start - Route through setData for filtering + this.damage = nbttagcompound.getShort("Damage"); + if (this.damage < 0) { + this.damage = 0; + } + */ + this.setData(nbttagcompound.getShort("Damage")); + // CraftBukkit end + + if (nbttagcompound.hasKeyOfType("tag", 10)) { + // CraftBukkit - make defensive copy as this data may be coming from the save thread + this.tag = (NBTTagCompound) nbttagcompound.getCompound("tag").clone(); + if (this.item != null) { + this.item.a(this.tag); + } + } + + } + + public int getMaxStackSize() { + return this.getItem().getMaxStackSize(); + } + + public boolean isStackable() { + return this.getMaxStackSize() > 1 && (!this.e() || !this.g()); + } + + public boolean e() { + // Spigot Start + if (this.item.getMaxDurability() <= 0) { + return false; + } + return (!hasTag()) || (!getTag().getBoolean("Unbreakable")); + // Spigot End + } + + public boolean usesData() { + return this.item.k(); + } + + public boolean g() { + return this.e() && this.damage > 0; + } + + public int h() { + return this.damage; + } + + public int getData() { + return this.damage; + } + + public void setData(int i) { + // CraftBukkit start - Filter out data for items that shouldn't have it + // The crafting system uses this value for a special purpose so we have to allow it + if (i == 32767) { + this.damage = i; + return; + } + + // Is this a block? + // PaperSpigot start - Allow specific blocks to retain their data values + int id = CraftMagicNumbers.getId(this.getItem()); + if (CraftMagicNumbers.getBlock(id) != Blocks.AIR) { + // If vanilla doesn't use data on it don't allow any + if ((PaperSpigotConfig.dataValueAllowedItems == null || !PaperSpigotConfig.dataValueAllowedItems.contains(id)) && + (!(this.usesData() || this.getItem().usesDurability()))) { + // PaperSpigot end + i = 0; + } + } + + // Filter invalid plant data + if (CraftMagicNumbers.getBlock(CraftMagicNumbers.getId(this.getItem())) == Blocks.DOUBLE_PLANT && (i > 5 || i < 0)) { + i = 0; + } + // CraftBukkit end + this.damage = i; + if (this.damage < -1) { // CraftBukkit + this.damage = 0; + } + + } + + public int j() { + return this.item.getMaxDurability(); + } + + public boolean isDamaged(int i, Random random) { + return isDamaged(i, random, null); + } + + public boolean isDamaged(int i, Random random, EntityLiving entityliving) { + // Spigot end + if (!this.e()) { + return false; + } else { + if (i > 0) { + int j = EnchantmentManager.getEnchantmentLevel(Enchantment.DURABILITY.id, this); + int k = 0; + + for (int l = 0; j > 0 && l < i; ++l) { + if (EnchantmentDurability.a(this, j, random)) { + ++k; + } + } + + i -= k; + // Spigot start + if (entityliving instanceof EntityPlayer) { + org.bukkit.craftbukkit.inventory.CraftItemStack item = org.bukkit.craftbukkit.inventory.CraftItemStack.asCraftMirror(this); + org.bukkit.event.player.PlayerItemDamageEvent event = new org.bukkit.event.player.PlayerItemDamageEvent((org.bukkit.entity.Player) entityliving.getBukkitEntity(), item, i); + org.bukkit.Bukkit.getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) return false; + i = event.getDamage(); + } + // Spigot end + if (i <= 0) { + return false; + } + } + + this.damage += i; + return this.damage > this.j(); + } + } + + public void damage(int i, EntityLiving entityliving) { + if (!(entityliving instanceof EntityHuman) || !((EntityHuman) entityliving).abilities.canInstantlyBuild) { + if (this.e()) { + if (this.isDamaged(i, entityliving.bc(), entityliving)) { // Spigot + entityliving.b(this); + --this.count; + if (entityliving instanceof EntityHuman) { + EntityHuman entityhuman = (EntityHuman) entityliving; + entityhuman.b(StatisticList.BREAK_ITEM_COUNT[Item.getId(this.item)]); + + if (this.count == 0 && this.getItem() instanceof ItemBow) { + entityhuman.ca(); + } + } + + if (this.count < 0) { + this.count = 0; + } + + // CraftBukkit start - Check for item breaking + if (this.count == 0 && entityliving instanceof EntityHuman) { + org.bukkit.craftbukkit.event.CraftEventFactory.callPlayerItemBreakEvent((EntityHuman) entityliving, this); + } + // CraftBukkit end + + this.damage = 0; + } + } + } + } + + public void a(EntityLiving entityliving, EntityHuman entityhuman) { + boolean flag = this.item.a(this, entityliving, entityhuman); + + if (flag) { + entityhuman.b(StatisticList.USE_ITEM_COUNT[Item.getId(this.item)]); + } + } + + public void a(World world, Block block, BlockPosition blockposition, EntityHuman entityhuman) { + boolean flag = this.item.a(this, world, block, blockposition, entityhuman); + + if (flag) { + entityhuman.b(StatisticList.USE_ITEM_COUNT[Item.getId(this.item)]); + } + } + + public boolean b(Block block) { + return this.item.canDestroySpecialBlock(block); + } + + public boolean a(EntityHuman entityhuman, EntityLiving entityliving) { + return this.item.a(this, entityhuman, entityliving); + } + + public ItemStack cloneItemStack() { + ItemStack itemstack = new ItemStack(this.item, this.count, this.damage); + + if (this.tag != null) { + itemstack.tag = (NBTTagCompound) this.tag.clone(); + } + + return itemstack; + } + + public static boolean equals(ItemStack itemstack, ItemStack itemstack1) { + return itemstack == null && itemstack1 == null || (itemstack != null && itemstack1 != null && ((itemstack.tag != null || itemstack1.tag == null) && (itemstack.tag == null || itemstack.tag.equals(itemstack1.tag)))); + } + + // Spigot Start + public static boolean fastMatches(ItemStack itemstack, ItemStack itemstack1) { + if (itemstack == null && itemstack1 == null) { + return true; + } + if (itemstack != null && itemstack1 != null) { + return itemstack.count == itemstack1.count && itemstack.item == itemstack1.item && itemstack.damage == itemstack1.damage; + } + return false; + } + // Spigot End + + // Spigot Start + public static boolean fastMatchesWithoutDurability(ItemStack itemstack, ItemStack itemstack1) { + if (itemstack == null && itemstack1 == null) { + return true; + } + if (itemstack != null && itemstack1 != null) { + return itemstack.count == itemstack1.count && itemstack.item == itemstack1.item; + } + return false; + } + // Spigot End + + public static boolean matches(ItemStack itemstack, ItemStack itemstack1) { + return itemstack == null && itemstack1 == null || (itemstack != null && itemstack1 != null && itemstack.d(itemstack1)); + } + + private boolean d(ItemStack itemstack) { + return this.count == itemstack.count && (this.item == itemstack.item && (this.damage == itemstack.damage && ((this.tag != null || itemstack.tag == null) && (this.tag == null || this.tag.equals(itemstack.tag))))); + } + + // Beanes - add method to check if item is the same without durability + public static boolean matchesWithoutDurability(ItemStack itemstack, ItemStack itemstack1) { + return itemstack == null && itemstack1 == null || (itemstack != null && itemstack1 != null && itemstack.sameWithoutDurability(itemstack1)); + } + + // Beanes - add method to check if item is the same without durability + private boolean sameWithoutDurability(ItemStack itemstack) { + return this.count == itemstack.count && (this.item == itemstack.item && (((this.tag != null || itemstack.tag == null) && (this.tag == null || this.tag.equals(itemstack.tag))))); + } + + public static boolean c(ItemStack itemstack, ItemStack itemstack1) { + return itemstack == null && itemstack1 == null || (itemstack != null && itemstack.doMaterialsMatch(itemstack1)); + } + + public boolean doMaterialsMatch(ItemStack itemstack) { + return itemstack != null && this.item == itemstack.item && this.damage == itemstack.damage; + } + + public String a() { + return this.item.e_(this); + } + + public static ItemStack b(ItemStack itemstack) { + return itemstack == null ? null : itemstack.cloneItemStack(); + } + + public String toString() { + return this.count + "x" + this.item.getName() + "@" + this.damage; + } + + public void a(World world, Entity entity, int i, boolean flag) { + if (this.c > 0) { + --this.c; + } + + this.item.a(this, world, entity, i, flag); + } + + public void a(World world, EntityHuman entityhuman, int i) { + entityhuman.a(StatisticList.CRAFT_BLOCK_COUNT[Item.getId(this.item)], i); + this.item.d(this, world, entityhuman); + } + + public int l() { + return this.getItem().d(this); + } + + public EnumAnimation m() { + return this.getItem().e(this); + } + + public void b(World world, EntityHuman entityhuman, int i) { + this.getItem().a(this, world, entityhuman, i); + } + + public boolean hasTag() { + return this.tag != null; + } + + public NBTTagCompound getTag() { + return this.tag; + } + + public NBTTagCompound a(String s, boolean flag) { + if (this.tag != null && this.tag.hasKeyOfType(s, 10)) { + return this.tag.getCompound(s); + } else if (flag) { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + + this.a(s, nbttagcompound); + return nbttagcompound; + } else { + return null; + } + } + + public NBTTagList getEnchantments() { + return this.tag == null ? null : this.tag.getList("ench", 10); + } + + public void setTag(NBTTagCompound nbttagcompound) { + this.tag = nbttagcompound; + } + + public String getName() { + String s = this.getItem().a(this); + + if (this.tag != null && this.tag.hasKeyOfType("display", 10)) { + NBTTagCompound nbttagcompound = this.tag.getCompound("display"); + + if (nbttagcompound.hasKeyOfType("Name", 8)) { + s = nbttagcompound.getString("Name"); + } + } + + return s; + } + + public ItemStack c(String s) { + if (this.tag == null) { + this.tag = new NBTTagCompound(); + } + + if (!this.tag.hasKeyOfType("display", 10)) { + this.tag.set("display", new NBTTagCompound()); + } + + this.tag.getCompound("display").setString("Name", s); + return this; + } + + public void r() { + if (this.tag != null) { + if (this.tag.hasKeyOfType("display", 10)) { + NBTTagCompound nbttagcompound = this.tag.getCompound("display"); + + nbttagcompound.remove("Name"); + if (nbttagcompound.isEmpty()) { + this.tag.remove("display"); + if (this.tag.isEmpty()) { + this.setTag(null); + } + } + + } + } + } + + public boolean hasName() { + return this.tag != null && (this.tag.hasKeyOfType("display", 10) && this.tag.getCompound("display").hasKeyOfType("Name", 8)); + } + + public EnumItemRarity u() { + return this.getItem().g(this); + } + + public boolean v() { + return this.getItem().f_(this) && !this.hasEnchantments(); + } + + public void addEnchantment(Enchantment enchantment, int i) { + if (this.tag == null) { + this.setTag(new NBTTagCompound()); + } + + if (!this.tag.hasKeyOfType("ench", 9)) { + this.tag.set("ench", new NBTTagList()); + } + + NBTTagList nbttaglist = this.tag.getList("ench", 10); + NBTTagCompound nbttagcompound = new NBTTagCompound(); + + nbttagcompound.setShort("id", (short) enchantment.id); + nbttagcompound.setShort("lvl", (short) ((byte) i)); + nbttaglist.add(nbttagcompound); + } + + public boolean hasEnchantments() { + return this.tag != null && this.tag.hasKeyOfType("ench", 9); + } + + public void a(String s, NBTBase nbtbase) { + if (this.tag == null) { + this.setTag(new NBTTagCompound()); + } + + this.tag.set(s, nbtbase); + } + + public boolean x() { + return this.getItem().s(); + } + + public boolean y() { + return this.g != null; + } + + public void a(EntityItemFrame entityitemframe) { + this.g = entityitemframe; + } + + public EntityItemFrame z() { + return this.g; + } + + public int getRepairCost() { + return this.hasTag() && this.tag.hasKeyOfType("RepairCost", 3) ? this.tag.getInt("RepairCost") : 0; + } + + public void setRepairCost(int i) { + if (!this.hasTag()) { + this.tag = new NBTTagCompound(); + } + + this.tag.setInt("RepairCost", i); + } + + public Multimap B() { + Multimap object; + + if (this.hasTag() && this.tag.hasKeyOfType("AttributeModifiers", 9)) { + object = HashMultimap.create(); + NBTTagList nbttaglist = this.tag.getList("AttributeModifiers", 10); + + for (int i = 0; i < nbttaglist.size(); ++i) { + NBTTagCompound nbttagcompound = nbttaglist.get(i); + AttributeModifier attributemodifier = GenericAttributes.a(nbttagcompound); + + if (attributemodifier != null && attributemodifier.a().getLeastSignificantBits() != 0L && attributemodifier.a().getMostSignificantBits() != 0L) { + object.put(nbttagcompound.getString("AttributeName"), attributemodifier); + } + } + } else { + object = this.getItem().i(); + } + + return object; + } + + public void setItem(Item item) { + this.item = item; + this.setData(this.getData()); // CraftBukkit - Set data again to ensure it is filtered properly + } + + public IChatBaseComponent C() { + ChatComponentText chatcomponenttext = new ChatComponentText(this.getName()); + + if (this.hasName()) { + chatcomponenttext.getChatModifier().setItalic(true); + } + + IChatBaseComponent ichatbasecomponent = (new ChatComponentText("[")).addSibling(chatcomponenttext).a("]"); + + if (this.item != null) { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + + this.save(nbttagcompound); + ichatbasecomponent.getChatModifier().setChatHoverable(new ChatHoverable(ChatHoverable.EnumHoverAction.SHOW_ITEM, new ChatComponentText(nbttagcompound.toString()))); + ichatbasecomponent.getChatModifier().setColor(this.u().e); + } + + return ichatbasecomponent; + } + + public boolean c(Block block) { + if (block == this.h) { + return this.i; + } else { + this.h = block; + if (this.hasTag() && this.tag.hasKeyOfType("CanDestroy", 9)) { + NBTTagList nbttaglist = this.tag.getList("CanDestroy", 8); + + for (int i = 0; i < nbttaglist.size(); ++i) { + Block block1 = Block.getByName(nbttaglist.getString(i)); + + if (block1 == block) { + this.i = true; + return true; + } + } + } + + this.i = false; + return false; + } + } + + public boolean d(Block block) { + if (block == this.j) { + return this.k; + } else { + this.j = block; + if (this.hasTag() && this.tag.hasKeyOfType("CanPlaceOn", 9)) { + NBTTagList nbttaglist = this.tag.getList("CanPlaceOn", 8); + + for (int i = 0; i < nbttaglist.size(); ++i) { + Block block1 = Block.getByName(nbttaglist.getString(i)); + + if (block1 == block) { + this.k = true; + return true; + } + } + } + + this.k = false; + return false; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemStep.java b/azurite-server/src/main/java/net/minecraft/server/ItemStep.java new file mode 100644 index 0000000..90373d6 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemStep.java @@ -0,0 +1,75 @@ +package net.minecraft.server; + +public class ItemStep extends ItemBlock { + + private final BlockStepAbstract b; + private final BlockStepAbstract c; + + public ItemStep(Block block, BlockStepAbstract blockstepabstract, BlockStepAbstract blockstepabstract1) { + super(block); + this.b = blockstepabstract; + this.c = blockstepabstract1; + this.setMaxDurability(0); + this.a(true); + } + + public int filterData(int i) { + return i; + } + + public String e_(ItemStack itemstack) { + return this.b.b(itemstack.getData()); + } + + public boolean interactWith(ItemStack itemstack, EntityHuman entityhuman, World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2) { + if (itemstack.count == 0) { + return false; + } else if (!entityhuman.a(blockposition.shift(enumdirection), enumdirection, itemstack)) { + return false; + } else { + Object object = this.b.a(itemstack); + IBlockData iblockdata = world.getType(blockposition); + + if (iblockdata.getBlock() == this.b) { + IBlockState iblockstate = this.b.n(); + Comparable comparable = iblockdata.get(iblockstate); + BlockStepAbstract.EnumSlabHalf blockstepabstract_enumslabhalf = iblockdata.get(BlockStepAbstract.HALF); + + if ((enumdirection == EnumDirection.UP && blockstepabstract_enumslabhalf == BlockStepAbstract.EnumSlabHalf.BOTTOM || enumdirection == EnumDirection.DOWN && blockstepabstract_enumslabhalf == BlockStepAbstract.EnumSlabHalf.TOP) && comparable == object) { + IBlockData iblockdata1 = this.c.getBlockData().set(iblockstate, comparable); + + if (world.b(this.c.a(world, blockposition, iblockdata1)) && world.setTypeAndData(blockposition, iblockdata1, 3)) { + world.makeSound((float) blockposition.getX() + 0.5F, (float) blockposition.getY() + 0.5F, (float) blockposition.getZ() + 0.5F, this.c.stepSound.getPlaceSound(), (this.c.stepSound.getVolume1() + 1.0F) / 2.0F, this.c.stepSound.getVolume2() * 0.8F); + --itemstack.count; + } + + return true; + } + } + + return this.a(itemstack, world, blockposition.shift(enumdirection), object) || super.interactWith(itemstack, entityhuman, world, blockposition, enumdirection, f, f1, f2); + } + } + + private boolean a(ItemStack itemstack, World world, BlockPosition blockposition, Object object) { + IBlockData iblockdata = world.getType(blockposition); + + if (iblockdata.getBlock() == this.b) { + Comparable comparable = iblockdata.get(this.b.n()); + + if (comparable == object) { + IBlockState state = this.b.n(); + IBlockData iblockdata1 = this.c.getBlockData().set(state, comparable); + + if (world.b(this.c.a(world, blockposition, iblockdata1)) && world.setTypeAndData(blockposition, iblockdata1, 3)) { + world.makeSound((float) blockposition.getX() + 0.5F, (float) blockposition.getY() + 0.5F, (float) blockposition.getZ() + 0.5F, this.c.stepSound.getPlaceSound(), (this.c.stepSound.getVolume1() + 1.0F) / 2.0F, this.c.stepSound.getVolume2() * 0.8F); + --itemstack.count; + } + + return true; + } + } + + return false; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemSword.java b/azurite-server/src/main/java/net/minecraft/server/ItemSword.java new file mode 100644 index 0000000..7ac6b2d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemSword.java @@ -0,0 +1,80 @@ +package net.minecraft.server; + +import com.google.common.collect.Multimap; + +public class ItemSword extends Item { + + private float a; + private final EnumToolMaterial b; + + public ItemSword(EnumToolMaterial item_enumtoolmaterial) { + this.b = item_enumtoolmaterial; + this.maxStackSize = 1; + this.setMaxDurability(item_enumtoolmaterial.a()); + this.a(CreativeModeTab.j); + this.a = 4.0F + item_enumtoolmaterial.c(); + } + + public float g() { + return this.b.c(); + } + + public float getDestroySpeed(ItemStack itemstack, Block block) { + if (block == Blocks.WEB) { + return 15.0F; + } else { + Material material = block.getMaterial(); + + return material != Material.PLANT && material != Material.REPLACEABLE_PLANT && material != Material.CORAL && material != Material.LEAVES && material != Material.PUMPKIN ? 1.0F : 1.5F; + } + } + + public boolean a(ItemStack itemstack, EntityLiving entityliving, EntityLiving entityliving1) { + itemstack.damage(1, entityliving1); + return true; + } + + public boolean a(ItemStack itemstack, World world, Block block, BlockPosition blockposition, EntityLiving entityliving) { + if ((double) block.g(world, blockposition) != 0.0D) { + itemstack.damage(2, entityliving); + } + + return true; + } + + public EnumAnimation e(ItemStack itemstack) { + return EnumAnimation.BLOCK; + } + + public int d(ItemStack itemstack) { + return 72000; + } + + public ItemStack a(ItemStack itemstack, World world, EntityHuman entityhuman) { + entityhuman.a(itemstack, this.d(itemstack)); + return itemstack; + } + + public boolean canDestroySpecialBlock(Block block) { + return block == Blocks.WEB; + } + + public int b() { + return this.b.e(); + } + + public String h() { + return this.b.toString(); + } + + public boolean a(ItemStack itemstack, ItemStack itemstack1) { + return this.b.f() == itemstack1.getItem() ? true : super.a(itemstack, itemstack1); + } + + public Multimap i() { + Multimap multimap = super.i(); + + multimap.put(GenericAttributes.ATTACK_DAMAGE.getName(), new AttributeModifier(ItemSword.f, "Weapon modifier", (double) this.a, 0)); + return multimap; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemTallPlant.java b/azurite-server/src/main/java/net/minecraft/server/ItemTallPlant.java new file mode 100644 index 0000000..8c9ca00 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemTallPlant.java @@ -0,0 +1,10 @@ +package net.minecraft.server; + +import com.google.common.base.Function; + +public class ItemTallPlant extends ItemMultiTexture { + + public ItemTallPlant(Block block, Block block1, Function function) { + super(block, block1, function); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemTool.java b/azurite-server/src/main/java/net/minecraft/server/ItemTool.java new file mode 100644 index 0000000..73cc572 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemTool.java @@ -0,0 +1,63 @@ +package net.minecraft.server; + +import com.google.common.collect.Multimap; + +import java.util.Set; + +public class ItemTool extends Item { + + private final Set c; + protected float a; + private final float d; + protected EnumToolMaterial b; + + protected ItemTool(float f, EnumToolMaterial item_enumtoolmaterial, Set set) { + this.b = item_enumtoolmaterial; + this.c = set; + this.maxStackSize = 1; + this.setMaxDurability(item_enumtoolmaterial.a()); + this.a = item_enumtoolmaterial.b(); + this.d = f + item_enumtoolmaterial.c(); + this.a(CreativeModeTab.i); + } + + public float getDestroySpeed(ItemStack itemstack, Block block) { + return this.c.contains(block) ? this.a : 1.0F; + } + + public boolean a(ItemStack itemstack, EntityLiving entityliving, EntityLiving entityliving1) { + itemstack.damage(2, entityliving1); + return true; + } + + public boolean a(ItemStack itemstack, World world, Block block, BlockPosition blockposition, EntityLiving entityliving) { + if ((double) block.g(world, blockposition) != 0.0D) { + itemstack.damage(1, entityliving); + } + + return true; + } + + public EnumToolMaterial g() { + return this.b; + } + + public int b() { + return this.b.e(); + } + + public String h() { + return this.b.toString(); + } + + public boolean a(ItemStack itemstack, ItemStack itemstack1) { + return this.b.f() == itemstack1.getItem() || super.a(itemstack, itemstack1); + } + + public Multimap i() { + Multimap multimap = super.i(); + + multimap.put(GenericAttributes.ATTACK_DAMAGE.getName(), new AttributeModifier(ItemTool.f, "Tool modifier", this.d, 0)); + return multimap; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemWaterLily.java b/azurite-server/src/main/java/net/minecraft/server/ItemWaterLily.java new file mode 100644 index 0000000..d9fae83 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemWaterLily.java @@ -0,0 +1,48 @@ +package net.minecraft.server; + +public class ItemWaterLily extends ItemWithAuxData { + + public ItemWaterLily(Block block) { + super(block, false); + } + + public ItemStack a(ItemStack itemstack, World world, EntityHuman entityhuman) { + MovingObjectPosition movingobjectposition = this.a(world, entityhuman, true); + + if (movingobjectposition != null) { + if (movingobjectposition.type == MovingObjectPosition.EnumMovingObjectType.BLOCK) { + BlockPosition blockposition = movingobjectposition.a(); + + if (!world.a(entityhuman, blockposition)) { + return itemstack; + } + + if (!entityhuman.a(blockposition.shift(movingobjectposition.direction), movingobjectposition.direction, itemstack)) { + return itemstack; + } + + BlockPosition blockposition1 = blockposition.up(); + IBlockData iblockdata = world.getType(blockposition); + + if (iblockdata.getBlock().getMaterial() == Material.WATER && iblockdata.get(BlockFluids.LEVEL) == 0 && world.isEmpty(blockposition1)) { + // CraftBukkit start - special case for handling block placement with water lilies + org.bukkit.block.BlockState blockstate = org.bukkit.craftbukkit.block.CraftBlockState.getBlockState(world, blockposition1.getX(), blockposition1.getY(), blockposition1.getZ()); + world.setTypeUpdate(blockposition1, Blocks.WATERLILY.getBlockData()); + org.bukkit.event.block.BlockPlaceEvent placeEvent = org.bukkit.craftbukkit.event.CraftEventFactory.callBlockPlaceEvent(world, entityhuman, blockstate, blockposition.getX(), blockposition.getY(), blockposition.getZ()); + if (placeEvent.isCancelled() || !placeEvent.canBuild()) { + blockstate.update(true, false); + return itemstack; + } + // CraftBukkit end + if (!entityhuman.abilities.canInstantlyBuild) { + --itemstack.count; + } + + entityhuman.b(StatisticList.USE_ITEM_COUNT[Item.getId(this)]); + } + } + + } + return itemstack; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemWithAuxData.java b/azurite-server/src/main/java/net/minecraft/server/ItemWithAuxData.java new file mode 100644 index 0000000..ff4eaa3 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemWithAuxData.java @@ -0,0 +1,33 @@ +package net.minecraft.server; + +public class ItemWithAuxData extends ItemBlock { + + private String[] c; + + public ItemWithAuxData(Block block, boolean flag) { + super(block); + if (flag) { + this.setMaxDurability(0); + this.a(true); + } + } + + public int filterData(int i) { + return i; + } + + public ItemWithAuxData a(String[] astring) { + this.c = astring; + return this; + } + + public String e_(ItemStack itemstack) { + if (this.c == null) { + return super.e_(itemstack); + } else { + int i = itemstack.getData(); + + return i >= 0 && i < this.c.length ? super.e_(itemstack) + "." + this.c[i] : super.e_(itemstack); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemWorldMap.java b/azurite-server/src/main/java/net/minecraft/server/ItemWorldMap.java new file mode 100644 index 0000000..d0d8c3a --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemWorldMap.java @@ -0,0 +1,212 @@ +package net.minecraft.server; + +import com.google.common.collect.HashMultiset; +import com.google.common.collect.Iterables; +import com.google.common.collect.Multisets; +import org.bukkit.Bukkit; +import org.bukkit.event.server.MapInitializeEvent; +// CraftBukkit end + +public class ItemWorldMap extends ItemWorldMapBase { + + protected ItemWorldMap() { + this.a(true); + } + + public WorldMap getSavedMap(ItemStack itemstack, World world) { + World worldMain = world.getServer().getServer().worlds.get(0); // CraftBukkit - store reference to primary world + String s = "map_" + itemstack.getData(); + WorldMap worldmap = (WorldMap) worldMain.a(WorldMap.class, s); // CraftBukkit - use primary world for maps + + if (worldmap == null) { + itemstack.setData(worldMain.b("map")); // CraftBukkit - use primary world for maps + s = "map_" + itemstack.getData(); + worldmap = new WorldMap(s); + worldmap.scale = 3; + worldmap.a(world.getWorldData().c(), world.getWorldData().e(), worldmap.scale); + worldmap.map = (byte) ((WorldServer) world).dimension; // CraftBukkit - fixes Bukkit multiworld maps + worldmap.c(); + worldMain.a(s, worldmap); // CraftBukkit - use primary world for maps + + // CraftBukkit start + MapInitializeEvent event = new MapInitializeEvent(worldmap.mapView); + Bukkit.getServer().getPluginManager().callEvent(event); + // CraftBukkit end + } + + return worldmap; + } + + public void a(World world, Entity entity, WorldMap worldmap) { + // CraftBukkit - world.worldProvider -> ((WorldServer) world) + if (((WorldServer) world).dimension == worldmap.map && entity instanceof EntityHuman) { + int i = 1 << worldmap.scale; + int j = worldmap.centerX; + int k = worldmap.centerZ; + int l = MathHelper.floor(entity.locX - (double) j) / i + 64; + int i1 = MathHelper.floor(entity.locZ - (double) k) / i + 64; + int j1 = 128 / i; + + if (world.worldProvider.o()) { + j1 /= 2; + } + + WorldMap.WorldMapHumanTracker worldmap_worldmaphumantracker = worldmap.a((EntityHuman) entity); + + ++worldmap_worldmaphumantracker.b; + boolean flag = false; + + for (int k1 = l - j1 + 1; k1 < l + j1; ++k1) { + if ((k1 & 15) == (worldmap_worldmaphumantracker.b & 15) || flag) { + flag = false; + double d0 = 0.0D; + + for (int l1 = i1 - j1 - 1; l1 < i1 + j1; ++l1) { + if (k1 >= 0 && l1 >= -1 && k1 < 128 && l1 < 128) { + int i2 = k1 - l; + int j2 = l1 - i1; + boolean flag1 = i2 * i2 + j2 * j2 > (j1 - 2) * (j1 - 2); + int k2 = (j / i + k1 - 64) * i; + int l2 = (k / i + l1 - 64) * i; + HashMultiset hashmultiset = HashMultiset.create(); + Chunk chunk = world.getChunkAtWorldCoords(k2, l2); + + if (!chunk.isEmpty()) { + int i3 = k2 & 15; + int j3 = l2 & 15; + int k3 = 0; + double d1 = 0.0D; + + if (world.worldProvider.o()) { + int l3 = k2 + l2 * 231871; + + l3 = l3 * l3 * 31287121 + l3 * 11; + if ((l3 >> 20 & 1) == 0) { + hashmultiset.add(Blocks.DIRT.g(Blocks.DIRT.getBlockData().set(BlockDirt.VARIANT, BlockDirt.EnumDirtVariant.DIRT)), 10); + } else { + hashmultiset.add(Blocks.STONE.g(Blocks.STONE.getBlockData().set(BlockStone.VARIANT, BlockStone.EnumStoneVariant.STONE)), 100); + } + + d1 = 100.0D; + } else { + for (int i4 = 0; i4 < i; ++i4) { + for (int j4 = 0; j4 < i; ++j4) { + int k4 = chunk.b(i4 + i3, j4 + j3) + 1; + IBlockData iblockdata = Blocks.AIR.getBlockData(); + + if (k4 > 1) { + do { + --k4; + iblockdata = chunk.getBlockData(i4 + i3, k4, j4 + j3); + } while (iblockdata.getBlock().g(iblockdata) == MaterialMapColor.b && k4 > 0); + + if (k4 > 0 && iblockdata.getBlock().getMaterial().isLiquid()) { + int l4 = k4 - 1; + + Block block; + + do { + block = chunk.getTypeAbs(i4 + i3, l4--, j4 + j3); + ++k3; + } while (l4 > 0 && block.getMaterial().isLiquid()); + } + } + + d1 += (double) k4 / (double) (i * i); + hashmultiset.add(iblockdata.getBlock().g(iblockdata)); + } + } + } + + k3 /= i * i; + double d2 = (d1 - d0) * 4.0D / (double) (i + 4) + ((double) (k1 + l1 & 1) - 0.5D) * 0.4D; + byte b0 = 1; + + if (d2 > 0.6D) { + b0 = 2; + } + + if (d2 < -0.6D) { + b0 = 0; + } + + MaterialMapColor materialmapcolor = Iterables.getFirst(Multisets.copyHighestCountFirst(hashmultiset), MaterialMapColor.b); + + if (materialmapcolor == MaterialMapColor.n) { + d2 = (double) k3 * 0.1D + (double) (k1 + l1 & 1) * 0.2D; + b0 = 1; + if (d2 < 0.5D) { + b0 = 2; + } + + if (d2 > 0.9D) { + b0 = 0; + } + } + + d0 = d1; + if (l1 >= 0 && i2 * i2 + j2 * j2 < j1 * j1 && (!flag1 || (k1 + l1 & 1) != 0)) { + byte b1 = worldmap.colors[k1 + l1 * 128]; + byte b2 = (byte) (materialmapcolor.M * 4 + b0); + + if (b1 != b2) { + worldmap.colors[k1 + l1 * 128] = b2; + worldmap.flagDirty(k1, l1); + flag = true; + } + } + } + } + } + } + } + + } + } + + public void a(ItemStack itemstack, World world, Entity entity, int i, boolean flag) { + WorldMap worldmap = this.getSavedMap(itemstack, world); + + if (entity instanceof EntityHuman) { + EntityHuman entityhuman = (EntityHuman) entity; + + worldmap.a(entityhuman, itemstack); + } + + if (flag) { + this.a(world, entity, worldmap); + } + + } + + public Packet c(ItemStack itemstack, World world, EntityHuman entityhuman) { + return this.getSavedMap(itemstack, world).a(itemstack, world, entityhuman); + } + + public void d(ItemStack itemstack, World world, EntityHuman entityhuman) { + if (itemstack.hasTag() && itemstack.getTag().getBoolean("map_is_scaling")) { + WorldMap worldmap = Items.FILLED_MAP.getSavedMap(itemstack, world); + + world = world.getServer().getServer().worlds.get(0); // CraftBukkit - use primary world for maps + + itemstack.setData(world.b("map")); + WorldMap worldmap1 = new WorldMap("map_" + itemstack.getData()); + + worldmap1.scale = (byte) (worldmap.scale + 1); + if (worldmap1.scale > 4) { + worldmap1.scale = 4; + } + + worldmap1.a(worldmap.centerX, worldmap.centerZ, worldmap1.scale); + worldmap1.map = worldmap.map; + worldmap1.c(); + world.a("map_" + itemstack.getData(), worldmap1); + + // CraftBukkit start + MapInitializeEvent event = new MapInitializeEvent(worldmap1.mapView); + Bukkit.getServer().getPluginManager().callEvent(event); + // CraftBukkit end + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemWorldMapBase.java b/azurite-server/src/main/java/net/minecraft/server/ItemWorldMapBase.java new file mode 100644 index 0000000..785e6f4 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemWorldMapBase.java @@ -0,0 +1,14 @@ +package net.minecraft.server; + +public class ItemWorldMapBase extends Item { + + protected ItemWorldMapBase() {} + + public boolean f() { + return true; + } + + public Packet c(ItemStack itemstack, World world, EntityHuman entityhuman) { + return null; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ItemWrittenBook.java b/azurite-server/src/main/java/net/minecraft/server/ItemWrittenBook.java new file mode 100644 index 0000000..5097e72 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ItemWrittenBook.java @@ -0,0 +1,66 @@ +package net.minecraft.server; + +import org.apache.commons.lang3.StringUtils; + +public class ItemWrittenBook extends Item { + public ItemWrittenBook() { + this.c(1); + } + + public static boolean b(NBTTagCompound var0) { + if (!ItemBookAndQuill.b(var0) || !var0.hasKeyOfType("title", 8)) { + return false; + } + String var = var0.getString("title"); + return var != null && var.length() <= 32 && var0.hasKeyOfType("author", 8); + } + + public static int h(ItemStack var0) { + return var0.getTag().getInt("generation"); + } + + @Override + public String a(ItemStack var1) { + if (var1.hasTag()) { + NBTTagCompound var2 = var1.getTag(); + String var3 = var2.getString("title"); + if (!StringUtils.isEmpty(var3)) { + return var3; + } + } + return super.a(var1); + } + + @Override + public ItemStack a(ItemStack var1, World var2, EntityHuman var3) { + this.a(var1, var3); + var3.openBook(var1); + return var1; + } + + private void a(ItemStack var1, EntityHuman var2) { + if (var1 != null && var1.getTag() != null) { + NBTTagCompound var3 = var1.getTag(); + if (!var3.getBoolean("resolved")) { + var3.setBoolean("resolved", true); + if (b(var3)) { + NBTTagList var4 = var3.getList("pages", 8); + for (int var5 = 0; var5 < var4.size(); ++var5) { + String var6 = var4.getString(var5); + IChatBaseComponent var8; + try { + var8 = ChatComponentUtils.filterForDisplay(var2, IChatBaseComponent.ChatSerializer.a(var6), var2); + } catch (Exception var10) { + var8 = new ChatComponentText(var6); + } + var4.a(var5, new NBTTagString(IChatBaseComponent.ChatSerializer.a(var8))); + } + var3.set("pages", var4); + if (var2 instanceof EntityPlayer && var2.bZ() == var1) { + var2.sendPacket(new PacketPlayOutSetSlot(0, var2.activeContainer.getSlot(var2.inventory, var2.inventory.itemInHandIndex).rawSlotIndex, var1)); + } + } + } + } + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/net/minecraft/server/Items.java b/azurite-server/src/main/java/net/minecraft/server/Items.java new file mode 100644 index 0000000..af1bcad --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/Items.java @@ -0,0 +1,390 @@ +package net.minecraft.server; + +public class Items { + + public static final Item IRON_SHOVEL; + public static final Item IRON_PICKAXE; + public static final Item IRON_AXE; + public static final Item FLINT_AND_STEEL; + public static final Item APPLE; + public static final ItemBow BOW; + public static final Item ARROW; + public static final Item COAL; + public static final Item DIAMOND; + public static final Item IRON_INGOT; + public static final Item GOLD_INGOT; + public static final Item IRON_SWORD; + public static final Item WOODEN_SWORD; + public static final Item WOODEN_SHOVEL; + public static final Item WOODEN_PICKAXE; + public static final Item WOODEN_AXE; + public static final Item STONE_SWORD; + public static final Item STONE_SHOVEL; + public static final Item STONE_PICKAXE; + public static final Item STONE_AXE; + public static final Item DIAMOND_SWORD; + public static final Item DIAMOND_SHOVEL; + public static final Item DIAMOND_PICKAXE; + public static final Item DIAMOND_AXE; + public static final Item STICK; + public static final Item BOWL; + public static final Item MUSHROOM_STEW; + public static final Item GOLDEN_SWORD; + public static final Item GOLDEN_SHOVEL; + public static final Item GOLDEN_PICKAXE; + public static final Item GOLDEN_AXE; + public static final Item STRING; + public static final Item FEATHER; + public static final Item GUNPOWDER; + public static final Item WOODEN_HOE; + public static final Item STONE_HOE; + public static final Item IRON_HOE; + public static final Item DIAMOND_HOE; + public static final Item GOLDEN_HOE; + public static final Item WHEAT_SEEDS; + public static final Item WHEAT; + public static final Item BREAD; + public static final ItemArmor LEATHER_HELMET; + public static final ItemArmor LEATHER_CHESTPLATE; + public static final ItemArmor LEATHER_LEGGINGS; + public static final ItemArmor LEATHER_BOOTS; + public static final ItemArmor CHAINMAIL_HELMET; + public static final ItemArmor CHAINMAIL_CHESTPLATE; + public static final ItemArmor CHAINMAIL_LEGGINGS; + public static final ItemArmor CHAINMAIL_BOOTS; + public static final ItemArmor IRON_HELMET; + public static final ItemArmor IRON_CHESTPLATE; + public static final ItemArmor IRON_LEGGINGS; + public static final ItemArmor IRON_BOOTS; + public static final ItemArmor DIAMOND_HELMET; + public static final ItemArmor DIAMOND_CHESTPLATE; + public static final ItemArmor DIAMOND_LEGGINGS; + public static final ItemArmor DIAMOND_BOOTS; + public static final ItemArmor GOLDEN_HELMET; + public static final ItemArmor GOLDEN_CHESTPLATE; + public static final ItemArmor GOLDEN_LEGGINGS; + public static final ItemArmor GOLDEN_BOOTS; + public static final Item FLINT; + public static final Item PORKCHOP; + public static final Item COOKED_PORKCHOP; + public static final Item PAINTING; + public static final Item GOLDEN_APPLE; + public static final Item SIGN; + public static final Item WOODEN_DOOR; + public static final Item SPRUCE_DOOR; + public static final Item BIRCH_DOOR; + public static final Item JUNGLE_DOOR; + public static final Item ACACIA_DOOR; + public static final Item DARK_OAK_DOOR; + public static final Item BUCKET; + public static final Item WATER_BUCKET; + public static final Item LAVA_BUCKET; + public static final Item MINECART; + public static final Item SADDLE; + public static final Item IRON_DOOR; + public static final Item REDSTONE; + public static final Item SNOWBALL; + public static final Item BOAT; + public static final Item LEATHER; + public static final Item MILK_BUCKET; + public static final Item BRICK; + public static final Item CLAY_BALL; + public static final Item REEDS; + public static final Item PAPER; + public static final Item BOOK; + public static final Item SLIME; + public static final Item CHEST_MINECART; + public static final Item FURNACE_MINECART; + public static final Item EGG; + public static final Item COMPASS; + public static final ItemFishingRod FISHING_ROD; + public static final Item CLOCK; + public static final Item GLOWSTONE_DUST; + public static final Item FISH; + public static final Item COOKED_FISH; + public static final Item DYE; + public static final Item BONE; + public static final Item SUGAR; + public static final Item CAKE; + public static final Item BED; + public static final Item REPEATER; + public static final Item COOKIE; + public static final ItemWorldMap FILLED_MAP; + public static final ItemShears SHEARS; + public static final Item MELON; + public static final Item PUMPKIN_SEEDS; + public static final Item MELON_SEEDS; + public static final Item BEEF; + public static final Item COOKED_BEEF; + public static final Item CHICKEN; + public static final Item COOKED_CHICKEN; + public static final Item MUTTON; + public static final Item COOKED_MUTTON; + public static final Item RABBIT; + public static final Item COOKED_RABBIT; + public static final Item RABBIT_STEW; + public static final Item RABBIT_FOOT; + public static final Item RABBIT_HIDE; + public static final Item ROTTEN_FLESH; + public static final Item ENDER_PEARL; + public static final Item BLAZE_ROD; + public static final Item GHAST_TEAR; + public static final Item GOLD_NUGGET; + public static final Item NETHER_WART; + public static final ItemPotion POTION; + public static final Item GLASS_BOTTLE; + public static final Item SPIDER_EYE; + public static final Item FERMENTED_SPIDER_EYE; + public static final Item BLAZE_POWDER; + public static final Item MAGMA_CREAM; + public static final Item BREWING_STAND; + public static final Item CAULDRON; + public static final Item ENDER_EYE; + public static final Item SPECKLED_MELON; + public static final Item SPAWN_EGG; + public static final Item EXPERIENCE_BOTTLE; + public static final Item FIRE_CHARGE; + public static final Item WRITABLE_BOOK; + public static final Item WRITTEN_BOOK; + public static final Item EMERALD; + public static final Item ITEM_FRAME; + public static final Item FLOWER_POT; + public static final Item CARROT; + public static final Item POTATO; + public static final Item BAKED_POTATO; + public static final Item POISONOUS_POTATO; + public static final ItemMapEmpty MAP; + public static final Item GOLDEN_CARROT; + public static final Item SKULL; + public static final Item CARROT_ON_A_STICK; + public static final Item NETHER_STAR; + public static final Item PUMPKIN_PIE; + public static final Item FIREWORKS; + public static final Item FIREWORK_CHARGE; + public static final ItemEnchantedBook ENCHANTED_BOOK; + public static final Item COMPARATOR; + public static final Item NETHERBRICK; + public static final Item QUARTZ; + public static final Item TNT_MINECART; + public static final Item HOPPER_MINECART; + public static final ItemArmorStand ARMOR_STAND; + public static final Item IRON_HORSE_ARMOR; + public static final Item GOLDEN_HORSE_ARMOR; + public static final Item DIAMOND_HORSE_ARMOR; + public static final Item LEAD; + public static final Item NAME_TAG; + public static final Item COMMAND_BLOCK_MINECART; + public static final Item RECORD_13; + public static final Item RECORD_CAT; + public static final Item RECORD_BLOCKS; + public static final Item RECORD_CHIRP; + public static final Item RECORD_FAR; + public static final Item RECORD_MALL; + public static final Item RECORD_MELLOHI; + public static final Item RECORD_STAL; + public static final Item RECORD_STRAD; + public static final Item RECORD_WARD; + public static final Item RECORD_11; + public static final Item RECORD_WAIT; + public static final Item PRISMARINE_SHARD; + public static final Item PRISMARINE_CRYSTALS; + public static final Item BANNER; + + private static Item get(String s) { + return Item.REGISTRY.get(new MinecraftKey(s)); + } + + static { + if (!DispenserRegistry.a()) { + throw new RuntimeException("Accessed Items before Bootstrap!"); + } else { + IRON_SHOVEL = get("iron_shovel"); + IRON_PICKAXE = get("iron_pickaxe"); + IRON_AXE = get("iron_axe"); + FLINT_AND_STEEL = get("flint_and_steel"); + APPLE = get("apple"); + BOW = (ItemBow) get("bow"); + ARROW = get("arrow"); + COAL = get("coal"); + DIAMOND = get("diamond"); + IRON_INGOT = get("iron_ingot"); + GOLD_INGOT = get("gold_ingot"); + IRON_SWORD = get("iron_sword"); + WOODEN_SWORD = get("wooden_sword"); + WOODEN_SHOVEL = get("wooden_shovel"); + WOODEN_PICKAXE = get("wooden_pickaxe"); + WOODEN_AXE = get("wooden_axe"); + STONE_SWORD = get("stone_sword"); + STONE_SHOVEL = get("stone_shovel"); + STONE_PICKAXE = get("stone_pickaxe"); + STONE_AXE = get("stone_axe"); + DIAMOND_SWORD = get("diamond_sword"); + DIAMOND_SHOVEL = get("diamond_shovel"); + DIAMOND_PICKAXE = get("diamond_pickaxe"); + DIAMOND_AXE = get("diamond_axe"); + STICK = get("stick"); + BOWL = get("bowl"); + MUSHROOM_STEW = get("mushroom_stew"); + GOLDEN_SWORD = get("golden_sword"); + GOLDEN_SHOVEL = get("golden_shovel"); + GOLDEN_PICKAXE = get("golden_pickaxe"); + GOLDEN_AXE = get("golden_axe"); + STRING = get("string"); + FEATHER = get("feather"); + GUNPOWDER = get("gunpowder"); + WOODEN_HOE = get("wooden_hoe"); + STONE_HOE = get("stone_hoe"); + IRON_HOE = get("iron_hoe"); + DIAMOND_HOE = get("diamond_hoe"); + GOLDEN_HOE = get("golden_hoe"); + WHEAT_SEEDS = get("wheat_seeds"); + WHEAT = get("wheat"); + BREAD = get("bread"); + LEATHER_HELMET = (ItemArmor) get("leather_helmet"); + LEATHER_CHESTPLATE = (ItemArmor) get("leather_chestplate"); + LEATHER_LEGGINGS = (ItemArmor) get("leather_leggings"); + LEATHER_BOOTS = (ItemArmor) get("leather_boots"); + CHAINMAIL_HELMET = (ItemArmor) get("chainmail_helmet"); + CHAINMAIL_CHESTPLATE = (ItemArmor) get("chainmail_chestplate"); + CHAINMAIL_LEGGINGS = (ItemArmor) get("chainmail_leggings"); + CHAINMAIL_BOOTS = (ItemArmor) get("chainmail_boots"); + IRON_HELMET = (ItemArmor) get("iron_helmet"); + IRON_CHESTPLATE = (ItemArmor) get("iron_chestplate"); + IRON_LEGGINGS = (ItemArmor) get("iron_leggings"); + IRON_BOOTS = (ItemArmor) get("iron_boots"); + DIAMOND_HELMET = (ItemArmor) get("diamond_helmet"); + DIAMOND_CHESTPLATE = (ItemArmor) get("diamond_chestplate"); + DIAMOND_LEGGINGS = (ItemArmor) get("diamond_leggings"); + DIAMOND_BOOTS = (ItemArmor) get("diamond_boots"); + GOLDEN_HELMET = (ItemArmor) get("golden_helmet"); + GOLDEN_CHESTPLATE = (ItemArmor) get("golden_chestplate"); + GOLDEN_LEGGINGS = (ItemArmor) get("golden_leggings"); + GOLDEN_BOOTS = (ItemArmor) get("golden_boots"); + FLINT = get("flint"); + PORKCHOP = get("porkchop"); + COOKED_PORKCHOP = get("cooked_porkchop"); + PAINTING = get("painting"); + GOLDEN_APPLE = get("golden_apple"); + SIGN = get("sign"); + WOODEN_DOOR = get("wooden_door"); + SPRUCE_DOOR = get("spruce_door"); + BIRCH_DOOR = get("birch_door"); + JUNGLE_DOOR = get("jungle_door"); + ACACIA_DOOR = get("acacia_door"); + DARK_OAK_DOOR = get("dark_oak_door"); + BUCKET = get("bucket"); + WATER_BUCKET = get("water_bucket"); + LAVA_BUCKET = get("lava_bucket"); + MINECART = get("minecart"); + SADDLE = get("saddle"); + IRON_DOOR = get("iron_door"); + REDSTONE = get("redstone"); + SNOWBALL = get("snowball"); + BOAT = get("boat"); + LEATHER = get("leather"); + MILK_BUCKET = get("milk_bucket"); + BRICK = get("brick"); + CLAY_BALL = get("clay_ball"); + REEDS = get("reeds"); + PAPER = get("paper"); + BOOK = get("book"); + SLIME = get("slime_ball"); + CHEST_MINECART = get("chest_minecart"); + FURNACE_MINECART = get("furnace_minecart"); + EGG = get("egg"); + COMPASS = get("compass"); + FISHING_ROD = (ItemFishingRod) get("fishing_rod"); + CLOCK = get("clock"); + GLOWSTONE_DUST = get("glowstone_dust"); + FISH = get("fish"); + COOKED_FISH = get("cooked_fish"); + DYE = get("dye"); + BONE = get("bone"); + SUGAR = get("sugar"); + CAKE = get("cake"); + BED = get("bed"); + REPEATER = get("repeater"); + COOKIE = get("cookie"); + FILLED_MAP = (ItemWorldMap) get("filled_map"); + SHEARS = (ItemShears) get("shears"); + MELON = get("melon"); + PUMPKIN_SEEDS = get("pumpkin_seeds"); + MELON_SEEDS = get("melon_seeds"); + BEEF = get("beef"); + COOKED_BEEF = get("cooked_beef"); + CHICKEN = get("chicken"); + COOKED_CHICKEN = get("cooked_chicken"); + MUTTON = get("mutton"); + COOKED_MUTTON = get("cooked_mutton"); + RABBIT = get("rabbit"); + COOKED_RABBIT = get("cooked_rabbit"); + RABBIT_STEW = get("rabbit_stew"); + RABBIT_FOOT = get("rabbit_foot"); + RABBIT_HIDE = get("rabbit_hide"); + ROTTEN_FLESH = get("rotten_flesh"); + ENDER_PEARL = get("ender_pearl"); + BLAZE_ROD = get("blaze_rod"); + GHAST_TEAR = get("ghast_tear"); + GOLD_NUGGET = get("gold_nugget"); + NETHER_WART = get("nether_wart"); + POTION = (ItemPotion) get("potion"); + GLASS_BOTTLE = get("glass_bottle"); + SPIDER_EYE = get("spider_eye"); + FERMENTED_SPIDER_EYE = get("fermented_spider_eye"); + BLAZE_POWDER = get("blaze_powder"); + MAGMA_CREAM = get("magma_cream"); + BREWING_STAND = get("brewing_stand"); + CAULDRON = get("cauldron"); + ENDER_EYE = get("ender_eye"); + SPECKLED_MELON = get("speckled_melon"); + SPAWN_EGG = get("spawn_egg"); + EXPERIENCE_BOTTLE = get("experience_bottle"); + FIRE_CHARGE = get("fire_charge"); + WRITABLE_BOOK = get("writable_book"); + WRITTEN_BOOK = get("written_book"); + EMERALD = get("emerald"); + ITEM_FRAME = get("item_frame"); + FLOWER_POT = get("flower_pot"); + CARROT = get("carrot"); + POTATO = get("potato"); + BAKED_POTATO = get("baked_potato"); + POISONOUS_POTATO = get("poisonous_potato"); + MAP = (ItemMapEmpty) get("map"); + GOLDEN_CARROT = get("golden_carrot"); + SKULL = get("skull"); + CARROT_ON_A_STICK = get("carrot_on_a_stick"); + NETHER_STAR = get("nether_star"); + PUMPKIN_PIE = get("pumpkin_pie"); + FIREWORKS = get("fireworks"); + FIREWORK_CHARGE = get("firework_charge"); + ENCHANTED_BOOK = (ItemEnchantedBook) get("enchanted_book"); + COMPARATOR = get("comparator"); + NETHERBRICK = get("netherbrick"); + QUARTZ = get("quartz"); + TNT_MINECART = get("tnt_minecart"); + HOPPER_MINECART = get("hopper_minecart"); + ARMOR_STAND = (ItemArmorStand) get("armor_stand"); + IRON_HORSE_ARMOR = get("iron_horse_armor"); + GOLDEN_HORSE_ARMOR = get("golden_horse_armor"); + DIAMOND_HORSE_ARMOR = get("diamond_horse_armor"); + LEAD = get("lead"); + NAME_TAG = get("name_tag"); + COMMAND_BLOCK_MINECART = get("command_block_minecart"); + RECORD_13 = get("record_13"); + RECORD_CAT = get("record_cat"); + RECORD_BLOCKS = get("record_blocks"); + RECORD_CHIRP = get("record_chirp"); + RECORD_FAR = get("record_far"); + RECORD_MALL = get("record_mall"); + RECORD_MELLOHI = get("record_mellohi"); + RECORD_STAL = get("record_stal"); + RECORD_STRAD = get("record_strad"); + RECORD_WARD = get("record_ward"); + RECORD_11 = get("record_11"); + RECORD_WAIT = get("record_wait"); + PRISMARINE_SHARD = get("prismarine_shard"); + PRISMARINE_CRYSTALS = get("prismarine_crystals"); + BANNER = get("banner"); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/IteratorUtils.java b/azurite-server/src/main/java/net/minecraft/server/IteratorUtils.java new file mode 100644 index 0000000..04d5ec4 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/IteratorUtils.java @@ -0,0 +1,173 @@ +package net.minecraft.server; + +import com.google.common.base.Function; +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; +import com.google.common.collect.UnmodifiableIterator; +import java.lang.reflect.Array; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.NoSuchElementException; + +public class IteratorUtils { + + public static Iterable a(Class oclass, Iterable> iterable) { + return new IteratorUtils.ClassIterable(oclass, (Iterable[]) b(Iterable.class, iterable), (IteratorUtils.SyntheticClass_1) null); + } + + public static Iterable> a(Iterable> iterable) { + return b(a(Object.class, iterable)); + } + + private static Iterable> b(Iterable iterable) { + return Iterables.transform(iterable, new IteratorUtils.ArrayToList((IteratorUtils.SyntheticClass_1) null)); + } + + private static T[] b(Class oclass, Iterable iterable) { + ArrayList arraylist = Lists.newArrayList(); + Iterator iterator = iterable.iterator(); + + while (iterator.hasNext()) { + Object object = iterator.next(); + + arraylist.add(object); + } + + return (T[]) arraylist.toArray(b(oclass, arraylist.size())); + } + + private static T[] b(Class oclass, int i) { + return (T[]) Array.newInstance(oclass, i); + } + + static class SyntheticClass_1 { } + + static class ClassIterable implements Iterable { + + private final Class a; + private final Iterable[] b; + + private ClassIterable(Class oclass, Iterable[] aiterable) { + this.a = oclass; + this.b = aiterable; + } + + public Iterator iterator() { + return (Iterator) (this.b.length <= 0 ? Collections.singletonList((Object[]) IteratorUtils.b(this.a, 0)).iterator() : new IteratorUtils.ClassIterable.ClassIterator(this.a, this.b, (IteratorUtils.SyntheticClass_1) null)); + } + + ClassIterable(Class oclass, Iterable[] aiterable, IteratorUtils.SyntheticClass_1 iteratorutils_syntheticclass_1) { + this(oclass, aiterable); + } + + static class ClassIterator extends UnmodifiableIterator { + + private int a; + private final Iterable[] b; + private final Iterator[] c; + private final T[] d; + + private ClassIterator(Class oclass, Iterable[] aiterable) { + this.a = -2; + this.b = aiterable; + this.c = (Iterator[]) IteratorUtils.b(Iterator.class, this.b.length); + + for (int i = 0; i < this.b.length; ++i) { + this.c[i] = aiterable[i].iterator(); + } + + this.d = IteratorUtils.b(oclass, this.c.length); + } + + private void b() { + this.a = -1; + Arrays.fill(this.c, (Object) null); + Arrays.fill(this.d, (Object) null); + } + + public boolean hasNext() { + if (this.a == -2) { + this.a = 0; + Iterator[] aiterator = this.c; + int i = aiterator.length; + + for (int j = 0; j < i; ++j) { + Iterator iterator = aiterator[j]; + + if (!iterator.hasNext()) { + this.b(); + break; + } + } + + return true; + } else { + if (this.a >= this.c.length) { + for (this.a = this.c.length - 1; this.a >= 0; --this.a) { + Iterator iterator1 = this.c[this.a]; + + if (iterator1.hasNext()) { + break; + } + + if (this.a == 0) { + this.b(); + break; + } + + iterator1 = this.b[this.a].iterator(); + this.c[this.a] = iterator1; + if (!iterator1.hasNext()) { + this.b(); + break; + } + } + } + + return this.a >= 0; + } + } + + public T[] a() { + if (!this.hasNext()) { + throw new NoSuchElementException(); + } else { + while (this.a < this.c.length) { + this.d[this.a] = this.c[this.a].next(); + ++this.a; + } + + return this.d.clone(); + } + } + + public T[] next() { + return this.a(); + } + + ClassIterator(Class oclass, Iterable[] aiterable, IteratorUtils.SyntheticClass_1 iteratorutils_syntheticclass_1) { + this(oclass, aiterable); + } + } + } + + static class ArrayToList implements Function> { + + private ArrayToList() {} + + public List a(Object[] aobject) { + return Arrays.asList((T[]) aobject); + } + + public List apply(Object[] object) { + return this.a(object); + } + + ArrayToList(IteratorUtils.SyntheticClass_1 iteratorutils_syntheticclass_1) { + this(); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/JsonList.java b/azurite-server/src/main/java/net/minecraft/server/JsonList.java new file mode 100644 index 0000000..1ad68cc --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/JsonList.java @@ -0,0 +1,205 @@ +package net.minecraft.server; + +import com.google.common.base.Charsets; +import com.google.common.collect.Maps; +import com.google.common.io.Files; +import com.google.gson.*; +import dev.azurite.spigot.Azurite; +import org.apache.commons.io.IOUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.io.*; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.Collection; +import java.util.List; +import java.util.Map; + +public class JsonList> { + + protected static final Logger a = LogManager.getLogger(); + protected final Gson b; + private final File c; + private final Map d = Maps.newConcurrentMap(); // Paper + private boolean e = true; + private static final ParameterizedType f = new ParameterizedType() { + public Type[] getActualTypeArguments() { + return new Type[]{JsonListEntry.class}; + } + + public Type getRawType() { + return List.class; + } + + public Type getOwnerType() { + return null; + } + }; + + public JsonList(File file) { + this.c = file; + GsonBuilder gsonbuilder = (new GsonBuilder()).setPrettyPrinting(); + + gsonbuilder.registerTypeHierarchyAdapter(JsonListEntry.class, new JsonList.JsonListEntrySerializer(null)); + this.b = gsonbuilder.create(); + } + + public boolean isEnabled() { + return this.e; + } + + public void a(boolean flag) { + this.e = flag; + } + + public File c() { + return this.c; + } + + public void add(V v0) { + this.d.put(this.a(v0.getKey()), v0); + + try { + this.save(); + } catch (IOException ioexception) { + JsonList.a.warn("Could not save the list after adding a user.", ioexception); + } + } + + public V get(K k0) { + // Paper start + return this.d.computeIfPresent(this.a(k0), (k, v) -> v.hasExpired() ? null : v); + // Paper end + } + + public void remove(K k0) { + this.d.remove(this.a(k0)); + + try { + this.save(); + } catch (IOException ioexception) { + JsonList.a.warn("Could not save the list after removing a user.", ioexception); + } + + } + + public String[] getEntries() { + return this.d.keySet().toArray(new String[0]); + } + + // CraftBukkit start + public Collection getValues() { + return this.d.values(); + } + // CraftBukkit end + + public boolean isEmpty() { + // return this.d.size() < 1; // Paper + return d.isEmpty(); // Paper - readability is the goal. As an aside, isEmpty() uses only sumCount() and a comparison. size() uses sumCount(), casts, and boolean logic + } + + protected String a(K k0) { + return k0.toString(); + } + + protected boolean d(K k0) { + return this.d.containsKey(this.a(k0)); + } + + private void h() { + this.d.values().removeIf(JsonListEntry::hasExpired); + } + + protected JsonListEntry a(JsonObject jsonobject) { + return new JsonListEntry<>(null, jsonobject); + } + + protected Map e() { + return this.d; + } + + public void save() throws IOException { + this.h(); // Paper - remove expired values before saving + // Azurite start - Async JsonList saving + Azurite.getInstance().getThreadingManager().getAsyncExecutor().execute(() -> { + Collection collection = this.d.values(); + String s = this.b.toJson(collection); + BufferedWriter bufferedwriter = null; + + try { + bufferedwriter = Files.newWriter(this.c, Charsets.UTF_8); + bufferedwriter.write(s); + } catch (IOException ex) { + JsonList.a.warn("Failed to save {}", this.c, ex); + } finally { + IOUtils.closeQuietly(bufferedwriter); + } + }); + // Azurite end + } + + public void load() throws FileNotFoundException { + Collection> collection = null; + BufferedReader bufferedreader = null; + + try { + bufferedreader = Files.newReader(this.c, Charsets.UTF_8); + collection = this.b.fromJson(bufferedreader, JsonList.f); + // Spigot Start + } catch (java.io.FileNotFoundException ex) { + org.bukkit.Bukkit.getLogger().log(java.util.logging.Level.INFO, "Unable to find file {0}, creating it.", this.c); + } catch (com.google.gson.JsonSyntaxException ex) { + org.bukkit.Bukkit.getLogger().log(java.util.logging.Level.WARNING, "Unable to read file {0}, backing it up to {0}.backup and creating new copy.", this.c); + File backup = new File(this.c + ".backup"); + this.c.renameTo(backup); + this.c.delete(); + // Spigot End + } finally { + IOUtils.closeQuietly(bufferedreader); + } + + if (collection != null) { + this.d.clear(); + + for (JsonListEntry jsonlistentry : collection) { + if (jsonlistentry.getKey() != null) { + this.d.put(this.a(jsonlistentry.getKey()), (V) jsonlistentry); // CraftBukkit - fix decompile error + } + } + } + + } + + class JsonListEntrySerializer implements JsonDeserializer>, JsonSerializer> { + + private JsonListEntrySerializer() { + } + + public JsonElement a(JsonListEntry jsonlistentry, Type type, JsonSerializationContext jsonserializationcontext) { + JsonObject jsonobject = new JsonObject(); + jsonlistentry.a(jsonobject); + return jsonobject; + } + + public JsonListEntry a(JsonElement jsonelement, Type type, JsonDeserializationContext jsondeserializationcontext) throws JsonParseException { + if (jsonelement.isJsonObject()) { + return JsonList.this.a(jsonelement.getAsJsonObject()); + } else { + return null; + } + } + + public JsonElement serialize(JsonListEntry object, Type type, JsonSerializationContext jsonserializationcontext) { // CraftBukkit - fix decompile error + return this.a(object, type, jsonserializationcontext); + } + + public JsonListEntry deserialize(JsonElement jsonelement, Type type, JsonDeserializationContext jsondeserializationcontext) throws JsonParseException { // CraftBukkit - fix decompile error + return this.a(jsonelement, type, jsondeserializationcontext); + } + + JsonListEntrySerializer(Object object) { + this(); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/JsonListEntry.java b/azurite-server/src/main/java/net/minecraft/server/JsonListEntry.java new file mode 100644 index 0000000..3d29f49 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/JsonListEntry.java @@ -0,0 +1,26 @@ +package net.minecraft.server; + +import com.google.gson.JsonObject; + +public class JsonListEntry { + + private final T a; + + public JsonListEntry(T t0) { + this.a = t0; + } + + protected JsonListEntry(T t0, JsonObject jsonobject) { + this.a = t0; + } + + public T getKey() { + return this.a; + } + + boolean hasExpired() { + return false; + } + + protected void a(JsonObject jsonobject) {} +} diff --git a/azurite-server/src/main/java/net/minecraft/server/LayerIsland.java b/azurite-server/src/main/java/net/minecraft/server/LayerIsland.java new file mode 100644 index 0000000..5236ec2 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/LayerIsland.java @@ -0,0 +1,35 @@ +package net.minecraft.server; + +import java.util.Arrays; + +public class LayerIsland extends GenLayer { + + private final World world; + + public LayerIsland(long i, World world) { + super(i); + this.world = world; + } + + public int[] a(int i, int j, int k, int l) { + int[] aint = IntCache.a(k * l); + + if (!world.generatorConfig.generateOceans.getValue()) { + Arrays.fill(aint, 1); + return aint; + } + + for (int i1 = 0; i1 < l; ++i1) { + for (int j1 = 0; j1 < k; ++j1) { + this.a(i + j1, (long) (j + i1)); + aint[j1 + i1 * k] = this.a(10) == 0 ? 1 : 0; + } + } + + if (i > -k && i <= 0 && j > -l && j <= 0) { + aint[-i + -j * k] = 1; + } + + return aint; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/LazyInitVar.java b/azurite-server/src/main/java/net/minecraft/server/LazyInitVar.java new file mode 100644 index 0000000..344c75c --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/LazyInitVar.java @@ -0,0 +1,20 @@ +package net.minecraft.server; + +public abstract class LazyInitVar { + + private T a; + private boolean b = false; + + public LazyInitVar() {} + + public T c() { + if (!this.b) { + this.b = true; + this.a = this.init(); + } + + return this.a; + } + + protected abstract T init(); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/LegacyPingHandler.java b/azurite-server/src/main/java/net/minecraft/server/LegacyPingHandler.java new file mode 100644 index 0000000..d675185 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/LegacyPingHandler.java @@ -0,0 +1,100 @@ +package net.minecraft.server; + +import com.google.common.base.Charsets; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelFutureListener; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelInboundHandlerAdapter; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.net.InetSocketAddress; + +public class LegacyPingHandler extends ChannelInboundHandlerAdapter { + private static final Logger a = LogManager.getLogger(); + private final ServerConnection b; + + public LegacyPingHandler(ServerConnection var1) { + this.b = var1; + } + + public void channelRead(ChannelHandlerContext var1, Object var2) { + ByteBuf var3 = (ByteBuf)var2; + var3.markReaderIndex(); + boolean var4 = true; + try { + if (var3.readUnsignedByte() == 254) { + InetSocketAddress var5 = (InetSocketAddress)var1.channel().remoteAddress(); + MinecraftServer var6 = this.b.d(); + int var7 = var3.readableBytes(); + String var8; + switch(var7) { + case 0: + a.debug("Ping: (<1.3.x) from {}:{}", var5.getAddress(), var5.getPort()); + var8 = String.format("%s§%d§%d", var6.getMotd(), var6.I(), var6.J()); + this.a(var1, this.a(var8)); + break; + case 1: + if (var3.readUnsignedByte() != 1) { + return; + } + + a.debug("Ping: (1.4-1.5.x) from {}:{}", var5.getAddress(), var5.getPort()); + var8 = String.format("§1\u0000%d\u0000%s\u0000%s\u0000%d\u0000%d", 127, var6.getVersion(), var6.getMotd(), var6.I(), var6.J()); + this.a(var1, this.a(var8)); + break; + default: + boolean var23 = var3.readUnsignedByte() == 1; + var23 &= var3.readUnsignedByte() == 250; + var23 &= "MC|PingHost".equals(new String(var3.readBytes(var3.readShort() * 2).array(), Charsets.UTF_16BE)); + int var9 = var3.readUnsignedShort(); + var23 &= var3.readUnsignedByte() >= 73; + var23 &= 3 + var3.readBytes(var3.readShort() * 2).array().length + 4 == var9; + var23 &= var3.readInt() <= 65535; + var23 &= var3.readableBytes() == 0; + if (!var23) { + return; + } + + a.debug("Ping: (1.6) from {}:{}", var5.getAddress(), var5.getPort()); + String var10 = String.format("§1\u0000%d\u0000%s\u0000%s\u0000%d\u0000%d", 127, var6.getVersion(), var6.getMotd(), var6.I(), var6.J()); + ByteBuf var11 = this.a(var10); + + try { + this.a(var1, var11); + } finally { + var11.release(); + } + } + + var3.release(); + var4 = false; + } + } catch (RuntimeException ignored) { + } finally { + if (var4) { + var3.resetReaderIndex(); + var1.channel().pipeline().remove("legacy_query"); + var1.fireChannelRead(var2); + } + + } + + } + + private void a(ChannelHandlerContext var1, ByteBuf var2) { + var1.pipeline().firstContext().writeAndFlush(var2).addListener(ChannelFutureListener.CLOSE); + } + + private ByteBuf a(String var1) { + ByteBuf var2 = Unpooled.buffer(); + var2.writeByte(255); + char[] var3 = var1.toCharArray(); + var2.writeShort(var3.length); + for (char var7 : var3) { + var2.writeChar(var7); + } + return var2; + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/net/minecraft/server/LocaleI18n.java b/azurite-server/src/main/java/net/minecraft/server/LocaleI18n.java new file mode 100644 index 0000000..61c3690 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/LocaleI18n.java @@ -0,0 +1,27 @@ +package net.minecraft.server; + +public class LocaleI18n { + + private static LocaleLanguage a = LocaleLanguage.a(); + private static LocaleLanguage b = new LocaleLanguage(); + + public static String get(String s) { + return LocaleI18n.a.a(s); + } + + public static String a(String s, Object... aobject) { + return LocaleI18n.a.a(s, aobject); + } + + public static String b(String s) { + return LocaleI18n.b.a(s); + } + + public static boolean c(String s) { + return LocaleI18n.a.b(s); + } + + public static long a() { + return LocaleI18n.a.c(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/LocaleLanguage.java b/azurite-server/src/main/java/net/minecraft/server/LocaleLanguage.java new file mode 100644 index 0000000..1af4090 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/LocaleLanguage.java @@ -0,0 +1,81 @@ +package net.minecraft.server; + +import com.google.common.base.Splitter; +import com.google.common.collect.Iterables; +import com.google.common.collect.Maps; +import java.io.IOException; +import java.io.InputStream; +import java.util.IllegalFormatException; +import java.util.Iterator; +import java.util.Map; +import java.util.regex.Pattern; +import org.apache.commons.io.Charsets; +import org.apache.commons.io.IOUtils; + +public class LocaleLanguage { + + private static final Pattern a = Pattern.compile("%(\\d+\\$)?[\\d\\.]*[df]"); + private static final Splitter b = Splitter.on('=').limit(2); + private static LocaleLanguage c = new LocaleLanguage(); + private final Map d = Maps.newHashMap(); + private long e; + + public LocaleLanguage() { + try { + InputStream inputstream = LocaleLanguage.class.getResourceAsStream("/assets/minecraft/lang/en_US.lang"); + Iterator iterator = IOUtils.readLines(inputstream, Charsets.UTF_8).iterator(); + + while (iterator.hasNext()) { + String s = (String) iterator.next(); + + if (!s.isEmpty() && s.charAt(0) != 35) { + String[] astring = (String[]) Iterables.toArray(LocaleLanguage.b.split(s), String.class); + + if (astring != null && astring.length == 2) { + String s1 = astring[0]; + String s2 = LocaleLanguage.a.matcher(astring[1]).replaceAll("%$1s"); + + this.d.put(s1, s2); + } + } + } + + this.e = System.currentTimeMillis(); + } catch (IOException ioexception) { + ; + } + + } + + static LocaleLanguage a() { + return LocaleLanguage.c; + } + + public synchronized String a(String s) { + return this.c(s); + } + + public synchronized String a(String s, Object... aobject) { + String s1 = this.c(s); + + try { + return String.format(s1, aobject); + } catch (IllegalFormatException illegalformatexception) { + return "Format error: " + s1; + } + } + + private String c(String s) { + String s1 = (String) this.d.get(s); + + return s1 == null ? s : s1; + } + + public synchronized boolean b(String s) { + return this.d.containsKey(s); + } + + public long c() { + return this.e; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/LoginListener.java b/azurite-server/src/main/java/net/minecraft/server/LoginListener.java new file mode 100644 index 0000000..0ecf850 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/LoginListener.java @@ -0,0 +1,182 @@ +package net.minecraft.server; + +import com.google.common.base.Charsets; +import com.mojang.authlib.GameProfile; +import com.mojang.authlib.exceptions.AuthenticationUnavailableException; +import com.mojang.authlib.properties.Property; +import dev.azurite.spigot.Azurite; +import io.netty.channel.ChannelFutureListener; +import org.apache.commons.lang3.Validate; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.bukkit.event.player.AsyncPlayerPreLoginEvent; + +import javax.crypto.SecretKey; +import java.math.BigInteger; +import java.net.InetSocketAddress; +import java.security.PrivateKey; +import java.util.Arrays; +import java.util.Objects; +import java.util.Random; +import java.util.UUID; +import java.util.concurrent.Future; +import java.util.logging.Level; + +public class LoginListener implements PacketLoginInListener, IUpdatePlayerListBox { + + private static final Logger c = LogManager.getLogger(); + private static final Random random = new Random(); + + public final NetworkManager networkManager; + private final byte[] e = new byte[4]; + private final MinecraftServer server; + private final String j; + public String hostname = ""; + private EnumProtocolState g; + private int h; + private GameProfile i; + private SecretKey loginKey; + private Future future; + + public LoginListener(MinecraftServer minecraftserver, NetworkManager networkmanager) { + this.g = EnumProtocolState.HELLO; + this.j = ""; + this.server = minecraftserver; + this.networkManager = networkmanager; + random.nextBytes(this.e); + } + + public void c() { + if (h++ == 600) { + future.cancel(true); + disconnect("Took too long to log in"); + } + } + + public void disconnect(String s) { + try { + c.info("Disconnecting {}: {}", d(), s); + ChatComponentText chatcomponenttext = new ChatComponentText(s); + networkManager.handle(new PacketLoginOutDisconnect(chatcomponenttext)); + networkManager.close(chatcomponenttext); + } catch (Exception exception) { + c.error("Error whilst disconnecting player", exception); + } + } + + public void initUUID() { + UUID uuid; + if (this.networkManager.spoofedUUID != null) { + uuid = this.networkManager.spoofedUUID; + } else { + uuid = UUID.nameUUIDFromBytes(("OfflinePlayer:" + this.i.getName()).getBytes(Charsets.UTF_8)); + } + this.i = new GameProfile(uuid, this.i.getName()); + if (this.networkManager.spoofedProfile != null) + for (Property property : this.networkManager.spoofedProfile) + this.i.getProperties().put(property.getName(), property); + } + + public void b() { + MinecraftServer.getServer().postToLoginTasks(() -> { + EntityPlayer s = this.server.getPlayerList().attemptLogin(this, this.i, this.hostname); + if (s != null) { + this.g = EnumProtocolState.ACCEPTED; + int compressionThreshold = server.aK(); + if (compressionThreshold >= 0 && !networkManager.c()) { + networkManager.a(new PacketLoginOutSetCompression(compressionThreshold), (ChannelFutureListener) future -> networkManager.a(compressionThreshold)); + } + + this.networkManager.handle(new PacketLoginOutSuccess(this.i)); + + try { + server.getPlayerList().a(networkManager, server.getPlayerList().processLogin(i, s)); // CraftBukkit - add player reference + } catch (NullPointerException e) { + s.getBukkitEntity().kickPlayer("Failed to process your login request."); + } + } + }); + } + + public void a(IChatBaseComponent ichatbasecomponent) { + c.info("{} lost connection: {}", d(), ichatbasecomponent.c()); + } + + public String d() { + String socketAddress = networkManager == null ? null : (networkManager.getSocketAddress() == null ? null : networkManager.getSocketAddress().toString()); + return i != null ? i + " (" + socketAddress + ")" : socketAddress; + } + + public void a(PacketLoginInStart packetlogininstart) { + Validate.validState((this.g == EnumProtocolState.HELLO), "Unexpected hello packet"); + this.i = packetlogininstart.a(); + if (this.server.getOnlineMode() && !this.networkManager.c()) { + this.g = EnumProtocolState.KEY; + this.networkManager.handle(new PacketLoginOutEncryptionBegin(this.j, this.server.Q().getPublic(), this.e)); + } else { + future = Azurite.getInstance().getThreadingManager().getAsyncExecutor().submit(() -> { + try { + initUUID(); + new LoginHandler().fireEvents(); + } catch (Exception ex) { + LoginListener.this.disconnect("Failed to verify username!"); + LoginListener.this.server.server.getLogger().log(Level.WARNING, "Exception verifying " + LoginListener.this.i.getName(), ex); + } + }); + } + } + + public void a(PacketLoginInEncryptionBegin packetlogininencryptionbegin) { + Validate.validState((this.g == EnumProtocolState.KEY), "Unexpected key packet"); + PrivateKey privatekey = this.server.Q().getPrivate(); + if (!Arrays.equals(this.e, packetlogininencryptionbegin.b(privatekey))) + throw new IllegalStateException("Invalid nonce!"); + loginKey = packetlogininencryptionbegin.a(privatekey); + g = EnumProtocolState.AUTHENTICATING; + networkManager.a(loginKey); + future = Azurite.getInstance().getThreadingManager().getAsyncExecutor().submit(() -> { + GameProfile gameprofile = i; + try { + String s = (new BigInteger(Objects.requireNonNull(MinecraftEncryption.a(j, server.Q().getPublic(), loginKey)))).toString(16); + i = server.aD().hasJoinedServer(new GameProfile(null, gameprofile.getName()), s); + if (i != null) { + if (!networkManager.g()) + return; + (new LoginListener.LoginHandler()).fireEvents(); + } else { + disconnect("Failed to verify username!"); + c.error("Username '{}' tried to join with an invalid session", gameprofile.getName()); + } + } catch (AuthenticationUnavailableException authenticationunavailableexception) { + disconnect("Authentication servers are down. Please try again later, sorry!"); + c.error("Couldn't verify username because servers are unavailable"); + } catch (Exception exception) { + disconnect("Failed to verify username!"); + server.server.getLogger().log(Level.WARNING, "Exception verifying " + gameprofile.getName(), exception); + } + }); + } + + protected GameProfile a(GameProfile gameprofile) { + UUID uuid = UUID.nameUUIDFromBytes(("OfflinePlayer:" + gameprofile.getName()).getBytes(Charsets.UTF_8)); + return new GameProfile(uuid, gameprofile.getName()); + } + + enum EnumProtocolState { + HELLO, KEY, AUTHENTICATING, READY_TO_ACCEPT, e, ACCEPTED + } + + public class LoginHandler { + public void fireEvents() { + AsyncPlayerPreLoginEvent event = new AsyncPlayerPreLoginEvent(i.getName(), ((InetSocketAddress) networkManager.getSocketAddress()).getAddress(), i.getId()); + server.server.getPluginManager().callEvent(event); + if (event.getLoginResult() != AsyncPlayerPreLoginEvent.Result.ALLOWED) { + disconnect(event.getKickMessage()); + return; + } + c.info("UUID of player {} is {}", i.getName(), i.getId()); + g = LoginListener.EnumProtocolState.READY_TO_ACCEPT; + b(); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/LongHashMap.java b/azurite-server/src/main/java/net/minecraft/server/LongHashMap.java new file mode 100644 index 0000000..ea3b398 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/LongHashMap.java @@ -0,0 +1,199 @@ +package net.minecraft.server; + +import java.util.Objects; + +public class LongHashMap { + + private transient LongHashMapEntry[] entries = new LongHashMapEntry[4096]; + private transient int count; + private int c; + private int d = 3072; + + public LongHashMap() { + this.c = this.entries.length - 1; + } + + private static int g(long i) { + return (int) i + (int) (i >>> 32) * 92821; // ArchaicFix - better LongHashMap + } + + private static int a(int i) { + i ^= i >>> 20 ^ i >>> 12; + return i ^ i >>> 7 ^ i >>> 4; + } + + private static int a(int i, int j) { + return i & j; + } + + public int count() { + return this.count; + } + + public V getEntry(long i) { + int j = g(i); + + for (LongHashMapEntry longhashmap_longhashmapentry = this.entries[a(j, this.c)]; longhashmap_longhashmapentry != null; longhashmap_longhashmapentry = longhashmap_longhashmapentry.c) { + if (longhashmap_longhashmapentry.a == i) { + return longhashmap_longhashmapentry.b; + } + } + + return null; + } + + public boolean contains(long i) { + return this.c(i) != null; + } + + final LongHashMapEntry c(long i) { + int j = g(i); + + for (LongHashMapEntry longhashmap_longhashmapentry = this.entries[a(j, this.c)]; longhashmap_longhashmapentry != null; longhashmap_longhashmapentry = longhashmap_longhashmapentry.c) { + if (longhashmap_longhashmapentry.a == i) { + return longhashmap_longhashmapentry; + } + } + + return null; + } + + public void put(long i, V v0) { + int j = g(i); + int k = a(j, this.c); + + for (LongHashMapEntry longhashmap_longhashmapentry = this.entries[k]; longhashmap_longhashmapentry != null; longhashmap_longhashmapentry = longhashmap_longhashmapentry.c) { + if (longhashmap_longhashmapentry.a == i) { + longhashmap_longhashmapentry.b = v0; + return; + } + } + + this.a(j, i, v0, k); + } + + private void b(int i) { + LongHashMapEntry[] alonghashmap_longhashmapentry = this.entries; + int j = alonghashmap_longhashmapentry.length; + + if (j == 1073741824) { + this.d = Integer.MAX_VALUE; + } else { + LongHashMapEntry[] alonghashmap_longhashmapentry1 = new LongHashMapEntry[i]; + + this.a(alonghashmap_longhashmapentry1); + this.entries = alonghashmap_longhashmapentry1; + this.c = this.entries.length - 1; + this.d = (int) ((float) i * 0.75F); + } + } + + private void a(LongHashMapEntry[] alonghashmap_longhashmapentry) { + LongHashMapEntry[] alonghashmap_longhashmapentry1 = this.entries; + int i = alonghashmap_longhashmapentry.length; + + for (int j = 0; j < alonghashmap_longhashmapentry1.length; ++j) { + LongHashMapEntry longhashmap_longhashmapentry = alonghashmap_longhashmapentry1[j]; + + if (longhashmap_longhashmapentry != null) { + alonghashmap_longhashmapentry1[j] = null; + + LongHashMapEntry longhashmap_longhashmapentry1; + + do { + longhashmap_longhashmapentry1 = longhashmap_longhashmapentry.c; + int k = a(longhashmap_longhashmapentry.d, i - 1); + + longhashmap_longhashmapentry.c = alonghashmap_longhashmapentry[k]; + alonghashmap_longhashmapentry[k] = longhashmap_longhashmapentry; + longhashmap_longhashmapentry = longhashmap_longhashmapentry1; + } while (longhashmap_longhashmapentry1 != null); + } + } + + } + + public V remove(long i) { + LongHashMapEntry longhashmap_longhashmapentry = this.e(i); + + return longhashmap_longhashmapentry == null ? null : longhashmap_longhashmapentry.b; + } + + final LongHashMapEntry e(long i) { + int j = g(i); + int k = a(j, this.c); + LongHashMapEntry longhashmap_longhashmapentry = this.entries[k]; + + LongHashMapEntry longhashmap_longhashmapentry1; + LongHashMapEntry longhashmap_longhashmapentry2; + + for (longhashmap_longhashmapentry1 = longhashmap_longhashmapentry; longhashmap_longhashmapentry1 != null; longhashmap_longhashmapentry1 = longhashmap_longhashmapentry2) { + longhashmap_longhashmapentry2 = longhashmap_longhashmapentry1.c; + if (longhashmap_longhashmapentry1.a == i) { + --this.count; + if (longhashmap_longhashmapentry == longhashmap_longhashmapentry1) { + this.entries[k] = longhashmap_longhashmapentry2; + } else { + longhashmap_longhashmapentry.c = longhashmap_longhashmapentry2; + } + + return longhashmap_longhashmapentry1; + } + + longhashmap_longhashmapentry = longhashmap_longhashmapentry1; + } + + return null; + } + + private void a(int i, long j, V v0, int k) { + LongHashMapEntry longhashmap_longhashmapentry = this.entries[k]; + this.entries[k] = new LongHashMapEntry<>(i, j, v0, longhashmap_longhashmapentry); + + if (this.count++ >= this.d) { + this.b(2 * this.entries.length); + } + } + + static class LongHashMapEntry { + + final long a; + V b; + LongHashMapEntry c; + final int d; + + LongHashMapEntry(int i, long j, V v0, LongHashMapEntry longhashmap_longhashmapentry) { + this.b = v0; + this.c = longhashmap_longhashmapentry; + this.a = j; + this.d = i; + } + + public final long a() { + return this.a; + } + + public final V b() { + return this.b; + } + + public final boolean equals(Object object) { + if (object instanceof LongHashMap.LongHashMapEntry) { + LongHashMapEntry longhashmap_longhashmapentry = (LongHashMapEntry) object; + if (Objects.equals(a(), longhashmap_longhashmapentry.a())) { + return Objects.equals(b(), longhashmap_longhashmapentry.b()); + } + + } + return false; + } + + public final int hashCode() { + return LongHashMap.g(this.a); + } + + public final String toString() { + return this.a() + "=" + this.b(); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/MapGeneratorUtils.java b/azurite-server/src/main/java/net/minecraft/server/MapGeneratorUtils.java new file mode 100644 index 0000000..5361446 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/MapGeneratorUtils.java @@ -0,0 +1,30 @@ +package net.minecraft.server; + +import com.google.common.collect.Maps; +import java.util.Iterator; +import java.util.Map; +import java.util.NoSuchElementException; + +public class MapGeneratorUtils { + + public static Map b(Iterable iterable, Iterable iterable1) { + return a(iterable, iterable1, Maps.newLinkedHashMap()); + } + + public static Map a(Iterable iterable, Iterable iterable1, Map map) { + Iterator iterator = iterable1.iterator(); + Iterator iterator1 = iterable.iterator(); + + while (iterator1.hasNext()) { + K object = iterator1.next(); + + map.put(object, iterator.next()); + } + + if (iterator.hasNext()) { + throw new NoSuchElementException(); + } else { + return map; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/MapIcon.java b/azurite-server/src/main/java/net/minecraft/server/MapIcon.java new file mode 100644 index 0000000..d7bf93c --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/MapIcon.java @@ -0,0 +1,60 @@ +package net.minecraft.server; + +public class MapIcon { + + private byte type; + private byte x; + private byte y; + private byte rotation; + + public MapIcon(byte b0, byte b1, byte b2, byte b3) { + this.type = b0; + this.x = b1; + this.y = b2; + this.rotation = b3; + } + + public MapIcon(MapIcon mapicon) { + this.type = mapicon.type; + this.x = mapicon.x; + this.y = mapicon.y; + this.rotation = mapicon.rotation; + } + + public byte getType() { + return this.type; + } + + public byte getX() { + return this.x; + } + + public byte getY() { + return this.y; + } + + public byte getRotation() { + return this.rotation; + } + + public boolean equals(Object object) { + if (this == object) { + return true; + } else if (!(object instanceof MapIcon)) { + return false; + } else { + MapIcon mapicon = (MapIcon) object; + + return this.type != mapicon.type ? false : (this.rotation != mapicon.rotation ? false : (this.x != mapicon.x ? false : this.y == mapicon.y)); + } + } + + public int hashCode() { + byte b0 = this.type; + int i = 31 * b0 + this.x; + + i = 31 * i + this.y; + i = 31 * i + this.rotation; + return i; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/Material.java b/azurite-server/src/main/java/net/minecraft/server/Material.java new file mode 100644 index 0000000..472e834 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/Material.java @@ -0,0 +1,128 @@ +package net.minecraft.server; + +public class Material { + + public static final Material AIR = new MaterialGas(MaterialMapColor.b); + public static final Material GRASS = new Material(MaterialMapColor.c); + public static final Material EARTH = new Material(MaterialMapColor.l); + public static final Material WOOD = (new Material(MaterialMapColor.o)).g(); + public static final Material STONE = (new Material(MaterialMapColor.m)).f(); + public static final Material ORE = (new Material(MaterialMapColor.h)).f(); + public static final Material HEAVY = (new Material(MaterialMapColor.h)).f().o(); + public static final Material WATER = (new MaterialLiquid(MaterialMapColor.n)).n(); + public static final Material LAVA = (new MaterialLiquid(MaterialMapColor.f)).n(); + public static final Material LEAVES = (new Material(MaterialMapColor.i)).g().s().n(); + public static final Material PLANT = (new MaterialDecoration(MaterialMapColor.i)).n(); + public static final Material REPLACEABLE_PLANT = (new MaterialDecoration(MaterialMapColor.i)).g().n().i(); + public static final Material SPONGE = new Material(MaterialMapColor.t); + public static final Material CLOTH = (new Material(MaterialMapColor.e)).g(); + public static final Material FIRE = (new MaterialGas(MaterialMapColor.b)).n(); + public static final Material SAND = new Material(MaterialMapColor.d); + public static final Material ORIENTABLE = (new MaterialDecoration(MaterialMapColor.b)).n(); + public static final Material WOOL = (new MaterialDecoration(MaterialMapColor.e)).g(); + public static final Material SHATTERABLE = (new Material(MaterialMapColor.b)).s().p(); + public static final Material BUILDABLE_GLASS = (new Material(MaterialMapColor.b)).p(); + public static final Material TNT = (new Material(MaterialMapColor.f)).g().s(); + public static final Material CORAL = (new Material(MaterialMapColor.i)).n(); + public static final Material ICE = (new Material(MaterialMapColor.g)).s().p(); + public static final Material SNOW_LAYER = (new Material(MaterialMapColor.g)).p(); + public static final Material PACKED_ICE = (new MaterialDecoration(MaterialMapColor.j)).i().s().f().n(); + public static final Material SNOW_BLOCK = (new Material(MaterialMapColor.j)).f(); + public static final Material CACTUS = (new Material(MaterialMapColor.i)).s().n(); + public static final Material CLAY = new Material(MaterialMapColor.k); + public static final Material PUMPKIN = (new Material(MaterialMapColor.i)).n(); + public static final Material DRAGON_EGG = (new Material(MaterialMapColor.i)).n(); + public static final Material PORTAL = (new MaterialPortal(MaterialMapColor.b)).o(); + public static final Material CAKE = (new Material(MaterialMapColor.b)).n(); + public static final Material WEB = (new Material(MaterialMapColor.e) { + public boolean isSolid() { + return false; + } + }).f().n(); + public static final Material PISTON = (new Material(MaterialMapColor.m)).o(); + public static final Material BANNER = (new Material(MaterialMapColor.b)).f().o(); + private boolean canBurn; + private boolean K; + private boolean L; + private final MaterialMapColor M; + private boolean N = true; + private int O; + + public Material(MaterialMapColor materialmapcolor) { + this.M = materialmapcolor; + } + + public boolean isLiquid() { + return false; + } + + public boolean isBuildable() { + return true; + } + + public boolean blocksLight() { + return true; + } + + public boolean isSolid() { + return true; + } + + private Material s() { + this.L = true; + return this; + } + + protected Material f() { + this.N = false; + return this; + } + + protected Material g() { + this.canBurn = true; + return this; + } + + public boolean isBurnable() { + return this.canBurn; + } + + public Material i() { + this.K = true; + return this; + } + + public boolean isReplaceable() { + return this.K; + } + + public boolean k() { + return !this.L && this.isSolid(); + } + + public boolean isAlwaysDestroyable() { + return this.N; + } + + public int getPushReaction() { + return this.O; + } + + protected Material n() { + this.O = 1; + return this; + } + + protected Material o() { + this.O = 2; + return this; + } + + protected Material p() { + return this; + } + + public MaterialMapColor r() { + return this.M; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/MaterialDecoration.java b/azurite-server/src/main/java/net/minecraft/server/MaterialDecoration.java new file mode 100644 index 0000000..3eebf79 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/MaterialDecoration.java @@ -0,0 +1,21 @@ +package net.minecraft.server; + +public class MaterialDecoration extends Material { + + public MaterialDecoration(MaterialMapColor materialmapcolor) { + super(materialmapcolor); + this.p(); + } + + public boolean isBuildable() { + return false; + } + + public boolean blocksLight() { + return false; + } + + public boolean isSolid() { + return false; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/MaterialGas.java b/azurite-server/src/main/java/net/minecraft/server/MaterialGas.java new file mode 100644 index 0000000..3328cd0 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/MaterialGas.java @@ -0,0 +1,21 @@ +package net.minecraft.server; + +public class MaterialGas extends Material { + + public MaterialGas(MaterialMapColor materialmapcolor) { + super(materialmapcolor); + this.i(); + } + + public boolean isBuildable() { + return false; + } + + public boolean blocksLight() { + return false; + } + + public boolean isSolid() { + return false; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/MaterialLiquid.java b/azurite-server/src/main/java/net/minecraft/server/MaterialLiquid.java new file mode 100644 index 0000000..f77eee9 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/MaterialLiquid.java @@ -0,0 +1,22 @@ +package net.minecraft.server; + +public class MaterialLiquid extends Material { + + public MaterialLiquid(MaterialMapColor materialmapcolor) { + super(materialmapcolor); + this.i(); + this.n(); + } + + public boolean isLiquid() { + return true; + } + + public boolean isSolid() { + return false; + } + + public boolean isBuildable() { + return false; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/MaterialMapColor.java b/azurite-server/src/main/java/net/minecraft/server/MaterialMapColor.java new file mode 100644 index 0000000..5254b17 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/MaterialMapColor.java @@ -0,0 +1,54 @@ +package net.minecraft.server; + +public class MaterialMapColor { + + public static final MaterialMapColor[] a = new MaterialMapColor[64]; + public static final MaterialMapColor b = new MaterialMapColor(0, 0); + public static final MaterialMapColor c = new MaterialMapColor(1, 8368696); + public static final MaterialMapColor d = new MaterialMapColor(2, 16247203); + public static final MaterialMapColor e = new MaterialMapColor(3, 13092807); + public static final MaterialMapColor f = new MaterialMapColor(4, 16711680); + public static final MaterialMapColor g = new MaterialMapColor(5, 10526975); + public static final MaterialMapColor h = new MaterialMapColor(6, 10987431); + public static final MaterialMapColor i = new MaterialMapColor(7, 31744); + public static final MaterialMapColor j = new MaterialMapColor(8, 16777215); + public static final MaterialMapColor k = new MaterialMapColor(9, 10791096); + public static final MaterialMapColor l = new MaterialMapColor(10, 9923917); + public static final MaterialMapColor m = new MaterialMapColor(11, 7368816); + public static final MaterialMapColor n = new MaterialMapColor(12, 4210943); + public static final MaterialMapColor o = new MaterialMapColor(13, 9402184); + public static final MaterialMapColor p = new MaterialMapColor(14, 16776437); + public static final MaterialMapColor q = new MaterialMapColor(15, 14188339); + public static final MaterialMapColor r = new MaterialMapColor(16, 11685080); + public static final MaterialMapColor s = new MaterialMapColor(17, 6724056); + public static final MaterialMapColor t = new MaterialMapColor(18, 15066419); + public static final MaterialMapColor u = new MaterialMapColor(19, 8375321); + public static final MaterialMapColor v = new MaterialMapColor(20, 15892389); + public static final MaterialMapColor w = new MaterialMapColor(21, 5000268); + public static final MaterialMapColor x = new MaterialMapColor(22, 10066329); + public static final MaterialMapColor y = new MaterialMapColor(23, 5013401); + public static final MaterialMapColor z = new MaterialMapColor(24, 8339378); + public static final MaterialMapColor A = new MaterialMapColor(25, 3361970); + public static final MaterialMapColor B = new MaterialMapColor(26, 6704179); + public static final MaterialMapColor C = new MaterialMapColor(27, 6717235); + public static final MaterialMapColor D = new MaterialMapColor(28, 10040115); + public static final MaterialMapColor E = new MaterialMapColor(29, 1644825); + public static final MaterialMapColor F = new MaterialMapColor(30, 16445005); + public static final MaterialMapColor G = new MaterialMapColor(31, 6085589); + public static final MaterialMapColor H = new MaterialMapColor(32, 4882687); + public static final MaterialMapColor I = new MaterialMapColor(33, '\ud93a'); + public static final MaterialMapColor J = new MaterialMapColor(34, 8476209); + public static final MaterialMapColor K = new MaterialMapColor(35, 7340544); + public final int L; + public final int M; + + private MaterialMapColor(int i, int j) { + if (i >= 0 && i <= 63) { + this.M = i; + this.L = j; + MaterialMapColor.a[i] = this; + } else { + throw new IndexOutOfBoundsException("Map colour ID must be between 0 and 63 (inclusive)"); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/MaterialPortal.java b/azurite-server/src/main/java/net/minecraft/server/MaterialPortal.java new file mode 100644 index 0000000..4f3ab40 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/MaterialPortal.java @@ -0,0 +1,20 @@ +package net.minecraft.server; + +public class MaterialPortal extends Material { + + public MaterialPortal(MaterialMapColor materialmapcolor) { + super(materialmapcolor); + } + + public boolean isBuildable() { + return false; + } + + public boolean blocksLight() { + return false; + } + + public boolean isSolid() { + return false; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/MathHelper.java b/azurite-server/src/main/java/net/minecraft/server/MathHelper.java new file mode 100644 index 0000000..9f72cf9 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/MathHelper.java @@ -0,0 +1,305 @@ +package net.minecraft.server; + +import java.util.Random; +import java.util.UUID; + +public class MathHelper { + public static final float a = c(2.0F); + private static final float[] b = new float[65536]; + private static final int[] c; + private static final double d; + private static final double[] e; + private static final double[] f; + + public static float sin(float var0) { + return b[(int) (var0 * 10430.378F) & '\uffff']; + } + + public static float cos(float var0) { + return b[(int) (var0 * 10430.378F + 16384.0F) & '\uffff']; + } + + public static float c(float var0) { + return (float) Math.sqrt(var0); + } + + public static float sqrt(double var0) { + return (float) Math.sqrt(var0); + } + + public static int d(float var0) { + int var1 = (int) var0; + return var0 < (float) var1 ? var1 - 1 : var1; + } + + public static int floor(double var0) { + int var2 = (int) var0; + return var0 < (double) var2 ? var2 - 1 : var2; + } + + public static long d(double var0) { + long var2 = (long) var0; + return var0 < (double) var2 ? var2 - 1L : var2; + } + + public static float e(float var0) { + return var0 >= 0.0F ? var0 : -var0; + } + + public static int a(int var0) { + return var0 >= 0 ? var0 : -var0; + } + + public static int f(float var0) { + int var1 = (int) var0; + return var0 > (float) var1 ? var1 + 1 : var1; + } + + public static int f(double var0) { + int var2 = (int) var0; + return var0 > (double) var2 ? var2 + 1 : var2; + } + + public static int clamp(int var0, int var1, int var2) { + if (var0 < var1) { + return var1; + } else { + return var0 > var2 ? var2 : var0; + } + } + + public static float a(float var0, float var1, float var2) { + if (var0 < var1) { + return var1; + } else { + return var0 > var2 ? var2 : var0; + } + } + + public static double a(double var0, double var2, double var4) { + if (var0 < var2) { + return var2; + } else { + return var0 > var4 ? var4 : var0; + } + } + + public static double b(double var0, double var2, double var4) { + if (var4 < 0.0) { + return var0; + } else { + return var4 > 1.0 ? var2 : var0 + (var2 - var0) * var4; + } + } + + public static double a(double var0, double var2) { + if (var0 < 0.0) { + var0 = -var0; + } + + if (var2 < 0.0) { + var2 = -var2; + } + + return var0 > var2 ? var0 : var2; + } + + public static int nextInt(Random var0, int var1, int var2) { + return var1 >= var2 ? var1 : var0.nextInt(var2 - var1 + 1) + var1; + } + + public static float a(Random var0, float var1, float var2) { + return var1 >= var2 ? var1 : var0.nextFloat() * (var2 - var1) + var1; + } + + public static double a(Random var0, double var1, double var3) { + return var1 >= var3 ? var1 : var0.nextDouble() * (var3 - var1) + var1; + } + + public static double a(long[] var0) { + long var1 = 0L; + + for (long var6 : var0) { + var1 += var6; + } + + return (double) var1 / (double) var0.length; + } + + public static float g(float var0) { + var0 %= 360.0F; + if (var0 >= 180.0F) { + var0 -= 360.0F; + } + + if (var0 < -180.0F) { + var0 += 360.0F; + } + + return var0; + } + + public static double g(double var0) { + var0 %= 360.0; + if (var0 >= 180.0) { + var0 -= 360.0; + } + + if (var0 < -180.0) { + var0 += 360.0; + } + + return var0; + } + + public static int a(String var0, int var1) { + try { + return Integer.parseInt(var0); + } catch (Throwable var3) { + return var1; + } + } + + public static int a(String var0, int var1, int var2) { + return Math.max(var2, a(var0, var1)); + } + + public static double a(String var0, double var1) { + try { + return Double.parseDouble(var0); + } catch (Throwable var4) { + return var1; + } + } + + public static double a(String var0, double var1, double var3) { + return Math.max(var3, a(var0, var1)); + } + + public static int b(int var0) { + int var1 = var0 - 1; + var1 |= var1 >> 1; + var1 |= var1 >> 2; + var1 |= var1 >> 4; + var1 |= var1 >> 8; + var1 |= var1 >> 16; + return var1 + 1; + } + + private static boolean d(int var0) { + return var0 != 0 && (var0 & var0 - 1) == 0; + } + + private static int e(int var0) { + var0 = d(var0) ? var0 : b(var0); + return c[(int) ((long) var0 * 125613361L >> 27) & 31]; + } + + public static int c(int var0) { + return e(var0) - (d(var0) ? 0 : 1); + } + + public static int c(int var0, int var1) { + if (var1 == 0) { + return 0; + } else if (var0 == 0) { + return var1; + } else { + if (var0 < 0) { + var1 *= -1; + } + + int var2 = var0 % var1; + return var2 == 0 ? var0 : var0 + var1 - var2; + } + } + + public static UUID a(Random var0) { + long var1 = var0.nextLong() & -61441L | 16384L; + long var3 = var0.nextLong() & 4611686018427387903L | Long.MIN_VALUE; + return new UUID(var1, var3); + } + + public static double c(double var0, double var2, double var4) { + return (var0 - var2) / (var4 - var2); + } + + public static double b(double var0, double var2) { + double var4 = var2 * var2 + var0 * var0; + if (Double.isNaN(var4)) { + return Double.NaN; + } else { + boolean var6 = var0 < 0.0; + if (var6) { + var0 = -var0; + } + + boolean var7 = var2 < 0.0; + if (var7) { + var2 = -var2; + } + + boolean var8 = var0 > var2; + double var9; + if (var8) { + var9 = var2; + var2 = var0; + var0 = var9; + } + + var9 = i(var4); + var2 *= var9; + var0 *= var9; + double var11 = d + var0; + int var13 = (int) Double.doubleToRawLongBits(var11); + double var14 = e[var13]; + double var16 = f[var13]; + double var18 = var11 - d; + double var20 = var0 * var16 - var2 * var18; + double var22 = (6.0 + var20 * var20) * var20 * 0.16666666666666666; + double var24 = var14 + var22; + if (var8) { + var24 = 1.5707963267948966 - var24; + } + + if (var7) { + var24 = Math.PI - var24; + } + + if (var6) { + var24 = -var24; + } + + return var24; + } + } + + public static double i(double var0) { + double var2 = 0.5 * var0; + long var4 = Double.doubleToRawLongBits(var0); + var4 = 6910469410427058090L - (var4 >> 1); + var0 = Double.longBitsToDouble(var4); + var0 *= 1.5 - var2 * var0 * var0; + return var0; + } + + static { + int var0; + for (var0 = 0; var0 < 65536; ++var0) { + b[var0] = (float) Math.sin((double) var0 * Math.PI * 2.0 / 65536.0); + } + + c = new int[]{0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8, 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9}; + d = Double.longBitsToDouble(4805340802404319232L); + e = new double[257]; + f = new double[257]; + + for (var0 = 0; var0 < 257; ++var0) { + double var1 = (double) var0 / 256.0; + double var3 = Math.asin(var1); + f[var0] = Math.cos(var3); + e[var0] = var3; + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/MerchantRecipe.java b/azurite-server/src/main/java/net/minecraft/server/MerchantRecipe.java new file mode 100644 index 0000000..99958c6 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/MerchantRecipe.java @@ -0,0 +1,120 @@ +package net.minecraft.server; + +public class MerchantRecipe { + + private ItemStack buyingItem1; + private ItemStack buyingItem2; + private ItemStack sellingItem; + private int uses; + private int maxUses; + private boolean rewardExp; + + public MerchantRecipe(NBTTagCompound nbttagcompound) { + this.a(nbttagcompound); + } + + public MerchantRecipe(ItemStack itemstack, ItemStack itemstack1, ItemStack itemstack2) { + this(itemstack, itemstack1, itemstack2, 0, 7); + } + + public MerchantRecipe(ItemStack itemstack, ItemStack itemstack1, ItemStack itemstack2, int i, int j) { + this.buyingItem1 = itemstack; + this.buyingItem2 = itemstack1; + this.sellingItem = itemstack2; + this.uses = i; + this.maxUses = j; + this.rewardExp = true; + } + + public MerchantRecipe(ItemStack itemstack, ItemStack itemstack1) { + this(itemstack, (ItemStack) null, itemstack1); + } + + public MerchantRecipe(ItemStack itemstack, Item item) { + this(itemstack, new ItemStack(item)); + } + + public ItemStack getBuyItem1() { + return this.buyingItem1; + } + + public ItemStack getBuyItem2() { + return this.buyingItem2; + } + + public boolean hasSecondItem() { + return this.buyingItem2 != null; + } + + public ItemStack getBuyItem3() { + return this.sellingItem; + } + + public int e() { + return this.uses; + } + + public int f() { + return this.maxUses; + } + + public void g() { + ++this.uses; + } + + public void a(int i) { + this.maxUses += i; + } + + public boolean h() { + return this.uses >= this.maxUses; + } + + public boolean j() { + return this.rewardExp; + } + + public void a(NBTTagCompound nbttagcompound) { + NBTTagCompound nbttagcompound1 = nbttagcompound.getCompound("buy"); + + this.buyingItem1 = ItemStack.createStack(nbttagcompound1); + NBTTagCompound nbttagcompound2 = nbttagcompound.getCompound("sell"); + + this.sellingItem = ItemStack.createStack(nbttagcompound2); + if (nbttagcompound.hasKeyOfType("buyB", 10)) { + this.buyingItem2 = ItemStack.createStack(nbttagcompound.getCompound("buyB")); + } + + if (nbttagcompound.hasKeyOfType("uses", 99)) { + this.uses = nbttagcompound.getInt("uses"); + } + + if (nbttagcompound.hasKeyOfType("maxUses", 99)) { + this.maxUses = nbttagcompound.getInt("maxUses"); + } else { + this.maxUses = 7; + } + + if (nbttagcompound.hasKeyOfType("rewardExp", 1)) { + this.rewardExp = nbttagcompound.getBoolean("rewardExp"); + } else { + this.rewardExp = true; + } + + } + + public NBTTagCompound k() { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + + nbttagcompound.set("buy", this.buyingItem1.save(new NBTTagCompound())); + nbttagcompound.set("sell", this.sellingItem.save(new NBTTagCompound())); + if (this.buyingItem2 != null) { + nbttagcompound.set("buyB", this.buyingItem2.save(new NBTTagCompound())); + } + + nbttagcompound.setInt("uses", this.uses); + nbttagcompound.setInt("maxUses", this.maxUses); + nbttagcompound.setBoolean("rewardExp", this.rewardExp); + return nbttagcompound; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/MerchantRecipeList.java b/azurite-server/src/main/java/net/minecraft/server/MerchantRecipeList.java new file mode 100644 index 0000000..3dd2255 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/MerchantRecipeList.java @@ -0,0 +1,81 @@ +package net.minecraft.server; + +import java.util.ArrayList; + +public class MerchantRecipeList extends ArrayList { + + public MerchantRecipeList() {} + + public MerchantRecipeList(NBTTagCompound nbttagcompound) { + this.a(nbttagcompound); + } + + public MerchantRecipe a(ItemStack itemstack, ItemStack itemstack1, int i) { + if (i > 0 && i < this.size()) { + MerchantRecipe merchantrecipe = (MerchantRecipe) this.get(i); + + return this.a(itemstack, merchantrecipe.getBuyItem1()) && (itemstack1 == null && !merchantrecipe.hasSecondItem() || merchantrecipe.hasSecondItem() && this.a(itemstack1, merchantrecipe.getBuyItem2())) && itemstack.count >= merchantrecipe.getBuyItem1().count && (!merchantrecipe.hasSecondItem() || itemstack1.count >= merchantrecipe.getBuyItem2().count) ? merchantrecipe : null; + } else { + for (int j = 0; j < this.size(); ++j) { + MerchantRecipe merchantrecipe1 = (MerchantRecipe) this.get(j); + + if (this.a(itemstack, merchantrecipe1.getBuyItem1()) && itemstack.count >= merchantrecipe1.getBuyItem1().count && (!merchantrecipe1.hasSecondItem() && itemstack1 == null || merchantrecipe1.hasSecondItem() && this.a(itemstack1, merchantrecipe1.getBuyItem2()) && itemstack1.count >= merchantrecipe1.getBuyItem2().count)) { + return merchantrecipe1; + } + } + + return null; + } + } + + private boolean a(ItemStack itemstack, ItemStack itemstack1) { + return ItemStack.c(itemstack, itemstack1) && (!itemstack1.hasTag() || itemstack.hasTag() && GameProfileSerializer.a(itemstack1.getTag(), itemstack.getTag(), false)); + } + + public void a(PacketDataSerializer packetdataserializer) { + packetdataserializer.writeByte((byte) (this.size() & 255)); + + for (int i = 0; i < this.size(); ++i) { + MerchantRecipe merchantrecipe = (MerchantRecipe) this.get(i); + + packetdataserializer.a(merchantrecipe.getBuyItem1()); + packetdataserializer.a(merchantrecipe.getBuyItem3()); + ItemStack itemstack = merchantrecipe.getBuyItem2(); + + packetdataserializer.writeBoolean(itemstack != null); + if (itemstack != null) { + packetdataserializer.a(itemstack); + } + + packetdataserializer.writeBoolean(merchantrecipe.h()); + packetdataserializer.writeInt(merchantrecipe.e()); + packetdataserializer.writeInt(merchantrecipe.f()); + } + + } + + public void a(NBTTagCompound nbttagcompound) { + NBTTagList nbttaglist = nbttagcompound.getList("Recipes", 10); + + for (int i = 0; i < nbttaglist.size(); ++i) { + NBTTagCompound nbttagcompound1 = nbttaglist.get(i); + + this.add(new MerchantRecipe(nbttagcompound1)); + } + + } + + public NBTTagCompound a() { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + NBTTagList nbttaglist = new NBTTagList(); + + for (int i = 0; i < this.size(); ++i) { + MerchantRecipe merchantrecipe = (MerchantRecipe) this.get(i); + + nbttaglist.add(merchantrecipe.k()); + } + + nbttagcompound.set("Recipes", nbttaglist); + return nbttagcompound; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/MethodProfiler.java b/azurite-server/src/main/java/net/minecraft/server/MethodProfiler.java new file mode 100644 index 0000000..3f8b1d2 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/MethodProfiler.java @@ -0,0 +1,51 @@ +package net.minecraft.server; + +import java.util.List; + +// CraftBukkit start - Strip down to empty methods, performance cost +public class MethodProfiler { + + public boolean a; + public MethodProfiler() {} + + public void a() { + } + + public void a(String s) { + } + + public void b() { + } + + public List b(String s) { + return null; + } + + public void c(String s) { + } + + public String c() { + return ""; + } + + public static final class ProfilerInfo implements Comparable { + + public double a; + public double b; + public String c; + + public ProfilerInfo(String s, double d0, double d1) { + this.c = s; + this.a = d0; + this.b = d1; + } + + public int a(MethodProfiler.ProfilerInfo methodprofiler_profilerinfo) { + return methodprofiler_profilerinfo.a < this.a ? -1 : (methodprofiler_profilerinfo.a > this.a ? 1 : methodprofiler_profilerinfo.c.compareTo(this.c)); + } + + public int compareTo(MethodProfiler.ProfilerInfo object) { + return this.a(object); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/MinecraftEncryption.java b/azurite-server/src/main/java/net/minecraft/server/MinecraftEncryption.java new file mode 100644 index 0000000..fb083ae --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/MinecraftEncryption.java @@ -0,0 +1,104 @@ +package net.minecraft.server; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import javax.crypto.*; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; +import java.io.UnsupportedEncodingException; +import java.security.*; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.X509EncodedKeySpec; + +public class MinecraftEncryption { + private static final Logger a = LogManager.getLogger(); + + public static KeyPair b() { + try { + KeyPairGenerator var0 = KeyPairGenerator.getInstance("RSA"); + var0.initialize(1024); + return var0.generateKeyPair(); + } catch (NoSuchAlgorithmException var1) { + var1.printStackTrace(); + a.error("Key pair generation failed!"); + return null; + } + } + + public static byte[] a(String var0, PublicKey var1, SecretKey var2) { + try { + return a("SHA-1", var0.getBytes("ISO_8859_1"), var2.getEncoded(), var1.getEncoded()); + } catch (UnsupportedEncodingException var4) { + var4.printStackTrace(); + return null; + } + } + + private static byte[] a(String var0, byte[]... var1) { + try { + MessageDigest var2 = MessageDigest.getInstance(var0); + for (byte[] var6 : var1) { + var2.update(var6); + } + return var2.digest(); + } catch (NoSuchAlgorithmException var7) { + var7.printStackTrace(); + return null; + } + } + + public static PublicKey a(byte[] var0) { + try { + X509EncodedKeySpec var1 = new X509EncodedKeySpec(var0); + KeyFactory var2 = KeyFactory.getInstance("RSA"); + return var2.generatePublic(var1); + } catch (NoSuchAlgorithmException | InvalidKeySpecException ignored) { + } + + a.error("Public key reconstitute failed!"); + return null; + } + + public static SecretKey a(PrivateKey var0, byte[] var1) { + return new SecretKeySpec(b(var0, var1), "AES"); + } + + public static byte[] b(Key var0, byte[] var1) { + return a(2, var0, var1); + } + + private static byte[] a(int var0, Key var1, byte[] var2) { + try { + return a(var0, var1.getAlgorithm(), var1).doFinal(var2); + } catch (IllegalBlockSizeException | BadPaddingException var4) { + var4.printStackTrace(); + } + + a.error("Cipher data failed!"); + return null; + } + + private static Cipher a(int var0, String var1, Key var2) { + try { + Cipher var3 = Cipher.getInstance(var1); + var3.init(var0, var2); + return var3; + } catch (InvalidKeyException | NoSuchPaddingException | NoSuchAlgorithmException var4) { + var4.printStackTrace(); + } + + a.error("Cipher creation failed!"); + return null; + } + + public static Cipher a(int var0, Key var1) { + try { + Cipher var2 = Cipher.getInstance("AES/CFB8/NoPadding"); + var2.init(var0, var1, new IvParameterSpec(var1.getEncoded())); + return var2; + } catch (GeneralSecurityException var3) { + throw new RuntimeException(var3); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/MinecraftKey.java b/azurite-server/src/main/java/net/minecraft/server/MinecraftKey.java new file mode 100644 index 0000000..dadc01e --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/MinecraftKey.java @@ -0,0 +1,58 @@ +package net.minecraft.server; + +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.Validate; + +public class MinecraftKey { + + protected final String a; + protected final String b; + + protected MinecraftKey(int i, String... astring) { + this.a = StringUtils.isEmpty(astring[0]) ? "minecraft" : astring[0].toLowerCase(); + this.b = astring[1]; + Validate.notNull(this.b); + } + + public MinecraftKey(String s) { + this(0, a(s)); + } + + protected static String[] a(String s) { + String[] astring = new String[] { null, s}; + int i = s.indexOf(58); + + if (i >= 0) { + astring[1] = s.substring(i + 1, s.length()); + if (i > 1) { + astring[0] = s.substring(0, i); + } + } + + return astring; + } + + public String a() { + return this.b; + } + + public String toString() { + return this.a + ':' + this.b; + } + + public boolean equals(Object object) { + if (this == object) { + return true; + } else if (!(object instanceof MinecraftKey)) { + return false; + } else { + MinecraftKey minecraftkey = (MinecraftKey) object; + + return this.a.equals(minecraftkey.a) && this.b.equals(minecraftkey.b); + } + } + + public int hashCode() { + return 31 * this.a.hashCode() + this.b.hashCode(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/MinecraftServer.java b/azurite-server/src/main/java/net/minecraft/server/MinecraftServer.java new file mode 100644 index 0000000..aa7db16 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/MinecraftServer.java @@ -0,0 +1,1338 @@ +package net.minecraft.server; + +import com.destroystokyo.paper.event.server.ServerTickEndEvent; +import com.destroystokyo.paper.event.server.ServerTickStartEvent; +import com.eatthepath.uuid.FastUUID; +import com.google.common.collect.Lists; +import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.ListenableFuture; +import com.google.common.util.concurrent.ListenableFutureTask; +import com.mojang.authlib.GameProfile; +import com.mojang.authlib.GameProfileRepository; +import com.mojang.authlib.minecraft.MinecraftSessionService; +import com.mojang.authlib.yggdrasil.YggdrasilAuthenticationService; +import dev.azurite.spigot.Azurite; +import dev.azurite.spigot.autosave.AutoSave; +import dev.azurite.spigot.configs.AzuriteConfig; +import dev.azurite.spigot.optimizations.ModernHopperOptimizations; +import dev.azurite.spigot.tickloop.AzuriteTickloop; +import dev.azurite.spigot.utils.CachedSizeConcurrentLinkedQueue; +import joptsimple.OptionSet; +import org.apache.commons.lang3.Validate; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.bukkit.craftbukkit.chunkio.ChunkIOExecutor; +import org.bukkit.event.server.ServerShutdownEvent; + +import java.io.File; +import java.io.IOException; +import java.net.Proxy; +import java.security.KeyPair; +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.concurrent.Callable; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.Executors; +// CraftBukkit end + +public abstract class MinecraftServer implements ICommandListener, IAsyncTaskHandler { + + public static boolean HAS_PROTOCOL_SUPPORT = false; + public final MethodProfiler methodProfiler = new MethodProfiler(); + public static final Logger LOGGER = LogManager.getLogger(); + public static final File a = new File("usercache.json"); + private static MinecraftServer l; + protected final ICommandHandler b; + protected final Random s = new Random(); + protected final Proxy e; + // beanes - make tasks no longer use FutureTask, if a plugin is dependent on it we can write it in another queue + public final Queue tasks = new ConcurrentLinkedQueue<>(); // Spigot, PAIL: Rename + public final Queue loginTasks = new ConcurrentLinkedQueue<>(); // Spigot, PAIL: Rename + private final List p = Lists.newArrayList(); + private final ServerConnection q; // Spigot + public final ServerPing r = new ServerPing(); + private final YggdrasilAuthenticationService V; + private final MinecraftSessionService W; + private final GameProfileRepository Y; + private final UserCache Z; + private final Object stopLock = new Object(); + public final Queue processQueue = new ConcurrentLinkedQueue() { + @Override + public boolean add(Runnable runnable) { + postToMainThreadRunnable(runnable); + return true; + } + }; + public Convertable convertable; + public File universe; + public WorldServer[] worldServer; + public String f; + public int g; + public long[][] i; + // CraftBukkit start + public List worlds = new ArrayList<>(); + public org.bukkit.craftbukkit.CraftServer server; + public OptionSet options; + public org.bukkit.command.ConsoleCommandSender console; + public org.bukkit.command.RemoteConsoleCommandSender remoteConsole; + public int autosavePeriod; + public double[] recentTps = new double[3]; // PaperSpigot - Fine have your darn compat with bad plugins + private String serverIp; + private int u = -1; + private PlayerList v; + private boolean isRunning = true; + public boolean isStopped; + private int ticks; + private boolean spawnAnimals = true; + private boolean spawnNPCs; + private boolean pvpMode; + // CraftBukkit end + private boolean allowFlight; + private String motd; + private int G = 0; + private KeyPair H; + // CraftBukkit end + private String I; + private String J; + private boolean demoMode; + private boolean N; + private String O = ""; + private String P = ""; + private boolean U; + public Thread primaryThread; + public Thread serverThread; + public long ab = az(); + // CraftBukkit start + private boolean hasStopped = false; + private final AutoSave autoSaveManager; + + public MinecraftServer(OptionSet options, Proxy proxy, File file1) { + q = new ServerConnection(this); + io.netty.util.ResourceLeakDetector.setEnabled(false); // Spigot - disable + this.e = proxy; + MinecraftServer.l = this; + + this.Z = new UserCache(this, file1); + this.autoSaveManager = new AutoSave(); + // Azurite - async chunk cache + this.Z.saveUserCache(AzuriteConfig.asyncUserCacheSave.getValue()); + this.b = this.h(); + // this.convertable = new WorldLoaderServer(file); // CraftBukkit - moved to DedicatedServer.init + this.V = new YggdrasilAuthenticationService(proxy, FastUUID.toString(UUID.randomUUID())); + this.W = this.V.createMinecraftSessionService(); + this.Y = this.V.createProfileRepository(); + + // CraftBukkit start + this.options = options; + + Runtime.getRuntime().addShutdownHook(new org.bukkit.craftbukkit.util.ServerShutdownThread(this)); + primaryThread = serverThread = new Thread(new AzuriteTickloop(this), "Server thread"); + primaryThread.setPriority(Thread.MAX_PRIORITY); + primaryThread.start(); + } + + public static void main(final OptionSet options) { // CraftBukkit - replaces main(String[] astring) + DispenserRegistry.c(); + + try { + DedicatedServer dedicatedserver = new DedicatedServer(options); + + if (options.has("port")) { + int port = (Integer) options.valueOf("port"); + if (port > 0) { + dedicatedserver.setPort(port); + } + } + + if (options.has("universe")) { + dedicatedserver.universe = (File) options.valueOf("universe"); + } + + if (options.has("world")) { + dedicatedserver.setWorld((String) options.valueOf("world")); + } + + // CraftBukkit end + } catch (Exception exception) { + MinecraftServer.LOGGER.fatal("Failed to start the minecraft server", exception); + } + } + + public static MinecraftServer getServer() { + return MinecraftServer.l; + } + + public static long az() { + return System.currentTimeMillis(); + } + + public abstract PropertyManager getPropertyManager(); + + protected CommandDispatcher h() { + return new CommandDispatcher(); + } + // CraftBukkit end + + public abstract boolean init() throws IOException; + + protected void a(String s) { + if (this.getConvertable().isConvertable(s)) { + MinecraftServer.LOGGER.info("Converting map!"); + this.getConvertable().convert(s, new IProgressUpdate() { + private long b = System.currentTimeMillis(); + + public void a(String s) { + } + + public void a(int i) { + if (System.currentTimeMillis() - this.b >= 1000L) { + this.b = System.currentTimeMillis(); + MinecraftServer.LOGGER.info("Converting... " + i + "%"); + } + + } + + public void c(String s) { + } + }); + } + + } + + protected synchronized void b(String s) { + } + + protected void a(String s, String s1, long i, WorldType worldtype, String s2) { + // SWM start + WorldServer[] defaultWorlds = (WorldServer[]) com.grinderwolf.swm.clsm.ClassModifier.getDefaultWorlds(); + if (defaultWorlds != null) { + System.out.println("Overriding default worlds"); + this.a(s); + this.worldServer = new WorldServer[3]; + + for (int index = 0; index < 3; index++) { + if (index == 1 && !getAllowNether()) { + continue; + } + + if (index == 2 && !server.getAllowEnd()) { + continue; + } + + WorldServer world = defaultWorlds[index]; + int dimension = (index == 1 ? -1 : (index == 2 ? 1 : 0)); + + WorldSettings worldSettings = new WorldSettings(i, this.getGamemode(), this.getGenerateStructures(), this.isHardcore(), worldtype); + java.lang.String worldTypeString = org.bukkit.World.Environment.getEnvironment(dimension).toString().toLowerCase(); + java.lang.String name; + + if (dimension == 0) { + name = s; + } else { + name = s + "_" + worldTypeString; + } + + if (world == null) { + worldSettings.setGeneratorSettings(s2); + } + + if (index == 0) { + if (world == null) { + IDataManager nbtStorage = new ServerNBTManager(server.getWorldContainer(), s1, true); + WorldData worldData = nbtStorage.getWorldData(); + + if (worldData == null) { + worldData = new WorldData(worldSettings, s1); + } + + worldData.checkName(s1); + world = (WorldServer) new WorldServer(this, nbtStorage, worldData, dimension, null, org.bukkit.World.Environment.getEnvironment(dimension), this.server.getGenerator(name), true).b(); + world.a(worldSettings); + } else { + org.spigotmc.SpigotConfig.disableStatSaving = true; + } + + this.server.scoreboardManager = new org.bukkit.craftbukkit.scoreboard.CraftScoreboardManager(this, world.getScoreboard()); + } else if (world == null) { + IDataManager nbtStorage = new ServerNBTManager(server.getWorldContainer(), name, true); + WorldData worldData = nbtStorage.getWorldData(); + + if (worldData == null) { + worldData = new WorldData(worldSettings, name); + } + + worldData.checkName(name); + world = (WorldServer) new SecondaryWorldServer(this, nbtStorage, dimension, this.worlds.get(0), null, worldData, org.bukkit.World.Environment.getEnvironment(dimension), this.server.getGenerator(name)).b(); + } + + this.server.getPluginManager().callEvent(new org.bukkit.event.world.WorldInitEvent(world.getWorld())); + + if (defaultWorlds[index] == null) { + world.addIWorldAccess(new WorldManager(this, world)); + } + + if (!this.T()) { + world.getWorldData().setGameType(this.getGamemode()); + } + + this.worlds.add(world); + this.getPlayerList().setPlayerFileData(this.worlds.toArray(new WorldServer[this.worlds.size()])); + } + + this.a(this.getDifficulty()); + this.k(); + + return; + } + // SWM end + + this.a(s); + this.worldServer = new WorldServer[3]; + + int worldCount = 3; + + for (int j = 0; j < worldCount; ++j) { + WorldServer world; + byte dimension = 0; + + if (j == 1) { + if (getAllowNether()) { + dimension = -1; + } else { + continue; + } + } + + if (j == 2) { + if (server.getAllowEnd()) { + dimension = 1; + } else { + continue; + } + } + + String worldType = org.bukkit.World.Environment.getEnvironment(dimension).toString().toLowerCase(); + String name = (dimension == 0) ? s : s + "_" + worldType; + + org.bukkit.generator.ChunkGenerator gen = this.server.getGenerator(name); + WorldSettings worldsettings = new WorldSettings(i, this.getGamemode(), this.getGenerateStructures(), + this.isHardcore(), worldtype); + worldsettings.setGeneratorSettings(s2); + + if (j == 0) { + IDataManager idatamanager = new ServerNBTManager(server.getWorldContainer(), s1, true); + WorldData worlddata = idatamanager.getWorldData(); + if (worlddata == null) { + worlddata = new WorldData(worldsettings, s1); + } + worlddata.checkName(s1); // CraftBukkit - Migration did not rewrite the level.dat; This forces 1.8 to + // take the last loaded world as respawn (in this case the end) + world = (WorldServer) (new WorldServer(this, idatamanager, worlddata, dimension, getServer().methodProfiler, + org.bukkit.World.Environment.getEnvironment(dimension), gen, true)).b(); + world.a(worldsettings); + this.server.scoreboardManager = new org.bukkit.craftbukkit.scoreboard.CraftScoreboardManager(this, + world.getScoreboard()); + } else { + String dim = "DIM" + dimension; + + File newWorld = new File(new File(name), dim); + File oldWorld = new File(new File(s), dim); + + if ((!newWorld.isDirectory()) && (oldWorld.isDirectory())) { + MinecraftServer.LOGGER.info("---- Migration of old " + worldType + " folder required ----"); + MinecraftServer.LOGGER.info( + "Unfortunately due to the way that Minecraft implemented multiworld support in 1.6, Bukkit requires that you move your " + + worldType + " folder to a new location in order to operate correctly."); + MinecraftServer.LOGGER.info( + "We will move this folder for you, but it will mean that you need to move it back should you wish to stop using Bukkit in the future."); + MinecraftServer.LOGGER.info("Attempting to move " + oldWorld + " to " + newWorld + "..."); + + if (newWorld.exists()) { + MinecraftServer.LOGGER.warn("A file or folder already exists at " + newWorld + "!"); + MinecraftServer.LOGGER.info("---- Migration of old " + worldType + " folder failed ----"); + } else if (newWorld.getParentFile().mkdirs()) { + if (oldWorld.renameTo(newWorld)) { + MinecraftServer.LOGGER.info("Success! To restore " + worldType + + " in the future, simply move " + newWorld + " to " + oldWorld); + // Migrate world data too. + try { + com.google.common.io.Files.copy(new File(new File(s), "level.dat"), + new File(new File(name), "level.dat")); + } catch (IOException exception) { + MinecraftServer.LOGGER.warn("Unable to migrate world data."); + } + MinecraftServer.LOGGER.info("---- Migration of old " + worldType + " folder complete ----"); + } else { + MinecraftServer.LOGGER.warn("Could not move folder " + oldWorld + " to " + newWorld + "!"); + MinecraftServer.LOGGER.info("---- Migration of old " + worldType + " folder failed ----"); + } + } else { + MinecraftServer.LOGGER.warn("Could not create path for " + newWorld + "!"); + MinecraftServer.LOGGER.info("---- Migration of old " + worldType + " folder failed ----"); + } + } + + IDataManager idatamanager = new ServerNBTManager(server.getWorldContainer(), name, true); + // world =, b0 to dimension, s1 to name, added Environment and gen + WorldData worlddata = idatamanager.getWorldData(); + if (worlddata == null) { + worlddata = new WorldData(worldsettings, name); + } + worlddata.checkName(name); // CraftBukkit - Migration did not rewrite the level.dat; This forces 1.8 to + // take the last loaded world as respawn (in this case the end) + world = (WorldServer) new SecondaryWorldServer(this, idatamanager, dimension, this.worlds.get(0), + null, worlddata, org.bukkit.World.Environment.getEnvironment(dimension), gen) + .b(); + } + + this.server.getPluginManager().callEvent(new org.bukkit.event.world.WorldInitEvent(world.getWorld())); + + world.addIWorldAccess(new WorldManager(this, world)); + world.getWorldData().setGameType(this.getGamemode()); + + worlds.add(world); + getPlayerList().setPlayerFileData(worlds.toArray(new WorldServer[0])); + } + + // CraftBukkit end + this.a(this.getDifficulty()); + this.k(); + } + + protected void k() { + // CraftBukkit start - fire WorldLoadEvent and handle whether or not to keep the + // spawn in memory + int i; + + for (WorldServer worldserver : worlds) { + if (!worldserver.getWorld().getKeepSpawnInMemory()) { + continue; + } + + ModernHopperOptimizations.skipHopperEvents = org.bukkit.event.inventory.InventoryMoveItemEvent.getHandlerList().getRegisteredListeners().length == 0; + + BlockPosition blockposition = worldserver.getSpawn(); + long j = az(); + i = 0; + + for (int k = -192; k <= 192 && isRunning(); k += 16) { + for (int l = -192; l <= 192 && isRunning(); l += 16) { + long i1 = az(); + + if (i1 - j > 1000L) { + this.a_("Preparing spawn area", i * 100 / 625); + j = i1; + } + + ++i; + worldserver.chunkProviderServer.getChunkAt(blockposition.getX() + k >> 4, blockposition.getZ() + l >> 4, () -> { + }); + } + } + } + + for (WorldServer world : this.worlds) { + this.server.getPluginManager().callEvent(new org.bukkit.event.world.WorldLoadEvent(world.getWorld())); + } + // CraftBukkit end + this.s(); + } + + protected void a(String s, IDataManager idatamanager) { + File file = new File(idatamanager.getDirectory(), "resources.zip"); + + if (file.isFile()) { + this.setResourcePack("level://" + s + "/" + file.getName(), ""); + } + + } + + public abstract boolean getGenerateStructures(); + + public abstract WorldSettings.EnumGamemode getGamemode(); + + public void setGamemode(WorldSettings.EnumGamemode worldsettings_enumgamemode) { + // CraftBukkit start + for (int i = 0; i < this.worlds.size(); ++i) { + getServer().worlds.get(i).getWorldData().setGameType(worldsettings_enumgamemode); + } + + } + + public abstract EnumDifficulty getDifficulty(); + + public abstract boolean isHardcore(); + + public abstract int p(); + + public abstract boolean q(); + + public abstract boolean r(); + // PaperSpigot End + + protected void a_(String s, int i) { + this.f = s; + this.g = i; + MinecraftServer.LOGGER.info("{}: {}%", s, i); + } + + protected void s() { + this.f = null; + this.g = 0; + + this.server.enablePlugins(org.bukkit.plugin.PluginLoadOrder.POSTWORLD); // CraftBukkit + } + + protected void saveChunks(boolean flag) throws ExceptionWorldConflict { // CraftBukkit - added throws + if (!this.N) { + + // CraftBukkit start + for (WorldServer worldserver : worlds) { + // CraftBukkit end + + if (worldserver != null) { + if (!flag) { + MinecraftServer.LOGGER.info("Saving chunks for level '{}'/{}", worldserver.getWorldData().getName(), worldserver.worldProvider.getName()); + } + + try { + worldserver.save(true, null); + worldserver.saveLevel(); // CraftBukkit + } catch (ExceptionWorldConflict exceptionworldconflict) { + MinecraftServer.LOGGER.warn(exceptionworldconflict.getMessage()); + } + } + } + } + } + + public void stop() throws ExceptionWorldConflict { // CraftBukkit - added throws + // CraftBukkit start - prevent double stopping on multiple threads + synchronized (stopLock) { + if (hasStopped) return; + hasStopped = true; + } + // CraftBukkit end + if (!this.N) { + this.server.getPluginManager().callEvent(new ServerShutdownEvent(this.server)); + MinecraftServer.LOGGER.info("Stopping server"); + + // CraftBukkit start + if (this.server != null) { + this.server.disablePlugins(); + } + // CraftBukkit end + if (this.aq() != null) { + this.aq().b(); + } + + Azurite.getInstance().shutdown(); // Shutdown before saves so files queued are ran sync + + if (v != null) { + MinecraftServer.LOGGER.info("Saving players"); + v.savePlayers(); + v.u(); + try { + Thread.sleep(100); + } catch (InterruptedException ignored) { + } // CraftBukkit - SPIGOT-625 - give server at least a chance to send packets + } + + if (this.worldServer != null) { + MinecraftServer.LOGGER.info("Saving worlds"); + saveChunks(false); + } + + // Spigot start + if (org.spigotmc.SpigotConfig.saveUserCacheOnStopOnly) { + LOGGER.info("Saving usercache.json"); + this.Z.c(); + } + //Spigot end + } + } + + public String getServerIp() { + return this.serverIp; + } + + public void c(String s) { + this.serverIp = s; + } + + public boolean isRunning() { + return this.isRunning; + } + + public void safeShutdown() { + this.isRunning = false; + } + + public File y() { + return new File("."); + } + + // PaperSpigot start - Further improve tick loop + public static long currentTickLong = 0L; // Paper + public static int currentTick = 0; + private static final int SAMPLE_INTERVAL = 20; // Paper + private static final java.math.BigDecimal TPS_BASE = new java.math.BigDecimal("1E9").multiply(new java.math.BigDecimal(SAMPLE_INTERVAL)); + public static final int TPS = 20; + private static final long SEC_IN_NANO = 1000000000; + public static final int TICK_TIME = 1000000000 / 20; + public long lastTick = 0; + public final RollingAverage tps1 = new RollingAverage(1); + public final RollingAverage tps5 = new RollingAverage(60 * 5); + public final RollingAverage tps15 = new RollingAverage(60 * 15); + public long tickSection; + + public void subTick() { + // Process all incoming packets (+ some main thread tasks) + if (AzuriteConfig.processPacketsInBetweenTicks.getValue()) { + this.processTasks(); + } + + // Flush world changes in between ticks + if (AzuriteConfig.flushWorldChangesInBetweenTicks.getValue()) { + for (WorldServer worldserver : worlds) { + worldserver.flushWorldChanges(); + } + } + } + + public void processTasks() { + // Process all tasks + Runnable runnable; + while ((runnable = tasks.poll()) != null) + runnable.run(); + } + + public void processLoginTasks() { + // Process all tasks + Runnable loginRunnable; + while ((loginRunnable = loginTasks.poll()) != null) + loginRunnable.run(); + } + + public void startTick() { + new ServerTickStartEvent(ticks + 1).callEvent(); + ++this.ticks; + } + + public void endTick() { + long endTime = System.nanoTime(); + long remaining = (TICK_TIME - (endTime - lastTick)); + new ServerTickEndEvent(ticks, ((double) (endTime - lastTick) / 1000000D), remaining).callEvent(); + } + + public void crash(Throwable throwable) { + MinecraftServer.LOGGER.error("Encountered an unexpected exception", throwable); + // Spigot Start + if (throwable.getCause() != null) { + MinecraftServer.LOGGER.error("\tCause of unexpected exception was", throwable.getCause()); + } + // Spigot End + CrashReport crashreport; + + if (throwable instanceof ReportedException) { + crashreport = this.b(((ReportedException) throwable).a()); + } else { + crashreport = this.b(new CrashReport("Exception in server tick loop", throwable)); + } + + File file = new File(new File(this.y(), "crash-reports"), "crash-" + (new SimpleDateFormat("yyyy-MM-dd_HH.mm.ss")).format(new Date()) + "-server.txt"); + + if (crashreport.a(file)) { + MinecraftServer.LOGGER.error("This crash report has been saved to: {}", file.getAbsolutePath()); + } else { + MinecraftServer.LOGGER.error("We were unable to save this crash report to disk."); + } + + this.a(crashreport); + } + + public void a(CrashReport crashreport) { + } + + public void z() { + } + + public void A() throws ExceptionWorldConflict { // CraftBukkit - added throws + long curTime = System.nanoTime(); + this.lastTick = curTime; + + ++MinecraftServer.currentTickLong; // Paper + if (++MinecraftServer.currentTick % MinecraftServer.SAMPLE_INTERVAL == 0) { + final long diff = curTime - tickSection; + java.math.BigDecimal currentTps = TPS_BASE.divide(new java.math.BigDecimal(diff), 30, java.math.RoundingMode.HALF_UP); + tps1.add(currentTps, diff); + tps5.add(currentTps, diff); + tps15.add(currentTps, diff); + // Backwards compat with bad plugins + this.recentTps[0] = tps1.getAverage(); + this.recentTps[1] = tps5.getAverage(); + this.recentTps[2] = tps15.getAverage(); + // Paper end + tickSection = curTime; + } + + B(); + + if (AzuriteConfig.autoSaveInIncrements.getValue()) { + if (this.autoSaveManager.isActive()) { + server.playerCommandState = true; + this.autoSaveManager.execute(); + server.playerCommandState = false; + + } else if ((this.autosavePeriod > 0) && ((this.ticks % this.autosavePeriod) == 0)) { // CraftBukkit + this.autoSaveManager.reset(); + for (WorldServer worldserver : worlds) { + this.autoSaveManager.queueWorld(worldserver); + } + this.autoSaveManager.start(); + } + } else { + if (autosavePeriod > 0 && ticks % autosavePeriod == 0) { // CraftBukkit + v.savePlayers(); + // Spigot Start + // We replace this with saving each individual world as this.saveChunks(...) is + // broken, + // and causes the main thread to sleep for random amounts of time depending on + // chunk activity + // Also pass flag to only save modified chunks + server.playerCommandState = true; + for (World world : worlds) { + world.getWorld().save(false); + } + server.playerCommandState = false; + // this.saveChunks(true); + // Spigot End + } + } + + org.spigotmc.WatchdogThread.tick(); // Spigot + } + + public void B() { + aq().c(); + server.getScheduler().mainThreadHeartbeat(ticks); + ChunkIOExecutor.tick(); + Azurite.getInstance().getMenuManager().tick(); // Azurite - Updating menus + + // PandaSpigot start - optimize time updates + for (final WorldServer world : this.worlds) { + final boolean doDaylight = world.getGameRules().getBoolean("doDaylightCycle"); + final long dayTime = world.getDayTime(); + long worldTime = world.getTime(); + final PacketPlayOutUpdateTime worldPacket = new PacketPlayOutUpdateTime(worldTime, dayTime, doDaylight); + for (EntityHuman entityhuman : world.players) { + if (!(entityhuman instanceof EntityPlayer) || (this.ticks + entityhuman.getId()) % 20 != 0) { + continue; + } + EntityPlayer entityplayer = (EntityPlayer) entityhuman; + long playerTime = entityplayer.getPlayerTime(); + + // Beanes - don't send time updates if day light cycle is off and it's the same time as last time (haha funny word joke!) + if (entityplayer.lastSentPlayerTime == playerTime && !doDaylight) { + continue; + } + + PacketPlayOutUpdateTime packet = (playerTime == dayTime) ? worldPacket : new PacketPlayOutUpdateTime(worldTime, playerTime, doDaylight); + entityplayer.playerConnection.sendPacket(packet); // Add support for per player time + entityplayer.lastSentPlayerTime = playerTime; + } + } + // PandaSpigot end + + for (WorldServer worldserver : worlds) { + // Azurite - check world session every 5 seconds + if (MinecraftServer.currentTick % (20 * 5) == 0) { + try { + worldserver.checkSession(); + } catch (Exception ex) { + throw new RuntimeException(ex); + } + } + + CrashReport crashreport; + + try { + worldserver.doTick(); + } catch (Exception e) { + e.printStackTrace(); + try { + crashreport = CrashReport.a(e, "Exception ticking world"); + } catch (Throwable t) { + throw new RuntimeException("Error generating crash report", t); + } + worldserver.a(crashreport); + throw new ReportedException(crashreport); + } + + try { + worldserver.tickEntities(); + } catch (Throwable throwable1) { + try { + crashreport = CrashReport.a(throwable1, + "Exception ticking world entities [World Name: " + worldserver.getWorld().getName() + + ", IWorldAccess Size: " + worldserver.u.size() + ", Entities: " + + worldserver.entityList.size() + "]"); + } catch (Throwable t) { + throw new RuntimeException("Error generating crash report", t); + } + worldserver.a(crashreport); + throw new ReportedException(crashreport); + } + + if (this.getPlayerList().getPlayerCount() != 0) { // Tuinity + worldserver.tracker.updatePlayers(); + + for (EntityHuman human : worldserver.players) { + if (human instanceof EntityPlayer) { + EntityPlayer player = (EntityPlayer) human; + player.playerConnection.networkManager.flushAndWriteCurrentQueue(); + } + } + } + + worldserver.explosionDensityCache.clear(); + worldserver.movementCache.clear(); + } + + if (AzuriteConfig.tickPlayerLatency.getValue()) { + v.tick(); + } + + for (int i = 0; i < this.p.size(); ++i) { + p.get(i).c(); + } + } + + public boolean getAllowNether() { + return true; + } + + public void a(IUpdatePlayerListBox iupdateplayerlistbox) { + this.p.add(iupdateplayerlistbox); + } + + public void C() { + } + + public File d(String s) { + return new File(this.y(), s); + } + + public void info(String s) { + MinecraftServer.LOGGER.info(s); + } + + public void warning(String s) { + MinecraftServer.LOGGER.warn(s); + } + + public WorldServer getWorldServer(int i) { + // CraftBukkit start + for (WorldServer world : worlds) { + if (world.dimension == i) { + return world; + } + } + return worlds.get(0); + // CraftBukkit end + } + + public String E() { + return this.serverIp; + } + + public int F() { + return this.u; + } + + public String G() { + return this.motd; + } + + public String getVersion() { + return "1.8.8"; + } + + public int I() { + return this.v.getPlayerCount(); + } + + public int J() { + return this.v.getMaxPlayers(); + } + + public String[] getPlayers() { + return this.v.f(); + } + + public GameProfile[] L() { + return this.v.g(); + } + + public boolean isDebugging() { + return this.getPropertyManager().getBoolean("debug", false); // CraftBukkit - don't hardcode + } + + public void g(String s) { + MinecraftServer.LOGGER.error(s); + } + + public void h(String s) { + if (this.isDebugging()) { + MinecraftServer.LOGGER.info(s); + } + + } + + public String getServerModName() { + return AzuriteConfig.serverBranding.getValue(); // PaperSpigot - PaperSpigot > // Spigot - Spigot > // CraftBukkit - cb > vanilla! + } + + public CrashReport b(CrashReport crashreport) { + if (this.v != null) { + crashreport.g().a("Player Count", new Callable() { + public String a() { + return MinecraftServer.this.v.getPlayerCount() + " / " + MinecraftServer.this.v.getMaxPlayers() + "; " + MinecraftServer.this.v.v(); + } + + public Object call() { + return this.a(); + } + }); + } + + return crashreport; + } + + public List tabCompleteCommand(ICommandListener icommandlistener, String s, BlockPosition blockposition) { + return server.tabComplete(icommandlistener, s, blockposition); + } + + public boolean O() { + return true; // CraftBukkit + } + + public String getName() { + return "Server"; + } + + public void sendMessage(IChatBaseComponent ichatbasecomponent) { + MinecraftServer.LOGGER.info(org.bukkit.craftbukkit.util.CraftChatMessage.fromComponent(ichatbasecomponent, net.minecraft.server.EnumChatFormat.WHITE)); + } + + public boolean a(int i, String s) { + return true; + } + + public ICommandHandler getCommandHandler() { + return this.b; + } + + public KeyPair Q() { + return this.H; + } + + public void au() { + } + + public int R() { + return this.u; + } + + public void setPort(int i) { + this.u = i; + } + + public String S() { + return this.I; + } + + public void i(String s) { + this.I = s; + } + + public boolean T() { + return this.I != null; + } + + public String U() { + return this.J; + } + + public void a(KeyPair keypair) { + this.H = keypair; + } + + public void a(EnumDifficulty enumdifficulty) { + // CraftBukkit start + for (WorldServer worldserver : this.worlds) { + // CraftBukkit end + + if (worldserver != null) { + if (worldserver.getWorldData().isHardcore()) { + worldserver.getWorldData().setDifficulty(EnumDifficulty.HARD); + worldserver.setSpawnFlags(true, true); + } else { + worldserver.getWorldData().setDifficulty(enumdifficulty); + worldserver.setSpawnFlags(this.getSpawnMonsters(), this.spawnAnimals); + } + } + } + } + + protected boolean getSpawnMonsters() { + return true; + } + + public boolean X() { + return this.demoMode; + } + + public void b(boolean flag) { + this.demoMode = flag; + } + + public void c(boolean flag) { + } + + public Convertable getConvertable() { + return this.convertable; + } + + public void aa() { + this.N = true; + this.getConvertable().d(); + + // CraftBukkit start + for (WorldServer worldserver : this.worlds) { + // CraftBukkit end + + if (worldserver != null) { + worldserver.saveLevel(); + } + } + + this.getConvertable().e(this.worlds.get(0).getDataManager().g()); // CraftBukkit + this.safeShutdown(); + } + + public String getResourcePack() { + return this.O; + } + + public String getResourcePackHash() { + return this.P; + } + + public void setResourcePack(String s, String s1) { + this.O = s; + this.P = s1; + } + + public void a(MojangStatisticsGenerator mojangstatisticsgenerator) { + } + + public void b(MojangStatisticsGenerator mojangstatisticsgenerator) { + } + + public boolean getSnooperEnabled() { + return false; + } + + public abstract boolean ae(); + + public boolean getOnlineMode() { + return server.getOnlineMode(); // CraftBukkit + } + + public void setOnlineMode(boolean flag) { + + } + + public boolean getSpawnAnimals() { + return this.spawnAnimals; + } + + public void setSpawnAnimals(boolean flag) { + this.spawnAnimals = flag; + } + + public boolean getSpawnNPCs() { + return this.spawnNPCs; + } + + public void setSpawnNPCs(boolean flag) { + this.spawnNPCs = flag; + } + + public abstract boolean ai(); + + public boolean getPVP() { + return this.pvpMode; + } + + public void setPVP(boolean flag) { + this.pvpMode = flag; + } + + public boolean getAllowFlight() { + return this.allowFlight; + } + + public void setAllowFlight(boolean flag) { + this.allowFlight = flag; + } + + public abstract boolean getEnableCommandBlock(); + + public String getMotd() { + return this.motd; + } + + public void setMotd(String s) { + this.motd = s; + } + + public int getMaxBuildHeight() { + return 16; + } + + public void c(int i) { + } + + public boolean isStopped() { + return this.isStopped; + } + + public PlayerList getPlayerList() { + return this.v; + } + + public void a(PlayerList playerlist) { + this.v = playerlist; + } + + // Spigot Start + public ServerConnection getServerConnection() { + return this.q; + } + + // Spigot End + public ServerConnection aq() { + return q; // Spigot + } + + public boolean as() { + return false; + } + + public abstract String a(WorldSettings.EnumGamemode worldsettings_enumgamemode, boolean flag); + + public int at() { + return this.ticks; + } + + public BlockPosition getChunkCoordinates() { + return BlockPosition.ZERO; + } + + public Vec3D d() { + return new Vec3D(0.0D, 0.0D, 0.0D); + } + + public World getWorld() { + return this.worlds.get(0); // CraftBukkit + } + + public void setWorld(String s) { + this.J = s; + } + + public Entity f() { + return null; + } + + public int getSpawnProtection() { + return 16; + } + + public boolean a(World world, BlockPosition blockposition, EntityHuman entityhuman) { + return false; + } + + public boolean getForceGamemode() { + return this.U; + } + + public void setForceGamemode(boolean flag) { + this.U = flag; + } + + public Proxy ay() { + return this.e; + } + + public int getIdleTimeout() { + return this.G; + } + + public void setIdleTimeout(int i) { + this.G = i; + } + + public IChatBaseComponent getScoreboardDisplayName() { + return new ChatComponentText(this.getName()); + } + + public boolean aB() { + return true; + } + + public MinecraftSessionService aD() { + return this.W; + } + + public GameProfileRepository getGameProfileRepository() { + return this.Y; + } + + public UserCache getUserCache() { + return this.Z; + } + + public ServerPing aG() { + return this.r; + } + + public Entity a(UUID uuid) { + // CraftBukkit start + for (WorldServer worldserver : worlds) { + // CraftBukkit end + + if (worldserver != null) { + Entity entity = worldserver.getEntity(uuid); + + if (entity != null) { + return entity; + } + } + } + + return null; + } + + public boolean getSendCommandFeedback() { + return getServer().worlds.get(0).getGameRules().getBoolean("sendCommandFeedback"); + } + + public void a(CommandObjectiveExecutor.EnumCommandResult commandobjectiveexecutor_enumcommandresult, int i) { + } + + public int aI() { + return 29999984; + } + + public ListenableFuture a(Callable callable) { + Validate.notNull(callable); + if (!isMainThread()) { + ListenableFutureTask listenablefuturetask = ListenableFutureTask.create(callable); + tasks.add(() -> SystemUtils.a(listenablefuturetask, LOGGER)); + return listenablefuturetask; + } else { + try { + return Futures.immediateFuture(callable.call()); + } catch (Exception exception) { + return Futures.immediateFailedCheckedFuture(exception); + } + } + } + + public void postToMainThreadRunnable(Runnable runnable) { + Validate.notNull(runnable); + if (!isMainThread()) { + this.postToTasks(runnable); + } else { + runnable.run(); + } + } + + public ListenableFuture postToMainThread(Runnable runnable) { + Validate.notNull(runnable); + return a(Executors.callable(runnable)); + } + + public void postToLoginTasks(Runnable runnable) { + Validate.notNull(runnable); + if (!isMainThread()) { + this.postToTasks(runnable); + } else { + runnable.run(); + } + } + + public void postToTasks(Runnable runnable) { + tasks.add(runnable); + } + + public boolean isMainThread() { + return Thread.currentThread() == this.serverThread; + } + + public int aK() { + return 256; + } + + public long aL() { + return this.ab; + } + + public Thread aM() { + return this.serverThread; + } + + public static class RollingAverage { + private final int size; + private long time; + private java.math.BigDecimal total; + private int index = 0; + private final java.math.BigDecimal[] samples; + private final long[] times; + + RollingAverage(int size) { + this.size = size; + this.time = size * SEC_IN_NANO; + this.total = dec(TPS).multiply(dec(SEC_IN_NANO)).multiply(dec(size)); + this.samples = new java.math.BigDecimal[size]; + this.times = new long[size]; + for (int i = 0; i < size; i++) { + this.samples[i] = dec(TPS); + this.times[i] = SEC_IN_NANO; + } + } + + private static java.math.BigDecimal dec(long t) { + return new java.math.BigDecimal(t); + } + + public void add(java.math.BigDecimal x, long t) { + time -= times[index]; + total = total.subtract(samples[index].multiply(dec(times[index]))); + samples[index] = x; + times[index] = t; + time += t; + total = total.add(x.multiply(dec(t))); + if (++index == size) { + index = 0; + } + } + + public double getAverage() { + return total.divide(dec(time), 30, java.math.RoundingMode.HALF_UP).doubleValue(); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/MobEffect.java b/azurite-server/src/main/java/net/minecraft/server/MobEffect.java new file mode 100644 index 0000000..778b8a3 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/MobEffect.java @@ -0,0 +1,182 @@ +package net.minecraft.server; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +public class MobEffect { + + private static final Logger a = LogManager.getLogger(); + private int effectId; + private int duration; + private int amplification; + private boolean splash; + private boolean ambient; + public boolean particles; // Beanes - make public + + public MobEffect(int i, int j) { + this(i, j, 0); + } + + public MobEffect(int i, int j, int k) { + this(i, j, k, false, true); + } + + public MobEffect(int i, int j, int k, boolean ambient, boolean particles) { + this.effectId = i; + this.duration = j; + this.amplification = k; + this.ambient = ambient; + this.particles = particles; + } + + public MobEffect(MobEffect mobeffect) { + this.effectId = mobeffect.effectId; + this.duration = mobeffect.duration; + this.amplification = mobeffect.amplification; + this.ambient = mobeffect.ambient; + this.particles = mobeffect.particles; + } + + public void a(MobEffect mobeffect) { + if (this.effectId != mobeffect.effectId) { + MobEffect.a.warn("This method should only be called for matching effects!"); + } + + if (mobeffect.amplification > this.amplification) { // if new effect is stronger + this.amplification = mobeffect.amplification; // set new effect to be the stronger one + this.duration = mobeffect.duration; // set the duration to be the new effect's duration + } else if (mobeffect.amplification == this.amplification && this.duration < mobeffect.duration) { // if the effects are the same strength but the new effect is longer + this.duration = mobeffect.duration; // set the duration to be the new effect's duration + } else if (!mobeffect.ambient && this.ambient) { + this.ambient = mobeffect.ambient; + } + + this.particles = mobeffect.particles; + } + + public int getEffectId() { + return this.effectId; + } + + public int getDuration() { + return this.duration; + } + + public int getAmplifier() { + return this.amplification; + } + + public void setSplash(boolean flag) { + this.splash = flag; + } + + public boolean isAmbient() { + return this.ambient; + } + + public boolean setShowParticles() { + return this.particles; + } + + public boolean isShowParticles() { + return this.particles; + } + + public boolean tick(EntityLiving entityliving) { + if (this.duration > 0) { + int time = (int) ((System.currentTimeMillis() / 50) & 0x7FFFFFF); // get the current time in ticks + if (MobEffectList.byId[this.effectId].a(time, this.amplification)) { // regen tick + this.b(entityliving); + } + + this.i(); + } + + return this.duration > 0; + } + + private int i() { + return --this.duration; + } + + public void b(EntityLiving entityliving) { + if (this.duration > 0) { + MobEffectList.byId[this.effectId].tick(entityliving, this.amplification); + } + + } + + public String g() { + return MobEffectList.byId[this.effectId].a(); + } + + public int hashCode() { + return this.effectId; + } + + public String toString() { + String s = ""; + + if (this.getAmplifier() > 0) { + s = this.g() + " x " + (this.getAmplifier() + 1) + ", Duration: " + this.getDuration(); + } else { + s = this.g() + ", Duration: " + this.getDuration(); + } + + if (this.splash) { + s = s + ", Splash: true"; + } + + if (!this.particles) { + s = s + ", Particles: false"; + } + + return MobEffectList.byId[this.effectId].j() ? "(" + s + ")" : s; + } + + public boolean equals(Object object) { + if (!(object instanceof MobEffect)) { + return false; + } else { + MobEffect mobeffect = (MobEffect) object; + + return this.effectId == mobeffect.effectId && this.amplification == mobeffect.amplification && this.duration == mobeffect.duration && this.splash == mobeffect.splash && this.ambient == mobeffect.ambient; + } + } + + public NBTTagCompound a(NBTTagCompound nbttagcompound) { + nbttagcompound.setByte("Id", (byte) this.getEffectId()); + nbttagcompound.setShort("Amplifier", (short) this.getAmplifier()); // cSpigot - Store as a short + nbttagcompound.setInt("Duration", this.getDuration()); + nbttagcompound.setBoolean("Ambient", this.isAmbient()); + nbttagcompound.setBoolean("ShowParticles", this.isShowParticles()); + return nbttagcompound; + } + + public static MobEffect b(NBTTagCompound nbttagcompound) { + byte b0 = nbttagcompound.getByte("Id"); + + if (b0 >= 0 && b0 < MobEffectList.byId.length && MobEffectList.byId[b0] != null) { + // Rivals start - Fix overflow + int amplifier; + if (nbttagcompound.hasKeyOfType("Amplifier", 1)) { + amplifier = nbttagcompound.getByte("Amplifier"); + } else { + amplifier = nbttagcompound.getShort("Amplifier"); + } + // Rivals end + + int i = nbttagcompound.getInt("Duration"); + boolean flag = nbttagcompound.getBoolean("Ambient"); + boolean flag1 = true; + + if (nbttagcompound.hasKeyOfType("ShowParticles", 1)) { + flag1 = nbttagcompound.getBoolean("ShowParticles"); + } + + return new MobEffect(b0, i, amplifier, flag, flag1); + } else { + return null; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/MobEffectAbsorption.java b/azurite-server/src/main/java/net/minecraft/server/MobEffectAbsorption.java new file mode 100644 index 0000000..b85bc4d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/MobEffectAbsorption.java @@ -0,0 +1,18 @@ +package net.minecraft.server; + +public class MobEffectAbsorption extends MobEffectList { + + protected MobEffectAbsorption(int i, MinecraftKey minecraftkey, boolean flag, int j) { + super(i, minecraftkey, flag, j); + } + + public void a(EntityLiving entityliving, AttributeMapBase attributemapbase, int i) { + entityliving.setAbsorptionHearts(entityliving.getAbsorptionHearts() - (float) (4 * (i + 1))); + super.a(entityliving, attributemapbase, i); + } + + public void b(EntityLiving entityliving, AttributeMapBase attributemapbase, int i) { + entityliving.setAbsorptionHearts(entityliving.getAbsorptionHearts() + (float) (4 * (i + 1))); + super.b(entityliving, attributemapbase, i); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/MobEffectAttackDamage.java b/azurite-server/src/main/java/net/minecraft/server/MobEffectAttackDamage.java new file mode 100644 index 0000000..6f13509 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/MobEffectAttackDamage.java @@ -0,0 +1,13 @@ +package net.minecraft.server; + +public class MobEffectAttackDamage extends MobEffectList { + + protected MobEffectAttackDamage(int i, MinecraftKey minecraftkey, boolean flag, int j) { + super(i, minecraftkey, flag, j); + } + + public double a(int i, AttributeModifier attributemodifier) { + // PaperSpigot - Configurable modifiers for strength and weakness effects + return this.id == MobEffectList.WEAKNESS.id ? (org.github.paperspigot.PaperSpigotConfig.weaknessEffectModifier * (float) (i + 1)) : org.github.paperspigot.PaperSpigotConfig.strengthEffectModifier * (double) (i + 1); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/MobEffectHealthBoost.java b/azurite-server/src/main/java/net/minecraft/server/MobEffectHealthBoost.java new file mode 100644 index 0000000..8e74380 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/MobEffectHealthBoost.java @@ -0,0 +1,16 @@ +package net.minecraft.server; + +public class MobEffectHealthBoost extends MobEffectList { + + public MobEffectHealthBoost(int i, MinecraftKey minecraftkey, boolean flag, int j) { + super(i, minecraftkey, flag, j); + } + + public void a(EntityLiving entityliving, AttributeMapBase attributemapbase, int i) { + super.a(entityliving, attributemapbase, i); + if (entityliving.getHealth() > entityliving.getMaxHealth()) { + entityliving.setHealth(entityliving.getMaxHealth()); + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/MobEffectList.java b/azurite-server/src/main/java/net/minecraft/server/MobEffectList.java new file mode 100644 index 0000000..ead47af --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/MobEffectList.java @@ -0,0 +1,227 @@ +package net.minecraft.server; + +import com.eatthepath.uuid.FastUUID; +import com.google.common.collect.Maps; +import dev.azurite.spigot.configs.AzuriteConfig; +import org.bukkit.craftbukkit.event.CraftEventFactory; +import org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason; + +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +// CraftBukkit end + +public class MobEffectList { + + public static final MobEffectList[] byId = new MobEffectList[32]; + private static final Map I = Maps.newHashMap(); + public static final MobEffectList b = null; + public static final MobEffectList FASTER_MOVEMENT = (new MobEffectList(1, new MinecraftKey("speed"), false, 8171462)).c("potion.moveSpeed").b(0, 0).a(GenericAttributes.MOVEMENT_SPEED, "91AEAA56-376B-4498-935B-2F7F68070635", 0.20000000298023224D, 2); + public static final MobEffectList SLOWER_MOVEMENT = (new MobEffectList(2, new MinecraftKey("slowness"), true, 5926017)).c("potion.moveSlowdown").b(1, 0).a(GenericAttributes.MOVEMENT_SPEED, "7107DE5E-7CE8-4030-940E-514C1F160890", -0.15000000596046448D, 2); + public static final MobEffectList FASTER_DIG = (new MobEffectList(3, new MinecraftKey("haste"), false, 14270531)).c("potion.digSpeed").b(2, 0).a(1.5D); + public static final MobEffectList SLOWER_DIG = (new MobEffectList(4, new MinecraftKey("mining_fatigue"), true, 4866583)).c("potion.digSlowDown").b(3, 0); + public static final MobEffectList INCREASE_DAMAGE = (new MobEffectAttackDamage(5, new MinecraftKey("strength"), false, 9643043)).c("potion.damageBoost").b(4, 0).a(GenericAttributes.ATTACK_DAMAGE, "648D7064-6A60-4F59-8ABE-C2C23A6DD7A9", 2.5D, 2); + public static final MobEffectList HEAL = (new InstantMobEffect(6, new MinecraftKey("instant_health"), false, 16262179)).c("potion.heal"); + public static final MobEffectList HARM = (new InstantMobEffect(7, new MinecraftKey("instant_damage"), true, 4393481)).c("potion.harm"); + public static final MobEffectList JUMP = (new MobEffectList(8, new MinecraftKey("jump_boost"), false, 2293580)).c("potion.jump").b(2, 1); + public static final MobEffectList CONFUSION = (new MobEffectList(9, new MinecraftKey("nausea"), true, 5578058)).c("potion.confusion").b(3, 1).a(0.25D); + public static final MobEffectList REGENERATION = (new MobEffectList(10, new MinecraftKey("regeneration"), false, 13458603)).c("potion.regeneration").b(7, 0).a(0.25D); + public static final MobEffectList RESISTANCE = (new MobEffectList(11, new MinecraftKey("resistance"), false, 10044730)).c("potion.resistance").b(6, 1); + public static final MobEffectList FIRE_RESISTANCE = (new MobEffectList(12, new MinecraftKey("fire_resistance"), false, 14981690)).c("potion.fireResistance").b(7, 1); + public static final MobEffectList WATER_BREATHING = (new MobEffectList(13, new MinecraftKey("water_breathing"), false, 3035801)).c("potion.waterBreathing").b(0, 2); + public static final MobEffectList INVISIBILITY = (new MobEffectList(14, new MinecraftKey("invisibility"), false, 8356754)).c("potion.invisibility").b(0, 1); + public static final MobEffectList BLINDNESS = (new MobEffectList(15, new MinecraftKey("blindness"), true, 2039587)).c("potion.blindness").b(5, 1).a(0.25D); + public static final MobEffectList NIGHT_VISION = (new MobEffectList(16, new MinecraftKey("night_vision"), false, 2039713)).c("potion.nightVision").b(4, 1); + public static final MobEffectList HUNGER = (new MobEffectList(17, new MinecraftKey("hunger"), true, 5797459)).c("potion.hunger").b(1, 1); + public static final MobEffectList WEAKNESS = (new MobEffectAttackDamage(18, new MinecraftKey("weakness"), true, 4738376)).c("potion.weakness").b(5, 0).a(GenericAttributes.ATTACK_DAMAGE, "22653B89-116E-49DC-9B6B-9971489B5BE5", 2.0D, 0); + public static final MobEffectList POISON = (new MobEffectList(19, new MinecraftKey("poison"), true, 5149489)).c("potion.poison").b(6, 0).a(0.25D); + public static final MobEffectList WITHER = (new MobEffectList(20, new MinecraftKey("wither"), true, 3484199)).c("potion.wither").b(1, 2).a(0.25D); + public static final MobEffectList HEALTH_BOOST = (new MobEffectHealthBoost(21, new MinecraftKey("health_boost"), false, 16284963)).c("potion.healthBoost").b(2, 2).a(GenericAttributes.maxHealth, "5D6F0BA2-1186-46AC-B896-C61C5CEE99CC", 4.0D, 0); + public static final MobEffectList ABSORBTION = (new MobEffectAbsorption(22, new MinecraftKey("absorption"), false, 2445989)).c("potion.absorption").b(2, 2); + public static final MobEffectList SATURATION = (new InstantMobEffect(23, new MinecraftKey("saturation"), false, 16262179)).c("potion.saturation"); + public static final MobEffectList z = null; + public static final MobEffectList A = null; + public static final MobEffectList B = null; + public static final MobEffectList C = null; + public static final MobEffectList D = null; + public static final MobEffectList E = null; + public static final MobEffectList F = null; + public static final MobEffectList G = null; + public final int id; + private final Map J = Maps.newHashMap(); + private final int L; + private String M = ""; + private double O; + private boolean P; + + protected MobEffectList(int i, MinecraftKey minecraftkey, boolean flag, int j) { + this.id = i; + MobEffectList.byId[i] = this; + MobEffectList.I.put(minecraftkey, this); + if (flag) { + this.O = 0.5D; + } else { + this.O = 1.0D; + } + + this.L = j; + org.bukkit.potion.PotionEffectType.registerPotionEffectType(new org.bukkit.craftbukkit.potion.CraftPotionEffectType(this)); // CraftBukkit + } + + public static MobEffectList b(String s) { + return MobEffectList.I.get(new MinecraftKey(s)); + } + + public static Set c() { + return MobEffectList.I.keySet(); + } + + protected MobEffectList b(int i, int j) { + return this; + } + + public int getId() { + return this.id; + } + + public void tick(EntityLiving entityliving, int i) { + final boolean heal = this.id == MobEffectList.HEAL.id, harm = id == MobEffectList.HARM.id, undead = entityliving.bm(); + if (this.id == MobEffectList.REGENERATION.id) { + if (entityliving.getHealth() < entityliving.getMaxHealth()) { + entityliving.heal(1.0F, RegainReason.MAGIC_REGEN); // CraftBukkit + } + } else if (this.id == MobEffectList.POISON.id) { + if (entityliving.getHealth() > 1.0F) { + entityliving.damageEntity(CraftEventFactory.POISON, 1.0F); // CraftBukkit - DamageSource.MAGIC -> CraftEventFactory.POISON + } + } else if (this.id == MobEffectList.WITHER.id) { + entityliving.damageEntity(DamageSource.WITHER, 1.0F); + } else if (this.id == MobEffectList.HUNGER.id && entityliving instanceof EntityPlayer) { + ((EntityHuman) entityliving).applyExhaustion(0.025F * (float) (i + 1)); + } else if (this.id == MobEffectList.SATURATION.id && entityliving instanceof EntityPlayer) { + + EntityPlayer entityhuman = (EntityPlayer) entityliving; + int oldFoodLevel = entityhuman.getFoodData().foodLevel; + + org.bukkit.event.entity.FoodLevelChangeEvent event = CraftEventFactory.callFoodLevelChangeEvent(entityhuman, i + 1 + oldFoodLevel); + + if (!event.isCancelled()) { + entityhuman.getFoodData().eat(event.getFoodLevel() - oldFoodLevel, 1.0F); + } + + // Beanes - reduce packets + entityhuman.updateHealthAndFood(); + // CraftBukkit end + + } else if (harm && !undead || heal && undead) { + entityliving.damageEntity(DamageSource.MAGIC, (float) (6 << i)); + } else { + entityliving.heal((float) Math.max(4 << i, 0), RegainReason.MAGIC); // CraftBukkit + } + } + + public void applyInstantEffect(Entity entity, Entity entity1, EntityLiving entityliving, int i, double d0) { + int j; + final boolean heal = this.id == MobEffectList.HEAL.id, undead = entityliving.bm(); + if ((!heal || undead) && (this.id != MobEffectList.HARM.id || !undead)) { + if (this.id == MobEffectList.HARM.id || heal) { + j = (int) (d0 * (6 << i) + 0.5D); + if (entity == null) { + entityliving.damageEntity(DamageSource.MAGIC, (float) j); + } else { + entityliving.damageEntity(DamageSource.b(entity, entity1), (float) j); + } + } + } else { + j = (int) (d0 * (4 << i) + 0.5D); + entityliving.heal(j, RegainReason.MAGIC); // CraftBukkit + } + } + + public boolean isInstant() { + return false; + } + + public boolean a(int i, int j) { + int k; + + if (this.id == MobEffectList.REGENERATION.id) { + k = getTickRegenValue(j, 50 >> j); + return k == 0 || i % k == 0; + } else if (this.id == MobEffectList.POISON.id) { + k = 25 >> j; + return k == 0 || i % k == 0; + } else if (this.id == MobEffectList.WITHER.id) { + k = 40 >> j; + return k == 0 || i % k == 0; + } else { + return this.id == MobEffectList.HUNGER.id; + } + } + + private int getTickRegenValue(int amplifier, int originalTickRate) { + return (AzuriteConfig.patchHCFRegenBug.getValue() ? (amplifier == 0 ? 45 : amplifier == 1 ? 39 : amplifier == 2 ? 18 : originalTickRate) : originalTickRate); + } + + public MobEffectList c(String s) { + this.M = s; + return this; + } + + public String a() { + return this.M; + } + + protected MobEffectList a(double d0) { + this.O = d0; + return this; + } + + public double getDurationModifier() { + return this.O; + } + + public boolean j() { + return this.P; + } + + public int k() { + return this.L; + } + + public MobEffectList a(IAttribute iattribute, String s, double d0, int i) { + this.J.put(iattribute, new AttributeModifier(FastUUID.parseUUID(s), this.a(), d0, i)); + return this; + } + + public void a(EntityLiving entityliving, AttributeMapBase attributemapbase, int i) { + + for (Entry iAttributeAttributeModifierEntry : this.J.entrySet()) { + AttributeInstance attributeinstance = attributemapbase.a(iAttributeAttributeModifierEntry.getKey()); + + if (attributeinstance != null) { + attributeinstance.c(iAttributeAttributeModifierEntry.getValue()); + } + } + + } + + public void b(EntityLiving entityliving, AttributeMapBase attributemapbase, int i) { + + for (Entry iAttributeAttributeModifierEntry : this.J.entrySet()) { + AttributeInstance attributeinstance = attributemapbase.a(iAttributeAttributeModifierEntry.getKey()); + + if (attributeinstance != null) { + AttributeModifier attributemodifier = iAttributeAttributeModifierEntry.getValue(); + + attributeinstance.c(attributemodifier); + attributeinstance.b(new AttributeModifier(attributemodifier.a(), this.a() + " " + i, this.a(i, attributemodifier), attributemodifier.c())); + } + } + + } + + public double a(int i, AttributeModifier attributemodifier) { + return attributemodifier.d() * (double) (i + 1); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/MobSpawnerAbstract.java b/azurite-server/src/main/java/net/minecraft/server/MobSpawnerAbstract.java new file mode 100644 index 0000000..0c09050 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/MobSpawnerAbstract.java @@ -0,0 +1,323 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; +import dev.azurite.spigot.configs.AzuriteConfig; +import org.apache.commons.lang3.StringUtils; +import org.bukkit.Chunk; +import org.bukkit.Location; +import org.bukkit.craftbukkit.event.CraftEventFactory; +import org.bukkit.entity.LivingEntity; +import org.bukkit.event.entity.CreatureSpawnEvent; +import org.bukkit.event.entity.SpawnerSpawnEvent; + +import java.util.List; + +public abstract class MobSpawnerAbstract { + + public int spawnDelay = 20; + private String mobName = "Pig"; + private final List mobs = Lists.newArrayList(); + private MobSpawnerAbstract.a spawnData; + private int tickDelay = 0; // PaperSpigot + + public MobSpawnerAbstract() { + } + + public String getMobName() { + if (i() == null) { + if (mobName == null) + mobName = "Pig"; + else if (mobName.equals("Minecart")) + mobName = "MinecartRideable"; + return mobName; + } + return i().d; + } + + public void setMobName(String s) { + this.mobName = s; + } + + private boolean g() { + BlockPosition blockposition = b(); + return a().isPlayerNearbyWhoAffectsSpawning(blockposition.getX() + 0.5D, blockposition.getY() + 0.5D, blockposition.getZ() + 0.5D, AzuriteConfig.playerSpawnRange.getValue()); + } + + public void c() { + // PaperSpigot start - Configurable mob spawner tick rate + if (spawnDelay > 0 && --tickDelay > 0) + return; + World world = a(); + + tickDelay = world.paperSpigotConfig.mobSpawnerTickRate; + // PaperSpigot end + + BlockPosition blockposition = b(); + + if (AzuriteConfig.playerSpawnRange.getValue() <= 0 || g()) { + if (spawnDelay < -tickDelay) { // PaperSpigot + h(); + } + + if (spawnDelay > 0) { + spawnDelay -= tickDelay; // PaperSpigot + return; + } + + boolean spawned = false; + + for (int i = 0; i < AzuriteConfig.spawnCount.getValue(); ++i) { + int chunkMobLimit = AzuriteConfig.chunkMobLimit.getValue(); + + if (chunkMobLimit > 0) { + Chunk chunk = new Location(world.getWorld(), blockposition.getX(), blockposition.getY(), blockposition.getZ()).getChunk(); + int amount = 0; + for (org.bukkit.entity.Entity e : chunk.getEntities()) { + if (e instanceof LivingEntity && !e.isDead()) { + if (amount++ > chunkMobLimit) + return; + } + } + } + + Entity entity = EntityTypes.createEntityByName(getMobName(), world); + + if (entity == null) { + return; + } + + double range = AzuriteConfig.spawnRange.getValue(); + int nearbyEntitiesLimit = AzuriteConfig.maximumNearbyEntities.getValue(); + + if (nearbyEntitiesLimit > 0) { + int entityCount = world.a(entity.getClass(), new AxisAlignedBB(blockposition.getX(), blockposition.getY(), blockposition.getZ(), blockposition.getX() + 1, blockposition.getY() + 1, blockposition.getZ() + 1).grow(range, range, range)).size(); + if (entityCount >= nearbyEntitiesLimit) { + h(); + return; + } + } + + double locX = blockposition.getX() + (world.random.nextDouble() - world.random.nextDouble()) * range + 0.5D; + double locY = (blockposition.getY() + world.random.nextInt(3) - 1); + double locZ = blockposition.getZ() + (world.random.nextDouble() - world.random.nextDouble()) * range + 0.5D; + + EntityInsentient entityinsentient = entity instanceof EntityInsentient ? (EntityInsentient) entity : null; + + entity.fromMobSpawner = true; + entity.setPosition(locX, locY, locZ); + + if (entityinsentient == null || entityinsentient.canSpawn() && (!AzuriteConfig.lightLevelCheck.getValue() || entityinsentient.bR())) { + a(entity, false); + if (AzuriteConfig.spawnerParticles.getValue()) { + world.triggerEffect(2004, blockposition, 0); + if (entityinsentient != null) + entityinsentient.y(); + } + spawned = true; + } + } + + if (spawned) { + h(); + } + } + } + + private Entity a(Entity entity, boolean flag) { + MobSpawnerAbstract.a spawnData = i(); + if (spawnData != null) { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + + entity.d(nbttagcompound); + + for (String s : spawnData.c.c()) { + nbttagcompound.set(s, spawnData.c.get(s).clone()); + } + + entity.f(nbttagcompound); + + if (entity.world != null) { + SpawnerSpawnEvent event = CraftEventFactory.callSpawnerSpawnEvent(entity, b().getX(), b().getY(), b().getZ()); + if (!event.isCancelled()) { + if (entity instanceof EntityInsentient && AzuriteConfig.mobAISpawners.getValue()) { + ((EntityInsentient) entity).intelligence = true; + } + + entity.fromMobSpawner = true; + entity.world.addEntity(entity, CreatureSpawnEvent.SpawnReason.SPAWNER); + } + } + + NBTTagCompound nbttagcompound1; + + for (Entity entity1 = entity; nbttagcompound.hasKeyOfType("Riding", 10); nbttagcompound = nbttagcompound1) { + nbttagcompound1 = nbttagcompound.getCompound("Riding"); + Entity entity2 = EntityTypes.createEntityByName(nbttagcompound1.getString("id"), entity.world); + + if (entity2 != null) { + if (entity2 instanceof EntityInsentient && AzuriteConfig.mobAISpawners.getValue()) { + ((EntityInsentient) entity2).intelligence = true; + } + + NBTTagCompound nbttagcompound2 = new NBTTagCompound(); + + entity2.d(nbttagcompound2); + + for (String s1 : nbttagcompound1.c()) { + NBTBase nbtbase1 = nbttagcompound1.get(s1); + + nbttagcompound2.set(s1, nbtbase1.clone()); + } + + entity2.f(nbttagcompound2); + entity2.setPositionRotation(entity1.locX, entity1.locY, entity1.locZ, entity1.yaw, entity1.pitch); + // CraftBukkit start - call SpawnerSpawnEvent, skip if cancelled + SpawnerSpawnEvent event = CraftEventFactory.callSpawnerSpawnEvent(entity2, b().getX(), b().getY(), b().getZ()); + if (event.isCancelled()) { + continue; + } + if (entity.world != null) { + entity.world.addEntity(entity2, CreatureSpawnEvent.SpawnReason.SPAWNER); // CraftBukkit + } + + entity1.mount(entity2); + } + + entity1 = entity2; + } + } else if (entity instanceof EntityLiving && entity.world != null) { + if (entity instanceof EntityInsentient) { + if (AzuriteConfig.mobAISpawners.getValue()) { + ((EntityInsentient) entity).intelligence = true; + } + ((EntityInsentient) entity).prepare(entity.world.E(MathHelper.floor(entity.locX), MathHelper.floor(entity.locY), MathHelper.floor(entity.locZ)), null); + } + SpawnerSpawnEvent event = CraftEventFactory.callSpawnerSpawnEvent(entity, b().getX(), b().getY(), b().getZ()); + if (!event.isCancelled()) { + entity.fromMobSpawner = true; + entity.world.addEntity(entity, CreatureSpawnEvent.SpawnReason.SPAWNER); + } + } + + return entity; + } + + private void h() { + int maxSpawnDelay = AzuriteConfig.maximumSpawnDelay.getValue(), minSpawnDelay = AzuriteConfig.minimumSpawnDelay.getValue(); + if (maxSpawnDelay <= minSpawnDelay) { + spawnDelay = minSpawnDelay; + } else { + spawnDelay = minSpawnDelay + a().random.nextInt(maxSpawnDelay - minSpawnDelay); + } + if (!mobs.isEmpty()) + a(WeightedRandom.a(a().random, mobs)); + a(1); + } + + public void a(NBTTagCompound nbttagcompound) { + mobName = nbttagcompound.getString("EntityId"); + spawnDelay = nbttagcompound.getShort("Delay"); + mobs.clear(); + + if (nbttagcompound.hasKeyOfType("SpawnPotentials", 9)) { + NBTTagList nbttaglist = nbttagcompound.getList("SpawnPotentials", 10); + for (int i = 0; i < nbttaglist.size(); ++i) { + mobs.add(new MobSpawnerAbstract.a(nbttaglist.get(i))); + } + } + + if (nbttagcompound.hasKeyOfType("SpawnData", 10)) { + a(new MobSpawnerAbstract.a(nbttagcompound.getCompound("SpawnData"), this.mobName)); + } else { + a((MobSpawnerAbstract.a) null); + } + + } + + public void b(NBTTagCompound nbttagcompound) { + String s = getMobName(); + + if (!StringUtils.isEmpty(s)) { + nbttagcompound.setString("EntityId", s); + nbttagcompound.setShort("Delay", (short) spawnDelay); + nbttagcompound.setShort("MinSpawnDelay", AzuriteConfig.minimumSpawnDelay.getValue().shortValue()); + nbttagcompound.setShort("MaxSpawnDelay", AzuriteConfig.maximumSpawnDelay.getValue().shortValue()); + nbttagcompound.setShort("SpawnCount", AzuriteConfig.spawnCount.getValue().shortValue()); + nbttagcompound.setShort("MaxNearbyEntities", AzuriteConfig.maximumNearbyEntities.getValue().shortValue()); + nbttagcompound.setShort("RequiredPlayerRange", AzuriteConfig.playerSpawnRange.getValue().shortValue()); + nbttagcompound.setShort("SpawnRange", AzuriteConfig.spawnRange.getValue().shortValue()); + if (i() != null) { + nbttagcompound.set("SpawnData", i().c.clone()); + } + + if (i() != null || !mobs.isEmpty()) { + NBTTagList nbttaglist = new NBTTagList(); + + if (!mobs.isEmpty()) { + for (a mob : mobs) { + nbttaglist.add(mob.a()); + } + } else { + nbttaglist.add(i().a()); + } + + nbttagcompound.set("SpawnPotentials", nbttaglist); + } + + } + } + + public boolean b(int i) { + return false; + } + + private MobSpawnerAbstract.a i() { + return spawnData; + } + + public void a(MobSpawnerAbstract.a spawnData) { + this.spawnData = spawnData; + } + + public abstract void a(int i); + + public abstract World a(); + + public abstract BlockPosition b(); + + public class a extends WeightedRandom.WeightedRandomChoice { + private final NBTTagCompound c; + private final String d; + + public a(NBTTagCompound nbttagcompound) { + this(nbttagcompound.getCompound("Properties"), nbttagcompound.getString("Type"), nbttagcompound.getInt("Weight")); + } + + public a(NBTTagCompound nbttagcompound, String s) { + this(nbttagcompound, s, 1); + } + + private a(NBTTagCompound nbttagcompound, String s, int i) { + super(i); + if (s.equals("Minecart")) { + if (nbttagcompound != null) { + s = EntityMinecartAbstract.EnumMinecartType.a(nbttagcompound.getInt("Type")).b(); + } else { + s = "MinecartRideable"; + } + } + + this.c = nbttagcompound; + this.d = s; + } + + public NBTTagCompound a() { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + + nbttagcompound.set("Properties", this.c); + nbttagcompound.setString("Type", this.d); + nbttagcompound.setInt("Weight", this.a); + return nbttagcompound; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/MojangStatisticsGenerator.java b/azurite-server/src/main/java/net/minecraft/server/MojangStatisticsGenerator.java new file mode 100644 index 0000000..076306d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/MojangStatisticsGenerator.java @@ -0,0 +1,134 @@ +package net.minecraft.server; + +import com.google.common.collect.Maps; +import java.lang.management.ManagementFactory; +import java.lang.management.RuntimeMXBean; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Timer; +import java.util.TimerTask; +import java.util.UUID; + +public class MojangStatisticsGenerator { + + private final Map a = Maps.newHashMap(); + private final Map b = Maps.newHashMap(); + private final String c = UUID.randomUUID().toString(); + private final URL d; + private final IMojangStatistics e; + private final Timer f = new Timer("Snooper Timer", true); + private final Object g = new Object(); + private final long h; + private boolean i; + private int j; + + public MojangStatisticsGenerator(String s, IMojangStatistics imojangstatistics, long i) { + try { + this.d = new URL("http://snoop.minecraft.net/" + s + "?version=" + 2); + } catch (MalformedURLException malformedurlexception) { + throw new IllegalArgumentException(); + } + + this.e = imojangstatistics; + this.h = i; + } + + public void a() { + if (!this.i) { + this.i = true; + this.h(); + this.f.schedule(new TimerTask() { + public void run() { + if (MojangStatisticsGenerator.this.e.getSnooperEnabled()) { + HashMap hashmap; + + synchronized (MojangStatisticsGenerator.this.g) { + hashmap = Maps.newHashMap(MojangStatisticsGenerator.this.b); + if (MojangStatisticsGenerator.this.j == 0) { + hashmap.putAll(MojangStatisticsGenerator.this.a); + } + + hashmap.put("snooper_count", Integer.valueOf(MojangStatisticsGenerator.f(MojangStatisticsGenerator.this))); + hashmap.put("snooper_token", MojangStatisticsGenerator.this.c); + } + + HttpUtilities.a(MojangStatisticsGenerator.this.d, (Map) hashmap, true); + } + } + }, 0L, 900000L); + } + } + + private void h() { + this.i(); + this.a("snooper_token", this.c); + this.b("snooper_token", this.c); + this.b("os_name", System.getProperty("os.name")); + this.b("os_version", System.getProperty("os.version")); + this.b("os_architecture", System.getProperty("os.arch")); + this.b("java_version", System.getProperty("java.version")); + this.a("version", "1.8.8"); + this.e.b(this); + } + + private void i() { + RuntimeMXBean runtimemxbean = ManagementFactory.getRuntimeMXBean(); + List list = runtimemxbean.getInputArguments(); + int i = 0; + Iterator iterator = list.iterator(); + + while (iterator.hasNext()) { + String s = (String) iterator.next(); + + if (s.startsWith("-X")) { + this.a("jvm_arg[" + i++ + "]", s); + } + } + + this.a("jvm_args", Integer.valueOf(i)); + } + + public void b() { + this.b("memory_total", Long.valueOf(Runtime.getRuntime().totalMemory())); + this.b("memory_max", Long.valueOf(Runtime.getRuntime().maxMemory())); + this.b("memory_free", Long.valueOf(Runtime.getRuntime().freeMemory())); + this.b("cpu_cores", Integer.valueOf(Runtime.getRuntime().availableProcessors())); + this.e.a(this); + } + + public void a(String s, Object object) { + Object object1 = this.g; + + synchronized (this.g) { + this.b.put(s, object); + } + } + + public void b(String s, Object object) { + Object object1 = this.g; + + synchronized (this.g) { + this.a.put(s, object); + } + } + + public boolean d() { + return this.i; + } + + public void e() { + this.f.cancel(); + } + + public long g() { + return this.h; + } + + static int f(MojangStatisticsGenerator mojangstatisticsgenerator) { + return mojangstatisticsgenerator.j++; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/MojangsonParseException.java b/azurite-server/src/main/java/net/minecraft/server/MojangsonParseException.java new file mode 100644 index 0000000..15cd833 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/MojangsonParseException.java @@ -0,0 +1,8 @@ +package net.minecraft.server; + +public class MojangsonParseException extends Exception { + + public MojangsonParseException(String s) { + super(s); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/MojangsonParser.java b/azurite-server/src/main/java/net/minecraft/server/MojangsonParser.java new file mode 100644 index 0000000..3378d7f --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/MojangsonParser.java @@ -0,0 +1,433 @@ +package net.minecraft.server; + +import com.google.common.base.Splitter; +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; +import java.util.Iterator; +import java.util.List; +import java.util.Stack; +import java.util.regex.Pattern; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +public class MojangsonParser { + + private static final Logger a = LogManager.getLogger(); + private static final Pattern b = Pattern.compile("\\[[-+\\d|,\\s]+\\]"); + + public static NBTTagCompound parse(String s) throws MojangsonParseException { + s = s.trim(); + if (!s.startsWith("{")) { + throw new MojangsonParseException("Invalid tag encountered, expected \'{\' as first char."); + } else if (b(s) != 1) { + throw new MojangsonParseException("Encountered multiple top tags, only one expected"); + } else { + return (NBTTagCompound) a("tag", s).a(); + } + } + + static int b(String s) throws MojangsonParseException { + int i = 0; + boolean flag = false; + Stack stack = new Stack(); + + for (int j = 0; j < s.length(); ++j) { + char c0 = s.charAt(j); + + if (c0 == 34) { + if (b(s, j)) { + if (!flag) { + throw new MojangsonParseException("Illegal use of \\\": " + s); + } + } else { + flag = !flag; + } + } else if (!flag) { + if (c0 != 123 && c0 != 91) { + if (c0 == 125 && (stack.isEmpty() || ((Character) stack.pop()).charValue() != 123)) { + throw new MojangsonParseException("Unbalanced curly brackets {}: " + s); + } + + if (c0 == 93 && (stack.isEmpty() || ((Character) stack.pop()).charValue() != 91)) { + throw new MojangsonParseException("Unbalanced square brackets []: " + s); + } + } else { + if (stack.isEmpty()) { + ++i; + } + + stack.push(Character.valueOf(c0)); + } + } + } + + if (flag) { + throw new MojangsonParseException("Unbalanced quotation: " + s); + } else if (!stack.isEmpty()) { + throw new MojangsonParseException("Unbalanced brackets: " + s); + } else { + if (i == 0 && !s.isEmpty()) { + i = 1; + } + + return i; + } + } + + static MojangsonParser.MojangsonTypeParser a(String... astring) throws MojangsonParseException { + return a(astring[0], astring[1]); + } + + static MojangsonParser.MojangsonTypeParser a(String s, String s1) throws MojangsonParseException { + s1 = s1.trim(); + String s2; + boolean flag; + char c0; + + if (s1.startsWith("{")) { + s1 = s1.substring(1, s1.length() - 1); + + MojangsonParser.MojangsonCompoundParser mojangsonparser_mojangsoncompoundparser; + + for (mojangsonparser_mojangsoncompoundparser = new MojangsonParser.MojangsonCompoundParser(s); s1.length() > 0; s1 = s1.substring(s2.length() + 1)) { + s2 = b(s1, true); + if (s2.length() > 0) { + flag = false; + mojangsonparser_mojangsoncompoundparser.b.add(a(s2, flag)); + } + + if (s1.length() < s2.length() + 1) { + break; + } + + c0 = s1.charAt(s2.length()); + if (c0 != 44 && c0 != 123 && c0 != 125 && c0 != 91 && c0 != 93) { + throw new MojangsonParseException("Unexpected token \'" + c0 + "\' at: " + s1.substring(s2.length())); + } + } + + return mojangsonparser_mojangsoncompoundparser; + } else if (s1.startsWith("[") && !MojangsonParser.b.matcher(s1).matches()) { + s1 = s1.substring(1, s1.length() - 1); + + MojangsonParser.MojangsonListParser mojangsonparser_mojangsonlistparser; + + for (mojangsonparser_mojangsonlistparser = new MojangsonParser.MojangsonListParser(s); s1.length() > 0; s1 = s1.substring(s2.length() + 1)) { + s2 = b(s1, false); + if (s2.length() > 0) { + flag = true; + mojangsonparser_mojangsonlistparser.b.add(a(s2, flag)); + } + + if (s1.length() < s2.length() + 1) { + break; + } + + c0 = s1.charAt(s2.length()); + if (c0 != 44 && c0 != 123 && c0 != 125 && c0 != 91 && c0 != 93) { + throw new MojangsonParseException("Unexpected token \'" + c0 + "\' at: " + s1.substring(s2.length())); + } + } + + return mojangsonparser_mojangsonlistparser; + } else { + return new MojangsonParser.MojangsonPrimitiveParser(s, s1); + } + } + + private static MojangsonParser.MojangsonTypeParser a(String s, boolean flag) throws MojangsonParseException { + String s1 = c(s, flag); + String s2 = d(s, flag); + + return a(new String[] { s1, s2}); + } + + private static String b(String s, boolean flag) throws MojangsonParseException { + int i = a(s, ':'); + int j = a(s, ','); + + if (flag) { + if (i == -1) { + throw new MojangsonParseException("Unable to locate name/value separator for string: " + s); + } + + if (j != -1 && j < i) { + throw new MojangsonParseException("Name error at: " + s); + } + } else if (i == -1 || i > j) { + i = -1; + } + + return a(s, i); + } + + private static String a(String s, int i) throws MojangsonParseException { + Stack stack = new Stack(); + int j = i + 1; + boolean flag = false; + boolean flag1 = false; + boolean flag2 = false; + + for (int k = 0; j < s.length(); ++j) { + char c0 = s.charAt(j); + + if (c0 == 34) { + if (b(s, j)) { + if (!flag) { + throw new MojangsonParseException("Illegal use of \\\": " + s); + } + } else { + flag = !flag; + if (flag && !flag2) { + flag1 = true; + } + + if (!flag) { + k = j; + } + } + } else if (!flag) { + if (c0 != 123 && c0 != 91) { + if (c0 == 125 && (stack.isEmpty() || ((Character) stack.pop()).charValue() != 123)) { + throw new MojangsonParseException("Unbalanced curly brackets {}: " + s); + } + + if (c0 == 93 && (stack.isEmpty() || ((Character) stack.pop()).charValue() != 91)) { + throw new MojangsonParseException("Unbalanced square brackets []: " + s); + } + + if (c0 == 44 && stack.isEmpty()) { + return s.substring(0, j); + } + } else { + stack.push(Character.valueOf(c0)); + } + } + + if (!Character.isWhitespace(c0)) { + if (!flag && flag1 && k != j) { + return s.substring(0, k + 1); + } + + flag2 = true; + } + } + + return s.substring(0, j); + } + + private static String c(String s, boolean flag) throws MojangsonParseException { + if (flag) { + s = s.trim(); + if (s.startsWith("{") || s.startsWith("[")) { + return ""; + } + } + + int i = a(s, ':'); + + if (i == -1) { + if (flag) { + return ""; + } else { + throw new MojangsonParseException("Unable to locate name/value separator for string: " + s); + } + } else { + return s.substring(0, i).trim(); + } + } + + private static String d(String s, boolean flag) throws MojangsonParseException { + if (flag) { + s = s.trim(); + if (s.startsWith("{") || s.startsWith("[")) { + return s; + } + } + + int i = a(s, ':'); + + if (i == -1) { + if (flag) { + return s; + } else { + throw new MojangsonParseException("Unable to locate name/value separator for string: " + s); + } + } else { + return s.substring(i + 1).trim(); + } + } + + private static int a(String s, char c0) { + int i = 0; + + for (boolean flag = true; i < s.length(); ++i) { + char c1 = s.charAt(i); + + if (c1 == 34) { + if (!b(s, i)) { + flag = !flag; + } + } else if (flag) { + if (c1 == c0) { + return i; + } + + if (c1 == 123 || c1 == 91) { + return -1; + } + } + } + + return -1; + } + + private static boolean b(String s, int i) { + return i > 0 && s.charAt(i - 1) == 92 && !b(s, i - 1); + } + + static class MojangsonPrimitiveParser extends MojangsonParser.MojangsonTypeParser { + + private static final Pattern c = Pattern.compile("[-+]?[0-9]*\\.?[0-9]+[d|D]"); + private static final Pattern d = Pattern.compile("[-+]?[0-9]*\\.?[0-9]+[f|F]"); + private static final Pattern e = Pattern.compile("[-+]?[0-9]+[b|B]"); + private static final Pattern f = Pattern.compile("[-+]?[0-9]+[l|L]"); + private static final Pattern g = Pattern.compile("[-+]?[0-9]+[s|S]"); + private static final Pattern h = Pattern.compile("[-+]?[0-9]+"); + private static final Pattern i = Pattern.compile("[-+]?[0-9]*\\.?[0-9]+"); + private static final Splitter j = Splitter.on(',').omitEmptyStrings(); + protected String b; + + public MojangsonPrimitiveParser(String s, String s1) { + this.a = s; + this.b = s1; + } + + public NBTBase a() throws MojangsonParseException { + try { + if (MojangsonParser.MojangsonPrimitiveParser.c.matcher(this.b).matches()) { + return new NBTTagDouble(Double.parseDouble(this.b.substring(0, this.b.length() - 1))); + } + + if (MojangsonParser.MojangsonPrimitiveParser.d.matcher(this.b).matches()) { + return new NBTTagFloat(Float.parseFloat(this.b.substring(0, this.b.length() - 1))); + } + + if (MojangsonParser.MojangsonPrimitiveParser.e.matcher(this.b).matches()) { + return new NBTTagByte(Byte.parseByte(this.b.substring(0, this.b.length() - 1))); + } + + if (MojangsonParser.MojangsonPrimitiveParser.f.matcher(this.b).matches()) { + return new NBTTagLong(Long.parseLong(this.b.substring(0, this.b.length() - 1))); + } + + if (MojangsonParser.MojangsonPrimitiveParser.g.matcher(this.b).matches()) { + return new NBTTagShort(Short.parseShort(this.b.substring(0, this.b.length() - 1))); + } + + if (MojangsonParser.MojangsonPrimitiveParser.h.matcher(this.b).matches()) { + return new NBTTagInt(Integer.parseInt(this.b)); + } + + if (MojangsonParser.MojangsonPrimitiveParser.i.matcher(this.b).matches()) { + return new NBTTagDouble(Double.parseDouble(this.b)); + } + + if (this.b.equalsIgnoreCase("true") || this.b.equalsIgnoreCase("false")) { + return new NBTTagByte((byte) (Boolean.parseBoolean(this.b) ? 1 : 0)); + } + } catch (NumberFormatException numberformatexception) { + this.b = this.b.replaceAll("\\\\\"", "\""); + return new NBTTagString(this.b); + } + + if (this.b.startsWith("[") && this.b.endsWith("]")) { + String s = this.b.substring(1, this.b.length() - 1); + String[] astring = (String[]) Iterables.toArray(MojangsonParser.MojangsonPrimitiveParser.j.split(s), String.class); + + try { + int[] aint = new int[astring.length]; + + for (int i = 0; i < astring.length; ++i) { + aint[i] = Integer.parseInt(astring[i].trim()); + } + + return new NBTTagIntArray(aint); + } catch (NumberFormatException numberformatexception1) { + return new NBTTagString(this.b); + } + } else { + if (this.b.startsWith("\"") && this.b.endsWith("\"")) { + this.b = this.b.substring(1, this.b.length() - 1); + } + + this.b = this.b.replaceAll("\\\\\"", "\""); + StringBuilder stringbuilder = new StringBuilder(); + + for (int j = 0; j < this.b.length(); ++j) { + if (j < this.b.length() - 1 && this.b.charAt(j) == 92 && this.b.charAt(j + 1) == 92) { + stringbuilder.append('\\'); + ++j; + } else { + stringbuilder.append(this.b.charAt(j)); + } + } + + return new NBTTagString(stringbuilder.toString()); + } + } + } + + static class MojangsonListParser extends MojangsonParser.MojangsonTypeParser { + + protected List b = Lists.newArrayList(); + + public MojangsonListParser(String s) { + this.a = s; + } + + public NBTBase a() throws MojangsonParseException { + NBTTagList nbttaglist = new NBTTagList(); + Iterator iterator = this.b.iterator(); + + while (iterator.hasNext()) { + MojangsonParser.MojangsonTypeParser mojangsonparser_mojangsontypeparser = (MojangsonParser.MojangsonTypeParser) iterator.next(); + + nbttaglist.add(mojangsonparser_mojangsontypeparser.a()); + } + + return nbttaglist; + } + } + + static class MojangsonCompoundParser extends MojangsonParser.MojangsonTypeParser { + + protected List b = Lists.newArrayList(); + + public MojangsonCompoundParser(String s) { + this.a = s; + } + + public NBTBase a() throws MojangsonParseException { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + Iterator iterator = this.b.iterator(); + + while (iterator.hasNext()) { + MojangsonParser.MojangsonTypeParser mojangsonparser_mojangsontypeparser = (MojangsonParser.MojangsonTypeParser) iterator.next(); + + nbttagcompound.set(mojangsonparser_mojangsontypeparser.a, mojangsonparser_mojangsontypeparser.a()); + } + + return nbttagcompound; + } + } + + abstract static class MojangsonTypeParser { + + protected String a; + + MojangsonTypeParser() {} + + public abstract NBTBase a() throws MojangsonParseException; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/MovingObjectPosition.java b/azurite-server/src/main/java/net/minecraft/server/MovingObjectPosition.java new file mode 100644 index 0000000..a0438c5 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/MovingObjectPosition.java @@ -0,0 +1,50 @@ +package net.minecraft.server; + +public class MovingObjectPosition { + + private BlockPosition e; + public MovingObjectPosition.EnumMovingObjectType type; + public EnumDirection direction; + public Vec3D pos; + public Entity entity; + + public MovingObjectPosition(Vec3D vec3d, EnumDirection enumdirection, BlockPosition blockposition) { + this(MovingObjectPosition.EnumMovingObjectType.BLOCK, vec3d, enumdirection, blockposition); + } + + public MovingObjectPosition(Vec3D vec3d, EnumDirection enumdirection) { + this(MovingObjectPosition.EnumMovingObjectType.BLOCK, vec3d, enumdirection, BlockPosition.ZERO); + } + + public MovingObjectPosition(Entity entity) { + this(entity, new Vec3D(entity.locX, entity.locY, entity.locZ)); + } + + public MovingObjectPosition(MovingObjectPosition.EnumMovingObjectType movingobjectposition_enummovingobjecttype, Vec3D vec3d, EnumDirection enumdirection, BlockPosition blockposition) { + this.type = movingobjectposition_enummovingobjecttype; + this.e = blockposition; + this.direction = enumdirection; + this.pos = new Vec3D(vec3d.a, vec3d.b, vec3d.c); + } + + public MovingObjectPosition(Entity entity, Vec3D vec3d) { + this.type = MovingObjectPosition.EnumMovingObjectType.ENTITY; + this.entity = entity; + this.pos = vec3d; + } + + public BlockPosition a() { + return this.e; + } + + public String toString() { + return "HitResult{type=" + this.type + ", blockpos=" + this.e + ", f=" + this.direction + ", pos=" + this.pos + ", entity=" + this.entity + '}'; + } + + public static enum EnumMovingObjectType { + + MISS, BLOCK, ENTITY; + + private EnumMovingObjectType() {} + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/NBTBase.java b/azurite-server/src/main/java/net/minecraft/server/NBTBase.java new file mode 100644 index 0000000..8756b63 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/NBTBase.java @@ -0,0 +1,104 @@ +package net.minecraft.server; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; + +public abstract class NBTBase { + + public static final String[] a = new String[] { "END", "BYTE", "SHORT", "INT", "LONG", "FLOAT", "DOUBLE", "BYTE[]", "STRING", "LIST", "COMPOUND", "INT[]"}; + + abstract void write(DataOutput dataoutput) throws IOException; + + abstract void load(DataInput datainput, int i, NBTReadLimiter nbtreadlimiter) throws IOException; + + public abstract String toString(); + + public abstract byte getTypeId(); + + protected NBTBase() {} + + protected static NBTBase createTag(byte b0) { + switch (b0) { + case 0: + return new NBTTagEnd(); + + case 1: + return new NBTTagByte(); + + case 2: + return new NBTTagShort(); + + case 3: + return new NBTTagInt(); + + case 4: + return new NBTTagLong(); + + case 5: + return new NBTTagFloat(); + + case 6: + return new NBTTagDouble(); + + case 7: + return new NBTTagByteArray(); + + case 8: + return new NBTTagString(); + + case 9: + return new NBTTagList(); + + case 10: + return new NBTTagCompound(); + + case 11: + return new NBTTagIntArray(); + + default: + return null; + } + } + + public abstract NBTBase clone(); + + public boolean isEmpty() { + return false; + } + + public boolean equals(Object object) { + if (!(object instanceof NBTBase)) { + return false; + } else { + NBTBase nbtbase = (NBTBase) object; + + return this.getTypeId() == nbtbase.getTypeId(); + } + } + + public int hashCode() { + return this.getTypeId(); + } + + protected String a_() { + return this.toString(); + } + + public abstract static class NBTNumber extends NBTBase { + + protected NBTNumber() {} + + public abstract long c(); + + public abstract int d(); + + public abstract short e(); + + public abstract byte f(); + + public abstract double g(); + + public abstract float h(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/NBTCompressedStreamTools.java b/azurite-server/src/main/java/net/minecraft/server/NBTCompressedStreamTools.java new file mode 100644 index 0000000..ab05626 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/NBTCompressedStreamTools.java @@ -0,0 +1,85 @@ +package net.minecraft.server; + +import java.io.*; +import java.util.zip.GZIPInputStream; +import java.util.zip.GZIPOutputStream; + +public class NBTCompressedStreamTools { + + public static NBTTagCompound readNBT(InputStream inputstream) throws IOException { return a(inputstream); } // PandaSpigot - OBFHELPER + public static NBTTagCompound a(InputStream inputstream) throws IOException { + DataInputStream datainputstream = new DataInputStream(new BufferedInputStream(new GZIPInputStream(inputstream))); + + NBTTagCompound nbttagcompound; + + try { + nbttagcompound = a(datainputstream, NBTReadLimiter.a); + } finally { + datainputstream.close(); + } + + return nbttagcompound; + } + + public static void writeNBT(NBTTagCompound nbttagcompound, OutputStream outputstream) throws IOException { a(nbttagcompound, outputstream); } // PandaSpigot - OBFHELPER + public static void a(NBTTagCompound nbttagcompound, OutputStream outputstream) throws IOException { + try (DataOutputStream dataoutputstream = new DataOutputStream(new BufferedOutputStream(new GZIPOutputStream(outputstream)))) { + a(nbttagcompound, (DataOutput) dataoutputstream); + } + } + + public static NBTTagCompound a(DataInputStream datainputstream) throws IOException { + return a(datainputstream, NBTReadLimiter.a); + } + + public static NBTTagCompound a(DataInput datainput, NBTReadLimiter nbtreadlimiter) throws IOException { + // Spigot start + if ( datainput instanceof io.netty.buffer.ByteBufInputStream ) + { + datainput = new DataInputStream(new org.spigotmc.LimitStream((InputStream) datainput, nbtreadlimiter)); + } + // Spigot end + NBTBase nbtbase = a(datainput, 0, nbtreadlimiter); + + if (nbtbase instanceof NBTTagCompound) { + return (NBTTagCompound) nbtbase; + } else { + throw new IOException("Root tag must be a named compound tag"); + } + } + + public static void a(NBTTagCompound nbttagcompound, DataOutput dataoutput) throws IOException { + a((NBTBase) nbttagcompound, dataoutput); + } + + private static void a(NBTBase nbtbase, DataOutput dataoutput) throws IOException { + dataoutput.writeByte(nbtbase.getTypeId()); + if (nbtbase.getTypeId() != 0) { + dataoutput.writeUTF(""); + nbtbase.write(dataoutput); + } + } + + private static NBTBase a(DataInput datainput, int i, NBTReadLimiter nbtreadlimiter) throws IOException { + byte b0 = datainput.readByte(); + + if (b0 == 0) { + return new NBTTagEnd(); + } else { + datainput.readUTF(); + NBTBase nbtbase = NBTBase.createTag(b0); + + try { + nbtbase.load(datainput, i, nbtreadlimiter); + return nbtbase; + } catch (IOException ioexception) { + CrashReport crashreport = CrashReport.a(ioexception, "Loading NBT data"); + CrashReportSystemDetails crashreportsystemdetails = crashreport.a("NBT Tag"); + + crashreportsystemdetails.a("Tag name", "[UNNAMED TAG]"); + crashreportsystemdetails.a("Tag type", b0); + throw new ReportedException(crashreport); + } + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/NBTReadLimiter.java b/azurite-server/src/main/java/net/minecraft/server/NBTReadLimiter.java new file mode 100644 index 0000000..58253cc --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/NBTReadLimiter.java @@ -0,0 +1,21 @@ +package net.minecraft.server; + +public class NBTReadLimiter { + + public static final NBTReadLimiter a = new NBTReadLimiter(0L) { + public void a(long i) {} + }; + private final long b; + private long c; + + public NBTReadLimiter(long i) { + this.b = i; + } + + public void a(long i) { + this.c += i / 8L; + if (this.c > this.b) { + throw new RuntimeException("Tried to read NBT tag that was too big; tried to allocate: " + this.c + "bytes where max allowed: " + this.b); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/NBTTagByte.java b/azurite-server/src/main/java/net/minecraft/server/NBTTagByte.java new file mode 100644 index 0000000..01c5afa --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/NBTTagByte.java @@ -0,0 +1,75 @@ +package net.minecraft.server; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; + +public class NBTTagByte extends NBTBase.NBTNumber { + + private byte data; + + NBTTagByte() {} + + public NBTTagByte(byte b0) { + this.data = b0; + } + + void write(DataOutput dataoutput) throws IOException { + dataoutput.writeByte(this.data); + } + + void load(DataInput datainput, int i, NBTReadLimiter nbtreadlimiter) throws IOException { + nbtreadlimiter.a(72L); + this.data = datainput.readByte(); + } + + public byte getTypeId() { + return (byte) 1; + } + + public String toString() { + return "" + this.data + "b"; + } + + public NBTBase clone() { + return new NBTTagByte(this.data); + } + + public boolean equals(Object object) { + if (super.equals(object)) { + NBTTagByte nbttagbyte = (NBTTagByte) object; + + return this.data == nbttagbyte.data; + } else { + return false; + } + } + + public int hashCode() { + return super.hashCode() ^ this.data; + } + + public long c() { + return (long) this.data; + } + + public int d() { + return this.data; + } + + public short e() { + return (short) this.data; + } + + public byte f() { + return this.data; + } + + public double g() { + return (double) this.data; + } + + public float h() { + return (float) this.data; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/NBTTagByteArray.java b/azurite-server/src/main/java/net/minecraft/server/NBTTagByteArray.java new file mode 100644 index 0000000..8a356f4 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/NBTTagByteArray.java @@ -0,0 +1,59 @@ +package net.minecraft.server; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; +import java.util.Arrays; + +public class NBTTagByteArray extends NBTBase { + + private byte[] data; + + NBTTagByteArray() {} + + public NBTTagByteArray(byte[] abyte) { + this.data = abyte; + } + + void write(DataOutput dataoutput) throws IOException { + dataoutput.writeInt(this.data.length); + dataoutput.write(this.data); + } + + void load(DataInput datainput, int i, NBTReadLimiter nbtreadlimiter) throws IOException { + nbtreadlimiter.a(192L); + int j = datainput.readInt(); + com.google.common.base.Preconditions.checkArgument( j < 1 << 24); + + nbtreadlimiter.a(8L * j); + this.data = new byte[j]; + datainput.readFully(this.data); + } + + public byte getTypeId() { + return (byte) 7; + } + + public String toString() { + return "[" + this.data.length + " bytes]"; + } + + public NBTBase clone() { + byte[] abyte = new byte[this.data.length]; + + System.arraycopy(this.data, 0, abyte, 0, this.data.length); + return new NBTTagByteArray(abyte); + } + + public boolean equals(Object object) { + return super.equals(object) && Arrays.equals(this.data, ((NBTTagByteArray) object).data); + } + + public int hashCode() { + return super.hashCode() ^ Arrays.hashCode(this.data); + } + + public byte[] c() { + return this.data; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/NBTTagCompound.java b/azurite-server/src/main/java/net/minecraft/server/NBTTagCompound.java new file mode 100644 index 0000000..2cdc284 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/NBTTagCompound.java @@ -0,0 +1,347 @@ +package net.minecraft.server; + +import it.unimi.dsi.fastutil.objects.Object2ObjectMap; +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.objects.ObjectIterator; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; +import java.util.Iterator; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +public class NBTTagCompound extends NBTBase { + + private final Object2ObjectOpenHashMap map; + + public NBTTagCompound() { + this.map = new Object2ObjectOpenHashMap<>(8, 0.8f); // Paper - reduce memory footprint + } + + public NBTTagCompound(Object2ObjectOpenHashMap map) { + this.map = map; + } + + void write(DataOutput dataoutput) throws IOException { + + for (String s : this.map.keySet()) { + NBTBase nbtbase = this.map.get(s); + + a(s, nbtbase, dataoutput); + } + + dataoutput.writeByte(0); + } + + void load(DataInput datainput, int i, NBTReadLimiter nbtreadlimiter) throws IOException { + nbtreadlimiter.a(384L); + if (i > 512) { + throw new RuntimeException("Tried to read NBT tag with too high complexity, depth > 512"); + } else { + this.map.clear(); + + byte b0; + + while ((b0 = a(datainput, nbtreadlimiter)) != 0) { + String s = b(datainput, nbtreadlimiter); + + nbtreadlimiter.a(224 + 16L * s.length()); + NBTBase nbtbase = a(b0, s, datainput, i + 1, nbtreadlimiter); + + if (this.map.put(s, nbtbase) != null) { + nbtreadlimiter.a(288L); + } + } + + } + } + + public Set c() { + return this.map.keySet(); + } + + public byte getTypeId() { + return (byte) 10; + } + + public void set(String s, NBTBase nbtbase) { + this.map.put(s, nbtbase); + } + + public void setByte(String s, byte b0) { + this.map.put(s, new NBTTagByte(b0)); + } + + public void setShort(String s, short short0) { + this.map.put(s, new NBTTagShort(short0)); + } + + public void setInt(String s, int i) { + this.map.put(s, new NBTTagInt(i)); + } + + public void setLong(String s, long i) { + this.map.put(s, new NBTTagLong(i)); + } + + public void setFloat(String s, float f) { + this.map.put(s, new NBTTagFloat(f)); + } + + public void setDouble(String s, double d0) { + this.map.put(s, new NBTTagDouble(d0)); + } + + public void setString(String s, String s1) { + this.map.put(s, new NBTTagString(s1)); + } + + public void setByteArray(String s, byte[] abyte) { + this.map.put(s, new NBTTagByteArray(abyte)); + } + + public void setIntArray(String s, int[] aint) { + this.map.put(s, new NBTTagIntArray(aint)); + } + + public void setBoolean(String s, boolean flag) { + this.setByte(s, (byte) (flag ? 1 : 0)); + } + + public NBTBase get(String s) { + return this.map.get(s); + } + + public byte b(String s) { + NBTBase nbtbase = this.map.get(s); + + return nbtbase != null ? nbtbase.getTypeId() : 0; + } + + public boolean hasKey(String s) { + return this.map.containsKey(s); + } + + public boolean hasKeyOfType(String s, int i) { + byte b0 = this.b(s); + + if (b0 == i) { + return true; + } else if (i != 99) { + return false; + } else { + return b0 == 1 || b0 == 2 || b0 == 3 || b0 == 4 || b0 == 5 || b0 == 6; + } + } + + public byte getByte(String s) { + try { + return !this.hasKeyOfType(s, 99) ? 0 : ((NBTBase.NBTNumber) this.map.get(s)).f(); + } catch (ClassCastException classcastexception) { + return (byte) 0; + } + } + + public short getShort(String s) { + try { + return !this.hasKeyOfType(s, 99) ? 0 : ((NBTBase.NBTNumber) this.map.get(s)).e(); + } catch (ClassCastException classcastexception) { + return (short) 0; + } + } + + public int getInt(String s) { + try { + return !this.hasKeyOfType(s, 99) ? 0 : ((NBTBase.NBTNumber) this.map.get(s)).d(); + } catch (ClassCastException classcastexception) { + return 0; + } + } + + public long getLong(String s) { + try { + return !this.hasKeyOfType(s, 99) ? 0L : ((NBTBase.NBTNumber) this.map.get(s)).c(); + } catch (ClassCastException classcastexception) { + return 0L; + } + } + + public float getFloat(String s) { + try { + return !this.hasKeyOfType(s, 99) ? 0.0F : ((NBTBase.NBTNumber) this.map.get(s)).h(); + } catch (ClassCastException classcastexception) { + return 0.0F; + } + } + + public double getDouble(String s) { + try { + return !this.hasKeyOfType(s, 99) ? 0.0D : ((NBTBase.NBTNumber) this.map.get(s)).g(); + } catch (ClassCastException classcastexception) { + return 0.0D; + } + } + + public String getString(String s) { + try { + return !this.hasKeyOfType(s, 8) ? "" : this.map.get(s).a_(); + } catch (ClassCastException classcastexception) { + return ""; + } + } + + public byte[] getByteArray(String s) { + try { + return !this.hasKeyOfType(s, 7) ? new byte[0] : ((NBTTagByteArray) this.map.get(s)).c(); + } catch (ClassCastException classcastexception) { + throw new ReportedException(this.a(s, 7, classcastexception)); + } + } + + public int[] getIntArray(String s) { + try { + return !this.hasKeyOfType(s, 11) ? new int[0] : ((NBTTagIntArray) this.map.get(s)).c(); + } catch (ClassCastException classcastexception) { + throw new ReportedException(this.a(s, 11, classcastexception)); + } + } + + public NBTTagCompound getCompound(String s) { + try { + return !this.hasKeyOfType(s, 10) ? new NBTTagCompound() : (NBTTagCompound) this.map.get(s); + } catch (ClassCastException classcastexception) { + throw new ReportedException(this.a(s, 10, classcastexception)); + } + } + + public NBTTagList getList(String s, int i) { + try { + if (this.b(s) != 9) { + return new NBTTagList(); + } else { + NBTTagList nbttaglist = (NBTTagList) this.map.get(s); + + return !nbttaglist.isEmpty() && nbttaglist.f() != i ? new NBTTagList() : nbttaglist; + } + } catch (ClassCastException classcastexception) { + throw new ReportedException(this.a(s, 9, classcastexception)); + } + } + + public boolean getBoolean(String s) { + return this.getByte(s) != 0; + } + + public void remove(String s) { + this.map.remove(s); + } + + public String toString() { + StringBuilder stringbuilder = new StringBuilder("{"); + + Entry entry; + + for (Iterator> iterator = this.map.entrySet().iterator(); iterator.hasNext(); stringbuilder.append(entry.getKey()).append(':').append(entry.getValue())) { + entry = iterator.next(); + if (stringbuilder.length() != 1) { + stringbuilder.append(','); + } + } + + return stringbuilder.append('}').toString(); + } + + public boolean isEmpty() { + return this.map.isEmpty(); + } + + private CrashReport a(final String s, final int i, ClassCastException classcastexception) { + CrashReport crashreport = CrashReport.a(classcastexception, "Reading NBT data"); + CrashReportSystemDetails crashreportsystemdetails = crashreport.a("Corrupt NBT tag", 1); + + crashreportsystemdetails.a("Tag type found", () -> NBTBase.a[NBTTagCompound.this.map.get(s).getTypeId()]); + crashreportsystemdetails.a("Tag type expected", () -> NBTBase.a[i]); + crashreportsystemdetails.a("Tag name", s); + return crashreport; + } + + // Paper - reduce memory footprints + public NBTBase clone() { + Object2ObjectOpenHashMap ret = new Object2ObjectOpenHashMap<>(this.map.size(), 0.8f); + ObjectIterator> iterator = this.map.object2ObjectEntrySet().fastIterator(); + while (iterator.hasNext()) { + Map.Entry entry = iterator.next(); + ret.put(entry.getKey(), entry.getValue().clone()); + } + return new NBTTagCompound(ret); + } + + public boolean equals(Object object) { + if (super.equals(object)) { + NBTTagCompound nbttagcompound = (NBTTagCompound) object; + + // Beanes - optimize equals by using the built-in fastutil equals + return this.map.equals(nbttagcompound.map); + } else { + return false; + } + } + + public int hashCode() { + return super.hashCode() ^ this.map.hashCode(); + } + + private static void a(String s, NBTBase nbtbase, DataOutput dataoutput) throws IOException { + dataoutput.writeByte(nbtbase.getTypeId()); + if (nbtbase.getTypeId() != 0) { + dataoutput.writeUTF(s); + nbtbase.write(dataoutput); + } + } + + private static byte a(DataInput datainput, NBTReadLimiter nbtreadlimiter) throws IOException { + return datainput.readByte(); + } + + private static String b(DataInput datainput, NBTReadLimiter nbtreadlimiter) throws IOException { + return datainput.readUTF(); + } + + static NBTBase a(byte b0, String s, DataInput datainput, int i, NBTReadLimiter nbtreadlimiter) throws IOException { + NBTBase nbtbase = NBTBase.createTag(b0); + + try { + nbtbase.load(datainput, i, nbtreadlimiter); + return nbtbase; + } catch (IOException ioexception) { + CrashReport crashreport = CrashReport.a(ioexception, "Loading NBT data"); + CrashReportSystemDetails crashreportsystemdetails = crashreport.a("NBT Tag"); + + crashreportsystemdetails.a("Tag name", s); + crashreportsystemdetails.a("Tag type", b0); + throw new ReportedException(crashreport); + } + } + + public void a(NBTTagCompound nbttagcompound) { + + for (String s : nbttagcompound.map.keySet()) { + NBTBase nbtbase = nbttagcompound.map.get(s); + + if (nbtbase.getTypeId() == 10) { + if (this.hasKeyOfType(s, 10)) { + NBTTagCompound nbttagcompound1 = this.getCompound(s); + + nbttagcompound1.a((NBTTagCompound) nbtbase); + } else { + this.set(s, nbtbase.clone()); + } + } else { + this.set(s, nbtbase.clone()); + } + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/NBTTagDouble.java b/azurite-server/src/main/java/net/minecraft/server/NBTTagDouble.java new file mode 100644 index 0000000..cdd2019 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/NBTTagDouble.java @@ -0,0 +1,77 @@ +package net.minecraft.server; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; + +public class NBTTagDouble extends NBTBase.NBTNumber { + + private double data; + + NBTTagDouble() {} + + public NBTTagDouble(double d0) { + this.data = d0; + } + + void write(DataOutput dataoutput) throws IOException { + dataoutput.writeDouble(this.data); + } + + void load(DataInput datainput, int i, NBTReadLimiter nbtreadlimiter) throws IOException { + nbtreadlimiter.a(128L); + this.data = datainput.readDouble(); + } + + public byte getTypeId() { + return (byte) 6; + } + + public String toString() { + return "" + this.data + "d"; + } + + public NBTBase clone() { + return new NBTTagDouble(this.data); + } + + public boolean equals(Object object) { + if (super.equals(object)) { + NBTTagDouble nbttagdouble = (NBTTagDouble) object; + + return this.data == nbttagdouble.data; + } else { + return false; + } + } + + public int hashCode() { + long i = Double.doubleToLongBits(this.data); + + return super.hashCode() ^ (int) (i ^ i >>> 32); + } + + public long c() { + return (long) Math.floor(this.data); + } + + public int d() { + return MathHelper.floor(this.data); + } + + public short e() { + return (short) (MathHelper.floor(this.data) & '\uffff'); + } + + public byte f() { + return (byte) (MathHelper.floor(this.data) & 255); + } + + public double g() { + return this.data; + } + + public float h() { + return (float) this.data; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/NBTTagEnd.java b/azurite-server/src/main/java/net/minecraft/server/NBTTagEnd.java new file mode 100644 index 0000000..376a5a4 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/NBTTagEnd.java @@ -0,0 +1,28 @@ +package net.minecraft.server; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; + +public class NBTTagEnd extends NBTBase { + + NBTTagEnd() {} + + void load(DataInput datainput, int i, NBTReadLimiter nbtreadlimiter) throws IOException { + nbtreadlimiter.a(64L); + } + + void write(DataOutput dataoutput) throws IOException {} + + public byte getTypeId() { + return (byte) 0; + } + + public String toString() { + return "END"; + } + + public NBTBase clone() { + return new NBTTagEnd(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/NBTTagFloat.java b/azurite-server/src/main/java/net/minecraft/server/NBTTagFloat.java new file mode 100644 index 0000000..af72960 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/NBTTagFloat.java @@ -0,0 +1,75 @@ +package net.minecraft.server; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; + +public class NBTTagFloat extends NBTBase.NBTNumber { + + private float data; + + NBTTagFloat() {} + + public NBTTagFloat(float f) { + this.data = f; + } + + void write(DataOutput dataoutput) throws IOException { + dataoutput.writeFloat(this.data); + } + + void load(DataInput datainput, int i, NBTReadLimiter nbtreadlimiter) throws IOException { + nbtreadlimiter.a(96L); + this.data = datainput.readFloat(); + } + + public byte getTypeId() { + return (byte) 5; + } + + public String toString() { + return "" + this.data + "f"; + } + + public NBTBase clone() { + return new NBTTagFloat(this.data); + } + + public boolean equals(Object object) { + if (super.equals(object)) { + NBTTagFloat nbttagfloat = (NBTTagFloat) object; + + return this.data == nbttagfloat.data; + } else { + return false; + } + } + + public int hashCode() { + return super.hashCode() ^ Float.floatToIntBits(this.data); + } + + public long c() { + return (long) this.data; + } + + public int d() { + return MathHelper.d(this.data); + } + + public short e() { + return (short) (MathHelper.d(this.data) & '\uffff'); + } + + public byte f() { + return (byte) (MathHelper.d(this.data) & 255); + } + + public double g() { + return (double) this.data; + } + + public float h() { + return this.data; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/NBTTagInt.java b/azurite-server/src/main/java/net/minecraft/server/NBTTagInt.java new file mode 100644 index 0000000..9ff8991 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/NBTTagInt.java @@ -0,0 +1,75 @@ +package net.minecraft.server; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; + +public class NBTTagInt extends NBTBase.NBTNumber { + + private int data; + + NBTTagInt() {} + + public NBTTagInt(int i) { + this.data = i; + } + + void write(DataOutput dataoutput) throws IOException { + dataoutput.writeInt(this.data); + } + + void load(DataInput datainput, int i, NBTReadLimiter nbtreadlimiter) throws IOException { + nbtreadlimiter.a(96L); + this.data = datainput.readInt(); + } + + public byte getTypeId() { + return (byte) 3; + } + + public String toString() { + return "" + this.data; + } + + public NBTBase clone() { + return new NBTTagInt(this.data); + } + + public boolean equals(Object object) { + if (super.equals(object)) { + NBTTagInt nbttagint = (NBTTagInt) object; + + return this.data == nbttagint.data; + } else { + return false; + } + } + + public int hashCode() { + return super.hashCode() ^ this.data; + } + + public long c() { + return (long) this.data; + } + + public int d() { + return this.data; + } + + public short e() { + return (short) (this.data & '\uffff'); + } + + public byte f() { + return (byte) (this.data & 255); + } + + public double g() { + return (double) this.data; + } + + public float h() { + return (float) this.data; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/NBTTagIntArray.java b/azurite-server/src/main/java/net/minecraft/server/NBTTagIntArray.java new file mode 100644 index 0000000..43bcb6e --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/NBTTagIntArray.java @@ -0,0 +1,75 @@ +package net.minecraft.server; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; +import java.util.Arrays; + +public class NBTTagIntArray extends NBTBase { + + private int[] data; + + NBTTagIntArray() {} + + public NBTTagIntArray(int[] aint) { + this.data = aint; + } + + void write(DataOutput dataoutput) throws IOException { + dataoutput.writeInt(this.data.length); + + for (int datum : this.data) { + dataoutput.writeInt(datum); + } + + } + + void load(DataInput datainput, int i, NBTReadLimiter nbtreadlimiter) throws IOException { + nbtreadlimiter.a(192L); + int j = datainput.readInt(); + com.google.common.base.Preconditions.checkArgument( j < 1 << 24); + + nbtreadlimiter.a(32L * j); + this.data = new int[j]; + + for (int k = 0; k < j; ++k) { + this.data[k] = datainput.readInt(); + } + + } + + public byte getTypeId() { + return (byte) 11; + } + + public String toString() { + String s = "["; + int[] aint = this.data; + int i = aint.length; + + for (int k : aint) { + s = s + k + ","; + } + + return s + "]"; + } + + public NBTBase clone() { + int[] aint = new int[this.data.length]; + + System.arraycopy(this.data, 0, aint, 0, this.data.length); + return new NBTTagIntArray(aint); + } + + public boolean equals(Object object) { + return super.equals(object) && Arrays.equals(this.data, ((NBTTagIntArray) object).data); + } + + public int hashCode() { + return super.hashCode() ^ Arrays.hashCode(this.data); + } + + public int[] c() { + return this.data; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/NBTTagList.java b/azurite-server/src/main/java/net/minecraft/server/NBTTagList.java new file mode 100644 index 0000000..eeccfac --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/NBTTagList.java @@ -0,0 +1,211 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; +import java.util.List; + +public class NBTTagList extends NBTBase { + + private static final Logger b = LogManager.getLogger(); + private List list = Lists.newArrayList(); + private byte type = 0; + + public NBTTagList() {} + + void write(DataOutput dataoutput) throws IOException { + if (!this.list.isEmpty()) { + this.type = this.list.get(0).getTypeId(); + } else { + this.type = 0; + } + + dataoutput.writeByte(this.type); + dataoutput.writeInt(this.list.size()); + + for (NBTBase nbtBase : this.list) { + nbtBase.write(dataoutput); + } + + } + + void load(DataInput datainput, int i, NBTReadLimiter nbtreadlimiter) throws IOException { + nbtreadlimiter.a(296L); + if (i > 512) { + throw new RuntimeException("Tried to read NBT tag with too high complexity, depth > 512"); + } else { + this.type = datainput.readByte(); + int j = datainput.readInt(); + nbtreadlimiter.a(j * 8L); // CraftBukkit + + if (this.type == 0 && j > 0) { + throw new RuntimeException("Missing type on ListTag"); + } else { + nbtreadlimiter.a(32L * (long) j); + this.list = Lists.newArrayListWithCapacity(j); + + for (int k = 0; k < j; ++k) { + NBTBase nbtbase = NBTBase.createTag(this.type); + + nbtbase.load(datainput, i + 1, nbtreadlimiter); + this.list.add(nbtbase); + } + + } + } + } + + public byte getTypeId() { + return (byte) 9; + } + + public String toString() { + StringBuilder stringbuilder = new StringBuilder("["); + + for (int i = 0; i < this.list.size(); ++i) { + if (i != 0) { + stringbuilder.append(','); + } + + stringbuilder.append(i).append(':').append(this.list.get(i)); + } + + return stringbuilder.append(']').toString(); + } + + public void add(NBTBase nbtbase) { + if (nbtbase.getTypeId() == 0) { + NBTTagList.b.warn("Invalid TagEnd added to ListTag"); + } else { + if (this.type == 0) { + this.type = nbtbase.getTypeId(); + } else if (this.type != nbtbase.getTypeId()) { + NBTTagList.b.warn("Adding mismatching tag types to tag list"); + return; + } + + this.list.add(nbtbase); + } + } + + public void a(int i, NBTBase nbtbase) { + if (nbtbase.getTypeId() == 0) { + NBTTagList.b.warn("Invalid TagEnd added to ListTag"); + } else if (i >= 0 && i < this.list.size()) { + if (this.type == 0) { + this.type = nbtbase.getTypeId(); + } else if (this.type != nbtbase.getTypeId()) { + NBTTagList.b.warn("Adding mismatching tag types to tag list"); + return; + } + + this.list.set(i, nbtbase); + } else { + NBTTagList.b.warn("index out of bounds to set tag in tag list"); + } + } + + public NBTBase a(int i) { + return this.list.remove(i); + } + + public boolean isEmpty() { + return this.list.isEmpty(); + } + + public NBTTagCompound get(int i) { + if (i >= 0 && i < this.list.size()) { + NBTBase nbtbase = this.list.get(i); + + return nbtbase.getTypeId() == 10 ? (NBTTagCompound) nbtbase : new NBTTagCompound(); + } else { + return new NBTTagCompound(); + } + } + + public int[] c(int i) { + if (i >= 0 && i < this.list.size()) { + NBTBase nbtbase = this.list.get(i); + + return nbtbase.getTypeId() == 11 ? ((NBTTagIntArray) nbtbase).c() : new int[0]; + } else { + return new int[0]; + } + } + + public double d(int i) { + if (i >= 0 && i < this.list.size()) { + NBTBase nbtbase = this.list.get(i); + + return nbtbase.getTypeId() == 6 ? ((NBTTagDouble) nbtbase).g() : 0.0D; + } else { + return 0.0D; + } + } + + public float e(int i) { + if (i >= 0 && i < this.list.size()) { + NBTBase nbtbase = this.list.get(i); + + return nbtbase.getTypeId() == 5 ? ((NBTTagFloat) nbtbase).h() : 0.0F; + } else { + return 0.0F; + } + } + + public String getString(int i) { + if (i >= 0 && i < this.list.size()) { + NBTBase nbtbase = this.list.get(i); + + return nbtbase.getTypeId() == 8 ? nbtbase.a_() : nbtbase.toString(); + } else { + return ""; + } + } + + public NBTBase g(int i) { + return (i >= 0 && i < this.list.size() ? this.list.get(i) : new NBTTagEnd()); + } + + public int size() { + return this.list.size(); + } + + public NBTBase clone() { + NBTTagList nbttaglist = new NBTTagList(); + + nbttaglist.type = this.type; + + for (NBTBase nbtbase : this.list) { + NBTBase nbtbase1 = nbtbase.clone(); + + nbttaglist.list.add(nbtbase1); + } + + return nbttaglist; + } + + public boolean equals(Object object) { + if (super.equals(object)) { + NBTTagList nbttaglist = (NBTTagList) object; + + if (this.type == nbttaglist.type) { + return this.list.equals(nbttaglist.list); + } + } + + return false; + } + + public int hashCode() { + return super.hashCode() ^ this.list.hashCode(); + } + + public int f() { + return this.type; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/NBTTagLong.java b/azurite-server/src/main/java/net/minecraft/server/NBTTagLong.java new file mode 100644 index 0000000..84b871d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/NBTTagLong.java @@ -0,0 +1,75 @@ +package net.minecraft.server; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; + +public class NBTTagLong extends NBTBase.NBTNumber { + + private long data; + + NBTTagLong() {} + + public NBTTagLong(long i) { + this.data = i; + } + + void write(DataOutput dataoutput) throws IOException { + dataoutput.writeLong(this.data); + } + + void load(DataInput datainput, int i, NBTReadLimiter nbtreadlimiter) throws IOException { + nbtreadlimiter.a(128L); + this.data = datainput.readLong(); + } + + public byte getTypeId() { + return (byte) 4; + } + + public String toString() { + return "" + this.data + "L"; + } + + public NBTBase clone() { + return new NBTTagLong(this.data); + } + + public boolean equals(Object object) { + if (super.equals(object)) { + NBTTagLong nbttaglong = (NBTTagLong) object; + + return this.data == nbttaglong.data; + } else { + return false; + } + } + + public int hashCode() { + return super.hashCode() ^ (int) (this.data ^ this.data >>> 32); + } + + public long c() { + return this.data; + } + + public int d() { + return (int) (this.data & -1L); + } + + public short e() { + return (short) ((int) (this.data & 65535L)); + } + + public byte f() { + return (byte) ((int) (this.data & 255L)); + } + + public double g() { + return (double) this.data; + } + + public float h() { + return (float) this.data; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/NBTTagShort.java b/azurite-server/src/main/java/net/minecraft/server/NBTTagShort.java new file mode 100644 index 0000000..690371d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/NBTTagShort.java @@ -0,0 +1,75 @@ +package net.minecraft.server; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; + +public class NBTTagShort extends NBTBase.NBTNumber { + + private short data; + + public NBTTagShort() {} + + public NBTTagShort(short short0) { + this.data = short0; + } + + void write(DataOutput dataoutput) throws IOException { + dataoutput.writeShort(this.data); + } + + void load(DataInput datainput, int i, NBTReadLimiter nbtreadlimiter) throws IOException { + nbtreadlimiter.a(80L); + this.data = datainput.readShort(); + } + + public byte getTypeId() { + return (byte) 2; + } + + public String toString() { + return "" + this.data + "s"; + } + + public NBTBase clone() { + return new NBTTagShort(this.data); + } + + public boolean equals(Object object) { + if (super.equals(object)) { + NBTTagShort nbttagshort = (NBTTagShort) object; + + return this.data == nbttagshort.data; + } else { + return false; + } + } + + public int hashCode() { + return super.hashCode() ^ this.data; + } + + public long c() { + return (long) this.data; + } + + public int d() { + return this.data; + } + + public short e() { + return this.data; + } + + public byte f() { + return (byte) (this.data & 255); + } + + public double g() { + return (double) this.data; + } + + public float h() { + return (float) this.data; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/NBTTagString.java b/azurite-server/src/main/java/net/minecraft/server/NBTTagString.java new file mode 100644 index 0000000..d1967dc --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/NBTTagString.java @@ -0,0 +1,65 @@ +package net.minecraft.server; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; + +public class NBTTagString extends NBTBase { + + private String data; + + public NBTTagString() { + this.data = ""; + } + + public NBTTagString(String s) { + this.data = s; + if (s == null) { + throw new IllegalArgumentException("Empty string not allowed"); + } + } + + void write(DataOutput dataoutput) throws IOException { + dataoutput.writeUTF(this.data); + } + + void load(DataInput datainput, int i, NBTReadLimiter nbtreadlimiter) throws IOException { + nbtreadlimiter.a(288L); + this.data = datainput.readUTF(); + nbtreadlimiter.a((long) (16 * this.data.length())); + } + + public byte getTypeId() { + return (byte) 8; + } + + public String toString() { + return "\"" + this.data.replace("\"", "\\\"") + "\""; + } + + public NBTBase clone() { + return new NBTTagString(this.data); + } + + public boolean isEmpty() { + return this.data.isEmpty(); + } + + public boolean equals(Object object) { + if (!super.equals(object)) { + return false; + } else { + NBTTagString nbttagstring = (NBTTagString) object; + + return this.data == null && nbttagstring.data == null || this.data != null && this.data.equals(nbttagstring.data); + } + } + + public int hashCode() { + return super.hashCode() ^ this.data.hashCode(); + } + + public String a_() { + return this.data; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/NPC.java b/azurite-server/src/main/java/net/minecraft/server/NPC.java new file mode 100644 index 0000000..d5cac48 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/NPC.java @@ -0,0 +1,3 @@ +package net.minecraft.server; + +public interface NPC extends IAnimal {} diff --git a/azurite-server/src/main/java/net/minecraft/server/NameReferencingFileConverter.java b/azurite-server/src/main/java/net/minecraft/server/NameReferencingFileConverter.java new file mode 100644 index 0000000..1b57a4d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/NameReferencingFileConverter.java @@ -0,0 +1,507 @@ +package net.minecraft.server; + +import com.eatthepath.uuid.FastUUID; +import com.google.common.base.Charsets; +import com.google.common.collect.Iterators; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import com.google.common.io.Files; +import com.mojang.authlib.Agent; +import com.mojang.authlib.GameProfile; +import com.mojang.authlib.ProfileLookupCallback; +import com.mojang.authlib.yggdrasil.ProfileNotFoundException; +import org.apache.commons.lang3.StringUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.io.File; +import java.io.IOException; +import java.text.ParseException; +import java.util.*; + +public class NameReferencingFileConverter { + + private static final Logger e = LogManager.getLogger(); + public static final File a = new File("banned-ips.txt"); + public static final File b = new File("banned-players.txt"); + public static final File c = new File("ops.txt"); + public static final File d = new File("white-list.txt"); + + static List a(File file, Map map) throws IOException { + List list = Files.readLines(file, Charsets.UTF_8); + + for (String s : list) { + s = s.trim(); + if (!s.startsWith("#") && s.length() >= 1) { + String[] astring = s.split("\\|"); + + map.put(astring[0].toLowerCase(Locale.ROOT), astring); + } + } + + return list; + } + + private static void a(MinecraftServer minecraftserver, Collection collection, ProfileLookupCallback profilelookupcallback) { + String[] astring = Iterators.toArray(Iterators.filter(collection.iterator(), s -> !StringUtils.isEmpty(s)), String.class); + + if (minecraftserver.getOnlineMode() || org.spigotmc.SpigotConfig.bungee) { // Spigot: bungee = online mode, for now. + minecraftserver.getGameProfileRepository().findProfilesByNames(astring, Agent.MINECRAFT, profilelookupcallback); + } else { + for (String s : astring) { + UUID uuid = EntityHuman.a(new GameProfile(null, s)); + GameProfile gameprofile = new GameProfile(uuid, s); + profilelookupcallback.onProfileLookupSucceeded(gameprofile); + } + } + + } + + public static boolean a(final MinecraftServer minecraftserver) { + final GameProfileBanList gameprofilebanlist = new GameProfileBanList(PlayerList.a); + + if (NameReferencingFileConverter.b.exists() && NameReferencingFileConverter.b.isFile()) { + if (gameprofilebanlist.c().exists()) { + try { + gameprofilebanlist.load(); + // CraftBukkit start - FileNotFoundException -> IOException, don't print stacetrace + } catch (IOException filenotfoundexception) { + NameReferencingFileConverter.e.warn("Could not load existing file " + gameprofilebanlist.c().getName()); + } + } + + try { + final HashMap hashmap = Maps.newHashMap(); + + a(NameReferencingFileConverter.b, hashmap); + ProfileLookupCallback profilelookupcallback = new ProfileLookupCallback() { + public void onProfileLookupSucceeded(GameProfile gameprofile) { + minecraftserver.getUserCache().a(gameprofile); + String[] astring = hashmap.get(gameprofile.getName().toLowerCase(Locale.ROOT)); + + if (astring == null) { + NameReferencingFileConverter.e.warn("Could not convert user banlist entry for " + gameprofile.getName()); + throw new NameReferencingFileConverter.FileConversionException("Profile not in the conversionlist", null); + } else { + Date date = astring.length > 1 ? NameReferencingFileConverter.b(astring[1], null) : null; + String s = astring.length > 2 ? astring[2] : null; + Date date1 = astring.length > 3 ? NameReferencingFileConverter.b(astring[3], null) : null; + String s1 = astring.length > 4 ? astring[4] : null; + + gameprofilebanlist.add(new GameProfileBanEntry(gameprofile, date, s, date1, s1)); + } + } + + public void onProfileLookupFailed(GameProfile gameprofile, Exception exception) { + NameReferencingFileConverter.e.warn("Could not lookup user banlist entry for " + gameprofile.getName(), exception); + if (!(exception instanceof ProfileNotFoundException)) { + throw new NameReferencingFileConverter.FileConversionException("Could not request user " + gameprofile.getName() + " from backend systems", exception, null); + } + } + }; + + a(minecraftserver, hashmap.keySet(), profilelookupcallback); + gameprofilebanlist.save(); + c(NameReferencingFileConverter.b); + return true; + } catch (IOException ioexception) { + NameReferencingFileConverter.e.warn("Could not read old user banlist to convert it!", ioexception); + return false; + } catch (NameReferencingFileConverter.FileConversionException namereferencingfileconverter_fileconversionexception) { + NameReferencingFileConverter.e.error("Conversion failed, please try again later", namereferencingfileconverter_fileconversionexception); + return false; + } + } else { + return true; + } + } + + public static boolean b(MinecraftServer minecraftserver) { + IpBanList ipbanlist = new IpBanList(PlayerList.b); + + if (NameReferencingFileConverter.a.exists() && NameReferencingFileConverter.a.isFile()) { + if (ipbanlist.c().exists()) { + try { + ipbanlist.load(); + // CraftBukkit start - FileNotFoundException -> IOException, don't print stacetrace + } catch (IOException filenotfoundexception) { + NameReferencingFileConverter.e.warn("Could not load existing file " + ipbanlist.c().getName()); + } + } + + try { + HashMap hashmap = Maps.newHashMap(); + + a(NameReferencingFileConverter.a, hashmap); + + for (String s : hashmap.keySet()) { + String[] astring = hashmap.get(s); + Date date = astring.length > 1 ? b(astring[1], null) : null; + String s1 = astring.length > 2 ? astring[2] : null; + Date date1 = astring.length > 3 ? b(astring[3], null) : null; + String s2 = astring.length > 4 ? astring[4] : null; + + ipbanlist.add(new IpBanEntry(s, date, s1, date1, s2)); + } + + ipbanlist.save(); + c(NameReferencingFileConverter.a); + return true; + } catch (IOException ioexception) { + NameReferencingFileConverter.e.warn("Could not parse old ip banlist to convert it!", ioexception); + return false; + } + } else { + return true; + } + } + + public static boolean c(final MinecraftServer minecraftserver) { + final OpList oplist = new OpList(PlayerList.c); + + if (NameReferencingFileConverter.c.exists() && NameReferencingFileConverter.c.isFile()) { + if (oplist.c().exists()) { + try { + oplist.load(); + // CraftBukkit start - FileNotFoundException -> IOException, don't print stacetrace + } catch (IOException filenotfoundexception) { + NameReferencingFileConverter.e.warn("Could not load existing file " + oplist.c().getName()); + } + } + + try { + a(minecraftserver, Files.readLines(NameReferencingFileConverter.c, Charsets.UTF_8), new ProfileLookupCallback() { + public void onProfileLookupSucceeded(GameProfile gameprofile) { + minecraftserver.getUserCache().a(gameprofile); + oplist.add(new OpListEntry(gameprofile, minecraftserver.p(), false)); + } + + public void onProfileLookupFailed(GameProfile gameprofile, Exception exception) { + NameReferencingFileConverter.e.warn("Could not lookup oplist entry for " + gameprofile.getName(), exception); + if (!(exception instanceof ProfileNotFoundException)) { + throw new NameReferencingFileConverter.FileConversionException("Could not request user " + gameprofile.getName() + " from backend systems", exception, null); + } + } + }); + oplist.save(); + c(NameReferencingFileConverter.c); + return true; + } catch (IOException ioexception) { + NameReferencingFileConverter.e.warn("Could not read old oplist to convert it!", ioexception); + return false; + } catch (NameReferencingFileConverter.FileConversionException namereferencingfileconverter_fileconversionexception) { + NameReferencingFileConverter.e.error("Conversion failed, please try again later", namereferencingfileconverter_fileconversionexception); + return false; + } + } else { + return true; + } + } + + public static boolean d(final MinecraftServer minecraftserver) { + final WhiteList whitelist = new WhiteList(PlayerList.d); + + if (NameReferencingFileConverter.d.exists() && NameReferencingFileConverter.d.isFile()) { + if (whitelist.c().exists()) { + try { + whitelist.load(); + // CraftBukkit start - FileNotFoundException -> IOException, don't print stacetrace + } catch (IOException filenotfoundexception) { + NameReferencingFileConverter.e.warn("Could not load existing file " + whitelist.c().getName()); + } + } + + try { + a(minecraftserver, Files.readLines(NameReferencingFileConverter.d, Charsets.UTF_8), new ProfileLookupCallback() { + public void onProfileLookupSucceeded(GameProfile gameprofile) { + minecraftserver.getUserCache().a(gameprofile); + whitelist.add(new WhiteListEntry(gameprofile)); + } + + public void onProfileLookupFailed(GameProfile gameprofile, Exception exception) { + NameReferencingFileConverter.e.warn("Could not lookup user whitelist entry for " + gameprofile.getName(), exception); + if (!(exception instanceof ProfileNotFoundException)) { + throw new NameReferencingFileConverter.FileConversionException("Could not request user " + gameprofile.getName() + " from backend systems", exception, null); + } + } + }); + whitelist.save(); + c(NameReferencingFileConverter.d); + return true; + } catch (IOException ioexception) { + NameReferencingFileConverter.e.warn("Could not read old whitelist to convert it!", ioexception); + return false; + } catch (NameReferencingFileConverter.FileConversionException namereferencingfileconverter_fileconversionexception) { + NameReferencingFileConverter.e.error("Conversion failed, please try again later", namereferencingfileconverter_fileconversionexception); + return false; + } + } else { + return true; + } + } + + public static String a(String s) { + if (!StringUtils.isEmpty(s) && s.length() <= 16) { + final MinecraftServer minecraftserver = MinecraftServer.getServer(); + GameProfile gameprofile = minecraftserver.getUserCache().getProfile(s); + + if (gameprofile != null && gameprofile.getId() != null) { + return gameprofile.getId().toString(); + } else if (minecraftserver.getOnlineMode()) { + final ArrayList arraylist = Lists.newArrayList(); + + a(minecraftserver, Lists.newArrayList(s), new ProfileLookupCallback() { + public void onProfileLookupSucceeded(GameProfile gameprofile) { + minecraftserver.getUserCache().a(gameprofile); + arraylist.add(gameprofile); + } + + public void onProfileLookupFailed(GameProfile gameprofile, Exception exception) { + NameReferencingFileConverter.e.warn("Could not lookup user whitelist entry for " + gameprofile.getName(), exception); + } + }); + if(arraylist.size() > 0) { + UUID id = arraylist.get(0).getId(); + if(id != null) { + return FastUUID.toString(id); + } + } + return ""; + } else { + return EntityHuman.a(new GameProfile( null, s)).toString(); + } + } else { + return s; + } + } + + public static boolean a(final DedicatedServer dedicatedserver, PropertyManager propertymanager) { + final File file = d(propertymanager); + final File file2 = new File(file.getParentFile(), "unknownplayers"); + + if (file.exists() && file.isDirectory()) { + File[] afile = file.listFiles(); + ArrayList arraylist = Lists.newArrayList(); + + for (File file3 : afile) { + String s = file3.getName(); + + if (s.toLowerCase(Locale.ROOT).endsWith(".dat")) { + String s1 = s.substring(0, s.length() - ".dat".length()); + + if (s1.length() > 0) { + arraylist.add(s1); + } + } + } + + try { + final String[] astring =arraylist.toArray(new String[0]); + a(dedicatedserver, Lists.newArrayList(astring), new ProfileLookupCallback() { + public void onProfileLookupSucceeded(GameProfile gameprofile) { + dedicatedserver.getUserCache().a(gameprofile); + UUID uuid = gameprofile.getId(); + + if (uuid == null) { + throw new NameReferencingFileConverter.FileConversionException("Missing UUID for user profile " + gameprofile.getName(), null); + } else { + this.a(file, this.a(gameprofile), uuid.toString()); + } + } + + public void onProfileLookupFailed(GameProfile gameprofile, Exception exception) { + NameReferencingFileConverter.e.warn("Could not lookup user uuid for " + gameprofile.getName(), exception); + if (exception instanceof ProfileNotFoundException) { + String s = this.a(gameprofile); + + this.a(file, s, s); + } else { + throw new NameReferencingFileConverter.FileConversionException("Could not request user " + gameprofile.getName() + " from backend systems", exception, null); + } + } + + private void a(File file, String s, String s1) { + File file1 = new File(file2, s + ".dat"); + File file3 = new File(file, s1 + ".dat"); + + // CraftBukkit start - Use old file name to seed lastKnownName + NBTTagCompound root = null; + + try { + root = NBTCompressedStreamTools.a(new java.io.FileInputStream(file1)); + } catch (Exception exception) { + exception.printStackTrace(); + } + + if (root != null) { + if (!root.hasKey("bukkit")) { + root.set("bukkit", new NBTTagCompound()); + } + NBTTagCompound data = root.getCompound("bukkit"); + data.setString("lastKnownName", s); + + try { + NBTCompressedStreamTools.a(root, new java.io.FileOutputStream(file2)); + } catch (Exception exception) { + exception.printStackTrace(); + } + } + // CraftBukkit end + + NameReferencingFileConverter.b(file); + if (!file1.renameTo(file3)) { + throw new NameReferencingFileConverter.FileConversionException("Could not convert file for " + s, null); + } + } + + private String a(GameProfile gameprofile) { + String s = null; + + for (String value : astring) { + if (value != null && value.equalsIgnoreCase(gameprofile.getName())) { + s = value; + break; + } + } + + if (s == null) { + throw new NameReferencingFileConverter.FileConversionException("Could not find the filename for " + gameprofile.getName() + " anymore", null); + } else { + return s; + } + } + }); + return true; + } catch (NameReferencingFileConverter.FileConversionException namereferencingfileconverter_fileconversionexception) { + NameReferencingFileConverter.e.error("Conversion failed, please try again later", namereferencingfileconverter_fileconversionexception); + return false; + } + } else { + return true; + } + } + + private static void b(File file) { + if (file.exists()) { + if (!file.isDirectory()) { + throw new NameReferencingFileConverter.FileConversionException("Can\'t create directory " + file.getName() + " in world save directory.", null); + } + } else if (!file.mkdirs()) { + throw new NameReferencingFileConverter.FileConversionException("Can\'t create directory " + file.getName() + " in world save directory.", null); + } + } + + public static boolean a(PropertyManager propertymanager) { + boolean flag = b(propertymanager); + + flag = flag && c(propertymanager); + return flag; + } + + private static boolean b(PropertyManager propertymanager) { + boolean flag = false; + + if (NameReferencingFileConverter.b.exists() && NameReferencingFileConverter.b.isFile()) { + flag = true; + } + + boolean flag1 = false; + + if (NameReferencingFileConverter.a.exists() && NameReferencingFileConverter.a.isFile()) { + flag1 = true; + } + + boolean flag2 = false; + + if (NameReferencingFileConverter.c.exists() && NameReferencingFileConverter.c.isFile()) { + flag2 = true; + } + + boolean flag3 = false; + + if (NameReferencingFileConverter.d.exists() && NameReferencingFileConverter.d.isFile()) { + flag3 = true; + } + + if (!flag && !flag1 && !flag2 && !flag3) { + return true; + } else { + NameReferencingFileConverter.e.warn("**** FAILED TO START THE SERVER AFTER ACCOUNT CONVERSION!"); + NameReferencingFileConverter.e.warn("** please remove the following files and restart the server:"); + if (flag) { + NameReferencingFileConverter.e.warn("* " + NameReferencingFileConverter.b.getName()); + } + + if (flag1) { + NameReferencingFileConverter.e.warn("* " + NameReferencingFileConverter.a.getName()); + } + + if (flag2) { + NameReferencingFileConverter.e.warn("* " + NameReferencingFileConverter.c.getName()); + } + + if (flag3) { + NameReferencingFileConverter.e.warn("* " + NameReferencingFileConverter.d.getName()); + } + + return false; + } + } + + private static boolean c(PropertyManager propertymanager) { + File file = d(propertymanager); + + if (file.exists() && file.isDirectory() && (file.list().length > 0 || !file.delete())) { + NameReferencingFileConverter.e.warn("**** DETECTED OLD PLAYER DIRECTORY IN THE WORLD SAVE"); + NameReferencingFileConverter.e.warn("**** THIS USUALLY HAPPENS WHEN THE AUTOMATIC CONVERSION FAILED IN SOME WAY"); + NameReferencingFileConverter.e.warn("** please restart the server and if the problem persists, remove the directory \'{}\'", new Object[] { file.getPath()}); + return false; + } else { + return true; + } + } + + private static File d(PropertyManager propertymanager) { + String s = propertymanager.getString("level-name", "world"); + File file = new File(MinecraftServer.getServer().server.getWorldContainer(), s); // CraftBukkit - Respect container setting + + return new File(file, "players"); + } + + private static void c(File file) { + File file1 = new File(file.getName() + ".converted"); + + file.renameTo(file1); + } + + private static Date b(String s, Date date) { + Date date1; + + try { + date1 = ExpirableListEntry.a.parse(s); + } catch (ParseException parseexception) { + date1 = date; + } + + return date1; + } + + static class FileConversionException extends RuntimeException { + + private FileConversionException(String s, Throwable throwable) { + super(s, throwable); + } + + private FileConversionException(String s) { + super(s); + } + + FileConversionException(String s, Object object) { + this(s); + } + + FileConversionException(String s, Throwable throwable, Object object) { + this(s, throwable); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/Navigation.java b/azurite-server/src/main/java/net/minecraft/server/Navigation.java new file mode 100644 index 0000000..b05ea37 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/Navigation.java @@ -0,0 +1,210 @@ +package net.minecraft.server; + +public class Navigation extends NavigationAbstract { + + protected PathfinderNormal a; + private boolean f; + + public Navigation(EntityInsentient entityinsentient, World world) { + super(entityinsentient, world); + } + + protected Pathfinder a() { + this.a = new PathfinderNormal(); + this.a.a(true); + return new Pathfinder(this.a); + } + + protected boolean b() { + return this.b.onGround || this.h() && this.o() || this.b.au() && this.b instanceof EntityZombie && this.b.vehicle instanceof EntityChicken; + } + + protected Vec3D c() { + return new Vec3D(this.b.locX, this.p(), this.b.locZ); + } + + private int p() { + if (this.b.V() && this.h()) { + int i = (int) this.b.getBoundingBox().b; + Block block = this.c.getType(new BlockPosition(MathHelper.floor(this.b.locX), i, MathHelper.floor(this.b.locZ))).getBlock(); + int j = 0; + + do { + if (block != Blocks.FLOWING_WATER && block != Blocks.WATER) { + return i; + } + + ++i; + block = this.c.getType(new BlockPosition(MathHelper.floor(this.b.locX), i, MathHelper.floor(this.b.locZ))).getBlock(); + ++j; + } while (j <= 16); + + return (int) this.b.getBoundingBox().b; + } else { + return (int) (this.b.getBoundingBox().b + 0.5D); + } + } + + protected void d() { + super.d(); + if (this.f) { + if (this.c.i(new BlockPosition(MathHelper.floor(this.b.locX), (int) (this.b.getBoundingBox().b + 0.5D), MathHelper.floor(this.b.locZ)))) { + return; + } + + for (int i = 0; i < this.d.d(); ++i) { + PathPoint pathpoint = this.d.a(i); + + if (this.c.i(new BlockPosition(pathpoint.a, pathpoint.b, pathpoint.c))) { + this.d.b(i - 1); + return; + } + } + } + + } + + protected boolean a(Vec3D vec3d, Vec3D vec3d1, int i, int j, int k) { + int l = MathHelper.floor(vec3d.a); + int i1 = MathHelper.floor(vec3d.c); + double d0 = vec3d1.a - vec3d.a; + double d1 = vec3d1.c - vec3d.c; + double d2 = d0 * d0 + d1 * d1; + + if (!(d2 < 1.0E-8D)) { + double d3 = 1.0D / Math.sqrt(d2); + + d0 *= d3; + d1 *= d3; + i += 2; + k += 2; + if (this.a(l, (int) vec3d.b, i1, i, j, k, vec3d, d0, d1)) { + i -= 2; + k -= 2; + double d4 = 1.0D / Math.abs(d0); + double d5 = 1.0D / Math.abs(d1); + double d6 = (double) (l) - vec3d.a; + double d7 = (double) (i1) - vec3d.c; + + if (d0 >= 0.0D) { + ++d6; + } + + if (d1 >= 0.0D) { + ++d7; + } + + d6 /= d0; + d7 /= d1; + int j1 = d0 < 0.0D ? -1 : 1; + int k1 = d1 < 0.0D ? -1 : 1; + int l1 = MathHelper.floor(vec3d1.a); + int i2 = MathHelper.floor(vec3d1.c); + int j2 = l1 - l; + int k2 = i2 - i1; + + do { + if (j2 * j1 <= 0 && k2 * k1 <= 0) { + return true; + } + + if (d6 < d7) { + d6 += d4; + l += j1; + j2 = l1 - l; + } else { + d7 += d5; + i1 += k1; + k2 = i2 - i1; + } + } while (this.a(l, (int) vec3d.b, i1, i, j, k, vec3d, d0, d1)); + + } + } + return false; + } + + private boolean a(int i, int j, int k, int l, int i1, int j1, Vec3D vec3d, double d0, double d1) { + int k1 = i - l / 2; + int l1 = k - j1 / 2; + + if (!this.b(k1, j, l1, l, i1, j1, vec3d, d0, d1)) { + return false; + } else { + for (int i2 = k1; i2 < k1 + l; ++i2) { + for (int j2 = l1; j2 < l1 + j1; ++j2) { + double d2 = (double) i2 + 0.5D - vec3d.a; + double d3 = (double) j2 + 0.5D - vec3d.c; + + if (d2 * d0 + d3 * d1 >= 0.0D) { + Block block = this.c.getType(new BlockPosition(i2, j - 1, j2)).getBlock(); + Material material = block.getMaterial(); + + if (material == Material.AIR) { + return false; + } + + if (material == Material.WATER && !this.b.V()) { + return false; + } + + if (material == Material.LAVA) { + return false; + } + } + } + } + + return true; + } + } + + private boolean b(int i, int j, int k, int l, int i1, int j1, Vec3D vec3d, double d0, double d1) { + for (BlockPosition blockposition : BlockPosition.a(new BlockPosition(i, j, k), new BlockPosition(i + l - 1, j + i1 - 1, k + j1 - 1))) { + double d2 = (double) blockposition.getX() + 0.5D - vec3d.a; + double d3 = (double) blockposition.getZ() + 0.5D - vec3d.c; + + if (d2 * d0 + d3 * d1 >= 0.0D) { + Block block = this.c.getType(blockposition).getBlock(); + + if (!block.b(this.c, blockposition)) { + return false; + } + } + } + + return true; + } + + public void a(boolean flag) { + this.a.c(flag); + } + + public boolean e() { + return this.a.e(); + } + + public void b(boolean flag) { + this.a.b(flag); + } + + public void c(boolean flag) { + this.a.a(flag); + } + + public boolean g() { + return this.a.b(); + } + + public void d(boolean flag) { + this.a.d(flag); + } + + public boolean h() { + return this.a.d(); + } + + public void e(boolean flag) { + this.f = flag; + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/net/minecraft/server/NavigationAbstract.java b/azurite-server/src/main/java/net/minecraft/server/NavigationAbstract.java new file mode 100644 index 0000000..ae8591a --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/NavigationAbstract.java @@ -0,0 +1,279 @@ +package net.minecraft.server; + +import dev.azurite.spigot.utils.WeakChunkCache; +import dev.azurite.spigot.pathsearch.PathSearchJobEntity; +import dev.azurite.spigot.pathsearch.PathSearchJobPosition; +import dev.azurite.spigot.pathsearch.PositionPathSearchType; + +import java.util.Iterator; +import java.util.List; + +public abstract class NavigationAbstract { + + protected EntityInsentient b; + protected World c; + protected PathEntity d; + protected double e; + private final AttributeInstance a; + private int f; + private int g; + private Vec3D h = new Vec3D(0.0D, 0.0D, 0.0D); + private float i = 1.0F; + private final Pathfinder j; + + public NavigationAbstract(EntityInsentient entityinsentient, World world) { + this.b = entityinsentient; + this.c = world; + this.a = entityinsentient.getAttributeInstance(GenericAttributes.FOLLOW_RANGE); + this.j = this.a(); + } + + protected abstract Pathfinder a(); + + public void a(double d0) { + this.e = d0; + } + + public float i() { + return (float) this.a.getValue(); + } + + public final PathEntity a(double d0, double d1, double d2) { + return this.a(new BlockPosition(MathHelper.floor(d0), (int) d1, MathHelper.floor(d2))); + } + + public PathEntity a(BlockPosition blockposition) { + if (!this.b()) { + return null; + } else { + float f = this.i(); + + BlockPosition blockposition1 = new BlockPosition(this.b); + int i = (int) (f + 8.0F); + + BlockPosition lower = blockposition1.a(-i, -i, -i); + BlockPosition upper = blockposition1.a(i, i, i); + + WeakChunkCache chunkcache = new WeakChunkCache(this.c, lower.getX(), lower.getZ(), upper.getX(), upper.getZ(), 0); + return this.j.a(chunkcache, this.b, blockposition, f); + } + } + + public boolean a(double d0, double d1, double d2, double d3) { + PathEntity pathentity = this.a(MathHelper.floor(d0), (int) d1, MathHelper.floor(d2)); + return this.a(pathentity, d3); + } + + public void a(float f) { + this.i = f; + } + + public PathEntity a(Entity entity) { + if (!this.b()) { + return null; + } else { + float f = this.i(); + BlockPosition blockposition = (new BlockPosition(this.b)).up(); + int i = (int) (f + 16.0F); + + BlockPosition lower = blockposition.a(-i, -i, -i); + BlockPosition upper = blockposition.a(i, i, i); + + WeakChunkCache chunkcache = new WeakChunkCache(this.c, lower.getX(), lower.getZ(), upper.getX(), upper.getZ(), 0); + return this.j.a(chunkcache, this.b, entity, f); + } + } + + public boolean a(Entity entity, double d0) { + PathEntity pathentity = this.a(entity); + return pathentity != null && this.a(pathentity, d0); + } + + public boolean a(PathEntity pathentity, double d0) { + if (pathentity == null) { + this.d = null; + return false; + } else { + if (!pathentity.a(this.d)) { + this.d = pathentity; + } + + this.d(); + if (this.d.d() == 0) { + return false; + } else { + this.e = d0; + Vec3D vec3d = this.c(); + + this.g = this.f; + this.h = vec3d; + return true; + } + } + } + + public PathEntity j() { + return this.d; + } + + public void k() { + ++this.f; + if (!this.m()) { + Vec3D vec3d; + + if (this.b()) { + this.l(); + } else if (this.d != null && this.d.e() < this.d.d()) { + vec3d = this.c(); + Vec3D vec3d1 = this.d.a(this.b, this.d.e()); + + if (vec3d.b > vec3d1.b && !this.b.onGround && MathHelper.floor(vec3d.a) == MathHelper.floor(vec3d1.a) && MathHelper.floor(vec3d.c) == MathHelper.floor(vec3d1.c)) { + this.d.c(this.d.e() + 1); + } + } + + if (!this.m()) { + vec3d = this.d.a(this.b); + if (vec3d != null) { + AxisAlignedBB axisalignedbb = (new AxisAlignedBB(vec3d.a, vec3d.b, vec3d.c, vec3d.a, vec3d.b, vec3d.c)).grow(0.5D, 0.5D, 0.5D); + List list = this.c.getCubes(this.b, axisalignedbb.a(0.0D, -1.0D, 0.0D)); + double d0 = -1.0D; + + axisalignedbb = axisalignedbb.c(0.0D, 1.0D, 0.0D); + + AxisAlignedBB axisalignedbb1; + + for (Iterator iterator = list.iterator(); iterator.hasNext(); d0 = axisalignedbb1.b(axisalignedbb, d0)) { + axisalignedbb1 = iterator.next(); + } + + this.b.getControllerMove().a(vec3d.a, vec3d.b + d0, vec3d.c, this.e); + } + } + } + } + + protected void l() { + Vec3D vec3d = this.c(); + int i = this.d.d(); + + for (int j = this.d.e(); j < this.d.d(); ++j) { + if (this.d.a(j).b != (int) vec3d.b) { + i = j; + break; + } + } + + float f = this.b.width * this.b.width * this.i; + + int k; + + for (k = this.d.e(); k < i; ++k) { + Vec3D vec3d1 = this.d.a(this.b, k); + + if (vec3d.distanceSquared(vec3d1) < (double) f) { + this.d.c(k + 1); + } + } + + k = MathHelper.f(this.b.width); + int l = (int) this.b.length + 1; + int i1 = k; + + for (int j1 = i - 1; j1 >= this.d.e(); --j1) { + if (this.a(vec3d, this.d.a(this.b, j1), k, l, i1)) { + this.d.c(j1); + break; + } + } + + this.a(vec3d); + } + + protected void a(Vec3D vec3d) { + if (this.f - this.g > 100) { + if (vec3d.distanceSquared(this.h) < 2.25D) { + this.n(); + } + + this.g = this.f; + this.h = vec3d; + } + + } + + public boolean m() { + return this.d == null || this.d.b(); + } + + public void n() { + this.d = null; + } + + protected abstract Vec3D c(); + + protected abstract boolean b(); + + protected boolean o() { + return this.b.V() || this.b.ab(); + } + + protected void d() { + } + + protected abstract boolean a(Vec3D vec3d, Vec3D vec3d1, int i, int j, int k); + + // Migot start + public EntityInsentient getEntity() { + return this.b; + } + + @Override + public int hashCode() { + return this.b.getUniqueID().hashCode(); + } + + public void cleanUpExpiredSearches() { + } + + public void setSearchResult(PathSearchJobEntity pathSearch) { + } + + public void setSearchResult(PathSearchJobPosition pathSearch) { + } + + public boolean a(double d0, double d1, double d2, double d3, PositionPathSearchType type) { + return this.a(d0, d1, d2, d3); + } + + public PathEntity a(double d0, double d1, double d2, PositionPathSearchType type) { + return this.a(d0, d1, d2); + } + + public WeakChunkCache createChunkCache(boolean forEntitySearch) { + if (this.b()) { + float f = this.i(); + BlockPosition blockposition1 = new BlockPosition(this.b); + int i = (int) (f + (forEntitySearch ? 16.0F : 8.0F)); + + final BlockPosition lower = blockposition1.a(-i, -i, -i); + final BlockPosition upper = blockposition1.a(i, i, i); + + return new WeakChunkCache(this.c, lower.getX(), lower.getZ(), upper.getX(), upper.getZ(), 0); + } + return null; + } + + public PathEntity doPathSearch(WeakChunkCache chunkCache, BlockPosition blockposition) { + if (this.b()) { + float f = this.i(); + return this.j.a(chunkCache, this.b, blockposition, f); + } + return null; + } + + public PathEntity doPathSearch(WeakChunkCache chunkCache, Entity entity) { + return this.doPathSearch(chunkCache, (new BlockPosition(entity)).up()); + } + // Migot end +} diff --git a/azurite-server/src/main/java/net/minecraft/server/NavigationGuardian.java b/azurite-server/src/main/java/net/minecraft/server/NavigationGuardian.java new file mode 100644 index 0000000..b7e8867 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/NavigationGuardian.java @@ -0,0 +1,51 @@ +package net.minecraft.server; + +public class NavigationGuardian extends NavigationAbstract { + + public NavigationGuardian(EntityInsentient entityinsentient, World world) { + super(entityinsentient, world); + } + + protected Pathfinder a() { + return new Pathfinder(new PathfinderWater()); + } + + protected boolean b() { + return this.o(); + } + + protected Vec3D c() { + return new Vec3D(this.b.locX, this.b.locY + (double) this.b.length * 0.5D, this.b.locZ); + } + + protected void l() { + Vec3D vec3d = this.c(); + float f = this.b.width * this.b.width; + byte b0 = 6; + + if (vec3d.distanceSquared(this.d.a(this.b, this.d.e())) < (double) f) { + this.d.a(); + } + + for (int i = Math.min(this.d.e() + b0, this.d.d() - 1); i > this.d.e(); --i) { + Vec3D vec3d1 = this.d.a(this.b, i); + + if (vec3d1.distanceSquared(vec3d) <= 36.0D && this.a(vec3d, vec3d1, 0, 0, 0)) { + this.d.c(i); + break; + } + } + + this.a(vec3d); + } + + protected void d() { + super.d(); + } + + protected boolean a(Vec3D vec3d, Vec3D vec3d1, int i, int j, int k) { + MovingObjectPosition movingobjectposition = this.c.rayTrace(vec3d, new Vec3D(vec3d1.a, vec3d1.b + (double) this.b.length * 0.5D, vec3d1.c), false, true, false); + + return movingobjectposition == null || movingobjectposition.type == MovingObjectPosition.EnumMovingObjectType.MISS; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/NavigationSpider.java b/azurite-server/src/main/java/net/minecraft/server/NavigationSpider.java new file mode 100644 index 0000000..c061f58 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/NavigationSpider.java @@ -0,0 +1,49 @@ +package net.minecraft.server; + +public class NavigationSpider extends Navigation { + + private BlockPosition f; + + public NavigationSpider(EntityInsentient entityinsentient, World world) { + super(entityinsentient, world); + } + + public PathEntity a(BlockPosition blockposition) { + this.f = blockposition; + return super.a(blockposition); + } + + public PathEntity a(Entity entity) { + this.f = new BlockPosition(entity); + return super.a(entity); + } + + public boolean a(Entity entity, double d0) { + PathEntity pathentity = this.a(entity); + + if (pathentity != null) { + return this.a(pathentity, d0); + } else { + this.f = new BlockPosition(entity); + this.e = d0; + return true; + } + } + + public void k() { + if (!this.m()) { + super.k(); + } else { + if (this.f != null) { + double d0 = (double) (this.b.width * this.b.width); + + if (this.b.c(this.f) >= d0 && (this.b.locY <= (double) this.f.getY() || this.b.c(new BlockPosition(this.f.getX(), MathHelper.floor(this.b.locY), this.f.getZ())) >= d0)) { + this.b.getControllerMove().a((double) this.f.getX(), (double) this.f.getY(), (double) this.f.getZ(), this.e); + } else { + this.f = null; + } + } + + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/NetworkManager.java b/azurite-server/src/main/java/net/minecraft/server/NetworkManager.java new file mode 100644 index 0000000..30115a2 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/NetworkManager.java @@ -0,0 +1,354 @@ +package net.minecraft.server; + +import com.mojang.authlib.properties.Property; +import com.velocitypowered.natives.compression.VelocityCompressor; +import com.velocitypowered.natives.util.Natives; +import dev.azurite.spigot.Azurite; +import dev.azurite.spigot.api.protocol.PacketHandler; +import dev.azurite.spigot.optimizations.FastNetworkManager; +import dev.azurite.spigot.optimizations.ObjectMapList; +import io.netty.channel.*; +import io.netty.channel.local.LocalChannel; +import io.netty.channel.local.LocalServerChannel; +import io.netty.handler.timeout.TimeoutException; +import io.netty.util.AttributeKey; +import io.netty.util.ReferenceCountUtil; +import io.netty.util.concurrent.Future; +import io.netty.util.concurrent.GenericFutureListener; +import org.apache.commons.lang3.ArrayUtils; +import org.apache.commons.lang3.Validate; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import javax.crypto.SecretKey; +import java.net.SocketAddress; +import java.util.List; +import java.util.UUID; + +// Vortex - Removed useless packet queue +public class NetworkManager extends ChannelInboundHandlerAdapter { + + public static final AttributeKey c = AttributeKey.valueOf("protocol"); + + private static final Logger g = LogManager.getLogger(); + public Channel channel; + public SocketAddress l; + public UUID spoofedUUID; + public Property[] spoofedProfile; + public boolean preparing = true; + private PacketListener m; + private IChatBaseComponent n; + private boolean p; + + // Azurite - Faster entity tracker methods + public final FastNetworkManager fastNetworkManager; + + // Azurite - optimize protocol attribute by just not using it, we have to keep reference to the packet encoder & decoder ourselves because viaversion wraps around it in the pipeline + private final PacketEncoder encoder; + private final PacketDecoder decoder; + private EnumProtocol currentProtocol; + + // Azurite - Constructor for plugin support that create fake network managers + public NetworkManager(EnumProtocolDirection h) { + this.fastNetworkManager = new FastNetworkManager(this); + this.encoder = new PacketEncoder(); // These need to be created as the plugins wouldn't + this.decoder = new PacketDecoder(); + } + + public NetworkManager(PacketEncoder encoder, PacketDecoder decoder) { + this.fastNetworkManager = new FastNetworkManager(this); + this.encoder = encoder; + this.decoder = decoder; + } + + private void setProtocol(EnumProtocol protocol) { + this.currentProtocol = protocol; + + decoder.setServerBoundConstructors(protocol.fastEnumProtocol.suppliers); + + channel.attr(c).set(protocol); // This is kept for legacy purposes if any plugin uses it + channel.config().setAutoRead(true); + } + + private void writeAndFlush(EnumProtocol protocolSwitch, Packet packet, GenericFutureListener>[] agenericfuturelistener) { + if (protocolSwitch != null) { + setProtocol(protocolSwitch); + } + ChannelFuture future = channel.writeAndFlush(packet); + if (agenericfuturelistener != null) { + future.addListeners(agenericfuturelistener); + } + future.addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE); + } + + public void channelActive(ChannelHandlerContext channelhandlercontext) throws Exception { + super.channelActive(channelhandlercontext); + + channel = channelhandlercontext.channel(); + l = channel.remoteAddress(); + preparing = false; + try { + a(EnumProtocol.HANDSHAKING); + } catch (Throwable throwable) { + throwable.printStackTrace(); + } + } + + public void a(EnumProtocol enumprotocol) { + this.setProtocol(enumprotocol); + } + + public void channelInactive(ChannelHandlerContext channelhandlercontext) { + close(new ChatMessage("disconnect.endOfStream")); + } + + public void exceptionCaught(ChannelHandlerContext channelhandlercontext, Throwable throwable) { + ChatMessage chatmessage; + if (throwable instanceof TimeoutException) { + chatmessage = new ChatMessage("disconnect.timeout"); + } else { + chatmessage = new ChatMessage("disconnect.genericReason", "Internal Exception: " + throwable); + } + close(chatmessage); + } + + protected void a(ChannelHandlerContext channelhandlercontext, Packet packet) throws Exception { + if (channel.isActive()) { + try { + if (shouldReceive(packet)) { + packet.a(m); + } + } catch (CancelledPacketHandleException ignored) { + } + } + } + + public void a(PacketListener packetlistener) { + Validate.notNull(packetlistener, "packetListener"); + m = packetlistener; + } + + public void handle(Packet packet) { + if (channel != null && channel.isActive()) { + a(packet, null); + } + } + + // Azurite start + public void handle(List> packets) { + if (channel != null && channel.isActive()) { + channel.eventLoop().execute(() -> { + for (Packet packet : packets) { + if (!shouldSend(packet)) { + continue; + } + ChannelFuture future = channel.write(packet); + future.addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE); + } + }); + } + } + + public void writePacketLazily(Packet packet) { + if (shouldSend(packet)) { + fastNetworkManager.writePacketLazily(channel, packet); + } + } + + public void flushAndWriteCurrentQueue() { + fastNetworkManager.flushAndWriteCurrentQueue(channel); + } + + public boolean shouldSend(Packet packet) { + ObjectMapList packetHandlers = Azurite.getInstance().getPacketHandlers(); + if (packetHandlers.isEmpty()) { + return true; + } + if (m instanceof PlayerConnection) { + PlayerConnection playerConnection = (PlayerConnection) m; + for (int p = 0; p < packetHandlers.count; p++) { + PacketHandler handler = packetHandlers.elements[p]; + if (!handler.handleSentPacket(playerConnection, packet)) { + return false; + } + } + } + return true; + } + + public boolean shouldReceive(Packet packet) { + ObjectMapList packetHandlers = Azurite.getInstance().getPacketHandlers(); + if (packetHandlers.isEmpty()) { + return true; + } + if (m instanceof PlayerConnection) { + PlayerConnection playerConnection = (PlayerConnection) m; + for (int p = 0; p < packetHandlers.count; p++) { + PacketHandler handler = packetHandlers.elements[p]; + if (!handler.handleReceivedPacket(playerConnection, packet)) { + return false; + } + } + } + return true; + } + // Azurite end + + public void a(Packet packet, GenericFutureListener> genericfuturelistener, GenericFutureListener>... agenericfuturelistener) { + if (channel != null && channel.isActive()) { + a(packet, ArrayUtils.add(agenericfuturelistener, 0, genericfuturelistener)); + } + } + + // Vortex - Avoid checking protocol & inEventLoop + public void a(Packet packet, GenericFutureListener>[] + agenericfuturelistener) { + EnumProtocol protocolForPacket = EnumProtocol.a(packet); + EnumProtocol switchProtocol; + + if (protocolForPacket != currentProtocol) { + switchProtocol = protocolForPacket; + channel.config().setAutoRead(false); + } else { + switchProtocol = null; + } + + if (channel.eventLoop().inEventLoop()) { + writeAndFlush(switchProtocol, packet, agenericfuturelistener); + } else { + channel.eventLoop().execute(() -> writeAndFlush(switchProtocol, packet, agenericfuturelistener)); + } + } + + public void a() { + if (m instanceof IUpdatePlayerListBox) { + ((IUpdatePlayerListBox) m).c(); + } + } + + public void close(IChatBaseComponent ichatbasecomponent) { + preparing = false; + if (channel != null && channel.isActive()) { + channel.close(); + n = ichatbasecomponent; + } + } + + public void a(SecretKey secretkey) { + ChannelPipeline pp = channel.pipeline(); + pp.addBefore("splitter", "decrypt", new PacketDecrypter(MinecraftEncryption.a(2, secretkey))); + pp.addBefore("prepender", "encrypt", new PacketEncrypter(MinecraftEncryption.a(1, secretkey))); + } + + private static final boolean JAVA_11 = Double.parseDouble(System.getProperty("java.specification.version")) >= 11.0; + + public void a(int compressionThreshold) { + if (compressionThreshold >= 0) { + VelocityCompressor compressor = Natives.compress.get().create(-1); // Paper + if (this.channel.pipeline().get("decompress") instanceof PacketDecompressor) { + ((PacketDecompressor) this.channel.pipeline().get("decompress")).setThreshold(compressionThreshold); + } else { + this.channel.pipeline().addBefore("decoder", "decompress", new PacketDecompressor(compressor, compressionThreshold)); // Paper + } + + if (this.channel.pipeline().get("compress") instanceof PacketCompressor) { + ((PacketCompressor) this.channel.pipeline().get("compress")).setThreshold(compressionThreshold); // PandaSpigot - Fix wrong handler name used for cast to PacketCompressor + } else { + this.channel.pipeline().addBefore("encoder", "compress", new PacketCompressor(compressor, compressionThreshold)); // Paper + } + } else { + if (this.channel.pipeline().get("decompress") instanceof PacketDecompressor) { + this.channel.pipeline().remove("decompress"); + } + + if (this.channel.pipeline().get("compress") instanceof PacketCompressor) { + this.channel.pipeline().remove("compress"); + } + } + } + + public void l() { + if (channel != null && !channel.isActive()) { + if (!p) { + p = true; + if (n != null) { + m.a(n); + } else if (m != null) { + m.a(new ChatComponentText("Disconnected")); + } + } else { + g.warn("handleDisconnection() called twice"); + } + } + } + + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) { + try { + if (!channel.isActive()) { + return; + } + + if (msg instanceof Packet) { + try { + Packet packet = (Packet) msg; + + if (!shouldReceive(packet)) { + return; + } + + boolean firstNettyThread = packet instanceof PacketPlayInKeepAlive + || packet instanceof PacketPlayInChat + || packet instanceof PacketStatusInPing + || packet instanceof PacketStatusInStart + || packet instanceof PacketLoginInStart + || packet instanceof PacketLoginInEncryptionBegin + || packet instanceof PacketHandshakingInSetProtocol; + + if (firstNettyThread) { + packet.a(m); + } else { + MinecraftServer.getServer().postToTasks(() -> { + packet.a(m); + }); + } + } catch (CancelledPacketHandleException ignored) { + } + } + } finally { + ReferenceCountUtil.release(msg); + } + } + + public boolean c() { + return channel instanceof LocalChannel || channel instanceof LocalServerChannel; + } + + public boolean g() { + return channel != null && channel.isActive(); + } + + public boolean h() { + return channel == null; + } + + public PacketListener getPacketListener() { + return m; + } + + public IChatBaseComponent j() { + return n; + } + + public void k() { + channel.config().setAutoRead(false); + } + + public SocketAddress getSocketAddress() { + return l; + } + + public SocketAddress getRawAddress() { + return channel.remoteAddress(); + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/net/minecraft/server/NextTickListEntry.java b/azurite-server/src/main/java/net/minecraft/server/NextTickListEntry.java new file mode 100644 index 0000000..7faa522 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/NextTickListEntry.java @@ -0,0 +1,61 @@ +package net.minecraft.server; + +import org.jetbrains.annotations.NotNull; + +public class NextTickListEntry implements Comparable { + + private static long d; + private final Block e; + public final BlockPosition a; + public long b; + public int c; + private long f; + + public NextTickListEntry(BlockPosition blockposition, Block block) { + if (blockposition instanceof BlockPosition.MutableBlockPosition) { + throw new IllegalArgumentException("Next Tick list entry should not have mutable block position."); + } + this.f = NextTickListEntry.d++; + this.a = blockposition; + this.e = block; + } + + public boolean equals(Object object) { + if (!(object instanceof NextTickListEntry)) { + return false; + } else { + NextTickListEntry nextticklistentry = (NextTickListEntry) object; + return this.a.equals(nextticklistentry.a) && Block.a(this.e, nextticklistentry.e); + } + } + + public int hashCode() { + return this.a.hashCode(); + } + + public NextTickListEntry a(long i) { + this.b = i; + return this; + } + + public void a(int i) { + this.c = i; + } + + public int a(NextTickListEntry nextticklistentry) { + return this.b < nextticklistentry.b ? -1 : (this.b > nextticklistentry.b ? 1 : (this.c != nextticklistentry.c ? this.c - nextticklistentry.c : (this.f < nextticklistentry.f ? -1 : (this.f > nextticklistentry.f ? 1 : 0)))); + } + + public String toString() { + return Block.getId(this.e) + ": " + this.a + ", " + this.b + ", " + this.c + ", " + this.f; + } + + public Block a() { + return this.e; + } + + @Override + public int compareTo(@NotNull NextTickListEntry object) { + return this.a(object); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/NibbleArray.java b/azurite-server/src/main/java/net/minecraft/server/NibbleArray.java new file mode 100644 index 0000000..0fddc8e --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/NibbleArray.java @@ -0,0 +1,45 @@ +package net.minecraft.server; + +public class NibbleArray { + + private final byte[] a; + + public NibbleArray() { + this.a = new byte[2048]; + } + + public NibbleArray(byte[] abyte) { + this.a = abyte; + if (abyte.length != 2048) { + throw new IllegalArgumentException("ChunkNibbleArrays should be 2048 bytes not: " + abyte.length); + } + } + + public int a(int i, int j, int k) { + return this.a(j << 8 | k << 4 | i); + } + + public void a(int i, int j, int k, int l) { + this.a(j << 8 | k << 4 | i, l); + } + + public int a(int i) { + int j = i >> 1; + + return this.a[j] >> ((i & 1) << 2) & 15; + } + + public void a(int i, int j) { + int k = i >> 1; + int shift = (i & 1) << 2; + this.a[k] = (byte) (this.a[k] & ~(15 << shift) | (j & 15) << shift); + } + + public byte[] a() { + return this.a; + } + + public NibbleArray clone() { + return new NibbleArray(this.a.clone()); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/NoiseGenerator.java b/azurite-server/src/main/java/net/minecraft/server/NoiseGenerator.java new file mode 100644 index 0000000..07827ed --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/NoiseGenerator.java @@ -0,0 +1,6 @@ +package net.minecraft.server; + +public abstract class NoiseGenerator { + + public NoiseGenerator() {} +} diff --git a/azurite-server/src/main/java/net/minecraft/server/NoiseGenerator3.java b/azurite-server/src/main/java/net/minecraft/server/NoiseGenerator3.java new file mode 100644 index 0000000..3fe6edf --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/NoiseGenerator3.java @@ -0,0 +1,55 @@ +package net.minecraft.server; + +import java.util.Arrays; +import java.util.Random; + +public class NoiseGenerator3 { + + private final NoiseGenerator3Handler[] a; + private final int b; + + public NoiseGenerator3(Random random, int i) { + this.b = i; + this.a = new NoiseGenerator3Handler[i]; + + for (int j = 0; j < i; ++j) { + this.a[j] = new NoiseGenerator3Handler(random); + } + + } + + public double a(double d0, double d1) { + double d2 = 0.0D; + double d3 = 1.0D; + + for (int i = 0; i < this.b; ++i) { + d2 += this.a[i].a(d0 * d3, d1 * d3) / d3; + d3 /= 2.0D; + } + + return d2; + } + + public double[] a(double[] adouble, double d0, double d1, int i, int j, double d2, double d3, double d4) { + return this.a(adouble, d0, d1, i, j, d2, d3, d4, 0.5D); + } + + public double[] a(double[] adouble, double d0, double d1, int i, int j, double d2, double d3, double d4, double d5) { + if (adouble != null && adouble.length >= i * j) { + Arrays.fill(adouble, 0.0D); + } else { + adouble = new double[i * j]; + } + + double d6 = 1.0D; + double d7 = 1.0D; + + for (int l = 0; l < this.b; ++l) { + this.a[l].a(adouble, d0, d1, i, j, d2 * d7 * d6, d3 * d7 * d6, 0.55D / d6); + d7 *= d4; + d6 *= d5; + } + + return adouble; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/NoiseGenerator3Handler.java b/azurite-server/src/main/java/net/minecraft/server/NoiseGenerator3Handler.java new file mode 100644 index 0000000..a853923 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/NoiseGenerator3Handler.java @@ -0,0 +1,187 @@ +package net.minecraft.server; + +import java.util.Random; + +public class NoiseGenerator3Handler { + + private static final int[][] e = {{1, 1, 0}, {-1, 1, 0}, {1, -1, 0}, {-1, -1, 0}, {1, 0, 1}, {-1, 0, 1}, {1, 0, -1}, {-1, 0, -1}, {0, 1, 1}, {0, -1, 1}, {0, 1, -1}, {0, -1, -1}}; + public static final double a = Math.sqrt(3.0D); + private final int[] f; + public double b; + public double c; + public double d; + private static final double g = 0.5D * (a - 1.0D); + private static final double h = (3.0D - a) / 6.0D; + + public NoiseGenerator3Handler() { + this(new Random()); + } + + public NoiseGenerator3Handler(Random random) { + this.f = new int[512]; + this.b = random.nextDouble() * 256.0D; + this.c = random.nextDouble() * 256.0D; + this.d = random.nextDouble() * 256.0D; + + int i; + + for (i = 0; i < 256; this.f[i] = i++) { + } + + for (i = 0; i < 256; ++i) { + int j = random.nextInt(256 - i) + i; + int k = this.f[i]; + + this.f[i] = this.f[j]; + this.f[j] = k; + this.f[i + 256] = this.f[i]; + } + + } + + private static int a(double d0) { + return d0 > 0.0D ? (int) d0 : (int) d0 - 1; + } + + private static double a(int[] aint, double d0, double d1) { + return (double) aint[0] * d0 + (double) aint[1] * d1; + } + + public double a(double d0, double d1) { + double d2 = 0.5D * (a - 1.0D); + double d3 = (d0 + d1) * d2; + int i = a(d0 + d3); + int j = a(d1 + d3); + double d4 = (3.0D - a) / 6.0D; + double d5 = (double) (i + j) * d4; + double d6 = (double) i - d5; + double d7 = (double) j - d5; + double d8 = d0 - d6; + double d9 = d1 - d7; + byte b0; + byte b1; + + if (d8 > d9) { + b0 = 1; + b1 = 0; + } else { + b0 = 0; + b1 = 1; + } + + double d10 = d8 - (double) b0 + d4; + double d11 = d9 - (double) b1 + d4; + double d12 = d8 - 1.0D + 2.0D * d4; + double d13 = d9 - 1.0D + 2.0D * d4; + int k = i & 255; + int l = j & 255; + int i1 = this.f[k + this.f[l]] % 12; + int j1 = this.f[k + b0 + this.f[l + b1]] % 12; + int k1 = this.f[k + 1 + this.f[l + 1]] % 12; + double d14 = 0.5D - d8 * d8 - d9 * d9; + double d15; + + if (d14 < 0.0D) { + d15 = 0.0D; + } else { + d14 *= d14; + d15 = d14 * d14 * a(e[i1], d8, d9); + } + + double d16 = 0.5D - d10 * d10 - d11 * d11; + double d17; + + if (d16 < 0.0D) { + d17 = 0.0D; + } else { + d16 *= d16; + d17 = d16 * d16 * a(e[j1], d10, d11); + } + + double d18 = 0.5D - d12 * d12 - d13 * d13; + double d19; + + if (d18 < 0.0D) { + d19 = 0.0D; + } else { + d18 *= d18; + d19 = d18 * d18 * a(e[k1], d12, d13); + } + + return 70.0D * (d15 + d17 + d19); + } + + public void a(double[] adouble, double d0, double d1, int i, int j, double d2, double d3, double d4) { + int k = 0; + + for (int l = 0; l < j; ++l) { + double d5 = (d1 + (double) l) * d3 + this.c; + + for (int i1 = 0; i1 < i; ++i1) { + double d6 = (d0 + (double) i1) * d2 + this.b; + double d7 = (d6 + d5) * g; + int j1 = a(d6 + d7); + int k1 = a(d5 + d7); + double d8 = (double) (j1 + k1) * h; + double d9 = (double) j1 - d8; + double d10 = (double) k1 - d8; + double d11 = d6 - d9; + double d12 = d5 - d10; + byte b0; + byte b1; + + if (d11 > d12) { + b0 = 1; + b1 = 0; + } else { + b0 = 0; + b1 = 1; + } + + double d13 = d11 - (double) b0 + h; + double d14 = d12 - (double) b1 + h; + double d15 = d11 - 1.0D + 2.0D * h; + double d16 = d12 - 1.0D + 2.0D * h; + int l1 = j1 & 255; + int i2 = k1 & 255; + int j2 = this.f[l1 + this.f[i2]] % 12; + int k2 = this.f[l1 + b0 + this.f[i2 + b1]] % 12; + int l2 = this.f[l1 + 1 + this.f[i2 + 1]] % 12; + double d17 = 0.5D - d11 * d11 - d12 * d12; + double d18; + + if (d17 < 0.0D) { + d18 = 0.0D; + } else { + d17 *= d17; + d18 = d17 * d17 * a(e[j2], d11, d12); + } + + double d19 = 0.5D - d13 * d13 - d14 * d14; + double d20; + + if (d19 < 0.0D) { + d20 = 0.0D; + } else { + d19 *= d19; + d20 = d19 * d19 * a(e[k2], d13, d14); + } + + double d21 = 0.5D - d15 * d15 - d16 * d16; + double d22; + + if (d21 < 0.0D) { + d22 = 0.0D; + } else { + d21 *= d21; + d22 = d21 * d21 * a(e[l2], d15, d16); + } + + int i3 = k++; + + adouble[i3] += 70.0D * (d18 + d20 + d22) * d4; + } + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/NoiseGeneratorOctaves.java b/azurite-server/src/main/java/net/minecraft/server/NoiseGeneratorOctaves.java new file mode 100644 index 0000000..f584ff6 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/NoiseGeneratorOctaves.java @@ -0,0 +1,53 @@ +package net.minecraft.server; + +import java.util.Arrays; +import java.util.Random; + +public class NoiseGeneratorOctaves { + + private final NoiseGeneratorPerlin[] a; + private final int b; + + public NoiseGeneratorOctaves(Random random, int i) { + this.b = i; + this.a = new NoiseGeneratorPerlin[i]; + + for (int j = 0; j < i; ++j) { + this.a[j] = new NoiseGeneratorPerlin(random); + } + + } + + public double[] a(double[] adouble, int i, int j, int k, int l, int i1, int j1, double d0, double d1, double d2) { + if (adouble == null) { + adouble = new double[l * i1 * j1]; + } else { + Arrays.fill(adouble, 0.0D); + } + + double d3 = 1.0D; + + for (int l1 = 0; l1 < this.b; ++l1) { + double d4 = (double) i * d3 * d0; + double d5 = (double) j * d3 * d1; + double d6 = (double) k * d3 * d2; + long i2 = MathHelper.d(d4); + long j2 = MathHelper.d(d6); + + d4 -= (double) i2; + d6 -= (double) j2; + i2 %= 16777216L; + j2 %= 16777216L; + d4 += (double) i2; + d6 += (double) j2; + this.a[l1].a(adouble, d4, d5, d6, l, i1, j1, d0 * d3, d1 * d3, d2 * d3, d3); + d3 /= 2.0D; + } + + return adouble; + } + + public double[] a(double[] adouble, int i, int j, int k, int l, double d0, double d1, double d2) { + return this.a(adouble, i, 10, j, k, 1, l, d0, 1.0D, d1); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/NoiseGeneratorPerlin.java b/azurite-server/src/main/java/net/minecraft/server/NoiseGeneratorPerlin.java new file mode 100644 index 0000000..ea66c91 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/NoiseGeneratorPerlin.java @@ -0,0 +1,193 @@ +package net.minecraft.server; + +import java.util.Random; + +public class NoiseGeneratorPerlin { + + private final int[] d; + public double a; + public double b; + public double c; + private static final double[] e = {1.0D, -1.0D, 1.0D, -1.0D, 1.0D, -1.0D, 1.0D, -1.0D, 0.0D, 0.0D, 0.0D, 0.0D, 1.0D, 0.0D, -1.0D, 0.0D}; + private static final double[] f = {1.0D, 1.0D, -1.0D, -1.0D, 0.0D, 0.0D, 0.0D, 0.0D, 1.0D, -1.0D, 1.0D, -1.0D, 1.0D, -1.0D, 1.0D, -1.0D}; + private static final double[] g = {0.0D, 0.0D, 0.0D, 0.0D, 1.0D, 1.0D, -1.0D, -1.0D, 1.0D, 1.0D, -1.0D, -1.0D, 0.0D, 1.0D, 0.0D, -1.0D}; + private static final double[] h = {1.0D, -1.0D, 1.0D, -1.0D, 1.0D, -1.0D, 1.0D, -1.0D, 0.0D, 0.0D, 0.0D, 0.0D, 1.0D, 0.0D, -1.0D, 0.0D}; + private static final double[] i = {0.0D, 0.0D, 0.0D, 0.0D, 1.0D, 1.0D, -1.0D, -1.0D, 1.0D, 1.0D, -1.0D, -1.0D, 0.0D, 1.0D, 0.0D, -1.0D}; + + public NoiseGeneratorPerlin() { + this(new Random()); + } + + public NoiseGeneratorPerlin(Random random) { + this.d = new int[512]; + this.a = random.nextDouble() * 256.0D; + this.b = random.nextDouble() * 256.0D; + this.c = random.nextDouble() * 256.0D; + + int i; + + for (i = 0; i < 256; this.d[i] = i++) { + } + + for (i = 0; i < 256; ++i) { + int j = random.nextInt(256 - i) + i; + int k = this.d[i]; + + this.d[i] = this.d[j]; + this.d[j] = k; + this.d[i + 256] = this.d[i]; + } + + } + + public final double b(double d0, double d1, double d2) { + return d1 + d0 * (d2 - d1); + } + + public final double a(int i, double d0, double d1) { + int j = i & 15; + + return h[j] * d0 + NoiseGeneratorPerlin.i[j] * d1; + } + + public final double a(int i, double d0, double d1, double d2) { + int j = i & 15; + + return e[j] * d0 + f[j] * d1 + g[j] * d2; + } + + public void a(double[] adouble, double d0, double d1, double d2, int i, int j, int k, double d3, double d4, double d5, double d6) { + int l; + int i1; + double d7; + double d8; + int j1; + double d9; + int k1; + int l1; + double d10; + int i2; + int j2; + + if (j == 1) { + double d11; + double d12; + + i2 = 0; + double d13 = 1.0D / d6; + + for (int k2 = 0; k2 < i; ++k2) { + d7 = d0 + (double) k2 * d3 + this.a; + int l2 = (int) d7; + + if (d7 < (double) l2) { + --l2; + } + + int i3 = l2 & 255; + + d7 -= l2; + d8 = d7 * d7 * d7 * (d7 * (d7 * 6.0D - 15.0D) + 10.0D); + + for (j1 = 0; j1 < k; ++j1) { + d9 = d2 + (double) j1 * d5 + this.c; + k1 = (int) d9; + if (d9 < (double) k1) { + --k1; + } + + l1 = k1 & 255; + d9 -= k1; + d10 = d9 * d9 * d9 * (d9 * (d9 * 6.0D - 15.0D) + 10.0D); + l = this.d[i3]; + int j3 = this.d[l] + l1; + int k3 = this.d[i3 + 1]; + + i1 = this.d[k3] + l1; + d11 = this.b(d8, this.a(this.d[j3], d7, d9), this.a(this.d[i1], d7 - 1.0D, 0.0D, d9)); + d12 = this.b(d8, this.a(this.d[j3 + 1], d7, 0.0D, d9 - 1.0D), this.a(this.d[i1 + 1], d7 - 1.0D, 0.0D, d9 - 1.0D)); + double d14 = this.b(d10, d11, d12); + + j2 = i2++; + adouble[j2] += d14 * d13; + } + } + + } else { + l = 0; + double d15 = 1.0D / d6; + + i1 = -1; + double d16 = 0.0D; + + d7 = 0.0D; + double d17 = 0.0D; + + d8 = 0.0D; + + for (j1 = 0; j1 < i; ++j1) { + d9 = d0 + (double) j1 * d3 + this.a; + k1 = (int) d9; + if (d9 < (double) k1) { + --k1; + } + + l1 = k1 & 255; + d9 -= k1; + d10 = d9 * d9 * d9 * (d9 * (d9 * 6.0D - 15.0D) + 10.0D); + + for (int l3 = 0; l3 < k; ++l3) { + double d18 = d2 + (double) l3 * d5 + this.c; + int i4 = (int) d18; + + if (d18 < (double) i4) { + --i4; + } + + int j4 = i4 & 255; + + d18 -= i4; + double d19 = d18 * d18 * d18 * (d18 * (d18 * 6.0D - 15.0D) + 10.0D); + + for (int k4 = 0; k4 < j; ++k4) { + double d20 = d1 + (double) k4 * d4 + this.b; + int l4 = (int) d20; + + if (d20 < (double) l4) { + --l4; + } + + int i5 = l4 & 255; + + d20 -= l4; + double d21 = d20 * d20 * d20 * (d20 * (d20 * 6.0D - 15.0D) + 10.0D); + + if (k4 == 0 || i5 != i1) { + i1 = i5; + int j5 = this.d[l1] + i5; + int k5 = this.d[j5] + j4; + int l5 = this.d[j5 + 1] + j4; + int i6 = this.d[l1 + 1] + i5; + + i2 = this.d[i6] + j4; + int j6 = this.d[i6 + 1] + j4; + + d16 = this.b(d10, this.a(this.d[k5], d9, d20, d18), this.a(this.d[i2], d9 - 1.0D, d20, d18)); + d7 = this.b(d10, this.a(this.d[l5], d9, d20 - 1.0D, d18), this.a(this.d[j6], d9 - 1.0D, d20 - 1.0D, d18)); + d17 = this.b(d10, this.a(this.d[k5 + 1], d9, d20, d18 - 1.0D), this.a(this.d[i2 + 1], d9 - 1.0D, d20, d18 - 1.0D)); + d8 = this.b(d10, this.a(this.d[l5 + 1], d9, d20 - 1.0D, d18 - 1.0D), this.a(this.d[j6 + 1], d9 - 1.0D, d20 - 1.0D, d18 - 1.0D)); + } + + double d22 = this.b(d21, d16, d7); + double d23 = this.b(d21, d17, d8); + double d24 = this.b(d19, d22, d23); + + j2 = l++; + adouble[j2] += d24 * d15; + } + } + } + + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/OldChunkLoader.java b/azurite-server/src/main/java/net/minecraft/server/OldChunkLoader.java new file mode 100644 index 0000000..670d626 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/OldChunkLoader.java @@ -0,0 +1,145 @@ +package net.minecraft.server; + +public class OldChunkLoader { + + public static OldChunkLoader.OldChunk a(NBTTagCompound nbttagcompound) { + int i = nbttagcompound.getInt("xPos"); + int j = nbttagcompound.getInt("zPos"); + OldChunkLoader.OldChunk oldchunkloader_oldchunk = new OldChunkLoader.OldChunk(i, j); + + oldchunkloader_oldchunk.g = nbttagcompound.getByteArray("Blocks"); + oldchunkloader_oldchunk.f = new OldNibbleArray(nbttagcompound.getByteArray("Data"), 7); + oldchunkloader_oldchunk.e = new OldNibbleArray(nbttagcompound.getByteArray("SkyLight"), 7); + oldchunkloader_oldchunk.d = new OldNibbleArray(nbttagcompound.getByteArray("BlockLight"), 7); + oldchunkloader_oldchunk.c = nbttagcompound.getByteArray("HeightMap"); + oldchunkloader_oldchunk.b = nbttagcompound.getBoolean("TerrainPopulated"); + oldchunkloader_oldchunk.h = nbttagcompound.getList("Entities", 10); + oldchunkloader_oldchunk.i = nbttagcompound.getList("TileEntities", 10); + oldchunkloader_oldchunk.j = nbttagcompound.getList("TileTicks", 10); + + try { + oldchunkloader_oldchunk.a = nbttagcompound.getLong("LastUpdate"); + } catch (ClassCastException classcastexception) { + oldchunkloader_oldchunk.a = (long) nbttagcompound.getInt("LastUpdate"); + } + + return oldchunkloader_oldchunk; + } + + public static void a(OldChunkLoader.OldChunk oldchunkloader_oldchunk, NBTTagCompound nbttagcompound, WorldChunkManager worldchunkmanager) { + nbttagcompound.setInt("xPos", oldchunkloader_oldchunk.k); + nbttagcompound.setInt("zPos", oldchunkloader_oldchunk.l); + nbttagcompound.setLong("LastUpdate", oldchunkloader_oldchunk.a); + int[] aint = new int[oldchunkloader_oldchunk.c.length]; + + for (int i = 0; i < oldchunkloader_oldchunk.c.length; ++i) { + aint[i] = oldchunkloader_oldchunk.c[i]; + } + + nbttagcompound.setIntArray("HeightMap", aint); + nbttagcompound.setBoolean("TerrainPopulated", oldchunkloader_oldchunk.b); + NBTTagList nbttaglist = new NBTTagList(); + + int j; + int k; + + for (int l = 0; l < 8; ++l) { + boolean flag = true; + + for (j = 0; j < 16 && flag; ++j) { + k = 0; + + while (k < 16 && flag) { + int i1 = 0; + + while (true) { + if (i1 < 16) { + int j1 = j << 11 | i1 << 7 | k + (l << 4); + byte b0 = oldchunkloader_oldchunk.g[j1]; + + if (b0 == 0) { + ++i1; + continue; + } + + flag = false; + } + + ++k; + break; + } + } + } + + if (!flag) { + byte[] abyte = new byte[4096]; + NibbleArray nibblearray = new NibbleArray(); + NibbleArray nibblearray1 = new NibbleArray(); + NibbleArray nibblearray2 = new NibbleArray(); + + for (int k1 = 0; k1 < 16; ++k1) { + for (int l1 = 0; l1 < 16; ++l1) { + for (int i2 = 0; i2 < 16; ++i2) { + int j2 = k1 << 11 | i2 << 7 | l1 + (l << 4); + byte b1 = oldchunkloader_oldchunk.g[j2]; + + abyte[l1 << 8 | i2 << 4 | k1] = (byte) (b1 & 255); + nibblearray.a(k1, l1, i2, oldchunkloader_oldchunk.f.a(k1, l1 + (l << 4), i2)); + nibblearray1.a(k1, l1, i2, oldchunkloader_oldchunk.e.a(k1, l1 + (l << 4), i2)); + nibblearray2.a(k1, l1, i2, oldchunkloader_oldchunk.d.a(k1, l1 + (l << 4), i2)); + } + } + } + + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + + nbttagcompound1.setByte("Y", (byte) (l & 255)); + nbttagcompound1.setByteArray("Blocks", abyte); + nbttagcompound1.setByteArray("Data", nibblearray.a()); + nbttagcompound1.setByteArray("SkyLight", nibblearray1.a()); + nbttagcompound1.setByteArray("BlockLight", nibblearray2.a()); + nbttaglist.add(nbttagcompound1); + } + } + + nbttagcompound.set("Sections", nbttaglist); + byte[] abyte1 = new byte[256]; + BlockPosition.MutableBlockPosition blockposition_mutableblockposition = new BlockPosition.MutableBlockPosition(); + + for (j = 0; j < 16; ++j) { + for (k = 0; k < 16; ++k) { + blockposition_mutableblockposition.c(oldchunkloader_oldchunk.k << 4 | j, 0, oldchunkloader_oldchunk.l << 4 | k); + abyte1[k << 4 | j] = (byte) (worldchunkmanager.getBiome(blockposition_mutableblockposition, BiomeBase.ad).id & 255); + } + } + + nbttagcompound.setByteArray("Biomes", abyte1); + nbttagcompound.set("Entities", oldchunkloader_oldchunk.h); + nbttagcompound.set("TileEntities", oldchunkloader_oldchunk.i); + if (oldchunkloader_oldchunk.j != null) { + nbttagcompound.set("TileTicks", oldchunkloader_oldchunk.j); + } + + } + + public static class OldChunk { + + public long a; + public boolean b; + public byte[] c; + public OldNibbleArray d; + public OldNibbleArray e; + public OldNibbleArray f; + public byte[] g; + public NBTTagList h; + public NBTTagList i; + public NBTTagList j; + public final int k; + public final int l; + + public OldChunk(int i, int j) { + this.k = i; + this.l = j; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/OldNibbleArray.java b/azurite-server/src/main/java/net/minecraft/server/OldNibbleArray.java new file mode 100644 index 0000000..ed090ae --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/OldNibbleArray.java @@ -0,0 +1,22 @@ +package net.minecraft.server; + +public class OldNibbleArray { + + public final byte[] a; + private final int b; + private final int c; + + public OldNibbleArray(byte[] abyte, int i) { + this.a = abyte; + this.b = i; + this.c = i + 4; + } + + public int a(int i, int j, int k) { + int l = i << this.c | k << this.b | j; + int i1 = l >> 1; + int j1 = l & 1; + + return j1 == 0 ? this.a[i1] & 15 : this.a[i1] >> 4 & 15; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/OpList.java b/azurite-server/src/main/java/net/minecraft/server/OpList.java new file mode 100644 index 0000000..c33b3f6 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/OpList.java @@ -0,0 +1,60 @@ +package net.minecraft.server; + +import com.google.gson.JsonObject; +import com.mojang.authlib.GameProfile; +import java.io.File; +import java.util.Iterator; + +public class OpList extends JsonList { + + public OpList(File file) { + super(file); + } + + protected JsonListEntry a(JsonObject jsonobject) { + return new OpListEntry(jsonobject); + } + + public String[] getEntries() { + String[] astring = new String[this.e().size()]; + int i = 0; + + OpListEntry oplistentry; + + for (Iterator iterator = this.e().values().iterator(); iterator.hasNext(); astring[i++] = ((GameProfile) oplistentry.getKey()).getName()) { + oplistentry = (OpListEntry) iterator.next(); + } + + return astring; + } + + public boolean b(GameProfile gameprofile) { + OpListEntry oplistentry = (OpListEntry) this.get(gameprofile); + + return oplistentry != null ? oplistentry.b() : false; + } + + protected String c(GameProfile gameprofile) { + return gameprofile.getId().toString(); + } + + public GameProfile a(String s) { + Iterator iterator = this.e().values().iterator(); + + OpListEntry oplistentry; + + do { + if (!iterator.hasNext()) { + return null; + } + + oplistentry = (OpListEntry) iterator.next(); + } while (!s.equalsIgnoreCase(((GameProfile) oplistentry.getKey()).getName())); + + return (GameProfile) oplistentry.getKey(); + } + + protected String a(GameProfile object) { + return this.c(object); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/OpListEntry.java b/azurite-server/src/main/java/net/minecraft/server/OpListEntry.java new file mode 100644 index 0000000..e339110 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/OpListEntry.java @@ -0,0 +1,60 @@ +package net.minecraft.server; + +import com.eatthepath.uuid.FastUUID; +import com.google.gson.JsonObject; +import com.mojang.authlib.GameProfile; +import java.util.UUID; + +public class OpListEntry extends JsonListEntry { + + private final int a; + private final boolean b; + + public OpListEntry(GameProfile gameprofile, int i, boolean flag) { + super(gameprofile); + this.a = i; + this.b = flag; + } + + public OpListEntry(JsonObject jsonobject) { + super(b(jsonobject), jsonobject); + this.a = jsonobject.has("level") ? jsonobject.get("level").getAsInt() : 0; + this.b = jsonobject.has("bypassesPlayerLimit") && jsonobject.get("bypassesPlayerLimit").getAsBoolean(); + } + + public int a() { + return this.a; + } + + public boolean b() { + return this.b; + } + + protected void a(JsonObject jsonobject) { + if (this.getKey() != null) { + jsonobject.addProperty("uuid", ((GameProfile) this.getKey()).getId() == null ? "" : ((GameProfile) this.getKey()).getId().toString()); + jsonobject.addProperty("name", ((GameProfile) this.getKey()).getName()); + super.a(jsonobject); + jsonobject.addProperty("level", Integer.valueOf(this.a)); + jsonobject.addProperty("bypassesPlayerLimit", Boolean.valueOf(this.b)); + } + } + + private static GameProfile b(JsonObject jsonobject) { + if (jsonobject.has("uuid") && jsonobject.has("name")) { + String s = jsonobject.get("uuid").getAsString(); + + UUID uuid; + + try { + uuid = FastUUID.parseUUID(s); + } catch (Throwable throwable) { + return null; + } + + return new GameProfile(uuid, jsonobject.get("name").getAsString()); + } else { + return null; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/Packet.java b/azurite-server/src/main/java/net/minecraft/server/Packet.java new file mode 100644 index 0000000..d698729 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/Packet.java @@ -0,0 +1,19 @@ +package net.minecraft.server; + +import java.io.IOException; + +public interface Packet { + void a(PacketDataSerializer var1) throws IOException; + + void b(PacketDataSerializer var1) throws IOException; + + void a(T var1); + + default int getSize() { + return -1; + } + + default int getId() { + return -1; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketCompressor.java b/azurite-server/src/main/java/net/minecraft/server/PacketCompressor.java new file mode 100644 index 0000000..4f5d2d9 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketCompressor.java @@ -0,0 +1,104 @@ +package net.minecraft.server; + +import com.velocitypowered.natives.compression.VelocityCompressor; +import com.velocitypowered.natives.util.MoreByteBufUtils; +import dev.azurite.spigot.optimizations.ReusableByteArray; +import io.netty.buffer.ByteBuf; +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.MessageToByteEncoder; + +import java.util.zip.Deflater; + +public class PacketCompressor extends MessageToByteEncoder { + + private static final ReusableByteArray REUSABLE_BYTE_ARRAY = new ReusableByteArray(0x70000); // rough size estimate from a quick play test + + private final byte[] encodeBuf; // Paper + private final Deflater deflater; + private final com.velocitypowered.natives.compression.VelocityCompressor compressor; // Paper + private int threshold; + + public PacketCompressor(int compressionThreshold) { + // Paper start + this(null, compressionThreshold); + } + + public PacketCompressor(VelocityCompressor compressor, int compressionThreshold) { + this.threshold = compressionThreshold; + if (compressor == null) { + this.encodeBuf = new byte[8192]; + this.deflater = new Deflater(); + } else { + this.encodeBuf = null; + this.deflater = null; + } + this.compressor = compressor; + // Paper end + } + + protected void encode(ChannelHandlerContext var1, ByteBuf var2, ByteBuf var3) throws Exception { + int var4 = var2.readableBytes(); + PacketDataSerializer var5 = new PacketDataSerializer(var3); + if (var4 < this.threshold) { + var5.b(0); + var5.writeBytes(var2); + } else { + // Paper start + if (this.deflater != null) { + byte[] var6 = REUSABLE_BYTE_ARRAY.get(var4); + var2.readBytes(var6); + var5.b(var6.length); + this.deflater.setInput(var6, 0, var4); + this.deflater.finish(); + + while (!this.deflater.finished()) { + int var7 = this.deflater.deflate(this.encodeBuf); + var5.writeBytes(this.encodeBuf, 0, var7); + } + + this.deflater.reset(); + return; + } + + var5.b(var4); + ByteBuf compatibleIn = MoreByteBufUtils.ensureCompatible(var1.alloc(), this.compressor, var2); + try { + this.compressor.deflate(compatibleIn, var3); + } finally { + compatibleIn.release(); + } + // Paper end + } + } + + // Paper start + @Override + protected ByteBuf allocateBuffer(ChannelHandlerContext ctx, ByteBuf msg, boolean preferDirect) throws Exception { + if (this.compressor != null) { + // We allocate bytes to be compressed plus 1 byte. This covers two cases: + // + // - Compression + // According to https://github.com/ebiggers/libdeflate/blob/master/libdeflate.h#L103, + // if the data compresses well (and we do not have some pathological case) then the maximum + // size the compressed size will ever be is the input size minus one. + // - Uncompressed + // This is fairly obvious - we will then have one more than the uncompressed size. + int initialBufferSize = msg.readableBytes() + 1; + return com.velocitypowered.natives.util.MoreByteBufUtils.preferredBuffer(ctx.alloc(), this.compressor, initialBufferSize); + } + + return super.allocateBuffer(ctx, msg, preferDirect); + } + + @Override + public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { + if (this.compressor != null) { + this.compressor.close(); + } + } + // Paper end + + public void setThreshold(int threshold) { + this.threshold = threshold; + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketDataSerializer.java b/azurite-server/src/main/java/net/minecraft/server/PacketDataSerializer.java new file mode 100644 index 0000000..c12415c --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketDataSerializer.java @@ -0,0 +1,954 @@ +package net.minecraft.server; + +import com.google.common.base.Charsets; +import dev.azurite.spigot.optimizations.ProtocolUtils; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.ByteBufAllocator; +import io.netty.buffer.ByteBufInputStream; +import io.netty.buffer.ByteBufOutputStream; +import io.netty.handler.codec.DecoderException; +import io.netty.handler.codec.EncoderException; +import io.netty.util.ByteProcessor; +import org.bukkit.craftbukkit.inventory.CraftItemStack; + +import java.io.DataOutput; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.channels.FileChannel; +import java.nio.channels.GatheringByteChannel; +import java.nio.channels.ScatteringByteChannel; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.UUID; + +public class PacketDataSerializer extends ByteBuf { + + private final ByteBuf a; + + public PacketDataSerializer(ByteBuf bytebuf) { + this.a = bytebuf; + } + + public static int a(int i) { + for (int j = 1; j < 5; ++j) { + if ((i & -1 << j * 7) == 0) { + return j; + } + } + + return 5; + } + + public void a(byte[] abyte) { + this.b(abyte.length); + this.writeBytes(abyte); + } + + public byte[] a() { + return readByteArray(MinecraftServer.HAS_PROTOCOL_SUPPORT ? 33553408 : 32767); + } + + public byte[] readByteArray(int limit) { + int len = this.e(); + if (len > limit) + throw new DecoderException("The received a byte array longer than allowed " + len + " > " + limit); + byte[] abyte = new byte[len]; + this.readBytes(abyte); + return abyte; + } + + public BlockPosition c() { + return BlockPosition.fromLong(this.readLong()); + } + + public void a(BlockPosition blockposition) { + this.writeLong(blockposition.asLong()); + } + + public IChatBaseComponent d() throws IOException { + return IChatBaseComponent.ChatSerializer.a(this.c(32767)); + } + + public void a(IChatBaseComponent ichatbasecomponent) throws IOException { + this.a(IChatBaseComponent.ChatSerializer.a(ichatbasecomponent)); + } + + public > T a(Class oclass) { + return ((T[]) oclass.getEnumConstants())[this.e()]; // CraftBukkit - fix decompile error + } + + public void a(Enum oenum) { + this.b(oenum.ordinal()); + } + + public int e() { + return ProtocolUtils.readVarInt(this.a); // PandaSpigot - Optimize VarInt reading + } + + public long f() { + long i = 0L; + int j = 0; + + byte b0; + + do { + b0 = this.readByte(); + i |= (long) (b0 & Byte.MAX_VALUE) << j++ * 7; + if (j > 10) { + throw new RuntimeException("VarLong too big"); + } + } while ((b0 & 128) == 128); + + return i; + } + + public void a(UUID uuid) { + this.writeLong(uuid.getMostSignificantBits()); + this.writeLong(uuid.getLeastSignificantBits()); + } + + public UUID g() { + return new UUID(this.readLong(), this.readLong()); + } + + public void b(int i) { + ProtocolUtils.writeVarInt(this.a, i); // PandaSpigot - Optimize VarInt writing + } + + public void b(long i) { + while ((i & -128L) != 0L) { + this.writeByte((int) (i & 127L) | 128); + i >>>= 7; + } + + this.writeByte((int) i); + } + + public void a(NBTTagCompound nbttagcompound) { + if (nbttagcompound == null) { + this.writeByte(0); + } else { + try { + NBTCompressedStreamTools.a(nbttagcompound, (DataOutput) (new ByteBufOutputStream(this))); + } catch (Exception ioexception) { // CraftBukkit - IOException -> Exception + throw new EncoderException(ioexception); + } + } + } + + public NBTTagCompound h() throws IOException { + int i = this.readerIndex(); + byte b0 = this.readByte(); + + if (b0 == 0) { + return null; + } else { + this.readerIndex(i); + return NBTCompressedStreamTools.a((new ByteBufInputStream(this)), new NBTReadLimiter(56000L)); // Vortex - Anticrash + } + } + + public void a(ItemStack itemstack) { + if (itemstack == null || itemstack.getItem() == null) { // CraftBukkit - NPE fix itemstack.getItem() + this.writeShort(-1); + } else { + this.writeShort(Item.getId(itemstack.getItem())); + this.writeByte(itemstack.count); + int data = itemstack.getData(); + + // Beanes - fake durability + if (itemstack.getItem().hasFakeDurability()) { + double percent = (double) data / itemstack.getItem().getMaxDurability(); + data = (int) (percent * itemstack.getItem().durability); + } + + this.writeShort(data); + NBTTagCompound nbttagcompound = null; + + if (itemstack.getItem().usesDurability() || itemstack.getItem().p()) { + // Spigot start - filter + itemstack = itemstack.cloneItemStack(); + CraftItemStack.setItemMeta(itemstack, CraftItemStack.getItemMeta(itemstack)); + // Spigot end + nbttagcompound = itemstack.getTag(); + } + + this.a(nbttagcompound); + } + } + + public ItemStack i() throws IOException { + ItemStack itemstack = null; + short itemId = readShort(); + if (itemId >= 0) { + itemstack = new ItemStack(Item.getById(itemId), readByte(), readShort()); + itemstack.setTag(h()); + if (itemstack.getTag() != null) { + CraftItemStack.setItemMeta(itemstack, CraftItemStack.getItemMeta(itemstack)); + } + } + return itemstack; + } + + public String c(int i) { + int j = e(); + if (j > i * 4) + throw new DecoderException("The received encoded string buffer length is longer than maximum allowed (" + j + " > " + (i * 4) + ")"); + if (j < 0) + throw new DecoderException("The received encoded string buffer length is less than zero! Weird string!"); + String str = toString(readerIndex(), j, StandardCharsets.UTF_8); + readerIndex(readerIndex() + j); + if (str.length() > i) + throw new DecoderException("The received string length is longer than maximum allowed (" + j + " > " + i + ")"); + return str; + } + + public PacketDataSerializer a(String s) { + // PandaSpigot start - Optimize string writing + int utf8Bytes = io.netty.buffer.ByteBufUtil.utf8Bytes(s); + if (utf8Bytes > 32767) { + throw new EncoderException("String too big (was " + s.length() + " bytes encoded, max " + 32767 + ")"); + } else { + this.b(utf8Bytes); + this.writeCharSequence(s, Charsets.UTF_8); + return this; + } + // PandaSpigot end + } + + public int capacity() { + return this.a.capacity(); + } + + public ByteBuf capacity(int i) { + return this.a.capacity(i); + } + + public int maxCapacity() { + return this.a.maxCapacity(); + } + + public ByteBufAllocator alloc() { + return this.a.alloc(); + } + + public ByteOrder order() { + return this.a.order(); + } + + public ByteBuf order(ByteOrder byteorder) { + return this.a.order(byteorder); + } + + public ByteBuf unwrap() { + return this.a.unwrap(); + } + + public boolean isDirect() { + return this.a.isDirect(); + } + + public boolean isReadOnly() { + return a.isReadOnly(); + } + + public ByteBuf asReadOnly() { + return a.asReadOnly(); + } + + public int readerIndex() { + return this.a.readerIndex(); + } + + public ByteBuf readerIndex(int i) { + return this.a.readerIndex(i); + } + + public int writerIndex() { + return this.a.writerIndex(); + } + + public ByteBuf writerIndex(int i) { + return this.a.writerIndex(i); + } + + public ByteBuf setIndex(int i, int j) { + return this.a.setIndex(i, j); + } + + public int readableBytes() { + return this.a.readableBytes(); + } + + public int writableBytes() { + return this.a.writableBytes(); + } + + public int maxWritableBytes() { + return this.a.maxWritableBytes(); + } + + public boolean isReadable() { + return this.a.isReadable(); + } + + public boolean isReadable(int i) { + return this.a.isReadable(i); + } + + public boolean isWritable() { + return this.a.isWritable(); + } + + public boolean isWritable(int i) { + return this.a.isWritable(i); + } + + public ByteBuf clear() { + return this.a.clear(); + } + + public ByteBuf markReaderIndex() { + return this.a.markReaderIndex(); + } + + public ByteBuf resetReaderIndex() { + return this.a.resetReaderIndex(); + } + + public ByteBuf markWriterIndex() { + return this.a.markWriterIndex(); + } + + public ByteBuf resetWriterIndex() { + return this.a.resetWriterIndex(); + } + + public ByteBuf discardReadBytes() { + return this.a.discardReadBytes(); + } + + public ByteBuf discardSomeReadBytes() { + return this.a.discardSomeReadBytes(); + } + + public ByteBuf ensureWritable(int i) { + return this.a.ensureWritable(i); + } + + public int ensureWritable(int i, boolean flag) { + return this.a.ensureWritable(i, flag); + } + + public boolean getBoolean(int i) { + return this.a.getBoolean(i); + } + + public byte getByte(int i) { + return this.a.getByte(i); + } + + public short getUnsignedByte(int i) { + return this.a.getUnsignedByte(i); + } + + public short getShort(int i) { + return this.a.getShort(i); + } + + public short getShortLE(int i) { + return a.getShortLE(i); + } + + public int getUnsignedShort(int i) { + return this.a.getUnsignedShort(i); + } + + public int getUnsignedShortLE(int i) { + return a.getUnsignedShortLE(i); + } + + public int getMedium(int i) { + return this.a.getMedium(i); + } + + public int getMediumLE(int i) { + return a.getMediumLE(i); + } + + public int getUnsignedMedium(int i) { + return this.a.getUnsignedMedium(i); + } + + public int getUnsignedMediumLE(int i) { + return a.getUnsignedMediumLE(i); + } + + public int getInt(int i) { + return this.a.getInt(i); + } + + public int getIntLE(int i) { + return a.getIntLE(i); + } + + public long getUnsignedInt(int i) { + return this.a.getUnsignedInt(i); + } + + public long getUnsignedIntLE(int i) { + return a.getUnsignedIntLE(i); + } + + public long getLong(int i) { + return this.a.getLong(i); + } + + public long getLongLE(int i) { + return a.getLongLE(i); + } + + public char getChar(int i) { + return this.a.getChar(i); + } + + public float getFloat(int i) { + return this.a.getFloat(i); + } + + public double getDouble(int i) { + return this.a.getDouble(i); + } + + public ByteBuf getBytes(int i, ByteBuf bytebuf) { + return this.a.getBytes(i, bytebuf); + } + + public ByteBuf getBytes(int i, ByteBuf bytebuf, int j) { + return this.a.getBytes(i, bytebuf, j); + } + + public ByteBuf getBytes(int i, ByteBuf bytebuf, int j, int k) { + return this.a.getBytes(i, bytebuf, j, k); + } + + public ByteBuf getBytes(int i, byte[] abyte) { + return this.a.getBytes(i, abyte); + } + + public ByteBuf getBytes(int i, byte[] abyte, int j, int k) { + return this.a.getBytes(i, abyte, j, k); + } + + public ByteBuf getBytes(int i, ByteBuffer bytebuffer) { + return this.a.getBytes(i, bytebuffer); + } + + public ByteBuf getBytes(int i, OutputStream outputstream, int j) throws IOException { + return this.a.getBytes(i, outputstream, j); + } + + public int getBytes(int i, GatheringByteChannel gatheringbytechannel, int j) throws IOException { + return this.a.getBytes(i, gatheringbytechannel, j); + } + + public int getBytes(int i, FileChannel fileChannel, long l, int i1) throws IOException { + return a.getBytes(i, fileChannel, l, i1); + } + + public CharSequence getCharSequence(int i, int i1, Charset charset) { + return a.getCharSequence(i, i1, charset); + } + + public ByteBuf setBoolean(int i, boolean flag) { + return this.a.setBoolean(i, flag); + } + + public ByteBuf setByte(int i, int j) { + return this.a.setByte(i, j); + } + + public ByteBuf setShort(int i, int j) { + return this.a.setShort(i, j); + } + + public ByteBuf setShortLE(int i, int i1) { + return a.setShortLE(i, i1); + } + + public ByteBuf setMedium(int i, int j) { + return this.a.setMedium(i, j); + } + + public ByteBuf setMediumLE(int i, int i1) { + return a.setMediumLE(i, i1); + } + + public ByteBuf setInt(int i, int j) { + return this.a.setInt(i, j); + } + + public ByteBuf setIntLE(int i, int i1) { + return a.setIntLE(i, i1); + } + + public ByteBuf setLong(int i, long j) { + return this.a.setLong(i, j); + } + + public ByteBuf setLongLE(int i, long l) { + return a.setLongLE(i, l); + } + + public ByteBuf setChar(int i, int j) { + return this.a.setChar(i, j); + } + + public ByteBuf setFloat(int i, float f) { + return this.a.setFloat(i, f); + } + + public ByteBuf setDouble(int i, double d0) { + return this.a.setDouble(i, d0); + } + + public ByteBuf setBytes(int i, ByteBuf bytebuf) { + return this.a.setBytes(i, bytebuf); + } + + public ByteBuf setBytes(int i, ByteBuf bytebuf, int j) { + return this.a.setBytes(i, bytebuf, j); + } + + public ByteBuf setBytes(int i, ByteBuf bytebuf, int j, int k) { + return this.a.setBytes(i, bytebuf, j, k); + } + + public ByteBuf setBytes(int i, byte[] abyte) { + return this.a.setBytes(i, abyte); + } + + public ByteBuf setBytes(int i, byte[] abyte, int j, int k) { + return this.a.setBytes(i, abyte, j, k); + } + + public ByteBuf setBytes(int i, ByteBuffer bytebuffer) { + return this.a.setBytes(i, bytebuffer); + } + + public int setBytes(int i, InputStream inputstream, int j) throws IOException { + return this.a.setBytes(i, inputstream, j); + } + + public int setBytes(int i, ScatteringByteChannel scatteringbytechannel, int j) throws IOException { + return this.a.setBytes(i, scatteringbytechannel, j); + } + + public int setBytes(int i, FileChannel fileChannel, long l, int i1) throws IOException { + return a.setBytes(i, fileChannel, l, i1); + } + + public ByteBuf setZero(int i, int j) { + return this.a.setZero(i, j); + } + + public int setCharSequence(int i, CharSequence charSequence, Charset charset) { + return a.setCharSequence(i, charSequence, charset); + } + + public boolean readBoolean() { + return this.a.readBoolean(); + } + + public byte readByte() { + return this.a.readByte(); + } + + public short readUnsignedByte() { + return this.a.readUnsignedByte(); + } + + public short readShort() { + return this.a.readShort(); + } + + public short readShortLE() { + return a.readShortLE(); + } + + public int readUnsignedShort() { + return this.a.readUnsignedShort(); + } + + public int readUnsignedShortLE() { + return a.readUnsignedShortLE(); + } + + public int readMedium() { + return this.a.readMedium(); + } + + public int readMediumLE() { + return a.readMediumLE(); + } + + public int readUnsignedMedium() { + return this.a.readUnsignedMedium(); + } + + public int readUnsignedMediumLE() { + return a.readUnsignedMediumLE(); + } + + public int readInt() { + return this.a.readInt(); + } + + public int readIntLE() { + return a.readIntLE(); + } + + public long readUnsignedInt() { + return this.a.readUnsignedInt(); + } + + public long readUnsignedIntLE() { + return a.readUnsignedIntLE(); + } + + public long readLong() { + return this.a.readLong(); + } + + public long readLongLE() { + return a.readLongLE(); + } + + public char readChar() { + return this.a.readChar(); + } + + public float readFloat() { + return this.a.readFloat(); + } + + public double readDouble() { + return this.a.readDouble(); + } + + public ByteBuf readBytes(int i) { + return this.a.readBytes(i); + } + + public ByteBuf readSlice(int i) { + return this.a.readSlice(i); + } + + public ByteBuf readRetainedSlice(int i) { + return a.readRetainedSlice(i); + } + + public ByteBuf readBytes(ByteBuf bytebuf) { + return this.a.readBytes(bytebuf); + } + + public ByteBuf readBytes(ByteBuf bytebuf, int i) { + return this.a.readBytes(bytebuf, i); + } + + public ByteBuf readBytes(ByteBuf bytebuf, int i, int j) { + return this.a.readBytes(bytebuf, i, j); + } + + public ByteBuf readBytes(byte[] abyte) { + return this.a.readBytes(abyte); + } + + public ByteBuf readBytes(byte[] abyte, int i, int j) { + return this.a.readBytes(abyte, i, j); + } + + public ByteBuf readBytes(ByteBuffer bytebuffer) { + return this.a.readBytes(bytebuffer); + } + + public ByteBuf readBytes(OutputStream outputstream, int i) throws IOException { + return this.a.readBytes(outputstream, i); + } + + public int readBytes(GatheringByteChannel gatheringbytechannel, int i) throws IOException { + return this.a.readBytes(gatheringbytechannel, i); + } + + public CharSequence readCharSequence(int i, Charset charset) { + return a.readCharSequence(i, charset); + } + + public int readBytes(FileChannel fileChannel, long l, int i) throws IOException { + return a.readBytes(fileChannel, l, i); + } + + public ByteBuf skipBytes(int i) { + return this.a.skipBytes(i); + } + + public ByteBuf writeBoolean(boolean flag) { + return this.a.writeBoolean(flag); + } + + public ByteBuf writeByte(int i) { + return this.a.writeByte(i); + } + + public ByteBuf writeShort(int i) { + return this.a.writeShort(i); + } + + public ByteBuf writeShortLE(int i) { + return a.writeShortLE(i); + } + + public ByteBuf writeMedium(int i) { + return this.a.writeMedium(i); + } + + public ByteBuf writeMediumLE(int i) { + return a.writeMediumLE(i); + } + + public ByteBuf writeInt(int i) { + return this.a.writeInt(i); + } + + public ByteBuf writeIntLE(int i) { + return a.writeIntLE(i); + } + + public ByteBuf writeLong(long i) { + return this.a.writeLong(i); + } + + public ByteBuf writeLongLE(long l) { + return a.writeLongLE(l); + } + + public ByteBuf writeChar(int i) { + return this.a.writeChar(i); + } + + public ByteBuf writeFloat(float f) { + return this.a.writeFloat(f); + } + + public ByteBuf writeDouble(double d0) { + return this.a.writeDouble(d0); + } + + public ByteBuf writeBytes(ByteBuf bytebuf) { + return this.a.writeBytes(bytebuf); + } + + public ByteBuf writeBytes(ByteBuf bytebuf, int i) { + return this.a.writeBytes(bytebuf, i); + } + + public ByteBuf writeBytes(ByteBuf bytebuf, int i, int j) { + return this.a.writeBytes(bytebuf, i, j); + } + + public ByteBuf writeBytes(byte[] abyte) { + return this.a.writeBytes(abyte); + } + + public ByteBuf writeBytes(byte[] abyte, int i, int j) { + return this.a.writeBytes(abyte, i, j); + } + + public ByteBuf writeBytes(ByteBuffer bytebuffer) { + return this.a.writeBytes(bytebuffer); + } + + public int writeBytes(InputStream inputstream, int i) throws IOException { + return this.a.writeBytes(inputstream, i); + } + + public int writeBytes(ScatteringByteChannel scatteringbytechannel, int i) throws IOException { + return this.a.writeBytes(scatteringbytechannel, i); + } + + public int writeBytes(FileChannel fileChannel, long l, int i) throws IOException { + return a.writeBytes(fileChannel, l, i); + } + + public ByteBuf writeZero(int i) { + return this.a.writeZero(i); + } + + public int writeCharSequence(CharSequence charSequence, Charset charset) { + return a.writeCharSequence(charSequence, charset); + } + + public int indexOf(int i, int j, byte b0) { + return this.a.indexOf(i, j, b0); + } + + public int bytesBefore(byte b0) { + return this.a.bytesBefore(b0); + } + + public int bytesBefore(int i, byte b0) { + return this.a.bytesBefore(i, b0); + } + + public int bytesBefore(int i, int j, byte b0) { + return this.a.bytesBefore(i, j, b0); + } + + public int forEachByte(ByteProcessor byteProcessor) { + return a.forEachByte(byteProcessor); + } + + public int forEachByte(int i, int i1, ByteProcessor byteProcessor) { + return a.forEachByte(i, i1, byteProcessor); + } + + public int forEachByteDesc(ByteProcessor byteProcessor) { + return a.forEachByteDesc(byteProcessor); + } + + public int forEachByteDesc(int i, int i1, ByteProcessor byteProcessor) { + return a.forEachByteDesc(i, i1, byteProcessor); + } + + public ByteBuf copy() { + return this.a.copy(); + } + + public ByteBuf copy(int i, int j) { + return this.a.copy(i, j); + } + + public ByteBuf slice() { + return this.a.slice(); + } + + public ByteBuf retainedSlice() { + return a.retainedSlice(); + } + + public ByteBuf slice(int i, int j) { + return this.a.slice(i, j); + } + + public ByteBuf retainedSlice(int i, int i1) { + return a.retainedSlice(i, i1); + } + + public ByteBuf duplicate() { + return this.a.duplicate(); + } + + public ByteBuf retainedDuplicate() { + return a.retainedDuplicate(); + } + + public int nioBufferCount() { + return this.a.nioBufferCount(); + } + + public ByteBuffer nioBuffer() { + return this.a.nioBuffer(); + } + + public ByteBuffer nioBuffer(int i, int j) { + return this.a.nioBuffer(i, j); + } + + public ByteBuffer internalNioBuffer(int i, int j) { + return this.a.internalNioBuffer(i, j); + } + + public ByteBuffer[] nioBuffers() { + return this.a.nioBuffers(); + } + + public ByteBuffer[] nioBuffers(int i, int j) { + return this.a.nioBuffers(i, j); + } + + public boolean hasArray() { + return this.a.hasArray(); + } + + public byte[] array() { + return this.a.array(); + } + + public int arrayOffset() { + return this.a.arrayOffset(); + } + + public boolean hasMemoryAddress() { + return this.a.hasMemoryAddress(); + } + + public long memoryAddress() { + return this.a.memoryAddress(); + } + + public String toString(Charset charset) { + return this.a.toString(charset); + } + + public String toString(int i, int j, Charset charset) { + return this.a.toString(i, j, charset); + } + + public int hashCode() { + return this.a.hashCode(); + } + + public boolean equals(Object object) { + return this.a.equals(object); + } + + public int compareTo(ByteBuf bytebuf) { + return this.a.compareTo(bytebuf); + } + + public String toString() { + return this.a.toString(); + } + + public ByteBuf retain(int i) { + return this.a.retain(i); + } + + public ByteBuf retain() { + return this.a.retain(); + } + + public ByteBuf touch() { + return a.touch(); + } + + public ByteBuf touch(Object o) { + return a.touch(o); + } + + public int refCnt() { + return this.a.refCnt(); + } + + public boolean release() { + return this.a.release(); + } + + public boolean release(int i) { + return this.a.release(i); + } + +} \ No newline at end of file diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketDecoder.java b/azurite-server/src/main/java/net/minecraft/server/PacketDecoder.java new file mode 100644 index 0000000..99afd88 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketDecoder.java @@ -0,0 +1,69 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; +import io.netty.buffer.ByteBuf; +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.ByteToMessageDecoder; +import io.netty.handler.codec.CorruptedFrameException; + +import java.util.List; +import java.util.function.Supplier; + +// Beanes: this should preferable be a ChannelInboundHandlerAdapter but to keep compatibility with plugins we still extend ByteToMessageDecoder +public class PacketDecoder extends ByteToMessageDecoder { + private Supplier>[] packetConstructors = new Supplier[0]; + + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { + if (msg instanceof ByteBuf) { + tryDecode(ctx, (ByteBuf) msg); + } else { + ctx.fireChannelRead(msg); + } + } + + @Override + protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List list) throws Exception { + throw new UnsupportedOperationException("AzuriteSpigot replaces this with the velocity packet decoding!"); + } + + protected void tryDecode(ChannelHandlerContext ctx, ByteBuf buf) { + // Only decode if the bytebuf is readable + if (!ctx.channel().isActive() || !buf.isReadable()) { + buf.release(); + return; + } + + int originalReaderIndex = buf.readerIndex(); + int packetId = ProtocolUtils.readVarInt(buf); + + if (packetId < 0 || packetId >= packetConstructors.length) { + buf.readerIndex(originalReaderIndex); + ctx.fireChannelRead(buf); + return; + } + + Supplier> supplier = packetConstructors[packetId]; + Packet packet = supplier.get(); + + try { + try { + packet.a(new PacketDataSerializer(buf)); + } catch (Exception e) { + throw new CorruptedFrameException("Error decoding " + packet.getClass(), e); + } + + if (buf.isReadable()) { + throw new CorruptedFrameException("Packet sent for " + packet.getClass() + " was too " + + "big (expected " + buf.readerIndex() + " bytes, got " + buf.writerIndex() + " bytes)"); + } + ctx.fireChannelRead(packet); + } finally { + buf.release(); + } + } + + public void setServerBoundConstructors(Supplier>[] serverBoundConstructors) { + this.packetConstructors = serverBoundConstructors; + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketDecompressor.java b/azurite-server/src/main/java/net/minecraft/server/PacketDecompressor.java new file mode 100644 index 0000000..0f3f42c --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketDecompressor.java @@ -0,0 +1,87 @@ +package net.minecraft.server; + +import com.velocitypowered.natives.compression.VelocityCompressor; +import com.velocitypowered.natives.util.MoreByteBufUtils; +import dev.azurite.spigot.optimizations.ReusableByteArray; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.ByteToMessageDecoder; +import io.netty.handler.codec.DecoderException; + +import java.util.List; +import java.util.zip.Inflater; + +public class PacketDecompressor extends ByteToMessageDecoder { + + private static final ReusableByteArray REUSABLE_BYTE_ARRAY = new ReusableByteArray(8192); + + private final Inflater inflater; + private final com.velocitypowered.natives.compression.VelocityCompressor compressor; // Paper + private int threshold; + + public PacketDecompressor(int compressionThreshold) { + this(null, compressionThreshold); + } + + public PacketDecompressor(VelocityCompressor compressor, int compressionThreshold) { + this.threshold = compressionThreshold; + this.inflater = compressor == null ? new Inflater() : null; + this.compressor = compressor; + } + + protected void decode(ChannelHandlerContext var1, ByteBuf var2, List var3) throws Exception { + if (var2.readableBytes() != 0) { + PacketDataSerializer var4 = new PacketDataSerializer(var2); + int var5 = var4.e(); + if (var5 == 0) { + var3.add(var4.readBytes(var4.readableBytes())); + } else { + if (var5 < this.threshold) { + throw new DecoderException("Badly compressed packet - size of " + var5 + " is below server threshold of " + this.threshold); + } + + if (var5 > 2097152) { + throw new DecoderException("Badly compressed packet - size of " + var5 + " is larger than protocol maximum of " + 2097152); + } + // Paper start + if (this.inflater != null) { + byte[] var6 = REUSABLE_BYTE_ARRAY.get(var4.readableBytes()); + var4.readBytes(var6); + this.inflater.setInput(var6); + byte[] var7 = new byte[var5]; + this.inflater.inflate(var7); + var3.add(Unpooled.wrappedBuffer(var7)); + this.inflater.reset(); + return; + } + ByteBuf compatibleIn = MoreByteBufUtils.ensureCompatible(var1.alloc(), this.compressor, var2); + ByteBuf uncompressed = MoreByteBufUtils.preferredBuffer(var1.alloc(), this.compressor, var5); + try { + this.compressor.inflate(compatibleIn, uncompressed, var5); + var3.add(uncompressed); + var2.clear(); + } catch (Exception e) { + uncompressed.release(); + throw e; + } finally { + compatibleIn.release(); + } + // Paper end + } + } + } + + // Paper start + @Override + public void handlerRemoved0(ChannelHandlerContext ctx) { + if (this.compressor != null) { + this.compressor.close(); + } + } + // Paper end + + public void setThreshold(int var1) { + this.threshold = var1; + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketDecrypter.java b/azurite-server/src/main/java/net/minecraft/server/PacketDecrypter.java new file mode 100644 index 0000000..4d02db9 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketDecrypter.java @@ -0,0 +1,24 @@ +package net.minecraft.server; + +import io.netty.buffer.ByteBuf; +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.MessageToMessageDecoder; +import java.util.List; +import javax.crypto.Cipher; + +public class PacketDecrypter extends MessageToMessageDecoder { + + private final PacketEncryptionHandler a; + + public PacketDecrypter(Cipher cipher) { + this.a = new PacketEncryptionHandler(cipher); + } + + protected void a(ChannelHandlerContext channelhandlercontext, ByteBuf bytebuf, List list) throws Exception { + list.add(this.a.a(channelhandlercontext, bytebuf)); + } + + protected void decode(ChannelHandlerContext channelhandlercontext, ByteBuf object, List list) throws Exception { + this.a(channelhandlercontext, object, list); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketEncoder.java b/azurite-server/src/main/java/net/minecraft/server/PacketEncoder.java new file mode 100644 index 0000000..d2bfb4f --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketEncoder.java @@ -0,0 +1,82 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.AzuriteConfig; +import dev.azurite.spigot.optimizations.ProtocolUtils; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelPromise; +import io.netty.handler.codec.CorruptedFrameException; +import io.netty.handler.codec.EncoderException; +import io.netty.handler.codec.MessageToByteEncoder; +import io.netty.util.ReferenceCountUtil; + +import java.io.IOException; + +// Beanes: adds estimated size + based on velocity +// We also override the write method so that we do not need to get the packet id twice +// (We do not make our own ChannelOutboundHandlerAdapter as that would make plugins more incompatible) +public class PacketEncoder extends MessageToByteEncoder> { + private final boolean shouldCalculateSize = AzuriteConfig.calculatePacketSize.getValue(); + + @Override + public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { + ByteBuf buf = null; + + try { + if (msg instanceof Packet) { + Packet packet = (Packet) msg; + int id = packet.getId(); + + if (id == -1) { + throw new IOException("Can't serialize unregistered packet"); + } + + // Beanes - option to pre calculate size of each packet: for chunk packets always do this as it's so big + if (shouldCalculateSize || packet instanceof PacketPlayOutMapChunk || packet instanceof PacketPlayOutMapChunkBulk) { + buf = ctx.alloc().ioBuffer(ProtocolUtils.varIntBytes(id) + packet.getSize()); + } else { + buf = ctx.alloc().ioBuffer(); + } + + try { + ProtocolUtils.writeVarInt(buf, id); + try { + packet.b(new PacketDataSerializer(buf)); + } catch (Throwable throwable) { + throw new CorruptedFrameException("Failed to serialize packet " + packet.getClass().getSimpleName() + " with id " + id, throwable); + } + } finally { + ReferenceCountUtil.release(packet); + } + + if (buf.isReadable()) { + ctx.write(buf, promise); + } else { + buf.release(); + ctx.write(Unpooled.EMPTY_BUFFER, promise); + } + + buf = null; + } else { + ctx.write(msg, promise); + } + } catch (EncoderException var17) { + EncoderException e = var17; + throw e; + } catch (Throwable var18) { + Throwable e = var18; + throw new EncoderException(e); + } finally { + if (buf != null) { + buf.release(); + } + + } + } + + @Override + protected void encode(ChannelHandlerContext channelHandlerContext, Packet packet, ByteBuf byteBuf) throws Exception { + throw new UnsupportedOperationException("AzuriteSpigot replaces this. If you need support for this feature please contact us."); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketEncrypter.java b/azurite-server/src/main/java/net/minecraft/server/PacketEncrypter.java new file mode 100644 index 0000000..e8ef472 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketEncrypter.java @@ -0,0 +1,23 @@ +package net.minecraft.server; + +import io.netty.buffer.ByteBuf; +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.MessageToByteEncoder; +import javax.crypto.Cipher; + +public class PacketEncrypter extends MessageToByteEncoder { + + private final PacketEncryptionHandler a; + + public PacketEncrypter(Cipher cipher) { + this.a = new PacketEncryptionHandler(cipher); + } + + protected void a(ChannelHandlerContext channelhandlercontext, ByteBuf bytebuf, ByteBuf bytebuf1) throws Exception { + this.a.a(bytebuf, bytebuf1); + } + + protected void encode(ChannelHandlerContext channelhandlercontext, ByteBuf object, ByteBuf bytebuf) throws Exception { + this.a(channelhandlercontext, object, bytebuf); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketEncryptionHandler.java b/azurite-server/src/main/java/net/minecraft/server/PacketEncryptionHandler.java new file mode 100644 index 0000000..a919da0 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketEncryptionHandler.java @@ -0,0 +1,49 @@ +package net.minecraft.server; + +import io.netty.buffer.ByteBuf; +import io.netty.channel.ChannelHandlerContext; +import javax.crypto.Cipher; +import javax.crypto.ShortBufferException; + +public class PacketEncryptionHandler { + + private final Cipher a; + private byte[] b = new byte[0]; + private byte[] c = new byte[0]; + + protected PacketEncryptionHandler(Cipher cipher) { + this.a = cipher; + } + + private byte[] a(ByteBuf bytebuf) { + int i = bytebuf.readableBytes(); + + if (this.b.length < i) { + this.b = new byte[i]; + } + + bytebuf.readBytes(this.b, 0, i); + return this.b; + } + + protected ByteBuf a(ChannelHandlerContext channelhandlercontext, ByteBuf bytebuf) throws ShortBufferException { + int i = bytebuf.readableBytes(); + byte[] abyte = this.a(bytebuf); + ByteBuf bytebuf1 = channelhandlercontext.alloc().heapBuffer(this.a.getOutputSize(i)); + + bytebuf1.writerIndex(this.a.update(abyte, 0, i, bytebuf1.array(), bytebuf1.arrayOffset())); + return bytebuf1; + } + + protected void a(ByteBuf bytebuf, ByteBuf bytebuf1) throws ShortBufferException { + int i = bytebuf.readableBytes(); + byte[] abyte = this.a(bytebuf); + int j = this.a.getOutputSize(i); + + if (this.c.length < j) { + this.c = new byte[j]; + } + + bytebuf1.writeBytes(this.c, 0, this.a.update(abyte, 0, i, this.c)); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketHandshakingInListener.java b/azurite-server/src/main/java/net/minecraft/server/PacketHandshakingInListener.java new file mode 100644 index 0000000..e91532b --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketHandshakingInListener.java @@ -0,0 +1,6 @@ +package net.minecraft.server; + +public interface PacketHandshakingInListener extends PacketListener { + + void a(PacketHandshakingInSetProtocol packethandshakinginsetprotocol); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketHandshakingInSetProtocol.java b/azurite-server/src/main/java/net/minecraft/server/PacketHandshakingInSetProtocol.java new file mode 100644 index 0000000..aa9f8a3 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketHandshakingInSetProtocol.java @@ -0,0 +1,40 @@ +package net.minecraft.server; + +import java.io.IOException; + +public class PacketHandshakingInSetProtocol implements Packet { + + public int a; + public String hostname; + public int port; + public EnumProtocol d; + + public PacketHandshakingInSetProtocol() { + } + + public void a(PacketDataSerializer packetdataserializer) throws IOException { + this.a = packetdataserializer.e(); + this.hostname = packetdataserializer.c(Short.MAX_VALUE); // Spigot + this.port = packetdataserializer.readUnsignedShort(); + this.d = EnumProtocol.a(packetdataserializer.e()); + } + + public void b(PacketDataSerializer packetdataserializer) throws IOException { + packetdataserializer.b(this.a); + packetdataserializer.a(this.hostname); + packetdataserializer.writeShort(this.port); + packetdataserializer.b(this.d.a()); + } + + public void a(PacketHandshakingInListener packethandshakinginlistener) { + packethandshakinginlistener.a(this); + } + + public EnumProtocol a() { + return this.d; + } + + public int b() { + return this.a; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketListener.java b/azurite-server/src/main/java/net/minecraft/server/PacketListener.java new file mode 100644 index 0000000..b0014c6 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketListener.java @@ -0,0 +1,6 @@ +package net.minecraft.server; + +public interface PacketListener { + + void a(IChatBaseComponent ichatbasecomponent); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketListenerPlayIn.java b/azurite-server/src/main/java/net/minecraft/server/PacketListenerPlayIn.java new file mode 100644 index 0000000..7682b0d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketListenerPlayIn.java @@ -0,0 +1,49 @@ +package net.minecraft.server; + +public interface PacketListenerPlayIn extends PacketListener { + void a(PacketPlayInArmAnimation var1); + + void a(PacketPlayInChat var1); + + void a(PacketPlayInTabComplete var1); + + void a(PacketPlayInClientCommand var1); + + void a(PacketPlayInSettings var1); + + void a(PacketPlayInTransaction var1); + + void a(PacketPlayInEnchantItem var1); + + void a(PacketPlayInWindowClick var1); + + void a(PacketPlayInCloseWindow var1); + + void a(PacketPlayInCustomPayload var1); + + void a(PacketPlayInUseEntity var1); + + void a(PacketPlayInKeepAlive var1); + + void a(PacketPlayInFlying var1); + + void a(PacketPlayInAbilities var1); + + void a(PacketPlayInBlockDig var1); + + void a(PacketPlayInEntityAction var1); + + void a(PacketPlayInSteerVehicle var1); + + void a(PacketPlayInHeldItemSlot var1); + + void a(PacketPlayInSetCreativeSlot var1); + + void a(PacketPlayInUpdateSign var1); + + void a(PacketPlayInBlockPlace var1); + + void a(PacketPlayInSpectate var1); + + void a(PacketPlayInResourcePackStatus var1); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketListenerPlayOut.java b/azurite-server/src/main/java/net/minecraft/server/PacketListenerPlayOut.java new file mode 100644 index 0000000..3d15eed --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketListenerPlayOut.java @@ -0,0 +1,146 @@ +package net.minecraft.server; + +public interface PacketListenerPlayOut extends PacketListener { + + void a(PacketPlayOutSpawnEntity packetplayoutspawnentity); + + void a(PacketPlayOutSpawnEntityExperienceOrb packetplayoutspawnentityexperienceorb); + + void a(PacketPlayOutSpawnEntityWeather packetplayoutspawnentityweather); + + void a(PacketPlayOutSpawnEntityLiving packetplayoutspawnentityliving); + + void a(PacketPlayOutScoreboardObjective packetplayoutscoreboardobjective); + + void a(PacketPlayOutSpawnEntityPainting packetplayoutspawnentitypainting); + + void a(PacketPlayOutNamedEntitySpawn packetplayoutnamedentityspawn); + + void a(PacketPlayOutAnimation packetplayoutanimation); + + void a(PacketPlayOutStatistic packetplayoutstatistic); + + void a(PacketPlayOutBlockBreakAnimation packetplayoutblockbreakanimation); + + void a(PacketPlayOutOpenSignEditor packetplayoutopensigneditor); + + void a(PacketPlayOutTileEntityData packetplayouttileentitydata); + + void a(PacketPlayOutBlockAction packetplayoutblockaction); + + void a(PacketPlayOutBlockChange packetplayoutblockchange); + + void a(PacketPlayOutChat packetplayoutchat); + + void a(PacketPlayOutTabComplete packetplayouttabcomplete); + + void a(PacketPlayOutMultiBlockChange packetplayoutmultiblockchange); + + void a(PacketPlayOutMap packetplayoutmap); + + void a(PacketPlayOutTransaction packetplayouttransaction); + + void a(PacketPlayOutCloseWindow packetplayoutclosewindow); + + void a(PacketPlayOutWindowItems packetplayoutwindowitems); + + void a(PacketPlayOutOpenWindow packetplayoutopenwindow); + + void a(PacketPlayOutWindowData packetplayoutwindowdata); + + void a(PacketPlayOutSetSlot packetplayoutsetslot); + + void a(PacketPlayOutCustomPayload packetplayoutcustompayload); + + void a(PacketPlayOutKickDisconnect packetplayoutkickdisconnect); + + void a(PacketPlayOutBed packetplayoutbed); + + void a(PacketPlayOutEntityStatus packetplayoutentitystatus); + + void a(PacketPlayOutAttachEntity packetplayoutattachentity); + + void a(PacketPlayOutExplosion packetplayoutexplosion); + + void a(PacketPlayOutGameStateChange packetplayoutgamestatechange); + + void a(PacketPlayOutKeepAlive packetplayoutkeepalive); + + void a(PacketPlayOutMapChunk packetplayoutmapchunk); + + void a(PacketPlayOutMapChunkBulk packetplayoutmapchunkbulk); + + void a(PacketPlayOutWorldEvent packetplayoutworldevent); + + void a(PacketPlayOutLogin packetplayoutlogin); + + void a(PacketPlayOutEntity packetplayoutentity); + + void a(PacketPlayOutPosition packetplayoutposition); + + void a(PacketPlayOutWorldParticles packetplayoutworldparticles); + + void a(PacketPlayOutAbilities packetplayoutabilities); + + void a(PacketPlayOutPlayerInfo packetplayoutplayerinfo); + + void a(PacketPlayOutEntityDestroy packetplayoutentitydestroy); + + void a(PacketPlayOutRemoveEntityEffect packetplayoutremoveentityeffect); + + void a(PacketPlayOutRespawn packetplayoutrespawn); + + void a(PacketPlayOutEntityHeadRotation packetplayoutentityheadrotation); + + void a(PacketPlayOutHeldItemSlot packetplayouthelditemslot); + + void a(PacketPlayOutScoreboardDisplayObjective packetplayoutscoreboarddisplayobjective); + + void a(PacketPlayOutEntityMetadata packetplayoutentitymetadata); + + void a(PacketPlayOutEntityVelocity packetplayoutentityvelocity); + + void a(PacketPlayOutEntityEquipment packetplayoutentityequipment); + + void a(PacketPlayOutExperience packetplayoutexperience); + + void a(PacketPlayOutUpdateHealth packetplayoutupdatehealth); + + void a(PacketPlayOutScoreboardTeam packetplayoutscoreboardteam); + + void a(PacketPlayOutScoreboardScore packetplayoutscoreboardscore); + + void a(PacketPlayOutSpawnPosition packetplayoutspawnposition); + + void a(PacketPlayOutUpdateTime packetplayoutupdatetime); + + void a(PacketPlayOutUpdateSign packetplayoutupdatesign); + + void a(PacketPlayOutNamedSoundEffect packetplayoutnamedsoundeffect); + + void a(PacketPlayOutCollect packetplayoutcollect); + + void a(PacketPlayOutEntityTeleport packetplayoutentityteleport); + + void a(PacketPlayOutUpdateAttributes packetplayoutupdateattributes); + + void a(PacketPlayOutEntityEffect packetplayoutentityeffect); + + void a(PacketPlayOutCombatEvent packetplayoutcombatevent); + + void a(PacketPlayOutServerDifficulty packetplayoutserverdifficulty); + + void a(PacketPlayOutCamera packetplayoutcamera); + + void a(PacketPlayOutWorldBorder packetplayoutworldborder); + + void a(PacketPlayOutTitle packetplayouttitle); + + void a(PacketPlayOutSetCompression packetplayoutsetcompression); + + void a(PacketPlayOutPlayerListHeaderFooter packetplayoutplayerlistheaderfooter); + + void a(PacketPlayOutResourcePackSend packetplayoutresourcepacksend); + + void a(PacketPlayOutUpdateEntityNBT packetplayoutupdateentitynbt); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketLoginInEncryptionBegin.java b/azurite-server/src/main/java/net/minecraft/server/PacketLoginInEncryptionBegin.java new file mode 100644 index 0000000..6769e9b --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketLoginInEncryptionBegin.java @@ -0,0 +1,37 @@ +package net.minecraft.server; + +import javax.crypto.SecretKey; +import java.io.IOException; +import java.security.PrivateKey; + +public class PacketLoginInEncryptionBegin implements Packet { + + public byte[] a = new byte[0]; + public byte[] b = new byte[0]; + + public PacketLoginInEncryptionBegin() {} + + public void a(PacketDataSerializer packetdataserializer) throws IOException { + // Paper start + this.a = packetdataserializer.readByteArray(256); + this.b = packetdataserializer.readByteArray(256); + // Paper end + } + + public void b(PacketDataSerializer packetdataserializer) throws IOException { + packetdataserializer.a(this.a); + packetdataserializer.a(this.b); + } + + public void a(PacketLoginInListener packetlogininlistener) { + packetlogininlistener.a(this); + } + + public SecretKey a(PrivateKey privatekey) { + return MinecraftEncryption.a(privatekey, this.a); + } + + public byte[] b(PrivateKey privatekey) { + return privatekey == null ? this.b : MinecraftEncryption.b(privatekey, this.b); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketLoginInListener.java b/azurite-server/src/main/java/net/minecraft/server/PacketLoginInListener.java new file mode 100644 index 0000000..96689a0 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketLoginInListener.java @@ -0,0 +1,8 @@ +package net.minecraft.server; + +public interface PacketLoginInListener extends PacketListener { + + void a(PacketLoginInStart packetlogininstart); + + void a(PacketLoginInEncryptionBegin packetlogininencryptionbegin); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketLoginInStart.java b/azurite-server/src/main/java/net/minecraft/server/PacketLoginInStart.java new file mode 100644 index 0000000..a8e3ff6 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketLoginInStart.java @@ -0,0 +1,32 @@ +package net.minecraft.server; + +import com.mojang.authlib.GameProfile; +import java.io.IOException; +import java.util.UUID; + +public class PacketLoginInStart implements Packet { + public GameProfile a; + + public PacketLoginInStart() { + } + + public PacketLoginInStart(GameProfile var1) { + this.a = var1; + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = new GameProfile((UUID)null, var1.c(16)); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.a(this.a.getName()); + } + + public void a(PacketLoginInListener var1) { + var1.a(this); + } + + public GameProfile a() { + return this.a; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketLoginOutDisconnect.java b/azurite-server/src/main/java/net/minecraft/server/PacketLoginOutDisconnect.java new file mode 100644 index 0000000..9dcc03f --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketLoginOutDisconnect.java @@ -0,0 +1,52 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; + +public class PacketLoginOutDisconnect implements Packet { + public IChatBaseComponent a; + private String serializedJson; + + public PacketLoginOutDisconnect() { + } + + public PacketLoginOutDisconnect(IChatBaseComponent var1) { + this.a = var1; + this.serializeJson(); + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.d(); + } + + public void b(PacketDataSerializer var1) throws IOException { + if (serializedJson != null) { + var1.a(serializedJson); + } else { + var1.a(this.a); + } + } + + public void serializeJson() { + this.serializedJson = IChatBaseComponent.ChatSerializer.a(this.a); + } + + @Override + public int getSize() { + if (serializedJson != null) { + return ProtocolUtils.getStringSize(this.serializedJson); + } else { + return ProtocolUtils.getChatComponentSize(this.a); + } + } + + @Override + public int getId() { + return 0x00; + } + + public void a(PacketLoginOutListener var1) { + var1.a(this); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketLoginOutEncryptionBegin.java b/azurite-server/src/main/java/net/minecraft/server/PacketLoginOutEncryptionBegin.java new file mode 100644 index 0000000..9dde55a --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketLoginOutEncryptionBegin.java @@ -0,0 +1,47 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; +import java.security.PublicKey; + +public class PacketLoginOutEncryptionBegin implements Packet { + public String a; + public PublicKey b; + public byte[] c; + + public PacketLoginOutEncryptionBegin() { + } + + public PacketLoginOutEncryptionBegin(String var1, PublicKey var2, byte[] var3) { + this.a = var1; + this.b = var2; + this.c = var3; + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.c(20); + this.b = MinecraftEncryption.a(var1.a()); + this.c = var1.a(); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.a(this.a); + var1.a(this.b.getEncoded()); + var1.a(this.c); + } + + @Override + public int getSize() { + return ProtocolUtils.getStringSize(this.a) + ProtocolUtils.getByteArraySize(this.b.getEncoded()) + ProtocolUtils.getByteArraySize(this.c); + } + + @Override + public int getId() { + return 0x01; + } + + public void a(PacketLoginOutListener var1) { + var1.a(this); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketLoginOutListener.java b/azurite-server/src/main/java/net/minecraft/server/PacketLoginOutListener.java new file mode 100644 index 0000000..2067b05 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketLoginOutListener.java @@ -0,0 +1,12 @@ +package net.minecraft.server; + +public interface PacketLoginOutListener extends PacketListener { + + void a(PacketLoginOutEncryptionBegin packetloginoutencryptionbegin); + + void a(PacketLoginOutSuccess packetloginoutsuccess); + + void a(PacketLoginOutDisconnect packetloginoutdisconnect); + + void a(PacketLoginOutSetCompression packetloginoutsetcompression); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketLoginOutSetCompression.java b/azurite-server/src/main/java/net/minecraft/server/PacketLoginOutSetCompression.java new file mode 100644 index 0000000..87cc4e8 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketLoginOutSetCompression.java @@ -0,0 +1,38 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; + +public class PacketLoginOutSetCompression implements Packet { + public int a; + + public PacketLoginOutSetCompression() { + } + + public PacketLoginOutSetCompression(int var1) { + this.a = var1; + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.e(); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.b(this.a); + } + + @Override + public int getSize() { + return ProtocolUtils.varIntBytes(this.a); + } + + @Override + public int getId() { + return 0x03; + } + + public void a(PacketLoginOutListener var1) { + var1.a(this); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketLoginOutSuccess.java b/azurite-server/src/main/java/net/minecraft/server/PacketLoginOutSuccess.java new file mode 100644 index 0000000..ebfcef1 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketLoginOutSuccess.java @@ -0,0 +1,46 @@ +package net.minecraft.server; + +import com.eatthepath.uuid.FastUUID; +import com.mojang.authlib.GameProfile; +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; +import java.util.UUID; + +public class PacketLoginOutSuccess implements Packet { + + public GameProfile a; + + public PacketLoginOutSuccess() { + } + + public PacketLoginOutSuccess(GameProfile gameprofile) { + this.a = gameprofile; + } + + public void a(PacketDataSerializer packetdataserializer) throws IOException { + this.a = new GameProfile(FastUUID.parseUUID(packetdataserializer.c(36)), packetdataserializer.c(16)); + } + + public void b(PacketDataSerializer packetdataserializer) throws IOException { + UUID uuid = this.a.getId(); + + packetdataserializer.a(uuid == null ? "" : FastUUID.toString(uuid)); + packetdataserializer.a(this.a.getName()); + } + + @Override + public int getSize() { + return ProtocolUtils.getStringSize(FastUUID.toString(this.a.getId())) + ProtocolUtils.getStringSize(this.a.getName()); + } + + @Override + public int getId() { + return 0x02; + } + + public void a(PacketLoginOutListener packetloginoutlistener) { + packetloginoutlistener.a(this); + } + +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayInAbilities.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayInAbilities.java new file mode 100644 index 0000000..fc2256b --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayInAbilities.java @@ -0,0 +1,101 @@ +package net.minecraft.server; + +import java.io.IOException; + +public class PacketPlayInAbilities implements Packet { + public boolean a; + public boolean b; + public boolean c; + public boolean d; + public float e; + public float f; + + public PacketPlayInAbilities() { + } + + public PacketPlayInAbilities(PlayerAbilities var1) { + this.a(var1.isInvulnerable); + this.b(var1.isFlying); + this.c(var1.canFly); + this.d(var1.canInstantlyBuild); + this.a(var1.a()); + this.b(var1.b()); + } + + public void a(PacketDataSerializer var1) throws IOException { + byte var2 = var1.readByte(); + this.a((var2 & 1) > 0); + this.b((var2 & 2) > 0); + this.c((var2 & 4) > 0); + this.d((var2 & 8) > 0); + this.a(var1.readFloat()); + this.b(var1.readFloat()); + } + + public void b(PacketDataSerializer var1) throws IOException { + byte var2 = 0; + if (this.a()) { + var2 = (byte)(var2 | 1); + } + + if (this.isFlying()) { + var2 = (byte)(var2 | 2); + } + + if (this.c()) { + var2 = (byte)(var2 | 4); + } + + if (this.d()) { + var2 = (byte)(var2 | 8); + } + + var1.writeByte(var2); + var1.writeFloat(this.e); + var1.writeFloat(this.f); + } + + public void a(PacketListenerPlayIn var1) { + var1.a(this); + } + + public boolean a() { + return this.a; + } + + public void a(boolean var1) { + this.a = var1; + } + + public boolean isFlying() { + return this.b; + } + + public void b(boolean var1) { + this.b = var1; + } + + public boolean c() { + return this.c; + } + + public void c(boolean var1) { + this.c = var1; + } + + public boolean d() { + return this.d; + } + + public void d(boolean var1) { + this.d = var1; + } + + public void a(float var1) { + this.e = var1; + } + + public void b(float var1) { + this.f = var1; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayInArmAnimation.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayInArmAnimation.java new file mode 100644 index 0000000..28cb5e3 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayInArmAnimation.java @@ -0,0 +1,20 @@ +package net.minecraft.server; + +import java.io.IOException; + +public class PacketPlayInArmAnimation implements Packet { + + public long timestamp; // Spigot + + public PacketPlayInArmAnimation() {} + + public void a(PacketDataSerializer packetdataserializer) throws IOException { + timestamp = System.currentTimeMillis(); // Spigot + } + + public void b(PacketDataSerializer packetdataserializer) throws IOException {} + + public void a(PacketListenerPlayIn packetlistenerplayin) { + packetlistenerplayin.a(this); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayInBlockDig.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayInBlockDig.java new file mode 100644 index 0000000..446865c --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayInBlockDig.java @@ -0,0 +1,52 @@ +package net.minecraft.server; + +import java.io.IOException; + +public class PacketPlayInBlockDig implements Packet { + public BlockPosition a; + public EnumDirection b; + public EnumPlayerDigType c; + + public PacketPlayInBlockDig() { + } + + public void a(PacketDataSerializer var1) throws IOException { + this.c = (EnumPlayerDigType)var1.a(EnumPlayerDigType.class); + this.a = var1.c(); + this.b = EnumDirection.fromType1(var1.readUnsignedByte()); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.a(this.c); + var1.a(this.a); + var1.writeByte(this.b.a()); + } + + public void a(PacketListenerPlayIn var1) { + var1.a(this); + } + + public BlockPosition a() { + return this.a; + } + + public EnumDirection b() { + return this.b; + } + + public EnumPlayerDigType c() { + return this.c; + } + + public static enum EnumPlayerDigType { + START_DESTROY_BLOCK, + ABORT_DESTROY_BLOCK, + STOP_DESTROY_BLOCK, + DROP_ALL_ITEMS, + DROP_ITEM, + RELEASE_USE_ITEM; + + private EnumPlayerDigType() { + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayInBlockPlace.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayInBlockPlace.java new file mode 100644 index 0000000..ac5928d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayInBlockPlace.java @@ -0,0 +1,78 @@ +package net.minecraft.server; + +import java.io.IOException; + +public class PacketPlayInBlockPlace implements Packet { + + public static final BlockPosition a = new BlockPosition(-1, -1, -1); + public BlockPosition b; + public int c; + public ItemStack d; + public float e; + public float f; + public float g; + + public long timestamp; // CraftBukkit + + public PacketPlayInBlockPlace() {} + + public PacketPlayInBlockPlace(ItemStack itemstack) { + this(PacketPlayInBlockPlace.a, 255, itemstack, 0.0F, 0.0F, 0.0F); + } + + public PacketPlayInBlockPlace(BlockPosition blockposition, int i, ItemStack itemstack, float f, float f1, float f2) { + this.b = blockposition; + this.c = i; + this.d = itemstack != null ? itemstack.cloneItemStack() : null; + this.e = f; + this.f = f1; + this.g = f2; + } + + public void a(PacketDataSerializer packetdataserializer) throws IOException { + timestamp = System.currentTimeMillis(); // CraftBukkit + this.b = packetdataserializer.c(); + this.c = packetdataserializer.readUnsignedByte(); + this.d = packetdataserializer.i(); + this.e = (float) packetdataserializer.readUnsignedByte() / 16.0F; + this.f = (float) packetdataserializer.readUnsignedByte() / 16.0F; + this.g = (float) packetdataserializer.readUnsignedByte() / 16.0F; + } + + public void b(PacketDataSerializer packetdataserializer) throws IOException { + packetdataserializer.a(this.b); + packetdataserializer.writeByte(this.c); + packetdataserializer.a(this.d); + packetdataserializer.writeByte((int) (this.e * 16.0F)); + packetdataserializer.writeByte((int) (this.f * 16.0F)); + packetdataserializer.writeByte((int) (this.g * 16.0F)); + } + + public void a(PacketListenerPlayIn packetlistenerplayin) { + packetlistenerplayin.a(this); + } + + public BlockPosition a() { + return this.b; + } + + public int getFace() { + return this.c; + } + + public ItemStack getItemStack() { + return this.d; + } + + public float d() { + return this.e; + } + + public float e() { + return this.f; + } + + public float f() { + return this.g; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayInChat.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayInChat.java new file mode 100644 index 0000000..2724550 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayInChat.java @@ -0,0 +1,43 @@ +package net.minecraft.server; + +import dev.azurite.spigot.Azurite; +import dev.azurite.spigot.configs.AzuriteConfig; + +import java.io.IOException; + +public class PacketPlayInChat implements Packet { + + public String a; + + public PacketPlayInChat() { + } + + public PacketPlayInChat(String s) { + if (s.length() > 100) { + s = s.substring(0, 100); + } + + this.a = s; + } + + public void a(PacketDataSerializer packetdataserializer) throws IOException { + this.a = packetdataserializer.c(AzuriteConfig.maxChatLength.getValue()); + } + + public void b(PacketDataSerializer packetdataserializer) throws IOException { + packetdataserializer.a(this.a); + } + + public void a(final PacketListenerPlayIn packetlistenerplayin) { + if (!a.startsWith("/")) { + Azurite.getInstance().getThreadingManager().getAsyncExecutor().queueChat(() -> packetlistenerplayin.a(PacketPlayInChat.this)); + return; + } + // Spigot End + packetlistenerplayin.a(this); + } + + public String a() { + return this.a; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayInClientCommand.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayInClientCommand.java new file mode 100644 index 0000000..1ded13b --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayInClientCommand.java @@ -0,0 +1,39 @@ +package net.minecraft.server; + +import java.io.IOException; + +public class PacketPlayInClientCommand implements Packet { + public EnumClientCommand a; + + public PacketPlayInClientCommand() { + } + + public PacketPlayInClientCommand(EnumClientCommand var1) { + this.a = var1; + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = (EnumClientCommand)var1.a(EnumClientCommand.class); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.a(this.a); + } + + public void a(PacketListenerPlayIn var1) { + var1.a(this); + } + + public EnumClientCommand a() { + return this.a; + } + + public static enum EnumClientCommand { + PERFORM_RESPAWN, + REQUEST_STATS, + OPEN_INVENTORY_ACHIEVEMENT; + + private EnumClientCommand() { + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayInCloseWindow.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayInCloseWindow.java new file mode 100644 index 0000000..05c88a6 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayInCloseWindow.java @@ -0,0 +1,28 @@ +package net.minecraft.server; + +import java.io.IOException; + +public class PacketPlayInCloseWindow implements Packet { + + public int id; + + public PacketPlayInCloseWindow() {} + + // CraftBukkit start + public PacketPlayInCloseWindow(int id) { + this.id = id; + } + // CraftBukkit end + + public void a(PacketListenerPlayIn packetlistenerplayin) { + packetlistenerplayin.a(this); + } + + public void a(PacketDataSerializer packetdataserializer) throws IOException { + this.id = packetdataserializer.readByte(); + } + + public void b(PacketDataSerializer packetdataserializer) throws IOException { + packetdataserializer.writeByte(this.id); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayInCustomPayload.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayInCustomPayload.java new file mode 100644 index 0000000..37197c3 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayInCustomPayload.java @@ -0,0 +1,38 @@ +package net.minecraft.server; + +import java.io.IOException; + +public class PacketPlayInCustomPayload implements Packet { + public String a; + public PacketDataSerializer b; + + public PacketPlayInCustomPayload() { + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.c(20); + int var2 = var1.readableBytes(); + if (var2 >= 0 && var2 <= 32767) { + this.b = new PacketDataSerializer(var1.readBytes(var2)); + } else { + throw new IOException("Payload may not be larger than 32767 bytes"); + } + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.a(this.a); + var1.writeBytes(this.b); + } + + public void a(PacketListenerPlayIn var1) { + var1.a(this); + } + + public String a() { + return this.a; + } + + public PacketDataSerializer b() { + return this.b; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayInEnchantItem.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayInEnchantItem.java new file mode 100644 index 0000000..9082aab --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayInEnchantItem.java @@ -0,0 +1,33 @@ +package net.minecraft.server; + +import java.io.IOException; + +public class PacketPlayInEnchantItem implements Packet { + public int a; + public int b; + + public PacketPlayInEnchantItem() { + } + + public void a(PacketListenerPlayIn var1) { + var1.a(this); + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.readByte(); + this.b = var1.readByte(); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.writeByte(this.a); + var1.writeByte(this.b); + } + + public int a() { + return this.a; + } + + public int b() { + return this.b; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayInEntityAction.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayInEntityAction.java new file mode 100644 index 0000000..9956b59 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayInEntityAction.java @@ -0,0 +1,49 @@ +package net.minecraft.server; + +import java.io.IOException; + +public class PacketPlayInEntityAction implements Packet { + public int a; + public EnumPlayerAction animation; + public int c; + + public PacketPlayInEntityAction() { + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.e(); + this.animation = (EnumPlayerAction)var1.a(EnumPlayerAction.class); + this.c = var1.e(); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.b(this.a); + var1.a(this.animation); + var1.b(this.c); + } + + public void a(PacketListenerPlayIn var1) { + var1.a(this); + } + + public EnumPlayerAction b() { + return this.animation; + } + + public int c() { + return this.c; + } + + public static enum EnumPlayerAction { + START_SNEAKING, + STOP_SNEAKING, + STOP_SLEEPING, + START_SPRINTING, + STOP_SPRINTING, + RIDING_JUMP, + OPEN_INVENTORY; + + private EnumPlayerAction() { + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayInFlying.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayInFlying.java new file mode 100644 index 0000000..9080d87 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayInFlying.java @@ -0,0 +1,128 @@ +package net.minecraft.server; + +import java.io.IOException; + +public class PacketPlayInFlying implements Packet { + public double x; + public double y; + public double z; + public float yaw; + public float pitch; + public boolean f; + public boolean hasPos; + public boolean hasLook; + + public PacketPlayInFlying() { + } + + public void a(PacketListenerPlayIn var1) { + var1.a(this); + } + + public void a(PacketDataSerializer var1) throws IOException { + this.f = var1.readUnsignedByte() != 0; + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.writeByte(this.f ? 1 : 0); + } + + public double a() { + return this.x; + } + + public double b() { + return this.y; + } + + public double c() { + return this.z; + } + + public float d() { + return this.yaw; + } + + public float e() { + return this.pitch; + } + + public boolean f() { + return this.f; + } + + public boolean g() { + return this.hasPos; + } + + public boolean h() { + return this.hasLook; + } + + public void a(boolean var1) { + this.hasPos = var1; + } + + public static class PacketPlayInLook extends PacketPlayInFlying { + public PacketPlayInLook() { + this.hasLook = true; + } + + public void a(PacketDataSerializer var1) throws IOException { + this.yaw = var1.readFloat(); + this.pitch = var1.readFloat(); + super.a(var1); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.writeFloat(this.yaw); + var1.writeFloat(this.pitch); + super.b(var1); + } + } + + public static class PacketPlayInPosition extends PacketPlayInFlying { + public PacketPlayInPosition() { + this.hasPos = true; + } + + public void a(PacketDataSerializer var1) throws IOException { + this.x = var1.readDouble(); + this.y = var1.readDouble(); + this.z = var1.readDouble(); + super.a(var1); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.writeDouble(this.x); + var1.writeDouble(this.y); + var1.writeDouble(this.z); + super.b(var1); + } + } + + public static class PacketPlayInPositionLook extends PacketPlayInFlying { + public PacketPlayInPositionLook() { + this.hasPos = true; + this.hasLook = true; + } + + public void a(PacketDataSerializer var1) throws IOException { + this.x = var1.readDouble(); + this.y = var1.readDouble(); + this.z = var1.readDouble(); + this.yaw = var1.readFloat(); + this.pitch = var1.readFloat(); + super.a(var1); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.writeDouble(this.x); + var1.writeDouble(this.y); + var1.writeDouble(this.z); + var1.writeFloat(this.yaw); + var1.writeFloat(this.pitch); + super.b(var1); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayInHeldItemSlot.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayInHeldItemSlot.java new file mode 100644 index 0000000..7314424 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayInHeldItemSlot.java @@ -0,0 +1,26 @@ +package net.minecraft.server; + +import java.io.IOException; + +public class PacketPlayInHeldItemSlot implements Packet { + public int itemInHandIndex; + + public PacketPlayInHeldItemSlot() { + } + + public void a(PacketDataSerializer var1) throws IOException { + this.itemInHandIndex = var1.readShort(); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.writeShort(this.itemInHandIndex); + } + + public void a(PacketListenerPlayIn var1) { + var1.a(this); + } + + public int a() { + return this.itemInHandIndex; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayInKeepAlive.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayInKeepAlive.java new file mode 100644 index 0000000..de07963 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayInKeepAlive.java @@ -0,0 +1,26 @@ +package net.minecraft.server; + +import java.io.IOException; + +public class PacketPlayInKeepAlive implements Packet { + public int a; + + public PacketPlayInKeepAlive() { + } + + public void a(PacketListenerPlayIn var1) { + var1.a(this); + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.e(); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.b(this.a); + } + + public int a() { + return this.a; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayInResourcePackStatus.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayInResourcePackStatus.java new file mode 100644 index 0000000..b9694ee --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayInResourcePackStatus.java @@ -0,0 +1,32 @@ +package net.minecraft.server; + +import java.io.IOException; + +public class PacketPlayInResourcePackStatus implements Packet { + + public String a; + public PacketPlayInResourcePackStatus.EnumResourcePackStatus b; // PAIL: private -> public, rename: status + + public PacketPlayInResourcePackStatus() {} + + public void a(PacketDataSerializer packetdataserializer) throws IOException { + this.a = packetdataserializer.c(40); + this.b = packetdataserializer.a(PacketPlayInResourcePackStatus.EnumResourcePackStatus.class); + } + + public void b(PacketDataSerializer packetdataserializer) throws IOException { + packetdataserializer.a(this.a); + packetdataserializer.a(this.b); + } + + public void a(PacketListenerPlayIn packetlistenerplayin) { + packetlistenerplayin.a(this); + } + + public enum EnumResourcePackStatus { + + SUCCESSFULLY_LOADED, DECLINED, FAILED_DOWNLOAD, ACCEPTED; + + EnumResourcePackStatus() {} + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayInSetCreativeSlot.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayInSetCreativeSlot.java new file mode 100644 index 0000000..27e5c36 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayInSetCreativeSlot.java @@ -0,0 +1,33 @@ +package net.minecraft.server; + +import java.io.IOException; + +public class PacketPlayInSetCreativeSlot implements Packet { + public int slot; + public ItemStack b; + + public PacketPlayInSetCreativeSlot() { + } + + public void a(PacketListenerPlayIn var1) { + var1.a(this); + } + + public void a(PacketDataSerializer var1) throws IOException { + this.slot = var1.readShort(); + this.b = var1.i(); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.writeShort(this.slot); + var1.a(this.b); + } + + public int a() { + return this.slot; + } + + public ItemStack getItemStack() { + return this.b; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayInSettings.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayInSettings.java new file mode 100644 index 0000000..2b28757 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayInSettings.java @@ -0,0 +1,51 @@ +package net.minecraft.server; + +import java.io.IOException; +import net.minecraft.server.EntityHuman.EnumChatVisibility; + +public class PacketPlayInSettings implements Packet { + public String a; + public int b; + public EntityHuman.EnumChatVisibility c; + public boolean d; + public int e; + + public PacketPlayInSettings() { + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.c(7); + this.b = var1.readByte(); + this.c = EnumChatVisibility.a(var1.readByte()); + this.d = var1.readBoolean(); + this.e = var1.readUnsignedByte(); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.a(this.a); + var1.writeByte(this.b); + var1.writeByte(this.c.a()); + var1.writeBoolean(this.d); + var1.writeByte(this.e); + } + + public void a(PacketListenerPlayIn var1) { + var1.a(this); + } + + public String a() { + return this.a; + } + + public EntityHuman.EnumChatVisibility c() { + return this.c; + } + + public boolean d() { + return this.d; + } + + public int e() { + return this.e; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayInSpectate.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayInSpectate.java new file mode 100644 index 0000000..4d754ad --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayInSpectate.java @@ -0,0 +1,31 @@ +package net.minecraft.server; + +import java.io.IOException; +import java.util.UUID; + +public class PacketPlayInSpectate implements Packet { + public UUID a; + + public PacketPlayInSpectate() { + } + + public PacketPlayInSpectate(UUID var1) { + this.a = var1; + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.g(); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.a(this.a); + } + + public void a(PacketListenerPlayIn var1) { + var1.a(this); + } + + public Entity a(WorldServer var1) { + return var1.getEntity(this.a); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayInSteerVehicle.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayInSteerVehicle.java new file mode 100644 index 0000000..c2f54d6 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayInSteerVehicle.java @@ -0,0 +1,56 @@ +package net.minecraft.server; + +import java.io.IOException; + +public class PacketPlayInSteerVehicle implements Packet { + public float a; + public float b; + public boolean c; + public boolean d; + + public PacketPlayInSteerVehicle() { + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.readFloat(); + this.b = var1.readFloat(); + byte var2 = var1.readByte(); + this.c = (var2 & 1) > 0; + this.d = (var2 & 2) > 0; + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.writeFloat(this.a); + var1.writeFloat(this.b); + byte var2 = 0; + if (this.c) { + var2 = (byte)(var2 | 1); + } + + if (this.d) { + var2 = (byte)(var2 | 2); + } + + var1.writeByte(var2); + } + + public void a(PacketListenerPlayIn var1) { + var1.a(this); + } + + public float a() { + return this.a; + } + + public float b() { + return this.b; + } + + public boolean c() { + return this.c; + } + + public boolean d() { + return this.d; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayInTabComplete.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayInTabComplete.java new file mode 100644 index 0000000..eed040d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayInTabComplete.java @@ -0,0 +1,52 @@ +package net.minecraft.server; + +import java.io.IOException; +import org.apache.commons.lang3.StringUtils; + +public class PacketPlayInTabComplete implements Packet { + public String a; + public BlockPosition b; + + public PacketPlayInTabComplete() { + } + + public PacketPlayInTabComplete(String var1) { + this(var1, (BlockPosition)null); + } + + public PacketPlayInTabComplete(String var1, BlockPosition var2) { + this.a = var1; + this.b = var2; + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.c(32767); + boolean var2 = var1.readBoolean(); + if (var2) { + this.b = var1.c(); + } + + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.a(StringUtils.substring(this.a, 0, 32767)); + boolean var2 = this.b != null; + var1.writeBoolean(var2); + if (var2) { + var1.a(this.b); + } + + } + + public void a(PacketListenerPlayIn var1) { + var1.a(this); + } + + public String a() { + return this.a; + } + + public BlockPosition b() { + return this.b; + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayInTransaction.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayInTransaction.java new file mode 100644 index 0000000..00baafd --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayInTransaction.java @@ -0,0 +1,36 @@ +package net.minecraft.server; + +import java.io.IOException; + +public class PacketPlayInTransaction implements Packet { + public int a; + public short b; + public boolean c; + + public PacketPlayInTransaction() { + } + + public void a(PacketListenerPlayIn var1) { + var1.a(this); + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.readByte(); + this.b = var1.readShort(); + this.c = var1.readByte() != 0; + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.writeByte(this.a); + var1.writeShort(this.b); + var1.writeByte(this.c ? 1 : 0); + } + + public int a() { + return this.a; + } + + public short b() { + return this.b; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayInUpdateSign.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayInUpdateSign.java new file mode 100644 index 0000000..1d305b8 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayInUpdateSign.java @@ -0,0 +1,47 @@ +package net.minecraft.server; + +import java.io.IOException; +import net.minecraft.server.IChatBaseComponent.ChatSerializer; + +public class PacketPlayInUpdateSign implements Packet { + public BlockPosition a; + public IChatBaseComponent[] b; + + public PacketPlayInUpdateSign() { + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.c(); + this.b = new IChatBaseComponent[4]; + + for(int var2 = 0; var2 < 4; ++var2) { + String var3 = var1.c(384); + IChatBaseComponent var4 = ChatSerializer.a(var3); + this.b[var2] = var4; + } + + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.a(this.a); + + for(int var2 = 0; var2 < 4; ++var2) { + IChatBaseComponent var3 = this.b[var2]; + String var4 = ChatSerializer.a(var3); + var1.a(var4); + } + + } + + public void a(PacketListenerPlayIn var1) { + var1.a(this); + } + + public BlockPosition a() { + return this.a; + } + + public IChatBaseComponent[] b() { + return this.b; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayInUseEntity.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayInUseEntity.java new file mode 100644 index 0000000..ce834d6 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayInUseEntity.java @@ -0,0 +1,51 @@ +package net.minecraft.server; + +import java.io.IOException; + +public class PacketPlayInUseEntity implements Packet { + public int a; + public EnumEntityUseAction action; + public Vec3D c; + + public void a(PacketDataSerializer serializer) throws IOException { + this.a = serializer.e(); + this.action = serializer.a(EnumEntityUseAction.class); + if (this.action == EnumEntityUseAction.INTERACT_AT) + this.c = new Vec3D(serializer.readFloat(), serializer.readFloat(), serializer.readFloat()); + } + + public void b(PacketDataSerializer serializer) throws IOException { + serializer.b(this.a); + serializer.a(this.action); + if (this.action == EnumEntityUseAction.INTERACT_AT) { + serializer.writeFloat((float)this.c.a); + serializer.writeFloat((float)this.c.b); + serializer.writeFloat((float)this.c.c); + } + } + + public void a(PacketListenerPlayIn listener) { + listener.a(this); + } + + public Entity a(World world) { + return world.a(this.a); + } + + public EnumEntityUseAction a() { + return this.action; + } + + public Vec3D b() { + return this.c; + } + + // Beanes - obf helper + public int getEntityId() { + return this.a; + } + + public enum EnumEntityUseAction { + INTERACT, ATTACK, INTERACT_AT + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayInWindowClick.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayInWindowClick.java new file mode 100644 index 0000000..a84d513 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayInWindowClick.java @@ -0,0 +1,61 @@ +package net.minecraft.server; + +import java.io.IOException; + +public class PacketPlayInWindowClick implements Packet { + public int a; + public int slot; + public int button; + public short d; + public ItemStack item; + public int shift; + + public PacketPlayInWindowClick() { + } + + public void a(PacketListenerPlayIn var1) { + var1.a(this); + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.readByte(); + this.slot = var1.readShort(); + this.button = var1.readByte(); + this.d = var1.readShort(); + this.shift = var1.readByte(); + this.item = var1.i(); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.writeByte(this.a); + var1.writeShort(this.slot); + var1.writeByte(this.button); + var1.writeShort(this.d); + var1.writeByte(this.shift); + var1.a(this.item); + } + + public int a() { + return this.a; + } + + public int b() { + return this.slot; + } + + public int c() { + return this.button; + } + + public short d() { + return this.d; + } + + public ItemStack e() { + return this.item; + } + + public int f() { + return this.shift; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutAbilities.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutAbilities.java new file mode 100644 index 0000000..9c53d27 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutAbilities.java @@ -0,0 +1,111 @@ +package net.minecraft.server; + +import java.io.IOException; + +public class PacketPlayOutAbilities implements Packet { + public boolean a; + public boolean b; + public boolean c; + public boolean d; + public float e; + public float f; + + public PacketPlayOutAbilities() { + } + + public PacketPlayOutAbilities(PlayerAbilities var1) { + this.a(var1.isInvulnerable); + this.b(var1.isFlying); + this.c(var1.canFly); + this.d(var1.canInstantlyBuild); + this.a(var1.a()); + this.b(var1.b()); + } + + public void a(PacketDataSerializer var1) throws IOException { + byte var2 = var1.readByte(); + this.a((var2 & 1) > 0); + this.b((var2 & 2) > 0); + this.c((var2 & 4) > 0); + this.d((var2 & 8) > 0); + this.a(var1.readFloat()); + this.b(var1.readFloat()); + } + + public void b(PacketDataSerializer var1) throws IOException { + byte var2 = 0; + if (this.a()) { + var2 = (byte)(var2 | 1); + } + + if (this.b()) { + var2 = (byte)(var2 | 2); + } + + if (this.c()) { + var2 = (byte)(var2 | 4); + } + + if (this.d()) { + var2 = (byte)(var2 | 8); + } + + var1.writeByte(var2); + var1.writeFloat(this.e); + var1.writeFloat(this.f); + } + + @Override + public int getSize() { + return 1 + 4 + 4; + } + + @Override + public int getId() { + return 0x39; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } + + public boolean a() { + return this.a; + } + + public void a(boolean var1) { + this.a = var1; + } + + public boolean b() { + return this.b; + } + + public void b(boolean var1) { + this.b = var1; + } + + public boolean c() { + return this.c; + } + + public void c(boolean var1) { + this.c = var1; + } + + public boolean d() { + return this.d; + } + + public void d(boolean var1) { + this.d = var1; + } + + public void a(float var1) { + this.e = var1; + } + + public void b(float var1) { + this.f = var1; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutAnimation.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutAnimation.java new file mode 100644 index 0000000..17475e2 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutAnimation.java @@ -0,0 +1,42 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; + +public class PacketPlayOutAnimation implements Packet { + public int a; + public int b; + + public PacketPlayOutAnimation() { + } + + public PacketPlayOutAnimation(Entity var1, int var2) { + this.a = var1.getId(); + this.b = var2; + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.e(); + this.b = var1.readUnsignedByte(); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.b(this.a); + var1.writeByte(this.b); + } + + @Override + public int getSize() { + return ProtocolUtils.varIntBytes(this.a) + 1; + } + + @Override + public int getId() { + return 0x0B; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutAttachEntity.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutAttachEntity.java new file mode 100644 index 0000000..3ef3f2c --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutAttachEntity.java @@ -0,0 +1,42 @@ +package net.minecraft.server; + +import java.io.IOException; + +public class PacketPlayOutAttachEntity implements Packet { + public int a, b, c; + + public PacketPlayOutAttachEntity(int leash, Entity entity, Entity vehicle) { + this.a = leash; + this.b = entity.getId(); + this.c = (vehicle != null) ? vehicle.getId() : -1; + } + + public PacketPlayOutAttachEntity() { + } + + public void a(PacketDataSerializer serializer) throws IOException { + this.b = serializer.readInt(); + this.c = serializer.readInt(); + this.a = serializer.readUnsignedByte(); + } + + public void b(PacketDataSerializer serializer) throws IOException { + serializer.writeInt(this.b); + serializer.writeInt(this.c); + serializer.writeByte(this.a); + } + + @Override + public int getSize() { + return 4 + 4 + 1; + } + + @Override + public int getId() { + return 0x1b; + } + + public void a(PacketListenerPlayOut listener) { + listener.a(this); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutBed.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutBed.java new file mode 100644 index 0000000..86f9a84 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutBed.java @@ -0,0 +1,43 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; + +public class PacketPlayOutBed implements Packet { + // Beanes make public + public int a; + public BlockPosition b; + + public PacketPlayOutBed() { + } + + public PacketPlayOutBed(EntityHuman var1, BlockPosition var2) { + this.a = var1.getId(); + this.b = var2; + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.e(); + this.b = var1.c(); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.b(this.a); + var1.a(this.b); + } + + @Override + public int getSize() { + return ProtocolUtils.varIntBytes(a) + 8; + } + + @Override + public int getId() { + return 0x0A; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutBlockAction.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutBlockAction.java new file mode 100644 index 0000000..66c3733 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutBlockAction.java @@ -0,0 +1,50 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; + +public class PacketPlayOutBlockAction implements Packet { + public BlockPosition a; + public int b; + public int c; + public Block d; + + public PacketPlayOutBlockAction() { + } + + public PacketPlayOutBlockAction(BlockPosition var1, Block var2, int var3, int var4) { + this.a = var1; + this.b = var3; + this.c = var4; + this.d = var2; + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.c(); + this.b = var1.readUnsignedByte(); + this.c = var1.readUnsignedByte(); + this.d = Block.getById(var1.e() & 4095); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.a(this.a); + var1.writeByte(this.b); + var1.writeByte(this.c); + var1.b(Block.getId(this.d) & 4095); + } + + @Override + public int getSize() { + return 8 + 1 + 1 + ProtocolUtils.varIntBytes(Block.getId(this.d) & 4095); + } + + @Override + public int getId() { + return 0x24; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutBlockBreakAnimation.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutBlockBreakAnimation.java new file mode 100644 index 0000000..9f48486 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutBlockBreakAnimation.java @@ -0,0 +1,46 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; + +public class PacketPlayOutBlockBreakAnimation implements Packet { + public int a; + public BlockPosition b; + public int c; + + public PacketPlayOutBlockBreakAnimation() { + } + + public PacketPlayOutBlockBreakAnimation(int var1, BlockPosition var2, int var3) { + this.a = var1; + this.b = var2; + this.c = var3; + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.e(); + this.b = var1.c(); + this.c = var1.readUnsignedByte(); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.b(this.a); + var1.a(this.b); + var1.writeByte(this.c); + } + + @Override + public int getSize() { + return ProtocolUtils.varIntBytes(this.a) + 8 + 1; + } + + @Override + public int getId() { + return 0x25; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutBlockChange.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutBlockChange.java new file mode 100644 index 0000000..a92f6dc --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutBlockChange.java @@ -0,0 +1,54 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; + +public class PacketPlayOutBlockChange implements Packet { + + public BlockPosition a; + public IBlockData block; + + public PacketPlayOutBlockChange() { + } + + public PacketPlayOutBlockChange(World world, BlockPosition blockposition) { + this.a = blockposition; + this.block = world.getType(blockposition); + } + + public PacketPlayOutBlockChange(World world, Chunk chunk, BlockPosition blockposition) { + this.a = blockposition; + this.block = world.getType(chunk, blockposition); + } + + public PacketPlayOutBlockChange(BlockPosition blockposition, IBlockData block) { + this.a = blockposition; + this.block = block; + } + + public void a(PacketDataSerializer packetdataserializer) throws IOException { + this.a = packetdataserializer.c(); + this.block = Block.d.a(packetdataserializer.e()); + } + + public void b(PacketDataSerializer packetdataserializer) throws IOException { + packetdataserializer.a(this.a); + packetdataserializer.b(Block.d.b(this.block)); + } + + @Override + public int getSize() { + return 8 + ProtocolUtils.varIntBytes(Block.d.b(this.block)); + } + + @Override + public int getId() { + return 0x23; + } + + public void a(PacketListenerPlayOut packetlistenerplayout) { + packetlistenerplayout.a(this); + } + +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutCamera.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutCamera.java new file mode 100644 index 0000000..79c009d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutCamera.java @@ -0,0 +1,38 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; + +public class PacketPlayOutCamera implements Packet { + public int a; + + public PacketPlayOutCamera() { + } + + public PacketPlayOutCamera(Entity var1) { + this.a = var1.getId(); + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.e(); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.b(this.a); + } + + @Override + public int getSize() { + return ProtocolUtils.varIntBytes(this.a); + } + + @Override + public int getId() { + return 0x43; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutChat.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutChat.java new file mode 100644 index 0000000..6316ee1 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutChat.java @@ -0,0 +1,76 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; + +public class PacketPlayOutChat implements Packet { + + public IChatBaseComponent a; + public net.md_5.bungee.api.chat.BaseComponent[] components; // Spigot + public byte b; + private String serializedJson = null; + + public PacketPlayOutChat() {} + + public PacketPlayOutChat(IChatBaseComponent ichatbasecomponent) { + this(ichatbasecomponent, (byte) 1); + } + + public PacketPlayOutChat(IChatBaseComponent ichatbasecomponent, byte b0) { + this.a = ichatbasecomponent; + this.b = b0; + this.serializeJson(); + } + + public void a(PacketDataSerializer packetdataserializer) throws IOException { + this.a = packetdataserializer.d(); + this.b = packetdataserializer.readByte(); + } + + public void b(PacketDataSerializer packetdataserializer) throws IOException { + // Spigot start + if (components != null) { + packetdataserializer.a(net.md_5.bungee.chat.ComponentSerializer.toString(components)); + } else { + packetdataserializer.a(this.a); + } + // Spigot end + packetdataserializer.writeByte(this.b); + } + + // Beanes - only serialize chat json once + public void serializeJson() { + if (components != null) { + serializedJson = net.md_5.bungee.chat.ComponentSerializer.toString(components); + } else { + serializedJson = IChatBaseComponent.ChatSerializer.a(this.a); + } + } + + @Override + public int getSize() { + if (serializedJson != null) { + return ProtocolUtils.getStringSize(serializedJson) + 1; + } + + if (components != null) { + return ProtocolUtils.getChatComponentSize(components) + 1; + } else { + return ProtocolUtils.getChatComponentSize(this.a) + 1; + } + } + + @Override + public int getId() { + return 0x02; + } + + public void a(PacketListenerPlayOut packetlistenerplayout) { + packetlistenerplayout.a(this); + } + + public boolean b() { + return this.b == 1 || this.b == 2; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutCloseWindow.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutCloseWindow.java new file mode 100644 index 0000000..4577c64 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutCloseWindow.java @@ -0,0 +1,41 @@ +// +// Source code recreated from a .class file by IntelliJ IDEA +// (powered by FernFlower decompiler) +// + +package net.minecraft.server; + +import java.io.IOException; + +public class PacketPlayOutCloseWindow implements Packet { + public int a; + + public PacketPlayOutCloseWindow() { + } + + public PacketPlayOutCloseWindow(int windowId) { + this.a = windowId; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.readUnsignedByte(); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.writeByte(this.a); + } + + @Override + public int getSize() { + return 1; + } + + @Override + public int getId() { + return 0x2e; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutCollect.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutCollect.java new file mode 100644 index 0000000..34efea9 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutCollect.java @@ -0,0 +1,42 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; + +public class PacketPlayOutCollect implements Packet { + public int a; + public int b; + + public PacketPlayOutCollect() { + } + + public PacketPlayOutCollect(int var1, int var2) { + this.a = var1; + this.b = var2; + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.e(); + this.b = var1.e(); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.b(this.a); + var1.b(this.b); + } + + @Override + public int getSize() { + return ProtocolUtils.varIntBytes(this.a) + ProtocolUtils.varIntBytes(this.b); + } + + @Override + public int getId() { + return 0x0D; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutCombatEvent.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutCombatEvent.java new file mode 100644 index 0000000..84d9bc9 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutCombatEvent.java @@ -0,0 +1,88 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; + +public class PacketPlayOutCombatEvent implements Packet { + public EnumCombatEventType a; + public int b; + public int c; + public int d; + public String e; + + public PacketPlayOutCombatEvent() { + } + + public PacketPlayOutCombatEvent(CombatTracker var1, EnumCombatEventType var2) { + this.a = var2; + EntityLiving var3 = var1.c(); + switch (var2) { + case END_COMBAT: + this.d = var1.f(); + this.c = var3 == null ? -1 : var3.getId(); + break; + case ENTITY_DIED: + this.b = var1.h().getId(); + this.c = var3 == null ? -1 : var3.getId(); + this.e = var1.b().c(); + } + + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = (EnumCombatEventType)var1.a(EnumCombatEventType.class); + if (this.a == PacketPlayOutCombatEvent.EnumCombatEventType.END_COMBAT) { + this.d = var1.e(); + this.c = var1.readInt(); + } else if (this.a == PacketPlayOutCombatEvent.EnumCombatEventType.ENTITY_DIED) { + this.b = var1.e(); + this.c = var1.readInt(); + this.e = var1.c(32767); + } + + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.a(this.a); + if (this.a == PacketPlayOutCombatEvent.EnumCombatEventType.END_COMBAT) { + var1.b(this.d); + var1.writeInt(this.c); + } else if (this.a == PacketPlayOutCombatEvent.EnumCombatEventType.ENTITY_DIED) { + var1.b(this.b); + var1.writeInt(this.c); + var1.a(this.e); + } + } + + @Override + public int getSize() { + int size = ProtocolUtils.getEnumSize(this.a); + + if (this.a == PacketPlayOutCombatEvent.EnumCombatEventType.END_COMBAT) { + size += ProtocolUtils.varIntBytes(this.d) + 4; + } else if (this.a == PacketPlayOutCombatEvent.EnumCombatEventType.ENTITY_DIED) { + size += ProtocolUtils.varIntBytes(this.b) + 4 + ProtocolUtils.getStringSize(this.e); + } + + return size; + } + + @Override + public int getId() { + return 0x42; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } + + public static enum EnumCombatEventType { + ENTER_COMBAT, + END_COMBAT, + ENTITY_DIED; + + private EnumCombatEventType() { + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutCustomPayload.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutCustomPayload.java new file mode 100644 index 0000000..6d7e35e --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutCustomPayload.java @@ -0,0 +1,50 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; + +public class PacketPlayOutCustomPayload implements Packet { + public String a; + public PacketDataSerializer b; + + public PacketPlayOutCustomPayload() { + } + + public PacketPlayOutCustomPayload(String channel, PacketDataSerializer packetDataSerializer) { + this.a = channel; + this.b = packetDataSerializer; + if (packetDataSerializer.writerIndex() > 1048576) { + throw new IllegalArgumentException("Payload may not be larger than 1048576 bytes"); + } + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.c(20); + int var2 = var1.readableBytes(); + if (var2 >= 0 && var2 <= 1048576) { + this.b = new PacketDataSerializer(var1.readBytes(var2)); + } else { + throw new IOException("Payload may not be larger than 1048576 bytes"); + } + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.a(this.a); + var1.writeBytes(this.b); + } + + @Override + public int getSize() { + return ProtocolUtils.getStringSize(this.a) + this.b.writerIndex(); + } + + @Override + public int getId() { + return 0x3f; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutEntity.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutEntity.java new file mode 100644 index 0000000..5d8699c --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutEntity.java @@ -0,0 +1,173 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; + +public class PacketPlayOutEntity implements Packet { + public int a; + public byte b; + public byte c; + public byte d; + public byte e; + public byte f; + public boolean g; + public boolean h; + + public PacketPlayOutEntity() { + } + + public PacketPlayOutEntity(int var1) { + this.a = var1; + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.e(); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.b(this.a); + } + + @Override + public int getSize() { + return ProtocolUtils.varIntBytes(this.a); + } + + @Override + public int getId() { + return 0x14; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } + + public String toString() { + return "Entity_" + super.toString(); + } + + public static class PacketPlayOutEntityLook extends PacketPlayOutEntity { + public PacketPlayOutEntityLook() { + this.h = true; + } + + public PacketPlayOutEntityLook(int var1, byte var2, byte var3, boolean var4) { + super(var1); + this.e = var2; + this.f = var3; + this.h = true; + this.g = var4; + } + + public void a(PacketDataSerializer var1) throws IOException { + super.a(var1); + this.e = var1.readByte(); + this.f = var1.readByte(); + this.g = var1.readBoolean(); + } + + public void b(PacketDataSerializer var1) throws IOException { + super.b(var1); + var1.writeByte(this.e); + var1.writeByte(this.f); + var1.writeBoolean(this.g); + } + + @Override + public int getSize() { + return super.getSize() + 1 + 1 + 1; + } + + @Override + public int getId() { + return 0x16; + } + } + + public static class PacketPlayOutRelEntityMove extends PacketPlayOutEntity { + public PacketPlayOutRelEntityMove() { + } + + public PacketPlayOutRelEntityMove(int var1, byte var2, byte var3, byte var4, boolean var5) { + super(var1); + this.b = var2; + this.c = var3; + this.d = var4; + this.g = var5; + } + + public void a(PacketDataSerializer var1) throws IOException { + super.a(var1); + this.b = var1.readByte(); + this.c = var1.readByte(); + this.d = var1.readByte(); + this.g = var1.readBoolean(); + } + + public void b(PacketDataSerializer var1) throws IOException { + super.b(var1); + var1.writeByte(this.b); + var1.writeByte(this.c); + var1.writeByte(this.d); + var1.writeBoolean(this.g); + } + + @Override + public int getSize() { + return super.getSize() + 1 + 1 + 1 + 1; + } + + @Override + public int getId() { + return 0x15; + } + } + + public static class PacketPlayOutRelEntityMoveLook extends PacketPlayOutEntity { + public PacketPlayOutRelEntityMoveLook() { + this.h = true; + } + + public PacketPlayOutRelEntityMoveLook(int var1, byte var2, byte var3, byte var4, byte var5, byte var6, boolean var7) { + super(var1); + this.b = var2; + this.c = var3; + this.d = var4; + this.e = var5; + this.f = var6; + this.g = var7; + this.h = true; + } + + public void a(PacketDataSerializer var1) throws IOException { + super.a(var1); + this.b = var1.readByte(); + this.c = var1.readByte(); + this.d = var1.readByte(); + this.e = var1.readByte(); + this.f = var1.readByte(); + this.g = var1.readBoolean(); + } + + public void b(PacketDataSerializer var1) throws IOException { + super.b(var1); + var1.writeByte(this.b); + var1.writeByte(this.c); + var1.writeByte(this.d); + var1.writeByte(this.e); + var1.writeByte(this.f); + var1.writeBoolean(this.g); + } + + @Override + public int getSize() { + return super.getSize() + 1 + 1 + 1 + 1 + 1 + 1; + } + + @Override + public int getId() { + return 0x17; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutEntityDestroy.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutEntityDestroy.java new file mode 100644 index 0000000..de2420f --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutEntityDestroy.java @@ -0,0 +1,52 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; + +public class PacketPlayOutEntityDestroy implements Packet { + public int[] a; + + public PacketPlayOutEntityDestroy() { + } + + public PacketPlayOutEntityDestroy(int... entities) { + this.a = entities; + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = new int[var1.e()]; + + for(int var2 = 0; var2 < this.a.length; ++var2) { + this.a[var2] = var1.e(); + } + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.b(this.a.length); + + for (int i : this.a) { + var1.b(i); + } + } + + @Override + public int getSize() { + int size = ProtocolUtils.varIntBytes(this.a.length); + + for (int entityId : this.a) { + size += ProtocolUtils.varIntBytes(entityId); + } + + return size; + } + + @Override + public int getId() { + return 0x13; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutEntityEffect.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutEntityEffect.java new file mode 100644 index 0000000..9742de1 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutEntityEffect.java @@ -0,0 +1,59 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; + +public class PacketPlayOutEntityEffect implements Packet { + public int a; + public byte b; + public byte c; + public int d; + public byte e; + + public PacketPlayOutEntityEffect() { + } + + public PacketPlayOutEntityEffect(int entityId, MobEffect effect) { + this.a = entityId; + this.b = (byte)(effect.getEffectId() & 255); + this.c = (byte)(effect.getAmplifier() & 255); + if (effect.getDuration() > 32767) { + this.d = 32767; + } else { + this.d = effect.getDuration(); + } + + this.e = (byte)(effect.isShowParticles() ? 1 : 0); + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.e(); + this.b = var1.readByte(); + this.c = var1.readByte(); + this.d = var1.e(); + this.e = var1.readByte(); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.b(this.a); + var1.writeByte(this.b); + var1.writeByte(this.c); + var1.b(this.d); + var1.writeByte(this.e); + } + + @Override + public int getSize() { + return ProtocolUtils.varIntBytes(this.a) + 1 + 1 + ProtocolUtils.varIntBytes(this.d) + 1; + } + + @Override + public int getId() { + return 0x1d; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutEntityEquipment.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutEntityEquipment.java new file mode 100644 index 0000000..c2aa53d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutEntityEquipment.java @@ -0,0 +1,74 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; + +public class PacketPlayOutEntityEquipment implements Packet { + public int a; + public int b; + public ItemStack c; + + static NBTTagList OBFUSCATED_ENCHANTMENTS; + + static { + OBFUSCATED_ENCHANTMENTS = new NBTTagList(); + NBTTagCompound nbttagcompound = new NBTTagCompound(); + nbttagcompound.setShort("id", (short) Enchantment.DURABILITY.id); + nbttagcompound.setShort("lvl", Short.MIN_VALUE); + OBFUSCATED_ENCHANTMENTS.add(nbttagcompound); + } + + public PacketPlayOutEntityEquipment() { + } + + public PacketPlayOutEntityEquipment(int var1, int var2, ItemStack var3) { + this.a = var1; + this.b = var2; + this.c = var3 == null ? null : var3.cloneItemStack(); + } + + public PacketPlayOutEntityEquipment(int var1, int var2, ItemStack var3, boolean obfuscate) { + this.a = var1; + this.b = var2; + this.c = var3 == null ? null : var3.cloneItemStack(); + if (obfuscate && c != null) { + boolean hadEnchants = c.hasEnchantments(); + if (c.e()) + c.setData(c.j()); + c.r(); + if (c.getTag() == null) + c.setTag(new NBTTagCompound()); + if (hadEnchants) { + c.getTag().set("ench", OBFUSCATED_ENCHANTMENTS); + } + c.count = 1; + } + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.e(); + this.b = var1.readShort(); + this.c = var1.i(); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.b(a); + var1.writeShort(b); + var1.a(c); + } + + @Override + public int getSize() { + return ProtocolUtils.varIntBytes(a) + 2 + ProtocolUtils.getItemSize(c); + } + + @Override + public int getId() { + return 0x04; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutEntityHeadRotation.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutEntityHeadRotation.java new file mode 100644 index 0000000..5d3ecf5 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutEntityHeadRotation.java @@ -0,0 +1,42 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; + +public class PacketPlayOutEntityHeadRotation implements Packet { + public int a; + public byte b; + + public PacketPlayOutEntityHeadRotation() { + } + + public PacketPlayOutEntityHeadRotation(Entity entity, byte look) { + this.a = entity.getId(); + this.b = look; + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.e(); + this.b = var1.readByte(); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.b(this.a); + var1.writeByte(this.b); + } + + @Override + public int getSize() { + return ProtocolUtils.varIntBytes(this.a) + 1; + } + + @Override + public int getId() { + return 0x19; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutEntityMetadata.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutEntityMetadata.java new file mode 100644 index 0000000..b2105a2 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutEntityMetadata.java @@ -0,0 +1,95 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; +import dev.azurite.spigot.utils.FixHealth; + +import java.io.IOException; +import java.util.Iterator; +import java.util.List; + +public class PacketPlayOutEntityMetadata implements Packet { + public int a; + public List b; + + public PacketPlayOutEntityMetadata(int entityId, DataWatcher watcher, boolean allMetadata) { + this.a = entityId; + this.b = allMetadata ? watcher.c() : watcher.b(); // if allmetadata is false it will only send the changed metadata + } + + public PacketPlayOutEntityMetadata() { + } + + // Constructor accepting List of change metadata + public PacketPlayOutEntityMetadata(int entityId, List list) { + this.a = entityId; + this.b = list; + } + + // replaces health with 1.0F + public PacketPlayOutEntityMetadata obfuscateHealth() { + Iterator iter = b.iterator(); + boolean found = false; + while (iter.hasNext()) { + DataWatcher.WatchableObject watchable = iter.next(); + if (watchable.a() == 6) { + iter.remove(); + found = true; + } + } + + if (found) b.add(new DataWatcher.WatchableObject(3, 6, 1.0F)); + return this; + } + + // Beanes - round health to fix rendering issue + public void fixHealth() { + for (DataWatcher.WatchableObject watchable : b) { + if (watchable.a() == 6) { + float hp = (float) watchable.b(); + watchable.a(FixHealth.roundHealth(hp)); + } + } + } + + // Beanes - toggleable own player potion particles + public void removePotionParticles() { + b.removeIf(w -> w.a() == 7 || w.a() == 8); + } + + public void stripFireBit() { + for (DataWatcher.WatchableObject watchable : b) { + if (watchable.a() == 0) { + byte bitmask = (byte) watchable.b(); + watchable.a(bitmask & ~0x01); // Strips the fire bit + } + } + } + + public void a(PacketDataSerializer serializer) throws IOException { + this.a = serializer.e(); + this.b = DataWatcher.b(serializer); + } + + public void b(PacketDataSerializer serializer) throws IOException { + serializer.b(this.a); + DataWatcher.a(this.b, serializer); + } + + @Override + public int getSize() { + return ProtocolUtils.varIntBytes(this.a) + ProtocolUtils.getDataWatcherListSize(this.b); + } + + @Override + public int getId() { + return 0x1c; + } + + public void a(PacketListenerPlayOut listener) { + listener.a(this); + } + + public List getData() { + return this.b; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutEntityStatus.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutEntityStatus.java new file mode 100644 index 0000000..2d7e766 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutEntityStatus.java @@ -0,0 +1,40 @@ +package net.minecraft.server; + +import java.io.IOException; + +public class PacketPlayOutEntityStatus implements Packet { + public int a; + public byte b; + + public PacketPlayOutEntityStatus() { + } + + public PacketPlayOutEntityStatus(Entity entity, byte status) { + this.a = entity.getId(); + this.b = status; + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.readInt(); + this.b = var1.readByte(); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.writeInt(this.a); + var1.writeByte(this.b); + } + + @Override + public int getSize() { + return 4 + 1; + } + + @Override + public int getId() { + return 0x1a ; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutEntityTeleport.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutEntityTeleport.java new file mode 100644 index 0000000..2c53dad --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutEntityTeleport.java @@ -0,0 +1,74 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; + +public class PacketPlayOutEntityTeleport implements Packet { + public int a; + public int b; + public int c; + public int d; + public boolean g; + public byte e; + public byte f; + + public PacketPlayOutEntityTeleport() { + } + + public PacketPlayOutEntityTeleport(Entity var1) { + this.a = var1.getId(); + // Beanes - better rounding + this.b = (int) Math.round(var1.locX * 32.0D); + this.c = (int) Math.round(var1.locY * 32.0D); + this.d = (int) Math.round(var1.locZ * 32.0D); + this.e = (byte) Math.round(var1.yaw * 256.0F / 360.0F); + this.f = (byte) Math.round(var1.pitch * 256.0F / 360.0F); + this.g = var1.onGround; + } + + public PacketPlayOutEntityTeleport(int var1, int var2, int var3, int var4, byte var5, byte var6, boolean var7) { + this.a = var1; + this.b = var2; + this.c = var3; + this.d = var4; + this.e = var5; + this.f = var6; + this.g = var7; + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.e(); + this.b = var1.readInt(); + this.c = var1.readInt(); + this.d = var1.readInt(); + this.e = var1.readByte(); + this.f = var1.readByte(); + this.g = var1.readBoolean(); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.b(this.a); + var1.writeInt(this.b); + var1.writeInt(this.c); + var1.writeInt(this.d); + var1.writeByte(this.e); + var1.writeByte(this.f); + var1.writeBoolean(this.g); + } + + @Override + public int getSize() { + return ProtocolUtils.varIntBytes(this.a) + 4 + 4 + 4 + 1 + 1 + 1; + } + + @Override + public int getId() { + return 0x18; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } + +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutEntityVelocity.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutEntityVelocity.java new file mode 100644 index 0000000..15eb0e8 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutEntityVelocity.java @@ -0,0 +1,81 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; + +public class PacketPlayOutEntityVelocity implements Packet { + public int a; + public int b; + public int c; + public int d; + + public PacketPlayOutEntityVelocity() { + } + + public PacketPlayOutEntityVelocity(Entity var1) { + this(var1.getId(), var1.motX, var1.motY, var1.motZ); + } + + public PacketPlayOutEntityVelocity(int var1, double var2, double var4, double var6) { + this.a = var1; + double var8 = 3.9D; + if (var2 < -var8) { + var2 = -var8; + } + + if (var4 < -var8) { + var4 = -var8; + } + + if (var6 < -var8) { + var6 = -var8; + } + + if (var2 > var8) { + var2 = var8; + } + + if (var4 > var8) { + var4 = var8; + } + + if (var6 > var8) { + var6 = var8; + } + + // Beanes - round + this.b = (int) Math.round(var2 * 8000.0D); + this.c = (int) Math.round(var4 * 8000.0D); + this.d = (int) Math.round(var6 * 8000.0D); + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.e(); + this.b = var1.readShort(); + this.c = var1.readShort(); + this.d = var1.readShort(); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.b(this.a); + var1.writeShort(this.b); + var1.writeShort(this.c); + var1.writeShort(this.d); + } + + @Override + public int getSize() { + return ProtocolUtils.varIntBytes(this.a) + 2 + 2 + 2; + } + + @Override + public int getId() { + return 0x12; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } + +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutExperience.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutExperience.java new file mode 100644 index 0000000..6822961 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutExperience.java @@ -0,0 +1,46 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; + +public class PacketPlayOutExperience implements Packet { + public float a; + public int b; + public int c; + + public PacketPlayOutExperience() { + } + + public PacketPlayOutExperience(float experience, int experienceTotal, int experienceLevel) { + this.a = experience; + this.b = experienceTotal; + this.c = experienceLevel; + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.readFloat(); + this.c = var1.e(); + this.b = var1.e(); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.writeFloat(this.a); + var1.b(this.c); + var1.b(this.b); + } + + @Override + public int getSize() { + return 4 + ProtocolUtils.varIntBytes(this.c) + ProtocolUtils.varIntBytes(this.b); + } + + @Override + public int getId() { + return 0x1f; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutExplosion.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutExplosion.java new file mode 100644 index 0000000..2418c53 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutExplosion.java @@ -0,0 +1,106 @@ +package net.minecraft.server; + +import it.unimi.dsi.fastutil.longs.LongArrayList; +import it.unimi.dsi.fastutil.longs.LongListIterator; + +import java.io.IOException; + +public class PacketPlayOutExplosion implements Packet { + public double a; + public double b; + public double c; + public float d; + public LongArrayList e; // Azurite + public float f; + public float g; + public float h; + + public PacketPlayOutExplosion() { + } + + public PacketPlayOutExplosion(double var1, double var3, double var5, float var7, LongArrayList var8, Vec3D var9) { // Azurite + this.a = var1; + this.b = var3; + this.c = var5; + this.d = var7; + this.e = var8.clone(); // Azurite + if (var9 != null) { + this.f = (float) var9.a; + this.g = (float) var9.b; + this.h = (float) var9.c; + } + + } + + public void a(PacketDataSerializer var1) throws IOException { + // Azurite - Client code + /* + this.a = var1.readFloat(); + this.b = var1.readFloat(); + this.c = var1.readFloat(); + this.d = var1.readFloat(); + int var2 = var1.readInt(); + this.e = Lists.newArrayListWithCapacity(var2); + int var3 = (int) this.a; + int var4 = (int) this.b; + int var5 = (int) this.c; + + for (int var6 = 0; var6 < var2; ++var6) { + int var7 = var1.readByte() + var3; + int var8 = var1.readByte() + var4; + int var9 = var1.readByte() + var5; + this.e.add(new BlockPosition(var7, var8, var9)); + } + + this.f = var1.readFloat(); + this.g = var1.readFloat(); + this.h = var1.readFloat(); + */ + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.writeFloat((float) this.a); + var1.writeFloat((float) this.b); + var1.writeFloat((float) this.c); + var1.writeFloat(this.d); + var1.writeInt(this.e.size()); + int var2 = (int) this.a; + int var3 = (int) this.b; + int var4 = (int) this.c; + + // Azurite start + LongListIterator iterator = e.iterator(); + while (iterator.hasNext()) { + long pos = iterator.nextLong(); + int x = BlockPosition.getXFromLong(pos); + int y = BlockPosition.getYFromLong(pos); + int z = BlockPosition.getZFromLong(pos); + int var7 = x - var2; + int var8 = y - var3; + int var9 = z - var4; + var1.writeByte(var7); + var1.writeByte(var8); + var1.writeByte(var9); + } + // Azurite end + + var1.writeFloat(this.f); + var1.writeFloat(this.g); + var1.writeFloat(this.h); + } + + @Override + public int getSize() { + return 4 + 4 + 4 + 4 + 4 + (e.size() * (2 + 2 + 2)) + 4 + 4 + 4; + } + + @Override + public int getId() { + return 0x27; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } + +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutGameStateChange.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutGameStateChange.java new file mode 100644 index 0000000..8092dd2 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutGameStateChange.java @@ -0,0 +1,40 @@ +package net.minecraft.server; + +import java.io.IOException; + +public class PacketPlayOutGameStateChange implements Packet { + public int b; + public float c; + + public PacketPlayOutGameStateChange() { + } + + public PacketPlayOutGameStateChange(int var1, float var2) { + this.b = var1; + this.c = var2; + } + + public void a(PacketDataSerializer var1) throws IOException { + this.b = var1.readUnsignedByte(); + this.c = var1.readFloat(); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.writeByte(this.b); + var1.writeFloat(this.c); + } + + @Override + public int getSize() { + return 1 + 4; + } + + @Override + public int getId() { + return 0x2b; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutHeldItemSlot.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutHeldItemSlot.java new file mode 100644 index 0000000..b949207 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutHeldItemSlot.java @@ -0,0 +1,36 @@ +package net.minecraft.server; + +import java.io.IOException; + +public class PacketPlayOutHeldItemSlot implements Packet { + public int a; + + public PacketPlayOutHeldItemSlot() { + } + + public PacketPlayOutHeldItemSlot(int slot) { + this.a = slot; + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.readByte(); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.writeByte(this.a); + } + + @Override + public int getSize() { + return 1; + } + + @Override + public int getId() { + return 0x09; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutKeepAlive.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutKeepAlive.java new file mode 100644 index 0000000..1b9db1a --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutKeepAlive.java @@ -0,0 +1,38 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; + +public class PacketPlayOutKeepAlive implements Packet { + public int a; + + public PacketPlayOutKeepAlive() { + } + + public PacketPlayOutKeepAlive(int id) { + this.a = id; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.e(); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.b(this.a); + } + + @Override + public int getSize() { + return ProtocolUtils.varIntBytes(this.a); + } + + @Override + public int getId() { + return 0x00; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutKickDisconnect.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutKickDisconnect.java new file mode 100644 index 0000000..0ed9cf1 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutKickDisconnect.java @@ -0,0 +1,54 @@ +// +// Source code recreated from a .class file by IntelliJ IDEA +// (powered by FernFlower decompiler) +// + +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; + +public class PacketPlayOutKickDisconnect implements Packet { + public IChatBaseComponent a; + private String serializedJson = null; + + public PacketPlayOutKickDisconnect() { + } + + public PacketPlayOutKickDisconnect(IChatBaseComponent var1) { + this.a = var1; + this.serializeJson(); + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.d(); + } + + public void b(PacketDataSerializer var1) throws IOException { + if (serializedJson != null) { + var1.a(this.serializedJson); + } else { + var1.a(this.a); + } + } + + // Beanes - only serialize json once + private void serializeJson() { + this.serializedJson = IChatBaseComponent.ChatSerializer.a(a); + } + + @Override + public int getSize() { + return serializedJson != null ? ProtocolUtils.getStringSize(this.serializedJson) : ProtocolUtils.getChatComponentSize(this.a); + } + + @Override + public int getId() { + return 0x40; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutLogin.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutLogin.java new file mode 100644 index 0000000..3d932cb --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutLogin.java @@ -0,0 +1,77 @@ +package net.minecraft.server; + +import java.io.IOException; + +import dev.azurite.spigot.optimizations.ProtocolUtils; +import net.minecraft.server.WorldSettings.EnumGamemode; + +public class PacketPlayOutLogin implements Packet { + public int a; + public boolean b; + public WorldSettings.EnumGamemode c; + public int d; + public EnumDifficulty e; + public int f; + public WorldType g; + public boolean h; + + public PacketPlayOutLogin() { + } + + public PacketPlayOutLogin(int entityId, WorldSettings.EnumGamemode gameMode, boolean hardcore, int dim, EnumDifficulty difficulty, int maxPlayers, WorldType worldType, boolean reducedDebugInfo) { + this.a = entityId; + this.d = dim; + this.e = difficulty; + this.c = gameMode; + this.f = maxPlayers; + this.b = hardcore; + this.g = worldType; + this.h = reducedDebugInfo; + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.readInt(); + int var2 = var1.readUnsignedByte(); + this.b = (var2 & 8) == 8; + var2 &= -9; + this.c = EnumGamemode.getById(var2); + this.d = var1.readByte(); + this.e = EnumDifficulty.getById(var1.readUnsignedByte()); + this.f = var1.readUnsignedByte(); + this.g = WorldType.getType(var1.c(16)); + if (this.g == null) { + this.g = WorldType.NORMAL; + } + + this.h = var1.readBoolean(); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.writeInt(this.a); + int var2 = this.c.getId(); + if (this.b) { + var2 |= 8; + } + + var1.writeByte(var2); + var1.writeByte(this.d); + var1.writeByte(this.e.a()); + var1.writeByte(this.f); + var1.a(this.g.name()); + var1.writeBoolean(this.h); + } + + @Override + public int getSize() { + return 4 + 1 + 1 + 1 + 1 + ProtocolUtils.getStringSize(this.g.name()) + 1; + } + + @Override + public int getId() { + return 0x01; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutMap.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutMap.java new file mode 100644 index 0000000..89f7423 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutMap.java @@ -0,0 +1,92 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; +import java.util.Collection; + +public class PacketPlayOutMap implements Packet { + public int a; + public byte b; + public MapIcon[] c; + public int d; + public int e; + public int f; + public int g; + public byte[] h; + + public PacketPlayOutMap() { + } + + public PacketPlayOutMap(int var1, byte var2, Collection var3, byte[] var4, int var5, int var6, int var7, int var8) { + this.a = var1; + this.b = var2; + this.c = (MapIcon[])var3.toArray(new MapIcon[var3.size()]); + this.d = var5; + this.e = var6; + this.f = var7; + this.g = var8; + this.h = new byte[var7 * var8]; + + for(int var9 = 0; var9 < var7; ++var9) { + for(int var10 = 0; var10 < var8; ++var10) { + this.h[var9 + var10 * var7] = var4[var5 + var9 + (var6 + var10) * 128]; + } + } + + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.e(); + this.b = var1.readByte(); + this.c = new MapIcon[var1.e()]; + + for(int var2 = 0; var2 < this.c.length; ++var2) { + short var3 = (short)var1.readByte(); + this.c[var2] = new MapIcon((byte)(var3 >> 4 & 15), var1.readByte(), var1.readByte(), (byte)(var3 & 15)); + } + + this.f = var1.readUnsignedByte(); + if (this.f > 0) { + this.g = var1.readUnsignedByte(); + this.d = var1.readUnsignedByte(); + this.e = var1.readUnsignedByte(); + this.h = var1.a(); + } + + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.b(this.a); + var1.writeByte(this.b); + var1.b(this.c.length); + + for (MapIcon var5 : this.c) { + var1.writeByte((var5.getType() & 15) << 4 | var5.getRotation() & 15); + var1.writeByte(var5.getX()); + var1.writeByte(var5.getY()); + } + + var1.writeByte(this.f); + if (this.f > 0) { + var1.writeByte(this.g); + var1.writeByte(this.d); + var1.writeByte(this.e); + var1.a(this.h); + } + } + + @Override + public int getSize() { + return ProtocolUtils.varIntBytes(this.a) + 1 + ProtocolUtils.varIntBytes(this.c.length) + (this.c.length * (1 + 1 + 1)) + (this.f > 0 ? (1 + 1 + 1 + ProtocolUtils.getByteArraySize(this.h)) : 0); + } + + @Override + public int getId() { + return 0x34; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutMapChunk.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutMapChunk.java new file mode 100644 index 0000000..3402f46 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutMapChunk.java @@ -0,0 +1,223 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.AzuriteConfig; +import dev.azurite.spigot.optimizations.FastAntiXray; +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; + +public class PacketPlayOutMapChunk implements Packet { + public int a; + public int b; + public ChunkMap c; + public boolean d; + + public PacketPlayOutMapChunk() { + } + + public PacketPlayOutMapChunk(Chunk chunk, boolean groundUp, int bitmask) { + this.a = chunk.locX; + this.b = chunk.locZ; + this.d = groundUp; + this.c = chunk.getChunkMap(groundUp, bitmask); + } + + // Azurite - create constructor for unload chunk packet + public PacketPlayOutMapChunk(Chunk chunk) { + this.a = chunk.locX; + this.b = chunk.locZ; + this.d = true; + PacketPlayOutMapChunk.ChunkMap chunkMap = new PacketPlayOutMapChunk.ChunkMap(); + chunkMap.a = new byte[0]; + this.c = chunkMap; + } + + public void a(PacketDataSerializer packetdataserializer) throws IOException { + this.a = packetdataserializer.readInt(); + this.b = packetdataserializer.readInt(); + this.d = packetdataserializer.readBoolean(); + this.c = new ChunkMap(); + this.c.b = packetdataserializer.readShort(); + this.c.a = packetdataserializer.a(); + } + + public void b(PacketDataSerializer packetdataserializer) throws IOException { + packetdataserializer.writeInt(this.a); + packetdataserializer.writeInt(this.b); + packetdataserializer.writeBoolean(this.d); + packetdataserializer.writeShort((short) (c.b & '\uffff')); + packetdataserializer.a(c.a); + } + + public void a(PacketListenerPlayOut packetlistenerplayout) { + packetlistenerplayout.a(this); + } + + protected static int getChunkDataSize(int sections, boolean sky, boolean groundUp) { + return (sections * 2 * 16 * 16 * 16) + (sections * 16 * 16 * 16 / 2) + (sky ? sections * 16 * 16 * 16 / 2 : 0) + (groundUp ? 256 : 0); + } + + @Override + public int getSize() { + return 4 // X + + 4 // Z + + 1 // groundUp + + 2 // Bitmask + + ProtocolUtils.getByteArraySize(c.a); // Chunk Data + } + + @Override + public int getId() { + return 0x21 ; + } + + private static final ChunkSection EMPTY_SECTION_WITH_SKYLIGHT = new ChunkSection(0, true, false); + + // Beanes - full rewrite of chunk serializing + // Azurite - added on top rewrite of antixray + public static ChunkMap serializeToChunkMap(Chunk chunk, boolean groundUp, boolean hasSky, int primaryBitmask) { + if (chunk.world.spigotConfig.antiXray) { + return serializeToChunkMapWithAntiXray(chunk, groundUp, hasSky, primaryBitmask); + } + + ChunkSection[] achunksection = chunk.getSections(); + ChunkMap map = new ChunkMap(); + ChunkSection[] sendingSections = new ChunkSection[Integer.bitCount(primaryBitmask)]; // Could be oversized but doesn't really matter as most of the time its fine + + int totalSections = 0; + int i; + for (i = 0; i < achunksection.length; ++i) { + ChunkSection chunksection = achunksection[i]; + + // Beanes - port over blossom patch to reduce skylight fps spikes + if (groundUp && AzuriteConfig.sendEmptyChunkSections.getValue()) { + // Selects either the defined section or empty section + map.b |= 1 << i; + sendingSections[totalSections++] = chunksection != null ? chunksection : EMPTY_SECTION_WITH_SKYLIGHT; + } else if (chunksection != null && (!groundUp || !chunksection.a()) && (primaryBitmask & 1 << i) != 0) { + map.b |= 1 << i; + sendingSections[totalSections++] = chunksection; + } + } + + int blockWriteIndex = 0; + int emittedLightIndex = 8192 * totalSections; // Emitted light starts at the end of section data (each section has 8192 bytes) + int skylightIndex = emittedLightIndex + (2048 * totalSections); + int biomeIndex = (hasSky ? (skylightIndex + 2048 * totalSections) : skylightIndex); + + map.a = new byte[biomeIndex + 256]; + for (i = 0; i < totalSections; i++) { + ChunkSection section = sendingSections[i]; + + for (char blockId : section.getIdArray()) { + map.a[blockWriteIndex++] = (byte) (blockId & 255); + map.a[blockWriteIndex++] = (byte) (blockId >> 8 & 255); + } + + byte[] emittedLight = section.getEmittedLightArray().a(); + System.arraycopy(emittedLight, 0, map.a, emittedLightIndex, 2048); + emittedLightIndex += 2048; + + if (hasSky) { + byte[] skylight = section.getSkyLightArray().a(); + System.arraycopy(skylight, 0, map.a, skylightIndex, 2048); + skylightIndex += 2048; + } + } + + if (groundUp) { + byte[] biome = chunk.getBiomeIndex(); + System.arraycopy(biome, 0, map.a, biomeIndex, 256); + } + + return map; + } + + public static ChunkMap serializeToChunkMapWithAntiXray(Chunk chunk, boolean groundUp, boolean hasSky, int primaryBitmask) { + ChunkSection[] achunksection = chunk.getSections(); + ChunkMap map = new ChunkMap(); + ChunkSection[] sendingSections = new ChunkSection[Integer.bitCount(primaryBitmask)]; // Could be oversized but doesn't really matter as most of the time its fine + + int totalSections = 0; + int i; + for (i = 0; i < achunksection.length; ++i) { + ChunkSection chunksection = achunksection[i]; + + // Beanes - port over blossom patch to reduce skylight fps spikes + if (groundUp && AzuriteConfig.sendEmptyChunkSections.getValue()) { + // Selects either the defined section or empty section + map.b |= 1 << i; + sendingSections[totalSections++] = chunksection != null ? chunksection : EMPTY_SECTION_WITH_SKYLIGHT; + } else if (chunksection != null && (!groundUp || !chunksection.a()) && (primaryBitmask & 1 << i) != 0) { + map.b |= 1 << i; + sendingSections[totalSections++] = chunksection; + } + } + + World world = chunk.world; + FastAntiXray antiXray = world.spigotConfig.antiXrayInstance; + int randomOre = 0; + + int blockWriteIndex = 0; + int emittedLightIndex = 8192 * totalSections; // Emitted light starts at the end of section data (each section has 8192 bytes) + int skylightIndex = emittedLightIndex + (2048 * totalSections); + int biomeIndex = (hasSky ? (skylightIndex + 2048 * totalSections) : skylightIndex); + + map.a = new byte[biomeIndex + 256]; + + for (i = 0; i < totalSections; i++) { + ChunkSection section = sendingSections[i]; + char[] idArray = section.getIdArray(); + + for (int k = 0; k < idArray.length; k++) { + char blockId = idArray[k]; + + // Azurite - Handle AntiXray here as spigots anti xray re-loops, we do it directly to save resources + if (antiXray.obfuscateBlocks[blockId]) { + switch (world.spigotConfig.engineMode) { + case 1: + blockId = antiXray.getReplacedIdEngine1(chunk, section, sendingSections, blockId, k, primaryBitmask, i, totalSections); + break; + case 2: + // Replace with random ore. + if (randomOre >= antiXray.replacementOres.length) { + randomOre = 0; + } + blockId = (char) (antiXray.replacementOres[randomOre] & 0xFF); + randomOre = randomOre + 1; + break; + } + } + + map.a[blockWriteIndex++] = (byte) (blockId & 0xFF); + map.a[blockWriteIndex++] = (byte) ((blockId >> 8) & 0xFF); + } + + byte[] emittedLight = section.getEmittedLightArray().a(); + System.arraycopy(emittedLight, 0, map.a, emittedLightIndex, 2048); + emittedLightIndex += 2048; + + if (hasSky) { + byte[] skylight = section.getSkyLightArray().a(); + System.arraycopy(skylight, 0, map.a, skylightIndex, 2048); + skylightIndex += 2048; + } + } + + if (groundUp) { + byte[] biome = chunk.getBiomeIndex(); + System.arraycopy(biome, 0, map.a, biomeIndex, 256); + } + + return map; + } + + public static class ChunkMap { + + public byte[] a; + public int b; + + public ChunkMap() { + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutMapChunkBulk.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutMapChunkBulk.java new file mode 100644 index 0000000..6f64efa --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutMapChunkBulk.java @@ -0,0 +1,94 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; +import java.util.List; + +public class PacketPlayOutMapChunkBulk implements Packet { + public int[] a; + public int[] b; + public PacketPlayOutMapChunk.ChunkMap[] c; + public boolean d; + + public PacketPlayOutMapChunkBulk() { + } + + public PacketPlayOutMapChunkBulk(List list) { + int i = list.size(); + + this.a = new int[i]; + this.b = new int[i]; + this.c = new PacketPlayOutMapChunk.ChunkMap[i]; + + for (int j = 0; j < i; ++j) { + Chunk chunk = list.get(j); + // Vortex - less iterations + if (j == 0) { + d = !chunk.getWorld().worldProvider.o(); + } + this.a[j] = chunk.locX; + this.b[j] = chunk.locZ; + this.c[j] = chunk.getChunkMap(true, '\uffff'); + } + } + + public void a(PacketDataSerializer packetdataserializer) throws IOException { + this.d = packetdataserializer.readBoolean(); + int i = packetdataserializer.e(); + this.a = new int[i]; + this.b = new int[i]; + this.c = new PacketPlayOutMapChunk.ChunkMap[i]; + int j; + for (j = 0; j < i; j++) { + this.a[j] = packetdataserializer.readInt(); + this.b[j] = packetdataserializer.readInt(); + this.c[j] = new PacketPlayOutMapChunk.ChunkMap(); + (this.c[j]).b = packetdataserializer.readShort() & 0xFFFF; + (this.c[j]).a = new byte[PacketPlayOutMapChunk.getChunkDataSize(Integer.bitCount((this.c[j]).b), this.d, true)]; + } + for (j = 0; j < i; j++) + packetdataserializer.readBytes((this.c[j]).a); + } + + public void b(PacketDataSerializer packetdataserializer) throws IOException { + packetdataserializer.writeBoolean(this.d); + packetdataserializer.b(this.c.length); + + int i; + + for (i = 0; i < this.a.length; ++i) { + packetdataserializer.writeInt(this.a[i]); + packetdataserializer.writeInt(this.b[i]); + packetdataserializer.writeShort((short) (this.c[i].b & '\uffff')); + } + + for (i = 0; i < this.a.length; ++i) { + PacketPlayOutMapChunk.ChunkMap chunkMap = c[i]; + packetdataserializer.writeBytes(chunkMap.a); + } + } + + @Override + public int getSize() { + int size = 1 + ProtocolUtils.varIntBytes(this.c.length); + + size += (this.a.length * (4 + 4 + 2)); + + for (int i = 0; i < this.a.length; ++i) { + PacketPlayOutMapChunk.ChunkMap chunkMap = c[i]; + size += ProtocolUtils.getByteArraySize(chunkMap.a); + } + + return size; + } + + @Override + public int getId() { + return 0x26; + } + + public void a(PacketListenerPlayOut packetlistenerplayout) { + packetlistenerplayout.a(this); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutMultiBlockChange.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutMultiBlockChange.java new file mode 100644 index 0000000..bd17e94 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutMultiBlockChange.java @@ -0,0 +1,95 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; + +/** + * @since 12/2/2017 + */ +public class PacketPlayOutMultiBlockChange implements Packet { + public ChunkCoordIntPair a; + public MultiBlockChangeInfo[] b; + + public PacketPlayOutMultiBlockChange() { + } + + public PacketPlayOutMultiBlockChange(int var1, short[] var2, Chunk var3) { + this.a = new ChunkCoordIntPair(var3.locX, var3.locZ); + this.b = new MultiBlockChangeInfo[var1]; + + for (int var4 = 0; var4 < this.b.length; ++var4) { + this.b[var4] = new MultiBlockChangeInfo(var2[var4], var3); + } + + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = new ChunkCoordIntPair(var1.readInt(), var1.readInt()); + this.b = new MultiBlockChangeInfo[var1.e()]; + + for (int var2 = 0; var2 < this.b.length; ++var2) { + this.b[var2] = new MultiBlockChangeInfo(var1.readShort(), Block.d.a(var1.e())); + } + + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.writeInt(this.a.x); + var1.writeInt(this.a.z); + var1.b(this.b.length); + for (MultiBlockChangeInfo var5 : b) { + var1.writeShort(var5.b()); + var1.b(Block.d.b(var5.c())); + } + + } + + @Override + public int getSize() { + int size = 4 + 4 + ProtocolUtils.varIntBytes(this.b.length); + + for (MultiBlockChangeInfo var5 : b) { + size += 2 + ProtocolUtils.varIntBytes(Block.d.b(var5.c())); + } + + return size; + } + + @Override + public int getId() { + return 0x22; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } + + public class MultiBlockChangeInfo { + private final short b; + private final IBlockData c; + + public MultiBlockChangeInfo(short var2, IBlockData var3) { + this.b = var2; + this.c = var3; + } + + public MultiBlockChangeInfo(short var2, Chunk var3) { + this.b = var2; + this.c = var3.getBlockData(this.a()); + } + + public BlockPosition a() { + return new BlockPosition(PacketPlayOutMultiBlockChange.this.a.a(this.b >> 12 & 15, this.b & 255, this.b >> 8 & 15)); + } + + public short b() { + return this.b; + } + + public IBlockData c() { + return this.c; + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutNamedEntitySpawn.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutNamedEntitySpawn.java new file mode 100644 index 0000000..d2cf943 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutNamedEntitySpawn.java @@ -0,0 +1,87 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; +import java.util.List; +import java.util.UUID; + +public class PacketPlayOutNamedEntitySpawn implements Packet { + public int a; + public UUID b; + public int c; + public int d; + public int e; + public byte f; + public byte g; + public int h; + public DataWatcher i; + public List j; + + public PacketPlayOutNamedEntitySpawn() { + } + + public PacketPlayOutNamedEntitySpawn(EntityHuman human) { + // Beanes - use new constructor + this(human, + (int) Math.round(human.locX * 32.0D), + (int) Math.round(human.locY * 32.0D), + (int) Math.round(human.locZ * 32.0D), + ((int) (human.yaw * 256.0F / 360.0F)), + ((int) (human.pitch * 256.0F / 360.0F)) + ); + } + + // Beanes - constructor that allows overriding spawn loc + public PacketPlayOutNamedEntitySpawn(EntityHuman human, int x, int y, int z, int yaw, int pitch) { + this.a = human.getId(); + this.b = human.getProfile().getId(); + // Beanes - more accurate positions (round instead of floor) + this.c = x; + this.d = y; + this.e = z; + this.f = (byte) yaw; + this.g = (byte) pitch; + ItemStack itemStack = human.inventory.getItemInHand(); + this.h = itemStack == null ? 0 : Item.getId(itemStack.getItem()); + this.i = human.getDataWatcher(); + } + + public void a(PacketDataSerializer packetdataserializer) throws IOException { + this.a = packetdataserializer.e(); + this.b = packetdataserializer.g(); + this.c = packetdataserializer.readInt(); + this.d = packetdataserializer.readInt(); + this.e = packetdataserializer.readInt(); + this.f = packetdataserializer.readByte(); + this.g = packetdataserializer.readByte(); + this.h = packetdataserializer.readShort(); + this.j = DataWatcher.b(packetdataserializer); + } + + public void b(PacketDataSerializer packetdataserializer) throws IOException { + packetdataserializer.b(this.a); + packetdataserializer.a(this.b); + packetdataserializer.writeInt(this.c); + packetdataserializer.writeInt(this.d); + packetdataserializer.writeInt(this.e); + packetdataserializer.writeByte(this.f); + packetdataserializer.writeByte(this.g); + packetdataserializer.writeShort(this.h); + this.i.a(packetdataserializer); + } + + @Override + public int getSize() { + return ProtocolUtils.varIntBytes(this.a) + 8 + 8 + 4 + 4 + 4 + 1 + 1 + 2 + ProtocolUtils.getDataWatcherSize(this.i); + } + + @Override + public int getId() { + return 0x0C; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutNamedSoundEffect.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutNamedSoundEffect.java new file mode 100644 index 0000000..8c454ce --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutNamedSoundEffect.java @@ -0,0 +1,62 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; +import org.apache.commons.lang3.Validate; + +import java.io.IOException; + +public class PacketPlayOutNamedSoundEffect implements Packet { + + public String a; + public int b; + public int c = Integer.MAX_VALUE; + public int d; + public float e; + public int f; + + public PacketPlayOutNamedSoundEffect() { + } + + public PacketPlayOutNamedSoundEffect(String s, double d0, double d1, double d2, float f, float f1) { + Validate.notNull(s, "name"); + this.a = s; + this.b = (int) (d0 * 8.0D); + this.c = (int) (d1 * 8.0D); + this.d = (int) (d2 * 8.0D); + this.e = f; + this.f = (int) (f1 * 63.0F); + } + + public void a(PacketDataSerializer packetdataserializer) throws IOException { + this.a = packetdataserializer.c(256); + this.b = packetdataserializer.readInt(); + this.c = packetdataserializer.readInt(); + this.d = packetdataserializer.readInt(); + this.e = packetdataserializer.readFloat(); + this.f = packetdataserializer.readUnsignedByte(); + } + + public void b(PacketDataSerializer packetdataserializer) throws IOException { + packetdataserializer.a(this.a); + packetdataserializer.writeInt(this.b); + packetdataserializer.writeInt(this.c); + packetdataserializer.writeInt(this.d); + packetdataserializer.writeFloat(this.e); + packetdataserializer.writeByte(this.f); + } + + @Override + public int getSize() { + return ProtocolUtils.getStringSize(this.a) + 4 + 4 + 4 + 4 + 1; + } + + @Override + public int getId() { + return 0x29; + } + + public void a(PacketListenerPlayOut packetlistenerplayout) { + packetlistenerplayout.a(this); + } + +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutOpenSignEditor.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutOpenSignEditor.java new file mode 100644 index 0000000..499723d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutOpenSignEditor.java @@ -0,0 +1,36 @@ +package net.minecraft.server; + +import java.io.IOException; + +public class PacketPlayOutOpenSignEditor implements Packet { + public BlockPosition a; + + public PacketPlayOutOpenSignEditor() { + } + + public PacketPlayOutOpenSignEditor(BlockPosition pos) { + this.a = pos; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.c(); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.a(this.a); + } + + @Override + public int getSize() { + return 8; + } + + @Override + public int getId() { + return 0x36; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutOpenWindow.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutOpenWindow.java new file mode 100644 index 0000000..1b753eb --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutOpenWindow.java @@ -0,0 +1,86 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; + +public class PacketPlayOutOpenWindow implements Packet { + public int a; + public String b; + public IChatBaseComponent c; + public int d; + public int e; + + private String serializedTitle = null; + + public PacketPlayOutOpenWindow() {} + + public PacketPlayOutOpenWindow(int i, String s, IChatBaseComponent ichatbasecomponent) { + this(i, s, ichatbasecomponent, 0); + } + + public PacketPlayOutOpenWindow(int i, String s, IChatBaseComponent ichatbasecomponent, int j) { + this.a = i; + this.b = s; + this.c = ichatbasecomponent; + this.d = j; + + this.serializeTitle(); + } + + public PacketPlayOutOpenWindow(int i, String s, IChatBaseComponent ichatbasecomponent, int j, int k) { + this(i, s, ichatbasecomponent, j); + this.e = k; + } + + public void a(PacketListenerPlayOut packetlistenerplayout) { + packetlistenerplayout.a(this); + } + + public void a(PacketDataSerializer packetdataserializer) throws IOException { + this.a = packetdataserializer.readUnsignedByte(); + this.b = packetdataserializer.c(32); + this.c = packetdataserializer.d(); + this.d = packetdataserializer.readUnsignedByte(); + if (this.b.equals("EntityHorse")) { + this.e = packetdataserializer.readInt(); + } + + } + + public void b(PacketDataSerializer packetdataserializer) throws IOException { + packetdataserializer.writeByte(this.a); + packetdataserializer.a(this.b); + + if (this.serializedTitle != null) { + packetdataserializer.a(this.serializedTitle); + } else { + packetdataserializer.a(this.c); + } + + packetdataserializer.writeByte(this.d); + if (this.b.equals("EntityHorse")) { + packetdataserializer.writeInt(this.e); + } + } + + // Beanes - only serialize once + private void serializeTitle() { + this.serializedTitle = IChatBaseComponent.ChatSerializer.a(this.c); + } + + @Override + public int getSize() { + return 1 + ProtocolUtils.getStringSize(this.b) + (this.serializedTitle != null ? ProtocolUtils.getStringSize(this.serializedTitle) : ProtocolUtils.getChatComponentSize(this.c)) + 1 + (this.b.equals("EntityHorse") ? 4 : 0); + } + + @Override + public int getId() { + return 0x2d; + } + + // Beanes - OBFHelper + public int getWindowId() { + return a; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutPlayerInfo.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutPlayerInfo.java new file mode 100644 index 0000000..e2a9441 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutPlayerInfo.java @@ -0,0 +1,314 @@ +package net.minecraft.server; + +import com.google.common.base.Objects; +import com.google.common.collect.Lists; +import com.mojang.authlib.GameProfile; +import com.mojang.authlib.properties.Property; +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; +import java.util.List; + +public class PacketPlayOutPlayerInfo implements Packet { + + public PacketPlayOutPlayerInfo.EnumPlayerInfoAction a; + public List b = Lists.newArrayList(); + + public PacketPlayOutPlayerInfo() { + } + + public PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction packetplayoutplayerinfo_enumplayerinfoaction, EntityPlayer... aentityplayer) { + this.a = packetplayoutplayerinfo_enumplayerinfoaction; + + for (EntityPlayer entityplayer : aentityplayer) { + this.b.add(new PlayerInfoData(entityplayer.getProfile(), entityplayer.ping, entityplayer.playerInteractManager.getGameMode(), entityplayer.getPlayerListName())); + } + } + + public PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction packetplayoutplayerinfo_enumplayerinfoaction, List b) { + this.a = packetplayoutplayerinfo_enumplayerinfoaction; + this.b = b; + } + + public PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction packetplayoutplayerinfo_enumplayerinfoaction, Iterable iterable) { + this.a = packetplayoutplayerinfo_enumplayerinfoaction; + + for (EntityPlayer entityplayer : iterable) { + this.b.add(new PlayerInfoData(entityplayer.getProfile(), entityplayer.ping, entityplayer.playerInteractManager.getGameMode(), entityplayer.getPlayerListName())); + } + } + + public void a(PacketDataSerializer packetdataserializer) throws IOException { + this.a = packetdataserializer.a(EnumPlayerInfoAction.class); + int i = packetdataserializer.e(); + + for (int j = 0; j < i; ++j) { + GameProfile gameprofile = null; + int k = 0; + WorldSettings.EnumGamemode worldsettings_enumgamemode = null; + IChatBaseComponent ichatbasecomponent = null; + + switch (PacketPlayOutPlayerInfo.SyntheticClass_1.a[this.a.ordinal()]) { + case 1: + gameprofile = new GameProfile(packetdataserializer.g(), packetdataserializer.c(16)); + int l = packetdataserializer.e(); + + for (int i1 = 0; i1 < l; ++i1) { + String s = packetdataserializer.c(32767); + String s1 = packetdataserializer.c(32767); + + if (packetdataserializer.readBoolean()) { + gameprofile.getProperties().put(s, new Property(s, s1, packetdataserializer.c(32767))); + } else { + gameprofile.getProperties().put(s, new Property(s, s1)); + } + } + + worldsettings_enumgamemode = WorldSettings.EnumGamemode.getById(packetdataserializer.e()); + k = packetdataserializer.e(); + if (packetdataserializer.readBoolean()) { + ichatbasecomponent = packetdataserializer.d(); + } + break; + + case 2: + gameprofile = new GameProfile(packetdataserializer.g(), null); + worldsettings_enumgamemode = WorldSettings.EnumGamemode.getById(packetdataserializer.e()); + break; + + case 3: + gameprofile = new GameProfile(packetdataserializer.g(), null); + k = packetdataserializer.e(); + break; + + case 4: + gameprofile = new GameProfile(packetdataserializer.g(), null); + if (packetdataserializer.readBoolean()) { + ichatbasecomponent = packetdataserializer.d(); + } + break; + + case 5: + gameprofile = new GameProfile(packetdataserializer.g(), null); + } + + this.b.add(new PacketPlayOutPlayerInfo.PlayerInfoData(gameprofile, k, worldsettings_enumgamemode, ichatbasecomponent)); + } + + } + + public void b(PacketDataSerializer packetdataserializer) throws IOException { + packetdataserializer.a(this.a); + packetdataserializer.b(this.b.size()); + + for (PlayerInfoData packetplayoutplayerinfo_playerinfodata : this.b) { + switch (SyntheticClass_1.a[this.a.ordinal()]) { + case 1: + GameProfile profile = packetplayoutplayerinfo_playerinfodata.a(); + packetdataserializer.a(profile.getId()); + packetdataserializer.a(profile.getName()); + packetdataserializer.b(profile.getProperties().size()); + + for (Property property : profile.getProperties().values()) { + packetdataserializer.a(property.getName()); + packetdataserializer.a(property.getValue()); + if (property.hasSignature()) { + packetdataserializer.writeBoolean(true); + packetdataserializer.a(property.getSignature()); + } else { + packetdataserializer.writeBoolean(false); + } + } + + packetdataserializer.b(packetplayoutplayerinfo_playerinfodata.c().getId()); + packetdataserializer.b(packetplayoutplayerinfo_playerinfodata.b()); + if (packetplayoutplayerinfo_playerinfodata.d() == null) { + packetdataserializer.writeBoolean(false); + } else { + packetdataserializer.writeBoolean(true); + packetdataserializer.a(packetplayoutplayerinfo_playerinfodata.d()); + } + break; + + case 2: + packetdataserializer.a(packetplayoutplayerinfo_playerinfodata.a().getId()); + packetdataserializer.b(packetplayoutplayerinfo_playerinfodata.c().getId()); + break; + + case 3: + packetdataserializer.a(packetplayoutplayerinfo_playerinfodata.a().getId()); + packetdataserializer.b(packetplayoutplayerinfo_playerinfodata.b()); + break; + + case 4: + packetdataserializer.a(packetplayoutplayerinfo_playerinfodata.a().getId()); + if (packetplayoutplayerinfo_playerinfodata.d() == null) { + packetdataserializer.writeBoolean(false); + } else { + packetdataserializer.writeBoolean(true); + packetdataserializer.a(packetplayoutplayerinfo_playerinfodata.d()); + } + break; + + case 5: + packetdataserializer.a(packetplayoutplayerinfo_playerinfodata.a().getId()); + } + } + } + + @Override + public int getSize() { + int size = ProtocolUtils.getEnumSize(this.a) + ProtocolUtils.varIntBytes(this.b.size()); + + for (PlayerInfoData packetplayoutplayerinfo_playerinfodata : this.b) { + switch (SyntheticClass_1.a[this.a.ordinal()]) { + case 1: + GameProfile profile = packetplayoutplayerinfo_playerinfodata.a(); + + size += 16; + size += ProtocolUtils.getStringSize(profile.getName()); + size += ProtocolUtils.varIntBytes(profile.getProperties().size()); + + for (Property property : profile.getProperties().values()) { + size += ProtocolUtils.getStringSize(property.getName()); + size += ProtocolUtils.getStringSize(property.getValue()); + size += 1; + + if (property.hasSignature()) { + size += ProtocolUtils.getStringSize(property.getSignature()); + } + } + + size += ProtocolUtils.varIntBytes(packetplayoutplayerinfo_playerinfodata.c().getId()); + size += ProtocolUtils.varIntBytes(packetplayoutplayerinfo_playerinfodata.b()); + + size += 1; + + if (packetplayoutplayerinfo_playerinfodata.d() != null) { + size += ProtocolUtils.getChatComponentSize(packetplayoutplayerinfo_playerinfodata.d()); + } + break; + + case 2: + size += 16 + ProtocolUtils.varIntBytes(packetplayoutplayerinfo_playerinfodata.c().getId()); + break; + + case 3: + size += 16 + ProtocolUtils.varIntBytes(packetplayoutplayerinfo_playerinfodata.b()); + break; + + case 4: + size += 16; + if (packetplayoutplayerinfo_playerinfodata.d() == null) { + size += 1; + } else { + size += 1 + ProtocolUtils.getChatComponentSize(packetplayoutplayerinfo_playerinfodata.d()); + } + break; + + case 5: + size += 16; + } + } + + return size; + } + + @Override + public int getId() { + return 0x38; + } + + public void a(PacketListenerPlayOut packetlistenerplayout) { + packetlistenerplayout.a(this); + } + + public String toString() { + return Objects.toStringHelper(this).add("action", this.a).add("entries", this.b).toString(); + } + + + static class SyntheticClass_1 { + + static final int[] a = new int[PacketPlayOutPlayerInfo.EnumPlayerInfoAction.values().length]; + + static { + try { + PacketPlayOutPlayerInfo.SyntheticClass_1.a[PacketPlayOutPlayerInfo.EnumPlayerInfoAction.ADD_PLAYER.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + } + + try { + PacketPlayOutPlayerInfo.SyntheticClass_1.a[PacketPlayOutPlayerInfo.EnumPlayerInfoAction.UPDATE_GAME_MODE.ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + } + + try { + PacketPlayOutPlayerInfo.SyntheticClass_1.a[PacketPlayOutPlayerInfo.EnumPlayerInfoAction.UPDATE_LATENCY.ordinal()] = 3; + } catch (NoSuchFieldError ignored) { + } + + try { + PacketPlayOutPlayerInfo.SyntheticClass_1.a[PacketPlayOutPlayerInfo.EnumPlayerInfoAction.UPDATE_DISPLAY_NAME.ordinal()] = 4; + } catch (NoSuchFieldError ignored) { + } + + try { + PacketPlayOutPlayerInfo.SyntheticClass_1.a[PacketPlayOutPlayerInfo.EnumPlayerInfoAction.REMOVE_PLAYER.ordinal()] = 5; + } catch (NoSuchFieldError ignored) { + } + + } + } + + public static class PlayerInfoData { + + private final int b; + private final WorldSettings.EnumGamemode c; + private final GameProfile d; + private final IChatBaseComponent e; + + public PlayerInfoData(GameProfile gameprofile, int i, WorldSettings.EnumGamemode worldsettings_enumgamemode, IChatBaseComponent ichatbasecomponent) { + this.d = gameprofile; + this.b = i; + this.c = worldsettings_enumgamemode; + this.e = ichatbasecomponent; + } + + // Azurite - add back info data constructor as vortex removed/change old one, and it breaks a few plugins... + public PlayerInfoData(PacketPlayOutPlayerInfo this$0, GameProfile param1GameProfile, int param1Int, WorldSettings.EnumGamemode param1EnumGamemode, IChatBaseComponent param1IChatBaseComponent) { + this.d = param1GameProfile; + this.b = param1Int; + this.c = param1EnumGamemode; + this.e = param1IChatBaseComponent; + } + + public GameProfile a() { + return this.d; + } + + public int b() { + return this.b; + } + + public WorldSettings.EnumGamemode c() { + return this.c; + } + + public IChatBaseComponent d() { + return this.e; + } + + public String toString() { + return Objects.toStringHelper(this).add("latency", this.b).add("gameMode", this.c).add("profile", this.d).add("displayName", this.e == null ? null : IChatBaseComponent.ChatSerializer.a(this.e)).toString(); + } + } + + public enum EnumPlayerInfoAction { + + ADD_PLAYER, UPDATE_GAME_MODE, UPDATE_LATENCY, UPDATE_DISPLAY_NAME, REMOVE_PLAYER; + + EnumPlayerInfoAction() { + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutPlayerListHeaderFooter.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutPlayerListHeaderFooter.java new file mode 100644 index 0000000..70dfa17 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutPlayerListHeaderFooter.java @@ -0,0 +1,103 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; + +public class PacketPlayOutPlayerListHeaderFooter implements Packet { + + public net.md_5.bungee.api.chat.BaseComponent[] header, footer; // Paper + + public IChatBaseComponent a; + public IChatBaseComponent b; + + private String serializedHeader = null; + private String serializedFooter = null; + + public PacketPlayOutPlayerListHeaderFooter() {} + + public PacketPlayOutPlayerListHeaderFooter(IChatBaseComponent ichatbasecomponent) { + this.a = ichatbasecomponent; + this.serialize(); + } + + // Beanes - constructor for header & footer + public PacketPlayOutPlayerListHeaderFooter(IChatBaseComponent header, IChatBaseComponent footer) { + this.a = header; + this.b = footer; + this.serialize(); + } + + public void a(PacketDataSerializer packetdataserializer) throws IOException { + this.a = packetdataserializer.d(); + this.b = packetdataserializer.d(); + } + + public void b(PacketDataSerializer packetdataserializer) throws IOException { + // Paper start + if (this.header != null) { + packetdataserializer.a(net.md_5.bungee.chat.ComponentSerializer.toString(this.header)); + } else { + packetdataserializer.a(this.a); + } + + if (this.footer != null) { + packetdataserializer.a(net.md_5.bungee.chat.ComponentSerializer.toString(this.footer)); + } else { + packetdataserializer.a(this.b); + } + // Paper end + } + + // Beanes - only serialize once + public void serialize() { + if (this.header != null) { + serializedHeader = net.md_5.bungee.chat.ComponentSerializer.toString(this.header); + } else { + serializedHeader = IChatBaseComponent.ChatSerializer.a(this.a); + } + + if (this.footer != null) { + serializedFooter = net.md_5.bungee.chat.ComponentSerializer.toString(this.footer); + } else { + serializedFooter = IChatBaseComponent.ChatSerializer.a(this.b); + } + } + + @Override + public int getSize() { + int size = 0; + + if (this.serializedHeader != null) { + size += ProtocolUtils.getStringSize(this.serializedHeader); + } else { + if (this.header != null) { + size += ProtocolUtils.getChatComponentSize(this.header); + } else { + size += ProtocolUtils.getChatComponentSize(this.a); + } + } + + if (this.serializedFooter != null) { + size += ProtocolUtils.getStringSize(this.serializedFooter); + } else { + if (this.footer != null) { + size += ProtocolUtils.getChatComponentSize(this.footer); + } else { + size += ProtocolUtils.getChatComponentSize(this.b); + } + } + + return size; + } + + @Override + public int getId() { + return 0x47; + } + + public void a(PacketListenerPlayOut packetlistenerplayout) { + packetlistenerplayout.a(this); + } + +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutPosition.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutPosition.java new file mode 100644 index 0000000..a3c1e29 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutPosition.java @@ -0,0 +1,121 @@ +package net.minecraft.server; + +import java.io.IOException; +import java.util.EnumSet; +import java.util.Iterator; +import java.util.Set; + +public class PacketPlayOutPosition implements Packet { + public double a; + public double b; + public double c; + public float d; + public float e; + public Set f; + + // Azurite start - Obfuscation helpers + public double getX() { + return a; + } + + public double getY() { + return b; + } + + public double getZ() { + return c; + } + + public Set getFlags() { + return f; + } + // Azurite end + + public PacketPlayOutPosition() { + } + + public PacketPlayOutPosition(double var1, double var3, double var5, float var7, float var8, Set var9) { + this.a = var1; + this.b = var3; + this.c = var5; + this.d = var7; + this.e = var8; + this.f = var9; + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.readDouble(); + this.b = var1.readDouble(); + this.c = var1.readDouble(); + this.d = var1.readFloat(); + this.e = var1.readFloat(); + this.f = PacketPlayOutPosition.EnumPlayerTeleportFlags.a(var1.readUnsignedByte()); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.writeDouble(this.a); + var1.writeDouble(this.b); + var1.writeDouble(this.c); + var1.writeFloat(this.d); + var1.writeFloat(this.e); + var1.writeByte(PacketPlayOutPosition.EnumPlayerTeleportFlags.a(this.f)); + } + + @Override + public int getSize() { + return 8 + 8 + 8 + 4 + 4 + 1; + } + + @Override + public int getId() { + return 0x08; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } + + public enum EnumPlayerTeleportFlags { + X(0), + Y(1), + Z(2), + Y_ROT(3), + X_ROT(4); + + private final int f; + + EnumPlayerTeleportFlags(int var3) { + this.f = var3; + } + + public static Set a(int var0) { + EnumSet var1 = EnumSet.noneOf(PacketPlayOutPosition.EnumPlayerTeleportFlags.class); + for (EnumPlayerTeleportFlags var5 : values()) { + if (var5.b(var0)) { + var1.add(var5); + } + } + + return var1; + } + + public static int a(Set var0) { + int var1 = 0; + + PacketPlayOutPosition.EnumPlayerTeleportFlags var3; + for (Iterator var2 = var0.iterator(); var2.hasNext(); var1 |= var3.a()) { + var3 = var2.next(); + } + + return var1; + } + + private int a() { + return 1 << this.f; + } + + private boolean b(int var1) { + return (var1 & this.a()) == this.a(); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutRemoveEntityEffect.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutRemoveEntityEffect.java new file mode 100644 index 0000000..27ef7ae --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutRemoveEntityEffect.java @@ -0,0 +1,42 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; + +public class PacketPlayOutRemoveEntityEffect implements Packet { + public int a; + public int b; + + public PacketPlayOutRemoveEntityEffect() { + } + + public PacketPlayOutRemoveEntityEffect(int entityId, MobEffect effect) { + this.a = entityId; + this.b = effect.getEffectId(); + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.e(); + this.b = var1.readUnsignedByte(); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.b(this.a); + var1.writeByte(this.b); + } + + @Override + public int getSize() { + return ProtocolUtils.varIntBytes(this.a) + 1; + } + + @Override + public int getId() { + return 0x1e; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutResourcePackSend.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutResourcePackSend.java new file mode 100644 index 0000000..a1b0e82 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutResourcePackSend.java @@ -0,0 +1,45 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; + +public class PacketPlayOutResourcePackSend implements Packet { + public String a; + public String b; + + public PacketPlayOutResourcePackSend() { + } + + public PacketPlayOutResourcePackSend(String var1, String var2) { + this.a = var1; + this.b = var2; + if (var2.length() > 40) { + throw new IllegalArgumentException("Hash is too long (max 40, was " + var2.length() + ")"); + } + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.c(32767); + this.b = var1.c(40); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.a(this.a); + var1.a(this.b); + } + + @Override + public int getSize() { + return ProtocolUtils.getStringSize(this.a) + ProtocolUtils.getStringSize(this.b); + } + + @Override + public int getId() { + return 0x48; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutRespawn.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutRespawn.java new file mode 100644 index 0000000..21360a0 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutRespawn.java @@ -0,0 +1,55 @@ +package net.minecraft.server; + +import java.io.IOException; + +import dev.azurite.spigot.optimizations.ProtocolUtils; +import net.minecraft.server.WorldSettings.EnumGamemode; + +public class PacketPlayOutRespawn implements Packet { + public int a; + public EnumDifficulty b; + public WorldSettings.EnumGamemode c; + public WorldType d; + + public PacketPlayOutRespawn() { + } + + public PacketPlayOutRespawn(int var1, EnumDifficulty var2, WorldType var3, WorldSettings.EnumGamemode var4) { + this.a = var1; + this.b = var2; + this.c = var4; + this.d = var3; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.readInt(); + this.b = EnumDifficulty.getById(var1.readUnsignedByte()); + this.c = EnumGamemode.getById(var1.readUnsignedByte()); + this.d = WorldType.getType(var1.c(16)); + if (this.d == null) { + this.d = WorldType.NORMAL; + } + + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.writeInt(this.a); + var1.writeByte(this.b.a()); + var1.writeByte(this.c.getId()); + var1.a(this.d.name()); + } + + @Override + public int getSize() { + return 4 + 1 + 1 + ProtocolUtils.getStringSize(this.d.name()); + } + + @Override + public int getId() { + return 0x07; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutScoreboardDisplayObjective.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutScoreboardDisplayObjective.java new file mode 100644 index 0000000..f21be4b --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutScoreboardDisplayObjective.java @@ -0,0 +1,58 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; + +public class PacketPlayOutScoreboardDisplayObjective implements Packet { + + public int a; + public String b; + + public PacketPlayOutScoreboardDisplayObjective() {} + + public PacketPlayOutScoreboardDisplayObjective(int i, ScoreboardObjective scoreboardobjective) { + this.a = i; + if (scoreboardobjective == null) { + this.b = ""; + } else { + this.b = scoreboardobjective.getName(); + } + + } + + // Beanes - add constructor without needing a scoreboard objective + public PacketPlayOutScoreboardDisplayObjective(int mode, String objectiveName) { + this.a = mode; + if (objectiveName == null) { + this.b = ""; + } else { + this.b = objectiveName; + } + + } + + public void a(PacketDataSerializer packetdataserializer) throws IOException { + this.a = packetdataserializer.readByte(); + this.b = packetdataserializer.c(16); + } + + public void b(PacketDataSerializer packetdataserializer) throws IOException { + packetdataserializer.writeByte(this.a); + packetdataserializer.a(this.b); + } + + @Override + public int getSize() { + return 1 + ProtocolUtils.getStringSize(this.b); + } + + @Override + public int getId() { + return 0x3d; + } + + public void a(PacketListenerPlayOut packetlistenerplayout) { + packetlistenerplayout.a(this); + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutScoreboardObjective.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutScoreboardObjective.java new file mode 100644 index 0000000..e259b3d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutScoreboardObjective.java @@ -0,0 +1,63 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; + +public class PacketPlayOutScoreboardObjective implements Packet { + + public String a; + public String b; + public IScoreboardCriteria.EnumScoreboardHealthDisplay c; + public int d; + + public PacketPlayOutScoreboardObjective() {} + + public PacketPlayOutScoreboardObjective(ScoreboardObjective scoreboardobjective, int i) { + this.a = scoreboardobjective.getName(); + this.b = scoreboardobjective.getDisplayName(); + this.c = scoreboardobjective.getCriteria().c(); + this.d = i; + } + + // Beanes - add constructor without needing a scoreboard objective + public PacketPlayOutScoreboardObjective(String objective, String objectiveDisplay, IScoreboardCriteria.EnumScoreboardHealthDisplay type, int mode) { + this.a = objective; + this.b = objectiveDisplay; + this.c = type; + this.d = mode; + } + + public void a(PacketDataSerializer packetdataserializer) throws IOException { + this.a = packetdataserializer.c(16); + this.d = packetdataserializer.readByte(); + if (this.d == 0 || this.d == 2) { + this.b = packetdataserializer.c(32); + this.c = IScoreboardCriteria.EnumScoreboardHealthDisplay.a(packetdataserializer.c(16)); + } + + } + + public void b(PacketDataSerializer packetdataserializer) throws IOException { + packetdataserializer.a(this.a); + packetdataserializer.writeByte(this.d); + if (this.d == 0 || this.d == 2) { + packetdataserializer.a(this.b); + packetdataserializer.a(this.c.a()); + } + } + + @Override + public int getSize() { + return ProtocolUtils.getStringSize(this.a) + 1 + ((this.d == 0 || this.d == 2) ? (ProtocolUtils.getStringSize(this.b) + ProtocolUtils.getStringSize(this.c.a())) : 0); + } + + @Override + public int getId() { + return 0x3b; + } + + public void a(PacketListenerPlayOut packetlistenerplayout) { + packetlistenerplayout.a(this); + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutScoreboardScore.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutScoreboardScore.java new file mode 100644 index 0000000..55f0523 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutScoreboardScore.java @@ -0,0 +1,83 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; + +public class PacketPlayOutScoreboardScore implements Packet { + public String a = ""; + public String b = ""; + public int c; + public EnumScoreboardAction d; + + public PacketPlayOutScoreboardScore(ScoreboardScore score) { + this.a = score.getPlayerName(); + this.b = score.getObjective().getName(); + this.c = score.getScore(); + this.d = EnumScoreboardAction.CHANGE; + } + + public PacketPlayOutScoreboardScore(String player) { + this.a = player; + this.c = 0; + this.d = EnumScoreboardAction.REMOVE; + } + + public PacketPlayOutScoreboardScore(String player, ScoreboardObjective objective) { + this.a = player; + this.b = objective.getName(); + this.c = 0; + this.d = EnumScoreboardAction.REMOVE; + } + + public PacketPlayOutScoreboardScore() {} + + // Beanes - add constructor + public PacketPlayOutScoreboardScore(String objective, String scoreName, EnumScoreboardAction action, int scoreValue) { + this.a = scoreName; + this.b = objective; + this.c = scoreValue; + this.d = action; + } + + // Beanes - add constructor + public PacketPlayOutScoreboardScore(String objective, String scoreName, EnumScoreboardAction action) { + this.a = scoreName; + this.b = objective; + this.d = action; + } + + public void a(PacketDataSerializer serializer) throws IOException { + this.a = serializer.c(40); + this.d = serializer.a(EnumScoreboardAction.class); + this.b = serializer.c(16); + if (this.d != EnumScoreboardAction.REMOVE) + this.c = serializer.e(); + } + + public void b(PacketDataSerializer serializer) throws IOException { + serializer.a(this.a); + serializer.a(this.d); + serializer.a(this.b); + if (this.d != EnumScoreboardAction.REMOVE) + serializer.b(this.c); + } + + @Override + public int getSize() { + return ProtocolUtils.getStringSize(this.a) + ProtocolUtils.getEnumSize(this.d) + ProtocolUtils.getStringSize(this.b) + ((this.d != EnumScoreboardAction.REMOVE) ? ProtocolUtils.varIntBytes(this.c) : 0); + } + + @Override + public int getId() { + return 0x3c; + } + + public void a(PacketListenerPlayOut listener) { + listener.a(this); + } + + public enum EnumScoreboardAction { + CHANGE, REMOVE + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutScoreboardTeam.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutScoreboardTeam.java new file mode 100644 index 0000000..83bd0bd --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutScoreboardTeam.java @@ -0,0 +1,144 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; + +public class PacketPlayOutScoreboardTeam implements Packet { + public String a = ""; + public String b = ""; + public String c = ""; + public String d = ""; + public String e = ScoreboardTeamBase.EnumNameTagVisibility.ALWAYS.e; + public int f = -1; + public Collection g = Lists.newArrayList(); + public int h; + public int i; + + public PacketPlayOutScoreboardTeam(ScoreboardTeam team, int action) { + this.a = team.getName(); + this.h = action; + if (action == 0 || action == 2) { + this.b = team.getDisplayName(); + this.c = team.getPrefix(); + this.d = team.getSuffix(); + this.i = team.packOptionData(); + this.e = (team.getNameTagVisibility()).e; + this.f = team.l().b(); + } + if (action == 0) + this.g.addAll(team.getPlayerNameSet()); + } + + public PacketPlayOutScoreboardTeam(ScoreboardTeam team, Collection players, int action) { + if (action != 3 && action != 4) + throw new IllegalArgumentException("Method must be join or leave for player constructor"); + if (players == null || players.isEmpty()) + throw new IllegalArgumentException("Players cannot be null/empty"); + this.h = action; + this.a = team.getName(); + this.g.addAll(players); + } + + public void a(PacketDataSerializer serializer) throws IOException { + this.a = serializer.c(16); + this.h = serializer.readByte(); + if (this.h == 0 || this.h == 2) { + this.b = serializer.c(32); + this.c = serializer.c(16); + this.d = serializer.c(16); + this.i = serializer.readByte(); + this.e = serializer.c(32); + this.f = serializer.readByte(); + } + if (this.h == 0 || this.h == 3 || this.h == 4) { + int j = serializer.e(); + for (byte b1 = 0; b1 < j; b1 = (byte)(b1 + 1)) + this.g.add(serializer.c(40)); + } + } + + public void b(PacketDataSerializer serializer) throws IOException { + serializer.a(this.a); + serializer.writeByte(this.h); + if (this.h == 0 || this.h == 2) { + serializer.a(this.b); + serializer.a(this.c); + serializer.a(this.d); + serializer.writeByte(this.i); + serializer.a(this.e); + serializer.writeByte(this.f); + } + if (this.h == 0 || this.h == 3 || this.h == 4) { + serializer.b(this.g.size()); + for (String str : this.g) + serializer.a(str); + } + } + + @Override + public int getSize() { + int size = ProtocolUtils.getStringSize(this.a) + 1; + + if (this.h == 0 || this.h == 2) { + size += ProtocolUtils.getStringSize(this.b) + ProtocolUtils.getStringSize(this.c) + ProtocolUtils.getStringSize(this.d) + 1 + ProtocolUtils.getStringSize(this.e) + 1; + } + if (this.h == 0 || this.h == 3 || this.h == 4) { + size += ProtocolUtils.varIntBytes(this.g.size()); + + for (String str : this.g) { + size += ProtocolUtils.getStringSize(str); + } + } + + return size; + } + + @Override + public int getId() { + return 0x3e; + } + + // Beanes - add constructor without needing a scoreboard team, used for scoreboards + public PacketPlayOutScoreboardTeam(String teamName, String prefix, String suffix, String memberName) { + this.e = ScoreboardTeamBase.EnumNameTagVisibility.ALWAYS.e; + this.f = -1; + this.g = new ArrayList<>(); + this.a = teamName; + this.h = 0; + + this.b = ""; + this.c = prefix; + this.d = suffix; + + this.g.add(memberName); + } + + // Beanes - add constructor without needing a team, used for scoreboards + public PacketPlayOutScoreboardTeam(String teamName, String prefix, String suffix) { + this.e = ScoreboardTeamBase.EnumNameTagVisibility.ALWAYS.e; + this.f = -1; + this.g = new ArrayList<>(); + this.a = teamName; + this.h = 2; + + this.b = ""; + this.c = prefix; + this.d = suffix; + } + + // Beanes - add constructor without needing a team, used for scoreboards + public PacketPlayOutScoreboardTeam(String teamName) { + this.a = teamName; + this.h = 1; + } + + public void a(PacketListenerPlayOut listener) { + listener.a(this); + } + + public PacketPlayOutScoreboardTeam() {} +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutServerDifficulty.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutServerDifficulty.java new file mode 100644 index 0000000..aee1df8 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutServerDifficulty.java @@ -0,0 +1,38 @@ +package net.minecraft.server; + +import java.io.IOException; + +public class PacketPlayOutServerDifficulty implements Packet { + public EnumDifficulty a; + public boolean b; + + public PacketPlayOutServerDifficulty() { + } + + public PacketPlayOutServerDifficulty(EnumDifficulty var1, boolean var2) { + this.a = var1; + this.b = var2; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = EnumDifficulty.getById(var1.readUnsignedByte()); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.writeByte(this.a.a()); + } + + @Override + public int getSize() { + return 1; + } + + @Override + public int getId() { + return 0x41; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutSetCompression.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutSetCompression.java new file mode 100644 index 0000000..b9ff6ab --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutSetCompression.java @@ -0,0 +1,34 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; + +public class PacketPlayOutSetCompression implements Packet { + public int a; + + public PacketPlayOutSetCompression() { + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.e(); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.b(this.a); + } + + @Override + public int getSize() { + return ProtocolUtils.varIntBytes(this.a); + } + + @Override + public int getId() { + return 0x46; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutSetSlot.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutSetSlot.java new file mode 100644 index 0000000..cc88fc5 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutSetSlot.java @@ -0,0 +1,51 @@ +// +// Source code recreated from a .class file by IntelliJ IDEA +// (powered by FernFlower decompiler) +// + +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; + +public class PacketPlayOutSetSlot implements Packet { + public int a; + public int b; + public ItemStack c; + + public PacketPlayOutSetSlot() { + } + + public PacketPlayOutSetSlot(int var1, int var2, ItemStack var3) { + this.a = var1; + this.b = var2; + this.c = var3 == null ? null : var3.cloneItemStack(); + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.readByte(); + this.b = var1.readShort(); + this.c = var1.i(); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.writeByte(this.a); + var1.writeShort(this.b); + var1.a(this.c); + } + + @Override + public int getSize() { + return 1 + 2 + ProtocolUtils.getItemSize(this.c); + } + + @Override + public int getId() { + return 0x2f; + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutSpawnEntity.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutSpawnEntity.java new file mode 100644 index 0000000..f2bcb4b --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutSpawnEntity.java @@ -0,0 +1,150 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; + +public class PacketPlayOutSpawnEntity implements Packet { + private static final double MOT_LIMIT = 3.9D; + public int a; + public int b; + public int c; + public int d; + public int e; + public int f; + public int g; + public int h; + public int i; + public int j; + public int k; + + public PacketPlayOutSpawnEntity() { + } + + public PacketPlayOutSpawnEntity(Entity entity, int type) { + this(entity, type, 0); + } + + public PacketPlayOutSpawnEntity(Entity entity, int type, int extraData) { + // Beanes - use new constructor + this(entity, + type, + extraData, + (int) Math.round(entity.locX * 32.0D), + (int) Math.round(entity.locY * 32.0D), + (int) Math.round(entity.locZ * 32.0D), + Math.round(entity.pitch * 256.0F / 360.0F), + Math.round(entity.yaw * 256.0F / 360.0F) + ); + } + + + // Beanes - constructor that allows overriding spawn loc + public PacketPlayOutSpawnEntity(Entity entity, int type, int extraData, int x, int y, int z, int yaw, int pitch) { + this.a = entity.getId(); + // Beanes - more accurate positions (round instead of floor) + this.b = x; + this.c = y; + this.d = z; + this.h = yaw; + this.i = pitch; + this.j = type; + this.k = extraData; + if (extraData > 0) { + double motX = entity.motX; + double motY = entity.motY; + double motZ = entity.motZ; + if (motX < -MOT_LIMIT) + motX = -MOT_LIMIT; + if (motY < -MOT_LIMIT) + motY = -MOT_LIMIT; + if (motZ < -MOT_LIMIT) + motZ = -MOT_LIMIT; + if (motX > MOT_LIMIT) + motX = MOT_LIMIT; + if (motY > MOT_LIMIT) + motY = MOT_LIMIT; + if (motZ > MOT_LIMIT) + motZ = MOT_LIMIT; + // Beanes - round + this.e = (int) Math.round(motX * 8000.0D); + this.f = (int) Math.round(motY * 8000.0D); + this.g = (int) Math.round(motZ * 8000.0D); + } + } + + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.e(); + this.j = var1.readByte(); + this.b = var1.readInt(); + this.c = var1.readInt(); + this.d = var1.readInt(); + this.h = var1.readByte(); + this.i = var1.readByte(); + this.k = var1.readInt(); + if (this.k > 0) { + this.e = var1.readShort(); + this.f = var1.readShort(); + this.g = var1.readShort(); + } + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.b(this.a); + var1.writeByte(this.j); + var1.writeInt(this.b); + var1.writeInt(this.c); + var1.writeInt(this.d); + var1.writeByte(this.h); + var1.writeByte(this.i); + var1.writeInt(this.k); + if (this.k > 0) { + var1.writeShort(this.e); + var1.writeShort(this.f); + var1.writeShort(this.g); + } + } + + @Override + public int getSize() { + return ProtocolUtils.varIntBytes(this.a) + 1 + 4 + 4 + 4 + 1 + 1 + 4 + (this.k > 0 ? 2 + 2 + 2 : 0); + } + + @Override + public int getId() { + return 0x0E; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } + + public void a(int var1) { + this.b = var1; + } + + public void b(int var1) { + this.c = var1; + } + + public void c(int var1) { + this.d = var1; + } + + public void d(int var1) { + this.e = var1; + } + + public void e(int var1) { + this.f = var1; + } + + public void f(int var1) { + this.g = var1; + } + + public void setType(int type) { + this.j = type; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutSpawnEntityExperienceOrb.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutSpawnEntityExperienceOrb.java new file mode 100644 index 0000000..a301732 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutSpawnEntityExperienceOrb.java @@ -0,0 +1,63 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; + +public class PacketPlayOutSpawnEntityExperienceOrb implements Packet { + public int a; + public int b; + public int c; + public int d; + public int e; + + public PacketPlayOutSpawnEntityExperienceOrb() { + } + + public PacketPlayOutSpawnEntityExperienceOrb(EntityExperienceOrb orb) { + this(orb, + (int) Math.round(orb.locX * 32.0), + (int) Math.round(orb.locY * 32.0), + (int) Math.round(orb.locZ * 32.0) + ); + } + + // Beanes - constructor that allows overriding spawn loc + public PacketPlayOutSpawnEntityExperienceOrb(EntityExperienceOrb orb, int x, int y, int z) { + this.a = orb.getId(); + this.b = x; + this.c = y; + this.d = z; + this.e = orb.j(); + } + + public void a(PacketDataSerializer packetdataserializer) throws IOException { + this.a = packetdataserializer.e(); + this.b = packetdataserializer.readInt(); + this.c = packetdataserializer.readInt(); + this.d = packetdataserializer.readInt(); + this.e = packetdataserializer.readShort(); + } + + public void b(PacketDataSerializer packetdataserializer) throws IOException { + packetdataserializer.b(this.a); + packetdataserializer.writeInt(this.b); + packetdataserializer.writeInt(this.c); + packetdataserializer.writeInt(this.d); + packetdataserializer.writeShort(this.e); + } + + @Override + public int getSize() { + return ProtocolUtils.varIntBytes(a) + 4 + 4 + 4 + 2; + } + + @Override + public int getId() { + return 0x11; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutSpawnEntityLiving.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutSpawnEntityLiving.java new file mode 100644 index 0000000..bd7d105 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutSpawnEntityLiving.java @@ -0,0 +1,118 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; +import java.util.List; + +public class PacketPlayOutSpawnEntityLiving implements Packet { + private static final double MOT_LIMIT = 3.9D; + public int a; + public int b; + public int c; + public int d; + public int e; + public int f; + public int g; + public int h; + public byte i; + public byte j; + public byte k; + public DataWatcher l; + public List m; + + public PacketPlayOutSpawnEntityLiving() { + } + + public PacketPlayOutSpawnEntityLiving(EntityLiving entity) { + this(entity, + (int) Math.round(entity.locX * 32.0D), + (int) Math.round(entity.locY * 32.0D), + (int) Math.round(entity.locZ * 32.0D), + Math.round(entity.yaw * 256.0F / 360.0F), + Math.round(entity.pitch * 256.0F / 360.0F), + Math.round(entity.aK * 256.0F / 360.0F) + ); + } + + // Beanes - constructor that allows overriding spawn loc + public PacketPlayOutSpawnEntityLiving(EntityLiving entity, int x, int y, int z, int yaw, int pitch, int yawHead) { + this.a = entity.getId(); + this.b = (byte) EntityTypes.a(entity); + // Azurite - more accurate positions (round instead of floor) + this.c = x; + this.d = y; + this.e = z; + this.i = (byte) yaw; + this.j = (byte) pitch; + this.k = (byte) yawHead; + double motX = entity.motX; + double motY = entity.motY; + double motZ = entity.motZ; + if (motX < -MOT_LIMIT) + motX = -MOT_LIMIT; + if (motY < -MOT_LIMIT) + motY = -MOT_LIMIT; + if (motZ < -MOT_LIMIT) + motZ = -MOT_LIMIT; + if (motX > MOT_LIMIT) + motX = MOT_LIMIT; + if (motY > MOT_LIMIT) + motY = MOT_LIMIT; + if (motZ > MOT_LIMIT) + motZ = MOT_LIMIT; + // Beanes - round + this.f = (int) Math.round(motX * 8000.0D); + this.g = (int) Math.round(motY * 8000.0D); + this.h = (int) Math.round(motZ * 8000.0D); + this.l = entity.getDataWatcher(); + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.e(); + this.b = var1.readByte() & 0xFF; + this.c = var1.readInt(); + this.d = var1.readInt(); + this.e = var1.readInt(); + this.i = var1.readByte(); + this.j = var1.readByte(); + this.k = var1.readByte(); + this.f = var1.readShort(); + this.g = var1.readShort(); + this.h = var1.readShort(); + this.m = DataWatcher.b(var1); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.b(this.a); + var1.writeByte(this.b & 0xFF); + var1.writeInt(this.c); + var1.writeInt(this.d); + var1.writeInt(this.e); + var1.writeByte(this.i); + var1.writeByte(this.j); + var1.writeByte(this.k); + var1.writeShort(this.f); + var1.writeShort(this.g); + var1.writeShort(this.h); + this.l.a(var1); + } + + @Override + public int getSize() { + return ProtocolUtils.varIntBytes(this.a) + 1 + 4 + 4 + 4 + 1 + 1 + 1 + 2 + 2 + 2 + ProtocolUtils.getDataWatcherSize(this.l); + } + + @Override + public int getId() { + return 0x0F; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } + + public DataWatcher getDataWatcher() { + return this.l; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutSpawnEntityPainting.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutSpawnEntityPainting.java new file mode 100644 index 0000000..fce5a8e --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutSpawnEntityPainting.java @@ -0,0 +1,51 @@ +package net.minecraft.server; + +import java.io.IOException; + +import dev.azurite.spigot.optimizations.ProtocolUtils; +import net.minecraft.server.EntityPainting.EnumArt; + +public class PacketPlayOutSpawnEntityPainting implements Packet { + public int a; + public BlockPosition b; + public EnumDirection c; + public String d; + + public PacketPlayOutSpawnEntityPainting() { + } + + public PacketPlayOutSpawnEntityPainting(EntityPainting painting) { + this.a = painting.getId(); + this.b = painting.getBlockPosition(); + this.c = painting.direction; + this.d = painting.art.B; + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.e(); + this.d = var1.c(EnumArt.A); + this.b = var1.c(); + this.c = EnumDirection.fromType2(var1.readUnsignedByte()); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.b(this.a); + var1.a(this.d); + var1.a(this.b); + var1.writeByte(this.c.b()); + } + + @Override + public int getSize() { + return ProtocolUtils.varIntBytes(this.a) + ProtocolUtils.getStringSize(this.d) + 8 + 1; + } + + @Override + public int getId() { + return 0x10; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutSpawnEntityWeather.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutSpawnEntityWeather.java new file mode 100644 index 0000000..a482233 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutSpawnEntityWeather.java @@ -0,0 +1,58 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; + +public class PacketPlayOutSpawnEntityWeather implements Packet { + public int a; + public int b; + public int c; + public int d; + public int e; + + public PacketPlayOutSpawnEntityWeather() {} + + public PacketPlayOutSpawnEntityWeather(Entity entity) { + this.a = entity.getId(); + // Beanes - more accurate positions + this.b = (int) Math.round(entity.locX * 32.0D); + this.c = (int) Math.round(entity.locY * 32.0D); + this.d = (int) Math.round(entity.locZ * 32.0D); + if (entity instanceof EntityLightning) { + this.e = 1; + } + + } + + public void a(PacketDataSerializer packetdataserializer) throws IOException { + this.a = packetdataserializer.e(); + this.e = packetdataserializer.readByte(); + this.b = packetdataserializer.readInt(); + this.c = packetdataserializer.readInt(); + this.d = packetdataserializer.readInt(); + } + + public void b(PacketDataSerializer packetdataserializer) throws IOException { + packetdataserializer.b(this.a); + packetdataserializer.writeByte(this.e); + packetdataserializer.writeInt(this.b); + packetdataserializer.writeInt(this.c); + packetdataserializer.writeInt(this.d); + } + + @Override + public int getSize() { + return ProtocolUtils.varIntBytes(this.a) + 1 + 4 + 4 + 4; + } + + @Override + public int getId() { + return 0x2c; + } + + public void a(PacketListenerPlayOut packetlistenerplayout) { + packetlistenerplayout.a(this); + } + +} \ No newline at end of file diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutSpawnPosition.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutSpawnPosition.java new file mode 100644 index 0000000..6fc2a31 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutSpawnPosition.java @@ -0,0 +1,36 @@ +package net.minecraft.server; + +import java.io.IOException; + +public class PacketPlayOutSpawnPosition implements Packet { + public BlockPosition position; + + public PacketPlayOutSpawnPosition() { + } + + public PacketPlayOutSpawnPosition(BlockPosition var1) { + this.position = var1; + } + + public void a(PacketDataSerializer var1) throws IOException { + this.position = var1.c(); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.a(this.position); + } + + @Override + public int getSize() { + return 8; + } + + @Override + public int getId() { + return 0x05; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutStatistic.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutStatistic.java new file mode 100644 index 0000000..b575813 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutStatistic.java @@ -0,0 +1,64 @@ +package net.minecraft.server; + +import com.google.common.collect.Maps; +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; +import java.util.Iterator; +import java.util.Map; + +public class PacketPlayOutStatistic implements Packet { + public Map a; + + public PacketPlayOutStatistic() { + } + + public PacketPlayOutStatistic(Map var1) { + this.a = var1; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } + + public void a(PacketDataSerializer var1) throws IOException { + int var2 = var1.e(); + this.a = Maps.newHashMap(); + + for(int var3 = 0; var3 < var2; ++var3) { + Statistic var4 = StatisticList.getStatistic(var1.c(32767)); + int var5 = var1.e(); + if (var4 != null) { + this.a.put(var4, var5); + } + } + + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.b(this.a.size()); + + for (Map.Entry statisticIntegerEntry : this.a.entrySet()) { + var1.a(statisticIntegerEntry.getKey().name); + var1.b(statisticIntegerEntry.getValue()); + } + } + + @Override + public int getSize() { + int size = ProtocolUtils.varIntBytes(this.a.size()); + + for (Map.Entry statisticIntegerEntry : this.a.entrySet()) { + + size += ProtocolUtils.getStringSize(statisticIntegerEntry.getKey().name); + size += ProtocolUtils.varIntBytes(statisticIntegerEntry.getValue()); + } + + return size; + } + + @Override + public int getId() { + return 0x37; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutTabComplete.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutTabComplete.java new file mode 100644 index 0000000..252beb5 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutTabComplete.java @@ -0,0 +1,53 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; + +public class PacketPlayOutTabComplete implements Packet { + public String[] a; + + public PacketPlayOutTabComplete() { + } + + public PacketPlayOutTabComplete(String[] options) { + this.a = options; + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = new String[var1.e()]; + + for(int var2 = 0; var2 < this.a.length; ++var2) { + this.a[var2] = var1.c(32767); + } + + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.b(this.a.length); + + for (String option : this.a) { + var1.a(option); + } + } + + @Override + public int getSize() { + int size = ProtocolUtils.varIntBytes(this.a.length); + + for (String option : this.a) { + size += ProtocolUtils.getStringSize(option); + } + + return size; + } + + @Override + public int getId() { + return 0x3a; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutTileEntityData.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutTileEntityData.java new file mode 100644 index 0000000..a9c6bee --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutTileEntityData.java @@ -0,0 +1,46 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; + +public class PacketPlayOutTileEntityData implements Packet { + public BlockPosition a; + public int b; + public NBTTagCompound c; + + public PacketPlayOutTileEntityData() { + } + + public PacketPlayOutTileEntityData(BlockPosition var1, int var2, NBTTagCompound var3) { + this.a = var1; + this.b = var2; + this.c = var3; + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.c(); + this.b = var1.readUnsignedByte(); + this.c = var1.h(); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.a(this.a); + var1.writeByte((byte)this.b); + var1.a(this.c); + } + + @Override + public int getSize() { + return 8 + 1 + ProtocolUtils.getNBTSize(this.c); + } + + @Override + public int getId() { + return 0x35; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutTitle.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutTitle.java new file mode 100644 index 0000000..8441947 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutTitle.java @@ -0,0 +1,152 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; + +public class PacketPlayOutTitle implements Packet { + + public EnumTitleAction a; + public IChatBaseComponent b; + public int c; + public int d; + public int e; + public net.md_5.bungee.api.chat.BaseComponent[] components; + public String serializedJson = null; + + public PacketPlayOutTitle(EnumTitleAction action, net.md_5.bungee.api.chat.BaseComponent[] components, int fadeIn, int stay, int fadeOut) { + this.a = action; + this.components = components; + this.c = fadeIn; + this.d = stay; + this.e = fadeOut; + } + + public PacketPlayOutTitle() {} + + public PacketPlayOutTitle(EnumTitleAction packetplayouttitle_enumtitleaction, IChatBaseComponent ichatbasecomponent) { + this(packetplayouttitle_enumtitleaction, ichatbasecomponent, -1, -1, -1); + } + + public PacketPlayOutTitle(int i, int j, int k) { + this(EnumTitleAction.TIMES, (IChatBaseComponent) null, i, j, k); + } + + public PacketPlayOutTitle(EnumTitleAction packetplayouttitle_enumtitleaction, IChatBaseComponent ichatbasecomponent, int i, int j, int k) { + this.a = packetplayouttitle_enumtitleaction; + this.b = ichatbasecomponent; + this.c = i; + this.d = j; + this.e = k; + + this.serializeJson(); + } + + public void a(PacketDataSerializer packetdataserializer) throws IOException { + this.a = packetdataserializer.a(EnumTitleAction.class); + if (this.a == EnumTitleAction.TITLE || this.a == EnumTitleAction.SUBTITLE) { + this.b = packetdataserializer.d(); + } + + if (this.a == EnumTitleAction.TIMES) { + this.c = packetdataserializer.readInt(); + this.d = packetdataserializer.readInt(); + this.e = packetdataserializer.readInt(); + } + + } + + public void b(PacketDataSerializer packetdataserializer) throws IOException { + packetdataserializer.a(this.a); + if (this.a == EnumTitleAction.TITLE || this.a == EnumTitleAction.SUBTITLE) { + if (this.serializedJson != null) { + packetdataserializer.a(this.serializedJson); + } else { + // Paper start + if (this.components != null) { + packetdataserializer.a(net.md_5.bungee.chat.ComponentSerializer.toString(components)); + } else { + packetdataserializer.a(this.b); + } + // Paper end + } + } + + if (this.a == EnumTitleAction.TIMES) { + packetdataserializer.writeInt(this.c); + packetdataserializer.writeInt(this.d); + packetdataserializer.writeInt(this.e); + } + } + + // Beanes - only serialize once + public void serializeJson() { + if (this.components != null) { + this.serializedJson = net.md_5.bungee.chat.ComponentSerializer.toString(components); + } else { + this.serializedJson = IChatBaseComponent.ChatSerializer.a(this.b); + } + } + + @Override + public int getSize() { + int size = ProtocolUtils.getEnumSize(this.a); + + if (this.a == EnumTitleAction.TITLE || this.a == EnumTitleAction.SUBTITLE) { + if (this.serializedJson != null) { + size += ProtocolUtils.getStringSize(this.serializedJson); + } else { + // Paper start + if (this.components != null) { + size += ProtocolUtils.getChatComponentSize(components); + } else { + size += ProtocolUtils.getChatComponentSize(this.b); + } + // Paper end + } + } + + if (this.a == EnumTitleAction.TIMES) { + size += 4 + 4 + 4; + } + + return size; + } + + @Override + public int getId() { + return 0x45; + } + + public void a(PacketListenerPlayOut packetlistenerplayout) { + packetlistenerplayout.a(this); + } + + public enum EnumTitleAction { + + TITLE, SUBTITLE, TIMES, CLEAR, RESET; + + EnumTitleAction() {} + + public static EnumTitleAction a(String s) { + for (EnumTitleAction packetplayouttitle_enumtitleaction : values()) { + if (packetplayouttitle_enumtitleaction.name().equalsIgnoreCase(s)) { + return packetplayouttitle_enumtitleaction; + } + } + + return EnumTitleAction.TITLE; + } + + public static String[] a() { + String[] astring = new String[values().length]; + int i = 0; + + for (EnumTitleAction packetplayouttitle_enumtitleaction : values()) { + astring[i++] = packetplayouttitle_enumtitleaction.name().toLowerCase(); + } + + return astring; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutTransaction.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutTransaction.java new file mode 100644 index 0000000..d9eb7a2 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutTransaction.java @@ -0,0 +1,44 @@ +package net.minecraft.server; + +import java.io.IOException; + +public class PacketPlayOutTransaction implements Packet { + public int a; + public short b; + public boolean c; + + public PacketPlayOutTransaction() { + } + + public PacketPlayOutTransaction(int var1, short var2, boolean var3) { + this.a = var1; + this.b = var2; + this.c = var3; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.readUnsignedByte(); + this.b = var1.readShort(); + this.c = var1.readBoolean(); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.writeByte(this.a); + var1.writeShort(this.b); + var1.writeBoolean(this.c); + } + + @Override + public int getSize() { + return 1 + 2 + 1; + } + + @Override + public int getId() { + return 0x32; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutUpdateAttributes.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutUpdateAttributes.java new file mode 100644 index 0000000..41f3704 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutUpdateAttributes.java @@ -0,0 +1,108 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +public class PacketPlayOutUpdateAttributes implements Packet { + public int a; + public final List b = Lists.newArrayList(); + + public PacketPlayOutUpdateAttributes() { + } + + public PacketPlayOutUpdateAttributes(int i, Collection collection) { + this.a = i; + for (AttributeInstance attributeinstance : collection) { + this.b.add(new AttributeSnapshot(attributeinstance.getAttribute().getName(), attributeinstance.b(), attributeinstance.c())); + } + } + + public void a(PacketDataSerializer packetdataserializer) throws IOException { + this.a = packetdataserializer.e(); + int i = packetdataserializer.readInt(); + + for (int j = 0; j < i; ++j) { + String s = packetdataserializer.c(64); + double d0 = packetdataserializer.readDouble(); + ArrayList arraylist = Lists.newArrayList(); + int k = packetdataserializer.e(); + + for (int l = 0; l < k; ++l) { + arraylist.add(new AttributeModifier(packetdataserializer.g(), "Unknown synced attribute modifier", packetdataserializer.readDouble(), packetdataserializer.readByte())); + } + + this.b.add(new AttributeSnapshot(s, d0, arraylist)); + } + + } + + public void b(PacketDataSerializer packetdataserializer) throws IOException { + packetdataserializer.b(this.a); + packetdataserializer.writeInt(this.b.size()); + + for (AttributeSnapshot snapshot : this.b) { + packetdataserializer.a(snapshot.a()); + packetdataserializer.writeDouble(snapshot.b()); + packetdataserializer.b(snapshot.c().size()); + + for (AttributeModifier modifier : snapshot.c()) { + packetdataserializer.a(modifier.a()); + packetdataserializer.writeDouble(modifier.d()); + packetdataserializer.writeByte(modifier.c()); + } + } + } + + @Override + public int getSize() { + int size = ProtocolUtils.varIntBytes(this.a) + 4; + + for (AttributeSnapshot snapshot : this.b) { + size += ProtocolUtils.getStringSize(snapshot.a()) + 8 + ProtocolUtils.varIntBytes(snapshot.c().size()); + + size += (snapshot.c().size() * (16 + 8 + 1)); + } + + return size; + } + + @Override + public int getId() { + return 0x20; + } + + public void a(PacketListenerPlayOut packetlistenerplayout) { + packetlistenerplayout.a(this); + } + + + public class AttributeSnapshot { + + public final String b; + public final double c; + public final Collection d; + + public AttributeSnapshot(String s, double d0, Collection collection) { + this.b = s; + this.c = d0; + this.d = collection; + } + + public String a() { + return this.b; + } + + public double b() { + return this.c; + } + + public Collection c() { + return this.d; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutUpdateEntityNBT.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutUpdateEntityNBT.java new file mode 100644 index 0000000..668600c --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutUpdateEntityNBT.java @@ -0,0 +1,42 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; + +public class PacketPlayOutUpdateEntityNBT implements Packet { + public int a; + public NBTTagCompound b; + + public PacketPlayOutUpdateEntityNBT() { + } + + public PacketPlayOutUpdateEntityNBT(int var1, NBTTagCompound var2) { + this.a = var1; + this.b = var2; + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.e(); + this.b = var1.h(); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.b(this.a); + var1.a(this.b); + } + + @Override + public int getSize() { + return ProtocolUtils.varIntBytes(this.a) + ProtocolUtils.getNBTSize(this.b); + } + + @Override + public int getId() { + return 0x49; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutUpdateHealth.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutUpdateHealth.java new file mode 100644 index 0000000..7e156ec --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutUpdateHealth.java @@ -0,0 +1,52 @@ +// +// Source code recreated from a .class file by IntelliJ IDEA +// (powered by FernFlower decompiler) +// + +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; +import dev.azurite.spigot.utils.FixHealth; + +import java.io.IOException; + +public class PacketPlayOutUpdateHealth implements Packet { + public float a; + public int b; + public float c; + + public PacketPlayOutUpdateHealth() { + } + + public PacketPlayOutUpdateHealth(float health, int food, float saturation) { + this.a = FixHealth.roundHealth(health); // Beanes - correctly scale health + this.b = food; + this.c = saturation; + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.readFloat(); + this.b = var1.e(); + this.c = var1.readFloat(); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.writeFloat(this.a); + var1.b(this.b); + var1.writeFloat(this.c); + } + + @Override + public int getSize() { + return 4 + ProtocolUtils.varIntBytes(this.b) + 4; + } + + @Override + public int getId() { + return 0x06; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutUpdateSign.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutUpdateSign.java new file mode 100644 index 0000000..db18679 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutUpdateSign.java @@ -0,0 +1,81 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; + +public class PacketPlayOutUpdateSign implements Packet { + public World a; + public BlockPosition b; + public IChatBaseComponent[] c; + public String[] serializedJson = null; + + public PacketPlayOutUpdateSign() { + } + + public PacketPlayOutUpdateSign(World var1, BlockPosition var2, IChatBaseComponent[] var3) { + this.a = var1; + this.b = var2; + this.c = new IChatBaseComponent[]{var3[0], var3[1], var3[2], var3[3]}; + + this.serializeJson(); + } + + // Beanes - only serialize update sign json once + public void serializeJson() { + serializedJson = new String[4]; + + for(int i = 0; i < 4; ++i) { + serializedJson[i] = IChatBaseComponent.ChatSerializer.a(this.c[i]); + } + } + + public void a(PacketDataSerializer var1) throws IOException { + this.b = var1.c(); + this.c = new IChatBaseComponent[4]; + + for(int var2 = 0; var2 < 4; ++var2) { + this.c[var2] = var1.d(); + } + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.a(this.b); + + if (serializedJson != null) { + for(int i = 0; i < 4; ++i) { + var1.a(this.serializedJson[i]); + } + } else { + for(int i = 0; i < 4; ++i) { + var1.a(this.c[i]); + } + } + } + + @Override + public int getSize() { + int size = 8; + + if (serializedJson != null) { + for(int i = 0; i < 4; ++i) { + size += ProtocolUtils.getStringSize(serializedJson[i]); + } + } else { + for(int i = 0; i < 4; ++i) { + size += ProtocolUtils.getChatComponentSize(this.c[i]); + } + } + + return size; + } + + @Override + public int getId() { + return 0x33; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutUpdateTime.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutUpdateTime.java new file mode 100644 index 0000000..451e185 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutUpdateTime.java @@ -0,0 +1,47 @@ +package net.minecraft.server; + +import java.io.IOException; + +public class PacketPlayOutUpdateTime implements Packet { + public long a; + public long b; + + public PacketPlayOutUpdateTime() { + } + + public PacketPlayOutUpdateTime(long totalWorldTime, long worldTime, boolean doDayLightCycle) { + this.a = totalWorldTime; + this.b = worldTime; + if (!doDayLightCycle) { + this.b = -this.b; + if (this.b == 0L) { + this.b = -1L; + } + } + + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.readLong(); + this.b = var1.readLong(); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.writeLong(this.a); + var1.writeLong(this.b); + } + + @Override + public int getSize() { + return 8 + 8; + } + + @Override + public int getId() { + return 0x03; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutWindowData.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutWindowData.java new file mode 100644 index 0000000..41c9f3b --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutWindowData.java @@ -0,0 +1,44 @@ +package net.minecraft.server; + +import java.io.IOException; + +public class PacketPlayOutWindowData implements Packet { + public int a; + public int b; + public int c; + + public PacketPlayOutWindowData() { + } + + public PacketPlayOutWindowData(int var1, int var2, int var3) { + this.a = var1; + this.b = var2; + this.c = var3; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.readUnsignedByte(); + this.b = var1.readShort(); + this.c = var1.readShort(); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.writeByte(this.a); + var1.writeShort(this.b); + var1.writeShort(this.c); + } + + @Override + public int getSize() { + return 1 + 2 + 2; + } + + @Override + public int getId() { + return 0x31; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutWindowItems.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutWindowItems.java new file mode 100644 index 0000000..256ab5d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutWindowItems.java @@ -0,0 +1,66 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; +import java.util.List; + +public class PacketPlayOutWindowItems implements Packet { + public int a; + public ItemStack[] b; + + public PacketPlayOutWindowItems() {} + + public PacketPlayOutWindowItems(int i, List list) { + this.a = i; + this.b = new ItemStack[list.size()]; + + for (int j = 0; j < this.b.length; ++j) { + ItemStack itemstack = list.get(j); + + this.b[j] = itemstack == null ? null : itemstack.cloneItemStack(); + } + + } + + public void a(PacketDataSerializer packetdataserializer) throws IOException { + this.a = packetdataserializer.readUnsignedByte(); + short short0 = packetdataserializer.readShort(); + + this.b = new ItemStack[short0]; + + for (int i = 0; i < short0; ++i) { + this.b[i] = packetdataserializer.i(); + } + + } + + public void b(PacketDataSerializer packetdataserializer) throws IOException { + packetdataserializer.writeByte(this.a); + packetdataserializer.writeShort(this.b.length); + + for (ItemStack itemstack : this.b) { + packetdataserializer.a(itemstack); + } + } + + @Override + public int getSize() { + int size = 1 + 2; + + for (ItemStack itemstack : this.b) { + size += ProtocolUtils.getItemSize(itemstack); + } + + return size; + } + + @Override + public int getId() { + return 0x30; + } + + public void a(PacketListenerPlayOut packetlistenerplayout) { + packetlistenerplayout.a(this); + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutWorldBorder.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutWorldBorder.java new file mode 100644 index 0000000..6ac8ba3 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutWorldBorder.java @@ -0,0 +1,166 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; + +public class PacketPlayOutWorldBorder implements Packet { + public EnumWorldBorderAction a; + public int b; + public double c; + public double d; + public double e; + public double f; + public long g; + public int h; + public int i; + + public PacketPlayOutWorldBorder() { + } + + public PacketPlayOutWorldBorder(WorldBorder var1, EnumWorldBorderAction var2) { + this.a = var2; + this.c = var1.getCenterX(); + this.d = var1.getCenterZ(); + this.f = var1.getSize(); + this.e = var1.j(); + this.g = var1.i(); + this.b = var1.l(); + this.i = var1.getWarningDistance(); + this.h = var1.getWarningTime(); + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = (EnumWorldBorderAction)var1.a(EnumWorldBorderAction.class); + switch (this.a) { + case SET_SIZE: + this.e = var1.readDouble(); + break; + case LERP_SIZE: + this.f = var1.readDouble(); + this.e = var1.readDouble(); + this.g = var1.f(); + break; + case SET_CENTER: + this.c = var1.readDouble(); + this.d = var1.readDouble(); + break; + case SET_WARNING_BLOCKS: + this.i = var1.e(); + break; + case SET_WARNING_TIME: + this.h = var1.e(); + break; + case INITIALIZE: + this.c = var1.readDouble(); + this.d = var1.readDouble(); + this.f = var1.readDouble(); + this.e = var1.readDouble(); + this.g = var1.f(); + this.b = var1.e(); + this.i = var1.e(); + this.h = var1.e(); + } + + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.a(this.a); + switch (this.a) { + case SET_SIZE: + var1.writeDouble(this.e); + break; + case LERP_SIZE: + var1.writeDouble(this.f); + var1.writeDouble(this.e); + var1.b(this.g); + break; + case SET_CENTER: + var1.writeDouble(this.c); + var1.writeDouble(this.d); + break; + case SET_WARNING_BLOCKS: + var1.b(this.i); + break; + case SET_WARNING_TIME: + var1.b(this.h); + break; + case INITIALIZE: + var1.writeDouble(this.c); + var1.writeDouble(this.d); + var1.writeDouble(this.f); + var1.writeDouble(this.e); + var1.b(this.g); + var1.b(this.b); + var1.b(this.i); + var1.b(this.h); + } + } + + @Override + public int getSize() { + int size = ProtocolUtils.getEnumSize(this.a); + switch (this.a) { + case SET_SIZE: + size += 8; + break; + case LERP_SIZE: + size += 8 + 8; + + long writeSim1 = this.g; + + while ((writeSim1 & -128L) != 0L) { + size += 1; + writeSim1 >>>= 7; + } + + size += 1; + break; + case SET_CENTER: + size += 8 + 8; + break; + case SET_WARNING_BLOCKS: + size += ProtocolUtils.varIntBytes(this.i); + break; + case SET_WARNING_TIME: + size += ProtocolUtils.varIntBytes(this.h); + break; + case INITIALIZE: + size += 8 + 8 + 8 + 8; + + long writeSim2 = this.g; + + while ((writeSim2 & -128L) != 0L) { + size += 1; + writeSim2 >>>= 7; + } + + size += 1; + + size += ProtocolUtils.varIntBytes(this.b) + ProtocolUtils.varIntBytes(this.i) + ProtocolUtils.varIntBytes(this.h); + } + + return size; + } + + @Override + public int getId() { + return 0x44; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } + + public static enum EnumWorldBorderAction { + SET_SIZE, + LERP_SIZE, + SET_CENTER, + INITIALIZE, + SET_WARNING_TIME, + SET_WARNING_BLOCKS; + + private EnumWorldBorderAction() { + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutWorldEvent.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutWorldEvent.java new file mode 100644 index 0000000..ccb5d9d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutWorldEvent.java @@ -0,0 +1,48 @@ +package net.minecraft.server; + +import java.io.IOException; + +public class PacketPlayOutWorldEvent implements Packet { + public int a; + public BlockPosition b; + public int c; + public boolean d; + + public PacketPlayOutWorldEvent() { + } + + public PacketPlayOutWorldEvent(int var1, BlockPosition var2, int var3, boolean var4) { + this.a = var1; + this.b = var2; + this.c = var3; + this.d = var4; + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.readInt(); + this.b = var1.c(); + this.c = var1.readInt(); + this.d = var1.readBoolean(); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.writeInt(this.a); + var1.a(this.b); + var1.writeInt(this.c); + var1.writeBoolean(this.d); + } + + @Override + public int getSize() { + return 4 + 8 + 4 + 1; + } + + @Override + public int getId() { + return 0x28; + } + + public void a(PacketListenerPlayOut var1) { + var1.a(this); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutWorldParticles.java b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutWorldParticles.java new file mode 100644 index 0000000..6028e6d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPlayOutWorldParticles.java @@ -0,0 +1,101 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; + +public class PacketPlayOutWorldParticles implements Packet { + + public EnumParticle a; + public float b; + public float c; + public float d; + public float e; + public float f; + public float g; + public float h; + public int i; + public boolean j; + public int[] k; + + public PacketPlayOutWorldParticles() {} + + public PacketPlayOutWorldParticles(EnumParticle enumparticle, boolean flag, float f, float f1, float f2, float f3, float f4, float f5, float f6, int i, int... aint) { + this.a = enumparticle; + this.j = flag; + this.b = f; + this.c = f1; + this.d = f2; + this.e = f3; + this.f = f4; + this.g = f5; + this.h = f6; + this.i = i; + this.k = aint; + } + + public void a(PacketDataSerializer packetdataserializer) throws IOException { + this.a = EnumParticle.a(packetdataserializer.readInt()); + if (this.a == null) { + this.a = EnumParticle.BARRIER; + } + + this.j = packetdataserializer.readBoolean(); + this.b = packetdataserializer.readFloat(); + this.c = packetdataserializer.readFloat(); + this.d = packetdataserializer.readFloat(); + this.e = packetdataserializer.readFloat(); + this.f = packetdataserializer.readFloat(); + this.g = packetdataserializer.readFloat(); + this.h = packetdataserializer.readFloat(); + this.i = packetdataserializer.readInt(); + int i = this.a.d(); + + this.k = new int[i]; + + for (int j = 0; j < i; ++j) { + this.k[j] = packetdataserializer.e(); + } + + } + + public void b(PacketDataSerializer packetdataserializer) throws IOException { + packetdataserializer.writeInt(this.a.c()); + packetdataserializer.writeBoolean(this.j); + packetdataserializer.writeFloat(this.b); + packetdataserializer.writeFloat(this.c); + packetdataserializer.writeFloat(this.d); + packetdataserializer.writeFloat(this.e); + packetdataserializer.writeFloat(this.f); + packetdataserializer.writeFloat(this.g); + packetdataserializer.writeFloat(this.h); + packetdataserializer.writeInt(this.i); + + int i = this.a.d(); + for (int j = 0; j < i; ++j) { + packetdataserializer.b(this.k[j]); + } + } + + @Override + public int getSize() { + int size = 4 + 1 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4; + + int i = this.a.d(); + for (int j = 0; j < i; ++j) { + size += ProtocolUtils.varIntBytes(this.k[j]); + } + + return size; + } + + @Override + public int getId() { + return 0x2a; + } + + public void a(PacketListenerPlayOut packetlistenerplayout) { + packetlistenerplayout.a(this); + } + +} \ No newline at end of file diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketPrepender.java b/azurite-server/src/main/java/net/minecraft/server/PacketPrepender.java new file mode 100644 index 0000000..6033d6f --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketPrepender.java @@ -0,0 +1,26 @@ +package net.minecraft.server; + +import dev.azurite.spigot.optimizations.ProtocolUtils; +import io.netty.buffer.ByteBuf; +import io.netty.channel.ChannelHandler; +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.MessageToMessageEncoder; + +import java.util.List; + +@ChannelHandler.Sharable +public class PacketPrepender extends MessageToMessageEncoder { + public static final PacketPrepender INSTANCE = new PacketPrepender(); + + public PacketPrepender() { + } + + @Override + protected void encode(ChannelHandlerContext ctx, ByteBuf buf, List out) { + int readableBytes = buf.readableBytes(); + ByteBuf varIntBuffer = ctx.alloc().buffer(ProtocolUtils.varIntBytes(readableBytes)); + ProtocolUtils.writeVarInt(varIntBuffer, readableBytes); + out.add(varIntBuffer); + out.add(buf.retain()); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketSplitter.java b/azurite-server/src/main/java/net/minecraft/server/PacketSplitter.java new file mode 100644 index 0000000..8ce6b7b --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketSplitter.java @@ -0,0 +1,121 @@ +package net.minecraft.server; + +import io.netty.buffer.ByteBuf; +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.ByteToMessageDecoder; +import io.netty.handler.codec.CorruptedFrameException; + +import java.util.List; + +import static io.netty.util.ByteProcessor.FIND_NON_NUL; + +public class PacketSplitter extends ByteToMessageDecoder { + + public PacketSplitter() { + } + + protected void decode(ChannelHandlerContext channelhandlercontext, ByteBuf in, List list) throws Exception { + if (!channelhandlercontext.channel().isActive()) { + in.clear(); + return; + } + + // skip any runs of 0x00 we might find + int packetStart = in.forEachByte(FIND_NON_NUL); + if (packetStart == -1) { + in.clear(); + return; + } + in.readerIndex(packetStart); + + // try to read the length of the packet + in.markReaderIndex(); + int preIndex = in.readerIndex(); + int length = readRawVarInt21(in); + if (preIndex == in.readerIndex()) { + return; + } + if (length < 0) { + throw new CorruptedFrameException("Bad packet length"); + } + + // note that zero-length packets are ignored + if (length > 0) { + if (in.readableBytes() < length) { + in.resetReaderIndex(); + } else { + list.add(in.readRetainedSlice(length)); + } + } + } + + /** + * Reads a VarInt from the buffer of up to 21 bits in size. + * + * @param buffer the buffer to read from + * @return the VarInt decoded, {@code 0} if no varint could be read + * @throws CorruptedFrameException if the VarInt is too big to be decoded + */ + private static int readRawVarInt21(ByteBuf buffer) { + if (buffer.readableBytes() < 4) { + // we don't have enough that we can read a potentially full varint, so fall back to + // the slow path. + return readRawVarintSmallBuf(buffer); + } + int wholeOrMore = buffer.getIntLE(buffer.readerIndex()); + + // take the last three bytes and check if any of them have the high bit set + int atStop = ~wholeOrMore & 0x808080; + if (atStop == 0) { + // all bytes have the high bit set, so the varint we are trying to decode is too wide + throw new CorruptedFrameException("VarInt too big"); + } + + int bitsToKeep = Integer.numberOfTrailingZeros(atStop) + 1; + buffer.skipBytes(bitsToKeep >> 3); + + // remove all bits we don't need to keep, a trick from + // https://github.com/netty/netty/pull/14050#issuecomment-2107750734: + // + // > The idea is that thisVarintMask has 0s above the first one of firstOneOnStop, and 1s at + // > and below it. For example if firstOneOnStop is 0x800080 (where the last 0x80 is the only + // > one that matters), then thisVarintMask is 0xFF. + // + // this is also documented in Hacker's Delight, section 2-1 "Manipulating Rightmost Bits" + int preservedBytes = wholeOrMore & (atStop ^ (atStop - 1)); + + // merge together using this trick: https://github.com/netty/netty/pull/14050#discussion_r1597896639 + preservedBytes = (preservedBytes & 0x007F007F) | ((preservedBytes & 0x00007F00) >> 1); + preservedBytes = (preservedBytes & 0x00003FFF) | ((preservedBytes & 0x3FFF0000) >> 2); + return preservedBytes; + } + + private static int readRawVarintSmallBuf(ByteBuf buffer) { + if (!buffer.isReadable()) { + return 0; + } + buffer.markReaderIndex(); + + byte tmp = buffer.readByte(); + if (tmp >= 0) { + return tmp; + } + int result = tmp & 0x7F; + if (!buffer.isReadable()) { + buffer.resetReaderIndex(); + return 0; + } + if ((tmp = buffer.readByte()) >= 0) { + return result | tmp << 7; + } + result |= (tmp & 0x7F) << 7; + if (!buffer.isReadable()) { + buffer.resetReaderIndex(); + return 0; + } + if ((tmp = buffer.readByte()) >= 0) { + return result | tmp << 14; + } + return result | (tmp & 0x7F) << 14; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketStatusInListener.java b/azurite-server/src/main/java/net/minecraft/server/PacketStatusInListener.java new file mode 100644 index 0000000..fb53dbe --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketStatusInListener.java @@ -0,0 +1,8 @@ +package net.minecraft.server; + +public interface PacketStatusInListener extends PacketListener { + + void a(PacketStatusInPing packetstatusinping); + + void a(PacketStatusInStart packetstatusinstart); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketStatusInPing.java b/azurite-server/src/main/java/net/minecraft/server/PacketStatusInPing.java new file mode 100644 index 0000000..fe0d38b --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketStatusInPing.java @@ -0,0 +1,26 @@ +package net.minecraft.server; + +import java.io.IOException; + +public class PacketStatusInPing implements Packet { + public long a; + + public PacketStatusInPing() { + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.readLong(); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.writeLong(this.a); + } + + public void a(PacketStatusInListener var1) { + var1.a(this); + } + + public long a() { + return this.a; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketStatusInStart.java b/azurite-server/src/main/java/net/minecraft/server/PacketStatusInStart.java new file mode 100644 index 0000000..9b43161 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketStatusInStart.java @@ -0,0 +1,18 @@ +package net.minecraft.server; + +import java.io.IOException; + +public class PacketStatusInStart implements Packet { + public PacketStatusInStart() { + } + + public void a(PacketDataSerializer var1) throws IOException { + } + + public void b(PacketDataSerializer var1) throws IOException { + } + + public void a(PacketStatusInListener var1) { + var1.a(this); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketStatusListener.java b/azurite-server/src/main/java/net/minecraft/server/PacketStatusListener.java new file mode 100644 index 0000000..219428f --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketStatusListener.java @@ -0,0 +1,125 @@ +package net.minecraft.server; + +// CraftBukkit start + +import com.mojang.authlib.GameProfile; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.util.CraftIconCache; +import org.bukkit.entity.Player; +import org.bukkit.util.CachedServerIcon; +import org.jetbrains.annotations.NotNull; + +import java.net.InetSocketAddress; +import java.util.Iterator; +import java.util.NoSuchElementException; + +// CraftBukkit end + +public class PacketStatusListener implements PacketStatusInListener { + + private static final IChatBaseComponent a = new ChatComponentText("Status request has been handled."); + private final MinecraftServer minecraftServer; + private final NetworkManager networkManager; + private boolean d; + + public PacketStatusListener(MinecraftServer minecraftserver, NetworkManager networkmanager) { + this.minecraftServer = minecraftserver; + this.networkManager = networkmanager; + } + + public void a(IChatBaseComponent ichatbasecomponent) {} + + public void a(PacketStatusInStart packetstatusinstart) { + if (this.d) { + this.networkManager.close(PacketStatusListener.a); + // CraftBukkit start - fire ping event + return; + } + this.d = true; + final Object[] players = (this.minecraftServer.getPlayerList()).players.toArray(); + class ServerListPingEvent extends org.bukkit.event.server.ServerListPingEvent { + CraftIconCache icon = PacketStatusListener.this.minecraftServer.server.getServerIcon(); + + ServerListPingEvent() { + super(((InetSocketAddress)PacketStatusListener.this.networkManager.getSocketAddress()).getAddress(), PacketStatusListener.this.minecraftServer.getMotd(), PacketStatusListener.this.minecraftServer.getPlayerList().getMaxPlayers()); + } + + public void setServerIcon(CachedServerIcon icon) { + if (!(icon instanceof CraftIconCache)) + throw new IllegalArgumentException(icon + " was not created by " + CraftServer.class); + this.icon = (CraftIconCache)icon; + } + + public @NotNull Iterator iterator() throws UnsupportedOperationException { + return new Iterator() { + int i; + + int ret = Integer.MIN_VALUE; + + EntityPlayer player; + + public boolean hasNext() { + if (this.player != null) + return true; + for (int length = players.length, i = this.i; i < length; i++) { + EntityPlayer player = (EntityPlayer) players[i]; + if (player != null) { + this.i = i + 1; + this.player = player; + return true; + } + } + return false; + } + + public Player next() { + if (!hasNext()) + throw new NoSuchElementException(); + EntityPlayer player = this.player; + this.player = null; + this.ret = this.i - 1; + return player.getBukkitEntity(); + } + + public void remove() { + int i = this.ret; + if (i < 0 || players[i] == null) + throw new IllegalStateException(); + players[i] = null; + } + }; + } + } + ServerListPingEvent event = new ServerListPingEvent(); + this.minecraftServer.server.getPluginManager().callEvent(event); + java.util.List profiles = new java.util.ArrayList<>(players.length); + for (Object player : players) { + if (player != null) + profiles.add(((EntityPlayer)player).getProfile()); + } + + ServerPing.ServerPingPlayerSample playerSample = new ServerPing.ServerPingPlayerSample(event.getMaxPlayers(), profiles.size()); + // Spigot Start + if ( !profiles.isEmpty() ) + { + java.util.Collections.shuffle( profiles ); // This sucks, its inefficient but we have no simple way of doing it differently + profiles = profiles.subList( 0, Math.min( profiles.size(), org.spigotmc.SpigotConfig.playerSample ) ); // Cap the sample to n (or less) displayed players, ie: Vanilla behaviour + } + // Spigot End + playerSample.a(profiles.toArray(new GameProfile[0])); + + ServerPing ping = new ServerPing(); + ping.setFavicon(event.icon.value); + ping.setMOTD(new ChatComponentText(event.getMotd())); + ping.setPlayerSample(playerSample); + ping.setServerInfo(new ServerPing.ServerData(minecraftServer.getServerModName() + " " + minecraftServer.getVersion(), 47)); // TODO: Update when protocol changes + + this.networkManager.handle(new PacketStatusOutServerInfo(ping)); + // CraftBukkit end + } + + public void a(PacketStatusInPing packetstatusinping) { + this.networkManager.handle(new PacketStatusOutPong(packetstatusinping.a())); + this.networkManager.close(PacketStatusListener.a); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketStatusOutListener.java b/azurite-server/src/main/java/net/minecraft/server/PacketStatusOutListener.java new file mode 100644 index 0000000..12d7a72 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketStatusOutListener.java @@ -0,0 +1,8 @@ +package net.minecraft.server; + +public interface PacketStatusOutListener extends PacketListener { + + void a(PacketStatusOutServerInfo packetstatusoutserverinfo); + + void a(PacketStatusOutPong packetstatusoutpong); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketStatusOutPong.java b/azurite-server/src/main/java/net/minecraft/server/PacketStatusOutPong.java new file mode 100644 index 0000000..1076860 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketStatusOutPong.java @@ -0,0 +1,36 @@ +package net.minecraft.server; + +import java.io.IOException; + +public class PacketStatusOutPong implements Packet { + public long a; + + public PacketStatusOutPong() { + } + + public PacketStatusOutPong(long var1) { + this.a = var1; + } + + public void a(PacketDataSerializer var1) throws IOException { + this.a = var1.readLong(); + } + + public void b(PacketDataSerializer var1) throws IOException { + var1.writeLong(this.a); + } + + @Override + public int getSize() { + return 8; + } + + @Override + public int getId() { + return 0x01; + } + + public void a(PacketStatusOutListener var1) { + var1.a(this); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PacketStatusOutServerInfo.java b/azurite-server/src/main/java/net/minecraft/server/PacketStatusOutServerInfo.java new file mode 100644 index 0000000..5953841 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PacketStatusOutServerInfo.java @@ -0,0 +1,61 @@ +package net.minecraft.server; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import dev.azurite.spigot.optimizations.ProtocolUtils; + +import java.io.IOException; + +public class PacketStatusOutServerInfo implements Packet { + private static final Gson a = (new GsonBuilder()) + .registerTypeAdapter(ServerPing.ServerData.class, new ServerPing.ServerData.ServerData$Serializer()) + .registerTypeAdapter(ServerPing.ServerPingPlayerSample.class, new ServerPing.ServerPingPlayerSample.ServerPingPlayerSample$Serializer()) + .registerTypeAdapter(ServerPing.class, new ServerPing.Serializer()) + .registerTypeHierarchyAdapter(IChatBaseComponent.class, new IChatBaseComponent.ChatSerializer()) + .registerTypeHierarchyAdapter(ChatModifier.class, new ChatModifier.ChatModifierSerializer()) + .registerTypeAdapterFactory(new ChatTypeAdapterFactory()).create(); + public ServerPing b; + public String serializedJson; + + public PacketStatusOutServerInfo() { + } + + public PacketStatusOutServerInfo(ServerPing var1) { + this.b = var1; + this.serializeJson(); + } + + public void a(PacketDataSerializer var1) throws IOException { + this.b = a.fromJson(var1.c(32767), ServerPing.class); + } + + public void b(PacketDataSerializer var1) throws IOException { + if (this.serializedJson != null) { + var1.a(this.serializedJson); + } else { + var1.a(a.toJson(this.b)); + } + } + + private void serializeJson() { + this.serializedJson = a.toJson(this.b); + } + + @Override + public int getSize() { + if (this.serializedJson != null) { + return ProtocolUtils.getStringSize(this.serializedJson); + } else { + return ProtocolUtils.getStringSize(a.toJson(this.b)); + } + } + + @Override + public int getId() { + return 0x00; + } + + public void a(PacketStatusOutListener var1) { + var1.a(this); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/Path.java b/azurite-server/src/main/java/net/minecraft/server/Path.java new file mode 100644 index 0000000..c976c98 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/Path.java @@ -0,0 +1,129 @@ +package net.minecraft.server; + +public class Path { + + private PathPoint[] a = new PathPoint[128]; // CraftBukkit - reduce default size + private int b; + + public Path() {} + + public PathPoint a(PathPoint pathpoint) { + if (pathpoint.d >= 0) { + throw new IllegalStateException("OW KNOWS!"); + } else { + if (this.b == this.a.length) { + PathPoint[] apathpoint = new PathPoint[this.b << 1]; + + System.arraycopy(this.a, 0, apathpoint, 0, this.b); + this.a = apathpoint; + } + + this.a[this.b] = pathpoint; + pathpoint.d = this.b; + this.a(this.b++); + return pathpoint; + } + } + + public void a() { + this.b = 0; + } + + public PathPoint c() { + PathPoint pathpoint = this.a[0]; + + this.a[0] = this.a[--this.b]; + this.a[this.b] = null; + if (this.b > 0) { + this.b(0); + } + + pathpoint.d = -1; + return pathpoint; + } + + public void a(PathPoint pathpoint, float f) { + float f1 = pathpoint.g; + + pathpoint.g = f; + if (f < f1) { + this.a(pathpoint.d); + } else { + this.b(pathpoint.d); + } + + } + + private void a(int i) { + PathPoint pathpoint = this.a[i]; + + int j; + + for (float f = pathpoint.g; i > 0; i = j) { + j = i - 1 >> 1; + PathPoint pathpoint1 = this.a[j]; + + if (f >= pathpoint1.g) { + break; + } + + this.a[i] = pathpoint1; + pathpoint1.d = i; + } + + this.a[i] = pathpoint; + pathpoint.d = i; + } + + private void b(int i) { + PathPoint pathpoint = this.a[i]; + float f = pathpoint.g; + + while (true) { + int j = 1 + (i << 1); + int k = j + 1; + + if (j >= this.b) { + break; + } + + PathPoint pathpoint1 = this.a[j]; + float f1 = pathpoint1.g; + PathPoint pathpoint2; + float f2; + + if (k >= this.b) { + pathpoint2 = null; + f2 = Float.POSITIVE_INFINITY; + } else { + pathpoint2 = this.a[k]; + f2 = pathpoint2.g; + } + + if (f1 < f2) { + if (f1 >= f) { + break; + } + + this.a[i] = pathpoint1; + pathpoint1.d = i; + i = j; + } else { + if (f2 >= f) { + break; + } + + this.a[i] = pathpoint2; + pathpoint2.d = i; + i = k; + } + } + + this.a[i] = pathpoint; + pathpoint.d = i; + } + + public boolean e() { + return this.b == 0; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathEntity.java b/azurite-server/src/main/java/net/minecraft/server/PathEntity.java new file mode 100644 index 0000000..92be678 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathEntity.java @@ -0,0 +1,79 @@ +package net.minecraft.server; + +public class PathEntity { + + private final PathPoint[] a; + private int b; + private int c; + + public PathEntity(PathPoint[] apathpoint) { + this.a = apathpoint; + this.c = apathpoint.length; + } + + public void a() { + ++this.b; + } + + public boolean b() { + return this.b >= this.c; + } + + public PathPoint c() { + return this.c > 0 ? this.a[this.c - 1] : null; + } + + public PathPoint a(int i) { + return this.a[i]; + } + + public int d() { + return this.c; + } + + public void b(int i) { + this.c = i; + } + + public int e() { + return this.b; + } + + public void c(int i) { + this.b = i; + } + + public Vec3D a(Entity entity, int i) { + double d0 = (double) this.a[i].a + (double) ((int) (entity.width + 1.0F)) * 0.5D; + double d1 = (double) this.a[i].b; + double d2 = (double) this.a[i].c + (double) ((int) (entity.width + 1.0F)) * 0.5D; + + return new Vec3D(d0, d1, d2); + } + + public Vec3D a(Entity entity) { + return this.a(entity, this.b); + } + + public boolean a(PathEntity pathentity) { + if (pathentity == null) { + return false; + } else if (pathentity.a.length != this.a.length) { + return false; + } else { + for (int i = 0; i < this.a.length; ++i) { + if (this.a[i].a != pathentity.a[i].a || this.a[i].b != pathentity.a[i].b || this.a[i].c != pathentity.a[i].c) { + return false; + } + } + + return true; + } + } + + public boolean b(Vec3D vec3d) { + PathPoint pathpoint = this.c(); + + return pathpoint != null && pathpoint.a == (int) vec3d.a && pathpoint.c == (int) vec3d.c; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathPoint.java b/azurite-server/src/main/java/net/minecraft/server/PathPoint.java new file mode 100644 index 0000000..4d48e88 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathPoint.java @@ -0,0 +1,64 @@ +package net.minecraft.server; + +public class PathPoint { + + public final int a; + public final int b; + public final int c; + private final int j; + int d = -1; + float e; + float f; + float g; + PathPoint h; + public boolean i; + + public PathPoint(int i, int j, int k) { + this.a = i; + this.b = j; + this.c = k; + this.j = a(i, j, k); + } + + public static int a(int i, int j, int k) { + return j & 255 | (i & 32767) << 8 | (k & 32767) << 24 | (i < 0 ? Integer.MIN_VALUE : 0) | (k < 0 ? '\u8000' : 0); + } + + public float a(PathPoint pathpoint) { + float f = (float) (pathpoint.a - this.a); + float f1 = (float) (pathpoint.b - this.b); + float f2 = (float) (pathpoint.c - this.c); + + return MathHelper.c(f * f + f1 * f1 + f2 * f2); + } + + public float b(PathPoint pathpoint) { + float f = (float) (pathpoint.a - this.a); + float f1 = (float) (pathpoint.b - this.b); + float f2 = (float) (pathpoint.c - this.c); + + return f * f + f1 * f1 + f2 * f2; + } + + public boolean equals(Object object) { + if (!(object instanceof PathPoint)) { + return false; + } else { + PathPoint pathpoint = (PathPoint) object; + + return this.j == pathpoint.j && this.a == pathpoint.a && this.b == pathpoint.b && this.c == pathpoint.c; + } + } + + public int hashCode() { + return this.j; + } + + public boolean a() { + return this.d >= 0; + } + + public String toString() { + return this.a + ", " + this.b + ", " + this.c; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/Pathfinder.java b/azurite-server/src/main/java/net/minecraft/server/Pathfinder.java new file mode 100644 index 0000000..2b27ba0 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/Pathfinder.java @@ -0,0 +1,100 @@ +package net.minecraft.server; + +public class Pathfinder { + + private final Path a = new Path(); + private final PathPoint[] b = new PathPoint[32]; + private final PathfinderAbstract c; + + public Pathfinder(PathfinderAbstract pathfinderabstract) { + this.c = pathfinderabstract; + } + + public PathEntity a(IBlockAccess iblockaccess, Entity entity, Entity entity1, float f) { + return this.a(iblockaccess, entity, entity1.locX, entity1.getBoundingBox().b, entity1.locZ, f); + } + + public PathEntity a(IBlockAccess iblockaccess, Entity entity, BlockPosition blockposition, float f) { + return this.a(iblockaccess, entity, (float) blockposition.getX() + 0.5F, (float) blockposition.getY() + 0.5F, (float) blockposition.getZ() + 0.5F, f); + } + + private PathEntity a(IBlockAccess iblockaccess, Entity entity, double d0, double d1, double d2, float f) { + this.a.a(); + this.c.a(iblockaccess, entity); + PathPoint pathpoint = this.c.a(entity); + PathPoint pathpoint1 = this.c.a(entity, d0, d1, d2); + PathEntity pathentity = this.a(entity, pathpoint, pathpoint1, f); + + this.c.a(); + return pathentity; + } + + private PathEntity a(Entity entity, PathPoint pathpoint, PathPoint pathpoint1, float f) { + pathpoint.e = 0.0F; + pathpoint.f = pathpoint.b(pathpoint1); + pathpoint.g = pathpoint.f; + this.a.a(); + this.a.a(pathpoint); + PathPoint pathpoint2 = pathpoint; + + while (!this.a.e()) { + PathPoint pathpoint3 = this.a.c(); + + if (pathpoint3.equals(pathpoint1)) { + return this.a(pathpoint, pathpoint1); + } + + if (pathpoint3.b(pathpoint1) < pathpoint2.b(pathpoint1)) { + pathpoint2 = pathpoint3; + } + + pathpoint3.i = true; + int i = this.c.a(this.b, entity, pathpoint3, pathpoint1, f); + + for (int j = 0; j < i; ++j) { + PathPoint pathpoint4 = this.b[j]; + float f1 = pathpoint3.e + pathpoint3.b(pathpoint4); + + if (f1 < f * 2.0F && (!pathpoint4.a() || f1 < pathpoint4.e)) { + pathpoint4.h = pathpoint3; + pathpoint4.e = f1; + pathpoint4.f = pathpoint4.b(pathpoint1); + if (pathpoint4.a()) { + this.a.a(pathpoint4, pathpoint4.e + pathpoint4.f); + } else { + pathpoint4.g = pathpoint4.e + pathpoint4.f; + this.a.a(pathpoint4); + } + } + } + } + + if (pathpoint2 == pathpoint) { + return null; + } else { + return this.a(pathpoint, pathpoint2); + } + } + + private PathEntity a(PathPoint pathpoint, PathPoint pathpoint1) { + int i = 1; + + PathPoint pathpoint2; + + for (pathpoint2 = pathpoint1; pathpoint2.h != null; pathpoint2 = pathpoint2.h) { + ++i; + } + + PathPoint[] apathpoint = new PathPoint[i]; + + pathpoint2 = pathpoint1; + --i; + + for (apathpoint[i] = pathpoint1; pathpoint2.h != null; apathpoint[i] = pathpoint2) { + pathpoint2 = pathpoint2.h; + --i; + } + + return new PathEntity(apathpoint); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderAbstract.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderAbstract.java new file mode 100644 index 0000000..c2f6e04 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderAbstract.java @@ -0,0 +1,42 @@ +package net.minecraft.server; + +public abstract class PathfinderAbstract { + + protected IBlockAccess a; + protected IntHashMap b = new IntHashMap<>(); + protected int c; + protected int d; + protected int e; + + public PathfinderAbstract() { + } + + public void a(IBlockAccess iblockaccess, Entity entity) { + this.a = iblockaccess; + this.b.c(); + this.c = MathHelper.d(entity.width + 1.0F); + this.d = MathHelper.d(entity.length + 1.0F); + this.e = MathHelper.d(entity.width + 1.0F); + } + + public void a() { + } + + protected PathPoint a(int i, int j, int k) { + int l = PathPoint.a(i, j, k); + PathPoint pathpoint = this.b.get(l); + + if (pathpoint == null) { + pathpoint = new PathPoint(i, j, k); + this.b.a(l, pathpoint); + } + + return pathpoint; + } + + public abstract PathPoint a(Entity entity); + + public abstract PathPoint a(Entity entity, double d0, double d1, double d2); + + public abstract int a(PathPoint[] apathpoint, Entity entity, PathPoint pathpoint, PathPoint pathpoint1, float f); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoal.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoal.java new file mode 100644 index 0000000..ed81b3a --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoal.java @@ -0,0 +1,36 @@ +package net.minecraft.server; + +public abstract class PathfinderGoal { + + private int a; + + public PathfinderGoal() { + } + + public abstract boolean a(); + + public boolean b() { + return this.a(); + } + + public boolean i() { + return true; + } + + public void c() { + } + + public void d() { + } + + public void e() { + } + + public void a(int i) { + this.a = i; + } + + public int j() { + return this.a; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalArrowAttack.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalArrowAttack.java new file mode 100644 index 0000000..390d758 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalArrowAttack.java @@ -0,0 +1,92 @@ +package net.minecraft.server; + +public class PathfinderGoalArrowAttack extends PathfinderGoal { + + private final EntityInsentient a; + private final IRangedEntity b; + private EntityLiving c; + private int d; + private final double e; + private int f; + private final int g; + private final int h; + private final float i; + private final float j; + + public PathfinderGoalArrowAttack(IRangedEntity irangedentity, double d0, int i, float f) { + this(irangedentity, d0, i, i, f); + } + + public PathfinderGoalArrowAttack(IRangedEntity irangedentity, double d0, int i, int j, float f) { + this.d = -1; + if (!(irangedentity instanceof EntityLiving)) { + throw new IllegalArgumentException("ArrowAttackGoal requires Mob implements RangedAttackMob"); + } else { + this.b = irangedentity; + this.a = (EntityInsentient) irangedentity; + this.e = d0; + this.g = i; + this.h = j; + this.i = f; + this.j = f * f; + this.a(3); + } + } + + public boolean a() { + EntityLiving entityliving = this.a.getGoalTarget(); + + if (entityliving == null) { + return false; + } else { + this.c = entityliving; + return true; + } + } + + public boolean b() { + return this.a() || !this.a.getNavigation().m(); + } + + public void d() { + this.c = null; + this.f = 0; + this.d = -1; + } + + public void e() { + double d0 = this.a.e(this.c.locX, this.c.getBoundingBox().b, this.c.locZ); + boolean flag = this.a.getEntitySenses().a(this.c); + + if (flag) { + ++this.f; + } else { + this.f = 0; + } + + if (d0 <= (double) this.j && this.f >= 20) { + this.a.getNavigation().n(); + } else { + this.a.getNavigation().a(this.c, this.e); + } + + this.a.getControllerLook().a(this.c, 30.0F, 30.0F); + float f; + + if (--this.d == 0) { + if (d0 > (double) this.j || !flag) { + return; + } + + f = MathHelper.sqrt(d0) / this.i; + float f1 = MathHelper.a(f, 0.1F, 1.0F); + + this.b.a(this.c, f1); + this.d = MathHelper.d(f * (float) (this.h - this.g) + (float) this.g); + } else if (this.d < 0) { + f = MathHelper.sqrt(d0) / this.i; + this.d = MathHelper.d(f * (float) (this.h - this.g) + (float) this.g); + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalAvoidTarget.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalAvoidTarget.java new file mode 100644 index 0000000..6602553 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalAvoidTarget.java @@ -0,0 +1,85 @@ +package net.minecraft.server; + +import com.google.common.base.Predicate; +import com.google.common.base.Predicates; +import dev.azurite.spigot.pathsearch.PositionPathSearchType; + +import java.util.List; + +public class PathfinderGoalAvoidTarget extends PathfinderGoal { + + private final Predicate c; + protected EntityCreature a; + private final double d; + private final double e; + protected T b; + private final float f; + private PathEntity g; + private final NavigationAbstract h; + private final Class i; + private final Predicate j; + + public PathfinderGoalAvoidTarget(EntityCreature entitycreature, Class oclass, float f, double d0, double d1) { + this(entitycreature, oclass, Predicates.alwaysTrue(), f, d0, d1); + } + + public PathfinderGoalAvoidTarget(EntityCreature entitycreature, Class oclass, Predicate predicate, float f, double d0, double d1) { + this.c = new Predicate() { + public boolean a(Entity entity) { + return entity.isAlive() && PathfinderGoalAvoidTarget.this.a.getEntitySenses().a(entity); + } + + public boolean apply(Entity object) { + return this.a(object); + } + }; + this.a = entitycreature; + this.i = oclass; + this.j = predicate; + this.f = f; + this.d = d0; + this.e = d1; + this.h = entitycreature.getNavigation(); + this.a(1); + } + + public boolean a() { + List list = this.a.world.a(this.i, this.a.getBoundingBox().grow(this.f, 3.0D, this.f), Predicates.and(new Predicate[]{IEntitySelector.d, this.c, this.j})); + + if (list.isEmpty()) { + return false; + } else { + this.b = (T) list.get(0); + Vec3D vec3d = RandomPositionGenerator.b(this.a, 16, 7, new Vec3D(this.b.locX, this.b.locY, this.b.locZ)); + + if (vec3d == null) { + return false; + } else if (this.b.e(vec3d.a, vec3d.b, vec3d.c) < this.b.h(this.a)) { + return false; + } else { + this.g = this.h.a(vec3d.a, vec3d.b, vec3d.c, PositionPathSearchType.AVOIDTARGET); // Migot + return this.g != null && this.g.b(vec3d); + } + } + } + + public boolean b() { + return !this.h.m(); + } + + public void c() { + this.h.a(this.g, this.d); + } + + public void d() { + this.b = null; + } + + public void e() { + if (this.a.h(this.b) < 49.0D) { + this.a.getNavigation().a(this.e); + } else { + this.a.getNavigation().a(this.d); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalBeg.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalBeg.java new file mode 100644 index 0000000..7f100e2 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalBeg.java @@ -0,0 +1,47 @@ +package net.minecraft.server; + +public class PathfinderGoalBeg extends PathfinderGoal { + + private final EntityWolf a; + private EntityHuman b; + private final World c; + private final float d; + private int e; + + public PathfinderGoalBeg(EntityWolf entitywolf, float f) { + this.a = entitywolf; + this.c = entitywolf.world; + this.d = f; + this.a(2); + } + + public boolean a() { + this.b = this.c.findNearbyPlayer(this.a, this.d); + return this.b != null && this.a(this.b); + } + + public boolean b() { + return this.b.isAlive() && (!(this.a.h(this.b) > (double) (this.d * this.d)) && this.e > 0 && this.a(this.b)); + } + + public void c() { + this.a.p(true); + this.e = 40 + this.a.bc().nextInt(40); + } + + public void d() { + this.a.p(false); + this.b = null; + } + + public void e() { + this.a.getControllerLook().a(this.b.locX, this.b.locY + (double) this.b.getHeadHeight(), this.b.locZ, 10.0F, (float) this.a.bQ()); + --this.e; + } + + private boolean a(EntityHuman entityhuman) { + ItemStack itemstack = entityhuman.inventory.getItemInHand(); + + return itemstack != null && (!this.a.isTamed() && itemstack.getItem() == Items.BONE || this.a.d(itemstack)); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalBreakDoor.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalBreakDoor.java new file mode 100644 index 0000000..7f82808 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalBreakDoor.java @@ -0,0 +1,69 @@ +package net.minecraft.server; + +public class PathfinderGoalBreakDoor extends PathfinderGoalDoorInteract { + + private int g; + private int h = -1; + + public PathfinderGoalBreakDoor(EntityInsentient entityinsentient) { + super(entityinsentient); + } + + public boolean a() { + if (!super.a()) { + return false; + } else if (!this.a.world.getGameRules().getBoolean("mobGriefing")) { + return false; + } else { + return !BlockDoor.f(this.a.world, this.b); + } + } + + public void c() { + super.c(); + this.g = 0; + } + + public boolean b() { + double d0 = this.a.b(this.b); + + if (this.g <= 240) { + return !BlockDoor.f(this.a.world, this.b) && d0 < 4.0D; + } + + return false; + } + + public void d() { + super.d(); + this.a.world.c(this.a.getId(), this.b, -1); + } + + public void e() { + super.e(); + if (this.a.bc().nextInt(20) == 0) { + this.a.world.triggerEffect(1010, this.b, 0); + } + + ++this.g; + int i = (int) ((float) this.g / 240.0F * 10.0F); + + if (i != this.h) { + this.a.world.c(this.a.getId(), this.b, i); + this.h = i; + } + + if (this.g == 240 && this.a.world.getDifficulty() == EnumDifficulty.HARD) { + // CraftBukkit start + if (org.bukkit.craftbukkit.event.CraftEventFactory.callEntityBreakDoorEvent(this.a, this.b.getX(), this.b.getY(), this.b.getZ()).isCancelled()) { + this.c(); + return; + } + // CraftBukkit end + this.a.world.setAir(this.b); + this.a.world.triggerEffect(1012, this.b, 0); + this.a.world.triggerEffect(2001, this.b, Block.getId(this.c)); + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalBreed.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalBreed.java new file mode 100644 index 0000000..07bb3fc --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalBreed.java @@ -0,0 +1,113 @@ +package net.minecraft.server; + +import java.util.List; +import java.util.Random; + +public class PathfinderGoalBreed extends PathfinderGoal { + + private final EntityAnimal d; + World a; + private EntityAnimal e; + int b; + double c; + + public PathfinderGoalBreed(EntityAnimal entityanimal, double d0) { + this.d = entityanimal; + this.a = entityanimal.world; + this.c = d0; + this.a(3); + } + + public boolean a() { + if (!this.d.isInLove()) { + return false; + } else { + this.e = this.f(); + return this.e != null; + } + } + + public boolean b() { + return this.e.isAlive() && this.e.isInLove() && this.b < 60; + } + + public void d() { + this.e = null; + this.b = 0; + } + + public void e() { + this.d.getControllerLook().a(this.e, 10.0F, (float) this.d.bQ()); + this.d.getNavigation().a(this.e, this.c); + ++this.b; + if (this.b >= 60 && this.d.h(this.e) < 9.0D) { + this.g(); + } + + } + + private EntityAnimal f() { + float f = 8.0F; + List list = this.a.a(this.d.getClass(), this.d.getBoundingBox().grow(f, f, f)); + double d0 = Double.MAX_VALUE; + EntityAnimal entityanimal = null; + + for (EntityAnimal entityanimal1 : list) { + if (this.d.mate(entityanimal1) && this.d.h(entityanimal1) < d0) { + entityanimal = entityanimal1; + d0 = this.d.h(entityanimal1); + } + } + + return entityanimal; + } + + private void g() { + EntityAgeable entityageable = this.d.createChild(this.e); + + if (entityageable != null) { + // CraftBukkit start - set persistence for tame animals + if (entityageable instanceof EntityTameableAnimal && ((EntityTameableAnimal) entityageable).isTamed()) { + entityageable.persistent = true; + } + // CraftBukkit end + EntityHuman entityhuman = this.d.cq(); + + if (entityhuman == null && this.e.cq() != null) { + entityhuman = this.e.cq(); + } + + if (entityhuman != null) { + entityhuman.b(StatisticList.A); + if (this.d instanceof EntityCow) { + entityhuman.b(AchievementList.H); + } + } + + this.d.setAgeRaw(6000); + this.e.setAgeRaw(6000); + this.d.cs(); + this.e.cs(); + entityageable.setAgeRaw(-24000); + entityageable.setPositionRotation(this.d.locX, this.d.locY, this.d.locZ, 0.0F, 0.0F); + this.a.addEntity(entityageable, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.BREEDING); // CraftBukkit - added SpawnReason + Random random = this.d.bc(); + + for (int i = 0; i < 7; ++i) { + double d0 = random.nextGaussian() * 0.02D; + double d1 = random.nextGaussian() * 0.02D; + double d2 = random.nextGaussian() * 0.02D; + double d3 = random.nextDouble() * this.d.width * 2.0D - (double) this.d.width; + double d4 = 0.5D + random.nextDouble() * (double) this.d.length; + double d5 = random.nextDouble() * this.d.width * 2.0D - (double) this.d.width; + + this.a.addParticle(EnumParticle.HEART, this.d.locX + d3, this.d.locY + d4, this.d.locZ + d5, d0, d1, d2, EnumParticle.EMPTY_ARRAY); + } + + if (this.a.getGameRules().getBoolean("doMobLoot")) { + this.a.addEntity(new EntityExperienceOrb(this.a, this.d.locX, this.d.locY, this.d.locZ, random.nextInt(7) + 1)); + } + + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalDefendVillage.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalDefendVillage.java new file mode 100644 index 0000000..d5b8759 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalDefendVillage.java @@ -0,0 +1,40 @@ +package net.minecraft.server; + +public class PathfinderGoalDefendVillage extends PathfinderGoalTarget { + + EntityIronGolem a; + EntityLiving b; + + public PathfinderGoalDefendVillage(EntityIronGolem entityirongolem) { + super(entityirongolem, false, true); + this.a = entityirongolem; + this.a(1); + } + + public boolean a() { + Village village = this.a.n(); + + if (village == null) { + return false; + } else { + this.b = village.b(this.a); + if (this.b instanceof EntityCreeper) { + return false; + } else if (!this.a(this.b, false)) { + if (this.e.bc().nextInt(20) == 0) { + this.b = village.c(this.a); + return this.a(this.b, false); + } else { + return false; + } + } else { + return true; + } + } + } + + public void c() { + this.a.setGoalTarget(this.b, org.bukkit.event.entity.EntityTargetEvent.TargetReason.DEFEND_VILLAGE, true); // CraftBukkit - reason + super.c(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalDoorInteract.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalDoorInteract.java new file mode 100644 index 0000000..05925c5 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalDoorInteract.java @@ -0,0 +1,75 @@ +package net.minecraft.server; + +public abstract class PathfinderGoalDoorInteract extends PathfinderGoal { + + protected EntityInsentient a; + protected BlockPosition b; + protected BlockDoor c; + boolean d; + float e; + float f; + + public PathfinderGoalDoorInteract(EntityInsentient entityinsentient) { + this.b = BlockPosition.ZERO; + this.a = entityinsentient; + if (!(entityinsentient.getNavigation() instanceof Navigation)) { + throw new IllegalArgumentException("Unsupported mob type for DoorInteractGoal"); + } + } + + public boolean a() { + if (!this.a.positionChanged) { + return false; + } else { + Navigation navigation = (Navigation) this.a.getNavigation(); + PathEntity pathentity = navigation.j(); + + if (pathentity != null && !pathentity.b() && navigation.g()) { + for (int i = 0; i < Math.min(pathentity.e() + 2, pathentity.d()); ++i) { + PathPoint pathpoint = pathentity.a(i); + + this.b = new BlockPosition(pathpoint.a, pathpoint.b + 1, pathpoint.c); + if (this.a.e(this.b.getX(), this.a.locY, this.b.getZ()) <= 2.25D) { + this.c = this.a(this.b); + if (this.c != null) { + return true; + } + } + } + + this.b = (new BlockPosition(this.a)).up(); + this.c = this.a(this.b); + return this.c != null; + } else { + return false; + } + } + } + + public boolean b() { + return !this.d; + } + + public void c() { + this.d = false; + this.e = (float) ((double) ((float) this.b.getX() + 0.5F) - this.a.locX); + this.f = (float) ((double) ((float) this.b.getZ() + 0.5F) - this.a.locZ); + } + + public void e() { + float f = (float) ((double) ((float) this.b.getX() + 0.5F) - this.a.locX); + float f1 = (float) ((double) ((float) this.b.getZ() + 0.5F) - this.a.locZ); + float f2 = this.e * f + this.f * f1; + + if (f2 < 0.0F) { + this.d = true; + } + + } + + private BlockDoor a(BlockPosition blockposition) { + Block block = this.a.world.getType(blockposition).getBlock(); + + return block instanceof BlockDoor && block.getMaterial() == Material.WOOD ? (BlockDoor) block : null; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalEatTile.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalEatTile.java new file mode 100644 index 0000000..ebc0b9b --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalEatTile.java @@ -0,0 +1,79 @@ +package net.minecraft.server; + +import com.google.common.base.Predicate; +import org.bukkit.Material; +import org.bukkit.craftbukkit.event.CraftEventFactory; + +import java.util.Objects; +// CraftBukkit end + +public class PathfinderGoalEatTile extends PathfinderGoal { + + private static final Predicate b = BlockStatePredicate.a(Blocks.TALLGRASS).a(BlockLongGrass.TYPE, enumTallGrassType -> Objects.equals(enumTallGrassType, BlockLongGrass.EnumTallGrassType.GRASS)); + private final EntityInsentient c; + private final World d; + int a; + + public PathfinderGoalEatTile(EntityInsentient entityinsentient) { + this.c = entityinsentient; + this.d = entityinsentient.world; + this.a(7); + } + + public boolean a() { + if (this.c.bc().nextInt(this.c.isBaby() ? 50 : 1000) != 0) { + return false; + } else { + BlockPosition blockposition = new BlockPosition(this.c.locX, this.c.locY, this.c.locZ); + + return PathfinderGoalEatTile.b.apply(this.d.getType(blockposition)) || this.d.getType(blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()).getBlock() == Blocks.GRASS; + } + } + + public void c() { + this.a = 40; + this.d.broadcastEntityEffect(this.c, (byte) 10); + this.c.getNavigation().n(); + } + + public void d() { + this.a = 0; + } + + public boolean b() { + return this.a > 0; + } + + public int f() { + return this.a; + } + + public void e() { + this.a = Math.max(0, this.a - 1); + if (this.a == 4) { + BlockPosition blockposition = new BlockPosition(this.c.locX, this.c.locY, this.c.locZ); + + if (PathfinderGoalEatTile.b.apply(this.d.getType(blockposition))) { + // CraftBukkit + if (!CraftEventFactory.callEntityChangeBlockEvent(this.c, this.c.world.getWorld().getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()), Material.AIR, !this.d.getGameRules().getBoolean("mobGriefing")).isCancelled()) { + this.d.setAir(blockposition, false); + } + + this.c.v(); + } else { + BlockPosition blockposition1 = blockposition.down(); + + if (this.d.getType(blockposition1).getBlock() == Blocks.GRASS) { + // CraftBukkit + if (!CraftEventFactory.callEntityChangeBlockEvent(this.c, this.c.world.getWorld().getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()), Material.AIR, !this.d.getGameRules().getBoolean("mobGriefing")).isCancelled()) { + this.d.triggerEffect(2001, blockposition1, Block.getId(Blocks.GRASS)); + this.d.setTypeAndData(blockposition1, Blocks.DIRT.getBlockData(), 2); + } + + this.c.v(); + } + } + + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalFleeSun.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalFleeSun.java new file mode 100644 index 0000000..ac2f6ba --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalFleeSun.java @@ -0,0 +1,66 @@ +package net.minecraft.server; + +import dev.azurite.spigot.pathsearch.PositionPathSearchType; + +import java.util.Random; + +public class PathfinderGoalFleeSun extends PathfinderGoal { + + private final EntityCreature a; + private double b; + private double c; + private double d; + private final double e; + private final World f; + + public PathfinderGoalFleeSun(EntityCreature entitycreature, double d0) { + this.a = entitycreature; + this.e = d0; + this.f = entitycreature.world; + this.a(1); + } + + public boolean a() { + if (!this.f.w()) { + return false; + } else if (!this.a.isBurning()) { + return false; + } else if (!this.f.i(new BlockPosition(this.a.locX, this.a.getBoundingBox().b, this.a.locZ))) { + return false; + } else { + Vec3D vec3d = this.f(); + + if (vec3d == null) { + return false; + } else { + this.b = vec3d.a; + this.c = vec3d.b; + this.d = vec3d.c; + return true; + } + } + } + + public boolean b() { + return !this.a.getNavigation().m(); + } + + public void c() { + this.a.getNavigation().a(this.b, this.c, this.d, this.e, PositionPathSearchType.FLEESUN); // Migot + } + + private Vec3D f() { + Random random = this.a.bc(); + BlockPosition blockposition = new BlockPosition(this.a.locX, this.a.getBoundingBox().b, this.a.locZ); + + for (int i = 0; i < 10; ++i) { + BlockPosition blockposition1 = blockposition.a(random.nextInt(20) - 10, random.nextInt(6) - 3, random.nextInt(20) - 10); + + if (!this.f.i(blockposition1) && this.a.a(blockposition1) < 0.0F) { + return new Vec3D(blockposition1.getX(), blockposition1.getY(), blockposition1.getZ()); + } + } + + return null; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalFloat.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalFloat.java new file mode 100644 index 0000000..2fe4e61 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalFloat.java @@ -0,0 +1,24 @@ +package net.minecraft.server; + +public class PathfinderGoalFloat extends PathfinderGoal { + + private final EntityInsentient a; + + public PathfinderGoalFloat(EntityInsentient entityinsentient) { + this.a = entityinsentient; + entityinsentient.goalFloat = this; // PaperSpigot + this.a(4); + ((Navigation) entityinsentient.getNavigation()).d(true); + } + + public boolean a() { + return this.a.V() || this.a.ab(); + } + + public void e() { + if (this.a.bc().nextFloat() < 0.8F) { + this.a.getControllerJump().a(); + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalFollowOwner.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalFollowOwner.java new file mode 100644 index 0000000..4370416 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalFollowOwner.java @@ -0,0 +1,94 @@ +package net.minecraft.server; + +public class PathfinderGoalFollowOwner extends PathfinderGoal { + + private final EntityTameableAnimal d; + private EntityLiving e; + World a; + private final double f; + private final NavigationAbstract g; + private int h; + float b; + float c; + + public PathfinderGoalFollowOwner(EntityTameableAnimal entitytameableanimal, double d0, float f, float f1) { + this.d = entitytameableanimal; + this.a = entitytameableanimal.world; + this.f = d0; + this.g = entitytameableanimal.getNavigation(); + this.c = f; + this.b = f1; + this.a(3); + if (!(entitytameableanimal.getNavigation() instanceof Navigation)) { + throw new IllegalArgumentException("Unsupported mob type for FollowOwnerGoal"); + } + } + + public boolean a() { + EntityLiving entityliving = this.d.getOwner(); + + if (entityliving == null) { + return false; + } else if (entityliving instanceof EntityHuman && ((EntityHuman) entityliving).isSpectator()) { + return false; + } else if (this.d.isSitting()) { + return false; + } else if (this.d.h(entityliving) < (double) (this.c * this.c)) { + return false; + } else { + this.e = entityliving; + return true; + } + } + + public boolean b() { + return !this.g.m() && this.d.h(this.e) > (double) (this.b * this.b) && !this.d.isSitting(); + } + + public void c() { + this.h = 0; + ((Navigation) this.d.getNavigation()).a(false); + } + + public void d() { + this.e = null; + this.g.n(); + ((Navigation) this.d.getNavigation()).a(true); + } + + private boolean a(BlockPosition blockposition) { + IBlockData iblockdata = this.a.getType(blockposition); + Block block = iblockdata.getBlock(); + + return block == Blocks.AIR || !block.d(); + } + + public void e() { + this.d.getControllerLook().a(this.e, 10.0F, (float) this.d.bQ()); + if (!this.d.isSitting()) { + if (--this.h <= 0) { + this.h = 10; + if (!this.g.a(this.e, this.f)) { + if (!this.d.cc()) { + if (this.d.h(this.e) >= 144.0D) { + int i = MathHelper.floor(this.e.locX) - 2; + int j = MathHelper.floor(this.e.locZ) - 2; + int k = MathHelper.floor(this.e.getBoundingBox().b); + + for (int l = 0; l <= 4; ++l) { + for (int i1 = 0; i1 <= 4; ++i1) { + if ((l < 1 || i1 < 1 || l > 3 || i1 > 3) && World.a(this.a, new BlockPosition(i + l, k - 1, j + i1)) && this.a(new BlockPosition(i + l, k, j + i1)) && this.a(new BlockPosition(i + l, k + 1, j + i1))) { + this.d.setPositionRotation(((float) (i + l) + 0.5F), k, ((float) (j + i1) + 0.5F), this.d.yaw, this.d.pitch); + this.g.n(); + return; + } + } + } + + } + } + } + } + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalFollowParent.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalFollowParent.java new file mode 100644 index 0000000..7b4ed1e --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalFollowParent.java @@ -0,0 +1,73 @@ +package net.minecraft.server; + +import java.util.List; + +public class PathfinderGoalFollowParent extends PathfinderGoal { + + EntityAnimal a; + EntityAnimal b; + double c; + private int d; + + public PathfinderGoalFollowParent(EntityAnimal entityanimal, double d0) { + this.a = entityanimal; + this.c = d0; + } + + public boolean a() { + if (this.a.getAge() >= 0) { + return false; + } else { + List list = this.a.world.a(this.a.getClass(), this.a.getBoundingBox().grow(8.0D, 4.0D, 8.0D)); + EntityAnimal entityanimal = null; + double d0 = Double.MAX_VALUE; + + for (EntityAnimal entityanimal1 : list) { + if (entityanimal1.getAge() >= 0) { + double d1 = this.a.h(entityanimal1); + + if (d1 <= d0) { + d0 = d1; + entityanimal = entityanimal1; + } + } + } + + if (entityanimal == null) { + return false; + } else if (d0 < 9.0D) { + return false; + } else { + this.b = entityanimal; + return true; + } + } + } + + public boolean b() { + if (this.a.getAge() >= 0) { + return false; + } else if (!this.b.isAlive()) { + return false; + } else { + double d0 = this.a.h(this.b); + + return d0 >= 9.0D && d0 <= 256.0D; + } + } + + public void c() { + this.d = 0; + } + + public void d() { + this.b = null; + } + + public void e() { + if (--this.d <= 0) { + this.d = 10; + this.a.getNavigation().a(this.b, this.c); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalGotoTarget.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalGotoTarget.java new file mode 100644 index 0000000..08c4bfd --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalGotoTarget.java @@ -0,0 +1,83 @@ +package net.minecraft.server; + +import dev.azurite.spigot.pathsearch.PositionPathSearchType; + +public abstract class PathfinderGoalGotoTarget extends PathfinderGoal { + + private final EntityCreature c; + private final double d; + protected int a; + private int e; + private int f; + protected BlockPosition b; + private boolean g; + private final int h; + + public PathfinderGoalGotoTarget(EntityCreature entitycreature, double d0, int i) { + this.b = BlockPosition.ZERO; + this.c = entitycreature; + this.d = d0; + this.h = i; + this.a(5); + } + + public boolean a() { + if (this.a > 0) { + --this.a; + return false; + } else { + this.a = 200 + this.c.bc().nextInt(200); + return this.g(); + } + } + + public boolean b() { + return this.e >= -this.f && this.e <= 1200 && this.a(this.c.world, this.b); + } + + public void c() { + this.c.getNavigation().a((double) ((float) this.b.getX()) + 0.5D, this.b.getY() + 1, (double) ((float) this.b.getZ()) + 0.5D, this.d, PositionPathSearchType.GOTOTARGET); // Migot + this.e = 0; + this.f = this.c.bc().nextInt(this.c.bc().nextInt(1200) + 1200) + 1200; + } + + public void e() { + if (this.c.c(this.b.up()) > 1.0D) { + this.g = false; + ++this.e; + if (this.e % 40 == 0) { + this.c.getNavigation().a((double) ((float) this.b.getX()) + 0.5D, this.b.getY() + 1, (double) ((float) this.b.getZ()) + 0.5D, this.d, PositionPathSearchType.GOTOTARGET); // Migot + } + } else { + this.g = true; + --this.e; + } + } + + protected boolean f() { + return this.g; + } + + private boolean g() { + BlockPosition blockposition = new BlockPosition(this.c); + + for (int j = 0; j <= 1; j = j > 0 ? -j : 1 - j) { + for (int k = 0; k < this.h; ++k) { + for (int l = 0; l <= k; l = l > 0 ? -l : 1 - l) { + for (int i1 = l < k && l > -k ? k : 0; i1 <= k; i1 = i1 > 0 ? -i1 : 1 - i1) { + BlockPosition blockposition1 = blockposition.a(l, j - 1, i1); + + if (this.c.e(blockposition1) && this.a(this.c.world, blockposition1)) { + this.b = blockposition1; + return true; + } + } + } + } + } + + return false; + } + + protected abstract boolean a(World world, BlockPosition blockposition); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalHurtByTarget.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalHurtByTarget.java new file mode 100644 index 0000000..a0f4f72 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalHurtByTarget.java @@ -0,0 +1,55 @@ +package net.minecraft.server; + +import java.util.List; + +public class PathfinderGoalHurtByTarget extends PathfinderGoalTarget { + + private final boolean a; + private int b; + private final Class[] c; + + public PathfinderGoalHurtByTarget(EntityCreature entitycreature, boolean flag, Class... aclass) { + super(entitycreature, false); + this.a = flag; + this.c = aclass; + this.a(1); + } + + public boolean a() { + int i = this.e.be(); + + return i != this.b && this.a(this.e.getLastDamager(), false); + } + + public void c() { + this.e.setGoalTarget(this.e.getLastDamager(), org.bukkit.event.entity.EntityTargetEvent.TargetReason.TARGET_ATTACKED_ENTITY, true); // CraftBukkit - reason + this.b = this.e.be(); + if (this.a) { + double d0 = this.f(); + List list = this.e.world.a(this.e.getClass(), (new AxisAlignedBB(this.e.locX, this.e.locY, this.e.locZ, this.e.locX + 1.0D, this.e.locY + 1.0D, this.e.locZ + 1.0D)).grow(d0, 10.0D, d0)); + + for (EntityCreature entitycreature : list) { + if (this.e != entitycreature && entitycreature.getGoalTarget() == null && !entitycreature.c(this.e.getLastDamager())) { + boolean flag = false; + + for (Class oclass : c) { + if (entitycreature.getClass() == oclass) { + flag = true; + break; + } + } + + if (!flag) { + this.a(entitycreature, this.e.getLastDamager()); + } + } + } + } + + super.c(); + } + + protected void a(EntityCreature entitycreature, EntityLiving entityliving) { + entitycreature.setGoalTarget(entityliving, org.bukkit.event.entity.EntityTargetEvent.TargetReason.TARGET_ATTACKED_NEARBY_ENTITY, true); // CraftBukkit - reason + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalInteract.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalInteract.java new file mode 100644 index 0000000..154bcef --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalInteract.java @@ -0,0 +1,9 @@ +package net.minecraft.server; + +public class PathfinderGoalInteract extends PathfinderGoalLookAtPlayer { + + public PathfinderGoalInteract(EntityInsentient entityinsentient, Class oclass, float f, float f1) { + super(entityinsentient, oclass, f, f1); + this.a(3); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalInteractVillagers.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalInteractVillagers.java new file mode 100644 index 0000000..2ff47d2 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalInteractVillagers.java @@ -0,0 +1,74 @@ +package net.minecraft.server; + +public class PathfinderGoalInteractVillagers extends PathfinderGoalInteract { + + private int e; + private final EntityVillager f; + + public PathfinderGoalInteractVillagers(EntityVillager entityvillager) { + super(entityvillager, EntityVillager.class, 3.0F, 0.02F); + this.f = entityvillager; + } + + public void c() { + super.c(); + if (this.f.cs() && this.b instanceof EntityVillager && ((EntityVillager) this.b).ct()) { + this.e = 10; + } else { + this.e = 0; + } + + } + + public void e() { + super.e(); + if (this.e > 0) { + --this.e; + if (this.e == 0) { + InventorySubcontainer inventorysubcontainer = this.f.cq(); + + for (int i = 0; i < inventorysubcontainer.getSize(); ++i) { + ItemStack itemstack = inventorysubcontainer.getItem(i); + ItemStack itemstack1 = null; + + if (itemstack != null) { + Item item = itemstack.getItem(); + int j; + + if ((item == Items.BREAD || item == Items.POTATO || item == Items.CARROT) && itemstack.count > 3) { + j = itemstack.count / 2; + itemstack.count -= j; + itemstack1 = new ItemStack(item, j, itemstack.getData()); + } else if (item == Items.WHEAT && itemstack.count > 5) { + j = itemstack.count / 2 / 3 * 3; + int k = j / 3; + + itemstack.count -= j; + itemstack1 = new ItemStack(Items.BREAD, k, 0); + } + + if (itemstack.count <= 0) { + inventorysubcontainer.setItem(i, null); + } + } + + if (itemstack1 != null) { + double d0 = this.f.locY - 0.30000001192092896D + (double) this.f.getHeadHeight(); + EntityItem entityitem = new EntityItem(this.f.world, this.f.locX, d0, this.f.locZ, itemstack1); + float f = 0.3F; + float f1 = this.f.aK; + float f2 = this.f.pitch; + + entityitem.motX = -MathHelper.sin(f1 / 180.0F * 3.1415927F) * MathHelper.cos(f2 / 180.0F * 3.1415927F) * f; + entityitem.motZ = MathHelper.cos(f1 / 180.0F * 3.1415927F) * MathHelper.cos(f2 / 180.0F * 3.1415927F) * f; + entityitem.motY = -MathHelper.sin(f2 / 180.0F * 3.1415927F) * f + 0.1F; + entityitem.p(); + this.f.world.addEntity(entityitem); + break; + } + } + } + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalJumpOnBlock.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalJumpOnBlock.java new file mode 100644 index 0000000..45e1e3e --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalJumpOnBlock.java @@ -0,0 +1,61 @@ +package net.minecraft.server; + +public class PathfinderGoalJumpOnBlock extends PathfinderGoalGotoTarget { + + private final EntityOcelot c; + + public PathfinderGoalJumpOnBlock(EntityOcelot entityocelot, double d0) { + super(entityocelot, d0, 8); + this.c = entityocelot; + } + + public boolean a() { + return this.c.isTamed() && !this.c.isSitting() && super.a(); + } + + public boolean b() { + return super.b(); + } + + public void c() { + super.c(); + this.c.getGoalSit().setSitting(false); + } + + public void d() { + super.d(); + this.c.setSitting(false); + } + + public void e() { + super.e(); + this.c.getGoalSit().setSitting(false); + if (!this.f()) { + this.c.setSitting(false); + } else if (!this.c.isSitting()) { + this.c.setSitting(true); + } + + } + + protected boolean a(World world, BlockPosition blockposition) { + if (!world.isEmpty(blockposition.up())) { + return false; + } else { + IBlockData iblockdata = world.getType(blockposition); + Block block = iblockdata.getBlock(); + + if (block == Blocks.CHEST) { + TileEntity tileentity = world.getTileEntity(blockposition); + + return tileentity instanceof TileEntityChest && ((TileEntityChest) tileentity).l < 1; + } else { + if (block == Blocks.LIT_FURNACE) { + return true; + } + + return block == Blocks.BED && iblockdata.get(BlockBed.PART) != BlockBed.EnumBedPart.HEAD; + } + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalLeapAtTarget.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalLeapAtTarget.java new file mode 100644 index 0000000..7e843e3 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalLeapAtTarget.java @@ -0,0 +1,39 @@ +package net.minecraft.server; + +public class PathfinderGoalLeapAtTarget extends PathfinderGoal { + + EntityInsentient a; + EntityLiving b; + float c; + + public PathfinderGoalLeapAtTarget(EntityInsentient entityinsentient, float f) { + this.a = entityinsentient; + this.c = f; + this.a(5); + } + + public boolean a() { + this.b = this.a.getGoalTarget(); + if (this.b == null) { + return false; + } else { + double d0 = this.a.h(this.b); + + return d0 >= 4.0D && d0 <= 16.0D && (this.a.onGround && this.a.bc().nextInt(5) == 0); + } + } + + public boolean b() { + return !this.a.onGround; + } + + public void c() { + double d0 = this.b.locX - this.a.locX; + double d1 = this.b.locZ - this.a.locZ; + float f = MathHelper.sqrt(d0 * d0 + d1 * d1); + + this.a.motX += d0 / (double) f * 0.5D * 0.800000011920929D + this.a.motX * 0.20000000298023224D; + this.a.motZ += d1 / (double) f * 0.5D * 0.800000011920929D + this.a.motZ * 0.20000000298023224D; + this.a.motY = this.c; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalLookAtPlayer.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalLookAtPlayer.java new file mode 100644 index 0000000..28a4959 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalLookAtPlayer.java @@ -0,0 +1,62 @@ +package net.minecraft.server; + +public class PathfinderGoalLookAtPlayer extends PathfinderGoal { + + protected EntityInsentient a; + protected Entity b; + protected float c; + private int e; + private final float f; + protected Class d; + + public PathfinderGoalLookAtPlayer(EntityInsentient entityinsentient, Class oclass, float f) { + this.a = entityinsentient; + this.d = oclass; + this.c = f; + this.f = 0.02F; + this.a(2); + } + + public PathfinderGoalLookAtPlayer(EntityInsentient entityinsentient, Class oclass, float f, float f1) { + this.a = entityinsentient; + this.d = oclass; + this.c = f; + this.f = f1; + this.a(2); + } + + public boolean a() { + if (this.a.bc().nextFloat() >= this.f) { + return false; + } else { + if (this.a.getGoalTarget() != null) { + this.b = this.a.getGoalTarget(); + } + + if (this.d == EntityHuman.class) { + this.b = this.a.world.findNearbyPlayer(this.a, this.c); + } else { + this.b = this.a.world.a(this.d, this.a.getBoundingBox().grow(this.c, 3.0D, this.c), this.a); + } + + return this.b != null; + } + } + + public boolean b() { + return this.b.isAlive() && (!(this.a.h(this.b) > (double) (this.c * this.c)) && this.e > 0); + } + + public void c() { + this.e = 40 + this.a.bc().nextInt(40); + } + + public void d() { + this.b = null; + } + + public void e() { + this.a.getControllerLook().a(this.b.locX, this.b.locY + (double) this.b.getHeadHeight(), this.b.locZ, 10.0F, (float) this.a.bQ()); + --this.e; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalLookAtTradingPlayer.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalLookAtTradingPlayer.java new file mode 100644 index 0000000..2ff106c --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalLookAtTradingPlayer.java @@ -0,0 +1,20 @@ +package net.minecraft.server; + +public class PathfinderGoalLookAtTradingPlayer extends PathfinderGoalLookAtPlayer { + + private final EntityVillager e; + + public PathfinderGoalLookAtTradingPlayer(EntityVillager entityvillager) { + super(entityvillager, EntityHuman.class, 8.0F); + this.e = entityvillager; + } + + public boolean a() { + if (this.e.co()) { + this.b = this.e.v_(); + return true; + } else { + return false; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalMakeLove.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalMakeLove.java new file mode 100644 index 0000000..15787fb --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalMakeLove.java @@ -0,0 +1,93 @@ +package net.minecraft.server; + +public class PathfinderGoalMakeLove extends PathfinderGoal { + + private final EntityVillager b; + private EntityVillager c; + private final World d; + private int e; + Village a; + + public PathfinderGoalMakeLove(EntityVillager entityvillager) { + this.b = entityvillager; + this.d = entityvillager.world; + this.a(3); + } + + public boolean a() { + if (this.b.getAge() != 0) { + return false; + } else if (this.b.bc().nextInt(500) != 0) { + return false; + } else { + this.a = this.d.ae().getClosestVillage(MathHelper.floor(b.locX), MathHelper.floor(b.locY), MathHelper.floor(b.locZ), 0); + if (this.a == null) { + return false; + } else if (this.f() && this.b.n(true)) { + Entity entity = this.d.a(EntityVillager.class, this.b.getBoundingBox().grow(8.0D, 3.0D, 8.0D), (Entity) this.b); + + if (entity == null) { + return false; + } else { + this.c = (EntityVillager) entity; + return this.c.getAge() == 0 && this.c.n(true); + } + } else { + return false; + } + } + } + + public void c() { + this.e = 300; + this.b.l(true); + } + + public void d() { + this.a = null; + this.c = null; + this.b.l(false); + } + + public boolean b() { + return this.e >= 0 && this.f() && this.b.getAge() == 0 && this.b.n(false); + } + + public void e() { + --this.e; + this.b.getControllerLook().a(this.c, 10.0F, 30.0F); + if (this.b.h(this.c) > 2.25D) { + this.b.getNavigation().a(this.c, 0.25D); + } else if (this.e == 0 && this.c.cm()) { + this.g(); + } + + if (this.b.bc().nextInt(35) == 0) { + this.d.broadcastEntityEffect(this.b, (byte) 12); + } + + } + + private boolean f() { + if (!this.a.i()) { + return false; + } else { + int i = (int) ((double) ((float) this.a.c()) * 0.35D); + + return this.a.e() < i; + } + } + + private void g() { + EntityVillager entityvillager = this.b.b(this.c); + + this.c.setAgeRaw(6000); + this.b.setAgeRaw(6000); + this.c.o(false); + this.b.o(false); + entityvillager.setAgeRaw(-24000); + entityvillager.setPositionRotation(this.b.locX, this.b.locY, this.b.locZ, 0.0F, 0.0F); + this.d.addEntity(entityvillager, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.BREEDING); // CraftBukkit - added SpawnReason + this.d.broadcastEntityEffect(entityvillager, (byte) 12); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalMeleeAttack.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalMeleeAttack.java new file mode 100644 index 0000000..3952428 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalMeleeAttack.java @@ -0,0 +1,97 @@ +package net.minecraft.server; + +public class PathfinderGoalMeleeAttack extends PathfinderGoal { + + protected EntityCreature b; + int c; + double d; + boolean e; + PathEntity f; + Class g; + private int h; + private double i; + private double j; + private double k; + + public PathfinderGoalMeleeAttack(EntityCreature entitycreature, Class oclass, double d0, boolean flag) { + this(entitycreature, d0, flag); + this.g = oclass; + } + + public PathfinderGoalMeleeAttack(EntityCreature entitycreature, double d0, boolean flag) { + this.b = entitycreature; + this.d = d0; + this.e = flag; + this.a(3); + } + + public boolean a() { + EntityLiving entityliving = this.b.getGoalTarget(); + + if (entityliving == null) { + return false; + } else if (!entityliving.isAlive()) { + return false; + } else if (this.g != null && !this.g.isAssignableFrom(entityliving.getClass())) { + return false; + } else { + this.f = this.b.getNavigation().a(entityliving); + return this.f != null; + } + } + + public boolean b() { + EntityLiving entityliving = this.b.getGoalTarget(); + + return entityliving != null && (entityliving.isAlive() && (!this.e ? !this.b.getNavigation().m() : this.b.e(new BlockPosition(entityliving)))); + } + + public void c() { + this.b.getNavigation().a(this.f, this.d); + this.h = 0; + } + + public void d() { + this.b.getNavigation().n(); + } + + public void e() { + EntityLiving entityliving = this.b.getGoalTarget(); + + this.b.getControllerLook().a(entityliving, 30.0F, 30.0F); + double d0 = this.b.e(entityliving.locX, entityliving.getBoundingBox().b, entityliving.locZ); + double d1 = this.a(entityliving); + + --this.h; + if ((this.e || this.b.getEntitySenses().a(entityliving)) && this.h <= 0 && (this.i == 0.0D && this.j == 0.0D && this.k == 0.0D || entityliving.e(this.i, this.j, this.k) >= 1.0D || this.b.bc().nextFloat() < 0.05F)) { + this.i = entityliving.locX; + this.j = entityliving.getBoundingBox().b; + this.k = entityliving.locZ; + this.h = 4 + this.b.bc().nextInt(7); + if (d0 > 1024.0D) { + this.h += 10; + } else if (d0 > 256.0D) { + this.h += 5; + } + + if (!this.b.getNavigation().a(entityliving, this.d)) { + this.h += 15; + } + } + + this.c = Math.max(this.c - 1, 0); + if (d0 <= d1 && this.c == 0) { + this.c = 20; + if (this.b.bA() != null) { + this.b.bw(); + } + + this.b.r(entityliving); + } + + } + + protected double a(EntityLiving entityliving) { + return this.b.width * 2.0F * this.b.width * 2.0F + entityliving.width; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalMoveIndoors.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalMoveIndoors.java new file mode 100644 index 0000000..f37d926 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalMoveIndoors.java @@ -0,0 +1,67 @@ +package net.minecraft.server; + +import dev.azurite.spigot.pathsearch.PositionPathSearchType; + +public class PathfinderGoalMoveIndoors extends PathfinderGoal { + + private final EntityCreature a; + private VillageDoor b; + private int c = -1; + private int d = -1; + + public PathfinderGoalMoveIndoors(EntityCreature entitycreature) { + this.a = entitycreature; + this.a(1); + } + + public boolean a() { + BlockPosition blockposition = new BlockPosition(this.a); + + if ((!this.a.world.w() || this.a.world.S() && !this.a.world.getBiome(blockposition).e()) && !this.a.world.worldProvider.o()) { + if (this.a.bc().nextInt(50) != 0) { + return false; + } else if (this.c != -1 && this.a.e(this.c, this.a.locY, this.d) < 4.0D) { + return false; + } else { + Village village = this.a.world.ae().getClosestVillage(blockposition, 14); + + if (village == null) { + return false; + } else { + this.b = village.c(blockposition); + return this.b != null; + } + } + } else { + return false; + } + } + + public boolean b() { + return !this.a.getNavigation().m(); + } + + public void c() { + this.c = -1; + BlockPosition blockposition = this.b.e(); + int i = blockposition.getX(); + int j = blockposition.getY(); + int k = blockposition.getZ(); + + if (this.a.b(blockposition) > 256.0D) { + Vec3D vec3d = RandomPositionGenerator.a(this.a, 14, 3, new Vec3D((double) i + 0.5D, j, (double) k + 0.5D)); + + if (vec3d != null) { + this.a.getNavigation().a(vec3d.a, vec3d.b, vec3d.c, 1.0D, PositionPathSearchType.MOVEINDOORS); // Migot + } + } else { + this.a.getNavigation().a((double) i + 0.5D, (double) j, (double) k + 0.5D, 1.0D, PositionPathSearchType.MOVEINDOORS); // Migot + } + } + + public void d() { + this.c = this.b.e().getX(); + this.d = this.b.e().getZ(); + this.b = null; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalMoveThroughVillage.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalMoveThroughVillage.java new file mode 100644 index 0000000..870b862 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalMoveThroughVillage.java @@ -0,0 +1,127 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; +import dev.azurite.spigot.pathsearch.PositionPathSearchType; + +import java.util.Iterator; +import java.util.List; + +public class PathfinderGoalMoveThroughVillage extends PathfinderGoal { + + private final EntityCreature a; + private final double b; + private PathEntity c; + private VillageDoor d; + private final boolean e; + private final List f = Lists.newArrayList(); + + public PathfinderGoalMoveThroughVillage(EntityCreature entitycreature, double d0, boolean flag) { + this.a = entitycreature; + this.b = d0; + this.e = flag; + this.a(1); + if (!(entitycreature.getNavigation() instanceof Navigation)) { + throw new IllegalArgumentException("Unsupported mob for MoveThroughVillageGoal"); + } + } + + public boolean a() { + this.f(); + if (this.e && this.a.world.w()) { + return false; + } else { + Village village = this.a.world.ae().getClosestVillage(new BlockPosition(this.a), 0); + + if (village == null) { + return false; + } else { + this.d = this.a(village); + if (this.d == null) { + return false; + } else { + Navigation navigation = (Navigation) this.a.getNavigation(); + boolean flag = navigation.g(); + + navigation.b(false); + this.c = navigation.a(this.d.d()); + navigation.b(flag); + if (this.c != null) { + return true; + } else { + Vec3D vec3d = RandomPositionGenerator.a(this.a, 10, 7, new Vec3D(this.d.d().getX(), this.d.d().getY(), this.d.d().getZ())); + + if (vec3d == null) { + return false; + } else { + navigation.b(false); + this.c = this.a.getNavigation().a(vec3d.a, vec3d.b, vec3d.c, PositionPathSearchType.MOVETHROUGHVILLAGE); // Migot + navigation.b(flag); + return this.c != null; + } + } + } + } + } + } + + public boolean b() { + if (this.a.getNavigation().m()) { + return false; + } else { + float f = this.a.width + 4.0F; + + return this.a.b(this.d.d()) > (double) (f * f); + } + } + + public void c() { + this.a.getNavigation().a(this.c, this.b); + } + + public void d() { + if (this.a.getNavigation().m() || this.a.b(this.d.d()) < 16.0D) { + this.f.add(this.d); + } + + } + + private VillageDoor a(Village village) { + VillageDoor villagedoor = null; + int i = Integer.MAX_VALUE; + List list = village.f(); + + for (VillageDoor villagedoor1 : list) { + int j = villagedoor1.b(MathHelper.floor(this.a.locX), MathHelper.floor(this.a.locY), MathHelper.floor(this.a.locZ)); + + if (j < i && !this.a(villagedoor1)) { + villagedoor = villagedoor1; + i = j; + } + } + + return villagedoor; + } + + private boolean a(VillageDoor villagedoor) { + Iterator iterator = this.f.iterator(); + + VillageDoor villagedoor1; + + do { + if (!iterator.hasNext()) { + return false; + } + + villagedoor1 = iterator.next(); + } while (!villagedoor.d().equals(villagedoor1.d())); + + return true; + } + + private void f() { + if (this.f.size() > 15) { + this.f.remove(0); + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalMoveTowardsRestriction.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalMoveTowardsRestriction.java new file mode 100644 index 0000000..66934c1 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalMoveTowardsRestriction.java @@ -0,0 +1,44 @@ +package net.minecraft.server; + +import dev.azurite.spigot.pathsearch.PositionPathSearchType; + +public class PathfinderGoalMoveTowardsRestriction extends PathfinderGoal { + + private final EntityCreature a; + private double b; + private double c; + private double d; + private final double e; + + public PathfinderGoalMoveTowardsRestriction(EntityCreature entitycreature, double d0) { + this.a = entitycreature; + this.e = d0; + this.a(1); + } + + public boolean a() { + if (this.a.cg()) { + return false; + } else { + BlockPosition blockposition = this.a.ch(); + Vec3D vec3d = RandomPositionGenerator.a(this.a, 16, 7, new Vec3D(blockposition.getX(), blockposition.getY(), blockposition.getZ())); + + if (vec3d == null) { + return false; + } else { + this.b = vec3d.a; + this.c = vec3d.b; + this.d = vec3d.c; + return true; + } + } + } + + public boolean b() { + return !this.a.getNavigation().m(); + } + + public void c() { + this.a.getNavigation().a(this.b, this.c, this.d, this.e, PositionPathSearchType.MOVETOWARDSRESTRICTION); // Migot + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalMoveTowardsTarget.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalMoveTowardsTarget.java new file mode 100644 index 0000000..0b72e10 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalMoveTowardsTarget.java @@ -0,0 +1,53 @@ +package net.minecraft.server; + +import dev.azurite.spigot.pathsearch.PositionPathSearchType; + +public class PathfinderGoalMoveTowardsTarget extends PathfinderGoal { + + private final EntityCreature a; + private EntityLiving b; + private double c; + private double d; + private double e; + private final double f; + private final float g; + + public PathfinderGoalMoveTowardsTarget(EntityCreature entitycreature, double d0, float f) { + this.a = entitycreature; + this.f = d0; + this.g = f; + this.a(1); + } + + public boolean a() { + this.b = this.a.getGoalTarget(); + if (this.b == null) { + return false; + } else if (this.b.h(this.a) > (double) (this.g * this.g)) { + return false; + } else { + Vec3D vec3d = RandomPositionGenerator.a(this.a, 16, 7, new Vec3D(this.b.locX, this.b.locY, this.b.locZ)); + + if (vec3d == null) { + return false; + } else { + this.c = vec3d.a; + this.d = vec3d.b; + this.e = vec3d.c; + return true; + } + } + } + + public boolean b() { + return !this.a.getNavigation().m() && this.b.isAlive() && this.b.h(this.a) < (double) (this.g * this.g); + } + + public void d() { + this.b = null; + } + + public void c() { + this.a.getNavigation().a(this.c, this.d, this.e, this.f, PositionPathSearchType.MOVETOWARDSTARGET); // Migot + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalNearestAttackableTarget.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalNearestAttackableTarget.java new file mode 100644 index 0000000..bce64da --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalNearestAttackableTarget.java @@ -0,0 +1,106 @@ +package net.minecraft.server; + +import com.google.common.base.Predicate; +import com.google.common.base.Predicates; + +import java.util.Comparator; +import java.util.List; + +public class PathfinderGoalNearestAttackableTarget extends PathfinderGoalTarget { + + protected final Class a; + private final int g; + protected final DistanceComparator b; + protected Predicate c; + protected EntityLiving d; + + public PathfinderGoalNearestAttackableTarget(EntityCreature entitycreature, Class oclass, boolean flag) { + this(entitycreature, oclass, flag, false); + } + + public PathfinderGoalNearestAttackableTarget(EntityCreature entitycreature, Class oclass, boolean flag, boolean flag1) { + this(entitycreature, oclass, 10, flag, flag1, null); + } + + public PathfinderGoalNearestAttackableTarget(EntityCreature entitycreature, Class oclass, int i, boolean flag, boolean flag1, final Predicate predicate) { + super(entitycreature, flag, flag1); + this.a = oclass; + this.g = i; + this.b = new DistanceComparator(entitycreature); + this.a(1); + this.c = new Predicate() { + public boolean a(T t0) { + if (predicate != null && !predicate.apply(t0)) { + return false; + } else { + if (t0 instanceof EntityHuman) { + double d0 = PathfinderGoalNearestAttackableTarget.this.f(); + + if (t0.isSneaking()) { + d0 *= 0.800000011920929D; + } + + if (t0.isInvisible()) { + float f = ((EntityHuman) t0).bY(); + + if (f < 0.1F) { + f = 0.1F; + } + + d0 *= 0.7F * f; + } + + if ((double) t0.g(PathfinderGoalNearestAttackableTarget.this.e) > d0) { + return false; + } + } + + return PathfinderGoalNearestAttackableTarget.this.a(t0, false); + } + } + + public boolean apply(Object object) { + return this.a((T) object); // CraftBukkit - fix decompile error + } + }; + } + + public boolean a() { + if (this.g > 0 && this.e.bc().nextInt(this.g) != 0) { + return false; + } else { + double d0 = this.f(); + List list = this.e.world.a(this.a, this.e.getBoundingBox().grow(d0, 4.0D, d0), Predicates.and(this.c, IEntitySelector.d)); + + list.sort(this.b); + if (list.isEmpty()) { + return false; + } else { + this.d = list.get(0); + return true; + } + } + } + + public void c() { + this.e.setGoalTarget(this.d, d instanceof EntityPlayer ? org.bukkit.event.entity.EntityTargetEvent.TargetReason.CLOSEST_PLAYER : org.bukkit.event.entity.EntityTargetEvent.TargetReason.CLOSEST_ENTITY, true); // Craftbukkit - reason + super.c(); + } + + public static class DistanceComparator implements Comparator { + + private final Entity a; + + public DistanceComparator(Entity entity) { + this.a = entity; + } + + public int a(Entity entity, Entity entity1) { + return Double.compare(a.h(entity), a.h(entity1)); + } + + public int compare(Entity object, Entity object1) { // CraftBukkit - fix decompile error + return this.a(object, object1); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalNearestAttackableTargetInsentient.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalNearestAttackableTargetInsentient.java new file mode 100644 index 0000000..45bf097 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalNearestAttackableTargetInsentient.java @@ -0,0 +1,85 @@ +package net.minecraft.server; + +import com.google.common.base.Predicate; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.util.List; + +public class PathfinderGoalNearestAttackableTargetInsentient extends PathfinderGoal { + + private static final Logger a = LogManager.getLogger(); + private final EntityInsentient b; + private final Predicate c; + private final PathfinderGoalNearestAttackableTarget.DistanceComparator d; + private EntityLiving e; + private final Class f; + + public PathfinderGoalNearestAttackableTargetInsentient(EntityInsentient entityinsentient, Class oclass) { + this.b = entityinsentient; + this.f = oclass; + if (entityinsentient instanceof EntityCreature) { + PathfinderGoalNearestAttackableTargetInsentient.a.warn("Use NearestAttackableTargetGoal.class for PathfinerMob mobs!"); + } + + this.c = new Predicate() { + public boolean a(EntityLiving entityliving) { + double d0 = PathfinderGoalNearestAttackableTargetInsentient.this.f(); + + if (entityliving.isSneaking()) { + d0 *= 0.800000011920929D; + } + + return !entityliving.isInvisible() && (!((double) entityliving.g(PathfinderGoalNearestAttackableTargetInsentient.this.b) > d0) && PathfinderGoalTarget.a(PathfinderGoalNearestAttackableTargetInsentient.this.b, entityliving, false, true)); + } + + public boolean apply(Object object) { + return this.a((EntityLiving) object); + } + }; + this.d = new PathfinderGoalNearestAttackableTarget.DistanceComparator(entityinsentient); + } + + public boolean a() { + double d0 = this.f(); + List list = this.b.world.a(this.f, this.b.getBoundingBox().grow(d0, 4.0D, d0), this.c); + + list.sort(this.d); + if (list.isEmpty()) { + return false; + } else { + this.e = list.get(0); + return true; + } + } + + public boolean b() { + EntityLiving entityliving = this.b.getGoalTarget(); + + if (entityliving == null) { + return false; + } else if (!entityliving.isAlive()) { + return false; + } else { + double d0 = this.f(); + + return !(this.b.h(entityliving) > d0 * d0) && (!(entityliving instanceof EntityPlayer) || !((EntityPlayer) entityliving).playerInteractManager.isCreative()); + } + } + + public void c() { + this.b.setGoalTarget(this.e, org.bukkit.event.entity.EntityTargetEvent.TargetReason.CLOSEST_ENTITY, true); // CraftBukkit - reason + super.c(); + } + + public void d() { + this.b.setGoalTarget(null); + super.c(); + } + + protected double f() { + AttributeInstance attributeinstance = this.b.getAttributeInstance(GenericAttributes.FOLLOW_RANGE); + + return attributeinstance == null ? 16.0D : attributeinstance.getValue(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalOcelotAttack.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalOcelotAttack.java new file mode 100644 index 0000000..c0f3fb8 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalOcelotAttack.java @@ -0,0 +1,55 @@ +package net.minecraft.server; + +public class PathfinderGoalOcelotAttack extends PathfinderGoal { + + EntityInsentient b; + EntityLiving c; + int d; + + public PathfinderGoalOcelotAttack(EntityInsentient entityinsentient) { + this.b = entityinsentient; + this.a(3); + } + + public boolean a() { + EntityLiving entityliving = this.b.getGoalTarget(); + + if (entityliving == null) { + return false; + } else { + this.c = entityliving; + return true; + } + } + + public boolean b() { + return this.c.isAlive() && (!(this.b.h(this.c) > 225.0D) && (!this.b.getNavigation().m() || this.a())); + } + + public void d() { + this.c = null; + this.b.getNavigation().n(); + } + + public void e() { + this.b.getControllerLook().a(this.c, 30.0F, 30.0F); + double d0 = this.b.width * 2.0F * this.b.width * 2.0F; + double d1 = this.b.e(this.c.locX, this.c.getBoundingBox().b, this.c.locZ); + double d2 = 0.8D; + + if (d1 > d0 && d1 < 16.0D) { + d2 = 1.33D; + } else if (d1 < 225.0D) { + d2 = 0.6D; + } + + this.b.getNavigation().a(this.c, d2); + this.d = Math.max(this.d - 1, 0); + if (d1 <= d0) { + if (this.d == 0) { + this.d = 20; + this.b.r(this.c); + } + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalOfferFlower.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalOfferFlower.java new file mode 100644 index 0000000..3c3f371 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalOfferFlower.java @@ -0,0 +1,43 @@ +package net.minecraft.server; + +public class PathfinderGoalOfferFlower extends PathfinderGoal { + + private final EntityIronGolem a; + private EntityVillager b; + private int c; + + public PathfinderGoalOfferFlower(EntityIronGolem entityirongolem) { + this.a = entityirongolem; + this.a(3); + } + + public boolean a() { + if (!this.a.world.w()) { + return false; + } else if (this.a.bc().nextInt(8000) != 0) { + return false; + } else { + this.b = (EntityVillager) this.a.world.a(EntityVillager.class, this.a.getBoundingBox().grow(6.0D, 2.0D, 6.0D), (Entity) this.a); + return this.b != null; + } + } + + public boolean b() { + return this.c > 0; + } + + public void c() { + this.c = 400; + this.a.a(true); + } + + public void d() { + this.a.a(false); + this.b = null; + } + + public void e() { + this.a.getControllerLook().a(this.b, 30.0F, 30.0F); + --this.c; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalOpenDoor.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalOpenDoor.java new file mode 100644 index 0000000..b0759b1 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalOpenDoor.java @@ -0,0 +1,34 @@ +package net.minecraft.server; + +public class PathfinderGoalOpenDoor extends PathfinderGoalDoorInteract { + + boolean g; + int h; + + public PathfinderGoalOpenDoor(EntityInsentient entityinsentient, boolean flag) { + super(entityinsentient); + this.a = entityinsentient; + this.g = flag; + } + + public boolean b() { + return this.g && this.h > 0 && super.b(); + } + + public void c() { + this.h = 20; + this.c.setDoor(this.a.world, this.b, true); + } + + public void d() { + if (this.g) { + this.c.setDoor(this.a.world, this.b, false); + } + + } + + public void e() { + --this.h; + super.e(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalOwnerHurtByTarget.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalOwnerHurtByTarget.java new file mode 100644 index 0000000..465cfd1 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalOwnerHurtByTarget.java @@ -0,0 +1,42 @@ +package net.minecraft.server; + +public class PathfinderGoalOwnerHurtByTarget extends PathfinderGoalTarget { + + EntityTameableAnimal a; + EntityLiving b; + private int c; + + public PathfinderGoalOwnerHurtByTarget(EntityTameableAnimal entitytameableanimal) { + super(entitytameableanimal, false); + this.a = entitytameableanimal; + this.a(1); + } + + public boolean a() { + if (!this.a.isTamed()) { + return false; + } else { + EntityLiving entityliving = this.a.getOwner(); + + if (entityliving == null) { + return false; + } else { + this.b = entityliving.getLastDamager(); + int i = entityliving.be(); + + return i != this.c && this.a(this.b, false) && this.a.a(this.b, entityliving); + } + } + } + + public void c() { + this.e.setGoalTarget(this.b, org.bukkit.event.entity.EntityTargetEvent.TargetReason.TARGET_ATTACKED_OWNER, true); // CraftBukkit - reason + EntityLiving entityliving = this.a.getOwner(); + + if (entityliving != null) { + this.c = entityliving.be(); + } + + super.c(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalOwnerHurtTarget.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalOwnerHurtTarget.java new file mode 100644 index 0000000..7269d2f --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalOwnerHurtTarget.java @@ -0,0 +1,42 @@ +package net.minecraft.server; + +public class PathfinderGoalOwnerHurtTarget extends PathfinderGoalTarget { + + EntityTameableAnimal a; + EntityLiving b; + private int c; + + public PathfinderGoalOwnerHurtTarget(EntityTameableAnimal entitytameableanimal) { + super(entitytameableanimal, false); + this.a = entitytameableanimal; + this.a(1); + } + + public boolean a() { + if (!this.a.isTamed()) { + return false; + } else { + EntityLiving entityliving = this.a.getOwner(); + + if (entityliving == null) { + return false; + } else { + this.b = entityliving.bf(); + int i = entityliving.bg(); + + return i != this.c && this.a(this.b, false) && this.a.a(this.b, entityliving); + } + } + } + + public void c() { + this.e.setGoalTarget(this.b, org.bukkit.event.entity.EntityTargetEvent.TargetReason.OWNER_ATTACKED_TARGET, true); // CraftBukkit - reason + EntityLiving entityliving = this.a.getOwner(); + + if (entityliving != null) { + this.c = entityliving.bg(); + } + + super.c(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalPanic.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalPanic.java new file mode 100644 index 0000000..96b2381 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalPanic.java @@ -0,0 +1,49 @@ +package net.minecraft.server; + +import dev.azurite.spigot.pathsearch.PositionPathSearchType; + +public class PathfinderGoalPanic extends PathfinderGoal { + + private final EntityCreature b; + protected double a; + private double c; + private double d; + private double e; + + public PathfinderGoalPanic(EntityCreature entitycreature, double d0) { + this.b = entitycreature; + this.a = d0; + this.a(1); + } + + public boolean a() { + if (this.b.getLastDamager() == null && !this.b.isBurning()) { + return false; + } else { + Vec3D vec3d = RandomPositionGenerator.a(this.b, 5, 4); + + if (vec3d == null) { + return false; + } else { + this.c = vec3d.a; + this.d = vec3d.b; + this.e = vec3d.c; + return true; + } + } + } + + public void c() { + this.b.getNavigation().a(this.c, this.d, this.e, this.a, PositionPathSearchType.PANIC); // Migot + } + + public boolean b() { + // CraftBukkit start - introduce a temporary timeout hack until this is fixed properly + if ((this.b.ticksLived - this.b.hurtTimestamp) > 100) { + this.b.b((EntityLiving) null); + return false; + } + // CraftBukkit end + return !this.b.getNavigation().m(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalPassengerCarrotStick.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalPassengerCarrotStick.java new file mode 100644 index 0000000..9cbf91e --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalPassengerCarrotStick.java @@ -0,0 +1,153 @@ +package net.minecraft.server; + +public class PathfinderGoalPassengerCarrotStick extends PathfinderGoal { + + private final EntityInsentient a; + private final float b; + private float c; + private boolean d; + private int e; + private int f; + + public PathfinderGoalPassengerCarrotStick(EntityInsentient entityinsentient, float f) { + this.a = entityinsentient; + this.b = f; + this.a(7); + } + + public void c() { + this.c = 0.0F; + } + + public void d() { + this.d = false; + this.c = 0.0F; + } + + public boolean a() { + return this.a.isAlive() && this.a.passenger != null && this.a.passenger instanceof EntityHuman && (this.d || this.a.bW()); + } + + public void e() { + EntityHuman entityhuman = (EntityHuman) this.a.passenger; + EntityCreature entitycreature = (EntityCreature) this.a; + float f = MathHelper.g(entityhuman.yaw - this.a.yaw) * 0.5F; + + if (f > 5.0F) { + f = 5.0F; + } + + if (f < -5.0F) { + f = -5.0F; + } + + this.a.yaw = MathHelper.g(this.a.yaw + f); + if (this.c < this.b) { + this.c += (this.b - this.c) * 0.01F; + } + + if (this.c > this.b) { + this.c = this.b; + } + + int i = MathHelper.floor(this.a.locX); + int j = MathHelper.floor(this.a.locY); + int k = MathHelper.floor(this.a.locZ); + float f1 = this.c; + + if (this.d) { + if (this.e++ > this.f) { + this.d = false; + } + + f1 += f1 * 1.15F * MathHelper.sin((float) this.e / (float) this.f * 3.1415927F); + } + + float f2 = 0.91F; + + if (this.a.onGround) { + f2 = this.a.world.getType(MathHelper.d(i), MathHelper.d(j) - 1, MathHelper.d(k)).getBlock().frictionFactor * 0.91F; + } + + float f3 = 0.16277136F / (f2 * f2 * f2); + float f4 = MathHelper.sin(entitycreature.yaw * 3.1415927F / 180.0F); + float f5 = MathHelper.cos(entitycreature.yaw * 3.1415927F / 180.0F); + float f6 = entitycreature.bI() * f3; + float f7 = Math.max(f1, 1.0F); + + f7 = f6 / f7; + float f8 = f1 * f7; + float f9 = -(f8 * f4); + float f10 = f8 * f5; + + if (MathHelper.e(f9) > MathHelper.e(f10)) { + if (f9 < 0.0F) { + f9 -= this.a.width / 2.0F; + } + + if (f9 > 0.0F) { + f9 += this.a.width / 2.0F; + } + + f10 = 0.0F; + } else { + f9 = 0.0F; + if (f10 < 0.0F) { + f10 -= this.a.width / 2.0F; + } + + if (f10 > 0.0F) { + f10 += this.a.width / 2.0F; + } + } + + int l = MathHelper.floor(this.a.locX + (double) f9); + int i1 = MathHelper.floor(this.a.locZ + (double) f10); + int j1 = MathHelper.d(this.a.width + 1.0F); + int k1 = MathHelper.d(this.a.length + entityhuman.length + 1.0F); + int l1 = MathHelper.d(this.a.width + 1.0F); + + if (i != l || k != i1) { + Block block = this.a.world.getType(i, j, k).getBlock(); + boolean flag = !this.a(block) && (block.getMaterial() != Material.AIR || !this.a(this.a.world.getType(i, j - 1, k).getBlock())); + + if (flag && 0 == PathfinderNormal.a(this.a.world, this.a, l, j, i1, j1, k1, l1, false, false, true) && 1 == PathfinderNormal.a(this.a.world, this.a, i, j + 1, k, j1, k1, l1, false, false, true) && 1 == PathfinderNormal.a(this.a.world, this.a, l, j + 1, i1, j1, k1, l1, false, false, true)) { + entitycreature.getControllerJump().a(); + } + } + + if (!entityhuman.abilities.canInstantlyBuild && this.c >= this.b * 0.5F && this.a.bc().nextFloat() < 0.006F && !this.d) { + ItemStack itemstack = entityhuman.bA(); + + if (itemstack != null && itemstack.getItem() == Items.CARROT_ON_A_STICK) { + itemstack.damage(1, entityhuman); + if (itemstack.count == 0) { + ItemStack itemstack1 = new ItemStack(Items.FISHING_ROD); + + itemstack1.setTag(itemstack.getTag()); + entityhuman.inventory.items[entityhuman.inventory.itemInHandIndex] = itemstack1; + } + } + } + + this.a.g(0.0F, f1); + } + + private boolean a(Block block) { + return block instanceof BlockStairs || block instanceof BlockStepAbstract; + } + + public boolean f() { + return this.d; + } + + public void g() { + this.d = true; + this.e = 0; + this.f = this.a.bc().nextInt(841) + 140; + } + + public boolean h() { + return !this.f() && this.c > this.b * 0.3F; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalPlay.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalPlay.java new file mode 100644 index 0000000..7853599 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalPlay.java @@ -0,0 +1,83 @@ +package net.minecraft.server; + +import dev.azurite.spigot.pathsearch.PositionPathSearchType; + +import java.util.List; + +public class PathfinderGoalPlay extends PathfinderGoal { + + private final EntityVillager a; + private EntityLiving b; + private final double c; + private int d; + + public PathfinderGoalPlay(EntityVillager entityvillager, double d0) { + this.a = entityvillager; + this.c = d0; + this.a(1); + } + + public boolean a() { + if (this.a.getAge() >= 0) { + return false; + } else if (this.a.bc().nextInt(400) != 0) { + return false; + } else { + List list = this.a.world.a(EntityVillager.class, this.a.getBoundingBox().grow(6.0D, 3.0D, 6.0D)); + double d0 = Double.MAX_VALUE; + + for (EntityVillager entityvillager : list) { + if (entityvillager != this.a && !entityvillager.cn() && entityvillager.getAge() < 0) { + double d1 = entityvillager.h(this.a); + + if (d1 <= d0) { + d0 = d1; + this.b = entityvillager; + } + } + } + + if (this.b == null) { + Vec3D vec3d = RandomPositionGenerator.a(this.a, 16, 3); + + return vec3d != null; + } + + return true; + } + } + + public boolean b() { + return this.d > 0; + } + + public void c() { + if (this.b != null) { + this.a.m(true); + } + + this.d = 1000; + } + + public void d() { + this.a.m(false); + this.b = null; + } + + public void e() { + --this.d; + if (this.b != null) { + if (this.a.h(this.b) > 4.0D) { + this.a.getNavigation().a(this.b, this.c); + } + } else if (this.a.getNavigation().m()) { + Vec3D vec3d = RandomPositionGenerator.a(this.a, 16, 3); + + if (vec3d == null) { + return; + } + + this.a.getNavigation().a(vec3d.a, vec3d.b, vec3d.c, this.c, PositionPathSearchType.PLAY); // Migot + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalRandomLookaround.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalRandomLookaround.java new file mode 100644 index 0000000..0179780 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalRandomLookaround.java @@ -0,0 +1,35 @@ +package net.minecraft.server; + +public class PathfinderGoalRandomLookaround extends PathfinderGoal { + + private final EntityInsentient a; + private double b; + private double c; + private int d; + + public PathfinderGoalRandomLookaround(EntityInsentient entityinsentient) { + this.a = entityinsentient; + this.a(3); + } + + public boolean a() { + return this.a.bc().nextFloat() < 0.02F; + } + + public boolean b() { + return this.d >= 0; + } + + public void c() { + double d0 = 6.283185307179586D * this.a.bc().nextDouble(); + + this.b = Math.cos(d0); + this.c = Math.sin(d0); + this.d = 20 + this.a.bc().nextInt(20); + } + + public void e() { + --this.d; + this.a.getControllerLook().a(this.a.locX + this.b, this.a.locY + (double) this.a.getHeadHeight(), this.a.locZ + this.c, 10.0F, (float) this.a.bQ()); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalRandomStroll.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalRandomStroll.java new file mode 100644 index 0000000..aed8078 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalRandomStroll.java @@ -0,0 +1,65 @@ +package net.minecraft.server; + +import dev.azurite.spigot.pathsearch.PositionPathSearchType; + +public class PathfinderGoalRandomStroll extends PathfinderGoal { + + private final EntityCreature a; + private double b; + private double c; + private double d; + private final double e; + private int f; + private boolean g; + + public PathfinderGoalRandomStroll(EntityCreature entitycreature, double d0) { + this(entitycreature, d0, 120); + } + + public PathfinderGoalRandomStroll(EntityCreature entitycreature, double d0, int i) { + this.a = entitycreature; + this.e = d0; + this.f = i; + this.a(1); + } + + public boolean a() { + if (!this.g) { + if (this.a.bh() >= 100) { + return false; + } + + if (this.a.bc().nextInt(this.f) != 0) { + return false; + } + } + + Vec3D vec3d = RandomPositionGenerator.a(this.a, 10, 7); + + if (vec3d == null) { + return false; + } else { + this.b = vec3d.a; + this.c = vec3d.b; + this.d = vec3d.c; + this.g = false; + return true; + } + } + + public boolean b() { + return !this.a.getNavigation().m(); + } + + public void c() { + this.a.getNavigation().a(this.b, this.c, this.d, this.e, PositionPathSearchType.RANDOMSTROLL); // Migot + } + + public void f() { + this.g = true; + } + + public void setTimeBetweenMovement(int i) { + this.f = i; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalRandomTargetNonTamed.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalRandomTargetNonTamed.java new file mode 100644 index 0000000..3542527 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalRandomTargetNonTamed.java @@ -0,0 +1,17 @@ +package net.minecraft.server; + +import com.google.common.base.Predicate; + +public class PathfinderGoalRandomTargetNonTamed extends PathfinderGoalNearestAttackableTarget { + + private final EntityTameableAnimal g; + + public PathfinderGoalRandomTargetNonTamed(EntityTameableAnimal entitytameableanimal, Class oclass, boolean flag, Predicate predicate) { + super(entitytameableanimal, oclass, 10, flag, false, predicate); + this.g = entitytameableanimal; + } + + public boolean a() { + return !this.g.isTamed() && super.a(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalRestrictOpenDoor.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalRestrictOpenDoor.java new file mode 100644 index 0000000..f6d90b0 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalRestrictOpenDoor.java @@ -0,0 +1,49 @@ +package net.minecraft.server; + +public class PathfinderGoalRestrictOpenDoor extends PathfinderGoal { + + private final EntityCreature a; + private VillageDoor b; + + public PathfinderGoalRestrictOpenDoor(EntityCreature entitycreature) { + this.a = entitycreature; + if (!(entitycreature.getNavigation() instanceof Navigation)) { + throw new IllegalArgumentException("Unsupported mob type for RestrictOpenDoorGoal"); + } + } + + public boolean a() { + if (this.a.world.w()) { + return false; + } else { + BlockPosition blockposition = new BlockPosition(this.a); + Village village = this.a.world.ae().getClosestVillage(blockposition, 16); + + if (village == null) { + return false; + } else { + this.b = village.b(blockposition); + return this.b != null && (double) this.b.b(blockposition) < 2.25D; + } + } + } + + public boolean b() { + return !this.a.world.w() && !this.b.i() && this.b.c(new BlockPosition(this.a)); + } + + public void c() { + ((Navigation) this.a.getNavigation()).b(false); + ((Navigation) this.a.getNavigation()).c(false); + } + + public void d() { + ((Navigation) this.a.getNavigation()).b(true); + ((Navigation) this.a.getNavigation()).c(true); + this.b = null; + } + + public void e() { + this.b.b(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalRestrictSun.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalRestrictSun.java new file mode 100644 index 0000000..1bced8e --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalRestrictSun.java @@ -0,0 +1,22 @@ +package net.minecraft.server; + +public class PathfinderGoalRestrictSun extends PathfinderGoal { + + private final EntityCreature a; + + public PathfinderGoalRestrictSun(EntityCreature entitycreature) { + this.a = entitycreature; + } + + public boolean a() { + return this.a.world.w(); + } + + public void c() { + ((Navigation) this.a.getNavigation()).e(true); + } + + public void d() { + ((Navigation) this.a.getNavigation()).e(false); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalSelector.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalSelector.java new file mode 100644 index 0000000..3db491e --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalSelector.java @@ -0,0 +1,134 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.AzuriteConfig; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.bukkit.craftbukkit.util.UnsafeList; + +import java.util.Iterator; +import java.util.List; + +public class PathfinderGoalSelector { + + private static final Logger a = LogManager.getLogger(); + private final List b = new UnsafeList<>(); + private final List c = new UnsafeList<>(); + private int e; + + public PathfinderGoalSelector(MethodProfiler methodprofiler) { + } + + public PathfinderGoalSelector() { + } + + public void a(int i, PathfinderGoal pathfindergoal) { + this.b.add(new PathfinderGoalSelectorItem(i, pathfindergoal)); + } + + public void a(PathfinderGoal pathfindergoal) { + Iterator iterator = this.b.iterator(); + + while (iterator.hasNext()) { + PathfinderGoalSelectorItem pathfindergoalselector_pathfindergoalselectoritem = iterator.next(); + PathfinderGoal pathfindergoal1 = pathfindergoalselector_pathfindergoalselectoritem.a; + + if (pathfindergoal1 == pathfindergoal) { + if (this.c.contains(pathfindergoalselector_pathfindergoalselectoritem)) { + pathfindergoal1.d(); + this.c.remove(pathfindergoalselector_pathfindergoalselectoritem); + } + + iterator.remove(); + } + } + + } + + public void a() { + Iterator iterator; + PathfinderGoalSelectorItem pathfindergoalselector_pathfindergoalselectoritem; + + if (this.e++ % 3 == 0) { + iterator = this.b.iterator(); + + while (iterator.hasNext()) { + pathfindergoalselector_pathfindergoalselectoritem = (PathfinderGoalSelectorItem) iterator.next(); + boolean flag = this.c.contains(pathfindergoalselector_pathfindergoalselectoritem); + + if (flag) { + if (this.b(pathfindergoalselector_pathfindergoalselectoritem) && this.a(pathfindergoalselector_pathfindergoalselectoritem)) { + continue; + } + + pathfindergoalselector_pathfindergoalselectoritem.a.d(); + this.c.remove(pathfindergoalselector_pathfindergoalselectoritem); + } + + if (this.b(pathfindergoalselector_pathfindergoalselectoritem) && pathfindergoalselector_pathfindergoalselectoritem.a.a()) { + pathfindergoalselector_pathfindergoalselectoritem.a.c(); + this.c.add(pathfindergoalselector_pathfindergoalselectoritem); + } + } + } else { + iterator = this.c.iterator(); + + while (iterator.hasNext()) { + pathfindergoalselector_pathfindergoalselectoritem = (PathfinderGoalSelectorItem) iterator.next(); + if (!this.a(pathfindergoalselector_pathfindergoalselectoritem)) { + pathfindergoalselector_pathfindergoalselectoritem.a.d(); + iterator.remove(); + } + } + } + + iterator = this.c.iterator(); + + while (iterator.hasNext()) { + pathfindergoalselector_pathfindergoalselectoritem = (PathfinderGoalSelectorItem) iterator.next(); + pathfindergoalselector_pathfindergoalselectoritem.a.e(); + } + + } + + private boolean a(PathfinderGoalSelectorItem pathfindergoalselector_pathfindergoalselectoritem) { + + return pathfindergoalselector_pathfindergoalselectoritem.a.b(); + } + + private boolean b(PathfinderGoalSelectorItem pathfindergoalselector_pathfindergoalselectoritem) { + Iterator iterator = this.b.iterator(); + + while (iterator.hasNext()) { + PathfinderGoalSelectorItem pathfindergoalselector_pathfindergoalselectoritem1 = iterator.next(); + + if (pathfindergoalselector_pathfindergoalselectoritem1 != pathfindergoalselector_pathfindergoalselectoritem) { + if (pathfindergoalselector_pathfindergoalselectoritem.b >= pathfindergoalselector_pathfindergoalselectoritem1.b) { + if (!this.a(pathfindergoalselector_pathfindergoalselectoritem, pathfindergoalselector_pathfindergoalselectoritem1) && this.c.contains(pathfindergoalselector_pathfindergoalselectoritem1)) { + ((UnsafeList.Itr) iterator).valid = false; // CraftBukkit - mark iterator for reuse + return false; + } + } else if (!pathfindergoalselector_pathfindergoalselectoritem1.a.i() && this.c.contains(pathfindergoalselector_pathfindergoalselectoritem1)) { + ((UnsafeList.Itr) iterator).valid = false; // CraftBukkit - mark iterator for reuse + return false; + } + } + } + + return true; + } + + private boolean a(PathfinderGoalSelectorItem pathfindergoalselector_pathfindergoalselectoritem, PathfinderGoalSelectorItem pathfindergoalselector_pathfindergoalselectoritem1) { + return (pathfindergoalselector_pathfindergoalselectoritem.a.j() & pathfindergoalselector_pathfindergoalselectoritem1.a.j()) == 0; + } + + static class PathfinderGoalSelectorItem { + + public PathfinderGoal a; + public int b; + + public PathfinderGoalSelectorItem(int i, PathfinderGoal pathfindergoal) { + this.b = i; + this.a = pathfindergoal; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalSit.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalSit.java new file mode 100644 index 0000000..fc1499d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalSit.java @@ -0,0 +1,39 @@ +package net.minecraft.server; + +public class PathfinderGoalSit extends PathfinderGoal { + + private final EntityTameableAnimal entity; + private boolean willSit; + + public PathfinderGoalSit(EntityTameableAnimal entitytameableanimal) { + this.entity = entitytameableanimal; + this.a(5); + } + + public boolean a() { + if (!this.entity.isTamed()) { + return this.willSit && this.entity.getGoalTarget() == null; // CraftBukkit - Allow sitting for wild animals + } else if (this.entity.V()) { + return false; + } else if (!this.entity.onGround) { + return false; + } else { + EntityLiving entityliving = this.entity.getOwner(); + + return entityliving == null || ((!(this.entity.h(entityliving) < 144.0D) || entityliving.getLastDamager() == null) && this.willSit); + } + } + + public void c() { + this.entity.getNavigation().n(); + this.entity.setSitting(true); + } + + public void d() { + this.entity.setSitting(false); + } + + public void setSitting(boolean flag) { + this.willSit = flag; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalSwell.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalSwell.java new file mode 100644 index 0000000..c8eebf8 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalSwell.java @@ -0,0 +1,39 @@ +package net.minecraft.server; + +public class PathfinderGoalSwell extends PathfinderGoal { + + EntityCreeper a; + EntityLiving b; + + public PathfinderGoalSwell(EntityCreeper entitycreeper) { + this.a = entitycreeper; + this.a(1); + } + + public boolean a() { + EntityLiving entityliving = this.a.getGoalTarget(); + + return this.a.cm() > 0 || entityliving != null && this.a.h(entityliving) < 9.0D; + } + + public void c() { + this.a.getNavigation().n(); + this.b = this.a.getGoalTarget(); + } + + public void d() { + this.b = null; + } + + public void e() { + if (this.b == null) { + this.a.a(-1); + } else if (this.a.h(this.b) > 49.0D) { + this.a.a(-1); + } else if (!this.a.getEntitySenses().a(this.b)) { + this.a.a(-1); + } else { + this.a.a(1); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalTakeFlower.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalTakeFlower.java new file mode 100644 index 0000000..cb82042 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalTakeFlower.java @@ -0,0 +1,73 @@ +package net.minecraft.server; + +import java.util.Iterator; +import java.util.List; + +public class PathfinderGoalTakeFlower extends PathfinderGoal { + + private final EntityVillager a; + private EntityIronGolem b; + private int c; + private boolean d; + + public PathfinderGoalTakeFlower(EntityVillager entityvillager) { + this.a = entityvillager; + this.a(3); + } + + public boolean a() { + if (this.a.getAge() >= 0) { + return false; + } else if (!this.a.world.w()) { + return false; + } else { + List list = this.a.world.a(EntityIronGolem.class, this.a.getBoundingBox().grow(6.0D, 2.0D, 6.0D)); + + if (list.isEmpty()) { + return false; + } else { + Iterator iterator = list.iterator(); + + while (iterator.hasNext()) { + EntityIronGolem entityirongolem = iterator.next(); + + if (entityirongolem.cm() > 0) { + this.b = entityirongolem; + break; + } + } + + return this.b != null; + } + } + } + + public boolean b() { + return this.b.cm() > 0; + } + + public void c() { + this.c = this.a.bc().nextInt(320); + this.d = false; + this.b.getNavigation().n(); + } + + public void d() { + this.b = null; + this.a.getNavigation().n(); + } + + public void e() { + this.a.getControllerLook().a(this.b, 30.0F, 30.0F); + if (this.b.cm() == this.c) { + this.a.getNavigation().a(this.b, 0.5D); + this.d = true; + } + + if (this.d && this.a.h(this.b) < 4.0D) { + this.b.a(false); + this.a.getNavigation().n(); + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalTame.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalTame.java new file mode 100644 index 0000000..de18733 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalTame.java @@ -0,0 +1,75 @@ +package net.minecraft.server; + +import dev.azurite.spigot.pathsearch.PositionPathSearchType; + +public class PathfinderGoalTame extends PathfinderGoal { + + private final EntityHorse entity; + private final double b; + private double c; + private double d; + private double e; + + public PathfinderGoalTame(EntityHorse entityhorse, double d0) { + this.entity = entityhorse; + this.b = d0; + this.a(1); + } + + public boolean a() { + if (!this.entity.isTame() && this.entity.passenger != null) { + Vec3D vec3d = RandomPositionGenerator.a(this.entity, 5, 4); + + if (vec3d == null) { + return false; + } else { + this.c = vec3d.a; + this.d = vec3d.b; + this.e = vec3d.c; + return true; + } + } else { + return false; + } + } + + public void c() { + this.entity.getNavigation().a(this.c, this.d, this.e, this.b, PositionPathSearchType.TAME); // Migot + } + + public boolean b() { + return !this.entity.getNavigation().m() && this.entity.passenger != null; + } + + public void e() { + if (this.entity.bc().nextInt(50) == 0) { + if (this.entity.passenger instanceof EntityHuman) { + int i = this.entity.getTemper(); + int j = this.entity.getMaxDomestication(); + + // CraftBukkit - fire EntityTameEvent + if (j > 0 && this.entity.bc().nextInt(j) < i && !org.bukkit.craftbukkit.event.CraftEventFactory.callEntityTameEvent(this.entity, (EntityHuman) this.entity.passenger).isCancelled() && this.entity.passenger instanceof EntityHuman) { + this.entity.h((EntityHuman) this.entity.passenger); + this.entity.world.broadcastEntityEffect(this.entity, (byte) 7); + return; + } + + this.entity.u(5); + } + + // CraftBukkit start - Handle dismounting to account for VehicleExitEvent being fired. + if (this.entity.passenger != null) { + this.entity.passenger.mount(null); + // If the entity still has a passenger, then a plugin cancelled the event. + if (this.entity.passenger != null) { + return; + } + } + // this.entity.passenger = null; + // CraftBukkit end + this.entity.cW(); + this.entity.world.broadcastEntityEffect(this.entity, (byte) 6); + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalTarget.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalTarget.java new file mode 100644 index 0000000..b00a338 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalTarget.java @@ -0,0 +1,147 @@ +package net.minecraft.server; + +import org.apache.commons.lang3.StringUtils; + +public abstract class PathfinderGoalTarget extends PathfinderGoal { + + protected final EntityCreature e; + protected boolean f; + private final boolean a; + private int b; + private int c; + private int d; + + public PathfinderGoalTarget(EntityCreature entitycreature, boolean flag) { + this(entitycreature, flag, false); + } + + public PathfinderGoalTarget(EntityCreature entitycreature, boolean flag, boolean flag1) { + this.e = entitycreature; + this.f = flag; + this.a = flag1; + } + + public boolean b() { + EntityLiving entityliving = this.e.getGoalTarget(); + + if (entityliving == null) { + return false; + } else if (!entityliving.isAlive()) { + return false; + } else { + ScoreboardTeamBase scoreboardteambase = this.e.getScoreboardTeam(); + ScoreboardTeamBase scoreboardteambase1 = entityliving.getScoreboardTeam(); + + if (scoreboardteambase != null && scoreboardteambase1 == scoreboardteambase) { + return false; + } else { + double d0 = this.f(); + + if (this.e.h(entityliving) > d0 * d0) { + return false; + } else { + if (this.f) { + if (this.e.getEntitySenses().a(entityliving)) { + this.d = 0; + } else if (++this.d > 60) { + return false; + } + } + + return !(entityliving instanceof EntityHuman) || !((EntityHuman) entityliving).abilities.isInvulnerable; + } + } + } + } + + protected double f() { + AttributeInstance attributeinstance = this.e.getAttributeInstance(GenericAttributes.FOLLOW_RANGE); + + return attributeinstance == null ? 16.0D : attributeinstance.getValue(); + } + + public void c() { + this.b = 0; + this.c = 0; + this.d = 0; + } + + public void d() { + this.e.setGoalTarget(null); + } + + public static boolean a(EntityInsentient entityinsentient, EntityLiving entityliving, boolean flag, boolean flag1) { + if (entityliving == null) { + return false; + } else if (entityliving == entityinsentient) { + return false; + } else if (!entityliving.isAlive()) { + return false; + } else if (!entityinsentient.a(entityliving.getClass())) { + return false; + } else { + ScoreboardTeamBase scoreboardteambase = entityinsentient.getScoreboardTeam(); + ScoreboardTeamBase scoreboardteambase1 = entityliving.getScoreboardTeam(); + + if (scoreboardteambase != null && scoreboardteambase1 == scoreboardteambase) { + return false; + } else { + if (entityinsentient instanceof EntityOwnable && StringUtils.isNotEmpty(((EntityOwnable) entityinsentient).getOwnerUUID())) { + if (entityliving instanceof EntityOwnable && ((EntityOwnable) entityinsentient).getOwnerUUID().equals(((EntityOwnable) entityliving).getOwnerUUID())) { + return false; + } + + if (entityliving == ((EntityOwnable) entityinsentient).getOwner()) { + return false; + } + } else if (entityliving instanceof EntityHuman && !flag && ((EntityHuman) entityliving).abilities.isInvulnerable) { + return false; + } + + return !flag1 || entityinsentient.getEntitySenses().a(entityliving); + } + } + } + + protected boolean a(EntityLiving entityliving, boolean flag) { + if (!a(this.e, entityliving, flag, this.f)) { + return false; + } else if (!this.e.e(new BlockPosition(entityliving))) { + return false; + } else { + if (this.a) { + if (--this.c <= 0) { + this.b = 0; + } + + if (this.b == 0) { + this.b = this.a(entityliving) ? 1 : 2; + } + + return this.b != 2; + } + + return true; + } + } + + private boolean a(EntityLiving entityliving) { + this.c = 10 + this.e.bc().nextInt(5); + PathEntity pathentity = this.e.getNavigation().a(entityliving); + + if (pathentity == null) { + return false; + } else { + PathPoint pathpoint = pathentity.c(); + + if (pathpoint == null) { + return false; + } else { + int i = pathpoint.a - MathHelper.floor(entityliving.locX); + int j = pathpoint.c - MathHelper.floor(entityliving.locZ); + + return (double) (i * i + j * j) <= 2.25D; + } + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalTargetNearestPlayer.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalTargetNearestPlayer.java new file mode 100644 index 0000000..fa77517 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalTargetNearestPlayer.java @@ -0,0 +1,108 @@ +package net.minecraft.server; + +import com.google.common.base.Predicate; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.util.List; + +public class PathfinderGoalTargetNearestPlayer extends PathfinderGoal { + + private static final Logger a = LogManager.getLogger(); + private final EntityInsentient b; + private final Predicate c; + private final PathfinderGoalNearestAttackableTarget.DistanceComparator d; + private EntityLiving e; + + public PathfinderGoalTargetNearestPlayer(EntityInsentient entityinsentient) { + this.b = entityinsentient; + if (entityinsentient instanceof EntityCreature) { + PathfinderGoalTargetNearestPlayer.a.warn("Use NearestAttackableTargetGoal.class for PathfinerMob mobs!"); + } + + this.c = new Predicate() { + public boolean a(Entity entity) { + if (!(entity instanceof EntityHuman)) { + return false; + } else if (((EntityHuman) entity).abilities.isInvulnerable) { + return false; + } else { + double d0 = PathfinderGoalTargetNearestPlayer.this.f(); + + if (entity.isSneaking()) { + d0 *= 0.800000011920929D; + } + + if (entity.isInvisible()) { + float f = ((EntityHuman) entity).bY(); + + if (f < 0.1F) { + f = 0.1F; + } + + d0 *= 0.7F * f; + } + + return !((double) entity.g(PathfinderGoalTargetNearestPlayer.this.b) > d0) && PathfinderGoalTarget.a(PathfinderGoalTargetNearestPlayer.this.b, (EntityLiving) entity, false, true); + } + } + + public boolean apply(Object object) { + return this.a((Entity) object); + } + }; + this.d = new PathfinderGoalNearestAttackableTarget.DistanceComparator(entityinsentient); + } + + public boolean a() { + double d0 = this.f(); + List list = this.b.world.a(EntityHuman.class, this.b.getBoundingBox().grow(d0, 4.0D, d0), this.c); + + list.sort(this.d); + if (list.isEmpty()) { + return false; + } else { + this.e = list.get(0); + return true; + } + } + + public boolean b() { + EntityLiving entityliving = this.b.getGoalTarget(); + + if (entityliving == null) { + return false; + } else if (!entityliving.isAlive()) { + return false; + } else if (entityliving instanceof EntityHuman && ((EntityHuman) entityliving).abilities.isInvulnerable) { + return false; + } else { + ScoreboardTeamBase scoreboardteambase = this.b.getScoreboardTeam(); + ScoreboardTeamBase scoreboardteambase1 = entityliving.getScoreboardTeam(); + + if (scoreboardteambase != null && scoreboardteambase1 == scoreboardteambase) { + return false; + } else { + double d0 = this.f(); + + return !(this.b.h(entityliving) > d0 * d0) && (!(entityliving instanceof EntityPlayer) || !((EntityPlayer) entityliving).playerInteractManager.isCreative()); + } + } + } + + public void c() { + this.b.setGoalTarget(this.e, org.bukkit.event.entity.EntityTargetEvent.TargetReason.CLOSEST_PLAYER, true); // CraftBukkit - added reason + super.c(); + } + + public void d() { + this.b.setGoalTarget(null); + super.c(); + } + + protected double f() { + AttributeInstance attributeinstance = this.b.getAttributeInstance(GenericAttributes.FOLLOW_RANGE); + + return attributeinstance == null ? 16.0D : attributeinstance.getValue(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalTempt.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalTempt.java new file mode 100644 index 0000000..82d45fc --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalTempt.java @@ -0,0 +1,99 @@ +package net.minecraft.server; + +public class PathfinderGoalTempt extends PathfinderGoal { + + private final EntityCreature a; + private final double b; + private double c; + private double d; + private double e; + private double f; + private double g; + private EntityHuman h; + private int i; + private boolean j; + private final Item k; + private final boolean l; + private boolean m; + + public PathfinderGoalTempt(EntityCreature entitycreature, double d0, Item item, boolean flag) { + this.a = entitycreature; + this.b = d0; + this.k = item; + this.l = flag; + this.a(3); + if (!(entitycreature.getNavigation() instanceof Navigation)) { + throw new IllegalArgumentException("Unsupported mob type for TemptGoal"); + } + } + + public boolean a() { + if (this.i > 0) { + --this.i; + return false; + } else { + this.h = this.a.world.findNearbyPlayer(this.a, 10.0D); + if (this.h == null) { + return false; + } else { + ItemStack itemstack = this.h.bZ(); + + return itemstack != null && itemstack.getItem() == this.k; + } + } + } + + public boolean b() { + if (this.l) { + if (this.a.h(this.h) < 36.0D) { + if (this.h.e(this.c, this.d, this.e) > 0.010000000000000002D) { + return false; + } + + if (Math.abs((double) this.h.pitch - this.f) > 5.0D || Math.abs((double) this.h.yaw - this.g) > 5.0D) { + return false; + } + } else { + this.c = this.h.locX; + this.d = this.h.locY; + this.e = this.h.locZ; + } + + this.f = this.h.pitch; + this.g = this.h.yaw; + } + + return this.a(); + } + + public void c() { + this.c = this.h.locX; + this.d = this.h.locY; + this.e = this.h.locZ; + this.j = true; + this.m = ((Navigation) this.a.getNavigation()).e(); + ((Navigation) this.a.getNavigation()).a(false); + } + + public void d() { + this.h = null; + this.a.getNavigation().n(); + this.i = 100; + this.j = false; + ((Navigation) this.a.getNavigation()).a(this.m); + } + + public void e() { + this.a.getControllerLook().a(this.h, 30.0F, (float) this.a.bQ()); + if (this.a.h(this.h) < 6.25D) { + this.a.getNavigation().n(); + } else { + this.a.getNavigation().a(this.h, this.b); + } + + } + + public boolean f() { + return this.j; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalTradeWithPlayer.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalTradeWithPlayer.java new file mode 100644 index 0000000..d1a5003 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalTradeWithPlayer.java @@ -0,0 +1,35 @@ +package net.minecraft.server; + +public class PathfinderGoalTradeWithPlayer extends PathfinderGoal { + + private final EntityVillager a; + + public PathfinderGoalTradeWithPlayer(EntityVillager entityvillager) { + this.a = entityvillager; + this.a(5); + } + + public boolean a() { + if (!this.a.isAlive()) { + return false; + } else if (this.a.V()) { + return false; + } else if (!this.a.onGround) { + return false; + } else if (this.a.velocityChanged) { + return false; + } else { + EntityHuman entityhuman = this.a.v_(); + + return entityhuman != null && (!(this.a.h(entityhuman) > 16.0D) && entityhuman.activeContainer != null); + } + } + + public void c() { + this.a.getNavigation().n(); + } + + public void d() { + this.a.a_((EntityHuman) null); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalVillagerFarm.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalVillagerFarm.java new file mode 100644 index 0000000..84814b3 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderGoalVillagerFarm.java @@ -0,0 +1,109 @@ +package net.minecraft.server; + +public class PathfinderGoalVillagerFarm extends PathfinderGoalGotoTarget { + + private final EntityVillager c; + private boolean d; + private boolean e; + private int f; + + public PathfinderGoalVillagerFarm(EntityVillager entityvillager, double d0) { + super(entityvillager, d0, 16); + this.c = entityvillager; + } + + public boolean a() { + if (this.a <= 0) { + if (!this.c.world.getGameRules().getBoolean("mobGriefing")) { + return false; + } + + this.f = -1; + this.d = this.c.cu(); + this.e = this.c.ct(); + } + + return super.a(); + } + + public boolean b() { + return this.f >= 0 && super.b(); + } + + public void c() { + super.c(); + } + + public void d() { + super.d(); + } + + public void e() { + super.e(); + this.c.getControllerLook().a((double) this.b.getX() + 0.5D, this.b.getY() + 1, (double) this.b.getZ() + 0.5D, 10.0F, (float) this.c.bQ()); + if (this.f()) { + World world = this.c.world; + BlockPosition blockposition = this.b.up(); + IBlockData iblockdata = world.getType(blockposition); + Block block = iblockdata.getBlock(); + + if (this.f == 0 && block instanceof BlockCrops && iblockdata.get(BlockCrops.AGE) == 7) { + world.setAir(blockposition, true); + } else if (this.f == 1 && block == Blocks.AIR) { + InventorySubcontainer inventorysubcontainer = this.c.cq(); + + for (int i = 0; i < inventorysubcontainer.getSize(); ++i) { + ItemStack itemstack = inventorysubcontainer.getItem(i); + boolean flag = false; + + if (itemstack != null) { + if (itemstack.getItem() == Items.WHEAT_SEEDS) { + world.setTypeAndData(blockposition, Blocks.WHEAT.getBlockData(), 3); + flag = true; + } else if (itemstack.getItem() == Items.POTATO) { + world.setTypeAndData(blockposition, Blocks.POTATOES.getBlockData(), 3); + flag = true; + } else if (itemstack.getItem() == Items.CARROT) { + world.setTypeAndData(blockposition, Blocks.CARROTS.getBlockData(), 3); + flag = true; + } + } + + if (flag) { + --itemstack.count; + if (itemstack.count <= 0) { + inventorysubcontainer.setItem(i, null); + } + break; + } + } + } + + this.f = -1; + this.a = 10; + } + + } + + protected boolean a(World world, BlockPosition blockposition) { + Block block = world.getType(blockposition).getBlock(); + + if (block == Blocks.FARMLAND) { + blockposition = blockposition.up(); + IBlockData iblockdata = world.getType(blockposition); + + block = iblockdata.getBlock(); + if (block instanceof BlockCrops && iblockdata.get(BlockCrops.AGE) == 7 && this.e && (this.f == 0 || this.f < 0)) { + this.f = 0; + return true; + } + + if (block == Blocks.AIR && this.d && (this.f == 1 || this.f < 0)) { + this.f = 1; + return true; + } + } + + return false; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderNormal.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderNormal.java new file mode 100644 index 0000000..89a6248 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderNormal.java @@ -0,0 +1,220 @@ +package net.minecraft.server; + +public class PathfinderNormal extends PathfinderAbstract { + + private boolean f; + private boolean g; + private boolean h; + private boolean i; + private boolean j; + + public PathfinderNormal() { + } + + public void a(IBlockAccess iblockaccess, Entity entity) { + super.a(iblockaccess, entity); + this.j = this.h; + } + + public void a() { + super.a(); + this.h = this.j; + } + + public PathPoint a(Entity entity) { + int i; + + if (this.i && entity.V()) { + i = (int) entity.getBoundingBox().b; + BlockPosition.MutableBlockPosition blockposition_mutableblockposition = new BlockPosition.MutableBlockPosition(MathHelper.floor(entity.locX), i, MathHelper.floor(entity.locZ)); + + for (Block block = this.a.getType(blockposition_mutableblockposition).getBlock(); block == Blocks.FLOWING_WATER || block == Blocks.WATER; block = this.a.getType(blockposition_mutableblockposition).getBlock()) { + ++i; + blockposition_mutableblockposition.c(MathHelper.floor(entity.locX), i, MathHelper.floor(entity.locZ)); + } + + this.h = false; + } else { + i = MathHelper.floor(entity.getBoundingBox().b + 0.5D); + } + + return this.a(MathHelper.floor(entity.getBoundingBox().a), i, MathHelper.floor(entity.getBoundingBox().c)); + } + + public PathPoint a(Entity entity, double d0, double d1, double d2) { + return this.a(MathHelper.floor(d0 - (double) (entity.width / 2.0F)), MathHelper.floor(d1), MathHelper.floor(d2 - (double) (entity.width / 2.0F))); + } + + public int a(PathPoint[] apathpoint, Entity entity, PathPoint pathpoint, PathPoint pathpoint1, float f) { + int i = 0; + byte b0 = 0; + + if (this.a(entity, pathpoint.a, pathpoint.b + 1, pathpoint.c) == 1) { + b0 = 1; + } + + PathPoint pathpoint2 = this.a(entity, pathpoint.a, pathpoint.b, pathpoint.c + 1, b0); + PathPoint pathpoint3 = this.a(entity, pathpoint.a - 1, pathpoint.b, pathpoint.c, b0); + PathPoint pathpoint4 = this.a(entity, pathpoint.a + 1, pathpoint.b, pathpoint.c, b0); + PathPoint pathpoint5 = this.a(entity, pathpoint.a, pathpoint.b, pathpoint.c - 1, b0); + + if (pathpoint2 != null && !pathpoint2.i && pathpoint2.a(pathpoint1) < f) { + apathpoint[i++] = pathpoint2; + } + + if (pathpoint3 != null && !pathpoint3.i && pathpoint3.a(pathpoint1) < f) { + apathpoint[i++] = pathpoint3; + } + + if (pathpoint4 != null && !pathpoint4.i && pathpoint4.a(pathpoint1) < f) { + apathpoint[i++] = pathpoint4; + } + + if (pathpoint5 != null && !pathpoint5.i && pathpoint5.a(pathpoint1) < f) { + apathpoint[i++] = pathpoint5; + } + + return i; + } + + private PathPoint a(Entity entity, int i, int j, int k, int l) { + PathPoint pathpoint = null; + int i1 = this.a(entity, i, j, k); + + if (i1 == 2) { + return this.a(i, j, k); + } else { + if (i1 == 1) { + pathpoint = this.a(i, j, k); + } + + if (pathpoint == null && l > 0 && i1 != -3 && i1 != -4 && this.a(entity, i, j + l, k) == 1) { + pathpoint = this.a(i, j + l, k); + j += l; + } + + if (pathpoint != null) { + int j1 = 0; + + int k1; + + for (k1 = 0; j > 0; pathpoint = this.a(i, j, k)) { + k1 = this.a(entity, i, j - 1, k); + if (this.h && k1 == -1) { + return null; + } + + if (k1 != 1) { + break; + } + + if (j1++ >= entity.aE()) { + return null; + } + + --j; + if (j <= 0) { + return null; + } + } + + if (k1 == -2) { + return null; + } + } + + return pathpoint; + } + } + + private int a(Entity entity, int i, int j, int k) { + return a(this.a, entity, i, j, k, this.c, this.d, this.e, this.h, this.g, this.f); + } + + public static int a(IBlockAccess iblockaccess, Entity entity, int i, int j, int k, int l, int i1, int j1, boolean flag, boolean flag1, boolean flag2) { + boolean flag3 = false; + BlockPosition.MutableBlockPosition blockposition_mutableblockposition = new BlockPosition.MutableBlockPosition(); + + for (int k1 = i; k1 < i + l; ++k1) { + for (int l1 = j; l1 < j + i1; ++l1) { + for (int i2 = k; i2 < k + j1; ++i2) { + Block block = iblockaccess.getType(k1, l1, i2).getBlock(); + + if (block.getMaterial() != Material.AIR) { + if (block != Blocks.TRAPDOOR && block != Blocks.IRON_TRAPDOOR) { + if (block != Blocks.FLOWING_WATER && block != Blocks.WATER) { + if (!flag2 && block instanceof BlockDoor && block.getMaterial() == Material.WOOD) { + return 0; + } + } else { + if (flag) { + return -1; + } + + flag3 = true; + } + } else { + flag3 = true; + } + + if (block instanceof BlockMinecartTrackAbstract) { // PaperSpigot - Pathfinder optimizations + if (iblockaccess.getType(blockposition_mutableblockposition).getBlock() instanceof BlockMinecartTrackAbstract) { // Migot - use @iblockaccess instead of entity.world + if (!(iblockaccess.getType(blockposition_mutableblockposition).getBlock() instanceof BlockMinecartTrackAbstract) && !(iblockaccess.getType(blockposition_mutableblockposition.down()).getBlock() instanceof BlockMinecartTrackAbstract)) { // Migot - use @iblockaccess instead of entity.world + return -3; + } + } + } else if (!block.b(iblockaccess, blockposition_mutableblockposition.c(k1, l1, i2)) && (!flag1 || !(block instanceof BlockDoor) || block.getMaterial() != Material.WOOD)) { + if (block instanceof BlockFence || block instanceof BlockFenceGate || block instanceof BlockCobbleWall) { + return -3; + } + + if (block == Blocks.TRAPDOOR || block == Blocks.IRON_TRAPDOOR) { + return -4; + } + + Material material = block.getMaterial(); + + if (material != Material.LAVA) { + return 0; + } + + if (!entity.ab(iblockaccess)) { // Migot + return -2; + } + } + } + } + } + } + + return flag3 ? 2 : 1; + } + + public void a(boolean flag) { + this.f = flag; + } + + public void b(boolean flag) { + this.g = flag; + } + + public void c(boolean flag) { + this.h = flag; + } + + public void d(boolean flag) { + this.i = flag; + } + + public boolean b() { + return this.f; + } + + public boolean d() { + return this.i; + } + + public boolean e() { + return this.h; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PathfinderWater.java b/azurite-server/src/main/java/net/minecraft/server/PathfinderWater.java new file mode 100644 index 0000000..4dc9dd6 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PathfinderWater.java @@ -0,0 +1,61 @@ +package net.minecraft.server; + +public class PathfinderWater extends PathfinderAbstract { + + public PathfinderWater() { + } + + public void a(IBlockAccess iblockaccess, Entity entity) { + super.a(iblockaccess, entity); + } + + public void a() { + super.a(); + } + + public PathPoint a(Entity entity) { + return this.a(MathHelper.floor(entity.getBoundingBox().a), MathHelper.floor(entity.getBoundingBox().b + 0.5D), MathHelper.floor(entity.getBoundingBox().c)); + } + + public PathPoint a(Entity entity, double d0, double d1, double d2) { + return this.a(MathHelper.floor(d0 - (double) (entity.width / 2.0F)), MathHelper.floor(d1 + 0.5D), MathHelper.floor(d2 - (double) (entity.width / 2.0F))); + } + + public int a(PathPoint[] apathpoint, Entity entity, PathPoint pathpoint, PathPoint pathpoint1, float f) { + int i = 0; + EnumDirection[] aenumdirection = EnumDirection.values(); + int j = aenumdirection.length; + + for (EnumDirection enumdirection : aenumdirection) { + PathPoint pathpoint2 = this.a(entity, pathpoint.a + enumdirection.getAdjacentX(), pathpoint.b + enumdirection.getAdjacentY(), pathpoint.c + enumdirection.getAdjacentZ()); + + if (pathpoint2 != null && !pathpoint2.i && pathpoint2.a(pathpoint1) < f) { + apathpoint[i++] = pathpoint2; + } + } + + return i; + } + + private PathPoint a(Entity entity, int i, int j, int k) { + int l = this.b(entity, i, j, k); + + return l == -1 ? this.a(i, j, k) : null; + } + + private int b(Entity entity, int i, int j, int k) { + for (int l = i; l < i + this.c; ++l) { + for (int i1 = j; i1 < j + this.d; ++i1) { + for (int j1 = k; j1 < k + this.e; ++j1) { + Block block = this.a.getType(l, i1, j1).getBlock(); + + if (block.getMaterial() != Material.WATER) { + return 0; + } + } + } + } + + return -1; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PersistentBase.java b/azurite-server/src/main/java/net/minecraft/server/PersistentBase.java new file mode 100644 index 0000000..d88fa51 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PersistentBase.java @@ -0,0 +1,27 @@ +package net.minecraft.server; + +public abstract class PersistentBase { + + public final String id; + private boolean b; + + public PersistentBase(String s) { + this.id = s; + } + + public abstract void a(NBTTagCompound nbttagcompound); + + public abstract void b(NBTTagCompound nbttagcompound); + + public void c() { + this.a(true); + } + + public void a(boolean flag) { + this.b = flag; + } + + public boolean d() { + return this.b; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PersistentCollection.java b/azurite-server/src/main/java/net/minecraft/server/PersistentCollection.java new file mode 100644 index 0000000..7e87d3a --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PersistentCollection.java @@ -0,0 +1,177 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import dev.azurite.spigot.Azurite; +import dev.azurite.spigot.async.tasks.NBTFileSaveJob; +import dev.azurite.spigot.configs.AzuriteConfig; + +import java.io.*; +import java.nio.file.Files; +import java.util.List; +import java.util.Map; + +public class PersistentCollection { + + private final IDataManager b; + protected Map a = Maps.newHashMap(); + public List c = Lists.newArrayList(); // Spigot + private final Map d = Maps.newHashMap(); + + public PersistentCollection(IDataManager idatamanager) { + this.b = idatamanager; + this.b(); + } + + public PersistentBase get(Class oclass, String s) { + PersistentBase persistentbase = this.a.get(s); + + if (persistentbase == null) { + if (this.b != null) { + try { + File file = this.b.getDataFile(s); + + if (file != null && file.exists()) { + try { + persistentbase = oclass.getConstructor(String.class).newInstance(s); + } catch (Exception exception) { + throw new RuntimeException("Failed to instantiate " + oclass.toString(), exception); + } + + FileInputStream fileinputstream = new FileInputStream(file); + NBTTagCompound nbttagcompound = NBTCompressedStreamTools.a(fileinputstream); + + fileinputstream.close(); + persistentbase.a(nbttagcompound.getCompound("data")); + } + } catch (Exception exception1) { + exception1.printStackTrace(); + } + } + + if (persistentbase != null) { + this.a.put(s, persistentbase); + this.c.add(persistentbase); + } + + } + return persistentbase; + } + + public void a(String s, PersistentBase persistentbase) { + if (this.a.containsKey(s)) { + this.c.remove(this.a.remove(s)); + } + + this.a.put(s, persistentbase); + this.c.add(persistentbase); + } + + public void a() { + for (PersistentBase persistentbase : this.c) { + if (persistentbase != null && persistentbase.d()) { + this.a(persistentbase); + persistentbase.a(false); + } + } + + } + + private void a(PersistentBase persistentbase) { + if (this.b != null) { + try { + File file = this.b.getDataFile(persistentbase.id); + + if (file != null) { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + + persistentbase.b(nbttagcompound); + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + + nbttagcompound1.set("data", nbttagcompound); + + NBTTagCompound compound = (NBTTagCompound) (nbttagcompound1.clone()); + this.saveNBTStorage(compound, file); + } + } catch (Exception exception) { + exception.printStackTrace(); + } + } + } + + private void b() { + try { + this.d.clear(); + if (this.b == null) { + return; + } + + File file = this.b.getDataFile("idcounts"); + + if (file != null && file.exists()) { + DataInputStream datainputstream = new DataInputStream(Files.newInputStream(file.toPath())); + NBTTagCompound nbttagcompound = NBTCompressedStreamTools.a(datainputstream); + + datainputstream.close(); + + for (String s : nbttagcompound.c()) { + NBTBase nbtbase = nbttagcompound.get(s); + + if (nbtbase instanceof NBTTagShort) { + NBTTagShort nbttagshort = (NBTTagShort) nbtbase; + short short0 = nbttagshort.e(); + + this.d.put(s, short0); + } + } + } + } catch (Exception exception) { + exception.printStackTrace(); + } + } + + public int a(String s) { + Short oshort = this.d.get(s); + + if (oshort == null) { + oshort = (short) 0; + } else { + oshort = (short) (oshort + 1); + } + + this.d.put(s, oshort); + if (this.b != null) { + try { + File file = this.b.getDataFile("idcounts"); + + if (file != null) { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + + for (String s1 : this.d.keySet()) { + short short0 = this.d.get(s1); + + nbttagcompound.setShort(s1, short0); + } + + DataOutputStream dataoutputstream = new DataOutputStream(Files.newOutputStream(file.toPath())); + + NBTCompressedStreamTools.a(nbttagcompound, (DataOutput) dataoutputstream); + dataoutputstream.close(); + } + } catch (Exception exception) { + exception.printStackTrace(); + } + + } + return oshort; + } + + // Azurite - Toggleable async save nbt storage + private void saveNBTStorage(NBTTagCompound compound, File file) { + if (AzuriteConfig.asyncNBTFileSave.getValue()) { + Azurite.getInstance().getThreadingManager().getAsyncExecutor().queueFileTask(new NBTFileSaveJob(compound, file)); + return; + } + new NBTFileSaveJob(compound, file).run(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PersistentScoreboard.java b/azurite-server/src/main/java/net/minecraft/server/PersistentScoreboard.java new file mode 100644 index 0000000..8f2c14c --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PersistentScoreboard.java @@ -0,0 +1,252 @@ +package net.minecraft.server; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.util.Collection; + +public class PersistentScoreboard extends PersistentBase { + + private static final Logger b = LogManager.getLogger(); + private Scoreboard c; + private NBTTagCompound d; + + public PersistentScoreboard() { + this("scoreboard"); + } + + public PersistentScoreboard(String s) { + super(s); + } + + public void a(Scoreboard scoreboard) { + this.c = scoreboard; + if (this.d != null) { + this.a(this.d); + } + + } + + public void a(NBTTagCompound nbttagcompound) { + if (this.c == null) { + this.d = nbttagcompound; + } else { + this.b(nbttagcompound.getList("Objectives", 10)); + this.c(nbttagcompound.getList("PlayerScores", 10)); + if (nbttagcompound.hasKeyOfType("DisplaySlots", 10)) { + this.c(nbttagcompound.getCompound("DisplaySlots")); + } + + if (nbttagcompound.hasKeyOfType("Teams", 9)) { + this.a(nbttagcompound.getList("Teams", 10)); + } + + } + } + + protected void a(NBTTagList nbttaglist) { + for (int i = 0; i < nbttaglist.size(); ++i) { + NBTTagCompound nbttagcompound = nbttaglist.get(i); + String s = nbttagcompound.getString("Name"); + if (s.length() > 16) { + s = s.substring(0, 16); + } + + ScoreboardTeam scoreboardteam = this.c.createTeam(s); + String s1 = nbttagcompound.getString("DisplayName"); + + if (s1.length() > 32) { + s1 = s1.substring(0, 32); + } + + scoreboardteam.setDisplayName(s1); + if (nbttagcompound.hasKeyOfType("TeamColor", 8)) { + scoreboardteam.a(EnumChatFormat.b(nbttagcompound.getString("TeamColor"))); + } + + scoreboardteam.setPrefix(nbttagcompound.getString("Prefix")); + scoreboardteam.setSuffix(nbttagcompound.getString("Suffix")); + if (nbttagcompound.hasKeyOfType("AllowFriendlyFire", 99)) { + scoreboardteam.setAllowFriendlyFire(nbttagcompound.getBoolean("AllowFriendlyFire")); + } + + if (nbttagcompound.hasKeyOfType("SeeFriendlyInvisibles", 99)) { + scoreboardteam.setCanSeeFriendlyInvisibles(nbttagcompound.getBoolean("SeeFriendlyInvisibles")); + } + + ScoreboardTeamBase.EnumNameTagVisibility scoreboardteambase_enumnametagvisibility; + + if (nbttagcompound.hasKeyOfType("NameTagVisibility", 8)) { + scoreboardteambase_enumnametagvisibility = ScoreboardTeamBase.EnumNameTagVisibility.a(nbttagcompound.getString("NameTagVisibility")); + if (scoreboardteambase_enumnametagvisibility != null) { + scoreboardteam.setNameTagVisibility(scoreboardteambase_enumnametagvisibility); + } + } + + if (nbttagcompound.hasKeyOfType("DeathMessageVisibility", 8)) { + scoreboardteambase_enumnametagvisibility = ScoreboardTeamBase.EnumNameTagVisibility.a(nbttagcompound.getString("DeathMessageVisibility")); + if (scoreboardteambase_enumnametagvisibility != null) { + scoreboardteam.b(scoreboardteambase_enumnametagvisibility); + } + } + + this.a(scoreboardteam, nbttagcompound.getList("Players", 8)); + } + + } + + protected void a(ScoreboardTeam scoreboardteam, NBTTagList nbttaglist) { + for (int i = 0; i < nbttaglist.size(); ++i) { + this.c.addPlayerToTeam(nbttaglist.getString(i), scoreboardteam.getName()); + } + + } + + protected void c(NBTTagCompound nbttagcompound) { + for (int i = 0; i < 19; ++i) { + if (nbttagcompound.hasKeyOfType("slot_" + i, 8)) { + this.c.setDisplaySlot(i, c.getObjective(nbttagcompound.getString("slot_" + i))); + } + } + + } + + protected void b(NBTTagList nbttaglist) { + for (int i = 0; i < nbttaglist.size(); ++i) { + NBTTagCompound nbttagcompound = nbttaglist.get(i); + IScoreboardCriteria iscoreboardcriteria = IScoreboardCriteria.criteria.get(nbttagcompound.getString("CriteriaName")); + + if (iscoreboardcriteria != null) { + String s = nbttagcompound.getString("Name"); + if (s.length() > 16) { + s = s.substring(0, 16); + } + + ScoreboardObjective scoreboardobjective = this.c.registerObjective(s, iscoreboardcriteria); + + scoreboardobjective.setDisplayName(nbttagcompound.getString("DisplayName")); + scoreboardobjective.a(IScoreboardCriteria.EnumScoreboardHealthDisplay.a(nbttagcompound.getString("RenderType"))); + } + } + + } + + protected void c(NBTTagList nbttaglist) { + for (int i = 0; i < nbttaglist.size(); ++i) { + NBTTagCompound nbttagcompound = nbttaglist.get(i); + ScoreboardObjective scoreboardobjective = this.c.getObjective(nbttagcompound.getString("Objective")); + String s = nbttagcompound.getString("Name"); + if (s.length() > 40) { + s = s.substring(0, 40); + } + + ScoreboardScore scoreboardscore = this.c.getPlayerScoreForObjective(s, scoreboardobjective); + + scoreboardscore.setScore(nbttagcompound.getInt("Score")); + if (nbttagcompound.hasKey("Locked")) { + scoreboardscore.a(nbttagcompound.getBoolean("Locked")); + } + } + + } + + public void b(NBTTagCompound nbttagcompound) { + if (c == null) { + b.warn("Tried to save scoreboard without having a scoreboard..."); + } else { + nbttagcompound.set("Objectives", b()); + nbttagcompound.set("PlayerScores", e()); + nbttagcompound.set("Teams", a()); + d(nbttagcompound); + } + } + + protected NBTTagList a() { + NBTTagList nbttaglist = new NBTTagList(); + Collection collection = this.c.getTeams(); + + for (ScoreboardTeam scoreboardteam : collection) { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + + nbttagcompound.setString("Name", scoreboardteam.getName()); + nbttagcompound.setString("DisplayName", scoreboardteam.getDisplayName()); + if (scoreboardteam.l().b() >= 0) { + nbttagcompound.setString("TeamColor", scoreboardteam.l().e()); + } + + nbttagcompound.setString("Prefix", scoreboardteam.getPrefix()); + nbttagcompound.setString("Suffix", scoreboardteam.getSuffix()); + nbttagcompound.setBoolean("AllowFriendlyFire", scoreboardteam.allowFriendlyFire()); + nbttagcompound.setBoolean("SeeFriendlyInvisibles", scoreboardteam.canSeeFriendlyInvisibles()); + nbttagcompound.setString("NameTagVisibility", scoreboardteam.getNameTagVisibility().e); + nbttagcompound.setString("DeathMessageVisibility", scoreboardteam.j().e); + NBTTagList nbttaglist1 = new NBTTagList(); + + for (String s : scoreboardteam.getPlayerNameSet()) { + nbttaglist1.add(new NBTTagString(s)); + } + + nbttagcompound.set("Players", nbttaglist1); + nbttaglist.add(nbttagcompound); + } + + return nbttaglist; + } + + protected void d(NBTTagCompound nbttagcompound) { + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + boolean flag = false; + + for (int i = 0; i < 19; ++i) { + ScoreboardObjective scoreboardobjective = this.c.getObjectiveForSlot(i); + + if (scoreboardobjective != null) { + nbttagcompound1.setString("slot_" + i, scoreboardobjective.getName()); + flag = true; + } + } + + if (flag) { + nbttagcompound.set("DisplaySlots", nbttagcompound1); + } + + } + + protected NBTTagList b() { + NBTTagList nbttaglist = new NBTTagList(); + Collection collection = this.c.getObjectives(); + + for (ScoreboardObjective scoreboardobjective : collection) { + if (scoreboardobjective.getCriteria() != null) { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + + nbttagcompound.setString("Name", scoreboardobjective.getName()); + nbttagcompound.setString("CriteriaName", scoreboardobjective.getCriteria().getName()); + nbttagcompound.setString("DisplayName", scoreboardobjective.getDisplayName()); + nbttagcompound.setString("RenderType", scoreboardobjective.e().a()); + nbttaglist.add(nbttagcompound); + } + } + + return nbttaglist; + } + + protected NBTTagList e() { + NBTTagList nbttaglist = new NBTTagList(); + Collection collection = this.c.getScores(); + + for (ScoreboardScore scoreboardscore : collection) { + if (scoreboardscore.getObjective() != null) { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + + nbttagcompound.setString("Name", scoreboardscore.getPlayerName()); + nbttagcompound.setString("Objective", scoreboardscore.getObjective().getName()); + nbttagcompound.setInt("Score", scoreboardscore.getScore()); + nbttagcompound.setBoolean("Locked", scoreboardscore.g()); + nbttaglist.add(nbttagcompound); + } + } + + return nbttaglist; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PersistentStructure.java b/azurite-server/src/main/java/net/minecraft/server/PersistentStructure.java new file mode 100644 index 0000000..6351bb0 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PersistentStructure.java @@ -0,0 +1,30 @@ +package net.minecraft.server; + +public class PersistentStructure extends PersistentBase { + + private NBTTagCompound b = new NBTTagCompound(); + + public PersistentStructure(String s) { + super(s); + } + + public void a(NBTTagCompound nbttagcompound) { + this.b = nbttagcompound.getCompound("Features"); + } + + public void b(NBTTagCompound nbttagcompound) { + nbttagcompound.set("Features", this.b); + } + + public void a(NBTTagCompound nbttagcompound, int i, int j) { + this.b.set(b(i, j), nbttagcompound); + } + + public static String b(int i, int j) { + return "[" + i + "," + j + "]"; + } + + public NBTTagCompound a() { + return this.b; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PersistentVillage.java b/azurite-server/src/main/java/net/minecraft/server/PersistentVillage.java new file mode 100644 index 0000000..9b57924 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PersistentVillage.java @@ -0,0 +1,255 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; + +import java.util.Iterator; +import java.util.List; + +public class PersistentVillage extends PersistentBase { + + private World world; + private final List c = Lists.newArrayList(); + private final List d = Lists.newArrayList(); + private final List villages = Lists.newArrayList(); + private int time; + + public PersistentVillage(String s) { + super(s); + } + + public PersistentVillage(World world) { + super(a(world.worldProvider)); + this.world = world; + this.c(); + } + + public void a(World world) { + this.world = world; + + for (Village village : this.villages) { + village.a(world); + } + + } + + public void a(BlockPosition blockposition) { + if (this.c.size() <= 64) { + if (!this.e(blockposition)) { + this.c.add(blockposition); + } + + } + } + + public void tick() { + ++this.time; + + for (Village village : this.villages) { + village.a(this.time); + } + + this.e(); + this.f(); + this.g(); + if (this.time % 400 == 0) { + this.c(); + } + + } + + private void e() { + Iterator iterator = this.villages.iterator(); + + while (iterator.hasNext()) { + if (iterator.next().g()) { + iterator.remove(); + this.c(); + } + } + + } + + public List getVillages() { + return this.villages; + } + + public Village getClosestVillage(BlockPosition blockposition, int i) { + return getClosestVillage(blockposition.getX(), blockposition.getY(), blockposition.getZ(), i); + } + + public Village getClosestVillage(int x, int y, int z, int i) { + Village village = null; + double d0 = 3.4028234663852886E38D; + + for (Village village1 : this.villages) { + double d1 = village1.a().i(x, y, z); + + if (d1 < d0) { + float f = (float) (i + village1.b()); + + if (d1 <= (double) (f * f)) { + village = village1; + d0 = d1; + } + } + } + + return village; + } + + private void f() { + if (!this.c.isEmpty()) { + this.b(this.c.remove(0)); + } + } + + private void g() { + for (VillageDoor villagedoor : this.d) { + Village village = this.getClosestVillage(villagedoor.d(), 32); + + if (village == null) { + village = new Village(this.world); + this.villages.add(village); + this.c(); + } + + village.a(villagedoor); + } + + this.d.clear(); + } + + private void b(BlockPosition blockposition) { + byte b0 = 16; + byte b1 = 4; + byte b2 = 16; + + for (int i = -b0; i < b0; ++i) { + for (int j = -b1; j < b1; ++j) { + for (int k = -b2; k < b2; ++k) { + BlockPosition blockposition1 = blockposition.a(i, j, k); + + if (this.f(blockposition1)) { + VillageDoor villagedoor = this.c(blockposition1); + + if (villagedoor == null) { + this.d(blockposition1); + } else { + villagedoor.a(this.time); + } + } + } + } + } + + } + + private VillageDoor c(BlockPosition blockposition) { + Iterator iterator = this.d.iterator(); + + VillageDoor villagedoor; + + do { + if (!iterator.hasNext()) { + iterator = this.villages.iterator(); + + VillageDoor villagedoor1; + + do { + if (!iterator.hasNext()) { + return null; + } + + villagedoor1 = ((Village) iterator.next()).e(blockposition); + } while (villagedoor1 == null); + + return villagedoor1; + } + + villagedoor = (VillageDoor) iterator.next(); + } while (villagedoor.d().getX() != blockposition.getX() || villagedoor.d().getZ() != blockposition.getZ() || Math.abs(villagedoor.d().getY() - blockposition.getY()) > 1); + + return villagedoor; + } + + private void d(BlockPosition blockposition) { + EnumDirection enumdirection = BlockDoor.h(this.world, blockposition); + EnumDirection enumdirection1 = enumdirection.opposite(); + int i = this.a(blockposition, enumdirection, 5); + int j = this.a(blockposition, enumdirection1, i + 1); + + if (i != j) { + this.d.add(new VillageDoor(blockposition, i < j ? enumdirection : enumdirection1, this.time)); + } + + } + + private int a(BlockPosition blockposition, EnumDirection enumdirection, int i) { + int j = 0; + + for (int k = 1; k <= 5; ++k) { + if (this.world.i(blockposition.shift(enumdirection, k))) { + ++j; + if (j >= i) { + return j; + } + } + } + + return j; + } + + private boolean e(BlockPosition blockposition) { + Iterator iterator = this.c.iterator(); + + BlockPosition blockposition1; + + do { + if (!iterator.hasNext()) { + return false; + } + + blockposition1 = iterator.next(); + } while (!blockposition1.equals(blockposition)); + + return true; + } + + private boolean f(BlockPosition blockposition) { + IBlockData iblockdata = this.world.getTypeIfLoaded(blockposition.getX(), blockposition.getY(), blockposition.getZ()); + if (iblockdata == null) + return false; + Block block = iblockdata.getBlock(); + return block instanceof BlockDoor && block.getMaterial() == Material.WOOD; + } + + public void a(NBTTagCompound nbttagcompound) { + this.time = nbttagcompound.getInt("Tick"); + NBTTagList nbttaglist = nbttagcompound.getList("Villages", 10); + + for (int i = 0; i < nbttaglist.size(); ++i) { + Village village = new Village(); + + village.a(nbttaglist.get(i)); + this.villages.add(village); + } + + } + + public void b(NBTTagCompound nbttagcompound) { + nbttagcompound.setInt("Tick", this.time); + NBTTagList nbttaglist = new NBTTagList(); + + for (Village village : this.villages) { + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + village.b(nbttagcompound1); + nbttaglist.add(nbttagcompound1); + } + + nbttagcompound.set("Villages", nbttaglist); + } + + public static String a(WorldProvider worldprovider) { + return "villages" + worldprovider.getSuffix(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PistonExtendsChecker.java b/azurite-server/src/main/java/net/minecraft/server/PistonExtendsChecker.java new file mode 100644 index 0000000..4d49320 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PistonExtendsChecker.java @@ -0,0 +1,129 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; +import dev.azurite.spigot.configs.AzuriteConfig; + +import java.util.ArrayList; +import java.util.List; + +public class PistonExtendsChecker { + private final World a; + private final BlockPosition b, c; + private final EnumDirection d; + private final List e = Lists.newArrayList(); + private final List f = Lists.newArrayList(); + + public PistonExtendsChecker(World paramWorld, BlockPosition paramBlockPosition, EnumDirection paramEnumDirection, boolean paramBoolean) { + this.a = paramWorld; + this.b = paramBlockPosition; + if (paramBoolean) { + this.d = paramEnumDirection; + this.c = paramBlockPosition.shift(paramEnumDirection); + } else { + this.d = paramEnumDirection.opposite(); + this.c = paramBlockPosition.shift(paramEnumDirection, 2); + } + } + + public boolean a() { + this.e.clear(); + this.f.clear(); + Block block = this.a.getType(this.c).getBlock(); + if (!BlockPiston.a(block, this.a, this.c, this.d, false)) { + if (block.k() != 1) + return false; + this.f.add(this.c); + return true; + } + if (!a(this.c)) + return false; + for (byte b = 0; b < this.e.size(); b++) { + BlockPosition blockPosition = this.e.get(b); + if (this.a.getType(blockPosition).getBlock() == Blocks.SLIME && + !b(blockPosition)) + return false; + } + return true; + } + + private boolean a(BlockPosition paramBlockPosition) { + Block block = this.a.getType(paramBlockPosition).getBlock(); + if (block.getMaterial() == Material.AIR || !BlockPiston.a(block, this.a, paramBlockPosition, this.d, false) || paramBlockPosition.equals(this.b) || this.e.contains(paramBlockPosition)) + return true; + byte b1 = 1; + if (b1 + this.e.size() > AzuriteConfig.pistonMaxBlockPush.getValue()) + return false; + while (block == Blocks.SLIME) { + BlockPosition blockPosition = paramBlockPosition.shift(this.d.opposite(), b1); + block = this.a.getType(blockPosition).getBlock(); + if (block.getMaterial() == Material.AIR || !BlockPiston.a(block, this.a, blockPosition, this.d, false) || blockPosition.equals(this.b)) + break; + b1++; + if (b1 + this.e.size() > AzuriteConfig.pistonMaxBlockPush.getValue()) + return false; + } + byte b2 = 0; + int i; + for (i = b1 - 1; i >= 0; i--) { + this.e.add(paramBlockPosition.shift(this.d.opposite(), i)); + b2++; + } + for (i = 1; ; i++) { + BlockPosition blockPosition = paramBlockPosition.shift(this.d, i); + int j = this.e.indexOf(blockPosition); + if (j > -1) { + a(b2, j); + for (byte b = 0; b <= j + b2; b++) { + BlockPosition blockPosition1 = this.e.get(b); + if (this.a.getType(blockPosition1).getBlock() == Blocks.SLIME && + !b(blockPosition1)) + return false; + } + return true; + } + block = this.a.getType(blockPosition).getBlock(); + if (block.getMaterial() == Material.AIR) + return true; + if (!BlockPiston.a(block, this.a, blockPosition, this.d, true) || blockPosition.equals(this.b)) + return false; + if (block.k() == 1) { + this.f.add(blockPosition); + return true; + } + if (this.e.size() >= AzuriteConfig.pistonMaxBlockPush.getValue()) + return false; + this.e.add(blockPosition); + b2++; + } + } + + private void a(int paramInt1, int paramInt2) { + ArrayList arrayList1 = Lists.newArrayList(); + ArrayList arrayList2 = Lists.newArrayList(); + ArrayList arrayList3 = Lists.newArrayList(); + arrayList1.addAll(this.e.subList(0, paramInt2)); + arrayList2.addAll(this.e.subList(this.e.size() - paramInt1, this.e.size())); + arrayList3.addAll(this.e.subList(paramInt2, this.e.size() - paramInt1)); + this.e.clear(); + this.e.addAll(arrayList1); + this.e.addAll(arrayList2); + this.e.addAll(arrayList3); + } + + private boolean b(BlockPosition paramBlockPosition) { + for (EnumDirection enumDirection : EnumDirection.values()) { + if (enumDirection.k() != this.d.k() && + !a(paramBlockPosition.shift(enumDirection))) + return false; + } + return true; + } + + public List getMovedBlocks() { + return this.e; + } + + public List getBrokenBlocks() { + return this.f; + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/net/minecraft/server/PlayerAbilities.java b/azurite-server/src/main/java/net/minecraft/server/PlayerAbilities.java new file mode 100644 index 0000000..b04b9e6 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PlayerAbilities.java @@ -0,0 +1,55 @@ +package net.minecraft.server; + +public class PlayerAbilities { + + public boolean isInvulnerable; + public boolean isFlying; + public boolean canFly; + public boolean canInstantlyBuild; + public boolean mayBuild = true; + public float flySpeed = 0.05F; + public float walkSpeed = 0.1F; + + public PlayerAbilities() {} + + public void a(NBTTagCompound nbttagcompound) { + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + + nbttagcompound1.setBoolean("invulnerable", this.isInvulnerable); + nbttagcompound1.setBoolean("flying", this.isFlying); + nbttagcompound1.setBoolean("mayfly", this.canFly); + nbttagcompound1.setBoolean("instabuild", this.canInstantlyBuild); + nbttagcompound1.setBoolean("mayBuild", this.mayBuild); + nbttagcompound1.setFloat("flySpeed", this.flySpeed); + nbttagcompound1.setFloat("walkSpeed", this.walkSpeed); + nbttagcompound.set("abilities", nbttagcompound1); + } + + public void b(NBTTagCompound nbttagcompound) { + if (nbttagcompound.hasKeyOfType("abilities", 10)) { + NBTTagCompound nbttagcompound1 = nbttagcompound.getCompound("abilities"); + + this.isInvulnerable = nbttagcompound1.getBoolean("invulnerable"); + this.isFlying = nbttagcompound1.getBoolean("flying"); + this.canFly = nbttagcompound1.getBoolean("mayfly"); + this.canInstantlyBuild = nbttagcompound1.getBoolean("instabuild"); + if (nbttagcompound1.hasKeyOfType("flySpeed", 99)) { + this.flySpeed = nbttagcompound1.getFloat("flySpeed"); + this.walkSpeed = nbttagcompound1.getFloat("walkSpeed"); + } + + if (nbttagcompound1.hasKeyOfType("mayBuild", 1)) { + this.mayBuild = nbttagcompound1.getBoolean("mayBuild"); + } + } + + } + + public float a() { + return this.flySpeed; + } + + public float b() { + return this.walkSpeed; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PlayerCache.java b/azurite-server/src/main/java/net/minecraft/server/PlayerCache.java new file mode 100644 index 0000000..2abacbf --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PlayerCache.java @@ -0,0 +1,18 @@ +package net.minecraft.server; + +import java.util.LinkedHashMap; +import java.util.Map; + +public class PlayerCache extends LinkedHashMap { + + private static final long serialVersionUID = 5272337123874421616L; + + public PlayerCache() { + super(100, 0.75F, true); + } + + @Override + protected boolean removeEldestEntry(Map.Entry eldest) { + return this.size() > MinecraftServer.getServer().getPlayerList().getPlayerCount(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PlayerChunkMap.java b/azurite-server/src/main/java/net/minecraft/server/PlayerChunkMap.java new file mode 100644 index 0000000..dcb6938 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PlayerChunkMap.java @@ -0,0 +1,560 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; +import dev.azurite.spigot.optimizations.ObjectMapList; +import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.bukkit.craftbukkit.chunkio.ChunkIOExecutor; + +import java.util.*; + +public class PlayerChunkMap { + + private static final Logger a = LogManager.getLogger(); + private final WorldServer world; + private final List managedPlayers = new ObjectArrayList<>(); // NeonPaper - ArrayList -> ObjectArrayList + private final LongHashMap d = new LongHashMap<>(); // Azurite - Changing LongHashMap breaks WorldEdit + private final List e = new ArrayList<>(); + // private long h; + private final int[][] i = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; + + private int g; + + public PlayerChunkMap(WorldServer worldserver, int viewDistance /* Spigot */) { + this.world = worldserver; + this.a(viewDistance); // Spigot + } + + public static int getFurthestViewableBlock(int i) { + return i * 16 - 16; + } + + public WorldServer a() { + return this.world; + } + + public void flush() { + for (PlayerChunk o : this.e) { + o.b(); + } + + this.e.clear(); + } + + public boolean a(int i, int j) { + return this.d.getEntry(i + 2147483647L | j + 2147483647L << 32) != null; + } + + private PlayerChunk a(int i, int j, boolean flag) { + long k = i + 2147483647L | j + 2147483647L << 32; + PlayerChunk playerchunkmap_playerchunk = this.d.getEntry(k); + if (playerchunkmap_playerchunk == null && flag) { + playerchunkmap_playerchunk = new PlayerChunk(i, j); + this.d.put(k, playerchunkmap_playerchunk); + } + + return playerchunkmap_playerchunk; + } + // CraftBukkit end + + // CraftBukkit start - add method + public final boolean isChunkInUse(int x, int z) { + PlayerChunk pi = a(x, z, false); + if (pi != null) { + return !pi.b.isEmpty(); + } + return false; + } + + public void flagDirty(BlockPosition blockposition) { + flagDirty(blockposition.getX(), blockposition.getY(), blockposition.getZ()); + } + + public void flagDirty(int x, int y, int z) { + int i = x >> 4; + int j = z >> 4; + PlayerChunk playerchunkmap_playerchunk = this.a(i, j, false); + if (playerchunkmap_playerchunk != null) { + playerchunkmap_playerchunk.a(x & 15, y, z & 15); + } + } + + public void addPlayer(EntityPlayer entityplayer) { + int i = MathHelper.floor(entityplayer.locX) >> 4; + int j = MathHelper.floor(entityplayer.locZ) >> 4; + + entityplayer.d = entityplayer.locX; + entityplayer.e = entityplayer.locZ; + + List chunkList = new ArrayList<>(); + + final int view = entityplayer.viewDistance; + for (int k = i - view; k <= i + view; ++k) { + for (int l = j - view; l <= j + view; ++l) { + chunkList.add(new ChunkCoordIntPair(k, l)); + } + } + + chunkList.sort(new ChunkCoordComparator(entityplayer)); + for (ChunkCoordIntPair pair : chunkList) { + this.a(pair.x, pair.z, true).a(entityplayer); + } + // CraftBukkit end + + this.managedPlayers.add(entityplayer); + this.b(entityplayer); + } + + public void b(EntityPlayer entityplayer) { + Set set = new HashSet<>(entityplayer.chunkCoordIntPairQueue); + int i = 0; + int j = entityplayer.viewDistance; // PaperSpigot - Player view distance API + final int k = MathHelper.floor(entityplayer.locX) >> 4; + final int l = MathHelper.floor(entityplayer.locZ) >> 4; + + int i1 = 0; + int j1 = 0; + ChunkCoordIntPair chunkcoordintpair = this.a(k, l, true).location; + + entityplayer.chunkCoordIntPairQueue.clear(); + if (set.contains(chunkcoordintpair)) { + entityplayer.chunkCoordIntPairQueue.add(chunkcoordintpair); + } + + int k1; + + for (k1 = 1; k1 <= j * 2; ++k1) { + for (int l1 = 0; l1 < 2; ++l1) { + int[] aint = this.i[i++ % 4]; + + for (int i2 = 0; i2 < k1; ++i2) { + i1 += aint[0]; + j1 += aint[1]; + chunkcoordintpair = this.a(k + i1, l + j1, true).location; + if (set.contains(chunkcoordintpair)) { + entityplayer.chunkCoordIntPairQueue.add(chunkcoordintpair); + } + } + } + } + + i %= 4; + + for (k1 = 0; k1 < j * 2; ++k1) { + i1 += this.i[i][0]; + j1 += this.i[i][1]; + chunkcoordintpair = this.a(k + i1, l + j1, true).location; + if (set.contains(chunkcoordintpair)) { + entityplayer.chunkCoordIntPairQueue.add(chunkcoordintpair); + } + } + + } + + public void removePlayer(EntityPlayer entityplayer) { + final int i = MathHelper.floor(entityplayer.d) >> 4; + final int j = MathHelper.floor(entityplayer.e) >> 4; + final int view = entityplayer.viewDistance; + for (int k = i - view; k <= i + view; ++k) { + for (int l = j - view; l <= j + view; ++l) { + PlayerChunk playerchunkmap_playerchunk = this.a(k, l, false); + + if (playerchunkmap_playerchunk != null) { + playerchunkmap_playerchunk.b(entityplayer); + } + } + } + + this.managedPlayers.remove(entityplayer); + } + + private boolean a(int i, int j, int k, int l, int i1) { + int j1 = i - k; + int k1 = j - l; + return j1 >= -i1 && j1 <= i1 && k1 >= -i1 && k1 <= i1; + } + + public void movePlayer(EntityPlayer entityplayer) { + int i = MathHelper.floor(entityplayer.locX) >> 4; + int j = MathHelper.floor(entityplayer.locZ) >> 4; + double d0 = entityplayer.d - entityplayer.locX; + double d1 = entityplayer.e - entityplayer.locZ; + + if ((d0 * d0 + d1 * d1) >= 64.0D) { + int k = MathHelper.floor(entityplayer.d) >> 4; + int l = MathHelper.floor(entityplayer.e) >> 4; + int i1 = entityplayer.viewDistance; // PaperSpigot - Player view distance API + int j1 = i - k; + int k1 = j - l; + List chunksToLoad = new ArrayList<>(); // CraftBukkit + + if (j1 != 0 || k1 != 0) { + for (int l1 = i - i1; l1 <= i + i1; ++l1) { + for (int i2 = j - i1; i2 <= j + i1; ++i2) { + if (!this.a(l1, i2, k, l, i1)) { + chunksToLoad.add(new ChunkCoordIntPair(l1, i2)); // CraftBukkit + } + + if (!this.a(l1 - j1, i2 - k1, i, j, i1)) { + PlayerChunk playerchunkmap_playerchunk = this.a(l1 - j1, i2 - k1, false); + + if (playerchunkmap_playerchunk != null) { + playerchunkmap_playerchunk.b(entityplayer); + } + } + } + } + + this.b(entityplayer); + entityplayer.d = entityplayer.locX; + entityplayer.e = entityplayer.locZ; + + // CraftBukkit start - send nearest chunks first + chunksToLoad.sort(new ChunkCoordComparator(entityplayer)); + for (ChunkCoordIntPair pair : chunksToLoad) { + this.a(pair.x, pair.z, true).a(entityplayer); + } + + if (j1 > 1 || j1 < -1 || k1 > 1 || k1 < -1) { + entityplayer.chunkCoordIntPairQueue.sort(new ChunkCoordComparator(entityplayer)); + } + // CraftBukkit end + } + } + } + + public boolean a(EntityPlayer entityplayer, int i, int j) { + PlayerChunk playerchunkmap_playerchunk = this.a(i, j, false); + + return playerchunkmap_playerchunk != null && playerchunkmap_playerchunk.b.contains(entityplayer) && !entityplayer.chunkCoordIntPairQueue.contains(playerchunkmap_playerchunk.location); + } + + public void a(int i) { + i = MathHelper.clamp(i, 3, 32); + if (i != this.g) { + int j = i - this.g; + ArrayList arraylist = Lists.newArrayList(this.managedPlayers); + + for (EntityPlayer entityplayer : arraylist) { + int k = (int) entityplayer.locX >> 4; + int l = (int) entityplayer.locZ >> 4; + int i1; + int j1; + + if (j > 0) { + for (i1 = k - i; i1 <= k + i; ++i1) { + for (j1 = l - i; j1 <= l + i; ++j1) { + PlayerChunk playerchunkmap_playerchunk = this.a(i1, j1, true); + + if (!playerchunkmap_playerchunk.b.contains(entityplayer)) { + playerchunkmap_playerchunk.a(entityplayer); + } + } + } + } else { + for (i1 = k - this.g; i1 <= k + this.g; ++i1) { + for (j1 = l - this.g; j1 <= l + this.g; ++j1) { + if (!this.a(i1, j1, k, l, i)) { + this.a(i1, j1, true).b(entityplayer); + } + } + } + } + } + + this.g = i; + } + } + // PaperSpigot end + + // PaperSpigot start - Player view distance API + public void updateViewDistance(EntityPlayer player, int viewDistance) { + viewDistance = MathHelper.clamp(viewDistance, 3, 32); + if (viewDistance != player.viewDistance) { + int cx = (int) player.locX >> 4; + int cz = (int) player.locZ >> 4; + + if (viewDistance - player.viewDistance > 0) { + for (int x = cx - viewDistance; x <= cx + viewDistance; ++x) { + for (int z = cz - viewDistance; z <= cz + viewDistance; ++z) { + PlayerChunk playerchunkmap_playerchunk = this.a(x, z, true); + + if (!playerchunkmap_playerchunk.b.contains(player)) { + playerchunkmap_playerchunk.a(player); + } + } + } + } else { + for (int x = cx - player.viewDistance; x <= cx + player.viewDistance; ++x) { + for (int z = cz - player.viewDistance; z <= cz + player.viewDistance; ++z) { + if (!this.a(x, z, cx, cz, viewDistance)) { + this.a(x, z, true).b(player); + } + } + } + } + + player.viewDistance = viewDistance; + } + } + + // CraftBukkit start - Sorter to load nearby chunks first + private static class ChunkCoordComparator implements java.util.Comparator { + private final int x; + private final int z; + + public ChunkCoordComparator(EntityPlayer entityplayer) { + x = MathHelper.floor(entityplayer.locX) >> 4; + z = MathHelper.floor(entityplayer.locZ) >> 4; + } + + public int compare(ChunkCoordIntPair a, ChunkCoordIntPair b) { + if (a.equals(b)) { + return 0; + } + + // Subtract current position to set center point + int ax = a.x - this.x; + int az = a.z - this.z; + int bx = b.x - this.x; + int bz = b.z - this.z; + + int result = ((ax - bx) * (ax + bx)) + ((az - bz) * (az + bz)); + if (result != 0) { + return result; + } + + if (ax < 0) { + if (bx < 0) { + return bz - az; + } else { + return -1; + } + } else { + if (bx < 0) { + return 1; + } else { + return az - bz; + } + } + } + } + + class PlayerChunk { + + private final List b = new ObjectMapList<>(EntityPlayer.class); // Azurite - faster contains and removes + private final ChunkCoordIntPair location; + // CraftBukkit start - add fields + private final Map players = new Int2ObjectOpenHashMap<>(); // Azurite + private final short[] dirtyBlocks = new short[64]; + private int dirtyCount; + private int f; + private long g; + private boolean loaded = false; + private final Runnable loadedRunnable = () -> loaded = true; + // CraftBukkit end + + public void resend() { + if (this.dirtyCount == 0) + (PlayerChunkMap.this.a().getPlayerChunkMap()).e.add(this); + this.dirtyCount = 64; + this.f = 65535; + } + + public PlayerChunk(int i, int j) { + this.location = new ChunkCoordIntPair(i, j); + PlayerChunkMap.this.a().chunkProviderServer.getChunkAt(i, j, loadedRunnable); // CraftBukkit + } + + public void a(final EntityPlayer entityplayer) { // CraftBukkit - added final to argument + if (this.b.contains(entityplayer)) { + PlayerChunkMap.a.debug("Failed to add player. {} already is in chunk {}, {}", entityplayer, this.location.x, this.location.z); + } else { + if (this.b.isEmpty()) { + this.g = PlayerChunkMap.this.world.getTime(); + } + + this.b.add(entityplayer); + // CraftBukkit start - use async chunk io + Runnable playerRunnable = null; + if (this.loaded) { + entityplayer.chunkCoordIntPairQueue.add(this.location); + } else { + playerRunnable = () -> entityplayer.chunkCoordIntPairQueue.add(location); + PlayerChunkMap.this.a().chunkProviderServer.getChunkAt(this.location.x, this.location.z, playerRunnable); + } + + this.players.put(entityplayer.getId(), playerRunnable); + // CraftBukkit end + } + } + + public void b(EntityPlayer entityplayer) { + if (this.b.contains(entityplayer)) { + // CraftBukkit start - If we haven't loaded yet don't load the chunk just so we can clean it up + if (!this.loaded) { + ChunkIOExecutor.dropQueuedChunkLoad(PlayerChunkMap.this.a(), this.location.x, this.location.z, this.players.get(entityplayer.getId())); + this.b.remove(entityplayer); + this.players.remove(entityplayer.getId()); + + if (this.b.isEmpty()) { + ChunkIOExecutor.dropQueuedChunkLoad(PlayerChunkMap.this.a(), this.location.x, this.location.z, this.loadedRunnable); + PlayerChunkMap.this.d.remove(this.location.x + 2147483647L | this.location.z + 2147483647L << 32); + // PlayerChunkMap.this.f.remove(this); + } + + return; + } + // CraftBukkit end + Chunk chunk = world.getChunkAt(this.location.x, this.location.z); + + if (chunk.isReady() && !entityplayer.playerConnection.processedDisconnect) { // Azurite - no need to send unload packets when the player is disconnecting + entityplayer.playerConnection.sendPacket(new PacketPlayOutMapChunk(chunk)); // Azurite - custom constructor for chunk unload packet + } + + this.players.remove(entityplayer.getId()); // CraftBukkit + this.b.remove(entityplayer); + entityplayer.chunkCoordIntPairQueue.remove(this.location); + if (this.b.isEmpty()) { + + this.a(chunk); + PlayerChunkMap.this.d.remove(location.x + 2147483647L | this.location.z + 2147483647L << 32); + // PlayerChunkMap.this.f.remove(this); + if (this.dirtyCount > 0) { + e.remove(this); + } + + PlayerChunkMap.this.a().chunkProviderServer.queueUnload(this.location.x, this.location.z); + } + + } + } + + public void a() { + this.a(world.getChunkAt(this.location.x, this.location.z)); + } + + private void a(Chunk chunk) { + chunk.c(chunk.w() + world.getTime() - this.g); + this.g = world.getTime(); + } + + public void a(int x, int y, int z) { + if (this.dirtyCount == 0) { + e.add(this); + } + + this.f |= 1 << (y >> 4); + if (this.dirtyCount < 64) { + short encodedPos = (short) (x << 12 | z << 8 | y); + + for (int l = 0; l < this.dirtyCount; ++l) { + if (this.dirtyBlocks[l] == encodedPos) { + return; + } + } + + this.dirtyBlocks[this.dirtyCount++] = encodedPos; + } + + } + + public void a(Packet packet) { + for (EntityPlayer entityplayer : b) { + if (!entityplayer.chunkCoordIntPairQueue.contains(location)) { + entityplayer.playerConnection.sendPacket(packet); + } + } + } + + public void b() { + if (this.dirtyCount != 0) { + if (this.dirtyCount == 1) { + short dirtyBlock = dirtyBlocks[0]; + + int i = (dirtyBlock >> 12 & 0xF) + this.location.x * 16; + int j = dirtyBlock & 0xFF; + int k = (dirtyBlock >> 8 & 0xF) + this.location.z * 16; + BlockPosition pos = new BlockPosition(i, j, k); + + // Vortex - Once block getting instead of 3 + Chunk chunk = world.getChunkAtWorldCoords(i, k); + IBlockData iblockdata = world.getType(chunk, i, j, k, true); + Block block = iblockdata.getBlock(); + + a(new PacketPlayOutBlockChange(pos, iblockdata)); + + if (block.isTileEntity()) { + a(world.getTileEntity(chunk, pos, block)); + } + } else { + + if (this.dirtyCount == 64) { + int i = this.location.x * 16; + int j = this.location.z * 16; + + // Azurite - only send chunk if it has to be sent + PacketPlayOutMapChunk packet = null; + for (EntityPlayer entityplayer : b) { + if (!entityplayer.chunkCoordIntPairQueue.contains(location)) { + if (packet == null) { + packet = new PacketPlayOutMapChunk(world.getChunkAt(this.location.x, this.location.z), false, this.f); + } + + entityplayer.sendPacket(packet); + } + } + + for (int k = 0; k < 16; ++k) { + if ((this.f & 1 << k) != 0) { + int l = k << 4; + List list = world.getTileEntities(i, l, j, i + 16, l + 16, j + 16); + + for (TileEntity tileEntity : list) { + this.a(tileEntity); + } + } + } + } else { + this.a(new PacketPlayOutMultiBlockChange(this.dirtyCount, this.dirtyBlocks, PlayerChunkMap.this.world.getChunkAt(this.location.x, this.location.z))); + + for (int i = 0; i < this.dirtyCount; ++i) { + short dirtyBlock = dirtyBlocks[i]; + + int j = (dirtyBlock >> 12 & 0xF) + location.x * 16; + int k = dirtyBlock & 0xFF; + int l = (dirtyBlock >> 8 & 0xF) + location.z * 16; + + Chunk chunk = world.getChunkAtWorldCoords(j, l); + Block block = world.getType(chunk, j, k, l, true).getBlock(); + if (block.isTileEntity()) { + a(world.getTileEntity(chunk, new BlockPosition(j, k, l), block)); + } + } + } + } + + this.dirtyCount = 0; + this.f = 0; + } + } + + private void a(TileEntity tileentity) { + if (tileentity != null) { + Packet packet = tileentity.getUpdatePacket(); + if (packet != null) { + this.a(packet); + } + } + } + } + + public void resend(int x, int z) { + PlayerChunk chunk = a(x, z, false); + if (chunk != null) + chunk.resend(); + } + // CraftBukkit end +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PlayerConnection.java b/azurite-server/src/main/java/net/minecraft/server/PlayerConnection.java new file mode 100644 index 0000000..547ae48 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PlayerConnection.java @@ -0,0 +1,2489 @@ +package net.minecraft.server; + +import com.google.common.base.Charsets; +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; +import com.google.common.primitives.Doubles; +import com.google.common.primitives.Floats; +import dev.azurite.spigot.Azurite; +import dev.azurite.spigot.api.protocol.MovementHandler; +import dev.azurite.spigot.configs.AzuriteConfig; +import dev.azurite.spigot.configs.LanguageConfig; +import dev.azurite.spigot.optimizations.ObjectMapList; +import dev.azurite.spigot.utils.BlockPlaceSignature; +import dev.azurite.spigot.utils.QueuedTeleport; +import io.netty.buffer.Unpooled; +import io.netty.util.concurrent.Future; +import io.netty.util.concurrent.GenericFutureListener; +import it.unimi.dsi.fastutil.ints.Int2ShortMap; +import it.unimi.dsi.fastutil.ints.Int2ShortOpenHashMap; +import org.apache.commons.lang3.StringUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.craftbukkit.event.CraftEventFactory; +import org.bukkit.craftbukkit.inventory.CraftInventoryView; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.craftbukkit.util.CraftChatMessage; +import org.bukkit.craftbukkit.util.LazyPlayerSet; +import org.bukkit.craftbukkit.util.Waitable; +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.block.Action; +import org.bukkit.event.block.SignChangeEvent; +import org.bukkit.event.inventory.*; +import org.bukkit.event.inventory.InventoryType.SlotType; +import org.bukkit.event.player.*; +import org.bukkit.inventory.CraftingInventory; +import org.bukkit.inventory.InventoryView; +import org.bukkit.util.NumberConversions; +import org.github.paperspigot.PaperSpigotConfig; +import org.spigotmc.AsyncCatcher; +import org.spigotmc.SpigotConfig; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.*; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; + +public class PlayerConnection implements PacketListenerPlayIn, IUpdatePlayerListBox { + + private static final Logger c = LogManager.getLogger(); + private static final Set TELEPORT_NO_ROT = Sets.immutableEnumSet(PacketPlayOutPosition.EnumPlayerTeleportFlags.X_ROT, PacketPlayOutPosition.EnumPlayerTeleportFlags.Y_ROT); + private static final AtomicIntegerFieldUpdater chatSpamField = AtomicIntegerFieldUpdater.newUpdater(PlayerConnection.class, "chatThrottle"); + private static final int SURVIVAL_PLACE_DISTANCE_SQUARED = 36; + private static final int CREATIVE_PLACE_DISTANCE_SQUARED = 49; + private final static List invalidItems = Arrays.asList(8, 9, 10, 11, 26, 34, 36, 43, 51, 52, 55, 59, 60, 62, 63, 64, 68, 71, 74, 75, 83, 90, 92, 93, 94, 104, 105, 115, 117, 118, 119, 125, 127, 132, 140, 141, 142, 144); // Vortex - Use arraylist + public final NetworkManager networkManager; + protected final org.bukkit.craftbukkit.CraftServer server; + private final MinecraftServer minecraftServer; + private final Int2ShortMap n = new Int2ShortOpenHashMap(); // Vortex + // Azurite - Movement & teleport rework + private final Queue teleportQueue = new ArrayDeque<>(); + public EntityPlayer player; + public boolean processedDisconnect; // CraftBukkit - added + public int lastDropTick = MinecraftServer.currentTick; + public long nextValidSwing = 0; + private int e; + private int f; + private int g; + private int i; + private long j; + private long k; + // CraftBukkit start - multithreaded fields + private volatile int chatThrottle; + // CraftBukkit end + private int m; + // Azurite - revert the following values back to o, p, q if a plugin uses them, but I doubt any plugin needs those values + private double lastX; + private double lastY; + private double lastZ; + private int dropCount = 0; + // Get position of last block hit for BlockDamageLevel.STOPPED + private double lastPosX = Double.MAX_VALUE; + private double lastPosY = Double.MAX_VALUE; + private double lastPosZ = Double.MAX_VALUE; + private float lastPitch = Float.MAX_VALUE; + private float lastYaw = Float.MAX_VALUE; + private boolean justTeleported; + private boolean hasMoved; // Spigot + // Spigot start - limit place/interactions + private long lastPlace = -1; + private int packets = 0; + private boolean checkMovement = true; + + public PlayerConnection(MinecraftServer minecraftserver, NetworkManager networkmanager, EntityPlayer entityplayer) { + networkmanager.a(this); + this.minecraftServer = minecraftserver; + this.networkManager = networkmanager; + this.player = entityplayer; + entityplayer.playerConnection = this; + entityplayer.trackerQueueRef = networkmanager.fastNetworkManager.trackerQueue; + + // CraftBukkit start - add fields and methods + this.server = minecraftserver.server; + } + + public CraftPlayer getPlayer() { + return player.getBukkitEntity(); + } + + public int getTeleportQueueSize() { + return teleportQueue.size(); + } + + public boolean isCheckMovement() { + return checkMovement; + } + + public void forceRespawn(EntityPlayer entityPlayer) { + this.minecraftServer.getPlayerList().forceRespawn(entityPlayer); + } + + // Beanes - extract + public void sendKeepAlive(boolean lazily) { + j = d(); + this.i = (int) (this.j & 0xFFFFFFFFL); + + if (lazily) { + writePacketLazily(new PacketPlayOutKeepAlive(i)); + } else { + sendPacket(new PacketPlayOutKeepAlive(i)); + } + + } + + public void c() { + if (++e - k > AzuriteConfig.keepAliveUpdateFrequency.getValue()) { + k = e; + this.sendKeepAlive(false); + } + + for (int spam; (spam = chatThrottle) > 0 && !chatSpamField.compareAndSet(this, spam, spam - 1); ) ; + + if (m > 0) { + --m; + } + + if (AzuriteConfig.playerIdleTimer.getValue() && player.D() > 0L && minecraftServer.getIdleTimeout() > 0 && MinecraftServer.az() - player.D() > (minecraftServer.getIdleTimeout() * 1000L * 60L)) { + player.resetIdleTimer(); + disconnect("You have been idle for too long!"); + } + } + + public NetworkManager a() { + return this.networkManager; + } + + public void disconnect(String s) { + + PlayerKickEvent event = new PlayerKickEvent(player.getBukkitEntity().getPlayer(), s, EnumChatFormat.YELLOW + player.getName() + " left the game."); + + if (server.getServer().isRunning()) { + server.getPluginManager().callEvent(event); + } + + if (event.isCancelled()) { + return; + } + + ChatComponentText chatcomponenttext = new ChatComponentText(event.getReason()); + networkManager.a(new PacketPlayOutKickDisconnect(chatcomponenttext), (GenericFutureListener>) future -> { // CraftBukkit - fix decompile error + networkManager.close(chatcomponenttext); + }); + + a(chatcomponenttext); + + networkManager.k(); + + minecraftServer.postToLoginTasks(networkManager::l); + + } + + public void a(PacketPlayInSteerVehicle packetplayinsteervehicle) { + PlayerConnectionUtils.ensureMainThread(packetplayinsteervehicle, this, this.player.u()); + if (packetplayinsteervehicle.a() >= Float.MAX_VALUE || packetplayinsteervehicle.b() >= Float.MAX_VALUE) // Vortex - Anticrash + this.disconnect("Invalid vehicle move packet received"); + + this.player.a(packetplayinsteervehicle.a(), packetplayinsteervehicle.b(), packetplayinsteervehicle.c(), packetplayinsteervehicle.d()); + } + + private boolean b(PacketPlayInFlying packetplayinflying) { + return this.isIllegal(packetplayinflying); + } + + private boolean isIllegal(PacketPlayInFlying packetplayinflying) { + return !Doubles.isFinite(packetplayinflying.x) || !Doubles.isFinite(packetplayinflying.y) || !Doubles.isFinite(packetplayinflying.z) || !Floats.isFinite(packetplayinflying.pitch) || !Floats.isFinite(packetplayinflying.yaw) || Math.abs(packetplayinflying.x) > 3.0E7D || Math.abs(packetplayinflying.z) > 3.0E7D; + } + + private boolean hasDoneFastKeepAlive = false; + + // Azurite - movement & teleport rework + public void a(PacketPlayInFlying packet) { + PlayerConnectionUtils.ensureMainThread(packet, this, player.u()); + + if (isIllegal(packet)) { + disconnect("Invalid move packet received"); + return; + } + + // Beanes - fast keepalive + if (!hasDoneFastKeepAlive && AzuriteConfig.fastKeepAlive.getValue()) { + hasDoneFastKeepAlive = true; + sendKeepAlive(true); + } + + // Beanes - check drop eat run bug + player.checkDropEatRunBug(); + + // Beanes - cps cap, we don't really care about client ticks in response of teleports as they'll just give more leniency + player.registerTickForCpsPenalty(); + + // Beanes - constant knockback tick + player.constantKnockbackTick(packet.f()); + + // Beanes - ping balance + player.calculatePingBalance(); + + // Azurite - item queue + player.processItemQueue(packet); + + if (AzuriteConfig.playerTeleportTracker.getValue()) { + QueuedTeleport peek = teleportQueue.peek(); + + // There is a queued teleport + if (peek != null) { + if (packet.hasPos && packet.hasLook) { + boolean correct = peek.isRelative() || (peek.getX() == packet.x && Math.abs(peek.getY() - packet.y) < 1.0E-3 && peek.getZ() == packet.z); + + if (correct) { + checkMovement = true; + teleportQueue.remove(); + lastX = peek.getX(); + lastY = peek.getY(); + lastZ = peek.getZ(); + player.setPosition(peek.getX(), peek.getY(), peek.getZ()); + + // Don't tick a teleport + } else { + // Player pos is not the teleport pos -> just tick + player.onGround = packet.f(); + player.l(); + } + } else { + // Player did not have flags set for teleport -> just tick + player.onGround = packet.f(); + player.l(); + } + return; + } + + // The player still has teleports to accept, don't accept the position update but do tick + if (!teleportQueue.isEmpty()) { + player.onGround = packet.f(); + player.l(); + return; + } + } + + if (player.viewingCredits) { + return; + } + + WorldServer worldserver = minecraftServer.getWorldServer(player.dimension); + CraftPlayer craftPlayer = getPlayer(); + + double diffSquared = 0.0D; + double diffXPrevious = packet.x - lastX; + double diffYPrevious = packet.y - lastY; + double diffZPrevious = packet.z - lastZ; + + if (packet.hasPos) { + diffSquared = diffXPrevious * diffXPrevious + diffYPrevious * diffYPrevious + diffZPrevious * diffZPrevious; + if (!checkMovement && diffSquared < 0.25D) + checkMovement = true; + } + + if (!hasMoved) { + Location curPos = craftPlayer.getLocation(); + lastPosX = curPos.getX(); + lastPosY = curPos.getY(); + lastPosZ = curPos.getZ(); + lastYaw = curPos.getYaw(); + lastPitch = curPos.getPitch(); + hasMoved = true; + } + + if (PlayerMoveEvent.getHandlerList().getRegisteredListeners().length > 0 || !Azurite.getInstance().getMovementHandlers().isEmpty()) { + Location from = new Location(craftPlayer.getWorld(), lastPosX, lastPosY, lastPosZ, lastYaw, lastPitch); + Location to = craftPlayer.getLocation().clone(); + + if (packet.hasPos && packet.y != -999.0D) { + to.setX(packet.x); + to.setY(packet.y); + to.setZ(packet.z); + } + + if (packet.hasLook) { + to.setYaw(packet.yaw); + to.setPitch(packet.pitch); + } + + // Prevent 40 event-calls for less than a single pixel of movement >.> + double delta = Math.pow(this.lastPosX - to.getX(), 2) + Math.pow(this.lastPosY - to.getY(), 2) + Math.pow(this.lastPosZ - to.getZ(), 2); + float deltaAngle = Math.abs(this.lastYaw - to.getYaw()) + Math.abs(this.lastPitch - to.getPitch()); + + if ((delta > 1f / 256 || deltaAngle > 10f) && (this.checkMovement && !this.player.dead)) { + lastPosX = to.getX(); + lastPosY = to.getY(); + lastPosZ = to.getZ(); + lastYaw = to.getYaw(); + lastPitch = to.getPitch(); + + boolean hasLook = packet.hasLook && deltaAngle > 0.0F, hasPos = packet.hasPos && delta > 0.0F; + ObjectMapList movementHandlers = Azurite.getInstance().getMovementHandlers(); + + for (int m = 0; m < movementHandlers.count; m++) { + MovementHandler handler = movementHandlers.elements[m]; + if (hasPos) { + handler.handleUpdateLocation(craftPlayer, from, to, packet); + if (from.getBlockX() != to.getBlockX() || from.getBlockY() != to.getBlockY() || from.getBlockZ() != to.getBlockZ()) + handler.handleBlockUpdateLocation(craftPlayer, from, to); + } + if (hasLook) { + handler.handleUpdateRotation(craftPlayer, from, to, packet); + } + } + + if (AzuriteConfig.firePlayerMoveEvent.getValue()) { + Location oldTo = to.clone(); + PlayerMoveEvent event = new PlayerMoveEvent(craftPlayer, from, to); + server.getPluginManager().callEvent(event); + + if (event.isCancelled()) { + // Azurite - Smooth Teleportation (PandaSpigot) + this.player.playerConnection.sendPacket(new PacketPlayOutPosition(from.getX(), from.getY(), from.getZ(), 0, 0, TELEPORT_NO_ROT)); + return; + } + + if (!oldTo.equals(event.getTo()) && !event.isCancelled()) { + player.getBukkitEntity().teleport(event.getTo(), PlayerTeleportEvent.TeleportCause.UNKNOWN); + return; + } + } + + if (!from.equals(getPlayer().getLocation()) && justTeleported) { + justTeleported = false; + return; + } + } + } + + if (checkMovement && !player.dead) { + f = e; + + if (player.vehicle != null) { + float yaw = player.yaw; + float pitch = player.pitch; + player.vehicle.al(); + + double savedX = player.locX; + double savedY = player.locY; + double savedZ = player.locZ; + + if (packet.hasLook) { + yaw = packet.yaw; + pitch = packet.pitch; + } + + player.onGround = packet.f(); + player.l(); // tick + player.setLocation(savedX, savedY, savedZ, yaw, pitch); + + if (player.vehicle != null) + player.vehicle.al(); + + minecraftServer.getPlayerList().d(player); + + if (player.vehicle != null) { + player.vehicle.ai = true; + if (diffSquared > 4.0D) { + Entity entity = player.vehicle; + player.playerConnection.sendPacket(new PacketPlayOutEntityTeleport(entity)); + a(player.locX, player.locY, player.locZ, player.yaw, player.pitch); + } + } + + if (checkMovement) { + lastX = player.locX; + lastY = player.locY; + lastZ = player.locZ; + } + + worldserver.g(player); + return; + } + + if (player.isSleeping()) { + player.l(); + player.setLocation(lastX, lastY, lastZ, player.yaw, player.pitch); + worldserver.g(player); + return; + } + + double savedY = player.locY; + + lastX = player.locX; + lastY = player.locY; + lastZ = player.locZ; + + double locX = player.locX; + double locY = player.locY; + double locZ = player.locZ; + float yaw = player.yaw; + float pitch = player.pitch; + + // Prevents vehicle desync + if (packet.hasPos && packet.y == -999.0D) { + packet.hasPos = false; + } + + if (packet.hasPos) { + locX = packet.x; + locY = packet.y; + locZ = packet.z; + + if (Math.abs(packet.x) > 3.0E7D || Math.abs(packet.z) > 3.0E7D) { + this.disconnect("Illegal position"); + return; + } + } + + if (packet.hasLook) { + yaw = packet.yaw; + pitch = packet.pitch; + } + + player.l(); + player.setLocation(lastX, lastY, lastZ, yaw, pitch); + + if (!this.checkMovement) { + return; + } + + double phaseLeniency = AzuriteConfig.playerPhaseLeniency.getValue(); + double diffY = locY - player.locY; + double diffX = locX - player.locX; + double diffZ = locZ - player.locZ; + double deltaSquared = diffX * diffX + diffY * diffY + diffZ * diffZ; + + if (AzuriteConfig.playerMovedTooQuicklyCheck.getValue()) { + double motionSquared = player.motX * player.motX + player.motY * player.motY + player.motZ * player.motZ; + + if (deltaSquared - motionSquared > SpigotConfig.movedTooQuicklyThreshold && checkMovement && (!this.minecraftServer.T() || !this.minecraftServer.S().equals(this.player.getName()))) { + c.warn("{} moved too quickly! {},{},{}", player.getName(), diffX, diffY, diffZ); + a(lastX, lastY, lastZ, player.yaw, player.pitch); + return; + } + } + + boolean couldHavePhased = packet.hasPos && !player.noclip; + List oldCollisions = couldHavePhased ? worldserver.getCollisionBlocks(player, player.getBoundingBox().shrink(phaseLeniency, phaseLeniency, phaseLeniency)) : null; + + // Process jump + if (player.onGround && !packet.f() && diffY > 0.0D) { + player.bF(); + } + + player.onGround = packet.f(); + + // Authorize the client position (also used for phase check) + player.setLocation(locX, locY, locZ, yaw, pitch); + player.checkMovement(locX - lastX, locY - lastY, locZ - lastZ); + + if (checkMovement && couldHavePhased) { + List newCollisions = worldserver.getCollisionBlocks(player, player.getBoundingBox().shrink(phaseLeniency, phaseLeniency, phaseLeniency)); + + if (newCollisions.size() > oldCollisions.size() || worldserver.isThroughBlock(new Vec3D(lastX, lastY + 0.6D, lastZ), new Vec3D(locX, locY + 0.6D, locZ), oldCollisions)) { + a(lastX, lastY, lastZ, yaw, pitch); + return; + } + } + + AxisAlignedBB axisalignedbb = player.getBoundingBox().grow(0.0625F, 0.0625F, 0.0625F).a(0.0D, -0.55D, 0.0D); + if (!minecraftServer.getAllowFlight() && !player.abilities.canFly && !worldserver.c(axisalignedbb)) { + if (diffY >= -0.03125D) { + g++; + if (g > 80) { + c.warn("{} was kicked for floating too long!", player.getName()); + disconnect("Flying is not enabled on this server"); + return; + } + } + } else { + g = 0; + } + + minecraftServer.getPlayerList().d(player); // send chunk packet updates + player.a(player.locY - savedY, packet.f()); // send dust particles + + if (packet.hasPos && AzuriteConfig.footstepSounds.getValue() && !player.abilities.isFlying && player.vehicle == null && !player.isSneaking()) { + player.N = (float) (player.N + MathHelper.sqrt(deltaSquared) * 0.6D); + emulateFootstepSound(); + } + } else if (!AzuriteConfig.playerTeleportTracker.getValue() && this.e - this.f > 20) { + this.a(this.lastX, this.lastY, this.lastZ, this.player.yaw, this.player.pitch); + } + } + + // Beanes - we have to emulate the footstep sounds as we don't run move (which is shit anyways) + private void emulateFootstepSound() { + BlockPosition blockposition = new BlockPosition(MathHelper.floor(player.locX), MathHelper.floor(player.locY - 0.20000000298023224D), MathHelper.floor(player.locZ)); + Block block = player.world.getType(blockposition).getBlock(); + + if (player.N > player.getH() && block != Blocks.AIR) { + player.setH((int) player.N + 1); + player.a(blockposition.getX(), blockposition.getY(), blockposition.getZ(), block); + } + } + + public void a(double d0, double d1, double d2, float f, float f1) { + this.a(d0, d1, d2, f, f1, Collections.emptySet()); + } + + public void a(double d0, double d1, double d2, float f, float f1, + Set set) { + // CraftBukkit start - Delegate to teleport(Location) + Player player = this.getPlayer(); + Location from = player.getLocation(); + + double x = d0; + double y = d1; + double z = d2; + float yaw = f; + float pitch = f1; + if (set.contains(PacketPlayOutPosition.EnumPlayerTeleportFlags.X)) { + x += from.getX(); + } + if (set.contains(PacketPlayOutPosition.EnumPlayerTeleportFlags.Y)) { + y += from.getY(); + } + if (set.contains(PacketPlayOutPosition.EnumPlayerTeleportFlags.Z)) { + z += from.getZ(); + } + if (set.contains(PacketPlayOutPosition.EnumPlayerTeleportFlags.Y_ROT)) { + yaw += from.getYaw(); + } + if (set.contains(PacketPlayOutPosition.EnumPlayerTeleportFlags.X_ROT)) { + pitch += from.getPitch(); + } + + Location to = new Location(this.getPlayer().getWorld(), x, y, z, yaw, pitch); + PlayerTeleportEvent event = new PlayerTeleportEvent(player, from.clone(), to.clone(), + PlayerTeleportEvent.TeleportCause.UNKNOWN); + this.server.getPluginManager().callEvent(event); + + if (event.isCancelled() || to.equals(event.getTo())) { + set.clear(); // Can't relative teleport + to = event.isCancelled() ? event.getFrom() : event.getTo(); + d0 = to.getX(); + d1 = to.getY(); + d2 = to.getZ(); + f = to.getYaw(); + f1 = to.getPitch(); + } + + this.internalTeleport(d0, d1, d2, f, f1, set); + } + + public void teleport(Location dest) { + this.teleport(dest, true); + } + + // Azurite - add the option to teleport the player without rotation + public void teleport(Location dest, boolean rotation) { + internalTeleport(dest.getX(), dest.getY(), dest.getZ(), rotation ? dest.getYaw() : 0, rotation ? dest.getPitch() : 0, rotation ? Collections.emptySet() : TELEPORT_NO_ROT); + } + + private void internalTeleport(double d0, double d1, double d2, float f, float f1, Set set) { + if (Float.isNaN(f)) { + f = 0; + } + + if (Float.isNaN(f1)) { + f1 = 0; + } + this.justTeleported = true; + // CraftBukkit end + this.checkMovement = false; + this.lastX = d0; + this.lastY = d1; + this.lastZ = d2; + + if (set.contains(PacketPlayOutPosition.EnumPlayerTeleportFlags.X)) { + this.lastX += this.player.locX; + } + + if (set.contains(PacketPlayOutPosition.EnumPlayerTeleportFlags.Y)) { + this.lastY += this.player.locY; + } + + if (set.contains(PacketPlayOutPosition.EnumPlayerTeleportFlags.Z)) { + this.lastZ += this.player.locZ; + } + + float f2 = f; + float f3 = f1; + + if (set.contains(PacketPlayOutPosition.EnumPlayerTeleportFlags.Y_ROT)) { + f2 = f + this.player.yaw; + } + + if (set.contains(PacketPlayOutPosition.EnumPlayerTeleportFlags.X_ROT)) { + f3 = f1 + this.player.pitch; + } + + // CraftBukkit start - update last location + this.lastPosX = this.lastX; + this.lastPosY = this.lastY; + this.lastPosZ = this.lastZ; + this.lastYaw = f2; + this.lastPitch = f3; + // CraftBukkit end + + this.player.setLocation(this.lastX, this.lastY, this.lastZ, f2, f3); + this.player.playerConnection.sendPacket(new PacketPlayOutPosition(d0, d1, d2, f, f1, set)); + } + + public void a(PacketPlayInBlockDig packetplayinblockdig) { + PlayerConnectionUtils.ensureMainThread(packetplayinblockdig, this, this.player.u()); + if (this.player.dead) + return; // CraftBukkit + this.player.resetIdleTimer(); + // CraftBukkit start + switch (SyntheticClass_1.a[packetplayinblockdig.c().ordinal()]) { + case 1: // DROP_ITEM + if (!this.player.isSpectator()) { + // limit how quickly items can be dropped + // If the ticks aren't the same then the count starts from 0 and we update the + // lastDropTick. + if (lastDropTick != MinecraftServer.currentTick) { + dropCount = 0; + lastDropTick = MinecraftServer.currentTick; + } else { + // Else we increment the drop count and check the amount. + dropCount++; + if (dropCount >= 20) { + c.warn("{} dropped their items too quickly!", this.player.getName()); + this.disconnect("You dropped your items too quickly (Hacking?)"); + return; + } + } + // CraftBukkit end + if (!AzuriteConfig.patchDropEatRunBug.getValue() && AzuriteConfig.patchDropEatBug.getValue() && player.isEating()) { + player.bU(); // stopUsingItem | VortexSpigot - Fix for eating and blocking and etc while // running + } + player.a(false); + } + + return; + + case 2: // DROP_ALL_ITEMS + if (!this.player.isSpectator()) { + this.player.a(true); + } + + return; + + case 3: // RELEASE_USE_ITEM + if (AzuriteConfig.patchBowMisdirection.getValue() && player.isBowing()) { + player.queueItemRelease(); + } else { + player.bU(); + } + return; + + case 4: // START_DESTROY_BLOCK + case 5: // ABORT_DESTROY_BLOCK + case 6: // STOP_DESTROY_BLOCK + BlockPosition blockposition = packetplayinblockdig.a(); + + double d0 = this.player.locX - (blockposition.getX() + 0.5D); + double d1 = this.player.locY - (blockposition.getY() + 0.5D) + 1.5D; + double d2 = this.player.locZ - (blockposition.getZ() + 0.5D); + double d3 = d0 * d0 + d1 * d1 + d2 * d2; + + if (d3 <= 36.0D) { + //Vortex - Don't have to get the chunk twice or more + WorldServer worldserver = this.minecraftServer.getWorldServer(this.player.dimension); + Chunk chunk = worldserver.getChunkAtWorldCoords(blockposition); + IBlockData iblockdata = worldserver.getType(chunk, blockposition); + + if (packetplayinblockdig.c() == PacketPlayInBlockDig.EnumPlayerDigType.START_DESTROY_BLOCK) { + if (!minecraftServer.a(worldserver, blockposition, player) && worldserver.getWorldBorder().a(blockposition)) { + player.playerInteractManager.a(chunk, blockposition, packetplayinblockdig.b()); + } else { + CraftEventFactory.callPlayerInteractEvent(player, Action.LEFT_CLICK_BLOCK, chunk.bukkitChunk.getBlock(blockposition.getX(), blockposition.getY(), blockposition.getZ()), blockposition, packetplayinblockdig.b(), this.player.inventory.getItemInHand(), false); + sendPacket(new PacketPlayOutBlockChange(worldserver, blockposition)); + TileEntity tileentity = worldserver.getTileEntity(chunk, blockposition, iblockdata.getBlock()); + if (tileentity != null) { + sendPacket(tileentity.getUpdatePacket()); + } + } + } else { + if (packetplayinblockdig.c() == PacketPlayInBlockDig.EnumPlayerDigType.STOP_DESTROY_BLOCK) { + this.player.playerInteractManager.a(chunk, iblockdata, blockposition); + } else if (packetplayinblockdig.c() == PacketPlayInBlockDig.EnumPlayerDigType.ABORT_DESTROY_BLOCK) { + this.player.playerInteractManager.e(); + this.player.playerConnection.sendPacket(new PacketPlayOutBlockChange(blockposition, iblockdata)); + } + } + } + return; + default: + throw new IllegalArgumentException("Invalid player action"); + } + // CraftBukkit end + } + + private BlockPlaceSignature lastBlock; // Rivals + + public void a(PacketPlayInBlockPlace packetplayinblockplace) { + PlayerConnectionUtils.ensureMainThread(packetplayinblockplace, this, this.player.u()); + + // Beanes - patch item drop bug + player.expectingItemUse = false; + + WorldServer worldserver = this.minecraftServer.getWorldServer(this.player.dimension); + boolean throttled = false; + // PaperSpigot - Allow disabling the player interaction limiter + if (PaperSpigotConfig.interactLimitEnabled && lastPlace != -1 + && packetplayinblockplace.timestamp - lastPlace < 30 && packets++ >= 4) { + throttled = true; + } else if (packetplayinblockplace.timestamp - lastPlace >= 30 || lastPlace == -1) { + lastPlace = AzuriteConfig.optimizePlayerPrinter.getValue() ? -1L : packetplayinblockplace.timestamp; + packets = 0; + } + // Spigot end + + // CraftBukkit start + if (this.player.dead) + return; + // CraftBukkit - if rightclick decremented the item, always send the update + // packet. */ + // this is not here for CraftBukkit's own functionality; rather it is to fix + // a notch bug where the item doesn't update correctly. + boolean always = false; + // CraftBukkit end + + ItemStack itemstack = this.player.inventory.getItemInHand(); + BlockPosition blockposition = packetplayinblockplace.a(); + EnumDirection enumdirection = EnumDirection.fromType1(packetplayinblockplace.getFace()); + + this.player.resetIdleTimer(); + if (packetplayinblockplace.getFace() == 255) { + if (itemstack == null) { + return; + } + + // CraftBukkit start + int itemstackAmount = itemstack.count; + // Spigot start - skip the event if throttled + if (!throttled) { + // Raytrace to look for 'rogue armswings' + float f1 = this.player.pitch; + float f2 = this.player.yaw; + Vec3D vec3d = new Vec3D(player.locX, player.locY + player.getHeadHeight(), player.locZ); + + float f3 = MathHelper.cos(-f2 * 0.017453292F - 3.1415927F); + float f4 = MathHelper.sin(-f2 * 0.017453292F - 3.1415927F); + float f5 = -MathHelper.cos(-f1 * 0.017453292F); + double d3 = player.playerInteractManager.getGameMode() == WorldSettings.EnumGamemode.CREATIVE ? 5.0D : 4.5D; + Vec3D vec3d1 = vec3d.add(f4 * f5 * d3, MathHelper.sin(-f1 * 0.017453292F) * d3, f3 * f5 * d3); + MovingObjectPosition movingobjectposition = this.player.world.rayTrace(vec3d, vec3d1, false); + + // Rivals start + boolean blockPlaceInteract = player.playerInteractManager.firedInteract && (lastBlock != null && lastBlock.matches(packetplayinblockplace)); + if (blockPlaceInteract) + lastBlock = null; + // Rivals end + + boolean cancelled; + if (!blockPlaceInteract) { // Imanity + org.bukkit.event.player.PlayerInteractEvent event = CraftEventFactory.callPlayerInteractEvent(this.player, Action.RIGHT_CLICK_AIR, itemstack); + cancelled = event.useItemInHand() == Event.Result.DENY; + } else { + if (player.playerInteractManager.firedInteract) { + player.playerInteractManager.firedInteract = false; + cancelled = player.playerInteractManager.interactResult; + } else { + org.bukkit.event.player.PlayerInteractEvent event = CraftEventFactory.callPlayerInteractEvent(player, Action.RIGHT_CLICK_BLOCK, movingobjectposition.a(), movingobjectposition.direction, itemstack, true); + cancelled = event.useItemInHand() == Event.Result.DENY; + } + } + + if (!cancelled) { + Item item = itemstack.getItem(); + boolean shouldQueue = (AzuriteConfig.patchGhostBuckets.getValue() && item instanceof ItemBucket) || + (AzuriteConfig.patchProjectileMisdirection.getValue() && + (item instanceof ItemFishingRod || item instanceof ItemEnderPearl || + item instanceof ItemSnowball || item instanceof ItemEgg || item instanceof ItemPotion)); + + // Azurite - item queue + if (shouldQueue) { + this.player.addToUseItemQueue(itemstack); + return; + } else { + this.player.playerInteractManager.useItem(this.player, this.player.world, itemstack); + } + } else { + this.player.updateInventory(this.player.activeContainer); + } + } + // Spigot end + + // CraftBukkit - notch decrements the counter by 1 in the above method with food, + // snowballs and so forth, but he does it in a place that doesn't cause the + // inventory update packet to get sent + always = (itemstack.count != itemstackAmount) || itemstack.getItem() == Item.getItemOf(Blocks.WATERLILY) || itemstack.getItem().getName().contains("bucket"); // Vortex - bucket + // CraftBukkit end + } else { + // CraftBukkit start - Check if we can actually do something over this large a + // distance + Location eyeLoc = this.getPlayer().getEyeLocation(); + double reachDistance = NumberConversions.square(eyeLoc.getX() - blockposition.getX()) + NumberConversions.square(eyeLoc.getY() - blockposition.getY()) + NumberConversions.square(eyeLoc.getZ() - blockposition.getZ()); + if (reachDistance > (this.getPlayer().getGameMode() == org.bukkit.GameMode.CREATIVE ? CREATIVE_PLACE_DISTANCE_SQUARED : SURVIVAL_PLACE_DISTANCE_SQUARED)) { + return; + } + + if (!worldserver.getWorldBorder().a(blockposition)) { + return; + } + + if (this.checkMovement && this.player.e(blockposition.getX() + 0.5D, blockposition.getY() + 0.5D, blockposition.getZ() + 0.5D) < 64.0D && !this.minecraftServer.a(worldserver, blockposition, this.player) && worldserver.getWorldBorder().a(blockposition)) { + always = throttled || !this.player.playerInteractManager.interact(this.player, worldserver, itemstack, blockposition, enumdirection, packetplayinblockplace.d(), packetplayinblockplace.e(), packetplayinblockplace.f()); + // Rivals start + if (player.playerInteractManager.firedInteract) + lastBlock = new BlockPlaceSignature(packetplayinblockplace); + // Rivals end + } + + sendPacket(new PacketPlayOutBlockChange(worldserver, blockposition)); + sendPacket(new PacketPlayOutBlockChange(worldserver, blockposition.shift(enumdirection))); + } + + itemstack = this.player.inventory.getItemInHand(); + if (itemstack != null && itemstack.count == 0) { + this.player.inventory.items[this.player.inventory.itemInHandIndex] = null; + itemstack = null; + } + + if (itemstack == null || itemstack.l() == 0) { + this.player.g = true; + this.player.inventory.items[this.player.inventory.itemInHandIndex] = ItemStack.b(this.player.inventory.items[this.player.inventory.itemInHandIndex]); + Slot slot = this.player.activeContainer.getSlot(this.player.inventory, this.player.inventory.itemInHandIndex); + + this.player.activeContainer.b(); + this.player.g = false; + // CraftBukkit - TODO CHECK IF NEEDED -- new if structure might not need + // 'always'. Kept it in for now, but may be able to remove in future + + if (!ItemStack.matches(this.player.inventory.getItemInHand(), packetplayinblockplace.getItemStack()) || always) + sendPacket(new PacketPlayOutSetSlot(this.player.activeContainer.windowId, slot.rawSlotIndex, this.player.inventory.getItemInHand())); + } + } + + public void a(PacketPlayInSpectate packetplayinspectate) { + PlayerConnectionUtils.ensureMainThread(packetplayinspectate, this, this.player.u()); + if (this.player.isSpectator()) { + Entity entity = null; + + // CraftBukkit - use the worlds array list + for (WorldServer worldserver : minecraftServer.worlds) { + if (worldserver != null) { + entity = packetplayinspectate.a(worldserver); + if (entity != null) { + break; + } + } + } + + if (entity != null) { + this.player.setSpectatorTarget(this.player); + this.player.mount(null); + this.player.getBukkitEntity().teleport(entity.getBukkitEntity(), PlayerTeleportEvent.TeleportCause.SPECTATE); + } + } + } + // CraftBukkit end + + // CraftBukkit start + public void a(PacketPlayInResourcePackStatus packetplayinresourcepackstatus) { + PlayerConnectionUtils.ensureMainThread(packetplayinresourcepackstatus, this, this.player.u()); + PlayerResourcePackStatusEvent.Status status = PlayerResourcePackStatusEvent.Status + .values()[packetplayinresourcepackstatus.b.ordinal()]; + + this.server.getPluginManager() + .callEvent(new PlayerResourcePackStatusEvent(getPlayer(), status, packetplayinresourcepackstatus.a)); + } + + public void a(IChatBaseComponent ichatbasecomponent) { + // CraftBukkit start - Rarely it would send a disconnect line twice + if (processedDisconnect) { + return; + } else { + processedDisconnect = true; + } + + PlayerConnection.c.info("{} lost connection: {}", player.getName(), ichatbasecomponent.c()); + player.q(); + + String quitMessage = minecraftServer.getPlayerList().disconnect(player); + if (quitMessage != null && !quitMessage.isEmpty()) { + minecraftServer.getPlayerList().sendMessage(CraftChatMessage.fromString(quitMessage)); + } + } + + // Azurite start - lazily/queue send packet method + public void sendPackets(List> packets) { + if (!packets.isEmpty()) { + networkManager.handle(packets); + } + } + + public void writePacketLazily(Packet packet) { + networkManager.writePacketLazily(packet); + } + + // We use this if there are packets that should not block entity tracker updating + public void queueEntityTrackerPacket(Packet packet, int trackerThread) { + if (networkManager.shouldSend(packet)) { + player.trackerQueueRef[trackerThread].add(packet); + } + } + // Azurite end + + public void sendPacket(Packet packet) { + if (packet == null || processedDisconnect) + return; + + if (networkManager.shouldSend(packet)) { + sendPacketSilently(packet); + } + } + + public void sendPacketSilently(Packet packet) { + if (packet == null || processedDisconnect) + return; + + if (packet instanceof PacketPlayOutChat) { + EntityHuman.EnumChatVisibility vis = player.getChatFlags(); + if (vis == EntityHuman.EnumChatVisibility.HIDDEN || vis == EntityHuman.EnumChatVisibility.SYSTEM && !((PacketPlayOutChat) packet).b()) + return; + } else if (packet instanceof PacketPlayOutSpawnPosition) { + PacketPlayOutSpawnPosition spawnPos = (PacketPlayOutSpawnPosition) packet; + player.compassTarget = new Location(getPlayer().getWorld(), spawnPos.position.getX(), spawnPos.position.getY(), spawnPos.position.getZ()); + } else if (packet instanceof PacketPlayOutTileEntityData) { + // Beanes - don't send useless packets + PacketPlayOutTileEntityData wrapper = (PacketPlayOutTileEntityData) packet; + if (wrapper.b == 3) { // Don't send beacons if ticking is off for it + if (!AzuriteConfig.tickBeacons.getValue()) { + return; + } + } else if (wrapper.b == 2) { // Don't send command block data if it's disabled + if (!MinecraftServer.getServer().getEnableCommandBlock()) { + return; + } + } + } else if (packet instanceof PacketPlayOutSetSlot) { + /* if (player.isEating() && packet.getId() == ) { + // Beanes - patch run & eating + if (AzuriteConfig.patchDropEatRunBug.getValue()) { + PacketPlayOutTransaction transaction = new PacketPlayOutTransaction(0, (short) (Short.MAX_VALUE - 1), false); + player.playerConnection.networkManager.writePacketLazily(transaction); + } else + } */ + + } + + if (AzuriteConfig.playerTeleportTracker.getValue() && packet instanceof PacketPlayOutPosition) { + PacketPlayOutPosition positionUpdate = (PacketPlayOutPosition) packet; + + boolean relative = positionUpdate.getFlags().contains(PacketPlayOutPosition.EnumPlayerTeleportFlags.X) || positionUpdate.getFlags().contains(PacketPlayOutPosition.EnumPlayerTeleportFlags.Y) || positionUpdate.getFlags().contains(PacketPlayOutPosition.EnumPlayerTeleportFlags.Z); + + AsyncCatcher.catchOp("Teleportation should never happen async"); + teleportQueue.add(new QueuedTeleport(positionUpdate.getX(), positionUpdate.getY(), positionUpdate.getZ(), relative)); + } + + networkManager.handle(packet); + + // Beanes - fix backpacking + if (packet instanceof PacketPlayOutOpenWindow) { + PacketPlayOutTransaction packetplayouttransaction = new PacketPlayOutTransaction(((PacketPlayOutOpenWindow) packet).getWindowId(), Short.MAX_VALUE, false); + sendPacket(packetplayouttransaction); + } + } + + public void a(PacketPlayInHeldItemSlot packetplayinhelditemslot) { + PlayerConnectionUtils.ensureMainThread(packetplayinhelditemslot, this, this.player.u()); + + // CraftBukkit start + if (this.player.dead) + return; + + int slot = packetplayinhelditemslot.a(); + if (slot >= 0 && slot < PlayerInventory.getHotbarSize()) { // Vortex - Anti crash + PlayerItemHeldEvent event = new PlayerItemHeldEvent(this.getPlayer(), this.player.inventory.itemInHandIndex, slot); + this.server.getPluginManager().callEvent(event); + this.player.resetIdleTimer(); + if (event.isCancelled()) { + this.sendPacket(new PacketPlayOutHeldItemSlot(this.player.inventory.itemInHandIndex)); + return; + } + // CraftBukkit end + this.player.inventory.itemInHandIndex = slot; + + // Rivals start + if (player.hookedFish != null) { + player.hookedFish.die(); + } + // Rivals end + + // Beanes - patch drop eat run bug + player.expectingItemUse = false; + + // Beanes - update hand attributes on held item slot change + player.checkHandAttributes(); + } else { + PlayerConnection.c.warn("{} tried to set an invalid carried item", this.player.getName()); + this.disconnect("Invalid hotbar selection (Hacking?)"); // CraftBukkit //Spigot "Nope" -> Descriptive reason + } + } + + public void a(PacketPlayInChat packetplayinchat) { + // CraftBukkit start - async chat + boolean isSync = packetplayinchat.a().startsWith("/"); + if (isSync) { + PlayerConnectionUtils.ensureMainThread(packetplayinchat, this, this.player.u()); + } + // CraftBukkit end + if (this.player.dead || this.player.getChatFlags() == EntityHuman.EnumChatVisibility.HIDDEN) { + ChatMessage chatmessage = new ChatMessage("chat.cannotSend"); + chatmessage.getChatModifier().setColor(EnumChatFormat.RED); + this.sendPacket(new PacketPlayOutChat(chatmessage)); + } else { + this.player.resetIdleTimer(); + String s = StringUtils.normalizeSpace(packetplayinchat.a()); + + for (int i = 0; i < s.length(); ++i) { + if (!SharedConstants.isAllowedChatCharacter(s.charAt(i))) { + // CraftBukkit start - threadsafety + if (!isSync) { + Waitable waitable = new Waitable() { + @Override + protected Object evaluate() { + PlayerConnection.this.disconnect("Illegal characters in chat"); + return null; + } + }; + + this.minecraftServer.postToMainThreadRunnable(waitable); + + try { + waitable.get(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } catch (ExecutionException e) { + throw new RuntimeException(e); + } + } else { + this.disconnect("Illegal characters in chat"); + } + // CraftBukkit end + return; + } + } + + // CraftBukkit start + if (isSync) { + try { + this.minecraftServer.server.playerCommandState = true; + this.handleCommand(s); + } finally { + this.minecraftServer.server.playerCommandState = false; + } + } else if (s.isEmpty()) { + c.warn("{} tried to send an empty message", this.player.getName()); + } else if (getPlayer().isConversing()) { + // Spigot start + final String message = s; + this.minecraftServer.postToMainThreadRunnable(new Waitable() { + @Override + protected Object evaluate() { + getPlayer().acceptConversationInput(message); + return null; + } + }); + // Spigot end + } else if (this.player.getChatFlags() == EntityHuman.EnumChatVisibility.SYSTEM) { // Re-add "Command Only" + // flag check + ChatMessage chatmessage = new ChatMessage("chat.cannotSend"); + + chatmessage.getChatModifier().setColor(EnumChatFormat.RED); + this.sendPacket(new PacketPlayOutChat(chatmessage)); + } else { + this.chat(s, true); + // CraftBukkit end - the below is for reference. :) + } + + // Spigot start - spam exclusions + boolean counted = true; + for (String exclude : org.spigotmc.SpigotConfig.spamExclusions) { + if (exclude != null && s.startsWith(exclude)) { + counted = false; + break; + } + } + // Spigot end + // CraftBukkit start - replaced with thread safe throttle + // this.chatThrottle += 20; + if (counted && chatSpamField.addAndGet(this, 20) > 200 && !this.minecraftServer.getPlayerList().isOp(this.player.getProfile())) { // Spigot + if (!isSync) { + Waitable waitable = new Waitable() { + @Override + protected Object evaluate() { + PlayerConnection.this.disconnect(LanguageConfig.disconnectSpam.getValue()); + return null; + } + }; + + this.minecraftServer.postToMainThreadRunnable(waitable); + + try { + waitable.get(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } catch (ExecutionException e) { + throw new RuntimeException(e); + } + } else { + this.disconnect(LanguageConfig.disconnectSpam.getValue()); + } + // CraftBukkit end + } + + } + } +// CraftBukkit end + + // CraftBukkit start - add method + public void chat(String s, boolean async) { + if (s.isEmpty() || this.player.getChatFlags() == EntityHuman.EnumChatVisibility.HIDDEN) { + return; + } + + if (!async && s.startsWith("/")) { + // PaperSpigot Start + if (!org.bukkit.Bukkit.isPrimaryThread()) { + final String fCommandLine = s; + MinecraftServer.LOGGER.log(org.apache.logging.log4j.Level.ERROR, + "Command Dispatched Async: " + fCommandLine); + MinecraftServer.LOGGER.log(org.apache.logging.log4j.Level.ERROR, + "Please notify author of plugin causing this execution to fix this bug! see: http://bit.ly/1oSiM6C", + new Throwable()); + Waitable wait = new Waitable() { + @Override + protected Object evaluate() { + chat(fCommandLine, false); + return null; + } + }; + minecraftServer.postToMainThreadRunnable(wait); + try { + wait.get(); + return; + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); // This is proper habit for java. If we aren't handling it, pass it on! + } catch (Exception e) { + throw new RuntimeException("Exception processing chat command", e.getCause()); + } + } + // PaperSpigot End + this.handleCommand(s); + } else if (this.player.getChatFlags() != EntityHuman.EnumChatVisibility.SYSTEM) { + Player player = this.getPlayer(); + AsyncPlayerChatEvent event = new AsyncPlayerChatEvent(async, player, s, new LazyPlayerSet()); + this.server.getPluginManager().callEvent(event); + if (PlayerChatEvent.getHandlerList().getRegisteredListeners().length != 0) { + // Evil plugins still listening to deprecated event + final PlayerChatEvent queueEvent = new PlayerChatEvent(player, event.getMessage(), event.getFormat(), event.getRecipients()); + queueEvent.setCancelled(event.isCancelled()); + Waitable waitable = new Waitable() { + @Override + protected Object evaluate() { + org.bukkit.Bukkit.getPluginManager().callEvent(queueEvent); + + if (queueEvent.isCancelled()) { + return null; + } + + String message = String.format(queueEvent.getFormat(), queueEvent.getPlayer().getDisplayName(), queueEvent.getMessage()); + PlayerConnection.this.minecraftServer.console.sendMessage(message); + if (((LazyPlayerSet) queueEvent.getRecipients()).isLazy()) { + for (EntityPlayer player : PlayerConnection.this.minecraftServer.getPlayerList().players) { + player.sendMessage(CraftChatMessage.fromString(message)); + } + } else { + for (Player player : queueEvent.getRecipients()) { + player.sendMessage(message); + } + } + return null; + } + }; + if (async) { + minecraftServer.postToMainThreadRunnable(waitable); + } else { + waitable.run(); + } + try { + waitable.get(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); // This is proper habit for java. If we aren't handling it, pass it on! + } catch (ExecutionException e) { + throw new RuntimeException("Exception processing chat event", e.getCause()); + } + } else { + if (event.isCancelled()) { + return; + } + + s = String.format(event.getFormat(), event.getPlayer().getDisplayName(), event.getMessage()); + minecraftServer.console.sendMessage(s); + if (((LazyPlayerSet) event.getRecipients()).isLazy()) { + for (EntityPlayer recipient : minecraftServer.getPlayerList().players) { + recipient.sendMessage(CraftChatMessage.fromString(s)); + } + } else { + for (Player recipient : event.getRecipients()) { + recipient.sendMessage(s); + } + } + } + } + } + + private void handleCommand(String s) { + // CraftBukkit start - whole method + if (org.spigotmc.SpigotConfig.logCommands) // Spigot + c.info("{} issued server command: {}", this.player.getName(), s); + + CraftPlayer player = this.getPlayer(); + + PlayerCommandPreprocessEvent event = new PlayerCommandPreprocessEvent(player, s, new LazyPlayerSet()); + this.server.getPluginManager().callEvent(event); + + getPlayer().getHandle().lastActivity = System.currentTimeMillis(); + + if (event.isCancelled()) { + return; + } + + try { + this.server.dispatchCommand(event.getPlayer(), event.getMessage().substring(1)); + } catch (org.bukkit.command.CommandException ex) { + player.sendMessage( + org.bukkit.ChatColor.RED + "An internal error occurred while attempting to perform this command"); + java.util.logging.Logger.getLogger(PlayerConnection.class.getName()).log(java.util.logging.Level.SEVERE, + null, ex); + } + } + + public void a(PacketPlayInArmAnimation packetplayinarmanimation) { + PlayerConnectionUtils.ensureMainThread(packetplayinarmanimation, this, this.player.u()); + + if (this.player.dead) + return; + + this.player.resetIdleTimer(); + + // Beanes - fix backpacking + this.player.checkBackpacking(); + + final float f1 = this.player.pitch; + final float f2 = this.player.yaw; + + Vec3D vec3d = new Vec3D(player.locX, player.locY + this.player.getHeadHeight(), player.locZ); + + float f5 = -MathHelper.cos(-f1 * 0.017453292F); + double d3 = player.playerInteractManager.getGameMode() == WorldSettings.EnumGamemode.CREATIVE ? 5.0D : 4.5D; + + MovingObjectPosition movingobjectposition = this.player.world.rayTrace(vec3d, vec3d.add(MathHelper.sin(-f2 * 0.017453292F - 3.1415927F) * f5 * d3, MathHelper.sin(-f1 * 0.017453292F) * d3, MathHelper.cos(-f2 * 0.017453292F - 3.1415927F) * f5 * d3), false); + + // Beanes - cps cap + if (movingobjectposition == null || movingobjectposition.type != MovingObjectPosition.EnumMovingObjectType.BLOCK) { + ItemStack stack = player.inventory.getItemInHand(); + if (stack == null || (stack.getItem() != Items.FISHING_ROD && stack.getItem() != Items.FLINT_AND_STEEL)) { + if (!AzuriteConfig.cpsCapSwordOnly.getValue() || (stack != null && stack.getItem() instanceof ItemSword)) { + this.player.registerSwing(); // Beanes - cps penalty cap + } + } + CraftEventFactory.callPlayerInteractEvent(this.player, Action.LEFT_CLICK_AIR, this.player.inventory.getItemInHand()); + } + + // Arm swing animation + PlayerAnimationEvent event = new PlayerAnimationEvent(this.getPlayer()); + this.server.getPluginManager().callEvent(event); + + if (event.isCancelled()) + return; + // CraftBukkit end + if ((System.currentTimeMillis() >= this.nextValidSwing)) { + this.player.justSwing(); + this.nextValidSwing = System.currentTimeMillis() + 5L * 50; + } + } + + public void a(PacketPlayInEntityAction packetplayinentityaction) { + PlayerConnectionUtils.ensureMainThread(packetplayinentityaction, this, this.player.u()); + + // Beanes - better slowdown + if (packetplayinentityaction.b() == PacketPlayInEntityAction.EnumPlayerAction.START_SPRINTING) { + Azurite.getInstance().getBetterSlowdown().startSprint(player.getUniqueID()); + } else if (packetplayinentityaction.b() == PacketPlayInEntityAction.EnumPlayerAction.STOP_SPRINTING) { + Azurite.getInstance().getBetterSlowdown().stopSprint(player.getUniqueID()); + } + + // CraftBukkit start + if (this.player.dead) return; + switch (packetplayinentityaction.b()) { + case START_SNEAKING: + case STOP_SNEAKING: + PlayerToggleSneakEvent event = new PlayerToggleSneakEvent(this.getPlayer(), packetplayinentityaction.b() == PacketPlayInEntityAction.EnumPlayerAction.START_SNEAKING); + this.server.getPluginManager().callEvent(event); + + if (event.isCancelled()) { + return; + } + break; + case START_SPRINTING: + case STOP_SPRINTING: + PlayerToggleSprintEvent e2 = new PlayerToggleSprintEvent(this.getPlayer(), packetplayinentityaction.b() == PacketPlayInEntityAction.EnumPlayerAction.START_SPRINTING); + this.server.getPluginManager().callEvent(e2); + + if (e2.isCancelled()) { + return; + } + break; + } + // CraftBukkit end + this.player.resetIdleTimer(); + switch (PlayerConnection.SyntheticClass_1.b[packetplayinentityaction.b().ordinal()]) { + case 1: + // Beanes - fix backpacking + this.player.checkBackpacking(); + this.player.setSneaking(true); + break; + + case 2: + this.player.setSneaking(false); + break; + + case 3: + this.player.setSneaking(false); // Beanes - you can't sneak and sprint :P + this.player.setSprinting(true); + + // Beanes - constant kb + player.shouldDealSprintKnockbackForConstantKnockback = true; + + // Beanes - fix backpacking + this.player.checkBackpacking(); + + // Azurite - stop using item if you sprint + if (!AzuriteConfig.patchDropEatRunBug.getValue() && (player.isBlocking() || (AzuriteConfig.patchRunEatBug.getValue() && player.isEating()))) { + player.bU(); // stopUsingItem + } + break; + + case 4: + // Beanes - constant kb + player.shouldDealSprintKnockbackForConstantKnockback = false; + + this.player.setSneaking(false); + this.player.setSprinting(false); + break; + + case 5: + this.player.a(false, true, true); + break; + + case 6: + if (this.player.vehicle instanceof EntityHorse) { + ((EntityHorse) this.player.vehicle).v(packetplayinentityaction.c()); + } + break; + + case 7: + if (this.player.vehicle instanceof EntityHorse) { + ((EntityHorse) this.player.vehicle).g(this.player); + } + break; + + default: + throw new IllegalArgumentException("Invalid client command!"); + } + + } + + public void betterHitsAttack(int entityId) { + PacketPlayInUseEntity packet = new PacketPlayInUseEntity(); + packet.a = entityId; + packet.action = PacketPlayInUseEntity.EnumEntityUseAction.ATTACK; + this.player.u().postToMainThreadRunnable(() -> this.useEntity(packet, false)); + } + + public void a(PacketPlayInUseEntity packetplayinuseentity) { + PlayerConnectionUtils.ensureMainThread(packetplayinuseentity, this, this.player.u()); + useEntity(packetplayinuseentity, true); + } + + public void useEntity(PacketPlayInUseEntity packetplayinuseentity, boolean cpsCap) { + if (this.player.dead) + return; // CraftBukkit + + // Beanes - cps cap + if (packetplayinuseentity.a() == PacketPlayInUseEntity.EnumEntityUseAction.ATTACK && cpsCap) { + ItemStack stack = player.inventory.getItemInHand(); + if (!AzuriteConfig.cpsCapSwordOnly.getValue() || (stack != null && stack.getItem() instanceof ItemSword)) { + player.registerAttack(); + } + } + + WorldServer worldserver = this.minecraftServer.getWorldServer(this.player.dimension); + Entity entity = packetplayinuseentity.a(worldserver); + // Spigot Start + if (entity == player && !player.isSpectator()) { + disconnect("Cannot interact with self!"); + return; + } + // Spigot End + this.player.resetIdleTimer(); + if (entity != null) { + double d0 = 81.0D; + if (AzuriteConfig.serverSideHitDetection.getValue() && !this.player.hasLineOfSight(entity)) { + d0 = 9.0D; + } + if (this.player.h(entity) < d0) { + ItemStack itemInHand = this.player.inventory.getItemInHand(); // CraftBukkit + + if (packetplayinuseentity.a() == PacketPlayInUseEntity.EnumEntityUseAction.INTERACT + || packetplayinuseentity.a() == PacketPlayInUseEntity.EnumEntityUseAction.INTERACT_AT) { + // CraftBukkit start + boolean triggerLeashUpdate = itemInHand != null && itemInHand.getItem() == Items.LEAD + && entity instanceof EntityInsentient; + Item origItem = this.player.inventory.getItemInHand() == null ? null + : this.player.inventory.getItemInHand().getItem(); + PlayerInteractEntityEvent event; + if (packetplayinuseentity.a() == PacketPlayInUseEntity.EnumEntityUseAction.INTERACT) { + event = new PlayerInteractEntityEvent(this.getPlayer(), entity.getBukkitEntity()); + } else { + Vec3D target = packetplayinuseentity.b(); + event = new PlayerInteractAtEntityEvent(this.getPlayer(), entity.getBukkitEntity(), + new org.bukkit.util.Vector(target.a, target.b, target.c)); + } + this.server.getPluginManager().callEvent(event); + + if (triggerLeashUpdate && (event.isCancelled() || this.player.inventory.getItemInHand() == null + || this.player.inventory.getItemInHand().getItem() != Items.LEAD)) { + // Refresh the current leash state + this.sendPacket( + new PacketPlayOutAttachEntity(1, entity, ((EntityInsentient) entity).getLeashHolder())); + } + + if (event.isCancelled() || this.player.inventory.getItemInHand() == null + || this.player.inventory.getItemInHand().getItem() != origItem) { + // Refresh the current entity metadata + PacketPlayOutEntityMetadata metadata = new PacketPlayOutEntityMetadata(entity.getId(), entity.datawatcher, true); + metadata.fixHealth(); // Beanes - correctly scale health + if (!AzuriteConfig.selfPotionParticles.getValue()) { + metadata.removePotionParticles(); + } + this.sendPacket(metadata); + } + + if (event.isCancelled()) { + return; + } + // CraftBukkit end + } + if (packetplayinuseentity.a() == PacketPlayInUseEntity.EnumEntityUseAction.INTERACT) { + this.player.u(entity); + + // CraftBukkit start + if (itemInHand != null && itemInHand.count <= -1) { + this.player.updateInventory(this.player.activeContainer); + } + // CraftBukkit end + } else if (packetplayinuseentity.a() == PacketPlayInUseEntity.EnumEntityUseAction.INTERACT_AT) { + entity.a(this.player, packetplayinuseentity.b()); + + // CraftBukkit start + if (itemInHand != null && itemInHand.count <= -1) { + this.player.updateInventory(this.player.activeContainer); + } + // CraftBukkit end + } else if (packetplayinuseentity.a() == PacketPlayInUseEntity.EnumEntityUseAction.ATTACK) { + if (entity instanceof EntityItem || entity instanceof EntityExperienceOrb || entity instanceof EntityArrow || (entity == this.player && !player.isSpectator())) { // CraftBukkit + this.disconnect("Attempting to attack an invalid entity"); + this.minecraftServer.warning("Player " + this.player.getName() + " tried to attack an invalid entity"); + return; + } + + this.player.attack(entity); + + // CraftBukkit start + if (itemInHand != null && itemInHand.count <= -1) { + this.player.updateInventory(this.player.activeContainer); + } + // CraftBukkit end + } + } + } + } + + public void a(PacketPlayInClientCommand packetplayinclientcommand) { + PlayerConnectionUtils.ensureMainThread(packetplayinclientcommand, this, this.player.u()); + this.player.resetIdleTimer(); + PacketPlayInClientCommand.EnumClientCommand packetplayinclientcommand_enumclientcommand = packetplayinclientcommand + .a(); + + switch (SyntheticClass_1.c[packetplayinclientcommand_enumclientcommand.ordinal()]) { + case 1: + if (this.player.viewingCredits) { + // CraftBukkit - reroute logic through custom + // portal management + this.minecraftServer.getPlayerList().changeDimension(this.player, 0, PlayerTeleportEvent.TeleportCause.END_PORTAL); + } else if (this.player.u().getWorldData().isHardcore()) { + GameProfileBanEntry gameprofilebanentry = new GameProfileBanEntry(this.player.getProfile(), null, + "(You just lost the game)", null, "Death in Hardcore"); + + this.minecraftServer.getPlayerList().getProfileBans().add(gameprofilebanentry); + this.player.playerConnection.disconnect("You have died. Game over, man, it's game over!"); + } else if (this.player.getHealth() <= 0.0F) { + this.player = this.minecraftServer.getPlayerList().moveToWorld(this.player, 0, false); + } + break; + + case 2: + this.player.getStatisticManager().a(this.player); + break; + case 3: + this.player.inventoryOpen = true; // Beanes - fix backpacking + this.player.b(AchievementList.f); + } + } + + public void a(PacketPlayInCloseWindow packetplayinclosewindow) { + PlayerConnectionUtils.ensureMainThread(packetplayinclosewindow, this, this.player.u()); + if (this.player.dead) + return; // CraftBukkit + + this.player.inventoryOpen = false; + + if (packetplayinclosewindow.id == player.activeContainer.windowId) { + CraftEventFactory.handleInventoryCloseEvent(this.player); + this.player.p(); + if (this.player.isAnimating()) { + this.player.bU(); // stopUsingItem | Vortex - Fix for eating and blocking and etc while running + } + } + } + + public void a(PacketPlayInWindowClick packetplayinwindowclick) { + PlayerConnectionUtils.ensureMainThread(packetplayinwindowclick, this, player.u()); + if (player.dead) + return; // CraftBukkit + + player.resetIdleTimer(); + if (player.activeContainer.windowId == packetplayinwindowclick.a() && player.activeContainer.c(player)) { + int b = packetplayinwindowclick.b(); + boolean cancelled = player.isSpectator(); + + if (b < 0 && b != -999 && b != -1) { // Vortex - Anticrash + return; + } + + InventoryView inventory = player.activeContainer.getBukkitView(); + + // Vortex - Anticrash + int maxSlots = inventory.countSlots(); + if (inventory.getBottomInventory().getType() == InventoryType.PLAYER && + inventory.getTopInventory().getType() == InventoryType.CRAFTING) { + maxSlots += 4; + } + if (b >= maxSlots) + return; + + SlotType type = CraftInventoryView.getSlotType(inventory, b); + + InventoryClickEvent event; + ClickType click = ClickType.UNKNOWN; + InventoryAction action = InventoryAction.UNKNOWN; + + ItemStack itemstack = null; + int c = packetplayinwindowclick.c(); + int f = packetplayinwindowclick.f(); + if (b == -1) { + type = SlotType.OUTSIDE; // override + click = c == 0 ? ClickType.WINDOW_BORDER_LEFT : ClickType.WINDOW_BORDER_RIGHT; + action = InventoryAction.NOTHING; + } else if (f == 0) { + if (c == 0) { + click = ClickType.LEFT; + } else if (c == 1) { + click = ClickType.RIGHT; + } + if (c == 0 || c == 1) { + action = InventoryAction.NOTHING; // Don't want to repeat ourselves + if (b < 0) { // Paper + if (player.inventory.getCarried() != null) { + action = c == 0 ? InventoryAction.DROP_ALL_CURSOR : InventoryAction.DROP_ONE_CURSOR; + } + } else { + Slot slot = this.player.activeContainer.getSlot(b); + if (slot != null) { + ItemStack clickedItem = slot.getItem(); + ItemStack cursor = player.inventory.getCarried(); + if (clickedItem == null) { + if (cursor != null) { + action = c == 0 ? InventoryAction.PLACE_ALL : InventoryAction.PLACE_ONE; + } + } else if (slot.isAllowed(player)) { + if (cursor == null) { + action = c == 0 ? InventoryAction.PICKUP_ALL : InventoryAction.PICKUP_HALF; + } else if (slot.isAllowed(cursor)) { + if (clickedItem.doMaterialsMatch(cursor) && ItemStack.equals(clickedItem, cursor)) { + int toPlace = c == 0 ? cursor.count : 1; + toPlace = Math.min(toPlace, clickedItem.getMaxStackSize() - clickedItem.count); + toPlace = Math.min(toPlace, + slot.inventory.getMaxStackSize() - clickedItem.count); + if (toPlace == 1) { + action = InventoryAction.PLACE_ONE; + } else if (toPlace == cursor.count) { + action = InventoryAction.PLACE_ALL; + } else if (toPlace < 0) { + action = toPlace != -1 ? InventoryAction.PICKUP_SOME + : InventoryAction.PICKUP_ONE; // this happens with oversized stacks + } else if (toPlace != 0) { + action = InventoryAction.PLACE_SOME; + } + } else if (cursor.count <= slot.getMaxStackSize()) { + action = InventoryAction.SWAP_WITH_CURSOR; + } + } else if (cursor.getItem() == clickedItem.getItem() + && (!cursor.usesData() || cursor.getData() == clickedItem.getData()) + && ItemStack.equals(cursor, clickedItem)) { + if (clickedItem.count >= 0) { + if (clickedItem.count + cursor.count <= cursor.getMaxStackSize()) { + // As of 1.5, this is result slots only + action = InventoryAction.PICKUP_ALL; + } + } + } + } + } + } + } + } else if (f == 1) { + if (c == 0) { + click = ClickType.SHIFT_LEFT; + } else if (c == 1) { + click = ClickType.SHIFT_RIGHT; + } + if (c == 0 || c == 1) { + if (b < 0) { + action = InventoryAction.NOTHING; + } else { + Slot slot = this.player.activeContainer.getSlot(b); + if (slot != null && slot.isAllowed(this.player) && slot.hasItem()) { + action = InventoryAction.MOVE_TO_OTHER_INVENTORY; + } else { + action = InventoryAction.NOTHING; + } + } + } + } else if (f == 2) { + if (c >= 0 && c < 9) { + click = ClickType.NUMBER_KEY; + Slot clickedSlot = this.player.activeContainer.getSlot(b); + if (clickedSlot.isAllowed(player)) { + ItemStack hotbar = this.player.inventory.getItem(c); + boolean canCleanSwap = hotbar == null || (clickedSlot.inventory == player.inventory && clickedSlot.isAllowed(hotbar)); + if (clickedSlot.hasItem()) { + if (canCleanSwap) { + action = InventoryAction.HOTBAR_SWAP; + } else { + int firstEmptySlot = player.inventory.getFirstEmptySlotIndex(); + if (firstEmptySlot > -1) { + action = InventoryAction.HOTBAR_MOVE_AND_READD; + } else { + action = InventoryAction.NOTHING; // This is not sane! Mojang: You should test for + // other slots of same type + } + } + } else if (!clickedSlot.hasItem() && hotbar != null && clickedSlot.isAllowed(hotbar)) { + action = InventoryAction.HOTBAR_SWAP; + } else { + action = InventoryAction.NOTHING; + } + } else { + action = InventoryAction.NOTHING; + } + } + } else if (f == 3) { + if (c == 2) { + click = ClickType.MIDDLE; + if (b == -999) { + action = InventoryAction.NOTHING; + } else { + Slot slot = this.player.activeContainer.getSlot(b); + if (slot != null && slot.hasItem() && player.abilities.canInstantlyBuild + && player.inventory.getCarried() == null) { + action = InventoryAction.CLONE_STACK; + } else { + action = InventoryAction.NOTHING; + } + } + } + } else if (f == 4) { + if (b >= 0) { + if (c == 0) { + click = ClickType.DROP; + Slot slot = this.player.activeContainer.getSlot(b); + if (slot != null && slot.hasItem() && slot.isAllowed(player) && slot.getItem() != null + && slot.getItem().getItem() != Item.getItemOf(Blocks.AIR)) { + action = InventoryAction.DROP_ONE_SLOT; + } else { + action = InventoryAction.NOTHING; + } + } else if (c == 1) { + click = ClickType.CONTROL_DROP; + Slot slot = this.player.activeContainer.getSlot(b); + if (slot != null && slot.hasItem() && slot.isAllowed(player) && slot.getItem() != null + && slot.getItem().getItem() != Item.getItemOf(Blocks.AIR)) { + action = InventoryAction.DROP_ALL_SLOT; + } else { + action = InventoryAction.NOTHING; + } + } + } else { + // Sane default (because this happens when they are holding nothing. Don't ask + // why.) + click = ClickType.LEFT; + if (c == 1) { + click = ClickType.RIGHT; + } + action = InventoryAction.NOTHING; + } + } else if (f == 5) { + itemstack = this.player.activeContainer.clickItem(b, c, 5, this.player); + } else if (f == 6) { + click = ClickType.DOUBLE_CLICK; + action = InventoryAction.NOTHING; + if (packetplayinwindowclick.b() >= 0 && this.player.inventory.getCarried() != null) { + ItemStack cursor = this.player.inventory.getCarried(); + // Quick check for if we have any of the item + if (inventory.getTopInventory() + .contains(org.bukkit.Material.getMaterial(Item.getId(cursor.getItem()))) + || inventory.getBottomInventory() + .contains(org.bukkit.Material.getMaterial(Item.getId(cursor.getItem())))) { + action = InventoryAction.COLLECT_TO_CURSOR; + } + } + } + + if (f != 5) { + if (click == ClickType.NUMBER_KEY) { + event = new InventoryClickEvent(inventory, type, b, click, action, c); + } else { + event = new InventoryClickEvent(inventory, type, b, click, action); + } + + org.bukkit.inventory.Inventory top = inventory.getTopInventory(); + if (packetplayinwindowclick.b() == 0 && top instanceof CraftingInventory) { + org.bukkit.inventory.Recipe recipe = ((CraftingInventory) top).getRecipe(); + if (recipe != null) { + if (click == ClickType.NUMBER_KEY) { + event = new CraftItemEvent(recipe, inventory, type, b, click, action, c); + } else { + event = new CraftItemEvent(recipe, inventory, type, b, click, action); + } + } + } + + event.setCancelled(cancelled || (AzuriteConfig.oldEnchantingSystem.getValue() && + inventory.getType() == InventoryType.ENCHANTING && b == 1)); + server.getPluginManager().callEvent(event); + switch (event.getResult()) { + case ALLOW: + case DEFAULT: + itemstack = this.player.activeContainer.clickItem(b, c, f, this.player); + // PaperSpigot start - Stackable Buckets + if (itemstack != null && ((itemstack.getItem() == Items.LAVA_BUCKET && PaperSpigotConfig.stackableLavaBuckets) || (itemstack.getItem() == Items.WATER_BUCKET && PaperSpigotConfig.stackableWaterBuckets) || (itemstack.getItem() == Items.MILK_BUCKET && PaperSpigotConfig.stackableMilkBuckets))) { + if (action == InventoryAction.MOVE_TO_OTHER_INVENTORY) { + this.player.updateInventory(this.player.activeContainer); + } else { + sendPacket(new PacketPlayOutSetSlot(-1, -1, this.player.inventory.getCarried())); + sendPacket(new PacketPlayOutSetSlot(this.player.activeContainer.windowId, b, this.player.activeContainer.getSlot(b).getItem())); + } + } + // PaperSpigot end + break; + case DENY: + switch (action) { + // Modified other slots + case PICKUP_ALL: + case MOVE_TO_OTHER_INVENTORY: + case HOTBAR_MOVE_AND_READD: + case HOTBAR_SWAP: + case COLLECT_TO_CURSOR: + case UNKNOWN: + this.player.updateInventory(this.player.activeContainer); + break; + // Modified cursor and clicked + case PICKUP_SOME: + case PICKUP_HALF: + case PICKUP_ONE: + case PLACE_ALL: + case PLACE_SOME: + case PLACE_ONE: + case SWAP_WITH_CURSOR: + sendPacket(new PacketPlayOutSetSlot(-1, -1, this.player.inventory.getCarried())); + sendPacket(new PacketPlayOutSetSlot(this.player.activeContainer.windowId, b, + this.player.activeContainer.getSlot(b).getItem())); + break; + // Modified clicked only + case DROP_ALL_SLOT: + case DROP_ONE_SLOT: + sendPacket(new PacketPlayOutSetSlot(this.player.activeContainer.windowId, b, + this.player.activeContainer.getSlot(b).getItem())); + break; + // Modified cursor only + case DROP_ALL_CURSOR: + case DROP_ONE_CURSOR: + case CLONE_STACK: + sendPacket(new PacketPlayOutSetSlot(-1, -1, this.player.inventory.getCarried())); + break; + // Nothing + case NOTHING: + break; + } + return; + } + + if (event instanceof CraftItemEvent) { + // Need to update the inventory on crafting to + // correctly support custom recipes + player.updateInventory(player.activeContainer); + } + } + // CraftBukkit end + + if (ItemStack.matches(packetplayinwindowclick.e(), itemstack)) { + // Beanes - don't send this useless packet + // sendPacket(new PacketPlayOutTransaction(packetplayinwindowclick.a(), packetplayinwindowclick.d(), true)); + player.g = true; + player.activeContainer.b(); + player.broadcastCarriedItem(); + player.g = false; + } else { + n.put(this.player.activeContainer.windowId, packetplayinwindowclick.d()); + sendPacket(new PacketPlayOutTransaction(packetplayinwindowclick.a(), packetplayinwindowclick.d(), false)); + player.activeContainer.a(player, false); + ArrayList arraylist1 = Lists.newArrayList(); + + for (int j = 0; j < player.activeContainer.c.size(); ++j) { + arraylist1.add(player.activeContainer.c.get(j).getItem()); + } + + player.a(player.activeContainer, arraylist1); + } + } + + } + + public void a(PacketPlayInEnchantItem packetplayinenchantitem) { + PlayerConnectionUtils.ensureMainThread(packetplayinenchantitem, this, this.player.u()); + this.player.resetIdleTimer(); + if (this.player.activeContainer.windowId == packetplayinenchantitem.a() + && this.player.activeContainer.c(this.player) && !this.player.isSpectator()) { + this.player.activeContainer.a(this.player, packetplayinenchantitem.b()); + this.player.activeContainer.b(); + } + + } + + public void a(PacketPlayInSetCreativeSlot packetplayinsetcreativeslot) { + PlayerConnectionUtils.ensureMainThread(packetplayinsetcreativeslot, this, this.player.u()); + if (this.player.playerInteractManager.isCreative()) { + boolean flag = packetplayinsetcreativeslot.a() < 0; + ItemStack itemstack = packetplayinsetcreativeslot.getItemStack(); + + if (itemstack != null && itemstack.hasTag() && itemstack.getTag().hasKeyOfType("BlockEntityTag", 10)) { + NBTTagCompound nbttagcompound = itemstack.getTag().getCompound("BlockEntityTag"); + + if (nbttagcompound.hasKey("x") && nbttagcompound.hasKey("y") && nbttagcompound.hasKey("z")) { + BlockPosition blockposition = new BlockPosition(nbttagcompound.getInt("x"), nbttagcompound.getInt("y"), nbttagcompound.getInt("z")); + TileEntity tileentity = this.player.world.getTileEntity(blockposition); + + if (tileentity != null) { + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + + tileentity.b(nbttagcompound1); + nbttagcompound1.remove("x"); + nbttagcompound1.remove("y"); + nbttagcompound1.remove("z"); + itemstack.a("BlockEntityTag", nbttagcompound1); + } + } + } + + boolean flag1 = packetplayinsetcreativeslot.a() >= 1 && packetplayinsetcreativeslot.a() < 36 + PlayerInventory.getHotbarSize(); + // CraftBukkit - Add invalidItems check + boolean flag2 = itemstack == null || itemstack.getItem() != null && (!invalidItems.contains(Item.getId(itemstack.getItem())) || !org.spigotmc.SpigotConfig.filterCreativeItems); // Spigot + boolean flag3 = itemstack == null || itemstack.getData() >= 0 && itemstack.count <= 64 && itemstack.count > 0; + // CraftBukkit start - Call click event + if (flag || (flag1 && !ItemStack.matches(this.player.defaultContainer.getSlot(packetplayinsetcreativeslot.a()).getItem(), packetplayinsetcreativeslot.getItemStack()))) { // Insist on valid slot + + org.bukkit.entity.HumanEntity player = this.player.getBukkitEntity(); + InventoryView inventory = new CraftInventoryView(player, player.getInventory(), this.player.defaultContainer); + org.bukkit.inventory.ItemStack item = CraftItemStack.asBukkitCopy(packetplayinsetcreativeslot.getItemStack()); + + SlotType type = SlotType.QUICKBAR; + if (flag) { + type = SlotType.OUTSIDE; + } else if (packetplayinsetcreativeslot.a() < 36) { + if (packetplayinsetcreativeslot.a() >= 5 && packetplayinsetcreativeslot.a() < 9) { + type = SlotType.ARMOR; + } else { + type = SlotType.CONTAINER; + } + } + InventoryCreativeEvent event = new InventoryCreativeEvent(inventory, type, flag ? -999 : packetplayinsetcreativeslot.a(), item); + server.getPluginManager().callEvent(event); + + itemstack = CraftItemStack.asNMSCopy(event.getCursor()); + + switch (event.getResult()) { + case ALLOW: + // Plugin cleared the id / stacksize checks + flag2 = flag3 = true; + break; + case DEFAULT: + break; + case DENY: + // Reset the slot + if (packetplayinsetcreativeslot.a() >= 0) { + sendPacket(new PacketPlayOutSetSlot(this.player.defaultContainer.windowId, packetplayinsetcreativeslot.a(), this.player.defaultContainer.getSlot(packetplayinsetcreativeslot.a()).getItem())); + sendPacket(new PacketPlayOutSetSlot(-1, -1, null)); + } + return; + } + } + // CraftBukkit end + + if (flag1 && flag2 && flag3) { + this.player.defaultContainer.setItem(packetplayinsetcreativeslot.a(), itemstack); + + this.player.defaultContainer.a(this.player, true); + } else if (flag && flag2 && flag3 && this.m < 200) { + this.m += 20; + EntityItem entityitem = this.player.drop(itemstack, true); + + if (entityitem != null) { + entityitem.j(); + } + } + } + + } + + public void a(PacketPlayInTransaction packetplayintransaction) { + PlayerConnectionUtils.ensureMainThread(packetplayintransaction, this, this.player.u()); + if (this.player.dead) + return; // CraftBukkit + + short oshort = this.n.getOrDefault(this.player.activeContainer.windowId, Short.MIN_VALUE); + + // Beanes - fix backpacking + if (packetplayintransaction.b() == Short.MAX_VALUE) { + this.player.inventoryOpen = true; + } + + // Beanes - fix drop eat run bug + if (packetplayintransaction.b() == (Short.MAX_VALUE - 1)) { + this.player.expectingItemUse = true; + this.player.expectingItemUseTicksExpire = 4; + } + + if (oshort != Short.MIN_VALUE && packetplayintransaction.b() == oshort && this.player.activeContainer.windowId == packetplayintransaction.a() && !this.player.activeContainer.c(this.player) && !this.player.isSpectator()) { + this.player.activeContainer.a(this.player, true); + } + } + + public void a(PacketPlayInUpdateSign packetplayinupdatesign) { + PlayerConnectionUtils.ensureMainThread(packetplayinupdatesign, this, this.player.u()); + if (this.player.dead) + return; + + this.player.resetIdleTimer(); + WorldServer worldserver = this.minecraftServer.getWorldServer(this.player.dimension); + BlockPosition blockposition = packetplayinupdatesign.a(); + + if (worldserver.isLoaded(blockposition)) { + TileEntity tileentity = worldserver.getTileEntity(blockposition); + + if (!(tileentity instanceof TileEntitySign)) { + return; + } + + TileEntitySign tileentitysign = (TileEntitySign) tileentity; + + if (!tileentitysign.b() || tileentitysign.c() != this.player) { + this.minecraftServer.warning("Player " + this.player.getName() + " just tried to change non-editable sign"); + this.sendPacket(new PacketPlayOutUpdateSign(tileentity.world, packetplayinupdatesign.a(), tileentitysign.lines)); // CraftBukkit + return; + } + + IChatBaseComponent[] aichatbasecomponent = packetplayinupdatesign.b(); + + // CraftBukkit start + Player player = this.server.getPlayer(this.player); + String[] lines = new String[4]; + + for (int i = 0; i < aichatbasecomponent.length; ++i) { + // PandaSpigot start - cap line length - modified clients can send longer data than normal + String line = aichatbasecomponent[i].c(); + if (line.length() > TileEntitySign.MAX_SIGN_LINE_LENGTH && TileEntitySign.MAX_SIGN_LINE_LENGTH > 0) { + int offset = line.codePoints().limit(TileEntitySign.MAX_SIGN_LINE_LENGTH).map(Character::charCount).sum(); + if (line.length() > offset) { + line = line.substring(0, offset); + } + } + lines[i] = EnumChatFormat.a(line); + // PandaSpigot end + } + + BlockPosition a = packetplayinupdatesign.a(); + SignChangeEvent event = new SignChangeEvent(player.getWorld().getBlockAt(a.getX(), a.getY(), a.getZ()), this.server.getPlayer(this.player), lines); + this.server.getPluginManager().callEvent(event); + + if (!event.isCancelled()) { + System.arraycopy(org.bukkit.craftbukkit.block.CraftSign.sanitizeLines(event.getLines()), 0, tileentitysign.lines, 0, 4); + tileentitysign.isEditable = false; + } + // CraftBukkit end + + tileentitysign.update(); + worldserver.notify(blockposition); + } + + } + + public void a(PacketPlayInKeepAlive packetplayinkeepalive) { + if (packetplayinkeepalive.a() == this.i) { + int responseTime = (int) (this.d() - this.j); + + // Beanes - fix ping "interpolation" at first keep alive + if (this.player.ping == 0 || !AzuriteConfig.playerPingInterpolation.getValue()) { + this.player.ping = responseTime; + } else { + this.player.ping = (this.player.ping * 3 + responseTime) / 4; + } + } + } + + private long d() { + return System.nanoTime() / 1000000L; + } + + public void a(PacketPlayInAbilities packetplayinabilities) { + PlayerConnectionUtils.ensureMainThread(packetplayinabilities, this, this.player.u()); + // CraftBukkit start + if (this.player.abilities.canFly && this.player.abilities.isFlying != packetplayinabilities.isFlying()) { + PlayerToggleFlightEvent event = new PlayerToggleFlightEvent(this.server.getPlayer(this.player), packetplayinabilities.isFlying()); + this.server.getPluginManager().callEvent(event); + if (!event.isCancelled()) { + this.player.abilities.isFlying = packetplayinabilities.isFlying(); // Actually set the player's flying status + } else { + this.player.updateAbilities(); // Tell the player their ability was reverted + } + } + // CraftBukkit end + } + + public void a(PacketPlayInTabComplete packetplayintabcomplete) { + PlayerConnectionUtils.ensureMainThread(packetplayintabcomplete, this, this.player.u()); + // CraftBukkit start + if (chatSpamField.addAndGet(this, 10) > 500 && !this.minecraftServer.getPlayerList().isOp(this.player.getProfile())) { + this.disconnect(LanguageConfig.disconnectSpam.getValue()); + return; + } + // CraftBukkit end + List arraylist = minecraftServer.tabCompleteCommand(this.player, packetplayintabcomplete.a(), packetplayintabcomplete.b()); // Vortex - Don't copy the list + sendPacket(new PacketPlayOutTabComplete(arraylist.toArray(new String[0]))); + } + + public void a(PacketPlayInSettings packetplayinsettings) { + PlayerConnectionUtils.ensureMainThread(packetplayinsettings, this, this.player.u()); + this.player.a(packetplayinsettings); + } + + public void a(PacketPlayInCustomPayload packetplayincustompayload) { + PlayerConnectionUtils.ensureMainThread(packetplayincustompayload, this, this.player.u()); + PacketDataSerializer pds = packetplayincustompayload.b(); + + String tag = packetplayincustompayload.a(); + + // Vortex start - Anticrash + int capacity = pds.capacity(); + if (tag == null || tag.trim().isEmpty()) { + disconnect("Invalid payload tag!"); + return; + } else if (capacity > 8192 || capacity < 1) { + disconnect("Invaid payload capacity! (" + capacity + ")"); + return; + } else if (pds.refCnt() < 1) { + disconnect("refCnt is lower than 1! (" + pds.refCnt() + ")"); + return; + } else if (pds.readableBytes() > 8192) { + disconnect("Too big packet! (" + pds.readableBytes() + ")"); + return; + } + // Vortex end + + // Vortex - use switch instead of "else if" + switch (tag) { + case "MC|BEdit": { + PacketDataSerializer packetdataserializer = new PacketDataSerializer(Unpooled.wrappedBuffer(pds)); + + try { + ItemStack itemstack = packetdataserializer.i(); + if (itemstack == null) { + return; + } + + if (!ItemBookAndQuill.b(itemstack.getTag())) { + throw new IOException("Invalid book tag!"); + } + + ItemStack itemstack1 = this.player.inventory.getItemInHand(); + if (itemstack1 != null && itemstack.getItem() == Items.WRITABLE_BOOK && itemstack.getItem() == itemstack1.getItem()) { + ItemStack newBook = itemstack1.cloneItemStack(); + if (!newBook.hasTag()) { + newBook.setTag(new NBTTagCompound()); + } + newBook.getTag().set("pages", itemstack.getTag().getList("pages", 8)); + } + + } catch (Exception exception) { + PlayerConnection.c.error("Couldn't handle book info", exception); + this.disconnect("Invalid book data!"); // CraftBukkit + return; + } + break; + } + + case "MC|BSign": { + PacketDataSerializer packetdataserializer = new PacketDataSerializer(Unpooled.wrappedBuffer(pds)); + + try { + ItemStack itemstack = packetdataserializer.i(); + if (itemstack == null) { + return; + } + if (!ItemWrittenBook.b(itemstack.getTag())) { + throw new IOException("Invalid book tag!"); + } + + ItemStack itemstack1 = this.player.inventory.getItemInHand(); + if (itemstack1 != null) { + if (itemstack.getItem() == Items.WRITTEN_BOOK && itemstack1.getItem() == Items.WRITABLE_BOOK) { + ItemStack newBook = itemstack1.cloneItemStack(); + NBTTagCompound tag1; + if (!newBook.hasTag()) { + newBook.setTag((tag1 = new NBTTagCompound())); + } else { + tag1 = newBook.getTag(); + } + tag1.set("author", new NBTTagString(this.player.getName())); + tag1.set("title", new NBTTagString(itemstack.getTag().getString("title"))); + tag1.set("pages", itemstack.getTag().getList("pages", 8)); + newBook.setItem(Items.WRITTEN_BOOK); + CraftEventFactory.handleEditBookEvent(player, newBook); // CraftBukkit + } + } + } catch (Exception exception1) { + PlayerConnection.c.error("Couldn't sign book", exception1); + this.disconnect("Invalid book data!"); // CraftBukkit + return; + } + break; + } + + case "MC|TrSel": { + try { + Container container = this.player.activeContainer; + if (container instanceof ContainerMerchant) { + ((ContainerMerchant) container).d(pds.readInt()); + } + } catch (Exception exception2) { + PlayerConnection.c.error("Couldn't select trade", exception2); + this.disconnect("Invalid trade data!"); // CraftBukkit + return; + } + break; + } + + case "MC|AdvCdm": { + if (!this.minecraftServer.getEnableCommandBlock()) { + this.player.sendMessage(new ChatMessage("advMode.notEnabled")); + } else if (this.player.getBukkitEntity().isOp() && this.player.abilities.canInstantlyBuild) { + try { + byte b0 = pds.readByte(); + CommandBlockListenerAbstract commandblocklistenerabstract = null; + + if (b0 == 0) { + TileEntity tileentity = this.player.world.getTileEntity(new BlockPosition(pds.readInt(), pds.readInt(), pds.readInt())); + + if (tileentity instanceof TileEntityCommand) { + commandblocklistenerabstract = ((TileEntityCommand) tileentity).getCommandBlock(); + } + } else if (b0 == 1) { + Entity entity = this.player.world.a(pds.readInt()); + + if (entity instanceof EntityMinecartCommandBlock) { + commandblocklistenerabstract = ((EntityMinecartCommandBlock) entity).getCommandBlock(); + } + } + + String s = pds.c(pds.readableBytes()); + boolean flag = pds.readBoolean(); + + if (commandblocklistenerabstract != null) { + commandblocklistenerabstract.setCommand(s); + commandblocklistenerabstract.a(flag); + if (!flag) { + commandblocklistenerabstract.b((IChatBaseComponent) null); + } + + commandblocklistenerabstract.h(); + this.player.sendMessage(new ChatMessage("advMode.setCommand.success", s)); + } + } catch (Exception exception3) { + PlayerConnection.c.error("Couldn't set command block", exception3); + this.disconnect("Invalid CommandBlock data!"); // CraftBukkit + return; + } + } else { + this.player.sendMessage(new ChatMessage("advMode.notAllowed")); + } + + break; + } + + case "MC|Beacon": { + + if (this.player.activeContainer instanceof ContainerBeacon) { + try { + ContainerBeacon containerbeacon = (ContainerBeacon) this.player.activeContainer; + Slot slot = containerbeacon.getSlot(0); + + if (slot.hasItem()) { + slot.a(1); + IInventory iinventory = containerbeacon.e(); + + iinventory.b(1, pds.readInt()); + iinventory.b(2, pds.readInt()); + iinventory.update(); + } + } catch (Exception exception4) { + PlayerConnection.c.error("Couldn't set beacon", exception4); + this.disconnect("Invalid beacon data!"); // CraftBukkit + return; + } + } + + break; + } + + case "MC|ItemName": { + + if (player.activeContainer instanceof ContainerAnvil) { + ContainerAnvil containeranvil = (ContainerAnvil) this.player.activeContainer; + + if (pds.readableBytes() >= 1) { + String s1 = SharedConstants.a(pds.c(32767)); + + if (s1.length() <= 30) { + containeranvil.a(s1); + } + } else { + containeranvil.a(""); + } + } + + break; + } + + case "REGISTER": { + String[] channels = pds.toString(Charsets.UTF_8).split("\0"); + if (channels.length > 124) { + disconnect("Too many channels"); // Vortex - Anti channel register spam crash + return; + } + for (String channel : channels) { + getPlayer().addChannel(channel); + } + break; + } + + case "UNREGISTER": { + String[] channels = pds.toString(Charsets.UTF_8).split("\0"); + + if (channels.length > 124) { + disconnect("Too many channels"); // Vortex - Anti channel register spam crash + return; + } + + for (String channel : channels) { + getPlayer().removeChannel(channel); + } + break; + } + + default: { + byte[] data = new byte[pds.readableBytes()]; + pds.readBytes(data); + server.getMessenger().dispatchIncomingMessage(player.getBukkitEntity(), tag, data); + break; + } + + } + + pds.release(); + } + + // CraftBukkit start - Add "isDisconnected" method + public boolean isDisconnected() { // Spigot + return !this.player.joining && !this.networkManager.channel.config().isAutoRead(); + } + + static class SyntheticClass_1 { + + static final int[] a; + static final int[] b; + static final int[] c = new int[PacketPlayInClientCommand.EnumClientCommand.values().length]; + + static { + try { + SyntheticClass_1.c[PacketPlayInClientCommand.EnumClientCommand.PERFORM_RESPAWN + .ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + + } + + try { + SyntheticClass_1.c[PacketPlayInClientCommand.EnumClientCommand.REQUEST_STATS + .ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + + } + + try { + SyntheticClass_1.c[PacketPlayInClientCommand.EnumClientCommand.OPEN_INVENTORY_ACHIEVEMENT + .ordinal()] = 3; + } catch (NoSuchFieldError ignored) { + } + + b = new int[PacketPlayInEntityAction.EnumPlayerAction.values().length]; + + try { + SyntheticClass_1.b[PacketPlayInEntityAction.EnumPlayerAction.START_SNEAKING + .ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + + } + + try { + SyntheticClass_1.b[PacketPlayInEntityAction.EnumPlayerAction.STOP_SNEAKING + .ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + + } + + try { + SyntheticClass_1.b[PacketPlayInEntityAction.EnumPlayerAction.START_SPRINTING + .ordinal()] = 3; + } catch (NoSuchFieldError ignored) { + + } + + try { + SyntheticClass_1.b[PacketPlayInEntityAction.EnumPlayerAction.STOP_SPRINTING + .ordinal()] = 4; + } catch (NoSuchFieldError ignored) { + + } + + try { + SyntheticClass_1.b[PacketPlayInEntityAction.EnumPlayerAction.STOP_SLEEPING + .ordinal()] = 5; + } catch (NoSuchFieldError ignored) { + + } + + try { + SyntheticClass_1.b[PacketPlayInEntityAction.EnumPlayerAction.RIDING_JUMP + .ordinal()] = 6; + } catch (NoSuchFieldError ignored) { + + } + + try { + SyntheticClass_1.b[PacketPlayInEntityAction.EnumPlayerAction.OPEN_INVENTORY + .ordinal()] = 7; + } catch (NoSuchFieldError ignored) { + + } + + a = new int[PacketPlayInBlockDig.EnumPlayerDigType.values().length]; + + try { + SyntheticClass_1.a[PacketPlayInBlockDig.EnumPlayerDigType.DROP_ITEM.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + + } + + try { + SyntheticClass_1.a[PacketPlayInBlockDig.EnumPlayerDigType.DROP_ALL_ITEMS + .ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + + } + + try { + SyntheticClass_1.a[PacketPlayInBlockDig.EnumPlayerDigType.RELEASE_USE_ITEM + .ordinal()] = 3; + } catch (NoSuchFieldError ignored) { + + } + + try { + SyntheticClass_1.a[PacketPlayInBlockDig.EnumPlayerDigType.START_DESTROY_BLOCK + .ordinal()] = 4; + } catch (NoSuchFieldError ignored) { + + } + + try { + SyntheticClass_1.a[PacketPlayInBlockDig.EnumPlayerDigType.ABORT_DESTROY_BLOCK + .ordinal()] = 5; + } catch (NoSuchFieldError ignored) { + + } + + try { + SyntheticClass_1.a[PacketPlayInBlockDig.EnumPlayerDigType.STOP_DESTROY_BLOCK + .ordinal()] = 6; + } catch (NoSuchFieldError ignored) { + + } + + } + } + +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PlayerConnectionUtils.java b/azurite-server/src/main/java/net/minecraft/server/PlayerConnectionUtils.java new file mode 100644 index 0000000..5174dfe --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PlayerConnectionUtils.java @@ -0,0 +1,10 @@ +package net.minecraft.server; + +public class PlayerConnectionUtils { + public static void ensureMainThread(Packet paramPacket, T paramT, IAsyncTaskHandler paramIAsyncTaskHandler) throws CancelledPacketHandleException { + if (!paramIAsyncTaskHandler.isMainThread()) { + paramIAsyncTaskHandler.postToMainThreadRunnable(() -> paramPacket.a(paramT)); + throw CancelledPacketHandleException.INSTANCE; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PlayerInteractManager.java b/azurite-server/src/main/java/net/minecraft/server/PlayerInteractManager.java new file mode 100644 index 0000000..be77a72 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PlayerInteractManager.java @@ -0,0 +1,518 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.AzuriteConfig; +import dev.imanity.antixray.sdk.AntiXrayAdapter; +import dev.imanity.antixray.sdk.AntiXraySDK; +import org.bukkit.Bukkit; +import org.bukkit.craftbukkit.entity.CraftItem; +import org.bukkit.craftbukkit.event.CraftEventFactory; +import org.bukkit.entity.Item; +import org.bukkit.event.Event; +import org.bukkit.event.block.Action; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockDropItemsEvent; +import org.bukkit.event.player.PlayerInteractEvent; + +import java.util.ArrayList; +import java.util.List; +// CraftBukkit end + +public class PlayerInteractManager { + + public World world; + public EntityPlayer player; + // CraftBukkit start + public boolean interactResult = false; + public boolean firedInteract = false; + private WorldSettings.EnumGamemode gamemode; + private boolean d; + private int lastDigTick; + private BlockPosition f; + private int currentTick; + private boolean h; + private BlockPosition i; + private int j; + private int k; + + public PlayerInteractManager(World world) { + this.gamemode = WorldSettings.EnumGamemode.NOT_SET; + this.f = BlockPosition.ZERO; + this.i = BlockPosition.ZERO; + this.k = -1; + this.world = world; + } + + public WorldSettings.EnumGamemode getGameMode() { + return this.gamemode; + } + + public void setGameMode(WorldSettings.EnumGamemode worldsettings_enumgamemode) { + this.gamemode = worldsettings_enumgamemode; + worldsettings_enumgamemode.a(this.player.abilities); + this.player.updateAbilities(); + // Azurite - This optimizes logins a ton. + this.player.server.getPlayerList().sendAllLazily(new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.UPDATE_GAME_MODE, this.player), this.player); + } + + public boolean c() { + return this.gamemode.e(); + } + + public boolean isCreative() { + return this.gamemode.d(); + } + + public void b(WorldSettings.EnumGamemode worldsettings_enumgamemode) { + if (this.gamemode == WorldSettings.EnumGamemode.NOT_SET) { + this.gamemode = worldsettings_enumgamemode; + } + + this.setGameMode(this.gamemode); + } + + public void a() { + this.currentTick = MinecraftServer.currentTick; // CraftBukkit; + float f; + int i; + + if (this.h) { + int x = this.i.getX(), y = this.i.getY(), z = this.i.getZ(); + Chunk ch = world.getChunkAtWorldCoords(x, z); + IBlockData iblockdata = world.getType(ch, x, y, z, true); + + if (iblockdata.getBlock().getMaterial() == Material.AIR) { + this.h = false; + } else { + f = iblockdata.getBlock().getDamage(this.player, this.player.world, this.i) * (float) ((currentTick - this.j) + 1); + i = (int) (f * 10.0F); + if (i != this.k) { + this.world.c(this.player.getId(), this.i, i); + this.k = i; + } + + if (f >= 1.0F) { + this.h = false; + this.breakBlock(ch.bukkitChunk.getBlock(x, y, z), iblockdata, ch, this.i); + } + } + } else if (this.d) { + int x = this.f.getX(), y = this.f.getY(), z = this.f.getZ(); + Block block1 = this.world.getType(x, y, z, true).getBlock(); + + if (block1.getMaterial() == Material.AIR) { + this.world.c(this.player.getId(), this.f, -1); + this.k = -1; + this.d = false; + } else { + f = block1.getDamage(this.player, this.player.world, this.i) * (float) ((this.currentTick - this.lastDigTick) + 1); + i = (int) (f * 10.0F); + if (i != this.k) { + this.world.c(this.player.getId(), this.f, i); + this.k = i; + } + } + } + + } + + // Vortex start - obf helper + public void a(BlockPosition blockposition, EnumDirection enumdirection) { + a(world.getChunkAtWorldCoords(blockposition), blockposition, enumdirection); + } + + private boolean c(BlockPosition blockposition) { + Chunk chunk = world.getChunkAtWorldCoords(blockposition); + return c(chunk, world.getType(chunk, blockposition), blockposition); + } + + public boolean breakBlock(BlockPosition blockposition) { + Chunk chunk = world.getChunkAtWorldCoords(blockposition); + IBlockData iblockdata = world.getType(chunk, blockposition); + return breakBlock(chunk.bukkitChunk.getBlock(blockposition.getX(), blockposition.getY(), blockposition.getZ()), iblockdata, chunk, blockposition); + } + + public void a(BlockPosition blockposition) { + Chunk chunk = world.getChunkAtWorldCoords(blockposition); + a(chunk, world.getType(chunk, blockposition), blockposition); + } + // Vortex end + + public void a(Chunk ch, BlockPosition blockposition, EnumDirection enumdirection) { + // CraftBukkit start + + // Imanity start - AntiXraySDK integration + AntiXrayAdapter adapter = AntiXraySDK.getAdapter(); + if (adapter != null) { + adapter.callPlayerLeftClickBlock(player.world.getWorld(), player.getBukkitEntity(), blockposition.getX(), blockposition.getY(), blockposition.getZ()); + } + // Imanity end + + org.bukkit.block.Block bukkitBlock = ch.bukkitChunk.getBlock(blockposition.getX(), blockposition.getY(), blockposition.getZ()); + + PlayerInteractEvent event = CraftEventFactory.callPlayerInteractEvent(this.player, Action.LEFT_CLICK_BLOCK, bukkitBlock, blockposition, enumdirection, this.player.inventory.getItemInHand(), false); + IBlockData blockdata = world.getType(ch, blockposition); + + if (event.isCancelled()) { + // Let the client know the block still exists + player.playerConnection.sendPacket(new PacketPlayOutBlockChange(blockposition, blockdata)); + // Update any tile entity data for this block + TileEntity tileentity = world.getTileEntity(ch, blockposition, blockdata.getBlock()); + if (tileentity != null) { + this.player.playerConnection.sendPacket(tileentity.getUpdatePacket()); + } + return; + } + + // CraftBukkit end + if (this.isCreative()) { + if (!this.world.douseFire(null, blockposition, enumdirection)) { + this.breakBlock(bukkitBlock, blockdata, ch, blockposition); + } + } else { + if (this.gamemode.c()) { + if (this.gamemode == WorldSettings.EnumGamemode.SPECTATOR) { + return; + } + + if (!this.player.cn()) { + ItemStack itemstack = this.player.bZ(); + + if (itemstack == null || !itemstack.c(blockdata.getBlock())) { + return; + } + } + } + + // this.world.douseFire((EntityHuman) null, blockposition, enumdirection); // + // CraftBukkit - Moved down + this.lastDigTick = this.currentTick; + float f = 1.0F; + + // CraftBukkit start - Swings at air do *NOT* exist. + if (event.useInteractedBlock() == Event.Result.DENY) { + // If we denied a door from opening, we need to send a correcting update to the + // client, as it already opened the door. + if (blockdata.getBlock() == Blocks.WOODEN_DOOR) { + // For some reason *BOTH* the bottom/top part have to be marked updated. + boolean bottom = blockdata.get(BlockDoor.HALF) == BlockDoor.EnumDoorHalf.LOWER; + player.playerConnection.sendPacket(new PacketPlayOutBlockChange(blockposition, blockdata)); + player.playerConnection.sendPacket(new PacketPlayOutBlockChange(world, bottom ? blockposition.up() : blockposition.down())); + } else if (blockdata.getBlock() == Blocks.TRAPDOOR) { + player.playerConnection.sendPacket(new PacketPlayOutBlockChange(blockposition, blockdata)); + } + } else if (blockdata.getBlock().getMaterial() != Material.AIR) { + blockdata.getBlock().attack(this.world, blockposition, this.player); + f = blockdata.getBlock().getDamage(this.player, this.player.world, blockposition); + // Allow fire punching to be blocked + this.world.douseFire(null, blockposition, enumdirection); + } + + if (event.useItemInHand() == Event.Result.DENY) { + // If we 'insta destroyed' then the client needs to be informed. + if (f >= 1.0f) { + player.playerConnection.sendPacket(new PacketPlayOutBlockChange(blockposition, blockdata)); + } + return; + } + org.bukkit.event.block.BlockDamageEvent blockEvent = CraftEventFactory.callBlockDamageEvent(this.player, bukkitBlock, this.player.inventory.getItemInHand(), f >= 1.0f); + + blockdata = world.getType(ch, blockposition); // after event + + if (blockEvent.isCancelled()) { + // Let the client know the block still exists + player.playerConnection.sendPacket(new PacketPlayOutBlockChange(blockposition, blockdata)); + return; + } + + if (blockEvent.getInstaBreak()) { + f = 2.0f; + } + // CraftBukkit end + + if (blockdata.getBlock().getMaterial() != Material.AIR && f >= 1.0F) { + this.breakBlock(bukkitBlock, blockdata, ch, blockposition); + + // GSpigot fix ghost blocks + if (blockEvent.getInstaBreak()) { + for (int x = -1; x <= 1; x++) { + for (int y = -1; y <= 1; y++) { + for (int z = -1; z <= 1; z++) { + this.player.playerConnection.sendPacket(new PacketPlayOutBlockChange(this.world, blockposition)); + } + } + } + } + // GSpigot end + } else { + // Beanes - if the block break speed is very low, send out block change incase it was a desync + // This is because the player could have switched slot (from sword to pickaxe) + // The slot change is reported after the block break and after the flying packet + // So to prevent the client from thinking the block was a insta break, send out a block change + if (f <= 0.1F) { + this.player.playerConnection.sendPacket(new PacketPlayOutBlockChange(blockposition, blockdata)); + } + + this.d = true; + this.f = blockposition; + int i = (int) (f * 10.0F); + + this.world.c(this.player.getId(), blockposition, i); + this.k = i; + } + + } + world.spigotConfig.antiXrayInstance.updateNearbyBlocks(world, blockposition); // Spigot + } + + public void a(Chunk ch, IBlockData iblockdata, BlockPosition blockposition) { + if (blockposition.equals(this.f)) { + this.currentTick = MinecraftServer.currentTick; // CraftBukkit + if (iblockdata.getBlock().getMaterial() != Material.AIR) { + if (iblockdata.getBlock().getDamage(this.player, this.player.world, blockposition) * ((currentTick - lastDigTick) + 1) >= 0.7F) { + this.d = false; + this.world.c(this.player.getId(), blockposition, -1); + this.breakBlock(ch.bukkitChunk.getBlock(blockposition.getX(), blockposition.getY(), blockposition.getZ()), iblockdata, ch, blockposition); + } else if (!this.h) { + this.d = false; + this.h = true; + this.i = blockposition; + this.j = this.lastDigTick; + } + } + // CraftBukkit start - Force block reset to client + } else { + this.player.playerConnection.sendPacket(new PacketPlayOutBlockChange(blockposition, iblockdata)); + // CraftBukkit end + } + + } + + public void e() { + this.d = false; + this.world.c(this.player.getId(), this.f, -1); + } + + private boolean c(Chunk chunk, IBlockData iblockdata, BlockPosition blockposition) { + iblockdata.getBlock().a(this.world, blockposition, iblockdata, this.player); + boolean flag = this.world.setTypeAndData(chunk, blockposition, Blocks.AIR.getBlockData(), 3, true, false); + if (flag) + iblockdata.getBlock().postBreak(this.world, blockposition, iblockdata); + return flag; + } + + public boolean breakBlock(org.bukkit.block.Block bukkitBlock, IBlockData nmsData, Chunk ch, BlockPosition blockposition) { + boolean isSwordNoBreak = this.gamemode.d() && this.player.bA() != null && this.player.bA().getItem() instanceof ItemSword; + + BlockBreakEvent event = new BlockBreakEvent(bukkitBlock, this.player.getBukkitEntity()); + // Sword + Creative mode pre-cancel + event.setCancelled(isSwordNoBreak); + + if (!event.isCancelled() && !this.isCreative() && this.player.b(nmsData.getBlock())) { + // Copied from block.a(World world, EntityHuman entityhuman, BlockPosition + // blockposition, IBlockData iblockdata, TileEntity tileentity) + if (!(nmsData.getBlock().I() && EnchantmentManager.hasSilkTouchEnchantment(this.player))) { + event.setExpToDrop(nmsData.getBlock().getExpDrop(this.world, nmsData, EnchantmentManager.getBonusBlockLootEnchantmentLevel(this.player))); + } + } + + this.world.getServer().getPluginManager().callEvent(event); + + nmsData = this.world.getType(ch, blockposition); + + if (event.isCancelled()) { + if (isSwordNoBreak) + return false; + player.playerConnection.sendPacket(new PacketPlayOutBlockChange(blockposition, nmsData)); + TileEntity tileEntity = world.getTileEntity(ch, blockposition, nmsData.getBlock()); + if (tileEntity != null) + player.playerConnection.sendPacket(tileEntity.getUpdatePacket()); + return false; + } + + // We still should notify client even if block got broken by event handler + TileEntity tileEntity = world.getTileEntity(ch, blockposition, nmsData.getBlock()); + if (!isSwordNoBreak && tileEntity == null) { + this.player.playerConnection.sendPacket(new PacketPlayOutBlockChange(blockposition, Blocks.AIR.getBlockData())); + } + + // If it's broken by event + if (nmsData.getBlock() == Blocks.AIR) return false; + + // Special case skulls, their item data comes from a tile entity + if (nmsData.getBlock() == Blocks.SKULL && !this.isCreative()) { + nmsData.getBlock().dropNaturally(world, blockposition, nmsData, 1.0F, 0); + return this.c(ch, nmsData, blockposition); + } + + if (this.gamemode.c()) { + if (this.gamemode == WorldSettings.EnumGamemode.SPECTATOR) { + return false; + } + + if (!this.player.cn()) { + ItemStack itemstack = this.player.bZ(); + if (itemstack == null || !itemstack.c(nmsData.getBlock())) { + return false; + } + } + } + + this.world.a(this.player, 2001, blockposition, Block.getCombinedId(nmsData)); + boolean flag = c(ch, nmsData, blockposition); + if (!isCreative()) { + ItemStack itemstack1 = this.player.bZ(); + boolean flag1 = this.player.b(nmsData.getBlock()); + if (itemstack1 != null) { + itemstack1.a(this.world, nmsData.getBlock(), blockposition, this.player); + if (itemstack1.count == 0) + this.player.ca(); + } + if (flag && flag1) { + Block block = nmsData.getBlock(); + List items = new ArrayList<>(1); + + block.droppedItemsCatcher = items; + block.a(this.world, this.player, blockposition, nmsData, tileEntity); + block.droppedItemsCatcher = null; + + BlockDropItemsEvent dropItemsEvent = new BlockDropItemsEvent(this.world.getWorld().getBlockAt( + blockposition.getX(), blockposition.getY(), blockposition.getZ()), + this.player.getBukkitEntity(), items); + + Bukkit.getPluginManager().callEvent(dropItemsEvent); + + if (!dropItemsEvent.isCancelled() && dropItemsEvent.getToDrop() != null) { + for (final org.bukkit.entity.Item item : dropItemsEvent.getToDrop()) { + this.world.addEntity(((CraftItem) item).getHandle()); + } + } + } + + if (flag) { + nmsData.getBlock().dropExperience(this.world, blockposition, event.getExpToDrop()); + } + } + return flag; + } + + public boolean useItem(EntityHuman entityhuman, World world, ItemStack itemstack) { + if (this.gamemode == WorldSettings.EnumGamemode.SPECTATOR) { + return false; + } else { + int i = itemstack.count; + int j = itemstack.getData(); + ItemStack itemstack1 = itemstack.a(world, entityhuman); + + // Vortex - Null item use exploit patch + if (itemstack1 == null || itemstack1 == itemstack && itemstack1.count == i && itemstack1.l() <= 0 && itemstack1.getData() == j) { + return false; + } else { + entityhuman.inventory.items[entityhuman.inventory.itemInHandIndex] = itemstack1; + if (this.isCreative()) { + itemstack1.count = i; + if (itemstack1.e()) { + itemstack1.setData(j); + } + } + + if (itemstack1.count == 0) { + entityhuman.inventory.items[entityhuman.inventory.itemInHandIndex] = null; + } + + if (!entityhuman.bS()) { + ((EntityPlayer) entityhuman).updateInventory(entityhuman.defaultContainer); + } + + return true; + } + } + } + // CraftBukkit end + + public boolean interact(EntityHuman entityhuman, World world, ItemStack itemstack, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2) { + Chunk ch = world.getChunkAtWorldCoords(blockposition); + IBlockData blockdata = world.getType(ch, blockposition); + Block block = blockdata.getBlock(); + boolean result = false; + if (block != Blocks.AIR) { + boolean cancelledBlock = false; + TileEntity tileentity = world.getTileEntity(ch, blockposition, block); + org.bukkit.block.Block bukkitBlock = ch.bukkitChunk.getBlock(blockposition.getX(), blockposition.getY(), blockposition.getZ()); + + if (this.gamemode == WorldSettings.EnumGamemode.SPECTATOR) { + cancelledBlock = !(tileentity instanceof IInventory); + } + + if (!entityhuman.getBukkitEntity().isOp() && itemstack != null && Block.asBlock(itemstack.getItem()) instanceof BlockCommand) { + cancelledBlock = true; + } + + // Azurite - Make potions launch when clicking certain blocks + if (itemstack != null && itemstack.getData() == 16421 && block != null && AzuriteConfig.potionLaunchOnClick.getValue().contains(bukkitBlock.getType().name())) { + cancelledBlock = true; + this.player.playerInteractManager.useItem(this.player, this.player.world, itemstack); + } + + PlayerInteractEvent event = CraftEventFactory.callPlayerInteractEvent(entityhuman, Action.RIGHT_CLICK_BLOCK, bukkitBlock, blockposition, enumdirection, itemstack, cancelledBlock); + firedInteract = true; + interactResult = event.useItemInHand() == Event.Result.DENY; + + if (event.useInteractedBlock() == Event.Result.DENY) { + // If we denied a door from opening, we need to send a correcting update to the + // client, as it already opened the door. + if (block instanceof BlockDoor) { + boolean bottom = blockdata.get(BlockDoor.HALF) == BlockDoor.EnumDoorHalf.LOWER; + entityhuman.sendPacket(new PacketPlayOutBlockChange(world, bottom ? blockposition.up() : blockposition.down())); + } + result = (event.useItemInHand() != Event.Result.ALLOW); + } else if (this.gamemode == WorldSettings.EnumGamemode.SPECTATOR) { + if (tileentity instanceof ITileInventory) { + ITileInventory itileinventory = (ITileInventory) tileentity; + + if (itileinventory instanceof TileEntityChest && block instanceof BlockChest) { + itileinventory = ((BlockChest) block).f(world, blockposition); + } + + if (itileinventory != null) { + entityhuman.openContainer(itileinventory); + return true; + } + } else if (tileentity instanceof IInventory) { + entityhuman.openContainer((IInventory) tileentity); + return true; + } + + return false; + } else if (!entityhuman.isSneaking() || itemstack == null) { + result = block.interact(world, blockposition, blockdata, entityhuman, enumdirection, f, f1, f2); + } + + if (itemstack != null && !result && !interactResult) { // add !interactResult SPIGOT-764 + int j1 = itemstack.getData(); + int k1 = itemstack.count; + // VortexSpigot start + try { + world.interceptSounds(); + result = itemstack.placeItem(entityhuman, world, blockposition, enumdirection, f, f1, f2); + } finally { + if (result) { + world.sendInterceptedSounds(); + } else { + world.clearInterceptedSounds(); + } + } + // The item count should not decrement in Creative mode. + if (this.isCreative()) { + itemstack.setData(j1); + itemstack.count = k1; + } + } + } + return result; + // CraftBukkit end + } + + public void a(WorldServer worldserver) { + this.world = worldserver; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PlayerInventory.java b/azurite-server/src/main/java/net/minecraft/server/PlayerInventory.java new file mode 100644 index 0000000..6bc7c98 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PlayerInventory.java @@ -0,0 +1,497 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.AzuriteConfig; +import org.bukkit.craftbukkit.entity.CraftHumanEntity; +import org.bukkit.entity.HumanEntity; +import org.bukkit.inventory.InventoryHolder; + +import java.util.ArrayList; +import java.util.List; + +public class PlayerInventory implements IInventory { + + public ItemStack[] items = new ItemStack[36]; + public ItemStack[] armor = new ItemStack[4]; + public int itemInHandIndex; + public EntityHuman player; + private ItemStack f; + public boolean e; + public List transaction = new ArrayList<>(); + private int maxStack = 64; + + public ItemStack[] getContents() { + return this.items; + } + + public ItemStack[] getArmorContents() { + return this.armor; + } + + public void onOpen(CraftHumanEntity who) { + this.transaction.add(who); + } + + public void onClose(CraftHumanEntity who) { + this.transaction.remove(who); + } + + public List getViewers() { + return this.transaction; + } + + public InventoryHolder getOwner() { + return this.player.getBukkitEntity(); + } + + public void setMaxStackSize(int size) { + this.maxStack = size; + } + + public PlayerInventory(EntityHuman entityhuman) { + this.player = entityhuman; + } + + public ItemStack getItemInHand() { + return (this.itemInHandIndex < 9 && this.itemInHandIndex >= 0) ? this.items[this.itemInHandIndex] : null; + } + + public static int getHotbarSize() { + return 9; + } + + private int c(Item item) { + for (int i = 0; i < this.items.length; i++) { + ItemStack itemstack = items[i]; + if (itemstack != null && itemstack.getItem() == item) + return i; + } + return -1; + } + + private int firstPartial(ItemStack itemstack) { + for (int i = 0; i < this.items.length; i++) { + ItemStack item = items[i]; + if (item != null && item.getItem() == itemstack.getItem() && item.isStackable() && item.count < item.getMaxStackSize() && item.count < getMaxStackSize() && (!item.usesData() || item.getData() == itemstack.getData()) && ItemStack.equals(item, itemstack)) + return i; + } + return -1; + } + + public int canHold(ItemStack itemstack) { + int remains = itemstack.count; + for (ItemStack item : this.items) { + if (item == null) + return itemstack.count; + if (item.getItem() == itemstack.getItem() && item.isStackable() && item.count < item.getMaxStackSize() && item.count < getMaxStackSize() && (!item.usesData() || item.getData() == itemstack.getData()) && ItemStack.equals(item, itemstack)) + remains -= (Math.min(item.getMaxStackSize(), getMaxStackSize())) - item.count; + if (remains <= 0) + return itemstack.count; + } + return itemstack.count - remains; + } + + public int getFirstEmptySlotIndex() { + for (int i = 0; i < this.items.length; i++) { + if (this.items[i] == null) + return i; + } + return -1; + } + + public int a(Item item, int i, int j, NBTTagCompound nbttagcompound) { + int k = 0; + int l; + for (l = 0; l < this.items.length; l++) { + ItemStack itemstack = this.items[l]; + if (itemstack != null && (item == null || itemstack.getItem() == item) && (i <= -1 || itemstack.getData() == i) && (nbttagcompound == null || GameProfileSerializer.a(nbttagcompound, itemstack.getTag(), true))) { + int i1 = (j <= 0) ? itemstack.count : Math.min(j - k, itemstack.count); + k += i1; + if (j != 0) { + (this.items[l]).count -= i1; + if ((this.items[l]).count == 0) + this.items[l] = null; + if (j > 0 && k >= j) + return k; + } + } + } + for (l = 0; l < this.armor.length; l++) { + ItemStack itemstack = this.armor[l]; + if (itemstack != null && (item == null || itemstack.getItem() == item) && (i <= -1 || itemstack.getData() == i) && (nbttagcompound == null || GameProfileSerializer.a(nbttagcompound, itemstack.getTag(), false))) { + int i1 = (j <= 0) ? itemstack.count : Math.min(j - k, itemstack.count); + k += i1; + if (j != 0) { + (this.armor[l]).count -= i1; + if ((this.armor[l]).count == 0) + this.player.setEquipment(l, null); + if (j > 0 && k >= j) + return k; + } + } + } + if (this.f != null) { + if (item != null && this.f.getItem() != item) + return k; + if (i > -1 && this.f.getData() != i) + return k; + if (nbttagcompound != null && !GameProfileSerializer.a(nbttagcompound, this.f.getTag(), false)) + return k; + l = (j <= 0) ? this.f.count : Math.min(j - k, this.f.count); + k += l; + if (j != 0) { + this.f.count -= l; + if (this.f.count == 0) + this.f = null; + if (j > 0 && k >= j) + return k; + } + } + return k; + } + + private int e(ItemStack itemstack) { + Item item = itemstack.getItem(); + int i = itemstack.count; + int j = firstPartial(itemstack); + if (j < 0) + j = getFirstEmptySlotIndex(); + if (j < 0) + return i; + ItemStack itemstack1 = items[j]; + if (itemstack1 == null) { + itemstack1 = new ItemStack(item, 0, itemstack.getData()); + this.items[j] = itemstack1; + if (itemstack.hasTag()) + itemstack1.setTag((NBTTagCompound) itemstack.getTag().clone()); + } + int k = Math.min(i, itemstack1.getMaxStackSize() - itemstack1.count); + if (k > getMaxStackSize() - itemstack1.count) + k = getMaxStackSize() - itemstack1.count; + if (k == 0) + return i; + i -= k; + itemstack1.count += k; + itemstack1.c = 5; + return i; + } + + public void k() { + for (int i = 0; i < this.items.length; i++) { + ItemStack item = items[i]; + if (item != null) + item.a(this.player.world, this.player, i, (this.itemInHandIndex == i)); + } + } + + public boolean a(Item item) { + int i = c(item); + if (i < 0) + return false; + if (--(this.items[i]).count <= 0) + this.items[i] = null; + return true; + } + + public boolean b(Item item) { + int i = c(item); + return (i >= 0); + } + + public boolean pickup(final ItemStack itemstack) { + if (itemstack != null && itemstack.count != 0 && itemstack.getItem() != null) + try { + int i; + if (itemstack.g()) { + i = getFirstEmptySlotIndex(); + if (i >= 0) { + ItemStack item = ItemStack.b(itemstack); + this.items[i] = item; + item.c = 5; + itemstack.count = 0; + return true; + } + if (this.player.abilities.canInstantlyBuild) { + itemstack.count = 0; + return true; + } + return false; + } + do { + i = itemstack.count; + itemstack.count = e(itemstack); + } while (itemstack.count > 0 && itemstack.count < i); + if (itemstack.count == i && this.player.abilities.canInstantlyBuild) { + itemstack.count = 0; + return true; + } + return (itemstack.count < i); + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.a(throwable, "Adding item to inventory"); + CrashReportSystemDetails crashreportsystemdetails = crashreport.a("Item being added"); + crashreportsystemdetails.a("Item ID", Item.getId(itemstack.getItem())); + crashreportsystemdetails.a("Item data", itemstack.getData()); + crashreportsystemdetails.a("Item name", itemstack::getName); + throw new ReportedException(crashreport); + } + return false; + } + + public ItemStack splitStack(int i, int j) { + ItemStack[] aitemstack = this.items; + boolean settingArmour = (i >= this.items.length); + if (settingArmour) { + aitemstack = this.armor; + i -= this.items.length; + } + ItemStack itemStack = aitemstack[i]; + if (itemStack != null) { + if (itemStack.count <= j) { + if (settingArmour) { + this.player.setEquipment(i, null); + } else { + aitemstack[i] = null; + } + return itemStack; + } + ItemStack itemstack = itemStack.cloneAndSubtract(j); + if (itemStack.count == 0) { + aitemstack[i] = null; + if (settingArmour) { + this.player.setEquipment(i, null); + } + } + return itemstack; + } + return null; + } + + public ItemStack splitWithoutUpdate(int i) { + ItemStack[] aitemstack = this.items; + boolean settingArmour = (i >= this.items.length); + if (settingArmour) { + aitemstack = this.armor; + i -= this.items.length; + } + ItemStack itemstack = aitemstack[i]; + if (itemstack != null) { + if (settingArmour) { + this.player.setEquipment(i, null); + } else { + aitemstack[i] = null; + } + return itemstack; + } + return null; + } + + public void setItem(int i, ItemStack itemstack) { + ItemStack[] aitemstack = this.items; + if (i >= aitemstack.length) { + i -= aitemstack.length; + this.player.setEquipment(i, itemstack); + } else { + aitemstack[i] = itemstack; + } + } + + public float a(Block block) { + float f = 1.0F; + ItemStack hand = items[itemInHandIndex]; + if (hand != null) + f *= hand.a(block); + return f; + } + + public NBTTagList a(NBTTagList nbttaglist) { + int i; + for (i = 0; i < this.items.length; i++) { + ItemStack item = items[i]; + if (item != null) { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + nbttagcompound.setByte("Slot", (byte) i); + item.save(nbttagcompound); + nbttaglist.add(nbttagcompound); + } + } + for (i = 0; i < this.armor.length; i++) { + ItemStack item = armor[i]; + if (item != null) { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + nbttagcompound.setByte("Slot", (byte) (i + 100)); + item.save(nbttagcompound); + nbttaglist.add(nbttagcompound); + } + } + return nbttaglist; + } + + public void b(NBTTagList nbttaglist) { + this.items = new ItemStack[36]; + this.armor = new ItemStack[4]; + for (int i = 0; i < nbttaglist.size(); i++) { + NBTTagCompound nbttagcompound = nbttaglist.get(i); + int j = nbttagcompound.getByte("Slot") & 0xFF; + ItemStack itemstack = ItemStack.createStack(nbttagcompound); + if (itemstack != null) { + if (j < this.items.length) + this.items[j] = itemstack; + if (j >= 100 && j < this.armor.length + 100) + this.player.setEquipment(j - 100, itemstack); + } + } + } + + public int getSize() { + return this.items.length + 4; + } + + public ItemStack getItem(int i) { + ItemStack[] aitemstack = this.items; + if (i >= aitemstack.length) { + i -= aitemstack.length; + aitemstack = this.armor; + } + return aitemstack[i]; + } + + public String getName() { + return "container.inventory"; + } + + public boolean hasCustomName() { + return false; + } + + public IChatBaseComponent getScoreboardDisplayName() { + return hasCustomName() ? new ChatComponentText(getName()) : new ChatMessage(getName()); + } + + public int getMaxStackSize() { + return this.maxStack; + } + + public boolean b(Block block) { + if (block.getMaterial().isAlwaysDestroyable()) + return true; + ItemStack itemstack = getItem(this.itemInHandIndex); + return (itemstack != null && itemstack.b(block)); + } + + public ItemStack e(int i) { + return this.armor[i]; + } + + public int m() { + int i = 0; + for (ItemStack itemStack : this.armor) { + if (itemStack != null && itemStack.getItem() instanceof ItemArmor) { + int k = ((ItemArmor) itemStack.getItem()).c; + i += k; + } + } + return i; + } + + public void a(float f) { + f /= AzuriteConfig.armorDamageDivision.getValue(); + if (f < 1.0F) + f = 1.0F; + for (int i = 0; i < this.armor.length; i++) { + ItemStack item = armor[i]; + if (item != null && item.getItem() instanceof ItemArmor) { + item.damage((int) f, this.player); + if (item.count == 0) + this.player.setEquipment(i, null); + } + } + } + + public void n() { + int i; + for (i = 0; i < this.items.length; i++) { + ItemStack item = items[i]; + if (item != null) { + this.player.a(item, true, false); + this.items[i] = null; + } + } + for (i = 0; i < this.armor.length; i++) { + ItemStack item = armor[i]; + if (item != null) { + this.player.a(item, true, false); + this.player.setEquipment(i, null); + } + } + } + + public void update() { + this.e = true; + } + + public void setCarried(ItemStack itemstack) { + this.f = itemstack; + } + + public ItemStack getCarried() { + if (this.f != null && this.f.count == 0) + setCarried(null); + return this.f; + } + + public boolean a(EntityHuman entityhuman) { + return !this.player.dead && ((entityhuman.h(this.player) <= 64.0D)); + } + + public boolean c(ItemStack itemstack) { + int i; + for (i = 0; i < this.armor.length; i++) { + ItemStack item = armor[i]; + if (item != null && item.doMaterialsMatch(itemstack)) + return true; + } + for (i = 0; i < this.items.length; i++) { + ItemStack item = items[i]; + if (item != null && item.doMaterialsMatch(itemstack)) + return true; + } + return false; + } + + public void startOpen(EntityHuman entityhuman) { + } + + public void closeContainer(EntityHuman entityhuman) { + } + + public boolean b(int i, ItemStack itemstack) { + return true; + } + + public void b(PlayerInventory playerinventory) { + int i; + for (i = 0; i < this.items.length; i++) + this.items[i] = ItemStack.b(playerinventory.items[i]); + for (i = 0; i < this.armor.length; i++) + this.player.setEquipment(i, ItemStack.b(playerinventory.armor[i])); + this.itemInHandIndex = playerinventory.itemInHandIndex; + } + + public int getProperty(int i) { + return 0; + } + + public void b(int i, int j) { + } + + public int g() { + return 0; + } + + public void l() { + int i; + for (i = 0; i < this.items.length; i++) + this.items[i] = null; + for (i = 0; i < this.armor.length; i++) + this.armor[i] = null; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PlayerList.java b/azurite-server/src/main/java/net/minecraft/server/PlayerList.java new file mode 100644 index 0000000..b22a09d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PlayerList.java @@ -0,0 +1,1164 @@ +package net.minecraft.server; + +import com.eatthepath.uuid.FastUUID; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import com.mojang.authlib.GameProfile; +import dev.azurite.spigot.Azurite; +import dev.azurite.spigot.configs.AzuriteConfig; +import dev.azurite.spigot.configs.LanguageConfig; +import dev.azurite.spigot.console.TerminalConsoleCommandSender; +import io.netty.buffer.Unpooled; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.TravelAgent; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.CraftWorld; +import org.bukkit.craftbukkit.chunkio.ChunkIOExecutor; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.craftbukkit.inventory.CraftInventoryView; +import org.bukkit.craftbukkit.util.CraftChatMessage; +import org.bukkit.entity.Player; +import org.bukkit.event.player.*; +import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; +import org.bukkit.util.Vector; +import org.spigotmc.SpigotConfig; +import org.spigotmc.event.player.PlayerSpawnLocationEvent; + +import java.io.File; +import java.net.InetSocketAddress; +import java.net.SocketAddress; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; + +public abstract class PlayerList { + + public static final File a = new File("banned-players.json"); + public static final File b = new File("banned-ips.json"); + public static final File c = new File("ops.json"); + public static final File d = new File("whitelist.json"); + private static final Logger f = LogManager.getLogger(); + private static final SimpleDateFormat g = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z"); + public final List players = new java.util.concurrent.CopyOnWriteArrayList<>(); + private final MinecraftServer server; + private final Map j = Maps.newHashMap(); + private final GameProfileBanList k; + private final IpBanList l; + private final OpList operators; + private final WhiteList whitelist; + private final Map o; + public final Map playersByName = new org.spigotmc.CaseInsensitiveMap<>(); + // CraftBukkit start + private final CraftServer cserver; + public IPlayerFileData playerFileData; + public int maxPlayers; + private boolean hasWhitelist; + private int r; + private int u; + + // Beanes - option for elevate + public static boolean BUKKIT_RESPAWN_CLEAR_CHUNKS = true; + + public PlayerList(MinecraftServer minecraftserver) { + this.cserver = minecraftserver.server = new CraftServer(minecraftserver, this); + minecraftserver.console = new TerminalConsoleCommandSender(); + + this.k = new GameProfileBanList(PlayerList.a); + this.l = new IpBanList(PlayerList.b); + this.operators = new OpList(PlayerList.c); + this.whitelist = new WhiteList(PlayerList.d); + this.o = Maps.newHashMap(); + this.server = minecraftserver; + this.k.a(false); + this.l.a(false); + this.maxPlayers = 8; + } + + public void a(NetworkManager networkmanager, EntityPlayer entityplayer) { + GameProfile gameprofile = entityplayer.getProfile(); + UserCache usercache = server.getUserCache(); + GameProfile gameprofile1 = usercache.a(gameprofile.getId()); + String s = gameprofile1 == null ? gameprofile.getName() : gameprofile1.getName(); + + usercache.a(gameprofile); + NBTTagCompound nbttagcompound = this.a(entityplayer); + // CraftBukkit start - Better rename detection + if (nbttagcompound != null && nbttagcompound.hasKey("bukkit")) { + NBTTagCompound bukkit = nbttagcompound.getCompound("bukkit"); + s = bukkit.hasKeyOfType("lastKnownName", 8) ? bukkit.getString("lastKnownName") : s; + } + // CraftBukkit end + + // PaperSpigot start - support PlayerInitialSpawnEvent + + PlayerInitialSpawnEvent event = new PlayerInitialSpawnEvent(entityplayer.getBukkitEntity(), new Location(entityplayer.world.getWorld(), entityplayer.locX, entityplayer.locY, entityplayer.locZ, entityplayer.yaw, entityplayer.pitch)); + server.server.getPluginManager().callEvent(event); + + Location newLoc = event.getSpawnLocation(); + WorldServer worldserver = ((CraftWorld) newLoc.getWorld()).getHandle(); + entityplayer.world = worldserver; + entityplayer.locX = newLoc.getX(); + entityplayer.locY = newLoc.getY(); + entityplayer.locZ = newLoc.getZ(); + entityplayer.yaw = newLoc.getYaw(); + entityplayer.pitch = newLoc.getPitch(); + entityplayer.dimension = worldserver.dimension; + entityplayer.spawnWorld = entityplayer.world.worldData.getName(); + // PaperSpigot end + entityplayer.spawnIn(worldserver); + + String s1 = "local"; + + if (networkmanager.getSocketAddress() != null) { + s1 = networkmanager.getSocketAddress().toString(); + } + + // Spigot start - spawn location event + Player bukkitPlayer = entityplayer.getBukkitEntity(); + PlayerSpawnLocationEvent ev = new PlayerSpawnLocationEvent(bukkitPlayer, bukkitPlayer.getLocation()); + Bukkit.getPluginManager().callEvent(ev); + + Location loc = ev.getSpawnLocation(); + + worldserver = ((CraftWorld) loc.getWorld()).getHandle(); + entityplayer.spawnIn(worldserver); + entityplayer.setPosition(loc.getX(), loc.getY(), loc.getZ()); + entityplayer.setYawPitch(loc.getYaw(), loc.getPitch()); + // Spigot end + + WorldData worlddata = worldserver.getWorldData(); + BlockPosition blockposition = worldserver.getSpawn(); + + entityplayer.playerInteractManager.b(worldserver.getWorldData().getGameType()); + + PlayerConnection playerconnection = new PlayerConnection(server, networkmanager, entityplayer); + + networkmanager.a(EnumProtocol.PLAY); // Beanes - set play protocol so that we don't need to check protocol for each packet + + playerconnection.sendPacket( + new PacketPlayOutLogin(entityplayer.getId(), entityplayer.playerInteractManager.getGameMode(), + worlddata.isHardcore(), worldserver.worldProvider.getDimension(), worldserver.getDifficulty(), + Math.min(getMaxPlayers(), 60), worlddata.getType(), + worldserver.getGameRules().getBoolean("reducedDebugInfo"))); // CraftBukkit - cap player list to 60 + entityplayer.getBukkitEntity().sendSupportedChannels(); // CraftBukkit + playerconnection.sendPacket(new PacketPlayOutCustomPayload("MC|Brand", new PacketDataSerializer(Unpooled.buffer()).a(this.getServer().getServerModName()))); + playerconnection.sendPacket(new PacketPlayOutServerDifficulty(worlddata.getDifficulty(), true)); + playerconnection.sendPacket(new PacketPlayOutSpawnPosition(blockposition)); + playerconnection.sendPacket(new PacketPlayOutAbilities(entityplayer.abilities)); + playerconnection.sendPacket(new PacketPlayOutHeldItemSlot(entityplayer.inventory.itemInHandIndex)); + + entityplayer.getStatisticManager().d(); + //entityplayer.getStatisticManager().updateStatistics(entityplayer); // Vortex - Remove achievements + + sendScoreboard((ScoreboardServer) worldserver.getScoreboard(), entityplayer); + + String joinMessage; + if (!entityplayer.getName().equalsIgnoreCase(s)) { + joinMessage = "\u00A7e" + LocaleI18n.a("multiplayer.player.joined.renamed", entityplayer.getName(), s); + } else { + joinMessage = "\u00A7e" + LocaleI18n.a("multiplayer.player.joined", entityplayer.getName()); + } + + onPlayerJoin(entityplayer, joinMessage); + + worldserver = server.getWorldServer(entityplayer.dimension); + playerconnection.a(entityplayer.locX, entityplayer.locY, entityplayer.locZ, entityplayer.yaw, entityplayer.pitch); + + b(entityplayer, worldserver); + + if (!server.getResourcePack().isEmpty()) { + entityplayer.setResourcePack(server.getResourcePack(), server.getResourcePackHash()); + } + + for (MobEffect effect : entityplayer.getEffects()) { + playerconnection.sendPacket(new PacketPlayOutEntityEffect(entityplayer.getId(), effect)); + } + + entityplayer.syncInventory(); + if (nbttagcompound != null && nbttagcompound.hasKeyOfType("Riding", 10)) { + Entity entity = EntityTypes.a(nbttagcompound.getCompound("Riding"), worldserver); + + if (entity != null) { + entity.attachedToPlayer = true; + worldserver.addEntity(entity); + entityplayer.mount(entity); + entity.attachedToPlayer = false; + } + } + + PlayerList.f.info(entityplayer.getName() + (AzuriteConfig.ipConsoleLog.getValue() ? "[" + s1 + "]" : "") + " logged in with entity id " + entityplayer.getId() + + " at ([" + entityplayer.world.worldData.getName() + "]" + entityplayer.locX + ", " + entityplayer.locY + + ", " + entityplayer.locZ + ")"); + } + + public void sendScoreboard(ScoreboardServer scoreboardserver, EntityPlayer entityplayer) { + List list = Lists.newArrayList(); + + for (ScoreboardTeam scoreboardTeam : scoreboardserver.getTeams()) { + entityplayer.playerConnection.sendPacket(new PacketPlayOutScoreboardTeam(scoreboardTeam, 0)); + } + + for (int i = 0; i < 19; ++i) { + ScoreboardObjective scoreboardobjective = scoreboardserver.getObjectiveForSlot(i); + + if (scoreboardobjective != null && !list.contains(scoreboardobjective)) { + + for (Packet packet : scoreboardserver.getScoreboardScorePacketsForObjective(scoreboardobjective)) { + entityplayer.playerConnection.sendPacket(packet); + } + + list.add(scoreboardobjective); + } + } + scoreboardserver.addViewer(entityplayer); + } + + public void setPlayerFileData(WorldServer[] aworldserver) { + if (playerFileData != null) + return; // CraftBukkit + this.playerFileData = aworldserver[0].getDataManager().getPlayerFileData(); + aworldserver[0].getWorldBorder().a(new IWorldBorderListener() { + public void a(WorldBorder worldborder, double d0) { + PlayerList.this.sendAll(new PacketPlayOutWorldBorder(worldborder, + PacketPlayOutWorldBorder.EnumWorldBorderAction.SET_SIZE)); + } + + public void a(WorldBorder worldborder, double d0, double d1, long i) { + PlayerList.this.sendAll(new PacketPlayOutWorldBorder(worldborder, + PacketPlayOutWorldBorder.EnumWorldBorderAction.LERP_SIZE)); + } + + public void a(WorldBorder worldborder, double d0, double d1) { + PlayerList.this.sendAll(new PacketPlayOutWorldBorder(worldborder, + PacketPlayOutWorldBorder.EnumWorldBorderAction.SET_CENTER)); + } + + public void a(WorldBorder worldborder, int i) { + PlayerList.this.sendAll(new PacketPlayOutWorldBorder(worldborder, + PacketPlayOutWorldBorder.EnumWorldBorderAction.SET_WARNING_TIME)); + } + + public void b(WorldBorder worldborder, int i) { + PlayerList.this.sendAll(new PacketPlayOutWorldBorder(worldborder, + PacketPlayOutWorldBorder.EnumWorldBorderAction.SET_WARNING_BLOCKS)); + } + + public void b(WorldBorder worldborder, double d0) { + } + + public void c(WorldBorder worldborder, double d0) { + } + }); + } + + public void a(EntityPlayer entityplayer, WorldServer worldserver) { + WorldServer worldserver1 = entityplayer.u(); + + if (worldserver != null) { + worldserver.getPlayerChunkMap().removePlayer(entityplayer); + } + + worldserver1.getPlayerChunkMap().addPlayer(entityplayer); + worldserver1.chunkProviderServer.getChunkAt(MathHelper.floor(entityplayer.locX) >> 4, MathHelper.floor(entityplayer.locZ) >> 4); + } + + public int d() { + return PlayerChunkMap.getFurthestViewableBlock(this.s()); + } + + public NBTTagCompound a(EntityPlayer entityplayer) { + return playerFileData.load(entityplayer); + } + + protected void savePlayerFile(EntityPlayer entityplayer) { + this.playerFileData.save(entityplayer); + ServerStatisticManager serverstatisticmanager = this.o.get(entityplayer.getUniqueID()); + + if (serverstatisticmanager != null) { + serverstatisticmanager.b(); + } + } + + private void sendInfos(EntityPlayer entityPlayer) { + PacketPlayOutPlayerInfo packet = new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.ADD_PLAYER, entityPlayer); + CraftPlayer player = entityPlayer.getBukkitEntity(); + + final List onlinePlayers = Lists.newArrayListWithExpectedSize(Math.max(this.players.size() - 1, 0)); // PandaSpigot - use single player info update packet + for (EntityPlayer onlinePlayer : players) { + CraftPlayer online = onlinePlayer.getBukkitEntity(); + + if (onlinePlayer != entityPlayer && online.canSee(player)) // PandaSpigot - don't include joining player + onlinePlayer.playerConnection.writePacketLazily(packet); // Azurite - Write packet lazily + if (player.canSee(online)) + onlinePlayers.add(onlinePlayer); // PandaSpigot - use single player info update packet + } + + // PandaSpigot start - use single player info update packet + if (!onlinePlayers.isEmpty()) { + entityPlayer.playerConnection.writePacketLazily(new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.ADD_PLAYER, onlinePlayers.toArray(new EntityPlayer[0]))); + } + // PandaSpigot end + } + + public void onPlayerJoin(EntityPlayer entityPlayer, String joinMessage) { // CraftBukkit added param + players.add(entityPlayer); + playersByName.put(entityPlayer.getName(), entityPlayer); // Spigot + j.put(entityPlayer.getUniqueID(), entityPlayer); + + WorldServer worldserver = server.getWorldServer(entityPlayer.dimension); + + if (AzuriteConfig.prePlayerInfos.getValue()) { + sendInfos(entityPlayer); + } + + PlayerJoinEvent playerJoinEvent = new PlayerJoinEvent(cserver.getPlayer(entityPlayer), joinMessage); + cserver.getPluginManager().callEvent(playerJoinEvent); + joinMessage = playerJoinEvent.getJoinMessage(); + if (joinMessage != null && !joinMessage.isEmpty()) + for (IChatBaseComponent line : CraftChatMessage.fromString(joinMessage)) + this.server.getPlayerList().sendAll(new PacketPlayOutChat(line)); + + ChunkIOExecutor.adjustPoolSize(getPlayerCount()); + + + if (!AzuriteConfig.prePlayerInfos.getValue()) { + sendInfos(entityPlayer); + } + + // CraftBukkit start - Only add if the player wasn't moved in the event + if (entityPlayer.world == worldserver && !worldserver.players.contains(entityPlayer)) { + worldserver.addEntity(entityPlayer); + a(entityPlayer, (WorldServer) null); + } + // CraftBukkit end + } + + public void d(EntityPlayer entityplayer) { + entityplayer.u().getPlayerChunkMap().movePlayer(entityplayer); + entityplayer.world.playerMap.move(entityplayer); + } + + public String disconnect(EntityPlayer entityplayer) { + entityplayer.b(StatisticList.f); + + // CraftBukkit start - Quitting must be before we do final save of data, in case + // plugins need to modify it + org.bukkit.craftbukkit.event.CraftEventFactory.handleInventoryCloseEvent(entityplayer); + + Player bukkit = cserver.getPlayer(entityplayer); + PlayerQuitEvent playerQuitEvent = new PlayerQuitEvent(bukkit, + "§e" + entityplayer.getName() + " left the game."); + cserver.getPluginManager().callEvent(playerQuitEvent); + + entityplayer.lastActivity = System.currentTimeMillis(); + entityplayer.getBukkitEntity().disconnect(playerQuitEvent.getQuitMessage()); + Azurite.getInstance().getBetterSlowdown().disconnect(entityplayer.getUniqueID()); // Beanes - remove from Better Slowdown + Azurite.getInstance().getKnockbackManager().getEditing().remove(entityplayer.getUniqueID()); // Azurite + // CraftBukkit end + + this.savePlayerFile(entityplayer); + WorldServer worldserver = entityplayer.u(); + + if (entityplayer.vehicle != null && !(entityplayer.vehicle instanceof EntityPlayer)) { // CraftBukkit - Don't remove players + worldserver.removeEntity(entityplayer.vehicle); + } + + worldserver.kill(entityplayer); + worldserver.getPlayerChunkMap().removePlayer(entityplayer); + this.players.remove(entityplayer); + this.playersByName.remove(entityplayer.getName()); // Spigot + UUID uuid = entityplayer.getUniqueID(); + EntityPlayer entityplayer1 = this.j.get(uuid); + if (entityplayer1 == entityplayer) { + this.j.remove(uuid); + this.o.remove(uuid); + } + + CraftingManager craftingManager = CraftingManager.getInstance(); + CraftInventoryView lastView = (CraftInventoryView) craftingManager.lastCraftView; + if (lastView != null && lastView.getHandle() instanceof ContainerPlayer && lastView.getPlayer() == bukkit) + craftingManager.lastCraftView = null; + + // CraftBukkit start + PacketPlayOutPlayerInfo packet = new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.REMOVE_PLAYER, entityplayer); + for (EntityPlayer player : players) { + player.playerConnection.sendPacket(packet); + } + // This removes the scoreboard (and player reference) for the specific player in + // the manager + cserver.getScoreboardManager().removePlayer(entityplayer.getBukkitEntity()); + // CraftBukkit end + + ChunkIOExecutor.adjustPoolSize(getPlayerCount()); // CraftBukkit + + return playerQuitEvent.getQuitMessage(); // CraftBukkit + } + + public EntityPlayer processLogin(GameProfile gameprofile, EntityPlayer player) { // CraftBukkit - added EntityPlayer + return player; + // CraftBukkit end + } + + public EntityPlayer attemptLogin(LoginListener loginlistener, GameProfile gameprofile, String hostname) { + UUID uuid = EntityHuman.a(gameprofile); + ArrayList arraylist = Lists.newArrayList(); + for (EntityPlayer player : players) { + if (player.getUniqueID().equals(uuid)) + arraylist.add(player); + } + for (EntityPlayer player : arraylist) { + savePlayerFile(player); + player.playerConnection.disconnect(LanguageConfig.loggedInAnotherLocation.getValue()); + } + SocketAddress socketaddress = loginlistener.networkManager.getSocketAddress(); + EntityPlayer entity = new EntityPlayer(this.server, this.server.getWorldServer(0), gameprofile, new PlayerInteractManager(this.server.getWorldServer(0))); + CraftPlayer craftPlayer = entity.getBukkitEntity(); + PlayerLoginEvent event = new PlayerLoginEvent(craftPlayer, hostname, ((InetSocketAddress) socketaddress).getAddress(), ((InetSocketAddress) loginlistener.networkManager.getRawAddress()).getAddress()); + if (getProfileBans().isBanned(gameprofile) && !getProfileBans().get(gameprofile).hasExpired()) { + GameProfileBanEntry gameprofilebanentry = this.k.get(gameprofile); + String s = "You are banned from this server!\nReason: " + gameprofilebanentry.getReason(); + if (gameprofilebanentry.getExpires() != null) + s = s + "\nYour ban will be removed on " + g.format(gameprofilebanentry.getExpires()); + if (!gameprofilebanentry.hasExpired()) + event.disallow(PlayerLoginEvent.Result.KICK_BANNED, s); + } else if (!isWhitelisted(gameprofile)) { + event.disallow(PlayerLoginEvent.Result.KICK_WHITELIST, SpigotConfig.whitelistMessage); + } else if (getIPBans().isBanned(socketaddress) && !getIPBans().get(socketaddress).hasExpired()) { + IpBanEntry ipbanentry = this.l.get(socketaddress); + String s = "Your IP address is banned from this server!\nReason: " + ipbanentry.getReason(); + if (ipbanentry.getExpires() != null) + s = s + "\nYour ban will be removed on " + g.format(ipbanentry.getExpires()); + event.disallow(PlayerLoginEvent.Result.KICK_BANNED, s); + } else if (this.players.size() >= this.maxPlayers && !f(gameprofile)) { + event.disallow(PlayerLoginEvent.Result.KICK_FULL, SpigotConfig.serverFullMessage); + } + this.cserver.getPluginManager().callEvent(event); + if (event.getResult() != PlayerLoginEvent.Result.ALLOWED) { + loginlistener.disconnect(event.getKickMessage()); + return null; + } + return entity; + } + + public void forceRespawn(EntityPlayer entityplayer) { + BlockPosition blockposition = entityplayer.getBed(); + entityplayer.viewingCredits = false; + Location location = null; + boolean isBedSpawn = false; + CraftWorld cworld = (CraftWorld) this.server.server.getWorld(entityplayer.spawnWorld); + if (cworld != null && blockposition != null) { + BlockPosition blockposition1 = EntityHuman.getBed(cworld.getHandle(), blockposition, entityplayer.isRespawnForced()); + if (blockposition1 != null) { + isBedSpawn = true; + location = new Location(cworld, blockposition1.getX() + 0.5, blockposition1.getY(), + blockposition1.getZ() + 0.5); + } else { + entityplayer.setRespawnPosition(null, true); + entityplayer.playerConnection.sendPacket(new PacketPlayOutGameStateChange(0, 0.0F)); + } + } + + if (location == null) { + cworld = (CraftWorld) this.server.server.getWorlds().get(0); + blockposition = cworld.getHandle().getSpawn(); + location = new Location(cworld, blockposition.getX() + 0.5, blockposition.getY(), blockposition.getZ() + 0.5); + } + + Player respawnPlayer = cserver.getPlayer(entityplayer); + PlayerRespawnEvent respawnEvent = new PlayerRespawnEvent(respawnPlayer, location, isBedSpawn); + cserver.getPluginManager().callEvent(respawnEvent); + // Spigot Start + if (entityplayer.playerConnection.isDisconnected()) { + return; + } + // Spigot End + entityplayer.reset(); + entityplayer.dead = false; + respawnPlayer.teleport(respawnEvent.getRespawnLocation()); + } + + // CraftBukkit start + public EntityPlayer moveToWorld(EntityPlayer entityplayer, int i, boolean flag) { + return this.moveToWorld(entityplayer, i, flag, null, true); + } + + public EntityPlayer moveToWorld(EntityPlayer entityplayer, int i, boolean flag, Location location, boolean avoidSuffocation) { + entityplayer.u().getTracker().untrackPlayer(entityplayer); + entityplayer.u().getPlayerChunkMap().removePlayer(entityplayer); + + this.players.remove(entityplayer); + this.playersByName.remove(entityplayer.getName()); // Spigot + this.server.getWorldServer(entityplayer.dimension).removeEntity(entityplayer); + + BlockPosition blockposition = entityplayer.getBed(); + boolean flag1 = entityplayer.isRespawnForced(); + org.bukkit.World fromWorld = entityplayer.getBukkitEntity().getWorld(); + entityplayer.viewingCredits = false; + + entityplayer.copyTo(entityplayer, flag); + entityplayer.d(entityplayer.getId()); + entityplayer.o(entityplayer); + + // CraftBukkit start - fire PlayerRespawnEvent + if (location == null) { + boolean isBedSpawn = false; + CraftWorld cworld = (CraftWorld) this.server.server.getWorld(entityplayer.spawnWorld); + if (cworld != null && blockposition != null) { + BlockPosition blockposition1 = EntityHuman.getBed(cworld.getHandle(), blockposition, flag1); + if (blockposition1 != null) { + isBedSpawn = true; + location = new Location(cworld, blockposition1.getX() + 0.5, blockposition1.getY(), + blockposition1.getZ() + 0.5); + } else { + entityplayer.setRespawnPosition(null, true); + entityplayer.playerConnection.sendPacket(new PacketPlayOutGameStateChange(0, 0.0F)); + } + } + + if (location == null) { + cworld = (CraftWorld) this.server.server.getWorlds().get(0); + blockposition = cworld.getHandle().getSpawn(); + location = new Location(cworld, blockposition.getX() + 0.5, blockposition.getY(), blockposition.getZ() + 0.5); + } + + Player respawnPlayer = cserver.getPlayer(entityplayer); + PlayerRespawnEvent respawnEvent = new PlayerRespawnEvent(respawnPlayer, location, isBedSpawn); + cserver.getPluginManager().callEvent(respawnEvent); + // Spigot Start + if (entityplayer.playerConnection.isDisconnected()) { + return entityplayer; + } + // Spigot End + + location = respawnEvent.getRespawnLocation(); + entityplayer.reset(); + } else { + location.setWorld(server.getWorldServer(i).getWorld()); + } + + WorldServer worldserver = ((CraftWorld) location.getWorld()).getHandle(); + entityplayer.setLocation(location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch()); + // CraftBukkit end + + worldserver.chunkProviderServer.getChunkAt(MathHelper.floor(entityplayer.locX) >> 4, MathHelper.floor(entityplayer.locZ) >> 4); + + while (avoidSuffocation && !worldserver.getCubes(entityplayer, entityplayer.getBoundingBox()).isEmpty() && entityplayer.locY < 256.0D) { + entityplayer.setPosition(entityplayer.locX, entityplayer.locY + 1.0D, entityplayer.locZ); + } + // CraftBukkit start + byte actualDimension = (byte) (worldserver.getWorld().getEnvironment().getId()); + // Force the client to refresh their chunk cache + if (BUKKIT_RESPAWN_CLEAR_CHUNKS && fromWorld.getEnvironment() == worldserver.getWorld().getEnvironment()) { + entityplayer.playerConnection.sendPacket(new PacketPlayOutRespawn((byte) (actualDimension >= 0 ? -1 : 0), worldserver.getDifficulty(), worldserver.getWorldData().getType(), entityplayer.playerInteractManager.getGameMode())); + } + entityplayer.playerConnection.sendPacket(new PacketPlayOutRespawn(actualDimension, worldserver.getDifficulty(), worldserver.getWorldData().getType(), entityplayer.playerInteractManager.getGameMode())); + + Azurite.getInstance().getBetterSlowdown().respawn(entityplayer.getUniqueID()); + + entityplayer.spawnIn(worldserver); + entityplayer.dead = false; + entityplayer.playerConnection.teleport(new Location(worldserver.getWorld(), entityplayer.locX, + entityplayer.locY, entityplayer.locZ, entityplayer.yaw, entityplayer.pitch)); + entityplayer.setSneaking(false); + entityplayer.playerConnection.sendPacket(new PacketPlayOutSpawnPosition(worldserver.getSpawn())); + entityplayer.playerConnection.sendPacket(new PacketPlayOutExperience(entityplayer.exp, entityplayer.expTotal, entityplayer.expLevel)); + b(entityplayer, worldserver); + + if (!entityplayer.playerConnection.isDisconnected()) { + worldserver.getPlayerChunkMap().addPlayer(entityplayer); + worldserver.addEntity(entityplayer); + this.players.add(entityplayer); + this.playersByName.put(entityplayer.getName(), entityplayer); // Spigot + this.j.put(entityplayer.getUniqueID(), entityplayer); + } + // Added from changeDimension + updateClient(entityplayer); // Update health, etc... + entityplayer.updateAbilities(); + for (MobEffect o1 : entityplayer.getEffects()) { + entityplayer.playerConnection.sendPacket(new PacketPlayOutEntityEffect(entityplayer.getId(), o1)); + } + // entityplayer1.syncInventory(); + // CraftBukkit end + entityplayer.setHealth(entityplayer.getHealth()); + + // CraftBukkit start + // Don't fire on respawn + if (fromWorld != location.getWorld()) { + server.server.getPluginManager().callEvent(new PlayerChangedWorldEvent(entityplayer.getBukkitEntity(), fromWorld)); + } + + // Save player file again if they were disconnected + if (entityplayer.playerConnection.isDisconnected()) { + this.savePlayerFile(entityplayer); + } + + // CraftBukkit end + return entityplayer; + } + + // CraftBukkit start - Replaced the standard handling of portals with a more + // customised method. + public void changeDimension(EntityPlayer entityplayer, int i, TeleportCause cause) { + WorldServer exitWorld = null; + if (entityplayer.dimension < CraftWorld.CUSTOM_DIMENSION_OFFSET) { // plugins must specify exit from custom + // Bukkit worlds + // only target existing worlds (compensate for allow-nether/allow-end as false) + for (WorldServer world : this.server.worlds) { + if (world.dimension == i) { + exitWorld = world; + } + } + } + + Location enter = entityplayer.getBukkitEntity().getLocation(); + Location exit = null; + boolean useTravelAgent = false; // don't use agent for custom worlds or return from THE_END + if (exitWorld != null) { + if ((cause == TeleportCause.END_PORTAL) && (i == 0)) { + // THE_END -> NORMAL; use bed if available, otherwise default spawn + exit = entityplayer.getBukkitEntity().getBedSpawnLocation(); + if (exit == null || ((CraftWorld) exit.getWorld()).getHandle().dimension != 0) { + exit = exitWorld.getWorld().getSpawnLocation(); + } + } else { + // NORMAL <-> NETHER or NORMAL -> THE_END + exit = this.calculateTarget(enter, exitWorld); + useTravelAgent = true; + } + } + + TravelAgent agent = exit != null ? (TravelAgent) ((CraftWorld) exit.getWorld()).getHandle().getTravelAgent() : org.bukkit.craftbukkit.CraftTravelAgent.DEFAULT; // return arbitrary TA to compensate for + // implementation dependent plugins + agent.setCanCreatePortal(cause != TeleportCause.END_PORTAL); // PaperSpigot - Configurable end credits, don't + // allow End Portals to create portals + + PlayerPortalEvent event = new PlayerPortalEvent(entityplayer.getBukkitEntity(), enter, exit, agent, cause); + event.useTravelAgent(useTravelAgent); + Bukkit.getServer().getPluginManager().callEvent(event); + if (event.isCancelled() || event.getTo() == null) { + return; + } + exitWorld = ((CraftWorld) event.getTo().getWorld()).getHandle(); // We need to set exit world again + + // Beanes - optimized portal travel by loading chunks async + if (AzuriteConfig.preloadChunksOnDimensionChange.getValue()) { + int chunkX = (MathHelper.floor(event.getTo().getX()) >> 4); + int chunkZ = (MathHelper.floor(event.getTo().getZ()) >> 4); + + int preLoadChunks = (int) Math.ceil(exitWorld.paperSpigotConfig.portalSearchRadius / 16.0D) + 1; + + AtomicInteger chunksRemainingForDimensionChange = new AtomicInteger((preLoadChunks + preLoadChunks) * (preLoadChunks + preLoadChunks)); + for (int addX = -preLoadChunks; addX < preLoadChunks; addX++) { + for (int addZ = -preLoadChunks; addZ < preLoadChunks; addZ++) { + int finalX = chunkX + addX; + int finalZ = chunkZ + addZ; + + exitWorld.chunkProviderServer.getChunkAt(finalX, finalZ, () -> { + // All requested chunks have been loaded, now we can do the portal search + if (chunksRemainingForDimensionChange.decrementAndGet() <= 0) { + Location teleportExit = cause != TeleportCause.END_PORTAL && event.useTravelAgent() + ? event.getPortalTravelAgent().findOrCreate(event.getTo()) + : event.getTo(); + + if (teleportExit == null) { + return; + } + + // This seems to race condition with load unload in the bukkit chunk management? Not sure what happens + MinecraftServer.getServer().postToMainThreadRunnable(() -> changeDimensionFinal(entityplayer, teleportExit, enter, cause)); + } + }); + } + } + } else { + exit = cause != TeleportCause.END_PORTAL && event.useTravelAgent() + ? event.getPortalTravelAgent().findOrCreate(event.getTo()) + : event.getTo(); + if (exit == null) { + return; + } + + changeDimensionFinal(entityplayer, exit, enter, cause); + } + } + + public void changeDimensionFinal(EntityPlayer entityplayer, Location exit, Location enter, TeleportCause cause) { + // PaperSpigot - Configurable end credits, if a plugin sets to use a travel + // agent even if the cause is an end portal, ignore it + WorldServer exitWorld = ((CraftWorld) exit.getWorld()).getHandle(); + + org.bukkit.event.player.PlayerTeleportEvent tpEvent = new org.bukkit.event.player.PlayerTeleportEvent( + entityplayer.getBukkitEntity(), enter, exit, cause); + Bukkit.getServer().getPluginManager().callEvent(tpEvent); + if (tpEvent.isCancelled() || tpEvent.getTo() == null) { + return; + } + + Vector velocity = entityplayer.getBukkitEntity().getVelocity(); + boolean before = exitWorld.chunkProviderServer.forceChunkLoad; + exitWorld.chunkProviderServer.forceChunkLoad = true; + exitWorld.getTravelAgent().adjustExit(entityplayer, exit, velocity); + exitWorld.chunkProviderServer.forceChunkLoad = before; + + this.moveToWorld(entityplayer, exitWorld.dimension, true, exit, false); // Vanilla doesn't check for suffocation + // when handling portals, so neither + // should we + if (entityplayer.motX != velocity.getX() || entityplayer.motY != velocity.getY() + || entityplayer.motZ != velocity.getZ()) { + entityplayer.getBukkitEntity().setVelocity(velocity); + } + } + + // Copy of original changeWorld(Entity, int, WorldServer, WorldServer) method + // with only location calculation logic + public Location calculateTarget(Location enter, World target) { + WorldServer worldserver = ((CraftWorld) enter.getWorld()).getHandle(); + WorldServer worldserver1 = target.getWorld().getHandle(); + int i = worldserver.dimension; + + double y = enter.getY(); + float yaw = enter.getYaw(); + float pitch = enter.getPitch(); + double d0 = enter.getX(); + double d1 = enter.getZ(); + double d2 = 8.0D; + + if (worldserver1.dimension == -1) { + d0 = MathHelper.a(d0 / d2, worldserver1.getWorldBorder().b() + 16.0D, + worldserver1.getWorldBorder().d() - 16.0D); + d1 = MathHelper.a(d1 / d2, worldserver1.getWorldBorder().c() + 16.0D, + worldserver1.getWorldBorder().e() - 16.0D); + } else if (worldserver1.dimension == 0) { + d0 = MathHelper.a(d0 * d2, worldserver1.getWorldBorder().b() + 16.0D, + worldserver1.getWorldBorder().d() - 16.0D); + d1 = MathHelper.a(d1 * d2, worldserver1.getWorldBorder().c() + 16.0D, + worldserver1.getWorldBorder().e() - 16.0D); + } else { + BlockPosition blockposition; + + if (i == 1) { + // use default NORMAL world spawn instead of target + worldserver1 = this.server.worlds.get(0); + blockposition = worldserver1.getSpawn(); + } else { + blockposition = worldserver1.getDimensionSpawn(); + } + + d0 = blockposition.getX(); + y = blockposition.getY(); + d1 = blockposition.getZ(); + + } + + if (i != 1) { + d0 = MathHelper.clamp((int) d0, -29999872, 29999872); + d1 = MathHelper.clamp((int) d1, -29999872, 29999872); + + } + + // entity.spawnIn(worldserver1); + return new Location(worldserver1.getWorld(), d0, y, d1, yaw, pitch); + } + + // copy of original a(Entity, int, WorldServer, WorldServer) method with only + // entity repositioning logic + public void repositionEntity(Entity entity, Location exit, boolean portal) { + WorldServer worldserver = (WorldServer) entity.world; + WorldServer worldserver1 = ((CraftWorld) exit.getWorld()).getHandle(); + int i = worldserver.dimension; + + entity.setPositionRotation(exit.getX(), exit.getY(), exit.getZ(), exit.getYaw(), exit.getPitch()); + if (entity.isAlive()) { + worldserver.entityJoinedWorld(entity, false); + } + + if (i != 1) { + + if (entity.isAlive()) { + if (portal) { + Vector velocity = entity.getBukkitEntity().getVelocity(); + worldserver1.getTravelAgent().adjustExit(entity, exit, velocity); + entity.setPositionRotation(exit.getX(), exit.getY(), exit.getZ(), exit.getYaw(), exit.getPitch()); + if (entity.motX != velocity.getX() || entity.motY != velocity.getY() + || entity.motZ != velocity.getZ()) { + entity.getBukkitEntity().setVelocity(velocity); + } + } + worldserver1.addEntity(entity); + worldserver1.entityJoinedWorld(entity, false); + } + + } + + entity.spawnIn(worldserver1); + // CraftBukkit end + } + + public void tick() { + if (++this.u > 600) { + // Azurite - send latency lazily as it is not that important + this.writeAllLazily(new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.UPDATE_LATENCY, this.players)); + this.u = 0; + } + } + + public void sendAll(Packet packet) { + for (EntityPlayer p : players) { + p.playerConnection.sendPacket(packet); + } + } + + public void writeAllLazily(Packet packet) { + for (EntityPlayer p : players) { + p.playerConnection.writePacketLazily(packet); + } + } + + // CraftBukkit start - add a world/entity limited version + public void sendAll(Packet packet, EntityHuman entityhuman) { + if (entityhuman instanceof EntityPlayer) + for (EntityPlayer entityplayer : players) { + if (!entityplayer.getBukkitEntity().canSee(((EntityPlayer) entityhuman).getBukkitEntity())) + continue; + entityplayer.playerConnection.sendPacket(packet); + } + else for (EntityPlayer entityplayer : players) + entityplayer.playerConnection.sendPacket(packet); + } + + // Azurite - Optimize player logins + public void sendAllLazily(Packet packet, EntityHuman entityhuman) { + if (entityhuman instanceof EntityPlayer) + for (EntityPlayer entityplayer : players) { + if (!entityplayer.getBukkitEntity().canSee(((EntityPlayer) entityhuman).getBukkitEntity())) + continue; + entityplayer.playerConnection.writePacketLazily(packet); + } + else for (EntityPlayer entityplayer : players) + entityplayer.playerConnection.writePacketLazily(packet); + } + + public void sendAll(Packet packet, World world) { + for (EntityPlayer p : players) { + p.playerConnection.sendPacket(packet); + } + } + // CraftBukkit end + + public void a(Packet packet, int i) { + for (EntityPlayer p : players) { + if (p.dimension == i) { + p.playerConnection.sendPacket(packet); + } + } + } + + public void a(EntityHuman entityhuman, IChatBaseComponent ichatbasecomponent) { + ScoreboardTeamBase scoreboardteambase = entityhuman.getScoreboardTeam(); + + if (scoreboardteambase != null) { + for (String s : scoreboardteambase.getPlayerNameSet()) { + EntityPlayer entityplayer = this.getPlayer(s); + + if (entityplayer != null && entityplayer != entityhuman) { + entityplayer.sendMessage(ichatbasecomponent); + } + } + + } + } + + public void b(EntityHuman entityhuman, IChatBaseComponent ichatbasecomponent) { + ScoreboardTeamBase scoreboardteambase = entityhuman.getScoreboardTeam(); + + if (scoreboardteambase == null) { + this.sendMessage(ichatbasecomponent); + } else { + for (EntityPlayer p : players) { + if (p.getScoreboardTeam() != scoreboardteambase) { + p.sendMessage(ichatbasecomponent); + } + } + + } + } + + public String b(boolean flag) { + StringBuilder s = new StringBuilder(); + List arraylist = Lists.newArrayList(this.players); + + for (int i = 0; i < arraylist.size(); ++i) { + if (i > 0) { + s.append(", "); + } + + s.append(arraylist.get(i).getName()); + if (flag) { + s.append(" (").append(arraylist.get(i).getUniqueID().toString()).append(")"); + } + } + + return s.toString(); + } + + public String[] f() { + String[] astring = new String[this.players.size()]; + + for (int i = 0; i < this.players.size(); ++i) { + astring[i] = players.get(i).getName(); + } + + return astring; + } + + public GameProfile[] g() { + GameProfile[] agameprofile = new GameProfile[this.players.size()]; + + for (int i = 0; i < this.players.size(); ++i) { + agameprofile[i] = players.get(i).getProfile(); + } + + return agameprofile; + } + + public GameProfileBanList getProfileBans() { + return this.k; + } + + public IpBanList getIPBans() { + return this.l; + } + + public void addOp(GameProfile gameprofile) { + this.operators.add(new OpListEntry(gameprofile, this.server.p(), this.operators.b(gameprofile))); + Player player = this.server.server.getPlayer(gameprofile.getId()); + if (player != null) + player.recalculatePermissions(); + } + + public void removeOp(GameProfile gameprofile) { + this.operators.remove(gameprofile); + Player player = this.server.server.getPlayer(gameprofile.getId()); + if (player != null) + player.recalculatePermissions(); + } + + public boolean isWhitelisted(GameProfile gameprofile) { + return !this.hasWhitelist || this.operators.d(gameprofile) || this.whitelist.d(gameprofile); + } + + public boolean isOp(GameProfile gameprofile) { + return this.operators.d(gameprofile); + } + + public EntityPlayer getPlayer(String s) { + return this.playersByName.get(s); // Spigot + } + + public void sendPacketNearby(double d0, double d1, double d2, double d3, int i, Packet packet) { + sendPacketNearby(null, d0, d1, d2, d3, i, packet); + } + + public void sendPacketNearby(EntityHuman entityhuman, double d0, double d1, double d2, double d3, int i, Packet packet) { + double squared = d3 * d3; + for (EntityPlayer entityplayer : this.players) { + if (!(entityhuman instanceof EntityPlayer) || entityplayer.getBukkitEntity().canSee(((EntityPlayer) entityhuman).getBukkitEntity())) + if (entityplayer != entityhuman && entityplayer.dimension == i) { + double d4 = d0 - entityplayer.locX; + double d5 = d1 - entityplayer.locY; + double d6 = d2 - entityplayer.locZ; + if (d4 * d4 + d5 * d5 + d6 * d6 < squared) + entityplayer.playerConnection.sendPacket(packet); + } + } + } + + public void savePlayers() { + for (EntityPlayer p : players) { + this.savePlayerFile(p); + } + } + + public void addWhitelist(GameProfile gameprofile) { + this.whitelist.add(new WhiteListEntry(gameprofile)); + } + + public void removeWhitelist(GameProfile gameprofile) { + this.whitelist.remove(gameprofile); + } + + public WhiteList getWhitelist() { + return this.whitelist; + } + + public String[] getWhitelisted() { + return this.whitelist.getEntries(); + } + + public OpList getOPs() { + return this.operators; + } + + public String[] n() { + return this.operators.getEntries(); + } + + public void reloadWhitelist() { + } + + public void b(EntityPlayer entityplayer, WorldServer worldserver) { + WorldBorder worldborder = entityplayer.world.getWorldBorder(); // CraftBukkit + + entityplayer.playerConnection.sendPacket( + new PacketPlayOutWorldBorder(worldborder, PacketPlayOutWorldBorder.EnumWorldBorderAction.INITIALIZE)); + entityplayer.playerConnection.sendPacket( + new PacketPlayOutUpdateTime(worldserver.getTime(), + worldserver.getDayTime(), worldserver.getGameRules().getBoolean("doDaylightCycle"))); + + if (worldserver.S()) { + // CraftBukkit start - handle player weather + entityplayer.setPlayerWeather(org.bukkit.WeatherType.DOWNFALL, false); + entityplayer.updateWeather(-worldserver.p, worldserver.p, -worldserver.r, worldserver.r); + // CraftBukkit end + } + + } + + public void updateClient(EntityPlayer entityplayer) { + entityplayer.updateInventory(entityplayer.defaultContainer); + // entityplayer.triggerHealthUpdate(); + entityplayer.getBukkitEntity().updateScaledHealth(); // CraftBukkit - Update scaled health on respawn and worldchange + entityplayer.playerConnection.sendPacket(new PacketPlayOutHeldItemSlot(entityplayer.inventory.itemInHandIndex)); + } + + public int getPlayerCount() { + return this.players.size(); + } + + public int getMaxPlayers() { + return this.maxPlayers; + } + + public String[] getSeenPlayers() { + return this.server.worlds.get(0).getDataManager().getPlayerFileData().getSeenPlayers(); // CraftBukkit + } + + public boolean getHasWhitelist() { + return this.hasWhitelist; + } + + public void setHasWhitelist(boolean flag) { + this.hasWhitelist = flag; + } + + public List b(String s) { + ArrayList arraylist = Lists.newArrayList(); + + for (EntityPlayer entityplayer : this.players) { + if (entityplayer.w().equals(s)) { + arraylist.add(entityplayer); + } + } + + return arraylist; + } + + public int s() { + return this.r; + } + + public MinecraftServer getServer() { + return this.server; + } + + public NBTTagCompound t() { + return null; + } + + private void a(EntityPlayer entityplayer, EntityPlayer entityplayer1, World world) { + if (entityplayer1 != null) { + entityplayer.playerInteractManager.setGameMode(entityplayer1.playerInteractManager.getGameMode()); + } + + entityplayer.playerInteractManager.b(world.getWorldData().getGameType()); + } + + public void u() { + for (EntityPlayer p : players) { + p.playerConnection.disconnect(server.server.getShutdownMessage()); // CraftBukkit - add custom shutdown message + } + } + + public void sendMessage(IChatBaseComponent[] iChatBaseComponents) { + for (IChatBaseComponent component : iChatBaseComponents) { + sendMessage(component, true); + } + } + + public void sendMessage(IChatBaseComponent ichatbasecomponent, boolean flag) { + this.server.sendMessage(ichatbasecomponent); + this.sendAll(new PacketPlayOutChat(CraftChatMessage.fixComponent(ichatbasecomponent), (byte) (flag ? 1 : 0))); + } + + public void sendMessage(IChatBaseComponent ichatbasecomponent) { + this.sendMessage(ichatbasecomponent, true); + } + + public ServerStatisticManager a(EntityHuman entityhuman) { + UUID uuid = entityhuman.getUniqueID(); + ServerStatisticManager serverstatisticmanager = uuid == null ? null : this.o.get(uuid); + + if (serverstatisticmanager == null) { + File file = new File(this.server.getWorldServer(0).getDataManager().getDirectory(), "stats"); + File file1 = new File(file, FastUUID.toString(uuid) + ".json"); + + if (!file1.exists()) { + File file2 = new File(file, entityhuman.getName() + ".json"); + + if (file2.exists() && file2.isFile()) { + file2.renameTo(file1); + } + } + + serverstatisticmanager = new ServerStatisticManager(this.server, file1); + serverstatisticmanager.a(); + this.o.put(uuid, serverstatisticmanager); + } + + return serverstatisticmanager; + } + + public void a(int i) { + this.r = i; + if (this.server.worldServer != null) { + // CraftBukkit start + for (int k = 0; k < server.worlds.size(); ++k) { + WorldServer worldserver = server.worlds.get(0); + // CraftBukkit end + + if (worldserver != null) { + worldserver.getPlayerChunkMap().a(i); + } + } + + } + } + + public List v() { + return this.players; + } + + public EntityPlayer a(UUID uuid) { + return this.j.get(uuid); + } + + public boolean f(GameProfile gameprofile) { + return false; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PlayerListBox.java b/azurite-server/src/main/java/net/minecraft/server/PlayerListBox.java new file mode 100644 index 0000000..46a762a --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PlayerListBox.java @@ -0,0 +1,28 @@ +package net.minecraft.server; + +import java.util.Vector; +import javax.swing.JList; + +public class PlayerListBox extends JList implements IUpdatePlayerListBox { + + private MinecraftServer a; + private int b; + + public PlayerListBox(MinecraftServer minecraftserver) { + this.a = minecraftserver; + minecraftserver.a((IUpdatePlayerListBox) this); + } + + public void c() { + if (this.b++ % 20 == 0) { + Vector vector = new Vector(); + + for (int i = 0; i < this.a.getPlayerList().v().size(); ++i) { + vector.add(((EntityPlayer) this.a.getPlayerList().v().get(i)).getName()); + } + + this.setListData(vector); + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PlayerSelector.java b/azurite-server/src/main/java/net/minecraft/server/PlayerSelector.java new file mode 100644 index 0000000..b14aa5f --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PlayerSelector.java @@ -0,0 +1,624 @@ +package net.minecraft.server; + +import com.google.common.base.Predicate; +import com.google.common.base.Predicates; +import com.google.common.collect.ComparisonChain; +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.Map.Entry; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class PlayerSelector { + + private static final Pattern a = Pattern.compile("^@([pare])(?:\\[([\\w=,!-]*)\\])?$"); + private static final Pattern b = Pattern.compile("\\G([-!]?[\\w-]*)(?:$|,)"); + private static final Pattern c = Pattern.compile("\\G(\\w+)=([-!]?[\\w-]*)(?:$|,)"); + private static final Set d = Sets.newHashSet("x", "y", "z", "dx", "dy", "dz", "rm", "r"); + + public static EntityPlayer getPlayer(ICommandListener icommandlistener, String s) { + return getEntity(icommandlistener, s, EntityPlayer.class); + } + + public static T getEntity(ICommandListener icommandlistener, String s, Class oclass) { + List list = getPlayers(icommandlistener, s, oclass); + + return list.size() == 1 ? list.get(0) : null; + } + + public static IChatBaseComponent getPlayerNames(ICommandListener icommandlistener, String s) { + List list = getPlayers(icommandlistener, s, Entity.class); + + if (list.isEmpty()) { + return null; + } else { + List arraylist = new ArrayList<>(); + + for (Object o : list) { + Entity entity = (Entity) o; + + arraylist.add(entity.getScoreboardDisplayName()); + } + + return CommandAbstract.a(arraylist); + } + } + + public static List getPlayers(ICommandListener icommandlistener, String s, Class oclass) { + Matcher matcher = PlayerSelector.a.matcher(s); + + if (matcher.matches() && icommandlistener.a(1, "@")) { + Map map = c(matcher.group(2)); + + if (!b(icommandlistener, map)) { + return Collections.emptyList(); + } else { + String s1 = matcher.group(1); + BlockPosition blockposition = b(map, icommandlistener.getChunkCoordinates()); + List list = a(icommandlistener, map); + ArrayList arraylist = new ArrayList<>(); + + for (Object o : list) { + World world = (World) o; + + if (world != null) { + ArrayList arraylist1 = new ArrayList<>(); + + arraylist1.addAll(a(map, s1)); + arraylist1.addAll(b(map)); + arraylist1.addAll(c(map)); + arraylist1.addAll(d(map)); + arraylist1.addAll(e(map)); + arraylist1.addAll(f(map)); + arraylist1.addAll(a(map, blockposition)); + arraylist1.addAll(g(map)); + arraylist.addAll(a(map, oclass, arraylist1, s1, world, blockposition)); + } + } + + return a(arraylist, map, icommandlistener, oclass, s1, blockposition); + } + } else { + return Collections.emptyList(); + } + } + + private static List a(ICommandListener icommandlistener, Map map) { + ArrayList arraylist = new ArrayList<>(); + + if (h(map)) { + arraylist.add(icommandlistener.getWorld()); + } else { + Collections.addAll(arraylist, MinecraftServer.getServer().worldServer); + } + + return arraylist; + } + + private static boolean b(ICommandListener icommandlistener, Map map) { + String s = b(map, "type"); + + s = s != null && s.startsWith("!") ? s.substring(1) : s; + if (s != null && !EntityTypes.b(s)) { + ChatMessage chatmessage = new ChatMessage("commands.generic.entity.invalidType", new Object[] { s}); + + chatmessage.getChatModifier().setColor(EnumChatFormat.RED); + icommandlistener.sendMessage(chatmessage); + return false; + } else { + return true; + } + } + + private static List> a(Map map, String s) { + ArrayList> arraylist = new ArrayList<>(); + String s1 = b(map, "type"); + final boolean flag = s1 != null && s1.startsWith("!"); + + if (flag) { + s1 = s1.substring(1); + } + + boolean flag1 = !s.equals("e"); + boolean flag2 = s.equals("r") && s1 != null; + + if ((s1 == null || !s.equals("e")) && !flag2) { + if (flag1) { + arraylist.add(new Predicate() { + public boolean a(Entity entity) { + return entity instanceof EntityHuman; + } + + public boolean apply(Object object) { + return this.a((Entity) object); + } + }); + } + } else { + final String s1Final = s1; + arraylist.add(new Predicate() { + public boolean a(Entity entity) { + return EntityTypes.a(entity, s1Final) != flag; + } + + public boolean apply(Object object) { + return this.a((Entity) object); + } + }); + } + + return arraylist; + } + + private static List> b(Map map) { + ArrayList> arraylist = new ArrayList<>(); + final int i = a(map, "lm", -1); + final int j = a(map, "l", -1); + + if (i > -1 || j > -1) { + arraylist.add(new Predicate() { + public boolean a(Entity entity) { + if (!(entity instanceof EntityPlayer)) { + return false; + } else { + EntityPlayer entityplayer = (EntityPlayer) entity; + + return (i <= -1 || entityplayer.expLevel >= i) && (j <= -1 || entityplayer.expLevel <= j); + } + } + + public boolean apply(Object object) { + return this.a((Entity) object); + } + }); + } + + return arraylist; + } + + private static List> c(Map map) { + ArrayList> arraylist = new ArrayList<>(); + final int i = a(map, "m", WorldSettings.EnumGamemode.NOT_SET.getId()); + + if (i != WorldSettings.EnumGamemode.NOT_SET.getId()) { + arraylist.add(new Predicate() { + public boolean a(Entity entity) { + if (!(entity instanceof EntityPlayer)) { + return false; + } else { + EntityPlayer entityplayer = (EntityPlayer) entity; + + return entityplayer.playerInteractManager.getGameMode().getId() == i; + } + } + + public boolean apply(Object object) { + return this.a((Entity) object); + } + }); + } + + return arraylist; + } + + private static List> d(Map map) { + List> arraylist = new ArrayList<>(); + String s = b(map, "team"); + final boolean flag = s != null && s.startsWith("!"); + + if (flag) { + s = s.substring(1); + } + final String sFinal = s; // required to use in anonymous class below + + if (s != null) { + arraylist.add(new Predicate() { + public boolean a(Entity entity) { + if (!(entity instanceof EntityLiving)) { + return false; + } else { + EntityLiving entityliving = (EntityLiving) entity; + ScoreboardTeamBase scoreboardteambase = entityliving.getScoreboardTeam(); + String s1 = scoreboardteambase == null ? "" : scoreboardteambase.getName(); + + return sFinal.equals(s1) != flag; + } + } + + public boolean apply(Object object) { + return this.a((Entity) object); + } + }); + } + + return arraylist; + } + + private static List> e(Map map) { + List> arraylist = new ArrayList<>(); + final Map map1 = a(map); + + if (map1 != null && map1.size() > 0) { + arraylist.add(new Predicate() { + public boolean a(Entity entity) { + Scoreboard scoreboard = MinecraftServer.getServer().getWorldServer(0).getScoreboard(); + Iterator> iterator = map1.entrySet().iterator(); + + Entry entry; + boolean flag; + int i; + + do { + if (!iterator.hasNext()) { + return true; + } + + entry = (Entry) iterator.next(); + String s = (String) entry.getKey(); + + flag = false; + if (s.endsWith("_min") && s.length() > 4) { + flag = true; + s = s.substring(0, s.length() - 4); + } + + ScoreboardObjective scoreboardobjective = scoreboard.getObjective(s); + + if (scoreboardobjective == null) { + return false; + } + + String s1 = entity instanceof EntityPlayer ? entity.getName() : entity.getUniqueID().toString(); + + if (!scoreboard.b(s1, scoreboardobjective)) { + return false; + } + + ScoreboardScore scoreboardscore = scoreboard.getPlayerScoreForObjective(s1, scoreboardobjective); + + i = scoreboardscore.getScore(); + if (i < (Integer) entry.getValue() && flag) { + return false; + } + } while (i <= (Integer) entry.getValue() || flag); + + return false; + } + + public boolean apply(Object object) { + return this.a((Entity) object); + } + }); + } + + return arraylist; + } + + private static List> f(Map map) { + List> arraylist = new ArrayList<>(); + String s = b(map, "name"); + final boolean flag = s != null && s.startsWith("!"); + + if (flag) { + s = s.substring(1); + } + final String sFinal = s; // required to use in anonymous class below + + if (s != null) { + arraylist.add(new Predicate() { + public boolean a(Entity entity) { + return entity.getName().equals(sFinal) != flag; + } + + public boolean apply(Object object) { + return this.a((Entity) object); + } + }); + } + + return arraylist; + } + + private static List> a(Map map, final BlockPosition blockposition) { + List> arraylist = new ArrayList<>(); + final int i = a(map, "rm", -1); + final int j = a(map, "r", -1); + + if (blockposition != null && (i >= 0 || j >= 0)) { + final int k = i * i; + final int l = j * j; + + arraylist.add(new Predicate() { + public boolean a(Entity entity) { + int i1 = (int) entity.c(blockposition); + + return (i < 0 || i1 >= k) && (j < 0 || i1 <= l); + } + + public boolean apply(Object object) { + return this.a((Entity) object); + } + }); + } + + return arraylist; + } + + private static List> g(Map map) { + List> arraylist = new ArrayList<>(); + + if (map.containsKey("rym") || map.containsKey("ry")) { + final int k = a(a(map, "rym", 0)); + final int j = a(a(map, "ry", 359)); + arraylist.add(new Predicate() { + public boolean a(Entity entity) { + int i = PlayerSelector.a((int) Math.floor(entity.yaw)); + + return j > k ? i >= j || i <= k : i >= j && i <= k; + } + + public boolean apply(Object object) { + return this.a((Entity) object); + } + }); + } + + if (map.containsKey("rxm") || map.containsKey("rx")) { + final int k = a(a(map, "rxm", 0));; + final int j = a(a(map, "rx", 359)); + arraylist.add(new Predicate() { + public boolean a(Entity entity) { + int i = PlayerSelector.a((int) Math.floor(entity.pitch)); + + return j > k ? i >= j || i <= k : i >= j && i <= k; + } + + public boolean apply(Object object) { + return this.a((Entity) object); + } + }); + } + + return arraylist; + } + + private static List a(Map map, Class oclass, List> list, String s, World world, BlockPosition blockposition) { + List arraylist = new ArrayList<>(); + String s1 = b(map, "type"); + + s1 = s1 != null && s1.startsWith("!") ? s1.substring(1) : s1; + boolean flag = !s.equals("e"); + boolean flag1 = s.equals("r") && s1 != null; + int i = a(map, "dx", 0); + int j = a(map, "dy", 0); + int k = a(map, "dz", 0); + int l = a(map, "r", -1); + Predicate predicate = Predicates.and(list); + Predicate predicate1 = Predicates.and(IEntitySelector.a, predicate); + + if (blockposition != null) { + int i1 = world.players.size(); + int j1 = world.entityList.size(); + boolean flag2 = i1 < j1 / 16; + final AxisAlignedBB axisalignedbb; + + if (!map.containsKey("dx") && !map.containsKey("dy") && !map.containsKey("dz")) { + if (l >= 0) { + axisalignedbb = new AxisAlignedBB(blockposition.getX() - l, blockposition.getY() - l, blockposition.getZ() - l, blockposition.getX() + l + 1, blockposition.getY() + l + 1, blockposition.getZ() + l + 1); + if (flag && flag2 && !flag1) { + arraylist.addAll(world.b(oclass, predicate1)); + } else { + arraylist.addAll(world.a(oclass, axisalignedbb, predicate1)); + } + } else if (s.equals("a")) { + arraylist.addAll(world.b(oclass, predicate)); + } else if (!s.equals("p") && (!s.equals("r") || flag1)) { + arraylist.addAll(world.a(oclass, predicate1)); + } else { + arraylist.addAll(world.b(oclass, predicate1)); + } + } else { + axisalignedbb = a(blockposition, i, j, k); + if (flag && flag2 && !flag1) { + Predicate predicate2 = new Predicate() { + public boolean a(Entity entity) { + return entity.locX >= axisalignedbb.a && entity.locY >= axisalignedbb.b && entity.locZ >= axisalignedbb.c && entity.locX < axisalignedbb.d && entity.locY < axisalignedbb.e && entity.locZ < axisalignedbb.f; + } + + public boolean apply(Object object) { + return this.a((Entity) object); + } + }; + + arraylist.addAll(world.b(oclass, Predicates.and(predicate1, predicate2))); + } else { + arraylist.addAll(world.a(oclass, axisalignedbb, predicate1)); + } + } + } else if (s.equals("a")) { + arraylist.addAll(world.b(oclass, predicate)); + } else if (!s.equals("p") && (!s.equals("r") || flag1)) { + arraylist.addAll(world.a(oclass, predicate1)); + } else { + arraylist.addAll(world.b(oclass, predicate1)); + } + + return arraylist; + } + + private static List a(List list, Map map, ICommandListener icommandlistener, Class oclass, String s, final BlockPosition blockposition) { + int i = a(map, "c", !s.equals("a") && !s.equals("e") ? 1 : 0); + + if (!s.equals("p") && !s.equals("a") && !s.equals("e")) { + if (s.equals("r")) { + Collections.shuffle(list); + } + } else if (blockposition != null) { + Collections.sort((List) list, new Comparator() { + public int a(Entity entity, Entity entity1) { + return ComparisonChain.start().compare(entity.b(blockposition), entity1.b(blockposition)).result(); + } + + public int compare(Object object, Object object1) { + return this.a((Entity) object, (Entity) object1); + } + }); + } + + Entity entity = icommandlistener.f(); + + if (entity != null && oclass.isAssignableFrom(entity.getClass()) && i == 1 && list.contains(entity) && !"r".equals(s)) { + list = (List) Lists.newArrayList(entity); + } + + if (i != 0) { + if (i < 0) { + Collections.reverse(list); + } + + list = ((List) list).subList(0, Math.min(Math.abs(i), list.size())); + } + + return list; + } + + private static AxisAlignedBB a(BlockPosition blockposition, int i, int j, int k) { + boolean flag = i < 0; + boolean flag1 = j < 0; + boolean flag2 = k < 0; + int l = blockposition.getX() + (flag ? i : 0); + int i1 = blockposition.getY() + (flag1 ? j : 0); + int j1 = blockposition.getZ() + (flag2 ? k : 0); + int k1 = blockposition.getX() + (flag ? 0 : i) + 1; + int l1 = blockposition.getY() + (flag1 ? 0 : j) + 1; + int i2 = blockposition.getZ() + (flag2 ? 0 : k) + 1; + + return new AxisAlignedBB(l, i1, j1, k1, l1, i2); + } + + public static int a(int i) { + i %= 360; + if (i >= 160) { + i -= 360; + } + + if (i < 0) { + i += 360; + } + + return i; + } + + private static BlockPosition b(Map map, BlockPosition blockposition) { + return new BlockPosition(a(map, "x", blockposition.getX()), a(map, "y", blockposition.getY()), a(map, "z", blockposition.getZ())); + } + + private static boolean h(Map map) { + Iterator iterator = PlayerSelector.d.iterator(); + + String s; + + do { + if (!iterator.hasNext()) { + return false; + } + + s = (String) iterator.next(); + } while (!map.containsKey(s)); + + return true; + } + + private static int a(Map map, String s, int i) { + return map.containsKey(s) ? MathHelper.a(map.get(s), i) : i; + } + + private static String b(Map map, String s) { + return map.get(s); + } + + public static Map a(Map map) { + HashMap hashmap = new HashMap<>(); + + for (String s : map.keySet()) { + if (s.startsWith("score_") && s.length() > "score_".length()) { + hashmap.put(s.substring("score_".length()), MathHelper.a(map.get(s), 1)); + } + } + + return hashmap; + } + + public static boolean isList(String s) { + Matcher matcher = PlayerSelector.a.matcher(s); + + if (!matcher.matches()) { + return false; + } else { + Map map = c(matcher.group(2)); + String s1 = matcher.group(1); + int i = !"a".equals(s1) && !"e".equals(s1) ? 1 : 0; + + return a(map, "c", i) != 1; + } + } + + public static boolean isPattern(String s) { + return PlayerSelector.a.matcher(s).matches(); + } + + private static Map c(String s) { + HashMap hashmap = new HashMap<>(); + + if (s == null) { + return hashmap; + } else { + int i = 0; + int j = -1; + + for (Matcher matcher = PlayerSelector.b.matcher(s); matcher.find(); j = matcher.end()) { + String s1 = null; + + switch (i++) { + case 0: + s1 = "x"; + break; + + case 1: + s1 = "y"; + break; + + case 2: + s1 = "z"; + break; + + case 3: + s1 = "r"; + } + + if (s1 != null && matcher.group(1).length() > 0) { + hashmap.put(s1, matcher.group(1)); + } + } + + if (j < s.length()) { + Matcher matcher1 = PlayerSelector.c.matcher(j == -1 ? s : s.substring(j)); + + while (matcher1.find()) { + hashmap.put(matcher1.group(1), matcher1.group(2)); + } + } + + return hashmap; + } + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/net/minecraft/server/PortalTravelAgent.java b/azurite-server/src/main/java/net/minecraft/server/PortalTravelAgent.java new file mode 100644 index 0000000..85a1838 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PortalTravelAgent.java @@ -0,0 +1,475 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; +import org.bukkit.Location; +import org.bukkit.event.entity.EntityPortalExitEvent; +import org.bukkit.util.Vector; + +import java.util.Iterator; +import java.util.List; +import java.util.Random; + +public class PortalTravelAgent { + + private final WorldServer a; + private final Random b; + private final LongHashMap c = new LongHashMap<>(); + private final List d = Lists.newArrayList(); + + public PortalTravelAgent(WorldServer worldserver) { + this.a = worldserver; + this.b = new Random(worldserver.getSeed()); + } + + public void a(Entity entity, float f) { + if (this.a.worldProvider.getDimension() != 1) { + if (!this.b(entity, f)) { + this.a(entity); + this.b(entity, f); + } + } else { + // CraftBukkit start - Modularize end portal creation + BlockPosition created = this.createEndPortal(entity.locX, entity.locY, entity.locZ); + entity.setPositionRotation(created.getX(), created.getY(), created.getZ(), entity.yaw, 0.0F); + entity.motX = entity.motY = entity.motZ = 0.0D; + } + } + + // Split out from original a(Entity, double, double, double, float) method in order to enable being called from createPortal + private BlockPosition createEndPortal(double x, double y, double z) { + int i = MathHelper.floor(x); + int j = MathHelper.floor(y) - 1; + int k = MathHelper.floor(z); + // CraftBukkit end + byte b0 = 1; + + for (int l = -2; l <= 2; ++l) { + for (int i1 = -2; i1 <= 2; ++i1) { + for (int j1 = -1; j1 < 3; ++j1) { + int k1 = i + i1 * b0; + int l1 = j + j1; + int i2 = k - l * b0; + boolean flag = j1 < 0; + + this.a.setTypeUpdate(new BlockPosition(k1, l1, i2), flag ? Blocks.OBSIDIAN.getBlockData() : Blocks.AIR.getBlockData()); + } + } + } + + // CraftBukkit start + return new BlockPosition(i, k, k); + } + + // use logic based on creation to verify end portal + private BlockPosition findEndPortal(BlockPosition portal) { + int i = portal.getX(); + int j = portal.getY() - 1; + int k = portal.getZ(); + byte b0 = 1; + + for (int l = -2; l <= 2; ++l) { + for (int i1 = -2; i1 <= 2; ++i1) { + for (int j1 = -1; j1 < 3; ++j1) { + int k1 = i + i1 * b0; + int l1 = j + j1; + int i2 = k - l * b0; + boolean flag = j1 < 0; + + if (this.a.getType(k1, l1, i2).getBlock() != (flag ? Blocks.OBSIDIAN : Blocks.AIR)) { + return null; + } + } + } + } + return new BlockPosition(i, j, k); + } + // CraftBukkit end + + public boolean b(Entity entity, float f) { + // CraftBukkit start - Modularize portal search process and entity teleportation + // Migot start + BlockPosition found = this.findPortal(entity.locX, entity.locY, entity.locZ, 10); + if (found == null) { + found = this.findPortal(entity.locX, entity.locY, entity.locZ, 128); + } + // Migot end + + Location exit = new Location(this.a.getWorld(), found.getX(), found.getY(), found.getZ(), f, entity.pitch); + Vector velocity = entity.getBukkitEntity().getVelocity(); + this.adjustExit(entity, exit, velocity); + entity.setPositionRotation(exit.getX(), exit.getY(), exit.getZ(), exit.getYaw(), exit.getPitch()); + if (entity.motX != velocity.getX() || entity.motY != velocity.getY() || entity.motZ != velocity.getZ()) { + entity.getBukkitEntity().setVelocity(velocity); + } + return true; + } + + public BlockPosition findPortal(double x, double y, double z, int searchRadius) { // Paper - actually use search radius + if (this.a.getWorld().getEnvironment() == org.bukkit.World.Environment.THE_END) { + return this.findEndPortal(this.a.worldProvider.h()); + } + // CraftBukkit end + double d0 = -1.0D; + // CraftBukkit start + int i = MathHelper.floor(x); + int j = MathHelper.floor(z); + // CraftBukkit end + boolean flag1 = true; + BlockPosition object = BlockPosition.ZERO; + long k = ChunkCoordIntPair.a(i, j); + + if (this.c.contains(k)) { + ChunkCoordinatesPortal portaltravelagent_chunkcoordinatesportal = this.c.getEntry(k); + + d0 = 0.0D; + object = portaltravelagent_chunkcoordinatesportal; + portaltravelagent_chunkcoordinatesportal.c = this.a.getTime(); + flag1 = false; + } else { + BlockPosition blockposition = new BlockPosition(x, y, z); + BlockPosition.MutableBlockPosition mutableblockposition = new BlockPosition.MutableBlockPosition(); + + int zOffset = 0, yOffset = 0; + for (int xDiff = -searchRadius; xDiff <= searchRadius; ++xDiff) { + zOffset = (zOffset + 1) % 2; + for (int zDiff = -searchRadius + zOffset; zDiff <= searchRadius; zDiff = zDiff + 2) { // skipping every 2nd block in z direction and alternating from row to row in x direction + yOffset = (yOffset + 1) % 3; + for (int yPos = this.a.V() - (1 + yOffset) ; yPos >= 0; yPos = yPos - 3) { // checking only every 3rd block in y direction and alternating in height in each column + mutableblockposition.c(blockposition.getX() + xDiff, yPos, blockposition.getZ() + zDiff); + if (this.a.getType(mutableblockposition).getBlock() == Blocks.PORTAL) { + int lowestCorrectHeight = mutableblockposition.getY(); + while (this.a.getType(mutableblockposition.c(mutableblockposition.getX(), mutableblockposition.getY() - 1, mutableblockposition.getZ())).getBlock() == Blocks.PORTAL) { + lowestCorrectHeight = mutableblockposition.getY(); + } + + double d1 = mutableblockposition.c(mutableblockposition.getX(), lowestCorrectHeight, mutableblockposition.getZ()).i(blockposition); + + if (d0 < 0.0D || d1 < d0) { + d0 = d1; + object = new BlockPosition(mutableblockposition); + } + } + } + } + } + } + + if (d0 >= 0.0D) { + if (flag1) { + this.c.put(k, new ChunkCoordinatesPortal(object, this.a.getTime())); + this.d.add(k); + } + // CraftBukkit start - Move entity teleportation logic into exit + return object; + } else { + return null; + } + } + + // Entity repositioning logic split out from original b method and combined with repositioning logic for The End from original a method + public void adjustExit(Entity entity, Location position, Vector velocity) { + Location from = position.clone(); + Vector before = velocity.clone(); + BlockPosition object = new BlockPosition(position.getBlockX(), position.getBlockY(), position.getBlockZ()); + float f = position.getYaw(); + + if (this.a.getWorld().getEnvironment() == org.bukkit.World.Environment.THE_END || entity.getBukkitEntity().getWorld().getEnvironment() == org.bukkit.World.Environment.THE_END || entity.aG() == null) { + position.setPitch(0.0F); + velocity.setX(0); + velocity.setY(0); + velocity.setZ(0); + } else { + // CraftBukkit end + + double d2 = object.getX() + 0.5D; + double d3; + double d4 = object.getZ() + 0.5D; + ShapeDetector.ShapeDetectorCollection shapedetector_shapedetectorcollection = Blocks.PORTAL.f(this.a, object); + boolean flag2 = shapedetector_shapedetectorcollection.b().e().c() == EnumDirection.EnumAxisDirection.NEGATIVE; + double d5 = shapedetector_shapedetectorcollection.b().k() == EnumDirection.EnumAxis.X ? (double) shapedetector_shapedetectorcollection.a().getZ() : (double) shapedetector_shapedetectorcollection.a().getX(); + + d3 = (double) (shapedetector_shapedetectorcollection.a().getY() + 1) - entity.aG().b * (double) shapedetector_shapedetectorcollection.e(); + if (flag2) { + ++d5; + } + + if (shapedetector_shapedetectorcollection.b().k() == EnumDirection.EnumAxis.X) { + d4 = d5 + (1.0D - entity.aG().a) * (double) shapedetector_shapedetectorcollection.d() * (double) shapedetector_shapedetectorcollection.b().e().c().a(); + } else { + d2 = d5 + (1.0D - entity.aG().a) * (double) shapedetector_shapedetectorcollection.d() * (double) shapedetector_shapedetectorcollection.b().e().c().a(); + } + + float f1 = 0.0F; + float f2 = 0.0F; + float f3 = 0.0F; + float f4 = 0.0F; + + if (shapedetector_shapedetectorcollection.b().opposite() == entity.aH()) { + f1 = 1.0F; + f2 = 1.0F; + } else if (shapedetector_shapedetectorcollection.b().opposite() == entity.aH().opposite()) { + f1 = -1.0F; + f2 = -1.0F; + } else if (shapedetector_shapedetectorcollection.b().opposite() == entity.aH().e()) { + f3 = 1.0F; + f4 = -1.0F; + } else { + f3 = -1.0F; + f4 = 1.0F; + } + + // CraftBukkit start + double d6 = velocity.getX(); + double d7 = velocity.getZ(); + // CraftBukkit end + + // CraftBukkit start - Adjust position and velocity instances instead of entity + velocity.setX(d6 * (double) f1 + d7 * (double) f4); + velocity.setZ(d6 * (double) f3 + d7 * (double) f2); + f = f - (float) (entity.aH().opposite().b() * 90) + (float) (shapedetector_shapedetectorcollection.b().b() * 90); + // entity.setPositionRotation(d2, d3, d4, entity.yaw, entity.pitch); + position.setX(d2); + position.setY(d3); + position.setZ(d4); + position.setYaw(f); + } + EntityPortalExitEvent event = new EntityPortalExitEvent(entity.getBukkitEntity(), from, position, before, velocity); + this.a.getServer().getPluginManager().callEvent(event); + Location to = event.getTo(); + if (event.isCancelled() || to == null || !entity.isAlive()) { + position.setX(from.getX()); + position.setY(from.getY()); + position.setZ(from.getZ()); + position.setYaw(from.getYaw()); + position.setPitch(from.getPitch()); + velocity.copy(before); + } else { + position.setX(to.getX()); + position.setY(to.getY()); + position.setZ(to.getZ()); + position.setYaw(to.getYaw()); + position.setPitch(to.getPitch()); + velocity.copy(event.getAfter()); // event.getAfter() will never be null, as setAfter() will cause an NPE if null is passed in + } + // CraftBukkit end + } + + public boolean a(Entity entity) { + // CraftBukkit start - Allow for portal creation to be based on coordinates instead of entity + return this.createPortal(entity.locX, entity.locY, entity.locZ, 16); + } + + public boolean createPortal(double x, double y, double z, int b0) { + if (this.a.getWorld().getEnvironment() == org.bukkit.World.Environment.THE_END) { + createEndPortal(x, y, z); + return true; + } + // CraftBukkit end + double d0 = -1.0D; + // CraftBukkit start + int i = MathHelper.floor(x); + int j = MathHelper.floor(y); + int k = MathHelper.floor(z); + // CraftBukkit end + int l = i; + int i1 = j; + int j1 = k; + int k1 = 0; + int l1 = this.b.nextInt(4); + + int i2; + double d1; + int j2; + double d2; + int k2; + int l2; + int i3; + int j3; + int k3; + int l3; + int i4; + int j4; + int k4; + double d3; + double d4; + + for (i2 = i - b0; i2 <= i + b0; ++i2) { + d1 = (double) i2 + 0.5D - x; // CraftBukkit + + for (j2 = k - b0; j2 <= k + b0; ++j2) { + d2 = (double) j2 + 0.5D - z; // CraftBukkit + + label271: + for (k2 = this.a.V() - 1; k2 >= 0; --k2) { + if (this.a.isEmpty(i2, k2, j2)) { + while (k2 > 0 && this.a.isEmpty(i2, k2 - 1, j2)) { + --k2; + } + + for (l2 = l1; l2 < l1 + 4; ++l2) { + i3 = l2 % 2; + j3 = 1 - i3; + if (l2 % 4 >= 2) { + i3 = -i3; + j3 = -j3; + } + + for (k3 = 0; k3 < 3; ++k3) { + for (l3 = 0; l3 < 4; ++l3) { + for (i4 = -1; i4 < 4; ++i4) { + j4 = i2 + (l3 - 1) * i3 + k3 * j3; + k4 = k2 + i4; + int l4 = j2 + (l3 - 1) * j3 - k3 * i3; + + if (i4 < 0 && !this.a.getType(j4, k4, l4).getBlock().getMaterial().isBuildable() || i4 >= 0 && !this.a.isEmpty(j4, k4, l4)) { + continue label271; + } + } + } + } + + d3 = (double) k2 + 0.5D - y; // CraftBukkit + d4 = d1 * d1 + d3 * d3 + d2 * d2; + if (d0 < 0.0D || d4 < d0) { + d0 = d4; + l = i2; + i1 = k2; + j1 = j2; + k1 = l2 % 4; + } + } + } + } + } + } + + if (d0 < 0.0D) { + for (i2 = i - b0; i2 <= i + b0; ++i2) { + d1 = (double) i2 + 0.5D - x; // CraftBukkit + + for (j2 = k - b0; j2 <= k + b0; ++j2) { + d2 = (double) j2 + 0.5D - z; // CraftBukkit + + label219: + for (k2 = this.a.V() - 1; k2 >= 0; --k2) { + if (this.a.isEmpty(i2, k2, j2)) { + while (k2 > 0 && this.a.isEmpty(i2, k2 - 1, j2)) { + --k2; + } + + for (l2 = l1; l2 < l1 + 2; ++l2) { + i3 = l2 % 2; + j3 = 1 - i3; + + for (k3 = 0; k3 < 4; ++k3) { + for (l3 = -1; l3 < 4; ++l3) { + i4 = i2 + (k3 - 1) * i3; + j4 = k2 + l3; + k4 = j2 + (k3 - 1) * j3; + if (l3 < 0 && !this.a.getType(i4, j4, k4).getBlock().getMaterial().isBuildable() || l3 >= 0 && !this.a.isEmpty(i4, j4, k4)) { + continue label219; + } + } + } + + d3 = (double) k2 + 0.5D - y; // CraftBukkit + d4 = d1 * d1 + d3 * d3 + d2 * d2; + if (d0 < 0.0D || d4 < d0) { + d0 = d4; + l = i2; + i1 = k2; + j1 = j2; + k1 = l2 % 2; + } + } + } + } + } + } + } + + int i5 = l; + int j5 = i1; + + j2 = j1; + int k5 = k1 % 2; + int l5 = 1 - k5; + + if (k1 % 4 >= 2) { + k5 = -k5; + l5 = -l5; + } + + if (d0 < 0.0D) { + i1 = MathHelper.clamp(i1, 70, this.a.V() - 10); + j5 = i1; + + for (k2 = -1; k2 <= 1; ++k2) { + for (l2 = 1; l2 < 3; ++l2) { + for (i3 = -1; i3 < 3; ++i3) { + j3 = i5 + (l2 - 1) * k5 + k2 * l5; + k3 = j5 + i3; + l3 = j2 + (l2 - 1) * l5 - k2 * k5; + boolean flag = i3 < 0; + + this.a.setTypeUpdate(new BlockPosition(j3, k3, l3), flag ? Blocks.OBSIDIAN.getBlockData() : Blocks.AIR.getBlockData()); + } + } + } + } + + IBlockData iblockdata = Blocks.PORTAL.getBlockData().set(BlockPortal.AXIS, k5 != 0 ? EnumDirection.EnumAxis.X : EnumDirection.EnumAxis.Z); + + for (l2 = 0; l2 < 4; ++l2) { + for (i3 = 0; i3 < 4; ++i3) { + for (j3 = -1; j3 < 4; ++j3) { + k3 = i5 + (i3 - 1) * k5; + l3 = j5 + j3; + i4 = j2 + (i3 - 1) * l5; + boolean flag1 = i3 == 0 || i3 == 3 || j3 == -1 || j3 == 3; + + this.a.setTypeAndData(new BlockPosition(k3, l3, i4), flag1 ? Blocks.OBSIDIAN.getBlockData() : iblockdata, 2); + } + } + + for (i3 = 0; i3 < 4; ++i3) { + for (j3 = -1; j3 < 4; ++j3) { + k3 = i5 + (i3 - 1) * k5; + l3 = j5 + j3; + i4 = j2 + (i3 - 1) * l5; + this.a.applyPhysics(k3, l3, i4, this.a.getType(k3, l3, i4).getBlock()); + } + } + } + + return true; + } + + public void a(long i) { + if (i % 100L == 0L) { + Iterator iterator = this.d.iterator(); + long j = i - 300L; + + while (iterator.hasNext()) { + Long olong = iterator.next(); + ChunkCoordinatesPortal portaltravelagent_chunkcoordinatesportal = this.c.getEntry(olong); + + if (portaltravelagent_chunkcoordinatesportal == null || portaltravelagent_chunkcoordinatesportal.c < j) { + iterator.remove(); + this.c.remove(olong); + } + } + } + + } + + public static class ChunkCoordinatesPortal extends BlockPosition { + + public long c; + + public ChunkCoordinatesPortal(BlockPosition blockposition, long i) { + super(blockposition.getX(), blockposition.getY(), blockposition.getZ()); + this.c = i; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/Position.java b/azurite-server/src/main/java/net/minecraft/server/Position.java new file mode 100644 index 0000000..6c40cc1 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/Position.java @@ -0,0 +1,26 @@ +package net.minecraft.server; + +public class Position implements IPosition { + + protected final double a; + protected final double b; + protected final double c; + + public Position(double d0, double d1, double d2) { + this.a = d0; + this.b = d1; + this.c = d2; + } + + public double getX() { + return this.a; + } + + public double getY() { + return this.b; + } + + public double getZ() { + return this.c; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PossibleFishingResult.java b/azurite-server/src/main/java/net/minecraft/server/PossibleFishingResult.java new file mode 100644 index 0000000..2e7f861 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PossibleFishingResult.java @@ -0,0 +1,50 @@ +package net.minecraft.server; + +import java.util.Random; + +public class PossibleFishingResult extends WeightedRandom.WeightedRandomChoice { + + private final ItemStack b; + private float c; + private boolean d; + + public PossibleFishingResult(ItemStack itemstack, int i) { + super(i); + this.b = itemstack; + } + + public ItemStack a(Random random) { + ItemStack itemstack = this.b.cloneItemStack(); + + if (this.c > 0.0F) { + int i = (int) (this.c * (float) this.b.j()); + int j = itemstack.j() - random.nextInt(random.nextInt(i) + 1); + + if (j > i) { + j = i; + } + + if (j < 1) { + j = 1; + } + + itemstack.setData(j); + } + + if (this.d) { + EnchantmentManager.a(random, itemstack, 30); + } + + return itemstack; + } + + public PossibleFishingResult a(float f) { + this.c = f; + return this; + } + + public PossibleFishingResult a() { + this.d = true; + return this; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/PotionBrewer.java b/azurite-server/src/main/java/net/minecraft/server/PotionBrewer.java new file mode 100644 index 0000000..c303823 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PotionBrewer.java @@ -0,0 +1,448 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; + +import java.util.*; + +public class PotionBrewer { + + public static final String a = null; + public static final String b; + public static final String c = "+0-1-2-3&4-4+13"; + public static final String d; + public static final String e; + public static final String f; + public static final String g; + public static final String h; + public static final String i; + public static final String j; + public static final String k; + public static final String l; + public static final String m; + public static final String n; + private static final Map effectDurations = new HashMap<>(); + private static final Map effectAmplifiers = new HashMap<>(); + private static final Map q; + private static final String[] appearances; + + public static boolean a(int i, int j) { + return (i & 1 << j) != 0; + } + + private static int c(int i, int j) { + return a(i, j) ? 1 : 0; + } + + private static int d(int i, int j) { + return a(i, j) ? 0 : 1; + } + + public static int a(int i) { + return a(i, 5, 4, 3, 2, 1); + } + + public static int a(Collection collection) { + int i = 3694022; + + if (collection != null && !collection.isEmpty()) { + float f = 0.0F; + float f1 = 0.0F; + float f2 = 0.0F; + float f3 = 0.0F; + + for (MobEffect mobeffect : collection) { + if (mobeffect.isShowParticles()) { + int j = MobEffectList.byId[mobeffect.getEffectId()].k(); + + for (int k = 0; k <= mobeffect.getAmplifier(); ++k) { + f += (float) (j >> 16 & 255) / 255.0F; + f1 += (float) (j >> 8 & 255) / 255.0F; + f2 += (float) (j & 255) / 255.0F; + ++f3; + } + } + } + + if (f3 == 0.0F) { + return 0; + } else { + f = f / f3 * 255.0F; + f1 = f1 / f3 * 255.0F; + f2 = f2 / f3 * 255.0F; + return (int) f << 16 | (int) f1 << 8 | (int) f2; + } + } else { + return i; + } + } + + public static boolean b(Collection collection) { + Iterator iterator = collection.iterator(); + + MobEffect mobeffect; + + do { + if (!iterator.hasNext()) { + return true; + } + + mobeffect = (MobEffect) iterator.next(); + } while (mobeffect.isAmbient()); + + return false; + } + + public static String c(int i) { + int j = a(i); + + return PotionBrewer.appearances[j]; + } + + private static int a(boolean flag, boolean flag1, boolean flag2, int i, int j, int k, int l) { + int i1 = 0; + + if (flag) { + i1 = d(l, j); + } else if (i != -1) { + if (i == 0 && h(l) == j) { + i1 = 1; + } else if (i == 1 && h(l) > j) { + i1 = 1; + } else if (i == 2 && h(l) < j) { + i1 = 1; + } + } else { + i1 = c(l, j); + } + + if (flag1) { + i1 *= k; + } + + if (flag2) { + i1 *= -1; + } + + return i1; + } + + private static int h(int i) { + int j; + + for (j = 0; i > 0; ++j) { + i &= i - 1; + } + + return j; + } + + private static int a(String s, int i, int j, int k) { + if (i < s.length() && j >= 0 && i < j) { + int l = s.indexOf(124, i); + int i1; + int j1; + + if (l >= 0 && l < j) { + i1 = a(s, i, l - 1, k); + if (i1 > 0) { + return i1; + } else { + j1 = a(s, l + 1, j, k); + return j1 > 0 ? j1 : 0; + } + } else { + i1 = s.indexOf(38, i); + if (i1 >= 0 && i1 < j) { + j1 = a(s, i, i1 - 1, k); + if (j1 <= 0) { + return 0; + } else { + int k1 = a(s, i1 + 1, j, k); + + return k1 <= 0 ? 0 : (j1 > k1 ? j1 : k1); + } + } else { + boolean flag = false; + boolean flag1 = false; + boolean flag2 = false; + boolean flag3 = false; + boolean flag4 = false; + byte b0 = -1; + int l1 = 0; + int i2 = 0; + int j2 = 0; + + for (int k2 = i; k2 < j; ++k2) { + char c0 = s.charAt(k2); + + if (c0 >= 48 && c0 <= 57) { + if (flag) { + i2 = c0 - 48; + flag1 = true; + } else { + l1 *= 10; + l1 += c0 - 48; + flag2 = true; + } + } else if (c0 == 42) { + flag = true; + } else if (c0 == 33) { + if (flag2) { + j2 += a(flag3, flag1, flag4, b0, l1, i2, k); + flag3 = false; + flag4 = false; + flag = false; + flag1 = false; + flag2 = false; + i2 = 0; + l1 = 0; + b0 = -1; + } + + flag3 = true; + } else if (c0 == 45) { + if (flag2) { + j2 += a(flag3, flag1, flag4, b0, l1, i2, k); + flag3 = false; + flag4 = false; + flag = false; + flag1 = false; + flag2 = false; + i2 = 0; + l1 = 0; + b0 = -1; + } + + flag4 = true; + } else if (c0 != 61 && c0 != 60 && c0 != 62) { + if (c0 == 43 && flag2) { + j2 += a(flag3, flag1, flag4, b0, l1, i2, k); + flag3 = false; + flag4 = false; + flag = false; + flag1 = false; + flag2 = false; + i2 = 0; + l1 = 0; + b0 = -1; + } + } else { + if (flag2) { + j2 += a(flag3, flag1, flag4, b0, l1, i2, k); + flag3 = false; + flag4 = false; + flag = false; + flag1 = false; + flag2 = false; + i2 = 0; + l1 = 0; + b0 = -1; + } + + if (c0 == 61) { + b0 = 0; + } else if (c0 == 60) { + b0 = 2; + } else if (c0 == 62) { + b0 = 1; + } + } + } + + if (flag2) { + j2 += a(flag3, flag1, flag4, b0, l1, i2, k); + } + + return j2; + } + } + } else { + return 0; + } + } + + public static List getEffects(int i, boolean flag) { + ArrayList arraylist = null; + MobEffectList[] amobeffectlist = MobEffectList.byId; + int j = amobeffectlist.length; + + for (MobEffectList mobeffectlist : amobeffectlist) { + if (mobeffectlist != null && (!mobeffectlist.j() || flag)) { + String s = PotionBrewer.effectDurations.get(mobeffectlist.getId()); + + if (s != null) { + int l = a(s, 0, s.length(), i); + + if (l > 0) { + int i1 = 0; + String s1 = PotionBrewer.effectAmplifiers.get(mobeffectlist.getId()); + + if (s1 != null) { + i1 = a(s1, 0, s1.length(), i); + if (i1 < 0) { + i1 = 0; + } + } + + if (mobeffectlist.isInstant()) { + l = 1; + } else { + l = 1200 * (l * 3 + (l - 1) * 2); + l >>= i1; + l = (int) Math.round((double) l * mobeffectlist.getDurationModifier()); + if ((i & 16384) != 0) { + l = (int) Math.round((double) l * 0.75D + 0.5D); + } + } + + if (arraylist == null) { + arraylist = new ArrayList<>(); + } + + MobEffect mobeffect = new MobEffect(mobeffectlist.getId(), l, i1); + + if ((i & 16384) != 0) { + mobeffect.setSplash(true); + } + + arraylist.add(mobeffect); + } + } + } + } + + return arraylist; + } + + private static int a(int i, int j, boolean flag, boolean flag1, boolean flag2) { + if (flag2) { + if (!a(i, j)) { + return 0; + } + } else if (flag) { + i &= ~(1 << j); + } else if (flag1) { + if ((i & 1 << j) == 0) { + i |= 1 << j; + } else { + i &= ~(1 << j); + } + } else { + i |= 1 << j; + } + + return i; + } + + public static int a(int i, String s) { + byte b0 = 0; + int j = s.length(); + boolean flag = false; + boolean flag1 = false; + boolean flag2 = false; + boolean flag3 = false; + int k = 0; + + for (int l = b0; l < j; ++l) { + char c0 = s.charAt(l); + + if (c0 >= 48 && c0 <= 57) { + k *= 10; + k += c0 - 48; + flag = true; + } else if (c0 == 33) { + if (flag) { + i = a(i, k, flag2, flag1, flag3); + flag3 = false; + flag1 = false; + flag2 = false; + flag = false; + k = 0; + } + + flag1 = true; + } else if (c0 == 45) { + if (flag) { + i = a(i, k, flag2, flag1, flag3); + flag3 = false; + flag1 = false; + flag2 = false; + flag = false; + k = 0; + } + + flag2 = true; + } else if (c0 == 43) { + if (flag) { + i = a(i, k, flag2, flag1, flag3); + flag3 = false; + flag1 = false; + flag2 = false; + flag = false; + k = 0; + } + } else if (c0 == 38) { + if (flag) { + i = a(i, k, flag2, flag1, flag3); + flag3 = false; + flag1 = false; + flag2 = false; + flag = false; + k = 0; + } + + flag3 = true; + } + } + + if (flag) { + i = a(i, k, flag2, flag1, flag3); + } + + return i & 32767; + } + + public static int a(int i, int j, int k, int l, int i1, int j1) { + return (a(i, j) ? 16 : 0) | (a(i, k) ? 8 : 0) | (a(i, l) ? 4 : 0) | (a(i, i1) ? 2 : 0) | (a(i, j1) ? 1 : 0); + } + + static { + PotionBrewer.effectDurations.put(MobEffectList.REGENERATION.getId(), "0 & !1 & !2 & !3 & 0+6"); + b = "-0+1-2-3&4-4+13"; + PotionBrewer.effectDurations.put(MobEffectList.FASTER_MOVEMENT.getId(), "!0 & 1 & !2 & !3 & 1+6"); + h = "+0+1-2-3&4-4+13"; + PotionBrewer.effectDurations.put(MobEffectList.FIRE_RESISTANCE.getId(), "0 & 1 & !2 & !3 & 0+6"); + f = "+0-1+2-3&4-4+13"; + PotionBrewer.effectDurations.put(MobEffectList.HEAL.getId(), "0 & !1 & 2 & !3"); + d = "-0-1+2-3&4-4+13"; + PotionBrewer.effectDurations.put(MobEffectList.POISON.getId(), "!0 & !1 & 2 & !3 & 2+6"); + e = "-0+3-4+13"; + PotionBrewer.effectDurations.put(MobEffectList.WEAKNESS.getId(), "!0 & !1 & !2 & 3 & 3+6"); + PotionBrewer.effectDurations.put(MobEffectList.HARM.getId(), "!0 & !1 & 2 & 3"); + PotionBrewer.effectDurations.put(MobEffectList.SLOWER_MOVEMENT.getId(), "!0 & 1 & !2 & 3 & 3+6"); + g = "+0-1-2+3&4-4+13"; + PotionBrewer.effectDurations.put(MobEffectList.INCREASE_DAMAGE.getId(), "0 & !1 & !2 & 3 & 3+6"); + l = "-0+1+2-3+13&4-4"; + PotionBrewer.effectDurations.put(MobEffectList.NIGHT_VISION.getId(), "!0 & 1 & 2 & !3 & 2+6"); + PotionBrewer.effectDurations.put(MobEffectList.INVISIBILITY.getId(), "!0 & 1 & 2 & 3 & 2+6"); + m = "+0-1+2+3+13&4-4"; + PotionBrewer.effectDurations.put(MobEffectList.WATER_BREATHING.getId(), "0 & !1 & 2 & 3 & 2+6"); + n = "+0+1-2+3&4-4+13"; + PotionBrewer.effectDurations.put(MobEffectList.JUMP.getId(), "0 & 1 & !2 & 3 & 3+6"); + j = "+5-6-7"; + PotionBrewer.effectAmplifiers.put(MobEffectList.FASTER_MOVEMENT.getId(), "5"); + PotionBrewer.effectAmplifiers.put(MobEffectList.FASTER_DIG.getId(), "5"); + PotionBrewer.effectAmplifiers.put(MobEffectList.INCREASE_DAMAGE.getId(), "5"); + PotionBrewer.effectAmplifiers.put(MobEffectList.REGENERATION.getId(), "5"); + PotionBrewer.effectAmplifiers.put(MobEffectList.HARM.getId(), "5"); + PotionBrewer.effectAmplifiers.put(MobEffectList.HEAL.getId(), "5"); + PotionBrewer.effectAmplifiers.put(MobEffectList.RESISTANCE.getId(), "5"); + PotionBrewer.effectAmplifiers.put(MobEffectList.POISON.getId(), "5"); + PotionBrewer.effectAmplifiers.put(MobEffectList.JUMP.getId(), "5"); + i = "-5+6-7"; + k = "+14&13-13"; + q = new HashMap<>(); + appearances = new String[] { "potion.prefix.mundane", "potion.prefix.uninteresting", "potion.prefix.bland", "potion.prefix.clear", "potion.prefix.milky", "potion.prefix.diffuse", "potion.prefix.artless", "potion.prefix.thin", "potion.prefix.awkward", "potion.prefix.flat", "potion.prefix.bulky", "potion.prefix.bungling", "potion.prefix.buttered", "potion.prefix.smooth", "potion.prefix.suave", "potion.prefix.debonair", "potion.prefix.thick", "potion.prefix.elegant", "potion.prefix.fancy", "potion.prefix.charming", "potion.prefix.dashing", "potion.prefix.refined", "potion.prefix.cordial", "potion.prefix.sparkling", "potion.prefix.potent", "potion.prefix.foul", "potion.prefix.odorless", "potion.prefix.rank", "potion.prefix.harsh", "potion.prefix.acrid", "potion.prefix.gross", "potion.prefix.stinky"}; + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/net/minecraft/server/PropertyManager.java b/azurite-server/src/main/java/net/minecraft/server/PropertyManager.java new file mode 100644 index 0000000..2b61a2b --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/PropertyManager.java @@ -0,0 +1,133 @@ +package net.minecraft.server; + +import joptsimple.OptionSet; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.Properties; + +public class PropertyManager { + + private static final Logger a = LogManager.getLogger(); + public final Properties properties = new Properties(); + private final File file; + + public PropertyManager(File file) { + this.file = file; + if (file.exists()) { + + try (FileInputStream fileinputstream = new FileInputStream(file)) { + this.properties.load(fileinputstream); + } catch (Exception exception) { + PropertyManager.a.warn("Failed to load {}", file, exception); + this.a(); + } + } else { + PropertyManager.a.warn("{} does not exist", file); + this.a(); + } + + } + + // CraftBukkit start + private OptionSet options = null; + + public PropertyManager(final OptionSet options) { + this((File) options.valueOf("config")); + + this.options = options; + } + + private T getOverride(String name, T value) { + if ((this.options != null) && (this.options.has(name)) && !name.equals( "online-mode")) { // Spigot + return (T) this.options.valueOf(name); + } + + return value; + } + // CraftBukkit end + + public void a() { + PropertyManager.a.info("Generating new properties file"); + this.savePropertiesFile(); + } + + public void savePropertiesFile() { + FileOutputStream fileoutputstream = null; + + try { + // CraftBukkit start - Don't attempt writing to file if it's read only + if (this.file.exists() && !this.file.canWrite()) { + return; + } + // CraftBukkit end + + fileoutputstream = new FileOutputStream(this.file); + this.properties.store(fileoutputstream, "Minecraft server properties"); + } catch (Exception exception) { + PropertyManager.a.warn("Failed to save {}", this.file, exception); + this.a(); + } finally { + if (fileoutputstream != null) { + try { + fileoutputstream.close(); + } catch (IOException ignored) { + } + } + + } + + } + + public File c() { + return this.file; + } + + public String getString(String s, String s1) { + if (!this.properties.containsKey(s)) { + this.properties.setProperty(s, s1); + this.savePropertiesFile(); + this.savePropertiesFile(); + } + + return getOverride(s, this.properties.getProperty(s, s1)); // CraftBukkit + } + + public int getInt(String s, int i) { + try { + return getOverride(s, Integer.parseInt(this.getString(s, "" + i))); // CraftBukkit + } catch (Exception exception) { + this.properties.setProperty(s, "" + i); + this.savePropertiesFile(); + return getOverride(s, i); // CraftBukkit + } + } + + public long getLong(String s, long i) { + try { + return getOverride(s, Long.parseLong(this.getString(s, "" + i))); // CraftBukkit + } catch (Exception exception) { + this.properties.setProperty(s, "" + i); + this.savePropertiesFile(); + return getOverride(s, i); // CraftBukkit + } + } + + public boolean getBoolean(String s, boolean flag) { + try { + return getOverride(s, Boolean.parseBoolean(this.getString(s, "" + flag))); //CraftBukkit + } catch (Exception exception) { + this.properties.setProperty(s, "" + flag); + this.savePropertiesFile(); + return getOverride(s, flag); // CraftBukkit + } + } + + public void setProperty(String s, Object object) { + this.properties.setProperty(s, "" + object); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/RandomPositionGenerator.java b/azurite-server/src/main/java/net/minecraft/server/RandomPositionGenerator.java new file mode 100644 index 0000000..17fe75f --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/RandomPositionGenerator.java @@ -0,0 +1,88 @@ +package net.minecraft.server; + +import java.util.Random; + +public class RandomPositionGenerator { + + private static Vec3D a = new Vec3D(0.0D, 0.0D, 0.0D); + + public static Vec3D a(EntityCreature entitycreature, int i, int j) { + return c(entitycreature, i, j, (Vec3D) null); + } + + public static Vec3D a(EntityCreature entitycreature, int i, int j, Vec3D vec3d) { + RandomPositionGenerator.a = vec3d.a(entitycreature.locX, entitycreature.locY, entitycreature.locZ); + return c(entitycreature, i, j, RandomPositionGenerator.a); + } + + public static Vec3D b(EntityCreature entitycreature, int i, int j, Vec3D vec3d) { + RandomPositionGenerator.a = (new Vec3D(entitycreature.locX, entitycreature.locY, entitycreature.locZ)).d(vec3d); + return c(entitycreature, i, j, RandomPositionGenerator.a); + } + + private static Vec3D c(EntityCreature entitycreature, int i, int j, Vec3D vec3d) { + Random random = entitycreature.bc(); + boolean flag = false; + int k = 0; + int l = 0; + int i1 = 0; + float f = -99999.0F; + boolean flag1; + + if (entitycreature.ck()) { + double d0 = entitycreature.ch().c((double) MathHelper.floor(entitycreature.locX), (double) MathHelper.floor(entitycreature.locY), (double) MathHelper.floor(entitycreature.locZ)) + 4.0D; + double d1 = (double) (entitycreature.ci() + (float) i); + + flag1 = d0 < d1 * d1; + } else { + flag1 = false; + } + + for (int j1 = 0; j1 < 10; ++j1) { + int k1 = random.nextInt(2 * i + 1) - i; + int l1 = random.nextInt(2 * j + 1) - j; + int i2 = random.nextInt(2 * i + 1) - i; + + if (vec3d == null || (double) k1 * vec3d.a + (double) i2 * vec3d.c >= 0.0D) { + BlockPosition blockposition; + + if (entitycreature.ck() && i > 1) { + blockposition = entitycreature.ch(); + if (entitycreature.locX > (double) blockposition.getX()) { + k1 -= random.nextInt(i / 2); + } else { + k1 += random.nextInt(i / 2); + } + + if (entitycreature.locZ > (double) blockposition.getZ()) { + i2 -= random.nextInt(i / 2); + } else { + i2 += random.nextInt(i / 2); + } + } + + k1 += MathHelper.floor(entitycreature.locX); + l1 += MathHelper.floor(entitycreature.locY); + i2 += MathHelper.floor(entitycreature.locZ); + blockposition = new BlockPosition(k1, l1, i2); + if (!flag1 || entitycreature.e(blockposition)) { + float f1 = entitycreature.a(blockposition); + + if (f1 > f) { + f = f1; + k = k1; + l = l1; + i1 = i2; + flag = true; + } + } + } + } + + if (flag) { + return new Vec3D((double) k, (double) l, (double) i1); + } else { + return null; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/RecipeArmorDye.java b/azurite-server/src/main/java/net/minecraft/server/RecipeArmorDye.java new file mode 100644 index 0000000..ce7afaa --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/RecipeArmorDye.java @@ -0,0 +1,141 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; + +import java.util.ArrayList; +import java.util.Collections; + +public class RecipeArmorDye extends ShapelessRecipes implements IRecipe { // CraftBukkit - added extends + + // CraftBukkit start - Delegate to new parent class with bogus info + public RecipeArmorDye() { + super(new ItemStack(Items.LEATHER_HELMET, 0, 0), Collections.singletonList(new ItemStack(Items.DYE, 0, 5))); + } + // CraftBukkit end + + public boolean a(InventoryCrafting inventorycrafting, World world) { + ItemStack itemstack = null; + ArrayList arraylist = Lists.newArrayList(); + + for (int i = 0; i < inventorycrafting.getSize(); ++i) { + ItemStack itemstack1 = inventorycrafting.getItem(i); + + if (itemstack1 != null) { + if (itemstack1.getItem() instanceof ItemArmor) { + ItemArmor itemarmor = (ItemArmor) itemstack1.getItem(); + + if (itemarmor.x_() != ItemArmor.EnumArmorMaterial.LEATHER || itemstack != null) { + return false; + } + + itemstack = itemstack1; + } else { + if (itemstack1.getItem() != Items.DYE) { + return false; + } + + arraylist.add(itemstack1); + } + } + } + + return itemstack != null && !arraylist.isEmpty(); + } + + public ItemStack craftItem(InventoryCrafting inventorycrafting) { + ItemStack itemstack = null; + int[] aint = new int[3]; + int i = 0; + int j = 0; + ItemArmor itemarmor = null; + + int k; + int l; + float f; + float f1; + int i1; + + for (k = 0; k < inventorycrafting.getSize(); ++k) { + ItemStack itemstack1 = inventorycrafting.getItem(k); + + if (itemstack1 != null) { + if (itemstack1.getItem() instanceof ItemArmor) { + itemarmor = (ItemArmor) itemstack1.getItem(); + if (itemarmor.x_() != ItemArmor.EnumArmorMaterial.LEATHER || itemstack != null) { + return null; + } + + itemstack = itemstack1.cloneItemStack(); + itemstack.count = 1; + if (itemarmor.d_(itemstack1)) { + l = itemarmor.b(itemstack); + f = (float) (l >> 16 & 255) / 255.0F; + f1 = (float) (l >> 8 & 255) / 255.0F; + float f2 = (float) (l & 255) / 255.0F; + + i = (int) ((float) i + Math.max(f, Math.max(f1, f2)) * 255.0F); + aint[0] = (int) ((float) aint[0] + f * 255.0F); + aint[1] = (int) ((float) aint[1] + f1 * 255.0F); + aint[2] = (int) ((float) aint[2] + f2 * 255.0F); + ++j; + } + } else { + if (itemstack1.getItem() != Items.DYE) { + return null; + } + + float[] afloat = EntitySheep.a(EnumColor.fromInvColorIndex(itemstack1.getData())); + int j1 = (int) (afloat[0] * 255.0F); + int k1 = (int) (afloat[1] * 255.0F); + + i1 = (int) (afloat[2] * 255.0F); + i += Math.max(j1, Math.max(k1, i1)); + aint[0] += j1; + aint[1] += k1; + aint[2] += i1; + ++j; + } + } + } + + if (itemarmor == null) { + return null; + } else { + k = aint[0] / j; + int l1 = aint[1] / j; + + l = aint[2] / j; + f = (float) i / (float) j; + f1 = (float) Math.max(k, Math.max(l1, l)); + k = (int) ((float) k * f / f1); + l1 = (int) ((float) l1 * f / f1); + l = (int) ((float) l * f / f1); + i1 = (k << 8) + l1; + i1 = (i1 << 8) + l; + itemarmor.b(itemstack, i1); + return itemstack; + } + } + + public int a() { + return 10; + } + + public ItemStack b() { + return null; + } + + public ItemStack[] b(InventoryCrafting inventorycrafting) { + ItemStack[] aitemstack = new ItemStack[inventorycrafting.getSize()]; + + for (int i = 0; i < aitemstack.length; ++i) { + ItemStack itemstack = inventorycrafting.getItem(i); + + if (itemstack != null && itemstack.getItem().r()) { + aitemstack[i] = new ItemStack(itemstack.getItem().q()); + } + } + + return aitemstack; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/RecipeBookClone.java b/azurite-server/src/main/java/net/minecraft/server/RecipeBookClone.java new file mode 100644 index 0000000..5dd69ff --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/RecipeBookClone.java @@ -0,0 +1,101 @@ +package net.minecraft.server; + +import java.util.Collections; + +public class RecipeBookClone extends ShapelessRecipes implements IRecipe { // CraftBukkit - added extends + + // CraftBukkit start - Delegate to new parent class + public RecipeBookClone() { + super(new ItemStack(Items.WRITTEN_BOOK, 0, -1), Collections.singletonList(new ItemStack(Items.WRITABLE_BOOK, 0, 0))); + } + // CraftBukkit end + + public boolean a(InventoryCrafting inventorycrafting, World world) { + int i = 0; + ItemStack itemstack = null; + + for (int j = 0; j < inventorycrafting.getSize(); ++j) { + ItemStack itemstack1 = inventorycrafting.getItem(j); + + if (itemstack1 != null) { + if (itemstack1.getItem() == Items.WRITTEN_BOOK) { + if (itemstack != null) { + return false; + } + + itemstack = itemstack1; + } else { + if (itemstack1.getItem() != Items.WRITABLE_BOOK) { + return false; + } + + ++i; + } + } + } + + return itemstack != null && i > 0; + } + + public ItemStack craftItem(InventoryCrafting inventorycrafting) { + int i = 0; + ItemStack itemstack = null; + + for (int j = 0; j < inventorycrafting.getSize(); ++j) { + ItemStack itemstack1 = inventorycrafting.getItem(j); + + if (itemstack1 != null) { + if (itemstack1.getItem() == Items.WRITTEN_BOOK) { + if (itemstack != null) { + return null; + } + + itemstack = itemstack1; + } else { + if (itemstack1.getItem() != Items.WRITABLE_BOOK) { + return null; + } + + ++i; + } + } + } + + if (itemstack != null && i >= 1 && ItemWrittenBook.h(itemstack) < 2) { + ItemStack itemstack2 = new ItemStack(Items.WRITTEN_BOOK, i); + + itemstack2.setTag((NBTTagCompound) itemstack.getTag().clone()); + itemstack2.getTag().setInt("generation", ItemWrittenBook.h(itemstack) + 1); + if (itemstack.hasName()) { + itemstack2.c(itemstack.getName()); + } + + return itemstack2; + } else { + return null; + } + } + + public int a() { + return 9; + } + + public ItemStack b() { + return null; + } + + public ItemStack[] b(InventoryCrafting inventorycrafting) { + ItemStack[] aitemstack = new ItemStack[inventorycrafting.getSize()]; + + for (int i = 0; i < aitemstack.length; ++i) { + ItemStack itemstack = inventorycrafting.getItem(i); + + if (itemstack != null && itemstack.getItem() instanceof ItemWrittenBook) { + aitemstack[i] = itemstack; + break; + } + } + + return aitemstack; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/RecipeFireworks.java b/azurite-server/src/main/java/net/minecraft/server/RecipeFireworks.java new file mode 100644 index 0000000..36c2c67 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/RecipeFireworks.java @@ -0,0 +1,193 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; + +import java.util.ArrayList; +import java.util.Collections; + +public class RecipeFireworks extends ShapelessRecipes implements IRecipe { // CraftBukkit - added extends + + private ItemStack a; + + // CraftBukkit start - Delegate to new parent class with bogus info + public RecipeFireworks() { + super(new ItemStack(Items.FIREWORKS, 0, 0), Collections.singletonList(new ItemStack(Items.GUNPOWDER, 0, 5))); + } + // CraftBukkit end + + public boolean a(InventoryCrafting inventorycrafting, World world) { + this.a = null; + int i = 0; + int j = 0; + int k = 0; + int l = 0; + int i1 = 0; + int j1 = 0; + + for (int k1 = 0; k1 < inventorycrafting.getSize(); ++k1) { + ItemStack itemstack = inventorycrafting.getItem(k1); + + if (itemstack != null) { + if (itemstack.getItem() == Items.GUNPOWDER) { + ++j; + } else if (itemstack.getItem() == Items.FIREWORK_CHARGE) { + ++l; + } else if (itemstack.getItem() == Items.DYE) { + ++k; + } else if (itemstack.getItem() == Items.PAPER) { + ++i; + } else if (itemstack.getItem() == Items.GLOWSTONE_DUST) { + ++i1; + } else if (itemstack.getItem() == Items.DIAMOND) { + ++i1; + } else if (itemstack.getItem() == Items.FIRE_CHARGE) { + ++j1; + } else if (itemstack.getItem() == Items.FEATHER) { + ++j1; + } else if (itemstack.getItem() == Items.GOLD_NUGGET) { + ++j1; + } else { + if (itemstack.getItem() != Items.SKULL) { + return false; + } + + ++j1; + } + } + } + + i1 += k + j1; + if (j <= 3 && i <= 1) { + NBTTagCompound nbttagcompound; + NBTTagCompound nbttagcompound1; + + if (j >= 1 && i == 1 && i1 == 0) { + this.a = new ItemStack(Items.FIREWORKS); + if (l > 0) { + nbttagcompound = new NBTTagCompound(); + nbttagcompound1 = new NBTTagCompound(); + NBTTagList nbttaglist = new NBTTagList(); + + for (int l1 = 0; l1 < inventorycrafting.getSize(); ++l1) { + ItemStack itemstack1 = inventorycrafting.getItem(l1); + + if (itemstack1 != null && itemstack1.getItem() == Items.FIREWORK_CHARGE && itemstack1.hasTag() && itemstack1.getTag().hasKeyOfType("Explosion", 10)) { + nbttaglist.add(itemstack1.getTag().getCompound("Explosion")); + } + } + + nbttagcompound1.set("Explosions", nbttaglist); + nbttagcompound1.setByte("Flight", (byte) j); + nbttagcompound.set("Fireworks", nbttagcompound1); + this.a.setTag(nbttagcompound); + } + + return true; + } else if (j == 1 && i == 0 && l == 0 && k > 0 && j1 <= 1) { + this.a = new ItemStack(Items.FIREWORK_CHARGE); + nbttagcompound = new NBTTagCompound(); + nbttagcompound1 = new NBTTagCompound(); + byte b0 = 0; + ArrayList arraylist = Lists.newArrayList(); + + for (int i2 = 0; i2 < inventorycrafting.getSize(); ++i2) { + ItemStack itemstack2 = inventorycrafting.getItem(i2); + + if (itemstack2 != null) { + if (itemstack2.getItem() == Items.DYE) { + arraylist.add(ItemDye.a[itemstack2.getData() & 15]); + } else if (itemstack2.getItem() == Items.GLOWSTONE_DUST) { + nbttagcompound1.setBoolean("Flicker", true); + } else if (itemstack2.getItem() == Items.DIAMOND) { + nbttagcompound1.setBoolean("Trail", true); + } else if (itemstack2.getItem() == Items.FIRE_CHARGE) { + b0 = 1; + } else if (itemstack2.getItem() == Items.FEATHER) { + b0 = 4; + } else if (itemstack2.getItem() == Items.GOLD_NUGGET) { + b0 = 2; + } else if (itemstack2.getItem() == Items.SKULL) { + b0 = 3; + } + } + } + + int[] aint = new int[arraylist.size()]; + + for (int j2 = 0; j2 < aint.length; ++j2) { + aint[j2] = arraylist.get(j2); + } + + nbttagcompound1.setIntArray("Colors", aint); + nbttagcompound1.setByte("Type", b0); + nbttagcompound.set("Explosion", nbttagcompound1); + this.a.setTag(nbttagcompound); + return true; + } else if (j == 0 && i == 0 && l == 1 && k > 0 && k == i1) { + ArrayList arraylist1 = Lists.newArrayList(); + + for (int k2 = 0; k2 < inventorycrafting.getSize(); ++k2) { + ItemStack itemstack3 = inventorycrafting.getItem(k2); + + if (itemstack3 != null) { + if (itemstack3.getItem() == Items.DYE) { + arraylist1.add(ItemDye.a[itemstack3.getData() & 15]); + } else if (itemstack3.getItem() == Items.FIREWORK_CHARGE) { + this.a = itemstack3.cloneItemStack(); + this.a.count = 1; + } + } + } + + int[] aint1 = new int[arraylist1.size()]; + + for (int l2 = 0; l2 < aint1.length; ++l2) { + aint1[l2] = arraylist1.get(l2); + } + + if (this.a != null && this.a.hasTag()) { + NBTTagCompound nbttagcompound2 = this.a.getTag().getCompound("Explosion"); + + if (nbttagcompound2 == null) { + return false; + } else { + nbttagcompound2.setIntArray("FadeColors", aint1); + return true; + } + } else { + return false; + } + } else { + return false; + } + } else { + return false; + } + } + + public ItemStack craftItem(InventoryCrafting inventorycrafting) { + return this.a.cloneItemStack(); + } + + public int a() { + return 10; + } + + public ItemStack b() { + return this.a; + } + + public ItemStack[] b(InventoryCrafting inventorycrafting) { + ItemStack[] aitemstack = new ItemStack[inventorycrafting.getSize()]; + + for (int i = 0; i < aitemstack.length; ++i) { + ItemStack itemstack = inventorycrafting.getItem(i); + + if (itemstack != null && itemstack.getItem().r()) { + aitemstack[i] = new ItemStack(itemstack.getItem().q()); + } + } + + return aitemstack; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/RecipeIngots.java b/azurite-server/src/main/java/net/minecraft/server/RecipeIngots.java new file mode 100644 index 0000000..01c8bfd --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/RecipeIngots.java @@ -0,0 +1,23 @@ +package net.minecraft.server; + +public class RecipeIngots { + + private Object[][] a; + + public RecipeIngots() { + this.a = new Object[][] { { Blocks.GOLD_BLOCK, new ItemStack(Items.GOLD_INGOT, 9)}, { Blocks.IRON_BLOCK, new ItemStack(Items.IRON_INGOT, 9)}, { Blocks.DIAMOND_BLOCK, new ItemStack(Items.DIAMOND, 9)}, { Blocks.EMERALD_BLOCK, new ItemStack(Items.EMERALD, 9)}, { Blocks.LAPIS_BLOCK, new ItemStack(Items.DYE, 9, EnumColor.BLUE.getInvColorIndex())}, { Blocks.REDSTONE_BLOCK, new ItemStack(Items.REDSTONE, 9)}, { Blocks.COAL_BLOCK, new ItemStack(Items.COAL, 9, 0)}, { Blocks.HAY_BLOCK, new ItemStack(Items.WHEAT, 9)}, { Blocks.SLIME, new ItemStack(Items.SLIME, 9)}}; + } + + public void a(CraftingManager craftingmanager) { + for (int i = 0; i < this.a.length; ++i) { + Block block = (Block) this.a[i][0]; + ItemStack itemstack = (ItemStack) this.a[i][1]; + + craftingmanager.registerShapedRecipe(new ItemStack(block), new Object[] { "###", "###", "###", Character.valueOf('#'), itemstack}); + craftingmanager.registerShapedRecipe(itemstack, new Object[] { "#", Character.valueOf('#'), block}); + } + + craftingmanager.registerShapedRecipe(new ItemStack(Items.GOLD_INGOT), new Object[] { "###", "###", "###", Character.valueOf('#'), Items.GOLD_NUGGET}); + craftingmanager.registerShapedRecipe(new ItemStack(Items.GOLD_NUGGET, 9), new Object[] { "#", Character.valueOf('#'), Items.GOLD_INGOT}); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/RecipeMapClone.java b/azurite-server/src/main/java/net/minecraft/server/RecipeMapClone.java new file mode 100644 index 0000000..579f6d1 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/RecipeMapClone.java @@ -0,0 +1,96 @@ +package net.minecraft.server; + +public class RecipeMapClone extends ShapelessRecipes implements IRecipe { // CraftBukkit - added extends + + // CraftBukkit start - Delegate to new parent class + public RecipeMapClone() { + super(new ItemStack(Items.MAP, 0, -1), java.util.Arrays.asList(new ItemStack(Items.MAP, 0, 0))); + } + // CraftBukkit end + + public boolean a(InventoryCrafting inventorycrafting, World world) { + int i = 0; + ItemStack itemstack = null; + + for (int j = 0; j < inventorycrafting.getSize(); ++j) { + ItemStack itemstack1 = inventorycrafting.getItem(j); + + if (itemstack1 != null) { + if (itemstack1.getItem() == Items.FILLED_MAP) { + if (itemstack != null) { + return false; + } + + itemstack = itemstack1; + } else { + if (itemstack1.getItem() != Items.MAP) { + return false; + } + + ++i; + } + } + } + + return itemstack != null && i > 0; + } + + public ItemStack craftItem(InventoryCrafting inventorycrafting) { + int i = 0; + ItemStack itemstack = null; + + for (int j = 0; j < inventorycrafting.getSize(); ++j) { + ItemStack itemstack1 = inventorycrafting.getItem(j); + + if (itemstack1 != null) { + if (itemstack1.getItem() == Items.FILLED_MAP) { + if (itemstack != null) { + return null; + } + + itemstack = itemstack1; + } else { + if (itemstack1.getItem() != Items.MAP) { + return null; + } + + ++i; + } + } + } + + if (itemstack != null && i >= 1) { + ItemStack itemstack2 = new ItemStack(Items.FILLED_MAP, i + 1, itemstack.getData()); + + if (itemstack.hasName()) { + itemstack2.c(itemstack.getName()); + } + + return itemstack2; + } else { + return null; + } + } + + public int a() { + return 9; + } + + public ItemStack b() { + return null; + } + + public ItemStack[] b(InventoryCrafting inventorycrafting) { + ItemStack[] aitemstack = new ItemStack[inventorycrafting.getSize()]; + + for (int i = 0; i < aitemstack.length; ++i) { + ItemStack itemstack = inventorycrafting.getItem(i); + + if (itemstack != null && itemstack.getItem().r()) { + aitemstack[i] = new ItemStack(itemstack.getItem().q()); + } + } + + return aitemstack; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/RecipeMapExtend.java b/azurite-server/src/main/java/net/minecraft/server/RecipeMapExtend.java new file mode 100644 index 0000000..accac7a --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/RecipeMapExtend.java @@ -0,0 +1,53 @@ +package net.minecraft.server; + +public class RecipeMapExtend extends ShapedRecipes { + + public RecipeMapExtend() { + super(3, 3, new ItemStack[] { new ItemStack(Items.PAPER), new ItemStack(Items.PAPER), new ItemStack(Items.PAPER), new ItemStack(Items.PAPER), new ItemStack(Items.FILLED_MAP, 0, 32767), new ItemStack(Items.PAPER), new ItemStack(Items.PAPER), new ItemStack(Items.PAPER), new ItemStack(Items.PAPER)}, new ItemStack(Items.MAP, 0, 0)); + } + + public boolean a(InventoryCrafting inventorycrafting, World world) { + if (!super.a(inventorycrafting, world)) { + return false; + } else { + ItemStack itemstack = null; + + for (int i = 0; i < inventorycrafting.getSize() && itemstack == null; ++i) { + ItemStack itemstack1 = inventorycrafting.getItem(i); + + if (itemstack1 != null && itemstack1.getItem() == Items.FILLED_MAP) { + itemstack = itemstack1; + } + } + + if (itemstack == null) { + return false; + } else { + WorldMap worldmap = Items.FILLED_MAP.getSavedMap(itemstack, world); + + return worldmap == null ? false : worldmap.scale < 4; + } + } + } + + public ItemStack craftItem(InventoryCrafting inventorycrafting) { + ItemStack itemstack = null; + + for (int i = 0; i < inventorycrafting.getSize() && itemstack == null; ++i) { + ItemStack itemstack1 = inventorycrafting.getItem(i); + + if (itemstack1 != null && itemstack1.getItem() == Items.FILLED_MAP) { + itemstack = itemstack1; + } + } + + itemstack = itemstack.cloneItemStack(); + itemstack.count = 1; + if (itemstack.getTag() == null) { + itemstack.setTag(new NBTTagCompound()); + } + + itemstack.getTag().setBoolean("map_is_scaling", true); + return itemstack; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/RecipeRepair.java b/azurite-server/src/main/java/net/minecraft/server/RecipeRepair.java new file mode 100644 index 0000000..5c5ba33 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/RecipeRepair.java @@ -0,0 +1,127 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; +import dev.azurite.spigot.configs.AzuriteConfig; + +import java.util.ArrayList; +import java.util.Collections; + +public class RecipeRepair extends ShapelessRecipes implements IRecipe { // CraftBukkit - added extends + + // CraftBukkit start - Delegate to new parent class + public RecipeRepair() { + super(new ItemStack(Items.LEATHER_HELMET), Collections.singletonList(new ItemStack(Items.LEATHER_HELMET))); + } + // CraftBukkit end + + public boolean a(InventoryCrafting inventorycrafting, World world) { + ArrayList arraylist = Lists.newArrayList(); + + for (int i = 0; i < inventorycrafting.getSize(); ++i) { + ItemStack itemstack = inventorycrafting.getItem(i); + + if (itemstack != null) { + arraylist.add(itemstack); + if (arraylist.size() > 1) { + ItemStack itemstack1 = arraylist.get(0); + + if (itemstack.getItem() != itemstack1.getItem() || itemstack1.count != 1 || itemstack.count != 1 || !itemstack1.getItem().usesDurability()) { + return false; + } + } + } + } + + return arraylist.size() == 2; + } + + public ItemStack craftItem(InventoryCrafting inventorycrafting) { + ArrayList arraylist = Lists.newArrayList(); + + ItemStack itemstack; + + for (int i = 0; i < inventorycrafting.getSize(); ++i) { + itemstack = inventorycrafting.getItem(i); + if (itemstack != null) { + arraylist.add(itemstack); + if (arraylist.size() > 1) { + ItemStack itemstack1 = arraylist.get(0); + + if (itemstack.getItem() != itemstack1.getItem() || itemstack1.count != 1 || itemstack.count != 1 || !itemstack1.getItem().usesDurability()) { + return null; + } + } + } + } + + if (arraylist.size() == 2) { + ItemStack itemstack2 = arraylist.get(0); + + itemstack = arraylist.get(1); + if (itemstack2.getItem() == itemstack.getItem() && itemstack2.count == 1 && itemstack.count == 1 && itemstack2.getItem().usesDurability()) { + Item item = itemstack2.getItem(); + // Rivals start - Alternative repair logic + int resultValue; + if (AzuriteConfig.alternativeRepair.getValue()) { + int j = item.getMaxDurability() - itemstack2.h(); // durability left + int k = item.getMaxDurability() - itemstack.h(); // durability left + int l = j + k; // total durability combined, no bonus + + if (l > item.getMaxDurability()) { + l = item.getMaxDurability(); // cap at max durability + } + + // new damage value + resultValue = item.getMaxDurability() - l; + } else { + int j = item.getMaxDurability() - itemstack2.h(); + int k = item.getMaxDurability() - itemstack.h(); + int l = j + k + item.getMaxDurability() * 5 / 100; + int i1 = item.getMaxDurability() - l; + + if (i1 < 0) { + i1 = 0; + } + + resultValue = i1; + } + // Rivals end + + // CraftBukkit start - Construct a dummy repair recipe + ItemStack result = new ItemStack(itemstack.getItem(), 1, resultValue); + java.util.List ingredients = new ArrayList<>(); + ingredients.add(itemstack2.cloneItemStack()); + ingredients.add(itemstack.cloneItemStack()); + inventorycrafting.currentRecipe = new ShapelessRecipes(result.cloneItemStack(), ingredients); + result = org.bukkit.craftbukkit.event.CraftEventFactory.callPreCraftEvent(inventorycrafting, result, CraftingManager.getInstance().lastCraftView, true); + return result; + // return new ItemStack(itemstack2.getItem(), 1, i1); + // CraftBukkit end + } + } + + return null; + } + + public int a() { + return 4; + } + + public ItemStack b() { + return null; + } + + public ItemStack[] b(InventoryCrafting inventorycrafting) { + ItemStack[] aitemstack = new ItemStack[inventorycrafting.getSize()]; + + for (int i = 0; i < aitemstack.length; ++i) { + ItemStack itemstack = inventorycrafting.getItem(i); + + if (itemstack != null && itemstack.getItem().r()) { + aitemstack[i] = new ItemStack(itemstack.getItem().q()); + } + } + + return aitemstack; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/RecipesArmor.java b/azurite-server/src/main/java/net/minecraft/server/RecipesArmor.java new file mode 100644 index 0000000..e922f16 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/RecipesArmor.java @@ -0,0 +1,24 @@ +package net.minecraft.server; + +public class RecipesArmor { + + private String[][] a = new String[][] { { "XXX", "X X"}, { "X X", "XXX", "XXX"}, { "XXX", "X X", "X X"}, { "X X", "X X"}}; + private Item[][] b; + + public RecipesArmor() { + this.b = new Item[][] { { Items.LEATHER, Items.IRON_INGOT, Items.DIAMOND, Items.GOLD_INGOT}, { Items.LEATHER_HELMET, Items.IRON_HELMET, Items.DIAMOND_HELMET, Items.GOLDEN_HELMET}, { Items.LEATHER_CHESTPLATE, Items.IRON_CHESTPLATE, Items.DIAMOND_CHESTPLATE, Items.GOLDEN_CHESTPLATE}, { Items.LEATHER_LEGGINGS, Items.IRON_LEGGINGS, Items.DIAMOND_LEGGINGS, Items.GOLDEN_LEGGINGS}, { Items.LEATHER_BOOTS, Items.IRON_BOOTS, Items.DIAMOND_BOOTS, Items.GOLDEN_BOOTS}}; + } + + public void a(CraftingManager craftingmanager) { + for (int i = 0; i < this.b[0].length; ++i) { + Item item = this.b[0][i]; + + for (int j = 0; j < this.b.length - 1; ++j) { + Item item1 = this.b[j + 1][i]; + + craftingmanager.registerShapedRecipe(new ItemStack(item1), new Object[] { this.a[j], Character.valueOf('X'), item}); + } + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/RecipesBanner.java b/azurite-server/src/main/java/net/minecraft/server/RecipesBanner.java new file mode 100644 index 0000000..28c0a27 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/RecipesBanner.java @@ -0,0 +1,314 @@ +package net.minecraft.server; + +import java.util.Collections; + +public class RecipesBanner { + + public RecipesBanner() {} + + void a(CraftingManager craftingmanager) { + + for (EnumColor enumcolor : EnumColor.values()) { + craftingmanager.registerShapedRecipe(new ItemStack(Items.BANNER, 1, enumcolor.getInvColorIndex()), "###", "###", " | ", '#', new ItemStack(Blocks.WOOL, 1, enumcolor.getColorIndex()), '|', Items.STICK); + } + + craftingmanager.a(new RecipesBanner.DuplicateRecipe(null)); + craftingmanager.a(new RecipesBanner.AddRecipe(null)); + } + + static class SyntheticClass_1 { } + + static class AddRecipe extends ShapelessRecipes implements IRecipe { // CraftBukkit - added extends + + // CraftBukkit start - Delegate to new parent class with bogus info + private AddRecipe() { + super(new ItemStack(Items.BANNER, 0, 0), Collections.singletonList(new ItemStack(Items.BANNER))); + } + // CraftBukkit end + + public boolean a(InventoryCrafting inventorycrafting, World world) { + boolean flag = false; + + for (int i = 0; i < inventorycrafting.getSize(); ++i) { + ItemStack itemstack = inventorycrafting.getItem(i); + + if (itemstack != null && itemstack.getItem() == Items.BANNER) { + if (flag) { + return false; + } + + if (TileEntityBanner.c(itemstack) >= 6) { + return false; + } + + flag = true; + } + } + + if (!flag) { + return false; + } else { + return this.c(inventorycrafting) != null; + } + } + + public ItemStack craftItem(InventoryCrafting inventorycrafting) { + ItemStack itemstack = null; + + for (int i = 0; i < inventorycrafting.getSize(); ++i) { + ItemStack itemstack1 = inventorycrafting.getItem(i); + + if (itemstack1 != null && itemstack1.getItem() == Items.BANNER) { + itemstack = itemstack1.cloneItemStack(); + itemstack.count = 1; + break; + } + } + + TileEntityBanner.EnumBannerPatternType tileentitybanner_enumbannerpatterntype = this.c(inventorycrafting); + + if (tileentitybanner_enumbannerpatterntype != null) { + int j = 0; + + ItemStack itemstack2; + + for (int k = 0; k < inventorycrafting.getSize(); ++k) { + itemstack2 = inventorycrafting.getItem(k); + if (itemstack2 != null && itemstack2.getItem() == Items.DYE) { + j = itemstack2.getData(); + break; + } + } + + NBTTagCompound nbttagcompound = itemstack.a("BlockEntityTag", true); + + NBTTagList nbttaglist; + + if (nbttagcompound.hasKeyOfType("Patterns", 9)) { + nbttaglist = nbttagcompound.getList("Patterns", 10); + } else { + nbttaglist = new NBTTagList(); + nbttagcompound.set("Patterns", nbttaglist); + } + + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + + nbttagcompound1.setString("Pattern", tileentitybanner_enumbannerpatterntype.b()); + nbttagcompound1.setInt("Color", j); + nbttaglist.add(nbttagcompound1); + } + + return itemstack; + } + + public int a() { + return 10; + } + + public ItemStack b() { + return null; + } + + public ItemStack[] b(InventoryCrafting inventorycrafting) { + ItemStack[] aitemstack = new ItemStack[inventorycrafting.getSize()]; + + for (int i = 0; i < aitemstack.length; ++i) { + ItemStack itemstack = inventorycrafting.getItem(i); + + if (itemstack != null && itemstack.getItem().r()) { + aitemstack[i] = new ItemStack(itemstack.getItem().q()); + } + } + + return aitemstack; + } + + private TileEntityBanner.EnumBannerPatternType c(InventoryCrafting inventorycrafting) { + + for (TileEntityBanner.EnumBannerPatternType tileentitybanner_enumbannerpatterntype : TileEntityBanner.EnumBannerPatternType.values()) { + if (tileentitybanner_enumbannerpatterntype.d()) { + boolean flag = true; + int k; + + if (tileentitybanner_enumbannerpatterntype.e()) { + boolean flag1 = false; + boolean flag2 = false; + + for (k = 0; k < inventorycrafting.getSize(); ++k) { + ItemStack itemstack = inventorycrafting.getItem(k); + + if (itemstack != null && itemstack.getItem() != Items.BANNER) { + if (itemstack.getItem() == Items.DYE) { + if (flag2) { + flag = false; + break; + } + + flag2 = true; + } else { + if (flag1 || !itemstack.doMaterialsMatch(tileentitybanner_enumbannerpatterntype.f())) { + flag = false; + break; + } + + flag1 = true; + } + } + } + + if (!flag1) { + flag = false; + } + } else if (inventorycrafting.getSize() != tileentitybanner_enumbannerpatterntype.c().length * tileentitybanner_enumbannerpatterntype.c()[0].length()) { + flag = false; + } else { + int l = -1; + + for (int i1 = 0; i1 < inventorycrafting.getSize(); ++i1) { + k = i1 / 3; + int j1 = i1 % 3; + ItemStack itemstack1 = inventorycrafting.getItem(i1); + + if (itemstack1 != null && itemstack1.getItem() != Items.BANNER) { + if (itemstack1.getItem() != Items.DYE) { + flag = false; + break; + } + + if (l != -1 && l != itemstack1.getData()) { + flag = false; + break; + } + + if (tileentitybanner_enumbannerpatterntype.c()[k].charAt(j1) == 32) { + flag = false; + break; + } + + l = itemstack1.getData(); + } else if (tileentitybanner_enumbannerpatterntype.c()[k].charAt(j1) != 32) { + flag = false; + break; + } + } + } + + if (flag) { + return tileentitybanner_enumbannerpatterntype; + } + } + } + + return null; + } + + AddRecipe(RecipesBanner.SyntheticClass_1 recipesbanner_syntheticclass_1) { + this(); + } + } + + static class DuplicateRecipe extends ShapelessRecipes implements IRecipe { // CraftBukkit - added extends + + // CraftBukkit start - Delegate to new parent class with bogus info + private DuplicateRecipe() { + super(new ItemStack(Items.BANNER, 0, 0), java.util.Arrays.asList(new ItemStack(Items.DYE, 0, 5))); + } + // CraftBukkit end + + public boolean a(InventoryCrafting inventorycrafting, World world) { + ItemStack itemstack = null; + ItemStack itemstack1 = null; + + for (int i = 0; i < inventorycrafting.getSize(); ++i) { + ItemStack itemstack2 = inventorycrafting.getItem(i); + + if (itemstack2 != null) { + if (itemstack2.getItem() != Items.BANNER) { + return false; + } + + if (itemstack != null && itemstack1 != null) { + return false; + } + + int j = TileEntityBanner.b(itemstack2); + boolean flag = TileEntityBanner.c(itemstack2) > 0; + + if (itemstack != null) { + if (flag) { + return false; + } + + if (j != TileEntityBanner.b(itemstack)) { + return false; + } + + itemstack1 = itemstack2; + } else if (itemstack1 != null) { + if (!flag) { + return false; + } + + if (j != TileEntityBanner.b(itemstack1)) { + return false; + } + + itemstack = itemstack2; + } else if (flag) { + itemstack = itemstack2; + } else { + itemstack1 = itemstack2; + } + } + } + + return itemstack != null && itemstack1 != null; + } + + public ItemStack craftItem(InventoryCrafting inventorycrafting) { + for (int i = 0; i < inventorycrafting.getSize(); ++i) { + ItemStack itemstack = inventorycrafting.getItem(i); + + if (itemstack != null && TileEntityBanner.c(itemstack) > 0) { + ItemStack itemstack1 = itemstack.cloneItemStack(); + + itemstack1.count = 1; + return itemstack1; + } + } + + return null; + } + + public int a() { + return 2; + } + + public ItemStack b() { + return null; + } + + public ItemStack[] b(InventoryCrafting inventorycrafting) { + ItemStack[] aitemstack = new ItemStack[inventorycrafting.getSize()]; + + for (int i = 0; i < aitemstack.length; ++i) { + ItemStack itemstack = inventorycrafting.getItem(i); + + if (itemstack != null) { + if (itemstack.getItem().r()) { + aitemstack[i] = new ItemStack(itemstack.getItem().q()); + } else if (itemstack.hasTag() && TileEntityBanner.c(itemstack) > 0) { + aitemstack[i] = itemstack.cloneItemStack(); + aitemstack[i].count = 1; + } + } + } + + return aitemstack; + } + + DuplicateRecipe(RecipesBanner.SyntheticClass_1 recipesbanner_syntheticclass_1) { + this(); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/RecipesCrafting.java b/azurite-server/src/main/java/net/minecraft/server/RecipesCrafting.java new file mode 100644 index 0000000..23106e5 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/RecipesCrafting.java @@ -0,0 +1,32 @@ +package net.minecraft.server; + +public class RecipesCrafting { + public RecipesCrafting() { + } + + public void a(CraftingManager var1) { + var1.registerShapedRecipe(new ItemStack(Blocks.CHEST), new Object[]{"###", "# #", "###", '#', Blocks.PLANKS}); + var1.registerShapedRecipe(new ItemStack(Blocks.TRAPPED_CHEST), new Object[]{"#-", '#', Blocks.CHEST, '-', Blocks.TRIPWIRE_HOOK}); + var1.registerShapedRecipe(new ItemStack(Blocks.ENDER_CHEST), new Object[]{"###", "#E#", "###", '#', Blocks.OBSIDIAN, 'E', Items.ENDER_EYE}); + var1.registerShapedRecipe(new ItemStack(Blocks.FURNACE), new Object[]{"###", "# #", "###", '#', Blocks.COBBLESTONE}); + var1.registerShapedRecipe(new ItemStack(Blocks.CRAFTING_TABLE), new Object[]{"##", "##", '#', Blocks.PLANKS}); + var1.registerShapedRecipe(new ItemStack(Blocks.SANDSTONE), new Object[]{"##", "##", '#', new ItemStack(Blocks.SAND, 1, BlockSand.EnumSandVariant.SAND.a())}); + var1.registerShapedRecipe(new ItemStack(Blocks.RED_SANDSTONE), new Object[]{"##", "##", '#', new ItemStack(Blocks.SAND, 1, BlockSand.EnumSandVariant.RED_SAND.a())}); + var1.registerShapedRecipe(new ItemStack(Blocks.STONEBRICK, 4), new Object[]{"##", "##", '#', new ItemStack(Blocks.STONE, 1, BlockStone.EnumStoneVariant.STONE.a())}); + var1.registerShapedRecipe(new ItemStack(Blocks.STONEBRICK, 1, BlockSmoothBrick.P), new Object[]{"#", "#", '#', new ItemStack(Blocks.STONE_SLAB, 1, BlockDoubleStepAbstract.EnumStoneSlabVariant.SMOOTHBRICK.a())}); + var1.registerShapelessRecipe(new ItemStack(Blocks.STONEBRICK, 1, BlockSmoothBrick.N), new Object[]{Blocks.STONEBRICK, Blocks.VINE}); + var1.registerShapelessRecipe(new ItemStack(Blocks.MOSSY_COBBLESTONE, 1), new Object[]{Blocks.COBBLESTONE, Blocks.VINE}); + var1.registerShapedRecipe(new ItemStack(Blocks.IRON_BARS, 16), new Object[]{"###", "###", '#', Items.IRON_INGOT}); + var1.registerShapedRecipe(new ItemStack(Blocks.GLASS_PANE, 16), new Object[]{"###", "###", '#', Blocks.GLASS}); + var1.registerShapedRecipe(new ItemStack(Blocks.REDSTONE_LAMP, 1), new Object[]{" R ", "RGR", " R ", 'R', Items.REDSTONE, 'G', Blocks.GLOWSTONE}); + var1.registerShapedRecipe(new ItemStack(Blocks.BEACON, 1), new Object[]{"GGG", "GSG", "OOO", 'G', Blocks.GLASS, 'S', Items.NETHER_STAR, 'O', Blocks.OBSIDIAN}); + var1.registerShapedRecipe(new ItemStack(Blocks.NETHER_BRICK, 1), new Object[]{"NN", "NN", 'N', Items.NETHERBRICK}); + var1.registerShapedRecipe(new ItemStack(Blocks.STONE, 2, BlockStone.EnumStoneVariant.DIORITE.a()), new Object[]{"CQ", "QC", 'C', Blocks.COBBLESTONE, 'Q', Items.QUARTZ}); + var1.registerShapelessRecipe(new ItemStack(Blocks.STONE, 1, BlockStone.EnumStoneVariant.GRANITE.a()), new Object[]{new ItemStack(Blocks.STONE, 1, BlockStone.EnumStoneVariant.DIORITE.a()), Items.QUARTZ}); + var1.registerShapelessRecipe(new ItemStack(Blocks.STONE, 2, BlockStone.EnumStoneVariant.ANDESITE.a()), new Object[]{new ItemStack(Blocks.STONE, 1, BlockStone.EnumStoneVariant.DIORITE.a()), Blocks.COBBLESTONE}); + var1.registerShapedRecipe(new ItemStack(Blocks.DIRT, 4, BlockDirt.EnumDirtVariant.COARSE_DIRT.a()), new Object[]{"DG", "GD", 'D', new ItemStack(Blocks.DIRT, 1, BlockDirt.EnumDirtVariant.DIRT.a()), 'G', Blocks.GRAVEL}); + var1.registerShapedRecipe(new ItemStack(Blocks.STONE, 4, BlockStone.EnumStoneVariant.DIORITE_SMOOTH.a()), new Object[]{"SS", "SS", 'S', new ItemStack(Blocks.STONE, 1, BlockStone.EnumStoneVariant.DIORITE.a())}); + var1.registerShapedRecipe(new ItemStack(Blocks.STONE, 4, BlockStone.EnumStoneVariant.GRANITE_SMOOTH.a()), new Object[]{"SS", "SS", 'S', new ItemStack(Blocks.STONE, 1, BlockStone.EnumStoneVariant.GRANITE.a())}); + var1.registerShapedRecipe(new ItemStack(Blocks.STONE, 4, BlockStone.EnumStoneVariant.ANDESITE_SMOOTH.a()), new Object[]{"SS", "SS", 'S', new ItemStack(Blocks.STONE, 1, BlockStone.EnumStoneVariant.ANDESITE.a())}); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/RecipesDyes.java b/azurite-server/src/main/java/net/minecraft/server/RecipesDyes.java new file mode 100644 index 0000000..48a08c1 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/RecipesDyes.java @@ -0,0 +1,50 @@ +package net.minecraft.server; + +public class RecipesDyes { + + public RecipesDyes() {} + + public void a(CraftingManager craftingmanager) { + int i; + + for (i = 0; i < 16; ++i) { + craftingmanager.registerShapelessRecipe(new ItemStack(Blocks.WOOL, 1, i), new Object[] { new ItemStack(Items.DYE, 1, 15 - i), new ItemStack(Item.getItemOf(Blocks.WOOL), 1, 0)}); + craftingmanager.registerShapedRecipe(new ItemStack(Blocks.STAINED_HARDENED_CLAY, 8, 15 - i), new Object[] { "###", "#X#", "###", Character.valueOf('#'), new ItemStack(Blocks.HARDENED_CLAY), Character.valueOf('X'), new ItemStack(Items.DYE, 1, i)}); + craftingmanager.registerShapedRecipe(new ItemStack(Blocks.STAINED_GLASS, 8, 15 - i), new Object[] { "###", "#X#", "###", Character.valueOf('#'), new ItemStack(Blocks.GLASS), Character.valueOf('X'), new ItemStack(Items.DYE, 1, i)}); + craftingmanager.registerShapedRecipe(new ItemStack(Blocks.STAINED_GLASS_PANE, 16, i), new Object[] { "###", "###", Character.valueOf('#'), new ItemStack(Blocks.STAINED_GLASS, 1, i)}); + } + + craftingmanager.registerShapelessRecipe(new ItemStack(Items.DYE, 1, EnumColor.YELLOW.getInvColorIndex()), new Object[] { new ItemStack(Blocks.YELLOW_FLOWER, 1, BlockFlowers.EnumFlowerVarient.DANDELION.b())}); + craftingmanager.registerShapelessRecipe(new ItemStack(Items.DYE, 1, EnumColor.RED.getInvColorIndex()), new Object[] { new ItemStack(Blocks.RED_FLOWER, 1, BlockFlowers.EnumFlowerVarient.POPPY.b())}); + craftingmanager.registerShapelessRecipe(new ItemStack(Items.DYE, 3, EnumColor.WHITE.getInvColorIndex()), new Object[] { Items.BONE}); + craftingmanager.registerShapelessRecipe(new ItemStack(Items.DYE, 2, EnumColor.PINK.getInvColorIndex()), new Object[] { new ItemStack(Items.DYE, 1, EnumColor.RED.getInvColorIndex()), new ItemStack(Items.DYE, 1, EnumColor.WHITE.getInvColorIndex())}); + craftingmanager.registerShapelessRecipe(new ItemStack(Items.DYE, 2, EnumColor.ORANGE.getInvColorIndex()), new Object[] { new ItemStack(Items.DYE, 1, EnumColor.RED.getInvColorIndex()), new ItemStack(Items.DYE, 1, EnumColor.YELLOW.getInvColorIndex())}); + craftingmanager.registerShapelessRecipe(new ItemStack(Items.DYE, 2, EnumColor.LIME.getInvColorIndex()), new Object[] { new ItemStack(Items.DYE, 1, EnumColor.GREEN.getInvColorIndex()), new ItemStack(Items.DYE, 1, EnumColor.WHITE.getInvColorIndex())}); + craftingmanager.registerShapelessRecipe(new ItemStack(Items.DYE, 2, EnumColor.GRAY.getInvColorIndex()), new Object[] { new ItemStack(Items.DYE, 1, EnumColor.BLACK.getInvColorIndex()), new ItemStack(Items.DYE, 1, EnumColor.WHITE.getInvColorIndex())}); + craftingmanager.registerShapelessRecipe(new ItemStack(Items.DYE, 2, EnumColor.SILVER.getInvColorIndex()), new Object[] { new ItemStack(Items.DYE, 1, EnumColor.GRAY.getInvColorIndex()), new ItemStack(Items.DYE, 1, EnumColor.WHITE.getInvColorIndex())}); + craftingmanager.registerShapelessRecipe(new ItemStack(Items.DYE, 3, EnumColor.SILVER.getInvColorIndex()), new Object[] { new ItemStack(Items.DYE, 1, EnumColor.BLACK.getInvColorIndex()), new ItemStack(Items.DYE, 1, EnumColor.WHITE.getInvColorIndex()), new ItemStack(Items.DYE, 1, EnumColor.WHITE.getInvColorIndex())}); + craftingmanager.registerShapelessRecipe(new ItemStack(Items.DYE, 2, EnumColor.LIGHT_BLUE.getInvColorIndex()), new Object[] { new ItemStack(Items.DYE, 1, EnumColor.BLUE.getInvColorIndex()), new ItemStack(Items.DYE, 1, EnumColor.WHITE.getInvColorIndex())}); + craftingmanager.registerShapelessRecipe(new ItemStack(Items.DYE, 2, EnumColor.CYAN.getInvColorIndex()), new Object[] { new ItemStack(Items.DYE, 1, EnumColor.BLUE.getInvColorIndex()), new ItemStack(Items.DYE, 1, EnumColor.GREEN.getInvColorIndex())}); + craftingmanager.registerShapelessRecipe(new ItemStack(Items.DYE, 2, EnumColor.PURPLE.getInvColorIndex()), new Object[] { new ItemStack(Items.DYE, 1, EnumColor.BLUE.getInvColorIndex()), new ItemStack(Items.DYE, 1, EnumColor.RED.getInvColorIndex())}); + craftingmanager.registerShapelessRecipe(new ItemStack(Items.DYE, 2, EnumColor.MAGENTA.getInvColorIndex()), new Object[] { new ItemStack(Items.DYE, 1, EnumColor.PURPLE.getInvColorIndex()), new ItemStack(Items.DYE, 1, EnumColor.PINK.getInvColorIndex())}); + craftingmanager.registerShapelessRecipe(new ItemStack(Items.DYE, 3, EnumColor.MAGENTA.getInvColorIndex()), new Object[] { new ItemStack(Items.DYE, 1, EnumColor.BLUE.getInvColorIndex()), new ItemStack(Items.DYE, 1, EnumColor.RED.getInvColorIndex()), new ItemStack(Items.DYE, 1, EnumColor.PINK.getInvColorIndex())}); + craftingmanager.registerShapelessRecipe(new ItemStack(Items.DYE, 4, EnumColor.MAGENTA.getInvColorIndex()), new Object[] { new ItemStack(Items.DYE, 1, EnumColor.BLUE.getInvColorIndex()), new ItemStack(Items.DYE, 1, EnumColor.RED.getInvColorIndex()), new ItemStack(Items.DYE, 1, EnumColor.RED.getInvColorIndex()), new ItemStack(Items.DYE, 1, EnumColor.WHITE.getInvColorIndex())}); + craftingmanager.registerShapelessRecipe(new ItemStack(Items.DYE, 1, EnumColor.LIGHT_BLUE.getInvColorIndex()), new Object[] { new ItemStack(Blocks.RED_FLOWER, 1, BlockFlowers.EnumFlowerVarient.BLUE_ORCHID.b())}); + craftingmanager.registerShapelessRecipe(new ItemStack(Items.DYE, 1, EnumColor.MAGENTA.getInvColorIndex()), new Object[] { new ItemStack(Blocks.RED_FLOWER, 1, BlockFlowers.EnumFlowerVarient.ALLIUM.b())}); + craftingmanager.registerShapelessRecipe(new ItemStack(Items.DYE, 1, EnumColor.SILVER.getInvColorIndex()), new Object[] { new ItemStack(Blocks.RED_FLOWER, 1, BlockFlowers.EnumFlowerVarient.HOUSTONIA.b())}); + craftingmanager.registerShapelessRecipe(new ItemStack(Items.DYE, 1, EnumColor.RED.getInvColorIndex()), new Object[] { new ItemStack(Blocks.RED_FLOWER, 1, BlockFlowers.EnumFlowerVarient.RED_TULIP.b())}); + craftingmanager.registerShapelessRecipe(new ItemStack(Items.DYE, 1, EnumColor.ORANGE.getInvColorIndex()), new Object[] { new ItemStack(Blocks.RED_FLOWER, 1, BlockFlowers.EnumFlowerVarient.ORANGE_TULIP.b())}); + craftingmanager.registerShapelessRecipe(new ItemStack(Items.DYE, 1, EnumColor.SILVER.getInvColorIndex()), new Object[] { new ItemStack(Blocks.RED_FLOWER, 1, BlockFlowers.EnumFlowerVarient.WHITE_TULIP.b())}); + craftingmanager.registerShapelessRecipe(new ItemStack(Items.DYE, 1, EnumColor.PINK.getInvColorIndex()), new Object[] { new ItemStack(Blocks.RED_FLOWER, 1, BlockFlowers.EnumFlowerVarient.PINK_TULIP.b())}); + craftingmanager.registerShapelessRecipe(new ItemStack(Items.DYE, 1, EnumColor.SILVER.getInvColorIndex()), new Object[] { new ItemStack(Blocks.RED_FLOWER, 1, BlockFlowers.EnumFlowerVarient.OXEYE_DAISY.b())}); + craftingmanager.registerShapelessRecipe(new ItemStack(Items.DYE, 2, EnumColor.YELLOW.getInvColorIndex()), new Object[] { new ItemStack(Blocks.DOUBLE_PLANT, 1, BlockTallPlant.EnumTallFlowerVariants.SUNFLOWER.a())}); + craftingmanager.registerShapelessRecipe(new ItemStack(Items.DYE, 2, EnumColor.MAGENTA.getInvColorIndex()), new Object[] { new ItemStack(Blocks.DOUBLE_PLANT, 1, BlockTallPlant.EnumTallFlowerVariants.SYRINGA.a())}); + craftingmanager.registerShapelessRecipe(new ItemStack(Items.DYE, 2, EnumColor.RED.getInvColorIndex()), new Object[] { new ItemStack(Blocks.DOUBLE_PLANT, 1, BlockTallPlant.EnumTallFlowerVariants.ROSE.a())}); + craftingmanager.registerShapelessRecipe(new ItemStack(Items.DYE, 2, EnumColor.PINK.getInvColorIndex()), new Object[] { new ItemStack(Blocks.DOUBLE_PLANT, 1, BlockTallPlant.EnumTallFlowerVariants.PAEONIA.a())}); + + for (i = 0; i < 16; ++i) { + craftingmanager.registerShapedRecipe(new ItemStack(Blocks.CARPET, 3, i), new Object[] { "##", Character.valueOf('#'), new ItemStack(Blocks.WOOL, 1, i)}); + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/RecipesFood.java b/azurite-server/src/main/java/net/minecraft/server/RecipesFood.java new file mode 100644 index 0000000..66e99e7 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/RecipesFood.java @@ -0,0 +1,20 @@ +package net.minecraft.server; + +public class RecipesFood { + + public RecipesFood() {} + + public void a(CraftingManager craftingmanager) { + craftingmanager.registerShapelessRecipe(new ItemStack(Items.MUSHROOM_STEW), new Object[] { Blocks.BROWN_MUSHROOM, Blocks.RED_MUSHROOM, Items.BOWL}); + craftingmanager.registerShapedRecipe(new ItemStack(Items.COOKIE, 8), new Object[] { "#X#", Character.valueOf('X'), new ItemStack(Items.DYE, 1, EnumColor.BROWN.getInvColorIndex()), Character.valueOf('#'), Items.WHEAT}); + craftingmanager.registerShapedRecipe(new ItemStack(Items.RABBIT_STEW), new Object[] { " R ", "CPM", " B ", Character.valueOf('R'), new ItemStack(Items.COOKED_RABBIT), Character.valueOf('C'), Items.CARROT, Character.valueOf('P'), Items.BAKED_POTATO, Character.valueOf('M'), Blocks.BROWN_MUSHROOM, Character.valueOf('B'), Items.BOWL}); + craftingmanager.registerShapedRecipe(new ItemStack(Items.RABBIT_STEW), new Object[] { " R ", "CPD", " B ", Character.valueOf('R'), new ItemStack(Items.COOKED_RABBIT), Character.valueOf('C'), Items.CARROT, Character.valueOf('P'), Items.BAKED_POTATO, Character.valueOf('D'), Blocks.RED_MUSHROOM, Character.valueOf('B'), Items.BOWL}); + craftingmanager.registerShapedRecipe(new ItemStack(Blocks.MELON_BLOCK), new Object[] { "MMM", "MMM", "MMM", Character.valueOf('M'), Items.MELON}); + craftingmanager.registerShapedRecipe(new ItemStack(Items.MELON_SEEDS), new Object[] { "M", Character.valueOf('M'), Items.MELON}); + craftingmanager.registerShapedRecipe(new ItemStack(Items.PUMPKIN_SEEDS, 4), new Object[] { "M", Character.valueOf('M'), Blocks.PUMPKIN}); + craftingmanager.registerShapelessRecipe(new ItemStack(Items.PUMPKIN_PIE), new Object[] { Blocks.PUMPKIN, Items.SUGAR, Items.EGG}); + craftingmanager.registerShapelessRecipe(new ItemStack(Items.FERMENTED_SPIDER_EYE), new Object[] { Items.SPIDER_EYE, Blocks.BROWN_MUSHROOM, Items.SUGAR}); + craftingmanager.registerShapelessRecipe(new ItemStack(Items.BLAZE_POWDER, 2), new Object[] { Items.BLAZE_ROD}); + craftingmanager.registerShapelessRecipe(new ItemStack(Items.MAGMA_CREAM), new Object[] { Items.BLAZE_POWDER, Items.SLIME}); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/RecipesFurnace.java b/azurite-server/src/main/java/net/minecraft/server/RecipesFurnace.java new file mode 100644 index 0000000..e049ade --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/RecipesFurnace.java @@ -0,0 +1,122 @@ +package net.minecraft.server; + +import com.google.common.collect.Maps; + +import java.util.Iterator; +import java.util.Map; +import java.util.Map.Entry; + +public class RecipesFurnace { + + private static final RecipesFurnace a = new RecipesFurnace(); + public Map recipes = Maps.newHashMap(); + private final Map c = Maps.newHashMap(); + public final Map customRecipes = Maps.newHashMap(); // CraftBukkit - add field + + public static RecipesFurnace getInstance() { + return RecipesFurnace.a; + } + + public RecipesFurnace() { // PAIL: Public + this.registerRecipe(Blocks.IRON_ORE, new ItemStack(Items.IRON_INGOT), 0.7F); + this.registerRecipe(Blocks.GOLD_ORE, new ItemStack(Items.GOLD_INGOT), 1.0F); + this.registerRecipe(Blocks.DIAMOND_ORE, new ItemStack(Items.DIAMOND), 1.0F); + this.registerRecipe(Blocks.SAND, new ItemStack(Blocks.GLASS), 0.1F); + this.a(Items.PORKCHOP, new ItemStack(Items.COOKED_PORKCHOP), 0.35F); + this.a(Items.BEEF, new ItemStack(Items.COOKED_BEEF), 0.35F); + this.a(Items.CHICKEN, new ItemStack(Items.COOKED_CHICKEN), 0.35F); + this.a(Items.RABBIT, new ItemStack(Items.COOKED_RABBIT), 0.35F); + this.a(Items.MUTTON, new ItemStack(Items.COOKED_MUTTON), 0.35F); + this.registerRecipe(Blocks.COBBLESTONE, new ItemStack(Blocks.STONE), 0.1F); + this.a(new ItemStack(Blocks.STONEBRICK, 1, BlockSmoothBrick.b), new ItemStack(Blocks.STONEBRICK, 1, BlockSmoothBrick.O), 0.1F); + this.a(Items.CLAY_BALL, new ItemStack(Items.BRICK), 0.3F); + this.registerRecipe(Blocks.CLAY, new ItemStack(Blocks.HARDENED_CLAY), 0.35F); + this.registerRecipe(Blocks.CACTUS, new ItemStack(Items.DYE, 1, EnumColor.GREEN.getInvColorIndex()), 0.2F); + this.registerRecipe(Blocks.LOG, new ItemStack(Items.COAL, 1, 1), 0.15F); + this.registerRecipe(Blocks.LOG2, new ItemStack(Items.COAL, 1, 1), 0.15F); + this.registerRecipe(Blocks.EMERALD_ORE, new ItemStack(Items.EMERALD), 1.0F); + this.a(Items.POTATO, new ItemStack(Items.BAKED_POTATO), 0.35F); + this.registerRecipe(Blocks.NETHERRACK, new ItemStack(Items.NETHERBRICK), 0.1F); + this.a(new ItemStack(Blocks.SPONGE, 1, 1), new ItemStack(Blocks.SPONGE, 1, 0), 0.15F); + + for (ItemFish.EnumFish itemfish_enumfish : ItemFish.EnumFish.values()) { + if (itemfish_enumfish.g()) { + this.a(new ItemStack(Items.FISH, 1, itemfish_enumfish.a()), new ItemStack(Items.COOKED_FISH, 1, itemfish_enumfish.a()), 0.35F); + } + } + + this.registerRecipe(Blocks.COAL_ORE, new ItemStack(Items.COAL), 0.1F); + this.registerRecipe(Blocks.REDSTONE_ORE, new ItemStack(Items.REDSTONE), 0.7F); + this.registerRecipe(Blocks.LAPIS_ORE, new ItemStack(Items.DYE, 1, EnumColor.BLUE.getInvColorIndex()), 0.2F); + this.registerRecipe(Blocks.QUARTZ_ORE, new ItemStack(Items.QUARTZ), 0.2F); + } + + // CraftBukkit start - add method + public void registerRecipe(ItemStack itemstack, ItemStack itemstack1) { + this.customRecipes.put(itemstack, itemstack1); + } + // CraftBukkit end + + public void registerRecipe(Block block, ItemStack itemstack, float f) { + this.a(Item.getItemOf(block), itemstack, f); + } + + public void a(Item item, ItemStack itemstack, float f) { + this.a(new ItemStack(item, 1, 32767), itemstack, f); + } + + public void a(ItemStack itemstack, ItemStack itemstack1, float f) { + this.recipes.put(itemstack, itemstack1); + this.c.put(itemstack1, f); + } + + public ItemStack getResult(ItemStack itemstack) { + // CraftBukkit start - initialize to customRecipes + boolean vanilla = false; + Iterator> iterator = this.customRecipes.entrySet().iterator(); + // CraftBukkit end + + Entry entry; + + do { + if (!iterator.hasNext()) { + // CraftBukkit start - fall back to vanilla recipes + if (!vanilla && !recipes.isEmpty()) { + iterator = this.recipes.entrySet().iterator(); + vanilla = true; + } else { + return null; + } + // CraftBukkit end + } + + entry = iterator.next(); + } while (!this.a(itemstack, entry.getKey())); + + return entry.getValue(); + } + + private boolean a(ItemStack itemstack, ItemStack itemstack1) { + return itemstack1.getItem() == itemstack.getItem() && (itemstack1.getData() == 32767 || itemstack1.getData() == itemstack.getData()); + } + + public Map getRecipes() { + return this.recipes; + } + + public float b(ItemStack itemstack) { + Iterator> iterator = this.c.entrySet().iterator(); + + Entry entry; + + do { + if (!iterator.hasNext()) { + return 0.0F; + } + + entry = iterator.next(); + } while (!this.a(itemstack, entry.getKey())); + + return entry.getValue(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/RecipesTools.java b/azurite-server/src/main/java/net/minecraft/server/RecipesTools.java new file mode 100644 index 0000000..5f23f6c --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/RecipesTools.java @@ -0,0 +1,25 @@ +package net.minecraft.server; + +public class RecipesTools { + + private String[][] a = new String[][] { { "XXX", " # ", " # "}, { "X", "#", "#"}, { "XX", "X#", " #"}, { "XX", " #", " #"}}; + private Object[][] b; + + public RecipesTools() { + this.b = new Object[][] { { Blocks.PLANKS, Blocks.COBBLESTONE, Items.IRON_INGOT, Items.DIAMOND, Items.GOLD_INGOT}, { Items.WOODEN_PICKAXE, Items.STONE_PICKAXE, Items.IRON_PICKAXE, Items.DIAMOND_PICKAXE, Items.GOLDEN_PICKAXE}, { Items.WOODEN_SHOVEL, Items.STONE_SHOVEL, Items.IRON_SHOVEL, Items.DIAMOND_SHOVEL, Items.GOLDEN_SHOVEL}, { Items.WOODEN_AXE, Items.STONE_AXE, Items.IRON_AXE, Items.DIAMOND_AXE, Items.GOLDEN_AXE}, { Items.WOODEN_HOE, Items.STONE_HOE, Items.IRON_HOE, Items.DIAMOND_HOE, Items.GOLDEN_HOE}}; + } + + public void a(CraftingManager craftingmanager) { + for (int i = 0; i < this.b[0].length; ++i) { + Object object = this.b[0][i]; + + for (int j = 0; j < this.b.length - 1; ++j) { + Item item = (Item) this.b[j + 1][i]; + + craftingmanager.registerShapedRecipe(new ItemStack(item), new Object[] { this.a[j], Character.valueOf('#'), Items.STICK, Character.valueOf('X'), object}); + } + } + + craftingmanager.registerShapedRecipe(new ItemStack(Items.SHEARS), new Object[] { " #", "# ", Character.valueOf('#'), Items.IRON_INGOT}); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/RecipesWeapons.java b/azurite-server/src/main/java/net/minecraft/server/RecipesWeapons.java new file mode 100644 index 0000000..d06b602 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/RecipesWeapons.java @@ -0,0 +1,26 @@ +package net.minecraft.server; + +public class RecipesWeapons { + + private String[][] a = new String[][] { { "X", "X", "#"}}; + private Object[][] b; + + public RecipesWeapons() { + this.b = new Object[][] { { Blocks.PLANKS, Blocks.COBBLESTONE, Items.IRON_INGOT, Items.DIAMOND, Items.GOLD_INGOT}, { Items.WOODEN_SWORD, Items.STONE_SWORD, Items.IRON_SWORD, Items.DIAMOND_SWORD, Items.GOLDEN_SWORD}}; + } + + public void a(CraftingManager craftingmanager) { + for (int i = 0; i < this.b[0].length; ++i) { + Object object = this.b[0][i]; + + for (int j = 0; j < this.b.length - 1; ++j) { + Item item = (Item) this.b[j + 1][i]; + + craftingmanager.registerShapedRecipe(new ItemStack(item), new Object[] { this.a[j], Character.valueOf('#'), Items.STICK, Character.valueOf('X'), object}); + } + } + + craftingmanager.registerShapedRecipe(new ItemStack(Items.BOW, 1), new Object[] { " #X", "# X", " #X", Character.valueOf('X'), Items.STRING, Character.valueOf('#'), Items.STICK}); + craftingmanager.registerShapedRecipe(new ItemStack(Items.ARROW, 4), new Object[] { "X", "#", "Y", Character.valueOf('Y'), Items.FEATHER, Character.valueOf('X'), Items.FLINT, Character.valueOf('#'), Items.STICK}); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/RedirectStream.java b/azurite-server/src/main/java/net/minecraft/server/RedirectStream.java new file mode 100644 index 0000000..2bd51d5 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/RedirectStream.java @@ -0,0 +1,32 @@ +package net.minecraft.server; + +import java.io.OutputStream; +import java.io.PrintStream; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +public class RedirectStream extends PrintStream { + + private static final Logger a = LogManager.getLogger(); + private final String b; + + public RedirectStream(String s, OutputStream outputstream) { + super(outputstream); + this.b = s; + } + + public void println(String s) { + this.a(s); + } + + public void println(Object object) { + this.a(String.valueOf(object)); + } + + private void a(String s) { + StackTraceElement[] astacktraceelement = Thread.currentThread().getStackTrace(); + StackTraceElement stacktraceelement = astacktraceelement[Math.min(3, astacktraceelement.length)]; + + RedirectStream.a.info("[{}]@.({}:{}): {}", new Object[] { this.b, stacktraceelement.getFileName(), Integer.valueOf(stacktraceelement.getLineNumber()), s}); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/RegionFile.java b/azurite-server/src/main/java/net/minecraft/server/RegionFile.java new file mode 100644 index 0000000..96bdbfd --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/RegionFile.java @@ -0,0 +1,321 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; + +import java.io.*; +import java.nio.ByteBuffer; +import java.nio.IntBuffer; +import java.util.List; +import java.util.zip.DeflaterOutputStream; +import java.util.zip.GZIPInputStream; +import java.util.zip.InflaterInputStream; + +public class RegionFile { + + private static final byte[] a = new byte[4096]; // Spigot - note: if this ever changes to not be 4096 bytes, update constructor! // PAIL: empty 4k block + private RandomAccessFile c; + private final int[] d = new int[1024]; + private List f; + // Azurite - Migot chunk exists cache + private final Boolean[] existsCache = new Boolean[1024]; + + private void cacheExistsState(int i, int j, boolean state) { + existsCache[i + j * 32] = state; + } + + private Boolean getExistsCache(int i, int j) { + return existsCache[i + j * 32]; + } + + public RegionFile(File file) { + + try { + this.c = new RandomAccessFile(file, "rw"); + int i; + + if (this.c.length() < 4096L) { + // Spigot - more effecient chunk zeroing + this.c.write(RegionFile.a); // Spigot + this.c.write(RegionFile.a); // Spigot + } + + if ((this.c.length() & 4095L) != 0L) { + for (i = 0; (long) i < (this.c.length() & 4095L); ++i) { + this.c.write(0); + } + } + + i = (int) this.c.length() / 4096; + this.f = Lists.newArrayListWithCapacity(i); + + int j; + + for (j = 0; j < i; ++j) { + this.f.add(true); + } + + this.f.set(0, false); + this.f.set(1, false); + this.c.seek(0L); + + int k; + // Paper Start + ByteBuffer header = ByteBuffer.allocate(8192); + while (header.hasRemaining()) { + if (c.getChannel().read(header) == -1) throw new EOFException(); + } + + header.clear(); + + IntBuffer headerAsInts = header.asIntBuffer(); + // Paper end + + for (j = 0; j < 1024; ++j) { + k = headerAsInts.get(); // Paper + this.d[j] = k; + if (k != 0 && (k >> 8) + (k & 255) <= this.f.size()) { + for (int l = 0; l < (k & 255); ++l) { + this.f.set((k >> 8) + l, false); + } + } + } + } catch (IOException ioexception) { + ioexception.printStackTrace(); + } + + } + + // CraftBukkit start - This is a copy (sort of) of the method below it, make sure they stay in sync + public boolean chunkExists(int i, int j) { + if (this.d(i, j)) { + return false; + } else { + // Azurite - Migot chunk exists cache + Boolean cached = getExistsCache(i, j); + + if (cached != null) { + return cached; + } + + synchronized (this) { + try { + int k = this.e(i, j); + + if (k == 0) { + return false; + } else { + int l = k >> 8; + int i1 = k & 255; + + if (l + i1 > this.f.size()) { + return false; + } + + this.c.seek(l * 4096L); + int j1 = this.c.readInt(); + + if (j1 > 4096 * i1 || j1 <= 0) { + return false; + } + + byte b0 = this.c.readByte(); + // Azurite - Migot chunk exists cache + boolean foundChunk = b0 == 1 || b0 == 2; + cacheExistsState(i, j, foundChunk); + + return foundChunk; + } + } catch (IOException ioexception) { + return false; + } + } + + } + } + // CraftBukkit end + + //read + public DataInputStream a(int i, int j) { + if (this.d(i, j)) { + return null; + } else { + synchronized (this) { + try { + int k = this.e(i, j); + + if (k == 0) { + return null; + } else { + int l = k >> 8; + int i1 = k & 255; + + if (l + i1 > this.f.size()) { + return null; + } else { + this.c.seek(l * 4096L); + int j1 = this.c.readInt(); + + if (j1 > 4096 * i1) { + return null; + } else if (j1 <= 0) { + return null; + } else { + byte b0 = this.c.readByte(); + byte[] abyte; + + if (b0 == 1) { + cacheExistsState(i, j, true); + abyte = new byte[j1 - 1]; + this.c.read(abyte); + return new DataInputStream(new BufferedInputStream(new GZIPInputStream(new ByteArrayInputStream(abyte)))); + } else if (b0 == 2) { + cacheExistsState(i, j, true); + abyte = new byte[j1 - 1]; + this.c.read(abyte); + return new DataInputStream(new BufferedInputStream(new InflaterInputStream(new ByteArrayInputStream(abyte)))); + } else { + cacheExistsState(i, j, false); + return null; + } + } + } + } + } catch (IOException ioexception) { + return null; + } + } + } + } + + public DataOutputStream b(int i, int j) { // PAIL: getChunkOutputStream + // PAIL: isInvalidRegion + return this.d(i, j) ? null : new DataOutputStream(new java.io.BufferedOutputStream(new DeflaterOutputStream(new RegionFile.ChunkBuffer(i, j)))); // Spigot - use a BufferedOutputStream to greatly improve file write performance + } + + //write + protected synchronized void a(int i, int j, byte[] abyte, int k) { + try { + int l = this.e(i, j); + int i1 = l >> 8; + int j1 = l & 255; + int k1 = (k + 5) / 4096 + 1; + + if (k1 >= 256) { + return; + } + + if (i1 != 0 && j1 == k1) { + this.a(i1, abyte, k); + } else { + int l1; + + for (l1 = 0; l1 < j1; ++l1) { + this.f.set(i1 + l1, true); + } + + l1 = this.f.indexOf(true); + int i2 = 0; + int j2; + + if (l1 != -1) { + for (j2 = l1; j2 < this.f.size(); ++j2) { + if (i2 != 0) { + if (this.f.get(j2)) { + ++i2; + } else { + i2 = 0; + } + } else if (this.f.get(j2)) { + l1 = j2; + i2 = 1; + } + + if (i2 >= k1) { + break; + } + } + } + + if (i2 >= k1) { + i1 = l1; + this.a(i, j, l1 << 8 | k1); + + for (j2 = 0; j2 < k1; ++j2) { + this.f.set(i1 + j2, false); + } + + this.a(i1, abyte, k); + } else { + this.c.seek(this.c.length()); + i1 = this.f.size(); + + for (j2 = 0; j2 < k1; ++j2) { + this.c.write(RegionFile.a); + this.f.add(false); + } + + this.a(i1, abyte, k); + this.a(i, j, i1 << 8 | k1); + } + } + + this.b(i, j, (int) (MinecraftServer.az() / 1000L)); + } catch (IOException ioexception) { + ioexception.printStackTrace(); + } + + } + + private void a(int i, byte[] abyte, int j) throws IOException { + this.c.seek(i * 4096L); + this.c.writeInt(j + 1); + this.c.writeByte(2); + this.c.write(abyte, 0, j); + } + + private boolean d(int i, int j) { + return i < 0 || i >= 32 || j < 0 || j >= 32; + } + + private int e(int i, int j) { + return this.d[i + j * 32]; + } + + public boolean c(int i, int j) { + return this.e(i, j) != 0; + } + + private void a(int i, int j, int k) throws IOException { + this.d[i + j * 32] = k; + this.c.seek(((i + j * 32L) * 4)); + this.c.writeInt(k); + } + + private void b(int i, int j, int k) throws IOException { + this.c.seek((4096 + (i + j * 32L) * 4)); + this.c.writeInt(k); + } + + public void c() throws IOException { + if (this.c != null) { + this.c.close(); + } + + } + + class ChunkBuffer extends ByteArrayOutputStream { + + private final int b; + private final int c; + + public ChunkBuffer(int i, int j) { + super(8096); + this.b = i; + this.c = j; + } + + public void close() { + RegionFile.this.a(this.b, this.c, this.buf, this.count); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/RegionFileCache.java b/azurite-server/src/main/java/net/minecraft/server/RegionFileCache.java new file mode 100644 index 0000000..ff0b963 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/RegionFileCache.java @@ -0,0 +1,65 @@ +package net.minecraft.server; + +import com.google.common.collect.Maps; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.File; +import java.io.IOException; +import java.util.Map; + +public class RegionFileCache { + + public static final Map a = Maps.newHashMap(); // Spigot - private -> public + + public static RegionFile a(File file, int i, int j) { // Paper - remove synchronization + return a(file, i, j, true); + } + + public static RegionFile a(File file, int i, int j, boolean create) { // Paper - remove synchronization + // PaperSpigot end + File file1 = new File(file, "region"); + File file2 = new File(file1, "r." + (i >> 5) + "." + (j >> 5) + ".mca"); + RegionFile regionfile = a.get(file2); + + if (regionfile != null) { + return regionfile; + } else { + if (!create && !file2.exists()) { return null; } // PaperSpigot + if (!file1.exists()) { + file1.mkdirs(); + } + + if (a.size() >= 256) { + a(); + } + + RegionFile regionfile1 = new RegionFile(file2); + + a.put(file2, regionfile1); + return regionfile1; + } + } + + public static void a() { // Paper - remove synchronization + for (RegionFile regionfile : a.values()) { + try { + if (regionfile != null) { + regionfile.c(); + } + } catch (IOException ioexception) { + ioexception.printStackTrace(); + } + } + + RegionFileCache.a.clear(); + } + + public static DataInputStream c(File file, int i, int j) { + return a(file, i, j).a(i & 31, j & 31); + } + + public static DataOutputStream d(File file, int i, int j) { + return a(file, i, j).b(i & 31, j & 31); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/Registry.java b/azurite-server/src/main/java/net/minecraft/server/Registry.java new file mode 100644 index 0000000..44f52d1 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/Registry.java @@ -0,0 +1,3 @@ +package net.minecraft.server; + +public interface Registry extends Iterable {} diff --git a/azurite-server/src/main/java/net/minecraft/server/RegistryBlocks.java b/azurite-server/src/main/java/net/minecraft/server/RegistryBlocks.java new file mode 100644 index 0000000..fa0c450 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/RegistryBlocks.java @@ -0,0 +1,37 @@ +package net.minecraft.server; + +import org.apache.commons.lang3.Validate; + +public class RegistryBlocks extends RegistryMaterials { + + private final K d; + private V e; + + public RegistryBlocks(K k0) { + this.d = k0; + } + + public void a(int i, K k0, V v0) { + if (this.d.equals(k0)) { + this.e = v0; + } + + super.a(i, k0, v0); + } + + public void a() { + Validate.notNull(this.d); + } + + public V get(K k0) { + V object = super.get(k0); + + return object == null ? this.e : object; + } + + public V a(int i) { + V object = super.a(i); + + return object == null ? this.e : object; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/RegistryDefault.java b/azurite-server/src/main/java/net/minecraft/server/RegistryDefault.java new file mode 100644 index 0000000..0988617 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/RegistryDefault.java @@ -0,0 +1,16 @@ +package net.minecraft.server; + +public class RegistryDefault extends RegistrySimple { + + private final V a; + + public RegistryDefault(V v0) { + this.a = v0; + } + + public V get(K k0) { + V object = super.get(k0); + + return object == null ? this.a : object; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/RegistryID.java b/azurite-server/src/main/java/net/minecraft/server/RegistryID.java new file mode 100644 index 0000000..0563974 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/RegistryID.java @@ -0,0 +1,41 @@ +package net.minecraft.server; + +import com.google.common.base.Predicates; +import com.google.common.collect.Iterators; +import com.google.common.collect.Lists; +import org.jetbrains.annotations.NotNull; + +import java.util.IdentityHashMap; +import java.util.Iterator; +import java.util.List; + +public class RegistryID implements Registry { + private final IdentityHashMap a = new IdentityHashMap<>(0); + private final List b = Lists.newArrayList(); + + public RegistryID() { + } + + public void a(T var1, int var2) { + this.a.put(var1, var2); + + while(this.b.size() <= var2) { + this.b.add(null); + } + + this.b.set(var2, var1); + } + + public int b(T var1) { + Integer var2 = this.a.get(var1); + return var2 == null ? -1 : var2; + } + + public T a(int var1) { + return var1 >= 0 && var1 < this.b.size() ? this.b.get(var1) : null; + } + + public @NotNull Iterator iterator() { + return Iterators.filter(this.b.iterator(), Predicates.notNull()); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/RegistryMaterials.java b/azurite-server/src/main/java/net/minecraft/server/RegistryMaterials.java new file mode 100644 index 0000000..936a6e3 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/RegistryMaterials.java @@ -0,0 +1,49 @@ +package net.minecraft.server; + +import com.google.common.collect.BiMap; +import com.google.common.collect.HashBiMap; +import java.util.Iterator; +import java.util.Map; + +public class RegistryMaterials extends RegistrySimple implements Registry { + + protected final RegistryID a = new RegistryID(); + protected final Map b; + + public RegistryMaterials() { + this.b = ((BiMap) this.c).inverse(); + } + + public void a(int i, K k0, V v0) { + this.a.a(v0, i); + this.a(k0, v0); + } + + protected Map b() { + return HashBiMap.create(); + } + + public V get(K k0) { + return super.get(k0); + } + + public K c(V v0) { + return this.b.get(v0); + } + + public boolean d(K k0) { + return super.d(k0); + } + + public int b(V v0) { + return this.a.b(v0); + } + + public V a(int i) { + return this.a.a(i); + } + + public Iterator iterator() { + return this.a.iterator(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/RegistrySimple.java b/azurite-server/src/main/java/net/minecraft/server/RegistrySimple.java new file mode 100644 index 0000000..e76cb6e --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/RegistrySimple.java @@ -0,0 +1,48 @@ +package net.minecraft.server; + +import com.google.common.collect.Maps; +import java.util.Collections; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; +import org.apache.commons.lang3.Validate; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +public class RegistrySimple implements IRegistry { + + private static final Logger a = LogManager.getLogger(); + protected final Map c = this.b(); + + public RegistrySimple() {} + + protected Map b() { + return Maps.newHashMap(); + } + + public V get(K k0) { + return this.c.get(k0); + } + + public void a(K k0, V v0) { + Validate.notNull(k0); + Validate.notNull(v0); + if (this.c.containsKey(k0)) { + RegistrySimple.a.debug("Adding duplicate key \'" + k0 + "\' to registry"); + } + + this.c.put(k0, v0); + } + + public Set keySet() { + return Collections.unmodifiableSet(this.c.keySet()); + } + + public boolean d(K k0) { + return this.c.containsKey(k0); + } + + public Iterator iterator() { + return this.c.values().iterator(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/RemoteConnectionThread.java b/azurite-server/src/main/java/net/minecraft/server/RemoteConnectionThread.java new file mode 100644 index 0000000..6109842 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/RemoteConnectionThread.java @@ -0,0 +1,147 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; +import java.io.IOException; +import java.net.DatagramSocket; +import java.net.ServerSocket; +import java.util.Iterator; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + +public abstract class RemoteConnectionThread implements Runnable { + + private static final AtomicInteger h = new AtomicInteger(0); + protected boolean a; + protected IMinecraftServer b; + protected final String c; + protected Thread d; + protected int e = 5; + protected List f = Lists.newArrayList(); + protected List g = Lists.newArrayList(); + + protected RemoteConnectionThread(IMinecraftServer iminecraftserver, String s) { + this.b = iminecraftserver; + this.c = s; + if (this.b.isDebugging()) { + this.c("Debugging is enabled, performance maybe reduced!"); + } + + } + + public synchronized void a() { + this.d = new Thread(this, this.c + " #" + RemoteConnectionThread.h.incrementAndGet()); + this.d.start(); + this.a = true; + } + + public boolean c() { + return this.a; + } + + protected void a(String s) { + this.b.h(s); + } + + protected void b(String s) { + this.b.info(s); + } + + protected void c(String s) { + this.b.warning(s); + } + + protected void d(String s) { + this.b.g(s); + } + + protected int d() { + return this.b.I(); + } + + protected void a(DatagramSocket datagramsocket) { + this.a("registerSocket: " + datagramsocket); + this.f.add(datagramsocket); + } + + protected boolean a(DatagramSocket datagramsocket, boolean flag) { + this.a("closeSocket: " + datagramsocket); + if (null == datagramsocket) { + return false; + } else { + boolean flag1 = false; + + if (!datagramsocket.isClosed()) { + datagramsocket.close(); + flag1 = true; + } + + if (flag) { + this.f.remove(datagramsocket); + } + + return flag1; + } + } + + protected boolean b(ServerSocket serversocket) { + return this.a(serversocket, true); + } + + protected boolean a(ServerSocket serversocket, boolean flag) { + this.a("closeSocket: " + serversocket); + if (null == serversocket) { + return false; + } else { + boolean flag1 = false; + + try { + if (!serversocket.isClosed()) { + serversocket.close(); + flag1 = true; + } + } catch (IOException ioexception) { + this.c("IO: " + ioexception.getMessage()); + } + + if (flag) { + this.g.remove(serversocket); + } + + return flag1; + } + } + + protected void e() { + this.a(false); + } + + protected void a(boolean flag) { + int i = 0; + Iterator iterator = this.f.iterator(); + + while (iterator.hasNext()) { + DatagramSocket datagramsocket = (DatagramSocket) iterator.next(); + + if (this.a(datagramsocket, false)) { + ++i; + } + } + + this.f.clear(); + iterator = this.g.iterator(); + + while (iterator.hasNext()) { + ServerSocket serversocket = (ServerSocket) iterator.next(); + + if (this.a(serversocket, false)) { + ++i; + } + } + + this.g.clear(); + if (flag && 0 < i) { + this.c("Force closed " + i + " sockets"); + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/RemoteControlCommandListener.java b/azurite-server/src/main/java/net/minecraft/server/RemoteControlCommandListener.java new file mode 100644 index 0000000..3fc8c85 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/RemoteControlCommandListener.java @@ -0,0 +1,65 @@ +package net.minecraft.server; + +public class RemoteControlCommandListener implements ICommandListener { + + private static final RemoteControlCommandListener instance = new RemoteControlCommandListener(); + private final StringBuffer b = new StringBuffer(); + + public RemoteControlCommandListener() {} + + public static RemoteControlCommandListener getInstance() { + return RemoteControlCommandListener.instance; + } + + public void i() { + this.b.setLength(0); + } + + public String j() { + return this.b.toString(); + } + + public String getName() { + return "Rcon"; + } + + public IChatBaseComponent getScoreboardDisplayName() { + return new ChatComponentText(this.getName()); + } + + // CraftBukkit start - Send a String + public void sendMessage(String message) { + this.b.append(message); + } + // CraftBukkit end + + public void sendMessage(IChatBaseComponent ichatbasecomponent) { + this.b.append(ichatbasecomponent.c()); + } + + public boolean a(int i, String s) { + return true; + } + + public BlockPosition getChunkCoordinates() { + return new BlockPosition(0, 0, 0); + } + + public Vec3D d() { + return new Vec3D(0.0D, 0.0D, 0.0D); + } + + public World getWorld() { + return MinecraftServer.getServer().getWorld(); + } + + public Entity f() { + return null; + } + + public boolean getSendCommandFeedback() { + return true; + } + + public void a(CommandObjectiveExecutor.EnumCommandResult commandobjectiveexecutor_enumcommandresult, int i) {} +} diff --git a/azurite-server/src/main/java/net/minecraft/server/RemoteControlListener.java b/azurite-server/src/main/java/net/minecraft/server/RemoteControlListener.java new file mode 100644 index 0000000..a4da2b4 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/RemoteControlListener.java @@ -0,0 +1,111 @@ +package net.minecraft.server; + +import com.google.common.collect.Maps; +import java.io.IOException; +import java.net.InetAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.SocketAddress; +import java.net.SocketTimeoutException; +import java.util.Iterator; +import java.util.Map; +import java.util.Map.Entry; + +public class RemoteControlListener extends RemoteConnectionThread { + + private int h; + private int i; + private String j; + private ServerSocket k; + private String l; + private Map m; + + public RemoteControlListener(IMinecraftServer iminecraftserver) { + super(iminecraftserver, "RCON Listener"); + this.h = iminecraftserver.a("rcon.port", 0); + this.l = iminecraftserver.a("rcon.password", ""); + this.j = iminecraftserver.E(); + this.i = iminecraftserver.F(); + if (0 == this.h) { + this.h = this.i + 10; + this.b("Setting default rcon port to " + this.h); + iminecraftserver.a("rcon.port", (Object) Integer.valueOf(this.h)); + if (0 == this.l.length()) { + iminecraftserver.a("rcon.password", (Object) ""); + } + + iminecraftserver.a(); + } + + if (0 == this.j.length()) { + this.j = "0.0.0.0"; + } + + this.f(); + this.k = null; + } + + private void f() { + this.m = Maps.newHashMap(); + } + + private void g() { + Iterator iterator = this.m.entrySet().iterator(); + + while (iterator.hasNext()) { + Entry entry = (Entry) iterator.next(); + + if (!((RemoteControlSession) entry.getValue()).c()) { + iterator.remove(); + } + } + + } + + public void run() { + this.b("RCON running on " + this.j + ":" + this.h); + + try { + while (this.a) { + try { + Socket socket = this.k.accept(); + + socket.setSoTimeout(500); + RemoteControlSession remotecontrolsession = new RemoteControlSession(this.b, socket); + + remotecontrolsession.a(); + this.m.put(socket.getRemoteSocketAddress(), remotecontrolsession); + this.g(); + } catch (SocketTimeoutException sockettimeoutexception) { + this.g(); + } catch (IOException ioexception) { + if (this.a) { + this.b("IO: " + ioexception.getMessage()); + } + } + } + } finally { + this.b(this.k); + } + + } + + public void a() { + if (0 == this.l.length()) { + this.c("No rcon password set in \'" + this.b.b() + "\', rcon disabled!"); + } else if (0 < this.h && '\uffff' >= this.h) { + if (!this.a) { + try { + this.k = new ServerSocket(this.h, 0, InetAddress.getByName(this.j)); + this.k.setSoTimeout(500); + super.a(); + } catch (IOException ioexception) { + this.c("Unable to initialise rcon on " + this.j + ":" + this.h + " : " + ioexception.getMessage()); + } + + } + } else { + this.c("Invalid rcon port " + this.h + " found in \'" + this.b.b() + "\', rcon disabled!"); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/RemoteControlSession.java b/azurite-server/src/main/java/net/minecraft/server/RemoteControlSession.java new file mode 100644 index 0000000..5c46e8c --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/RemoteControlSession.java @@ -0,0 +1,144 @@ +package net.minecraft.server; + +import java.io.BufferedInputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.net.Socket; +import java.net.SocketTimeoutException; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +public class RemoteControlSession extends RemoteConnectionThread { + + private static final Logger h = LogManager.getLogger(); + private boolean i; + private Socket j; + private byte[] k = new byte[1460]; + private String l; + + RemoteControlSession(IMinecraftServer iminecraftserver, Socket socket) { + super(iminecraftserver, "RCON Client"); + this.j = socket; + + try { + this.j.setSoTimeout(0); + } catch (Exception exception) { + this.a = false; + } + + this.l = iminecraftserver.a("rcon.password", ""); + this.b("Rcon connection from: " + socket.getInetAddress()); + } + + public void run() { + try { + while (true) { + if (!this.a) { + break; + } + + BufferedInputStream bufferedinputstream = new BufferedInputStream(this.j.getInputStream()); + int i = bufferedinputstream.read(this.k, 0, 1460); + + if (10 <= i) { + byte b0 = 0; + int j = StatusChallengeUtils.b(this.k, 0, i); + + if (j != i - 4) { + return; + } + + int k = b0 + 4; + int l = StatusChallengeUtils.b(this.k, k, i); + + k += 4; + int i1 = StatusChallengeUtils.b(this.k, k); + + k += 4; + switch (i1) { + case 2: + if (this.i) { + String s = StatusChallengeUtils.a(this.k, k, i); + + try { + this.a(l, this.b.executeRemoteCommand(s)); + } catch (Exception exception) { + this.a(l, "Error executing: " + s + " (" + exception.getMessage() + ")"); + } + break; + } + + this.f(); + break; + + case 3: + String s1 = StatusChallengeUtils.a(this.k, k, i); + int j1 = k + s1.length(); + + if (0 != s1.length() && s1.equals(this.l)) { + this.i = true; + this.a(l, 2, ""); + break; + } + + this.i = false; + this.f(); + break; + + default: + this.a(l, String.format("Unknown request %s", new Object[] { Integer.toHexString(i1)})); + } + } + } + } catch (IOException ioexception) { + } catch (Exception exception1) { + RemoteControlSession.h.error("Exception whilst parsing RCON input", exception1); + } finally { + this.g(); + } + } + + private void a(int i, int j, String s) throws IOException { + ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream(1248); + DataOutputStream dataoutputstream = new DataOutputStream(bytearrayoutputstream); + byte[] abyte = s.getBytes("UTF-8"); + + dataoutputstream.writeInt(Integer.reverseBytes(abyte.length + 10)); + dataoutputstream.writeInt(Integer.reverseBytes(i)); + dataoutputstream.writeInt(Integer.reverseBytes(j)); + dataoutputstream.write(abyte); + dataoutputstream.write(0); + dataoutputstream.write(0); + this.j.getOutputStream().write(bytearrayoutputstream.toByteArray()); + } + + private void f() throws IOException { + this.a(-1, 2, ""); + } + + private void a(int i, String s) throws IOException { + int j = s.length(); + + do { + int k = 4096 <= j ? 4096 : j; + + this.a(i, 0, s.substring(0, k)); + s = s.substring(k); + j = s.length(); + } while (0 != j); + + } + + private void g() { + if (null != this.j) { + try { + this.j.close(); + } catch (IOException ioexception) { + this.c("IO: " + ioexception.getMessage()); + } + + this.j = null; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/RemoteStatusListener.java b/azurite-server/src/main/java/net/minecraft/server/RemoteStatusListener.java new file mode 100644 index 0000000..82c97f2 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/RemoteStatusListener.java @@ -0,0 +1,331 @@ +package net.minecraft.server; + +import com.google.common.collect.Maps; +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; +import java.net.PortUnreachableException; +import java.net.SocketAddress; +import java.net.SocketException; +import java.net.SocketTimeoutException; +import java.net.UnknownHostException; +import java.util.Date; +import java.util.Iterator; +import java.util.Map; +import java.util.Random; +import java.util.Map.Entry; + +public class RemoteStatusListener extends RemoteConnectionThread { + + private long h; + private int i; + private int j; + private int k; + private String l; + private String m; + private DatagramSocket n; + private byte[] o = new byte[1460]; + private DatagramPacket p; + private Map q; + private String r; + private String s; + private Map t; + private long u; + private RemoteStatusReply v; + private long w; + + public RemoteStatusListener(IMinecraftServer iminecraftserver) { + super(iminecraftserver, "Query Listener"); + this.i = iminecraftserver.a("query.port", 0); + this.s = iminecraftserver.E(); + this.j = iminecraftserver.F(); + this.l = iminecraftserver.G(); + this.k = iminecraftserver.J(); + this.m = iminecraftserver.U(); + this.w = 0L; + this.r = "0.0.0.0"; + if (0 != this.s.length() && !this.r.equals(this.s)) { + this.r = this.s; + } else { + this.s = "0.0.0.0"; + + try { + InetAddress inetaddress = InetAddress.getLocalHost(); + + this.r = inetaddress.getHostAddress(); + } catch (UnknownHostException unknownhostexception) { + this.c("Unable to determine local host IP, please set server-ip in \'" + iminecraftserver.b() + "\' : " + unknownhostexception.getMessage()); + } + } + + if (0 == this.i) { + this.i = this.j; + this.b("Setting default query port to " + this.i); + iminecraftserver.a("query.port", (Object) Integer.valueOf(this.i)); + iminecraftserver.a("debug", (Object) Boolean.valueOf(false)); + iminecraftserver.a(); + } + + this.q = Maps.newHashMap(); + this.v = new RemoteStatusReply(1460); + this.t = Maps.newHashMap(); + this.u = (new Date()).getTime(); + } + + private void a(byte[] abyte, DatagramPacket datagrampacket) throws IOException { + this.n.send(new DatagramPacket(abyte, abyte.length, datagrampacket.getSocketAddress())); + } + + private boolean a(DatagramPacket datagrampacket) throws IOException { + byte[] abyte = datagrampacket.getData(); + int i = datagrampacket.getLength(); + SocketAddress socketaddress = datagrampacket.getSocketAddress(); + + this.a("Packet len " + i + " [" + socketaddress + "]"); + if (3 <= i && -2 == abyte[0] && -3 == abyte[1]) { + this.a("Packet \'" + StatusChallengeUtils.a(abyte[2]) + "\' [" + socketaddress + "]"); + switch (abyte[2]) { + case 0: + if (!this.c(datagrampacket).booleanValue()) { + this.a("Invalid challenge [" + socketaddress + "]"); + return false; + } else if (15 == i) { + this.a(this.b(datagrampacket), datagrampacket); + this.a("Rules [" + socketaddress + "]"); + } else { + RemoteStatusReply remotestatusreply = new RemoteStatusReply(1460); + + remotestatusreply.a((int) 0); + remotestatusreply.a(this.a(datagrampacket.getSocketAddress())); + remotestatusreply.a(this.l); + remotestatusreply.a("SMP"); + remotestatusreply.a(this.m); + remotestatusreply.a(Integer.toString(this.d())); + remotestatusreply.a(Integer.toString(this.k)); + remotestatusreply.a((short) this.j); + remotestatusreply.a(this.r); + this.a(remotestatusreply.a(), datagrampacket); + this.a("Status [" + socketaddress + "]"); + } + + default: + return true; + + case 9: + this.d(datagrampacket); + this.a("Challenge [" + socketaddress + "]"); + return true; + } + } else { + this.a("Invalid packet [" + socketaddress + "]"); + return false; + } + } + + private byte[] b(DatagramPacket datagrampacket) throws IOException { + long i = MinecraftServer.az(); + + if (i < this.w + 5000L) { + byte[] abyte = this.v.a(); + byte[] abyte1 = this.a(datagrampacket.getSocketAddress()); + + abyte[1] = abyte1[0]; + abyte[2] = abyte1[1]; + abyte[3] = abyte1[2]; + abyte[4] = abyte1[3]; + return abyte; + } else { + this.w = i; + this.v.b(); + this.v.a((int) 0); + this.v.a(this.a(datagrampacket.getSocketAddress())); + this.v.a("splitnum"); + this.v.a((int) 128); + this.v.a((int) 0); + this.v.a("hostname"); + this.v.a(this.l); + this.v.a("gametype"); + this.v.a("SMP"); + this.v.a("game_id"); + this.v.a("MINECRAFT"); + this.v.a("version"); + this.v.a(this.b.getVersion()); + this.v.a("plugins"); + this.v.a(this.b.getPlugins()); + this.v.a("map"); + this.v.a(this.m); + this.v.a("numplayers"); + this.v.a("" + this.d()); + this.v.a("maxplayers"); + this.v.a("" + this.k); + this.v.a("hostport"); + this.v.a("" + this.j); + this.v.a("hostip"); + this.v.a(this.r); + this.v.a((int) 0); + this.v.a((int) 1); + this.v.a("player_"); + this.v.a((int) 0); + String[] astring = this.b.getPlayers(); + String[] astring1 = astring; + int j = astring.length; + + for (int k = 0; k < j; ++k) { + String s = astring1[k]; + + this.v.a(s); + } + + this.v.a((int) 0); + return this.v.a(); + } + } + + private byte[] a(SocketAddress socketaddress) { + return ((RemoteStatusListener.RemoteStatusChallenge) this.t.get(socketaddress)).c(); + } + + private Boolean c(DatagramPacket datagrampacket) { + SocketAddress socketaddress = datagrampacket.getSocketAddress(); + + if (!this.t.containsKey(socketaddress)) { + return Boolean.valueOf(false); + } else { + byte[] abyte = datagrampacket.getData(); + + return ((RemoteStatusListener.RemoteStatusChallenge) this.t.get(socketaddress)).a() != StatusChallengeUtils.c(abyte, 7, datagrampacket.getLength()) ? Boolean.valueOf(false) : Boolean.valueOf(true); + } + } + + private void d(DatagramPacket datagrampacket) throws IOException { + RemoteStatusListener.RemoteStatusChallenge remotestatuslistener_remotestatuschallenge = new RemoteStatusListener.RemoteStatusChallenge(datagrampacket); + + this.t.put(datagrampacket.getSocketAddress(), remotestatuslistener_remotestatuschallenge); + this.a(remotestatuslistener_remotestatuschallenge.b(), datagrampacket); + } + + private void f() { + if (this.a) { + long i = MinecraftServer.az(); + + if (i >= this.h + 30000L) { + this.h = i; + Iterator iterator = this.t.entrySet().iterator(); + + while (iterator.hasNext()) { + Entry entry = (Entry) iterator.next(); + + if (((RemoteStatusListener.RemoteStatusChallenge) entry.getValue()).a(i).booleanValue()) { + iterator.remove(); + } + } + + } + } + } + + public void run() { + this.b("Query running on " + this.s + ":" + this.i); + this.h = MinecraftServer.az(); + this.p = new DatagramPacket(this.o, this.o.length); + + try { + while (this.a) { + try { + this.n.receive(this.p); + this.f(); + this.a(this.p); + } catch (SocketTimeoutException sockettimeoutexception) { + this.f(); + } catch (PortUnreachableException portunreachableexception) { + ; + } catch (IOException ioexception) { + this.a((Exception) ioexception); + } + } + } finally { + this.e(); + } + + } + + public void a() { + if (!this.a) { + if (0 < this.i && '\uffff' >= this.i) { + if (this.g()) { + super.a(); + } + + } else { + this.c("Invalid query port " + this.i + " found in \'" + this.b.b() + "\' (queries disabled)"); + } + } + } + + private void a(Exception exception) { + if (this.a) { + this.c("Unexpected exception, buggy JRE? (" + exception.toString() + ")"); + if (!this.g()) { + this.d("Failed to recover from buggy JRE, shutting down!"); + this.a = false; + } + + } + } + + private boolean g() { + try { + this.n = new DatagramSocket(this.i, InetAddress.getByName(this.s)); + this.a(this.n); + this.n.setSoTimeout(500); + return true; + } catch (SocketException socketexception) { + this.c("Unable to initialise query system on " + this.s + ":" + this.i + " (Socket): " + socketexception.getMessage()); + } catch (UnknownHostException unknownhostexception) { + this.c("Unable to initialise query system on " + this.s + ":" + this.i + " (Unknown Host): " + unknownhostexception.getMessage()); + } catch (Exception exception) { + this.c("Unable to initialise query system on " + this.s + ":" + this.i + " (E): " + exception.getMessage()); + } + + return false; + } + + class RemoteStatusChallenge { + + private long time = (new Date()).getTime(); + private int token; + private byte[] identity; + private byte[] response; + private String f; + + public RemoteStatusChallenge(DatagramPacket datagrampacket) { + byte[] abyte = datagrampacket.getData(); + + this.identity = new byte[4]; + this.identity[0] = abyte[3]; + this.identity[1] = abyte[4]; + this.identity[2] = abyte[5]; + this.identity[3] = abyte[6]; + this.f = new String(this.identity); + this.token = (new Random()).nextInt(16777216); + this.response = String.format("\t%s%d\u0000", new Object[] { this.f, Integer.valueOf(this.token)}).getBytes(); + } + + public Boolean a(long i) { + return Boolean.valueOf(this.time < i); + } + + public int a() { + return this.token; + } + + public byte[] b() { + return this.response; + } + + public byte[] c() { + return this.identity; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/RemoteStatusReply.java b/azurite-server/src/main/java/net/minecraft/server/RemoteStatusReply.java new file mode 100644 index 0000000..a1dbd1e --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/RemoteStatusReply.java @@ -0,0 +1,41 @@ +package net.minecraft.server; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; + +public class RemoteStatusReply { + + private ByteArrayOutputStream buffer; + private DataOutputStream stream; + + public RemoteStatusReply(int i) { + this.buffer = new ByteArrayOutputStream(i); + this.stream = new DataOutputStream(this.buffer); + } + + public void a(byte[] abyte) throws IOException { + this.stream.write(abyte, 0, abyte.length); + } + + public void a(String s) throws IOException { + this.stream.writeBytes(s); + this.stream.write(0); + } + + public void a(int i) throws IOException { + this.stream.write(i); + } + + public void a(short short0) throws IOException { + this.stream.writeShort(Short.reverseBytes(short0)); + } + + public byte[] a() { + return this.buffer.toByteArray(); + } + + public void b() { + this.buffer.reset(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ReportedException.java b/azurite-server/src/main/java/net/minecraft/server/ReportedException.java new file mode 100644 index 0000000..434854e --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ReportedException.java @@ -0,0 +1,22 @@ +package net.minecraft.server; + +public class ReportedException extends RuntimeException { + + private final CrashReport a; + + public ReportedException(CrashReport crashreport) { + this.a = crashreport; + } + + public CrashReport a() { + return this.a; + } + + public Throwable getCause() { + return this.a.b(); + } + + public String getMessage() { + return this.a.a(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/Scoreboard.java b/azurite-server/src/main/java/net/minecraft/server/Scoreboard.java new file mode 100644 index 0000000..7c01c5a --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/Scoreboard.java @@ -0,0 +1,362 @@ +package net.minecraft.server; + +import com.eatthepath.uuid.FastUUID; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; + +import java.util.*; + +public class Scoreboard { + + private final Map objectivesByName = Maps.newHashMap(); + protected Set viewers; + private final Map> objectivesByCriteria = Maps.newHashMap(); + private final Map> playerScores = Maps.newHashMap(); + private final ScoreboardObjective[] displaySlots = new ScoreboardObjective[19]; + private final Map teamsByName = Maps.newHashMap(); + private final Map teamsByPlayer = Maps.newHashMap(); + private static String[] g = null; + + public Scoreboard() { + } + + public ScoreboardObjective getObjective(String s) { + return this.objectivesByName.get(s); + } + + public void addViewer(EntityPlayer player) { + if (viewers == null) viewers = Collections.newSetFromMap(new WeakHashMap<>()); // Beanes - for some reason this memory leaks, not sure why the removeViewer isn't called so to counteract this we make a weak set of it + viewers.add(player); + } + + public void removeViewer(EntityPlayer player) { + if (viewers != null && viewers.remove(player) && viewers.isEmpty()) + viewers = null; + } + + public ScoreboardObjective registerObjective(String s, IScoreboardCriteria iscoreboardcriteria) { + if (s.length() > 16) { + throw new IllegalArgumentException("The objective name '" + s + "' is too long!"); + } else { + ScoreboardObjective scoreboardobjective = this.getObjective(s); + + if (scoreboardobjective != null) { + throw new IllegalArgumentException("An objective with the name '" + s + "' already exists!"); + } else { + scoreboardobjective = new ScoreboardObjective(this, s, iscoreboardcriteria); + objectivesByCriteria.computeIfAbsent(iscoreboardcriteria, k -> Lists.newArrayList()).add(scoreboardobjective); + this.objectivesByName.put(s, scoreboardobjective); + this.handleObjectiveAdded(scoreboardobjective); + return scoreboardobjective; + } + } + } + + public Collection getObjectivesForCriteria(IScoreboardCriteria iscoreboardcriteria) { + Collection collection = this.objectivesByCriteria.get(iscoreboardcriteria); + + return collection == null ? Lists.newArrayList() : Lists.newArrayList(collection); + } + + public boolean b(String s, ScoreboardObjective scoreboardobjective) { + Map map = this.playerScores.get(s); + + if (map == null) { + return false; + } else { + ScoreboardScore scoreboardscore = map.get(scoreboardobjective); + + return scoreboardscore != null; + } + } + + public ScoreboardScore getPlayerScoreForObjective(String s, ScoreboardObjective scoreboardobjective) { + if (s.length() > 40) { + throw new IllegalArgumentException("The player name '" + s + "' is too long!"); + } else { + Map object = this.playerScores.computeIfAbsent(s, k -> Maps.newHashMap()); + + ScoreboardScore scoreboardscore = object.get(scoreboardobjective); + + if (scoreboardscore == null) { + scoreboardscore = new ScoreboardScore(this, scoreboardobjective, s); + object.put(scoreboardobjective, scoreboardscore); + } + + return scoreboardscore; + } + } + + public Collection getScoresForObjective(ScoreboardObjective scoreboardobjective) { + ArrayList arraylist = Lists.newArrayList(); + + for (Map map : this.playerScores.values()) { + ScoreboardScore scoreboardscore = map.get(scoreboardobjective); + + if (scoreboardscore != null) { + arraylist.add(scoreboardscore); + } + } + + arraylist.sort(ScoreboardScore.a); + return arraylist; + } + + public Collection getObjectives() { + return this.objectivesByName.values(); + } + + public Collection getPlayers() { + return this.playerScores.keySet(); + } + + public void resetPlayerScores(String s, ScoreboardObjective scoreboardobjective) { + Map map; + + if (scoreboardobjective == null) { + map = this.playerScores.remove(s); + if (map != null) { + this.handlePlayerRemoved(s); + } + } else { + map = this.playerScores.get(s); + if (map != null) { + ScoreboardScore scoreboardscore = map.remove(scoreboardobjective); + + if (map.size() < 1) { + if (playerScores.remove(s) != null) { + this.handlePlayerRemoved(s); + } + } else if (scoreboardscore != null) { + this.a(s, scoreboardobjective); + } + } + } + + } + + public Collection getScores() { + Collection> collection = this.playerScores.values(); + List arraylist = Lists.newArrayList(); + + for (Map map : collection) { + arraylist.addAll(map.values()); + } + + return arraylist; + } + + public Map getPlayerObjectives(String s) { + Map object = this.playerScores.get(s); + + if (object == null) { + object = Maps.newHashMap(); + } + + return object; + } + + public void unregisterObjective(ScoreboardObjective scoreboardobjective) { + this.objectivesByName.remove(scoreboardobjective.getName()); + + for (int i = 0; i < 19; ++i) { + if (this.getObjectiveForSlot(i) == scoreboardobjective) { + this.setDisplaySlot(i, null); + } + } + + List list = this.objectivesByCriteria.get(scoreboardobjective.getCriteria()); + + if (list != null) { + list.remove(scoreboardobjective); + } + + for (Map map : this.playerScores.values()) { + map.remove(scoreboardobjective); + } + + this.handleObjectiveRemoved(scoreboardobjective); + } + + public void setDisplaySlot(int i, ScoreboardObjective scoreboardobjective) { + this.displaySlots[i] = scoreboardobjective; + } + + public ScoreboardObjective getObjectiveForSlot(int i) { + return this.displaySlots[i]; + } + + public ScoreboardTeam getTeam(String s) { + return this.teamsByName.get(s); + } + + public ScoreboardTeam createTeam(String s) { + if (s.length() > 16) { + throw new IllegalArgumentException("The team name '" + s + "' is too long!"); + } else { + ScoreboardTeam scoreboardteam = this.getTeam(s); + + if (scoreboardteam != null) { + throw new IllegalArgumentException("A team with the name '" + s + "' already exists!"); + } else { + scoreboardteam = new ScoreboardTeam(this, s); + this.teamsByName.put(s, scoreboardteam); + this.handleTeamAdded(scoreboardteam); + return scoreboardteam; + } + } + } + + public void removeTeam(ScoreboardTeam scoreboardteam) { + this.teamsByName.remove(scoreboardteam.getName()); + + for (String s : scoreboardteam.getPlayerNameSet()) { + this.teamsByPlayer.remove(s); + } + + this.handleTeamRemoved(scoreboardteam); + } + + public boolean addPlayerToTeam(String s, String s1) { + if (s.length() > 40) { + throw new IllegalArgumentException("The player name '" + s + "' is too long!"); + } else if (!this.teamsByName.containsKey(s1)) { + return false; + } else { + ScoreboardTeam scoreboardteam = this.getTeam(s1); + + if (this.getPlayerTeam(s) != null) { + this.removePlayerFromTeam(s); + } + + this.teamsByPlayer.put(s, scoreboardteam); + scoreboardteam.getPlayerNameSet().add(s); + return true; + } + } + + public boolean removePlayerFromTeam(String s) { + ScoreboardTeam scoreboardteam = this.getPlayerTeam(s); + + if (scoreboardteam != null) { + this.removePlayerFromTeam(s, scoreboardteam); + return true; + } else { + return false; + } + } + + public void removePlayerFromTeam(String s, ScoreboardTeam scoreboardteam) { + if (this.getPlayerTeam(s) != scoreboardteam) { + throw new IllegalStateException("Player is either on another team or not on any team. Cannot remove from team \'" + scoreboardteam.getName() + "\'."); + } else { + this.teamsByPlayer.remove(s); + scoreboardteam.getPlayerNameSet().remove(s); + } + } + + public Collection getTeamNames() { + return this.teamsByName.keySet(); + } + + public Collection getTeams() { + return this.teamsByName.values(); + } + + public ScoreboardTeam getPlayerTeam(String s) { + return this.teamsByPlayer.get(s); + } + + public void handleObjectiveAdded(ScoreboardObjective scoreboardobjective) { + } + + public void handleObjectiveChanged(ScoreboardObjective scoreboardobjective) { + } + + public void handleObjectiveRemoved(ScoreboardObjective scoreboardobjective) { + } + + public void handleScoreChanged(ScoreboardScore scoreboardscore) { + } + + public void handlePlayerRemoved(String s) { + } + + public void a(String s, ScoreboardObjective scoreboardobjective) { + } + + public void handleTeamAdded(ScoreboardTeam scoreboardteam) { + } + + public void handleTeamChanged(ScoreboardTeam scoreboardteam) { + } + + public void handleTeamRemoved(ScoreboardTeam scoreboardteam) { + } + + public static String getSlotName(int i) { + switch (i) { + case 0: + return "list"; + + case 1: + return "sidebar"; + + case 2: + return "belowName"; + + default: + if (i >= 3 && i <= 18) { + EnumChatFormat enumchatformat = EnumChatFormat.a(i - 3); + + if (enumchatformat != null && enumchatformat != EnumChatFormat.RESET) { + return "sidebar.team." + enumchatformat.e(); + } + } + + return null; + } + } + + public static int getSlotForName(String s) { + if (s.equalsIgnoreCase("list")) { + return 0; + } else if (s.equalsIgnoreCase("sidebar")) { + return 1; + } else if (s.equalsIgnoreCase("belowName")) { + return 2; + } else { + if (s.startsWith("sidebar.team.")) { + String s1 = s.substring("sidebar.team.".length()); + EnumChatFormat enumchatformat = EnumChatFormat.b(s1); + + if (enumchatformat != null && enumchatformat.b() >= 0) { + return enumchatformat.b() + 3; + } + } + + return -1; + } + } + + public static String[] h() { + if (Scoreboard.g == null) { + Scoreboard.g = new String[19]; + + for (int i = 0; i < 19; ++i) { + Scoreboard.g[i] = getSlotName(i); + } + } + + return Scoreboard.g; + } + + public void a(Entity entity) { + if (entity != null && !(entity instanceof EntityHuman) && !entity.isAlive()) { + String s = FastUUID.toString(entity.getUniqueID()); + + this.resetPlayerScores(s, null); + this.removePlayerFromTeam(s); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ScoreboardBaseCriteria.java b/azurite-server/src/main/java/net/minecraft/server/ScoreboardBaseCriteria.java new file mode 100644 index 0000000..72422ec --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ScoreboardBaseCriteria.java @@ -0,0 +1,29 @@ +package net.minecraft.server; + +import java.util.List; + +public class ScoreboardBaseCriteria implements IScoreboardCriteria { + + private final String j; + + public ScoreboardBaseCriteria(String s) { + this.j = s; + IScoreboardCriteria.criteria.put(s, this); + } + + public String getName() { + return this.j; + } + + public int getScoreModifier(List list) { + return 0; + } + + public boolean isReadOnly() { + return false; + } + + public IScoreboardCriteria.EnumScoreboardHealthDisplay c() { + return IScoreboardCriteria.EnumScoreboardHealthDisplay.INTEGER; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ScoreboardCriteriaInteger.java b/azurite-server/src/main/java/net/minecraft/server/ScoreboardCriteriaInteger.java new file mode 100644 index 0000000..9e8111d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ScoreboardCriteriaInteger.java @@ -0,0 +1,29 @@ +package net.minecraft.server; + +import java.util.List; + +public class ScoreboardCriteriaInteger implements IScoreboardCriteria { + + private final String j; + + public ScoreboardCriteriaInteger(String s, EnumChatFormat enumchatformat) { + this.j = s + enumchatformat.e(); + IScoreboardCriteria.criteria.put(this.j, this); + } + + public String getName() { + return this.j; + } + + public int getScoreModifier(List list) { + return 0; + } + + public boolean isReadOnly() { + return false; + } + + public IScoreboardCriteria.EnumScoreboardHealthDisplay c() { + return IScoreboardCriteria.EnumScoreboardHealthDisplay.INTEGER; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ScoreboardHealthCriteria.java b/azurite-server/src/main/java/net/minecraft/server/ScoreboardHealthCriteria.java new file mode 100644 index 0000000..18d489a --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ScoreboardHealthCriteria.java @@ -0,0 +1,35 @@ +package net.minecraft.server; + +import java.util.Iterator; +import java.util.List; + +public class ScoreboardHealthCriteria extends ScoreboardBaseCriteria { + + public ScoreboardHealthCriteria(String s) { + super(s); + } + + public int getScoreModifier(List list) { + float f = 0.0F; + + EntityHuman entityhuman; + + for (Iterator iterator = list.iterator(); iterator.hasNext(); f += entityhuman.getHealth() + entityhuman.getAbsorptionHearts()) { + entityhuman = (EntityHuman) iterator.next(); + } + + if (list.size() > 0) { + f /= (float) list.size(); + } + + return MathHelper.f(f); + } + + public boolean isReadOnly() { + return true; + } + + public IScoreboardCriteria.EnumScoreboardHealthDisplay c() { + return IScoreboardCriteria.EnumScoreboardHealthDisplay.HEARTS; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ScoreboardObjective.java b/azurite-server/src/main/java/net/minecraft/server/ScoreboardObjective.java new file mode 100644 index 0000000..791fc18 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ScoreboardObjective.java @@ -0,0 +1,44 @@ +package net.minecraft.server; + +public class ScoreboardObjective { + + private final Scoreboard a; + private final String b; + private final IScoreboardCriteria c; + private IScoreboardCriteria.EnumScoreboardHealthDisplay d; + private String e; + + public ScoreboardObjective(Scoreboard scoreboard, String s, IScoreboardCriteria iscoreboardcriteria) { + this.a = scoreboard; + this.b = s; + this.c = iscoreboardcriteria; + this.e = s; + this.d = iscoreboardcriteria.c(); + } + + public String getName() { + return this.b; + } + + public IScoreboardCriteria getCriteria() { + return this.c; + } + + public String getDisplayName() { + return this.e; + } + + public void setDisplayName(String s) { + this.e = s; + this.a.handleObjectiveChanged(this); + } + + public IScoreboardCriteria.EnumScoreboardHealthDisplay e() { + return this.d; + } + + public void a(IScoreboardCriteria.EnumScoreboardHealthDisplay iscoreboardcriteria_enumscoreboardhealthdisplay) { + this.d = iscoreboardcriteria_enumscoreboardhealthdisplay; + this.a.handleObjectiveChanged(this); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ScoreboardScore.java b/azurite-server/src/main/java/net/minecraft/server/ScoreboardScore.java new file mode 100644 index 0000000..712a7da --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ScoreboardScore.java @@ -0,0 +1,93 @@ +package net.minecraft.server; + +import java.util.Comparator; +import java.util.List; + +public class ScoreboardScore { + + public static final Comparator a = new Comparator() { + public int a(ScoreboardScore scoreboardscore, ScoreboardScore scoreboardscore1) { + return scoreboardscore.getScore() > scoreboardscore1.getScore() ? 1 : (scoreboardscore.getScore() < scoreboardscore1.getScore() ? -1 : scoreboardscore1.getPlayerName().compareToIgnoreCase(scoreboardscore.getPlayerName())); + } + + public int compare(Object object, Object object1) { + return this.a((ScoreboardScore) object, (ScoreboardScore) object1); + } + }; + private final Scoreboard b; + private final ScoreboardObjective c; + private final String playerName; + private int score; + private boolean f; + private boolean g; + + public ScoreboardScore(Scoreboard scoreboard, ScoreboardObjective scoreboardobjective, String s) { + this.b = scoreboard; + this.c = scoreboardobjective; + this.playerName = s; + this.g = true; + } + + public void addScore(int i) { + if (this.c.getCriteria().isReadOnly()) { + throw new IllegalStateException("Cannot modify read-only score"); + } else { + this.setScore(this.getScore() + i); + } + } + + public void removeScore(int i) { + if (this.c.getCriteria().isReadOnly()) { + throw new IllegalStateException("Cannot modify read-only score"); + } else { + this.setScore(this.getScore() - i); + } + } + + public void incrementScore() { + if (this.c.getCriteria().isReadOnly()) { + throw new IllegalStateException("Cannot modify read-only score"); + } else { + this.addScore(1); + } + } + + public int getScore() { + return this.score; + } + + public void setScore(int i) { + int j = this.score; + + this.score = i; + if (j != i || this.g) { + this.g = false; + this.f().handleScoreChanged(this); + } + + } + + public ScoreboardObjective getObjective() { + return this.c; + } + + public String getPlayerName() { + return this.playerName; + } + + public Scoreboard f() { + return this.b; + } + + public boolean g() { + return this.f; + } + + public void a(boolean flag) { + this.f = flag; + } + + public void updateForList(List list) { + setScore(c.getCriteria().getScoreModifier(list)); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ScoreboardServer.java b/azurite-server/src/main/java/net/minecraft/server/ScoreboardServer.java new file mode 100644 index 0000000..d56a020 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ScoreboardServer.java @@ -0,0 +1,209 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Set; + +public class ScoreboardServer extends Scoreboard { + + private final Set b = Sets.newHashSet(); + private PersistentScoreboard c; + + public ScoreboardServer(MinecraftServer minecraftserver) { + } + + public void handleScoreChanged(ScoreboardScore scoreboardscore) { + super.handleScoreChanged(scoreboardscore); + if (this.b.contains(scoreboardscore.getObjective())) { + this.sendAll(new PacketPlayOutScoreboardScore(scoreboardscore)); + } + + this.b(); + } + + public void handlePlayerRemoved(String s) { + super.handlePlayerRemoved(s); + this.sendAll(new PacketPlayOutScoreboardScore(s)); + this.b(); + } + + public void a(String s, ScoreboardObjective scoreboardobjective) { + super.a(s, scoreboardobjective); + this.sendAll(new PacketPlayOutScoreboardScore(s, scoreboardobjective)); + this.b(); + } + + public void setDisplaySlot(int i, ScoreboardObjective scoreboardobjective) { + ScoreboardObjective scoreboardobjective1 = this.getObjectiveForSlot(i); + + super.setDisplaySlot(i, scoreboardobjective); + if (scoreboardobjective1 != scoreboardobjective && scoreboardobjective1 != null) { + if (this.h(scoreboardobjective1) > 0) { + this.sendAll(new PacketPlayOutScoreboardDisplayObjective(i, scoreboardobjective)); + } else { + this.g(scoreboardobjective1); + } + } + + if (scoreboardobjective != null) { + if (this.b.contains(scoreboardobjective)) { + this.sendAll(new PacketPlayOutScoreboardDisplayObjective(i, scoreboardobjective)); + } else { + this.e(scoreboardobjective); + } + } + + this.b(); + } + + public boolean addPlayerToTeam(String s, String s1) { + if (super.addPlayerToTeam(s, s1)) { + ScoreboardTeam scoreboardteam = this.getTeam(s1); + + this.sendAll(new PacketPlayOutScoreboardTeam(scoreboardteam, Collections.singletonList(s), 3)); + this.b(); + return true; + } else { + return false; + } + } + + public void removePlayerFromTeam(String s, ScoreboardTeam scoreboardteam) { + super.removePlayerFromTeam(s, scoreboardteam); + this.sendAll(new PacketPlayOutScoreboardTeam(scoreboardteam, Collections.singletonList(s), 4)); + this.b(); + } + + public void handleObjectiveAdded(ScoreboardObjective scoreboardobjective) { + super.handleObjectiveAdded(scoreboardobjective); + this.b(); + } + + public void handleObjectiveChanged(ScoreboardObjective scoreboardobjective) { + super.handleObjectiveChanged(scoreboardobjective); + if (this.b.contains(scoreboardobjective)) { + this.sendAll(new PacketPlayOutScoreboardObjective(scoreboardobjective, 2)); + } + + this.b(); + } + + public void handleObjectiveRemoved(ScoreboardObjective scoreboardobjective) { + super.handleObjectiveRemoved(scoreboardobjective); + if (this.b.contains(scoreboardobjective)) { + this.g(scoreboardobjective); + } + + this.b(); + } + + public void handleTeamAdded(ScoreboardTeam scoreboardteam) { + super.handleTeamAdded(scoreboardteam); + this.sendAll(new PacketPlayOutScoreboardTeam(scoreboardteam, 0)); + this.b(); + } + + public void handleTeamChanged(ScoreboardTeam scoreboardteam) { + super.handleTeamChanged(scoreboardteam); + this.sendAll(new PacketPlayOutScoreboardTeam(scoreboardteam, 2)); + this.b(); + } + + public void handleTeamRemoved(ScoreboardTeam scoreboardteam) { + super.handleTeamRemoved(scoreboardteam); + this.sendAll(new PacketPlayOutScoreboardTeam(scoreboardteam, 1)); + this.b(); + } + + public void a(PersistentScoreboard persistentscoreboard) { + this.c = persistentscoreboard; + } + + protected void b() { + if (this.c != null) { + this.c.c(); + } + + } + + public List> getScoreboardScorePacketsForObjective(ScoreboardObjective scoreboardobjective) { + ArrayList> arraylist = Lists.newArrayList(); + + arraylist.add(new PacketPlayOutScoreboardObjective(scoreboardobjective, 0)); + + for (int i = 0; i < 19; ++i) { + if (this.getObjectiveForSlot(i) == scoreboardobjective) { + arraylist.add(new PacketPlayOutScoreboardDisplayObjective(i, scoreboardobjective)); + } + } + + for (ScoreboardScore scoreboardScore : this.getScoresForObjective(scoreboardobjective)) { + arraylist.add(new PacketPlayOutScoreboardScore(scoreboardScore)); + } + + return arraylist; + } + + public void e(ScoreboardObjective scoreboardobjective) { + List> list = this.getScoreboardScorePacketsForObjective(scoreboardobjective); + + if (viewers != null) + for (EntityPlayer entityplayer : viewers) { + for (Packet packet : list) { + entityplayer.playerConnection.sendPacket(packet); + } + } + + this.b.add(scoreboardobjective); + } + + public List> f(ScoreboardObjective scoreboardobjective) { + ArrayList> arraylist = Lists.newArrayList(); + + arraylist.add(new PacketPlayOutScoreboardObjective(scoreboardobjective, 1)); + + for (int i = 0; i < 19; ++i) { + if (this.getObjectiveForSlot(i) == scoreboardobjective) { + arraylist.add(new PacketPlayOutScoreboardDisplayObjective(i, scoreboardobjective)); + } + } + + return arraylist; + } + + public void g(ScoreboardObjective scoreboardobjective) { + List> list = this.f(scoreboardobjective); + + if (viewers != null) + for (EntityPlayer entityplayer : viewers) { + for (Packet packet : list) { + entityplayer.playerConnection.sendPacket(packet); + } + } + + this.b.remove(scoreboardobjective); + } + + public int h(ScoreboardObjective scoreboardobjective) { + int i = 0; + + for (int j = 0; j < 19; ++j) { + if (this.getObjectiveForSlot(j) == scoreboardobjective) { + ++i; + } + } + + return i; + } + + // CraftBukkit start - Send to players + private void sendAll(Packet packet) { + if (viewers != null) + for (EntityPlayer entityplayer : viewers) entityplayer.playerConnection.sendPacket(packet); + } + // CraftBukkit end +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ScoreboardStatisticCriteria.java b/azurite-server/src/main/java/net/minecraft/server/ScoreboardStatisticCriteria.java new file mode 100644 index 0000000..e1e3bc0 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ScoreboardStatisticCriteria.java @@ -0,0 +1,11 @@ +package net.minecraft.server; + +public class ScoreboardStatisticCriteria extends ScoreboardBaseCriteria { + + private final Statistic j; + + public ScoreboardStatisticCriteria(Statistic statistic) { + super(statistic.name); + this.j = statistic; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ScoreboardTeam.java b/azurite-server/src/main/java/net/minecraft/server/ScoreboardTeam.java new file mode 100644 index 0000000..11944a2 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ScoreboardTeam.java @@ -0,0 +1,148 @@ +package net.minecraft.server; + +import com.google.common.collect.Sets; + +import java.util.Collection; +import java.util.Set; + +public class ScoreboardTeam extends ScoreboardTeamBase { + + private final Scoreboard a; + private final String b; + private final Set c = Sets.newHashSet(); + private String d; + private String e = ""; + private String f = ""; + private boolean g = true; + private boolean h = true; + private EnumNameTagVisibility i; + private EnumNameTagVisibility j; + private EnumChatFormat k; + private boolean tagVisible = true; + + public ScoreboardTeam(Scoreboard scoreboard, String s) { + this.i = EnumNameTagVisibility.ALWAYS; + this.j = EnumNameTagVisibility.ALWAYS; + this.k = EnumChatFormat.RESET; + this.a = scoreboard; + this.b = s; + this.d = s; + } + + public String getName() { + return this.b; + } + + public String getDisplayName() { + return this.d; + } + + public void setDisplayName(String s) { + if (s == null) { + throw new IllegalArgumentException("Name cannot be null"); + } else { + this.d = s; + this.a.handleTeamChanged(this); + } + } + + public Collection getPlayerNameSet() { + return this.c; + } + + public String getPrefix() { + return this.e; + } + + public void setPrefix(String s) { + if (s == null) { + throw new IllegalArgumentException("Prefix cannot be null"); + } else { + this.e = s; + this.a.handleTeamChanged(this); + } + } + + public String getSuffix() { + return this.f; + } + + public void setSuffix(String s) { + this.f = s; + this.a.handleTeamChanged(this); + } + + public String getFormattedName(String s) { + return this.getPrefix() + s + this.getSuffix(); + } + + public static String getPlayerDisplayName(ScoreboardTeamBase scoreboardteambase, String s) { + return scoreboardteambase == null ? s : scoreboardteambase.getFormattedName(s); + } + + public boolean allowFriendlyFire() { + return this.g; + } + + public void setAllowFriendlyFire(boolean flag) { + this.g = flag; + this.a.handleTeamChanged(this); + } + + public boolean canSeeFriendlyInvisibles() { + return this.h; + } + + public void setCanSeeFriendlyInvisibles(boolean flag) { + this.h = flag; + this.a.handleTeamChanged(this); + } + + public EnumNameTagVisibility getNameTagVisibility() { + return this.i; + } + + public EnumNameTagVisibility j() { + return this.j; + } + + public void setNameTagVisibility(EnumNameTagVisibility scoreboardteambase_enumnametagvisibility) { + this.i = scoreboardteambase_enumnametagvisibility; + this.a.handleTeamChanged(this); + } + + public void b(EnumNameTagVisibility scoreboardteambase_enumnametagvisibility) { + this.j = scoreboardteambase_enumnametagvisibility; + this.a.handleTeamChanged(this); + } + + public int packOptionData() { + int i = 0; + + if (this.allowFriendlyFire()) { + i |= 1; + } + + if (this.canSeeFriendlyInvisibles()) { + i |= 2; + } + + return i; + } + + public void a(EnumChatFormat enumchatformat) { + this.k = enumchatformat; + } + + public EnumChatFormat l() { + return this.k; + } + + public boolean isTagVisible() { + return this.tagVisible; + } + + public void setTagVisible(boolean tagVisible) { + this.tagVisible = tagVisible; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ScoreboardTeamBase.java b/azurite-server/src/main/java/net/minecraft/server/ScoreboardTeamBase.java new file mode 100644 index 0000000..a1452f3 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ScoreboardTeamBase.java @@ -0,0 +1,58 @@ +package net.minecraft.server; + +import com.google.common.collect.Maps; + +import java.util.Collection; +import java.util.Map; + +public abstract class ScoreboardTeamBase { + + public ScoreboardTeamBase() { + } + + public boolean isAlly(ScoreboardTeamBase scoreboardteambase) { + return this == scoreboardteambase; + } + + public abstract String getName(); + + public abstract String getFormattedName(String s); + + public abstract boolean allowFriendlyFire(); + + public abstract Collection getPlayerNameSet(); + + public abstract ScoreboardTeamBase.EnumNameTagVisibility j(); + + public enum EnumNameTagVisibility { + + ALWAYS("always", 0), NEVER("never", 1), HIDE_FOR_OTHER_TEAMS("hideForOtherTeams", 2), HIDE_FOR_OWN_TEAM("hideForOwnTeam", 3); + + private static final Map g = Maps.newHashMap(); + + static { + ScoreboardTeamBase.EnumNameTagVisibility[] ascoreboardteambase_enumnametagvisibility = values(); + + for (EnumNameTagVisibility scoreboardteambase_enumnametagvisibility : ascoreboardteambase_enumnametagvisibility) { + EnumNameTagVisibility.g.put(scoreboardteambase_enumnametagvisibility.e, scoreboardteambase_enumnametagvisibility); + } + + } + + public final String e; + public final int f; + + EnumNameTagVisibility(String s, int i) { + this.e = s; + this.f = i; + } + + public static String[] a() { + return EnumNameTagVisibility.g.keySet().toArray(new String[0]); + } + + public static ScoreboardTeamBase.EnumNameTagVisibility a(String s) { + return EnumNameTagVisibility.g.get(s); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/SecondaryWorldData.java b/azurite-server/src/main/java/net/minecraft/server/SecondaryWorldData.java new file mode 100644 index 0000000..252cfa6 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/SecondaryWorldData.java @@ -0,0 +1,134 @@ +package net.minecraft.server; + +public class SecondaryWorldData extends WorldData { + + private final WorldData b; + + public SecondaryWorldData(WorldData worlddata) { + this.b = worlddata; + } + + public NBTTagCompound a() { + return this.b.a(); + } + + public NBTTagCompound a(NBTTagCompound nbttagcompound) { + return this.b.a(nbttagcompound); + } + + public long getSeed() { + return this.b.getSeed(); + } + + public int c() { + return this.b.c(); + } + + public int d() { + return this.b.d(); + } + + public int e() { + return this.b.e(); + } + + public long getTime() { + return this.b.getTime(); + } + + public long getDayTime() { + return this.b.getDayTime(); + } + + public NBTTagCompound i() { + return this.b.i(); + } + + public String getName() { + return this.b.getName(); + } + + public int l() { + return this.b.l(); + } + + public boolean isThundering() { + return this.b.isThundering(); + } + + public int getThunderDuration() { + return this.b.getThunderDuration(); + } + + public boolean hasStorm() { + return this.b.hasStorm(); + } + + public int getWeatherDuration() { + return this.b.getWeatherDuration(); + } + + public WorldSettings.EnumGamemode getGameType() { + return this.b.getGameType(); + } + + public void setTime(long i) {} + + public void setDayTime(long i) {} + + public void setSpawn(BlockPosition blockposition) {} + + public void a(String s) {} + + public void e(int i) {} + + public void setThundering(boolean flag) {} + + public void setThunderDuration(int i) {} + + public void setStorm(boolean flag) {} + + public void setWeatherDuration(int i) {} + + public boolean shouldGenerateMapFeatures() { + return this.b.shouldGenerateMapFeatures(); + } + + public boolean isHardcore() { + return this.b.isHardcore(); + } + + public WorldType getType() { + return this.b.getType(); + } + + public void a(WorldType worldtype) {} + + public boolean v() { + return this.b.v(); + } + + public void c(boolean flag) {} + + public boolean w() { + return this.b.w(); + } + + public void d(boolean flag) {} + + public GameRules x() { + return this.b.x(); + } + + public EnumDifficulty getDifficulty() { + return this.b.getDifficulty(); + } + + public void setDifficulty(EnumDifficulty enumdifficulty) {} + + public boolean isDifficultyLocked() { + return this.b.isDifficultyLocked(); + } + + public void e(boolean flag) {} +} diff --git a/azurite-server/src/main/java/net/minecraft/server/SecondaryWorldServer.java b/azurite-server/src/main/java/net/minecraft/server/SecondaryWorldServer.java new file mode 100644 index 0000000..a34ff63 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/SecondaryWorldServer.java @@ -0,0 +1,32 @@ +package net.minecraft.server; + +public class SecondaryWorldServer extends WorldServer { + + private final WorldServer a; + + // CraftBukkit start - Add WorldData, Environment and ChunkGenerator arguments + public SecondaryWorldServer(MinecraftServer minecraftserver, IDataManager idatamanager, int i, WorldServer worldserver, MethodProfiler methodprofiler, WorldData worldData, org.bukkit.World.Environment env, org.bukkit.generator.ChunkGenerator gen) { + super(minecraftserver, idatamanager, worldData, i, methodprofiler, env, gen, false); + // CraftBukkit end + this.a = worldserver; + } + + // protected void a() {} // CraftBukkit + + public World b() { + this.worldMaps = this.a.T(); + // this.scoreboard = this.a.getScoreboard(); // CraftBukkit + String s = PersistentVillage.a(this.worldProvider); + PersistentVillage persistentvillage = (PersistentVillage) this.worldMaps.get(PersistentVillage.class, s); + + if (persistentvillage == null) { + this.villages = new PersistentVillage(this); + this.worldMaps.a(s, this.villages); + } else { + this.villages = persistentvillage; + this.villages.a(this); + } + + return super.b(); // CraftBukkit + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ServerCommand.java b/azurite-server/src/main/java/net/minecraft/server/ServerCommand.java new file mode 100644 index 0000000..c8232f6 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ServerCommand.java @@ -0,0 +1,12 @@ +package net.minecraft.server; + +public class ServerCommand { + + public final String command; + public final ICommandListener source; + + public ServerCommand(String s, ICommandListener icommandlistener) { + this.command = s; + this.source = icommandlistener; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ServerConnection.java b/azurite-server/src/main/java/net/minecraft/server/ServerConnection.java new file mode 100644 index 0000000..f5503aa --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ServerConnection.java @@ -0,0 +1,223 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; +import dev.azurite.spigot.Azurite; +import dev.azurite.spigot.configs.AzuriteConfig; +import io.netty.bootstrap.ServerBootstrap; +import io.netty.buffer.ByteBufAllocator; +import io.netty.channel.*; +import io.netty.channel.epoll.Epoll; +import io.netty.channel.epoll.EpollIoHandler; +import io.netty.channel.epoll.EpollServerSocketChannel; +import io.netty.channel.kqueue.KQueue; +import io.netty.channel.kqueue.KQueueIoHandler; +import io.netty.channel.kqueue.KQueueServerSocketChannel; +import io.netty.channel.nio.NioIoHandler; +import io.netty.channel.socket.nio.NioServerSocketChannel; +import io.netty.channel.uring.IoUring; +import io.netty.channel.uring.IoUringIoHandler; +import io.netty.channel.uring.IoUringServerSocketChannel; +import io.netty.handler.timeout.ReadTimeoutHandler; +import io.netty.util.concurrent.EventExecutor; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.io.IOException; +import java.net.InetAddress; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.function.Supplier; + +public class ServerConnection { + + public static boolean IS_USING_IO_URING = false; + + private static final Logger e = LogManager.getLogger(); + private static final WriteBufferWaterMark SERVER_WRITE_MARK = new WriteBufferWaterMark(1 << 20, 1 << 21); + + private final MinecraftServer f; + private final List g = Collections.synchronizedList(Lists.newArrayList()); + private final List h = AzuriteConfig.networkBlockingJoin.getValue() ? + Lists.newArrayList() : + Collections.synchronizedList(Lists.newArrayList()); + + public volatile boolean d; + + // Paper start - prevent blocking on adding a new network manager while the server is ticking + public final java.util.Queue pending = new java.util.concurrent.ConcurrentLinkedQueue<>(); + + private void addPending() { + if (!AzuriteConfig.networkBlockingJoin.getValue()) return; + NetworkManager manager; + while ((manager = pending.poll()) != null) { + this.h.add(manager); + } + } + // Paper end + + public ServerConnection(MinecraftServer minecraftserver) { + f = minecraftserver; + d = true; + } + + // Beanes - copy from epoll + public EventLoopGroup createEventLoopGroup(EventLoopType type, Supplier ioHandlerFactorySupplier) { + return new MultiThreadIoEventLoopGroup( + type.getThreads(), ioHandlerFactorySupplier.get()); + } + + private enum EventLoopType { + PARENT { + @Override + public int getThreads() { + return AzuriteConfig.parentNettyThreads.getValue(); + } + }, + CHILD { + @Override + public int getThreads() { + return AzuriteConfig.childNettyThreads.getValue(); + } + }; + + public abstract int getThreads(); + } + + public void a(InetAddress inetaddress, int i) throws IOException { + synchronized (g) { + this.addPending(); + + EventLoopGroup parentGroup = null, childGroup = null; + Class channel = null; + + if (f.ai()) { + if (IoUring.isAvailable() && AzuriteConfig.ioUring.getValue()) { + IS_USING_IO_URING = true; + + channel = IoUringServerSocketChannel.class; + parentGroup = createEventLoopGroup(EventLoopType.PARENT, IoUringIoHandler::newFactory); + childGroup = createEventLoopGroup(EventLoopType.CHILD, IoUringIoHandler::newFactory); + e.info("Using IO Uring channel type, compression will be disabled"); + } else if (Epoll.isAvailable()) { + channel = EpollServerSocketChannel.class; + parentGroup = createEventLoopGroup(EventLoopType.PARENT, EpollIoHandler::newFactory); + childGroup = createEventLoopGroup(EventLoopType.CHILD, EpollIoHandler::newFactory); + e.info("Using Epoll channel type"); + } else if (KQueue.isAvailable()) { + channel = KQueueServerSocketChannel.class; + parentGroup = createEventLoopGroup(EventLoopType.PARENT, KQueueIoHandler::newFactory); + childGroup = createEventLoopGroup(EventLoopType.CHILD, KQueueIoHandler::newFactory); + e.info("Using kqueue channel type"); + } + } + if (channel == null) { + channel = NioServerSocketChannel.class; + parentGroup = createEventLoopGroup(EventLoopType.PARENT, NioIoHandler::newFactory); + childGroup = createEventLoopGroup(EventLoopType.CHILD, NioIoHandler::newFactory); + e.info("Using default channel type"); + } + + // Beanes - netty thread watchdog + for (EventExecutor executor : childGroup) { + executor.execute(() -> { + Azurite.getInstance().getNettyWatchdog().watchEventLoop(executor); + }); + } + + g.add(new ServerBootstrap().channel(channel).childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, SERVER_WRITE_MARK).childHandler(new ChannelInitializer() { + @Override + protected void initChannel(Channel channel) { + try { + ChannelConfig config = channel.config(); + config.setOption(ChannelOption.TCP_NODELAY, true); + config.setOption(ChannelOption.IP_TOS, 24); // IPTOS_LOWDELAY & IPTOS_THROUGHPUT + config.setOption(ChannelOption.TCP_FASTOPEN, 1); + config.setOption(ChannelOption.TCP_FASTOPEN_CONNECT, true); + config.setAllocator(ByteBufAllocator.DEFAULT); + } catch (ChannelException ignored) { + } + + PacketDecoder decoder = new PacketDecoder(); + PacketEncoder encoder = new PacketEncoder(); + + channel.pipeline() + .addLast("timeout", new ReadTimeoutHandler(30)) + .addLast("splitter", new PacketSplitter()) + .addLast("prepender", PacketPrepender.INSTANCE) + .addLast("decoder", decoder) + .addLast("encoder", encoder); + + NetworkManager networkmanager = new NetworkManager(encoder, decoder); + + // Azurite - Make network blocking toggleable + if (AzuriteConfig.networkBlockingJoin.getValue()) { + pending.add(networkmanager); + + } else h.add(networkmanager); + + channel.pipeline().addLast("packet_handler", networkmanager); + networkmanager.a(new HandshakeListener(f, networkmanager)); + + // Beanes - prevent netty watchdog errors on java compile (I assume) + Azurite.getInstance().getNettyWatchdog().newConnection(); + } + }).group(parentGroup, childGroup).localAddress(inetaddress, i).bind().syncUninterruptibly()); + } + } + + public void b() { + this.d = false; + for (ChannelFuture future : g) { + try { + future.channel().close().sync(); + } catch (InterruptedException interruptedexception) { + e.error("Interrupted whilst closing channel"); + } + } + } + + public void c() { + synchronized (h) { + this.addPending(); // Paper + + Iterator iterator = h.iterator(); + while (iterator.hasNext()) { + NetworkManager networkmanager = iterator.next(); + + if (!networkmanager.h()) { + if (!networkmanager.g()) { + // Spigot Start + // Fix a race condition where a NetworkManager could be unregistered just before connection. + if (networkmanager.preparing) continue; + // Spigot End + iterator.remove(); + networkmanager.l(); + } else { + try { + networkmanager.a(); + } catch (Exception exception) { + if (networkmanager.c()) { + CrashReport crashreport = CrashReport.a(exception, "Ticking memory connection"); + CrashReportSystemDetails crashreportsystemdetails = crashreport.a("Ticking connection"); + + crashreportsystemdetails.a("Connection", networkmanager::toString); + throw new ReportedException(crashreport); + } + + ServerConnection.e.warn("Failed to handle packet for {}", networkmanager.getSocketAddress(), exception); + ChatComponentText chatcomponenttext = new ChatComponentText("Internal server error"); + + networkmanager.a(new PacketPlayOutKickDisconnect(chatcomponenttext), future -> networkmanager.close(chatcomponenttext)); + networkmanager.k(); + } + } + } + } + } + } + + public MinecraftServer d() { + return this.f; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ServerGUI.java b/azurite-server/src/main/java/net/minecraft/server/ServerGUI.java new file mode 100644 index 0000000..cf4ff0e --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ServerGUI.java @@ -0,0 +1,169 @@ +package net.minecraft.server; + +import com.mojang.util.QueueLogAppender; +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.FocusAdapter; +import java.awt.event.FocusEvent; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import javax.swing.JComponent; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.JScrollBar; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; +import javax.swing.JTextField; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; +import javax.swing.border.EtchedBorder; +import javax.swing.border.TitledBorder; +import javax.swing.text.AttributeSet; +import javax.swing.text.BadLocationException; +import javax.swing.text.Document; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +public class ServerGUI extends JComponent { + + private static final Font a = new Font("Monospaced", 0, 12); + private static final Logger b = LogManager.getLogger(); + private DedicatedServer c; + + public static void a(final DedicatedServer dedicatedserver) { + try { + UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + } catch (Exception exception) { + ; + } + + ServerGUI servergui = new ServerGUI(dedicatedserver); + JFrame jframe = new JFrame("Minecraft server"); + + jframe.add(servergui); + jframe.pack(); + jframe.setLocationRelativeTo((Component) null); + jframe.setVisible(true); + jframe.addWindowListener(new WindowAdapter() { + public void windowClosing(WindowEvent windowevent) { + dedicatedserver.safeShutdown(); + + while (!dedicatedserver.isStopped()) { + try { + Thread.sleep(100L); + } catch (InterruptedException interruptedexception) { + interruptedexception.printStackTrace(); + } + } + + System.exit(0); + } + }); + } + + public ServerGUI(DedicatedServer dedicatedserver) { + this.c = dedicatedserver; + this.setPreferredSize(new Dimension(854, 480)); + this.setLayout(new BorderLayout()); + + try { + this.add(this.c(), "Center"); + this.add(this.a(), "West"); + } catch (Exception exception) { + ServerGUI.b.error("Couldn\'t build server GUI", exception); + } + + } + + private JComponent a() throws Exception { + JPanel jpanel = new JPanel(new BorderLayout()); + + jpanel.add(new GuiStatsComponent(this.c), "North"); + jpanel.add(this.b(), "Center"); + jpanel.setBorder(new TitledBorder(new EtchedBorder(), "Stats")); + return jpanel; + } + + private JComponent b() throws Exception { + PlayerListBox playerlistbox = new PlayerListBox(this.c); + JScrollPane jscrollpane = new JScrollPane(playerlistbox, 22, 30); + + jscrollpane.setBorder(new TitledBorder(new EtchedBorder(), "Players")); + return jscrollpane; + } + + private JComponent c() throws Exception { + JPanel jpanel = new JPanel(new BorderLayout()); + final JTextArea jtextarea = new JTextArea(); + final JScrollPane jscrollpane = new JScrollPane(jtextarea, 22, 30); + + jtextarea.setEditable(false); + jtextarea.setFont(ServerGUI.a); + final JTextField jtextfield = new JTextField(); + + jtextfield.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent actionevent) { + String s = jtextfield.getText().trim(); + + if (s.length() > 0) { + ServerGUI.this.c.issueCommand(s, MinecraftServer.getServer()); + } + + jtextfield.setText(""); + } + }); + jtextarea.addFocusListener(new FocusAdapter() { + public void focusGained(FocusEvent focusevent) {} + }); + jpanel.add(jscrollpane, "Center"); + jpanel.add(jtextfield, "South"); + jpanel.setBorder(new TitledBorder(new EtchedBorder(), "Log and chat")); + Thread thread = new Thread(new Runnable() { + public void run() { + String s; + + while ((s = QueueLogAppender.getNextLogEvent("ServerGuiConsole")) != null) { + ServerGUI.this.a(jtextarea, jscrollpane, s); + } + + } + }); + + thread.setDaemon(true); + thread.start(); + return jpanel; + } + + public void a(final JTextArea jtextarea, final JScrollPane jscrollpane, final String s) { + if (!SwingUtilities.isEventDispatchThread()) { + SwingUtilities.invokeLater(new Runnable() { + public void run() { + ServerGUI.this.a(jtextarea, jscrollpane, s); + } + }); + } else { + Document document = jtextarea.getDocument(); + JScrollBar jscrollbar = jscrollpane.getVerticalScrollBar(); + boolean flag = false; + + if (jscrollpane.getViewport().getView() == jtextarea) { + flag = (double) jscrollbar.getValue() + jscrollbar.getSize().getHeight() + (double) (ServerGUI.a.getSize() * 4) > (double) jscrollbar.getMaximum(); + } + + try { + document.insertString(document.getLength(), s, (AttributeSet) null); + } catch (BadLocationException badlocationexception) { + ; + } + + if (flag) { + jscrollbar.setValue(Integer.MAX_VALUE); + } + + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ServerNBTManager.java b/azurite-server/src/main/java/net/minecraft/server/ServerNBTManager.java new file mode 100644 index 0000000..7b3985f --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ServerNBTManager.java @@ -0,0 +1,42 @@ +package net.minecraft.server; + +import java.io.File; + +public class ServerNBTManager extends WorldNBTStorage { + + public ServerNBTManager(File file, String s, boolean flag) { + super(file, s, flag); + } + + public IChunkLoader createChunkLoader(WorldProvider worldprovider) { + File file = this.getDirectory(); + File file1; + + if (worldprovider instanceof WorldProviderHell) { + file1 = new File(file, "DIM-1"); + file1.mkdirs(); + return new ChunkRegionLoader(file1); + } else if (worldprovider instanceof WorldProviderTheEnd) { + file1 = new File(file, "DIM1"); + file1.mkdirs(); + return new ChunkRegionLoader(file1); + } else { + return new ChunkRegionLoader(file); + } + } + + public void saveWorldData(WorldData worlddata, NBTTagCompound nbttagcompound) { + worlddata.e(19133); + super.saveWorldData(worlddata, nbttagcompound); + } + + public void a() { + try { + FileIOThread.a().b(); + } catch (InterruptedException interruptedexception) { + interruptedexception.printStackTrace(); + } + + RegionFileCache.a(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ServerPing.java b/azurite-server/src/main/java/net/minecraft/server/ServerPing.java new file mode 100644 index 0000000..95fb8fc --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ServerPing.java @@ -0,0 +1,226 @@ +package net.minecraft.server; + +import com.eatthepath.uuid.FastUUID; +import com.google.gson.*; +import com.mojang.authlib.GameProfile; + +import java.lang.reflect.Type; +import java.util.UUID; + +public class ServerPing { + + private IChatBaseComponent a; + private ServerPingPlayerSample b; + private ServerData c; + private String d; + + public ServerPing() { + } + + public IChatBaseComponent a() { + return this.a; + } + + public void setMOTD(IChatBaseComponent ichatbasecomponent) { + this.a = ichatbasecomponent; + } + + public ServerPingPlayerSample b() { + return this.b; + } + + public void setPlayerSample(ServerPingPlayerSample serverping_serverpingplayersample) { + this.b = serverping_serverpingplayersample; + } + + public ServerData c() { + return this.c; + } + + public void setServerInfo(ServerData serverping_serverdata) { + this.c = serverping_serverdata; + } + + public void setFavicon(String s) { + this.d = s; + } + + public String d() { + return this.d; + } + + public static class Serializer implements JsonDeserializer, JsonSerializer { + + public Serializer() { + } + + public ServerPing a(JsonElement jsonelement, Type type, JsonDeserializationContext jsondeserializationcontext) throws JsonParseException { + JsonObject jsonobject = ChatDeserializer.l(jsonelement, "status"); + ServerPing serverping = new ServerPing(); + + if (jsonobject.has("description")) { + serverping.setMOTD(jsondeserializationcontext.deserialize(jsonobject.get("description"), IChatBaseComponent.class)); + } + + if (jsonobject.has("players")) { + serverping.setPlayerSample(jsondeserializationcontext.deserialize(jsonobject.get("players"), ServerPingPlayerSample.class)); + } + + if (jsonobject.has("version")) { + serverping.setServerInfo(jsondeserializationcontext.deserialize(jsonobject.get("version"), ServerData.class)); + } + + if (jsonobject.has("favicon")) { + serverping.setFavicon(ChatDeserializer.h(jsonobject, "favicon")); + } + + return serverping; + } + + public JsonElement a(ServerPing serverping, Type type, JsonSerializationContext jsonserializationcontext) { + JsonObject jsonobject = new JsonObject(); + + if (serverping.a() != null) { + jsonobject.add("description", jsonserializationcontext.serialize(serverping.a())); + } + + if (serverping.b() != null) { + jsonobject.add("players", jsonserializationcontext.serialize(serverping.b())); + } + + if (serverping.c() != null) { + jsonobject.add("version", jsonserializationcontext.serialize(serverping.c())); + } + + if (serverping.d() != null) { + jsonobject.addProperty("favicon", serverping.d()); + } + + return jsonobject; + } + + @Override + public JsonElement serialize(ServerPing serverPing, Type type, JsonSerializationContext jsonSerializationContext) { + return this.a(serverPing, type, jsonSerializationContext); + } + + public ServerPing deserialize(JsonElement jsonelement, Type type, JsonDeserializationContext jsondeserializationcontext) throws JsonParseException { + return this.a(jsonelement, type, jsondeserializationcontext); + } + } + + public static class ServerData { + + private final String a; + private final int b; + + public ServerData(String s, int i) { + this.a = s; + this.b = i; + } + + public String a() { + return this.a; + } + + public int b() { + return this.b; + } + + public static class ServerData$Serializer implements JsonDeserializer, JsonSerializer { + + @Override + public JsonElement serialize(ServerData serverData, Type type, JsonSerializationContext jsonSerializationContext) { + JsonObject jsonobject = new JsonObject(); + + jsonobject.addProperty("name", serverData.a()); + jsonobject.addProperty("protocol", serverData.b()); + return jsonobject; + } + + public ServerData deserialize(JsonElement jsonelement, Type type, JsonDeserializationContext jsondeserializationcontext) throws JsonParseException { + JsonObject jsonobject = ChatDeserializer.l(jsonelement, "version"); + return new ServerData(ChatDeserializer.h(jsonobject, "name"), ChatDeserializer.m(jsonobject, "protocol")); + } + } + } + + public static class ServerPingPlayerSample { + + private final int a; + private final int b; + private GameProfile[] c; + + public ServerPingPlayerSample(int i, int j) { + this.a = i; + this.b = j; + } + + public int a() { + return this.a; + } + + public int b() { + return this.b; + } + + public GameProfile[] c() { + return this.c; + } + + public void a(GameProfile[] agameprofile) { + this.c = agameprofile; + } + + public static class ServerPingPlayerSample$Serializer implements JsonDeserializer, JsonSerializer { + + @Override + public JsonElement serialize(ServerPingPlayerSample serverPingPlayerSample, Type type, JsonSerializationContext jsonSerializationContext) { + JsonObject jsonobject = new JsonObject(); + + jsonobject.addProperty("max", serverPingPlayerSample.a()); + jsonobject.addProperty("online", serverPingPlayerSample.b()); + if (serverPingPlayerSample.c() != null && serverPingPlayerSample.c().length > 0) { + JsonArray jsonarray = new JsonArray(); + + for (int i = 0; i < serverPingPlayerSample.c().length; ++i) { + JsonObject jsonobject1 = new JsonObject(); + UUID uuid = serverPingPlayerSample.c()[i].getId(); + + jsonobject1.addProperty("id", uuid == null ? "" : FastUUID.toString(uuid)); + jsonobject1.addProperty("name", serverPingPlayerSample.c()[i].getName()); + jsonarray.add(jsonobject1); + } + + jsonobject.add("sample", jsonarray); + } + + return jsonobject; + } + + public ServerPingPlayerSample deserialize(JsonElement jsonelement, Type type, JsonDeserializationContext jsondeserializationcontext) throws JsonParseException { + JsonObject jsonobject = ChatDeserializer.l(jsonelement, "players"); + ServerPingPlayerSample serverping_serverpingplayersample = new ServerPingPlayerSample(ChatDeserializer.m(jsonobject, "max"), ChatDeserializer.m(jsonobject, "online")); + + if (ChatDeserializer.d(jsonobject, "sample")) { + JsonArray jsonarray = ChatDeserializer.t(jsonobject, "sample"); + + if (jsonarray.size() > 0) { + GameProfile[] agameprofile = new GameProfile[jsonarray.size()]; + + for (int i = 0; i < agameprofile.length; ++i) { + JsonObject jsonobject1 = ChatDeserializer.l(jsonarray.get(i), "player[" + i + "]"); + String s = ChatDeserializer.h(jsonobject1, "id"); + + agameprofile[i] = new GameProfile(FastUUID.parseUUID(s), ChatDeserializer.h(jsonobject1, "name")); + } + + serverping_serverpingplayersample.a(agameprofile); + } + } + + return serverping_serverpingplayersample; + } + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ServerStatisticManager.java b/azurite-server/src/main/java/net/minecraft/server/ServerStatisticManager.java new file mode 100644 index 0000000..8c35036 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ServerStatisticManager.java @@ -0,0 +1,207 @@ +package net.minecraft.server; + +import com.google.common.collect.Maps; +import com.google.common.collect.Sets; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.JsonParser; +import dev.azurite.spigot.Azurite; +import dev.azurite.spigot.async.tasks.PlayerStatsSaveJob; +import dev.azurite.spigot.configs.AzuriteConfig; +import org.apache.commons.io.FileUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.io.File; +import java.io.IOException; +import java.lang.reflect.Constructor; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +public class ServerStatisticManager extends StatisticManager { + + private static final Logger b = LogManager.getLogger(); + private final MinecraftServer c; + private final File d; + private final Set e = Sets.newHashSet(); + private int f = -300; + private boolean g = false; + + public ServerStatisticManager(MinecraftServer minecraftserver, File file) { + this.c = minecraftserver; + this.d = file; + // Spigot start + for (String name : org.spigotmc.SpigotConfig.forcedStats.keySet()) { + StatisticWrapper wrapper = new StatisticWrapper(); + wrapper.a(org.spigotmc.SpigotConfig.forcedStats.get(name)); + a.put(StatisticList.getStatistic(name), wrapper); + } + // Spigot end + } + + public void a() { + if (this.d.isFile()) { + try { + this.a.clear(); + this.a.putAll(this.a(FileUtils.readFileToString(this.d))); + } catch (IOException ioexception) { + ServerStatisticManager.b.error("Couldn't read statistics file {}", this.d, ioexception); + } catch (JsonParseException jsonparseexception) { + ServerStatisticManager.b.error("Couldn't parse statistics file {}", this.d, jsonparseexception); + } + } + } + + public void b() { + if (org.spigotmc.SpigotConfig.disableStatSaving) return; // Spigot + + // Azurite - asynchronously save stats + if (AzuriteConfig.asyncPlayerStatsSave.getValue()) { + Azurite.getInstance().getThreadingManager().getAsyncExecutor().queueFileTask(new PlayerStatsSaveJob(this.d, this.a)); + return; + } + new PlayerStatsSaveJob(this.d, this.a).run(); + } + + public void setStatistic(EntityHuman entityhuman, Statistic statistic, int i) { + if (org.spigotmc.SpigotConfig.disableStatSaving) return; // Spigot + int j = statistic.d() ? this.getStatisticValue(statistic) : 0; + + super.setStatistic(entityhuman, statistic, i); + this.e.add(statistic); + if (statistic.d() && j == 0 && i > 0) { + this.g = true; + if (this.c.aB()) { + this.c.getPlayerList().sendMessage(new ChatMessage("chat.type.achievement", entityhuman.getScoreboardDisplayName(), statistic.j())); + } + } + + if (statistic.d() && j > 0 && i == 0) { + this.g = true; + if (this.c.aB()) { + this.c.getPlayerList().sendMessage(new ChatMessage("chat.type.achievement.taken", entityhuman.getScoreboardDisplayName(), statistic.j())); + } + } + + } + + public Set c() { + HashSet hashset = Sets.newHashSet(this.e); + + this.e.clear(); + this.g = false; + return hashset; + } + + public Map a(String s) { + JsonElement jsonelement = (new JsonParser()).parse(s); + + if (!jsonelement.isJsonObject()) { + return Maps.newHashMap(); + } else { + JsonObject jsonobject = jsonelement.getAsJsonObject(); + HashMap hashmap = Maps.newHashMap(); + + for (Entry entry : jsonobject.entrySet()) { + Statistic statistic = StatisticList.getStatistic(entry.getKey()); + + if (statistic != null) { + StatisticWrapper statisticwrapper = new StatisticWrapper(); + + JsonElement element = entry.getValue(); + if (element.isJsonPrimitive() && element.getAsJsonPrimitive().isNumber()) { + statisticwrapper.a(element.getAsInt()); + } else if (element.isJsonObject()) { + JsonObject jsonobject1 = element.getAsJsonObject(); + + if (jsonobject1.has("value") && jsonobject1.get("value").isJsonPrimitive() && jsonobject1.get("value").getAsJsonPrimitive().isNumber()) { + statisticwrapper.a(jsonobject1.getAsJsonPrimitive("value").getAsInt()); + } + + if (jsonobject1.has("progress") && statistic.l() != null) { + try { + Constructor constructor = statistic.l().getConstructor(); + IJsonStatistic ijsonstatistic = constructor.newInstance(); + + ijsonstatistic.a(jsonobject1.get("progress")); + statisticwrapper.a(ijsonstatistic); + } catch (Throwable throwable) { + ServerStatisticManager.b.warn("Invalid statistic progress in {}", this.d, throwable); + } + } + } + + hashmap.put(statistic, statisticwrapper); + } else { + ServerStatisticManager.b.warn("Invalid statistic in {}: Don't know what {} is", this.d, entry.getKey()); + } + } + + return hashmap; + } + } + + public static String a(Map map) { + JsonObject jsonobject = new JsonObject(); + + for (Entry entry : map.entrySet()) { + if (entry.getValue().b() != null) { + JsonObject jsonobject1 = new JsonObject(); + + jsonobject1.addProperty("value", entry.getValue().a()); + + try { + jsonobject1.add("progress", entry.getValue().b().a()); + } catch (Throwable throwable) { + ServerStatisticManager.b.warn("Couldn't save statistic {}: error serializing progress", entry.getKey().e(), throwable); + } + + jsonobject.add(entry.getKey().name, jsonobject1); + } else { + jsonobject.addProperty(entry.getKey().name, entry.getValue().a()); + } + } + + return jsonobject.toString(); + } + + public void d() { + this.e.addAll(this.a.keySet()); + } + + public void a(EntityPlayer entityplayer) { + int i = this.c.at(); + HashMap hashmap = Maps.newHashMap(); + + if (this.g || i - this.f > 300) { + this.f = i; + + for (Statistic statistic : this.c()) { + hashmap.put(statistic, this.getStatisticValue(statistic)); + } + } + + entityplayer.playerConnection.sendPacket(new PacketPlayOutStatistic(hashmap)); + } + + public void updateStatistics(EntityPlayer entityplayer) { + HashMap hashmap = Maps.newHashMap(); + + for (Achievement achievement : AchievementList.e) { + if (this.hasAchievement(achievement)) { + hashmap.put(achievement, this.getStatisticValue(achievement)); + this.e.remove(achievement); + } + } + + entityplayer.playerConnection.sendPacket(new PacketPlayOutStatistic(hashmap)); + } + + public boolean e() { + return this.g; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ShapeDetector.java b/azurite-server/src/main/java/net/minecraft/server/ShapeDetector.java new file mode 100644 index 0000000..765f8eb --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ShapeDetector.java @@ -0,0 +1,171 @@ +package net.minecraft.server; + +import com.google.common.base.Objects; +import com.google.common.base.Predicate; +import com.google.common.cache.CacheBuilder; +import com.google.common.cache.CacheLoader; +import com.google.common.cache.LoadingCache; +import java.util.Iterator; + +public class ShapeDetector { + + private final Predicate[][][] a; + private final int b; + private final int c; + private final int d; + + public ShapeDetector(Predicate[][][] apredicate) { + this.a = apredicate; + this.b = apredicate.length; + if (this.b > 0) { + this.c = apredicate[0].length; + if (this.c > 0) { + this.d = apredicate[0][0].length; + } else { + this.d = 0; + } + } else { + this.c = 0; + this.d = 0; + } + + } + + public int b() { + return this.c; + } + + public int c() { + return this.d; + } + + private ShapeDetector.ShapeDetectorCollection a(BlockPosition blockposition, EnumDirection enumdirection, EnumDirection enumdirection1, LoadingCache loadingcache) { + for (int i = 0; i < this.d; ++i) { + for (int j = 0; j < this.c; ++j) { + for (int k = 0; k < this.b; ++k) { + if (!this.a[k][j][i].apply(loadingcache.getUnchecked(a(blockposition, enumdirection, enumdirection1, i, j, k)))) { + return null; + } + } + } + } + + return new ShapeDetector.ShapeDetectorCollection(blockposition, enumdirection, enumdirection1, loadingcache, this.d, this.c, this.b); + } + + public ShapeDetector.ShapeDetectorCollection a(World world, BlockPosition blockposition) { + LoadingCache loadingcache = a(world, false); + int i = Math.max(Math.max(this.d, this.c), this.b); + Iterator iterator = BlockPosition.a(blockposition, blockposition.a(i - 1, i - 1, i - 1)).iterator(); + + while (iterator.hasNext()) { + BlockPosition blockposition1 = (BlockPosition) iterator.next(); + EnumDirection[] aenumdirection = EnumDirection.values(); + int j = aenumdirection.length; + + for (int k = 0; k < j; ++k) { + EnumDirection enumdirection = aenumdirection[k]; + EnumDirection[] aenumdirection1 = EnumDirection.values(); + int l = aenumdirection1.length; + + for (int i1 = 0; i1 < l; ++i1) { + EnumDirection enumdirection1 = aenumdirection1[i1]; + + if (enumdirection1 != enumdirection && enumdirection1 != enumdirection.opposite()) { + ShapeDetector.ShapeDetectorCollection shapedetector_shapedetectorcollection = this.a(blockposition1, enumdirection, enumdirection1, loadingcache); + + if (shapedetector_shapedetectorcollection != null) { + return shapedetector_shapedetectorcollection; + } + } + } + } + } + + return null; + } + + public static LoadingCache a(World world, boolean flag) { + return CacheBuilder.newBuilder().build(new ShapeDetector.BlockLoader(world, flag)); + } + + protected static BlockPosition a(BlockPosition blockposition, EnumDirection enumdirection, EnumDirection enumdirection1, int i, int j, int k) { + if (enumdirection != enumdirection1 && enumdirection != enumdirection1.opposite()) { + BaseBlockPosition baseblockposition = new BaseBlockPosition(enumdirection.getAdjacentX(), enumdirection.getAdjacentY(), enumdirection.getAdjacentZ()); + BaseBlockPosition baseblockposition1 = new BaseBlockPosition(enumdirection1.getAdjacentX(), enumdirection1.getAdjacentY(), enumdirection1.getAdjacentZ()); + BaseBlockPosition baseblockposition2 = baseblockposition.d(baseblockposition1); + + return blockposition.a(baseblockposition1.getX() * -j + baseblockposition2.getX() * i + baseblockposition.getX() * k, baseblockposition1.getY() * -j + baseblockposition2.getY() * i + baseblockposition.getY() * k, baseblockposition1.getZ() * -j + baseblockposition2.getZ() * i + baseblockposition.getZ() * k); + } else { + throw new IllegalArgumentException("Invalid forwards & up combination"); + } + } + + public static class ShapeDetectorCollection { + + private final BlockPosition a; + private final EnumDirection b; + private final EnumDirection c; + private final LoadingCache d; + private final int e; + private final int f; + private final int g; + + public ShapeDetectorCollection(BlockPosition blockposition, EnumDirection enumdirection, EnumDirection enumdirection1, LoadingCache loadingcache, int i, int j, int k) { + this.a = blockposition; + this.b = enumdirection; + this.c = enumdirection1; + this.d = loadingcache; + this.e = i; + this.f = j; + this.g = k; + } + + public BlockPosition a() { + return this.a; + } + + public EnumDirection b() { + return this.b; + } + + public EnumDirection c() { + return this.c; + } + + public int d() { + return this.e; + } + + public int e() { + return this.f; + } + + public ShapeDetectorBlock a(int i, int j, int k) { + return (ShapeDetectorBlock) this.d.getUnchecked(ShapeDetector.a(this.a, this.b(), this.c(), i, j, k)); + } + + public String toString() { + return Objects.toStringHelper(this).add("up", this.c).add("forwards", this.b).add("frontTopLeft", this.a).toString(); + } + } + + static class BlockLoader extends CacheLoader { + + private final World a; + private final boolean b; + + public BlockLoader(World world, boolean flag) { + this.a = world; + this.b = flag; + } + + public ShapeDetectorBlock a(BlockPosition blockposition) throws Exception { + return new ShapeDetectorBlock(this.a, blockposition, this.b); + } + + public ShapeDetectorBlock load(BlockPosition object) throws Exception { + return this.a(object); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ShapeDetectorBlock.java b/azurite-server/src/main/java/net/minecraft/server/ShapeDetectorBlock.java new file mode 100644 index 0000000..3fe62af --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ShapeDetectorBlock.java @@ -0,0 +1,52 @@ +package net.minecraft.server; + +import com.google.common.base.Predicate; + +public class ShapeDetectorBlock { + + private final World a; + private final BlockPosition b; + private final boolean c; + private IBlockData d; + private TileEntity e; + private boolean f; + + public ShapeDetectorBlock(World world, BlockPosition blockposition, boolean flag) { + this.a = world; + this.b = blockposition; + this.c = flag; + } + + public IBlockData a() { + if (this.d == null && (this.c || this.a.isLoaded(this.b))) { + this.d = this.a.getType(this.b); + } + + return this.d; + } + + public TileEntity b() { + if (this.e == null && !this.f) { + this.e = this.a.getTileEntity(this.b); + this.f = true; + } + + return this.e; + } + + public BlockPosition getPosition() { + return this.b; + } + + public static Predicate a(final Predicate predicate) { + return new Predicate() { + public boolean a(ShapeDetectorBlock shapedetectorblock) { + return shapedetectorblock != null && predicate.apply(shapedetectorblock.a()); + } + + public boolean apply(Object object) { + return this.a((ShapeDetectorBlock) object); + } + }; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ShapeDetectorBuilder.java b/azurite-server/src/main/java/net/minecraft/server/ShapeDetectorBuilder.java new file mode 100644 index 0000000..65b077d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ShapeDetectorBuilder.java @@ -0,0 +1,113 @@ +package net.minecraft.server; + +import com.google.common.base.Joiner; +import com.google.common.base.Predicate; +import com.google.common.base.Predicates; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import java.lang.reflect.Array; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import org.apache.commons.lang3.ArrayUtils; +import org.apache.commons.lang3.StringUtils; + +public class ShapeDetectorBuilder { + + private static final Joiner a = Joiner.on(","); + private final List b = Lists.newArrayList(); + private final Map> c = Maps.newHashMap(); + private int d; + private int e; + + private ShapeDetectorBuilder() { + this.c.put(Character.valueOf(' '), Predicates.alwaysTrue()); + } + + public ShapeDetectorBuilder a(String... astring) { + if (!ArrayUtils.isEmpty(astring) && !StringUtils.isEmpty(astring[0])) { + if (this.b.isEmpty()) { + this.d = astring.length; + this.e = astring[0].length(); + } + + if (astring.length != this.d) { + throw new IllegalArgumentException("Expected aisle with height of " + this.d + ", but was given one with a height of " + astring.length + ")"); + } else { + String[] astring1 = astring; + int i = astring.length; + + for (int j = 0; j < i; ++j) { + String s = astring1[j]; + + if (s.length() != this.e) { + throw new IllegalArgumentException("Not all rows in the given aisle are the correct width (expected " + this.e + ", found one with " + s.length() + ")"); + } + + char[] achar = s.toCharArray(); + int k = achar.length; + + for (int l = 0; l < k; ++l) { + char c0 = achar[l]; + + if (!this.c.containsKey(c0)) { + this.c.put(c0, null); + } + } + } + + this.b.add(astring); + return this; + } + } else { + throw new IllegalArgumentException("Empty pattern for aisle"); + } + } + + public static ShapeDetectorBuilder a() { + return new ShapeDetectorBuilder(); + } + + public ShapeDetectorBuilder a(char c0, Predicate predicate) { + this.c.put(Character.valueOf(c0), predicate); + return this; + } + + public ShapeDetector b() { + return new ShapeDetector(this.c()); + } + + private Predicate[][][] c() { + this.d(); + Predicate[][][] apredicate = (Predicate[][][]) ((Predicate[][][]) Array.newInstance(Predicate.class, new int[] { this.b.size(), this.d, this.e})); + + for (int i = 0; i < this.b.size(); ++i) { + for (int j = 0; j < this.d; ++j) { + for (int k = 0; k < this.e; ++k) { + apredicate[i][j][k] = (Predicate) this.c.get(Character.valueOf(((String[]) this.b.get(i))[j].charAt(k))); + } + } + } + + return apredicate; + } + + private void d() { + ArrayList arraylist = Lists.newArrayList(); + Iterator iterator = this.c.entrySet().iterator(); + + while (iterator.hasNext()) { + Entry entry = (Entry) iterator.next(); + + if (entry.getValue() == null) { + arraylist.add(entry.getKey()); + } + } + + if (!arraylist.isEmpty()) { + throw new IllegalStateException("Predicates for character(s) " + ShapeDetectorBuilder.a.join(arraylist) + " are missing"); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ShapedRecipes.java b/azurite-server/src/main/java/net/minecraft/server/ShapedRecipes.java new file mode 100644 index 0000000..ea7cd5d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ShapedRecipes.java @@ -0,0 +1,175 @@ +package net.minecraft.server; + +// CraftBukkit start +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.craftbukkit.inventory.CraftShapedRecipe; +// CraftBukkit end + +public class ShapedRecipes implements IRecipe { + + private final int width; + private final int height; + private final ItemStack[] items; + public ItemStack result; // Spigot + private boolean e; + + public ShapedRecipes(int i, int j, ItemStack[] aitemstack, ItemStack itemstack) { + this.width = i; + this.height = j; + this.items = aitemstack; + this.result = itemstack; + } + + // CraftBukkit start + public org.bukkit.inventory.ShapedRecipe toBukkitRecipe() { + CraftItemStack result = CraftItemStack.asCraftMirror(this.result); + CraftShapedRecipe recipe = new CraftShapedRecipe(result, this); + switch (this.height) { + case 1: + switch (this.width) { + case 1: + recipe.shape("a"); + break; + case 2: + recipe.shape("ab"); + break; + case 3: + recipe.shape("abc"); + break; + } + break; + case 2: + switch (this.width) { + case 1: + recipe.shape("a","b"); + break; + case 2: + recipe.shape("ab","cd"); + break; + case 3: + recipe.shape("abc","def"); + break; + } + break; + case 3: + switch (this.width) { + case 1: + recipe.shape("a","b","c"); + break; + case 2: + recipe.shape("ab","cd","ef"); + break; + case 3: + recipe.shape("abc","def","ghi"); + break; + } + break; + } + char c = 'a'; + for (ItemStack stack : this.items) { + if (stack != null) { + recipe.setIngredient(c, org.bukkit.craftbukkit.util.CraftMagicNumbers.getMaterial(stack.getItem()), stack.getData()); + } + c++; + } + return recipe; + } + // CraftBukkit end + + public ItemStack b() { + return this.result; + } + + public ItemStack[] b(InventoryCrafting inventorycrafting) { + ItemStack[] aitemstack = new ItemStack[inventorycrafting.getSize()]; + + for (int i = 0; i < aitemstack.length; ++i) { + ItemStack itemstack = inventorycrafting.getItem(i); + + if (itemstack != null && itemstack.getItem().r()) { + aitemstack[i] = new ItemStack(itemstack.getItem().q()); + } + } + + return aitemstack; + } + + public boolean a(InventoryCrafting inventorycrafting, World world) { + for (int i = 0; i <= 3 - this.width; ++i) { + for (int j = 0; j <= 3 - this.height; ++j) { + if (this.a(inventorycrafting, i, j, true)) { + return true; + } + + if (this.a(inventorycrafting, i, j, false)) { + return true; + } + } + } + + return false; + } + + private boolean a(InventoryCrafting inventorycrafting, int i, int j, boolean flag) { + for (int k = 0; k < 3; ++k) { + for (int l = 0; l < 3; ++l) { + int i1 = k - i; + int j1 = l - j; + ItemStack itemstack = null; + + if (i1 >= 0 && j1 >= 0 && i1 < this.width && j1 < this.height) { + if (flag) { + itemstack = this.items[this.width - i1 - 1 + j1 * this.width]; + } else { + itemstack = this.items[i1 + j1 * this.width]; + } + } + + ItemStack itemstack1 = inventorycrafting.c(k, l); + + if (itemstack1 != null || itemstack != null) { + if (itemstack1 == null || itemstack == null) { + return false; + } + + if (itemstack.getItem() != itemstack1.getItem()) { + return false; + } + + if (itemstack.getData() != 32767 && itemstack.getData() != itemstack1.getData()) { + return false; + } + } + } + } + + return true; + } + + public ItemStack craftItem(InventoryCrafting inventorycrafting) { + ItemStack itemstack = this.b().cloneItemStack(); + + if (this.e) { + for (int i = 0; i < inventorycrafting.getSize(); ++i) { + ItemStack itemstack1 = inventorycrafting.getItem(i); + + if (itemstack1 != null && itemstack1.hasTag()) { + itemstack.setTag((NBTTagCompound) itemstack1.getTag().clone()); + } + } + } + + return itemstack; + } + + public int a() { + return this.width * this.height; + } + + // Spigot start + public java.util.List getIngredients() + { + return java.util.Arrays.asList( items ); + } + // Spigot end +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ShapelessRecipes.java b/azurite-server/src/main/java/net/minecraft/server/ShapelessRecipes.java new file mode 100644 index 0000000..6ce36b9 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ShapelessRecipes.java @@ -0,0 +1,94 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.craftbukkit.inventory.CraftShapelessRecipe; + +import java.util.ArrayList; +import java.util.List; +// CraftBukkit end + +public class ShapelessRecipes implements IRecipe { + + public final ItemStack result; // Spigot + private final List ingredients; + + public ShapelessRecipes(ItemStack itemstack, List list) { + this.result = itemstack; + this.ingredients = list; + } + + // CraftBukkit start + public org.bukkit.inventory.ShapelessRecipe toBukkitRecipe() { + CraftItemStack result = CraftItemStack.asCraftMirror(this.result); + CraftShapelessRecipe recipe = new CraftShapelessRecipe(result, this); + for (ItemStack stack : this.ingredients) { + if (stack != null) { + recipe.addIngredient(org.bukkit.craftbukkit.util.CraftMagicNumbers.getMaterial(stack.getItem()), stack.getData()); + } + } + return recipe; + } + // CraftBukkit end + + public ItemStack b() { + return this.result; + } + + public ItemStack[] b(InventoryCrafting inventorycrafting) { + ItemStack[] aitemstack = new ItemStack[inventorycrafting.getSize()]; + + for (int i = 0; i < aitemstack.length; ++i) { + ItemStack itemstack = inventorycrafting.getItem(i); + + if (itemstack != null && itemstack.getItem().r()) { + aitemstack[i] = new ItemStack(itemstack.getItem().q()); + } + } + + return aitemstack; + } + + public boolean a(InventoryCrafting inventorycrafting, World world) { + ArrayList arraylist = Lists.newArrayList(this.ingredients); + + for (int i = 0; i < inventorycrafting.h(); ++i) { + for (int j = 0; j < inventorycrafting.i(); ++j) { + ItemStack itemstack = inventorycrafting.c(j, i); + + if (itemstack != null) { + boolean flag = false; + + for (ItemStack itemstack1 : arraylist) { + if (itemstack.getItem() == itemstack1.getItem() && (itemstack1.getData() == 32767 || itemstack.getData() == itemstack1.getData())) { + flag = true; + arraylist.remove(itemstack1); + break; + } + } + + if (!flag) { + return false; + } + } + } + } + + return arraylist.isEmpty(); + } + + public ItemStack craftItem(InventoryCrafting inventorycrafting) { + return this.result.cloneItemStack(); + } + + public int a() { + return this.ingredients.size(); + } + + // Spigot start + public java.util.List getIngredients() + { + return java.util.Collections.unmodifiableList( ingredients ); + } + // Spigot end +} diff --git a/azurite-server/src/main/java/net/minecraft/server/SharedConstants.java b/azurite-server/src/main/java/net/minecraft/server/SharedConstants.java new file mode 100644 index 0000000..fcf4c79 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/SharedConstants.java @@ -0,0 +1,26 @@ +package net.minecraft.server; + +public class SharedConstants { + + public static final char[] allowedCharacters = new char[] { '/', '\n', '\r', '\t', '\u0000', '\f', '`', '?', '*', '\\', '<', '>', '|', '\"', ':'}; + + public static boolean isAllowedChatCharacter(char c0) { + return c0 != 167 && c0 >= 32 && c0 != 127; + } + + public static String a(String s) { + StringBuilder stringbuilder = new StringBuilder(); + char[] achar = s.toCharArray(); + int i = achar.length; + + for (int j = 0; j < i; ++j) { + char c0 = achar[j]; + + if (isAllowedChatCharacter(c0)) { + stringbuilder.append(c0); + } + } + + return stringbuilder.toString(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/Slot.java b/azurite-server/src/main/java/net/minecraft/server/Slot.java new file mode 100644 index 0000000..01b51d6 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/Slot.java @@ -0,0 +1,81 @@ +package net.minecraft.server; + +public class Slot { + + public final int index; + public final IInventory inventory; + public int rawSlotIndex; + public int f; + public int g; + + public Slot(IInventory iinventory, int index, int xDisplayPos, int yDisplayPos) { + this.inventory = iinventory; + this.index = index; + this.f = xDisplayPos; + this.g = yDisplayPos; + } + + public void a(ItemStack itemstack, ItemStack itemstack1) { + if (itemstack != null && itemstack1 != null) { + if (itemstack.getItem() == itemstack1.getItem()) { + int i = itemstack1.count - itemstack.count; + + if (i > 0) { + this.a(itemstack, i); + } + } + } + } + + protected void a(ItemStack itemstack, int i) {} + + protected void c(ItemStack itemstack) {} + + public void a(EntityHuman entityhuman, ItemStack itemstack) { + this.f(); + } + + public boolean isAllowed(ItemStack itemstack) { + return true; + } + + public ItemStack getItem() { + return this.inventory.getItem(this.index); + } + + public boolean hasItem() { + if (getItem() != null && getItem().count == 0) { + set(null); + } + return this.getItem() != null; + } + + public void set(ItemStack itemstack) { + this.inventory.setItem(this.index, itemstack); + this.f(); + } + + public void f() { + this.inventory.update(); + } + + public int getMaxStackSize() { + return this.inventory.getMaxStackSize(); + } + + public int getMaxStackSize(ItemStack itemstack) { + return this.getMaxStackSize(); + } + + public ItemStack a(int i) { + return this.inventory.splitStack(this.index, i); + } + + public boolean a(IInventory iinventory, int i) { + return iinventory == this.inventory && i == this.index; + } + + public boolean isAllowed(EntityHuman entityhuman) { + return true; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/SlotFurnaceFuel.java b/azurite-server/src/main/java/net/minecraft/server/SlotFurnaceFuel.java new file mode 100644 index 0000000..2bbedad --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/SlotFurnaceFuel.java @@ -0,0 +1,20 @@ +package net.minecraft.server; + +public class SlotFurnaceFuel extends Slot { + + public SlotFurnaceFuel(IInventory iinventory, int i, int j, int k) { + super(iinventory, i, j, k); + } + + public boolean isAllowed(ItemStack itemstack) { + return TileEntityFurnace.isFuel(itemstack) || c_(itemstack); + } + + public int getMaxStackSize(ItemStack itemstack) { + return c_(itemstack) ? 1 : super.getMaxStackSize(itemstack); + } + + public static boolean c_(ItemStack itemstack) { + return itemstack != null && itemstack.getItem() != null && itemstack.getItem() == Items.BUCKET; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/SlotFurnaceResult.java b/azurite-server/src/main/java/net/minecraft/server/SlotFurnaceResult.java new file mode 100644 index 0000000..8198ad1 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/SlotFurnaceResult.java @@ -0,0 +1,85 @@ +package net.minecraft.server; + +// CraftBukkit start + +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.FurnaceExtractEvent; +// CraftBukkit end + +public class SlotFurnaceResult extends Slot { + + private final EntityHuman a; + private int b; + + public SlotFurnaceResult(EntityHuman entityhuman, IInventory iinventory, int i, int j, int k) { + super(iinventory, i, j, k); + this.a = entityhuman; + } + + public boolean isAllowed(ItemStack itemstack) { + return false; + } + + public ItemStack a(int i) { + if (this.hasItem()) { + this.b += Math.min(i, this.getItem().count); + } + + return super.a(i); + } + + public void a(EntityHuman entityhuman, ItemStack itemstack) { + this.c(itemstack); + super.a(entityhuman, itemstack); + } + + protected void a(ItemStack itemstack, int i) { + this.b += i; + this.c(itemstack); + } + + protected void c(ItemStack itemstack) { + itemstack.a(this.a.world, this.a, this.b); + int i = this.b; + float f = RecipesFurnace.getInstance().b(itemstack); + int j; + + if (f == 0.0F) { + i = 0; + } else if (f < 1.0F) { + j = MathHelper.d((float) i * f); + if (j < MathHelper.f((float) i * f) && Math.random() < (double) ((float) i * f - (float) j)) { + ++j; + } + + i = j; + } + + // CraftBukkit start - fire FurnaceExtractEvent + Player player = (Player) a.getBukkitEntity(); + TileEntityFurnace furnace = ((TileEntityFurnace) this.inventory); + org.bukkit.block.Block block = a.world.getWorld().getBlockAt(furnace.position.getX(), furnace.position.getY(), furnace.position.getZ()); + + if (b != 0) { + FurnaceExtractEvent event = new FurnaceExtractEvent(player, block, org.bukkit.craftbukkit.util.CraftMagicNumbers.getMaterial(itemstack.getItem()), b, i); + a.world.getServer().getPluginManager().callEvent(event); + i = event.getExpToDrop(); + } + // CraftBukkit end + + while (i > 0) { + j = EntityExperienceOrb.getOrbValue(i); + i -= j; + this.a.world.addEntity(new EntityExperienceOrb(this.a.world, this.a.locX, this.a.locY + 0.5D, this.a.locZ + 0.5D, j)); + } + + this.b = 0; + if (itemstack.getItem() == Items.IRON_INGOT) { + this.a.b(AchievementList.k); + } + + if (itemstack.getItem() == Items.COOKED_FISH) { + this.a.b(AchievementList.p); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/SlotMerchantResult.java b/azurite-server/src/main/java/net/minecraft/server/SlotMerchantResult.java new file mode 100644 index 0000000..468d3d2 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/SlotMerchantResult.java @@ -0,0 +1,84 @@ +package net.minecraft.server; + +public class SlotMerchantResult extends Slot { + + private final InventoryMerchant a; + private EntityHuman b; + private int c; + private final IMerchant h; + + public SlotMerchantResult(EntityHuman entityhuman, IMerchant imerchant, InventoryMerchant inventorymerchant, int i, int j, int k) { + super(inventorymerchant, i, j, k); + this.b = entityhuman; + this.h = imerchant; + this.a = inventorymerchant; + } + + public boolean isAllowed(ItemStack itemstack) { + return false; + } + + public ItemStack a(int i) { + if (this.hasItem()) { + this.c += Math.min(i, this.getItem().count); + } + + return super.a(i); + } + + protected void a(ItemStack itemstack, int i) { + this.c += i; + this.c(itemstack); + } + + protected void c(ItemStack itemstack) { + itemstack.a(this.b.world, this.b, this.c); + this.c = 0; + } + + public void a(EntityHuman entityhuman, ItemStack itemstack) { + this.c(itemstack); + MerchantRecipe merchantrecipe = this.a.getRecipe(); + + if (merchantrecipe != null) { + ItemStack itemstack1 = this.a.getItem(0); + ItemStack itemstack2 = this.a.getItem(1); + + if (this.a(merchantrecipe, itemstack1, itemstack2) || this.a(merchantrecipe, itemstack2, itemstack1)) { + this.h.a(merchantrecipe); + entityhuman.b(StatisticList.G); + if (itemstack1 != null && itemstack1.count <= 0) { + itemstack1 = null; + } + + if (itemstack2 != null && itemstack2.count <= 0) { + itemstack2 = null; + } + + this.a.setItem(0, itemstack1); + this.a.setItem(1, itemstack2); + } + } + + } + + private boolean a(MerchantRecipe merchantrecipe, ItemStack itemstack, ItemStack itemstack1) { + ItemStack itemstack2 = merchantrecipe.getBuyItem1(); + ItemStack itemstack3 = merchantrecipe.getBuyItem2(); + + if (itemstack != null && itemstack.getItem() == itemstack2.getItem()) { + if (itemstack3 != null && itemstack1 != null && itemstack3.getItem() == itemstack1.getItem()) { + itemstack.count -= itemstack2.count; + itemstack1.count -= itemstack3.count; + return true; + } + + if (itemstack3 == null && itemstack1 == null) { + itemstack.count -= itemstack2.count; + return true; + } + } + + return false; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/SlotResult.java b/azurite-server/src/main/java/net/minecraft/server/SlotResult.java new file mode 100644 index 0000000..d2551cf --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/SlotResult.java @@ -0,0 +1,106 @@ +package net.minecraft.server; + +public class SlotResult extends Slot { + + private final InventoryCrafting a; + private final EntityHuman b; + private int c; + + public SlotResult(EntityHuman entityhuman, InventoryCrafting inventorycrafting, IInventory iinventory, int i, int j, int k) { + super(iinventory, i, j, k); + this.b = entityhuman; + this.a = inventorycrafting; + } + + public boolean isAllowed(ItemStack itemstack) { + return false; + } + + public ItemStack a(int i) { + if (this.hasItem()) { + this.c += Math.min(i, this.getItem().count); + } + + return super.a(i); + } + + protected void a(ItemStack itemstack, int i) { + this.c += i; + this.c(itemstack); + } + + protected void c(ItemStack itemstack) { + if (this.c > 0) { + itemstack.a(this.b.world, this.b, this.c); + } + + this.c = 0; + if (itemstack.getItem() == Item.getItemOf(Blocks.CRAFTING_TABLE)) { + this.b.b((Statistic) AchievementList.h); + } + + if (itemstack.getItem() instanceof ItemPickaxe) { + this.b.b((Statistic) AchievementList.i); + } + + if (itemstack.getItem() == Item.getItemOf(Blocks.FURNACE)) { + this.b.b((Statistic) AchievementList.j); + } + + if (itemstack.getItem() instanceof ItemHoe) { + this.b.b((Statistic) AchievementList.l); + } + + if (itemstack.getItem() == Items.BREAD) { + this.b.b((Statistic) AchievementList.m); + } + + if (itemstack.getItem() == Items.CAKE) { + this.b.b((Statistic) AchievementList.n); + } + + if (itemstack.getItem() instanceof ItemPickaxe && ((ItemPickaxe) itemstack.getItem()).g() != Item.EnumToolMaterial.WOOD) { + this.b.b((Statistic) AchievementList.o); + } + + if (itemstack.getItem() instanceof ItemSword) { + this.b.b((Statistic) AchievementList.r); + } + + if (itemstack.getItem() == Item.getItemOf(Blocks.ENCHANTING_TABLE)) { + this.b.b((Statistic) AchievementList.E); + } + + if (itemstack.getItem() == Item.getItemOf(Blocks.BOOKSHELF)) { + this.b.b((Statistic) AchievementList.G); + } + + if (itemstack.getItem() == Items.GOLDEN_APPLE && itemstack.getData() == 1) { + this.b.b((Statistic) AchievementList.M); + } + + } + + public void a(EntityHuman entityhuman, ItemStack itemstack) { + this.c(itemstack); + ItemStack[] aitemstack = CraftingManager.getInstance().b(this.a, entityhuman.world); + + for (int i = 0; i < aitemstack.length; ++i) { + ItemStack itemstack1 = this.a.getItem(i); + ItemStack itemstack2 = aitemstack[i]; + + if (itemstack1 != null) { + this.a.splitStack(i, 1); + } + + if (itemstack2 != null) { + if (this.a.getItem(i) == null) { + this.a.setItem(i, itemstack2); + } else if (!this.b.inventory.pickup(itemstack2)) { + this.b.drop(itemstack2, false); + } + } + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/SourceBlock.java b/azurite-server/src/main/java/net/minecraft/server/SourceBlock.java new file mode 100644 index 0000000..7390678 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/SourceBlock.java @@ -0,0 +1,42 @@ +package net.minecraft.server; + +public class SourceBlock implements ISourceBlock { + + private final World a; + private final BlockPosition b; + + public SourceBlock(World world, BlockPosition blockposition) { + this.a = world; + this.b = blockposition; + } + + public World getWorld() { + return this.a; + } + + public double getX() { + return (double) this.b.getX() + 0.5D; + } + + public double getY() { + return (double) this.b.getY() + 0.5D; + } + + public double getZ() { + return (double) this.b.getZ() + 0.5D; + } + + public BlockPosition getBlockPosition() { + return this.b; + } + + public int f() { + IBlockData iblockdata = this.a.getType(this.b); + + return iblockdata.getBlock().toLegacyData(iblockdata); + } + + public T getTileEntity() { + return (T) this.a.getTileEntity(this.b); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/SpawnerCreature.java b/azurite-server/src/main/java/net/minecraft/server/SpawnerCreature.java new file mode 100644 index 0000000..e165929 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/SpawnerCreature.java @@ -0,0 +1,274 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.AzuriteConfig; +import net.minecraft.server.BiomeBase.BiomeMeta; +import org.bukkit.craftbukkit.util.LongHash; +import org.bukkit.craftbukkit.util.LongHashSet; +import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason; +import org.github.paperspigot.PaperWorldEntityList; + +import java.util.Iterator; +import java.util.List; +import java.util.Random; + +public final class SpawnerCreature { + + private final LongHashSet b = new LongHashSet(); + + public SpawnerCreature() { + } + + private static BlockPosition getRandomPosition(World world, int i, int j) { + Chunk chunk = world.getChunkIfLoaded(i, j); // Azurite - Don't load chunks for mob spawns + + if (chunk != null) { + int k = i * 16 + world.random.nextInt(16); + int l = j * 16 + world.random.nextInt(16); + int i1 = MathHelper.c(chunk.f(k, l) + 1, 16); + int j1 = world.random.nextInt(i1 > 0 ? i1 : chunk.g() + 16 - 1); + return new BlockPosition(k, j1, l); + } + + return null; + } + + public static boolean a(EntityInsentient.EnumEntityPositionType entityinsentient_enumentitypositiontype, World world, BlockPosition blockposition) { + int x = blockposition.getX(), y = blockposition.getY(), z = blockposition.getZ(); + if (!world.getWorldBorder().a(x, z)) { + return false; + } else { + Block block = world.getType(x, y, z).getBlock(); + + if (entityinsentient_enumentitypositiontype == EntityInsentient.EnumEntityPositionType.IN_WATER) { + return block.getMaterial().isLiquid() && world.getType(x, y - 1, z).getBlock().getMaterial().isLiquid() && !world.getType(x, y + 1, z).getBlock().isOccluding(); + } else { + if (!World.a(world, x, y - 1, z)) { + return false; + } else { + Block block1 = world.getType(x, y - 1, z).getBlock(); + return block1 != Blocks.BEDROCK && block1 != Blocks.BARRIER && !block.isOccluding() && !block.getMaterial().isLiquid() && !world.getType(x, y + 1, z).getBlock().isOccluding(); + } + } + } + } + + public static void a(World world, BiomeBase biomebase, int i, int j, int k, int l, Random random) { + if (!AzuriteConfig.naturalMobSpawn.getValue()) + return; + + List list = biomebase.getMobs(EnumCreatureType.CREATURE); + + if (!list.isEmpty()) { + while (random.nextFloat() < biomebase.g()) { + BiomeMeta biomebase_biomemeta = WeightedRandom.a(world.random, list); + int i1 = biomebase_biomemeta.c + random.nextInt(1 + biomebase_biomemeta.d - biomebase_biomemeta.c); + GroupDataEntity groupdataentity = null; + int j1 = i + random.nextInt(k); + int k1 = j + random.nextInt(l); + int l1 = j1; + int i2 = k1; + + for (int j2 = 0; j2 < i1; ++j2) { + boolean flag = false; + + for (int k2 = 0; !flag && k2 < 4; ++k2) { + BlockPosition blockposition = world.r(j1, k1); + + if (a(EntityInsentient.EnumEntityPositionType.ON_GROUND, world, blockposition)) { + EntityInsentient entityinsentient; + + try { + entityinsentient = biomebase_biomemeta.constructor.newInstance(world); + } catch (Exception exception) { + exception.printStackTrace(); + continue; + } + + entityinsentient.setPositionRotation(j1 + 0.5F, blockposition.getY(), k1 + 0.5F, random.nextFloat() * 360.0F, 0.0F); + // CraftBukkit start - Added a reason for spawning this creature, moved entityinsentient.prepare(groupdataentity) up + groupdataentity = entityinsentient.prepare(world.E(MathHelper.floor(entityinsentient.locX), MathHelper.floor(entityinsentient.locY), MathHelper.floor(entityinsentient.locZ)), groupdataentity); + world.addEntity(entityinsentient, SpawnReason.CHUNK_GEN); + // CraftBukkit end + flag = true; + } + + j1 += random.nextInt(5) - random.nextInt(5); + + for (k1 += random.nextInt(5) - random.nextInt(5); j1 < i || j1 >= i + k || k1 < j || k1 >= j + k; k1 = i2 + random.nextInt(5) - random.nextInt(5)) { + j1 = l1 + random.nextInt(5) - random.nextInt(5); + } + } + } + } + } + } + + // Azurite - Backport paper entity list + public int getEntityCount(WorldServer worldServer, EnumCreatureType enumCreatureType) { + return ((PaperWorldEntityList) worldServer.entityList).getCreatureCount(enumCreatureType); + } + + public int a(WorldServer worldserver, boolean flag, boolean flag1, boolean flag2) { + if (!flag && !flag1) { + return 0; + } else { + this.b.clear(); + int i = 0; + + for (EntityHuman entityhuman : worldserver.players) { + if (!entityhuman.isSpectator() || !entityhuman.affectsSpawning) { // PaperSpigot + int l = MathHelper.floor(entityhuman.locX / 16.0D); + int j = MathHelper.floor(entityhuman.locZ / 16.0D); + int k; + byte b0; + + // Spigot Start + b0 = worldserver.spigotConfig.mobSpawnRange; + b0 = (b0 > worldserver.spigotConfig.viewDistance) ? (byte) worldserver.spigotConfig.viewDistance : b0; + b0 = (b0 > 8) ? 8 : b0; + // Spigot End + + for (int i1 = -b0; i1 <= b0; ++i1) { + for (k = -b0; k <= b0; ++k) { + boolean flag3 = i1 == -b0 || i1 == b0 || k == -b0 || k == b0; + long chunkCoords = LongHash.toLong(i1 + l, k + j); + if (!this.b.contains(chunkCoords)) { + ++i; + if (!flag3 && worldserver.getWorldBorder().isInBounds(i1 + l, k + j)) { + this.b.add(chunkCoords); + } + } + } + } + } + } + + int j1 = 0; + BlockPosition blockposition = worldserver.getSpawn(); + for (EnumCreatureType enumcreaturetype : EnumCreatureType.values()) { + // CraftBukkit start - Use per-world spawn limits + int limit = enumcreaturetype.b(); + switch (enumcreaturetype) { + case MONSTER: + limit = worldserver.getWorld().getMonsterSpawnLimit(); + break; + case CREATURE: + limit = worldserver.getWorld().getAnimalSpawnLimit(); + break; + case WATER_CREATURE: + limit = worldserver.getWorld().getWaterAnimalSpawnLimit(); + break; + case AMBIENT: + limit = worldserver.getWorld().getAmbientSpawnLimit(); + break; + } + + if (limit == 0) { + continue; + } + int mobcnt; // Spigot + // CraftBukkit end + + if ((!enumcreaturetype.d() || flag1) && (enumcreaturetype.d() || flag) && (!enumcreaturetype.e() || flag2)) { + if ((mobcnt = getEntityCount(worldserver, enumcreaturetype)) <= limit * i / 289) { // TacoSpigot - use 17x17 like vanilla (a at top of file) + Iterator iterator1 = this.b.iterator(); + + int moblimit = (limit * i / 256) - mobcnt + 1; // Spigot - up to 1 more than limit + label115: + while (iterator1.hasNext() && (moblimit > 0)) { // Spigot - while more allowed + // CraftBukkit start = use LongHash and LongObjectHashMap + long key = iterator1.next(); + BlockPosition blockposition1 = getRandomPosition(worldserver, LongHash.msw(key), LongHash.lsw(key)); + + if (blockposition1 == null) continue; + + // CraftBukkit + int i2 = blockposition1.getX(); + int j2 = blockposition1.getY(); + int k2 = blockposition1.getZ(); + Block block = worldserver.getType(blockposition1).getBlock(); + + if (!block.isOccluding()) { + int l2 = 0; + int i3 = 0; + + while (i3 < 3) { + int j3 = i2; + int l3 = k2; + byte b1 = 6; + BiomeMeta biomebase_biomemeta = null; + GroupDataEntity groupdataentity = null; + int i4 = 0; + + while (true) { + if (i4 < 4) { + label108: + { + j3 += worldserver.random.nextInt(b1) - worldserver.random.nextInt(b1); + l3 += worldserver.random.nextInt(b1) - worldserver.random.nextInt(b1); + BlockPosition blockposition2 = new BlockPosition(j3, j2, l3); + float f = (float) j3 + 0.5F; + float f1 = (float) l3 + 0.5F; + + if (!worldserver.isPlayerNearbyWhoAffectsSpawning(f, j2, f1, 24.0D) + && worldserver.isLoaded(blockposition2) // Azurite - Don't load chunks for mob spawns + && blockposition.c(f, j2, f1) >= 576.0D) { // PaperSpigot - Affects Spawning API + + if (biomebase_biomemeta == null) { + biomebase_biomemeta = worldserver.a(enumcreaturetype, blockposition2); + if (biomebase_biomemeta == null) { + break label108; + } + } + + if (worldserver.a(enumcreaturetype, biomebase_biomemeta, blockposition2) && a(EntityPositionTypes.a(biomebase_biomemeta.b), worldserver, blockposition2)) { + EntityInsentient entityinsentient; + + try { + entityinsentient = biomebase_biomemeta.constructor.newInstance(worldserver); + } catch (Exception exception) { + exception.printStackTrace(); + return j1; + } + + entityinsentient.setPositionRotation(f, j2, f1, worldserver.random.nextFloat() * 360.0F, 0.0F); + if (entityinsentient.bR() && entityinsentient.canSpawn()) { + groupdataentity = entityinsentient.prepare(worldserver.E(MathHelper.floor(entityinsentient.locX), MathHelper.floor(entityinsentient.locY), MathHelper.floor(entityinsentient.locZ)), groupdataentity); + if (entityinsentient.canSpawn()) { + ++l2; + worldserver.addEntity(entityinsentient, SpawnReason.NATURAL); // CraftBukkit - Added a reason for spawning this creature + } + + // Spigot start + if (--moblimit <= 0) { + // If we're past limit, stop spawn + continue label115; + } + // Spigot end + if (l2 >= entityinsentient.bV()) { + continue label115; + } + } + + j1 += l2; + } + } + + ++i4; + continue; + } + } + + ++i3; + break; + } + } + } + } + } + } + } + return j1; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/Statistic.java b/azurite-server/src/main/java/net/minecraft/server/Statistic.java new file mode 100644 index 0000000..5be70d4 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/Statistic.java @@ -0,0 +1,105 @@ +package net.minecraft.server; + +import java.text.DecimalFormat; +import java.text.NumberFormat; +import java.util.Locale; + +public class Statistic { + + public final String name; + private final IChatBaseComponent a; + public boolean f; + private final Counter b; + private final IScoreboardCriteria c; + private Class d; + private static NumberFormat k = NumberFormat.getIntegerInstance(Locale.US); + public static Counter g = new Counter() { + }; + private static DecimalFormat l = new DecimalFormat("########0.00"); + public static Counter h = new Counter() { + }; + public static Counter i = new Counter() { + }; + public static Counter j = new Counter() { + }; + + public Statistic(String s, IChatBaseComponent ichatbasecomponent, Counter counter) { + this.name = s; + this.a = ichatbasecomponent; + this.b = counter; + this.c = new ScoreboardStatisticCriteria(this); + IScoreboardCriteria.criteria.put(this.c.getName(), this.c); + } + + public Statistic(String s, IChatBaseComponent ichatbasecomponent) { + this(s, ichatbasecomponent, Statistic.g); + } + + public Statistic i() { + this.f = true; + return this; + } + + public Statistic h() { + if (StatisticList.a.containsKey(this.name)) { + throw new RuntimeException("Duplicate stat id: \"" + ((Statistic) StatisticList.a.get(this.name)).a + "\" and \"" + this.a + "\" at id " + this.name); + } else { + StatisticList.stats.add(this); + StatisticList.a.put(this.name, this); + return this; + } + } + + public boolean d() { + return false; + } + + public IChatBaseComponent e() { + IChatBaseComponent ichatbasecomponent = this.a.f(); + + ichatbasecomponent.getChatModifier().setColor(EnumChatFormat.GRAY); + ichatbasecomponent.getChatModifier().setChatHoverable(new ChatHoverable(ChatHoverable.EnumHoverAction.SHOW_ACHIEVEMENT, new ChatComponentText(this.name))); + return ichatbasecomponent; + } + + public IChatBaseComponent j() { + IChatBaseComponent ichatbasecomponent = this.e(); + IChatBaseComponent ichatbasecomponent1 = (new ChatComponentText("[")).addSibling(ichatbasecomponent).a("]"); + + ichatbasecomponent1.setChatModifier(ichatbasecomponent.getChatModifier()); + return ichatbasecomponent1; + } + + public boolean equals(Object object) { + if (this == object) { + return true; + } else if (object != null && this.getClass() == object.getClass()) { + Statistic statistic = (Statistic) object; + + return this.name.equals(statistic.name); + } else { + return false; + } + } + + public int hashCode() { + return this.name.hashCode(); + } + + public String toString() { + return "Stat{id=" + this.name + ", nameId=" + this.a + ", awardLocallyOnly=" + this.f + ", formatter=" + this.b + ", objectiveCriteria=" + this.c + '}'; + } + + public IScoreboardCriteria k() { + return this.c; + } + + public Class l() { + return this.d; + } + + public Statistic b(Class oclass) { + this.d = oclass; + return this; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/StatisticList.java b/azurite-server/src/main/java/net/minecraft/server/StatisticList.java new file mode 100644 index 0000000..b5ceb9a --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/StatisticList.java @@ -0,0 +1,232 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import com.google.common.collect.Sets; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +public class StatisticList { + + protected static Map a = Maps.newHashMap(); + public static List stats = Lists.newArrayList(); + public static List c = Lists.newArrayList(); + public static List d = Lists.newArrayList(); + public static List e = Lists.newArrayList(); + public static Statistic f = (new CounterStatistic("stat.leaveGame", new ChatMessage("stat.leaveGame", new Object[0]))).i().h(); + public static Statistic g = (new CounterStatistic("stat.playOneMinute", new ChatMessage("stat.playOneMinute", new Object[0]), Statistic.h)).i().h(); + public static Statistic h = (new CounterStatistic("stat.timeSinceDeath", new ChatMessage("stat.timeSinceDeath", new Object[0]), Statistic.h)).i().h(); + public static Statistic i = (new CounterStatistic("stat.walkOneCm", new ChatMessage("stat.walkOneCm", new Object[0]), Statistic.i)).i().h(); + public static Statistic j = (new CounterStatistic("stat.crouchOneCm", new ChatMessage("stat.crouchOneCm", new Object[0]), Statistic.i)).i().h(); + public static Statistic k = (new CounterStatistic("stat.sprintOneCm", new ChatMessage("stat.sprintOneCm", new Object[0]), Statistic.i)).i().h(); + public static Statistic l = (new CounterStatistic("stat.swimOneCm", new ChatMessage("stat.swimOneCm", new Object[0]), Statistic.i)).i().h(); + public static Statistic m = (new CounterStatistic("stat.fallOneCm", new ChatMessage("stat.fallOneCm", new Object[0]), Statistic.i)).i().h(); + public static Statistic n = (new CounterStatistic("stat.climbOneCm", new ChatMessage("stat.climbOneCm", new Object[0]), Statistic.i)).i().h(); + public static Statistic o = (new CounterStatistic("stat.flyOneCm", new ChatMessage("stat.flyOneCm", new Object[0]), Statistic.i)).i().h(); + public static Statistic p = (new CounterStatistic("stat.diveOneCm", new ChatMessage("stat.diveOneCm", new Object[0]), Statistic.i)).i().h(); + public static Statistic q = (new CounterStatistic("stat.minecartOneCm", new ChatMessage("stat.minecartOneCm", new Object[0]), Statistic.i)).i().h(); + public static Statistic r = (new CounterStatistic("stat.boatOneCm", new ChatMessage("stat.boatOneCm", new Object[0]), Statistic.i)).i().h(); + public static Statistic s = (new CounterStatistic("stat.pigOneCm", new ChatMessage("stat.pigOneCm", new Object[0]), Statistic.i)).i().h(); + public static Statistic t = (new CounterStatistic("stat.horseOneCm", new ChatMessage("stat.horseOneCm", new Object[0]), Statistic.i)).i().h(); + public static Statistic u = (new CounterStatistic("stat.jump", new ChatMessage("stat.jump", new Object[0]))).i().h(); + public static Statistic v = (new CounterStatistic("stat.drop", new ChatMessage("stat.drop", new Object[0]))).i().h(); + public static Statistic w = (new CounterStatistic("stat.damageDealt", new ChatMessage("stat.damageDealt", new Object[0]), Statistic.j)).h(); + public static Statistic x = (new CounterStatistic("stat.damageTaken", new ChatMessage("stat.damageTaken", new Object[0]), Statistic.j)).h(); + public static Statistic y = (new CounterStatistic("stat.deaths", new ChatMessage("stat.deaths", new Object[0]))).h(); + public static Statistic z = (new CounterStatistic("stat.mobKills", new ChatMessage("stat.mobKills", new Object[0]))).h(); + public static Statistic A = (new CounterStatistic("stat.animalsBred", new ChatMessage("stat.animalsBred", new Object[0]))).h(); + public static Statistic B = (new CounterStatistic("stat.playerKills", new ChatMessage("stat.playerKills", new Object[0]))).h(); + public static Statistic C = (new CounterStatistic("stat.fishCaught", new ChatMessage("stat.fishCaught", new Object[0]))).h(); + public static Statistic D = (new CounterStatistic("stat.junkFished", new ChatMessage("stat.junkFished", new Object[0]))).h(); + public static Statistic E = (new CounterStatistic("stat.treasureFished", new ChatMessage("stat.treasureFished", new Object[0]))).h(); + public static Statistic F = (new CounterStatistic("stat.talkedToVillager", new ChatMessage("stat.talkedToVillager", new Object[0]))).h(); + public static Statistic G = (new CounterStatistic("stat.tradedWithVillager", new ChatMessage("stat.tradedWithVillager", new Object[0]))).h(); + public static Statistic H = (new CounterStatistic("stat.cakeSlicesEaten", new ChatMessage("stat.cakeSlicesEaten", new Object[0]))).h(); + public static Statistic I = (new CounterStatistic("stat.cauldronFilled", new ChatMessage("stat.cauldronFilled", new Object[0]))).h(); + public static Statistic J = (new CounterStatistic("stat.cauldronUsed", new ChatMessage("stat.cauldronUsed", new Object[0]))).h(); + public static Statistic K = (new CounterStatistic("stat.armorCleaned", new ChatMessage("stat.armorCleaned", new Object[0]))).h(); + public static Statistic L = (new CounterStatistic("stat.bannerCleaned", new ChatMessage("stat.bannerCleaned", new Object[0]))).h(); + public static Statistic M = (new CounterStatistic("stat.brewingstandInteraction", new ChatMessage("stat.brewingstandInteraction", new Object[0]))).h(); + public static Statistic N = (new CounterStatistic("stat.beaconInteraction", new ChatMessage("stat.beaconInteraction", new Object[0]))).h(); + public static Statistic O = (new CounterStatistic("stat.dropperInspected", new ChatMessage("stat.dropperInspected", new Object[0]))).h(); + public static Statistic P = (new CounterStatistic("stat.hopperInspected", new ChatMessage("stat.hopperInspected", new Object[0]))).h(); + public static Statistic Q = (new CounterStatistic("stat.dispenserInspected", new ChatMessage("stat.dispenserInspected", new Object[0]))).h(); + public static Statistic R = (new CounterStatistic("stat.noteblockPlayed", new ChatMessage("stat.noteblockPlayed", new Object[0]))).h(); + public static Statistic S = (new CounterStatistic("stat.noteblockTuned", new ChatMessage("stat.noteblockTuned", new Object[0]))).h(); + public static Statistic T = (new CounterStatistic("stat.flowerPotted", new ChatMessage("stat.flowerPotted", new Object[0]))).h(); + public static Statistic U = (new CounterStatistic("stat.trappedChestTriggered", new ChatMessage("stat.trappedChestTriggered", new Object[0]))).h(); + public static Statistic V = (new CounterStatistic("stat.enderchestOpened", new ChatMessage("stat.enderchestOpened", new Object[0]))).h(); + public static Statistic W = (new CounterStatistic("stat.itemEnchanted", new ChatMessage("stat.itemEnchanted", new Object[0]))).h(); + public static Statistic X = (new CounterStatistic("stat.recordPlayed", new ChatMessage("stat.recordPlayed", new Object[0]))).h(); + public static Statistic Y = (new CounterStatistic("stat.furnaceInteraction", new ChatMessage("stat.furnaceInteraction", new Object[0]))).h(); + public static Statistic Z = (new CounterStatistic("stat.craftingTableInteraction", new ChatMessage("stat.workbenchInteraction", new Object[0]))).h(); + public static Statistic aa = (new CounterStatistic("stat.chestOpened", new ChatMessage("stat.chestOpened", new Object[0]))).h(); + public static final Statistic[] MINE_BLOCK_COUNT = new Statistic[4096]; + public static final Statistic[] CRAFT_BLOCK_COUNT = new Statistic[32000]; + public static final Statistic[] USE_ITEM_COUNT = new Statistic[32000]; + public static final Statistic[] BREAK_ITEM_COUNT = new Statistic[32000]; + + public static void a() { + c(); + d(); + e(); + b(); + AchievementList.a(); + EntityTypes.a(); + } + + private static void b() { + HashSet hashset = Sets.newHashSet(); + Iterator iterator = CraftingManager.getInstance().getRecipes().iterator(); + + while (iterator.hasNext()) { + IRecipe irecipe = (IRecipe) iterator.next(); + + if (irecipe.b() != null) { + hashset.add(irecipe.b().getItem()); + } + } + + iterator = RecipesFurnace.getInstance().getRecipes().values().iterator(); + + while (iterator.hasNext()) { + ItemStack itemstack = (ItemStack) iterator.next(); + + hashset.add(itemstack.getItem()); + } + + iterator = hashset.iterator(); + + while (iterator.hasNext()) { + Item item = (Item) iterator.next(); + + if (item != null) { + int i = Item.getId(item); + String s = a(item); + + if (s != null) { + StatisticList.CRAFT_BLOCK_COUNT[i] = (new CraftingStatistic("stat.craftItem.", s, new ChatMessage("stat.craftItem", new Object[] { (new ItemStack(item)).C()}), item)).h(); + } + } + } + + a(StatisticList.CRAFT_BLOCK_COUNT); + } + + private static void c() { + Iterator iterator = Block.REGISTRY.iterator(); + + while (iterator.hasNext()) { + Block block = (Block) iterator.next(); + Item item = Item.getItemOf(block); + + if (item != null) { + int i = Block.getId(block); + String s = a(item); + + if (s != null && block.J()) { + StatisticList.MINE_BLOCK_COUNT[i] = (new CraftingStatistic("stat.mineBlock.", s, new ChatMessage("stat.mineBlock", new Object[] { (new ItemStack(block)).C()}), item)).h(); + StatisticList.e.add((CraftingStatistic) StatisticList.MINE_BLOCK_COUNT[i]); + } + } + } + + a(StatisticList.MINE_BLOCK_COUNT); + } + + private static void d() { + Iterator iterator = Item.REGISTRY.iterator(); + + while (iterator.hasNext()) { + Item item = (Item) iterator.next(); + + if (item != null) { + int i = Item.getId(item); + String s = a(item); + + if (s != null) { + StatisticList.USE_ITEM_COUNT[i] = (new CraftingStatistic("stat.useItem.", s, new ChatMessage("stat.useItem", new Object[] { (new ItemStack(item)).C()}), item)).h(); + if (!(item instanceof ItemBlock)) { + StatisticList.d.add((CraftingStatistic) StatisticList.USE_ITEM_COUNT[i]); + } + } + } + } + + a(StatisticList.USE_ITEM_COUNT); + } + + private static void e() { + Iterator iterator = Item.REGISTRY.iterator(); + + while (iterator.hasNext()) { + Item item = (Item) iterator.next(); + + if (item != null) { + int i = Item.getId(item); + String s = a(item); + + if (s != null && item.usesDurability()) { + StatisticList.BREAK_ITEM_COUNT[i] = (new CraftingStatistic("stat.breakItem.", s, new ChatMessage("stat.breakItem", new Object[] { (new ItemStack(item)).C()}), item)).h(); + } + } + } + + a(StatisticList.BREAK_ITEM_COUNT); + } + + private static String a(Item item) { + MinecraftKey minecraftkey = (MinecraftKey) Item.REGISTRY.c(item); + + return minecraftkey != null ? minecraftkey.toString().replace(':', '.') : null; + } + + private static void a(Statistic[] astatistic) { + a(astatistic, Blocks.WATER, Blocks.FLOWING_WATER); + a(astatistic, Blocks.LAVA, Blocks.FLOWING_LAVA); + a(astatistic, Blocks.LIT_PUMPKIN, Blocks.PUMPKIN); + a(astatistic, Blocks.LIT_FURNACE, Blocks.FURNACE); + a(astatistic, Blocks.LIT_REDSTONE_ORE, Blocks.REDSTONE_ORE); + a(astatistic, Blocks.POWERED_REPEATER, Blocks.UNPOWERED_REPEATER); + a(astatistic, Blocks.POWERED_COMPARATOR, Blocks.UNPOWERED_COMPARATOR); + a(astatistic, Blocks.REDSTONE_TORCH, Blocks.UNLIT_REDSTONE_TORCH); + a(astatistic, Blocks.LIT_REDSTONE_LAMP, Blocks.REDSTONE_LAMP); + a(astatistic, Blocks.DOUBLE_STONE_SLAB, Blocks.STONE_SLAB); + a(astatistic, Blocks.DOUBLE_WOODEN_SLAB, Blocks.WOODEN_SLAB); + a(astatistic, Blocks.DOUBLE_STONE_SLAB2, Blocks.STONE_SLAB2); + a(astatistic, Blocks.GRASS, Blocks.DIRT); + a(astatistic, Blocks.FARMLAND, Blocks.DIRT); + } + + private static void a(Statistic[] astatistic, Block block, Block block1) { + int i = Block.getId(block); + int j = Block.getId(block1); + + if (astatistic[i] != null && astatistic[j] == null) { + astatistic[j] = astatistic[i]; + } else { + StatisticList.stats.remove(astatistic[i]); + StatisticList.e.remove(astatistic[i]); + StatisticList.c.remove(astatistic[i]); + astatistic[i] = astatistic[j]; + } + } + + public static Statistic a(EntityTypes.MonsterEggInfo entitytypes_monsteregginfo) { + String s = EntityTypes.b(entitytypes_monsteregginfo.a); + + return s == null ? null : (new Statistic("stat.killEntity." + s, new ChatMessage("stat.entityKill", new Object[] { new ChatMessage("entity." + s + ".name", new Object[0])}))).h(); + } + + public static Statistic b(EntityTypes.MonsterEggInfo entitytypes_monsteregginfo) { + String s = EntityTypes.b(entitytypes_monsteregginfo.a); + + return s == null ? null : (new Statistic("stat.entityKilledBy." + s, new ChatMessage("stat.entityKilledBy", new Object[] { new ChatMessage("entity." + s + ".name", new Object[0])}))).h(); + } + + public static Statistic getStatistic(String s) { + return (Statistic) StatisticList.a.get(s); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/StatisticManager.java b/azurite-server/src/main/java/net/minecraft/server/StatisticManager.java new file mode 100644 index 0000000..8f5aaa5 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/StatisticManager.java @@ -0,0 +1,60 @@ +package net.minecraft.server; + +import com.google.common.collect.Maps; +import org.bukkit.event.player.PlayerAchievementAwardedEvent; +import org.bukkit.event.player.PlayerStatisticIncrementEvent; + +import java.util.Map; + +public class StatisticManager { + + protected final Map a = Maps.newConcurrentMap(); + + public StatisticManager() {} + + public boolean hasAchievement(Achievement achievement) { + return this.getStatisticValue(achievement) > 0; + } + + public boolean b(Achievement achievement) { + return achievement.c == null || this.hasAchievement(achievement.c); + } + + public void b(EntityHuman entityhuman, Statistic statistic, int i) { + if (!statistic.d() || this.b((Achievement) statistic)) { + if (PlayerAchievementAwardedEvent.getHandlerList().getRegisteredListeners().length > 0 || PlayerStatisticIncrementEvent.getHandlerList().getRegisteredListeners().length > 0) { // Azurite - only trigger event if there a listeners + // CraftBukkit start - fire Statistic events + org.bukkit.event.Cancellable cancellable = org.bukkit.craftbukkit.event.CraftEventFactory.handleStatisticsIncrease(entityhuman, statistic, this.getStatisticValue(statistic), i); + if (cancellable != null && cancellable.isCancelled()) { + return; + } + // CraftBukkit end + } + + this.setStatistic(entityhuman, statistic, this.getStatisticValue(statistic) + i); + } + } + + public void setStatistic(EntityHuman entityhuman, Statistic statistic, int i) { + StatisticWrapper statisticwrapper = this.a.computeIfAbsent(statistic, k -> new StatisticWrapper()); + statisticwrapper.a(i); + } + + public int getStatisticValue(Statistic statistic) { + StatisticWrapper statisticwrapper = this.a.get(statistic); + + return statisticwrapper == null ? 0 : statisticwrapper.a(); + } + + public T b(Statistic statistic) { + StatisticWrapper statisticwrapper = this.a.get(statistic); + + return statisticwrapper != null ? (T) statisticwrapper.b() : null; // CraftBukkit - fix decompile error + } + + public T a(Statistic statistic, T t0) { + StatisticWrapper statisticwrapper = this.a.computeIfAbsent(statistic, k -> new StatisticWrapper()); + statisticwrapper.a(t0); + return t0; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/StatisticWrapper.java b/azurite-server/src/main/java/net/minecraft/server/StatisticWrapper.java new file mode 100644 index 0000000..906aa3d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/StatisticWrapper.java @@ -0,0 +1,25 @@ +package net.minecraft.server; + +public class StatisticWrapper { + + private int a; + private IJsonStatistic b; + + public StatisticWrapper() {} + + public int a() { + return this.a; + } + + public void a(int i) { + this.a = i; + } + + public T b() { + return (T) this.b; + } + + public void a(IJsonStatistic ijsonstatistic) { + this.b = ijsonstatistic; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/StatusChallengeUtils.java b/azurite-server/src/main/java/net/minecraft/server/StatusChallengeUtils.java new file mode 100644 index 0000000..32dae8f --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/StatusChallengeUtils.java @@ -0,0 +1,36 @@ +package net.minecraft.server; + +import com.google.common.base.Charsets; + +public class StatusChallengeUtils { + + public static final char[] a = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; + + public static String a(byte[] abyte, int i, int j) { + int k = j - 1; + + int l; + + for (l = i > k ? k : i; 0 != abyte[l] && l < k; ++l) { + ; + } + + return new String(abyte, i, l - i, Charsets.UTF_8); + } + + public static int b(byte[] abyte, int i) { + return b(abyte, i, abyte.length); + } + + public static int b(byte[] abyte, int i, int j) { + return 0 > j - i - 4 ? 0 : abyte[i + 3] << 24 | (abyte[i + 2] & 255) << 16 | (abyte[i + 1] & 255) << 8 | abyte[i] & 255; + } + + public static int c(byte[] abyte, int i, int j) { + return 0 > j - i - 4 ? 0 : abyte[i] << 24 | (abyte[i + 1] & 255) << 16 | (abyte[i + 2] & 255) << 8 | abyte[i + 3] & 255; + } + + public static String a(byte b0) { + return "" + StatusChallengeUtils.a[(b0 & 240) >>> 4] + StatusChallengeUtils.a[b0 & 15]; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/StructureBoundingBox.java b/azurite-server/src/main/java/net/minecraft/server/StructureBoundingBox.java new file mode 100644 index 0000000..10a5ea8 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/StructureBoundingBox.java @@ -0,0 +1,146 @@ +package net.minecraft.server; + +import com.google.common.base.Objects; + +public class StructureBoundingBox { + public int a; + public int b; + public int c; + public int d; + public int e; + public int f; + + public StructureBoundingBox() { + } + + public StructureBoundingBox(int[] var1) { + if (var1.length == 6) { + this.a = var1[0]; + this.b = var1[1]; + this.c = var1[2]; + this.d = var1[3]; + this.e = var1[4]; + this.f = var1[5]; + } + + } + + public static StructureBoundingBox a() { + return new StructureBoundingBox(Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE); + } + + public static StructureBoundingBox a(int var0, int var1, int var2, int var3, int var4, int var5, int var6, int var7, int var8, EnumDirection var9) { + switch (var9) { + case NORTH: + return new StructureBoundingBox(var0 + var3, var1 + var4, var2 - var8 + 1 + var5, var0 + var6 - 1 + var3, var1 + var7 - 1 + var4, var2 + var5); + case WEST: + return new StructureBoundingBox(var0 - var8 + 1 + var5, var1 + var4, var2 + var3, var0 + var5, var1 + var7 - 1 + var4, var2 + var6 - 1 + var3); + case EAST: + return new StructureBoundingBox(var0 + var5, var1 + var4, var2 + var3, var0 + var8 - 1 + var5, var1 + var7 - 1 + var4, var2 + var6 - 1 + var3); + default: + return new StructureBoundingBox(var0 + var3, var1 + var4, var2 + var5, var0 + var6 - 1 + var3, var1 + var7 - 1 + var4, var2 + var8 - 1 + var5); + } + } + + public static StructureBoundingBox a(int var0, int var1, int var2, int var3, int var4, int var5) { + return new StructureBoundingBox(Math.min(var0, var3), Math.min(var1, var4), Math.min(var2, var5), Math.max(var0, var3), Math.max(var1, var4), Math.max(var2, var5)); + } + + public StructureBoundingBox(StructureBoundingBox var1) { + this.a = var1.a; + this.b = var1.b; + this.c = var1.c; + this.d = var1.d; + this.e = var1.e; + this.f = var1.f; + } + + public StructureBoundingBox(int var1, int var2, int var3, int var4, int var5, int var6) { + this.a = var1; + this.b = var2; + this.c = var3; + this.d = var4; + this.e = var5; + this.f = var6; + } + + public StructureBoundingBox(BaseBlockPosition var1, BaseBlockPosition var2) { + this.a = Math.min(var1.getX(), var2.getX()); + this.b = Math.min(var1.getY(), var2.getY()); + this.c = Math.min(var1.getZ(), var2.getZ()); + this.d = Math.max(var1.getX(), var2.getX()); + this.e = Math.max(var1.getY(), var2.getY()); + this.f = Math.max(var1.getZ(), var2.getZ()); + } + + public StructureBoundingBox(int var1, int var2, int var3, int var4) { + this.a = var1; + this.c = var2; + this.d = var3; + this.f = var4; + this.b = 1; + this.e = 512; + } + + public boolean a(StructureBoundingBox var1) { + return this.d >= var1.a && this.a <= var1.d && this.f >= var1.c && this.c <= var1.f && this.e >= var1.b && this.b <= var1.e; + } + + public boolean a(int var1, int var2, int var3, int var4) { + return this.d >= var1 && this.a <= var3 && this.f >= var2 && this.c <= var4; + } + + public void b(StructureBoundingBox var1) { + this.a = Math.min(this.a, var1.a); + this.b = Math.min(this.b, var1.b); + this.c = Math.min(this.c, var1.c); + this.d = Math.max(this.d, var1.d); + this.e = Math.max(this.e, var1.e); + this.f = Math.max(this.f, var1.f); + } + + public void a(int var1, int var2, int var3) { + this.a += var1; + this.b += var2; + this.c += var3; + this.d += var1; + this.e += var2; + this.f += var3; + } + + public boolean b(BaseBlockPosition var1) { + return var1.getX() >= this.a && var1.getX() <= this.d && var1.getZ() >= this.c && var1.getZ() <= this.f && var1.getY() >= this.b && var1.getY() <= this.e; + } + + public boolean b(int x, int y, int z) { + return x >= this.a && x <= this.d && z >= this.c && z <= this.f && y >= this.b && y <= this.e; + } + + public BaseBlockPosition b() { + return new BaseBlockPosition(this.d - this.a, this.e - this.b, this.f - this.c); + } + + public int c() { + return this.d - this.a + 1; + } + + public int d() { + return this.e - this.b + 1; + } + + public int e() { + return this.f - this.c + 1; + } + + public BaseBlockPosition f() { + return new BlockPosition(this.a + (this.d - this.a + 1) / 2, this.b + (this.e - this.b + 1) / 2, this.c + (this.f - this.c + 1) / 2); + } + + public String toString() { + return Objects.toStringHelper(this).add("x0", this.a).add("y0", this.b).add("z0", this.c).add("x1", this.d).add("y1", this.e).add("z1", this.f).toString(); + } + + public NBTTagIntArray g() { + return new NBTTagIntArray(new int[]{this.a, this.b, this.c, this.d, this.e, this.f}); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/StructureGenerator.java b/azurite-server/src/main/java/net/minecraft/server/StructureGenerator.java new file mode 100644 index 0000000..106a900 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/StructureGenerator.java @@ -0,0 +1,236 @@ +package net.minecraft.server; + +import com.google.common.collect.Maps; + +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.concurrent.Callable; + +public abstract class StructureGenerator extends WorldGenBase { + + private PersistentStructure d; + protected Map e = Maps.newHashMap(); + + public StructureGenerator() {} + + public abstract String a(); + + protected final void a(World world, final int i, final int j, int k, int l, ChunkSnapshot chunksnapshot) { + this.a(world); + long hash = ChunkCoordIntPair.a(i, j); + if (!this.e.containsKey(hash)) { + + try { + if (this.a(i, j)) { + StructureStart structurestart = this.b(i, j); + + this.e.put(hash, structurestart); + this.a(i, j, structurestart); + } + + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.a(throwable, "Exception preparing structure feature"); + CrashReportSystemDetails crashreportsystemdetails = crashreport.a("Feature being prepared"); + + crashreportsystemdetails.a("Is feature chunk", new Callable() { + public String a() { + return StructureGenerator.this.a(i, j) ? "True" : "False"; + } + + public Object call() { + return this.a(); + } + }); + crashreportsystemdetails.a("Chunk location", String.format("%d,%d", i, j)); + crashreportsystemdetails.a("Chunk pos hash", new Callable() { + public String a() { + return String.valueOf(hash); + } + + public Object call() { + return this.a(); + } + }); + crashreportsystemdetails.a("Structure type", new Callable() { + public String a() { + return StructureGenerator.this.getClass().getCanonicalName(); + } + + public Object call() { + return this.a(); + } + }); + throw new ReportedException(crashreport); + } + } + } + + public boolean a(World world, Random random, ChunkCoordIntPair chunkcoordintpair) { + this.a(world); + int i = (chunkcoordintpair.x << 4) + 8; + int j = (chunkcoordintpair.z << 4) + 8; + boolean flag = false; + + for (StructureStart structurestart : this.e.values()) { + if (structurestart.d() && structurestart.a(chunkcoordintpair) && structurestart.a().a(i, j, i + 15, j + 15)) { + structurestart.a(world, random, new StructureBoundingBox(i, j, i + 15, j + 15)); + structurestart.b(chunkcoordintpair); + flag = true; + this.a(structurestart.e(), structurestart.f(), structurestart); + } + } + + return flag; + } + + public boolean b(BlockPosition blockposition) { + if (this.c == null) return false; // PaperSpigot + this.a(this.c); + return this.c(blockposition) != null; + } + + protected StructureStart c(BlockPosition blockposition) { + + for (StructureStart structurestart : this.e.values()) { + if (structurestart.d() && structurestart.a().b(blockposition)) { + + for (StructurePiece structurepiece : structurestart.b()) { + if (structurepiece.c().b(blockposition)) { + return structurestart; + } + } + } + } + + return null; + } + + public boolean a(World world, BlockPosition blockposition) { + if (this.c == null) return false; // PaperSpigot + this.a(world); + Iterator iterator = this.e.values().iterator(); + + StructureStart structurestart; + + do { + if (!iterator.hasNext()) { + return false; + } + + structurestart = iterator.next(); + } while (!structurestart.d() || !structurestart.a().b(blockposition)); + + return true; + } + + public BlockPosition getNearestGeneratedFeature(World world, BlockPosition blockposition) { + this.c = world; + this.a(world); + this.b.setSeed(world.getSeed()); + long i = this.b.nextLong(); + long j = this.b.nextLong(); + long k = (long) (blockposition.getX() >> 4) * i; + long l = (long) (blockposition.getZ() >> 4) * j; + + this.b.setSeed(k ^ l ^ world.getSeed()); + this.a(world, blockposition.getX() >> 4, blockposition.getZ() >> 4, 0, 0, null); + double d0 = Double.MAX_VALUE; + BlockPosition blockposition1 = null; + Iterator iterator = this.e.values().iterator(); + + BlockPosition blockposition2; + double d1; + + while (iterator.hasNext()) { + StructureStart structurestart = iterator.next(); + + if (structurestart.d()) { + StructurePiece structurepiece = structurestart.b().get(0); + + blockposition2 = structurepiece.a(); + d1 = blockposition2.i(blockposition); + if (d1 < d0) { + d0 = d1; + blockposition1 = blockposition2; + } + } + } + + if (blockposition1 != null) { + return blockposition1; + } else { + List list = this.z_(); + + if (list != null) { + BlockPosition blockposition3 = null; + + for (BlockPosition blockPosition : list) { + blockposition2 = blockPosition; + d1 = blockposition2.i(blockposition); + if (d1 < d0) { + d0 = d1; + blockposition3 = blockposition2; + } + } + + return blockposition3; + } else { + return null; + } + } + } + + protected List z_() { + return null; + } + + private void a(World world) { + if (this.d == null) { + // Spigot Start + if ( world.spigotConfig.saveStructureInfo && !this.a().equals( "Mineshaft" ) ) + { + this.d = (PersistentStructure) world.a(PersistentStructure.class, this.a()); + } else + { + this.d = new PersistentStructure( this.a() ); + } + // Spigot End + if (this.d == null) { + this.d = new PersistentStructure(this.a()); + world.a(this.a(), this.d); + } else { + NBTTagCompound nbttagcompound = this.d.a(); + + for (String s : nbttagcompound.c()) { + NBTBase nbtbase = nbttagcompound.get(s); + + if (nbtbase.getTypeId() == 10) { + NBTTagCompound nbttagcompound1 = (NBTTagCompound) nbtbase; + + if (nbttagcompound1.hasKey("ChunkX") && nbttagcompound1.hasKey("ChunkZ")) { + int i = nbttagcompound1.getInt("ChunkX"); + int j = nbttagcompound1.getInt("ChunkZ"); + StructureStart structurestart = WorldGenFactory.a(nbttagcompound1, world); + + if (structurestart != null) { + this.e.put(ChunkCoordIntPair.a(i, j), structurestart); + } + } + } + } + } + } + + } + + private void a(int i, int j, StructureStart structurestart) { + this.d.a(structurestart.a(i, j), i, j); + this.d.c(); + } + + protected abstract boolean a(int i, int j); + + protected abstract StructureStart b(int i, int j); +} diff --git a/azurite-server/src/main/java/net/minecraft/server/StructurePiece.java b/azurite-server/src/main/java/net/minecraft/server/StructurePiece.java new file mode 100644 index 0000000..41cc1df --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/StructurePiece.java @@ -0,0 +1,631 @@ +package net.minecraft.server; + +import java.util.Iterator; +import java.util.List; +import java.util.Random; + +public abstract class StructurePiece { + + protected StructureBoundingBox l; + protected EnumDirection m; + protected int n; + + public StructurePiece() { + } + + protected StructurePiece(int i) { + this.n = i; + } + + public NBTTagCompound b() { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + + nbttagcompound.setString("id", WorldGenFactory.a(this)); + nbttagcompound.set("BB", this.l.g()); + nbttagcompound.setInt("O", this.m == null ? -1 : this.m.b()); + nbttagcompound.setInt("GD", this.n); + this.a(nbttagcompound); + return nbttagcompound; + } + + protected abstract void a(NBTTagCompound nbttagcompound); + + public void a(World world, NBTTagCompound nbttagcompound) { + if (nbttagcompound.hasKey("BB")) { + this.l = new StructureBoundingBox(nbttagcompound.getIntArray("BB")); + } + + int i = nbttagcompound.getInt("O"); + + this.m = i == -1 ? null : EnumDirection.fromType2(i); + this.n = nbttagcompound.getInt("GD"); + this.b(nbttagcompound); + } + + protected abstract void b(NBTTagCompound nbttagcompound); + + public void a(StructurePiece structurepiece, List list, Random random) { + } + + public abstract boolean a(World world, Random random, StructureBoundingBox structureboundingbox); + + public StructureBoundingBox c() { + return this.l; + } + + public int d() { + return this.n; + } + + public static StructurePiece a(List list, StructureBoundingBox structureboundingbox) { + Iterator iterator = list.iterator(); + + StructurePiece structurepiece; + + do { + if (!iterator.hasNext()) { + return null; + } + + structurepiece = iterator.next(); + } while (structurepiece.c() == null || !structurepiece.c().a(structureboundingbox)); + + return structurepiece; + } + + public BlockPosition a() { + return new BlockPosition(this.l.f()); + } + + protected boolean a(World world, StructureBoundingBox structureboundingbox) { + int i = Math.max(this.l.a - 1, structureboundingbox.a); + int j = Math.max(this.l.b - 1, structureboundingbox.b); + int k = Math.max(this.l.c - 1, structureboundingbox.c); + int l = Math.min(this.l.d + 1, structureboundingbox.d); + int i1 = Math.min(this.l.e + 1, structureboundingbox.e); + int j1 = Math.min(this.l.f + 1, structureboundingbox.f); + + int k1; + int l1; + + for (k1 = i; k1 <= l; ++k1) { + for (l1 = k; l1 <= j1; ++l1) { + if (world.getType(k1, j, l1).getBlock().getMaterial().isLiquid() || world.getType(k1, i1, l1).getBlock().getMaterial().isLiquid()) { + return true; + } + } + } + + for (k1 = i; k1 <= l; ++k1) { + for (l1 = j; l1 <= i1; ++l1) { + if (world.getType(k1, l1, k).getBlock().getMaterial().isLiquid() || world.getType(k1, l1, j1).getBlock().getMaterial().isLiquid()) { + return true; + } + } + } + + for (k1 = k; k1 <= j1; ++k1) { + for (l1 = j; l1 <= i1; ++l1) { + if (world.getType(i, l1, k1).getBlock().getMaterial().isLiquid() || world.getType(l, l1, k1).getBlock().getMaterial().isLiquid()) { + return true; + } + } + } + + return false; + } + + protected int a(int i, int j) { + if (this.m == null) { + return i; + } else { + switch (StructurePiece.SyntheticClass_1.a[this.m.ordinal()]) { + case 1: + case 2: + return this.l.a + i; + + case 3: + return this.l.d - j; + + case 4: + return this.l.a + j; + + default: + return i; + } + } + } + + protected int d(int i) { + return this.m == null ? i : i + this.l.b; + } + + protected int b(int i, int j) { + if (this.m == null) { + return j; + } else { + switch (StructurePiece.SyntheticClass_1.a[this.m.ordinal()]) { + case 1: + return this.l.f - j; + + case 2: + return this.l.c + j; + + case 3: + case 4: + return this.l.c + i; + + default: + return j; + } + } + } + + protected int a(Block block, int i) { + if (block == Blocks.RAIL) { + if (this.m == EnumDirection.WEST || this.m == EnumDirection.EAST) { + if (i == 1) { + return 0; + } + + return 1; + } + } else if (block instanceof BlockDoor) { + if (this.m == EnumDirection.SOUTH) { + if (i == 0) { + return 2; + } + + if (i == 2) { + return 0; + } + } else { + if (this.m == EnumDirection.WEST) { + return i + 1 & 3; + } + + if (this.m == EnumDirection.EAST) { + return i + 3 & 3; + } + } + } else if (block != Blocks.STONE_STAIRS && block != Blocks.OAK_STAIRS && block != Blocks.NETHER_BRICK_STAIRS && block != Blocks.STONE_BRICK_STAIRS && block != Blocks.SANDSTONE_STAIRS) { + if (block == Blocks.LADDER) { + if (this.m == EnumDirection.SOUTH) { + if (i == EnumDirection.NORTH.a()) { + return EnumDirection.SOUTH.a(); + } + + if (i == EnumDirection.SOUTH.a()) { + return EnumDirection.NORTH.a(); + } + } else if (this.m == EnumDirection.WEST) { + if (i == EnumDirection.NORTH.a()) { + return EnumDirection.WEST.a(); + } + + if (i == EnumDirection.SOUTH.a()) { + return EnumDirection.EAST.a(); + } + + if (i == EnumDirection.WEST.a()) { + return EnumDirection.NORTH.a(); + } + + if (i == EnumDirection.EAST.a()) { + return EnumDirection.SOUTH.a(); + } + } else if (this.m == EnumDirection.EAST) { + if (i == EnumDirection.NORTH.a()) { + return EnumDirection.EAST.a(); + } + + if (i == EnumDirection.SOUTH.a()) { + return EnumDirection.WEST.a(); + } + + if (i == EnumDirection.WEST.a()) { + return EnumDirection.NORTH.a(); + } + + if (i == EnumDirection.EAST.a()) { + return EnumDirection.SOUTH.a(); + } + } + } else if (block == Blocks.STONE_BUTTON) { + if (this.m == EnumDirection.SOUTH) { + if (i == 3) { + return 4; + } + + if (i == 4) { + return 3; + } + } else if (this.m == EnumDirection.WEST) { + if (i == 3) { + return 1; + } + + if (i == 4) { + return 2; + } + + if (i == 2) { + return 3; + } + + if (i == 1) { + return 4; + } + } else if (this.m == EnumDirection.EAST) { + if (i == 3) { + return 2; + } + + if (i == 4) { + return 1; + } + + if (i == 2) { + return 3; + } + + if (i == 1) { + return 4; + } + } + } else if (block != Blocks.TRIPWIRE_HOOK && !(block instanceof BlockDirectional)) { + if (block == Blocks.PISTON || block == Blocks.STICKY_PISTON || block == Blocks.LEVER || block == Blocks.DISPENSER) { + if (this.m == EnumDirection.SOUTH) { + if (i == EnumDirection.NORTH.a() || i == EnumDirection.SOUTH.a()) { + return EnumDirection.fromType1(i).opposite().a(); + } + } else if (this.m == EnumDirection.WEST) { + if (i == EnumDirection.NORTH.a()) { + return EnumDirection.WEST.a(); + } + + if (i == EnumDirection.SOUTH.a()) { + return EnumDirection.EAST.a(); + } + + if (i == EnumDirection.WEST.a()) { + return EnumDirection.NORTH.a(); + } + + if (i == EnumDirection.EAST.a()) { + return EnumDirection.SOUTH.a(); + } + } else if (this.m == EnumDirection.EAST) { + if (i == EnumDirection.NORTH.a()) { + return EnumDirection.EAST.a(); + } + + if (i == EnumDirection.SOUTH.a()) { + return EnumDirection.WEST.a(); + } + + if (i == EnumDirection.WEST.a()) { + return EnumDirection.NORTH.a(); + } + + if (i == EnumDirection.EAST.a()) { + return EnumDirection.SOUTH.a(); + } + } + } + } else { + EnumDirection enumdirection = EnumDirection.fromType2(i); + + if (this.m == EnumDirection.SOUTH) { + if (enumdirection == EnumDirection.SOUTH || enumdirection == EnumDirection.NORTH) { + return enumdirection.opposite().b(); + } + } else if (this.m == EnumDirection.WEST) { + if (enumdirection == EnumDirection.NORTH) { + return EnumDirection.WEST.b(); + } + + if (enumdirection == EnumDirection.SOUTH) { + return EnumDirection.EAST.b(); + } + + if (enumdirection == EnumDirection.WEST) { + return EnumDirection.NORTH.b(); + } + + if (enumdirection == EnumDirection.EAST) { + return EnumDirection.SOUTH.b(); + } + } else if (this.m == EnumDirection.EAST) { + if (enumdirection == EnumDirection.NORTH) { + return EnumDirection.EAST.b(); + } + + if (enumdirection == EnumDirection.SOUTH) { + return EnumDirection.WEST.b(); + } + + if (enumdirection == EnumDirection.WEST) { + return EnumDirection.NORTH.b(); + } + + if (enumdirection == EnumDirection.EAST) { + return EnumDirection.SOUTH.b(); + } + } + } + } else if (this.m == EnumDirection.SOUTH) { + if (i == 2) { + return 3; + } + + if (i == 3) { + return 2; + } + } else if (this.m == EnumDirection.WEST) { + if (i == 0) { + return 2; + } + + if (i == 1) { + return 3; + } + + if (i == 2) { + return 0; + } + + if (i == 3) { + return 1; + } + } else if (this.m == EnumDirection.EAST) { + if (i == 0) { + return 2; + } + + if (i == 1) { + return 3; + } + + if (i == 2) { + return 1; + } + + if (i == 3) { + return 0; + } + } + + return i; + } + + protected void a(World world, IBlockData iblockdata, int i, int j, int k, StructureBoundingBox structureboundingbox) { + int x = a(i, k), y = d(j), z = b(i, k); + if (structureboundingbox.b(x, y, z)) { + world.setTypeAndData(new BlockPosition(x, y, z), iblockdata, 2); + } + } + + protected IBlockData a(World world, int i, int j, int k, StructureBoundingBox structureboundingbox) { + int l = this.a(i, k); + int i1 = this.d(j); + int j1 = this.b(i, k); + + return !structureboundingbox.b(l, i1, j1) ? Blocks.AIR.getBlockData() : world.getType(l, i1, j1); + } + + protected void a(World world, StructureBoundingBox structureboundingbox, int i, int j, int k, int l, int i1, int j1) { + for (int k1 = j; k1 <= i1; ++k1) { + for (int l1 = i; l1 <= l; ++l1) { + for (int i2 = k; i2 <= j1; ++i2) { + this.a(world, Blocks.AIR.getBlockData(), l1, k1, i2, structureboundingbox); + } + } + } + + } + + protected void a(World world, StructureBoundingBox structureboundingbox, int i, int j, int k, int l, int i1, int j1, IBlockData iblockdata, IBlockData iblockdata1, boolean flag) { + for (int k1 = j; k1 <= i1; ++k1) { + for (int l1 = i; l1 <= l; ++l1) { + for (int i2 = k; i2 <= j1; ++i2) { + if (!flag || this.a(world, l1, k1, i2, structureboundingbox).getBlock().getMaterial() != Material.AIR) { + if (k1 != j && k1 != i1 && l1 != i && l1 != l && i2 != k && i2 != j1) { + this.a(world, iblockdata1, l1, k1, i2, structureboundingbox); + } else { + this.a(world, iblockdata, l1, k1, i2, structureboundingbox); + } + } + } + } + } + + } + + protected void a(World world, StructureBoundingBox structureboundingbox, int i, int j, int k, int l, int i1, int j1, boolean flag, Random random, StructurePiece.StructurePieceBlockSelector structurepiece_structurepieceblockselector) { + for (int k1 = j; k1 <= i1; ++k1) { + for (int l1 = i; l1 <= l; ++l1) { + for (int i2 = k; i2 <= j1; ++i2) { + if (!flag || this.a(world, l1, k1, i2, structureboundingbox).getBlock().getMaterial() != Material.AIR) { + structurepiece_structurepieceblockselector.a(random, l1, k1, i2, k1 == j || k1 == i1 || l1 == i || l1 == l || i2 == k || i2 == j1); + this.a(world, structurepiece_structurepieceblockselector.a(), l1, k1, i2, structureboundingbox); + } + } + } + } + + } + + protected void a(World world, StructureBoundingBox structureboundingbox, Random random, float f, int i, int j, int k, int l, int i1, int j1, IBlockData iblockdata, IBlockData iblockdata1, boolean flag) { + for (int k1 = j; k1 <= i1; ++k1) { + for (int l1 = i; l1 <= l; ++l1) { + for (int i2 = k; i2 <= j1; ++i2) { + if (random.nextFloat() <= f && (!flag || this.a(world, l1, k1, i2, structureboundingbox).getBlock().getMaterial() != Material.AIR)) { + if (k1 != j && k1 != i1 && l1 != i && l1 != l && i2 != k && i2 != j1) { + this.a(world, iblockdata1, l1, k1, i2, structureboundingbox); + } else { + this.a(world, iblockdata, l1, k1, i2, structureboundingbox); + } + } + } + } + } + + } + + protected void a(World world, StructureBoundingBox structureboundingbox, Random random, float f, int i, int j, int k, IBlockData iblockdata) { + if (random.nextFloat() < f) { + this.a(world, iblockdata, i, j, k, structureboundingbox); + } + + } + + protected void a(World world, StructureBoundingBox structureboundingbox, int i, int j, int k, int l, int i1, int j1, IBlockData iblockdata, boolean flag) { + float f = (float) (l - i + 1); + float f1 = (float) (i1 - j + 1); + float f2 = (float) (j1 - k + 1); + float f3 = (float) i + f / 2.0F; + float f4 = (float) k + f2 / 2.0F; + + for (int k1 = j; k1 <= i1; ++k1) { + float f5 = (float) (k1 - j) / f1; + + for (int l1 = i; l1 <= l; ++l1) { + float f6 = ((float) l1 - f3) / (f * 0.5F); + + for (int i2 = k; i2 <= j1; ++i2) { + float f7 = ((float) i2 - f4) / (f2 * 0.5F); + + if (!flag || this.a(world, l1, k1, i2, structureboundingbox).getBlock().getMaterial() != Material.AIR) { + float f8 = f6 * f6 + f5 * f5 + f7 * f7; + + if (f8 <= 1.05F) { + this.a(world, iblockdata, l1, k1, i2, structureboundingbox); + } + } + } + } + } + + } + + protected void b(World world, int i, int j, int k, StructureBoundingBox structureboundingbox) { + int l = this.a(i, k); + int i1 = this.d(j); + int j1 = this.b(i, k); + + if (structureboundingbox.b(l, i1, j1)) { + BlockPosition.MutableBlockPosition pos = new BlockPosition.MutableBlockPosition(); + while (!world.isEmpty(l, i1, j1) && i1 < 255) { + world.setTypeAndData(pos.c(l, i1, j1), Blocks.AIR.getBlockData(), 2); + i1++; + } + + } + } + + protected void b(World world, IBlockData iblockdata, int i, int j, int k, StructureBoundingBox structureboundingbox) { + int l = this.a(i, k); + int i1 = this.d(j); + int j1 = this.b(i, k); + + if (structureboundingbox.b(l, i1, j1)) { + BlockPosition.MutableBlockPosition pos = new BlockPosition.MutableBlockPosition(); + while ((world.isEmpty(l, i1, j1) || world.getType(l, i1, j1).getBlock().getMaterial().isLiquid()) && i1 > 1) { + world.setTypeAndData(pos.c(l, i1, j1), iblockdata, 2); + --i1; + } + + } + } + + protected boolean a(World world, StructureBoundingBox structureboundingbox, Random random, int i, int j, int k, List list, int l) { + BlockPosition blockposition = new BlockPosition(this.a(i, k), this.d(j), this.b(i, k)); + + if (structureboundingbox.b(blockposition) && world.getType(blockposition).getBlock() != Blocks.CHEST) { + IBlockData iblockdata = Blocks.CHEST.getBlockData(); + + world.setTypeAndData(blockposition, Blocks.CHEST.f(world, blockposition, iblockdata), 2); + TileEntity tileentity = world.getTileEntity(blockposition); + + if (tileentity instanceof TileEntityChest) { + StructurePieceTreasure.a(random, list, (IInventory) ((TileEntityChest) tileentity), l); + } + + return true; + } else { + return false; + } + } + + protected boolean a(World world, StructureBoundingBox structureboundingbox, Random random, int i, int j, int k, int l, List list, int i1) { + BlockPosition blockposition = new BlockPosition(this.a(i, k), this.d(j), this.b(i, k)); + + if (structureboundingbox.b(blockposition) && world.getType(blockposition).getBlock() != Blocks.DISPENSER) { + world.setTypeAndData(blockposition, Blocks.DISPENSER.fromLegacyData(this.a(Blocks.DISPENSER, l)), 2); + TileEntity tileentity = world.getTileEntity(blockposition); + + if (tileentity instanceof TileEntityDispenser) { + StructurePieceTreasure.a(random, list, (TileEntityDispenser) tileentity, i1); + } + + return true; + } else { + return false; + } + } + + protected void a(World world, StructureBoundingBox structureboundingbox, Random random, int i, int j, int k, EnumDirection enumdirection) { + int x = a(i, k), y = d(j), z = b(i, k); + if (structureboundingbox.b(x, y, z)) { + ItemDoor.a(world, new BlockPosition(x, y, z), enumdirection.f(), Blocks.WOODEN_DOOR); + } + } + + public void a(int i, int j, int k) { + this.l.a(i, j, k); + } + + static class SyntheticClass_1 { + + static final int[] a = new int[EnumDirection.values().length]; + + static { + try { + StructurePiece.SyntheticClass_1.a[EnumDirection.NORTH.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + } + + try { + StructurePiece.SyntheticClass_1.a[EnumDirection.SOUTH.ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + } + + try { + StructurePiece.SyntheticClass_1.a[EnumDirection.WEST.ordinal()] = 3; + } catch (NoSuchFieldError ignored) { + } + + try { + StructurePiece.SyntheticClass_1.a[EnumDirection.EAST.ordinal()] = 4; + } catch (NoSuchFieldError ignored) { + } + + } + } + + public abstract static class StructurePieceBlockSelector { + + protected IBlockData a; + + protected StructurePieceBlockSelector() { + this.a = Blocks.AIR.getBlockData(); + } + + public abstract void a(Random random, int i, int j, int k, boolean flag); + + public IBlockData a() { + return this.a; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/StructurePieceTreasure.java b/azurite-server/src/main/java/net/minecraft/server/StructurePieceTreasure.java new file mode 100644 index 0000000..6265085 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/StructurePieceTreasure.java @@ -0,0 +1,80 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Random; + +public class StructurePieceTreasure extends WeightedRandom.WeightedRandomChoice { + + private final ItemStack b; + private final int c; + private final int d; + + public StructurePieceTreasure(Item item, int i, int j, int k, int l) { + super(l); + this.b = new ItemStack(item, 1, i); + this.c = j; + this.d = k; + } + + public StructurePieceTreasure(ItemStack itemstack, int i, int j, int k) { + super(k); + this.b = itemstack; + this.c = i; + this.d = j; + } + + public static void a(Random random, List list, IInventory iinventory, int i) { + for (int j = 0; j < i; ++j) { + StructurePieceTreasure structurepiecetreasure = WeightedRandom.a(random, list); + int k = structurepiecetreasure.c + random.nextInt(structurepiecetreasure.d - structurepiecetreasure.c + 1); + + if (structurepiecetreasure.b.getMaxStackSize() >= k) { + ItemStack itemstack = structurepiecetreasure.b.cloneItemStack(); + + itemstack.count = k; + iinventory.setItem(random.nextInt(iinventory.getSize()), itemstack); + } else { + for (int l = 0; l < k; ++l) { + ItemStack itemstack1 = structurepiecetreasure.b.cloneItemStack(); + + itemstack1.count = 1; + iinventory.setItem(random.nextInt(iinventory.getSize()), itemstack1); + } + } + } + + } + + public static void a(Random random, List list, TileEntityDispenser tileentitydispenser, int i) { + for (int j = 0; j < i; ++j) { + StructurePieceTreasure structurepiecetreasure = WeightedRandom.a(random, list); + int k = structurepiecetreasure.c + random.nextInt(structurepiecetreasure.d - structurepiecetreasure.c + 1); + + if (structurepiecetreasure.b.getMaxStackSize() >= k) { + ItemStack itemstack = structurepiecetreasure.b.cloneItemStack(); + + itemstack.count = k; + tileentitydispenser.setItem(random.nextInt(tileentitydispenser.getSize()), itemstack); + } else { + for (int l = 0; l < k; ++l) { + ItemStack itemstack1 = structurepiecetreasure.b.cloneItemStack(); + + itemstack1.count = 1; + tileentitydispenser.setItem(random.nextInt(tileentitydispenser.getSize()), itemstack1); + } + } + } + + } + + public static List a(List list, StructurePieceTreasure... astructurepiecetreasure) { + ArrayList arraylist = Lists.newArrayList(list); + + Collections.addAll(arraylist, astructurepiecetreasure); + return arraylist; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/StructureStart.java b/azurite-server/src/main/java/net/minecraft/server/StructureStart.java new file mode 100644 index 0000000..d2afa51 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/StructureStart.java @@ -0,0 +1,138 @@ +package net.minecraft.server; + +import java.util.LinkedList; +import java.util.Random; + +public abstract class StructureStart { + + protected LinkedList a = new LinkedList<>(); + protected StructureBoundingBox b; + private int c; + private int d; + + public StructureStart() { + } + + public StructureStart(int i, int j) { + this.c = i; + this.d = j; + } + + public StructureBoundingBox a() { + return this.b; + } + + public LinkedList b() { + return this.a; + } + + public void a(World world, Random random, StructureBoundingBox structureboundingbox) { + this.a.removeIf(structurepiece -> structurepiece.c().a(structureboundingbox) && !structurepiece.a(world, random, structureboundingbox)); + } + + protected void c() { + this.b = StructureBoundingBox.a(); + + for (StructurePiece structurepiece : this.a) { + this.b.b(structurepiece.c()); + } + + } + + public NBTTagCompound a(int i, int j) { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + + nbttagcompound.setString("id", WorldGenFactory.a(this)); + nbttagcompound.setInt("ChunkX", i); + nbttagcompound.setInt("ChunkZ", j); + nbttagcompound.set("BB", this.b.g()); + NBTTagList nbttaglist = new NBTTagList(); + + for (StructurePiece structurepiece : this.a) { + nbttaglist.add(structurepiece.b()); + } + + nbttagcompound.set("Children", nbttaglist); + this.a(nbttagcompound); + return nbttagcompound; + } + + public void a(NBTTagCompound nbttagcompound) { + } + + public void a(World world, NBTTagCompound nbttagcompound) { + this.c = nbttagcompound.getInt("ChunkX"); + this.d = nbttagcompound.getInt("ChunkZ"); + if (nbttagcompound.hasKey("BB")) { + this.b = new StructureBoundingBox(nbttagcompound.getIntArray("BB")); + } + + NBTTagList nbttaglist = nbttagcompound.getList("Children", 10); + + for (int i = 0; i < nbttaglist.size(); ++i) { + this.a.add(WorldGenFactory.b(nbttaglist.get(i), world)); + } + + this.b(nbttagcompound); + } + + public void b(NBTTagCompound nbttagcompound) { + } + + protected void a(World world, Random random, int i) { + int j = world.F() - i; + int k = this.b.d() + 1; + + if (k < j) { + k += random.nextInt(j - k); + } + + int l = k - this.b.e; + + this.b.a(0, l, 0); + + for (StructurePiece structurepiece : this.a) { + structurepiece.a(0, l, 0); + } + + } + + protected void a(World world, Random random, int i, int j) { + int k = j - i + 1 - this.b.d(); + int l; + + if (k > 1) { + l = i + random.nextInt(k); + } else { + l = i; + } + + int i1 = l - this.b.b; + + this.b.a(0, i1, 0); + + for (StructurePiece structurepiece : this.a) { + structurepiece.a(0, i1, 0); + } + + } + + public boolean d() { + return true; + } + + public boolean a(ChunkCoordIntPair chunkcoordintpair) { + return true; + } + + public void b(ChunkCoordIntPair chunkcoordintpair) { + } + + public int e() { + return this.c; + } + + public int f() { + return this.d; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/SystemUtils.java b/azurite-server/src/main/java/net/minecraft/server/SystemUtils.java new file mode 100644 index 0000000..e65ffc1 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/SystemUtils.java @@ -0,0 +1,21 @@ +package net.minecraft.server; + +import java.util.concurrent.ExecutionException; +import java.util.concurrent.FutureTask; +import org.apache.logging.log4j.Logger; + +public class SystemUtils { + + public static V a(FutureTask futuretask, Logger logger) { + try { + futuretask.run(); + return futuretask.get(); + } catch (ExecutionException executionexception) { + logger.fatal("Error executing task", executionexception); + } catch (InterruptedException interruptedexception) { + logger.fatal("Error executing task", interruptedexception); + } + + return null; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/ThreadWatchdog.java b/azurite-server/src/main/java/net/minecraft/server/ThreadWatchdog.java new file mode 100644 index 0000000..8a56c23 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/ThreadWatchdog.java @@ -0,0 +1,93 @@ +package net.minecraft.server; + +import java.io.File; +import java.lang.management.ManagementFactory; +import java.lang.management.ThreadInfo; +import java.lang.management.ThreadMXBean; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Timer; +import java.util.TimerTask; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +public class ThreadWatchdog implements Runnable { + + private static final Logger a = LogManager.getLogger(); + private final DedicatedServer b; + private final long c; + + public ThreadWatchdog(DedicatedServer dedicatedserver) { + this.b = dedicatedserver; + this.c = dedicatedserver.aS(); + } + + public void run() { + while (this.b.isRunning()) { + long i = this.b.aL(); + long j = MinecraftServer.az(); + long k = j - i; + + if (k > this.c) { + ThreadWatchdog.a.fatal("A single server tick took " + String.format("%.2f", new Object[] { Float.valueOf((float) k / 1000.0F)}) + " seconds (should be max " + String.format("%.2f", new Object[] { Float.valueOf(0.05F)}) + ")"); + ThreadWatchdog.a.fatal("Considering it to be crashed, server will forcibly shutdown."); + ThreadMXBean threadmxbean = ManagementFactory.getThreadMXBean(); + ThreadInfo[] athreadinfo = threadmxbean.dumpAllThreads(true, true); + StringBuilder stringbuilder = new StringBuilder(); + Error error = new Error(); + ThreadInfo[] athreadinfo1 = athreadinfo; + int l = athreadinfo.length; + + for (int i1 = 0; i1 < l; ++i1) { + ThreadInfo threadinfo = athreadinfo1[i1]; + + if (threadinfo.getThreadId() == this.b.aM().getId()) { + error.setStackTrace(threadinfo.getStackTrace()); + } + + stringbuilder.append(threadinfo); + stringbuilder.append("\n"); + } + + CrashReport crashreport = new CrashReport("Watching Server", error); + + this.b.b(crashreport); + CrashReportSystemDetails crashreportsystemdetails = crashreport.a("Thread Dump"); + + crashreportsystemdetails.a("Threads", (Object) stringbuilder); + File file = new File(new File(this.b.y(), "crash-reports"), "crash-" + (new SimpleDateFormat("yyyy-MM-dd_HH.mm.ss")).format(new Date()) + "-server.txt"); + + if (crashreport.a(file)) { + ThreadWatchdog.a.error("This crash report has been saved to: " + file.getAbsolutePath()); + } else { + ThreadWatchdog.a.error("We were unable to save this crash report to disk."); + } + + this.a(); + } + + try { + Thread.sleep(i + this.c - j); + } catch (InterruptedException interruptedexception) { + ; + } + } + + } + + private void a() { + try { + Timer timer = new Timer(); + + timer.schedule(new TimerTask() { + public void run() { + Runtime.getRuntime().halt(1); + } + }, 10000L); + System.exit(1); + } catch (Throwable throwable) { + Runtime.getRuntime().halt(1); + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/TileEntity.java b/azurite-server/src/main/java/net/minecraft/server/TileEntity.java new file mode 100644 index 0000000..0d7a7ef --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/TileEntity.java @@ -0,0 +1,236 @@ +package net.minecraft.server; + +import com.google.common.collect.Maps; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.bukkit.inventory.InventoryHolder; + +import java.util.Map; + +public abstract class TileEntity { + + private static final Logger a = LogManager.getLogger(); + private static final Map> f = Maps.newHashMap(); + private static final Map, String> g = Maps.newHashMap(); + protected World world; + public BlockPosition position; + protected boolean d; + private int h; + protected Block e; + + public TileEntity() { + this.position = BlockPosition.ZERO; + this.h = -1; + } + + private static void a(Class oclass, String s) { + if (TileEntity.f.containsKey(s)) { + throw new IllegalArgumentException("Duplicate id: " + s); + } else { + TileEntity.f.put(s, oclass); + TileEntity.g.put(oclass, s); + } + } + + public World getWorld() { + return this.world; + } + + public void a(World world) { + this.world = world; + } + + public boolean t() { + return this.world != null; + } + + public void a(NBTTagCompound nbttagcompound) { + this.position = new BlockPosition(nbttagcompound.getInt("x"), nbttagcompound.getInt("y"), nbttagcompound.getInt("z")); + } + + public void b(NBTTagCompound nbttagcompound) { + String s = TileEntity.g.get(this.getClass()); + + if (s == null) { + throw new RuntimeException(this.getClass() + " is missing a mapping! This is a bug!"); + } else { + nbttagcompound.setString("id", s); + nbttagcompound.setInt("x", this.position.getX()); + nbttagcompound.setInt("y", this.position.getY()); + nbttagcompound.setInt("z", this.position.getZ()); + } + } + + public static TileEntity c(NBTTagCompound nbttagcompound) { + TileEntity tileentity = null; + + try { + Class oclass = TileEntity.f.get(nbttagcompound.getString("id")); + + if (oclass != null) { + tileentity = oclass.newInstance(); + } + } catch (Exception exception) { + exception.printStackTrace(); + } + + if (tileentity != null) { + tileentity.a(nbttagcompound); + } else { + TileEntity.a.warn("Skipping BlockEntity with id {}", nbttagcompound.getString("id")); + } + + return tileentity; + } + + public int u() { + if (this.h == -1) { + IBlockData iblockdata = this.world.getType(this.position); + + this.h = iblockdata.getBlock().toLegacyData(iblockdata); + } + + return this.h; + } + + public static boolean IGNORE_TILE_UPDATES = false; // Paper + + public void update() { + if (this.world != null) { + if (IGNORE_TILE_UPDATES) return; // Paper + IBlockData iblockdata = this.world.getType(this.position); + Block block = iblockdata.getBlock(); + this.h = block.toLegacyData(iblockdata); + this.world.b(this.position, this); + if (this.w(block) != Blocks.AIR) { + this.world.updateAdjacentComparators(this.position, this.w(block)); + } + } + } + + public BlockPosition getPosition() { + return this.position; + } + + public Block w() { + if (this.e == null) { + this.e = this.world.getType(this.position).getBlock(); + } + + return this.e; + } + + public Block w(Block block) { + if (this.e == null) { + this.e = block; + } + return this.e; + } + + public Packet getUpdatePacket() { + return null; + } + + public boolean x() { + return this.d; + } + + public void y() { + this.d = true; + } + + public void D() { + this.d = false; + } + + public boolean c(int i, int j) { + return false; + } + + public void E() { + this.e = null; + this.h = -1; + } + + public void a(CrashReportSystemDetails crashreportsystemdetails) { + crashreportsystemdetails.a("Name", () -> TileEntity.g.get(TileEntity.this.getClass()) + " // " + TileEntity.this.getClass().getCanonicalName()); + if (this.world != null) { + // PaperSpigot start - Prevent tile entity and entity crashes + Block block = this.w(); + if (block != null) { + CrashReportSystemDetails.a(crashreportsystemdetails, this.position, this.w(), this.u()); + } + // PaperSpigot end + crashreportsystemdetails.a("Actual block type", () -> { + int i = Block.getId(TileEntity.this.world.getType(TileEntity.this.position).getBlock()); + + try { + return String.format("ID #%d (%s // %s)", i, Block.getById(i).a(), Block.getById(i).getClass().getCanonicalName()); + } catch (Throwable throwable) { + return "ID #" + i; + } + }); + crashreportsystemdetails.a("Actual block data value", () -> { + IBlockData iblockdata = TileEntity.this.world.getType(TileEntity.this.position); + int i = iblockdata.getBlock().toLegacyData(iblockdata); + + if (i < 0) { + return "Unknown? (Got " + i + ")"; + } else { + String s = String.format("%4s", new Object[]{Integer.toBinaryString(i)}).replace(" ", "0"); + + return String.format("%1$d / 0x%1$X / 0b%2$s", i, s); + } + }); + } + } + + public void a(BlockPosition blockposition) { + this.position = blockposition; + } + + public boolean F() { + return false; + } + + static { + a(TileEntityFurnace.class, "Furnace"); + a(TileEntityChest.class, "Chest"); + a(TileEntityEnderChest.class, "EnderChest"); + a(BlockJukeBox.TileEntityRecordPlayer.class, "RecordPlayer"); + a(TileEntityDispenser.class, "Trap"); + a(TileEntityDropper.class, "Dropper"); + a(TileEntitySign.class, "Sign"); + a(TileEntityMobSpawner.class, "MobSpawner"); + a(TileEntityNote.class, "Music"); + a(TileEntityPiston.class, "Piston"); + a(TileEntityBrewingStand.class, "Cauldron"); + a(TileEntityEnchantTable.class, "EnchantTable"); + a(TileEntityEnderPortal.class, "Airportal"); + a(TileEntityCommand.class, "Control"); + a(TileEntityBeacon.class, "Beacon"); + a(TileEntitySkull.class, "Skull"); + a(TileEntityLightDetector.class, "DLDetector"); + a(TileEntityHopper.class, "Hopper"); + a(TileEntityComparator.class, "Comparator"); + a(TileEntityFlowerPot.class, "FlowerPot"); + a(TileEntityBanner.class, "Banner"); + } + + // CraftBukkit start - add method + public InventoryHolder getOwner() { + if (world == null) return null; + // Spigot start + org.bukkit.block.Block block = world.getWorld().getBlockAt(position.getX(), position.getY(), position.getZ()); + if (block == null) { + org.bukkit.Bukkit.getLogger().log(java.util.logging.Level.WARNING, "No block for owner at %s %d %d %d", new Object[]{world.getWorld(), position.getX(), position.getY(), position.getZ()}); + return null; + } + // Spigot end + org.bukkit.block.BlockState state = block.getState(); + if (state instanceof InventoryHolder) return (InventoryHolder) state; + return null; + } + // CraftBukkit end+ + +} diff --git a/azurite-server/src/main/java/net/minecraft/server/TileEntityBanner.java b/azurite-server/src/main/java/net/minecraft/server/TileEntityBanner.java new file mode 100644 index 0000000..1251212 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/TileEntityBanner.java @@ -0,0 +1,151 @@ +package net.minecraft.server; + +public class TileEntityBanner extends TileEntity { + + public int color; + public NBTTagList patterns; + + public TileEntityBanner() {} + + public void a(ItemStack itemstack) { + this.patterns = null; + if (itemstack.hasTag() && itemstack.getTag().hasKeyOfType("BlockEntityTag", 10)) { + NBTTagCompound nbttagcompound = itemstack.getTag().getCompound("BlockEntityTag"); + + if (nbttagcompound.hasKey("Patterns")) { + this.patterns = (NBTTagList) nbttagcompound.getList("Patterns", 10).clone(); + // CraftBukkit start + while (this.patterns.size() > 20) { + this.patterns.a(20); // PAIL Rename remove + } + // CraftBukkit end + } + + if (nbttagcompound.hasKeyOfType("Base", 99)) { + this.color = nbttagcompound.getInt("Base"); + } else { + this.color = itemstack.getData() & 15; + } + } else { + this.color = itemstack.getData() & 15; + } + + } + + public void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + a(nbttagcompound, this.color, this.patterns); + } + + public static void a(NBTTagCompound nbttagcompound, int i, NBTTagList nbttaglist) { + nbttagcompound.setInt("Base", i); + if (nbttaglist != null) { + nbttagcompound.set("Patterns", nbttaglist); + } + + } + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + this.color = nbttagcompound.getInt("Base"); + this.patterns = nbttagcompound.getList("Patterns", 10); + // CraftBukkit start + while (this.patterns.size() > 20) { + this.patterns.a(20); // PAIL Rename remove + } + // CraftBukkit end + + } + + public Packet getUpdatePacket() { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + + this.b(nbttagcompound); + return new PacketPlayOutTileEntityData(this.position, 6, nbttagcompound); + } + + public int b() { + return this.color; + } + + public static int b(ItemStack itemstack) { + NBTTagCompound nbttagcompound = itemstack.a("BlockEntityTag", false); + + return nbttagcompound != null && nbttagcompound.hasKey("Base") ? nbttagcompound.getInt("Base") : itemstack.getData(); + } + + public static int c(ItemStack itemstack) { + NBTTagCompound nbttagcompound = itemstack.a("BlockEntityTag", false); + + return nbttagcompound != null && nbttagcompound.hasKey("Patterns") ? nbttagcompound.getList("Patterns", 10).size() : 0; + } + + public NBTTagList d() { + return this.patterns; + } + + public static void e(ItemStack itemstack) { + NBTTagCompound nbttagcompound = itemstack.a("BlockEntityTag", false); + + if (nbttagcompound != null && nbttagcompound.hasKeyOfType("Patterns", 9)) { + NBTTagList nbttaglist = nbttagcompound.getList("Patterns", 10); + + if (nbttaglist.size() > 0) { + nbttaglist.a(nbttaglist.size() - 1); + if (nbttaglist.isEmpty()) { + itemstack.getTag().remove("BlockEntityTag"); + if (itemstack.getTag().isEmpty()) { + itemstack.setTag(null); + } + } + + } + } + } + + public enum EnumBannerPatternType { + + BASE("base", "b"), SQUARE_BOTTOM_LEFT("square_bottom_left", "bl", " ", " ", "# "), SQUARE_BOTTOM_RIGHT("square_bottom_right", "br", " ", " ", " #"), SQUARE_TOP_LEFT("square_top_left", "tl", "# ", " ", " "), SQUARE_TOP_RIGHT("square_top_right", "tr", " #", " ", " "), STRIPE_BOTTOM("stripe_bottom", "bs", " ", " ", "###"), STRIPE_TOP("stripe_top", "ts", "###", " ", " "), STRIPE_LEFT("stripe_left", "ls", "# ", "# ", "# "), STRIPE_RIGHT("stripe_right", "rs", " #", " #", " #"), STRIPE_CENTER("stripe_center", "cs", " # ", " # ", " # "), STRIPE_MIDDLE("stripe_middle", "ms", " ", "###", " "), STRIPE_DOWNRIGHT("stripe_downright", "drs", "# ", " # ", " #"), STRIPE_DOWNLEFT("stripe_downleft", "dls", " #", " # ", "# "), STRIPE_SMALL("small_stripes", "ss", "# #", "# #", " "), CROSS("cross", "cr", "# #", " # ", "# #"), STRAIGHT_CROSS("straight_cross", "sc", " # ", "###", " # "), TRIANGLE_BOTTOM("triangle_bottom", "bt", " ", " # ", "# #"), TRIANGLE_TOP("triangle_top", "tt", "# #", " # ", " "), TRIANGLES_BOTTOM("triangles_bottom", "bts", " ", "# #", " # "), TRIANGLES_TOP("triangles_top", "tts", " # ", "# #", " "), DIAGONAL_LEFT("diagonal_left", "ld", "## ", "# ", " "), DIAGONAL_RIGHT("diagonal_up_right", "rd", " ", " #", " ##"), DIAGONAL_LEFT_MIRROR("diagonal_up_left", "lud", " ", "# ", "## "), DIAGONAL_RIGHT_MIRROR("diagonal_right", "rud", " ##", " #", " "), CIRCLE_MIDDLE("circle", "mc", " ", " # ", " "), RHOMBUS_MIDDLE("rhombus", "mr", " # ", "# #", " # "), HALF_VERTICAL("half_vertical", "vh", "## ", "## ", "## "), HALF_HORIZONTAL("half_horizontal", "hh", "###", "###", " "), HALF_VERTICAL_MIRROR("half_vertical_right", "vhr", " ##", " ##", " ##"), HALF_HORIZONTAL_MIRROR("half_horizontal_bottom", "hhb", " ", "###", "###"), BORDER("border", "bo", "###", "# #", "###"), CURLY_BORDER("curly_border", "cbo", new ItemStack(Blocks.VINE)), CREEPER("creeper", "cre", new ItemStack(Items.SKULL, 1, 4)), GRADIENT("gradient", "gra", "# #", " # ", " # "), GRADIENT_UP("gradient_up", "gru", " # ", " # ", "# #"), BRICKS("bricks", "bri", new ItemStack(Blocks.BRICK_BLOCK)), SKULL("skull", "sku", new ItemStack(Items.SKULL, 1, 1)), FLOWER("flower", "flo", new ItemStack(Blocks.RED_FLOWER, 1, BlockFlowers.EnumFlowerVarient.OXEYE_DAISY.b())), MOJANG("mojang", "moj", new ItemStack(Items.GOLDEN_APPLE, 1, 1)); + + private final String O; + private final String[] P; + private ItemStack Q; + + EnumBannerPatternType(String s, String s1) { + this.P = new String[3]; + this.O = s1; + } + + EnumBannerPatternType(String s, String s1, ItemStack itemstack) { + this(s, s1); + this.Q = itemstack; + } + + EnumBannerPatternType(String s, String s1, String s2, String s3, String s4) { + this(s, s1); + this.P[0] = s2; + this.P[1] = s3; + this.P[2] = s4; + } + + public String b() { + return this.O; + } + + public String[] c() { + return this.P; + } + + public boolean d() { + return this.Q != null || this.P[0] != null; + } + + public boolean e() { + return this.Q != null; + } + + public ItemStack f() { + return this.Q; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/TileEntityBeacon.java b/azurite-server/src/main/java/net/minecraft/server/TileEntityBeacon.java new file mode 100644 index 0000000..6999861 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/TileEntityBeacon.java @@ -0,0 +1,366 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.AzuriteConfig; +import org.bukkit.craftbukkit.entity.CraftHumanEntity; +import org.bukkit.craftbukkit.event.CraftEventFactory; +import org.bukkit.entity.HumanEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.PotionEffectAddEvent; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; +import org.github.paperspigot.event.block.BeaconEffectEvent; + +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; + +public class TileEntityBeacon extends TileEntityContainer implements IUpdatePlayerListBox, IInventory { + + public static final MobEffectList[][] a = new MobEffectList[][]{{MobEffectList.FASTER_MOVEMENT, MobEffectList.FASTER_DIG}, {MobEffectList.RESISTANCE, MobEffectList.JUMP}, {MobEffectList.INCREASE_DAMAGE}, {MobEffectList.REGENERATION}}; + private boolean i; + private int j = -1; + private int k; + private int l; + private ItemStack inventorySlot; + private String n; + // CraftBukkit start - add fields and methods + public final List transaction = new java.util.ArrayList<>(); + private int maxStack = MAX_STACK; + + public ItemStack[] getContents() { + return new ItemStack[]{this.inventorySlot}; + } + + public void onOpen(CraftHumanEntity who) { + transaction.add(who); + } + + public void onClose(CraftHumanEntity who) { + transaction.remove(who); + } + + public List getViewers() { + return transaction; + } + + public void setMaxStackSize(int size) { + maxStack = size; + } + // CraftBukkit end + + public TileEntityBeacon() { + } + + public void c() { + if (AzuriteConfig.tickBeacons.getValue() && this.world.getTime() % 80L == 0L) { + this.m(); + } + } + + public void m() { + this.B(); + this.A(); + } + + private void A() { + if (this.i && this.j > 0 && this.k > 0) { + double d0 = this.j * 10 + 10; + byte b0 = 0; + + if (this.j >= 4 && this.k == this.l) { + b0 = 1; + } + + int i = this.position.getX(); + int j = this.position.getY(); + int k = this.position.getZ(); + List list = world.playerMap.getNearbyPlayersIgnoreHeight(i, k, d0); + Iterator iterator = list.iterator(); + org.bukkit.block.Block block = this.world.getWorld().getBlockAt(this.position.getX(), this.position.getY(), this.position.getZ()); + PotionEffect primaryEffect = new PotionEffect(PotionEffectType.getById(this.k), 180, b0, true, true); + while (iterator.hasNext()) { + EntityHuman entityhuman = iterator.next(); + BeaconEffectEvent event = new BeaconEffectEvent(block, primaryEffect, (Player) entityhuman.getBukkitEntity(), true); + if (CraftEventFactory.callEvent(event).isCancelled()) + continue; + PotionEffect effect = event.getEffect(); + entityhuman.addEffect(new MobEffect(effect.getType().getId(), effect.getDuration(), effect.getAmplifier(), effect.isAmbient(), effect.hasParticles()), PotionEffectAddEvent.EffectCause.BEACON); + } + if (this.j >= 4 && this.k != this.l && this.l > 0) { + iterator = list.iterator(); + PotionEffect secondaryEffect = new PotionEffect(PotionEffectType.getById(this.l), 180, 0, true, true); + while (iterator.hasNext()) { + EntityHuman entityhuman = iterator.next(); + BeaconEffectEvent event = new BeaconEffectEvent(block, secondaryEffect, (Player) entityhuman.getBukkitEntity(), false); + if (CraftEventFactory.callEvent(event).isCancelled()) + continue; + PotionEffect effect = event.getEffect(); + entityhuman.addEffect(new MobEffect(effect.getType().getId(), effect.getDuration(), effect.getAmplifier(), effect.isAmbient(), effect.hasParticles()), PotionEffectAddEvent.EffectCause.BEACON); + } + } + } + + } + + private void B() { + int i = this.j; + int j = this.position.getX(); + int k = this.position.getY(); + int l = this.position.getZ(); + + this.j = 0; + this.i = true; + BeaconColorTracker tileentitybeacon_beaconcolortracker = new BeaconColorTracker(EntitySheep.a(EnumColor.WHITE)); + + boolean flag = true; + + int i1; + + for (i1 = k + 1; i1 < 256; ++i1) { + IBlockData iblockdata = this.world.getType(j, i1, l); + float[] afloat; + + Block block = iblockdata.getBlock(); + if (block == Blocks.STAINED_GLASS) { + afloat = EntitySheep.a(iblockdata.get(BlockStainedGlass.COLOR)); + } else { + if (block != Blocks.STAINED_GLASS_PANE) { + if (block.p() >= 15 && block != Blocks.BEDROCK) { + this.i = false; + break; + } + + tileentitybeacon_beaconcolortracker.a(); + continue; + } + + afloat = EntitySheep.a(iblockdata.get(BlockStainedGlassPane.COLOR)); + } + + if (!flag) { + afloat = new float[]{(tileentitybeacon_beaconcolortracker.b()[0] + afloat[0]) / 2.0F, (tileentitybeacon_beaconcolortracker.b()[1] + afloat[1]) / 2.0F, (tileentitybeacon_beaconcolortracker.b()[2] + afloat[2]) / 2.0F}; + } + + if (Arrays.equals(afloat, tileentitybeacon_beaconcolortracker.b())) { + tileentitybeacon_beaconcolortracker.a(); + } else { + tileentitybeacon_beaconcolortracker = new BeaconColorTracker(afloat); + } + + flag = false; + } + + if (this.i) { + for (i1 = 1; i1 <= 4; this.j = i1++) { + int j1 = k - i1; + + if (j1 < 0) { + break; + } + + boolean flag1 = true; + + for (int k1 = j - i1; k1 <= j + i1 && flag1; ++k1) { + for (int l1 = l - i1; l1 <= l + i1; ++l1) { + Block block = this.world.getType(k1, j1, l1).getBlock(); + + if (block != Blocks.EMERALD_BLOCK && block != Blocks.GOLD_BLOCK && block != Blocks.DIAMOND_BLOCK && block != Blocks.IRON_BLOCK) { + flag1 = false; + break; + } + } + } + + if (!flag1) { + break; + } + } + + if (this.j == 0) { + this.i = false; + } + } + + if (!this.world.isClientSide && this.j == 4 && i < this.j && AzuriteConfig.trackPlayerStatistics.getValue()) { + for (EntityHuman entityhuman : this.world.a(EntityHuman.class, (new AxisAlignedBB(j, k, l, j, k - 4, l)).grow(10.0D, 5.0D, 10.0D))) { + entityhuman.b(AchievementList.K); + } + } + } + + public Packet getUpdatePacket() { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + + this.b(nbttagcompound); + return new PacketPlayOutTileEntityData(this.position, 3, nbttagcompound); + } + + private int h(int i) { + if (i >= 0 && i < MobEffectList.byId.length && MobEffectList.byId[i] != null) { + MobEffectList mobeffectlist = MobEffectList.byId[i]; + + return mobeffectlist != MobEffectList.FASTER_MOVEMENT && mobeffectlist != MobEffectList.FASTER_DIG && mobeffectlist != MobEffectList.RESISTANCE && mobeffectlist != MobEffectList.JUMP && mobeffectlist != MobEffectList.INCREASE_DAMAGE && mobeffectlist != MobEffectList.REGENERATION ? 0 : i; + } else { + return 0; + } + } + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + this.k = this.h(nbttagcompound.getInt("Primary")); + this.l = this.h(nbttagcompound.getInt("Secondary")); + this.j = nbttagcompound.getInt("Levels"); + } + + public void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + nbttagcompound.setInt("Primary", this.k); + nbttagcompound.setInt("Secondary", this.l); + nbttagcompound.setInt("Levels", this.j); + } + + public int getSize() { + return 1; + } + + public ItemStack getItem(int i) { + return i == 0 ? this.inventorySlot : null; + } + + public ItemStack splitStack(int i, int j) { + if (i == 0 && this.inventorySlot != null) { + if (j >= this.inventorySlot.count) { + ItemStack itemstack = this.inventorySlot; + + this.inventorySlot = null; + return itemstack; + } else { + this.inventorySlot.count -= j; + return new ItemStack(this.inventorySlot.getItem(), j, this.inventorySlot.getData()); + } + } else { + return null; + } + } + + public ItemStack splitWithoutUpdate(int i) { + if (i == 0 && this.inventorySlot != null) { + ItemStack itemstack = this.inventorySlot; + + this.inventorySlot = null; + return itemstack; + } else { + return null; + } + } + + public void setItem(int i, ItemStack itemstack) { + if (i == 0) { + this.inventorySlot = itemstack; + } + + } + + public String getName() { + return this.hasCustomName() ? this.n : "container.beacon"; + } + + public boolean hasCustomName() { + return this.n != null && this.n.length() > 0; + } + + public void a(String s) { + this.n = s; + } + + public int getMaxStackSize() { + return maxStack; // CraftBukkit + } + + public boolean a(EntityHuman entityhuman) { + return this.world.getTileEntity(this.position) == this && entityhuman.e((double) this.position.getX() + 0.5D, (double) this.position.getY() + 0.5D, (double) this.position.getZ() + 0.5D) <= 64.0D; + } + + public void startOpen(EntityHuman entityhuman) { + } + + public void closeContainer(EntityHuman entityhuman) { + } + + public boolean b(int i, ItemStack itemstack) { + return itemstack.getItem() == Items.EMERALD || itemstack.getItem() == Items.DIAMOND || itemstack.getItem() == Items.GOLD_INGOT || itemstack.getItem() == Items.IRON_INGOT; + } + + public String getContainerName() { + return "minecraft:beacon"; + } + + public Container createContainer(PlayerInventory playerinventory, EntityHuman entityhuman) { + return new ContainerBeacon(playerinventory, this); + } + + public int getProperty(int i) { + switch (i) { + case 0: + return this.j; + + case 1: + return this.k; + + case 2: + return this.l; + + default: + return 0; + } + } + + public void b(int i, int j) { + switch (i) { + case 0: + this.j = j; + break; + + case 1: + this.k = this.h(j); + break; + + case 2: + this.l = this.h(j); + } + + } + + public int g() { + return 3; + } + + public void l() { + this.inventorySlot = null; + } + + public boolean c(int i, int j) { + if (i == 1) { + this.m(); + return true; + } else { + return super.c(i, j); + } + } + + public static class BeaconColorTracker { + + private final float[] a; + + public BeaconColorTracker(float[] afloat) { + this.a = afloat; + } + + protected void a() { + } + + public float[] b() { + return this.a; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/TileEntityBrewingStand.java b/azurite-server/src/main/java/net/minecraft/server/TileEntityBrewingStand.java new file mode 100644 index 0000000..783c7e0 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/TileEntityBrewingStand.java @@ -0,0 +1,343 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.AzuriteConfig; +import org.bukkit.craftbukkit.entity.CraftHumanEntity; +import org.bukkit.entity.HumanEntity; +import org.bukkit.event.inventory.BrewEvent; + +import java.util.Arrays; +import java.util.List; + +public class TileEntityBrewingStand extends TileEntityContainer implements IUpdatePlayerListBox, IWorldInventory { + + private static final int[] a = new int[]{3}; + private static final int[] f = new int[]{0, 1, 2}; + public int brewTime; + // CraftBukkit start - add fields and methods + public List transaction = new java.util.ArrayList<>(); + private ItemStack[] items = new ItemStack[4]; + private boolean[] i; + private Item j; + private String k; + private int lastTick = MinecraftServer.currentTick; // CraftBukkit - add field + private int maxStack = 64; + + public TileEntityBrewingStand() { + } + + public void onOpen(CraftHumanEntity who) { + transaction.add(who); + } + + public void onClose(CraftHumanEntity who) { + transaction.remove(who); + } + + public List getViewers() { + return transaction; + } + + public ItemStack[] getContents() { + return this.items; + } + + public String getName() { + return this.hasCustomName() ? this.k : "container.brewing"; + } + // CraftBukkit end + + public boolean hasCustomName() { + return this.k != null && !this.k.isEmpty(); + } + + public void a(String s) { + this.k = s; + } + + public int getSize() { + return this.items.length; + } + + public void c() { + if (!AzuriteConfig.tickBrewingStands.getValue()) return; + // CraftBukkit start - Use wall time instead of ticks for brewing + int elapsedTicks = MinecraftServer.currentTick - this.lastTick; + this.lastTick = MinecraftServer.currentTick; + + if (this.brewTime > 0) { + this.brewTime -= (int) (elapsedTicks * AzuriteConfig.brewingModifier.getValue()); + if (this.brewTime <= 0) { // == -> <= + // CraftBukkit end + this.o(); + this.update(); + } else if (!this.n()) { + this.brewTime = 0; + this.update(); + } else if (this.j != this.items[3].getItem()) { + this.brewTime = 0; + this.update(); + } + } else if (this.n()) { + this.brewTime = 400; + this.j = this.items[3].getItem(); + } + + boolean[] aboolean = this.m(); + + if (!Arrays.equals(aboolean, this.i)) { + this.i = aboolean; + IBlockData iblockdata = this.world.getType(this.getPosition()); + + if (!(iblockdata.getBlock() instanceof BlockBrewingStand)) { + return; + } + + for (int i = 0; i < BlockBrewingStand.HAS_BOTTLE.length; ++i) { + iblockdata = iblockdata.set(BlockBrewingStand.HAS_BOTTLE[i], aboolean[i]); + } + + this.world.setTypeAndData(this.position, iblockdata, 2); + } + + } + + private boolean n() { + if (this.items[3] != null && this.items[3].count > 0) { + ItemStack itemstack = this.items[3]; + + if (!itemstack.getItem().l(itemstack)) { + return false; + } else { + boolean flag = false; + + for (int i = 0; i < 3; ++i) { + if (this.items[i] != null && this.items[i].getItem() == Items.POTION) { + int j = this.items[i].getData(); + int k = this.c(j, itemstack); + + if (!ItemPotion.f(j) && ItemPotion.f(k)) { + flag = true; + break; + } + + List list = Items.POTION.e(j); + List list1 = Items.POTION.e(k); + + if ((j <= 0 || list != list1) && (list == null || !list.equals(list1) && list1 != null) && j != k) { + flag = true; + break; + } + } + } + + return flag; + } + } else { + return false; + } + } + + private void o() { + if (this.n()) { + ItemStack itemstack = this.items[3]; + + // CraftBukkit start + if (getOwner() != null) { + BrewEvent event = new BrewEvent(world.getWorld().getBlockAt(position.getX(), position.getY(), position.getZ()), (org.bukkit.inventory.BrewerInventory) this.getOwner().getInventory()); + org.bukkit.Bukkit.getPluginManager().callEvent(event); + if (event.isCancelled()) { + return; + } + } + // CraftBukkit end + + for (int i = 0; i < 3; ++i) { + if (this.items[i] != null && this.items[i].getItem() == Items.POTION) { + int j = this.items[i].getData(); + int k = this.c(j, itemstack); + List list = Items.POTION.e(j); + List list1 = Items.POTION.e(k); + + if ((j <= 0 || list != list1) && (list == null || !list.equals(list1) && list1 != null)) { + if (j != k) { + this.items[i].setData(k); + } + } else if (!ItemPotion.f(j) && ItemPotion.f(k)) { + this.items[i].setData(k); + } + } + } + + if (itemstack.getItem().r()) { + this.items[3] = new ItemStack(itemstack.getItem().q()); + } else { + --this.items[3].count; + if (this.items[3].count <= 0) { + this.items[3] = null; + } + } + + } + } + + private int c(int i, ItemStack itemstack) { + return itemstack == null ? i : (itemstack.getItem().l(itemstack) ? PotionBrewer.a(i, itemstack.getItem().j(itemstack)) : i); + } + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + NBTTagList nbttaglist = nbttagcompound.getList("Items", 10); + + this.items = new ItemStack[this.getSize()]; + + for (int i = 0; i < nbttaglist.size(); ++i) { + NBTTagCompound nbttagcompound1 = nbttaglist.get(i); + byte b0 = nbttagcompound1.getByte("Slot"); + + if (b0 >= 0 && b0 < this.items.length) { + this.items[b0] = ItemStack.createStack(nbttagcompound1); + } + } + + this.brewTime = nbttagcompound.getShort("BrewTime"); + if (nbttagcompound.hasKeyOfType("CustomName", 8)) { + this.k = nbttagcompound.getString("CustomName"); + } + + } + + public void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + nbttagcompound.setShort("BrewTime", (short) this.brewTime); + NBTTagList nbttaglist = new NBTTagList(); + + for (int i = 0; i < this.items.length; ++i) { + if (this.items[i] != null) { + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + + nbttagcompound1.setByte("Slot", (byte) i); + this.items[i].save(nbttagcompound1); + nbttaglist.add(nbttagcompound1); + } + } + + nbttagcompound.set("Items", nbttaglist); + if (this.hasCustomName()) { + nbttagcompound.setString("CustomName", this.k); + } + + } + + public ItemStack getItem(int i) { + return i >= 0 && i < this.items.length ? this.items[i] : null; + } + + public ItemStack splitStack(int i, int j) { + if (i >= 0 && i < this.items.length) { + ItemStack itemstack = this.items[i]; + + this.items[i] = null; + return itemstack; + } else { + return null; + } + } + + public ItemStack splitWithoutUpdate(int i) { + if (i >= 0 && i < this.items.length) { + ItemStack itemstack = this.items[i]; + + this.items[i] = null; + return itemstack; + } else { + return null; + } + } + + public void setItem(int i, ItemStack itemstack) { + if (i >= 0 && i < this.items.length) { + this.items[i] = itemstack; + } + + } + + public int getMaxStackSize() { + return this.maxStack; // CraftBukkit + } + + public void setMaxStackSize(int size) { + maxStack = size; + } + + public boolean a(EntityHuman entityhuman) { + return this.world.getTileEntity(this.position) == this && entityhuman.e((double) this.position.getX() + 0.5D, (double) this.position.getY() + 0.5D, (double) this.position.getZ() + 0.5D) <= 64.0D; + } + + public void startOpen(EntityHuman entityhuman) { + } + + public void closeContainer(EntityHuman entityhuman) { + } + + public boolean b(int i, ItemStack itemstack) { + return i == 3 ? itemstack.getItem().l(itemstack) : itemstack.getItem() == Items.POTION || itemstack.getItem() == Items.GLASS_BOTTLE; + } + + public boolean[] m() { + boolean[] aboolean = new boolean[3]; + + for (int i = 0; i < 3; ++i) { + if (this.items[i] != null) { + aboolean[i] = true; + } + } + + return aboolean; + } + + public int[] getSlotsForFace(EnumDirection enumdirection) { + return enumdirection == EnumDirection.UP ? TileEntityBrewingStand.a : TileEntityBrewingStand.f; + } + + public int[] getSlotsForDownFace() { + return TileEntityBrewingStand.f; + } + + public boolean canPlaceItemThroughFace(int i, ItemStack itemstack, EnumDirection enumdirection) { + return this.b(i, itemstack); + } + + public boolean canTakeItemThroughFace(int i, ItemStack itemstack, EnumDirection enumdirection) { + return true; + } + + public String getContainerName() { + return "minecraft:brewing_stand"; + } + + public Container createContainer(PlayerInventory playerinventory, EntityHuman entityhuman) { + return new ContainerBrewingStand(playerinventory, this); + } + + public int getProperty(int i) { + if (i == 0) { + return this.brewTime; + } + return 0; + } + + public void b(int i, int j) { + if (i == 0) { + this.brewTime = j; + } + } + + public int g() { + return 1; + } + + public void l() { + Arrays.fill(this.items, null); + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/TileEntityChest.java b/azurite-server/src/main/java/net/minecraft/server/TileEntityChest.java new file mode 100644 index 0000000..817d95e --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/TileEntityChest.java @@ -0,0 +1,431 @@ +package net.minecraft.server; + +import org.bukkit.craftbukkit.entity.CraftHumanEntity; +import org.bukkit.entity.HumanEntity; + +import java.util.Arrays; +import java.util.List; +// CraftBukkit end + +public class TileEntityChest extends TileEntityContainer implements IInventory { // PaperSpigot - remove IUpdatePlayerListBox + + private ItemStack[] items = new ItemStack[27]; + public boolean a; + public TileEntityChest f; // PaperSpigot - adjacentChestZNeg + public TileEntityChest g; // PaperSpigot - adjacentChestXPos + public TileEntityChest h; // PaperSpigot - adjacentChestXNeg + public TileEntityChest i; // PaperSpigot - adjacentChestZPos + public float j; // PaperSpigot - lidAngle + public float k; + public int l; // PaperSpigot - numPlayersUsing + + private int o = -1; + private String p; + + public TileEntityChest() {} + + // CraftBukkit start - add fields and methods + public List transaction = new java.util.ArrayList<>(); + private int maxStack = MAX_STACK; + + public ItemStack[] getContents() { + return this.items; + } + + public void onOpen(CraftHumanEntity who) { + transaction.add(who); + } + + public void onClose(CraftHumanEntity who) { + transaction.remove(who); + } + + public List getViewers() { + return transaction; + } + + public void setMaxStackSize(int size) { + maxStack = size; + } + // CraftBukkit end + + public int getSize() { + return 27; + } + + public ItemStack getItem(int i) { + return this.items[i]; + } + + public ItemStack splitStack(int i, int j) { + if (this.items[i] != null) { + ItemStack itemstack; + + if (this.items[i].count <= j) { + itemstack = this.items[i]; + this.items[i] = null; + } else { + itemstack = this.items[i].cloneAndSubtract(j); + if (this.items[i].count == 0) { + this.items[i] = null; + } + + } + this.update(); + return itemstack; + } else { + return null; + } + } + + public ItemStack splitWithoutUpdate(int i) { + if (this.items[i] != null) { + ItemStack itemstack = this.items[i]; + + this.items[i] = null; + return itemstack; + } else { + return null; + } + } + + public void setItem(int i, ItemStack itemstack) { + this.items[i] = itemstack; + if (itemstack != null && itemstack.count > this.getMaxStackSize()) { + itemstack.count = this.getMaxStackSize(); + } + + this.update(); + } + + public String getName() { + return this.hasCustomName() ? this.p : "container.chest"; + } + + public boolean hasCustomName() { + return this.p != null && !this.p.isEmpty(); + } + + public void a(String s) { + this.p = s; + } + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + NBTTagList nbttaglist = nbttagcompound.getList("Items", 10); + + this.items = new ItemStack[this.getSize()]; + if (nbttagcompound.hasKeyOfType("CustomName", 8)) { + this.p = nbttagcompound.getString("CustomName"); + } + + for (int i = 0; i < nbttaglist.size(); ++i) { + NBTTagCompound nbttagcompound1 = nbttaglist.get(i); + int j = nbttagcompound1.getByte("Slot") & 255; + + if (j < this.items.length) { + this.items[j] = ItemStack.createStack(nbttagcompound1); + } + } + + } + + public void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + NBTTagList nbttaglist = new NBTTagList(); + + for (int i = 0; i < this.items.length; ++i) { + if (this.items[i] != null) { + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + + nbttagcompound1.setByte("Slot", (byte) i); + this.items[i].save(nbttagcompound1); + nbttaglist.add(nbttagcompound1); + } + } + + nbttagcompound.set("Items", nbttaglist); + if (this.hasCustomName()) { + nbttagcompound.setString("CustomName", this.p); + } + + } + + public int getMaxStackSize() { + return maxStack; // CraftBukkit + } + + public boolean a(EntityHuman entityhuman) { + if (this.world == null) return true; // CraftBukkit + return this.world.getTileEntity(this.position) == this && entityhuman.e((double) this.position.getX() + 0.5D, (double) this.position.getY() + 0.5D, (double) this.position.getZ() + 0.5D) <= 64.0D; + } + + public void E() { + super.E(); + this.a = false; + } + + private void a(TileEntityChest tileentitychest, EnumDirection enumdirection) { + if (tileentitychest.x()) { + this.a = false; + } else if (this.a) { + switch (TileEntityChest.SyntheticClass_1.a[enumdirection.ordinal()]) { + case 1: + if (this.f != tileentitychest) { + this.a = false; + } + break; + + case 2: + if (this.i != tileentitychest) { + this.a = false; + } + break; + + case 3: + if (this.g != tileentitychest) { + this.a = false; + } + break; + + case 4: + if (this.h != tileentitychest) { + this.a = false; + } + } + } + + } + + public void m() { + if (!this.a) { + this.a = true; + this.h = this.a(EnumDirection.WEST); + this.g = this.a(EnumDirection.EAST); + this.f = this.a(EnumDirection.NORTH); + this.i = this.a(EnumDirection.SOUTH); + } + } + + protected TileEntityChest a(EnumDirection enumdirection) { + BlockPosition blockposition = this.position.shift(enumdirection); + + if (this.b(blockposition)) { + TileEntity tileentity = this.world.getTileEntity(blockposition); + + if (tileentity instanceof TileEntityChest) { + TileEntityChest tileentitychest = (TileEntityChest) tileentity; + + tileentitychest.a(this, enumdirection.opposite()); + return tileentitychest; + } + } + + return null; + } + + private boolean b(BlockPosition blockposition) { + if (this.world == null) { + return false; + } else { + Block block = this.world.getType(blockposition).getBlock(); + + return block instanceof BlockChest && ((BlockChest) block).b == this.n(); + } + } + + public void c() { + + } + + public boolean c(int i, int j) { + if (i == 1) { + this.l = j; + return true; + } else { + return super.c(i, j); + } + } + + public void startOpen(EntityHuman entityhuman) { + if (!entityhuman.isSpectator()) { + if (this.l < 0) { + this.l = 0; + } + int oldPower = Math.min(15, this.l); // CraftBukkit - Get power before new viewer is added + + ++this.l; + if (this.world == null) return; // CraftBukkit + + // PaperSpigot start - Move chest open sound out of the tick loop + this.m(); + + if (this.l > 0 && this.j == 0.0F && this.f == null && this.h == null) { + this.j = 0.7F; + + double d0 = (double) this.position.getZ() + 0.5D; + double d1 = (double) this.position.getX() + 0.5D; + + if (this.i != null) { + d0 += 0.5D; + } + + if (this.g != null) { + d1 += 0.5D; + } + + this.world.makeSound(d1, (double) this.position.getY() + 0.5D, d0, "random.chestopen", 0.5F, this.world.random.nextFloat() * 0.1F + 0.9F); + } + // PaperSpigot end + + this.world.playBlockAction(this.position, this.w(), 1, this.l); + + // CraftBukkit start - Call redstone event + if (this.w() == Blocks.TRAPPED_CHEST) { + int newPower = Math.max(0, Math.min(15, this.l)); + + if (oldPower != newPower) { + org.bukkit.craftbukkit.event.CraftEventFactory.callRedstoneChange(world, position.getX(), position.getY(), position.getZ(), oldPower, newPower); + } + } + // CraftBukkit end + world.applyPhysics(position, w()); + world.applyPhysics(position.getX(), position.getY() - 1, position.getZ(), w()); + } + + } + + public void closeContainer(EntityHuman entityhuman) { + if (!entityhuman.isSpectator() && this.w() instanceof BlockChest) { + int oldPower = Math.max(0, Math.min(15, this.l)); // CraftBukkit - Get power before new viewer is added + --this.l; + if (this.world == null) return; // CraftBukkit + + // PaperSpigot start - Move chest close sound handling out of the tick loop + if (this.l == 0 && this.j > 0.0F || this.l > 0 && this.j < 1.0F) { + float f = 0.1F; + + if (this.l > 0) { + this.j += f; + } else { + this.j -= f; + } + + double d0 = (double) this.getPosition().getX() + 0.5D; + double d2 = (double) this.getPosition().getZ() + 0.5D; + + if (this.i != null) { + d2 += 0.5D; + } + + if (this.g != null) { + d0 += 0.5D; + } + + this.world.makeSound(d0, (double) this.getPosition().getY() + 0.5D, d2, "random.chestclosed", 0.5F, this.world.random.nextFloat() * 0.1F + 0.9F); + this.j = 0.0F; + } + // PaperSpigot end + + this.world.playBlockAction(this.position, this.w(), 1, this.l); + + // CraftBukkit start - Call redstone event + if (this.w() == Blocks.TRAPPED_CHEST) { + int newPower = Math.max(0, Math.min(15, this.l)); + + if (oldPower != newPower) { + org.bukkit.craftbukkit.event.CraftEventFactory.callRedstoneChange(world, position.getX(), position.getY(), position.getZ(), oldPower, newPower); + } + } + // CraftBukkit end + world.applyPhysics(position, w()); + world.applyPhysics(position.getX(), position.getY() - 1, position.getZ(), w()); + } + + } + + public boolean b(int i, ItemStack itemstack) { + return true; + } + + public void y() { + super.y(); + this.E(); + this.m(); + } + + public int n() { + if (this.o == -1) { + if (this.world == null || !(this.w() instanceof BlockChest)) { + return 0; + } + + this.o = ((BlockChest) this.w()).b; + } + + return this.o; + } + + public String getContainerName() { + return "minecraft:chest"; + } + + public Container createContainer(PlayerInventory playerinventory, EntityHuman entityhuman) { + return new ContainerChest(playerinventory, this, entityhuman); + } + + public int getProperty(int i) { + return 0; + } + + public void b(int i, int j) {} + + public int g() { + return 0; + } + + public void l() { + Arrays.fill(this.items, null); + + } + + // CraftBukkit start + // PAIL + @Override + public boolean F() { + return true; + } + // CraftBukkit end + + static class SyntheticClass_1 { + + static final int[] a = new int[EnumDirection.values().length]; + + static { + try { + TileEntityChest.SyntheticClass_1.a[EnumDirection.NORTH.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + + } + + try { + TileEntityChest.SyntheticClass_1.a[EnumDirection.SOUTH.ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + + } + + try { + TileEntityChest.SyntheticClass_1.a[EnumDirection.EAST.ordinal()] = 3; + } catch (NoSuchFieldError ignored) { + + } + + try { + TileEntityChest.SyntheticClass_1.a[EnumDirection.WEST.ordinal()] = 4; + } catch (NoSuchFieldError ignored) { + + } + + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/TileEntityCommand.java b/azurite-server/src/main/java/net/minecraft/server/TileEntityCommand.java new file mode 100644 index 0000000..d5ceda6 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/TileEntityCommand.java @@ -0,0 +1,66 @@ +package net.minecraft.server; + +public class TileEntityCommand extends TileEntity { + + private final CommandBlockListenerAbstract a = new CommandBlockListenerAbstract() { + { + sender = new org.bukkit.craftbukkit.command.CraftBlockCommandSender(this); // CraftBukkit - add sender + } + + public BlockPosition getChunkCoordinates() { + return TileEntityCommand.this.position; + } + + public Vec3D d() { + return new Vec3D((double) TileEntityCommand.this.position.getX() + 0.5D, (double) TileEntityCommand.this.position.getY() + 0.5D, (double) TileEntityCommand.this.position.getZ() + 0.5D); + } + + public World getWorld() { + return TileEntityCommand.this.getWorld(); + } + + public void setCommand(String s) { + super.setCommand(s); + TileEntityCommand.this.update(); + } + + public void h() { + TileEntityCommand.this.getWorld().notify(TileEntityCommand.this.position); + } + + public Entity f() { + return null; + } + }; + + public TileEntityCommand() { + } + + public void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + this.a.a(nbttagcompound); + } + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + this.a.b(nbttagcompound); + } + + public Packet getUpdatePacket() { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + this.b(nbttagcompound); + return new PacketPlayOutTileEntityData(this.position, 2, nbttagcompound); + } + + public boolean F() { + return true; + } + + public CommandBlockListenerAbstract getCommandBlock() { + return this.a; + } + + public CommandObjectiveExecutor c() { + return this.a.n(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/TileEntityComparator.java b/azurite-server/src/main/java/net/minecraft/server/TileEntityComparator.java new file mode 100644 index 0000000..0150c3d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/TileEntityComparator.java @@ -0,0 +1,26 @@ +package net.minecraft.server; + +public class TileEntityComparator extends TileEntity { + + private int a; + + public TileEntityComparator() {} + + public void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + nbttagcompound.setInt("OutputSignal", this.a); + } + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + this.a = nbttagcompound.getInt("OutputSignal"); + } + + public int b() { + return this.a; + } + + public void a(int i) { + this.a = i; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/TileEntityContainer.java b/azurite-server/src/main/java/net/minecraft/server/TileEntityContainer.java new file mode 100644 index 0000000..b1d337b --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/TileEntityContainer.java @@ -0,0 +1,72 @@ +package net.minecraft.server; + +import java.util.HashSet; +import java.util.Set; + +public abstract class TileEntityContainer extends TileEntity implements ITileEntityContainer, ITileInventory { + + private ChestLock a; + private TileEntityHopper pullingHopper; + // Beanes - hopper cache + private Set usingAsPush; + + public TileEntityContainer() { + this.a = ChestLock.a; + this.usingAsPush = new HashSet<>(); + } + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + this.a = ChestLock.b(nbttagcompound); + } + + public void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + if (this.a != null) { + this.a.a(nbttagcompound); + } + } + + public boolean r_() { + return this.a != null && !this.a.a(); + } + + public ChestLock i() { + return this.a; + } + + public void a(ChestLock chestlock) { + this.a = chestlock; + } + + public IChatBaseComponent getScoreboardDisplayName() { + return this.hasCustomName() ? new ChatComponentText(this.getName()) : new ChatMessage(this.getName(), new Object[0]); + } + + // Beanes - hoppers cache + public void y() { + super.y(); + // This is the invalidate function + this.invalidateHopperCache(); + } + + public void setAsPull(TileEntityHopper tileentityhopper) { + this.pullingHopper = tileentityhopper; + } + + public void addAsPush(TileEntityHopper tileentityhopper) { + this.usingAsPush.add(tileentityhopper); + } + + public void invalidateHopperCache() { + if (this.pullingHopper != null) { + this.pullingHopper.cachedPullInventory = null; + } + this.pullingHopper = null; + + for (TileEntityHopper tileentityhopper : this.usingAsPush) { + tileentityhopper.cachedPushInventory = null; + } + this.usingAsPush.clear(); + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/net/minecraft/server/TileEntityDispenser.java b/azurite-server/src/main/java/net/minecraft/server/TileEntityDispenser.java new file mode 100644 index 0000000..3c65de7 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/TileEntityDispenser.java @@ -0,0 +1,225 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.AzuriteConfig; +import org.bukkit.craftbukkit.entity.CraftHumanEntity; +import org.bukkit.entity.HumanEntity; + +import java.util.Arrays; +import java.util.List; +import java.util.Random; +// CraftBukkit end + +public class TileEntityDispenser extends TileEntityContainer implements IInventory { + + private static final Random f = new Random(); + private ItemStack[] items = new ItemStack[9]; + protected String a; + + // CraftBukkit start - add fields and methods + public List transaction = new java.util.ArrayList<>(); + private int maxStack = MAX_STACK; + + public ItemStack[] getContents() { + return this.items; + } + + public void onOpen(CraftHumanEntity who) { + transaction.add(who); + } + + public void onClose(CraftHumanEntity who) { + transaction.remove(who); + } + + public List getViewers() { + return transaction; + } + + public void setMaxStackSize(int size) { + maxStack = size; + } + // CraftBukkit end + + public TileEntityDispenser() { + } + + public int getSize() { + return 9; + } + + public ItemStack getItem(int i) { + return this.items[i]; + } + + public ItemStack splitStack(int i, int j) { + ItemStack itemstack = items[i]; + + if (itemstack != null) { + if (itemstack.count <= j) { + this.items[i] = null; + } else { + if (itemstack.count == 0) { + this.items[i] = null; + } + itemstack = itemstack.cloneAndSubtract(j); + } + this.update(); + return itemstack; + } else { + return null; + } + } + + public ItemStack splitWithoutUpdate(int i) { + ItemStack itemstack = this.items[i]; + + if (itemstack != null) { + this.items[i] = null; + return itemstack; + } else { + return null; + } + } + + public int m() { + if (!AzuriteConfig.dispenserRandomness.getValue()) { + for (int k = 0; k < this.items.length; ++k) { + if (this.items[k] != null) { + return k; + } + } + return -1; + } + int i = -1; + int j = 1; + + for (int k = 0; k < this.items.length; ++k) { + ItemStack itemstack = this.items[k]; + + if (itemstack != null && TileEntityDispenser.f.nextInt(j++) == 0) { + if (itemstack.count == 0) continue; // CraftBukkit + i = k; + } + } + + return i; + } + + public void setItem(int i, ItemStack itemstack) { + this.items[i] = itemstack; + if (itemstack != null && itemstack.count > this.getMaxStackSize()) { + itemstack.count = this.getMaxStackSize(); + } + + this.update(); + } + + public int addItem(ItemStack itemstack) { + for (int i = 0; i < this.items.length; ++i) { + ItemStack itemstack1 = this.items[i]; + if (itemstack1 == null || itemstack1.getItem() == null) { + this.setItem(i, itemstack); + return i; + } + } + + return -1; + } + + public String getName() { + return this.hasCustomName() ? this.a : "container.dispenser"; + } + + public void a(String s) { + this.a = s; + } + + public boolean hasCustomName() { + return this.a != null; + } + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + NBTTagList nbttaglist = nbttagcompound.getList("Items", 10); + + this.items = new ItemStack[this.getSize()]; + + for (int i = 0; i < nbttaglist.size(); ++i) { + NBTTagCompound nbttagcompound1 = nbttaglist.get(i); + int j = nbttagcompound1.getByte("Slot") & 255; + + if (j < this.items.length) { + this.items[j] = ItemStack.createStack(nbttagcompound1); + } + } + + if (nbttagcompound.hasKeyOfType("CustomName", 8)) { + this.a = nbttagcompound.getString("CustomName"); + } + + } + + public void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + NBTTagList nbttaglist = new NBTTagList(); + + for (int i = 0; i < this.items.length; ++i) { + ItemStack itemstack = items[i]; + if (itemstack != null) { + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + + nbttagcompound1.setByte("Slot", (byte) i); + itemstack.save(nbttagcompound1); + nbttaglist.add(nbttagcompound1); + } + } + + nbttagcompound.set("Items", nbttaglist); + if (this.hasCustomName()) { + nbttagcompound.setString("CustomName", this.a); + } + + } + + public int getMaxStackSize() { + return maxStack; // CraftBukkit + } + + public boolean a(EntityHuman entityhuman) { + return this.world.getTileEntity(this.position) == this && entityhuman.e((double) this.position.getX() + 0.5D, (double) this.position.getY() + 0.5D, (double) this.position.getZ() + 0.5D) <= 64.0D; + } + + public void startOpen(EntityHuman entityhuman) { + } + + public void closeContainer(EntityHuman entityhuman) { + } + + public boolean b(int i, ItemStack itemstack) { + return true; + } + + public String getContainerName() { + return "minecraft:dispenser"; + } + + public Container createContainer(PlayerInventory playerinventory, EntityHuman entityhuman) { + return new ContainerDispenser(playerinventory, this); + } + + public int getProperty(int i) { + return 0; + } + + public void b(int i, int j) { + } + + public int g() { + return 0; + } + + public void l() { + Arrays.fill(this.items, null); + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/TileEntityDropper.java b/azurite-server/src/main/java/net/minecraft/server/TileEntityDropper.java new file mode 100644 index 0000000..ec7722d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/TileEntityDropper.java @@ -0,0 +1,14 @@ +package net.minecraft.server; + +public class TileEntityDropper extends TileEntityDispenser { + + public TileEntityDropper() {} + + public String getName() { + return this.hasCustomName() ? this.a : "container.dropper"; + } + + public String getContainerName() { + return "minecraft:dropper"; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/TileEntityEnchantTable.java b/azurite-server/src/main/java/net/minecraft/server/TileEntityEnchantTable.java new file mode 100644 index 0000000..e054166 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/TileEntityEnchantTable.java @@ -0,0 +1,122 @@ +package net.minecraft.server; + +import java.util.Random; + +public class TileEntityEnchantTable extends TileEntity implements IUpdatePlayerListBox, ITileEntityContainer { + + public int a; + public float f; + public float g; + public float h; + public float i; + public float j; + public float k; + public float l; + public float m; + public float n; + private static Random o = new Random(); + private String p; + + public TileEntityEnchantTable() {} + + public void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + if (this.hasCustomName()) { + nbttagcompound.setString("CustomName", this.p); + } + + } + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + if (nbttagcompound.hasKeyOfType("CustomName", 8)) { + this.p = nbttagcompound.getString("CustomName"); + } + + } + + public void c() { + this.k = this.j; + this.m = this.l; + EntityHuman entityhuman = this.world.findNearbyPlayer((double) ((float) this.position.getX() + 0.5F), (double) ((float) this.position.getY() + 0.5F), (double) ((float) this.position.getZ() + 0.5F), 3.0D); + + if (entityhuman != null) { + double d0 = entityhuman.locX - (double) ((float) this.position.getX() + 0.5F); + double d1 = entityhuman.locZ - (double) ((float) this.position.getZ() + 0.5F); + + this.n = (float) MathHelper.b(d1, d0); + this.j += 0.1F; + if (this.j < 0.5F || TileEntityEnchantTable.o.nextInt(40) == 0) { + float f = this.h; + + do { + this.h += (float) (TileEntityEnchantTable.o.nextInt(4) - TileEntityEnchantTable.o.nextInt(4)); + } while (f == this.h); + } + } else { + this.n += 0.02F; + this.j -= 0.1F; + } + + while (this.l >= 3.1415927F) { + this.l -= 6.2831855F; + } + + while (this.l < -3.1415927F) { + this.l += 6.2831855F; + } + + while (this.n >= 3.1415927F) { + this.n -= 6.2831855F; + } + + while (this.n < -3.1415927F) { + this.n += 6.2831855F; + } + + float f1; + + for (f1 = this.n - this.l; f1 >= 3.1415927F; f1 -= 6.2831855F) { + ; + } + + while (f1 < -3.1415927F) { + f1 += 6.2831855F; + } + + this.l += f1 * 0.4F; + this.j = MathHelper.a(this.j, 0.0F, 1.0F); + ++this.a; + this.g = this.f; + float f2 = (this.h - this.f) * 0.4F; + float f3 = 0.2F; + + f2 = MathHelper.a(f2, -f3, f3); + this.i += (f2 - this.i) * 0.9F; + this.f += this.i; + } + + public String getName() { + return this.hasCustomName() ? this.p : "container.enchant"; + } + + public boolean hasCustomName() { + return this.p != null && this.p.length() > 0; + } + + public void a(String s) { + this.p = s; + } + + public IChatBaseComponent getScoreboardDisplayName() { + return (IChatBaseComponent) (this.hasCustomName() ? new ChatComponentText(this.getName()) : new ChatMessage(this.getName(), new Object[0])); + } + + public Container createContainer(PlayerInventory playerinventory, EntityHuman entityhuman) { + return new ContainerEnchantTable(playerinventory, this.world, this.position); + } + + public String getContainerName() { + return "minecraft:enchanting_table"; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/TileEntityEnderChest.java b/azurite-server/src/main/java/net/minecraft/server/TileEntityEnderChest.java new file mode 100644 index 0000000..4c25d35 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/TileEntityEnderChest.java @@ -0,0 +1,64 @@ +package net.minecraft.server; + +public class TileEntityEnderChest extends TileEntity { // PaperSpigot - remove IUpdatePlayerListBox + + public float a; // PaperSpigot - lidAngle + public float f; + public int g; // PaperSpigot - numPlayersUsing + + public TileEntityEnderChest() {} + + public void c() { + } + + public boolean c(int i, int j) { + if (i == 1) { + this.g = j; + return true; + } else { + return super.c(i, j); + } + } + + public void y() { + this.E(); + super.y(); + } + + public void b() { + ++this.g; + + // PaperSpigot start - Move enderchest open sounds out of the tick loop + if (this.g > 0 && this.a == 0.0F) { + this.a = 0.7F; + + double d1 = (double) this.getPosition().getX() + 0.5D; + double d0 = (double) this.getPosition().getZ() + 0.5D; + + this.world.makeSound(d1, (double) this.getPosition().getY() + 0.5D, d0, "random.chestopen", 0.5F, this.world.random.nextFloat() * 0.1F + 0.9F); + } + // PaperSpigot end + + this.world.playBlockAction(this.position, Blocks.ENDER_CHEST, 1, this.g); + } + + public void d() { + --this.g; + + // PaperSpigot start - Move enderchest close sounds out of the tick loop + if (this.g == 0 && this.a > 0.0F || this.g > 0 && this.a < 1.0F) { + double d0 = (double) this.getPosition().getX() + 0.5D; + double d2 = (double) this.getPosition().getZ() + 0.5D; + + this.world.makeSound(d0, (double) this.getPosition().getY() + 0.5D, d2, "random.chestclosed", 0.5F, this.world.random.nextFloat() * 0.1F + 0.9F); + this.a = 0.0F; + } + // PaperSpigot end + + this.world.playBlockAction(this.position, Blocks.ENDER_CHEST, 1, this.g); + } + + public boolean a(EntityHuman entityhuman) { + return this.world.getTileEntity(this.position) == this && entityhuman.e((double) this.position.getX() + 0.5D, (double) this.position.getY() + 0.5D, (double) this.position.getZ() + 0.5D) <= 64.0D; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/TileEntityEnderPortal.java b/azurite-server/src/main/java/net/minecraft/server/TileEntityEnderPortal.java new file mode 100644 index 0000000..09c78a9 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/TileEntityEnderPortal.java @@ -0,0 +1,6 @@ +package net.minecraft.server; + +public class TileEntityEnderPortal extends TileEntity { + + public TileEntityEnderPortal() {} +} diff --git a/azurite-server/src/main/java/net/minecraft/server/TileEntityFlowerPot.java b/azurite-server/src/main/java/net/minecraft/server/TileEntityFlowerPot.java new file mode 100644 index 0000000..676e101 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/TileEntityFlowerPot.java @@ -0,0 +1,55 @@ +package net.minecraft.server; + +public class TileEntityFlowerPot extends TileEntity { + + private Item a; + private int f; + + public TileEntityFlowerPot() {} + + public TileEntityFlowerPot(Item item, int i) { + this.a = item; + this.f = i; + } + + public void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + MinecraftKey minecraftkey = (MinecraftKey) Item.REGISTRY.c(this.a); + + nbttagcompound.setString("Item", minecraftkey == null ? "" : minecraftkey.toString()); + nbttagcompound.setInt("Data", this.f); + } + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + if (nbttagcompound.hasKeyOfType("Item", 8)) { + this.a = Item.d(nbttagcompound.getString("Item")); + } else { + this.a = Item.getById(nbttagcompound.getInt("Item")); + } + + this.f = nbttagcompound.getInt("Data"); + } + + public Packet getUpdatePacket() { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + + this.b(nbttagcompound); + nbttagcompound.remove("Item"); + nbttagcompound.setInt("Item", Item.getId(this.a)); + return new PacketPlayOutTileEntityData(this.position, 5, nbttagcompound); + } + + public void a(Item item, int i) { + this.a = item; + this.f = i; + } + + public Item b() { + return this.a; + } + + public int c() { + return this.f; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/TileEntityFurnace.java b/azurite-server/src/main/java/net/minecraft/server/TileEntityFurnace.java new file mode 100644 index 0000000..5ec991a --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/TileEntityFurnace.java @@ -0,0 +1,423 @@ +package net.minecraft.server; + +// CraftBukkit start + +import dev.azurite.spigot.configs.AzuriteConfig; +import org.bukkit.craftbukkit.entity.CraftHumanEntity; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.craftbukkit.util.LongHash; +import org.bukkit.entity.HumanEntity; +import org.bukkit.event.inventory.FurnaceBurnEvent; +import org.bukkit.event.inventory.FurnaceSmeltEvent; + +import java.util.Arrays; +import java.util.List; + +public class TileEntityFurnace extends TileEntityContainer implements IUpdatePlayerListBox, IWorldInventory { + + private static final int[] a = new int[]{0}; + private static final int[] f = new int[]{2, 1}; + private static final int[] g = new int[]{1}; + public int burnTime; + public int cookTime; + public List transaction = new java.util.ArrayList<>(); + private ItemStack[] items = new ItemStack[3]; + private int ticksForCurrentFuel; + private int cookTimeTotal; + private String m; + // CraftBukkit start - add fields and methods + private int lastTick = MinecraftServer.currentTick; + private int maxStack = MAX_STACK; + + public TileEntityFurnace() { + } + + public static int fuelTime(ItemStack itemstack) { + if (itemstack == null) { + return 0; + } else { + Item item = itemstack.getItem(); + + if (item instanceof ItemBlock && Block.asBlock(item) != Blocks.AIR) { + Block block = Block.asBlock(item); + + if (block == Blocks.WOODEN_SLAB) { + return 150; + } else if (block.getMaterial() == Material.WOOD) { + return 300; + } else if (block == Blocks.COAL_BLOCK) { + return 16000; + } + } + if (item == Items.COAL) return 1600; + return item instanceof ItemTool && ((ItemTool) item).h().equals("WOOD") ? 200 : item instanceof ItemSword && ((ItemSword) item).h().equals("WOOD") ? 200 : item instanceof ItemHoe && ((ItemHoe) item).g().equals("WOOD") ? 200 : item == Items.STICK ? 100 : item == Items.LAVA_BUCKET ? 20000 : item == Item.getItemOf(Blocks.SAPLING) ? 100 : item == Items.BLAZE_ROD ? 2400 : 0; + } + } + + public static boolean isFuel(ItemStack itemstack) { + return fuelTime(itemstack) > 0; + } + + public ItemStack[] getContents() { + return this.items; + } + + public void onOpen(CraftHumanEntity who) { + transaction.add(who); + } + // CraftBukkit end + + public void onClose(CraftHumanEntity who) { + transaction.remove(who); + } + + public List getViewers() { + return transaction; + } + + public int getSize() { + return this.items.length; + } + + public ItemStack getItem(int i) { + return this.items[i]; + } + + public ItemStack splitStack(int i, int j) { + ItemStack itemstack = items[i]; + if (itemstack != null) { + if (itemstack.count <= j) { + this.items[i] = null; + } else { + if (itemstack.count == 0) { + this.items[i] = null; + } + itemstack = itemstack.cloneAndSubtract(j); + } + return itemstack; + } else { + return null; + } + } + + public ItemStack splitWithoutUpdate(int i) { + ItemStack itemstack = this.items[i]; + if (itemstack != null) { + this.items[i] = null; + return itemstack; + } else { + return null; + } + } + + public void setItem(int i, ItemStack itemstack) { + ItemStack itemstack1 = this.items[i]; + boolean flag = itemstack != null && itemstack.doMaterialsMatch(itemstack1) && ItemStack.equals(itemstack, itemstack1); + + this.items[i] = itemstack; + if (itemstack != null && itemstack.count > this.getMaxStackSize()) { + itemstack.count = this.getMaxStackSize(); + } + + if (i == 0 && !flag) { + this.cookTimeTotal = this.a(itemstack); + this.cookTime -= this.cookTimeTotal; + this.update(); + } + + } + + public String getName() { + return this.hasCustomName() ? this.m : "container.furnace"; + } + + public boolean hasCustomName() { + return this.m != null && !this.m.isEmpty(); + } + + public void a(String s) { + this.m = s; + } + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + NBTTagList nbttaglist = nbttagcompound.getList("Items", 10); + + this.items = new ItemStack[this.getSize()]; + + for (int i = 0; i < nbttaglist.size(); ++i) { + NBTTagCompound nbttagcompound1 = nbttaglist.get(i); + byte b0 = nbttagcompound1.getByte("Slot"); + + if (b0 >= 0 && b0 < this.items.length) { + this.items[b0] = ItemStack.createStack(nbttagcompound1); + } + } + + this.burnTime = nbttagcompound.getShort("BurnTime"); + this.cookTime = nbttagcompound.getShort("CookTime"); + this.cookTimeTotal = nbttagcompound.getShort("CookTimeTotal"); + this.ticksForCurrentFuel = fuelTime(this.items[1]); + if (nbttagcompound.hasKeyOfType("CustomName", 8)) { + this.m = nbttagcompound.getString("CustomName"); + } + } + + public void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + nbttagcompound.setShort("BurnTime", (short) this.burnTime); + nbttagcompound.setShort("CookTime", (short) this.cookTime); + nbttagcompound.setShort("CookTimeTotal", (short) this.cookTimeTotal); + NBTTagList nbttaglist = new NBTTagList(); + + for (int i = 0; i < this.items.length; ++i) { + ItemStack itemstack = this.items[i]; + if (itemstack != null) { + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + + nbttagcompound1.setByte("Slot", (byte) i); + itemstack.save(nbttagcompound1); + nbttaglist.add(nbttagcompound1); + } + } + + nbttagcompound.set("Items", nbttaglist); + if (this.hasCustomName()) { + nbttagcompound.setString("CustomName", this.m); + } + + } + + public int getMaxStackSize() { + return maxStack; // CraftBukkit + } + + public void setMaxStackSize(int size) { + maxStack = size; + } + + public boolean isBurning() { + return this.burnTime > 0; + } + + public void c() { + if (!AzuriteConfig.tickFurnaces.getValue()) return; + boolean flag = (this.w() == Blocks.LIT_FURNACE); // CraftBukkit - SPIGOT-844 - Check if furnace block is lit using the block instead of burn time // PAIL: Rename + boolean flag1 = false; + + // CraftBukkit start - Use wall time instead of ticks for cooking + int elapsedTicks = MinecraftServer.currentTick - this.lastTick; + this.lastTick = MinecraftServer.currentTick; + + // CraftBukkit - moved from below + if (this.isBurning() && this.canBurn()) { + this.cookTime += (int) (elapsedTicks * AzuriteConfig.furnaceModifier.getValue()); + if (this.cookTime >= this.cookTimeTotal) { + this.cookTime = 0; + this.cookTimeTotal = this.a(this.items[0]); + this.burn(); + flag1 = true; + } + } else { + this.cookTime = 0; + } + // CraftBukkit end + + if (this.isBurning()) { + this.burnTime -= elapsedTicks; // CraftBukkit - use elapsedTicks in place of constant + } + + ItemStack itemstack1 = items[1]; + if (!isBurning() && (itemstack1 == null || items[0] == null)) { + if (!isBurning() && cookTime > 0) { + cookTime = MathHelper.clamp(cookTime - 2, 0, cookTimeTotal); + } + } else if (itemstack1 != null && itemstack1.getItem() != Items.BUCKET) { + // CraftBukkit start - Handle multiple elapsed ticks + if (this.burnTime <= 0 && this.canBurn()) { // CraftBukkit - == to <= + + FurnaceBurnEvent furnaceBurnEvent = new FurnaceBurnEvent(this.world.getWorld().getBlockAt(position.getX(), position.getY(), position.getZ()), CraftItemStack.asCraftMirror(itemstack1), fuelTime(itemstack1)); + this.world.getServer().getPluginManager().callEvent(furnaceBurnEvent); + + if (furnaceBurnEvent.isCancelled()) { + return; + } + + this.ticksForCurrentFuel = furnaceBurnEvent.getBurnTime(); + this.burnTime += this.ticksForCurrentFuel; + if (this.burnTime > 0 && furnaceBurnEvent.isBurning()) { + // CraftBukkit end + flag1 = true; + itemstack1 = items[1]; + if (itemstack1 != null) { + --itemstack1.count; + if (itemstack1.count == 0) { + Item item = itemstack1.getItem().q(); + + this.items[1] = item != null ? new ItemStack(item) : null; + } + } + } + } + } + + if (flag != this.isBurning()) { + flag1 = true; + BlockFurnace.a(this.isBurning(), this.world, this.position); + this.E(); // CraftBukkit - Invalidate tile entity's cached block type // PAIL: Rename + } + + if (flag1) { + this.update(); + } + + } + + public int a(ItemStack itemstack) { + return 200; + } + + private boolean canBurn() { + ItemStack firstItem = items[0]; + if (firstItem != null && world.isLoaded(position) && !((WorldServer) world).chunkProviderServer.unloadQueue.contains(LongHash.toLong(position.getX() >> 4, position.getZ() >> 4))) { + // CraftBukkit - consider resultant count instead of current count + ItemStack result = RecipesFurnace.getInstance().getResult(firstItem), secondItem = items[2]; + return result != null && (secondItem == null || (secondItem.doMaterialsMatch(result) && (secondItem.count + result.count <= getMaxStackSize() && secondItem.count < secondItem.getMaxStackSize() || secondItem.count + result.count <= result.getMaxStackSize()))); + } + return false; + } + + public void burn() { + if (this.canBurn()) { + ItemStack itemstack = RecipesFurnace.getInstance().getResult(this.items[0]); + + // CraftBukkit start - fire FurnaceSmeltEvent + CraftItemStack source = CraftItemStack.asCraftMirror(this.items[0]); + org.bukkit.inventory.ItemStack result = CraftItemStack.asBukkitCopy(itemstack); + + FurnaceSmeltEvent furnaceSmeltEvent = new FurnaceSmeltEvent(this.world.getWorld().getBlockAt(position.getX(), position.getY(), position.getZ()), source, result); + this.world.getServer().getPluginManager().callEvent(furnaceSmeltEvent); + + if (furnaceSmeltEvent.isCancelled()) { + return; + } + + result = furnaceSmeltEvent.getResult(); + itemstack = CraftItemStack.asNMSCopy(result); + + if (itemstack != null) { + if (this.items[2] == null) { + this.items[2] = itemstack; + } else if (CraftItemStack.asCraftMirror(this.items[2]).isSimilar(result)) { + this.items[2].count += itemstack.count; + } else { + return; + } + } + + // CraftBukkit end + + if (this.items[0].getItem() == Item.getItemOf(Blocks.SPONGE) && this.items[0].getData() == 1 && this.items[1] != null && this.items[1].getItem() == Items.BUCKET) { + this.items[1] = new ItemStack(Items.WATER_BUCKET); + } + + --this.items[0].count; + if (this.items[0].count <= 0) { + this.items[0] = null; + } + + } + } + + public boolean a(EntityHuman entityhuman) { + return this.world.getTileEntity(this.position) == this && entityhuman.e((double) this.position.getX() + 0.5D, (double) this.position.getY() + 0.5D, (double) this.position.getZ() + 0.5D) <= 64.0D; + } + + public void startOpen(EntityHuman entityhuman) { + } + + public void closeContainer(EntityHuman entityhuman) { + } + + public boolean b(int i, ItemStack itemstack) { + return i != 2 && (i != 1 || isFuel(itemstack) || SlotFurnaceFuel.c_(itemstack)); + } + + public int[] getSlotsForFace(EnumDirection enumdirection) { + return enumdirection == EnumDirection.DOWN ? TileEntityFurnace.f : (enumdirection == EnumDirection.UP ? TileEntityFurnace.a : TileEntityFurnace.g); + } + + public int[] getSlotsForDownFace() { + return TileEntityFurnace.f; + } + + public boolean canPlaceItemThroughFace(int i, ItemStack itemstack, EnumDirection enumdirection) { + return this.b(i, itemstack); + } + + public boolean canTakeItemThroughFace(int i, ItemStack itemstack, EnumDirection enumdirection) { + if (enumdirection == EnumDirection.DOWN && i == 1) { + Item item = itemstack.getItem(); + + return item == Items.WATER_BUCKET || item == Items.BUCKET; + } + + return true; + } + + public String getContainerName() { + return "minecraft:furnace"; + } + + public Container createContainer(PlayerInventory playerinventory, EntityHuman entityhuman) { + return new ContainerFurnace(playerinventory, this); + } + + public int getProperty(int i) { + switch (i) { + case 0: + return this.burnTime; + + case 1: + return this.ticksForCurrentFuel; + + case 2: + return this.cookTime; + + case 3: + return this.cookTimeTotal; + + default: + return 0; + } + } + + public void b(int i, int j) { + switch (i) { + case 0: + this.burnTime = j; + break; + + case 1: + this.ticksForCurrentFuel = j; + break; + + case 2: + this.cookTime = j; + break; + + case 3: + this.cookTimeTotal = j; + } + + } + + public int g() { + return 4; + } + + public void l() { + Arrays.fill(this.items, null); + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/TileEntityHopper.java b/azurite-server/src/main/java/net/minecraft/server/TileEntityHopper.java new file mode 100644 index 0000000..ab3da81 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/TileEntityHopper.java @@ -0,0 +1,848 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.AzuriteConfig; +import dev.azurite.spigot.optimizations.ModernHopperOptimizations; +import net.techcable.tacospigot.HopperHelper; +import org.bukkit.craftbukkit.entity.CraftHumanEntity; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.craftbukkit.util.CraftMagicNumbers; +import org.bukkit.craftbukkit.util.LongHash; +import org.bukkit.entity.HumanEntity; +import org.bukkit.event.inventory.InventoryMoveItemEvent; +import org.bukkit.event.inventory.InventoryPickupItemEvent; +import org.bukkit.inventory.Inventory; + +import java.util.Arrays; +import java.util.List; + +public class TileEntityHopper extends TileEntityContainer implements IHopper, IUpdatePlayerListBox { + + // CraftBukkit start - add fields and methods + public List transaction = new java.util.ArrayList<>(); + private ItemStack[] items = new ItemStack[5]; + private String f; + // private int g = -1; + private int g = -1; + private int maxStack = MAX_STACK; + + // Beanes - optimized hoppers + public IInventory cachedPullInventory, cachedPushInventory; + public boolean isEmpty = true; + public boolean isFull = false; + + private static boolean b(IInventory iinventory, EnumDirection enumdirection) { + if (iinventory instanceof IWorldInventory) { + IWorldInventory iworldinventory = (IWorldInventory) iinventory; + for (int j : iworldinventory.getSlotsForFace(enumdirection)) { + if (iworldinventory.getItem(j) != null) { + return false; + } + } + } else { + int j = iinventory.getSize(); + + for (int k = 0; k < j; ++k) { + if (iinventory.getItem(k) != null) { + return false; + } + } + } + + return true; + } + + private static boolean isInventoryEmptyOptimized(IInventory iinventory) { + // Beanes - fast path for hoppers + if (iinventory instanceof TileEntityHopper) { + return ((TileEntityHopper) iinventory).isEmpty; + } + + return true; + } + + // TacoSpigot start - Split methods, one that pushes and one that pulls + @Deprecated + public static boolean a(IHopper ihopper) { + IInventory iinventory; + if (ihopper instanceof TileEntityHopper) { + iinventory = HopperHelper.getInventory(ihopper.getWorld(), ((TileEntityHopper) ihopper).getPosition().up()); // Only pull from a above, because + } else { + iinventory = b(ihopper); // Use old behavior for BB entity searching + } + return acceptItem(ihopper, iinventory); + } + + public static boolean acceptItem(IHopper ihopper, IInventory iinventory) { + // TacoSpigot end + if (iinventory != null) { + EnumDirection enumdirection = EnumDirection.DOWN; + + if (b(iinventory, enumdirection)) { + return false; + } + + ModernHopperOptimizations.skipPushModeEventFire = ModernHopperOptimizations.skipHopperEvents; + + if (iinventory instanceof IWorldInventory) { + for (int j : ((IWorldInventory) iinventory).getSlotsForFace(enumdirection)) { + if (a(ihopper, iinventory, j, enumdirection)) { + return true; + } + } + } else { + int j = iinventory.getSize(); + + for (int k = 0; k < j; ++k) { + if (a(ihopper, iinventory, k, enumdirection)) { + return true; + } + } + } + } + + return false; + } + + private static boolean optimizedPull(IHopper ihopper, IInventory iinventory, int i, EnumDirection enumdirection) { + ItemStack itemstack = iinventory.getItem(i); + + if (itemstack != null && b(iinventory, itemstack, i, enumdirection)) { + return ModernHopperOptimizations.hopperPull(ihopper, iinventory, itemstack, i); // Beanes - Paper 1.12.2 patch + } + + return false; + } + + private static boolean a(IHopper ihopper, IInventory iinventory, int i, EnumDirection enumdirection) { + ItemStack itemstack = iinventory.getItem(i); + + if (itemstack != null && b(iinventory, itemstack, i, enumdirection)) { + ItemStack itemstack1 = itemstack.cloneItemStack(); + + // CraftBukkit start - Call event on collection of items from inventories into + // the hopper + CraftItemStack oitemstack = CraftItemStack.asCraftMirror(iinventory.splitStack(i, ihopper.getWorld().spigotConfig.hopperAmount)); // Spigot + // TacoSpigot start - add an option to turn of InventoryMoveItemEvent + final org.bukkit.inventory.ItemStack stack; + if (HopperHelper.isFireInventoryMoveItemEvent(ihopper)) { + // TacoSpigot end + + Inventory sourceInventory; + // Have to special case large chests as they work oddly + if (iinventory instanceof InventoryLargeChest) { + sourceInventory = new org.bukkit.craftbukkit.inventory.CraftInventoryDoubleChest((InventoryLargeChest) iinventory); + } else { + sourceInventory = iinventory.getOwner().getInventory(); + } + + InventoryMoveItemEvent event = new InventoryMoveItemEvent(sourceInventory, oitemstack.clone(), + ihopper.getOwner().getInventory(), false); + + ihopper.getWorld().getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { + iinventory.setItem(i, itemstack1); + + if (ihopper instanceof TileEntityHopper) { + ((TileEntityHopper) ihopper).d(ihopper.getWorld().spigotConfig.hopperTransfer); // Spigot + } else if (ihopper instanceof EntityMinecartHopper) { + ((EntityMinecartHopper) ihopper).m(ihopper.getWorld().spigotConfig.hopperTransfer / 2); // Spigot + } + return false; + } + // TacoSpigot start + stack = event.getItem(); + // handle cases where the event is not fired + } else { + stack = oitemstack; + } + int origCount = stack.getAmount(); // Spigot + ItemStack itemstack2 = addItem(ihopper, CraftItemStack.asNMSCopy(stack), null); + // TacoSpigot end + + if (itemstack2 == null || itemstack2.count == 0) { + if (stack.equals(oitemstack)) { + iinventory.update(); + } else { + iinventory.setItem(i, itemstack1); + } + // CraftBukkit end + return true; + } + itemstack1.count -= origCount - itemstack2.count; // Spigot + + iinventory.setItem(i, itemstack1); + } + + return false; + } + + public static boolean a(IInventory iinventory, EntityItem entityitem) { + boolean flag = false; + + if (entityitem == null) { + return false; + } else { + // CraftBukkit start + InventoryPickupItemEvent event = new InventoryPickupItemEvent(ModernHopperOptimizations.getInventory(iinventory), (org.bukkit.entity.Item) entityitem.getBukkitEntity()); // Paper - avoid snapshot creation + entityitem.world.getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { + return false; + } + // CraftBukkit end + + ItemStack itemstack1 = addItem(iinventory, entityitem.getItemStack().cloneItemStack(), null); + + if (itemstack1 != null && itemstack1.count != 0) { + entityitem.setItemStack(itemstack1); + } else { + flag = true; + entityitem.die(); + } + + return flag; + } + } + + public static ItemStack addItem(IInventory iinventory, ItemStack itemstack, EnumDirection direction) { + if (iinventory instanceof IWorldInventory && direction != null) { + IWorldInventory iworldinventory = (IWorldInventory) iinventory; + int[] slots = iworldinventory.getSlotsForFace(direction); + + for (int slotI = 0; slotI < slots.length && itemstack != null && itemstack.count > 0; ++slotI) { + itemstack = c(iinventory, itemstack, slots[slotI], direction); + } + } else { + for (int slot = 0; slot < iinventory.getSize() && itemstack != null && itemstack.count > 0; ++slot) { + itemstack = c(iinventory, itemstack, slot, direction); + } + } + + if (itemstack != null && itemstack.count == 0) { + itemstack = null; + } + + return itemstack; + } + + private static boolean a(IInventory iinventory, ItemStack itemstack, int i, EnumDirection enumdirection) { + return iinventory.b(i, itemstack) && (!(iinventory instanceof IWorldInventory) + || ((IWorldInventory) iinventory).canPlaceItemThroughFace(i, itemstack, enumdirection)); + } + // CraftBukkit end + + private static boolean b(IInventory iinventory, ItemStack itemstack, int i, EnumDirection enumdirection) { + return !(iinventory instanceof IWorldInventory) + || ((IWorldInventory) iinventory).canTakeItemThroughFace(i, itemstack, enumdirection); + } + + private static ItemStack c(IInventory iinventory, ItemStack itemstack, int slot, EnumDirection direction) { + ItemStack itemstack1 = iinventory.getItem(slot); + + if (a(iinventory, itemstack, slot, direction)) { + boolean flag = false; + + if (itemstack1 == null) { + iinventory.setItem(slot, itemstack); + + itemstack = null; + flag = true; + } else if (a(itemstack1, itemstack)) { + int k = Math.min(itemstack.count, itemstack.getMaxStackSize() - itemstack1.count); + + itemstack.count -= k; + itemstack1.count += k; + flag = k > 0; + } + + if (flag) { + if (iinventory instanceof TileEntityHopper) { + TileEntityHopper tileentityhopper = (TileEntityHopper) iinventory; + + if (tileentityhopper.o()) { + tileentityhopper.d(tileentityhopper.world.spigotConfig.hopperTransfer); // Spigot + } + + iinventory.update(); + } + + iinventory.update(); + } + } + + return itemstack; + } + + public static IInventory b(IHopper ihopper) { + return b(ihopper.getWorld(), ihopper.A(), ihopper.B() + 1.0D, ihopper.C()); + } + + public static List a(World world, double d0, double d1, double d2) { + return world.a(EntityItem.class, new AxisAlignedBB(d0 - 0.5D, d1 - 0.5D, d2 - 0.5D, d0 + 0.5D, d1 + 0.5D, d2 + 0.5D), IEntitySelector.a); + } + + public static IInventory b(World world, double d0, double d1, double d2) { + Object object = null; + int i = MathHelper.floor(d0), j = MathHelper.floor(d1), k = MathHelper.floor(d2); + if (!world.isValidLocation(i, j, k)) + return null; + long hash = LongHash.toLong(i >> 4, k >> 4); + Chunk chunk = world.getChunkIfLoaded(hash); + if (chunk == null || ((ChunkProviderServer) world.chunkProvider).unloadQueue.contains(hash)) + return null; + Block block = world.getType(chunk, i, j, k, true).getBlock(); + + BlockPosition blockposition = new BlockPosition(i, j, k); + if (block.isTileEntity()) { + TileEntity tileentity = world.getTileEntity(chunk, blockposition, block); + + if (tileentity instanceof IInventory) { + object = tileentity; + if (object instanceof TileEntityChest && block instanceof BlockChest) { + object = ((BlockChest) block).f(world, blockposition); + } + } + } + + if (object == null && !CraftMagicNumbers.getMaterial(block).isOccluding() && chunk.getItemCount(blockposition) > 0) { + List list = world.a((Entity) null, + new AxisAlignedBB(d0 - 0.5D, d1 - 0.5D, d2 - 0.5D, d0 + 0.5D, d1 + 0.5D, d2 + 0.5D), + IEntitySelector.c); + + if (!list.isEmpty()) { + object = list.get(world.random.nextInt(list.size())); + } + } + + return (IInventory) object; + } + + private static boolean a(ItemStack itemstack, ItemStack itemstack1) { + return itemstack.getItem() == itemstack1.getItem() && (itemstack.getData() == itemstack1.getData() && (itemstack.count <= itemstack.getMaxStackSize() && ItemStack.equals(itemstack, itemstack1))); + } + + public ItemStack[] getContents() { + return this.items; + } + + public void onOpen(CraftHumanEntity who) { + transaction.add(who); + } + + public void onClose(CraftHumanEntity who) { + transaction.remove(who); + } + + public List getViewers() { + return transaction; + } + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + NBTTagList nbttaglist = nbttagcompound.getList("Items", 10); + + this.items = new ItemStack[this.getSize()]; + if (nbttagcompound.hasKeyOfType("CustomName", 8)) { + this.f = nbttagcompound.getString("CustomName"); + } + + this.g = nbttagcompound.getInt("TransferCooldown"); + + for (int i = 0; i < nbttaglist.size(); ++i) { + NBTTagCompound nbttagcompound1 = nbttaglist.get(i); + byte b0 = nbttagcompound1.getByte("Slot"); + + if (b0 >= 0 && b0 < this.items.length) { + this.items[b0] = ItemStack.createStack(nbttagcompound1); + } + } + + this.recalculateEmptyAndFull(); + } + + public void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + NBTTagList nbttaglist = new NBTTagList(); + + for (int i = 0; i < this.items.length; ++i) { + if (this.items[i] != null) { + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + + nbttagcompound1.setByte("Slot", (byte) i); + this.items[i].save(nbttagcompound1); + nbttaglist.add(nbttagcompound1); + } + } + + nbttagcompound.set("Items", nbttaglist); + nbttagcompound.setInt("TransferCooldown", this.g); + if (this.hasCustomName()) { + nbttagcompound.setString("CustomName", this.f); + } + + } + + public int getSize() { + return this.items.length; + } + + public ItemStack getItem(int i) { + return this.items[i]; + } + + public ItemStack splitStack(int i, int j) { + if (this.items[i] != null) { + ItemStack itemstack = items[i]; + if (itemstack.count <= j) { + this.items[i] = null; + } else { + if (itemstack.count == 0) { + this.items[i] = null; + } + itemstack = itemstack.cloneAndSubtract(j); + } + + this.recalculateEmptyAndFull(); + + return itemstack; + } else { + return null; + } + } + + public ItemStack splitWithoutUpdate(int i) { + if (this.items[i] != null) { + ItemStack itemstack = this.items[i]; + + this.items[i] = null; + + this.recalculateEmptyAndFull(); + + return itemstack; + } else { + return null; + } + } + // TacoSpigot end + + public void setItem(int i, ItemStack itemstack) { + this.items[i] = itemstack; + if (itemstack != null && itemstack.count > this.getMaxStackSize()) { + itemstack.count = this.getMaxStackSize(); + } + + this.recalculateEmptyAndFull(); + } + + public String getName() { + return this.hasCustomName() ? this.f : "container.hopper"; + } + + public boolean hasCustomName() { + return this.f != null && !this.f.isEmpty(); + } + + public void a(String s) { + this.f = s; + } + + public int getMaxStackSize() { + return maxStack; // CraftBukkit + } + + public void setMaxStackSize(int size) { + maxStack = size; + } + + public boolean a(EntityHuman entityhuman) { + return this.world.getTileEntity(this.position) == this && entityhuman.e(this.position.getX() + 0.5D, this.position.getY() + 0.5D, + this.position.getZ() + 0.5D) <= 64.0D; + } + + public void startOpen(EntityHuman entityhuman) { + } + + public void closeContainer(EntityHuman entityhuman) { + } + + public boolean b(int i, ItemStack itemstack) { + return true; + } + + public void c() { + if (!AzuriteConfig.tickHoppers.getValue()) { + return; + } + + --this.g; + if (g > 0) { + return; + } + + this.g = 0; + + int state = this.u(); + + if ((state & 8) == 8) { // Check if block is locked + return; + } + + if (AzuriteConfig.optimizeHoppers.getValue()) { + optimizedUpdate(state); + } else { + vanillaUpdate(); + } + } + + public void optimizedUpdate(int state) { + boolean transferred = false; + + if (!isEmpty) { // If not empty -> transfer items out + EnumDirection pointingDirection = BlockHopper.b(state); + + // We cache the push inventory + if (cachedPushInventory == null) { + cachedPushInventory = HopperHelper.getInventoryForPushingOptimizedPath(getWorld(), getPosition().shift(pointingDirection), this); + } + + if (cachedPushInventory != null) { + EnumDirection oppositePointing = pointingDirection.opposite(); + + // It might actually be more optimal to check if the inventory is full (this is very quick and is less intensive as the hopperPush code) + if (!isInventoryFullOptimized(cachedPushInventory, oppositePointing)) { + transferred = ModernHopperOptimizations.hopperPush(this, cachedPushInventory, pointingDirection); + } + } + } + + if (!isFull) { // If not full -> capture dropped items + // We cache the pull inventory + if (this.cachedPullInventory == null && MinecraftServer.currentTick % 5 == 0) { + this.cachedPullInventory = HopperHelper.getInventoryForPullingOptimizedPath(this.getWorld(), this.getPosition().up(), this); + } + + if (this.cachedPullInventory != null) { + EnumDirection enumdirection = EnumDirection.DOWN; + + // Beanes + // Before vanilla would: + // 1. Check if inventory is empty by looping over all slots + // 2. If not empty, loop over all slots again that are not empty and try pull it.... + // isInventoryEmptyOptimized only checks the fast empty state "isEmpty" (todo: also add chest empty support) + + if (isInventoryEmptyOptimized(this.cachedPullInventory)) { + ModernHopperOptimizations.skipPushModeEventFire = ModernHopperOptimizations.skipHopperEvents; + + if (this.cachedPullInventory instanceof IWorldInventory) { + for (int slot : ((IWorldInventory) this.cachedPullInventory).getSlotsForDownFace()) { + ItemStack itemstack = this.cachedPullInventory.getItem(slot); + + if (itemstack != null && b(this.cachedPullInventory, itemstack, slot, enumdirection)) { + transferred |= ModernHopperOptimizations.hopperPull(this, this.cachedPullInventory, itemstack, slot); // Beanes - Paper 1.12.2 patch + } + } + } else { + int j = this.cachedPullInventory.getSize(); + + for (int slot = 0; slot < j; ++slot) { + ItemStack itemstack = this.cachedPullInventory.getItem(slot); + + if (itemstack != null && b(this.cachedPullInventory, itemstack, slot, enumdirection)) { + transferred |= ModernHopperOptimizations.hopperPull(this, this.cachedPullInventory, itemstack, slot); // Beanes - Paper 1.12.2 patch + } + } + } + } + } + } + + if (transferred) { + this.d(world.spigotConfig.hopperTransfer); // Spigot - put on cooldown + this.update(); // Block update near + } + } + + public void vanillaUpdate() { + boolean transferred = false; + + if (!this.p()) { // If not empty -> transfer items out + transferred = this.r(); + } + + if (!this.q()) { // If not full -> capture dropped items + transferred |= a(this); + } + + if (transferred) { + this.d(world.spigotConfig.hopperTransfer); // Spigot - put on cooldown + this.update(); // Block update near + } + } + + public boolean m() { + if (this.world != null) { + if (BlockHopper.f(this.u())) { + boolean flag = false; + + if (!this.p()) { + flag = this.r(); + } + + if (!this.q()) { + flag = TileEntityHopper.a(this) || flag; + } + + if (flag) { + this.d(world.spigotConfig.hopperTransfer); // Spigot + this.update(); + return true; + } + } + + } + return false; + } + + private boolean p() { + for (ItemStack itemstack : items) { + if (itemstack != null) { + return false; + } + } + + return true; + } + + public boolean canAcceptItems() { + return !this.n() && !this.q() && BlockHopper.f(this.u()); + } + + private boolean q() { + for (ItemStack itemstack : items) { + if (itemstack == null || itemstack.count != itemstack.getMaxStackSize()) { + return false; + } + } + + return true; + } + + private boolean r() { + // TacoSpigot start - Don't use inefficient H() which does another bounding box + // search + + boolean optimizeHoppers = AzuriteConfig.optimizeHoppers.getValue(); + + EnumDirection enumdirection = BlockHopper.b(this.u()); + + // Beanes - optimized hoppers (only fetch when optimized hoppers are turned off or cached push inventory is null) + if (cachedPushInventory == null || !optimizeHoppers) { + cachedPushInventory = HopperHelper.getInventoryForPushing(getWorld(), getPosition().shift(enumdirection), this); + } + // TacoSpigot end + + if (cachedPushInventory != null) { + EnumDirection enumdirection1 = enumdirection.opposite(); + + if (!this.a(cachedPushInventory, enumdirection1)) { + for (int i = 0; i < getSize(); ++i) { + ItemStack item = getItem(i); + if (item != null) { + ItemStack itemstack = item.cloneItemStack(); + + // CraftBukkit start - Call event when pushing items into other inventories + CraftItemStack oitemstack = CraftItemStack.asCraftMirror(this.splitStack(i, world.spigotConfig.hopperAmount)); // Spigot + // TacoSpigot start - add an option to turn of InventoryMoveItemEvent + final org.bukkit.inventory.ItemStack stack; + if (HopperHelper.isFireInventoryMoveItemEvent(this)) { + // TacoSpigot end + + Inventory destinationInventory; + // Have to special case large chests as they work oddly + if (cachedPushInventory instanceof InventoryLargeChest) { + destinationInventory = new org.bukkit.craftbukkit.inventory.CraftInventoryDoubleChest( + (InventoryLargeChest) cachedPushInventory); + } else { + destinationInventory = cachedPushInventory.getOwner().getInventory(); + } + + InventoryMoveItemEvent event = new InventoryMoveItemEvent(this.getOwner().getInventory(), + oitemstack.clone(), destinationInventory, true); + this.getWorld().getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { + this.setItem(i, itemstack); + this.d(world.spigotConfig.hopperTransfer); // Spigot + return false; + } + // TacoSpigot start + stack = event.getItem(); + // handle cases where the event is not fired + } else { + stack = oitemstack; + } + int origCount = stack.getAmount(); // Spigot + ItemStack itemstack1 = addItem(cachedPushInventory, CraftItemStack.asNMSCopy(stack), enumdirection1); + // TacoSpigot end + + if (itemstack1 == null || itemstack1.count == 0) { + if (stack.equals(oitemstack)) { // TacoSpigot - event.getItem() -> stack + cachedPushInventory.update(); + } else { + this.setItem(i, itemstack); + } + // CraftBukkit end + return true; + } + itemstack.count -= origCount - itemstack1.count; // Spigot + this.setItem(i, itemstack); + } + } + } + } + return false; + } + + private static boolean isInventoryFullOptimized(IInventory iinventory, EnumDirection enumdirection) { + // Beanes - fast path for hoppers + if (iinventory instanceof TileEntityHopper) { + return ((TileEntityHopper) iinventory).isFull; + } + + if (iinventory instanceof IWorldInventory) { + IWorldInventory iworldinventory = (IWorldInventory) iinventory; + + for (int j : iworldinventory.getSlotsForFace(enumdirection)) { + ItemStack itemstack = iworldinventory.getItem(j); + + if (itemstack == null || itemstack.count != itemstack.getMaxStackSize()) { + return false; + } + } + } else { + int j = iinventory.getSize(); + + for (int k = 0; k < j; ++k) { + ItemStack itemstack1 = iinventory.getItem(k); + + if (itemstack1 == null || itemstack1.count != itemstack1.getMaxStackSize()) { + return false; + } + } + } + + return true; + } + + private boolean a(IInventory iinventory, EnumDirection enumdirection) { + if (iinventory instanceof IWorldInventory) { + IWorldInventory iworldinventory = (IWorldInventory) iinventory; + + for (int j : iworldinventory.getSlotsForFace(enumdirection)) { + ItemStack itemstack = iworldinventory.getItem(j); + + if (itemstack == null || itemstack.count != itemstack.getMaxStackSize()) { + return false; + } + } + } else { + int j = iinventory.getSize(); + + for (int k = 0; k < j; ++k) { + ItemStack itemstack1 = iinventory.getItem(k); + + if (itemstack1 == null || itemstack1.count != itemstack1.getMaxStackSize()) { + return false; + } + } + } + + return true; + } + + public double A() { + return this.position.getX() + 0.5D; + } + + public double B() { + return this.position.getY() + 0.5D; + } + + public double C() { + return this.position.getZ() + 0.5D; + } + + public void d(int i) { + this.g = i; + } + + public boolean n() { + return this.g > 0; + } + + public boolean o() { + return this.g <= 1; + } + + public String getContainerName() { + return "minecraft:hopper"; + } + + public Container createContainer(PlayerInventory playerinventory, EntityHuman entityhuman) { + return new ContainerHopper(playerinventory, this, entityhuman); + } + + public int getProperty(int i) { + return 0; + } + + public void b(int i, int j) { + } + + public int g() { + return 0; + } + + public void l() { + Arrays.fill(this.items, null); + recalculateEmptyAndFull(); + } + + // Beanes - optimized hoppers + public void recalculateEmptyAndFull() { + boolean hasItems = false; + boolean allFull = true; + + { + ItemStack itemstack = items[0]; + boolean isNotEmpty = itemstack != null; + hasItems |= isNotEmpty; + allFull &= isNotEmpty && itemstack.count == itemstack.getMaxStackSize(); + } + { + ItemStack itemstack = items[1]; + boolean isNotEmpty = itemstack != null; + hasItems |= isNotEmpty; + allFull &= isNotEmpty && itemstack.count == itemstack.getMaxStackSize(); + } + { + ItemStack itemstack = items[2]; + boolean isNotEmpty = itemstack != null; + hasItems |= isNotEmpty; + allFull &= isNotEmpty && itemstack.count == itemstack.getMaxStackSize(); + } + { + ItemStack itemstack = items[3]; + boolean isNotEmpty = itemstack != null; + hasItems |= isNotEmpty; + allFull &= isNotEmpty && itemstack.count == itemstack.getMaxStackSize(); + } + { + ItemStack itemstack = items[4]; + boolean isNotEmpty = itemstack != null; + hasItems |= isNotEmpty; + allFull &= isNotEmpty && itemstack.count == itemstack.getMaxStackSize(); + } + + isEmpty = !hasItems; + isFull = allFull; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/TileEntityLightDetector.java b/azurite-server/src/main/java/net/minecraft/server/TileEntityLightDetector.java new file mode 100644 index 0000000..b1445be --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/TileEntityLightDetector.java @@ -0,0 +1,16 @@ +package net.minecraft.server; + +public class TileEntityLightDetector extends TileEntity implements IUpdatePlayerListBox { + + public TileEntityLightDetector() {} + + public void c() { + if (this.world != null && this.world.getTime() % 20L == 0L) { + this.e = this.w(); + if (this.e instanceof BlockDaylightDetector) { + ((BlockDaylightDetector) this.e).f(this.world, this.position); + } + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/TileEntityMobSpawner.java b/azurite-server/src/main/java/net/minecraft/server/TileEntityMobSpawner.java new file mode 100644 index 0000000..0292277 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/TileEntityMobSpawner.java @@ -0,0 +1,61 @@ +package net.minecraft.server; + +public class TileEntityMobSpawner extends TileEntity implements IUpdatePlayerListBox { + + public final MobSpawnerAbstract a = new MobSpawnerAbstract() { + public void a(int i) { + TileEntityMobSpawner.this.world.playBlockAction(TileEntityMobSpawner.this.position, Blocks.MOB_SPAWNER, i, 0); + } + + public World a() { + return TileEntityMobSpawner.this.world; + } + + public BlockPosition b() { + return TileEntityMobSpawner.this.position; + } + + public void a(MobSpawnerAbstract.a mobspawnerabstract_a) { + super.a(mobspawnerabstract_a); + if (this.a() != null) { + this.a().notify(TileEntityMobSpawner.this.position); + } + } + }; + + public TileEntityMobSpawner() { + } + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + a.a(nbttagcompound); + } + + public void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + a.b(nbttagcompound); + } + + public void c() { + this.a.c(); + } + + public Packet getUpdatePacket() { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + b(nbttagcompound); + nbttagcompound.remove("SpawnPotentials"); + return new PacketPlayOutTileEntityData(position, 1, nbttagcompound); + } + + public boolean c(int i, int j) { + return this.a.b(i) || super.c(i, j); + } + + public boolean F() { + return true; + } + + public MobSpawnerAbstract getSpawner() { + return this.a; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/TileEntityNote.java b/azurite-server/src/main/java/net/minecraft/server/TileEntityNote.java new file mode 100644 index 0000000..a8bd6d9 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/TileEntityNote.java @@ -0,0 +1,49 @@ +package net.minecraft.server; + +public class TileEntityNote extends TileEntity { + + public byte note; + public boolean f; + + public TileEntityNote() {} + + public void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + nbttagcompound.setByte("note", this.note); + } + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + this.note = nbttagcompound.getByte("note"); + this.note = (byte) MathHelper.clamp(this.note, 0, 24); + } + + public void b() { + this.note = (byte) ((this.note + 1) % 25); + this.update(); + } + + public void play(World world, BlockPosition blockposition) { + if (world.getType(blockposition.getX(), blockposition.getY() + 1, blockposition.getZ()).getBlock().getMaterial() == Material.AIR) { + Material material = world.getType(blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()).getBlock().getMaterial(); + byte b0 = 0; + + if (material == Material.STONE) { + b0 = 1; + } else if (material == Material.SAND) { + b0 = 2; + } else if (material == Material.SHATTERABLE) { + b0 = 3; + } else if (material == Material.WOOD) { + b0 = 4; + } + + // CraftBukkit start + org.bukkit.event.block.NotePlayEvent event = org.bukkit.craftbukkit.event.CraftEventFactory.callNotePlayEvent(this.world, blockposition.getX(), blockposition.getY(), blockposition.getZ(), b0, this.note); + if (!event.isCancelled()) { + world.playBlockAction(blockposition, Blocks.NOTEBLOCK, event.getInstrument().getType(), event.getNote().getId()); + } + // CraftBukkit end + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/TileEntityPiston.java b/azurite-server/src/main/java/net/minecraft/server/TileEntityPiston.java new file mode 100644 index 0000000..efca179 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/TileEntityPiston.java @@ -0,0 +1,162 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.AzuriteConfig; + +import java.util.List; + +public class TileEntityPiston extends TileEntity implements IUpdatePlayerListBox { + + private IBlockData a; + private EnumDirection f; + private boolean g; + private float i; + private float j; + + public TileEntityPiston() { + } + + public TileEntityPiston(IBlockData iblockdata, EnumDirection enumdirection, boolean flag, boolean flag1) { + this.a = iblockdata; + this.f = enumdirection; + this.g = flag; + } + + public IBlockData b() { + return this.a; + } + + public int u() { + return 0; + } + + public boolean d() { + return this.g; + } + + public EnumDirection e() { + return this.f; + } + + public float a(float f) { + if (f > 1.0F) { + f = 1.0F; + } + + return this.j + (this.i - this.j) * f; + } + + private void a(float f, float f1) { + if (this.g) { + f = 1.0F - f; + } else { + --f; + } + + AxisAlignedBB axisalignedbb = Blocks.PISTON_EXTENSION.a(this.world, this.position, this.a, f, this.f); + + if (axisalignedbb != null) { + List list = this.world.getEntities(null, axisalignedbb); + + if (!list.isEmpty()) { + boolean slime = a.getBlock() == Blocks.SLIME; + for (Entity entity : list) { + if (slime && this.g) { + switch (SyntheticClass_1.a[this.f.k().ordinal()]) { + case 1: + entity.motX = this.f.getAdjacentX(); + break; + + case 2: + entity.motY = this.f.getAdjacentY(); + break; + + case 3: + entity.motZ = this.f.getAdjacentZ(); + } + } else { + entity.move(f1 * (float) this.f.getAdjacentX(), f1 * (float) this.f.getAdjacentY(), f1 * (float) this.f.getAdjacentZ()); + } + } + } + } + + } + + public void h() { + if (this.j < 1.0F && this.world != null) { + this.j = this.i = 1.0F; + this.world.t(this.position); + this.y(); + if (this.world.getType(this.position).getBlock() == Blocks.PISTON_EXTENSION) { + this.world.setTypeAndData(this.position, this.a, 3); + this.world.d(this.position, this.a.getBlock()); + } + } + + } + + public void c() { + if (this.world == null) return; // CraftBukkit + this.j = this.i; + if (this.j >= 1.0F) { + if (AzuriteConfig.pistonPushEntities.getValue()) + this.a(1.0F, 0.25F); + this.world.t(this.position); + this.y(); + if (this.world.getType(this.position).getBlock() == Blocks.PISTON_EXTENSION) { + this.world.setTypeAndData(this.position, this.a, 3); + this.world.d(this.position, this.a.getBlock()); + } + + } else { + this.i += 0.5F; + if (this.i >= 1.0F) { + this.i = 1.0F; + } + + if (this.g && AzuriteConfig.pistonPushEntities.getValue()) { + this.a(this.i, this.i - this.j + 0.0625F); + } + } + } + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + this.a = Block.getById(nbttagcompound.getInt("blockId")).fromLegacyData(nbttagcompound.getInt("blockData")); + this.f = EnumDirection.fromType1(nbttagcompound.getInt("facing")); + this.j = this.i = nbttagcompound.getFloat("progress"); + this.g = nbttagcompound.getBoolean("extending"); + } + + public void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + nbttagcompound.setInt("blockId", Block.getId(this.a.getBlock())); + nbttagcompound.setInt("blockData", this.a.getBlock().toLegacyData(this.a)); + nbttagcompound.setInt("facing", this.f.a()); + nbttagcompound.setFloat("progress", this.j); + nbttagcompound.setBoolean("extending", this.g); + } + + static class SyntheticClass_1 { + + static final int[] a = new int[EnumDirection.EnumAxis.values().length]; + + static { + try { + TileEntityPiston.SyntheticClass_1.a[EnumDirection.EnumAxis.X.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + } + + try { + TileEntityPiston.SyntheticClass_1.a[EnumDirection.EnumAxis.Y.ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + } + + try { + TileEntityPiston.SyntheticClass_1.a[EnumDirection.EnumAxis.Z.ordinal()] = 3; + } catch (NoSuchFieldError ignored) { + } + + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/TileEntitySign.java b/azurite-server/src/main/java/net/minecraft/server/TileEntitySign.java new file mode 100644 index 0000000..a58d5a9 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/TileEntitySign.java @@ -0,0 +1,156 @@ +package net.minecraft.server; + +import com.google.gson.JsonParseException; + +public class TileEntitySign extends TileEntity { + + public final IChatBaseComponent[] lines = new IChatBaseComponent[]{new ChatComponentText(""), new ChatComponentText(""), new ChatComponentText(""), new ChatComponentText("")}; + public int f = -1; + public boolean isEditable = true; + private EntityHuman h; + private final CommandObjectiveExecutor i = new CommandObjectiveExecutor(); + public static final int MAX_SIGN_LINE_LENGTH = Integer.getInteger("Panda.maxSignLength", 80); // PandaSpigot + + public TileEntitySign() { + } + + public void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + + for (int i = 0; i < 4; ++i) { + String s = IChatBaseComponent.ChatSerializer.a(this.lines[i]); + + nbttagcompound.setString("Text" + (i + 1), s); + } + + // CraftBukkit start + if (Boolean.getBoolean("convertLegacySigns")) { + nbttagcompound.setBoolean("Bukkit.isConverted", true); + } + // CraftBukkit end + + this.i.b(nbttagcompound); + } + + public void a(NBTTagCompound nbttagcompound) { + this.isEditable = false; + super.a(nbttagcompound); + ICommandListener icommandlistener = new ICommandListener() { + public String getName() { + return "Sign"; + } + + public IChatBaseComponent getScoreboardDisplayName() { + return new ChatComponentText(this.getName()); + } + + public void sendMessage(IChatBaseComponent ichatbasecomponent) { + } + + public boolean a(int i, String s) { + return true; + } + + public BlockPosition getChunkCoordinates() { + return TileEntitySign.this.position; + } + + public Vec3D d() { + return new Vec3D((double) TileEntitySign.this.position.getX() + 0.5D, (double) TileEntitySign.this.position.getY() + 0.5D, (double) TileEntitySign.this.position.getZ() + 0.5D); + } + + public World getWorld() { + return TileEntitySign.this.world; + } + + public Entity f() { + return null; + } + + public boolean getSendCommandFeedback() { + return false; + } + + public void a(CommandObjectiveExecutor.EnumCommandResult commandobjectiveexecutor_enumcommandresult, int i) { + } + }; + + // CraftBukkit start - Add an option to convert signs correctly + // This is done with a flag instead of all the time because + // we have no way to tell whether a sign is from 1.7.10 or 1.8 + + boolean oldSign = Boolean.getBoolean("convertLegacySigns") && !nbttagcompound.getBoolean("Bukkit.isConverted"); + + for (int i = 0; i < 4; ++i) { + String s = nbttagcompound.getString("Text" + (i + 1)); + if (s != null && s.length() > 2048) { + s = "\"\""; + } + + try { + IChatBaseComponent ichatbasecomponent = IChatBaseComponent.ChatSerializer.a(s); + + if (oldSign) { + lines[i] = org.bukkit.craftbukkit.util.CraftChatMessage.fromString(s)[0]; + continue; + } + // CraftBukkit end + + try { + this.lines[i] = ChatComponentUtils.filterForDisplay(icommandlistener, ichatbasecomponent, null); + } catch (CommandException commandexception) { + this.lines[i] = ichatbasecomponent; + } + } catch (JsonParseException jsonparseexception) { + this.lines[i] = new ChatComponentText(s); + } + } + + this.i.a(nbttagcompound); + } + + public Packet getUpdatePacket() { + IChatBaseComponent[] aichatbasecomponent = new IChatBaseComponent[4]; + System.arraycopy(this.lines, 0, aichatbasecomponent, 0, 4); + return new PacketPlayOutUpdateSign(this.world, this.position, aichatbasecomponent); + } + + public boolean F() { + return true; + } + + public boolean b() { + return this.isEditable; + } + + public void a(EntityHuman entityhuman) { + this.h = entityhuman; + } + + public EntityHuman c() { + return this.h; + } + + public boolean b(final EntityHuman entityhuman) { + for (IChatBaseComponent line : this.lines) { + ChatModifier chatmodifier = line == null ? null : line.getChatModifier(); + + if (chatmodifier != null && chatmodifier.h() != null) { + ChatClickable chatclickable = chatmodifier.h(); + + if (chatclickable.a() == ChatClickable.EnumClickAction.RUN_COMMAND) { + // CraftBukkit start + // MinecraftServer.getServer().getCommandHandler().a(tileentitysignplayerwrapper, chatclickable.b()); + CommandBlockListenerAbstract.executeCommand(entityhuman, entityhuman.getBukkitEntity(), chatclickable.b()); + // CraftBukkit end + } + } + } + + return true; + } + + public CommandObjectiveExecutor d() { + return this.i; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/TileEntitySkull.java b/azurite-server/src/main/java/net/minecraft/server/TileEntitySkull.java new file mode 100644 index 0000000..3619a78 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/TileEntitySkull.java @@ -0,0 +1,183 @@ +package net.minecraft.server; + +import com.google.common.base.Predicate; +import com.google.common.cache.CacheBuilder; +import com.google.common.cache.CacheLoader; +import com.google.common.cache.LoadingCache; +import com.google.common.collect.Iterables; +import com.mojang.authlib.Agent; +import com.mojang.authlib.GameProfile; +import com.mojang.authlib.ProfileLookupCallback; +import com.mojang.authlib.properties.Property; +import dev.azurite.spigot.Azurite; +import org.apache.commons.lang3.StringUtils; + +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +public class TileEntitySkull extends TileEntity { + + private int a; + private int rotation; + private GameProfile g = null; + // Spigot start + + public static final LoadingCache skinCache = CacheBuilder.newBuilder() + .maximumSize( 5000 ) + .expireAfterAccess( 60, TimeUnit.MINUTES ) + .build( new CacheLoader() + { + @Override + public GameProfile load(String key) throws Exception + { + final GameProfile[] profiles = new GameProfile[1]; + ProfileLookupCallback gameProfileLookup = new ProfileLookupCallback() { + + @Override + public void onProfileLookupSucceeded(GameProfile gp) { + profiles[0] = gp; + } + + @Override + public void onProfileLookupFailed(GameProfile gp, Exception excptn) { + profiles[0] = gp; + } + }; + + MinecraftServer.getServer().getGameProfileRepository().findProfilesByNames(new String[]{key}, Agent.MINECRAFT, gameProfileLookup); + + GameProfile profile = profiles[0]; + if (profile == null) { + UUID uuid = EntityHuman.a(new GameProfile(null, key)); + profile = new GameProfile(uuid, key); + + gameProfileLookup.onProfileLookupSucceeded(profile); + } else { + Property property = Iterables.getFirst(profile.getProperties().get("textures"), null); + + if (property == null) { + profile = MinecraftServer.getServer().aD().fillProfileProperties(profile, true); + } + } + + return profile; + } + }); + // Spigot end + + public TileEntitySkull() { + } + + public void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + nbttagcompound.setByte("SkullType", (byte) (this.a & 255)); + nbttagcompound.setByte("Rot", (byte) (this.rotation & 255)); + if (this.g != null) { + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + + GameProfileSerializer.serialize(nbttagcompound1, this.g); + nbttagcompound.set("Owner", nbttagcompound1); + } + + } + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + this.a = nbttagcompound.getByte("SkullType"); + this.rotation = nbttagcompound.getByte("Rot"); + if (this.a == 3) { + if (nbttagcompound.hasKeyOfType("Owner", 10)) { + this.g = GameProfileSerializer.deserialize(nbttagcompound.getCompound("Owner")); + } else if (nbttagcompound.hasKeyOfType("ExtraType", 8)) { + String s = nbttagcompound.getString("ExtraType"); + + if (!StringUtils.isEmpty(s)) { + this.g = new GameProfile(null, s); + this.e(); + } + } + } + + } + + public GameProfile getGameProfile() { + return this.g; + } + + public Packet getUpdatePacket() { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + this.b(nbttagcompound); + return new PacketPlayOutTileEntityData(this.position, 4, nbttagcompound); + } + + public void setSkullType(int i) { + this.a = i; + this.g = null; + } + + public void setGameProfile(GameProfile gameprofile) { + this.a = 3; + this.g = gameprofile; + this.e(); + } + + private void e() { + // Spigot start + GameProfile profile = this.g; + setSkullType(0); // Work around client bug + b(profile, input -> { + setSkullType(3); // Work around client bug + g = input; + update(); + if (world != null) { + world.notify(position); + } + return false; + }); + // Spigot end + } + + // Spigot start - Support async lookups + public static void b(final GameProfile gameprofile, final Predicate callback) { + if (gameprofile != null && !StringUtils.isEmpty(gameprofile.getName())) { + if (gameprofile.isComplete() && gameprofile.getProperties().containsKey("textures")) { + callback.apply(gameprofile); + } else if (MinecraftServer.getServer() == null) { + callback.apply(gameprofile); + } else { + GameProfile profile = skinCache.getIfPresent(gameprofile.getName().toLowerCase()); // PandaSpigot - Fix SPIGOT-3348: Skin Cache Bug + if (profile != null && Iterables.getFirst(profile.getProperties().get("textures"), null) != null) { + callback.apply(profile); + } else { + Azurite.getInstance().getThreadingManager().getAsyncExecutor().queueHeadLoading(() -> { + final GameProfile profile1 = skinCache.getIfPresent(gameprofile.getName().toLowerCase(java.util.Locale.ROOT)); + MinecraftServer.getServer().processQueue.add(() -> { + if (profile1 == null) { + callback.apply(gameprofile); + } else { + callback.apply(profile1); + } + }); + }); + } + } + } else { + callback.apply(gameprofile); + } + } + // Spigot end + + public int getSkullType() { + return this.a; + } + + public void setRotation(int i) { + this.rotation = i; + } + + // CraftBukkit start - add method + public int getRotation() { + return this.rotation; + } + // CraftBukkit end +} diff --git a/azurite-server/src/main/java/net/minecraft/server/Tuple.java b/azurite-server/src/main/java/net/minecraft/server/Tuple.java new file mode 100644 index 0000000..29df471 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/Tuple.java @@ -0,0 +1,20 @@ +package net.minecraft.server; + +public class Tuple { + + private A a; + private B b; + + public Tuple(A a0, B b0) { + this.a = a0; + this.b = b0; + } + + public A a() { + return this.a; + } + + public B b() { + return this.b; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/UserCache.java b/azurite-server/src/main/java/net/minecraft/server/UserCache.java new file mode 100644 index 0000000..bc2c599 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/UserCache.java @@ -0,0 +1,324 @@ +package net.minecraft.server; + +import com.eatthepath.uuid.FastUUID; +import com.google.common.base.Charsets; +import com.google.common.collect.Iterators; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import com.google.common.io.Files; +import com.google.gson.*; +import com.mojang.authlib.Agent; +import com.mojang.authlib.GameProfile; +import com.mojang.authlib.ProfileLookupCallback; +import dev.azurite.spigot.Azurite; +import dev.azurite.spigot.async.tasks.UserCacheSaveJob; +import dev.azurite.spigot.configs.AzuriteConfig; +import org.apache.commons.io.IOUtils; + +import java.io.*; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.*; + +public class UserCache { + + public static final SimpleDateFormat a = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z"); + private final Map c = Maps.newHashMap(); + private final Map d = Maps.newHashMap(); + private final java.util.Deque e = new java.util.concurrent.LinkedBlockingDeque<>(); // CraftBukkit + private final MinecraftServer f; + protected final Gson b; + private final File g; + private static final ParameterizedType h = new ParameterizedType() { + public Type[] getActualTypeArguments() { + return new Type[]{UserCacheEntry.class}; + } + + public Type getRawType() { + return List.class; + } + + public Type getOwnerType() { + return null; + } + }; + + public UserCache(MinecraftServer minecraftserver, File file) { + this.f = minecraftserver; + this.g = file; + GsonBuilder gsonbuilder = new GsonBuilder(); + + gsonbuilder.registerTypeHierarchyAdapter(UserCacheEntry.class, new BanEntrySerializer(null)); + this.b = gsonbuilder.create(); + this.b(); + } + + private static GameProfile a(MinecraftServer minecraftserver, String s) { + final GameProfile[] agameprofile = new GameProfile[1]; + ProfileLookupCallback profilelookupcallback = new ProfileLookupCallback() { + public void onProfileLookupSucceeded(GameProfile gameprofile) { + agameprofile[0] = gameprofile; + } + + public void onProfileLookupFailed(GameProfile gameprofile, Exception exception) { + agameprofile[0] = null; + } + }; + + minecraftserver.getGameProfileRepository().findProfilesByNames(new String[]{s}, Agent.MINECRAFT, profilelookupcallback); + if (!minecraftserver.getOnlineMode() && agameprofile[0] == null) { + profilelookupcallback.onProfileLookupSucceeded(new GameProfile(EntityHuman.a(new GameProfile(null, s)), s)); + } + + return agameprofile[0]; + } + + public void a(GameProfile gameprofile) { + this.a(gameprofile, null, true); + } + + private void a(GameProfile gameprofile, Date date) { + this.a(gameprofile, date, false); + } + + private void a(GameProfile gameprofile, Date date, boolean save) { + UUID uuid = gameprofile.getId(); + + if (date == null) { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(new Date()); + calendar.add(Calendar.MONTH, 1); + date = calendar.getTime(); + } + + UserCacheEntry usercache_usercacheentry = new UserCacheEntry(gameprofile, date, null); + UserCacheEntry usercache_usercacheentry1 = d.get(uuid); // Azurite - only get once + + if (usercache_usercacheentry1 != null) { + this.c.remove(usercache_usercacheentry1.a().getName().toLowerCase(Locale.ROOT)); + this.e.remove(gameprofile); + } + + this.c.put(gameprofile.getName().toLowerCase(Locale.ROOT), usercache_usercacheentry); + this.d.put(uuid, usercache_usercacheentry); + this.e.addFirst(gameprofile); + if (!org.spigotmc.SpigotConfig.saveUserCacheOnStopOnly && save) + saveUserCache(AzuriteConfig.asyncUserCacheSave.getValue()); // Spigot - skip saving if disabled + } + + public GameProfile getProfile(String s) { + String s1 = s.toLowerCase(Locale.ROOT); + UserCacheEntry usercache_usercacheentry = this.c.get(s1); + + if (usercache_usercacheentry != null && (new Date()).getTime() >= usercache_usercacheentry.c.getTime()) { + this.d.remove(usercache_usercacheentry.a().getId()); + this.c.remove(usercache_usercacheentry.a().getName().toLowerCase(Locale.ROOT)); + this.e.remove(usercache_usercacheentry.a()); + usercache_usercacheentry = null; + } + + GameProfile gameprofile; + + if (usercache_usercacheentry != null) { + gameprofile = usercache_usercacheentry.a(); + this.e.remove(gameprofile); + this.e.addFirst(gameprofile); + } else { + gameprofile = a(this.f, s); // Spigot - use correct case for offline players + if (gameprofile != null) { + this.a(gameprofile); + usercache_usercacheentry = this.c.get(s1); + } + } + + if (!org.spigotmc.SpigotConfig.saveUserCacheOnStopOnly) saveUserCache(AzuriteConfig.asyncUserCacheSave.getValue()); // Spigot - skip saving if disabled + return usercache_usercacheentry == null ? null : usercache_usercacheentry.a(); + } + + public String[] a() { + ArrayList arraylist = Lists.newArrayList(this.c.keySet()); + return arraylist.toArray(new String[0]); + } + + public GameProfile a(UUID uuid) { + UserCacheEntry usercache_usercacheentry = this.d.get(uuid); + return usercache_usercacheentry == null ? null : usercache_usercacheentry.a(); + } + + private UserCacheEntry b(UUID uuid) { + UserCacheEntry usercache_usercacheentry = this.d.get(uuid); + + if (usercache_usercacheentry != null) { + GameProfile gameprofile = usercache_usercacheentry.a(); + + this.e.remove(gameprofile); + this.e.addFirst(gameprofile); + } + + return usercache_usercacheentry; + } + + public void b() { + BufferedReader bufferedreader = null; + + try { + bufferedreader = Files.newReader(this.g, Charsets.UTF_8); + List list = this.b.fromJson(bufferedreader, UserCache.h); + + this.c.clear(); + this.d.clear(); + this.e.clear(); + + for (UserCacheEntry usercache_usercacheentry : Lists.reverse(list)) { + if (usercache_usercacheentry != null) { + this.a(usercache_usercacheentry.a(), usercache_usercacheentry.b(), false); // Azurite - we save after changing all the user cache entries are processed at start + } + } + } catch (FileNotFoundException filenotfoundexception) { + // Spigot Start + } catch (com.google.gson.JsonSyntaxException | NullPointerException ex) { // PandaSpigot - Add additional catch to handle NPE on usercache loading + JsonList.a.warn("Usercache.json is corrupted or has bad formatting. Deleting it to prevent further issues."); + this.g.delete(); + // Spigot End + } catch (JsonParseException ignored) { + } finally { + IOUtils.closeQuietly(bufferedreader); + } + } + + public void c() { + this.saveUserCache(false); + } + + // Azurite - async user cache save + public void saveUserCache(boolean async) { + List entries = this.a(org.spigotmc.SpigotConfig.userCacheCap); + if (async) { + Azurite.getInstance().getThreadingManager().getAsyncExecutor().queueFileTask(new UserCacheSaveJob(entries)); + } else { + this.saveEntries(entries); + } + } + + public void saveEntries(List entries) { + String s = this.b.toJson(entries); + BufferedWriter bufferedwriter = null; + + try { + bufferedwriter = Files.newWriter(this.g, Charsets.UTF_8); + bufferedwriter.write(s); + } catch (IOException ignored) { + } finally { + IOUtils.closeQuietly(bufferedwriter); + } + } + + private List a(int i) { + ArrayList arraylist = Lists.newArrayList(); + ArrayList arraylist1 = Lists.newArrayList(Iterators.limit(this.e.iterator(), i)); + + for (GameProfile gameProfile : arraylist1) { + UserCacheEntry usercache_usercacheentry = this.b(gameProfile.getId()); + + if (usercache_usercacheentry != null) { + arraylist.add(usercache_usercacheentry); + } + } + + return arraylist; + } + + public static class UserCacheEntry { + + private final GameProfile b; + private final Date c; + + private UserCacheEntry(GameProfile gameprofile, Date date) { + this.b = gameprofile; + this.c = date; + } + + public GameProfile a() { + return this.b; + } + + public Date b() { + return this.c; + } + + UserCacheEntry(GameProfile gameprofile, Date date, Object object) { + this(gameprofile, date); + } + } + + static class BanEntrySerializer implements JsonDeserializer, JsonSerializer { + + private BanEntrySerializer() { + } + + public JsonElement a(UserCacheEntry usercache_usercacheentry, Type type, JsonSerializationContext jsonserializationcontext) { + JsonObject jsonobject = new JsonObject(); + + jsonobject.addProperty("name", usercache_usercacheentry.a().getName()); + UUID uuid = usercache_usercacheentry.a().getId(); + + jsonobject.addProperty("uuid", uuid == null ? "" : FastUUID.toString(uuid)); + jsonobject.addProperty("expiresOn", UserCache.a.format(usercache_usercacheentry.b())); + return jsonobject; + } + + public UserCacheEntry a(JsonElement jsonelement, Type type, JsonDeserializationContext jsondeserializationcontext) throws JsonParseException { + if (jsonelement.isJsonObject()) { + JsonObject jsonobject = jsonelement.getAsJsonObject(); + JsonElement jsonelement1 = jsonobject.get("name"); + JsonElement jsonelement2 = jsonobject.get("uuid"); + JsonElement jsonelement3 = jsonobject.get("expiresOn"); + + if (jsonelement1 != null && jsonelement2 != null) { + String s = jsonelement2.getAsString(); + String s1 = jsonelement1.getAsString(); + Date date = null; + + if (jsonelement3 != null) { + try { + date = UserCache.a.parse(jsonelement3.getAsString()); + } catch (ParseException ignored) { + } + } + + if (s1 != null && s != null) { + UUID uuid; + + try { + uuid = FastUUID.parseUUID(s); + } catch (Throwable throwable) { + return null; + } + + return new UserCacheEntry(new GameProfile(uuid, s1), date, null); + } else { + return null; + } + } else { + return null; + } + } else { + return null; + } + } + + public JsonElement serialize(UserCacheEntry object, Type type, JsonSerializationContext jsonserializationcontext) { // CraftBukkit - decompile error + return this.a(object, type, jsonserializationcontext); + } + + public UserCacheEntry deserialize(JsonElement jsonelement, Type type, JsonDeserializationContext jsondeserializationcontext) throws JsonParseException { // CraftBukkit - decompile error + return this.a(jsonelement, type, jsondeserializationcontext); + } + + BanEntrySerializer(Object object) { + this(); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/UtilColor.java b/azurite-server/src/main/java/net/minecraft/server/UtilColor.java new file mode 100644 index 0000000..ed94451 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/UtilColor.java @@ -0,0 +1,13 @@ +package net.minecraft.server; + +import java.util.regex.Pattern; +import org.apache.commons.lang3.StringUtils; + +public class UtilColor { + + private static final Pattern a = Pattern.compile("(?i)\\u00A7[0-9A-FK-OR]"); + + public static boolean b(String s) { + return StringUtils.isEmpty(s); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/Vec3D.java b/azurite-server/src/main/java/net/minecraft/server/Vec3D.java new file mode 100644 index 0000000..92983fe --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/Vec3D.java @@ -0,0 +1,166 @@ +package net.minecraft.server; + +public class Vec3D { + + public double a; + public double b; + public double c; + + public Vec3D(double paramDouble1, double paramDouble2, double paramDouble3) { + if (paramDouble1 == -0.0D) + paramDouble1 = 0.0D; + if (paramDouble2 == -0.0D) + paramDouble2 = 0.0D; + if (paramDouble3 == -0.0D) + paramDouble3 = 0.0D; + this.a = paramDouble1; + this.b = paramDouble2; + this.c = paramDouble3; + } + + public Vec3D(BaseBlockPosition paramBaseBlockPosition) { + this(paramBaseBlockPosition.getX(), paramBaseBlockPosition.getY(), paramBaseBlockPosition.getZ()); + } + + public Vec3D a() { + double d = MathHelper.sqrt(this.a * this.a + this.b * this.b + this.c * this.c); + if (d < 1.0E-4D) + return new Vec3D(0.0D, 0.0D, 0.0D); + return new Vec3D(this.a / d, this.b / d, this.c / d); + } + + public double b(Vec3D paramVec3D) { + return this.a * paramVec3D.a + this.b * paramVec3D.b + this.c * paramVec3D.c; + } + + public Vec3D d(Vec3D paramVec3D) { + return a(paramVec3D.a, paramVec3D.b, paramVec3D.c); + } + + public Vec3D a(double paramDouble1, double paramDouble2, double paramDouble3) { + return add(-paramDouble1, -paramDouble2, -paramDouble3); + } + + public Vec3D e(Vec3D paramVec3D) { + return add(paramVec3D.a, paramVec3D.b, paramVec3D.c); + } + + public Vec3D add(double paramDouble1, double paramDouble2, double paramDouble3) { + return new Vec3D(this.a + paramDouble1, this.b + paramDouble2, this.c + paramDouble3); + } + + public double distanceSquared(Vec3D paramVec3D) { + double d1 = paramVec3D.a - this.a; + double d2 = paramVec3D.b - this.b; + double d3 = paramVec3D.c - this.c; + return d1 * d1 + d2 * d2 + d3 * d3; + } + + public double b() { + return MathHelper.sqrt(this.a * this.a + this.b * this.b + this.c * this.c); + } + + public Vec3D a(Vec3D paramVec3D, double paramDouble) { + double d1 = paramVec3D.a - this.a; + double d2 = paramVec3D.b - this.b; + double d3 = paramVec3D.c - this.c; + if (d1 * d1 < 1.0000000116860974E-7D) + return null; + double d4 = (paramDouble - this.a) / d1; + if (d4 < 0.0D || d4 > 1.0D) + return null; + return new Vec3D(this.a + d1 * d4, this.b + d2 * d4, this.c + d3 * d4); + } + + public Vec3D b(Vec3D paramVec3D, double paramDouble) { + double d1 = paramVec3D.a - this.a; + double d2 = paramVec3D.b - this.b; + double d3 = paramVec3D.c - this.c; + if (d2 * d2 < 1.0000000116860974E-7D) + return null; + double d4 = (paramDouble - this.b) / d2; + if (d4 < 0.0D || d4 > 1.0D) + return null; + return new Vec3D(this.a + d1 * d4, this.b + d2 * d4, this.c + d3 * d4); + } + + public Vec3D c(Vec3D paramVec3D, double paramDouble) { + double d1 = paramVec3D.a - this.a; + double d2 = paramVec3D.b - this.b; + double d3 = paramVec3D.c - this.c; + if (d3 * d3 < 1.0000000116860974E-7D) + return null; + double d4 = (paramDouble - this.c) / d3; + if (d4 < 0.0D || d4 > 1.0D) + return null; + return new Vec3D(this.a + d1 * d4, this.b + d2 * d4, this.c + d3 * d4); + } + + public String toString() { + return "(" + this.a + ", " + this.b + ", " + this.c + ")"; + } + + public Vec3D a(float paramFloat) { + float f1 = MathHelper.cos(paramFloat); + float f2 = MathHelper.sin(paramFloat); + double d2 = this.b * f1 + this.c * f2; + double d3 = this.c * f1 - this.b * f2; + return new Vec3D(a, d2, d3); + } + + public Vec3D b(float paramFloat) { + float f1 = MathHelper.cos(paramFloat); + float f2 = MathHelper.sin(paramFloat); + return new Vec3D(a * f1 + c * f2, b, c * f1 - a * f2); + } + + // Azurite start + public static final class MutableVec3D extends Vec3D { + + public MutableVec3D() { + super(0, 0, 0); + } + + public MutableVec3D(int i, int j, int k) { + super(0, 0, 0); + setX(i); + setY(j); + setZ(k); + } + + public void setX(double a) { + this.a = a; + } + + public void setY(double b) { + this.b = b; + } + + public void setZ(double c) { + this.c = c; + } + + public MutableVec3D add(double x, double y, double z) { + return c(a + x, b + y, c + z); + } + + public MutableVec3D a() { + double d = MathHelper.sqrt(this.a * this.a + this.b * this.b + this.c * this.c); + if (d < 1.0E-4D) c(0.0D, 0.0D, 0.0D); + c(this.a / d, this.b / d, this.c / d); + return this; + } + + public MutableVec3D setValues(double x, double y, double z) { + return c(x, y, z); + } + + public MutableVec3D c(double i, double j, double k) { + setX(i); + setY(j); + setZ(k); + return this; + } + } + // Azurite end +} diff --git a/azurite-server/src/main/java/net/minecraft/server/Vector3f.java b/azurite-server/src/main/java/net/minecraft/server/Vector3f.java new file mode 100644 index 0000000..cb6fb53 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/Vector3f.java @@ -0,0 +1,51 @@ +package net.minecraft.server; + +public class Vector3f { + + protected final float x; + protected final float y; + protected final float z; + + public Vector3f(float f, float f1, float f2) { + this.x = f; + this.y = f1; + this.z = f2; + } + + public Vector3f(NBTTagList nbttaglist) { + this.x = nbttaglist.e(0); + this.y = nbttaglist.e(1); + this.z = nbttaglist.e(2); + } + + public NBTTagList a() { + NBTTagList nbttaglist = new NBTTagList(); + + nbttaglist.add(new NBTTagFloat(this.x)); + nbttaglist.add(new NBTTagFloat(this.y)); + nbttaglist.add(new NBTTagFloat(this.z)); + return nbttaglist; + } + + public boolean equals(Object object) { + if (!(object instanceof Vector3f)) { + return false; + } else { + Vector3f vector3f = (Vector3f) object; + + return this.x == vector3f.x && this.y == vector3f.y && this.z == vector3f.z; + } + } + + public float getX() { + return this.x; + } + + public float getY() { + return this.y; + } + + public float getZ() { + return this.z; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/Village.java b/azurite-server/src/main/java/net/minecraft/server/Village.java new file mode 100644 index 0000000..98ac1f4 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/Village.java @@ -0,0 +1,483 @@ +package net.minecraft.server; + +import com.eatthepath.uuid.FastUUID; +import com.google.common.collect.Lists; +import com.mojang.authlib.GameProfile; + +import java.util.Iterator; +import java.util.List; +import java.util.TreeMap; + +public class Village { + + private final List b = Lists.newArrayList(); + private World a; + private BlockPosition c; + private BlockPosition d; + private int e; + private int f; + private int g; + private int h; + private int i; + private final TreeMap j; + private final List k; + private int l; + private BlockPosition[] positions = null; + + public Village() { + this.c = BlockPosition.ZERO; + this.d = BlockPosition.ZERO; + this.j = new TreeMap<>(); + this.k = Lists.newArrayList(); + } + + public Village(World world) { + this.c = BlockPosition.ZERO; + this.d = BlockPosition.ZERO; + this.j = new TreeMap<>(); + this.k = Lists.newArrayList(); + this.a = world; + } + + public void a(World world) { + this.a = world; + } + + private void calculateNewCheckPositions() { + if (this.d == null || this.d.equals(BlockPosition.ZERO)) { + this.positions = null; + } else { + this.positions = new BlockPosition[]{this.d.a(-this.e, 0, -this.e), + this.d.a(-this.e, 0, this.e), + this.d.a(this.e, 0, -this.e), + this.d.a(this.e, 0, this.e), + this.d}; + } + } + + public boolean isVillageAreaLoaded() { + for (int i = 0; this.positions != null && i < this.positions.length; i++) { + if (this.a.isLoaded(this.positions[i])) { + return true; + } + } + return false; + } + + public void a(int i) { + if (!this.isVillageAreaLoaded()) { + return; + } + this.g = i; + this.m(); + this.l(); + if (i % 20 == 0) { + this.k(); + } + + if (i % 30 == 0) { + this.j(); + } + + int j = this.h / 10; + + if (this.l < j && this.b.size() > 20 && this.a.random.nextInt(7000) == 0) { + Vec3D vec3d = this.a(this.d, 2, 4, 2); + + if (vec3d != null) { + EntityIronGolem entityirongolem = new EntityIronGolem(this.a); + + entityirongolem.setPosition(vec3d.a, vec3d.b, vec3d.c); + this.a.addEntity(entityirongolem, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.VILLAGE_DEFENSE); // CraftBukkit + ++this.l; + } + } + + } + + private Vec3D a(BlockPosition blockposition, int i, int j, int k) { + for (int l = 0; l < 10; ++l) { + int x = blockposition.getX() + a.random.nextInt(16) - 8, y = blockposition.getY() + a.random.nextInt(6) - 3, z = blockposition.getZ() + a.random.nextInt(16) - 8; + + if (this.a(x, y, z) && this.a(i, j, k, x, y, z)) { + return new Vec3D(x, y, z); + } + } + + return null; + } + + private boolean a(int x, int y, int z, int x1, int y1, int z1) { + if (!World.a(this.a, x1, y1 - 1, z1)) { + return false; + } else { + int i = x1 - x / 2; + int j = z1 - z / 2; + + for (int k = i; k < i + x; ++k) { + for (int l = y1; l < y1 + y; ++l) { + for (int i1 = j; i1 < j + z; ++i1) { + if (this.a.getType(k, l, i1).getBlock().isOccluding()) { + return false; + } + } + } + } + + return true; + } + } + + private void j() { + List list = this.a.a(EntityIronGolem.class, new AxisAlignedBB(this.d.getX() - this.e, this.d.getY() - 4, this.d.getZ() - this.e, this.d.getX() + this.e, this.d.getY() + 4, this.d.getZ() + this.e)); + this.l = list.size(); + } + + private void k() { + List list = this.a.a(EntityVillager.class, new AxisAlignedBB(this.d.getX() - this.e, this.d.getY() - 4, this.d.getZ() - this.e, this.d.getX() + this.e, this.d.getY() + 4, this.d.getZ() + this.e)); + this.h = list.size(); + if (this.h == 0) { + this.j.clear(); + } + } + + public BlockPosition a() { + return this.d; + } + + public int b() { + return this.e; + } + + public int c() { + return this.b.size(); + } + + public int d() { + return this.g - this.f; + } + + public int e() { + return this.h; + } + + public boolean a(BlockPosition blockposition) { + return this.d.i(blockposition) < (double) (this.e * this.e); + } + + public boolean a(int x, int y, int z) { + return this.d.i(x, y, z) < (double) (this.e * this.e); + } + + public List f() { + return this.b; + } + + public VillageDoor b(BlockPosition blockposition) { + VillageDoor villagedoor = null; + int i = Integer.MAX_VALUE; + + for (VillageDoor villagedoor1 : this.b) { + int j = villagedoor1.a(blockposition); + + if (j < i) { + villagedoor = villagedoor1; + i = j; + } + } + + return villagedoor; + } + + public VillageDoor c(BlockPosition blockposition) { + VillageDoor villagedoor = null; + int i = Integer.MAX_VALUE; + + for (VillageDoor villagedoor1 : this.b) { + int j = villagedoor1.a(blockposition); + + if (j > 256) { + j *= 1000; + } else { + j = villagedoor1.c(); + } + + if (j < i) { + villagedoor = villagedoor1; + i = j; + } + } + + return villagedoor; + } + + public VillageDoor e(BlockPosition blockposition) { + if (this.d.i(blockposition) > (double) (this.e * this.e)) { + return null; + } else { + Iterator iterator = this.b.iterator(); + + VillageDoor villagedoor; + + do { + if (!iterator.hasNext()) { + return null; + } + + villagedoor = iterator.next(); + } while (villagedoor.d().getX() != blockposition.getX() || villagedoor.d().getZ() != blockposition.getZ() || Math.abs(villagedoor.d().getY() - blockposition.getY()) > 1); + + return villagedoor; + } + } + + public void a(VillageDoor villagedoor) { + this.b.add(villagedoor); + this.c = this.c.a(villagedoor.d()); + this.n(); + this.f = villagedoor.h(); + } + + public boolean g() { + return this.b.isEmpty(); + } + + public void a(EntityLiving entityliving) { + Iterator iterator = this.k.iterator(); + + Aggressor village_aggressor; + + do { + if (!iterator.hasNext()) { + this.k.add(new Aggressor(entityliving, this.g)); + return; + } + + village_aggressor = iterator.next(); + } while (village_aggressor.a != entityliving); + + village_aggressor.b = this.g; + } + + public EntityLiving b(EntityLiving entityliving) { + double d0 = Double.MAX_VALUE; + Aggressor village_aggressor = null; + + for (Aggressor village_aggressor1 : this.k) { + double d1 = village_aggressor1.a.h(entityliving); + + if (d1 <= d0) { + village_aggressor = village_aggressor1; + d0 = d1; + } + } + + return village_aggressor != null ? village_aggressor.a : null; + } + + public EntityHuman c(EntityLiving entityliving) { + double d0 = Double.MAX_VALUE; + EntityHuman entityhuman = null; + + for (String s : this.j.keySet()) { + if (this.d(s)) { + EntityHuman entityhuman1 = this.a.a(s); + + if (entityhuman1 != null) { + double d1 = entityhuman1.h(entityliving); + + if (d1 <= d0) { + entityhuman = entityhuman1; + d0 = d1; + } + } + } + } + + return entityhuman; + } + + private void l() { + this.k.removeIf(village_aggressor -> !village_aggressor.a.isAlive() || Math.abs(this.g - village_aggressor.b) > 300); + } + + private void m() { + boolean flag = false; + boolean flag1 = this.a.random.nextInt(50) == 0; + Iterator iterator = this.b.iterator(); + + while (iterator.hasNext()) { + VillageDoor villagedoor = iterator.next(); + + if (flag1) { + villagedoor.a(); + } + + if (!this.f(villagedoor.d()) || Math.abs(this.g - villagedoor.h()) > 1200) { + this.c = this.c.b(villagedoor.d()); + flag = true; + villagedoor.a(true); + iterator.remove(); + } + } + + if (flag) { + this.n(); + } + + } + + private boolean f(BlockPosition blockposition) { + IBlockData iblockdata = this.a.getTypeIfLoaded(blockposition.getX(), blockposition.getY(), blockposition.getZ()); + if (iblockdata == null) + return false; + Block block = iblockdata.getBlock(); + return block instanceof BlockDoor && block.getMaterial() == Material.WOOD; + } + + private void n() { + int i = this.b.size(); + + if (i == 0) { + this.d = new BlockPosition(0, 0, 0); + this.e = 0; + } else { + this.d = new BlockPosition(this.c.getX() / i, this.c.getY() / i, this.c.getZ() / i); + int j = 0; + + VillageDoor villagedoor; + + for (Iterator iterator = this.b.iterator(); iterator.hasNext(); j = Math.max(villagedoor.a(this.d), j)) { + villagedoor = iterator.next(); + } + + this.e = Math.max(32, (int) Math.sqrt(j) + 1); + calculateNewCheckPositions(); + } + } + + public int a(String s) { + Integer integer = this.j.get(s); + + return integer != null ? integer : 0; + } + + public int a(String s, int i) { + int j = this.a(s); + int k = MathHelper.clamp(j + i, -30, 10); + + this.j.put(s, k); + return k; + } + + public boolean d(String s) { + return this.a(s) <= -15; + } + + public void a(NBTTagCompound nbttagcompound) { + this.h = nbttagcompound.getInt("PopSize"); + this.e = nbttagcompound.getInt("Radius"); + this.l = nbttagcompound.getInt("Golems"); + this.f = nbttagcompound.getInt("Stable"); + this.g = nbttagcompound.getInt("Tick"); + this.i = nbttagcompound.getInt("MTick"); + this.d = new BlockPosition(nbttagcompound.getInt("CX"), nbttagcompound.getInt("CY"), nbttagcompound.getInt("CZ")); + this.c = new BlockPosition(nbttagcompound.getInt("ACX"), nbttagcompound.getInt("ACY"), nbttagcompound.getInt("ACZ")); + NBTTagList nbttaglist = nbttagcompound.getList("Doors", 10); + + for (int i = 0; i < nbttaglist.size(); ++i) { + NBTTagCompound nbttagcompound1 = nbttaglist.get(i); + VillageDoor villagedoor = new VillageDoor(new BlockPosition(nbttagcompound1.getInt("X"), nbttagcompound1.getInt("Y"), nbttagcompound1.getInt("Z")), nbttagcompound1.getInt("IDX"), nbttagcompound1.getInt("IDZ"), nbttagcompound1.getInt("TS")); + + this.b.add(villagedoor); + } + + NBTTagList nbttaglist1 = nbttagcompound.getList("Players", 10); + + for (int j = 0; j < nbttaglist1.size(); ++j) { + NBTTagCompound nbttagcompound2 = nbttaglist1.get(j); + + if (nbttagcompound2.hasKey("UUID")) { + UserCache usercache = MinecraftServer.getServer().getUserCache(); + GameProfile gameprofile = usercache.a(FastUUID.parseUUID(nbttagcompound2.getString("UUID"))); + + if (gameprofile != null) { + this.j.put(gameprofile.getName(), nbttagcompound2.getInt("S")); + } + } else { + this.j.put(nbttagcompound2.getString("Name"), nbttagcompound2.getInt("S")); + } + } + calculateNewCheckPositions(); + } + + public void b(NBTTagCompound nbttagcompound) { + nbttagcompound.setInt("PopSize", this.h); + nbttagcompound.setInt("Radius", this.e); + nbttagcompound.setInt("Golems", this.l); + nbttagcompound.setInt("Stable", this.f); + nbttagcompound.setInt("Tick", this.g); + nbttagcompound.setInt("MTick", this.i); + nbttagcompound.setInt("CX", this.d.getX()); + nbttagcompound.setInt("CY", this.d.getY()); + nbttagcompound.setInt("CZ", this.d.getZ()); + nbttagcompound.setInt("ACX", this.c.getX()); + nbttagcompound.setInt("ACY", this.c.getY()); + nbttagcompound.setInt("ACZ", this.c.getZ()); + NBTTagList nbttaglist = new NBTTagList(); + + for (VillageDoor villagedoor : this.b) { + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + + nbttagcompound1.setInt("X", villagedoor.d().getX()); + nbttagcompound1.setInt("Y", villagedoor.d().getY()); + nbttagcompound1.setInt("Z", villagedoor.d().getZ()); + nbttagcompound1.setInt("IDX", villagedoor.f()); + nbttagcompound1.setInt("IDZ", villagedoor.g()); + nbttagcompound1.setInt("TS", villagedoor.h()); + nbttaglist.add(nbttagcompound1); + } + + nbttagcompound.set("Doors", nbttaglist); + NBTTagList nbttaglist1 = new NBTTagList(); + + for (String s : this.j.keySet()) { + NBTTagCompound nbttagcompound2 = new NBTTagCompound(); + UserCache usercache = MinecraftServer.getServer().getUserCache(); + GameProfile gameprofile = usercache.getProfile(s); + + if (gameprofile != null) { + nbttagcompound2.setString("UUID", FastUUID.toString(gameprofile.getId())); + nbttagcompound2.setInt("S", this.j.get(s)); + nbttaglist1.add(nbttagcompound2); + } + } + + nbttagcompound.set("Players", nbttaglist1); + } + + public void h() { + this.i = this.g; + } + + public boolean i() { + return this.i == 0 || this.g - this.i >= 3600; + } + + public void b(int i) { + for (String s : this.j.keySet()) { + this.a(s, i); + } + } + + static class Aggressor { + + public EntityLiving a; + public int b; + + Aggressor(EntityLiving entityliving, int i) { + this.a = entityliving; + this.b = i; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/VillageDoor.java b/azurite-server/src/main/java/net/minecraft/server/VillageDoor.java new file mode 100644 index 0000000..74b74dd --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/VillageDoor.java @@ -0,0 +1,89 @@ +package net.minecraft.server; + +public class VillageDoor { + + private final BlockPosition a; + private final BlockPosition b; + private final EnumDirection c; + private int d; + private boolean e; + private int f; + + public VillageDoor(BlockPosition blockposition, int i, int j, int k) { + this(blockposition, a(i, j), k); + } + + private static EnumDirection a(int i, int j) { + return i < 0 ? EnumDirection.WEST : (i > 0 ? EnumDirection.EAST : (j < 0 ? EnumDirection.NORTH : EnumDirection.SOUTH)); + } + + public VillageDoor(BlockPosition blockposition, EnumDirection enumdirection, int i) { + this.a = blockposition; + this.c = enumdirection; + this.b = blockposition.shift(enumdirection, 2); + this.d = i; + } + + public int b(int i, int j, int k) { + return (int) this.a.c((double) i, (double) j, (double) k); + } + + public int a(BlockPosition blockposition) { + return (int) blockposition.i(this.d()); + } + + public int b(BlockPosition blockposition) { + return (int) this.b.i(blockposition); + } + + public boolean c(BlockPosition blockposition) { + int i = blockposition.getX() - this.a.getX(); + int j = blockposition.getZ() - this.a.getY(); + + return i * this.c.getAdjacentX() + j * this.c.getAdjacentZ() >= 0; + } + + public void a() { + this.f = 0; + } + + public void b() { + ++this.f; + } + + public int c() { + return this.f; + } + + public BlockPosition d() { + return this.a; + } + + public BlockPosition e() { + return this.b; + } + + public int f() { + return this.c.getAdjacentX() * 2; + } + + public int g() { + return this.c.getAdjacentZ() * 2; + } + + public int h() { + return this.d; + } + + public void a(int i) { + this.d = i; + } + + public boolean i() { + return this.e; + } + + public void a(boolean flag) { + this.e = flag; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/VillageSiege.java b/azurite-server/src/main/java/net/minecraft/server/VillageSiege.java new file mode 100644 index 0000000..0cea4a7 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/VillageSiege.java @@ -0,0 +1,155 @@ +package net.minecraft.server; + +import java.util.List; + +public class VillageSiege { + + private final World a; + private boolean b; + private int c = -1; + private int d; + private int e; + private Village f; + private int g; + private int h; + private int i; + + public VillageSiege(World world) { + this.a = world; + } + + public void a() { + if (this.a.w()) { + this.c = 0; + } else if (this.c != 2) { + if (this.c == 0) { + float f = this.a.c(0.0F); + + if ((double) f < 0.5D || (double) f > 0.501D) { + return; + } + + this.c = this.a.random.nextInt(10) == 0 ? 1 : 2; + this.b = false; + if (this.c == 2) { + return; + } + } + + if (this.c != -1) { + if (!this.b) { + if (!this.b()) { + return; + } + + this.b = true; + } + + if (this.e > 0) { + --this.e; + } else { + this.e = 2; + if (this.d > 0) { + this.c(); + --this.d; + } else { + this.c = 2; + } + + } + } + } + } + + private boolean b() { + List list = this.a.players; + + for (EntityHuman entityhuman : list) { + if (!entityhuman.isSpectator()) { + this.f = this.a.ae().getClosestVillage(MathHelper.floor(entityhuman.locX), MathHelper.floor(entityhuman.locY), MathHelper.floor(entityhuman.locZ), 1); + if (this.f != null && this.f.c() >= 10 && this.f.d() >= 20 && this.f.e() >= 20) { + BlockPosition blockposition = this.f.a(); + float f = (float) this.f.b(); + boolean flag = false; + int i = 0; + + while (true) { + if (i < 10) { + float f1 = this.a.random.nextFloat() * 3.1415927F * 2.0F; + + this.g = blockposition.getX() + (int) ((double) (MathHelper.cos(f1) * f) * 0.9D); + this.h = blockposition.getY(); + this.i = blockposition.getZ() + (int) ((double) (MathHelper.sin(f1) * f) * 0.9D); + flag = false; + + for (Village village : this.a.ae().getVillages()) { + if (village != this.f && village.a(this.g, this.h, this.i)) { + flag = true; + break; + } + } + + if (flag) { + ++i; + continue; + } + } + + if (flag) { + return false; + } + + Vec3D vec3d = this.a(new BlockPosition(this.g, this.h, this.i)); + + if (vec3d != null) { + this.e = 0; + this.d = 20; + return true; + } + break; + } + } + } + } + + return false; + } + + private boolean c() { + Vec3D vec3d = this.a(new BlockPosition(this.g, this.h, this.i)); + + if (vec3d == null) { + return false; + } else { + EntityZombie entityzombie; + + try { + entityzombie = new EntityZombie(this.a); + entityzombie.prepare(this.a.E(MathHelper.floor(entityzombie.locX), MathHelper.floor(entityzombie.locY), MathHelper.floor(entityzombie.locZ)), null); + entityzombie.setVillager(false); + } catch (Exception exception) { + exception.printStackTrace(); + return false; + } + + entityzombie.setPositionRotation(vec3d.a, vec3d.b, vec3d.c, this.a.random.nextFloat() * 360.0F, 0.0F); + this.a.addEntity(entityzombie, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.VILLAGE_INVASION); // CraftBukkit + BlockPosition blockposition = this.f.a(); + + entityzombie.a(blockposition, this.f.b()); + return true; + } + } + + private Vec3D a(BlockPosition blockposition) { + for (int i = 0; i < 10; ++i) { + BlockPosition blockposition1 = blockposition.a(this.a.random.nextInt(16) - 8, this.a.random.nextInt(6) - 3, this.a.random.nextInt(16) - 8); + + if (this.f.a(blockposition1) && SpawnerCreature.a(EntityInsentient.EnumEntityPositionType.ON_GROUND, this.a, blockposition1)) { + return new Vec3D(blockposition1.getX(), blockposition1.getY(), blockposition1.getZ()); + } + } + + return null; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WatchableArrayMap.java b/azurite-server/src/main/java/net/minecraft/server/WatchableArrayMap.java new file mode 100644 index 0000000..b413ef4 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WatchableArrayMap.java @@ -0,0 +1,140 @@ +package net.minecraft.server; + +import com.google.common.base.Objects; +import net.minecraft.server.DataWatcher.WatchableObject; +import org.jetbrains.annotations.NotNull; + +import java.util.*; + +public class WatchableArrayMap implements Map { + + private WatchableObject[] dataValues = new WatchableObject[23]; + + @Override + public int size() { + return dataValues.length; + } + + @Override + public boolean isEmpty() { + for (WatchableObject dataValue : dataValues) { + if (dataValue != null) return false; + } + + return true; + } + + public boolean containsKey(int i) { + return dataValues[i] != null; + } + + @Override + public boolean containsKey(Object key) { + return key instanceof Integer && dataValues[(Integer) key] != null; + } + + @Override + public boolean containsValue(Object value) { + for (WatchableObject dataValue : dataValues) { + if (Objects.equal(dataValue, value)) return true; + } + + return false; + } + + public WatchableObject get(int i) { + return dataValues[i]; + } + + @Override + public WatchableObject get(Object key) { + return key instanceof Integer ? dataValues[(Integer) key] : null; + } + + public void put(int i, WatchableObject watchableObject) { + dataValues[i] = watchableObject; + } + + @Override + public WatchableObject put(Integer key, WatchableObject value) { + int index = key; + WatchableObject old = dataValues[index]; + dataValues[index] = value; + return old; + } + + @Override + public WatchableObject remove(Object key) { + if (!(key instanceof Integer)) return null; + + int index = (Integer) key; + WatchableObject old = dataValues[index]; + dataValues[index] = null; + return old; + } + + @Override + public void putAll(Map m) { + for (Object object : m.entrySet()) { + if (!(object instanceof Entry)) continue; + Entry entry = (Entry) object; + Object key = entry.getKey(); + Object value = entry.getValue(); + + if (!(key instanceof Integer) || (!(value instanceof WatchableObject))) continue; + + put((Integer) key, (WatchableObject) value); + } + } + + @Override + public void clear() { + this.dataValues = new WatchableObject[23]; + } + + @Override + public Set keySet() { + Set set = new HashSet<>(); + for (int i = 0; i < dataValues.length; i++) { + if (dataValues[i] != null) set.add(i); + } + + return set; + } + + @Override + public Collection values() { + Set set = new HashSet<>(); + for (WatchableObject dataValue : dataValues) { + if (dataValue != null) set.add(dataValue); + } + + return set; + } + + @Override + public @NotNull Set> entrySet() { + Set> set = new HashSet<>(); + for (int i = 0; i < dataValues.length; i++) { + WatchableObject watchableObject = dataValues[i]; + if (watchableObject != null) { + set.add(new AbstractMap.SimpleEntry<>(i, watchableObject)); + } + } + + return set; + } + + // Clone the WatchableObjects and deep clone ItemStacks if there are any + @Override + public WatchableArrayMap clone() { + WatchableArrayMap watchableArrayMap = new WatchableArrayMap(); + for (int i = 0; i < this.dataValues.length; i++) { + WatchableObject watchableObject = this.dataValues[i]; + if (watchableObject != null) { + watchableArrayMap.dataValues[i] = watchableObject.b() instanceof ItemStack ? new WatchableObject(watchableObject.c(), watchableObject.a(), ((ItemStack) watchableObject.b()).cloneItemStack()) : watchableObject.clone(); + } + } + return watchableArrayMap; + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/net/minecraft/server/WeightedRandom.java b/azurite-server/src/main/java/net/minecraft/server/WeightedRandom.java new file mode 100644 index 0000000..56ed848 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WeightedRandom.java @@ -0,0 +1,60 @@ +package net.minecraft.server; + +import java.util.Collection; +import java.util.Iterator; +import java.util.Random; + +public class WeightedRandom { + + public static int a(Collection collection) { + int i = 0; + + WeightedRandom.WeightedRandomChoice weightedrandom_weightedrandomchoice; + + for (Iterator iterator = collection.iterator(); iterator.hasNext(); i += weightedrandom_weightedrandomchoice.a) { + weightedrandom_weightedrandomchoice = iterator.next(); + } + + return i; + } + + public static T a(Random random, Collection collection, int i) { + if (i <= 0) { + throw new IllegalArgumentException(); + } else { + int j = random.nextInt(i); + + return a(collection, j); + } + } + + public static T a(Collection collection, int i) { + Iterator iterator = collection.iterator(); + + T weightedrandom_weightedrandomchoice; + + do { + if (!iterator.hasNext()) { + return null; + } + + weightedrandom_weightedrandomchoice = iterator.next(); + i -= weightedrandom_weightedrandomchoice.a; + } while (i >= 0); + + return weightedrandom_weightedrandomchoice; + } + + public static T a(Random random, Collection collection) { + return a(random, collection, a(collection)); + } + + public static class WeightedRandomChoice { + + protected int a; + + public WeightedRandomChoice(int i) { + this.a = i; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WeightedRandomEnchant.java b/azurite-server/src/main/java/net/minecraft/server/WeightedRandomEnchant.java new file mode 100644 index 0000000..68595aa --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WeightedRandomEnchant.java @@ -0,0 +1,13 @@ +package net.minecraft.server; + +public class WeightedRandomEnchant extends WeightedRandom.WeightedRandomChoice { + + public final Enchantment enchantment; + public final int level; + + public WeightedRandomEnchant(Enchantment enchantment, int i) { + super(enchantment.getRandomWeight()); + this.enchantment = enchantment; + this.level = i; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WhiteList.java b/azurite-server/src/main/java/net/minecraft/server/WhiteList.java new file mode 100644 index 0000000..13c0039 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WhiteList.java @@ -0,0 +1,59 @@ +package net.minecraft.server; + +import com.google.gson.JsonObject; +import com.mojang.authlib.GameProfile; + +import java.io.File; +import java.util.Iterator; + +public class WhiteList extends JsonList { + + public WhiteList(File file) { + super(file); + } + + protected JsonListEntry a(JsonObject jsonobject) { + return new WhiteListEntry(jsonobject); + } + + public boolean isWhitelisted(GameProfile gameprofile) { + return this.d(gameprofile); + } + + public String[] getEntries() { + String[] astring = new String[this.e().size()]; + int i = 0; + + WhiteListEntry whitelistentry; + + for (Iterator iterator = this.e().values().iterator(); iterator.hasNext(); astring[i++] = whitelistentry.getKey().getName()) { + whitelistentry = iterator.next(); + } + + return astring; + } + + protected String b(GameProfile gameprofile) { + return gameprofile.getId().toString(); + } + + public GameProfile a(String s) { + Iterator iterator = this.e().values().iterator(); + + WhiteListEntry whitelistentry; + + do { + if (!iterator.hasNext()) { + return null; + } + + whitelistentry = iterator.next(); + } while (!s.equalsIgnoreCase(whitelistentry.getKey().getName())); + + return whitelistentry.getKey(); + } + + protected String a(GameProfile object) { + return this.b(object); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WhiteListEntry.java b/azurite-server/src/main/java/net/minecraft/server/WhiteListEntry.java new file mode 100644 index 0000000..da93bb5 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WhiteListEntry.java @@ -0,0 +1,43 @@ +package net.minecraft.server; + +import com.eatthepath.uuid.FastUUID; +import com.google.gson.JsonObject; +import com.mojang.authlib.GameProfile; +import java.util.UUID; + +public class WhiteListEntry extends JsonListEntry { + + public WhiteListEntry(GameProfile gameprofile) { + super(gameprofile); + } + + public WhiteListEntry(JsonObject jsonobject) { + super(b(jsonobject), jsonobject); + } + + protected void a(JsonObject jsonobject) { + if (this.getKey() != null) { + jsonobject.addProperty("uuid", ((GameProfile) this.getKey()).getId() == null ? "" : ((GameProfile) this.getKey()).getId().toString()); + jsonobject.addProperty("name", ((GameProfile) this.getKey()).getName()); + super.a(jsonobject); + } + } + + private static GameProfile b(JsonObject jsonobject) { + if (jsonobject.has("uuid") && jsonobject.has("name")) { + String s = jsonobject.get("uuid").getAsString(); + + UUID uuid; + + try { + uuid = FastUUID.parseUUID(s); + } catch (Throwable throwable) { + return null; + } + + return new GameProfile(uuid, jsonobject.get("name").getAsString()); + } else { + return null; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/World.java b/azurite-server/src/main/java/net/minecraft/server/World.java new file mode 100644 index 0000000..1af18c2 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/World.java @@ -0,0 +1,3857 @@ +package net.minecraft.server; + +import com.google.common.base.Predicate; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import com.google.common.util.concurrent.ThreadFactoryBuilder; +import dev.azurite.spigot.Azurite; +import dev.azurite.spigot.autosave.AutoSaveWorldData; +import dev.azurite.spigot.configs.AzuriteConfig; +import dev.azurite.spigot.configs.PearlConfig; +import dev.azurite.spigot.generator.Generator; +import dev.azurite.spigot.optimizations.ChunkTickList; +import dev.azurite.spigot.optimizations.OptimizedNonEmptyList; +import dev.azurite.spigot.optimizations.PlayerMap; +import dev.azurite.spigot.optimizations.SimpleRandom; +import dev.azurite.spigot.utils.PearlUtil; +import dev.azurite.spigot.utils.Utils; +import dev.imanity.antixray.sdk.AntiXrayAdapter; +import dev.imanity.antixray.sdk.AntiXraySDK; +import it.unimi.dsi.fastutil.ints.Int2FloatMap; +import it.unimi.dsi.fastutil.ints.Int2FloatOpenHashMap; +import org.bukkit.Bukkit; +import org.bukkit.block.BlockState; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.CraftWorld; +import org.bukkit.craftbukkit.event.CraftEventFactory; +import org.bukkit.craftbukkit.util.CraftMagicNumbers; +import org.bukkit.craftbukkit.util.LongHash; +import org.bukkit.event.Cancellable; +import org.bukkit.event.block.BlockCanBuildEvent; +import org.bukkit.event.block.BlockPhysicsEvent; +import org.bukkit.event.entity.CreatureSpawnEvent; +import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason; +import org.bukkit.generator.ChunkGenerator; +import org.github.paperspigot.PaperWorldEntityList; +import org.github.paperspigot.event.ServerExceptionEvent; +import org.github.paperspigot.exception.ServerInternalException; +import org.spigotmc.ActivationRange; +import org.spigotmc.AsyncCatcher; + +import java.util.*; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +public abstract class World implements IBlockAccess { + public static final Explosion emptyExplosion = new Explosion(null, null, 0, 0, 0, 0, false, false).cancel(); + public static boolean haveWeSilencedAPhysicsCrash; + public static String blockLocation; + public List tileEntityList = Lists.newArrayList(); + public List players = Lists.newArrayList(); + public List k = Lists.newArrayList(); + public MethodProfiler methodProfiler; + public Random random = new SimpleRandom(); + public SimpleRandom simpleRandom = new SimpleRandom(0L); // SpottedLeaf + public boolean isClientSide; + + public final Int2FloatMap explosionDensityCache = new Int2FloatOpenHashMap(); + public final Map rayTraceCache = Maps.newHashMap(); + private final Queue queuedSpawn = new ArrayDeque<>(); + public final CannonCache movementCache = new CannonCache(); + + public org.spigotmc.SpigotWorldConfig spigotConfig; // Spigot + public org.github.paperspigot.PaperSpigotWorldConfig paperSpigotConfig; // PaperSpigot + public Generator generatorConfig; + public BiomeBase spawnBiome; + // Spigot end + protected Set g = new ArraySet<>(); // Paper + protected IntHashMap entitiesById = new IntHashMap<>(); + protected int n = 1013904223; + protected IDataManager dataManager; + public ChunkTickList chunkTickList; // Beanes - optimized tick list + private final List b = Lists.newArrayList(); + private final Set c = new ArraySet<>(); // Paper + private final Calendar K = Calendar.getInstance(); + private final WorldBorder N; + // CraftBukkit start Added the following + private final CraftWorld world; + private final List interceptedSounds = new ArrayList<>(); + public byte chunkTickRadius; + public WorldProvider worldProvider; // CraftBukkit - remove final + public WorldData worldData; // CraftBukkit - public + public PersistentCollection worldMaps; // CraftBukkit - public + public Scoreboard scoreboard = new Scoreboard(); // CraftBukkit - public + public boolean allowMonsters; // CraftBukkit - public + public boolean allowAnimals; // CraftBukkit - public + public boolean pvpMode; + public boolean keepSpawnInMemory; + public ChunkGenerator generator; + public boolean captureBlockStates = false; + public boolean captureTreeGeneration = false; + public ArrayList capturedBlockStates = new ArrayList() { + @Override + public boolean add(BlockState blockState) { + for (BlockState blockState1 : this) { + if (blockState1.getLocation().equals(blockState.getLocation())) { + return false; + } + } + return super.add(blockState); + } + }; + public long ticksPerAnimalSpawns; + public long ticksPerMonsterSpawns; + public boolean populating; + public ExecutorService lightingExecutor = Executors.newSingleThreadExecutor(new ThreadFactoryBuilder().setNameFormat("Paper - Lighting Thread").build()); // PaperSpigot - Asynchronous lighting updates + public Map capturedTileEntities = Maps.newHashMap(); + protected boolean e; + protected int m = random.nextInt(); + protected float o; + protected float p; + protected float q; + protected float r; + protected List u = Lists.newArrayList(); + protected IChunkProvider chunkProvider; + protected boolean isLoading; + protected PersistentVillage villages; + protected float growthOdds = 100; + protected float modifiedOdds = 100; + int[] H; + private int a = 63; + public int I; // Beanes - make skylightSubstracted public + private boolean M; + private int tickPosition; + public boolean guardEntityList; + public List entityList = new PaperWorldEntityList(this); // Azurite - Use paper world entity list + private boolean interceptSounds; + public final PlayerMap playerMap = new PlayerMap(); + private final AutoSaveWorldData autoSaveWorldData; + + protected World(IDataManager idatamanager, WorldData worlddata, WorldProvider worldprovider, MethodProfiler methodprofiler, boolean flag, ChunkGenerator gen, org.bukkit.World.Environment env) { + this(idatamanager, worlddata, worldprovider, methodprofiler, flag, gen, env, false); + } + + protected World(IDataManager idatamanager, WorldData worlddata, WorldProvider worldprovider, MethodProfiler methodprofiler, boolean flag, ChunkGenerator gen, org.bukkit.World.Environment env, boolean shouldGenerateConfig) { + // Beanes - do not generate config for slime worlds + if (shouldGenerateConfig) { + if (com.grinderwolf.swm.clsm.ClassModifier.isCustomWorld(this)) { + shouldGenerateConfig = false; + } + } + + explosionDensityCache.defaultReturnValue(-1.0f); + this.generatorConfig = (env == org.bukkit.World.Environment.NORMAL && shouldGenerateConfig ? Azurite.getInstance().getGeneratorManager().getOrCreate(worlddata.getName()) : Azurite.getInstance().getGeneratorManager().getDefaultConfig()); + this.spawnBiome = BiomeBase.o.get(generatorConfig.spawnBiome.getValue()); + this.spigotConfig = new org.spigotmc.SpigotWorldConfig(worlddata.getName()); // Spigot + this.paperSpigotConfig = new org.github.paperspigot.PaperSpigotWorldConfig(worlddata.getName()); // PaperSpigot + this.generator = gen; + this.world = new CraftWorld((WorldServer) this, gen, env); + this.ticksPerAnimalSpawns = this.getServer().getTicksPerAnimalSpawns(); // CraftBukkit + this.ticksPerMonsterSpawns = this.getServer().getTicksPerMonsterSpawns(); // CraftBukkit + // CraftBukkit end + // Spigot start + this.chunkTickRadius = (byte) ((getServer().getViewDistance() < 7) ? getServer().getViewDistance() : 7); + this.chunkTickList = new ChunkTickList(); // Beanes - optimized chunk tick list + // Spigot end + + this.methodProfiler = methodprofiler; + + this.allowMonsters = true; + this.allowAnimals = true; + this.H = new int['\u8000']; + this.dataManager = idatamanager; + this.worldData = worlddata; + this.worldProvider = worldprovider; + this.isClientSide = false; + this.N = worldprovider.getWorldBorder(); + // CraftBukkit start + // Moved from PlayerList + this.N.a(new IWorldBorderListener() { + public void a(WorldBorder worldborder, double d0) { + getServer().getHandle().sendAll(new PacketPlayOutWorldBorder(worldborder, PacketPlayOutWorldBorder.EnumWorldBorderAction.SET_SIZE), World.this); + } + + public void a(WorldBorder worldborder, double d0, double d1, long i) { + getServer().getHandle().sendAll(new PacketPlayOutWorldBorder(worldborder, PacketPlayOutWorldBorder.EnumWorldBorderAction.LERP_SIZE), World.this); + } + + public void a(WorldBorder worldborder, double d0, double d1) { + getServer().getHandle().sendAll(new PacketPlayOutWorldBorder(worldborder, PacketPlayOutWorldBorder.EnumWorldBorderAction.SET_CENTER), World.this); + } + + public void a(WorldBorder worldborder, int i) { + getServer().getHandle().sendAll(new PacketPlayOutWorldBorder(worldborder, PacketPlayOutWorldBorder.EnumWorldBorderAction.SET_WARNING_TIME), World.this); + } + + public void b(WorldBorder worldborder, int i) { + getServer().getHandle().sendAll(new PacketPlayOutWorldBorder(worldborder, PacketPlayOutWorldBorder.EnumWorldBorderAction.SET_WARNING_BLOCKS), World.this); + } + + public void b(WorldBorder worldborder, double d0) { + } + + public void c(WorldBorder worldborder, double d0) { + } + }); + this.getServer().addWorld(this.world); + // CraftBukkit end + this.keepSpawnInMemory = this.paperSpigotConfig.keepSpawnInMemory; // PaperSpigot + this.autoSaveWorldData = new AutoSaveWorldData(this); + } + + public AutoSaveWorldData getAutoSaveWorldData() { + return this.autoSaveWorldData; + } + + public static long chunkToKey(int x, int z) { + return LongHash.toLong(x, z); + } + + public static int keyToX(long k) { + return (int) (((k >> 16) & 0xFFFF0000L) | (k & 0x0000FFFF)); + } + + public static int keyToZ(long k) { + return (int) (((k >> 32) & 0xFFFF0000L) | ((k >> 16) & 0x0000FFFF)); + } + + public static boolean a(IBlockAccess iblockaccess, BlockPosition blockposition) { + return a(iblockaccess, blockposition.getX(), blockposition.getY(), blockposition.getZ()); + } + + public static boolean a(IBlockAccess iblockaccess, int x, int y, int z) { + IBlockData iblockdata = iblockaccess.getType(x, y, z); + Block block = iblockdata.getBlock(); + return block.getMaterial().k() && + block.d() || (block instanceof BlockStairs ? iblockdata.get(BlockStairs.HALF) == BlockStairs.EnumHalf.TOP + : (block instanceof BlockStepAbstract + ? iblockdata.get(BlockStepAbstract.HALF) == BlockStepAbstract.EnumSlabHalf.TOP + : (block instanceof BlockHopper || (block instanceof BlockSnow && iblockdata.get(BlockSnow.LAYERS) == 7)))); + } + + public static boolean a(World world, Chunk chunk, int x, int y, int z) { + IBlockData iblockdata = world.getType(chunk, x, y, z, true); + Block block = iblockdata.getBlock(); + return block.getMaterial().k() && + block.d() || (block instanceof BlockStairs ? iblockdata.get(BlockStairs.HALF) == BlockStairs.EnumHalf.TOP + : (block instanceof BlockStepAbstract + ? iblockdata.get(BlockStepAbstract.HALF) == BlockStepAbstract.EnumSlabHalf.TOP + : (block instanceof BlockHopper || (block instanceof BlockSnow && iblockdata.get(BlockSnow.LAYERS) == 7)))); + } + + public static boolean a(IBlockData iblockdata) { + Block block = iblockdata.getBlock(); + return block.getMaterial().k() && + block.d() || (block instanceof BlockStairs ? iblockdata.get(BlockStairs.HALF) == BlockStairs.EnumHalf.TOP + : (block instanceof BlockStepAbstract + ? iblockdata.get(BlockStepAbstract.HALF) == BlockStepAbstract.EnumSlabHalf.TOP + : (block instanceof BlockHopper || (block instanceof BlockSnow && iblockdata.get(BlockSnow.LAYERS) == 7)))); + } + + public CraftWorld getWorld() { + return this.world; + } + + public CraftServer getServer() { + return (CraftServer) Bukkit.getServer(); + } + + public Chunk getChunkIfLoaded(int x, int z) { + return ((ChunkProviderServer) this.chunkProvider).getChunkIfLoaded(x, z); + } + + public Chunk getChunkIfLoaded(long hash) { + return ((ChunkProviderServer) this.chunkProvider).getChunkIfLoaded(hash); + } + + public World b() { + return this; + } + + public BiomeBase getBiome(BlockPosition blockposition) { + return getBiome(blockposition.getX(), blockposition.getY(), blockposition.getZ()); + } + + public WorldChunkManager getWorldChunkManager() { + return this.worldProvider.m(); + } + + //Vortex - Start + public boolean isValidLocation(int x, int y, int z) { + return isValidLocation(x, z) && y >= 0 && y < 256; + } + + public IBlockData getCapturedBlockType(int x, int y, int z) { + for (BlockState previous : this.capturedBlockStates) { + if (previous.getX() == x && previous.getY() == y && previous.getZ() == z) + return CraftMagicNumbers.getBlock(previous.getTypeId()).fromLegacyData(previous.getRawData()); + } + return null; + } + + public DifficultyDamageScaler E(int x, int y, int z) { + long i = 0L; + float f = 0.0F; + + if (this.isLoaded(x, y, z)) { + f = this.y(); + i = this.getChunkAtWorldCoords(x, z).w(); + } + + return new DifficultyDamageScaler(this.getDifficulty(), this.getDayTime(), i, f); + } + + public IBlockData getTypeIfLoaded(int x, int y, int z) { + if (captureTreeGeneration) { + IBlockData previous = getCapturedBlockType(x, y, z); + if (previous != null) + return previous; + } + Chunk chunk = ((ChunkProviderServer) this.chunkProvider).getChunkIfLoaded(x >> 4, z >> 4); + if (chunk != null) + return chunk.getBlockData(x, y, z); + return null; + } + + public boolean areChunksLoadedBetween(int x, int y, int z, int x1, int y1, int z1) { + return isAreaLoaded(x, y, z, x1, y1, z1, true); + } + + public boolean isLoaded(int x, int y, int z) { + return isValidLocation(x, y, z) && isChunkLoaded(x >> 4, z >> 4, true); + } + + public boolean i(int x, int y, int z) { + return getChunkAtWorldCoords(x, z).d(x, y, z); + } + + public int getLightLevel(BlockPosition blockposition) { + if (AzuriteConfig.disableBlockLighting.getValue()) + return 15; + return c(blockposition.getX(), blockposition.getY(), blockposition.getZ(), true); + } + + // PandaSpigot start - test if meets light level, return faster + // logic copied from below + public boolean isLightLevel(int x, int y, int z, int level) { + if (isValidLocation(x, z)) { + if (this.getType(x, y, z).getBlock().s()) { + if (this.c(x, y + 1, z, false) >= level) { + return true; + } + if (this.c(x + 1, y, z, false) >= level) { + return true; + } + if (this.c(x - 1, y, z, false) >= level) { + return true; + } + if (this.c(x, y, z + 1, false) >= level) { + return true; + } + if (this.c(x, y, z - 1, false) >= level) { + return true; + } + return false; + } else { + if (y >= 256) { + y = 255; + } + + // Azurite - Don't load chunks for light level checks + // Azurite - Don't load chunks for light level checks + Chunk chunk = getChunkIfLoaded(x >> 4, z >> 4); + if (chunk == null) return 0 >= level; + return chunk.a(x, y, z, this.I) >= level; + } + } else { + return true; + } + } + // PandaSpigot end + + public int getLightLevel(int x, int y, int z) { + if (AzuriteConfig.disableBlockLighting.getValue()) + return 15; + return c(x, y, z, true); + } + + public int c(int x, int y, int z, boolean flag) { + if (isValidLocation(x, z)) { + if (flag && this.getType(x, y, z).getBlock().s()) { + + int i = this.c(x, y + 1, z, false); + int j = this.c(x + 1, y, z, false); + int k = this.c(x - 1, y, z, false); + int l = this.c(x, y, z + 1, false); + int i1 = this.c(x, y, z - 1, false); + + if (j > i) { + i = j; + } + + if (k > i) { + i = k; + } + + if (l > i) { + i = l; + } + + if (i1 > i) { + i = i1; + } + + return i; + } else if (y < 0) { + return 0; + } else { + if (y >= 256) { + y = 255; + } + + // Azurite - Don't load chunks for light level checks + Chunk chunk = getChunkIfLoaded(x >> 4, z >> 4); + if (chunk == null) return 0; + return chunk.a(x, y, z, this.I); + } + } else { + return 15; + } + } + + public void queueSpawn(Entity entity) { + queuedSpawn.add(entity); + } + + public void dispatch() { + Entity entity; + while ((entity = queuedSpawn.poll()) != null) { + addEntity(entity); + if (AzuriteConfig.dispenserEffects.getValue()) + makeSound(entity, "game.tnt.primed", 1.0F, 1.0F); + } + } + + public BiomeBase getBiome(int x, int y, int z) { + if (isValidLocation(x, y, z)) { + Chunk ch = getChunkIfLoaded(x, z); + if (ch != null) { + try { + return ch.getBiome(x, z, this.worldProvider.m()); + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.a(throwable, "Getting biome"); + CrashReportSystemDetails crashreportsystemdetails = crashreport.a("Coordinates of biome request"); + + crashreportsystemdetails.a("Location", () -> CrashReportSystemDetails.a(new BlockPosition(x, y, z))); + throw new ReportedException(crashreport); + } + } else { + return this.worldProvider.m().getBiome(x, z, BiomeBase.PLAINS); + } + } else { + return this.worldProvider.m().getBiome(x, z, BiomeBase.PLAINS); + } + } + + public boolean isValidLocation(int x, int z) { // Vortex - Optimized player ticking + return x >= -30000000 && z >= -30000000 && x < 30000000 && z < 30000000; + } + + public void a(EnumSkyBlock enumskyblock, int x, int y, int z, int i) { + if (isLoaded(x, y, z)) { + getChunkAtWorldCoords(x, z).a(enumskyblock, x, y, z, i); + this.n(new BlockPosition(x, y, z)); + } + } + + private int a(int x, int y, int z, EnumSkyBlock enumskyblock) { + if (enumskyblock == EnumSkyBlock.SKY && this.i(x, y, z)) { + return 15; + } else { + Block block = this.getType(x, y, z).getBlock(); + int i = enumskyblock == EnumSkyBlock.SKY ? 0 : block.r(); + int j = block.p(); + + if (j >= 15 && block.r() > 0) { + j = 1; + } + + if (j < 1) { + j = 1; + } + + if (j >= 15) { + return 0; + } else if (i >= 14) { + return i; + } else { + for (EnumDirection enumdirection : EnumDirection.values()) { + int i1 = this.b(enumskyblock, x + enumdirection.getAdjacentX(), y + enumdirection.getAdjacentY(), z + enumdirection.getAdjacentZ()) - j; + + if (i1 > i) { + i = i1; + } + + if (i >= 14) { + return i; + } + } + + return i; + } + } + } + + public void applyPhysics(int x, int y, int z, Block block) { + BlockPosition source = new BlockPosition(x, y, z); // Azurite - Eigencraft Redstone + d(x - 1, y, z, block, source); + d(x + 1, y, z, block, source); + d(x, y - 1, z, block, source); + d(x, y + 1, z, block, source); + d(x, y, z - 1, block, source); + d(x, y, z + 1, block, source); + } + + public void applyPhysics(BlockPosition blockposition, Block block) { + applyPhysics(blockposition.getX(), blockposition.getY(), blockposition.getZ(), block); + spigotConfig.antiXrayInstance.updateNearbyBlocks(this, blockposition); + } + + public IBlockData getType(Chunk chunk, BlockPosition position) { // Vortex - Optimized block breaking + return getType(chunk, position.getX(), position.getY(), position.getZ(), true); + } + + public IBlockData getType(Chunk chunk, int x, int y, int z, boolean useCaptured) { // Vortex - Optimized block breaking + if (captureTreeGeneration && useCaptured) { + IBlockData previous = getCapturedBlockType(x, y, z); + if (previous != null) + return previous; + } + if (!isValidLocation(x, y, z)) { + return Blocks.AIR.getBlockData(); + } else { + return chunk.getBlockData(x, y, z); + } + } + + protected abstract IChunkProvider k(); + + public void a(WorldSettings worldsettings) { + this.worldData.d(true); + } + + public Block c1(int x, int z) { + int y1 = F(); + + for (; !isEmpty(x, y1 + 1, z); y1++) { + } + + return this.getType(x, y1, z).getBlock(); + } + + public Block c(BlockPosition blockposition) { + return c1(blockposition.getX(), blockposition.getZ()); + } + + public boolean isValidLocation(BlockPosition blockposition) { + return blockposition.getX() >= -30000000 && blockposition.getZ() >= -30000000 && blockposition.getX() < 30000000 && blockposition.getZ() < 30000000 && blockposition.getY() >= 0 && blockposition.getY() < 256; + } + + public boolean isEmpty(BlockPosition blockposition) { + return getType(blockposition).getBlock().getMaterial() == Material.AIR; + } + + public boolean isEmpty(int x, int y, int z) { + return getType(x, y, z).getBlock().getMaterial() == Material.AIR; + } + + public boolean isLoaded(BlockPosition blockposition) { + return getChunkIfLoaded(blockposition.getX() >> 4, blockposition.getZ() >> 4) != null; + } + + public boolean a(BlockPosition blockposition, boolean flag) { + return isValidLocation(blockposition) && isChunkLoaded(blockposition.getX() >> 4, blockposition.getZ() >> 4, flag); + } + + public boolean areChunksLoaded(BlockPosition blockposition, int i) { + return areChunksLoaded(blockposition, i, true); + } + + public boolean areChunksLoaded(BlockPosition blockposition, int i, boolean flag) { + return isAreaLoaded(blockposition.getX() - i, blockposition.getY() - i, blockposition.getZ() - i, blockposition.getX() + i, blockposition.getY() + i, blockposition.getZ() + i, flag); + } + + public boolean areChunksLoadedBetween(BlockPosition blockposition, BlockPosition blockposition1) { + return areChunksLoadedBetween(blockposition, blockposition1, true); + } + + public boolean areChunksLoadedBetween(BlockPosition blockposition, BlockPosition blockposition1, boolean flag) { + return isAreaLoaded(blockposition.getX(), blockposition.getY(), blockposition.getZ(), blockposition1.getX(), blockposition1.getY(), blockposition1.getZ(), flag); + } + + public boolean a(StructureBoundingBox structureboundingbox) { + return b(structureboundingbox, true); + } + + public boolean b(StructureBoundingBox structureboundingbox, boolean flag) { + return isAreaLoaded(structureboundingbox.a, structureboundingbox.b, structureboundingbox.c, structureboundingbox.d, structureboundingbox.e, structureboundingbox.f, flag); + } + + private boolean isAreaLoaded(int i, int j, int k, int l, int i1, int j1, boolean flag) { + if (i1 >= 0 && j < 256) { + i >>= 4; + k >>= 4; + l >>= 4; + j1 >>= 4; + + for (int k1 = i; k1 <= l; ++k1) { + for (int l1 = k; l1 <= j1; ++l1) { + if (!isChunkLoaded(k1, l1, flag)) { + return false; + } + } + } + + return true; + } else { + return false; + } + } + // CraftBukkit end + + protected boolean isChunkLoaded(int i, int j, boolean flag) { + return chunkProvider.isChunkLoaded(i, j) && (flag || !chunkProvider.getOrCreateChunk(i, j).isEmpty()); + } + + public Chunk getChunkAtWorldCoords(BlockPosition blockposition) { + return getChunkAt(blockposition.getX() >> 4, blockposition.getZ() >> 4); + } + + public Chunk getChunkAt(int i, int j) { + return chunkProvider.getOrCreateChunk(i, j); + } + + public boolean setTypeAndData(BlockPosition blockposition, IBlockData iblockdata, int i) { + return setTypeAndData(blockposition, iblockdata, i, true, false); + } + + public boolean setTypeAndData(BlockPosition blockposition, IBlockData iblockdata, int i, boolean light, boolean sand) { + return setTypeAndData(null, blockposition, iblockdata, i, light, sand); + } + + public boolean setTypeAndData(Chunk chunk, BlockPosition blockposition, IBlockData iblockdata, int i, boolean light, boolean sand) { + if (this.captureTreeGeneration) { + BlockState blockstate = null; + Iterator it = capturedBlockStates.iterator(); + while (it.hasNext()) { + BlockState previous = it.next(); + if (previous.getX() == blockposition.getX() && previous.getY() == blockposition.getY() && previous.getZ() == blockposition.getZ()) { + blockstate = previous; + it.remove(); + break; + } + } + if (blockstate == null) { + blockstate = org.bukkit.craftbukkit.block.CraftBlockState.getBlockState(this, blockposition.getX(), blockposition.getY(), blockposition.getZ(), i); + } + blockstate.setTypeId(CraftMagicNumbers.getId(iblockdata.getBlock())); + blockstate.setRawData((byte) iblockdata.getBlock().toLegacyData(iblockdata)); + capturedBlockStates.add(blockstate); + return true; + } else if (!this.isValidLocation(blockposition)) { + return false; + } else { + if (chunk == null) chunk = getChunkAtWorldCoords(blockposition); + Block block = iblockdata.getBlock(); + + // CraftBukkit start - capture blockstates + BlockState blockstate = null; + if (captureBlockStates) { + blockstate = org.bukkit.craftbukkit.block.CraftBlockState.getBlockState(this, blockposition.getX(), blockposition.getY(), blockposition.getZ(), i); + capturedBlockStates.add(blockstate); + } + // CraftBukkit end + + IBlockData iblockdata1 = chunk.a(blockposition, iblockdata, light); + // Imanity start - AntiXraySDK integration + AntiXrayAdapter adapter = AntiXraySDK.getAdapter(); + if (adapter != null) { + adapter.callBlockChange(world, blockposition.getX(), blockposition.getY(), blockposition.getZ(), CraftMagicNumbers.getMaterial(iblockdata.getBlock())); + } + // Imanity end + + if (iblockdata1 == null) { + // CraftBukkit start - remove blockstate if failed + if (captureBlockStates) { + capturedBlockStates.remove(blockstate); + } + // CraftBukkit end + return false; + } else { + Block block1 = iblockdata1.getBlock(); + + if (light && block.p() != block1.p() || block.r() != block1.r()) { + this.x(blockposition); + } + + movementCache.clear(); + // CraftBukkit start + if (!captureBlockStates) { // Don't notify clients or update physics while capturing blockstates + // Modularize client and physic updates + notifyAndUpdatePhysics(blockposition, chunk, block1, block, i, sand); + } + // CraftBukkit end + + return true; + } + } + } + + public void notifyAndUpdatePhysics(BlockPosition blockposition, Chunk chunk, Block oldBlock, Block newBlock, int flag) { + notifyAndUpdatePhysics(blockposition, chunk, oldBlock, newBlock, flag, false); + } + + // CraftBukkit start - Split off from original setTypeAndData(int i, int j, int k, Block block, int l, int i1) method in order to directly send client and physic updates + public void notifyAndUpdatePhysics(BlockPosition blockposition, Chunk chunk, Block oldBlock, Block newBlock, int flag, boolean sand) { + if ((flag & 2) != 0 && (chunk == null || chunk.isReady())) { // allow chunk to be null here as chunk.isReady() is false when we send our notification during block placement + notify(blockposition); + } + if ((flag & 1) != 0) { + if (!sand) { + update(blockposition, oldBlock); + if (newBlock.isComplexRedstone()) { + updateAdjacentComparators(blockposition, newBlock); + } + } else { + d(blockposition.getX(), blockposition.getY() + 1, blockposition.getZ(), oldBlock, blockposition); + } + } + } + + public boolean setAir(BlockPosition blockposition) { + return this.setTypeAndData(blockposition, Blocks.AIR.getBlockData(), 3); + } + + public boolean setAir(BlockPosition blockposition, boolean flag) { + IBlockData iblockdata = this.getType(blockposition); + Block block = iblockdata.getBlock(); + + if (block.getMaterial() == Material.AIR) { + return false; + } else { + this.triggerEffect(2001, blockposition, Block.getCombinedId(iblockdata)); + if (flag) { + block.b(this, blockposition, iblockdata, 0); + } + + return this.setTypeAndData(blockposition, Blocks.AIR.getBlockData(), 3); + } + } + + public boolean setTypeUpdate(BlockPosition blockposition, IBlockData iblockdata) { + return this.setTypeAndData(blockposition, iblockdata, 3); + } + + public void notify(BlockPosition blockposition) { + this.notify(blockposition.getX(), blockposition.getY(), blockposition.getZ()); + } + + // Azurite - Add notify without block position usage + public void notify(int x, int y, int z) { + for (IWorldAccess iWorldAccess : this.u) { + iWorldAccess.a(x, y, z); + } + } + + public void update(BlockPosition blockposition, Block block) { + // CraftBukkit start + if (populating) { + return; + } + // CraftBukkit end + applyPhysics(blockposition, block); + } + + public void a(int i, int j, int k, int l) { + int i1; + + if (k > l) { + i1 = l; + l = k; + k = i1; + } + + if (!worldProvider.o()) { + for (i1 = k; i1 <= l; ++i1) { + updateLight(EnumSkyBlock.SKY, i, i1, j); // PaperSpigot - Asynchronous lighting updates + } + } + + this.b(i, k, j, i, l, j); + } + + public void b(BlockPosition blockposition, BlockPosition blockposition1) { + this.b(blockposition.getX(), blockposition.getY(), blockposition.getZ(), blockposition1.getX(), blockposition1.getY(), blockposition1.getZ()); + } + + public void b(int i, int j, int k, int l, int i1, int j1) { + for (IWorldAccess iWorldAccess : this.u) { + iWorldAccess.a(i, j, k, l, i1, j1); + } + } + + public void a(int x, int y, int z, Block block, EnumDirection enumdirection) { + BlockPosition source = new BlockPosition(x, y, z); + if (enumdirection != EnumDirection.WEST) + d(x - 1, y, z, block, source); + if (enumdirection != EnumDirection.EAST) + d(x + 1, y, z, block, source); + if (enumdirection != EnumDirection.DOWN) + d(x, y - 1, z, block, source); + if (enumdirection != EnumDirection.UP) + d(x, y + 1, z, block, source); + if (enumdirection != EnumDirection.NORTH) + d(x, y, z - 1, block, source); + if (enumdirection != EnumDirection.SOUTH) + d(x, y, z + 1, block, source); + } + + public void d(int x, int y, int z, Block block, EnumDirection enumdirection) { + a(x, y, z, block, enumdirection); + } + + public void a(BlockPosition blockposition, Block block, EnumDirection enumdirection) { + a(blockposition.getX(), blockposition.getY(), blockposition.getZ(), block, enumdirection); + } + + public void d(BlockPosition blockposition, Block block) { + d(blockposition.getX(), blockposition.getY(), blockposition.getZ(), block); + } + + public void d(int x, int y, int z, Block block) { + this.d(x, y, z, block, (BlockPosition) null); + } + + // Azurite - Eigencraft redstone support with source param added + public void d(int x, int y, int z, Block block, BlockPosition source) { + Chunk chunk = null; + IBlockData iblockdata = captureTreeGeneration ? getCapturedBlockType(x, y, z) : null; + if (iblockdata == null) { + if (isValidLocation(x, y, z)) { + chunk = getChunkAtWorldCoords(x, z); + iblockdata = chunk.getBlockData(x, y, z); + } else { + return; + } + } + + try { + CraftWorld world = getWorld(); + if (AzuriteConfig.fireBlockPhysicsEvent.getValue() && world != null + && (AzuriteConfig.fireRedstonePhysicsEvent.getValue() || !(block instanceof BlockRedstoneWire || block instanceof BlockRedstoneTorch || block instanceof BlockRepeater)) + && (AzuriteConfig.fireSandPhysicsEvent.getValue() || !(block instanceof BlockFalling))) { + BlockPhysicsEvent event = new BlockPhysicsEvent(world.getBlockAt(x, y, z), CraftMagicNumbers.getId(block)); + this.getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { + return; + } + } + iblockdata.getBlock().doChunkPhysics(this, chunk, new BlockPosition(x, y, z), iblockdata, block, source); + } catch (StackOverflowError stackoverflowerror) { // Spigot Start + haveWeSilencedAPhysicsCrash = true; + blockLocation = x + ", " + y + ", " + z; // Spigot End + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.a(throwable, "Exception while updating neighbours"); + CrashReportSystemDetails crashreportsystemdetails = crashreport.a("Block being updated"); + + crashreportsystemdetails.a("Source block type", new Callable() { + public String a() { + try { + return String.format("ID #%d (%s // %s)", Block.getId(block), + block.a(), block.getClass().getCanonicalName()); + } catch (Throwable throwable) { + return "ID #" + Block.getId(block); + } + } + + public String call() { + return this.a(); + } + }); + CrashReportSystemDetails.a(crashreportsystemdetails, null, iblockdata); + throw new ReportedException(crashreport); + } + } + + public boolean a(BlockPosition blockposition, Block block) { + return false; + } + + public boolean i(BlockPosition blockposition) { + return i(blockposition.getX(), blockposition.getY(), blockposition.getZ()); + } + + public boolean j(BlockPosition blockposition) { + int x = blockposition.getX(), y = blockposition.getY(), z = blockposition.getZ(); + if (y >= a) { + return this.i(x, y, z); + } else { + int y1 = a; + + if (!this.i(x, y1, z)) { + return false; + } else { + for (y1 -= 1; y1 > y; y1 -= 1) { + Block block = this.getType(x, y1, z).getBlock(); + + if (block.p() > 0 && !block.getMaterial().isLiquid()) { + return false; + } + } + + return true; + } + } + } + + public int k(int x, int y, int z) { + if (y < 0) { + return 0; + } else { + if (y >= 256) + y = 255; + Chunk chunk = getChunkIfLoaded(x >> 4, z >> 4); // Vortex + return chunk != null ? chunk.a(x, y, z, 0) : 0; + } + } + + public int k(BlockPosition blockposition) { + return k(blockposition.getX(), blockposition.getY(), blockposition.getZ()); + } + + public int c(BlockPosition blockposition, boolean flag) { + return c(blockposition.getX(), blockposition.getY(), blockposition.getZ(), flag); + } + + public BlockPosition getHighestBlockYAt(BlockPosition blockposition) { + return getHighestBlockYAt(blockposition.getX(), blockposition.getZ()); + } + + public BlockPosition getHighestBlockYAt(int x, int z) { + int i = 0; + if (x >= -30000000 && z >= -30000000 && x < 30000000 && z < 30000000) { + Chunk chunk = getChunkIfLoaded(x >> 4, z >> 4); + if (chunk != null) { + i = chunk.b(x & 15, z & 15); + } + } else { + i = this.F() + 1; + } + + return new BlockPosition(x, i, z); + } + + public int getHighestBlockYAt(int x, int z, boolean chunkAlreadyLoaded) { // Vortex - Optimized chunks light updates + if (x >= -30000000 && z >= -30000000 && x < 30000000 && z < 30000000) { + if (!chunkAlreadyLoaded && !chunkProvider.isChunkLoaded(x >> 4, z >> 4)) { + return 0; + } else { + return getChunkAt(x >> 4, z >> 4).b(x & 15, z & 15); + } + } else { + return F() + 1; + } + } + + public boolean areChunksLoaded(int x, int y, int z, int i) { + return isAreaLoaded(x - i, y - i, z - i, x + i, y + i, z + i, true); + } + + public int b(int i, int j) { + return b(i, j, false); + } + + public int b(int i, int j, boolean chunkAlreadyLoaded) { // Vortex - Optimized chunks light updates + if (i >= -30000000 && j >= -30000000 && i < 30000000 && j < 30000000) { + if (!chunkAlreadyLoaded && !chunkProvider.isChunkLoaded(i >> 4, j >> 4)) { + return 0; + } else { + return getChunkAt(i >> 4, j >> 4).v(); + } + } else { + return this.F() + 1; + } + } + + public int b(EnumSkyBlock enumskyblock, BlockPosition blockposition) { + return b(enumskyblock, blockposition.getX(), blockposition.getY(), blockposition.getZ()); + } + + public int b(EnumSkyBlock enumskyblock, int x, int y, int z) { + if (y < 0) + y = 0; + if (!this.isLoaded(x, y, z)) { + return enumskyblock.c; + } else { + return getChunkAtWorldCoords(x, z).getBrightness(enumskyblock, x, y, z); + } + } + + public void a(EnumSkyBlock enumskyblock, BlockPosition blockposition, int i) { + if (isLoaded(blockposition)) { + getChunkAtWorldCoords(blockposition).a(enumskyblock, blockposition, i); + this.n(blockposition); + } + } + + public void n(BlockPosition blockposition) { + for (IWorldAccess iWorldAccess : this.u) { + iWorldAccess.b(blockposition); + } + } + + public float o(BlockPosition blockposition) { + return o(blockposition.getX(), blockposition.getY(), blockposition.getZ()); + } + + public float o(int x, int y, int z) { + return worldProvider.p()[getLightLevel(x, y, z)]; + } + + // Spigot start + public IBlockData getType(BlockPosition blockposition) { + return getType(blockposition, true); + } + + public IBlockData getType(BlockPosition blockposition, boolean useCaptured) { + // CraftBukkit start - tree generation + if (captureTreeGeneration && useCaptured) { + IBlockData previous = getCapturedBlockType(blockposition.getX(), blockposition.getY(), blockposition.getZ()); + if (previous != null) + return previous; + } + // CraftBukkit end + if (!isValidLocation(blockposition)) { + return Blocks.AIR.getBlockData(); + } else { + return getChunkAtWorldCoords(blockposition).getBlockData(blockposition); + } + } + + public IBlockData getType(int x, int y, int z) { + return getType(x, y, z, true); + } + + public IBlockData getType(int x, int y, int z, boolean useCaptured) { + if (captureTreeGeneration && useCaptured) { + IBlockData previous = getCapturedBlockType(x, y, z); + if (previous != null) + return previous; + } + if (!isValidLocation(x, y, z)) { + return Blocks.AIR.getBlockData(); + } else { + return getChunkAtWorldCoords(x, z).getBlockData(x, y, z); + } + } + + public Chunk getChunkAtWorldCoords(int x, int z) { + return getChunkAt(x >> 4, z >> 4); + } + + public boolean w() { + return this.I < 4; + } + + public MovingObjectPosition rayTrace(Vec3D vec3d, Vec3D vec3d1) { + return this.rayTrace(vec3d, vec3d1, false, false, false); + } + + public MovingObjectPosition rayTrace(Vec3D vec3d, Vec3D vec3d1, boolean flag) { + return this.rayTrace(vec3d, vec3d1, flag, false, false); + } + + public MovingObjectPosition rayTrace(Vec3D vec3d, Vec3D vec3d1, boolean flag, boolean flag1, boolean flag2) { + if (!Double.isNaN(vec3d.a) && !Double.isNaN(vec3d.b) && !Double.isNaN(vec3d.c)) { + if (!Double.isNaN(vec3d1.a) && !Double.isNaN(vec3d1.b) && !Double.isNaN(vec3d1.c)) { + int i = MathHelper.floor(vec3d1.a); + int j = MathHelper.floor(vec3d1.b); + int k = MathHelper.floor(vec3d1.c); + int l = MathHelper.floor(vec3d.a); + int i1 = MathHelper.floor(vec3d.b); + int j1 = MathHelper.floor(vec3d.c); + BlockPosition blockposition = new BlockPosition(l, i1, j1); + IBlockData iblockdata = getType(blockposition); + Block block = iblockdata.getBlock(); + if ((!flag1 || block.a(this, blockposition, iblockdata) != null) && block.a(iblockdata, flag)) { + MovingObjectPosition movingobjectposition = block.a(this, blockposition, vec3d, vec3d1); + if (movingobjectposition != null) + return movingobjectposition; + } + MovingObjectPosition movingobjectposition1 = null; + int k1 = 200; + while (k1-- >= 0) { + EnumDirection enumdirection; + if (Double.isNaN(vec3d.a) || Double.isNaN(vec3d.b) || Double.isNaN(vec3d.c)) + return null; + if (l == i && i1 == j && j1 == k) + return flag2 ? movingobjectposition1 : null; + boolean flag3 = true; + boolean flag4 = true; + boolean flag5 = true; + double d0 = 999.0D; + double d1 = 999.0D; + double d2 = 999.0D; + if (i > l) { + d0 = l + 1.0D; + } else if (i < l) { + d0 = l + 0.0D; + } else { + flag3 = false; + } + if (j > i1) { + d1 = i1 + 1.0D; + } else if (j < i1) { + d1 = i1 + 0.0D; + } else { + flag4 = false; + } + if (k > j1) { + d2 = j1 + 1.0D; + } else if (k < j1) { + d2 = j1 + 0.0D; + } else { + flag5 = false; + } + double d3 = 999.0D; + double d4 = 999.0D; + double d5 = 999.0D; + double d6 = vec3d1.a - vec3d.a; + double d7 = vec3d1.b - vec3d.b; + double d8 = vec3d1.c - vec3d.c; + if (flag3) + d3 = (d0 - vec3d.a) / d6; + if (flag4) + d4 = (d1 - vec3d.b) / d7; + if (flag5) + d5 = (d2 - vec3d.c) / d8; + if (d3 == -0.0D) + d3 = -1.0E-4D; + if (d4 == -0.0D) + d4 = -1.0E-4D; + if (d5 == -0.0D) + d5 = -1.0E-4D; + if (d3 < d4 && d3 < d5) { + enumdirection = (i > l) ? EnumDirection.WEST : EnumDirection.EAST; + vec3d = new Vec3D(d0, vec3d.b + d7 * d3, vec3d.c + d8 * d3); + } else if (d4 < d5) { + enumdirection = (j > i1) ? EnumDirection.DOWN : EnumDirection.UP; + vec3d = new Vec3D(vec3d.a + d6 * d4, d1, vec3d.c + d8 * d4); + } else { + enumdirection = (k > j1) ? EnumDirection.NORTH : EnumDirection.SOUTH; + vec3d = new Vec3D(vec3d.a + d6 * d5, vec3d.b + d7 * d5, d2); + } + l = MathHelper.floor(vec3d.a) - ((enumdirection == EnumDirection.EAST) ? 1 : 0); + i1 = MathHelper.floor(vec3d.b) - ((enumdirection == EnumDirection.UP) ? 1 : 0); + j1 = MathHelper.floor(vec3d.c) - ((enumdirection == EnumDirection.SOUTH) ? 1 : 0); + blockposition = new BlockPosition(l, i1, j1); + IBlockData iblockdata1 = getType(blockposition); + Block block1 = iblockdata1.getBlock(); + if (!flag1 || block1.a(this, blockposition, iblockdata1) != null) { + if (block1.a(iblockdata1, flag)) { + MovingObjectPosition movingobjectposition2 = block1.a(this, blockposition, vec3d, vec3d1); + if (movingobjectposition2 != null) + return movingobjectposition2; + continue; + } + movingobjectposition1 = new MovingObjectPosition(MovingObjectPosition.EnumMovingObjectType.MISS, vec3d, enumdirection, blockposition); + } + } + return flag2 ? movingobjectposition1 : null; + } + return null; + } + return null; + } + + // Azurite - better method to check for phase + public boolean isThroughBlock(Vec3D start, Vec3D end, Collection toIgnore) { + if (!Double.isNaN(start.a) && !Double.isNaN(start.b) && !Double.isNaN(start.c)) { + if (!Double.isNaN(end.a) && !Double.isNaN(end.b) && !Double.isNaN(end.c)) { + boolean chestsAndAnvil = AzuriteConfig.playerPhaseChestsAndAnvils.getValue(); + + int endX = MathHelper.floor(end.a); + int endY = MathHelper.floor(end.b); + int endZ = MathHelper.floor(end.c); + int x = MathHelper.floor(start.a); + int y = MathHelper.floor(start.b); + int z = MathHelper.floor(start.c); + + MovingObjectPosition movingobjectposition1 = null; + int k1 = 200; + outer: + while (k1-- >= 0) { + EnumDirection enumdirection; + if (Double.isNaN(start.a) || Double.isNaN(start.b) || Double.isNaN(start.c)) + return false; + if (x == endX && y == endY && z == endZ) + return false; + boolean flag3 = true; + boolean flag4 = true; + boolean flag5 = true; + double d0 = 999.0D; + double d1 = 999.0D; + double d2 = 999.0D; + if (endX > x) { + d0 = x + 1.0D; + } else if (endX < x) { + d0 = x + 0.0D; + } else { + flag3 = false; + } + if (endY > y) { + d1 = y + 1.0D; + } else if (endY < y) { + d1 = y + 0.0D; + } else { + flag4 = false; + } + if (endZ > z) { + d2 = z + 1.0D; + } else if (endZ < z) { + d2 = z + 0.0D; + } else { + flag5 = false; + } + double d3 = 999.0D; + double d4 = 999.0D; + double d5 = 999.0D; + double d6 = end.a - start.a; + double d7 = end.b - start.b; + double d8 = end.c - start.c; + if (flag3) + d3 = (d0 - start.a) / d6; + if (flag4) + d4 = (d1 - start.b) / d7; + if (flag5) + d5 = (d2 - start.c) / d8; + if (d3 == -0.0D) + d3 = -1.0E-4D; + if (d4 == -0.0D) + d4 = -1.0E-4D; + if (d5 == -0.0D) + d5 = -1.0E-4D; + if (d3 < d4 && d3 < d5) { + enumdirection = (endX > x) ? EnumDirection.WEST : EnumDirection.EAST; + start = new Vec3D(d0, start.b + d7 * d3, start.c + d8 * d3); + } else if (d4 < d5) { + enumdirection = (endY > y) ? EnumDirection.DOWN : EnumDirection.UP; + start = new Vec3D(start.a + d6 * d4, d1, start.c + d8 * d4); + } else { + enumdirection = (endZ > z) ? EnumDirection.NORTH : EnumDirection.SOUTH; + start = new Vec3D(start.a + d6 * d5, start.b + d7 * d5, d2); + } + x = MathHelper.floor(start.a) - ((enumdirection == EnumDirection.EAST) ? 1 : 0); + y = MathHelper.floor(start.b) - ((enumdirection == EnumDirection.UP) ? 1 : 0); + z = MathHelper.floor(start.c) - ((enumdirection == EnumDirection.SOUTH) ? 1 : 0); + + for (BlockPosition ignore : toIgnore) { + if (ignore.getX() == x && ignore.getY() == y && ignore.getZ() == z) { + continue outer; + } + } + + BlockPosition blockposition = new BlockPosition(x, y, z); + IBlockData iblockdata1 = getType(blockposition); + Block block1 = iblockdata1.getBlock(); + + if (!chestsAndAnvil && (block1 instanceof BlockChest || block1 instanceof BlockAnvil)) { + continue; + } + + // Beanes - ignore pane blocks because they don't have raytrace properly implemented, cba implementing it properly + if (block1 instanceof BlockThin || block1 instanceof BlockCauldron || block1 instanceof BlockFence) { + continue; + } + + if (block1.a(this, blockposition, iblockdata1) != null) { + if (block1.a(iblockdata1, false)) { + MovingObjectPosition movingobjectposition2 = block1.a(this, blockposition, start, end); + if (movingobjectposition2 != null) { + return true; + } + } + } + } + return false; + } + return false; + } + return false; + } + + public MovingObjectPosition rayTracePearls(Vec3D vec3d, Vec3D vec3d1) { + return rayTracePearls(vec3d, vec3d1, false, false, false); + } + + public MovingObjectPosition rayTracePearls(Vec3D vec3d, Vec3D vec3d1, boolean flag, boolean flag1, boolean flag2) { + if (!Double.isNaN(vec3d.a) && !Double.isNaN(vec3d.b) && !Double.isNaN(vec3d.c)) { + if (!Double.isNaN(vec3d1.a) && !Double.isNaN(vec3d1.b) && !Double.isNaN(vec3d1.c)) { + int i = MathHelper.floor(vec3d1.a); + int j = MathHelper.floor(vec3d1.b); + int k = MathHelper.floor(vec3d1.c); + int l = MathHelper.floor(vec3d.a); + int i1 = MathHelper.floor(vec3d.b); + int j1 = MathHelper.floor(vec3d.c); + BlockPosition blockposition = new BlockPosition(l, i1, j1); + IBlockData iblockdata = getType(blockposition); + Block block = iblockdata.getBlock(); + if ((!flag1 || block.a(this, blockposition, iblockdata) != null) && !cancelChecksFor(l, i1, j1, block) && block.a(iblockdata, flag)) { + MovingObjectPosition movingobjectposition = block.a(this, blockposition, vec3d, vec3d1); + if (movingobjectposition != null) + return movingobjectposition; + } + MovingObjectPosition movingobjectposition1 = null; + int k1 = 200; + while (k1-- >= 0) { + EnumDirection enumdirection; + if (Double.isNaN(vec3d.a) || Double.isNaN(vec3d.b) || Double.isNaN(vec3d.c)) + return null; + if (l == i && i1 == j && j1 == k) + return flag2 ? movingobjectposition1 : null; + boolean flag3 = true; + boolean flag4 = true; + boolean flag5 = true; + double d0 = 999.0D; + double d1 = 999.0D; + double d2 = 999.0D; + if (i > l) { + d0 = l + 1.0D; + } else if (i < l) { + d0 = l + 0.0D; + } else { + flag3 = false; + } + if (j > i1) { + d1 = i1 + 1.0D; + } else if (j < i1) { + d1 = i1 + 0.0D; + } else { + flag4 = false; + } + if (k > j1) { + d2 = j1 + 1.0D; + } else if (k < j1) { + d2 = j1 + 0.0D; + } else { + flag5 = false; + } + double d3 = 999.0D; + double d4 = 999.0D; + double d5 = 999.0D; + double d6 = vec3d1.a - vec3d.a; + double d7 = vec3d1.b - vec3d.b; + double d8 = vec3d1.c - vec3d.c; + if (flag3) + d3 = (d0 - vec3d.a) / d6; + if (flag4) + d4 = (d1 - vec3d.b) / d7; + if (flag5) + d5 = (d2 - vec3d.c) / d8; + if (d3 == -0.0D) + d3 = -1.0E-4D; + if (d4 == -0.0D) + d4 = -1.0E-4D; + if (d5 == -0.0D) + d5 = -1.0E-4D; + if (d3 < d4 && d3 < d5) { + enumdirection = (i > l) ? EnumDirection.WEST : EnumDirection.EAST; + vec3d = new Vec3D(d0, vec3d.b + d7 * d3, vec3d.c + d8 * d3); + } else if (d4 < d5) { + enumdirection = (j > i1) ? EnumDirection.DOWN : EnumDirection.UP; + vec3d = new Vec3D(vec3d.a + d6 * d4, d1, vec3d.c + d8 * d4); + } else { + enumdirection = (k > j1) ? EnumDirection.NORTH : EnumDirection.SOUTH; + vec3d = new Vec3D(vec3d.a + d6 * d5, vec3d.b + d7 * d5, d2); + } + l = MathHelper.floor(vec3d.a) - ((enumdirection == EnumDirection.EAST) ? 1 : 0); + i1 = MathHelper.floor(vec3d.b) - ((enumdirection == EnumDirection.UP) ? 1 : 0); + j1 = MathHelper.floor(vec3d.c) - ((enumdirection == EnumDirection.SOUTH) ? 1 : 0); + blockposition = new BlockPosition(l, i1, j1); + IBlockData iblockdata1 = getType(blockposition); + Block block1 = iblockdata1.getBlock(); + + if (cancelChecksFor(l, i1, j1, block1)) { + continue; + } + + if (!flag1 || block1.a(this, blockposition, iblockdata1) != null) { + if (block1.a(iblockdata1, flag)) { + MovingObjectPosition movingobjectposition2 = block1.a(this, blockposition, vec3d, vec3d1); + if (movingobjectposition2 != null) { + return movingobjectposition2; + } + continue; + } + movingobjectposition1 = new MovingObjectPosition(MovingObjectPosition.EnumMovingObjectType.MISS, vec3d, enumdirection, blockposition); + } + } + return flag2 ? movingobjectposition1 : null; + } + return null; + } + return null; + } + + private boolean cancelChecksFor(int x, int y, int z, Block nmsBlock) { + org.bukkit.block.Block bukkitBlock = getWorld().getBlockAt(x, y, z); + return (PearlConfig.pearlThruPlants.getValue() && PearlUtil.isPlantBukkit(bukkitBlock.getType())) || + (PearlConfig.pearlThruFence.getValue() && nmsBlock instanceof BlockFenceGate && PearlUtil.isOpenFenceGate(bukkitBlock)) || + (PearlConfig.pearlThruWeb.getValue() && bukkitBlock.getType() == org.bukkit.Material.WEB) || + (PearlConfig.pearlThruString.getValue() && bukkitBlock.getType() == org.bukkit.Material.TRIPWIRE); + } + + public void interceptSounds() { + interceptSounds = true; + } + + public void sendInterceptedSounds() { + for (Runnable r : interceptedSounds) { + r.run(); + } + interceptedSounds.clear(); + interceptSounds = false; + } + + public void clearInterceptedSounds() { + interceptedSounds.clear(); + interceptSounds = false; + } + + public void makeSound(double d0, double d1, double d2, String s, float f, float f1) { + if (interceptSounds && org.bukkit.Bukkit.isPrimaryThread()) { + interceptedSounds.add(() -> { + for (IWorldAccess w : u) { + w.a(s, d0, d1, d2, f, f1); + } + }); + return; + } + // Vortex end + for (IWorldAccess w : u) { + w.a(s, d0, d1, d2, f, f1); + } + } + + public void makeSound(Entity entity, String s, float f, float f1) { + for (IWorldAccess anU : this.u) + anU.a(s, entity.locX, entity.locY, entity.locZ, f, f1); + } + + public void makeSound(Entity entity, String s, float f, float f1, boolean self) { + for (IWorldAccess anU : this.u) + anU.a(s, entity.locX, entity.locY, entity.locZ, f, f1, self); // Beanes - add self variable + } + + public void a(EntityHuman entityhuman, String s, float f, float f1) { + for (IWorldAccess iWorldAccess : this.u) + iWorldAccess.a(entityhuman, s, entityhuman.locX, entityhuman.locY, entityhuman.locZ, f, f1); + } + + public void a(BlockPosition blockposition, String s) { + for (IWorldAccess iWorldAccess : this.u) + iWorldAccess.a(s, blockposition); + } + + public void addParticle(EnumParticle enumparticle, double d0, double d1, double d2, double d3, double d4, double d5, int... aint) { + this.a(enumparticle.c(), enumparticle.e(), d0, d1, d2, d3, d4, d5, aint); + } + + private void a(int i, boolean flag, double d0, double d1, double d2, double d3, double d4, double d5, int... aint) { + for (IWorldAccess iWorldAccess : this.u) { + iWorldAccess.a(i, flag, d0, d1, d2, d3, d4, d5, aint); + } + } + + public boolean strikeLightning(Entity entity) { + k.add(entity); + return true; + } + + public boolean addEntity(EntityPlayer entity) { // Vortex - addEntity for players to have less checks + if (entity == null) + return false; + + this.players.add(entity); + this.playerMap.add(entity); + this.everyoneSleeping(); + + this.getChunkAt(MathHelper.floor(entity.locX / 16.0D), MathHelper.floor(entity.locZ / 16.0D)).a(entity); + this.entityList.add(entity); + this.a(entity); + return true; + } + + public boolean addEntity(EntityFallingBlock entity) { // Vortex - addEntity for sand to have less checks + if (entity == null) + return false; + int i = MathHelper.floor(entity.locX / 16.0D); + int j = MathHelper.floor(entity.locZ / 16.0D); + Chunk chunk = getChunkIfLoaded(i, j); + + if (!entity.attachedToPlayer && chunk == null) { + entity.dead = true; + return false; + } else { + chunk.addCannonEntity(entity); + this.entityList.add(entity); + this.a(entity); + return true; + } + } + + public boolean addEntity(EntityTNTPrimed entity) { // Vortex - addEntity for tnt to have less checks + if (entity == null) + return false; + // CraftBukkit end + int i = MathHelper.floor(entity.locX / 16.0D); + int j = MathHelper.floor(entity.locZ / 16.0D); + + Chunk chunk = getChunkIfLoaded(i, j); + + if (!entity.attachedToPlayer && chunk == null) { + entity.dead = true; + return false; + } else { + chunk.addCannonEntity(entity); + this.entityList.add(entity); + this.a(entity); + return true; + } + } + + public boolean addEntity(Entity entity) { + // CraftBukkit start - Used for entities other than creatures + return addEntity(entity, SpawnReason.DEFAULT); + } + + public boolean addEntity(Entity entity, CreatureSpawnEvent.SpawnReason spawnReason) { + AsyncCatcher.catchOp("entity add"); + if (entity == null) + return false; + if (entity.spawnReason == null) entity.spawnReason = spawnReason; // Azurite + int i = MathHelper.floor(entity.locX / 16.0D); + int j = MathHelper.floor(entity.locZ / 16.0D); + boolean flag = entity.attachedToPlayer; + if (entity instanceof EntityHuman) + flag = true; + Cancellable event = null; + if (entity instanceof EntityLiving && !(entity instanceof EntityPlayer)) { + boolean isAnimal = (entity instanceof EntityAnimal || entity instanceof EntityWaterAnimal || entity instanceof EntityGolem); + boolean isMonster = (entity instanceof EntityMonster || entity instanceof EntityGhast || entity instanceof EntitySlime); + if (spawnReason != CreatureSpawnEvent.SpawnReason.CUSTOM && ((isAnimal && !allowAnimals) || (isMonster && !allowMonsters))) { + entity.dead = true; + return false; + } + event = CraftEventFactory.callCreatureSpawnEvent((EntityLiving) entity, spawnReason); + } else if (entity instanceof EntityItem) { + event = CraftEventFactory.callItemSpawnEvent((EntityItem) entity); + } else if (entity.getBukkitEntity() instanceof org.bukkit.entity.Projectile) { + event = CraftEventFactory.callProjectileLaunchEvent(entity); + } else if (entity instanceof EntityExperienceOrb) { + EntityExperienceOrb xp = (EntityExperienceOrb) entity; + double radius = this.spigotConfig.expMerge; + if (radius > 0.0D) { + List entities = getEntities(entity, entity.getBoundingBox().grow(radius, radius, radius)); + for (Entity e : entities) { + if (e instanceof EntityExperienceOrb) { + EntityExperienceOrb loopItem = (EntityExperienceOrb) e; + if (!loopItem.dead) { + xp.value += loopItem.value; + loopItem.die(); + } + } + } + } + } + if (event != null && (event.isCancelled() || entity.dead)) { + entity.dead = true; + return false; + } + Chunk chunk = getChunkIfLoaded(i, j); + if (!flag && chunk == null) { + entity.dead = true; + return false; + } + if (entity instanceof EntityHuman) { + EntityHuman entityhuman = (EntityHuman) entity; + players.add(entityhuman); + everyoneSleeping(); + } + (chunk == null ? getChunkAt(i, j) : chunk).a(entity); + entityList.add(entity); + a(entity); + return true; + } + + protected void a(Entity entity) { + for (IWorldAccess iWorldAccess : u) { + iWorldAccess.a(entity); + } + + entity.valid = true; // CraftBukkit + } + + protected void b(Entity entity) { + for (IWorldAccess iWorldAccess : u) { + iWorldAccess.b(entity); + } + + entity.valid = false; // CraftBukkit + } + + public void kill(Entity entity) { + if (entity.passenger != null) { + entity.passenger.mount(null); + } + + if (entity.vehicle != null) { + entity.mount(null); + } + + entity.die(); + if (entity instanceof EntityHuman) { + this.players.remove(entity); + this.playerMap.remove((EntityPlayer) entity); + // Spigot start + for (Object o : worldMaps.c) { + if (o instanceof WorldMap) { + WorldMap map = (WorldMap) o; + map.i.remove(entity); + map.g.removeIf(worldMapHumanTracker -> worldMapHumanTracker.trackee == entity); + } + } + // Spigot end + this.everyoneSleeping(); + this.b(entity); + } + + } + + public void removeEntity(Entity entity) { + entity.die(); + if (entity instanceof EntityHuman) { + players.remove(entity); + playerMap.remove((EntityPlayer) entity); + everyoneSleeping(); + } + + if (!guardEntityList) { // Spigot - It will get removed after the tick if we are ticking + int i = entity.ae; + int j = entity.ag; + + if (entity.ad) { + Chunk chunk = getChunkIfLoaded(i, j); + if (chunk != null) chunk.b(entity); // Paper + ((PaperWorldEntityList) entityList).updateEntityCount(entity, -1); + } + + // CraftBukkit start - Decrement loop variable field if we've already ticked this entity + int index = this.entityList.indexOf(entity); + if (index != -1) { + if (index <= this.tickPosition) { + this.tickPosition--; + } + this.entityList.remove(index); + } + // CraftBukkit end + } // Spigot + this.b(entity); + } + + public void addIWorldAccess(IWorldAccess iworldaccess) { + this.u.add(iworldaccess); + } + + public List getCubes(Entity entity, AxisAlignedBB axisalignedbb) { + List arraylist = Lists.newArrayList(); + int i = MathHelper.floor(axisalignedbb.a); + int j = MathHelper.floor(axisalignedbb.d + 1.0D); + int k = MathHelper.floor(axisalignedbb.b); + int l = MathHelper.floor(axisalignedbb.e + 1.0D); + int i1 = MathHelper.floor(axisalignedbb.c); + int j1 = MathHelper.floor(axisalignedbb.f + 1.0D); + WorldBorder worldborder = this.getWorldBorder(); + boolean flag = entity.aT(); + boolean flag1 = this.a(worldborder, entity); + + // Spigot start + int ystart = Math.max((k - 1), 0); + BlockPosition.MutableBlockPosition pos = new BlockPosition.MutableBlockPosition(); + for (int chunkx = (i >> 4); chunkx <= ((j - 1) >> 4); chunkx++) { + int cx = chunkx << 4; + for (int chunkz = (i1 >> 4); chunkz <= ((j1 - 1) >> 4); chunkz++) { + Chunk chunk = entity.loadChunks && chunkx == Entity.lastChunkX && chunkz == Entity.lastChunkZ + ? Entity.lastChunk + : entity.loadChunks ? ((ChunkProviderServer) entity.world.chunkProvider).getChunkAt(chunkx, chunkz) : getChunkIfLoaded(chunkx, chunkz); + + if (chunk == null) { + entity.inUnloadedChunk = true; // PaperSpigot - Remove entities in unloaded chunks + continue; + } + + int cz = chunkz << 4; + // Compute ranges within chunk + int xstart = Math.max(i, cx); + int xend = Math.min(j, (cx + 16)); + int zstart = Math.max(i1, cz); + int zend = Math.min(j1, (cz + 16)); + // Loop through blocks within chunk + for (int x = xstart; x < xend; x++) { + for (int z = zstart; z < zend; z++) { + for (int y = ystart; y < l; y++) { + if (flag && flag1) { + entity.h(false); + } else if (!flag && !flag1) { + entity.h(true); + } + + IBlockData block; + if (!this.getWorldBorder().a(x, z) && flag1) { + block = Blocks.STONE.getBlockData(); + } else { + block = chunk.getBlockData(x, y, z); + } + if (block != null) { + // PaperSpigot start - FallingBlocks and TNT collide with specific non-collidable blocks + Block b = block.getBlock(); + if (entity.world.paperSpigotConfig.fallingBlocksCollideWithSigns && (entity instanceof EntityTNTPrimed || entity instanceof EntityFallingBlock) && (b instanceof BlockSign || b instanceof BlockFenceGate || b instanceof BlockTorch || b instanceof BlockButtonAbstract || b instanceof BlockLever || b instanceof BlockTripwireHook || b instanceof BlockTripwire || b instanceof BlockChest || b instanceof BlockSlowSand || b instanceof BlockBed || b instanceof BlockEnderChest || b instanceof BlockEnchantmentTable || b instanceof BlockBrewingStand)) { + AxisAlignedBB aabb = AxisAlignedBB.a(x, y, z, x + 1.0, y + 1.0, z + 1.0); + if (axisalignedbb.b(aabb)) arraylist.add(aabb); + } else { + b.a(this, pos.c(x, y, z), block, axisalignedbb, arraylist, entity); + } + // PaperSpigot end + } + } + } + } + } + } + // Spigot end + + return arraylist; + } + + // Beanes - an optimal isEmpty check, ideally we implement a collide method on each block that doesnt allocate aabbs and adds them to list, but that's a lot of work, so I created a custom list implementation that should help with empty check + public boolean isEmpty(Entity entity, AxisAlignedBB axisalignedbb) { + OptimizedNonEmptyList arraylist = new OptimizedNonEmptyList<>(); + int i = MathHelper.floor(axisalignedbb.a); + int j = MathHelper.floor(axisalignedbb.d + 1.0D); + int k = MathHelper.floor(axisalignedbb.b); + int l = MathHelper.floor(axisalignedbb.e + 1.0D); + int i1 = MathHelper.floor(axisalignedbb.c); + int j1 = MathHelper.floor(axisalignedbb.f + 1.0D); + WorldBorder worldborder = this.getWorldBorder(); + boolean flag = entity.aT(); + boolean flag1 = this.a(worldborder, entity); + + // Spigot start + int ystart = Math.max((k - 1), 0); + BlockPosition.MutableBlockPosition pos = new BlockPosition.MutableBlockPosition(); + for (int chunkx = (i >> 4); chunkx <= ((j - 1) >> 4); chunkx++) { + int cx = chunkx << 4; + for (int chunkz = (i1 >> 4); chunkz <= ((j1 - 1) >> 4); chunkz++) { + Chunk chunk = entity.loadChunks && chunkx == Entity.lastChunkX && chunkz == Entity.lastChunkZ + ? Entity.lastChunk + : entity.loadChunks ? ((ChunkProviderServer) entity.world.chunkProvider).getChunkAt(chunkx, chunkz) : getChunkIfLoaded(chunkx, chunkz); + + if (chunk == null) { + entity.inUnloadedChunk = true; // PaperSpigot - Remove entities in unloaded chunks + continue; + } + + int cz = chunkz << 4; + // Compute ranges within chunk + int xstart = Math.max(i, cx); + int xend = Math.min(j, (cx + 16)); + int zstart = Math.max(i1, cz); + int zend = Math.min(j1, (cz + 16)); + // Loop through blocks within chunk + for (int x = xstart; x < xend; x++) { + for (int z = zstart; z < zend; z++) { + for (int y = ystart; y < l; y++) { + if (flag && flag1) { + entity.h(false); + } else if (!flag && !flag1) { + entity.h(true); + } + + IBlockData block; + if (!this.getWorldBorder().a(x, z) && flag1) { + block = Blocks.STONE.getBlockData(); + } else { + block = chunk.getBlockData(x, y, z); + } + if (block != null) { + // PaperSpigot start - FallingBlocks and TNT collide with specific non-collidable blocks + Block b = block.getBlock(); + if (entity.world.paperSpigotConfig.fallingBlocksCollideWithSigns && (entity instanceof EntityTNTPrimed || entity instanceof EntityFallingBlock) && (b instanceof BlockSign || b instanceof BlockFenceGate || b instanceof BlockTorch || b instanceof BlockButtonAbstract || b instanceof BlockLever || b instanceof BlockTripwireHook || b instanceof BlockTripwire || b instanceof BlockChest || b instanceof BlockSlowSand || b instanceof BlockBed || b instanceof BlockEnderChest || b instanceof BlockEnchantmentTable || b instanceof BlockBrewingStand)) { + AxisAlignedBB aabb = AxisAlignedBB.a(x, y, z, x + 1.0, y + 1.0, z + 1.0); + if (axisalignedbb.b(aabb)) arraylist.add(aabb); + } else { + b.a(this, pos.c(x, y, z), block, axisalignedbb, arraylist, entity); + } + // PaperSpigot end + + // Exit iteration if the list is already filled + if (!arraylist.isEmpty()) { + return false; + } + } + } + } + } + } + } + // Spigot end + + return true; + } + + // Azurite - a stupid but more optimal way for comparing collisions + public List getCollisionBlocks(Entity entity, net.minecraft.server.AxisAlignedBB axisalignedbb) { + List blockPositions = new ArrayList<>(); + List arraylist = new OptimizedNonEmptyList<>(); + int i = MathHelper.floor(axisalignedbb.a); + int j = MathHelper.floor(axisalignedbb.d + 1.0D); + int k = MathHelper.floor(axisalignedbb.b); + int l = MathHelper.floor(axisalignedbb.e + 1.0D); + int i1 = MathHelper.floor(axisalignedbb.c); + int j1 = MathHelper.floor(axisalignedbb.f + 1.0D); + WorldBorder worldborder = this.getWorldBorder(); + boolean flag = entity.aT(); + boolean flag1 = this.a(worldborder, entity); + + boolean chestsAndAnvil = AzuriteConfig.playerPhaseChestsAndAnvils.getValue(); + + // Spigot start + int ystart = Math.max((k - 1), 0); + BlockPosition.MutableBlockPosition pos = new BlockPosition.MutableBlockPosition(); + for (int chunkx = (i >> 4); chunkx <= ((j - 1) >> 4); chunkx++) { + int cx = chunkx << 4; + for (int chunkz = (i1 >> 4); chunkz <= ((j1 - 1) >> 4); chunkz++) { + Chunk chunk = entity.loadChunks && chunkx == Entity.lastChunkX && chunkz == Entity.lastChunkZ + ? Entity.lastChunk + : entity.loadChunks ? ((ChunkProviderServer) entity.world.chunkProvider).getChunkAt(chunkx, chunkz) : getChunkIfLoaded(chunkx, chunkz); + + if (chunk == null) { + entity.inUnloadedChunk = true; // PaperSpigot - Remove entities in unloaded chunks + continue; + } + + int cz = chunkz << 4; + // Compute ranges within chunk + int xstart = Math.max(i, cx); + int xend = Math.min(j, (cx + 16)); + int zstart = Math.max(i1, cz); + int zend = Math.min(j1, (cz + 16)); + // Loop through blocks within chunk + for (int x = xstart; x < xend; x++) { + for (int z = zstart; z < zend; z++) { + for (int y = ystart; y < l; y++) { + if (flag && flag1) { + entity.h(false); + } else if (!flag && !flag1) { + entity.h(true); + } + + IBlockData block; + if (!this.getWorldBorder().a(x, z) && flag1) { + block = Blocks.STONE.getBlockData(); + } else { + block = chunk.getBlockData(x, y, z); + } + if (block != null) { + Block b = block.getBlock(); + + if (!chestsAndAnvil && (b instanceof BlockAnvil || b instanceof BlockChest)) { + continue; + } + + b.a(this, pos.c(x, y, z), block, axisalignedbb, arraylist, entity); + + if (!arraylist.isEmpty()) { + blockPositions.add(new BlockPosition(x, y, z)); + arraylist.clear(); + } + } + } + } + } + } + } + // Spigot end + + return blockPositions; + } + + public boolean a(WorldBorder worldborder, Entity entity) { + double d0 = worldborder.b(); + double d1 = worldborder.c(); + double d2 = worldborder.d(); + double d3 = worldborder.e(); + + if (entity.aT()) { + ++d0; + ++d1; + --d2; + --d3; + } else { + --d0; + --d1; + ++d2; + ++d3; + } + + return entity.locX > d0 && entity.locX < d2 && entity.locZ > d1 && entity.locZ < d3; + } + + public List a(AxisAlignedBB axisalignedbb) { + List arraylist = Lists.newArrayList(); + int i = MathHelper.floor(axisalignedbb.a); + int j = MathHelper.floor(axisalignedbb.d + 1.0D); + int k = MathHelper.floor(axisalignedbb.b); + int l = MathHelper.floor(axisalignedbb.e + 1.0D); + int i1 = MathHelper.floor(axisalignedbb.c); + int j1 = MathHelper.floor(axisalignedbb.f + 1.0D); + BlockPosition.MutableBlockPosition blockposition_mutableblockposition = new BlockPosition.MutableBlockPosition(); + + for (int k1 = i; k1 < j; ++k1) { + for (int l1 = i1; l1 < j1; ++l1) { + if (this.isLoaded(k1, 64, l1)) { + for (int i2 = k - 1; i2 < l; ++i2) { + blockposition_mutableblockposition.c(k1, i2, l1); + IBlockData iblockdata; + + if (k1 >= -30000000 && k1 < 30000000 && l1 >= -30000000 && l1 < 30000000) { + iblockdata = this.getType(blockposition_mutableblockposition); + } else { + iblockdata = Blocks.BEDROCK.getBlockData(); + } + + iblockdata.getBlock().a(this, blockposition_mutableblockposition, iblockdata, axisalignedbb, arraylist, null); + } + } + } + } + + return arraylist; + } + + public int a(float f) { + float f1 = this.c(f); + float f2 = 1.0F - (MathHelper.cos(f1 * 3.1415927F * 2.0F) * 2.0F + 0.5F); + + f2 = MathHelper.a(f2, 0.0F, 1.0F); + f2 = 1.0F - f2; + f2 = (float) ((double) f2 * (1.0D - (double) (this.j(f) * 5.0F) / 16.0D)); + f2 = (float) ((double) f2 * (1.0D - (double) (this.h(f) * 5.0F) / 16.0D)); + f2 = 1.0F - f2; + return (int) (f2 * 11.0F); + } + + public float c(float f) { + return this.worldProvider.a(this.worldData.getDayTime(), f); + } + + public float y() { + return WorldProvider.a[this.worldProvider.a(this.worldData.getDayTime())]; + } + + public float d(float f) { + return c(f) * 3.1415927F * 2.0F; + } + + public BlockPosition q(BlockPosition blockposition) { + return getChunkAtWorldCoords(blockposition).h(blockposition); + } + + public BlockPosition q(int x, int z) { + return getChunkAtWorldCoords(x, z).h(x, z); + } + + public BlockPosition r(int x, int z) { + Chunk chunk = getChunkAtWorldCoords(x, z); + + int y1, y2; + + for (y1 = chunk.g() + 16; y1 >= 0; y1 = y2) { + y2 = y1 - 1; + Material material = chunk.getTypeAbs(x, y2, z).getMaterial(); + + if (material.isSolid() && material != Material.LEAVES) { + break; + } + } + + return new BlockPosition(x, y1, z); + } + + + public BlockPosition r(BlockPosition blockposition) { + return r(blockposition.getX(), blockposition.getZ()); + } + + public void a(BlockPosition blockposition, Block block, int i) { + } + + public void a(BlockPosition blockposition, Block block, int i, int j) { + } + + public void b(BlockPosition blockposition, Block block, int i, int j) { + } + + public void tickEntities() { + int i; + Entity entity; + CrashReport crashreport; + CrashReportSystemDetails crashreportsystemdetails; + + for (i = 0; i < k.size(); ++i) { + entity = k.get(i); + + if (entity == null) { + continue; + } + + try { + ++entity.ticksLived; + entity.t_(); + } catch (Throwable throwable) { + crashreport = CrashReport.a(throwable, "Ticking entity"); + crashreportsystemdetails = crashreport.a("Entity being ticked"); + entity.appendEntityCrashDetails(crashreportsystemdetails); + throw new ReportedException(crashreport); + } + + if (entity.dead) { + k.remove(i--); + } + } + + entityList.removeAll(g); + + int j; + int k; + + Chunk chunk = null; // Vortex - cache chunk + + // Paper start - Set based removal lists + for (Entity en : g) { + j = en.ae; + k = en.ag; + if (en.ad) { + if (chunk == null || !chunk.o() || chunk.locX != j || chunk.locZ != k) + chunk = getChunkIfLoaded(j, k); + if (chunk != null) + chunk.b(en); + } + } + + for (Entity en : g) { + b(en); + } + // Paper end + + g.clear(); + + ActivationRange.activateEntities(this); // Spigot + guardEntityList = true; // Spigot + + Entity lastEntity = null; + for (tickPosition = 0; tickPosition < entityList.size(); tickPosition++) { + entity = entityList.get(tickPosition); + + if (entity.vehicle != null) { + if (!entity.vehicle.dead && entity.vehicle.passenger == entity) { + continue; + } + + entity.vehicle.passenger = null; + entity.vehicle = null; + } + + if (!entity.dead) { + try { + if (lastEntity != null && entity.merge(lastEntity)) { + entity.die(); + lastEntity.potential += entity.potential; + } else { + lastEntity = entity; + g(entity); + } + } catch (Throwable throwable1) { + String msg = "Entity threw exception at " + entity.world.getWorld().getName() + ":" + entity.locX + "," + entity.locY + "," + entity.locZ; + System.err.println(msg); + throwable1.printStackTrace(); + entity.dead = true; + } + } + + if (entity.dead) { + j = entity.ae; + k = entity.ag; + if (entity.ad) { + if (chunk == null || !chunk.o() || chunk.locX != j || chunk.locZ != k) + chunk = getChunkIfLoaded(j, k); + if (chunk != null) + chunk.b(entity); + } + + guardEntityList = false; // Spigot + entityList.remove(tickPosition--); // CraftBukkit - Use field for loop variable + guardEntityList = true; // Spigot + b(entity); + } + } + + Entity.lastChunkX = Entity.lastChunkZ = Integer.MAX_VALUE; + Entity.lastChunk = null; + guardEntityList = false; // Spigot + + if (AzuriteConfig.tickTileEntities.getValue()) { + M = true; + + // CraftBukkit start - From below, clean up tile entities before ticking them + if (!c.isEmpty()) { + // Paper - Use alternate implementation with faster contains + Set toRemove = Collections.newSetFromMap(new IdentityHashMap<>()); + toRemove.addAll(c); + tileEntityList.removeAll(toRemove); + // Paper end + c.clear(); + } + + // CraftBukkit end + Chunk tileChunk = null; + + // Spigot start + int tileTickPosition; + for (tileTickPosition = 0; tileTickPosition < tileEntityList.size(); tileTickPosition++) { // PaperSpigot - Disable tick limiters + TileEntity tileentity = tileEntityList.get(tileTickPosition); + + // Spigot start + if (tileentity == null) { + getServer().getLogger().severe("Spigot has detected a null entity and has removed it, preventing a crash"); + tileEntityList.remove(tileTickPosition--); + continue; + } + // Spigot end + + if (!tileentity.x() && tileentity.t()) { + BlockPosition pos = tileentity.getPosition(); + + // Azurite start + int chunkX = pos.getX() >> 4; + int chunkZ = pos.getZ() >> 4; + boolean loaded; + + if (tileChunk != null && tileChunk.locX == chunkX && tileChunk.locZ == chunkZ) { + loaded = true; + + } else { + tileChunk = getChunkIfLoaded(chunkX, chunkZ); + loaded = tileChunk != null; + } + // Azurite end + + if (loaded && N.a(pos)) { + try { + ((IUpdatePlayerListBox) tileentity).c(); + } catch (Throwable throwable2) { + // PaperSpigot start - Prevent tile entity and entity crashes + String msg = "TileEntity threw exception at " + tileentity.world.getWorld().getName() + ":" + pos.getX() + "," + pos.getY() + "," + pos.getZ(); + System.err.println(msg); + throwable2.printStackTrace(); + getServer().getPluginManager().callEvent(new ServerExceptionEvent(new ServerInternalException(msg, throwable2))); + tileEntityList.remove(tileTickPosition--); + continue; + // PaperSpigot end + } + } + } + + if (tileentity.x()) { + tileEntityList.remove(tileTickPosition--); + BlockPosition position = tileentity.getPosition(); + int chunkX = position.getX() >> 4, chunkZ = position.getZ() >> 4; + if (Utils.isInvalidChunk(chunk, chunkX, chunkZ)) + chunk = getChunkIfLoaded(chunkX, chunkZ); + if (chunk != null) { + chunk.e(position); + } + } + } + + M = false; + + if (!b.isEmpty()) { + for (TileEntity tileentity1 : b) { + if (!tileentity1.x()) { + BlockPosition position = tileentity1.getPosition(); + + int chunkX = position.getX() >> 4, chunkZ = position.getZ() >> 4; + if (Utils.isInvalidChunk(chunk, chunkX, chunkZ)) + chunk = getChunkIfLoaded(chunkX, chunkZ); + + if (chunk != null) { + chunk.a(position, tileentity1); + } + + notify(position); + } + } + + b.clear(); + } + } + } + + public boolean a(TileEntity tileentity) { + if (tileentity instanceof IUpdatePlayerListBox) { + this.tileEntityList.add(tileentity); + } + return true; + } + + public void a(Collection collection) { + if (this.M) { + this.b.addAll(collection); + } else { + + for (TileEntity tileentity : collection) { + if (tileentity instanceof IUpdatePlayerListBox) { + this.tileEntityList.add(tileentity); + } + } + } + + } + + public void g(Entity entity) { + entityJoinedWorld(entity, true); + } + + public void entityJoinedWorld(Entity entity, boolean flag) { + int i = MathHelper.floor(entity.locX); + int j = MathHelper.floor(entity.locZ); + if (!ActivationRange.checkIfActive(entity)) { + entity.ticksLived++; + entity.inactiveTick(); + if (!isChunkLoaded(i, j, true) && ((entity instanceof EntityEnderPearl && this.paperSpigotConfig.removeUnloadedEnderPearls) || (entity instanceof EntityFallingBlock && this.paperSpigotConfig.removeUnloadedFallingBlocks) || (entity instanceof EntityTNTPrimed && this.paperSpigotConfig.removeUnloadedTNTEntities))) { + entity.inUnloadedChunk = true; + entity.die(); + } + } else { + entity.P = entity.locX; + entity.Q = entity.locY; + entity.R = entity.locZ; + entity.lastYaw = entity.yaw; + entity.lastPitch = entity.pitch; + if (flag && entity.ad) { + entity.ticksLived++; + if (entity.vehicle != null) { + entity.ak(); + } else { + entity.t_(); + } + } + if (Double.isNaN(entity.locX) || Double.isInfinite(entity.locX)) + entity.locX = entity.P; + if (Double.isNaN(entity.locY) || Double.isInfinite(entity.locY)) + entity.locY = entity.Q; + if (Double.isNaN(entity.locZ) || Double.isInfinite(entity.locZ)) + entity.locZ = entity.R; + if (Double.isNaN(entity.pitch) || Double.isInfinite(entity.pitch)) + entity.pitch = entity.lastPitch; + if (Double.isNaN(entity.yaw) || Double.isInfinite(entity.yaw)) + entity.yaw = entity.lastYaw; + int k = MathHelper.floor(entity.locX / 16.0D); + int l = MathHelper.floor(entity.locY / 16.0D); + int i1 = MathHelper.floor(entity.locZ / 16.0D); + if (!entity.ad || entity.ae != k || entity.af != l || entity.ag != i1) { + + if (entity.loadChunks) + entity.loadChunks(); + + if (entity.ad) { + Chunk chunk = getChunkIfLoaded(entity.ae, entity.ag); + if (chunk != null) + chunk.a(entity, entity.af); + } + + Chunk chunk = getChunkIfLoaded(k, i1); + if (chunk != null) { + entity.ad = true; + chunk.a(entity); + } else { + entity.ad = false; + } + + } + if (flag && entity.ad && entity.passenger != null) { + if (!entity.passenger.dead && entity.passenger.vehicle == entity) { + g(entity.passenger); + } else { + entity.passenger.vehicle = null; + entity.passenger = null; + } + } + } + } + + public boolean b(AxisAlignedBB axisalignedbb) { + return this.a(axisalignedbb, (Entity) null); + } + + public boolean a(AxisAlignedBB axisalignedbb, Entity entity) { + for (Entity entity1 : getEntities(null, axisalignedbb)) { + // PaperSpigot start - Allow block placement if the placer cannot see the vanished blocker + if (entity instanceof EntityPlayer && entity1 instanceof EntityPlayer) { + if (!((EntityPlayer) entity).getBukkitEntity().canSee(((EntityPlayer) entity1).getBukkitEntity())) { + continue; + } + } + + if (!entity1.dead && entity1.k && entity1 != entity && (entity == null || entity.vehicle != entity1 && entity.passenger != entity1)) { + return false; + } + } + + return true; + } + + public boolean c(AxisAlignedBB axisalignedbb) { + int i = MathHelper.floor(axisalignedbb.a), j = MathHelper.floor(axisalignedbb.d), k = MathHelper.floor(axisalignedbb.b), l = MathHelper.floor(axisalignedbb.e), i1 = MathHelper.floor(axisalignedbb.c), j1 = MathHelper.floor(axisalignedbb.f); + for (int k1 = i; k1 <= j; ++k1) { + for (int l1 = k; l1 <= l; ++l1) { + for (int i2 = i1; i2 <= j1; ++i2) { + if (this.getType(k1, l1, i2).getBlock().getMaterial() != Material.AIR) { + return true; + } + } + } + } + return false; + } + + public boolean containsLiquid(AxisAlignedBB axisalignedbb) { + int i = MathHelper.floor(axisalignedbb.a), j = MathHelper.floor(axisalignedbb.d), k = MathHelper.floor(axisalignedbb.b), l = MathHelper.floor(axisalignedbb.e), i1 = MathHelper.floor(axisalignedbb.c), j1 = MathHelper.floor(axisalignedbb.f); + for (int k1 = i; k1 <= j; ++k1) { + for (int l1 = k; l1 <= l; ++l1) { + for (int i2 = i1; i2 <= j1; ++i2) { + if (getType(k1, l1, i2).getBlock().getMaterial().isLiquid()) + return true; + } + } + } + + return false; + } + + public boolean e(AxisAlignedBB axisalignedbb) { + int i = MathHelper.floor(axisalignedbb.a), j = MathHelper.floor(axisalignedbb.d + 1.0D), k = MathHelper.floor(axisalignedbb.b), l = MathHelper.floor(axisalignedbb.e + 1.0D), i1 = MathHelper.floor(axisalignedbb.c), j1 = MathHelper.floor(axisalignedbb.f + 1.0D); + if (this.isAreaLoaded(i, k, i1, j, l, j1, true)) { + for (int k1 = i; k1 < j; ++k1) { + for (int l1 = k; l1 < l; ++l1) { + for (int i2 = i1; i2 < j1; ++i2) { + Block block = this.getType(k1, l1, i2).getBlock(); + if (block == Blocks.FIRE || block == Blocks.FLOWING_LAVA || block == Blocks.LAVA) { + return true; + } + } + } + } + } + + return false; + } + + public boolean a(AxisAlignedBB axisalignedbb, Material material, Entity entity) { + int i = MathHelper.floor(axisalignedbb.a); + int j = MathHelper.floor(axisalignedbb.d + 1.0D); + int k = MathHelper.floor(axisalignedbb.b); + int l = MathHelper.floor(axisalignedbb.e + 1.0D); + int i1 = MathHelper.floor(axisalignedbb.c); + int j1 = MathHelper.floor(axisalignedbb.f + 1.0D); + + if (!this.isAreaLoaded(i, k, i1, j, l, j1, true)) { + return false; + } else { + boolean flag = false; + Vec3D vec3d = new Vec3D(0.0D, 0.0D, 0.0D); + BlockPosition.MutableBlockPosition blockposition_mutableblockposition = new BlockPosition.MutableBlockPosition(); + + for (int k1 = i; k1 < j; ++k1) { + for (int l1 = k; l1 < l; ++l1) { + for (int i2 = i1; i2 < j1; ++i2) { + IBlockData iblockdata = this.getType(k1, l1, i2); + Block block = iblockdata.getBlock(); + + if (block.getMaterial() == material) { + if (l >= ((l1 + 1) - BlockFluids.b(iblockdata.get(BlockFluids.LEVEL)))) { + flag = true; + vec3d = block.a(this, blockposition_mutableblockposition.c(k1, l1, i2), entity, vec3d); + } + } + } + } + } + + if (vec3d.b() > 0.0D && entity.aL()) { + vec3d = vec3d.a(); + entity.motX += vec3d.a * 0.014D; + entity.motY += vec3d.b * 0.014D; + entity.motZ += vec3d.c * 0.014D; + } + + return flag; + } + } + + public boolean a(AxisAlignedBB axisalignedbb, Material material) { + // Migot start + return this.a(this, axisalignedbb, material); + } + + public boolean a(IBlockAccess iblockaccess, AxisAlignedBB axisalignedbb, Material material) { + // Migot end + int i = MathHelper.floor(axisalignedbb.a); + int j = MathHelper.floor(axisalignedbb.d + 1.0D); + int k = MathHelper.floor(axisalignedbb.b); + int l = MathHelper.floor(axisalignedbb.e + 1.0D); + int i1 = MathHelper.floor(axisalignedbb.c); + int j1 = MathHelper.floor(axisalignedbb.f + 1.0D); + BlockPosition.MutableBlockPosition blockposition_mutableblockposition = new BlockPosition.MutableBlockPosition(); + + for (int k1 = i; k1 < j; ++k1) { + for (int l1 = k; l1 < l; ++l1) { + for (int i2 = i1; i2 < j1; ++i2) { + if (iblockaccess.getType(blockposition_mutableblockposition.c(k1, l1, i2)).getBlock().getMaterial() == material) { // Migot + return true; + } + } + } + } + + return false; + } + + public boolean b(AxisAlignedBB axisalignedbb, Material material) { + int i = MathHelper.floor(axisalignedbb.a), j = MathHelper.floor(axisalignedbb.d + 1.0D), k = MathHelper.floor(axisalignedbb.b), l = MathHelper.floor(axisalignedbb.e + 1.0D), i1 = MathHelper.floor(axisalignedbb.c), j1 = MathHelper.floor(axisalignedbb.f + 1.0D); + + for (int k1 = i; k1 < j; ++k1) { + for (int l1 = k; l1 < l; ++l1) { + for (int i2 = i1; i2 < j1; ++i2) { + IBlockData iblockdata = this.getType(k1, l1, i2); + Block block = iblockdata.getBlock(); + + if (block.getMaterial() == material) { + int j2 = iblockdata.get(BlockFluids.LEVEL); + double d0 = (l1 + 1); + + if (j2 < 8) { + d0 = (double) (l1 + 1) - (double) j2 / 8.0D; + } + + if (d0 >= axisalignedbb.b) { + return true; + } + } + } + } + } + + return false; + } + + public Explosion explode(Entity entity, double d0, double d1, double d2, float f, boolean flag) { + return createExplosion(entity, d0, d1, d2, f, false, flag); + } + + public Explosion createExplosion(Entity entity, double d0, double d1, double d2, float f, boolean flag, boolean flag1) { + Explosion explosion = new Explosion(this, entity, d0, d1, d2, f, flag, flag1); + explosion.a(); + explosion.a(true); + return explosion; + } + + public int getDurability(int x, int y, int z) { + return getChunkAtWorldCoords(x, z).getBlockDurability(x, y, z); + } + + public int getDurability(Chunk chunk, int x, int y, int z) { + return !isValidLocation(x, y, z) ? 0 : chunk.getBlockDurability(x, y, z); + } + + public void setDurability(Chunk chunk, int x, int y, int z, int durability) { + if (!isValidLocation(x, y, z) || y <= 1) + return; + chunk.setBlockDurability(x, y, z, durability); + } + + public float getExplosionDensity(Vec3D vec3d, AxisAlignedBB axisalignedbb) { + int arrived = 0, rays = 0; + double[] vectors = Explosion.densityVectors; + for (int i = 0, length = vectors.length; i < length;) { + double x = vectors[i]; + double y = vectors[i + 1]; + double z = vectors[i + 2]; + i += 3; + if (rays == 8 && arrived == 8) + return 1.0F; + if (explosionRayTrace(new Vec3D(axisalignedbb.a + (axisalignedbb.d - axisalignedbb.a) * x + 0.1621621665160441, axisalignedbb.b + (axisalignedbb.e - axisalignedbb.b) * y, axisalignedbb.c + (axisalignedbb.f - axisalignedbb.c) * z + 0.1621621665160441), vec3d) == null) { + ++arrived; + } + ++rays; + } + return (float) arrived / (float) rays; + } + + public MovingObjectPosition explosionRayTrace(Vec3D vec3d, Vec3D vec3d1) { + int i = MathHelper.floor(vec3d1.a), j = MathHelper.floor(vec3d1.b), k = MathHelper.floor(vec3d1.c), l = MathHelper.floor(vec3d.a), i1 = MathHelper.floor(vec3d.b), j1 = MathHelper.floor(vec3d.c); + + BlockPosition blockposition = new BlockPosition(l, i1, j1); + + IBlockData iblockdata = rayTraceCache.get(blockposition); + if (iblockdata == null) { + iblockdata = getType(l, i1, j1); + rayTraceCache.put(blockposition, iblockdata); + } + + Block block = iblockdata.getBlock(); + if (block.a(iblockdata, false)) { + MovingObjectPosition movingobjectposition = block.a(this, blockposition, vec3d, vec3d1); + if (movingobjectposition != null) + return movingobjectposition; + } + + int k1 = 200; + while (k1-- >= 0) { + EnumDirection enumdirection; + + if (l == i && i1 == j && j1 == k) + return null; + + int flag3 = 1; + int flag4 = 1; + int flag5 = 1; + + double d0 = 999.0; + double d1 = 999.0; + double d2 = 999.0; + + if (i > l) { + d0 = l + 1.0; + } else if (i < l) { + d0 = l + 0.0; + } else { + flag3 = 0; + } + + if (j > i1) { + d1 = i1 + 1.0; + } else if (j < i1) { + d1 = i1 + 0.0; + } else { + flag4 = 0; + } + + if (k > j1) { + d2 = j1 + 1.0; + } else if (k < j1) { + d2 = j1 + 0.0; + } else { + flag5 = 0; + } + + double d3 = 999.0; + double d4 = 999.0; + double d5 = 999.0; + + double d6 = vec3d1.a - vec3d.a; + double d7 = vec3d1.b - vec3d.b; + double d8 = vec3d1.c - vec3d.c; + + if (flag3 != 0) + d3 = (d0 - vec3d.a) / d6; + + if (flag4 != 0) + d4 = (d1 - vec3d.b) / d7; + + if (flag5 != 0) + d5 = (d2 - vec3d.c) / d8; + + if (d3 == -0.0) + d3 = -1.0E-4; + + if (d4 == -0.0) + d4 = -1.0E-4; + + if (d5 == -0.0) + d5 = -1.0E-4; + + if (d3 < d4 && d3 < d5) { + enumdirection = i > l ? EnumDirection.WEST : EnumDirection.EAST; + vec3d = new Vec3D(d0, vec3d.b + d7 * d3, vec3d.c + d8 * d3); + } else if (d4 < d5) { + enumdirection = j > i1 ? EnumDirection.DOWN : EnumDirection.UP; + vec3d = new Vec3D(vec3d.a + d6 * d4, d1, vec3d.c + d8 * d4); + } else { + enumdirection = k > j1 ? EnumDirection.NORTH : EnumDirection.SOUTH; + vec3d = new Vec3D(vec3d.a + d6 * d5, vec3d.b + d7 * d5, d2); + } + + l = MathHelper.floor(vec3d.a) - (enumdirection == EnumDirection.EAST ? 1 : 0); + i1 = MathHelper.floor(vec3d.b) - (enumdirection == EnumDirection.UP ? 1 : 0); + j1 = MathHelper.floor(vec3d.c) - (enumdirection == EnumDirection.SOUTH ? 1 : 0); + + blockposition = new BlockPosition(l, i1, j1); + iblockdata = rayTraceCache.get(blockposition); + if (iblockdata == null) { + iblockdata = getType(l, i1, j1); + rayTraceCache.put(blockposition, iblockdata); + } + + block = iblockdata.getBlock(); + if (block.a(iblockdata, false)) { + MovingObjectPosition movingobjectposition = block.a(this, blockposition, vec3d, vec3d1); + if (movingobjectposition != null) + return movingobjectposition; + } + } + return null; + } + + public float a(Vec3D vec3d, AxisAlignedBB axisalignedbb) { + double d0 = 1.0D / ((axisalignedbb.d - axisalignedbb.a) * 2.0D + 1.0D); + double d1 = 1.0D / ((axisalignedbb.e - axisalignedbb.b) * 2.0D + 1.0D); + double d2 = 1.0D / ((axisalignedbb.f - axisalignedbb.c) * 2.0D + 1.0D); + double d3 = (1.0D - Math.floor(1.0D / d0) * d0) / 2.0D; + double d4 = (1.0D - Math.floor(1.0D / d2) * d2) / 2.0D; + + if (d0 >= 0.0D && d1 >= 0.0D && d2 >= 0.0D) { + int i = 0; + int j = 0; + + for (float f = 0.0F; f <= 1.0F; f = (float) (f + d0)) { + for (float f1 = 0.0F; f1 <= 1.0F; f1 = (float) (f1 + d1)) { + for (float f2 = 0.0F; f2 <= 1.0F; f2 = (float) (f2 + d2)) { + if (this.rayTrace(new Vec3D(axisalignedbb.a + (axisalignedbb.d - axisalignedbb.a) * f + d3, axisalignedbb.b + (axisalignedbb.e - axisalignedbb.b) * f1, axisalignedbb.c + (axisalignedbb.f - axisalignedbb.c) * f2 + d4), vec3d) == null) { + ++i; + } + ++j; + } + } + } + + return (float) i / (float) j; + } else { + return 0.0F; + } + } + + public boolean douseFire(EntityHuman entityhuman, BlockPosition blockposition, EnumDirection enumdirection) { + blockposition = blockposition.shift(enumdirection); + if (this.getType(blockposition).getBlock() == Blocks.FIRE) { + this.a(entityhuman, 1004, blockposition, 0); + this.setAir(blockposition); + return true; + } else { + return false; + } + } + + public TileEntity getTileEntity(BlockPosition blockposition) { + return getTileEntity(null, blockposition); + } + + public TileEntity getTileEntity(Chunk chunk, BlockPosition blockposition) { + if (!this.isValidLocation(blockposition)) { + return null; + } else { + // Vortex start - optimized captured tiles (only get() instead of containsKey() & get()) + TileEntity tileentity = null; + + if (!capturedTileEntities.isEmpty()) { + tileentity = capturedTileEntities.get(blockposition); + if (tileentity != null) + return tileentity; + } + // Vortex end + + int i; + TileEntity tileentity1; + + if (this.M) { + for (i = 0; i < this.b.size(); ++i) { + tileentity1 = this.b.get(i); + if (!tileentity1.x() && tileentity1.getPosition().equals(blockposition)) { + tileentity = tileentity1; + break; + } + } + } + + if (tileentity == null) { + tileentity = (chunk != null ? chunk : getChunkAtWorldCoords(blockposition)).a(blockposition, Chunk.EnumTileEntityState.IMMEDIATE); + } + + if (tileentity == null) { + for (i = 0; i < this.b.size(); ++i) { + tileentity1 = this.b.get(i); + if (!tileentity1.x() && tileentity1.getPosition().equals(blockposition)) { + tileentity = tileentity1; + break; + } + } + } + + return tileentity; + } + } + + public TileEntity getTileEntity(Chunk chunk, BlockPosition blockposition, Block block) { + return getTileEntity(chunk, blockposition); + } + + public void setTileEntity(BlockPosition blockposition, TileEntity tileentity) { + if (tileentity != null && !tileentity.x()) { + // CraftBukkit start + if (captureBlockStates) { + tileentity.a(this); + tileentity.a(blockposition); + capturedTileEntities.put(blockposition, tileentity); + return; + } + // CraftBukkit end + if (this.M) { + tileentity.a(blockposition); + Iterator iterator = this.b.iterator(); + + while (iterator.hasNext()) { + TileEntity tileentity1 = iterator.next(); + if (tileentity1.getPosition().equals(blockposition)) { + tileentity1.y(); + iterator.remove(); + } + } + + tileentity.a(this); // Spigot - No null worlds + this.b.add(tileentity); + } else { + this.a(tileentity); + this.getChunkAtWorldCoords(blockposition).a(blockposition, tileentity); + } + } + } + + public void t(BlockPosition blockposition) { + TileEntity tileentity = this.getTileEntity(blockposition); + + if (tileentity != null && this.M) { + tileentity.y(); + this.b.remove(tileentity); + } else { + if (tileentity != null) { + this.b.remove(tileentity); + this.tileEntityList.remove(tileentity); + } + + this.getChunkAtWorldCoords(blockposition).e(blockposition); + } + + } + + public void b(TileEntity tileentity) { + this.c.add(tileentity); + } + + public boolean u(BlockPosition blockposition) { + IBlockData iblockdata = this.getType(blockposition); + AxisAlignedBB axisalignedbb = iblockdata.getBlock().a(this, blockposition, iblockdata); + + return axisalignedbb != null && axisalignedbb.a() >= 1.0D; + } + + public boolean d(BlockPosition blockposition, boolean flag) { + if (!this.isValidLocation(blockposition)) { + return flag; + } else { + if (chunkProvider.getChunkAt(blockposition).isEmpty()) { + return flag; + } else { + Block block = this.getType(blockposition).getBlock(); + + return block.getMaterial().k() && block.d(); + } + } + } + + public void B() { + int i = this.a(1.0F); + + if (i != this.I) { + this.I = i; + } + + } + + public void setSpawnFlags(boolean flag, boolean flag1) { + this.allowMonsters = flag; + this.allowAnimals = flag1; + } + + public void doTick() { + this.p(); + } + + protected void C() { + if (this.worldData.hasStorm()) { + this.p = 1.0F; + if (this.worldData.isThundering()) { + this.r = 1.0F; + } + } + } + + protected void p() { + if (!this.worldProvider.o()) { + int i = this.worldData.A(); + + if (i > 0) { + --i; + this.worldData.i(i); + this.worldData.setThunderDuration(this.worldData.isThundering() ? 1 : 2); + this.worldData.setWeatherDuration(this.worldData.hasStorm() ? 1 : 2); + } + + int j = this.worldData.getThunderDuration(); + + if (j <= 0) { + if (this.worldData.isThundering()) { + this.worldData.setThunderDuration(random.nextInt(12000) + 3600); + } else { + this.worldData.setThunderDuration(random.nextInt(168000) + 12000); + } + } else { + --j; + this.worldData.setThunderDuration(j); + if (j <= 0) { + this.worldData.setThundering(!this.worldData.isThundering()); + } + } + + this.q = this.r; + if (this.worldData.isThundering()) { + this.r = (float) ((double) this.r + 0.01D); + } else { + this.r = (float) ((double) this.r - 0.01D); + } + + this.r = MathHelper.a(this.r, 0.0F, 1.0F); + int k = this.worldData.getWeatherDuration(); + + if (k <= 0) { + if (this.worldData.hasStorm()) { + this.worldData.setWeatherDuration(random.nextInt(12000) + 12000); + } else { + this.worldData.setWeatherDuration(random.nextInt(168000) + 12000); + } + } else { + --k; + this.worldData.setWeatherDuration(k); + if (k <= 0) { + this.worldData.setStorm(!this.worldData.hasStorm()); + } + } + + this.o = this.p; + if (this.worldData.hasStorm()) { + this.p = (float) ((double) this.p + 0.01D); + } else { + this.p = (float) ((double) this.p - 0.01D); + } + + this.p = MathHelper.a(this.p, 0.0F, 1.0F); + + // CraftBukkit start + for (EntityHuman player : players) { + if (player.world == this) + ((EntityPlayer) player).tickWeather(); + } + // CraftBukkit end + } + } + + protected void D() { + addChunksToTickList(); + } + + private void addChunksToTickList() { + int optimalChunks = spigotConfig.chunksPerTick; + // Quick conditions to allow us to exist early + if (optimalChunks > 0) { + // Keep chunks with growth inside of the optimal chunk range + int chunksPerPlayer = Math.min(200, Math.max(1, (int) (((optimalChunks - players.size()) / (double) players.size()) + 0.5))); + int randRange = 3 + chunksPerPlayer / 30; + // Limit to normal tick radius - including view distance + randRange = (randRange > chunkTickRadius) ? chunkTickRadius : randRange; + // odds of growth happening vs growth happening in vanilla + this.growthOdds = this.modifiedOdds = Math.max(35, Math.min(100, ((chunksPerPlayer + 1) * 100F) / 15F)); + // Spigot end + for (EntityHuman entityhuman : players) { + int x = MathHelper.floor(entityhuman.locX / 16.0D); + int z = MathHelper.floor(entityhuman.locZ / 16.0D); + + // Spigot start - Always update the chunk the player is on + long key = chunkToKey(x, z); + + if (!chunkTickList.contains(key)) { + Chunk chunk = ((ChunkProviderServer) chunkProvider).getChunkIfLoaded(key); + + if (chunk != null) { + chunkTickList.add(chunk); + } + } + + // Check and see if we update the chunks surrounding the player this tick + for (int chunk = 0; chunk < chunksPerPlayer; chunk++) { + int dx = (simpleRandom.nextBoolean() ? 1 : -1) * simpleRandom.nextInt(randRange); + int dz = (simpleRandom.nextBoolean() ? 1 : -1) * simpleRandom.nextInt(randRange); + long hash = chunkToKey(dx + x, dz + z); + + Chunk c = ((ChunkProviderServer) chunkProvider).getChunkIfLoaded(hash); + + if (c != null) { + chunkTickList.add(c); + } + } + } + } + } + + protected abstract int q(); + + protected void a(int i, int j, Chunk chunk) { + chunk.m(); + } + + protected void h() { + D(); + } + + public void a(Block block, BlockPosition blockposition, Random random) { + this.e = true; + block.b(this, blockposition, this.getType(blockposition), random); + this.e = false; + } + + public boolean v(BlockPosition blockposition) { + return this.e(blockposition, false); + } + + public boolean w(BlockPosition blockposition) { + return this.e(blockposition, true); + } + + // Vortex start - Optimized snow fall and placing + public boolean e(BlockPosition blockposition, boolean flag) { + int y = blockposition.getY(), x = blockposition.getX(), z = blockposition.getZ(); + if (y >= 0 && y < 256 && getBiome(x, y, z).aV(x, y, z) <= 0.15F && this.b(EnumSkyBlock.BLOCK, x, y, z) < 10) { + IBlockData iblockdata = this.getType(x, y, z); + Block block = iblockdata.getBlock(); + + if ((block == Blocks.WATER || block == Blocks.FLOWING_WATER) && iblockdata.get(BlockFluids.LEVEL) == 0) { + if (!flag) { + return true; + } + + return !(getType(x - 1, y, z).getBlock().getMaterial() == Material.WATER + && getType(x + 1, y, z).getBlock().getMaterial() == Material.WATER + && getType(x, y, z - 1).getBlock().getMaterial() == Material.WATER + && getType(x, y, z + 1).getBlock().getMaterial() == Material.WATER); + } + } + return false; + } + + public boolean canBlockFreeze(Chunk chunk, BiomeBase biome, int x, int y, int z) { + if (y >= 0 && y < 256 && biome.aV(x, y, z) <= 0.15F && chunk.getBrightness(EnumSkyBlock.BLOCK, x, y, z) < 10) { + IBlockData iblockdata = this.getType(x, y, z); + Block block = iblockdata.getBlock(); + + if ((block == Blocks.WATER || block == Blocks.FLOWING_WATER) && iblockdata.get(BlockFluids.LEVEL) == 0) { + return !(getType(x - 1, y, z).getBlock().getMaterial() == Material.WATER + && getType(x + 1, y, z).getBlock().getMaterial() == Material.WATER + && getType(x, y, z - 1).getBlock().getMaterial() == Material.WATER + && getType(x, y, z + 1).getBlock().getMaterial() == Material.WATER); + } + } + return false; + } + + public boolean f(BlockPosition blockposition, boolean flag) { + return f(blockposition.getX(), blockposition.getY(), blockposition.getZ(), flag); + } + + public boolean f(int x, int y, int z, boolean flag) { + return f(getBiome(x, y, z), x, y, z, flag); + } + + public boolean f(BiomeBase biome, int x, int y, int z, boolean flag) { + float f = biome.aV(x, y, z); + + if (f > 0.15F) { + return false; + } else if (!flag) { + return true; + } else { + if (y >= 0 && y < 256 && this.b(EnumSkyBlock.BLOCK, x, y, z) < 10) { + return getType(x, y, z).getBlock().getMaterial() == Material.AIR && canPlaceSnow(x, y, z); + } + + return false; + } + } + + public boolean canSnowAt(Chunk chunk, BiomeBase biome, int x, int y, int z, boolean flag) { + float f = biome.aV(x, y, z); + + if (f > 0.15F) { + return false; + } else if (!flag) { + return true; + } else { + if (y >= 0 && y < 256 && chunk.getBrightness(EnumSkyBlock.BLOCK, x, y, z) < 10) { + return getType(x, y, z).getBlock().getMaterial() == Material.AIR && canPlaceSnow(x, y, z); + } + return false; + } + } + + private boolean canPlaceSnow(int x, int y, int z) { + IBlockData iblockdata = getType(x, y - 1, z); + Block block = iblockdata.getBlock(); + + return block != Blocks.ICE && block != Blocks.PACKED_ICE && (block.getMaterial() == Material.LEAVES || (block == Blocks.SNOW_LAYER && iblockdata.get(BlockSnow.LAYERS) >= 7 || block.c() && block.material.isSolid())); + } + // Vortex - end + + public boolean x(BlockPosition position) { + return x(position.getX(), position.getY(), position.getZ()); + } + + public boolean x(int x, int y, int z) { + if (AzuriteConfig.disableBlockLighting.getValue()) + return true; + boolean flag = false; + + if (!this.worldProvider.o()) { + flag = this.updateLight(EnumSkyBlock.SKY, x, y, z); // PaperSpigot - Asynchronous lighting updates + } + + flag |= this.updateLight(EnumSkyBlock.BLOCK, x, y, z); // PaperSpigot - Asynchronous lighting updates + return flag; + } + + public boolean c(EnumSkyBlock enumskyblock, BlockPosition blockposition, Chunk chunk, List neighbors) { // PaperSpigot + return c(enumskyblock, blockposition.getX(), blockposition.getY(), blockposition.getZ(), chunk, neighbors); + } + + public boolean c(EnumSkyBlock enumskyblock, int x, int y, int z, Chunk chunk, List neighbors) { // PaperSpigot + // CraftBukkit start - Use neighbor cache instead of looking up + //Chunk chunk = this.getChunkIfLoaded(blockposition.getX() >> 4, blockposition.getZ() >> 4); + if (chunk == null /*|| !chunk.areNeighborsLoaded(1)*/ /*!this.areChunksLoaded(blockposition, 17, false)*/) { + // CraftBukkit end + return false; + } else { + int i = 0; + int j = 0; + int k = this.b(enumskyblock, x, y, z); + int l = this.a(x, y, z, enumskyblock); + int l1; + int i2; + int j2; + int k2; + int l2; + int i3; + int j3; + int k3; + + if (l > k) { + this.H[j++] = 133152; + } else if (l < k) { + this.H[j++] = 133152 | k << 18; + + while (i < j) { + l1 = this.H[i++]; + i2 = (l1 & 63) - 32 + x; + j2 = (l1 >> 6 & 63) - 32 + y; + k2 = (l1 >> 12 & 63) - 32 + z; + int l3 = l1 >> 18 & 15; + l2 = this.b(enumskyblock, i2, j2, k2); + if (l2 == l3) { + this.a(enumskyblock, i2, j2, k2, 0); + if (l3 > 0) { + i3 = MathHelper.a(i2 - x); + j3 = MathHelper.a(j2 - y); + k3 = MathHelper.a(k2 - z); + if (i3 + j3 + k3 < 17) { + BlockPosition.MutableBlockPosition blockposition_mutableblockposition = new BlockPosition.MutableBlockPosition(); + EnumDirection[] aenumdirection = EnumDirection.values(); + + for (EnumDirection enumdirection : aenumdirection) { + int k4 = i2 + enumdirection.getAdjacentX(); + int l4 = j2 + enumdirection.getAdjacentY(); + int i5 = k2 + enumdirection.getAdjacentZ(); + + blockposition_mutableblockposition.c(k4, l4, i5); + int j5 = Math.max(1, this.getType(blockposition_mutableblockposition).getBlock().p()); + + l2 = this.b(enumskyblock, blockposition_mutableblockposition); + if (l2 == l3 - j5 && j < this.H.length) { + this.H[j++] = k4 - x + 32 | l4 - y + 32 << 6 | i5 - z + 32 << 12 | l3 - j5 << 18; + } + } + } + } + } + } + + i = 0; + } + + while (i < j) { + l1 = this.H[i++]; + i2 = (l1 & 63) - 32 + x; + j2 = (l1 >> 6 & 63) - 32 + y; + k2 = (l1 >> 12 & 63) - 32 + z; + int k5 = this.b(enumskyblock, i2, j2, k2); + + l2 = this.a(i2, j2, k2, enumskyblock); + if (l2 != k5) { + this.a(enumskyblock, i2, j2, k2, l2); + if (l2 > k5) { + i3 = Math.abs(i2 - x); + j3 = Math.abs(j2 - y); + k3 = Math.abs(k2 - z); + boolean flag = j < this.H.length - 6; + + if (i3 + j3 + k3 < 17 && flag) { + + if (this.b(enumskyblock, i2 - 1, j2, k2) < l2) { + this.H[j++] = i2 - 1 - x + 32 + (j2 - y + 32 << 6) + (k2 - z + 32 << 12); + } + + if (this.b(enumskyblock, i2 + 1, j2, k2) < l2) { + this.H[j++] = i2 + 1 - x + 32 + (j2 - y + 32 << 6) + (k2 - z + 32 << 12); + } + + if (this.b(enumskyblock, i2, j2 - 1, k2) < l2) { + this.H[j++] = i2 - x + 32 + (j2 - 1 - y + 32 << 6) + (k2 - z + 32 << 12); + } + + if (this.b(enumskyblock, i2, j2 + 1, k2) < l2) { + this.H[j++] = i2 - x + 32 + (j2 + 1 - y + 32 << 6) + (k2 - z + 32 << 12); + } + + if (this.b(enumskyblock, i2, j2, k2 - 1) < l2) { + this.H[j++] = i2 - x + 32 + (j2 - y + 32 << 6) + (k2 - 1 - z + 32 << 12); + } + + if (this.b(enumskyblock, i2, j2, k2 + 1) < l2) { + this.H[j++] = i2 - x + 32 + (j2 - y + 32 << 6) + (k2 + 1 - z + 32 << 12); + } + } + } + } + } + + // PaperSpigot start - Asynchronous light updates + if (chunk.world.paperSpigotConfig.useAsyncLighting) { + chunk.pendingLightUpdates.decrementAndGet(); + if (neighbors != null) { + for (Chunk neighbor : neighbors) { + neighbor.pendingLightUpdates.decrementAndGet(); + } + } + } + // PaperSpigot end + return true; + } + } + + public boolean updateLight(EnumSkyBlock enumskyblock, int x, int y, int z) { + if (AzuriteConfig.disableBlockLighting.getValue()) + return true; + Chunk chunk = getChunkIfLoaded(x >> 4, z >> 4); + return this.updateLight(enumskyblock, x, y, z, chunk); + } + + public boolean updateLight(EnumSkyBlock enumskyblock, int x, int y, int z, Chunk chunk) { + if (AzuriteConfig.disableBlockLighting.getValue()) + return true; + if (chunk == null || !chunk.areNeighborsLoaded(2)) + return false; + else if (!chunk.world.paperSpigotConfig.useAsyncLighting) + return c(enumskyblock, x, y, z, chunk, null); + chunk.pendingLightUpdates.incrementAndGet(); + chunk.lightUpdateTime = chunk.world.getTime(); + List neighbors = new ArrayList<>(); + + int chunkX = chunk.locX, chunkZ = chunk.locZ; // VortexSpigot - Don't calculate X and Z every time in loop + + for (int cx = chunkX - 2; cx <= chunkX + 2; cx++) { + for (int cz = chunkZ - 2; cz <= chunkZ + 2; cz++) { + if (cx != chunkX || cz != chunkZ) { + Chunk neighbor = getChunkIfLoaded(cx, cz); + if (neighbor != null) { + neighbor.pendingLightUpdates.incrementAndGet(); + neighbor.lightUpdateTime = chunk.world.getTime(); + neighbors.add(neighbor); + } + } + } + } + if (!Bukkit.isPrimaryThread()) + return c(enumskyblock, x, y, z, chunk, neighbors); + lightingExecutor.submit(() -> { + c(enumskyblock, x, y, z, chunk, neighbors); + }); + return true; + } + + /** + * PaperSpigot - Asynchronous lighting updates + */ + public boolean updateLight(EnumSkyBlock enumskyblock, BlockPosition position) { + return updateLight(enumskyblock, position.getX(), position.getY(), position.getZ()); + } + + public boolean a(boolean flag) { + return false; + } + + public List a(Chunk chunk, boolean flag) { + return null; + } + + public void a(BlockPosition blockposition, Chunk chunk, Block block, int i, int j) { + } + + public List a(StructureBoundingBox structureboundingbox, boolean flag) { + return null; + } + + public List getEntities(Entity entity, AxisAlignedBB axisalignedbb) { + return a(entity, axisalignedbb, IEntitySelector.d); + } + + public List a(Entity entity, AxisAlignedBB axisalignedbb, Predicate predicate) { + List arraylist = Lists.newArrayList(); + int i = MathHelper.floor((axisalignedbb.a - 2.0D) / 16.0D); + int j = MathHelper.floor((axisalignedbb.d + 2.0D) / 16.0D); + int k = MathHelper.floor((axisalignedbb.c - 2.0D) / 16.0D); + int l = MathHelper.floor((axisalignedbb.f + 2.0D) / 16.0D); + + for (int i1 = i; i1 <= j; ++i1) { + for (int j1 = k; j1 <= l; ++j1) { + Chunk chunk = getChunkIfLoaded(i1, j1); + if (chunk != null) { + chunk.a(entity, axisalignedbb, arraylist, predicate); + } + } + } + + return arraylist; + } + + public List a(Class oclass, Predicate predicate) { + List arraylist = Lists.newArrayList(); + + for (Entity entity : entityList) { + if (oclass.isAssignableFrom(entity.getClass()) && predicate.apply((T) entity)) { // CraftBukkit - fix decompile error + arraylist.add((T) entity); + } + } + + return arraylist; + } + + public List b(Class oclass, Predicate predicate) { + List arraylist = Lists.newArrayList(); + + for (Entity entity : players) { + if (oclass.isAssignableFrom(entity.getClass()) && predicate.apply((T) entity)) { // CraftBukkit - fix decompile error + arraylist.add((T) entity); + } + } + + return arraylist; + } + + public List a(Class oclass, AxisAlignedBB axisalignedbb) { + return this.a(oclass, axisalignedbb, IEntitySelector.d); + } + + public List a(Class oclass, AxisAlignedBB axisalignedbb, Predicate predicate) { + int i = MathHelper.floor((axisalignedbb.a - 2.0D) / 16.0D); + int j = MathHelper.floor((axisalignedbb.d + 2.0D) / 16.0D); + int k = MathHelper.floor((axisalignedbb.c - 2.0D) / 16.0D); + int l = MathHelper.floor((axisalignedbb.f + 2.0D) / 16.0D); + List arraylist = Lists.newArrayList(); + + for (int i1 = i; i1 <= j; ++i1) { + for (int j1 = k; j1 <= l; ++j1) { + Chunk chunk = getChunkIfLoaded(i1, j1); + if (chunk != null) { + chunk.a(oclass, axisalignedbb, arraylist, predicate); + } + } + } + + return arraylist; + } + + public T a(Class oclass, AxisAlignedBB axisalignedbb, T t0) { + + Entity entity = null; + double d0 = Double.MAX_VALUE; + + for (Entity entity1 : a(oclass, axisalignedbb)) { + if (entity1 != t0 && IEntitySelector.d.apply(entity1)) { + double d1 = t0.h(entity1); + + if (d1 <= d0) { + entity = entity1; + d0 = d1; + } + } + } + + return (T) entity; // CraftBukkit fix decompile error + } + + public Entity a(int i) { + return entitiesById.get(i); + } + + public void b(BlockPosition blockposition, TileEntity tileentity) { + if (isValidLocation(blockposition)) { + Chunk chunk = getChunkIfLoaded(blockposition.getX() >> 4, blockposition.getZ() >> 4); + if (chunk != null) + chunk.e(); + } + } + + public int a(Class oclass) { + int i = 0; + for (Entity entity : entityList) { + // CraftBukkit start - Split out persistent check, don't apply it to special persistent mobs + if (entity instanceof EntityInsentient) { + EntityInsentient entityinsentient = (EntityInsentient) entity; + if (entityinsentient.isTypeNotPersistent() && entityinsentient.isPersistent()) { + continue; + } + } + + if (oclass.isAssignableFrom(entity.getClass())) + ++i; + } + + return i; + } + + public void b(Collection collection) { + for (Entity entity : collection) { + entityList.add(entity); + a(entity); + } + } + + public void c(Collection collection) { + g.addAll(collection); + } + + public boolean a(Block block, BlockPosition blockposition, boolean flag, EnumDirection enumdirection, Entity entity, ItemStack itemstack) { + Block block1 = getType(blockposition).getBlock(); + AxisAlignedBB axisalignedbb = flag ? null : block.a(this, blockposition, block.getBlockData()); + + // CraftBukkit start - store default return + boolean defaultReturn = (axisalignedbb == null || this.a(axisalignedbb, entity)) && (block1.getMaterial() == Material.ORIENTABLE && block == Blocks.ANVIL || block1.getMaterial().isReplaceable() && block.canPlace(this, blockposition, enumdirection, itemstack)); + BlockCanBuildEvent event = new BlockCanBuildEvent(this.getWorld().getBlockAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()), CraftMagicNumbers.getId(block), defaultReturn); + this.getServer().getPluginManager().callEvent(event); + + return event.isBuildable(); + // CraftBukkit end + } + + public int F() { + return this.a; + } + + public void b(int i) { + this.a = i; + } + + public int getBlockPower(BlockPosition blockposition, EnumDirection enumdirection) { + IBlockData iblockdata = this.getType(blockposition); + + return iblockdata.getBlock().b(this, blockposition, iblockdata, enumdirection); + } + + public WorldType G() { + return this.worldData.getType(); + } + + public int getBlockPower(BlockPosition blockposition) { + int i = Math.max(0, this.getBlockPower(blockposition.down(), EnumDirection.DOWN)); + + if (i < 15) { + i = Math.max(i, this.getBlockPower(blockposition.up(), EnumDirection.UP)); + if (i < 15) { + i = Math.max(i, this.getBlockPower(blockposition.north(), EnumDirection.NORTH)); + if (i < 15) { + i = Math.max(i, this.getBlockPower(blockposition.south(), EnumDirection.SOUTH)); + if (i < 15) { + i = Math.max(i, this.getBlockPower(blockposition.west(), EnumDirection.WEST)); + if (i < 15) { + i = Math.max(i, this.getBlockPower(blockposition.east(), EnumDirection.EAST)); + } + } + } + } + } + return i; + } + + public boolean isBlockFacePowered(BlockPosition blockposition, EnumDirection enumdirection) { + return getBlockFacePower(blockposition, enumdirection) > 0; + } + + public int getBlockFacePower(BlockPosition blockposition, EnumDirection enumdirection) { + IBlockData iblockdata = this.getType(blockposition); + Block block = iblockdata.getBlock(); + + return block.isOccluding() ? this.getBlockPower(blockposition) : block.a(this, blockposition, iblockdata, enumdirection); + } + + public boolean isBlockIndirectlyPowered(BlockPosition blockposition) { + return getBlockFacePower(blockposition.down(), EnumDirection.DOWN) > 0 || + (getBlockFacePower(blockposition.up(), EnumDirection.UP) > 0 || + (getBlockFacePower(blockposition.north(), EnumDirection.NORTH) > 0 || + (getBlockFacePower(blockposition.south(), EnumDirection.SOUTH) > 0 || + (getBlockFacePower(blockposition.west(), EnumDirection.WEST) > 0 || + getBlockFacePower(blockposition.east(), EnumDirection.EAST) > 0)))); + } + + public int A(BlockPosition blockposition) { + int i = 0; + for (EnumDirection enumdirection : EnumDirection.values()) { + int l = this.getBlockFacePower(blockposition.shift(enumdirection), enumdirection); + + if (l >= 15) { + return 15; + } + + if (l > i) { + i = l; + } + } + + return i; + } + + public EntityHuman findNearbyPlayer(Entity entity, double d0) { + return this.findNearbyPlayer(entity.locX, entity.locY, entity.locZ, d0); + } + + public EntityHuman findNearbyPlayer(double d0, double d1, double d2, double d3) { + if (0 <= d3 && d3 <= 64) { + return this.playerMap.getNearestPlayer(d0, d1, d2, d3); + } + + double d4 = -1.0D, squaredDistance = d3 * d3; + EntityHuman entityhuman = null; + + for (EntityHuman entityhuman1 : players) { + if (entityhuman1.dead || entityhuman1.isSpectator()) { + continue; + } + + double d5 = entityhuman1.e(d0, d1, d2); + + if ((d3 < 0.0D || d5 < squaredDistance) && (d4 == -1.0D || d5 < d4)) { + d4 = d5; + entityhuman = entityhuman1; + } + } + + return entityhuman; + } + + public boolean isPlayerNearby(double d0, double d1, double d2, double d3) { + double squaredDistance = d3 * d3; + for (EntityHuman entityhuman : players) { + if (!entityhuman.isSpectator()) { // Vortex - less check + double d4 = entityhuman.e(d0, d1, d2); + + if (d3 < 0.0D || d4 < squaredDistance) { + return true; + } + } + } + + return false; + } + + // PaperSpigot start - Modified methods for affects spawning + public EntityHuman findNearbyPlayerWhoAffectsSpawning(Entity entity, double d0) { + return this.findNearbyPlayerWhoAffectsSpawning(entity.locX, entity.locY, entity.locZ, d0); + } + + public EntityHuman findNearbyPlayerWhoAffectsSpawning(double x, double y, double z, double distance) { + if (0 <= distance && distance <= 64.0) { + return this.playerMap.getNearbyPlayer(x, y, z, distance, true); + } + + double d4 = -1.0D, squaredDistance = distance * distance; + EntityHuman entityhuman = null; + + for (EntityHuman entityhuman1 : players) { + if (entityhuman1.dead || !entityhuman1.affectsSpawning) { + continue; + } + + double d5 = entityhuman1.e(x, y, z); + + if ((distance < 0.0D || d5 < squaredDistance) && (d4 == -1.0D || d5 < d4)) { + // Azurite - Check isSpectator last as it's the heaviest. + if (!entityhuman1.isSpectator()) { + d4 = d5; + entityhuman = entityhuman1; + } + } + } + + return entityhuman; + } + + public boolean isPlayerNearbyWhoAffectsSpawning(double d0, double d1, double d2, double d3) { + if (0 <= d3 && d3 <= 64.0) { + return this.playerMap.getNearbyPlayer(d0, d1, d2, d3, true) != null; + } + + double squaredDistance = d3 * d3; + for (EntityHuman entityhuman : players) { + if (entityhuman.affectsSpawning && !entityhuman.isSpectator()) { + double d4 = entityhuman.e(d0, d1, d2); + + if (d3 < 0.0D || d4 < squaredDistance) { + return true; + } + } + } + + return false; + } + // PaperSpigot end + + public EntityHuman a(String s) { + for (EntityHuman entityhuman : players) { + if (s.equals(entityhuman.getName())) { + return entityhuman; + } + } + + return null; + } + + public EntityHuman b(UUID uuid) { + for (EntityHuman entityhuman : players) { + if (uuid.equals(entityhuman.getUniqueID())) { + return entityhuman; + } + } + + return null; + } + + public void checkSession() throws ExceptionWorldConflict { + this.dataManager.checkSession(); + } + + public long getSeed() { + return this.worldData.getSeed(); + } + + public long getTime() { + return this.worldData.getTime(); + } + + public long getDayTime() { + return this.worldData.getDayTime(); + } + + public void setDayTime(long i) { + this.worldData.setDayTime(i); + } + + public BlockPosition getSpawn() { + BlockPosition blockposition = new BlockPosition(worldData.c(), worldData.d(), worldData.e()); + + if (!getWorldBorder().a(blockposition)) { + blockposition = getHighestBlockYAt(MathHelper.floor(getWorldBorder().getCenterX()), MathHelper.floor(getWorldBorder().getCenterZ())); + } + + return blockposition; + } + + public void B(BlockPosition blockposition) { + this.worldData.setSpawn(blockposition); + } + + public boolean a(EntityHuman entityhuman, BlockPosition blockposition) { + return true; + } + + public void broadcastEntityEffect(Entity entity, byte b0) { + } + + public IChunkProvider N() { + return this.chunkProvider; + } + + public void playBlockAction(BlockPosition blockposition, Block block, int i, int j) { + block.a(this, blockposition, this.getType(blockposition), i, j); + } + + public IDataManager getDataManager() { + return this.dataManager; + } + + public WorldData getWorldData() { + return this.worldData; + } + + public GameRules getGameRules() { + return this.worldData.x(); + } + + public void everyoneSleeping() { + } + + // CraftBukkit start + // Calls the method that checks to see if players are sleeping + // Called by CraftPlayer.setPermanentSleeping() + public void checkSleepStatus() { + this.everyoneSleeping(); + } + // CraftBukkit end + + public float h(float f) { + return (this.q + (this.r - this.q) * f) * this.j(f); + } + + public float j(float f) { + return this.o + (this.p - this.o) * f; + } + + public boolean R() { + return (double) this.h(1.0F) > 0.9D; + } + + public boolean S() { + return (double) this.j(1.0F) > 0.2D; + } + + public boolean isRainingAt(int x, int y, int z) { + if (!S() || !i(x, y, z) || q(x, z).getY() > y) { + return false; + } + BiomeBase biomebase = getBiome(x, y, z); + return !biomebase.d() && (!f(biomebase, x, y, z, false) && biomebase.e()); + } + + public boolean isRainingAt(BlockPosition blockposition) { + return isRainingAt(blockposition.getX(), blockposition.getY(), blockposition.getZ()); + } + + public boolean D(BlockPosition blockposition) { + return getBiome(blockposition).f(); + } + + public PersistentCollection T() { + return this.worldMaps; + } + + public void a(String s, PersistentBase persistentbase) { + this.worldMaps.a(s, persistentbase); + } + + public PersistentBase a(Class oclass, String s) { + return this.worldMaps.get(oclass, s); + } + + public int b(String s) { + return this.worldMaps.a(s); + } + + public void a(int i, BlockPosition blockposition, int j) { + for (IWorldAccess iWorldAccess : this.u) { + iWorldAccess.a(i, blockposition, j); + } + } + + public void triggerEffect(int i, BlockPosition blockposition, int j) { + this.a(null, i, blockposition, j); + } + + public void a(EntityHuman entityhuman, int i, BlockPosition blockposition, int j) { + try { + for (IWorldAccess iWorldAccess : this.u) { + iWorldAccess.a(entityhuman, i, blockposition, j); + } + + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.a(throwable, "Playing level event"); + CrashReportSystemDetails crashreportsystemdetails = crashreport.a("Level event being played"); + + crashreportsystemdetails.a("Block coordinates", CrashReportSystemDetails.a(blockposition)); + crashreportsystemdetails.a("Event source", entityhuman); + crashreportsystemdetails.a("Event type", i); + crashreportsystemdetails.a("Event data", j); + throw new ReportedException(crashreport); + } + } + + public int getHeight() { + return 256; + } + + public int V() { + return this.worldProvider.o() ? 128 : 256; + } + + public Random a(int i, int j, int k) { + long l = (long) i * 341873128712L + (long) j * 132897987541L + this.getWorldData().getSeed() + (long) k; + + random.setSeed(l); + return random; + } + + public BlockPosition a(String s, BlockPosition blockposition) { + return this.N().findNearestMapFeature(this, s, blockposition); + } + + public CrashReportSystemDetails a(CrashReport crashreport) { + CrashReportSystemDetails crashreportsystemdetails = crashreport.a("Affected level", 1); + + crashreportsystemdetails.a("Level name", (this.worldData == null ? "????" : this.worldData.getName())); + crashreportsystemdetails.a("All players", players.size() + " total; " + players); + crashreportsystemdetails.a("Chunk stats", chunkProvider.getName()); + + try { + this.worldData.a(crashreportsystemdetails); + } catch (Throwable throwable) { + crashreportsystemdetails.a("Level Data Unobtainable", throwable); + } + + return crashreportsystemdetails; + } + + public void c(int i, BlockPosition blockposition, int j) { + for (IWorldAccess iWorldAccess : this.u) { + iWorldAccess.b(i, blockposition, j); + } + } + + public Calendar Y() { + if (this.getTime() % 600L == 0L) { + this.K.setTimeInMillis(MinecraftServer.az()); + } + + return this.K; + } + + public Scoreboard getScoreboard() { + return this.scoreboard; + } + + public void updateAdjacentComparators(BlockPosition blockposition, Block block) { + + for (EnumDirection enumdirection : EnumDirection.EnumDirectionLimit.HORIZONTAL) { + BlockPosition blockposition1 = blockposition.shift(enumdirection); + + if (this.isLoaded(blockposition1)) { + IBlockData iblockdata = this.getType(blockposition1); + + if (Blocks.UNPOWERED_COMPARATOR.e(iblockdata.getBlock())) { + iblockdata.getBlock().doPhysics(this, blockposition1, iblockdata, block, blockposition); + } else if (iblockdata.getBlock().isOccluding()) { + blockposition1 = blockposition1.shift(enumdirection); + iblockdata = this.getType(blockposition1); + if (Blocks.UNPOWERED_COMPARATOR.e(iblockdata.getBlock())) { + iblockdata.getBlock().doPhysics(this, blockposition1, iblockdata, block, blockposition); + } + } + } + } + } + + public DifficultyDamageScaler E(BlockPosition blockposition) { + return E(blockposition.getX(), blockposition.getY(), blockposition.getZ()); + } + + public EnumDifficulty getDifficulty() { + return this.getWorldData().getDifficulty(); + } + + public int ab() { + return this.I; + } + + public void c(int i) { + this.I = i; + } + + public boolean ad() { + return this.isLoading; + } + + public PersistentVillage ae() { + return this.villages; + } + + public WorldBorder getWorldBorder() { + return this.N; + } + + public boolean c(int i, int j) { + BlockPosition blockposition = this.getSpawn(); + int k = i * 16 + 8 - blockposition.getX(); + int l = j * 16 + 8 - blockposition.getZ(); + return k >= -128 && k <= 128 && l >= -128 && l <= 128 && this.keepSpawnInMemory; // CraftBukkit - Added 'this.keepSpawnInMemory' + } + + public int getRandomTickSpeed() { + return this.getGameRules().c("randomTickSpeed"); + } + + public boolean shouldSectionsHaveTickList() { + return getRandomTickSpeed() > 0; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldBorder.java b/azurite-server/src/main/java/net/minecraft/server/WorldBorder.java new file mode 100644 index 0000000..7e333ba --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldBorder.java @@ -0,0 +1,250 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; + +import java.util.List; + +public class WorldBorder { + + private final List a = Lists.newArrayList(); + private double b = 0.0D; + private double c = 0.0D; + private double d = 6.0E7D; + private double e; + private long f; + private long g; + private int h; + private double i; + private double j; + private int k; + private int l; + public WorldServer world; // CraftBukkit + + public WorldBorder() { + this.e = this.d; + this.h = 29999984; + this.i = 0.2D; + this.j = 5.0D; + this.k = 15; + this.l = 5; + } + + public boolean a(BlockPosition blockposition) { + return blockposition.getX() + 1 > this.b() && blockposition.getX() < this.d() && blockposition.getZ() + 1 > this.c() && blockposition.getZ() < this.e(); + } + + public boolean a(final int x, final int z) { + return x + 1 > this.b() && x < this.d() && z + 1 > this.c() && z < this.e(); + } + + // CraftBukkit start - split method + public boolean isInBounds(ChunkCoordIntPair chunkcoordintpair) { + return isInBounds(chunkcoordintpair.x, chunkcoordintpair.z); + } + + // Inlined the getters from ChunkCoordIntPair + public boolean isInBounds(long chunkcoords) { + return isInBounds(org.bukkit.craftbukkit.util.LongHash.msw(chunkcoords), org.bukkit.craftbukkit.util.LongHash.lsw(chunkcoords)); + } + + // Inlined the getters from ChunkCoordIntPair + public boolean isInBounds(int x, int z) { + return (double) ((x << 4) + 15) > this.b() && (double) (x << 4) < this.d() && (double) ((z << 4) + 15) > this.c() && (double) (z << 4) < this.e(); // PandaSpigot - Fix isInBounds(int x, int z) checking the wrong variable + } + + public boolean a(AxisAlignedBB axisalignedbb) { + return axisalignedbb.d > this.b() && axisalignedbb.a < this.d() && axisalignedbb.f > this.c() && axisalignedbb.c < this.e(); + } + + public double a(Entity entity) { + return this.b(entity.locX, entity.locZ); + } + + public double b(double d0, double d1) { + double d2 = d1 - this.c(); + double d3 = this.e() - d1; + double d4 = d0 - this.b(); + double d5 = this.d() - d0; + double d6 = Math.min(d4, d5); + + d6 = Math.min(d6, d2); + return Math.min(d6, d3); + } + + public EnumWorldBorderState getState() { + return this.e < this.d ? EnumWorldBorderState.SHRINKING : (this.e > this.d ? EnumWorldBorderState.GROWING : EnumWorldBorderState.STATIONARY); + } + + public double b() { + double d0 = this.getCenterX() - this.getSize() / 2.0D; + + if (d0 < -this.h) { + d0 = -this.h; + } + + return d0; + } + + public double c() { + double d0 = this.getCenterZ() - this.getSize() / 2.0D; + + if (d0 < -this.h) { + d0 = -this.h; + } + + return d0; + } + + public double d() { + double d0 = this.getCenterX() + this.getSize() / 2.0D; + + if (d0 > this.h) { + d0 = this.h; + } + + return d0; + } + + public double e() { + double d0 = this.getCenterZ() + this.getSize() / 2.0D; + + if (d0 > this.h) { + d0 = this.h; + } + + return d0; + } + + public double getCenterX() { + return this.b; + } + + public double getCenterZ() { + return this.c; + } + + public void setCenter(double d0, double d1) { + this.b = d0; + this.c = d1; + + for (IWorldBorderListener iWorldBorderListener : this.k()) { + iWorldBorderListener.a(this, d0, d1); + } + + } + + public double getSize() { + if (this.getState() != EnumWorldBorderState.STATIONARY) { + double d0 = ((float) (System.currentTimeMillis() - this.g) / (float) (this.f - this.g)); + + if (d0 < 1.0D) { + return this.d + (this.e - this.d) * d0; + } + + this.setSize(this.e); + } + + return this.d; + } + + public long i() { + return this.getState() != EnumWorldBorderState.STATIONARY ? this.f - System.currentTimeMillis() : 0L; + } + + public double j() { + return this.e; + } + + public void setSize(double d0) { + this.d = d0; + this.e = d0; + this.f = System.currentTimeMillis(); + this.g = this.f; + + for (IWorldBorderListener iWorldBorderListener : this.k()) { + iWorldBorderListener.a(this, d0); + } + + } + + public void transitionSizeBetween(double d0, double d1, long i) { + this.d = d0; + this.e = d1; + this.g = System.currentTimeMillis(); + this.f = this.g + i; + + for (IWorldBorderListener iWorldBorderListener : this.k()) { + iWorldBorderListener.a(this, d0, d1, i); + } + + } + + protected List k() { + return Lists.newArrayList(this.a); + } + + public void a(IWorldBorderListener iworldborderlistener) { + if (a.contains(iworldborderlistener)) return; // CraftBukkit + this.a.add(iworldborderlistener); + } + + public void a(int i) { + this.h = i; + } + + public int l() { + return this.h; + } + + public double getDamageBuffer() { + return this.j; + } + + public void setDamageBuffer(double d0) { + this.j = d0; + + for (IWorldBorderListener iWorldBorderListener : this.k()) { + iWorldBorderListener.c(this, d0); + } + + } + + public double getDamageAmount() { + return this.i; + } + + public void setDamageAmount(double d0) { + this.i = d0; + + for (IWorldBorderListener iWorldBorderListener : this.k()) { + iWorldBorderListener.b(this, d0); + } + + } + + public int getWarningTime() { + return this.k; + } + + public void setWarningTime(int i) { + this.k = i; + + for (IWorldBorderListener iWorldBorderListener : this.k()) { + iWorldBorderListener.a(this, i); + } + + } + + public int getWarningDistance() { + return this.l; + } + + public void setWarningDistance(int i) { + this.l = i; + + for (IWorldBorderListener iWorldBorderListener : this.k()) { + iWorldBorderListener.b(this, i); + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldChunkManager.java b/azurite-server/src/main/java/net/minecraft/server/WorldChunkManager.java new file mode 100644 index 0000000..b53561a --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldChunkManager.java @@ -0,0 +1,200 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; + +import java.util.List; +import java.util.Random; + +public class WorldChunkManager { + + private GenLayer b; + private GenLayer c; + private final BiomeCache d; + private final List e; + + protected WorldChunkManager() { + this.d = new BiomeCache(this); + this.e = Lists.newArrayList(); + this.e.add(BiomeBase.FOREST); + this.e.add(BiomeBase.PLAINS); + this.e.add(BiomeBase.TAIGA); + this.e.add(BiomeBase.TAIGA_HILLS); + this.e.add(BiomeBase.FOREST_HILLS); + this.e.add(BiomeBase.JUNGLE); + this.e.add(BiomeBase.JUNGLE_HILLS); + } + + public WorldChunkManager(long i, WorldType worldtype, String s, World world) { + this(); + GenLayer[] agenlayer = GenLayer.a(i, worldtype, s, world); + + this.b = agenlayer[0]; + this.c = agenlayer[1]; + } + + public WorldChunkManager(World world) { + this(world.getSeed(), world.getWorldData().getType(), world.getWorldData().getGeneratorOptions(), world); + } + + public List a() { + return this.e; + } + + public BiomeBase getBiome(BlockPosition blockposition) { + return this.getBiome(blockposition, null); + } + + public BiomeBase getBiome(BlockPosition blockposition, BiomeBase biomebase) { + return this.d.a(blockposition.getX(), blockposition.getZ(), biomebase); + } + + public BiomeBase getBiome(int x, int z) { + return this.d.a(x, z, null); + } + + public BiomeBase getBiome(int x, int z, BiomeBase biomebase) { + return this.d.a(x, z, biomebase); + } + + public float[] getWetness(float[] var1, int var2, int var3, int var4, int var5) { + IntCache.a(); + if (var1 == null || var1.length < var4 * var5) { + var1 = new float[var4 * var5]; + } + + int[] var6 = this.c.a(var2, var3, var4, var5); + + for(int var7 = 0; var7 < var4 * var5; ++var7) { + try { + float var8 = (float)BiomeBase.getBiome(var6[var7], BiomeBase.ad).h() / 65536.0F; + if (var8 > 1.0F) { + var8 = 1.0F; + } + + var1[var7] = var8; + } catch (Throwable var11) { + CrashReport var9 = CrashReport.a(var11, "Invalid Biome id"); + CrashReportSystemDetails var10 = var9.a("DownfallBlock"); + var10.a("biome id", var7); + var10.a("downfalls[] size", var1.length); + var10.a("x", var2); + var10.a("z", var3); + var10.a("w", var4); + var10.a("h", var5); + throw new ReportedException(var9); + } + } + + return var1; + } + + public BiomeBase[] getBiomes(BiomeBase[] var1, int var2, int var3, int var4, int var5) { + IntCache.a(); + if (var1 == null || var1.length < var4 * var5) { + var1 = new BiomeBase[var4 * var5]; + } + + int[] var6 = this.b.a(var2, var3, var4, var5); + + try { + for(int var7 = 0; var7 < var4 * var5; ++var7) { + var1[var7] = BiomeBase.getBiome(var6[var7], BiomeBase.ad); + } + + return var1; + } catch (Throwable var10) { + CrashReport var8 = CrashReport.a(var10, "Invalid Biome id"); + CrashReportSystemDetails var9 = var8.a("RawBiomeBlock"); + var9.a("biomes[] size", var1.length); + var9.a("x", var2); + var9.a("z", var3); + var9.a("w", var4); + var9.a("h", var5); + throw new ReportedException(var8); + } + } + + public BiomeBase[] getBiomeBlock(BiomeBase[] var1, int var2, int var3, int var4, int var5) { + return this.a(var1, var2, var3, var4, var5, true); + } + + public BiomeBase[] a(BiomeBase[] var1, int var2, int var3, int var4, int var5, boolean var6) { + IntCache.a(); + if (var1 == null || var1.length < var4 * var5) { + var1 = new BiomeBase[var4 * var5]; + } + + if (var6 && var4 == 16 && var5 == 16 && (var2 & 15) == 0 && (var3 & 15) == 0) { + BiomeBase[] var9 = this.d.c(var2, var3); + System.arraycopy(var9, 0, var1, 0, var4 * var5); + } else { + int[] var7 = this.c.a(var2, var3, var4, var5); + + for(int var8 = 0; var8 < var4 * var5; ++var8) { + var1[var8] = BiomeBase.getBiome(var7[var8], BiomeBase.ad); + } + + } + return var1; + } + + public boolean a(int var1, int var2, int var3, List var4) { + IntCache.a(); + int var5 = var1 - var3 >> 2; + int var6 = var2 - var3 >> 2; + int var7 = var1 + var3 >> 2; + int var8 = var2 + var3 >> 2; + int var9 = var7 - var5 + 1; + int var10 = var8 - var6 + 1; + int[] var11 = this.b.a(var5, var6, var9, var10); + + try { + for(int var12 = 0; var12 < var9 * var10; ++var12) { + BiomeBase var16 = BiomeBase.getBiome(var11[var12]); + if (!var4.contains(var16)) { + return false; + } + } + + return true; + } catch (Throwable var15) { + CrashReport var13 = CrashReport.a(var15, "Invalid Biome id"); + CrashReportSystemDetails var14 = var13.a("Layer"); + var14.a("Layer", this.b.toString()); + var14.a("x", var1); + var14.a("z", var2); + var14.a("radius", var3); + var14.a("allowed", var4); + throw new ReportedException(var13); + } + } + + public BlockPosition a(int var1, int var2, int var3, List var4, Random var5) { + IntCache.a(); + int var6 = var1 - var3 >> 2; + int var7 = var2 - var3 >> 2; + int var8 = var1 + var3 >> 2; + int var9 = var2 + var3 >> 2; + int var10 = var8 - var6 + 1; + int var11 = var9 - var7 + 1; + int[] var12 = this.b.a(var6, var7, var10, var11); + BlockPosition var13 = null; + int var14 = 0; + + for(int var15 = 0; var15 < var10 * var11; ++var15) { + int var16 = var6 + var15 % var10 << 2; + int var17 = var7 + var15 / var10 << 2; + BiomeBase var18 = BiomeBase.getBiome(var12[var15]); + if (var4.contains(var18) && (var13 == null || var5.nextInt(var14 + 1) == 0)) { + var13 = new BlockPosition(var16, 0, var17); + ++var14; + } + } + + return var13; + } + + public void b() { + this.d.a(); + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldChunkManagerHell.java b/azurite-server/src/main/java/net/minecraft/server/WorldChunkManagerHell.java new file mode 100644 index 0000000..bdea69f --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldChunkManagerHell.java @@ -0,0 +1,59 @@ +package net.minecraft.server; + +import java.util.Arrays; +import java.util.List; +import java.util.Random; + +public class WorldChunkManagerHell extends WorldChunkManager { + + private BiomeBase b; + private float c; + + public WorldChunkManagerHell(BiomeBase biomebase, float f) { + this.b = biomebase; + this.c = f; + } + + public BiomeBase getBiome(BlockPosition blockposition) { + return this.b; + } + + public BiomeBase[] getBiomes(BiomeBase[] abiomebase, int i, int j, int k, int l) { + if (abiomebase == null || abiomebase.length < k * l) { + abiomebase = new BiomeBase[k * l]; + } + + Arrays.fill(abiomebase, 0, k * l, this.b); + return abiomebase; + } + + public float[] getWetness(float[] afloat, int i, int j, int k, int l) { + if (afloat == null || afloat.length < k * l) { + afloat = new float[k * l]; + } + + Arrays.fill(afloat, 0, k * l, this.c); + return afloat; + } + + public BiomeBase[] getBiomeBlock(BiomeBase[] abiomebase, int i, int j, int k, int l) { + if (abiomebase == null || abiomebase.length < k * l) { + abiomebase = new BiomeBase[k * l]; + } + + Arrays.fill(abiomebase, 0, k * l, this.b); + return abiomebase; + } + + public BiomeBase[] a(BiomeBase[] abiomebase, int i, int j, int k, int l, boolean flag) { + return this.getBiomeBlock(abiomebase, i, j, k, l); + } + + public BlockPosition a(int i, int j, int k, List list, Random random) { + return list.contains(this.b) ? new BlockPosition(i - k + random.nextInt(k * 2 + 1), 0, j - k + random.nextInt(k * 2 + 1)) : null; + } + + public boolean a(int i, int j, int k, List list) { + return list.contains(this.b); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldData.java b/azurite-server/src/main/java/net/minecraft/server/WorldData.java new file mode 100644 index 0000000..dcbb9bb --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldData.java @@ -0,0 +1,675 @@ +package net.minecraft.server; + +import org.bukkit.Bukkit; +import org.bukkit.event.weather.ThunderChangeEvent; +import org.bukkit.event.weather.WeatherChangeEvent; + +import java.util.concurrent.Callable; +// CraftBukkit end + +public class WorldData { + + public static final EnumDifficulty a = EnumDifficulty.NORMAL; + private long b; + private WorldType c; + private String d; + private int e; + private int f; + private int g; + private long h; + private long i; + private long j; + private long k; + private NBTTagCompound l; + private int m; + private String n; + private int o; + private int p; + private boolean q; + private int r; + private boolean s; + private int t; + private WorldSettings.EnumGamemode u; + private boolean v; + private boolean w; + private boolean x; + private boolean y; + private EnumDifficulty z; + private boolean A; + private double B; + private double C; + private double D; + private long E; + private double F; + private double G; + private double H; + private int I; + private int J; + private GameRules K; + public WorldServer world; // CraftBukkit + + protected WorldData() { + this.c = WorldType.NORMAL; + this.d = ""; + this.B = 0.0D; + this.C = 0.0D; + this.D = 6.0E7D; + this.E = 0L; + this.F = 0.0D; + this.G = 5.0D; + this.H = 0.2D; + this.I = 5; + this.J = 15; + this.K = new GameRules(); + } + + public WorldData(NBTTagCompound nbttagcompound) { + this.c = WorldType.NORMAL; + this.d = ""; + this.B = 0.0D; + this.C = 0.0D; + this.D = 6.0E7D; + this.E = 0L; + this.F = 0.0D; + this.G = 5.0D; + this.H = 0.2D; + this.I = 5; + this.J = 15; + this.K = new GameRules(); + this.b = nbttagcompound.getLong("RandomSeed"); + if (nbttagcompound.hasKeyOfType("generatorName", 8)) { + String s = nbttagcompound.getString("generatorName"); + this.c = WorldType.getType(s); + if (this.c == null) { + this.c = WorldType.NORMAL; + } else if (this.c.f()) { + int i = 0; + if (nbttagcompound.hasKeyOfType("generatorVersion", 99)) + i = nbttagcompound.getInt("generatorVersion"); + this.c = this.c.a(i); + } + if (nbttagcompound.hasKeyOfType("generatorOptions", 8)) + this.d = nbttagcompound.getString("generatorOptions"); + } + this.u = WorldSettings.EnumGamemode.getById(nbttagcompound.getInt("GameType")); + if (nbttagcompound.hasKeyOfType("MapFeatures", 99)) { + this.v = nbttagcompound.getBoolean("MapFeatures"); + } else { + this.v = true; + } + this.e = nbttagcompound.getInt("SpawnX"); + this.f = nbttagcompound.getInt("SpawnY"); + this.g = nbttagcompound.getInt("SpawnZ"); + this.h = nbttagcompound.getLong("Time"); + if (nbttagcompound.hasKeyOfType("DayTime", 99)) { + this.i = nbttagcompound.getLong("DayTime"); + } else { + this.i = this.h; + } + this.j = nbttagcompound.getLong("LastPlayed"); + this.k = nbttagcompound.getLong("SizeOnDisk"); + this.n = nbttagcompound.getString("LevelName"); + this.o = nbttagcompound.getInt("version"); + this.p = nbttagcompound.getInt("clearWeatherTime"); + this.r = nbttagcompound.getInt("rainTime"); + this.q = nbttagcompound.getBoolean("raining"); + this.t = nbttagcompound.getInt("thunderTime"); + this.s = nbttagcompound.getBoolean("thundering"); + this.w = nbttagcompound.getBoolean("hardcore"); + if (nbttagcompound.hasKeyOfType("initialized", 99)) { + this.y = nbttagcompound.getBoolean("initialized"); + } else { + this.y = true; + } + if (nbttagcompound.hasKeyOfType("allowCommands", 99)) { + this.x = nbttagcompound.getBoolean("allowCommands"); + } else { + this.x = (this.u == WorldSettings.EnumGamemode.CREATIVE); + } + if (nbttagcompound.hasKeyOfType("Player", 10)) { + this.l = nbttagcompound.getCompound("Player"); + this.m = this.l.getInt("Dimension"); + } + if (nbttagcompound.hasKeyOfType("GameRules", 10)) + this.K.a(nbttagcompound.getCompound("GameRules")); + if (nbttagcompound.hasKeyOfType("Difficulty", 99)) + this.z = EnumDifficulty.getById(nbttagcompound.getByte("Difficulty")); + if (nbttagcompound.hasKeyOfType("DifficultyLocked", 1)) + this.A = nbttagcompound.getBoolean("DifficultyLocked"); + if (nbttagcompound.hasKeyOfType("BorderCenterX", 99)) + this.B = nbttagcompound.getDouble("BorderCenterX"); + if (nbttagcompound.hasKeyOfType("BorderCenterZ", 99)) + this.C = nbttagcompound.getDouble("BorderCenterZ"); + if (nbttagcompound.hasKeyOfType("BorderSize", 99)) + this.D = nbttagcompound.getDouble("BorderSize"); + if (nbttagcompound.hasKeyOfType("BorderSizeLerpTime", 99)) + this.E = nbttagcompound.getLong("BorderSizeLerpTime"); + if (nbttagcompound.hasKeyOfType("BorderSizeLerpTarget", 99)) + this.F = nbttagcompound.getDouble("BorderSizeLerpTarget"); + if (nbttagcompound.hasKeyOfType("BorderSafeZone", 99)) + this.G = nbttagcompound.getDouble("BorderSafeZone"); + if (nbttagcompound.hasKeyOfType("BorderDamagePerBlock", 99)) + this.H = nbttagcompound.getDouble("BorderDamagePerBlock"); + if (nbttagcompound.hasKeyOfType("BorderWarningBlocks", 99)) + this.I = nbttagcompound.getInt("BorderWarningBlocks"); + if (nbttagcompound.hasKeyOfType("BorderWarningTime", 99)) + this.J = nbttagcompound.getInt("BorderWarningTime"); + } + + public WorldData(WorldSettings worldsettings, String s) { + this.c = WorldType.NORMAL; + this.d = ""; + this.B = 0.0D; + this.C = 0.0D; + this.D = 6.0E7D; + this.E = 0L; + this.F = 0.0D; + this.G = 5.0D; + this.H = 0.2D; + this.I = 5; + this.J = 15; + this.K = new GameRules(); + a(worldsettings); + this.n = s; + this.z = a; + this.y = false; + } + + public void a(WorldSettings worldsettings) { + this.b = worldsettings.d(); + this.u = worldsettings.e(); + this.v = worldsettings.g(); + this.w = worldsettings.f(); + this.c = worldsettings.h(); + this.d = worldsettings.j(); + this.x = worldsettings.i(); + } + + public WorldData(WorldData worlddata) { + this.c = WorldType.NORMAL; + this.d = ""; + this.B = 0.0D; + this.C = 0.0D; + this.D = 6.0E7D; + this.E = 0L; + this.F = 0.0D; + this.G = 5.0D; + this.H = 0.2D; + this.I = 5; + this.J = 15; + this.K = new GameRules(); + this.b = worlddata.b; + this.c = worlddata.c; + this.d = worlddata.d; + this.u = worlddata.u; + this.v = worlddata.v; + this.e = worlddata.e; + this.f = worlddata.f; + this.g = worlddata.g; + this.h = worlddata.h; + this.i = worlddata.i; + this.j = worlddata.j; + this.k = worlddata.k; + this.l = worlddata.l; + this.m = worlddata.m; + this.n = worlddata.n; + this.o = worlddata.o; + this.r = worlddata.r; + this.q = worlddata.q; + this.t = worlddata.t; + this.s = worlddata.s; + this.w = worlddata.w; + this.x = worlddata.x; + this.y = worlddata.y; + this.K = worlddata.K; + this.z = worlddata.z; + this.A = worlddata.A; + this.B = worlddata.B; + this.C = worlddata.C; + this.D = worlddata.D; + this.E = worlddata.E; + this.F = worlddata.F; + this.G = worlddata.G; + this.H = worlddata.H; + this.J = worlddata.J; + this.I = worlddata.I; + } + + public NBTTagCompound a() { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + + this.a(nbttagcompound, this.l); + return nbttagcompound; + } + + public NBTTagCompound a(NBTTagCompound nbttagcompound) { + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + + this.a(nbttagcompound1, nbttagcompound); + return nbttagcompound1; + } + + private void a(NBTTagCompound nbttagcompound, NBTTagCompound nbttagcompound1) { + nbttagcompound.setLong("RandomSeed", this.b); + nbttagcompound.setString("generatorName", this.c.name()); + nbttagcompound.setInt("generatorVersion", this.c.getVersion()); + nbttagcompound.setString("generatorOptions", this.d); + nbttagcompound.setInt("GameType", this.u.getId()); + nbttagcompound.setBoolean("MapFeatures", this.v); + nbttagcompound.setInt("SpawnX", this.e); + nbttagcompound.setInt("SpawnY", this.f); + nbttagcompound.setInt("SpawnZ", this.g); + nbttagcompound.setLong("Time", this.h); + nbttagcompound.setLong("DayTime", this.i); + nbttagcompound.setLong("SizeOnDisk", this.k); + nbttagcompound.setLong("LastPlayed", MinecraftServer.az()); + nbttagcompound.setString("LevelName", this.n); + nbttagcompound.setInt("version", this.o); + nbttagcompound.setInt("clearWeatherTime", this.p); + nbttagcompound.setInt("rainTime", this.r); + nbttagcompound.setBoolean("raining", this.q); + nbttagcompound.setInt("thunderTime", this.t); + nbttagcompound.setBoolean("thundering", this.s); + nbttagcompound.setBoolean("hardcore", this.w); + nbttagcompound.setBoolean("allowCommands", this.x); + nbttagcompound.setBoolean("initialized", this.y); + nbttagcompound.setDouble("BorderCenterX", this.B); + nbttagcompound.setDouble("BorderCenterZ", this.C); + nbttagcompound.setDouble("BorderSize", this.D); + nbttagcompound.setLong("BorderSizeLerpTime", this.E); + nbttagcompound.setDouble("BorderSafeZone", this.G); + nbttagcompound.setDouble("BorderDamagePerBlock", this.H); + nbttagcompound.setDouble("BorderSizeLerpTarget", this.F); + nbttagcompound.setDouble("BorderWarningBlocks", this.I); + nbttagcompound.setDouble("BorderWarningTime", this.J); + if (this.z != null) { + nbttagcompound.setByte("Difficulty", (byte) this.z.a()); + } + + nbttagcompound.setBoolean("DifficultyLocked", this.A); + nbttagcompound.set("GameRules", this.K.a()); + if (nbttagcompound1 != null) { + nbttagcompound.set("Player", nbttagcompound1); + } + + } + + public long getSeed() { + return this.b; + } + + public int c() { + return this.e; + } + + public int d() { + return this.f; + } + + public int e() { + return this.g; + } + + public long getTime() { + return this.h; + } + + public long getDayTime() { + return this.i; + } + + public NBTTagCompound i() { + return this.l; + } + + public void setTime(long i) { + this.h = i; + } + + public void setDayTime(long i) { + this.i = i; + } + + public void setSpawn(BlockPosition blockposition) { + this.e = blockposition.getX(); + this.f = blockposition.getY(); + this.g = blockposition.getZ(); + } + + public String getName() { + return this.n; + } + + public void a(String s) { + this.n = s; + } + + public int l() { + return this.o; + } + + public void e(int i) { + this.o = i; + } + + public int A() { + return this.p; + } + + public void i(int i) { + this.p = i; + } + + public boolean isThundering() { + return this.s; + } + + public void setThundering(boolean flag) { + // CraftBukkit start + org.bukkit.World world = Bukkit.getWorld(getName()); + if (world != null) { + ThunderChangeEvent thunder = new ThunderChangeEvent(world, flag); + Bukkit.getServer().getPluginManager().callEvent(thunder); + if (thunder.isCancelled()) { + return; + } + + setThunderDuration(0); // Will force a time reset + } + // CraftBukkit end + this.s = flag; + } + + public int getThunderDuration() { + return this.t; + } + + public void setThunderDuration(int i) { + this.t = i; + } + + public boolean hasStorm() { + return this.q; + } + + public void setStorm(boolean flag) { + // CraftBukkit start + org.bukkit.World world = Bukkit.getWorld(getName()); + if (world != null) { + WeatherChangeEvent weather = new WeatherChangeEvent(world, flag); + Bukkit.getServer().getPluginManager().callEvent(weather); + if (weather.isCancelled()) { + return; + } + + setWeatherDuration(0); // Will force a time reset + } + // CraftBukkit end + this.q = flag; + } + + public int getWeatherDuration() { + return this.r; + } + + public void setWeatherDuration(int i) { + this.r = i; + } + + public WorldSettings.EnumGamemode getGameType() { + return this.u; + } + + public boolean shouldGenerateMapFeatures() { + return this.v; + } + + public void f(boolean flag) { + this.v = flag; + } + + public void setGameType(WorldSettings.EnumGamemode worldsettings_enumgamemode) { + this.u = worldsettings_enumgamemode; + } + + public boolean isHardcore() { + return this.w; + } + + public void g(boolean flag) { + this.w = flag; + } + + public WorldType getType() { + return this.c; + } + + public void a(WorldType worldtype) { + this.c = worldtype; + } + + public String getGeneratorOptions() { + return this.d; + } + + public boolean v() { + return this.x; + } + + public void c(boolean flag) { + this.x = flag; + } + + public boolean w() { + return this.y; + } + + public void d(boolean flag) { + this.y = flag; + } + + public GameRules x() { + return this.K; + } + + public double C() { + return this.B; + } + + public double D() { + return this.C; + } + + public double E() { + return this.D; + } + + public void a(double d0) { + this.D = d0; + } + + public long F() { + return this.E; + } + + public void e(long i) { + this.E = i; + } + + public double G() { + return this.F; + } + + public void b(double d0) { + this.F = d0; + } + + public void c(double d0) { + this.C = d0; + } + + public void d(double d0) { + this.B = d0; + } + + public double H() { + return this.G; + } + + public void e(double d0) { + this.G = d0; + } + + public double I() { + return this.H; + } + + public void f(double d0) { + this.H = d0; + } + + public int J() { + return this.I; + } + + public int K() { + return this.J; + } + + public void j(int i) { + this.I = i; + } + + public void k(int i) { + this.J = i; + } + + public EnumDifficulty getDifficulty() { + return this.z; + } + + public void setDifficulty(EnumDifficulty enumdifficulty) { + this.z = enumdifficulty; + // CraftBukkit start + PacketPlayOutServerDifficulty packet = new PacketPlayOutServerDifficulty(this.getDifficulty(), this.isDifficultyLocked()); + + for (EntityHuman player : world.players) { + ((EntityPlayer) player).playerConnection.sendPacket(packet); + } + // CraftBukkit end + } + + public boolean isDifficultyLocked() { + return this.A; + } + + public void e(boolean flag) { + this.A = flag; + } + + public void a(CrashReportSystemDetails crashreportsystemdetails) { + crashreportsystemdetails.a("Level seed", new Callable() { + public String a() { + return String.valueOf(WorldData.this.getSeed()); + } + + public Object call() { + return this.a(); + } + }); + crashreportsystemdetails.a("Level generator", new Callable() { + public String a() { + return String.format("ID %02d - %s, ver %d. Features enabled: %b", WorldData.this.c.g(), WorldData.this.c.name(), WorldData.this.c.getVersion(), WorldData.this.v); + } + + public Object call() { + return this.a(); + } + }); + crashreportsystemdetails.a("Level generator options", new Callable() { + public String a() { + return WorldData.this.d; + } + + public Object call() { + return this.a(); + } + }); + crashreportsystemdetails.a("Level spawn location", new Callable() { + public String a() { + return CrashReportSystemDetails.a(WorldData.this.e, WorldData.this.f, WorldData.this.g); + } + + public Object call() { + return this.a(); + } + }); + crashreportsystemdetails.a("Level time", new Callable() { + public String a() { + return String.format("%d game time, %d day time", WorldData.this.h, WorldData.this.i); + } + + public Object call() { + return this.a(); + } + }); + crashreportsystemdetails.a("Level dimension", new Callable() { + public String a() { + return String.valueOf(WorldData.this.m); + } + + public Object call() { + return this.a(); + } + }); + crashreportsystemdetails.a("Level storage version", new Callable() { + public String a() { + String s = "Unknown?"; + + try { + switch (WorldData.this.o) { + case 19132: + s = "McRegion"; + break; + + case 19133: + s = "Anvil"; + } + } catch (Throwable ignored) { + } + + return String.format("0x%05X - %s", WorldData.this.o, s); + } + + public Object call() { + return this.a(); + } + }); + crashreportsystemdetails.a("Level weather", new Callable() { + public String a() { + return String.format("Rain time: %d (now: %b), thunder time: %d (now: %b)", WorldData.this.r, WorldData.this.q, WorldData.this.t, WorldData.this.s); + } + + public Object call() { + return this.a(); + } + }); + crashreportsystemdetails.a("Level game mode", new Callable() { + public String a() { + return String.format("Game mode: %s (ID %d). Hardcore: %b. Cheats: %b", WorldData.this.u.b(), WorldData.this.u.getId(), WorldData.this.w, WorldData.this.x); + } + + public Object call() { + return this.a(); + } + }); + } + + // CraftBukkit start - Check if the name stored in NBT is the correct one + public void checkName(String name) { + if (!this.n.equals(name)) { + this.n = name; + } + } + // CraftBukkit end +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenAcaciaTree.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenAcaciaTree.java new file mode 100644 index 0000000..9daefcb --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenAcaciaTree.java @@ -0,0 +1,176 @@ +package net.minecraft.server; + +import java.util.Random; + +public class WorldGenAcaciaTree extends WorldGenTreeAbstract { + + private static final IBlockData a = Blocks.LOG2.getBlockData().set(BlockLog2.VARIANT, BlockWood.EnumLogVariant.ACACIA); + private static final IBlockData b = Blocks.LEAVES2.getBlockData().set(BlockLeaves2.VARIANT, BlockWood.EnumLogVariant.ACACIA).set(BlockLeaves.CHECK_DECAY, Boolean.FALSE); + + public WorldGenAcaciaTree(boolean flag) { + super(flag); + } + + public boolean generate(World world, Random random, BlockPosition blockposition) { + int i = random.nextInt(3) + random.nextInt(3) + 5; + boolean flag = true; + + if (blockposition.getY() >= 1 && blockposition.getY() + i + 1 <= 256) { + int j; + int k; + + for (int l = blockposition.getY(); l <= blockposition.getY() + 1 + i; ++l) { + byte b0 = 1; + + if (l == blockposition.getY()) { + b0 = 0; + } + + if (l >= blockposition.getY() + 1 + i - 2) { + b0 = 2; + } + + for (j = blockposition.getX() - b0; j <= blockposition.getX() + b0 && flag; ++j) { + for (k = blockposition.getZ() - b0; k <= blockposition.getZ() + b0 && flag; ++k) { + if (l >= 0 && l < 256) { + if (!this.a(world.getType(j, l, k).getBlock())) { + flag = false; + } + } else { + flag = false; + } + } + } + } + + if (!flag) { + return false; + } else { + Block block = world.getType(blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()).getBlock(); + + if ((block == Blocks.GRASS || block == Blocks.DIRT) && blockposition.getY() < 256 - i - 1) { + this.a(world, blockposition.down()); + EnumDirection enumdirection = EnumDirection.EnumDirectionLimit.HORIZONTAL.a(random); + int i1 = i - random.nextInt(4) - 1; + + j = 3 - random.nextInt(3); + k = blockposition.getX(); + int j1 = blockposition.getZ(); + int k1 = 0; + + int l1; + + for (int i2 = 0; i2 < i; ++i2) { + l1 = blockposition.getY() + i2; + if (i2 >= i1 && j > 0) { + k += enumdirection.getAdjacentX(); + j1 += enumdirection.getAdjacentZ(); + --j; + } + + Material material = world.getType(k, l1, j1).getBlock().getMaterial(); + + if (material == Material.AIR || material == Material.LEAVES) { + this.b(world, new BlockPosition(k, l1, j1)); + k1 = l1; + } + } + + BlockPosition blockposition2 = new BlockPosition(k, k1, j1); + + int j2; + + for (l1 = -3; l1 <= 3; ++l1) { + for (j2 = -3; j2 <= 3; ++j2) { + if (Math.abs(l1) != 3 || Math.abs(j2) != 3) { + this.c(world, blockposition2.a(l1, 0, j2)); + } + } + } + + blockposition2 = blockposition2.up(); + + for (l1 = -1; l1 <= 1; ++l1) { + for (j2 = -1; j2 <= 1; ++j2) { + this.c(world, blockposition2.a(l1, 0, j2)); + } + } + + this.c(world, blockposition2.east(2)); + this.c(world, blockposition2.west(2)); + this.c(world, blockposition2.south(2)); + this.c(world, blockposition2.north(2)); + k = blockposition.getX(); + j1 = blockposition.getZ(); + EnumDirection enumdirection1 = EnumDirection.EnumDirectionLimit.HORIZONTAL.a(random); + + if (enumdirection1 != enumdirection) { + l1 = i1 - random.nextInt(2) - 1; + j2 = 1 + random.nextInt(3); + k1 = 0; + + int k2; + + for (int l2 = l1; l2 < i && j2 > 0; --j2) { + if (l2 >= 1) { + k2 = blockposition.getY() + l2; + k += enumdirection1.getAdjacentX(); + j1 += enumdirection1.getAdjacentZ(); + + Material material1 = world.getType(k, k2, j1).getBlock().getMaterial(); + + if (material1 == Material.AIR || material1 == Material.LEAVES) { + this.b(world, new BlockPosition(k, k2, j1)); + k1 = k2; + } + } + + ++l2; + } + + if (k1 > 0) { + BlockPosition blockposition4 = new BlockPosition(k, k1, j1); + + int i3; + + for (k2 = -2; k2 <= 2; ++k2) { + for (i3 = -2; i3 <= 2; ++i3) { + if (Math.abs(k2) != 2 || Math.abs(i3) != 2) { + this.c(world, blockposition4.a(k2, 0, i3)); + } + } + } + + blockposition4 = blockposition4.up(); + + for (k2 = -1; k2 <= 1; ++k2) { + for (i3 = -1; i3 <= 1; ++i3) { + this.c(world, blockposition4.a(k2, 0, i3)); + } + } + } + } + + return true; + } else { + return false; + } + } + } else { + return false; + } + } + + private void b(World world, BlockPosition blockposition) { + this.a(world, blockposition, WorldGenAcaciaTree.a); + } + + private void c(World world, BlockPosition blockposition) { + Material material = world.getType(blockposition).getBlock().getMaterial(); + + if (material == Material.AIR || material == Material.LEAVES) { + this.a(world, blockposition, WorldGenAcaciaTree.b); + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenBase.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenBase.java new file mode 100644 index 0000000..3290a5d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenBase.java @@ -0,0 +1,36 @@ +package net.minecraft.server; + +import java.util.Random; + +public class WorldGenBase { + + protected int a = 8; + protected Random b = new Random(); + protected World c; + + public WorldGenBase() { + } + + public void a(IChunkProvider ichunkprovider, World world, int i, int j, ChunkSnapshot chunksnapshot) { + int k = this.a; + + this.c = world; + this.b.setSeed(world.getSeed()); + long l = this.b.nextLong(); + long i1 = this.b.nextLong(); + + for (int j1 = i - k; j1 <= i + k; ++j1) { + for (int k1 = j - k; k1 <= j + k; ++k1) { + long l1 = (long) j1 * l; + long i2 = (long) k1 * i1; + + this.b.setSeed(l1 ^ i2 ^ world.getSeed()); + this.a(world, j1, k1, i, j, chunksnapshot); + } + } + + } + + protected void a(World world, int i, int j, int k, int l, ChunkSnapshot chunksnapshot) { + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenBigTree.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenBigTree.java new file mode 100644 index 0000000..2568013 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenBigTree.java @@ -0,0 +1,285 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; + +import java.util.List; +import java.util.Random; + +public class WorldGenBigTree extends WorldGenTreeAbstract { + + private Random k; + private World l; + private BlockPosition m; + int a; + int b; + double c; + double d; + double e; + double f; + int g; + int h; + int i; + List j; + + public WorldGenBigTree(boolean flag) { + super(flag); + this.m = BlockPosition.ZERO; + this.c = 0.618D; + this.d = 0.381D; + this.e = 1.0D; + this.f = 1.0D; + this.g = 1; + this.h = 12; + this.i = 4; + } + + void a() { + this.b = (int) ((double) this.a * this.c); + if (this.b >= this.a) { + this.b = this.a - 1; + } + + int i = (int) (1.382D + Math.pow(this.f * (double) this.a / 13.0D, 2.0D)); + + if (i < 1) { + i = 1; + } + + int j = this.m.getY() + this.b; + int k = this.a - this.i; + + this.j = Lists.newArrayList(); + this.j.add(new Position(this.m.up(k), j)); + + for (; k >= 0; --k) { + float f = this.a(k); + + if (f >= 0.0F) { + for (int l = 0; l < i; ++l) { + double d0 = this.e * (double) f * ((double) this.k.nextFloat() + 0.328D); + double d1 = (double) (this.k.nextFloat() * 2.0F) * 3.141592653589793D; + double d2 = d0 * Math.sin(d1) + 0.5D; + double d3 = d0 * Math.cos(d1) + 0.5D; + BlockPosition blockposition = this.m.a(d2, k - 1, d3); + BlockPosition blockposition1 = blockposition.up(this.i); + + if (this.a(blockposition, blockposition1) == -1) { + int i1 = this.m.getX() - blockposition.getX(); + int j1 = this.m.getZ() - blockposition.getZ(); + double d4 = (double) blockposition.getY() - Math.sqrt(i1 * i1 + j1 * j1) * this.d; + int k1 = d4 > (double) j ? j : (int) d4; + BlockPosition blockposition2 = new BlockPosition(this.m.getX(), k1, this.m.getZ()); + + if (this.a(blockposition2, blockposition) == -1) { + this.j.add(new Position(blockposition, blockposition2.getY())); + } + } + } + } + } + + } + + void a(BlockPosition blockposition, float f, IBlockData iblockdata) { + int i = (int) ((double) f + 0.618D); + + for (int j = -i; j <= i; ++j) { + for (int k = -i; k <= i; ++k) { + if (Math.pow((double) Math.abs(j) + 0.5D, 2.0D) + Math.pow((double) Math.abs(k) + 0.5D, 2.0D) <= (double) (f * f)) { + BlockPosition blockposition1 = blockposition.a(j, 0, k); + Material material = this.l.getType(blockposition1).getBlock().getMaterial(); + + if (material == Material.AIR || material == Material.LEAVES) { + this.a(this.l, blockposition1, iblockdata); + } + } + } + } + + } + + float a(int i) { + if ((float) i < (float) this.a * 0.3F) { + return -1.0F; + } else { + float f = (float) this.a / 2.0F; + float f1 = f - (float) i; + float f2 = MathHelper.c(f * f - f1 * f1); + + if (f1 == 0.0F) { + f2 = f; + } else if (Math.abs(f1) >= f) { + return 0.0F; + } + + return f2 * 0.5F; + } + } + + float b(int i) { + return i >= 0 && i < this.i ? (i != 0 && i != this.i - 1 ? 3.0F : 2.0F) : -1.0F; + } + + void a(BlockPosition blockposition) { + for (int i = 0; i < this.i; ++i) { + this.a(blockposition.up(i), this.b(i), Blocks.LEAVES.getBlockData().set(BlockLeaves.CHECK_DECAY, Boolean.FALSE)); + } + + } + + void a(BlockPosition blockposition, BlockPosition blockposition1, Block block) { + BlockPosition blockposition2 = blockposition1.a(-blockposition.getX(), -blockposition.getY(), -blockposition.getZ()); + int i = this.b(blockposition2); + float f = (float) blockposition2.getX() / (float) i; + float f1 = (float) blockposition2.getY() / (float) i; + float f2 = (float) blockposition2.getZ() / (float) i; + + for (int j = 0; j <= i; ++j) { + BlockPosition blockposition3 = blockposition.a(0.5F + (float) j * f, 0.5F + (float) j * f1, 0.5F + (float) j * f2); + BlockLogAbstract.EnumLogRotation blocklogabstract_enumlogrotation = this.b(blockposition, blockposition3); + + this.a(this.l, blockposition3, block.getBlockData().set(BlockLogAbstract.AXIS, blocklogabstract_enumlogrotation)); + } + + } + + private int b(BlockPosition blockposition) { + int i = MathHelper.a(blockposition.getX()); + int j = MathHelper.a(blockposition.getY()); + int k = MathHelper.a(blockposition.getZ()); + + return k > i && k > j ? k : (Math.max(j, i)); + } + + private BlockLogAbstract.EnumLogRotation b(BlockPosition blockposition, BlockPosition blockposition1) { + BlockLogAbstract.EnumLogRotation blocklogabstract_enumlogrotation = BlockLogAbstract.EnumLogRotation.Y; + int i = Math.abs(blockposition1.getX() - blockposition.getX()); + int j = Math.abs(blockposition1.getZ() - blockposition.getZ()); + int k = Math.max(i, j); + + if (k > 0) { + if (i == k) { + blocklogabstract_enumlogrotation = BlockLogAbstract.EnumLogRotation.X; + } else { + blocklogabstract_enumlogrotation = BlockLogAbstract.EnumLogRotation.Z; + } + } + + return blocklogabstract_enumlogrotation; + } + + void b() { + + for (Position worldgenbigtree_position : this.j) { + this.a(worldgenbigtree_position); + } + + } + + boolean c(int i) { + return (double) i >= (double) this.a * 0.2D; + } + + void c() { + BlockPosition blockposition = this.m; + BlockPosition blockposition1 = this.m.up(this.b); + Block block = Blocks.LOG; + + this.a(blockposition, blockposition1, block); + if (this.g == 2) { + this.a(blockposition.east(), blockposition1.east(), block); + this.a(blockposition.east().south(), blockposition1.east().south(), block); + this.a(blockposition.south(), blockposition1.south(), block); + } + + } + + void d() { + + for (Position worldgenbigtree_position : this.j) { + int i = worldgenbigtree_position.q(); + BlockPosition blockposition = new BlockPosition(this.m.getX(), i, this.m.getZ()); + + if (!blockposition.equals(worldgenbigtree_position) && this.c(i - this.m.getY())) { + this.a(blockposition, worldgenbigtree_position, Blocks.LOG); + } + } + + } + + int a(BlockPosition blockposition, BlockPosition blockposition1) { + BlockPosition blockposition2 = blockposition1.a(-blockposition.getX(), -blockposition.getY(), -blockposition.getZ()); + int i = this.b(blockposition2); + float f = (float) blockposition2.getX() / (float) i; + float f1 = (float) blockposition2.getY() / (float) i; + float f2 = (float) blockposition2.getZ() / (float) i; + + if (i != 0) { + for (int j = 0; j <= i; ++j) { + BlockPosition blockposition3 = blockposition.a(0.5F + (float) j * f, 0.5F + (float) j * f1, 0.5F + (float) j * f2); + + if (!this.a(this.l.getType(blockposition3).getBlock())) { + return j; + } + } + + } + return -1; + } + + public void e() { + this.i = 5; + } + + public boolean generate(World world, Random random, BlockPosition blockposition) { + this.l = world; + this.m = blockposition; + this.k = new Random(random.nextLong()); + if (this.a == 0) { + this.a = 5 + this.k.nextInt(this.h); + } + + if (!this.f()) { + return false; + } else { + this.a(); + this.b(); + this.c(); + this.d(); + return true; + } + } + + private boolean f() { + Block block = this.l.getType(m.getX(), m.getY() - 1, m.getZ()).getBlock(); + + if (block != Blocks.DIRT && block != Blocks.GRASS && block != Blocks.FARMLAND) { + return false; + } else { + int i = this.a(this.m, this.m.up(this.a - 1)); + + if (i == -1) { + return true; + } else if (i < 6) { + return false; + } else { + this.a = i; + return true; + } + } + } + + static class Position extends BlockPosition { + + private final int c; + + public Position(BlockPosition blockposition, int i) { + super(blockposition.getX(), blockposition.getY(), blockposition.getZ()); + this.c = i; + } + + public int q() { + return this.c; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenBonusChest.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenBonusChest.java new file mode 100644 index 0000000..07f06ad --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenBonusChest.java @@ -0,0 +1,65 @@ +package net.minecraft.server; + +import java.util.List; +import java.util.Random; + +public class WorldGenBonusChest extends WorldGenerator { + + private final List a; + private final int b; + + public WorldGenBonusChest(List list, int i) { + this.a = list; + this.b = i; + } + + public boolean generate(World world, Random random, BlockPosition blockposition) { + Block block; + + while (((block = world.getType(blockposition).getBlock()).getMaterial() == Material.AIR || block.getMaterial() == Material.LEAVES) && blockposition.getY() > 1) { + blockposition = blockposition.down(); + } + + if (blockposition.getY() >= 1) { + blockposition = blockposition.up(); + + for (int i = 0; i < 4; ++i) { + BlockPosition blockposition1 = blockposition.a(random.nextInt(4) - random.nextInt(4), random.nextInt(3) - random.nextInt(3), random.nextInt(4) - random.nextInt(4)); + + if (world.isEmpty(blockposition1) && World.a(world, blockposition1.getX(), blockposition1.getY() - 1, blockposition1.getZ())) { + world.setTypeAndData(blockposition1, Blocks.CHEST.getBlockData(), 2); + TileEntity tileentity = world.getTileEntity(blockposition1); + + if (tileentity instanceof TileEntityChest) { + StructurePieceTreasure.a(random, this.a, (TileEntityChest) tileentity, this.b); + } + + BlockPosition blockposition2 = blockposition1.east(); + BlockPosition blockposition3 = blockposition1.west(); + BlockPosition blockposition4 = blockposition1.north(); + BlockPosition blockposition5 = blockposition1.south(); + + if (world.isEmpty(blockposition3) && World.a(world, blockposition3.getX(), blockposition3.getY() - 1, blockposition3.getZ())) { + world.setTypeAndData(blockposition3, Blocks.TORCH.getBlockData(), 2); + } + + if (world.isEmpty(blockposition2) && World.a(world, blockposition2.getX(), blockposition2.getY() - 1, blockposition2.getZ())) { + world.setTypeAndData(blockposition2, Blocks.TORCH.getBlockData(), 2); + } + + if (world.isEmpty(blockposition4) && World.a(world, blockposition4.getX(), blockposition4.getY() - 1, blockposition4.getZ())) { + world.setTypeAndData(blockposition4, Blocks.TORCH.getBlockData(), 2); + } + + if (world.isEmpty(blockposition5) && World.a(world, blockposition5.getX(), blockposition5.getY() - 1, blockposition5.getZ())) { + world.setTypeAndData(blockposition5, Blocks.TORCH.getBlockData(), 2); + } + + return true; + } + } + + } + return false; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenCactus.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenCactus.java new file mode 100644 index 0000000..1131c07 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenCactus.java @@ -0,0 +1,27 @@ +package net.minecraft.server; + +import java.util.Random; + +public class WorldGenCactus extends WorldGenerator { + + public WorldGenCactus() { + } + + public boolean generate(World world, Random random, BlockPosition blockposition) { + for (int i = 0; i < 10; ++i) { + BlockPosition blockposition1 = blockposition.a(random.nextInt(8) - random.nextInt(8), random.nextInt(4) - random.nextInt(4), random.nextInt(8) - random.nextInt(8)); + + if (world.isEmpty(blockposition1)) { + int j = 1 + random.nextInt(random.nextInt(3) + 1); + + for (int k = 0; k < j; ++k) { + if (Blocks.CACTUS.e(world, blockposition1)) { + world.setTypeAndData(blockposition1.up(k), Blocks.CACTUS.getBlockData(), 2); + } + } + } + } + + return true; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenCanyon.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenCanyon.java new file mode 100644 index 0000000..f1d7b2c --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenCanyon.java @@ -0,0 +1,188 @@ +package net.minecraft.server; + +import java.util.Random; + +public class WorldGenCanyon extends WorldGenBase { + + private final float[] d = new float[1024]; + + public WorldGenCanyon() { + } + + protected void a(long i, int j, int k, ChunkSnapshot chunksnapshot, double d0, double d1, double d2, float f, float f1, float f2, int l, int i1, double d3) { + Random random = new Random(i); + double d4 = (j * 16 + 8); + double d5 = (k * 16 + 8); + float f3 = 0.0F; + float f4 = 0.0F; + + if (i1 <= 0) { + int j1 = this.a * 16 - 16; + + i1 = j1 - random.nextInt(j1 / 4); + } + + boolean flag = false; + + if (l == -1) { + l = i1 / 2; + flag = true; + } + + float f5 = 1.0F; + + for (int k1 = 0; k1 < 256; ++k1) { + if (k1 == 0 || random.nextInt(3) == 0) { + f5 = 1.0F + random.nextFloat() * random.nextFloat() * 1.0F; + } + + this.d[k1] = f5 * f5; + } + + for (; l < i1; ++l) { + double d6 = 1.5D + (double) (MathHelper.sin((float) l * 3.1415927F / (float) i1) * f * 1.0F); + double d7 = d6 * d3; + + d6 *= (double) random.nextFloat() * 0.25D + 0.75D; + d7 *= (double) random.nextFloat() * 0.25D + 0.75D; + float f6 = MathHelper.cos(f2); + float f7 = MathHelper.sin(f2); + + d0 += (MathHelper.cos(f1) * f6); + d1 += f7; + d2 += (MathHelper.sin(f1) * f6); + f2 *= 0.7F; + f2 += f4 * 0.05F; + f1 += f3 * 0.05F; + f4 *= 0.8F; + f3 *= 0.5F; + f4 += (random.nextFloat() - random.nextFloat()) * random.nextFloat() * 2.0F; + f3 += (random.nextFloat() - random.nextFloat()) * random.nextFloat() * 4.0F; + if (flag || random.nextInt(4) != 0) { + double d8 = d0 - d4; + double d9 = d2 - d5; + double d10 = (i1 - l); + double d11 = (f + 2.0F + 16.0F); + + if (d8 * d8 + d9 * d9 - d10 * d10 > d11 * d11) { + return; + } + + if (d0 >= d4 - 16.0D - d6 * 2.0D && d2 >= d5 - 16.0D - d6 * 2.0D && d0 <= d4 + 16.0D + d6 * 2.0D && d2 <= d5 + 16.0D + d6 * 2.0D) { + int l1 = MathHelper.floor(d0 - d6) - j * 16 - 1; + int i2 = MathHelper.floor(d0 + d6) - j * 16 + 1; + int j2 = MathHelper.floor(d1 - d7) - 1; + int k2 = MathHelper.floor(d1 + d7) + 1; + int l2 = MathHelper.floor(d2 - d6) - k * 16 - 1; + int i3 = MathHelper.floor(d2 + d6) - k * 16 + 1; + + if (l1 < 0) { + l1 = 0; + } + + if (i2 > 16) { + i2 = 16; + } + + if (j2 < 1) { + j2 = 1; + } + + if (k2 > 248) { + k2 = 248; + } + + if (l2 < 0) { + l2 = 0; + } + + if (i3 > 16) { + i3 = 16; + } + + boolean flag1 = false; + + int j3; + + for (int k3 = l1; !flag1 && k3 < i2; ++k3) { + for (j3 = l2; !flag1 && j3 < i3; ++j3) { + for (int l3 = k2 + 1; !flag1 && l3 >= j2 - 1; --l3) { + if (l3 < 256) { + IBlockData iblockdata = chunksnapshot.a(k3, l3, j3); + + if (iblockdata.getBlock() == Blocks.FLOWING_WATER || iblockdata.getBlock() == Blocks.WATER) { + flag1 = true; + } + + if (l3 != j2 - 1 && k3 != l1 && k3 != i2 - 1 && j3 != l2 && j3 != i3 - 1) { + l3 = j2; + } + } + } + } + } + + if (!flag1) { + + for (j3 = l1; j3 < i2; ++j3) { + double d12 = ((double) (j3 + j * 16) + 0.5D - d0) / d6; + + for (int i4 = l2; i4 < i3; ++i4) { + double d13 = ((double) (i4 + k * 16) + 0.5D - d2) / d6; + boolean flag2 = false; + + if (d12 * d12 + d13 * d13 < 1.0D) { + for (int j4 = k2; j4 > j2; --j4) { + double d14 = ((double) (j4 - 1) + 0.5D - d1) / d7; + + if ((d12 * d12 + d13 * d13) * (double) this.d[j4 - 1] + d14 * d14 / 6.0D < 1.0D) { + IBlockData iblockdata1 = chunksnapshot.a(j3, j4, i4); + + if (iblockdata1.getBlock() == Blocks.GRASS) { + flag2 = true; + } + + if (iblockdata1.getBlock() == Blocks.STONE || iblockdata1.getBlock() == Blocks.DIRT || iblockdata1.getBlock() == Blocks.GRASS) { + if (j4 - 1 < 10) { + chunksnapshot.a(j3, j4, i4, Blocks.FLOWING_LAVA.getBlockData()); + } else { + chunksnapshot.a(j3, j4, i4, Blocks.AIR.getBlockData()); + if (flag2 && chunksnapshot.a(j3, j4 - 1, i4).getBlock() == Blocks.DIRT) { + chunksnapshot.a(j3, j4 - 1, i4, this.c.getBiome(j3 + j * 16, 0, i4 + k * 16).ak); + } + } + } + } + } + } + } + } + + if (flag) { + break; + } + } + } + } + } + + } + + protected void a(World world, int i, int j, int k, int l, ChunkSnapshot chunksnapshot) { + if (this.b.nextInt(50) == 0) { + double d0 = (i * 16 + this.b.nextInt(16)); + double d1 = (this.b.nextInt(this.b.nextInt(40) + 8) + 20); + double d2 = (j * 16 + this.b.nextInt(16)); + byte b0 = 1; + + for (int i1 = 0; i1 < b0; ++i1) { + float f = this.b.nextFloat() * 3.1415927F * 2.0F; + float f1 = (this.b.nextFloat() - 0.5F) * 2.0F / 8.0F; + float f2 = (this.b.nextFloat() * 2.0F + this.b.nextFloat()) * 2.0F; + + this.a(this.b.nextLong(), k, l, chunksnapshot, d0, d1, d2, f2, f, f1, 0, 0, 3.0D); + } + + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenCaves.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenCaves.java new file mode 100644 index 0000000..0a10218 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenCaves.java @@ -0,0 +1,215 @@ +package net.minecraft.server; + +import com.google.common.base.Objects; + +import java.util.Random; + +public class WorldGenCaves extends WorldGenBase { + + public WorldGenCaves() { + } + + protected void a(long i, int j, int k, ChunkSnapshot chunksnapshot, double d0, double d1, double d2) { + this.a(i, j, k, chunksnapshot, d0, d1, d2, 1.0F + this.b.nextFloat() * 6.0F, 0.0F, 0.0F, -1, -1, 0.5D); + } + + protected void a(long i, int j, int k, ChunkSnapshot chunksnapshot, double d0, double d1, double d2, float f, float f1, float f2, int l, int i1, double d3) { + double d4 = (j * 16 + 8); + double d5 = (k * 16 + 8); + float f3 = 0.0F; + float f4 = 0.0F; + Random random = new Random(i); + + if (i1 <= 0) { + int j1 = this.a * 16 - 16; + + i1 = j1 - random.nextInt(j1 / 4); + } + + boolean flag = false; + + if (l == -1) { + l = i1 / 2; + flag = true; + } + + int k1 = random.nextInt(i1 / 2) + i1 / 4; + + for (boolean flag1 = random.nextInt(6) == 0; l < i1; ++l) { + double d6 = 1.5D + (double) (MathHelper.sin((float) l * 3.1415927F / (float) i1) * f * 1.0F); + double d7 = d6 * d3; + float f5 = MathHelper.cos(f2); + float f6 = MathHelper.sin(f2); + + d0 += (MathHelper.cos(f1) * f5); + d1 += f6; + d2 += (MathHelper.sin(f1) * f5); + if (flag1) { + f2 *= 0.92F; + } else { + f2 *= 0.7F; + } + + f2 += f4 * 0.1F; + f1 += f3 * 0.1F; + f4 *= 0.9F; + f3 *= 0.75F; + f4 += (random.nextFloat() - random.nextFloat()) * random.nextFloat() * 2.0F; + f3 += (random.nextFloat() - random.nextFloat()) * random.nextFloat() * 4.0F; + if (!flag && l == k1 && f > 1.0F && i1 > 0) { + this.a(random.nextLong(), j, k, chunksnapshot, d0, d1, d2, random.nextFloat() * 0.5F + 0.5F, f1 - 1.5707964F, f2 / 3.0F, l, i1, 1.0D); + this.a(random.nextLong(), j, k, chunksnapshot, d0, d1, d2, random.nextFloat() * 0.5F + 0.5F, f1 + 1.5707964F, f2 / 3.0F, l, i1, 1.0D); + return; + } + + if (flag || random.nextInt(4) != 0) { + double d8 = d0 - d4; + double d9 = d2 - d5; + double d10 = (i1 - l); + double d11 = (f + 2.0F + 16.0F); + + if (d8 * d8 + d9 * d9 - d10 * d10 > d11 * d11) { + return; + } + + if (d0 >= d4 - 16.0D - d6 * 2.0D && d2 >= d5 - 16.0D - d6 * 2.0D && d0 <= d4 + 16.0D + d6 * 2.0D && d2 <= d5 + 16.0D + d6 * 2.0D) { + int l1 = MathHelper.floor(d0 - d6) - j * 16 - 1; + int i2 = MathHelper.floor(d0 + d6) - j * 16 + 1; + int j2 = MathHelper.floor(d1 - d7) - 1; + int k2 = MathHelper.floor(d1 + d7) + 1; + int l2 = MathHelper.floor(d2 - d6) - k * 16 - 1; + int i3 = MathHelper.floor(d2 + d6) - k * 16 + 1; + + if (l1 < 0) { + l1 = 0; + } + + if (i2 > 16) { + i2 = 16; + } + + if (j2 < 1) { + j2 = 1; + } + + if (k2 > 248) { + k2 = 248; + } + + if (l2 < 0) { + l2 = 0; + } + + if (i3 > 16) { + i3 = 16; + } + + boolean flag2 = false; + + int j3; + + for (int k3 = l1; !flag2 && k3 < i2; ++k3) { + for (j3 = l2; !flag2 && j3 < i3; ++j3) { + for (int l3 = k2 + 1; !flag2 && l3 >= j2 - 1; --l3) { + if (l3 < 256) { + IBlockData iblockdata = chunksnapshot.a(k3, l3, j3); + + if (iblockdata.getBlock() == Blocks.FLOWING_WATER || iblockdata.getBlock() == Blocks.WATER) { + flag2 = true; + } + + if (l3 != j2 - 1 && k3 != l1 && k3 != i2 - 1 && j3 != l2 && j3 != i3 - 1) { + l3 = j2; + } + } + } + } + } + + if (!flag2) { + for (j3 = l1; j3 < i2; ++j3) { + double d12 = ((double) (j3 + j * 16) + 0.5D - d0) / d6; + + for (int i4 = l2; i4 < i3; ++i4) { + double d13 = ((double) (i4 + k * 16) + 0.5D - d2) / d6; + boolean flag3 = false; + + if (d12 * d12 + d13 * d13 < 1.0D) { + for (int j4 = k2; j4 > j2; --j4) { + double d14 = ((double) (j4 - 1) + 0.5D - d1) / d7; + + if (d14 > -0.7D && d12 * d12 + d14 * d14 + d13 * d13 < 1.0D) { + IBlockData iblockdata1 = chunksnapshot.a(j3, j4, i4); + IBlockData iblockdata2 = Objects.firstNonNull(chunksnapshot.a(j3, j4 + 1, i4), Blocks.AIR.getBlockData()); + + if (iblockdata1.getBlock() == Blocks.GRASS || iblockdata1.getBlock() == Blocks.MYCELIUM) { + flag3 = true; + } + + if (this.a(iblockdata1, iblockdata2)) { + if (j4 - 1 < 10) { + chunksnapshot.a(j3, j4, i4, Blocks.LAVA.getBlockData()); + } else { + chunksnapshot.a(j3, j4, i4, Blocks.AIR.getBlockData()); + if (iblockdata2.getBlock() == Blocks.SAND) { + chunksnapshot.a(j3, j4 + 1, i4, iblockdata2.get(BlockSand.VARIANT) == BlockSand.EnumSandVariant.RED_SAND ? Blocks.RED_SANDSTONE.getBlockData() : Blocks.SANDSTONE.getBlockData()); + } + + if (flag3 && chunksnapshot.a(j3, j4 - 1, i4).getBlock() == Blocks.DIRT) { + chunksnapshot.a(j3, j4 - 1, i4, this.c.getBiome(j3 + j * 16, 0, i4 + k * 16).ak.getBlock().getBlockData()); + } + } + } + } + } + } + } + } + + if (flag) { + break; + } + } + } + } + } + + } + + protected boolean a(IBlockData iblockdata, IBlockData iblockdata1) { + return iblockdata.getBlock() == Blocks.STONE || (iblockdata.getBlock() == Blocks.DIRT || (iblockdata.getBlock() == Blocks.GRASS || (iblockdata.getBlock() == Blocks.HARDENED_CLAY || (iblockdata.getBlock() == Blocks.STAINED_HARDENED_CLAY || (iblockdata.getBlock() == Blocks.SANDSTONE || (iblockdata.getBlock() == Blocks.RED_SANDSTONE || (iblockdata.getBlock() == Blocks.MYCELIUM || (iblockdata.getBlock() == Blocks.SNOW_LAYER || (iblockdata.getBlock() == Blocks.SAND || iblockdata.getBlock() == Blocks.GRAVEL) && iblockdata1.getBlock().getMaterial() != Material.WATER)))))))); + } + + protected void a(World world, int i, int j, int k, int l, ChunkSnapshot chunksnapshot) { + int i1 = this.b.nextInt(this.b.nextInt(this.b.nextInt((int) (15 * world.generatorConfig.cavesMultiplier.getValue())) + 1) + 1); + + if (this.b.nextFloat() > world.generatorConfig.cavesMultiplier.getValue() / 7) { + i1 = 0; + } + + for (int j1 = 0; j1 < i1; ++j1) { + double d0 = (i * 16 + this.b.nextInt(16)); + double d1 = this.b.nextInt(this.b.nextInt(120) + 8); + double d2 = (j * 16 + this.b.nextInt(16)); + int k1 = 1; + + if (this.b.nextInt(4) == 0) { + this.a(this.b.nextLong(), k, l, chunksnapshot, d0, d1, d2); + k1 += this.b.nextInt(4); + } + + for (int l1 = 0; l1 < k1; ++l1) { + float f = this.b.nextFloat() * 3.1415927F * 2.0F; + float f1 = (this.b.nextFloat() - 0.5F) * 2.0F / 8.0F; + float f2 = this.b.nextFloat() * 2.0F + this.b.nextFloat(); + + if (this.b.nextInt(10) == 0) { + f2 *= this.b.nextFloat() * this.b.nextFloat() * 3.0F + 1.0F; + } + + this.a(this.b.nextLong(), k, l, chunksnapshot, d0, d1, d2, f2, f, f1, 0, 0, 1.0D); + } + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenCavesHell.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenCavesHell.java new file mode 100644 index 0000000..8c47258 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenCavesHell.java @@ -0,0 +1,186 @@ +package net.minecraft.server; + +import java.util.Random; + +public class WorldGenCavesHell extends WorldGenBase { + + public WorldGenCavesHell() { + } + + protected void a(long i, int j, int k, ChunkSnapshot chunksnapshot, double d0, double d1, double d2) { + this.a(i, j, k, chunksnapshot, d0, d1, d2, 1.0F + this.b.nextFloat() * 6.0F, 0.0F, 0.0F, -1, -1, 0.5D); + } + + protected void a(long i, int j, int k, ChunkSnapshot chunksnapshot, double d0, double d1, double d2, float f, float f1, float f2, int l, int i1, double d3) { + double d4 = j * 16 + 8; + double d5 = k * 16 + 8; + float f3 = 0.0F; + float f4 = 0.0F; + Random random = new Random(i); + + if (i1 <= 0) { + int j1 = this.a * 16 - 16; + + i1 = j1 - random.nextInt(j1 / 4); + } + + boolean flag = false; + + if (l == -1) { + l = i1 / 2; + flag = true; + } + + int k1 = random.nextInt(i1 / 2) + i1 / 4; + + for (boolean flag1 = random.nextInt(6) == 0; l < i1; ++l) { + double d6 = 1.5D + (double) (MathHelper.sin((float) l * 3.1415927F / (float) i1) * f * 1.0F); + double d7 = d6 * d3; + float f5 = MathHelper.cos(f2); + float f6 = MathHelper.sin(f2); + + d0 += MathHelper.cos(f1) * f5; + d1 += f6; + d2 += MathHelper.sin(f1) * f5; + if (flag1) { + f2 *= 0.92F; + } else { + f2 *= 0.7F; + } + + f2 += f4 * 0.1F; + f1 += f3 * 0.1F; + f4 *= 0.9F; + f3 *= 0.75F; + f4 += (random.nextFloat() - random.nextFloat()) * random.nextFloat() * 2.0F; + f3 += (random.nextFloat() - random.nextFloat()) * random.nextFloat() * 4.0F; + if (!flag && l == k1 && f > 1.0F) { + this.a(random.nextLong(), j, k, chunksnapshot, d0, d1, d2, random.nextFloat() * 0.5F + 0.5F, f1 - 1.5707964F, f2 / 3.0F, l, i1, 1.0D); + this.a(random.nextLong(), j, k, chunksnapshot, d0, d1, d2, random.nextFloat() * 0.5F + 0.5F, f1 + 1.5707964F, f2 / 3.0F, l, i1, 1.0D); + return; + } + + if (flag || random.nextInt(4) != 0) { + double d8 = d0 - d4; + double d9 = d2 - d5; + double d10 = i1 - l; + double d11 = f + 2.0F + 16.0F; + + if (d8 * d8 + d9 * d9 - d10 * d10 > d11 * d11) { + return; + } + + if (d0 >= d4 - 16.0D - d6 * 2.0D && d2 >= d5 - 16.0D - d6 * 2.0D && d0 <= d4 + 16.0D + d6 * 2.0D && d2 <= d5 + 16.0D + d6 * 2.0D) { + int l1 = MathHelper.floor(d0 - d6) - j * 16 - 1; + int i2 = MathHelper.floor(d0 + d6) - j * 16 + 1; + int j2 = MathHelper.floor(d1 - d7) - 1; + int k2 = MathHelper.floor(d1 + d7) + 1; + int l2 = MathHelper.floor(d2 - d6) - k * 16 - 1; + int i3 = MathHelper.floor(d2 + d6) - k * 16 + 1; + + if (l1 < 0) { + l1 = 0; + } + + if (i2 > 16) { + i2 = 16; + } + + if (j2 < 1) { + j2 = 1; + } + + if (k2 > 120) { + k2 = 120; + } + + if (l2 < 0) { + l2 = 0; + } + + if (i3 > 16) { + i3 = 16; + } + + boolean flag2 = false; + + int j3; + + for (j3 = l1; !flag2 && j3 < i2; ++j3) { + for (int k3 = l2; !flag2 && k3 < i3; ++k3) { + for (int l3 = k2 + 1; !flag2 && l3 >= j2 - 1; --l3) { + if (l3 < 128) { + IBlockData iblockdata = chunksnapshot.a(j3, l3, k3); + + if (iblockdata.getBlock() == Blocks.FLOWING_LAVA || iblockdata.getBlock() == Blocks.LAVA) { + flag2 = true; + } + + if (l3 != j2 - 1 && j3 != l1 && j3 != i2 - 1 && k3 != l2 && k3 != i3 - 1) { + l3 = j2; + } + } + } + } + } + + if (!flag2) { + for (j3 = l1; j3 < i2; ++j3) { + double d12 = ((double) (j3 + j * 16) + 0.5D - d0) / d6; + + for (int i4 = l2; i4 < i3; ++i4) { + double d13 = ((double) (i4 + k * 16) + 0.5D - d2) / d6; + + for (int j4 = k2; j4 > j2; --j4) { + double d14 = ((double) (j4 - 1) + 0.5D - d1) / d7; + + if (d14 > -0.7D && d12 * d12 + d14 * d14 + d13 * d13 < 1.0D) { + IBlockData iblockdata1 = chunksnapshot.a(j3, j4, i4); + + if (iblockdata1.getBlock() == Blocks.NETHERRACK || iblockdata1.getBlock() == Blocks.DIRT || iblockdata1.getBlock() == Blocks.GRASS) { + chunksnapshot.a(j3, j4, i4, Blocks.AIR.getBlockData()); + } + } + } + } + } + + if (flag) { + break; + } + } + } + } + } + + } + + protected void a(World world, int i, int j, int k, int l, ChunkSnapshot chunksnapshot) { + int i1 = this.b.nextInt(this.b.nextInt(this.b.nextInt(10) + 1) + 1); + + if (this.b.nextInt(5) != 0) { + i1 = 0; + } + + for (int j1 = 0; j1 < i1; ++j1) { + double d0 = i * 16 + this.b.nextInt(16); + double d1 = this.b.nextInt(128); + double d2 = j * 16 + this.b.nextInt(16); + int k1 = 1; + + if (this.b.nextInt(4) == 0) { + this.a(this.b.nextLong(), k, l, chunksnapshot, d0, d1, d2); + k1 += this.b.nextInt(4); + } + + for (int l1 = 0; l1 < k1; ++l1) { + float f = this.b.nextFloat() * 3.1415927F * 2.0F; + float f1 = (this.b.nextFloat() - 0.5F) * 2.0F / 8.0F; + float f2 = this.b.nextFloat() * 2.0F + this.b.nextFloat(); + + this.a(this.b.nextLong(), k, l, chunksnapshot, d0, d1, d2, f2 * 2.0F, f, f1, 0, 0, 0.5D); + } + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenClay.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenClay.java new file mode 100644 index 0000000..d04c5ab --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenClay.java @@ -0,0 +1,42 @@ +package net.minecraft.server; + +import java.util.Random; + +public class WorldGenClay extends WorldGenerator { + + private final Block a; + private final int b; + + public WorldGenClay(int i) { + this.a = Blocks.CLAY; + this.b = i; + } + + public boolean generate(World world, Random random, BlockPosition blockposition) { + if (world.getType(blockposition).getBlock().getMaterial() != Material.WATER) { + return false; + } else { + int i = random.nextInt(this.b - 2) + 2; + byte b0 = 1; + + for (int j = blockposition.getX() - i; j <= blockposition.getX() + i; ++j) { + for (int k = blockposition.getZ() - i; k <= blockposition.getZ() + i; ++k) { + int l = j - blockposition.getX(); + int i1 = k - blockposition.getZ(); + + if (l * l + i1 * i1 <= i * i) { + for (int j1 = blockposition.getY() - b0; j1 <= blockposition.getY() + b0; ++j1) { + Block block = world.getType(j, j1, k).getBlock(); + + if (block == Blocks.DIRT || block == Blocks.CLAY) { + world.setTypeAndData(new BlockPosition(j, j1, k), this.a.getBlockData(), 2); + } + } + } + } + } + + return true; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenDeadBush.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenDeadBush.java new file mode 100644 index 0000000..7bb73bf --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenDeadBush.java @@ -0,0 +1,27 @@ +package net.minecraft.server; + +import java.util.Random; + +public class WorldGenDeadBush extends WorldGenerator { + + public WorldGenDeadBush() { + } + + public boolean generate(World world, Random random, BlockPosition blockposition) { + Block block; + + while (((block = world.getType(blockposition).getBlock()).getMaterial() == Material.AIR || block.getMaterial() == Material.LEAVES) && blockposition.getY() > 0) { + blockposition = blockposition.down(); + } + + for (int i = 0; i < 4; ++i) { + BlockPosition blockposition1 = blockposition.a(random.nextInt(8) - random.nextInt(8), random.nextInt(4) - random.nextInt(4), random.nextInt(8) - random.nextInt(8)); + + if (world.isEmpty(blockposition1) && Blocks.DEADBUSH.f(world, blockposition1, Blocks.DEADBUSH.getBlockData())) { + world.setTypeAndData(blockposition1, Blocks.DEADBUSH.getBlockData(), 2); + } + } + + return true; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenDesertWell.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenDesertWell.java new file mode 100644 index 0000000..dec369b --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenDesertWell.java @@ -0,0 +1,90 @@ +package net.minecraft.server; + +import com.google.common.base.Predicates; + +import java.util.Iterator; +import java.util.Random; + +public class WorldGenDesertWell extends WorldGenerator { + + private static final BlockStatePredicate a = BlockStatePredicate.a((Block) Blocks.SAND).a(BlockSand.VARIANT, Predicates.equalTo(BlockSand.EnumSandVariant.SAND)); + private final IBlockData b; + private final IBlockData c; + private final IBlockData d; + + public WorldGenDesertWell() { + this.b = Blocks.STONE_SLAB.getBlockData().set(BlockDoubleStepAbstract.VARIANT, BlockDoubleStepAbstract.EnumStoneSlabVariant.SAND).set(BlockStepAbstract.HALF, BlockStepAbstract.EnumSlabHalf.BOTTOM); + this.c = Blocks.SANDSTONE.getBlockData(); + this.d = Blocks.FLOWING_WATER.getBlockData(); + } + + public boolean generate(World world, Random random, BlockPosition blockposition) { + while (world.isEmpty(blockposition) && blockposition.getY() > 2) { + blockposition = blockposition.down(); + } + + if (!WorldGenDesertWell.a.a(world.getType(blockposition))) { + return false; + } else { + int i; + int j; + + for (i = -2; i <= 2; ++i) { + for (j = -2; j <= 2; ++j) { + if (world.isEmpty(blockposition.a(i, -1, j)) && world.isEmpty(blockposition.a(i, -2, j))) { + return false; + } + } + } + + for (i = -1; i <= 0; ++i) { + for (j = -2; j <= 2; ++j) { + for (int k = -2; k <= 2; ++k) { + world.setTypeAndData(blockposition.a(j, i, k), this.c, 2); + } + } + } + + world.setTypeAndData(blockposition, this.d, 2); + Iterator iterator = EnumDirection.EnumDirectionLimit.HORIZONTAL.iterator(); + + while (iterator.hasNext()) { + EnumDirection enumdirection = (EnumDirection) iterator.next(); + + world.setTypeAndData(blockposition.shift(enumdirection), this.d, 2); + } + + for (i = -2; i <= 2; ++i) { + for (j = -2; j <= 2; ++j) { + if (i == -2 || i == 2 || j == -2 || j == 2) { + world.setTypeAndData(blockposition.a(i, 1, j), this.c, 2); + } + } + } + + world.setTypeAndData(blockposition.a(2, 1, 0), this.b, 2); + world.setTypeAndData(blockposition.a(-2, 1, 0), this.b, 2); + world.setTypeAndData(blockposition.a(0, 1, 2), this.b, 2); + world.setTypeAndData(blockposition.a(0, 1, -2), this.b, 2); + + for (i = -1; i <= 1; ++i) { + for (j = -1; j <= 1; ++j) { + if (i == 0 && j == 0) { + world.setTypeAndData(blockposition.a(i, 4, j), this.c, 2); + } else { + world.setTypeAndData(blockposition.a(i, 4, j), this.b, 2); + } + } + } + + for (i = 1; i <= 3; ++i) { + world.setTypeAndData(blockposition.a(-1, i, -1), this.c, 2); + world.setTypeAndData(blockposition.a(-1, i, 1), this.c, 2); + world.setTypeAndData(blockposition.a(1, i, -1), this.c, 2); + world.setTypeAndData(blockposition.a(1, i, 1), this.c, 2); + } + + return true; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenDungeons.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenDungeons.java new file mode 100644 index 0000000..5b3f229 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenDungeons.java @@ -0,0 +1,143 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.util.List; +import java.util.Random; + +public class WorldGenDungeons extends WorldGenerator { + + private static final Logger a = LogManager.getLogger(); + private static final String[] b = new String[]{"Skeleton", "Zombie", "Zombie", "Spider"}; + private static final List c = Lists.newArrayList(new StructurePieceTreasure(Items.SADDLE, 0, 1, 1, 10), new StructurePieceTreasure(Items.IRON_INGOT, 0, 1, 4, 10), new StructurePieceTreasure(Items.BREAD, 0, 1, 1, 10), new StructurePieceTreasure(Items.WHEAT, 0, 1, 4, 10), new StructurePieceTreasure(Items.GUNPOWDER, 0, 1, 4, 10), new StructurePieceTreasure(Items.STRING, 0, 1, 4, 10), new StructurePieceTreasure(Items.BUCKET, 0, 1, 1, 10), new StructurePieceTreasure(Items.GOLDEN_APPLE, 0, 1, 1, 1), new StructurePieceTreasure(Items.REDSTONE, 0, 1, 4, 10), new StructurePieceTreasure(Items.RECORD_13, 0, 1, 1, 4), new StructurePieceTreasure(Items.RECORD_CAT, 0, 1, 1, 4), new StructurePieceTreasure(Items.NAME_TAG, 0, 1, 1, 10), new StructurePieceTreasure(Items.GOLDEN_HORSE_ARMOR, 0, 1, 1, 2), new StructurePieceTreasure(Items.IRON_HORSE_ARMOR, 0, 1, 1, 5), new StructurePieceTreasure(Items.DIAMOND_HORSE_ARMOR, 0, 1, 1, 1)); + + public WorldGenDungeons() { + } + + public boolean generate(World world, Random random, BlockPosition blockposition) { + + int i = random.nextInt(2) + 2; + int j = -i - 1; + int k = i + 1; + + int l = random.nextInt(2) + 2; + int i1 = -l - 1; + int j1 = l + 1; + int k1 = 0; + + int l1; + int i2; + int j2; + BlockPosition blockposition1; + + for (l1 = j; l1 <= k; ++l1) { + for (i2 = -1; i2 <= 4; ++i2) { + for (j2 = i1; j2 <= j1; ++j2) { + blockposition1 = blockposition.a(l1, i2, j2); + Material material = world.getType(blockposition1).getBlock().getMaterial(); + boolean flag3 = material.isBuildable(); + + if (i2 == -1 && !flag3) { + return false; + } + + if (i2 == 4 && !flag3) { + return false; + } + + if ((l1 == j || l1 == k || j2 == i1 || j2 == j1) && i2 == 0 && world.isEmpty(blockposition1) && world.isEmpty(blockposition1.getX(), blockposition1.getY() + 1, blockposition1.getZ())) { + ++k1; + } + } + } + } + + if (k1 >= 1 && k1 <= 5) { + for (l1 = j; l1 <= k; ++l1) { + for (i2 = 3; i2 >= -1; --i2) { + for (j2 = i1; j2 <= j1; ++j2) { + blockposition1 = blockposition.a(l1, i2, j2); + if (l1 != j && i2 != -1 && j2 != i1 && l1 != k && i2 != 4 && j2 != j1) { + if (world.getType(blockposition1).getBlock() != Blocks.CHEST) { + world.setAir(blockposition1); + } + } else if (blockposition1.getY() >= 0 && !world.getType(blockposition1.getX(), blockposition1.getY() - 1, blockposition1.getZ()).getBlock().getMaterial().isBuildable()) { + world.setAir(blockposition1); + } else if (world.getType(blockposition1).getBlock().getMaterial().isBuildable() && world.getType(blockposition1).getBlock() != Blocks.CHEST) { + if (i2 == -1 && random.nextInt(4) != 0) { + world.setTypeAndData(blockposition1, Blocks.MOSSY_COBBLESTONE.getBlockData(), 2); + } else { + world.setTypeAndData(blockposition1, Blocks.COBBLESTONE.getBlockData(), 2); + } + } + } + } + } + + l1 = 0; + + while (l1 < 2) { + i2 = 0; + + while (true) { + if (i2 < 3) { + label197: + { + j2 = blockposition.getX() + random.nextInt(i * 2 + 1) - i; + int k2 = blockposition.getY(); + int l2 = blockposition.getZ() + random.nextInt(l * 2 + 1) - l; + + if (world.isEmpty(j2, k2, l2)) { + BlockPosition blockposition2 = new BlockPosition(j2, k2, l2); + + int i3 = 0; + + for (EnumDirection enumdirection : EnumDirection.EnumDirectionLimit.HORIZONTAL) { + if (world.getType(blockposition2.shift(enumdirection)).getBlock().getMaterial().isBuildable()) { + ++i3; + } + } + + if (i3 == 1) { + world.setTypeAndData(blockposition2, Blocks.CHEST.f(world, blockposition2, Blocks.CHEST.getBlockData()), 2); + List list = StructurePieceTreasure.a(WorldGenDungeons.c, Items.ENCHANTED_BOOK.b(random)); + TileEntity tileentity = world.getTileEntity(blockposition2); + + if (tileentity instanceof TileEntityChest) { + StructurePieceTreasure.a(random, list, (IInventory) tileentity, 8); + } + break label197; + } + } + + ++i2; + continue; + } + } + + ++l1; + break; + } + } + + world.setTypeAndData(blockposition, Blocks.MOB_SPAWNER.getBlockData(), 2); + TileEntity tileentity1 = world.getTileEntity(blockposition); + + if (tileentity1 instanceof TileEntityMobSpawner) { + ((TileEntityMobSpawner) tileentity1).getSpawner().setMobName(this.a(random)); + } else { + WorldGenDungeons.a.error("Failed to fetch mob spawner entity at (" + blockposition.getX() + ", " + blockposition.getY() + ", " + blockposition.getZ() + ")"); + } + + return true; + } else { + return false; + } + } + + private String a(Random random) { + return WorldGenDungeons.b[random.nextInt(WorldGenDungeons.b.length)]; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenEnder.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenEnder.java new file mode 100644 index 0000000..78b137e --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenEnder.java @@ -0,0 +1,56 @@ +package net.minecraft.server; + +import java.util.Random; + +public class WorldGenEnder extends WorldGenerator { + + private Block a; + + public WorldGenEnder(Block block) { + this.a = block; + } + + public boolean generate(World world, Random random, BlockPosition blockposition) { + if (world.isEmpty(blockposition) && world.getType(blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()).getBlock() == this.a) { + int i = random.nextInt(32) + 6; + int j = random.nextInt(4) + 1; + + int k; + int l; + int i1; + int j1; + + for (k = blockposition.getX() - j; k <= blockposition.getX() + j; ++k) { + for (l = blockposition.getZ() - j; l <= blockposition.getZ() + j; ++l) { + i1 = k - blockposition.getX(); + j1 = l - blockposition.getZ(); + if (i1 * i1 + j1 * j1 <= j * j + 1 && world.getType(k, blockposition.getY() - 1, l).getBlock() != this.a) { + return false; + } + } + } + + for (k = blockposition.getY(); k < blockposition.getY() + i && k < 256; ++k) { + for (l = blockposition.getX() - j; l <= blockposition.getX() + j; ++l) { + for (i1 = blockposition.getZ() - j; i1 <= blockposition.getZ() + j; ++i1) { + j1 = l - blockposition.getX(); + int k1 = i1 - blockposition.getZ(); + + if (j1 * j1 + k1 * k1 <= j * j + 1) { + world.setTypeAndData(new BlockPosition(l, k, i1), Blocks.OBSIDIAN.getBlockData(), 2); + } + } + } + } + + EntityEnderCrystal entityendercrystal = new EntityEnderCrystal(world); + + entityendercrystal.setPositionRotation((float) blockposition.getX() + 0.5F, blockposition.getY() + i, (float) blockposition.getZ() + 0.5F, random.nextFloat() * 360.0F, 0.0F); + world.addEntity(entityendercrystal); + world.setTypeAndData(blockposition.up(i), Blocks.BEDROCK.getBlockData(), 2); + return true; + } else { + return false; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenFactory.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenFactory.java new file mode 100644 index 0000000..6c5b60d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenFactory.java @@ -0,0 +1,95 @@ +package net.minecraft.server; + +import com.google.common.collect.Maps; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.util.Map; + +public class WorldGenFactory { + + private static final Logger a = LogManager.getLogger(); + private static final Map> b = Maps.newHashMap(); + private static final Map, String> c = Maps.newHashMap(); + private static final Map> d = Maps.newHashMap(); + private static final Map, String> e = Maps.newHashMap(); + + static { + b(WorldGenMineshaftStart.class, "Mineshaft"); + b(WorldGenVillage.WorldGenVillageStart.class, "Village"); + b(WorldGenNether.WorldGenNetherStart.class, "Fortress"); + b(WorldGenStronghold.WorldGenStronghold2Start.class, "Stronghold"); + b(WorldGenLargeFeature.WorldGenLargeFeatureStart.class, "Temple"); + b(WorldGenMonument.WorldGenMonumentStart.class, "Monument"); + WorldGenMineshaftPieces.a(); + WorldGenVillagePieces.a(); + WorldGenNetherPieces.a(); + WorldGenStrongholdPieces.a(); + WorldGenRegistration.a(); + WorldGenMonumentPieces.a(); + } + + private static void b(Class oclass, String s) { + b.put(s, oclass); + c.put(oclass, s); + } + + static void a(Class oclass, String s) { + d.put(s, oclass); + e.put(oclass, s); + } + + public static String a(StructureStart structurestart) { + return c.get(structurestart.getClass()); + } + + public static String a(StructurePiece structurepiece) { + return e.get(structurepiece.getClass()); + } + + public static StructureStart a(NBTTagCompound nbttagcompound, World world) { + StructureStart structurestart = null; + + try { + Class oclass = b.get(nbttagcompound.getString("id")); + + if (oclass != null) { + structurestart = oclass.newInstance(); + } + } catch (Exception exception) { + a.warn("Failed Start with id " + nbttagcompound.getString("id")); + exception.printStackTrace(); + } + + if (structurestart != null) { + structurestart.a(world, nbttagcompound); + } else { + a.warn("Skipping Structure with id " + nbttagcompound.getString("id")); + } + + return structurestart; + } + + public static StructurePiece b(NBTTagCompound nbttagcompound, World world) { + StructurePiece structurepiece = null; + + try { + Class oclass = d.get(nbttagcompound.getString("id")); + + if (oclass != null) { + structurepiece = oclass.newInstance(); + } + } catch (Exception exception) { + a.warn("Failed Piece with id " + nbttagcompound.getString("id")); + exception.printStackTrace(); + } + + if (structurepiece != null) { + structurepiece.a(world, nbttagcompound); + } else { + a.warn("Skipping Piece with id " + nbttagcompound.getString("id")); + } + + return structurepiece; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenFire.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenFire.java new file mode 100644 index 0000000..3a8c905 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenFire.java @@ -0,0 +1,21 @@ +package net.minecraft.server; + +import java.util.Random; + +public class WorldGenFire extends WorldGenerator { + + public WorldGenFire() { + } + + public boolean generate(World world, Random random, BlockPosition blockposition) { + for (int i = 0; i < 64; ++i) { + BlockPosition blockposition1 = blockposition.a(random.nextInt(8) - random.nextInt(8), random.nextInt(4) - random.nextInt(4), random.nextInt(8) - random.nextInt(8)); + + if (world.isEmpty(blockposition1) && world.getType(blockposition1.getX(), blockposition1.getY() - 1, blockposition1.getZ()).getBlock() == Blocks.NETHERRACK) { + world.setTypeAndData(blockposition1, Blocks.FIRE.getBlockData(), 2); + } + } + + return true; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenFlatInfo.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenFlatInfo.java new file mode 100644 index 0000000..63ce5cb --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenFlatInfo.java @@ -0,0 +1,258 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; + +import java.util.*; +import java.util.Map.Entry; + +public class WorldGenFlatInfo { + + private final List layers = Lists.newArrayList(); + private final Map> structures = Maps.newHashMap(); + private int c; + + public WorldGenFlatInfo() { + } + + public int a() { + return this.c; + } + + public void a(int i) { + this.c = i; + } + + public Map> b() { + return this.structures; + } + + public List c() { + return this.layers; + } + + public void d() { + int i = 0; + + WorldGenFlatLayerInfo worldgenflatlayerinfo; + + for (Iterator iterator = this.layers.iterator(); iterator.hasNext(); i += worldgenflatlayerinfo.b()) { + worldgenflatlayerinfo = iterator.next(); + worldgenflatlayerinfo.b(i); + } + + } + + public String toString() { + StringBuilder stringbuilder = new StringBuilder(); + + stringbuilder.append(3); + stringbuilder.append(";"); + + int i; + + for (i = 0; i < this.layers.size(); ++i) { + if (i > 0) { + stringbuilder.append(","); + } + + stringbuilder.append(this.layers.get(i).toString()); + } + + stringbuilder.append(";"); + stringbuilder.append(this.c); + if (!this.structures.isEmpty()) { + stringbuilder.append(";"); + i = 0; + + for (Entry> entry : this.structures.entrySet()) { + if (i++ > 0) { + stringbuilder.append(","); + } + + stringbuilder.append(entry.getKey().toLowerCase()); + Map map = entry.getValue(); + + if (!map.isEmpty()) { + stringbuilder.append("("); + int j = 0; + + for (Entry stringStringEntry : map.entrySet()) { + + if (j++ > 0) { + stringbuilder.append(" "); + } + + stringbuilder.append(stringStringEntry.getKey()); + stringbuilder.append("="); + stringbuilder.append(stringStringEntry.getValue()); + } + + stringbuilder.append(")"); + } + } + } else { + stringbuilder.append(";"); + } + + return stringbuilder.toString(); + } + + private static WorldGenFlatLayerInfo a(int i, String s, int j) { + String[] astring = i >= 3 ? s.split("\\*", 2) : s.split("x", 2); + int k = 1; + int l = 0; + + if (astring.length == 2) { + try { + k = Integer.parseInt(astring[0]); + if (j + k >= 256) { + k = 256 - j; + } + + if (k < 0) { + k = 0; + } + } catch (Throwable throwable) { + return null; + } + } + + Block block; + + try { + String s1 = astring[astring.length - 1]; + + if (i < 3) { + astring = s1.split(":", 2); + if (astring.length > 1) { + l = Integer.parseInt(astring[1]); + } + + block = Block.getById(Integer.parseInt(astring[0])); + } else { + astring = s1.split(":", 3); + block = astring.length > 1 ? Block.getByName(astring[0] + ":" + astring[1]) : null; + if (block != null) { + l = astring.length > 2 ? Integer.parseInt(astring[2]) : 0; + } else { + block = Block.getByName(astring[0]); + if (block != null) { + l = astring.length > 1 ? Integer.parseInt(astring[1]) : 0; + } + } + + if (block == null) { + return null; + } + } + + if (block == Blocks.AIR) { + l = 0; + } + + if (l < 0 || l > 15) { + l = 0; + } + } catch (Throwable throwable1) { + return null; + } + + WorldGenFlatLayerInfo worldgenflatlayerinfo = new WorldGenFlatLayerInfo(i, k, block, l); + + worldgenflatlayerinfo.b(j); + return worldgenflatlayerinfo; + } + + private static List a(int i, String s) { + if (s != null && s.length() >= 1) { + ArrayList arraylist = Lists.newArrayList(); + String[] astring = s.split(","); + int j = 0; + + for (String s1 : astring) { + WorldGenFlatLayerInfo worldgenflatlayerinfo = a(i, s1, j); + + if (worldgenflatlayerinfo == null) { + return null; + } + + arraylist.add(worldgenflatlayerinfo); + j += worldgenflatlayerinfo.b(); + } + + return arraylist; + } else { + return null; + } + } + + public static WorldGenFlatInfo a(String s) { + if (s == null) { + return e(); + } else { + String[] astring = s.split(";", -1); + int i = astring.length == 1 ? 0 : MathHelper.a(astring[0], 0); + + if (i >= 0 && i <= 3) { + WorldGenFlatInfo worldgenflatinfo = new WorldGenFlatInfo(); + int j = astring.length == 1 ? 0 : 1; + List list = a(i, astring[j++]); + + if (list != null && !list.isEmpty()) { + worldgenflatinfo.c().addAll(list); + worldgenflatinfo.d(); + int k = BiomeBase.PLAINS.id; + + if (i > 0 && astring.length > j) { + k = MathHelper.a(astring[j++], k); + } + + worldgenflatinfo.a(k); + if (i > 0 && astring.length > j) { + String[] astring1 = astring[j++].toLowerCase().split(","); + for (String s1 : astring1) { + String[] astring3 = s1.split("\\(", 2); + HashMap hashmap = Maps.newHashMap(); + + if (astring3[0].length() > 0) { + worldgenflatinfo.b().put(astring3[0], hashmap); + if (astring3.length > 1 && astring3[1].endsWith(")") && astring3[1].length() > 1) { + String[] astring4 = astring3[1].substring(0, astring3[1].length() - 1).split(" "); + + for (String value : astring4) { + String[] astring5 = value.split("=", 2); + + if (astring5.length == 2) { + hashmap.put(astring5[0], astring5[1]); + } + } + } + } + } + } else { + worldgenflatinfo.b().put("village", Maps.newHashMap()); + } + + return worldgenflatinfo; + } else { + return e(); + } + } else { + return e(); + } + } + } + + public static WorldGenFlatInfo e() { + WorldGenFlatInfo worldgenflatinfo = new WorldGenFlatInfo(); + + worldgenflatinfo.a(BiomeBase.PLAINS.id); + worldgenflatinfo.c().add(new WorldGenFlatLayerInfo(1, Blocks.BEDROCK)); + worldgenflatinfo.c().add(new WorldGenFlatLayerInfo(2, Blocks.DIRT)); + worldgenflatinfo.c().add(new WorldGenFlatLayerInfo(1, Blocks.GRASS)); + worldgenflatinfo.d(); + worldgenflatinfo.b().put("village", Maps.newHashMap()); + return worldgenflatinfo; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenFlatLayerInfo.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenFlatLayerInfo.java new file mode 100644 index 0000000..d14d0c6 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenFlatLayerInfo.java @@ -0,0 +1,75 @@ +package net.minecraft.server; + +public class WorldGenFlatLayerInfo { + + private final int a; + private IBlockData b; + private int c; + private int d; + + public WorldGenFlatLayerInfo(int i, Block block) { + this(3, i, block); + } + + public WorldGenFlatLayerInfo(int i, int j, Block block) { + this.c = 1; + this.a = i; + this.c = j; + this.b = block.getBlockData(); + } + + public WorldGenFlatLayerInfo(int i, int j, Block block, int k) { + this(i, j, block); + this.b = block.fromLegacyData(k); + } + + public int b() { + return this.c; + } + + public IBlockData c() { + return this.b; + } + + private Block e() { + return this.b.getBlock(); + } + + private int f() { + return this.b.getBlock().toLegacyData(this.b); + } + + public int d() { + return this.d; + } + + public void b(int i) { + this.d = i; + } + + public String toString() { + String s; + + if (this.a >= 3) { + MinecraftKey minecraftkey = Block.REGISTRY.c(this.e()); + + s = minecraftkey == null ? "null" : minecraftkey.toString(); + if (this.c > 1) { + s = this.c + "*" + s; + } + } else { + s = Integer.toString(Block.getId(this.e())); + if (this.c > 1) { + s = this.c + "x" + s; + } + } + + int i = this.f(); + + if (i > 0) { + s = s + ":" + i; + } + + return s; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenFlowers.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenFlowers.java new file mode 100644 index 0000000..e9de8cc --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenFlowers.java @@ -0,0 +1,30 @@ +package net.minecraft.server; + +import java.util.Random; + +public class WorldGenFlowers extends WorldGenerator { + + private BlockFlowers a; + private IBlockData b; + + public WorldGenFlowers(BlockFlowers blockflowers, BlockFlowers.EnumFlowerVarient blockflowers_enumflowervarient) { + this.a(blockflowers, blockflowers_enumflowervarient); + } + + public void a(BlockFlowers blockflowers, BlockFlowers.EnumFlowerVarient blockflowers_enumflowervarient) { + this.a = blockflowers; + this.b = blockflowers.getBlockData().set(blockflowers.n(), blockflowers_enumflowervarient); + } + + public boolean generate(World world, Random random, BlockPosition blockposition) { + for (int i = 0; i < 64; ++i) { + BlockPosition blockposition1 = blockposition.a(random.nextInt(8) - random.nextInt(8), random.nextInt(4) - random.nextInt(4), random.nextInt(8) - random.nextInt(8)); + + if (world.isEmpty(blockposition1) && (!world.worldProvider.o() || blockposition1.getY() < 255) && this.a.f(world, blockposition1, this.b)) { + world.setTypeAndData(blockposition1, this.b, 2); + } + } + + return true; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenForest.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenForest.java new file mode 100644 index 0000000..6e40ecb --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenForest.java @@ -0,0 +1,102 @@ +package net.minecraft.server; + +import java.util.Random; + +public class WorldGenForest extends WorldGenTreeAbstract { + + private static final IBlockData a = Blocks.LOG.getBlockData().set(BlockLog1.VARIANT, BlockWood.EnumLogVariant.BIRCH); + private static final IBlockData b = Blocks.LEAVES.getBlockData().set(BlockLeaves1.VARIANT, BlockWood.EnumLogVariant.BIRCH).set(BlockLeaves1.CHECK_DECAY, Boolean.FALSE); + private final boolean c; + + public WorldGenForest(boolean flag, boolean flag1) { + super(flag); + this.c = flag1; + } + + public boolean generate(World world, Random random, BlockPosition blockposition) { + int i = random.nextInt(3) + 5; + + if (this.c) { + i += random.nextInt(7); + } + + boolean flag = true; + + if (blockposition.getY() >= 1 && blockposition.getY() + i + 1 <= 256) { + int j; + int k; + + for (int l = blockposition.getY(); l <= blockposition.getY() + 1 + i; ++l) { + byte b0 = 1; + + if (l == blockposition.getY()) { + b0 = 0; + } + + if (l >= blockposition.getY() + 1 + i - 2) { + b0 = 2; + } + + for (j = blockposition.getX() - b0; j <= blockposition.getX() + b0 && flag; ++j) { + for (k = blockposition.getZ() - b0; k <= blockposition.getZ() + b0 && flag; ++k) { + if (l >= 0 && l < 256) { + if (!this.a(world.getType(j, l, k).getBlock())) { + flag = false; + } + } else { + flag = false; + } + } + } + } + + if (!flag) { + return false; + } else { + Block block = world.getType(blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()).getBlock(); + + if ((block == Blocks.GRASS || block == Blocks.DIRT || block == Blocks.FARMLAND) && blockposition.getY() < 256 - i - 1) { + this.a(world, blockposition.down()); + + int i1; + + for (i1 = blockposition.getY() - 3 + i; i1 <= blockposition.getY() + i; ++i1) { + int j1 = i1 - (blockposition.getY() + i); + + j = 1 - j1 / 2; + + for (k = blockposition.getX() - j; k <= blockposition.getX() + j; ++k) { + int k1 = k - blockposition.getX(); + + for (int l1 = blockposition.getZ() - j; l1 <= blockposition.getZ() + j; ++l1) { + int i2 = l1 - blockposition.getZ(); + + if (Math.abs(k1) != j || Math.abs(i2) != j || random.nextInt(2) != 0 && j1 != 0) { + Block block1 = world.getType(k, i1, l1).getBlock(); + + if (block1.getMaterial() == Material.AIR || block1.getMaterial() == Material.LEAVES) { + this.a(world, new BlockPosition(k, i1, l1), WorldGenForest.b); + } + } + } + } + } + + for (i1 = 0; i1 < i; ++i1) { + Block block2 = world.getType(blockposition.up(i1)).getBlock(); + + if (block2.getMaterial() == Material.AIR || block2.getMaterial() == Material.LEAVES) { + this.a(world, blockposition.up(i1), WorldGenForest.a); + } + } + + return true; + } else { + return false; + } + } + } else { + return false; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenForestTree.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenForestTree.java new file mode 100644 index 0000000..08ac445 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenForestTree.java @@ -0,0 +1,177 @@ +package net.minecraft.server; + +import java.util.Random; + +public class WorldGenForestTree extends WorldGenTreeAbstract { + + private static final IBlockData a = Blocks.LOG2.getBlockData().set(BlockLog2.VARIANT, BlockWood.EnumLogVariant.DARK_OAK); + private static final IBlockData b = Blocks.LEAVES2.getBlockData().set(BlockLeaves2.VARIANT, BlockWood.EnumLogVariant.DARK_OAK).set(BlockLeaves.CHECK_DECAY, Boolean.FALSE); + + public WorldGenForestTree(boolean flag) { + super(flag); + } + + public boolean generate(World world, Random random, BlockPosition blockposition) { + int i = random.nextInt(3) + random.nextInt(2) + 6; + int j = blockposition.getX(); + int k = blockposition.getY(); + int l = blockposition.getZ(); + + if (k >= 1 && k + i + 1 < 256) { + BlockPosition blockposition1 = blockposition.down(); + Block block = world.getType(blockposition1).getBlock(); + + if (block != Blocks.GRASS && block != Blocks.DIRT) { + return false; + } else if (!this.a(world, blockposition, i)) { + return false; + } else { + this.a(world, blockposition1); + this.a(world, blockposition1.east()); + this.a(world, blockposition1.south()); + this.a(world, blockposition1.south().east()); + EnumDirection enumdirection = EnumDirection.EnumDirectionLimit.HORIZONTAL.a(random); + int i1 = i - random.nextInt(4); + int j1 = 2 - random.nextInt(3); + int k1 = j; + int l1 = l; + int i2 = k + i - 1; + + int j2; + int k2; + + for (j2 = 0; j2 < i; ++j2) { + if (j2 >= i1 && j1 > 0) { + k1 += enumdirection.getAdjacentX(); + l1 += enumdirection.getAdjacentZ(); + --j1; + } + + k2 = k + j2; + BlockPosition blockposition2 = new BlockPosition(k1, k2, l1); + Material material = world.getType(blockposition2).getBlock().getMaterial(); + + if (material == Material.AIR || material == Material.LEAVES) { + this.b(world, blockposition2); + this.b(world, blockposition2.east()); + this.b(world, blockposition2.south()); + this.b(world, blockposition2.east().south()); + } + } + + for (j2 = -2; j2 <= 0; ++j2) { + for (k2 = -2; k2 <= 0; ++k2) { + byte b0 = -1; + + this.a(world, k1 + j2, i2 + b0, l1 + k2); + this.a(world, 1 + k1 - j2, i2 + b0, l1 + k2); + this.a(world, k1 + j2, i2 + b0, 1 + l1 - k2); + this.a(world, 1 + k1 - j2, i2 + b0, 1 + l1 - k2); + if ((j2 > -2 || k2 > -1) && (j2 != -1 || k2 != -2)) { + byte b1 = 1; + + this.a(world, k1 + j2, i2 + b1, l1 + k2); + this.a(world, 1 + k1 - j2, i2 + b1, l1 + k2); + this.a(world, k1 + j2, i2 + b1, 1 + l1 - k2); + this.a(world, 1 + k1 - j2, i2 + b1, 1 + l1 - k2); + } + } + } + + if (random.nextBoolean()) { + this.a(world, k1, i2 + 2, l1); + this.a(world, k1 + 1, i2 + 2, l1); + this.a(world, k1 + 1, i2 + 2, l1 + 1); + this.a(world, k1, i2 + 2, l1 + 1); + } + + for (j2 = -3; j2 <= 4; ++j2) { + for (k2 = -3; k2 <= 4; ++k2) { + if ((j2 != -3 || k2 != -3) && (j2 != -3 || k2 != 4) && (j2 != 4 || k2 != -3) && (j2 != 4 || k2 != 4) && (Math.abs(j2) < 3 || Math.abs(k2) < 3)) { + this.a(world, k1 + j2, i2, l1 + k2); + } + } + } + + for (j2 = -1; j2 <= 2; ++j2) { + for (k2 = -1; k2 <= 2; ++k2) { + if ((j2 < 0 || j2 > 1 || k2 < 0 || k2 > 1) && random.nextInt(3) <= 0) { + int l2 = random.nextInt(3) + 2; + + int i3; + + for (i3 = 0; i3 < l2; ++i3) { + this.b(world, new BlockPosition(j + j2, i2 - i3 - 1, l + k2)); + } + + int j3; + + for (i3 = -1; i3 <= 1; ++i3) { + for (j3 = -1; j3 <= 1; ++j3) { + this.a(world, k1 + j2 + i3, i2, l1 + k2 + j3); + } + } + + for (i3 = -2; i3 <= 2; ++i3) { + for (j3 = -2; j3 <= 2; ++j3) { + if (Math.abs(i3) != 2 || Math.abs(j3) != 2) { + this.a(world, k1 + j2 + i3, i2 - 1, l1 + k2 + j3); + } + } + } + } + } + } + + return true; + } + } else { + return false; + } + } + + private boolean a(World world, BlockPosition blockposition, int i) { + int j = blockposition.getX(); + int k = blockposition.getY(); + int l = blockposition.getZ(); + + for (int i1 = 0; i1 <= i + 1; ++i1) { + byte b0 = 1; + + if (i1 == 0) { + b0 = 0; + } + + if (i1 >= i - 1) { + b0 = 2; + } + + for (int j1 = -b0; j1 <= b0; ++j1) { + for (int k1 = -b0; k1 <= b0; ++k1) { + if (!this.a(world.getType(j + j1, k + i1, l + k1).getBlock())) { + return false; + } + } + } + } + + return true; + } + + private void b(World world, BlockPosition blockposition) { + if (this.a(world.getType(blockposition).getBlock())) { + this.a(world, blockposition, WorldGenForestTree.a); + } + + } + + private void a(World world, int i, int j, int k) { + BlockPosition blockposition = new BlockPosition(i, j, k); + Block block = world.getType(blockposition).getBlock(); + + if (block.getMaterial() == Material.AIR) { + this.a(world, blockposition, WorldGenForestTree.b); + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenGrass.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenGrass.java new file mode 100644 index 0000000..2c84c05 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenGrass.java @@ -0,0 +1,30 @@ +package net.minecraft.server; + +import java.util.Random; + +public class WorldGenGrass extends WorldGenerator { + + private final IBlockData a; + + public WorldGenGrass(BlockLongGrass.EnumTallGrassType blocklonggrass_enumtallgrasstype) { + this.a = Blocks.TALLGRASS.getBlockData().set(BlockLongGrass.TYPE, blocklonggrass_enumtallgrasstype); + } + + public boolean generate(World world, Random random, BlockPosition blockposition) { + Block block; + + while (((block = world.getType(blockposition).getBlock()).getMaterial() == Material.AIR || block.getMaterial() == Material.LEAVES) && blockposition.getY() > 0) { + blockposition = blockposition.down(); + } + + for (int i = 0; i < 128; ++i) { + BlockPosition blockposition1 = blockposition.a(random.nextInt(8) - random.nextInt(8), random.nextInt(4) - random.nextInt(4), random.nextInt(8) - random.nextInt(8)); + + if (world.isEmpty(blockposition1) && Blocks.TALLGRASS.f(world, blockposition1, this.a)) { + world.setTypeAndData(blockposition1, this.a, 2); + } + } + + return true; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenGroundBush.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenGroundBush.java new file mode 100644 index 0000000..febdef0 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenGroundBush.java @@ -0,0 +1,57 @@ +package net.minecraft.server; + +import java.util.Random; + +public class WorldGenGroundBush extends WorldGenTrees { + + private final IBlockData a; + private final IBlockData b; + + public WorldGenGroundBush(IBlockData iblockdata, IBlockData iblockdata1) { + super(false); + this.b = iblockdata; + this.a = iblockdata1; + } + + public boolean generate(World world, Random random, BlockPosition blockposition) { + Block block; + + while (((block = world.getType(blockposition).getBlock()).getMaterial() == Material.AIR || block.getMaterial() == Material.LEAVES) && blockposition.getY() > 0) { + blockposition = blockposition.down(); + } + + Block block1 = world.getType(blockposition).getBlock(); + + if (block1 == Blocks.DIRT || block1 == Blocks.GRASS) { + blockposition = blockposition.up(); + this.a(world, blockposition, this.b); + + for (int i = blockposition.getY(); i <= blockposition.getY() + 2; ++i) { + int j = i - blockposition.getY(); + int k = 2 - j; + + for (int l = blockposition.getX() - k; l <= blockposition.getX() + k; ++l) { + int i1 = l - blockposition.getX(); + + for (int j1 = blockposition.getZ() - k; j1 <= blockposition.getZ() + k; ++j1) { + int k1 = j1 - blockposition.getZ(); + + if (Math.abs(i1) != k || Math.abs(k1) != k || random.nextInt(2) != 0) { + if (!world.getType(l, i, j1).getBlock().o()) { + BlockPosition blockposition1 = new BlockPosition(l, i, j1); + this.a(world, blockposition1, this.a); + } + } + } + } + } + // CraftBukkit start - Return false if gen was unsuccessful + } else { + return false; + } + // CraftBukkit end + + + return true; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenHellLava.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenHellLava.java new file mode 100644 index 0000000..95aee70 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenHellLava.java @@ -0,0 +1,73 @@ +package net.minecraft.server; + +import java.util.Random; + +public class WorldGenHellLava extends WorldGenerator { + + private final Block a; + private final boolean b; + + public WorldGenHellLava(Block block, boolean flag) { + this.a = block; + this.b = flag; + } + + public boolean generate(World world, Random random, BlockPosition blockposition) { + if (world.getType(blockposition.getX(), blockposition.getY() + 1, blockposition.getZ()).getBlock() != Blocks.NETHERRACK) { + return false; + } else if (world.getType(blockposition).getBlock().getMaterial() != Material.AIR && world.getType(blockposition).getBlock() != Blocks.NETHERRACK) { + return false; + } else { + int i = 0; + + if (world.getType(blockposition.getX() - 1, blockposition.getY(), blockposition.getZ()).getBlock() == Blocks.NETHERRACK) { + ++i; + } + + if (world.getType(blockposition.getX() + 1, blockposition.getY(), blockposition.getZ()).getBlock() == Blocks.NETHERRACK) { + ++i; + } + + if (world.getType(blockposition.getX(), blockposition.getY(), blockposition.getZ() - 1).getBlock() == Blocks.NETHERRACK) { + ++i; + } + + if (world.getType(blockposition.getX(), blockposition.getY(), blockposition.getZ() + 1).getBlock() == Blocks.NETHERRACK) { + ++i; + } + + if (world.getType(blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()).getBlock() == Blocks.NETHERRACK) { + ++i; + } + + int j = 0; + + if (world.isEmpty(blockposition.getX() - 1, blockposition.getY(), blockposition.getZ())) { + ++j; + } + + if (world.isEmpty(blockposition.getX() + 1, blockposition.getY(), blockposition.getZ())) { + ++j; + } + + if (world.isEmpty(blockposition.getX(), blockposition.getY(), blockposition.getZ() - 1)) { + ++j; + } + + if (world.isEmpty(blockposition.getX(), blockposition.getY(), blockposition.getZ() + 1)) { + ++j; + } + + if (world.isEmpty(blockposition.getX(), blockposition.getY() - 1, blockposition.getZ())) { + ++j; + } + + if (!this.b && i == 4 && j == 1 || i == 5) { + world.setTypeAndData(blockposition, this.a.getBlockData(), 2); + world.a(this.a, blockposition, random); + } + + return true; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenHugeMushroom.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenHugeMushroom.java new file mode 100644 index 0000000..a1a6f5b --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenHugeMushroom.java @@ -0,0 +1,168 @@ +package net.minecraft.server; + +import java.util.Random; + +public class WorldGenHugeMushroom extends WorldGenerator { + + private Block a; + + public WorldGenHugeMushroom(Block block) { + super(true); + this.a = block; + } + + public WorldGenHugeMushroom() { + super(false); + } + + public boolean generate(World world, Random random, BlockPosition blockposition) { + if (this.a == null) { + this.a = random.nextBoolean() ? Blocks.BROWN_MUSHROOM_BLOCK : Blocks.RED_MUSHROOM_BLOCK; + } + + int i = random.nextInt(3) + 4; + boolean flag = true; + + if (blockposition.getY() >= 1 && blockposition.getY() + i + 1 < 256) { + int j; + int k; + + for (int l = blockposition.getY(); l <= blockposition.getY() + 1 + i; ++l) { + byte b0 = 3; + + if (l <= blockposition.getY() + 3) { + b0 = 0; + } + + for (j = blockposition.getX() - b0; j <= blockposition.getX() + b0 && flag; ++j) { + for (k = blockposition.getZ() - b0; k <= blockposition.getZ() + b0 && flag; ++k) { + if (l >= 0 && l < 256) { + Block block = world.getType(j, l, k).getBlock(); + + if (block.getMaterial() != Material.AIR && block.getMaterial() != Material.LEAVES) { + flag = false; + } + } else { + flag = false; + } + } + } + } + + if (!flag) { + return false; + } else { + Block block1 = world.getType(blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()).getBlock(); + + if (block1 != Blocks.DIRT && block1 != Blocks.GRASS && block1 != Blocks.MYCELIUM) { + return false; + } else { + int i1 = blockposition.getY() + i; + + if (this.a == Blocks.RED_MUSHROOM_BLOCK) { + i1 = blockposition.getY() + i - 3; + } + + int j1; + + for (j1 = i1; j1 <= blockposition.getY() + i; ++j1) { + j = 1; + if (j1 < blockposition.getY() + i) { + ++j; + } + + if (this.a == Blocks.BROWN_MUSHROOM_BLOCK) { + j = 3; + } + + k = blockposition.getX() - j; + int k1 = blockposition.getX() + j; + int l1 = blockposition.getZ() - j; + int i2 = blockposition.getZ() + j; + + for (int j2 = k; j2 <= k1; ++j2) { + for (int k2 = l1; k2 <= i2; ++k2) { + int l2 = 5; + + if (j2 == k) { + --l2; + } else if (j2 == k1) { + ++l2; + } + + if (k2 == l1) { + l2 -= 3; + } else if (k2 == i2) { + l2 += 3; + } + + BlockHugeMushroom.EnumHugeMushroomVariant blockhugemushroom_enumhugemushroomvariant = BlockHugeMushroom.EnumHugeMushroomVariant.a(l2); + + if (this.a == Blocks.BROWN_MUSHROOM_BLOCK || j1 < blockposition.getY() + i) { + if ((j2 == k || j2 == k1) && (k2 == l1 || k2 == i2)) { + continue; + } + + if (j2 == blockposition.getX() - (j - 1) && k2 == l1) { + blockhugemushroom_enumhugemushroomvariant = BlockHugeMushroom.EnumHugeMushroomVariant.NORTH_WEST; + } + + if (j2 == k && k2 == blockposition.getZ() - (j - 1)) { + blockhugemushroom_enumhugemushroomvariant = BlockHugeMushroom.EnumHugeMushroomVariant.NORTH_WEST; + } + + if (j2 == blockposition.getX() + (j - 1) && k2 == l1) { + blockhugemushroom_enumhugemushroomvariant = BlockHugeMushroom.EnumHugeMushroomVariant.NORTH_EAST; + } + + if (j2 == k1 && k2 == blockposition.getZ() - (j - 1)) { + blockhugemushroom_enumhugemushroomvariant = BlockHugeMushroom.EnumHugeMushroomVariant.NORTH_EAST; + } + + if (j2 == blockposition.getX() - (j - 1) && k2 == i2) { + blockhugemushroom_enumhugemushroomvariant = BlockHugeMushroom.EnumHugeMushroomVariant.SOUTH_WEST; + } + + if (j2 == k && k2 == blockposition.getZ() + (j - 1)) { + blockhugemushroom_enumhugemushroomvariant = BlockHugeMushroom.EnumHugeMushroomVariant.SOUTH_WEST; + } + + if (j2 == blockposition.getX() + (j - 1) && k2 == i2) { + blockhugemushroom_enumhugemushroomvariant = BlockHugeMushroom.EnumHugeMushroomVariant.SOUTH_EAST; + } + + if (j2 == k1 && k2 == blockposition.getZ() + (j - 1)) { + blockhugemushroom_enumhugemushroomvariant = BlockHugeMushroom.EnumHugeMushroomVariant.SOUTH_EAST; + } + } + + if (blockhugemushroom_enumhugemushroomvariant == BlockHugeMushroom.EnumHugeMushroomVariant.CENTER && j1 < blockposition.getY() + i) { + blockhugemushroom_enumhugemushroomvariant = BlockHugeMushroom.EnumHugeMushroomVariant.ALL_INSIDE; + } + + if (blockposition.getY() >= blockposition.getY() + i - 1 || blockhugemushroom_enumhugemushroomvariant != BlockHugeMushroom.EnumHugeMushroomVariant.ALL_INSIDE) { + if (!world.getType(j2, j1, k2).getBlock().o()) { + this.a(world, new BlockPosition(j2, j1, k2), this.a.getBlockData().set(BlockHugeMushroom.VARIANT, blockhugemushroom_enumhugemushroomvariant)); + } + } + } + } + } + + for (j1 = 0; j1 < i; ++j1) { + BlockPosition up = blockposition.up(j1); + Block block2 = world.getType(up).getBlock(); + + if (!block2.o()) { + this.a(world, up, this.a.getBlockData().set(BlockHugeMushroom.VARIANT, BlockHugeMushroom.EnumHugeMushroomVariant.STEM)); + } + } + + return true; + } + } + } else { + return false; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenJungleTree.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenJungleTree.java new file mode 100644 index 0000000..3def2b6 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenJungleTree.java @@ -0,0 +1,104 @@ +package net.minecraft.server; + +import java.util.Random; + +public class WorldGenJungleTree extends WorldGenMegaTreeAbstract { + + public WorldGenJungleTree(boolean flag, int i, int j, IBlockData iblockdata, IBlockData iblockdata1) { + super(flag, i, j, iblockdata, iblockdata1); + } + + public boolean generate(World world, Random random, BlockPosition blockposition) { + int i = this.a(random); + + if (!this.a(world, random, blockposition, i)) { + return false; + } else { + this.c(world, blockposition.up(i), 2); + + for (int j = blockposition.getY() + i - 2 - random.nextInt(4); j > blockposition.getY() + i / 2; j -= 2 + random.nextInt(4)) { + float f = random.nextFloat() * 3.1415927F * 2.0F; + int k = blockposition.getX() + (int) (0.5F + MathHelper.cos(f) * 4.0F); + int l = blockposition.getZ() + (int) (0.5F + MathHelper.sin(f) * 4.0F); + + int i1; + + for (i1 = 0; i1 < 5; ++i1) { + k = blockposition.getX() + (int) (1.5F + MathHelper.cos(f) * (float) i1); + l = blockposition.getZ() + (int) (1.5F + MathHelper.sin(f) * (float) i1); + this.a(world, new BlockPosition(k, j - 3 + i1 / 2, l), this.b); + } + + i1 = 1 + random.nextInt(2); + + for (int k1 = j - i1; k1 <= j; ++k1) { + int l1 = k1 - j; + + this.b(world, new BlockPosition(k, k1, l), 1 - l1); + } + } + + for (int i2 = 0; i2 < i; ++i2) { + BlockPosition blockposition1 = blockposition.up(i2); + + if (this.a(world.getType(blockposition1).getBlock())) { + this.a(world, blockposition1, this.b); + if (i2 > 0) { + this.a(world, random, blockposition1.west(), BlockVine.EAST); + this.a(world, random, blockposition1.north(), BlockVine.SOUTH); + } + } + + if (i2 < i - 1) { + BlockPosition blockposition2 = blockposition1.east(); + + if (this.a(world.getType(blockposition2).getBlock())) { + this.a(world, blockposition2, this.b); + if (i2 > 0) { + this.a(world, random, blockposition2.east(), BlockVine.WEST); + this.a(world, random, blockposition2.north(), BlockVine.SOUTH); + } + } + + BlockPosition blockposition3 = blockposition1.south().east(); + + if (this.a(world.getType(blockposition3).getBlock())) { + this.a(world, blockposition3, this.b); + if (i2 > 0) { + this.a(world, random, blockposition3.east(), BlockVine.WEST); + this.a(world, random, blockposition3.south(), BlockVine.NORTH); + } + } + + BlockPosition blockposition4 = blockposition1.south(); + + if (this.a(world.getType(blockposition4).getBlock())) { + this.a(world, blockposition4, this.b); + if (i2 > 0) { + this.a(world, random, blockposition4.west(), BlockVine.EAST); + this.a(world, random, blockposition4.south(), BlockVine.NORTH); + } + } + } + } + + return true; + } + } + + private void a(World world, Random random, BlockPosition blockposition, BlockStateBoolean blockstateboolean) { + if (random.nextInt(3) > 0 && world.isEmpty(blockposition)) { + this.a(world, blockposition, Blocks.VINE.getBlockData().set(blockstateboolean, true)); + } + + } + + private void c(World world, BlockPosition blockposition, int i) { + byte b0 = 2; + + for (int j = -b0; j <= 0; ++j) { + this.a(world, blockposition.up(j), i + 1 - j); + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenLakes.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenLakes.java new file mode 100644 index 0000000..595fca1 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenLakes.java @@ -0,0 +1,131 @@ +package net.minecraft.server; + +import java.util.Random; + +public class WorldGenLakes extends WorldGenerator { + + private final Block a; + + public WorldGenLakes(Block block) { + this.a = block; + } + + public boolean generate(World world, Random random, BlockPosition blockposition) { + for (blockposition = blockposition.a(-8, 0, -8); blockposition.getY() > 5 && world.isEmpty(blockposition); blockposition = blockposition.down()) { + } + + if (blockposition.getY() <= 4) { + return false; + } else { + blockposition = blockposition.down(4); + boolean[] aboolean = new boolean[2048]; + int i = random.nextInt(4) + 4; + + int j; + + for (j = 0; j < i; ++j) { + double d0 = random.nextDouble() * 6.0D + 3.0D; + double d1 = random.nextDouble() * 4.0D + 2.0D; + double d2 = random.nextDouble() * 6.0D + 3.0D; + double d3 = random.nextDouble() * (16.0D - d0 - 2.0D) + 1.0D + d0 / 2.0D; + double d4 = random.nextDouble() * (8.0D - d1 - 4.0D) + 2.0D + d1 / 2.0D; + double d5 = random.nextDouble() * (16.0D - d2 - 2.0D) + 1.0D + d2 / 2.0D; + + for (int k = 1; k < 15; ++k) { + for (int l = 1; l < 15; ++l) { + for (int i1 = 1; i1 < 7; ++i1) { + double d6 = ((double) k - d3) / (d0 / 2.0D); + double d7 = ((double) i1 - d4) / (d1 / 2.0D); + double d8 = ((double) l - d5) / (d2 / 2.0D); + double d9 = d6 * d6 + d7 * d7 + d8 * d8; + + if (d9 < 1.0D) { + aboolean[(k * 16 + l) * 8 + i1] = true; + } + } + } + } + } + + int j1; + int k1; + boolean flag; + + for (j = 0; j < 16; ++j) { + for (k1 = 0; k1 < 16; ++k1) { + for (j1 = 0; j1 < 8; ++j1) { + flag = !aboolean[(j * 16 + k1) * 8 + j1] && (j < 15 && aboolean[((j + 1) * 16 + k1) * 8 + j1] || j > 0 && aboolean[((j - 1) * 16 + k1) * 8 + j1] || k1 < 15 && aboolean[(j * 16 + k1 + 1) * 8 + j1] || k1 > 0 && aboolean[(j * 16 + (k1 - 1)) * 8 + j1] || j1 < 7 && aboolean[(j * 16 + k1) * 8 + j1 + 1] || j1 > 0 && aboolean[(j * 16 + k1) * 8 + (j1 - 1)]); + if (flag) { + Material material = world.getType(blockposition.a(j, j1, k1)).getBlock().getMaterial(); + + if (j1 >= 4 && material.isLiquid()) { + return false; + } + + if (j1 < 4 && !material.isBuildable() && world.getType(blockposition.a(j, j1, k1)).getBlock() != this.a) { + return false; + } + } + } + } + } + + for (j = 0; j < 16; ++j) { + for (k1 = 0; k1 < 16; ++k1) { + for (j1 = 0; j1 < 8; ++j1) { + if (aboolean[(j * 16 + k1) * 8 + j1]) { + world.setTypeAndData(blockposition.a(j, j1, k1), j1 >= 4 ? Blocks.AIR.getBlockData() : this.a.getBlockData(), 2); + } + } + } + } + + for (j = 0; j < 16; ++j) { + for (k1 = 0; k1 < 16; ++k1) { + for (j1 = 4; j1 < 8; ++j1) { + if (aboolean[(j * 16 + k1) * 8 + j1]) { + BlockPosition blockposition1 = blockposition.a(j, j1 - 1, k1); + + if (world.getType(blockposition1).getBlock() == Blocks.DIRT && world.b(EnumSkyBlock.SKY, blockposition.a(j, j1, k1)) > 0) { + BiomeBase biomebase = world.getBiome(blockposition1); + + if (biomebase.ak.getBlock() == Blocks.MYCELIUM) { + world.setTypeAndData(blockposition1, Blocks.MYCELIUM.getBlockData(), 2); + } else { + world.setTypeAndData(blockposition1, Blocks.GRASS.getBlockData(), 2); + } + } + } + } + } + } + + if (this.a.getMaterial() == Material.LAVA) { + for (j = 0; j < 16; ++j) { + for (k1 = 0; k1 < 16; ++k1) { + for (j1 = 0; j1 < 8; ++j1) { + flag = !aboolean[(j * 16 + k1) * 8 + j1] && (j < 15 && aboolean[((j + 1) * 16 + k1) * 8 + j1] || j > 0 && aboolean[((j - 1) * 16 + k1) * 8 + j1] || k1 < 15 && aboolean[(j * 16 + k1 + 1) * 8 + j1] || k1 > 0 && aboolean[(j * 16 + (k1 - 1)) * 8 + j1] || j1 < 7 && aboolean[(j * 16 + k1) * 8 + j1 + 1] || j1 > 0 && aboolean[(j * 16 + k1) * 8 + (j1 - 1)]); + if (flag && (j1 < 4 || random.nextInt(2) != 0) && world.getType(blockposition.a(j, j1, k1)).getBlock().getMaterial().isBuildable()) { + world.setTypeAndData(blockposition.a(j, j1, k1), Blocks.STONE.getBlockData(), 2); + } + } + } + } + } + + if (this.a.getMaterial() == Material.WATER) { + for (j = 0; j < 16; ++j) { + for (k1 = 0; k1 < 16; ++k1) { + byte b0 = 4; + + if (world.v(blockposition.a(j, b0, k1))) { + world.setTypeAndData(blockposition.a(j, b0, k1), Blocks.ICE.getBlockData(), 2); + } + } + } + } + + return true; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenLargeFeature.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenLargeFeature.java new file mode 100644 index 0000000..b60c776 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenLargeFeature.java @@ -0,0 +1,119 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Random; + +public class WorldGenLargeFeature extends StructureGenerator { + + private static final List d = Arrays.asList(BiomeBase.DESERT, BiomeBase.DESERT_HILLS, BiomeBase.JUNGLE, BiomeBase.JUNGLE_HILLS, BiomeBase.SWAMPLAND); + private final List f; + private int g; + private final int h; + + public WorldGenLargeFeature() { + this.f = Lists.newArrayList(); + this.g = 32; + this.h = 8; + this.f.add(new BiomeBase.BiomeMeta(EntityWitch.class, 1, 1, 1)); + } + + public WorldGenLargeFeature(Map map) { + this(); + + for (Entry entry : map.entrySet()) { + if (entry.getKey().equals("distance")) { + this.g = MathHelper.a(entry.getValue(), this.g, this.h + 1); + } + } + + } + + public String a() { + return "Temple"; + } + + protected boolean a(int i, int j) { + int k = i; + int l = j; + + if (i < 0) { + i -= this.g - 1; + } + + if (j < 0) { + j -= this.g - 1; + } + + int i1 = i / this.g; + int j1 = j / this.g; + Random random = this.c.a(i1, j1, this.c.spigotConfig.largeFeatureSeed); // Spigot + + i1 *= this.g; + j1 *= this.g; + i1 += random.nextInt(this.g - this.h); + j1 += random.nextInt(this.g - this.h); + if (k == i1 && l == j1) { + BiomeBase biomebase = this.c.getWorldChunkManager().getBiome(k * 16 + 8, l * 16 + 8); + + if (biomebase == null) { + return false; + } + + for (BiomeBase biomebase1 : WorldGenLargeFeature.d) { + if (biomebase == biomebase1) { + return true; + } + } + } + + return false; + } + + protected StructureStart b(int i, int j) { + return new WorldGenLargeFeatureStart(this.c, this.b, i, j); + } + + public boolean a(BlockPosition blockposition) { + StructureStart structurestart = this.c(blockposition); + + if (structurestart instanceof WorldGenLargeFeatureStart && !structurestart.a.isEmpty()) { + StructurePiece structurepiece = structurestart.a.getFirst(); + + return structurepiece instanceof WorldGenRegistration.WorldGenWitchHut; + } else { + return false; + } + } + + public List b() { + return this.f; + } + + public static class WorldGenLargeFeatureStart extends StructureStart { + + public WorldGenLargeFeatureStart() { + } + + public WorldGenLargeFeatureStart(World world, Random random, int i, int j) { + super(i, j); + BiomeBase biomebase = world.getBiome(i * 16 + 8, 0, j * 16 + 8); + + if (biomebase != BiomeBase.JUNGLE && biomebase != BiomeBase.JUNGLE_HILLS) { + if (biomebase == BiomeBase.SWAMPLAND) { + this.a.add(new WorldGenRegistration.WorldGenWitchHut(random, i * 16, j * 16)); + } else if (biomebase == BiomeBase.DESERT || biomebase == BiomeBase.DESERT_HILLS) { + this.a.add(new WorldGenRegistration.WorldGenPyramidPiece(random, i * 16, j * 16)); + } + } else { + this.a.add(new WorldGenRegistration.WorldGenJungleTemple(random, i * 16, j * 16)); + } + + this.c(); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenLightStone1.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenLightStone1.java new file mode 100644 index 0000000..b314598 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenLightStone1.java @@ -0,0 +1,43 @@ +package net.minecraft.server; + +import java.util.Random; + +public class WorldGenLightStone1 extends WorldGenerator { + + public WorldGenLightStone1() { + } + + public boolean generate(World world, Random random, BlockPosition blockposition) { + if (!world.isEmpty(blockposition)) { + return false; + } else if (world.getType(blockposition.getX(), blockposition.getY() + 1, blockposition.getZ()).getBlock() != Blocks.NETHERRACK) { + return false; + } else { + world.setTypeAndData(blockposition, Blocks.GLOWSTONE.getBlockData(), 2); + + for (int i = 0; i < 1500; ++i) { + BlockPosition blockposition1 = blockposition.a(random.nextInt(8) - random.nextInt(8), -random.nextInt(12), random.nextInt(8) - random.nextInt(8)); + + if (world.getType(blockposition1).getBlock().getMaterial() == Material.AIR) { + int j = 0; + + for (EnumDirection enumdirection : EnumDirection.values()) { + if (world.getType(blockposition1.getX() + enumdirection.getAdjacentX(), blockposition1.getY() + enumdirection.getAdjacentY(), blockposition1.getZ() + enumdirection.getAdjacentZ()).getBlock() == Blocks.GLOWSTONE) { + ++j; + } + + if (j > 1) { + break; + } + } + + if (j == 1) { + world.setTypeAndData(blockposition1, Blocks.GLOWSTONE.getBlockData(), 2); + } + } + } + + return true; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenLightStone2.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenLightStone2.java new file mode 100644 index 0000000..1af6a2d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenLightStone2.java @@ -0,0 +1,43 @@ +package net.minecraft.server; + +import java.util.Random; + +public class WorldGenLightStone2 extends WorldGenerator { + + public WorldGenLightStone2() { + } + + public boolean generate(World world, Random random, BlockPosition blockposition) { + if (!world.isEmpty(blockposition)) { + return false; + } else if (world.getType(blockposition.getX(), blockposition.getY() + 1, blockposition.getZ()).getBlock() != Blocks.NETHERRACK) { + return false; + } else { + world.setTypeAndData(blockposition, Blocks.GLOWSTONE.getBlockData(), 2); + + for (int i = 0; i < 1500; ++i) { + BlockPosition blockposition1 = blockposition.a(random.nextInt(8) - random.nextInt(8), -random.nextInt(12), random.nextInt(8) - random.nextInt(8)); + + if (world.getType(blockposition1).getBlock().getMaterial() == Material.AIR) { + int j = 0; + + for (EnumDirection enumdirection : EnumDirection.values()) { + if (world.getType(blockposition1.getX() + enumdirection.getAdjacentX(), blockposition1.getY() + enumdirection.getAdjacentY(), blockposition1.getZ() + enumdirection.getAdjacentZ()).getBlock() == Blocks.GLOWSTONE) { + ++j; + } + + if (j > 1) { + break; + } + } + + if (j == 1) { + world.setTypeAndData(blockposition1, Blocks.GLOWSTONE.getBlockData(), 2); + } + } + } + + return true; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenLiquids.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenLiquids.java new file mode 100644 index 0000000..393fbe9 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenLiquids.java @@ -0,0 +1,65 @@ +package net.minecraft.server; + +import java.util.Random; + +public class WorldGenLiquids extends WorldGenerator { + + private final Block a; + + public WorldGenLiquids(Block block) { + this.a = block; + } + + public boolean generate(World world, Random random, BlockPosition blockposition) { + if (world.getType(blockposition.getX(), blockposition.getY() + 1, blockposition.getZ()).getBlock() != Blocks.STONE) { + return false; + } else if (world.getType(blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()).getBlock() != Blocks.STONE) { + return false; + } else if (world.getType(blockposition).getBlock().getMaterial() != Material.AIR && world.getType(blockposition).getBlock() != Blocks.STONE) { + return false; + } else { + int i = 0; + + if (world.getType(blockposition.getX() - 1, blockposition.getY(), blockposition.getZ()).getBlock() == Blocks.STONE) { + ++i; + } + + if (world.getType(blockposition.getX() + 1, blockposition.getY(), blockposition.getZ()).getBlock() == Blocks.STONE) { + ++i; + } + + if (world.getType(blockposition.getX(), blockposition.getY(), blockposition.getZ() - 1).getBlock() == Blocks.STONE) { + ++i; + } + + if (world.getType(blockposition.getX(), blockposition.getY(), blockposition.getZ() + 1).getBlock() == Blocks.STONE) { + ++i; + } + + int j = 0; + + if (world.isEmpty(blockposition.getX() - 1, blockposition.getY(), blockposition.getZ())) { + ++j; + } + + if (world.isEmpty(blockposition.getX() + 1, blockposition.getY(), blockposition.getZ())) { + ++j; + } + + if (world.isEmpty(blockposition.getX(), blockposition.getY(), blockposition.getZ() - 1)) { + ++j; + } + + if (world.isEmpty(blockposition.getX(), blockposition.getY(), blockposition.getZ() + 1)) { + ++j; + } + + if (i == 3 && j == 1) { + world.setTypeAndData(blockposition, this.a.getBlockData(), 2); + world.a(this.a, blockposition, random); + } + + return true; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenMegaTree.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenMegaTree.java new file mode 100644 index 0000000..5d9241a --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenMegaTree.java @@ -0,0 +1,112 @@ +package net.minecraft.server; + +import java.util.Random; + +public class WorldGenMegaTree extends WorldGenMegaTreeAbstract { + + private static final IBlockData e = Blocks.LOG.getBlockData().set(BlockLog1.VARIANT, BlockWood.EnumLogVariant.SPRUCE); + private static final IBlockData f = Blocks.LEAVES.getBlockData().set(BlockLeaves1.VARIANT, BlockWood.EnumLogVariant.SPRUCE).set(BlockLeaves.CHECK_DECAY, Boolean.FALSE); + private static final IBlockData g = Blocks.DIRT.getBlockData().set(BlockDirt.VARIANT, BlockDirt.EnumDirtVariant.PODZOL); + private final boolean h; + + public WorldGenMegaTree(boolean flag, boolean flag1) { + super(flag, 13, 15, WorldGenMegaTree.e, WorldGenMegaTree.f); + this.h = flag1; + } + + public boolean generate(World world, Random random, BlockPosition blockposition) { + int i = this.a(random); + + if (!this.a(world, random, blockposition, i)) { + return false; + } else { + this.a(world, blockposition.getX(), blockposition.getZ(), blockposition.getY() + i, 0, random); + + for (int j = 0; j < i; ++j) { + Block block = world.getType(blockposition.getX(), blockposition.getY() + j, blockposition.getZ()).getBlock(); + + if (block.getMaterial() == Material.AIR || block.getMaterial() == Material.LEAVES) { + this.a(world, blockposition.up(j), this.b); + } + + if (j < i - 1) { + block = world.getType(blockposition.a(1, j, 0)).getBlock(); + if (block.getMaterial() == Material.AIR || block.getMaterial() == Material.LEAVES) { + this.a(world, blockposition.a(1, j, 0), this.b); + } + + block = world.getType(blockposition.a(1, j, 1)).getBlock(); + if (block.getMaterial() == Material.AIR || block.getMaterial() == Material.LEAVES) { + this.a(world, blockposition.a(1, j, 1), this.b); + } + + block = world.getType(blockposition.a(0, j, 1)).getBlock(); + if (block.getMaterial() == Material.AIR || block.getMaterial() == Material.LEAVES) { + this.a(world, blockposition.a(0, j, 1), this.b); + } + } + } + + return true; + } + } + + private void a(World world, int i, int j, int k, int l, Random random) { + int i1 = random.nextInt(5) + (this.h ? this.a : 3); + int j1 = 0; + + for (int k1 = k - i1; k1 <= k; ++k1) { + int l1 = k - k1; + int i2 = l + MathHelper.d((float) l1 / (float) i1 * 3.5F); + + this.a(world, new BlockPosition(i, k1, j), i2 + (l1 > 0 && i2 == j1 && (k1 & 1) == 0 ? 1 : 0)); + j1 = i2; + } + + } + + public void a(World world, Random random, BlockPosition blockposition) { + this.b(world, blockposition.west().north()); + this.b(world, blockposition.east(2).north()); + this.b(world, blockposition.west().south(2)); + this.b(world, blockposition.east(2).south(2)); + + for (int i = 0; i < 5; ++i) { + int j = random.nextInt(64); + int k = j % 8; + int l = j / 8; + + if (k == 0 || k == 7 || l == 0 || l == 7) { + this.b(world, blockposition.a(-3 + k, 0, -3 + l)); + } + } + + } + + private void b(World world, BlockPosition blockposition) { + for (int i = -2; i <= 2; ++i) { + for (int j = -2; j <= 2; ++j) { + if (Math.abs(i) != 2 || Math.abs(j) != 2) { + this.c(world, blockposition.a(i, 0, j)); + } + } + } + + } + + private void c(World world, BlockPosition blockposition) { + for (int i = 2; i >= -3; --i) { + Block block = world.getType(blockposition.getX(), blockposition.getY() + i, blockposition.getZ()).getBlock(); + + if (block == Blocks.GRASS || block == Blocks.DIRT) { + this.a(world, blockposition.up(i), WorldGenMegaTree.g); + break; + } + + if (block.getMaterial() != Material.AIR && i < 0) { + break; + } + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenMegaTreeAbstract.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenMegaTreeAbstract.java new file mode 100644 index 0000000..2955cf9 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenMegaTreeAbstract.java @@ -0,0 +1,113 @@ +package net.minecraft.server; + +import java.util.Random; + +public abstract class WorldGenMegaTreeAbstract extends WorldGenTreeAbstract { + + protected final int a; + protected final IBlockData b; + protected final IBlockData c; + protected int d; + + public WorldGenMegaTreeAbstract(boolean flag, int i, int j, IBlockData iblockdata, IBlockData iblockdata1) { + super(flag); + this.a = i; + this.d = j; + this.b = iblockdata; + this.c = iblockdata1; + } + + protected int a(Random random) { + int i = random.nextInt(3) + this.a; + + if (this.d > 1) { + i += random.nextInt(this.d); + } + + return i; + } + + private boolean c(World world, BlockPosition blockposition, int i) { + boolean flag = true; + + if (blockposition.getY() >= 1 && blockposition.getY() + i + 1 <= 256) { + for (int j = 0; j <= 1 + i; ++j) { + byte b0 = 2; + + if (j == 0) { + b0 = 1; + } + + for (int k = -b0; k <= b0 && flag; ++k) { + for (int l = -b0; l <= b0 && flag; ++l) { + if (blockposition.getY() + j < 0 || blockposition.getY() + j >= 256 || (!this.a(world.getType(blockposition.a(k, j, l)).getBlock()) && world.getType(blockposition.a(k, j, l)).getBlock() != Blocks.SAPLING)) { // CraftBukkit - ignore our own saplings + flag = false; + } + } + } + } + + return flag; + } else { + return false; + } + } + + private boolean a(BlockPosition blockposition, World world) { + BlockPosition blockposition1 = blockposition.down(); + Block block = world.getType(blockposition1).getBlock(); + + if ((block == Blocks.GRASS || block == Blocks.DIRT) && blockposition.getY() >= 2) { + this.a(world, blockposition1); + this.a(world, blockposition1.east()); + this.a(world, blockposition1.south()); + this.a(world, blockposition1.south().east()); + return true; + } else { + return false; + } + } + + protected boolean a(World world, Random random, BlockPosition blockposition, int i) { + return this.c(world, blockposition, i) && this.a(blockposition, world); + } + + protected void a(World world, BlockPosition blockposition, int i) { + int j = i * i; + + for (int k = -i; k <= i + 1; ++k) { + for (int l = -i; l <= i + 1; ++l) { + int i1 = k - 1; + int j1 = l - 1; + + if (k * k + l * l <= j || i1 * i1 + j1 * j1 <= j || k * k + j1 * j1 <= j || i1 * i1 + l * l <= j) { + BlockPosition blockposition1 = blockposition.a(k, 0, l); + Material material = world.getType(blockposition1).getBlock().getMaterial(); + + if (material == Material.AIR || material == Material.LEAVES) { + this.a(world, blockposition1, this.c); + } + } + } + } + + } + + protected void b(World world, BlockPosition blockposition, int i) { + int j = i * i; + + for (int k = -i; k <= i; ++k) { + for (int l = -i; l <= i; ++l) { + if (k * k + l * l <= j) { + BlockPosition blockposition1 = blockposition.a(k, 0, l); + Material material = world.getType(blockposition1).getBlock().getMaterial(); + + if (material == Material.AIR || material == Material.LEAVES) { + this.a(world, blockposition1, this.c); + } + } + } + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenMelon.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenMelon.java new file mode 100644 index 0000000..651f265 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenMelon.java @@ -0,0 +1,21 @@ +package net.minecraft.server; + +import java.util.Random; + +public class WorldGenMelon extends WorldGenerator { + + public WorldGenMelon() { + } + + public boolean generate(World world, Random random, BlockPosition blockposition) { + for (int i = 0; i < 64; ++i) { + BlockPosition blockposition1 = blockposition.a(random.nextInt(8) - random.nextInt(8), random.nextInt(4) - random.nextInt(4), random.nextInt(8) - random.nextInt(8)); + + if (Blocks.MELON_BLOCK.canPlace(world, blockposition1) && world.getType(blockposition1.getX(), blockposition1.getY() - 1, blockposition1.getZ()).getBlock() == Blocks.GRASS) { + world.setTypeAndData(blockposition1, Blocks.MELON_BLOCK.getBlockData(), 2); + } + } + + return true; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenMinable.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenMinable.java new file mode 100644 index 0000000..f5178c1 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenMinable.java @@ -0,0 +1,101 @@ +package net.minecraft.server; + +import com.google.common.base.Predicate; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +public class WorldGenMinable extends WorldGenerator { + + private final IBlockData a; + private final int b; + private final Predicate c; + private boolean mustTouchAir; + + public WorldGenMinable(IBlockData iblockdata, int i) { + this(iblockdata, i, BlockPredicate.a(Blocks.STONE)); + } + + public WorldGenMinable(IBlockData iblockdata, int i, Predicate predicate) { + this.a = iblockdata; + this.b = i; + this.c = predicate; + } + + public WorldGenMinable(IBlockData block, int size, boolean mustTouchAir) { + this(block, size); + this.mustTouchAir = mustTouchAir; + } + + public boolean generate(World world, Random random, BlockPosition blockposition) { + float f = random.nextFloat() * 3.1415927F; + double d0 = (float) (blockposition.getX() + 8) + MathHelper.sin(f) * (float) this.b / 8.0F; + double d1 = (float) (blockposition.getX() + 8) - MathHelper.sin(f) * (float) this.b / 8.0F; + double d2 = (float) (blockposition.getZ() + 8) + MathHelper.cos(f) * (float) this.b / 8.0F; + double d3 = (float) (blockposition.getZ() + 8) - MathHelper.cos(f) * (float) this.b / 8.0F; + double d4 = blockposition.getY() + random.nextInt(3) - 2; + double d5 = blockposition.getY() + random.nextInt(3) - 2; + + boolean touchedAir = false; + List blocks = mustTouchAir ? new ArrayList<>() : null; + + for (int i = 0; i < this.b; ++i) { + float f1 = (float) i / (float) this.b; + double d6 = d0 + (d1 - d0) * (double) f1; + double d7 = d4 + (d5 - d4) * (double) f1; + double d8 = d2 + (d3 - d2) * (double) f1; + double d9 = random.nextDouble() * (double) this.b / 16.0D; + double d10 = (double) (MathHelper.sin(3.1415927F * f1) + 1.0F) * d9 + 1.0D; + double d11 = (double) (MathHelper.sin(3.1415927F * f1) + 1.0F) * d9 + 1.0D; + int j = MathHelper.floor(d6 - d10 / 2.0D); + int k = MathHelper.floor(d7 - d11 / 2.0D); + int l = MathHelper.floor(d8 - d10 / 2.0D); + int i1 = MathHelper.floor(d6 + d10 / 2.0D); + int j1 = MathHelper.floor(d7 + d11 / 2.0D); + int k1 = MathHelper.floor(d8 + d10 / 2.0D); + + for (int l1 = j; l1 <= i1; ++l1) { + double d12 = ((double) l1 + 0.5D - d6) / (d10 / 2.0D); + + if (d12 * d12 < 1.0D) { + for (int i2 = k; i2 <= j1; ++i2) { + double d13 = ((double) i2 + 0.5D - d7) / (d11 / 2.0D); + + if (d12 * d12 + d13 * d13 < 1.0D) { + for (int j2 = l; j2 <= k1; ++j2) { + double d14 = ((double) j2 + 0.5D - d8) / (d10 / 2.0D); + + if (d12 * d12 + d13 * d13 + d14 * d14 < 1.0D) { + if (this.c.apply(world.getType(l1, i2, j2))) { + BlockPosition blockposition1 = new BlockPosition(l1, i2, j2); + if (mustTouchAir) { + blocks.add(blockposition1); + touchedAir |= + world.getType(l1 + 1, i2, j2).getBlock() == Blocks.AIR || + world.getType(l1 - 1, i2, j2).getBlock() == Blocks.AIR || + world.getType(l1, i2 + 1, j2).getBlock() == Blocks.AIR || + world.getType(l1, i2 - 1, j2).getBlock() == Blocks.AIR || + world.getType(l1, i2, j2 + 1).getBlock() == Blocks.AIR || + world.getType(l1, i2, j2 - 1).getBlock() == Blocks.AIR; + } else { + world.setTypeAndData(blockposition1, this.a, 2); + } + } + } + } + } + } + } + } + } + + if (mustTouchAir && touchedAir) { + for (BlockPosition pos : blocks) { + world.setTypeAndData(pos, this.a, 2); + } + } + + return true; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenMineshaft.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenMineshaft.java new file mode 100644 index 0000000..ead036d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenMineshaft.java @@ -0,0 +1,33 @@ +package net.minecraft.server; + +import java.util.Map; +import java.util.Map.Entry; + +public class WorldGenMineshaft extends StructureGenerator { + + private double d = 0.004D; + + public WorldGenMineshaft() { + } + + public String a() { + return "Mineshaft"; + } + + public WorldGenMineshaft(Map map) { + for (Entry entry : map.entrySet()) { + if (entry.getKey().equals("chance")) { + this.d = MathHelper.a(entry.getValue(), this.d); + } + } + + } + + protected boolean a(int i, int j) { + return this.b.nextDouble() < this.d && this.b.nextInt(80) < Math.max(Math.abs(i), Math.abs(j)); + } + + protected StructureStart b(int i, int j) { + return new WorldGenMineshaftStart(this.c, this.b, i, j); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenMineshaftPieces.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenMineshaftPieces.java new file mode 100644 index 0000000..76aa09f --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenMineshaftPieces.java @@ -0,0 +1,694 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; + +import java.util.List; +import java.util.Random; + +public class WorldGenMineshaftPieces { + + private static final List a = Lists.newArrayList(new StructurePieceTreasure(Items.IRON_INGOT, 0, 1, 5, 10), new StructurePieceTreasure(Items.GOLD_INGOT, 0, 1, 3, 5), new StructurePieceTreasure(Items.REDSTONE, 0, 4, 9, 5), new StructurePieceTreasure(Items.DYE, EnumColor.BLUE.getInvColorIndex(), 4, 9, 5), new StructurePieceTreasure(Items.DIAMOND, 0, 1, 2, 3), new StructurePieceTreasure(Items.COAL, 0, 3, 8, 10), new StructurePieceTreasure(Items.BREAD, 0, 1, 3, 15), new StructurePieceTreasure(Items.IRON_PICKAXE, 0, 1, 1, 1), new StructurePieceTreasure(Item.getItemOf(Blocks.RAIL), 0, 4, 8, 1), new StructurePieceTreasure(Items.MELON_SEEDS, 0, 2, 4, 10), new StructurePieceTreasure(Items.PUMPKIN_SEEDS, 0, 2, 4, 10), new StructurePieceTreasure(Items.SADDLE, 0, 1, 1, 3), new StructurePieceTreasure(Items.IRON_HORSE_ARMOR, 0, 1, 1, 1)); + + public static void a() { + WorldGenFactory.a(WorldGenMineshaftCorridor.class, "MSCorridor"); + WorldGenFactory.a(WorldGenMineshaftCross.class, "MSCrossing"); + WorldGenFactory.a(WorldGenMineshaftRoom.class, "MSRoom"); + WorldGenFactory.a(WorldGenMineshaftStairs.class, "MSStairs"); + } + + private static StructurePiece a(List list, Random random, int i, int j, int k, EnumDirection enumdirection, int l) { + int i1 = random.nextInt(100); + StructureBoundingBox structureboundingbox; + + if (i1 >= 80) { + structureboundingbox = WorldGenMineshaftCross.a(list, random, i, j, k, enumdirection); + if (structureboundingbox != null) { + return new WorldGenMineshaftCross(l, random, structureboundingbox, enumdirection); + } + } else if (i1 >= 70) { + structureboundingbox = WorldGenMineshaftStairs.a(list, random, i, j, k, enumdirection); + if (structureboundingbox != null) { + return new WorldGenMineshaftStairs(l, random, structureboundingbox, enumdirection); + } + } else { + structureboundingbox = WorldGenMineshaftCorridor.a(list, random, i, j, k, enumdirection); + if (structureboundingbox != null) { + return new WorldGenMineshaftCorridor(l, random, structureboundingbox, enumdirection); + } + } + + return null; + } + + private static StructurePiece b(StructurePiece structurepiece, List list, Random random, int i, int j, int k, EnumDirection enumdirection, int l) { + if (l > 8) { + return null; + } else if (Math.abs(i - structurepiece.c().a) <= 80 && Math.abs(k - structurepiece.c().c) <= 80) { + StructurePiece structurepiece1 = a(list, random, i, j, k, enumdirection, l + 1); + + if (structurepiece1 != null) { + list.add(structurepiece1); + structurepiece1.a(structurepiece, list, random); + } + + return structurepiece1; + } else { + return null; + } + } + + static class SyntheticClass_1 { + + static final int[] a = new int[EnumDirection.values().length]; + + static { + try { + SyntheticClass_1.a[EnumDirection.NORTH.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.a[EnumDirection.SOUTH.ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.a[EnumDirection.WEST.ordinal()] = 3; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.a[EnumDirection.EAST.ordinal()] = 4; + } catch (NoSuchFieldError ignored) { + } + + } + } + + public static class WorldGenMineshaftStairs extends StructurePiece { + + public WorldGenMineshaftStairs() { + } + + public WorldGenMineshaftStairs(int i, Random random, StructureBoundingBox structureboundingbox, EnumDirection enumdirection) { + super(i); + this.m = enumdirection; + this.l = structureboundingbox; + } + + protected void a(NBTTagCompound nbttagcompound) { + } + + protected void b(NBTTagCompound nbttagcompound) { + } + + public static StructureBoundingBox a(List list, Random random, int i, int j, int k, EnumDirection enumdirection) { + StructureBoundingBox structureboundingbox = new StructureBoundingBox(i, j - 5, k, i, j + 2, k); + + switch (SyntheticClass_1.a[enumdirection.ordinal()]) { + case 1: + structureboundingbox.d = i + 2; + structureboundingbox.c = k - 8; + break; + + case 2: + structureboundingbox.d = i + 2; + structureboundingbox.f = k + 8; + break; + + case 3: + structureboundingbox.a = i - 8; + structureboundingbox.f = k + 2; + break; + + case 4: + structureboundingbox.d = i + 8; + structureboundingbox.f = k + 2; + } + + return StructurePiece.a(list, structureboundingbox) != null ? null : structureboundingbox; + } + + public void a(StructurePiece structurepiece, List list, Random random) { + int i = this.d(); + + if (this.m != null) { + switch (SyntheticClass_1.a[this.m.ordinal()]) { + case 1: + WorldGenMineshaftPieces.b(structurepiece, list, random, this.l.a, this.l.b, this.l.c - 1, EnumDirection.NORTH, i); + break; + + case 2: + WorldGenMineshaftPieces.b(structurepiece, list, random, this.l.a, this.l.b, this.l.f + 1, EnumDirection.SOUTH, i); + break; + + case 3: + WorldGenMineshaftPieces.b(structurepiece, list, random, this.l.a - 1, this.l.b, this.l.c, EnumDirection.WEST, i); + break; + + case 4: + WorldGenMineshaftPieces.b(structurepiece, list, random, this.l.d + 1, this.l.b, this.l.c, EnumDirection.EAST, i); + } + } + + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + if (this.a(world, structureboundingbox)) { + return false; + } else { + this.a(world, structureboundingbox, 0, 5, 0, 2, 7, 1, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, 0, 0, 7, 2, 2, 8, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + + for (int i = 0; i < 5; ++i) { + this.a(world, structureboundingbox, 0, 5 - i - (i < 4 ? 1 : 0), 2 + i, 2, 7 - i, 2 + i, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + } + + return true; + } + } + } + + public static class WorldGenMineshaftCross extends StructurePiece { + + private EnumDirection a; + private boolean b; + + public WorldGenMineshaftCross() { + } + + protected void a(NBTTagCompound nbttagcompound) { + nbttagcompound.setBoolean("tf", this.b); + nbttagcompound.setInt("D", this.a.b()); + } + + protected void b(NBTTagCompound nbttagcompound) { + this.b = nbttagcompound.getBoolean("tf"); + this.a = EnumDirection.fromType2(nbttagcompound.getInt("D")); + } + + public WorldGenMineshaftCross(int i, Random random, StructureBoundingBox structureboundingbox, EnumDirection enumdirection) { + super(i); + this.a = enumdirection; + this.l = structureboundingbox; + this.b = structureboundingbox.d() > 3; + } + + public static StructureBoundingBox a(List list, Random random, int i, int j, int k, EnumDirection enumdirection) { + StructureBoundingBox structureboundingbox = new StructureBoundingBox(i, j, k, i, j + 2, k); + + if (random.nextInt(4) == 0) { + structureboundingbox.e += 4; + } + + switch (SyntheticClass_1.a[enumdirection.ordinal()]) { + case 1: + structureboundingbox.a = i - 1; + structureboundingbox.d = i + 3; + structureboundingbox.c = k - 4; + break; + + case 2: + structureboundingbox.a = i - 1; + structureboundingbox.d = i + 3; + structureboundingbox.f = k + 4; + break; + + case 3: + structureboundingbox.a = i - 4; + structureboundingbox.c = k - 1; + structureboundingbox.f = k + 3; + break; + + case 4: + structureboundingbox.d = i + 4; + structureboundingbox.c = k - 1; + structureboundingbox.f = k + 3; + } + + return StructurePiece.a(list, structureboundingbox) != null ? null : structureboundingbox; + } + + public void a(StructurePiece structurepiece, List list, Random random) { + int i = this.d(); + + switch (SyntheticClass_1.a[this.a.ordinal()]) { + case 1: + WorldGenMineshaftPieces.b(structurepiece, list, random, this.l.a + 1, this.l.b, this.l.c - 1, EnumDirection.NORTH, i); + WorldGenMineshaftPieces.b(structurepiece, list, random, this.l.a - 1, this.l.b, this.l.c + 1, EnumDirection.WEST, i); + WorldGenMineshaftPieces.b(structurepiece, list, random, this.l.d + 1, this.l.b, this.l.c + 1, EnumDirection.EAST, i); + break; + + case 2: + WorldGenMineshaftPieces.b(structurepiece, list, random, this.l.a + 1, this.l.b, this.l.f + 1, EnumDirection.SOUTH, i); + WorldGenMineshaftPieces.b(structurepiece, list, random, this.l.a - 1, this.l.b, this.l.c + 1, EnumDirection.WEST, i); + WorldGenMineshaftPieces.b(structurepiece, list, random, this.l.d + 1, this.l.b, this.l.c + 1, EnumDirection.EAST, i); + break; + + case 3: + WorldGenMineshaftPieces.b(structurepiece, list, random, this.l.a + 1, this.l.b, this.l.c - 1, EnumDirection.NORTH, i); + WorldGenMineshaftPieces.b(structurepiece, list, random, this.l.a + 1, this.l.b, this.l.f + 1, EnumDirection.SOUTH, i); + WorldGenMineshaftPieces.b(structurepiece, list, random, this.l.a - 1, this.l.b, this.l.c + 1, EnumDirection.WEST, i); + break; + + case 4: + WorldGenMineshaftPieces.b(structurepiece, list, random, this.l.a + 1, this.l.b, this.l.c - 1, EnumDirection.NORTH, i); + WorldGenMineshaftPieces.b(structurepiece, list, random, this.l.a + 1, this.l.b, this.l.f + 1, EnumDirection.SOUTH, i); + WorldGenMineshaftPieces.b(structurepiece, list, random, this.l.d + 1, this.l.b, this.l.c + 1, EnumDirection.EAST, i); + } + + if (this.b) { + if (random.nextBoolean()) { + WorldGenMineshaftPieces.b(structurepiece, list, random, this.l.a + 1, this.l.b + 3 + 1, this.l.c - 1, EnumDirection.NORTH, i); + } + + if (random.nextBoolean()) { + WorldGenMineshaftPieces.b(structurepiece, list, random, this.l.a - 1, this.l.b + 3 + 1, this.l.c + 1, EnumDirection.WEST, i); + } + + if (random.nextBoolean()) { + WorldGenMineshaftPieces.b(structurepiece, list, random, this.l.d + 1, this.l.b + 3 + 1, this.l.c + 1, EnumDirection.EAST, i); + } + + if (random.nextBoolean()) { + WorldGenMineshaftPieces.b(structurepiece, list, random, this.l.a + 1, this.l.b + 3 + 1, this.l.f + 1, EnumDirection.SOUTH, i); + } + } + + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + if (this.a(world, structureboundingbox)) { + return false; + } else { + if (this.b) { + this.a(world, structureboundingbox, this.l.a + 1, this.l.b, this.l.c, this.l.d - 1, this.l.b + 3 - 1, this.l.f, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, this.l.a, this.l.b, this.l.c + 1, this.l.d, this.l.b + 3 - 1, this.l.f - 1, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, this.l.a + 1, this.l.e - 2, this.l.c, this.l.d - 1, this.l.e, this.l.f, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, this.l.a, this.l.e - 2, this.l.c + 1, this.l.d, this.l.e, this.l.f - 1, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, this.l.a + 1, this.l.b + 3, this.l.c + 1, this.l.d - 1, this.l.b + 3, this.l.f - 1, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + } else { + this.a(world, structureboundingbox, this.l.a + 1, this.l.b, this.l.c, this.l.d - 1, this.l.e, this.l.f, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, this.l.a, this.l.b, this.l.c + 1, this.l.d, this.l.e, this.l.f - 1, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + } + + this.a(world, structureboundingbox, this.l.a + 1, this.l.b, this.l.c + 1, this.l.a + 1, this.l.e, this.l.c + 1, Blocks.PLANKS.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, this.l.a + 1, this.l.b, this.l.f - 1, this.l.a + 1, this.l.e, this.l.f - 1, Blocks.PLANKS.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, this.l.d - 1, this.l.b, this.l.c + 1, this.l.d - 1, this.l.e, this.l.c + 1, Blocks.PLANKS.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, this.l.d - 1, this.l.b, this.l.f - 1, this.l.d - 1, this.l.e, this.l.f - 1, Blocks.PLANKS.getBlockData(), Blocks.AIR.getBlockData(), false); + + for (int i = this.l.a; i <= this.l.d; ++i) { + for (int j = this.l.c; j <= this.l.f; ++j) { + if (this.a(world, i, this.l.b - 1, j, structureboundingbox).getBlock().getMaterial() == Material.AIR) { + this.a(world, Blocks.PLANKS.getBlockData(), i, this.l.b - 1, j, structureboundingbox); + } + } + } + + return true; + } + } + } + + public static class WorldGenMineshaftCorridor extends StructurePiece { + + private boolean a; + private boolean b; + private boolean c; + private int d; + + public WorldGenMineshaftCorridor() { + } + + protected void a(NBTTagCompound nbttagcompound) { + nbttagcompound.setBoolean("hr", this.a); + nbttagcompound.setBoolean("sc", this.b); + nbttagcompound.setBoolean("hps", this.c); + nbttagcompound.setInt("Num", this.d); + } + + protected void b(NBTTagCompound nbttagcompound) { + this.a = nbttagcompound.getBoolean("hr"); + this.b = nbttagcompound.getBoolean("sc"); + this.c = nbttagcompound.getBoolean("hps"); + this.d = nbttagcompound.getInt("Num"); + } + + public WorldGenMineshaftCorridor(int i, Random random, StructureBoundingBox structureboundingbox, EnumDirection enumdirection) { + super(i); + this.m = enumdirection; + this.l = structureboundingbox; + this.a = random.nextInt(3) == 0; + this.b = !this.a && random.nextInt(23) == 0; + if (this.m != EnumDirection.NORTH && this.m != EnumDirection.SOUTH) { + this.d = structureboundingbox.c() / 5; + } else { + this.d = structureboundingbox.e() / 5; + } + + } + + public static StructureBoundingBox a(List list, Random random, int i, int j, int k, EnumDirection enumdirection) { + StructureBoundingBox structureboundingbox = new StructureBoundingBox(i, j, k, i, j + 2, k); + + int l; + + for (l = random.nextInt(3) + 2; l > 0; --l) { + int i1 = l * 5; + + switch (SyntheticClass_1.a[enumdirection.ordinal()]) { + case 1: + structureboundingbox.d = i + 2; + structureboundingbox.c = k - (i1 - 1); + break; + + case 2: + structureboundingbox.d = i + 2; + structureboundingbox.f = k + (i1 - 1); + break; + + case 3: + structureboundingbox.a = i - (i1 - 1); + structureboundingbox.f = k + 2; + break; + + case 4: + structureboundingbox.d = i + (i1 - 1); + structureboundingbox.f = k + 2; + } + + if (StructurePiece.a(list, structureboundingbox) == null) { + break; + } + } + + return l > 0 ? structureboundingbox : null; + } + + public void a(StructurePiece structurepiece, List list, Random random) { + int i = this.d(); + int j = random.nextInt(4); + + if (this.m != null) { + switch (SyntheticClass_1.a[this.m.ordinal()]) { + case 1: + if (j <= 1) { + WorldGenMineshaftPieces.b(structurepiece, list, random, this.l.a, this.l.b - 1 + random.nextInt(3), this.l.c - 1, this.m, i); + } else if (j == 2) { + WorldGenMineshaftPieces.b(structurepiece, list, random, this.l.a - 1, this.l.b - 1 + random.nextInt(3), this.l.c, EnumDirection.WEST, i); + } else { + WorldGenMineshaftPieces.b(structurepiece, list, random, this.l.d + 1, this.l.b - 1 + random.nextInt(3), this.l.c, EnumDirection.EAST, i); + } + break; + + case 2: + if (j <= 1) { + WorldGenMineshaftPieces.b(structurepiece, list, random, this.l.a, this.l.b - 1 + random.nextInt(3), this.l.f + 1, this.m, i); + } else if (j == 2) { + WorldGenMineshaftPieces.b(structurepiece, list, random, this.l.a - 1, this.l.b - 1 + random.nextInt(3), this.l.f - 3, EnumDirection.WEST, i); + } else { + WorldGenMineshaftPieces.b(structurepiece, list, random, this.l.d + 1, this.l.b - 1 + random.nextInt(3), this.l.f - 3, EnumDirection.EAST, i); + } + break; + + case 3: + if (j <= 1) { + WorldGenMineshaftPieces.b(structurepiece, list, random, this.l.a - 1, this.l.b - 1 + random.nextInt(3), this.l.c, this.m, i); + } else if (j == 2) { + WorldGenMineshaftPieces.b(structurepiece, list, random, this.l.a, this.l.b - 1 + random.nextInt(3), this.l.c - 1, EnumDirection.NORTH, i); + } else { + WorldGenMineshaftPieces.b(structurepiece, list, random, this.l.a, this.l.b - 1 + random.nextInt(3), this.l.f + 1, EnumDirection.SOUTH, i); + } + break; + + case 4: + if (j <= 1) { + WorldGenMineshaftPieces.b(structurepiece, list, random, this.l.d + 1, this.l.b - 1 + random.nextInt(3), this.l.c, this.m, i); + } else if (j == 2) { + WorldGenMineshaftPieces.b(structurepiece, list, random, this.l.d - 3, this.l.b - 1 + random.nextInt(3), this.l.c - 1, EnumDirection.NORTH, i); + } else { + WorldGenMineshaftPieces.b(structurepiece, list, random, this.l.d - 3, this.l.b - 1 + random.nextInt(3), this.l.f + 1, EnumDirection.SOUTH, i); + } + } + } + + if (i < 8) { + int k; + int l; + + if (this.m != EnumDirection.NORTH && this.m != EnumDirection.SOUTH) { + for (k = this.l.a + 3; k + 3 <= this.l.d; k += 5) { + l = random.nextInt(5); + if (l == 0) { + WorldGenMineshaftPieces.b(structurepiece, list, random, k, this.l.b, this.l.c - 1, EnumDirection.NORTH, i + 1); + } else if (l == 1) { + WorldGenMineshaftPieces.b(structurepiece, list, random, k, this.l.b, this.l.f + 1, EnumDirection.SOUTH, i + 1); + } + } + } else { + for (k = this.l.c + 3; k + 3 <= this.l.f; k += 5) { + l = random.nextInt(5); + if (l == 0) { + WorldGenMineshaftPieces.b(structurepiece, list, random, this.l.a - 1, this.l.b, k, EnumDirection.WEST, i + 1); + } else if (l == 1) { + WorldGenMineshaftPieces.b(structurepiece, list, random, this.l.d + 1, this.l.b, k, EnumDirection.EAST, i + 1); + } + } + } + } + + } + + protected boolean a(World world, StructureBoundingBox structureboundingbox, Random random, int i, int j, int k, List list, int l) { + BlockPosition blockposition = new BlockPosition(this.a(i, k), this.d(j), this.b(i, k)); + + if (structureboundingbox.b(blockposition) && world.getType(blockposition).getBlock().getMaterial() == Material.AIR) { + int i1 = random.nextBoolean() ? 1 : 0; + + world.setTypeAndData(blockposition, Blocks.RAIL.fromLegacyData(this.a(Blocks.RAIL, i1)), 2); + EntityMinecartChest entityminecartchest = new EntityMinecartChest(world, (float) blockposition.getX() + 0.5F, (float) blockposition.getY() + 0.5F, (float) blockposition.getZ() + 0.5F); + + StructurePieceTreasure.a(random, list, entityminecartchest, l); + world.addEntity(entityminecartchest); + return true; + } else { + return false; + } + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + if (this.a(world, structureboundingbox)) { + return false; + } else { + + int i = this.d * 5 - 1; + + this.a(world, structureboundingbox, 0, 0, 0, 2, 1, i, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, random, 0.8F, 0, 2, 0, 2, 2, i, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + if (this.b) { + this.a(world, structureboundingbox, random, 0.6F, 0, 0, 0, 2, 1, i, Blocks.WEB.getBlockData(), Blocks.AIR.getBlockData(), false); + } + + int j; + int k; + + for (j = 0; j < this.d; ++j) { + k = 2 + j * 5; + this.a(world, structureboundingbox, 0, 0, k, 0, 1, k, Blocks.FENCE.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, 2, 0, k, 2, 1, k, Blocks.FENCE.getBlockData(), Blocks.AIR.getBlockData(), false); + if (random.nextInt(4) == 0) { + this.a(world, structureboundingbox, 0, 2, k, 0, 2, k, Blocks.PLANKS.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, 2, 2, k, 2, 2, k, Blocks.PLANKS.getBlockData(), Blocks.AIR.getBlockData(), false); + } else { + this.a(world, structureboundingbox, 0, 2, k, 2, 2, k, Blocks.PLANKS.getBlockData(), Blocks.AIR.getBlockData(), false); + } + + this.a(world, structureboundingbox, random, 0.1F, 0, 2, k - 1, Blocks.WEB.getBlockData()); + this.a(world, structureboundingbox, random, 0.1F, 2, 2, k - 1, Blocks.WEB.getBlockData()); + this.a(world, structureboundingbox, random, 0.1F, 0, 2, k + 1, Blocks.WEB.getBlockData()); + this.a(world, structureboundingbox, random, 0.1F, 2, 2, k + 1, Blocks.WEB.getBlockData()); + this.a(world, structureboundingbox, random, 0.05F, 0, 2, k - 2, Blocks.WEB.getBlockData()); + this.a(world, structureboundingbox, random, 0.05F, 2, 2, k - 2, Blocks.WEB.getBlockData()); + this.a(world, structureboundingbox, random, 0.05F, 0, 2, k + 2, Blocks.WEB.getBlockData()); + this.a(world, structureboundingbox, random, 0.05F, 2, 2, k + 2, Blocks.WEB.getBlockData()); + this.a(world, structureboundingbox, random, 0.05F, 1, 2, k - 1, Blocks.TORCH.fromLegacyData(EnumDirection.UP.a())); + this.a(world, structureboundingbox, random, 0.05F, 1, 2, k + 1, Blocks.TORCH.fromLegacyData(EnumDirection.UP.a())); + if (random.nextInt(100) == 0) { + this.a(world, structureboundingbox, random, 2, 0, k - 1, StructurePieceTreasure.a(WorldGenMineshaftPieces.a, Items.ENCHANTED_BOOK.b(random)), 3 + random.nextInt(4)); + } + + if (random.nextInt(100) == 0) { + this.a(world, structureboundingbox, random, 0, 0, k + 1, StructurePieceTreasure.a(WorldGenMineshaftPieces.a, Items.ENCHANTED_BOOK.b(random)), 3 + random.nextInt(4)); + } + + if (this.b && !this.c) { + int l = this.d(0); + int i1 = k - 1 + random.nextInt(3); + int j1 = this.a(1, i1); + + i1 = this.b(1, i1); + if (structureboundingbox.b(j1, l, i1)) { + BlockPosition blockposition = new BlockPosition(j1, l, i1); + + this.c = true; + world.setTypeAndData(blockposition, Blocks.MOB_SPAWNER.getBlockData(), 2); + TileEntity tileentity = world.getTileEntity(blockposition); + + if (tileentity instanceof TileEntityMobSpawner) { + ((TileEntityMobSpawner) tileentity).getSpawner().setMobName("CaveSpider"); + } + } + } + } + + for (j = 0; j <= 2; ++j) { + for (k = 0; k <= i; ++k) { + byte b0 = -1; + IBlockData iblockdata = this.a(world, j, b0, k, structureboundingbox); + + if (iblockdata.getBlock().getMaterial() == Material.AIR) { + byte b1 = -1; + + this.a(world, Blocks.PLANKS.getBlockData(), j, b1, k, structureboundingbox); + } + } + } + + if (this.a) { + for (j = 0; j <= i; ++j) { + IBlockData iblockdata1 = this.a(world, 1, -1, j, structureboundingbox); + + if (iblockdata1.getBlock().getMaterial() != Material.AIR && iblockdata1.getBlock().o()) { + this.a(world, structureboundingbox, random, 0.7F, 1, 0, j, Blocks.RAIL.fromLegacyData(this.a(Blocks.RAIL, 0))); + } + } + } + + return true; + } + } + } + + public static class WorldGenMineshaftRoom extends StructurePiece { + + private final List a = Lists.newLinkedList(); + + public WorldGenMineshaftRoom() { + } + + public WorldGenMineshaftRoom(int i, Random random, int j, int k) { + super(i); + this.l = new StructureBoundingBox(j, 50, k, j + 7 + random.nextInt(6), 54 + random.nextInt(6), k + 7 + random.nextInt(6)); + } + + public void a(StructurePiece structurepiece, List list, Random random) { + int i = this.d(); + int j = this.l.d() - 3 - 1; + + if (j <= 0) { + j = 1; + } + + int k; + StructurePiece structurepiece1; + StructureBoundingBox structureboundingbox; + + for (k = 0; k < this.l.c(); k += 4) { + k += random.nextInt(this.l.c()); + if (k + 3 > this.l.c()) { + break; + } + + structurepiece1 = WorldGenMineshaftPieces.b(structurepiece, list, random, this.l.a + k, this.l.b + random.nextInt(j) + 1, this.l.c - 1, EnumDirection.NORTH, i); + if (structurepiece1 != null) { + structureboundingbox = structurepiece1.c(); + this.a.add(new StructureBoundingBox(structureboundingbox.a, structureboundingbox.b, this.l.c, structureboundingbox.d, structureboundingbox.e, this.l.c + 1)); + } + } + + for (k = 0; k < this.l.c(); k += 4) { + k += random.nextInt(this.l.c()); + if (k + 3 > this.l.c()) { + break; + } + + structurepiece1 = WorldGenMineshaftPieces.b(structurepiece, list, random, this.l.a + k, this.l.b + random.nextInt(j) + 1, this.l.f + 1, EnumDirection.SOUTH, i); + if (structurepiece1 != null) { + structureboundingbox = structurepiece1.c(); + this.a.add(new StructureBoundingBox(structureboundingbox.a, structureboundingbox.b, this.l.f - 1, structureboundingbox.d, structureboundingbox.e, this.l.f)); + } + } + + for (k = 0; k < this.l.e(); k += 4) { + k += random.nextInt(this.l.e()); + if (k + 3 > this.l.e()) { + break; + } + + structurepiece1 = WorldGenMineshaftPieces.b(structurepiece, list, random, this.l.a - 1, this.l.b + random.nextInt(j) + 1, this.l.c + k, EnumDirection.WEST, i); + if (structurepiece1 != null) { + structureboundingbox = structurepiece1.c(); + this.a.add(new StructureBoundingBox(this.l.a, structureboundingbox.b, structureboundingbox.c, this.l.a + 1, structureboundingbox.e, structureboundingbox.f)); + } + } + + for (k = 0; k < this.l.e(); k += 4) { + k += random.nextInt(this.l.e()); + if (k + 3 > this.l.e()) { + break; + } + + structurepiece1 = WorldGenMineshaftPieces.b(structurepiece, list, random, this.l.d + 1, this.l.b + random.nextInt(j) + 1, this.l.c + k, EnumDirection.EAST, i); + if (structurepiece1 != null) { + structureboundingbox = structurepiece1.c(); + this.a.add(new StructureBoundingBox(this.l.d - 1, structureboundingbox.b, structureboundingbox.c, this.l.d, structureboundingbox.e, structureboundingbox.f)); + } + } + + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + if (this.a(world, structureboundingbox)) { + return false; + } else { + this.a(world, structureboundingbox, this.l.a, this.l.b, this.l.c, this.l.d, this.l.b, this.l.f, Blocks.DIRT.getBlockData(), Blocks.AIR.getBlockData(), true); + this.a(world, structureboundingbox, this.l.a, this.l.b + 1, this.l.c, this.l.d, Math.min(this.l.b + 3, this.l.e), this.l.f, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + + for (StructureBoundingBox structureboundingbox1 : this.a) { + this.a(world, structureboundingbox, structureboundingbox1.a, structureboundingbox1.e - 2, structureboundingbox1.c, structureboundingbox1.d, structureboundingbox1.e, structureboundingbox1.f, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + } + + this.a(world, structureboundingbox, this.l.a, this.l.b + 4, this.l.c, this.l.d, this.l.e, this.l.f, Blocks.AIR.getBlockData(), false); + return true; + } + } + + public void a(int i, int j, int k) { + super.a(i, j, k); + + for (StructureBoundingBox structureboundingbox : this.a) { + structureboundingbox.a(i, j, k); + } + + } + + protected void a(NBTTagCompound nbttagcompound) { + NBTTagList nbttaglist = new NBTTagList(); + + for (StructureBoundingBox structureboundingbox : this.a) { + nbttaglist.add(structureboundingbox.g()); + } + + nbttagcompound.set("Entrances", nbttaglist); + } + + protected void b(NBTTagCompound nbttagcompound) { + NBTTagList nbttaglist = nbttagcompound.getList("Entrances", 11); + + for (int i = 0; i < nbttaglist.size(); ++i) { + this.a.add(new StructureBoundingBox(nbttaglist.c(i))); + } + + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenMineshaftStart.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenMineshaftStart.java new file mode 100644 index 0000000..be6ae68 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenMineshaftStart.java @@ -0,0 +1,19 @@ +package net.minecraft.server; + +import java.util.Random; + +public class WorldGenMineshaftStart extends StructureStart { + + public WorldGenMineshaftStart() { + } + + public WorldGenMineshaftStart(World world, Random random, int i, int j) { + super(i, j); + WorldGenMineshaftPieces.WorldGenMineshaftRoom worldgenmineshaftpieces_worldgenmineshaftroom = new WorldGenMineshaftPieces.WorldGenMineshaftRoom(0, random, (i << 4) + 2, (j << 4) + 2); + + this.a.add(worldgenmineshaftpieces_worldgenmineshaftroom); + worldgenmineshaftpieces_worldgenmineshaftroom.a(worldgenmineshaftpieces_worldgenmineshaftroom, this.a, random); + this.c(); + this.a(world, random, 10); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenMonument.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenMonument.java new file mode 100644 index 0000000..8f92f93 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenMonument.java @@ -0,0 +1,159 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; + +import java.util.*; +import java.util.Map.Entry; + +public class WorldGenMonument extends StructureGenerator { + + private int f; + private int g; + public static final List d = Arrays.asList(BiomeBase.OCEAN, BiomeBase.DEEP_OCEAN, BiomeBase.RIVER, BiomeBase.FROZEN_OCEAN, BiomeBase.FROZEN_RIVER); + private static final List h = Lists.newArrayList(); + + public WorldGenMonument() { + this.f = 32; + this.g = 5; + } + + public WorldGenMonument(Map map) { + this(); + + for (Entry entry : map.entrySet()) { + + if (entry.getKey().equals("spacing")) { + this.f = MathHelper.a(entry.getValue(), this.f, 1); + } else if (entry.getKey().equals("separation")) { + this.g = MathHelper.a(entry.getValue(), this.g, 1); + } + } + + } + + public String a() { + return "Monument"; + } + + protected boolean a(int i, int j) { + int k = i; + int l = j; + + if (i < 0) { + i -= this.f - 1; + } + + if (j < 0) { + j -= this.f - 1; + } + + int i1 = i / this.f; + int j1 = j / this.f; + Random random = this.c.a(i1, j1, 10387313); + + i1 *= this.f; + j1 *= this.f; + i1 += (random.nextInt(this.f - this.g) + random.nextInt(this.f - this.g)) / 2; + j1 += (random.nextInt(this.f - this.g) + random.nextInt(this.f - this.g)) / 2; + if (k == i1 && l == j1) { + if (this.c.getWorldChunkManager().getBiome(k * 16 + 8, l * 16 + 8) != BiomeBase.DEEP_OCEAN) { + return false; + } + + return this.c.getWorldChunkManager().a(k * 16 + 8, l * 16 + 8, 29, WorldGenMonument.d); + } + + return false; + } + + protected StructureStart b(int i, int j) { + return new WorldGenMonumentStart(this.c, this.b, i, j); + } + + public List b() { + return WorldGenMonument.h; + } + + static { + WorldGenMonument.h.add(new BiomeBase.BiomeMeta(EntityGuardian.class, 1, 2, 4)); + } + + public static class WorldGenMonumentStart extends StructureStart { + + private final Set c = Sets.newHashSet(); + private boolean d; + + public WorldGenMonumentStart() { + } + + public WorldGenMonumentStart(World world, Random random, int i, int j) { + super(i, j); + this.b(world, random, i, j); + } + + private void b(World world, Random random, int i, int j) { + random.setSeed(world.getSeed()); + long k = random.nextLong(); + long l = random.nextLong(); + long i1 = (long) i * k; + long j1 = (long) j * l; + + random.setSeed(i1 ^ j1 ^ world.getSeed()); + int k1 = i * 16 + 8 - 29; + int l1 = j * 16 + 8 - 29; + EnumDirection enumdirection = EnumDirection.EnumDirectionLimit.HORIZONTAL.a(random); + + this.a.add(new WorldGenMonumentPieces.WorldGenMonumentPiece1(random, k1, l1, enumdirection)); + this.c(); + this.d = true; + } + + public void a(World world, Random random, StructureBoundingBox structureboundingbox) { + if (!this.d) { + this.a.clear(); + this.b(world, random, this.e(), this.f()); + } + + super.a(world, random, structureboundingbox); + } + + public boolean a(ChunkCoordIntPair chunkcoordintpair) { + return !this.c.contains(chunkcoordintpair) && super.a(chunkcoordintpair); + } + + public void b(ChunkCoordIntPair chunkcoordintpair) { + super.b(chunkcoordintpair); + this.c.add(chunkcoordintpair); + } + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + NBTTagList nbttaglist = new NBTTagList(); + + for (ChunkCoordIntPair chunkcoordintpair : this.c) { + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + + nbttagcompound1.setInt("X", chunkcoordintpair.x); + nbttagcompound1.setInt("Z", chunkcoordintpair.z); + nbttaglist.add(nbttagcompound1); + } + + nbttagcompound.set("Processed", nbttaglist); + } + + public void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + if (nbttagcompound.hasKeyOfType("Processed", 9)) { + NBTTagList nbttaglist = nbttagcompound.getList("Processed", 10); + + for (int i = 0; i < nbttaglist.size(); ++i) { + NBTTagCompound nbttagcompound1 = nbttaglist.get(i); + + this.c.add(new ChunkCoordIntPair(nbttagcompound1.getInt("X"), nbttagcompound1.getInt("Z"))); + } + } + + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenMonumentPieces.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenMonumentPieces.java new file mode 100644 index 0000000..403ea34 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenMonumentPieces.java @@ -0,0 +1,1994 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Random; + +public class WorldGenMonumentPieces { + + public static void a() { + WorldGenFactory.a(WorldGenMonumentPiece1.class, "OMB"); + WorldGenFactory.a(WorldGenMonumentPiece2.class, "OMCR"); + WorldGenFactory.a(WorldGenMonumentPiece3.class, "OMDXR"); + WorldGenFactory.a(WorldGenMonumentPiece4.class, "OMDXYR"); + WorldGenFactory.a(WorldGenMonumentPiece5.class, "OMDYR"); + WorldGenFactory.a(WorldGenMonumentPiece6.class, "OMDYZR"); + WorldGenFactory.a(WorldGenMonumentPiece7.class, "OMDZR"); + WorldGenFactory.a(WorldGenMonumentPieceEntry.class, "OMEntry"); + WorldGenFactory.a(WorldGenMonumentPiecePenthouse.class, "OMPenthouse"); + WorldGenFactory.a(WorldGenMonumentPieceSimple.class, "OMSimple"); + WorldGenFactory.a(WorldGenMonumentPieceSimpleT.class, "OMSimpleT"); + } + + static class SyntheticClass_1 { + + static final int[] a = new int[EnumDirection.values().length]; + + static { + try { + SyntheticClass_1.a[EnumDirection.NORTH.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.a[EnumDirection.SOUTH.ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.a[EnumDirection.WEST.ordinal()] = 3; + } catch (NoSuchFieldError ignored) { + } + + } + } + + static class WorldGenMonumentPieceSelector4 implements IWorldGenMonumentPieceSelector { + + private WorldGenMonumentPieceSelector4() { + } + + public boolean a(WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker) { + if (worldgenmonumentpieces_worldgenmonumentstatetracker.c[EnumDirection.NORTH.a()] && !worldgenmonumentpieces_worldgenmonumentstatetracker.b[EnumDirection.NORTH.a()].d && worldgenmonumentpieces_worldgenmonumentstatetracker.c[EnumDirection.UP.a()] && !worldgenmonumentpieces_worldgenmonumentstatetracker.b[EnumDirection.UP.a()].d) { + WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker1 = worldgenmonumentpieces_worldgenmonumentstatetracker.b[EnumDirection.NORTH.a()]; + + return worldgenmonumentpieces_worldgenmonumentstatetracker1.c[EnumDirection.UP.a()] && !worldgenmonumentpieces_worldgenmonumentstatetracker1.b[EnumDirection.UP.a()].d; + } else { + return false; + } + } + + public WorldGenMonumentPiece a(EnumDirection enumdirection, WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker, Random random) { + worldgenmonumentpieces_worldgenmonumentstatetracker.d = true; + worldgenmonumentpieces_worldgenmonumentstatetracker.b[EnumDirection.NORTH.a()].d = true; + worldgenmonumentpieces_worldgenmonumentstatetracker.b[EnumDirection.UP.a()].d = true; + worldgenmonumentpieces_worldgenmonumentstatetracker.b[EnumDirection.NORTH.a()].b[EnumDirection.UP.a()].d = true; + return new WorldGenMonumentPiece6(enumdirection, worldgenmonumentpieces_worldgenmonumentstatetracker, random); + } + + WorldGenMonumentPieceSelector4(SyntheticClass_1 worldgenmonumentpieces_syntheticclass_1) { + this(); + } + } + + static class WorldGenMonumentPieceSelector6 implements IWorldGenMonumentPieceSelector { + + private WorldGenMonumentPieceSelector6() { + } + + public boolean a(WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker) { + if (worldgenmonumentpieces_worldgenmonumentstatetracker.c[EnumDirection.EAST.a()] && !worldgenmonumentpieces_worldgenmonumentstatetracker.b[EnumDirection.EAST.a()].d && worldgenmonumentpieces_worldgenmonumentstatetracker.c[EnumDirection.UP.a()] && !worldgenmonumentpieces_worldgenmonumentstatetracker.b[EnumDirection.UP.a()].d) { + WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker1 = worldgenmonumentpieces_worldgenmonumentstatetracker.b[EnumDirection.EAST.a()]; + + return worldgenmonumentpieces_worldgenmonumentstatetracker1.c[EnumDirection.UP.a()] && !worldgenmonumentpieces_worldgenmonumentstatetracker1.b[EnumDirection.UP.a()].d; + } else { + return false; + } + } + + public WorldGenMonumentPiece a(EnumDirection enumdirection, WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker, Random random) { + worldgenmonumentpieces_worldgenmonumentstatetracker.d = true; + worldgenmonumentpieces_worldgenmonumentstatetracker.b[EnumDirection.EAST.a()].d = true; + worldgenmonumentpieces_worldgenmonumentstatetracker.b[EnumDirection.UP.a()].d = true; + worldgenmonumentpieces_worldgenmonumentstatetracker.b[EnumDirection.EAST.a()].b[EnumDirection.UP.a()].d = true; + return new WorldGenMonumentPiece4(enumdirection, worldgenmonumentpieces_worldgenmonumentstatetracker, random); + } + + WorldGenMonumentPieceSelector6(SyntheticClass_1 worldgenmonumentpieces_syntheticclass_1) { + this(); + } + } + + static class WorldGenMonumentPieceSelector3 implements IWorldGenMonumentPieceSelector { + + private WorldGenMonumentPieceSelector3() { + } + + public boolean a(WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker) { + return worldgenmonumentpieces_worldgenmonumentstatetracker.c[EnumDirection.NORTH.a()] && !worldgenmonumentpieces_worldgenmonumentstatetracker.b[EnumDirection.NORTH.a()].d; + } + + public WorldGenMonumentPiece a(EnumDirection enumdirection, WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker, Random random) { + WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker1 = worldgenmonumentpieces_worldgenmonumentstatetracker; + + if (!worldgenmonumentpieces_worldgenmonumentstatetracker.c[EnumDirection.NORTH.a()] || worldgenmonumentpieces_worldgenmonumentstatetracker.b[EnumDirection.NORTH.a()].d) { + worldgenmonumentpieces_worldgenmonumentstatetracker1 = worldgenmonumentpieces_worldgenmonumentstatetracker.b[EnumDirection.SOUTH.a()]; + } + + worldgenmonumentpieces_worldgenmonumentstatetracker1.d = true; + worldgenmonumentpieces_worldgenmonumentstatetracker1.b[EnumDirection.NORTH.a()].d = true; + return new WorldGenMonumentPiece7(enumdirection, worldgenmonumentpieces_worldgenmonumentstatetracker1, random); + } + + WorldGenMonumentPieceSelector3(SyntheticClass_1 worldgenmonumentpieces_syntheticclass_1) { + this(); + } + } + + static class WorldGenMonumentPieceSelector7 implements IWorldGenMonumentPieceSelector { + + private WorldGenMonumentPieceSelector7() { + } + + public boolean a(WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker) { + return worldgenmonumentpieces_worldgenmonumentstatetracker.c[EnumDirection.EAST.a()] && !worldgenmonumentpieces_worldgenmonumentstatetracker.b[EnumDirection.EAST.a()].d; + } + + public WorldGenMonumentPiece a(EnumDirection enumdirection, WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker, Random random) { + worldgenmonumentpieces_worldgenmonumentstatetracker.d = true; + worldgenmonumentpieces_worldgenmonumentstatetracker.b[EnumDirection.EAST.a()].d = true; + return new WorldGenMonumentPiece3(enumdirection, worldgenmonumentpieces_worldgenmonumentstatetracker, random); + } + + WorldGenMonumentPieceSelector7(SyntheticClass_1 worldgenmonumentpieces_syntheticclass_1) { + this(); + } + } + + static class WorldGenMonumentPieceSelector5 implements IWorldGenMonumentPieceSelector { + + private WorldGenMonumentPieceSelector5() { + } + + public boolean a(WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker) { + return worldgenmonumentpieces_worldgenmonumentstatetracker.c[EnumDirection.UP.a()] && !worldgenmonumentpieces_worldgenmonumentstatetracker.b[EnumDirection.UP.a()].d; + } + + public WorldGenMonumentPiece a(EnumDirection enumdirection, WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker, Random random) { + worldgenmonumentpieces_worldgenmonumentstatetracker.d = true; + worldgenmonumentpieces_worldgenmonumentstatetracker.b[EnumDirection.UP.a()].d = true; + return new WorldGenMonumentPiece5(enumdirection, worldgenmonumentpieces_worldgenmonumentstatetracker, random); + } + + WorldGenMonumentPieceSelector5(SyntheticClass_1 worldgenmonumentpieces_syntheticclass_1) { + this(); + } + } + + static class WorldGenMonumentPieceSelector1 implements IWorldGenMonumentPieceSelector { + + private WorldGenMonumentPieceSelector1() { + } + + public boolean a(WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker) { + return !worldgenmonumentpieces_worldgenmonumentstatetracker.c[EnumDirection.WEST.a()] && !worldgenmonumentpieces_worldgenmonumentstatetracker.c[EnumDirection.EAST.a()] && !worldgenmonumentpieces_worldgenmonumentstatetracker.c[EnumDirection.NORTH.a()] && !worldgenmonumentpieces_worldgenmonumentstatetracker.c[EnumDirection.SOUTH.a()] && !worldgenmonumentpieces_worldgenmonumentstatetracker.c[EnumDirection.UP.a()]; + } + + public WorldGenMonumentPiece a(EnumDirection enumdirection, WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker, Random random) { + worldgenmonumentpieces_worldgenmonumentstatetracker.d = true; + return new WorldGenMonumentPieceSimpleT(enumdirection, worldgenmonumentpieces_worldgenmonumentstatetracker, random); + } + + WorldGenMonumentPieceSelector1(SyntheticClass_1 worldgenmonumentpieces_syntheticclass_1) { + this(); + } + } + + static class WorldGenMonumentPieceSelector2 implements IWorldGenMonumentPieceSelector { + + private WorldGenMonumentPieceSelector2() { + } + + public boolean a(WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker) { + return true; + } + + public WorldGenMonumentPiece a(EnumDirection enumdirection, WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker, Random random) { + worldgenmonumentpieces_worldgenmonumentstatetracker.d = true; + return new WorldGenMonumentPieceSimple(enumdirection, worldgenmonumentpieces_worldgenmonumentstatetracker, random); + } + + WorldGenMonumentPieceSelector2(SyntheticClass_1 worldgenmonumentpieces_syntheticclass_1) { + this(); + } + } + + interface IWorldGenMonumentPieceSelector { + + boolean a(WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker); + + WorldGenMonumentPiece a(EnumDirection enumdirection, WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker, Random random); + } + + static class WorldGenMonumentStateTracker { + + int a; + WorldGenMonumentStateTracker[] b = new WorldGenMonumentStateTracker[6]; + boolean[] c = new boolean[6]; + boolean d; + boolean e; + int f; + + public WorldGenMonumentStateTracker(int i) { + this.a = i; + } + + public void a(EnumDirection enumdirection, WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker) { + this.b[enumdirection.a()] = worldgenmonumentpieces_worldgenmonumentstatetracker; + worldgenmonumentpieces_worldgenmonumentstatetracker.b[enumdirection.opposite().a()] = this; + } + + public void a() { + for (int i = 0; i < 6; ++i) { + this.c[i] = this.b[i] != null; + } + + } + + public boolean a(int i) { + if (this.e) { + return true; + } else { + this.f = i; + + for (int j = 0; j < 6; ++j) { + if (this.b[j] != null && this.c[j] && this.b[j].f != i && this.b[j].a(i)) { + return true; + } + } + + return false; + } + } + + public boolean b() { + return this.a >= 75; + } + + public int c() { + int i = 0; + + for (int j = 0; j < 6; ++j) { + if (this.c[j]) { + ++i; + } + } + + return i; + } + } + + public static class WorldGenMonumentPiecePenthouse extends WorldGenMonumentPiece { + + public WorldGenMonumentPiecePenthouse() { + } + + public WorldGenMonumentPiecePenthouse(EnumDirection enumdirection, StructureBoundingBox structureboundingbox) { + super(enumdirection, structureboundingbox); + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + this.a(world, structureboundingbox, 2, -1, 2, 11, -1, 11, WorldGenMonumentPiecePenthouse.b, WorldGenMonumentPiecePenthouse.b, false); + this.a(world, structureboundingbox, 0, -1, 0, 1, -1, 11, WorldGenMonumentPiecePenthouse.a, WorldGenMonumentPiecePenthouse.a, false); + this.a(world, structureboundingbox, 12, -1, 0, 13, -1, 11, WorldGenMonumentPiecePenthouse.a, WorldGenMonumentPiecePenthouse.a, false); + this.a(world, structureboundingbox, 2, -1, 0, 11, -1, 1, WorldGenMonumentPiecePenthouse.a, WorldGenMonumentPiecePenthouse.a, false); + this.a(world, structureboundingbox, 2, -1, 12, 11, -1, 13, WorldGenMonumentPiecePenthouse.a, WorldGenMonumentPiecePenthouse.a, false); + this.a(world, structureboundingbox, 0, 0, 0, 0, 0, 13, WorldGenMonumentPiecePenthouse.b, WorldGenMonumentPiecePenthouse.b, false); + this.a(world, structureboundingbox, 13, 0, 0, 13, 0, 13, WorldGenMonumentPiecePenthouse.b, WorldGenMonumentPiecePenthouse.b, false); + this.a(world, structureboundingbox, 1, 0, 0, 12, 0, 0, WorldGenMonumentPiecePenthouse.b, WorldGenMonumentPiecePenthouse.b, false); + this.a(world, structureboundingbox, 1, 0, 13, 12, 0, 13, WorldGenMonumentPiecePenthouse.b, WorldGenMonumentPiecePenthouse.b, false); + + for (int i = 2; i <= 11; i += 3) { + this.a(world, WorldGenMonumentPiecePenthouse.e, 0, 0, i, structureboundingbox); + this.a(world, WorldGenMonumentPiecePenthouse.e, 13, 0, i, structureboundingbox); + this.a(world, WorldGenMonumentPiecePenthouse.e, i, 0, 0, structureboundingbox); + } + + this.a(world, structureboundingbox, 2, 0, 3, 4, 0, 9, WorldGenMonumentPiecePenthouse.b, WorldGenMonumentPiecePenthouse.b, false); + this.a(world, structureboundingbox, 9, 0, 3, 11, 0, 9, WorldGenMonumentPiecePenthouse.b, WorldGenMonumentPiecePenthouse.b, false); + this.a(world, structureboundingbox, 4, 0, 9, 9, 0, 11, WorldGenMonumentPiecePenthouse.b, WorldGenMonumentPiecePenthouse.b, false); + this.a(world, WorldGenMonumentPiecePenthouse.b, 5, 0, 8, structureboundingbox); + this.a(world, WorldGenMonumentPiecePenthouse.b, 8, 0, 8, structureboundingbox); + this.a(world, WorldGenMonumentPiecePenthouse.b, 10, 0, 10, structureboundingbox); + this.a(world, WorldGenMonumentPiecePenthouse.b, 3, 0, 10, structureboundingbox); + this.a(world, structureboundingbox, 3, 0, 3, 3, 0, 7, WorldGenMonumentPiecePenthouse.c, WorldGenMonumentPiecePenthouse.c, false); + this.a(world, structureboundingbox, 10, 0, 3, 10, 0, 7, WorldGenMonumentPiecePenthouse.c, WorldGenMonumentPiecePenthouse.c, false); + this.a(world, structureboundingbox, 6, 0, 10, 7, 0, 10, WorldGenMonumentPiecePenthouse.c, WorldGenMonumentPiecePenthouse.c, false); + byte b0 = 3; + + for (int j = 0; j < 2; ++j) { + for (int k = 2; k <= 8; k += 3) { + this.a(world, structureboundingbox, b0, 0, k, b0, 2, k, WorldGenMonumentPiecePenthouse.b, WorldGenMonumentPiecePenthouse.b, false); + } + + b0 = 10; + } + + this.a(world, structureboundingbox, 5, 0, 10, 5, 2, 10, WorldGenMonumentPiecePenthouse.b, WorldGenMonumentPiecePenthouse.b, false); + this.a(world, structureboundingbox, 8, 0, 10, 8, 2, 10, WorldGenMonumentPiecePenthouse.b, WorldGenMonumentPiecePenthouse.b, false); + this.a(world, structureboundingbox, 6, -1, 7, 7, -1, 8, WorldGenMonumentPiecePenthouse.c, WorldGenMonumentPiecePenthouse.c, false); + this.a(world, structureboundingbox, 6, -1, 3, 7, -1, 4, false); + this.a(world, structureboundingbox, 6, 1, 6); + return true; + } + } + + public static class WorldGenMonumentPiece8 extends WorldGenMonumentPiece { + + private int o; + + public WorldGenMonumentPiece8() { + } + + public WorldGenMonumentPiece8(EnumDirection enumdirection, StructureBoundingBox structureboundingbox, int i) { + super(enumdirection, structureboundingbox); + this.o = i & 1; + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + if (this.o == 0) { + int i; + + for (i = 0; i < 4; ++i) { + this.a(world, structureboundingbox, 10 - i, 3 - i, 20 - i, 12 + i, 3 - i, 20, WorldGenMonumentPiece8.b, WorldGenMonumentPiece8.b, false); + } + + this.a(world, structureboundingbox, 7, 0, 6, 15, 0, 16, WorldGenMonumentPiece8.b, WorldGenMonumentPiece8.b, false); + this.a(world, structureboundingbox, 6, 0, 6, 6, 3, 20, WorldGenMonumentPiece8.b, WorldGenMonumentPiece8.b, false); + this.a(world, structureboundingbox, 16, 0, 6, 16, 3, 20, WorldGenMonumentPiece8.b, WorldGenMonumentPiece8.b, false); + this.a(world, structureboundingbox, 7, 1, 7, 7, 1, 20, WorldGenMonumentPiece8.b, WorldGenMonumentPiece8.b, false); + this.a(world, structureboundingbox, 15, 1, 7, 15, 1, 20, WorldGenMonumentPiece8.b, WorldGenMonumentPiece8.b, false); + this.a(world, structureboundingbox, 7, 1, 6, 9, 3, 6, WorldGenMonumentPiece8.b, WorldGenMonumentPiece8.b, false); + this.a(world, structureboundingbox, 13, 1, 6, 15, 3, 6, WorldGenMonumentPiece8.b, WorldGenMonumentPiece8.b, false); + this.a(world, structureboundingbox, 8, 1, 7, 9, 1, 7, WorldGenMonumentPiece8.b, WorldGenMonumentPiece8.b, false); + this.a(world, structureboundingbox, 13, 1, 7, 14, 1, 7, WorldGenMonumentPiece8.b, WorldGenMonumentPiece8.b, false); + this.a(world, structureboundingbox, 9, 0, 5, 13, 0, 5, WorldGenMonumentPiece8.b, WorldGenMonumentPiece8.b, false); + this.a(world, structureboundingbox, 10, 0, 7, 12, 0, 7, WorldGenMonumentPiece8.c, WorldGenMonumentPiece8.c, false); + this.a(world, structureboundingbox, 8, 0, 10, 8, 0, 12, WorldGenMonumentPiece8.c, WorldGenMonumentPiece8.c, false); + this.a(world, structureboundingbox, 14, 0, 10, 14, 0, 12, WorldGenMonumentPiece8.c, WorldGenMonumentPiece8.c, false); + + for (i = 18; i >= 7; i -= 3) { + this.a(world, WorldGenMonumentPiece8.e, 6, 3, i, structureboundingbox); + this.a(world, WorldGenMonumentPiece8.e, 16, 3, i, structureboundingbox); + } + + this.a(world, WorldGenMonumentPiece8.e, 10, 0, 10, structureboundingbox); + this.a(world, WorldGenMonumentPiece8.e, 12, 0, 10, structureboundingbox); + this.a(world, WorldGenMonumentPiece8.e, 10, 0, 12, structureboundingbox); + this.a(world, WorldGenMonumentPiece8.e, 12, 0, 12, structureboundingbox); + this.a(world, WorldGenMonumentPiece8.e, 8, 3, 6, structureboundingbox); + this.a(world, WorldGenMonumentPiece8.e, 14, 3, 6, structureboundingbox); + this.a(world, WorldGenMonumentPiece8.b, 4, 2, 4, structureboundingbox); + this.a(world, WorldGenMonumentPiece8.e, 4, 1, 4, structureboundingbox); + this.a(world, WorldGenMonumentPiece8.b, 4, 0, 4, structureboundingbox); + this.a(world, WorldGenMonumentPiece8.b, 18, 2, 4, structureboundingbox); + this.a(world, WorldGenMonumentPiece8.e, 18, 1, 4, structureboundingbox); + this.a(world, WorldGenMonumentPiece8.b, 18, 0, 4, structureboundingbox); + this.a(world, WorldGenMonumentPiece8.b, 4, 2, 18, structureboundingbox); + this.a(world, WorldGenMonumentPiece8.e, 4, 1, 18, structureboundingbox); + this.a(world, WorldGenMonumentPiece8.b, 4, 0, 18, structureboundingbox); + this.a(world, WorldGenMonumentPiece8.b, 18, 2, 18, structureboundingbox); + this.a(world, WorldGenMonumentPiece8.e, 18, 1, 18, structureboundingbox); + this.a(world, WorldGenMonumentPiece8.b, 18, 0, 18, structureboundingbox); + this.a(world, WorldGenMonumentPiece8.b, 9, 7, 20, structureboundingbox); + this.a(world, WorldGenMonumentPiece8.b, 13, 7, 20, structureboundingbox); + this.a(world, structureboundingbox, 6, 0, 21, 7, 4, 21, WorldGenMonumentPiece8.b, WorldGenMonumentPiece8.b, false); + this.a(world, structureboundingbox, 15, 0, 21, 16, 4, 21, WorldGenMonumentPiece8.b, WorldGenMonumentPiece8.b, false); + this.a(world, structureboundingbox, 11, 2, 16); + } else if (this.o == 1) { + this.a(world, structureboundingbox, 9, 3, 18, 13, 3, 20, WorldGenMonumentPiece8.b, WorldGenMonumentPiece8.b, false); + this.a(world, structureboundingbox, 9, 0, 18, 9, 2, 18, WorldGenMonumentPiece8.b, WorldGenMonumentPiece8.b, false); + this.a(world, structureboundingbox, 13, 0, 18, 13, 2, 18, WorldGenMonumentPiece8.b, WorldGenMonumentPiece8.b, false); + byte b0 = 9; + byte b1 = 20; + byte b2 = 5; + + int j; + + for (j = 0; j < 2; ++j) { + this.a(world, WorldGenMonumentPiece8.b, b0, b2 + 1, b1, structureboundingbox); + this.a(world, WorldGenMonumentPiece8.e, b0, b2, b1, structureboundingbox); + this.a(world, WorldGenMonumentPiece8.b, b0, b2 - 1, b1, structureboundingbox); + b0 = 13; + } + + this.a(world, structureboundingbox, 7, 3, 7, 15, 3, 14, WorldGenMonumentPiece8.b, WorldGenMonumentPiece8.b, false); + b0 = 10; + + for (j = 0; j < 2; ++j) { + this.a(world, structureboundingbox, b0, 0, 10, b0, 6, 10, WorldGenMonumentPiece8.b, WorldGenMonumentPiece8.b, false); + this.a(world, structureboundingbox, b0, 0, 12, b0, 6, 12, WorldGenMonumentPiece8.b, WorldGenMonumentPiece8.b, false); + this.a(world, WorldGenMonumentPiece8.e, b0, 0, 10, structureboundingbox); + this.a(world, WorldGenMonumentPiece8.e, b0, 0, 12, structureboundingbox); + this.a(world, WorldGenMonumentPiece8.e, b0, 4, 10, structureboundingbox); + this.a(world, WorldGenMonumentPiece8.e, b0, 4, 12, structureboundingbox); + b0 = 12; + } + + b0 = 8; + + for (j = 0; j < 2; ++j) { + this.a(world, structureboundingbox, b0, 0, 7, b0, 2, 7, WorldGenMonumentPiece8.b, WorldGenMonumentPiece8.b, false); + this.a(world, structureboundingbox, b0, 0, 14, b0, 2, 14, WorldGenMonumentPiece8.b, WorldGenMonumentPiece8.b, false); + b0 = 14; + } + + this.a(world, structureboundingbox, 8, 3, 8, 8, 3, 13, WorldGenMonumentPiece8.c, WorldGenMonumentPiece8.c, false); + this.a(world, structureboundingbox, 14, 3, 8, 14, 3, 13, WorldGenMonumentPiece8.c, WorldGenMonumentPiece8.c, false); + this.a(world, structureboundingbox, 11, 5, 13); + } + + return true; + } + } + + public static class WorldGenMonumentPiece2 extends WorldGenMonumentPiece { + + public WorldGenMonumentPiece2() { + } + + public WorldGenMonumentPiece2(EnumDirection enumdirection, WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker, Random random) { + super(1, enumdirection, worldgenmonumentpieces_worldgenmonumentstatetracker, 2, 2, 2); + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + this.a(world, structureboundingbox, 1, 8, 0, 14, 8, 14, WorldGenMonumentPiece2.a); + byte b0 = 7; + IBlockData iblockdata = WorldGenMonumentPiece2.b; + + this.a(world, structureboundingbox, 0, b0, 0, 0, b0, 15, iblockdata, iblockdata, false); + this.a(world, structureboundingbox, 15, b0, 0, 15, b0, 15, iblockdata, iblockdata, false); + this.a(world, structureboundingbox, 1, b0, 0, 15, b0, 0, iblockdata, iblockdata, false); + this.a(world, structureboundingbox, 1, b0, 15, 14, b0, 15, iblockdata, iblockdata, false); + + int i; + + for (i = 1; i <= 6; ++i) { + iblockdata = WorldGenMonumentPiece2.b; + if (i == 2 || i == 6) { + iblockdata = WorldGenMonumentPiece2.a; + } + + for (int j = 0; j <= 15; j += 15) { + this.a(world, structureboundingbox, j, i, 0, j, i, 1, iblockdata, iblockdata, false); + this.a(world, structureboundingbox, j, i, 6, j, i, 9, iblockdata, iblockdata, false); + this.a(world, structureboundingbox, j, i, 14, j, i, 15, iblockdata, iblockdata, false); + } + + this.a(world, structureboundingbox, 1, i, 0, 1, i, 0, iblockdata, iblockdata, false); + this.a(world, structureboundingbox, 6, i, 0, 9, i, 0, iblockdata, iblockdata, false); + this.a(world, structureboundingbox, 14, i, 0, 14, i, 0, iblockdata, iblockdata, false); + this.a(world, structureboundingbox, 1, i, 15, 14, i, 15, iblockdata, iblockdata, false); + } + + this.a(world, structureboundingbox, 6, 3, 6, 9, 6, 9, WorldGenMonumentPiece2.c, WorldGenMonumentPiece2.c, false); + this.a(world, structureboundingbox, 7, 4, 7, 8, 5, 8, Blocks.GOLD_BLOCK.getBlockData(), Blocks.GOLD_BLOCK.getBlockData(), false); + + for (i = 3; i <= 6; i += 3) { + for (int k = 6; k <= 9; k += 3) { + this.a(world, WorldGenMonumentPiece2.e, k, i, 6, structureboundingbox); + this.a(world, WorldGenMonumentPiece2.e, k, i, 9, structureboundingbox); + } + } + + this.a(world, structureboundingbox, 5, 1, 6, 5, 2, 6, WorldGenMonumentPiece2.b, WorldGenMonumentPiece2.b, false); + this.a(world, structureboundingbox, 5, 1, 9, 5, 2, 9, WorldGenMonumentPiece2.b, WorldGenMonumentPiece2.b, false); + this.a(world, structureboundingbox, 10, 1, 6, 10, 2, 6, WorldGenMonumentPiece2.b, WorldGenMonumentPiece2.b, false); + this.a(world, structureboundingbox, 10, 1, 9, 10, 2, 9, WorldGenMonumentPiece2.b, WorldGenMonumentPiece2.b, false); + this.a(world, structureboundingbox, 6, 1, 5, 6, 2, 5, WorldGenMonumentPiece2.b, WorldGenMonumentPiece2.b, false); + this.a(world, structureboundingbox, 9, 1, 5, 9, 2, 5, WorldGenMonumentPiece2.b, WorldGenMonumentPiece2.b, false); + this.a(world, structureboundingbox, 6, 1, 10, 6, 2, 10, WorldGenMonumentPiece2.b, WorldGenMonumentPiece2.b, false); + this.a(world, structureboundingbox, 9, 1, 10, 9, 2, 10, WorldGenMonumentPiece2.b, WorldGenMonumentPiece2.b, false); + this.a(world, structureboundingbox, 5, 2, 5, 5, 6, 5, WorldGenMonumentPiece2.b, WorldGenMonumentPiece2.b, false); + this.a(world, structureboundingbox, 5, 2, 10, 5, 6, 10, WorldGenMonumentPiece2.b, WorldGenMonumentPiece2.b, false); + this.a(world, structureboundingbox, 10, 2, 5, 10, 6, 5, WorldGenMonumentPiece2.b, WorldGenMonumentPiece2.b, false); + this.a(world, structureboundingbox, 10, 2, 10, 10, 6, 10, WorldGenMonumentPiece2.b, WorldGenMonumentPiece2.b, false); + this.a(world, structureboundingbox, 5, 7, 1, 5, 7, 6, WorldGenMonumentPiece2.b, WorldGenMonumentPiece2.b, false); + this.a(world, structureboundingbox, 10, 7, 1, 10, 7, 6, WorldGenMonumentPiece2.b, WorldGenMonumentPiece2.b, false); + this.a(world, structureboundingbox, 5, 7, 9, 5, 7, 14, WorldGenMonumentPiece2.b, WorldGenMonumentPiece2.b, false); + this.a(world, structureboundingbox, 10, 7, 9, 10, 7, 14, WorldGenMonumentPiece2.b, WorldGenMonumentPiece2.b, false); + this.a(world, structureboundingbox, 1, 7, 5, 6, 7, 5, WorldGenMonumentPiece2.b, WorldGenMonumentPiece2.b, false); + this.a(world, structureboundingbox, 1, 7, 10, 6, 7, 10, WorldGenMonumentPiece2.b, WorldGenMonumentPiece2.b, false); + this.a(world, structureboundingbox, 9, 7, 5, 14, 7, 5, WorldGenMonumentPiece2.b, WorldGenMonumentPiece2.b, false); + this.a(world, structureboundingbox, 9, 7, 10, 14, 7, 10, WorldGenMonumentPiece2.b, WorldGenMonumentPiece2.b, false); + this.a(world, structureboundingbox, 2, 1, 2, 2, 1, 3, WorldGenMonumentPiece2.b, WorldGenMonumentPiece2.b, false); + this.a(world, structureboundingbox, 3, 1, 2, 3, 1, 2, WorldGenMonumentPiece2.b, WorldGenMonumentPiece2.b, false); + this.a(world, structureboundingbox, 13, 1, 2, 13, 1, 3, WorldGenMonumentPiece2.b, WorldGenMonumentPiece2.b, false); + this.a(world, structureboundingbox, 12, 1, 2, 12, 1, 2, WorldGenMonumentPiece2.b, WorldGenMonumentPiece2.b, false); + this.a(world, structureboundingbox, 2, 1, 12, 2, 1, 13, WorldGenMonumentPiece2.b, WorldGenMonumentPiece2.b, false); + this.a(world, structureboundingbox, 3, 1, 13, 3, 1, 13, WorldGenMonumentPiece2.b, WorldGenMonumentPiece2.b, false); + this.a(world, structureboundingbox, 13, 1, 12, 13, 1, 13, WorldGenMonumentPiece2.b, WorldGenMonumentPiece2.b, false); + this.a(world, structureboundingbox, 12, 1, 13, 12, 1, 13, WorldGenMonumentPiece2.b, WorldGenMonumentPiece2.b, false); + return true; + } + } + + public static class WorldGenMonumentPiece6 extends WorldGenMonumentPiece { + + public WorldGenMonumentPiece6() { + } + + public WorldGenMonumentPiece6(EnumDirection enumdirection, WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker, Random random) { + super(1, enumdirection, worldgenmonumentpieces_worldgenmonumentstatetracker, 1, 2, 2); + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker = this.k.b[EnumDirection.NORTH.a()]; + WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker1 = this.k; + WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker2 = worldgenmonumentpieces_worldgenmonumentstatetracker.b[EnumDirection.UP.a()]; + WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker3 = worldgenmonumentpieces_worldgenmonumentstatetracker1.b[EnumDirection.UP.a()]; + + if (this.k.a / 25 > 0) { + this.a(world, structureboundingbox, 0, 8, worldgenmonumentpieces_worldgenmonumentstatetracker.c[EnumDirection.DOWN.a()]); + this.a(world, structureboundingbox, 0, 0, worldgenmonumentpieces_worldgenmonumentstatetracker1.c[EnumDirection.DOWN.a()]); + } + + if (worldgenmonumentpieces_worldgenmonumentstatetracker3.b[EnumDirection.UP.a()] == null) { + this.a(world, structureboundingbox, 1, 8, 1, 6, 8, 7, WorldGenMonumentPiece6.a); + } + + if (worldgenmonumentpieces_worldgenmonumentstatetracker2.b[EnumDirection.UP.a()] == null) { + this.a(world, structureboundingbox, 1, 8, 8, 6, 8, 14, WorldGenMonumentPiece6.a); + } + + int i; + IBlockData iblockdata; + + for (i = 1; i <= 7; ++i) { + iblockdata = WorldGenMonumentPiece6.b; + if (i == 2 || i == 6) { + iblockdata = WorldGenMonumentPiece6.a; + } + + this.a(world, structureboundingbox, 0, i, 0, 0, i, 15, iblockdata, iblockdata, false); + this.a(world, structureboundingbox, 7, i, 0, 7, i, 15, iblockdata, iblockdata, false); + this.a(world, structureboundingbox, 1, i, 0, 6, i, 0, iblockdata, iblockdata, false); + this.a(world, structureboundingbox, 1, i, 15, 6, i, 15, iblockdata, iblockdata, false); + } + + for (i = 1; i <= 7; ++i) { + iblockdata = WorldGenMonumentPiece6.c; + if (i == 2 || i == 6) { + iblockdata = WorldGenMonumentPiece6.e; + } + + this.a(world, structureboundingbox, 3, i, 7, 4, i, 8, iblockdata, iblockdata, false); + } + + if (worldgenmonumentpieces_worldgenmonumentstatetracker1.c[EnumDirection.SOUTH.a()]) { + this.a(world, structureboundingbox, 3, 1, 0, 4, 2, 0, false); + } + + if (worldgenmonumentpieces_worldgenmonumentstatetracker1.c[EnumDirection.EAST.a()]) { + this.a(world, structureboundingbox, 7, 1, 3, 7, 2, 4, false); + } + + if (worldgenmonumentpieces_worldgenmonumentstatetracker1.c[EnumDirection.WEST.a()]) { + this.a(world, structureboundingbox, 0, 1, 3, 0, 2, 4, false); + } + + if (worldgenmonumentpieces_worldgenmonumentstatetracker.c[EnumDirection.NORTH.a()]) { + this.a(world, structureboundingbox, 3, 1, 15, 4, 2, 15, false); + } + + if (worldgenmonumentpieces_worldgenmonumentstatetracker.c[EnumDirection.WEST.a()]) { + this.a(world, structureboundingbox, 0, 1, 11, 0, 2, 12, false); + } + + if (worldgenmonumentpieces_worldgenmonumentstatetracker.c[EnumDirection.EAST.a()]) { + this.a(world, structureboundingbox, 7, 1, 11, 7, 2, 12, false); + } + + if (worldgenmonumentpieces_worldgenmonumentstatetracker3.c[EnumDirection.SOUTH.a()]) { + this.a(world, structureboundingbox, 3, 5, 0, 4, 6, 0, false); + } + + if (worldgenmonumentpieces_worldgenmonumentstatetracker3.c[EnumDirection.EAST.a()]) { + this.a(world, structureboundingbox, 7, 5, 3, 7, 6, 4, false); + this.a(world, structureboundingbox, 5, 4, 2, 6, 4, 5, WorldGenMonumentPiece6.b, WorldGenMonumentPiece6.b, false); + this.a(world, structureboundingbox, 6, 1, 2, 6, 3, 2, WorldGenMonumentPiece6.b, WorldGenMonumentPiece6.b, false); + this.a(world, structureboundingbox, 6, 1, 5, 6, 3, 5, WorldGenMonumentPiece6.b, WorldGenMonumentPiece6.b, false); + } + + if (worldgenmonumentpieces_worldgenmonumentstatetracker3.c[EnumDirection.WEST.a()]) { + this.a(world, structureboundingbox, 0, 5, 3, 0, 6, 4, false); + this.a(world, structureboundingbox, 1, 4, 2, 2, 4, 5, WorldGenMonumentPiece6.b, WorldGenMonumentPiece6.b, false); + this.a(world, structureboundingbox, 1, 1, 2, 1, 3, 2, WorldGenMonumentPiece6.b, WorldGenMonumentPiece6.b, false); + this.a(world, structureboundingbox, 1, 1, 5, 1, 3, 5, WorldGenMonumentPiece6.b, WorldGenMonumentPiece6.b, false); + } + + if (worldgenmonumentpieces_worldgenmonumentstatetracker2.c[EnumDirection.NORTH.a()]) { + this.a(world, structureboundingbox, 3, 5, 15, 4, 6, 15, false); + } + + if (worldgenmonumentpieces_worldgenmonumentstatetracker2.c[EnumDirection.WEST.a()]) { + this.a(world, structureboundingbox, 0, 5, 11, 0, 6, 12, false); + this.a(world, structureboundingbox, 1, 4, 10, 2, 4, 13, WorldGenMonumentPiece6.b, WorldGenMonumentPiece6.b, false); + this.a(world, structureboundingbox, 1, 1, 10, 1, 3, 10, WorldGenMonumentPiece6.b, WorldGenMonumentPiece6.b, false); + this.a(world, structureboundingbox, 1, 1, 13, 1, 3, 13, WorldGenMonumentPiece6.b, WorldGenMonumentPiece6.b, false); + } + + if (worldgenmonumentpieces_worldgenmonumentstatetracker2.c[EnumDirection.EAST.a()]) { + this.a(world, structureboundingbox, 7, 5, 11, 7, 6, 12, false); + this.a(world, structureboundingbox, 5, 4, 10, 6, 4, 13, WorldGenMonumentPiece6.b, WorldGenMonumentPiece6.b, false); + this.a(world, structureboundingbox, 6, 1, 10, 6, 3, 10, WorldGenMonumentPiece6.b, WorldGenMonumentPiece6.b, false); + this.a(world, structureboundingbox, 6, 1, 13, 6, 3, 13, WorldGenMonumentPiece6.b, WorldGenMonumentPiece6.b, false); + } + + return true; + } + } + + public static class WorldGenMonumentPiece4 extends WorldGenMonumentPiece { + + public WorldGenMonumentPiece4() { + } + + public WorldGenMonumentPiece4(EnumDirection enumdirection, WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker, Random random) { + super(1, enumdirection, worldgenmonumentpieces_worldgenmonumentstatetracker, 2, 2, 1); + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker = this.k.b[EnumDirection.EAST.a()]; + WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker1 = this.k; + WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker2 = worldgenmonumentpieces_worldgenmonumentstatetracker1.b[EnumDirection.UP.a()]; + WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker3 = worldgenmonumentpieces_worldgenmonumentstatetracker.b[EnumDirection.UP.a()]; + + if (this.k.a / 25 > 0) { + this.a(world, structureboundingbox, 8, 0, worldgenmonumentpieces_worldgenmonumentstatetracker.c[EnumDirection.DOWN.a()]); + this.a(world, structureboundingbox, 0, 0, worldgenmonumentpieces_worldgenmonumentstatetracker1.c[EnumDirection.DOWN.a()]); + } + + if (worldgenmonumentpieces_worldgenmonumentstatetracker2.b[EnumDirection.UP.a()] == null) { + this.a(world, structureboundingbox, 1, 8, 1, 7, 8, 6, WorldGenMonumentPiece4.a); + } + + if (worldgenmonumentpieces_worldgenmonumentstatetracker3.b[EnumDirection.UP.a()] == null) { + this.a(world, structureboundingbox, 8, 8, 1, 14, 8, 6, WorldGenMonumentPiece4.a); + } + + for (int i = 1; i <= 7; ++i) { + IBlockData iblockdata = WorldGenMonumentPiece4.b; + + if (i == 2 || i == 6) { + iblockdata = WorldGenMonumentPiece4.a; + } + + this.a(world, structureboundingbox, 0, i, 0, 0, i, 7, iblockdata, iblockdata, false); + this.a(world, structureboundingbox, 15, i, 0, 15, i, 7, iblockdata, iblockdata, false); + this.a(world, structureboundingbox, 1, i, 0, 15, i, 0, iblockdata, iblockdata, false); + this.a(world, structureboundingbox, 1, i, 7, 14, i, 7, iblockdata, iblockdata, false); + } + + this.a(world, structureboundingbox, 2, 1, 3, 2, 7, 4, WorldGenMonumentPiece4.b, WorldGenMonumentPiece4.b, false); + this.a(world, structureboundingbox, 3, 1, 2, 4, 7, 2, WorldGenMonumentPiece4.b, WorldGenMonumentPiece4.b, false); + this.a(world, structureboundingbox, 3, 1, 5, 4, 7, 5, WorldGenMonumentPiece4.b, WorldGenMonumentPiece4.b, false); + this.a(world, structureboundingbox, 13, 1, 3, 13, 7, 4, WorldGenMonumentPiece4.b, WorldGenMonumentPiece4.b, false); + this.a(world, structureboundingbox, 11, 1, 2, 12, 7, 2, WorldGenMonumentPiece4.b, WorldGenMonumentPiece4.b, false); + this.a(world, structureboundingbox, 11, 1, 5, 12, 7, 5, WorldGenMonumentPiece4.b, WorldGenMonumentPiece4.b, false); + this.a(world, structureboundingbox, 5, 1, 3, 5, 3, 4, WorldGenMonumentPiece4.b, WorldGenMonumentPiece4.b, false); + this.a(world, structureboundingbox, 10, 1, 3, 10, 3, 4, WorldGenMonumentPiece4.b, WorldGenMonumentPiece4.b, false); + this.a(world, structureboundingbox, 5, 7, 2, 10, 7, 5, WorldGenMonumentPiece4.b, WorldGenMonumentPiece4.b, false); + this.a(world, structureboundingbox, 5, 5, 2, 5, 7, 2, WorldGenMonumentPiece4.b, WorldGenMonumentPiece4.b, false); + this.a(world, structureboundingbox, 10, 5, 2, 10, 7, 2, WorldGenMonumentPiece4.b, WorldGenMonumentPiece4.b, false); + this.a(world, structureboundingbox, 5, 5, 5, 5, 7, 5, WorldGenMonumentPiece4.b, WorldGenMonumentPiece4.b, false); + this.a(world, structureboundingbox, 10, 5, 5, 10, 7, 5, WorldGenMonumentPiece4.b, WorldGenMonumentPiece4.b, false); + this.a(world, WorldGenMonumentPiece4.b, 6, 6, 2, structureboundingbox); + this.a(world, WorldGenMonumentPiece4.b, 9, 6, 2, structureboundingbox); + this.a(world, WorldGenMonumentPiece4.b, 6, 6, 5, structureboundingbox); + this.a(world, WorldGenMonumentPiece4.b, 9, 6, 5, structureboundingbox); + this.a(world, structureboundingbox, 5, 4, 3, 6, 4, 4, WorldGenMonumentPiece4.b, WorldGenMonumentPiece4.b, false); + this.a(world, structureboundingbox, 9, 4, 3, 10, 4, 4, WorldGenMonumentPiece4.b, WorldGenMonumentPiece4.b, false); + this.a(world, WorldGenMonumentPiece4.e, 5, 4, 2, structureboundingbox); + this.a(world, WorldGenMonumentPiece4.e, 5, 4, 5, structureboundingbox); + this.a(world, WorldGenMonumentPiece4.e, 10, 4, 2, structureboundingbox); + this.a(world, WorldGenMonumentPiece4.e, 10, 4, 5, structureboundingbox); + if (worldgenmonumentpieces_worldgenmonumentstatetracker1.c[EnumDirection.SOUTH.a()]) { + this.a(world, structureboundingbox, 3, 1, 0, 4, 2, 0, false); + } + + if (worldgenmonumentpieces_worldgenmonumentstatetracker1.c[EnumDirection.NORTH.a()]) { + this.a(world, structureboundingbox, 3, 1, 7, 4, 2, 7, false); + } + + if (worldgenmonumentpieces_worldgenmonumentstatetracker1.c[EnumDirection.WEST.a()]) { + this.a(world, structureboundingbox, 0, 1, 3, 0, 2, 4, false); + } + + if (worldgenmonumentpieces_worldgenmonumentstatetracker.c[EnumDirection.SOUTH.a()]) { + this.a(world, structureboundingbox, 11, 1, 0, 12, 2, 0, false); + } + + if (worldgenmonumentpieces_worldgenmonumentstatetracker.c[EnumDirection.NORTH.a()]) { + this.a(world, structureboundingbox, 11, 1, 7, 12, 2, 7, false); + } + + if (worldgenmonumentpieces_worldgenmonumentstatetracker.c[EnumDirection.EAST.a()]) { + this.a(world, structureboundingbox, 15, 1, 3, 15, 2, 4, false); + } + + if (worldgenmonumentpieces_worldgenmonumentstatetracker2.c[EnumDirection.SOUTH.a()]) { + this.a(world, structureboundingbox, 3, 5, 0, 4, 6, 0, false); + } + + if (worldgenmonumentpieces_worldgenmonumentstatetracker2.c[EnumDirection.NORTH.a()]) { + this.a(world, structureboundingbox, 3, 5, 7, 4, 6, 7, false); + } + + if (worldgenmonumentpieces_worldgenmonumentstatetracker2.c[EnumDirection.WEST.a()]) { + this.a(world, structureboundingbox, 0, 5, 3, 0, 6, 4, false); + } + + if (worldgenmonumentpieces_worldgenmonumentstatetracker3.c[EnumDirection.SOUTH.a()]) { + this.a(world, structureboundingbox, 11, 5, 0, 12, 6, 0, false); + } + + if (worldgenmonumentpieces_worldgenmonumentstatetracker3.c[EnumDirection.NORTH.a()]) { + this.a(world, structureboundingbox, 11, 5, 7, 12, 6, 7, false); + } + + if (worldgenmonumentpieces_worldgenmonumentstatetracker3.c[EnumDirection.EAST.a()]) { + this.a(world, structureboundingbox, 15, 5, 3, 15, 6, 4, false); + } + + return true; + } + } + + public static class WorldGenMonumentPiece7 extends WorldGenMonumentPiece { + + public WorldGenMonumentPiece7() { + } + + public WorldGenMonumentPiece7(EnumDirection enumdirection, WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker, Random random) { + super(1, enumdirection, worldgenmonumentpieces_worldgenmonumentstatetracker, 1, 1, 2); + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker = this.k.b[EnumDirection.NORTH.a()]; + WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker1 = this.k; + + if (this.k.a / 25 > 0) { + this.a(world, structureboundingbox, 0, 8, worldgenmonumentpieces_worldgenmonumentstatetracker.c[EnumDirection.DOWN.a()]); + this.a(world, structureboundingbox, 0, 0, worldgenmonumentpieces_worldgenmonumentstatetracker1.c[EnumDirection.DOWN.a()]); + } + + if (worldgenmonumentpieces_worldgenmonumentstatetracker1.b[EnumDirection.UP.a()] == null) { + this.a(world, structureboundingbox, 1, 4, 1, 6, 4, 7, WorldGenMonumentPiece7.a); + } + + if (worldgenmonumentpieces_worldgenmonumentstatetracker.b[EnumDirection.UP.a()] == null) { + this.a(world, structureboundingbox, 1, 4, 8, 6, 4, 14, WorldGenMonumentPiece7.a); + } + + this.a(world, structureboundingbox, 0, 3, 0, 0, 3, 15, WorldGenMonumentPiece7.b, WorldGenMonumentPiece7.b, false); + this.a(world, structureboundingbox, 7, 3, 0, 7, 3, 15, WorldGenMonumentPiece7.b, WorldGenMonumentPiece7.b, false); + this.a(world, structureboundingbox, 1, 3, 0, 7, 3, 0, WorldGenMonumentPiece7.b, WorldGenMonumentPiece7.b, false); + this.a(world, structureboundingbox, 1, 3, 15, 6, 3, 15, WorldGenMonumentPiece7.b, WorldGenMonumentPiece7.b, false); + this.a(world, structureboundingbox, 0, 2, 0, 0, 2, 15, WorldGenMonumentPiece7.a, WorldGenMonumentPiece7.a, false); + this.a(world, structureboundingbox, 7, 2, 0, 7, 2, 15, WorldGenMonumentPiece7.a, WorldGenMonumentPiece7.a, false); + this.a(world, structureboundingbox, 1, 2, 0, 7, 2, 0, WorldGenMonumentPiece7.a, WorldGenMonumentPiece7.a, false); + this.a(world, structureboundingbox, 1, 2, 15, 6, 2, 15, WorldGenMonumentPiece7.a, WorldGenMonumentPiece7.a, false); + this.a(world, structureboundingbox, 0, 1, 0, 0, 1, 15, WorldGenMonumentPiece7.b, WorldGenMonumentPiece7.b, false); + this.a(world, structureboundingbox, 7, 1, 0, 7, 1, 15, WorldGenMonumentPiece7.b, WorldGenMonumentPiece7.b, false); + this.a(world, structureboundingbox, 1, 1, 0, 7, 1, 0, WorldGenMonumentPiece7.b, WorldGenMonumentPiece7.b, false); + this.a(world, structureboundingbox, 1, 1, 15, 6, 1, 15, WorldGenMonumentPiece7.b, WorldGenMonumentPiece7.b, false); + this.a(world, structureboundingbox, 1, 1, 1, 1, 1, 2, WorldGenMonumentPiece7.b, WorldGenMonumentPiece7.b, false); + this.a(world, structureboundingbox, 6, 1, 1, 6, 1, 2, WorldGenMonumentPiece7.b, WorldGenMonumentPiece7.b, false); + this.a(world, structureboundingbox, 1, 3, 1, 1, 3, 2, WorldGenMonumentPiece7.b, WorldGenMonumentPiece7.b, false); + this.a(world, structureboundingbox, 6, 3, 1, 6, 3, 2, WorldGenMonumentPiece7.b, WorldGenMonumentPiece7.b, false); + this.a(world, structureboundingbox, 1, 1, 13, 1, 1, 14, WorldGenMonumentPiece7.b, WorldGenMonumentPiece7.b, false); + this.a(world, structureboundingbox, 6, 1, 13, 6, 1, 14, WorldGenMonumentPiece7.b, WorldGenMonumentPiece7.b, false); + this.a(world, structureboundingbox, 1, 3, 13, 1, 3, 14, WorldGenMonumentPiece7.b, WorldGenMonumentPiece7.b, false); + this.a(world, structureboundingbox, 6, 3, 13, 6, 3, 14, WorldGenMonumentPiece7.b, WorldGenMonumentPiece7.b, false); + this.a(world, structureboundingbox, 2, 1, 6, 2, 3, 6, WorldGenMonumentPiece7.b, WorldGenMonumentPiece7.b, false); + this.a(world, structureboundingbox, 5, 1, 6, 5, 3, 6, WorldGenMonumentPiece7.b, WorldGenMonumentPiece7.b, false); + this.a(world, structureboundingbox, 2, 1, 9, 2, 3, 9, WorldGenMonumentPiece7.b, WorldGenMonumentPiece7.b, false); + this.a(world, structureboundingbox, 5, 1, 9, 5, 3, 9, WorldGenMonumentPiece7.b, WorldGenMonumentPiece7.b, false); + this.a(world, structureboundingbox, 3, 2, 6, 4, 2, 6, WorldGenMonumentPiece7.b, WorldGenMonumentPiece7.b, false); + this.a(world, structureboundingbox, 3, 2, 9, 4, 2, 9, WorldGenMonumentPiece7.b, WorldGenMonumentPiece7.b, false); + this.a(world, structureboundingbox, 2, 2, 7, 2, 2, 8, WorldGenMonumentPiece7.b, WorldGenMonumentPiece7.b, false); + this.a(world, structureboundingbox, 5, 2, 7, 5, 2, 8, WorldGenMonumentPiece7.b, WorldGenMonumentPiece7.b, false); + this.a(world, WorldGenMonumentPiece7.e, 2, 2, 5, structureboundingbox); + this.a(world, WorldGenMonumentPiece7.e, 5, 2, 5, structureboundingbox); + this.a(world, WorldGenMonumentPiece7.e, 2, 2, 10, structureboundingbox); + this.a(world, WorldGenMonumentPiece7.e, 5, 2, 10, structureboundingbox); + this.a(world, WorldGenMonumentPiece7.b, 2, 3, 5, structureboundingbox); + this.a(world, WorldGenMonumentPiece7.b, 5, 3, 5, structureboundingbox); + this.a(world, WorldGenMonumentPiece7.b, 2, 3, 10, structureboundingbox); + this.a(world, WorldGenMonumentPiece7.b, 5, 3, 10, structureboundingbox); + if (worldgenmonumentpieces_worldgenmonumentstatetracker1.c[EnumDirection.SOUTH.a()]) { + this.a(world, structureboundingbox, 3, 1, 0, 4, 2, 0, false); + } + + if (worldgenmonumentpieces_worldgenmonumentstatetracker1.c[EnumDirection.EAST.a()]) { + this.a(world, structureboundingbox, 7, 1, 3, 7, 2, 4, false); + } + + if (worldgenmonumentpieces_worldgenmonumentstatetracker1.c[EnumDirection.WEST.a()]) { + this.a(world, structureboundingbox, 0, 1, 3, 0, 2, 4, false); + } + + if (worldgenmonumentpieces_worldgenmonumentstatetracker.c[EnumDirection.NORTH.a()]) { + this.a(world, structureboundingbox, 3, 1, 15, 4, 2, 15, false); + } + + if (worldgenmonumentpieces_worldgenmonumentstatetracker.c[EnumDirection.WEST.a()]) { + this.a(world, structureboundingbox, 0, 1, 11, 0, 2, 12, false); + } + + if (worldgenmonumentpieces_worldgenmonumentstatetracker.c[EnumDirection.EAST.a()]) { + this.a(world, structureboundingbox, 7, 1, 11, 7, 2, 12, false); + } + + return true; + } + } + + public static class WorldGenMonumentPiece3 extends WorldGenMonumentPiece { + + public WorldGenMonumentPiece3() { + } + + public WorldGenMonumentPiece3(EnumDirection enumdirection, WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker, Random random) { + super(1, enumdirection, worldgenmonumentpieces_worldgenmonumentstatetracker, 2, 1, 1); + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker = this.k.b[EnumDirection.EAST.a()]; + WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker1 = this.k; + + if (this.k.a / 25 > 0) { + this.a(world, structureboundingbox, 8, 0, worldgenmonumentpieces_worldgenmonumentstatetracker.c[EnumDirection.DOWN.a()]); + this.a(world, structureboundingbox, 0, 0, worldgenmonumentpieces_worldgenmonumentstatetracker1.c[EnumDirection.DOWN.a()]); + } + + if (worldgenmonumentpieces_worldgenmonumentstatetracker1.b[EnumDirection.UP.a()] == null) { + this.a(world, structureboundingbox, 1, 4, 1, 7, 4, 6, WorldGenMonumentPiece3.a); + } + + if (worldgenmonumentpieces_worldgenmonumentstatetracker.b[EnumDirection.UP.a()] == null) { + this.a(world, structureboundingbox, 8, 4, 1, 14, 4, 6, WorldGenMonumentPiece3.a); + } + + this.a(world, structureboundingbox, 0, 3, 0, 0, 3, 7, WorldGenMonumentPiece3.b, WorldGenMonumentPiece3.b, false); + this.a(world, structureboundingbox, 15, 3, 0, 15, 3, 7, WorldGenMonumentPiece3.b, WorldGenMonumentPiece3.b, false); + this.a(world, structureboundingbox, 1, 3, 0, 15, 3, 0, WorldGenMonumentPiece3.b, WorldGenMonumentPiece3.b, false); + this.a(world, structureboundingbox, 1, 3, 7, 14, 3, 7, WorldGenMonumentPiece3.b, WorldGenMonumentPiece3.b, false); + this.a(world, structureboundingbox, 0, 2, 0, 0, 2, 7, WorldGenMonumentPiece3.a, WorldGenMonumentPiece3.a, false); + this.a(world, structureboundingbox, 15, 2, 0, 15, 2, 7, WorldGenMonumentPiece3.a, WorldGenMonumentPiece3.a, false); + this.a(world, structureboundingbox, 1, 2, 0, 15, 2, 0, WorldGenMonumentPiece3.a, WorldGenMonumentPiece3.a, false); + this.a(world, structureboundingbox, 1, 2, 7, 14, 2, 7, WorldGenMonumentPiece3.a, WorldGenMonumentPiece3.a, false); + this.a(world, structureboundingbox, 0, 1, 0, 0, 1, 7, WorldGenMonumentPiece3.b, WorldGenMonumentPiece3.b, false); + this.a(world, structureboundingbox, 15, 1, 0, 15, 1, 7, WorldGenMonumentPiece3.b, WorldGenMonumentPiece3.b, false); + this.a(world, structureboundingbox, 1, 1, 0, 15, 1, 0, WorldGenMonumentPiece3.b, WorldGenMonumentPiece3.b, false); + this.a(world, structureboundingbox, 1, 1, 7, 14, 1, 7, WorldGenMonumentPiece3.b, WorldGenMonumentPiece3.b, false); + this.a(world, structureboundingbox, 5, 1, 0, 10, 1, 4, WorldGenMonumentPiece3.b, WorldGenMonumentPiece3.b, false); + this.a(world, structureboundingbox, 6, 2, 0, 9, 2, 3, WorldGenMonumentPiece3.a, WorldGenMonumentPiece3.a, false); + this.a(world, structureboundingbox, 5, 3, 0, 10, 3, 4, WorldGenMonumentPiece3.b, WorldGenMonumentPiece3.b, false); + this.a(world, WorldGenMonumentPiece3.e, 6, 2, 3, structureboundingbox); + this.a(world, WorldGenMonumentPiece3.e, 9, 2, 3, structureboundingbox); + if (worldgenmonumentpieces_worldgenmonumentstatetracker1.c[EnumDirection.SOUTH.a()]) { + this.a(world, structureboundingbox, 3, 1, 0, 4, 2, 0, false); + } + + if (worldgenmonumentpieces_worldgenmonumentstatetracker1.c[EnumDirection.NORTH.a()]) { + this.a(world, structureboundingbox, 3, 1, 7, 4, 2, 7, false); + } + + if (worldgenmonumentpieces_worldgenmonumentstatetracker1.c[EnumDirection.WEST.a()]) { + this.a(world, structureboundingbox, 0, 1, 3, 0, 2, 4, false); + } + + if (worldgenmonumentpieces_worldgenmonumentstatetracker.c[EnumDirection.SOUTH.a()]) { + this.a(world, structureboundingbox, 11, 1, 0, 12, 2, 0, false); + } + + if (worldgenmonumentpieces_worldgenmonumentstatetracker.c[EnumDirection.NORTH.a()]) { + this.a(world, structureboundingbox, 11, 1, 7, 12, 2, 7, false); + } + + if (worldgenmonumentpieces_worldgenmonumentstatetracker.c[EnumDirection.EAST.a()]) { + this.a(world, structureboundingbox, 15, 1, 3, 15, 2, 4, false); + } + + return true; + } + } + + public static class WorldGenMonumentPiece5 extends WorldGenMonumentPiece { + + public WorldGenMonumentPiece5() { + } + + public WorldGenMonumentPiece5(EnumDirection enumdirection, WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker, Random random) { + super(1, enumdirection, worldgenmonumentpieces_worldgenmonumentstatetracker, 1, 2, 1); + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + if (this.k.a / 25 > 0) { + this.a(world, structureboundingbox, 0, 0, this.k.c[EnumDirection.DOWN.a()]); + } + + WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker = this.k.b[EnumDirection.UP.a()]; + + if (worldgenmonumentpieces_worldgenmonumentstatetracker.b[EnumDirection.UP.a()] == null) { + this.a(world, structureboundingbox, 1, 8, 1, 6, 8, 6, WorldGenMonumentPiece5.a); + } + + this.a(world, structureboundingbox, 0, 4, 0, 0, 4, 7, WorldGenMonumentPiece5.b, WorldGenMonumentPiece5.b, false); + this.a(world, structureboundingbox, 7, 4, 0, 7, 4, 7, WorldGenMonumentPiece5.b, WorldGenMonumentPiece5.b, false); + this.a(world, structureboundingbox, 1, 4, 0, 6, 4, 0, WorldGenMonumentPiece5.b, WorldGenMonumentPiece5.b, false); + this.a(world, structureboundingbox, 1, 4, 7, 6, 4, 7, WorldGenMonumentPiece5.b, WorldGenMonumentPiece5.b, false); + this.a(world, structureboundingbox, 2, 4, 1, 2, 4, 2, WorldGenMonumentPiece5.b, WorldGenMonumentPiece5.b, false); + this.a(world, structureboundingbox, 1, 4, 2, 1, 4, 2, WorldGenMonumentPiece5.b, WorldGenMonumentPiece5.b, false); + this.a(world, structureboundingbox, 5, 4, 1, 5, 4, 2, WorldGenMonumentPiece5.b, WorldGenMonumentPiece5.b, false); + this.a(world, structureboundingbox, 6, 4, 2, 6, 4, 2, WorldGenMonumentPiece5.b, WorldGenMonumentPiece5.b, false); + this.a(world, structureboundingbox, 2, 4, 5, 2, 4, 6, WorldGenMonumentPiece5.b, WorldGenMonumentPiece5.b, false); + this.a(world, structureboundingbox, 1, 4, 5, 1, 4, 5, WorldGenMonumentPiece5.b, WorldGenMonumentPiece5.b, false); + this.a(world, structureboundingbox, 5, 4, 5, 5, 4, 6, WorldGenMonumentPiece5.b, WorldGenMonumentPiece5.b, false); + this.a(world, structureboundingbox, 6, 4, 5, 6, 4, 5, WorldGenMonumentPiece5.b, WorldGenMonumentPiece5.b, false); + WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker1 = this.k; + + for (int i = 1; i <= 5; i += 4) { + byte b0 = 0; + + if (worldgenmonumentpieces_worldgenmonumentstatetracker1.c[EnumDirection.SOUTH.a()]) { + this.a(world, structureboundingbox, 2, i, b0, 2, i + 2, b0, WorldGenMonumentPiece5.b, WorldGenMonumentPiece5.b, false); + this.a(world, structureboundingbox, 5, i, b0, 5, i + 2, b0, WorldGenMonumentPiece5.b, WorldGenMonumentPiece5.b, false); + this.a(world, structureboundingbox, 3, i + 2, b0, 4, i + 2, b0, WorldGenMonumentPiece5.b, WorldGenMonumentPiece5.b, false); + } else { + this.a(world, structureboundingbox, 0, i, b0, 7, i + 2, b0, WorldGenMonumentPiece5.b, WorldGenMonumentPiece5.b, false); + this.a(world, structureboundingbox, 0, i + 1, b0, 7, i + 1, b0, WorldGenMonumentPiece5.a, WorldGenMonumentPiece5.a, false); + } + + b0 = 7; + if (worldgenmonumentpieces_worldgenmonumentstatetracker1.c[EnumDirection.NORTH.a()]) { + this.a(world, structureboundingbox, 2, i, b0, 2, i + 2, b0, WorldGenMonumentPiece5.b, WorldGenMonumentPiece5.b, false); + this.a(world, structureboundingbox, 5, i, b0, 5, i + 2, b0, WorldGenMonumentPiece5.b, WorldGenMonumentPiece5.b, false); + this.a(world, structureboundingbox, 3, i + 2, b0, 4, i + 2, b0, WorldGenMonumentPiece5.b, WorldGenMonumentPiece5.b, false); + } else { + this.a(world, structureboundingbox, 0, i, b0, 7, i + 2, b0, WorldGenMonumentPiece5.b, WorldGenMonumentPiece5.b, false); + this.a(world, structureboundingbox, 0, i + 1, b0, 7, i + 1, b0, WorldGenMonumentPiece5.a, WorldGenMonumentPiece5.a, false); + } + + byte b1 = 0; + + if (worldgenmonumentpieces_worldgenmonumentstatetracker1.c[EnumDirection.WEST.a()]) { + this.a(world, structureboundingbox, b1, i, 2, b1, i + 2, 2, WorldGenMonumentPiece5.b, WorldGenMonumentPiece5.b, false); + this.a(world, structureboundingbox, b1, i, 5, b1, i + 2, 5, WorldGenMonumentPiece5.b, WorldGenMonumentPiece5.b, false); + this.a(world, structureboundingbox, b1, i + 2, 3, b1, i + 2, 4, WorldGenMonumentPiece5.b, WorldGenMonumentPiece5.b, false); + } else { + this.a(world, structureboundingbox, b1, i, 0, b1, i + 2, 7, WorldGenMonumentPiece5.b, WorldGenMonumentPiece5.b, false); + this.a(world, structureboundingbox, b1, i + 1, 0, b1, i + 1, 7, WorldGenMonumentPiece5.a, WorldGenMonumentPiece5.a, false); + } + + b1 = 7; + if (worldgenmonumentpieces_worldgenmonumentstatetracker1.c[EnumDirection.EAST.a()]) { + this.a(world, structureboundingbox, b1, i, 2, b1, i + 2, 2, WorldGenMonumentPiece5.b, WorldGenMonumentPiece5.b, false); + this.a(world, structureboundingbox, b1, i, 5, b1, i + 2, 5, WorldGenMonumentPiece5.b, WorldGenMonumentPiece5.b, false); + this.a(world, structureboundingbox, b1, i + 2, 3, b1, i + 2, 4, WorldGenMonumentPiece5.b, WorldGenMonumentPiece5.b, false); + } else { + this.a(world, structureboundingbox, b1, i, 0, b1, i + 2, 7, WorldGenMonumentPiece5.b, WorldGenMonumentPiece5.b, false); + this.a(world, structureboundingbox, b1, i + 1, 0, b1, i + 1, 7, WorldGenMonumentPiece5.a, WorldGenMonumentPiece5.a, false); + } + + worldgenmonumentpieces_worldgenmonumentstatetracker1 = worldgenmonumentpieces_worldgenmonumentstatetracker; + } + + return true; + } + } + + public static class WorldGenMonumentPieceSimpleT extends WorldGenMonumentPiece { + + public WorldGenMonumentPieceSimpleT() { + } + + public WorldGenMonumentPieceSimpleT(EnumDirection enumdirection, WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker, Random random) { + super(1, enumdirection, worldgenmonumentpieces_worldgenmonumentstatetracker, 1, 1, 1); + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + if (this.k.a / 25 > 0) { + this.a(world, structureboundingbox, 0, 0, this.k.c[EnumDirection.DOWN.a()]); + } + + if (this.k.b[EnumDirection.UP.a()] == null) { + this.a(world, structureboundingbox, 1, 4, 1, 6, 4, 6, WorldGenMonumentPieceSimpleT.a); + } + + for (int i = 1; i <= 6; ++i) { + for (int j = 1; j <= 6; ++j) { + if (random.nextInt(3) != 0) { + int k = 2 + (random.nextInt(4) == 0 ? 0 : 1); + + this.a(world, structureboundingbox, i, k, j, i, 3, j, Blocks.SPONGE.fromLegacyData(1), Blocks.SPONGE.fromLegacyData(1), false); + } + } + } + + this.a(world, structureboundingbox, 0, 1, 0, 0, 1, 7, WorldGenMonumentPieceSimpleT.b, WorldGenMonumentPieceSimpleT.b, false); + this.a(world, structureboundingbox, 7, 1, 0, 7, 1, 7, WorldGenMonumentPieceSimpleT.b, WorldGenMonumentPieceSimpleT.b, false); + this.a(world, structureboundingbox, 1, 1, 0, 6, 1, 0, WorldGenMonumentPieceSimpleT.b, WorldGenMonumentPieceSimpleT.b, false); + this.a(world, structureboundingbox, 1, 1, 7, 6, 1, 7, WorldGenMonumentPieceSimpleT.b, WorldGenMonumentPieceSimpleT.b, false); + this.a(world, structureboundingbox, 0, 2, 0, 0, 2, 7, WorldGenMonumentPieceSimpleT.c, WorldGenMonumentPieceSimpleT.c, false); + this.a(world, structureboundingbox, 7, 2, 0, 7, 2, 7, WorldGenMonumentPieceSimpleT.c, WorldGenMonumentPieceSimpleT.c, false); + this.a(world, structureboundingbox, 1, 2, 0, 6, 2, 0, WorldGenMonumentPieceSimpleT.c, WorldGenMonumentPieceSimpleT.c, false); + this.a(world, structureboundingbox, 1, 2, 7, 6, 2, 7, WorldGenMonumentPieceSimpleT.c, WorldGenMonumentPieceSimpleT.c, false); + this.a(world, structureboundingbox, 0, 3, 0, 0, 3, 7, WorldGenMonumentPieceSimpleT.b, WorldGenMonumentPieceSimpleT.b, false); + this.a(world, structureboundingbox, 7, 3, 0, 7, 3, 7, WorldGenMonumentPieceSimpleT.b, WorldGenMonumentPieceSimpleT.b, false); + this.a(world, structureboundingbox, 1, 3, 0, 6, 3, 0, WorldGenMonumentPieceSimpleT.b, WorldGenMonumentPieceSimpleT.b, false); + this.a(world, structureboundingbox, 1, 3, 7, 6, 3, 7, WorldGenMonumentPieceSimpleT.b, WorldGenMonumentPieceSimpleT.b, false); + this.a(world, structureboundingbox, 0, 1, 3, 0, 2, 4, WorldGenMonumentPieceSimpleT.c, WorldGenMonumentPieceSimpleT.c, false); + this.a(world, structureboundingbox, 7, 1, 3, 7, 2, 4, WorldGenMonumentPieceSimpleT.c, WorldGenMonumentPieceSimpleT.c, false); + this.a(world, structureboundingbox, 3, 1, 0, 4, 2, 0, WorldGenMonumentPieceSimpleT.c, WorldGenMonumentPieceSimpleT.c, false); + this.a(world, structureboundingbox, 3, 1, 7, 4, 2, 7, WorldGenMonumentPieceSimpleT.c, WorldGenMonumentPieceSimpleT.c, false); + if (this.k.c[EnumDirection.SOUTH.a()]) { + this.a(world, structureboundingbox, 3, 1, 0, 4, 2, 0, false); + } + + return true; + } + } + + public static class WorldGenMonumentPieceSimple extends WorldGenMonumentPiece { + + private int o; + + public WorldGenMonumentPieceSimple() { + } + + public WorldGenMonumentPieceSimple(EnumDirection enumdirection, WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker, Random random) { + super(1, enumdirection, worldgenmonumentpieces_worldgenmonumentstatetracker, 1, 1, 1); + this.o = random.nextInt(3); + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + if (this.k.a / 25 > 0) { + this.a(world, structureboundingbox, 0, 0, this.k.c[EnumDirection.DOWN.a()]); + } + + if (this.k.b[EnumDirection.UP.a()] == null) { + this.a(world, structureboundingbox, 1, 4, 1, 6, 4, 6, WorldGenMonumentPieceSimple.a); + } + + boolean flag = this.o != 0 && random.nextBoolean() && !this.k.c[EnumDirection.DOWN.a()] && !this.k.c[EnumDirection.UP.a()] && this.k.c() > 1; + + if (this.o == 0) { + this.a(world, structureboundingbox, 0, 1, 0, 2, 1, 2, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + this.a(world, structureboundingbox, 0, 3, 0, 2, 3, 2, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + this.a(world, structureboundingbox, 0, 2, 0, 0, 2, 2, WorldGenMonumentPieceSimple.a, WorldGenMonumentPieceSimple.a, false); + this.a(world, structureboundingbox, 1, 2, 0, 2, 2, 0, WorldGenMonumentPieceSimple.a, WorldGenMonumentPieceSimple.a, false); + this.a(world, WorldGenMonumentPieceSimple.e, 1, 2, 1, structureboundingbox); + this.a(world, structureboundingbox, 5, 1, 0, 7, 1, 2, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + this.a(world, structureboundingbox, 5, 3, 0, 7, 3, 2, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + this.a(world, structureboundingbox, 7, 2, 0, 7, 2, 2, WorldGenMonumentPieceSimple.a, WorldGenMonumentPieceSimple.a, false); + this.a(world, structureboundingbox, 5, 2, 0, 6, 2, 0, WorldGenMonumentPieceSimple.a, WorldGenMonumentPieceSimple.a, false); + this.a(world, WorldGenMonumentPieceSimple.e, 6, 2, 1, structureboundingbox); + this.a(world, structureboundingbox, 0, 1, 5, 2, 1, 7, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + this.a(world, structureboundingbox, 0, 3, 5, 2, 3, 7, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + this.a(world, structureboundingbox, 0, 2, 5, 0, 2, 7, WorldGenMonumentPieceSimple.a, WorldGenMonumentPieceSimple.a, false); + this.a(world, structureboundingbox, 1, 2, 7, 2, 2, 7, WorldGenMonumentPieceSimple.a, WorldGenMonumentPieceSimple.a, false); + this.a(world, WorldGenMonumentPieceSimple.e, 1, 2, 6, structureboundingbox); + this.a(world, structureboundingbox, 5, 1, 5, 7, 1, 7, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + this.a(world, structureboundingbox, 5, 3, 5, 7, 3, 7, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + this.a(world, structureboundingbox, 7, 2, 5, 7, 2, 7, WorldGenMonumentPieceSimple.a, WorldGenMonumentPieceSimple.a, false); + this.a(world, structureboundingbox, 5, 2, 7, 6, 2, 7, WorldGenMonumentPieceSimple.a, WorldGenMonumentPieceSimple.a, false); + this.a(world, WorldGenMonumentPieceSimple.e, 6, 2, 6, structureboundingbox); + if (this.k.c[EnumDirection.SOUTH.a()]) { + this.a(world, structureboundingbox, 3, 3, 0, 4, 3, 0, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + } else { + this.a(world, structureboundingbox, 3, 3, 0, 4, 3, 1, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + this.a(world, structureboundingbox, 3, 2, 0, 4, 2, 0, WorldGenMonumentPieceSimple.a, WorldGenMonumentPieceSimple.a, false); + this.a(world, structureboundingbox, 3, 1, 0, 4, 1, 1, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + } + + if (this.k.c[EnumDirection.NORTH.a()]) { + this.a(world, structureboundingbox, 3, 3, 7, 4, 3, 7, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + } else { + this.a(world, structureboundingbox, 3, 3, 6, 4, 3, 7, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + this.a(world, structureboundingbox, 3, 2, 7, 4, 2, 7, WorldGenMonumentPieceSimple.a, WorldGenMonumentPieceSimple.a, false); + this.a(world, structureboundingbox, 3, 1, 6, 4, 1, 7, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + } + + if (this.k.c[EnumDirection.WEST.a()]) { + this.a(world, structureboundingbox, 0, 3, 3, 0, 3, 4, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + } else { + this.a(world, structureboundingbox, 0, 3, 3, 1, 3, 4, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + this.a(world, structureboundingbox, 0, 2, 3, 0, 2, 4, WorldGenMonumentPieceSimple.a, WorldGenMonumentPieceSimple.a, false); + this.a(world, structureboundingbox, 0, 1, 3, 1, 1, 4, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + } + + if (this.k.c[EnumDirection.EAST.a()]) { + this.a(world, structureboundingbox, 7, 3, 3, 7, 3, 4, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + } else { + this.a(world, structureboundingbox, 6, 3, 3, 7, 3, 4, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + this.a(world, structureboundingbox, 7, 2, 3, 7, 2, 4, WorldGenMonumentPieceSimple.a, WorldGenMonumentPieceSimple.a, false); + this.a(world, structureboundingbox, 6, 1, 3, 7, 1, 4, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + } + } else if (this.o == 1) { + this.a(world, structureboundingbox, 2, 1, 2, 2, 3, 2, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + this.a(world, structureboundingbox, 2, 1, 5, 2, 3, 5, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + this.a(world, structureboundingbox, 5, 1, 5, 5, 3, 5, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + this.a(world, structureboundingbox, 5, 1, 2, 5, 3, 2, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + this.a(world, WorldGenMonumentPieceSimple.e, 2, 2, 2, structureboundingbox); + this.a(world, WorldGenMonumentPieceSimple.e, 2, 2, 5, structureboundingbox); + this.a(world, WorldGenMonumentPieceSimple.e, 5, 2, 5, structureboundingbox); + this.a(world, WorldGenMonumentPieceSimple.e, 5, 2, 2, structureboundingbox); + this.a(world, structureboundingbox, 0, 1, 0, 1, 3, 0, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + this.a(world, structureboundingbox, 0, 1, 1, 0, 3, 1, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + this.a(world, structureboundingbox, 0, 1, 7, 1, 3, 7, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + this.a(world, structureboundingbox, 0, 1, 6, 0, 3, 6, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + this.a(world, structureboundingbox, 6, 1, 7, 7, 3, 7, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + this.a(world, structureboundingbox, 7, 1, 6, 7, 3, 6, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + this.a(world, structureboundingbox, 6, 1, 0, 7, 3, 0, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + this.a(world, structureboundingbox, 7, 1, 1, 7, 3, 1, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + this.a(world, WorldGenMonumentPieceSimple.a, 1, 2, 0, structureboundingbox); + this.a(world, WorldGenMonumentPieceSimple.a, 0, 2, 1, structureboundingbox); + this.a(world, WorldGenMonumentPieceSimple.a, 1, 2, 7, structureboundingbox); + this.a(world, WorldGenMonumentPieceSimple.a, 0, 2, 6, structureboundingbox); + this.a(world, WorldGenMonumentPieceSimple.a, 6, 2, 7, structureboundingbox); + this.a(world, WorldGenMonumentPieceSimple.a, 7, 2, 6, structureboundingbox); + this.a(world, WorldGenMonumentPieceSimple.a, 6, 2, 0, structureboundingbox); + this.a(world, WorldGenMonumentPieceSimple.a, 7, 2, 1, structureboundingbox); + if (!this.k.c[EnumDirection.SOUTH.a()]) { + this.a(world, structureboundingbox, 1, 3, 0, 6, 3, 0, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + this.a(world, structureboundingbox, 1, 2, 0, 6, 2, 0, WorldGenMonumentPieceSimple.a, WorldGenMonumentPieceSimple.a, false); + this.a(world, structureboundingbox, 1, 1, 0, 6, 1, 0, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + } + + if (!this.k.c[EnumDirection.NORTH.a()]) { + this.a(world, structureboundingbox, 1, 3, 7, 6, 3, 7, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + this.a(world, structureboundingbox, 1, 2, 7, 6, 2, 7, WorldGenMonumentPieceSimple.a, WorldGenMonumentPieceSimple.a, false); + this.a(world, structureboundingbox, 1, 1, 7, 6, 1, 7, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + } + + if (!this.k.c[EnumDirection.WEST.a()]) { + this.a(world, structureboundingbox, 0, 3, 1, 0, 3, 6, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + this.a(world, structureboundingbox, 0, 2, 1, 0, 2, 6, WorldGenMonumentPieceSimple.a, WorldGenMonumentPieceSimple.a, false); + this.a(world, structureboundingbox, 0, 1, 1, 0, 1, 6, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + } + + if (!this.k.c[EnumDirection.EAST.a()]) { + this.a(world, structureboundingbox, 7, 3, 1, 7, 3, 6, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + this.a(world, structureboundingbox, 7, 2, 1, 7, 2, 6, WorldGenMonumentPieceSimple.a, WorldGenMonumentPieceSimple.a, false); + this.a(world, structureboundingbox, 7, 1, 1, 7, 1, 6, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + } + } else if (this.o == 2) { + this.a(world, structureboundingbox, 0, 1, 0, 0, 1, 7, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + this.a(world, structureboundingbox, 7, 1, 0, 7, 1, 7, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + this.a(world, structureboundingbox, 1, 1, 0, 6, 1, 0, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + this.a(world, structureboundingbox, 1, 1, 7, 6, 1, 7, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + this.a(world, structureboundingbox, 0, 2, 0, 0, 2, 7, WorldGenMonumentPieceSimple.c, WorldGenMonumentPieceSimple.c, false); + this.a(world, structureboundingbox, 7, 2, 0, 7, 2, 7, WorldGenMonumentPieceSimple.c, WorldGenMonumentPieceSimple.c, false); + this.a(world, structureboundingbox, 1, 2, 0, 6, 2, 0, WorldGenMonumentPieceSimple.c, WorldGenMonumentPieceSimple.c, false); + this.a(world, structureboundingbox, 1, 2, 7, 6, 2, 7, WorldGenMonumentPieceSimple.c, WorldGenMonumentPieceSimple.c, false); + this.a(world, structureboundingbox, 0, 3, 0, 0, 3, 7, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + this.a(world, structureboundingbox, 7, 3, 0, 7, 3, 7, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + this.a(world, structureboundingbox, 1, 3, 0, 6, 3, 0, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + this.a(world, structureboundingbox, 1, 3, 7, 6, 3, 7, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + this.a(world, structureboundingbox, 0, 1, 3, 0, 2, 4, WorldGenMonumentPieceSimple.c, WorldGenMonumentPieceSimple.c, false); + this.a(world, structureboundingbox, 7, 1, 3, 7, 2, 4, WorldGenMonumentPieceSimple.c, WorldGenMonumentPieceSimple.c, false); + this.a(world, structureboundingbox, 3, 1, 0, 4, 2, 0, WorldGenMonumentPieceSimple.c, WorldGenMonumentPieceSimple.c, false); + this.a(world, structureboundingbox, 3, 1, 7, 4, 2, 7, WorldGenMonumentPieceSimple.c, WorldGenMonumentPieceSimple.c, false); + if (this.k.c[EnumDirection.SOUTH.a()]) { + this.a(world, structureboundingbox, 3, 1, 0, 4, 2, 0, false); + } + + if (this.k.c[EnumDirection.NORTH.a()]) { + this.a(world, structureboundingbox, 3, 1, 7, 4, 2, 7, false); + } + + if (this.k.c[EnumDirection.WEST.a()]) { + this.a(world, structureboundingbox, 0, 1, 3, 0, 2, 4, false); + } + + if (this.k.c[EnumDirection.EAST.a()]) { + this.a(world, structureboundingbox, 7, 1, 3, 7, 2, 4, false); + } + } + + if (flag) { + this.a(world, structureboundingbox, 3, 1, 3, 4, 1, 4, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + this.a(world, structureboundingbox, 3, 2, 3, 4, 2, 4, WorldGenMonumentPieceSimple.a, WorldGenMonumentPieceSimple.a, false); + this.a(world, structureboundingbox, 3, 3, 3, 4, 3, 4, WorldGenMonumentPieceSimple.b, WorldGenMonumentPieceSimple.b, false); + } + + return true; + } + } + + public static class WorldGenMonumentPieceEntry extends WorldGenMonumentPiece { + + public WorldGenMonumentPieceEntry() { + } + + public WorldGenMonumentPieceEntry(EnumDirection enumdirection, WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker) { + super(1, enumdirection, worldgenmonumentpieces_worldgenmonumentstatetracker, 1, 1, 1); + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + this.a(world, structureboundingbox, 0, 3, 0, 2, 3, 7, WorldGenMonumentPieceEntry.b, WorldGenMonumentPieceEntry.b, false); + this.a(world, structureboundingbox, 5, 3, 0, 7, 3, 7, WorldGenMonumentPieceEntry.b, WorldGenMonumentPieceEntry.b, false); + this.a(world, structureboundingbox, 0, 2, 0, 1, 2, 7, WorldGenMonumentPieceEntry.b, WorldGenMonumentPieceEntry.b, false); + this.a(world, structureboundingbox, 6, 2, 0, 7, 2, 7, WorldGenMonumentPieceEntry.b, WorldGenMonumentPieceEntry.b, false); + this.a(world, structureboundingbox, 0, 1, 0, 0, 1, 7, WorldGenMonumentPieceEntry.b, WorldGenMonumentPieceEntry.b, false); + this.a(world, structureboundingbox, 7, 1, 0, 7, 1, 7, WorldGenMonumentPieceEntry.b, WorldGenMonumentPieceEntry.b, false); + this.a(world, structureboundingbox, 0, 1, 7, 7, 3, 7, WorldGenMonumentPieceEntry.b, WorldGenMonumentPieceEntry.b, false); + this.a(world, structureboundingbox, 1, 1, 0, 2, 3, 0, WorldGenMonumentPieceEntry.b, WorldGenMonumentPieceEntry.b, false); + this.a(world, structureboundingbox, 5, 1, 0, 6, 3, 0, WorldGenMonumentPieceEntry.b, WorldGenMonumentPieceEntry.b, false); + if (this.k.c[EnumDirection.NORTH.a()]) { + this.a(world, structureboundingbox, 3, 1, 7, 4, 2, 7, false); + } + + if (this.k.c[EnumDirection.WEST.a()]) { + this.a(world, structureboundingbox, 0, 1, 3, 1, 2, 4, false); + } + + if (this.k.c[EnumDirection.EAST.a()]) { + this.a(world, structureboundingbox, 6, 1, 3, 7, 2, 4, false); + } + + return true; + } + } + + public static class WorldGenMonumentPiece1 extends WorldGenMonumentPiece { + + private WorldGenMonumentStateTracker o; + private WorldGenMonumentStateTracker p; + private final List q = Lists.newArrayList(); + + public WorldGenMonumentPiece1() { + } + + public WorldGenMonumentPiece1(Random random, int i, int j, EnumDirection enumdirection) { + super(0); + this.m = enumdirection; + switch (SyntheticClass_1.a[this.m.ordinal()]) { + case 1: + case 2: + this.l = new StructureBoundingBox(i, 39, j, i + 58 - 1, 61, j + 58 - 1); + break; + + default: + this.l = new StructureBoundingBox(i, 39, j, i + 58 - 1, 61, j + 58 - 1); + } + + List list = this.a(random); + + this.o.d = true; + this.q.add(new WorldGenMonumentPieceEntry(this.m, this.o)); + this.q.add(new WorldGenMonumentPiece2(this.m, this.p, random)); + ArrayList arraylist = Lists.newArrayList(); + + arraylist.add(new WorldGenMonumentPieceSelector6(null)); + arraylist.add(new WorldGenMonumentPieceSelector4(null)); + arraylist.add(new WorldGenMonumentPieceSelector3(null)); + arraylist.add(new WorldGenMonumentPieceSelector7(null)); + arraylist.add(new WorldGenMonumentPieceSelector5(null)); + arraylist.add(new WorldGenMonumentPieceSelector1(null)); + arraylist.add(new WorldGenMonumentPieceSelector2(null)); + + for (WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker : list) { + if (!worldgenmonumentpieces_worldgenmonumentstatetracker.d && !worldgenmonumentpieces_worldgenmonumentstatetracker.b()) { + for (IWorldGenMonumentPieceSelector worldgenmonumentpieces_iworldgenmonumentpieceselector : arraylist) { + if (worldgenmonumentpieces_iworldgenmonumentpieceselector.a(worldgenmonumentpieces_worldgenmonumentstatetracker)) { + this.q.add(worldgenmonumentpieces_iworldgenmonumentpieceselector.a(this.m, worldgenmonumentpieces_worldgenmonumentstatetracker, random)); + break; + } + } + } + } + + int k = this.l.b; + int l = this.a(9, 22); + int i1 = this.b(9, 22); + + for (WorldGenMonumentPiece worldgenmonumentpieces_worldgenmonumentpiece : this.q) { + worldgenmonumentpieces_worldgenmonumentpiece.c().a(l, k, i1); + } + + StructureBoundingBox structureboundingbox = StructureBoundingBox.a(this.a(1, 1), this.d(1), this.b(1, 1), this.a(23, 21), this.d(8), this.b(23, 21)); + StructureBoundingBox structureboundingbox1 = StructureBoundingBox.a(this.a(34, 1), this.d(1), this.b(34, 1), this.a(56, 21), this.d(8), this.b(56, 21)); + StructureBoundingBox structureboundingbox2 = StructureBoundingBox.a(this.a(22, 22), this.d(13), this.b(22, 22), this.a(35, 35), this.d(17), this.b(35, 35)); + int j1 = random.nextInt(); + + this.q.add(new WorldGenMonumentPiece8(this.m, structureboundingbox, j1++)); + this.q.add(new WorldGenMonumentPiece8(this.m, structureboundingbox1, j1++)); + this.q.add(new WorldGenMonumentPiecePenthouse(this.m, structureboundingbox2)); + } + + private List a(Random random) { + WorldGenMonumentStateTracker[] aworldgenmonumentpieces_worldgenmonumentstatetracker = new WorldGenMonumentStateTracker[75]; + + int i; + int j; + byte b0; + int k; + + for (i = 0; i < 5; ++i) { + for (j = 0; j < 4; ++j) { + b0 = 0; + k = b(i, b0, j); + aworldgenmonumentpieces_worldgenmonumentstatetracker[k] = new WorldGenMonumentStateTracker(k); + } + } + + for (i = 0; i < 5; ++i) { + for (j = 0; j < 4; ++j) { + b0 = 1; + k = b(i, b0, j); + aworldgenmonumentpieces_worldgenmonumentstatetracker[k] = new WorldGenMonumentStateTracker(k); + } + } + + for (i = 1; i < 4; ++i) { + for (j = 0; j < 2; ++j) { + b0 = 2; + k = b(i, b0, j); + aworldgenmonumentpieces_worldgenmonumentstatetracker[k] = new WorldGenMonumentStateTracker(k); + } + } + + this.o = aworldgenmonumentpieces_worldgenmonumentstatetracker[WorldGenMonumentPiece1.g]; + + int l; + int i1; + int j1; + int k1; + int l1; + + for (i = 0; i < 5; ++i) { + for (j = 0; j < 5; ++j) { + for (int i2 = 0; i2 < 3; ++i2) { + k = b(i, i2, j); + if (aworldgenmonumentpieces_worldgenmonumentstatetracker[k] != null) { + EnumDirection[] aenumdirection = EnumDirection.values(); + + l = aenumdirection.length; + + for (i1 = 0; i1 < l; ++i1) { + EnumDirection enumdirection = aenumdirection[i1]; + + j1 = i + enumdirection.getAdjacentX(); + k1 = i2 + enumdirection.getAdjacentY(); + l1 = j + enumdirection.getAdjacentZ(); + if (j1 >= 0 && j1 < 5 && l1 >= 0 && l1 < 5 && k1 >= 0 && k1 < 3) { + int j2 = b(j1, k1, l1); + + if (aworldgenmonumentpieces_worldgenmonumentstatetracker[j2] != null) { + if (l1 != j) { + aworldgenmonumentpieces_worldgenmonumentstatetracker[k].a(enumdirection.opposite(), aworldgenmonumentpieces_worldgenmonumentstatetracker[j2]); + } else { + aworldgenmonumentpieces_worldgenmonumentstatetracker[k].a(enumdirection, aworldgenmonumentpieces_worldgenmonumentstatetracker[j2]); + } + } + } + } + } + } + } + } + + WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker; + WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker1; + WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker2; + + aworldgenmonumentpieces_worldgenmonumentstatetracker[WorldGenMonumentPiece1.h].a(EnumDirection.UP, worldgenmonumentpieces_worldgenmonumentstatetracker = new WorldGenMonumentStateTracker(1003)); + aworldgenmonumentpieces_worldgenmonumentstatetracker[WorldGenMonumentPiece1.i].a(EnumDirection.SOUTH, worldgenmonumentpieces_worldgenmonumentstatetracker1 = new WorldGenMonumentStateTracker(1001)); + aworldgenmonumentpieces_worldgenmonumentstatetracker[WorldGenMonumentPiece1.j].a(EnumDirection.SOUTH, worldgenmonumentpieces_worldgenmonumentstatetracker2 = new WorldGenMonumentStateTracker(1002)); + worldgenmonumentpieces_worldgenmonumentstatetracker.d = true; + worldgenmonumentpieces_worldgenmonumentstatetracker1.d = true; + worldgenmonumentpieces_worldgenmonumentstatetracker2.d = true; + this.o.e = true; + this.p = aworldgenmonumentpieces_worldgenmonumentstatetracker[b(random.nextInt(4), 0, 2)]; + this.p.d = true; + this.p.b[EnumDirection.EAST.a()].d = true; + this.p.b[EnumDirection.NORTH.a()].d = true; + this.p.b[EnumDirection.EAST.a()].b[EnumDirection.NORTH.a()].d = true; + this.p.b[EnumDirection.UP.a()].d = true; + this.p.b[EnumDirection.EAST.a()].b[EnumDirection.UP.a()].d = true; + this.p.b[EnumDirection.NORTH.a()].b[EnumDirection.UP.a()].d = true; + this.p.b[EnumDirection.EAST.a()].b[EnumDirection.NORTH.a()].b[EnumDirection.UP.a()].d = true; + ArrayList arraylist = Lists.newArrayList(); + + l = aworldgenmonumentpieces_worldgenmonumentstatetracker.length; + + for (i1 = 0; i1 < l; ++i1) { + WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker3 = aworldgenmonumentpieces_worldgenmonumentstatetracker[i1]; + + if (worldgenmonumentpieces_worldgenmonumentstatetracker3 != null) { + worldgenmonumentpieces_worldgenmonumentstatetracker3.a(); + arraylist.add(worldgenmonumentpieces_worldgenmonumentstatetracker3); + } + } + + worldgenmonumentpieces_worldgenmonumentstatetracker.a(); + Collections.shuffle(arraylist, random); + int k2 = 1; + + for (WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker4 : arraylist) { + int l2 = 0; + + j1 = 0; + + while (l2 < 2 && j1 < 5) { + ++j1; + k1 = random.nextInt(6); + if (worldgenmonumentpieces_worldgenmonumentstatetracker4.c[k1]) { + l1 = EnumDirection.fromType1(k1).opposite().a(); + worldgenmonumentpieces_worldgenmonumentstatetracker4.c[k1] = false; + worldgenmonumentpieces_worldgenmonumentstatetracker4.b[k1].c[l1] = false; + if (worldgenmonumentpieces_worldgenmonumentstatetracker4.a(k2++) && worldgenmonumentpieces_worldgenmonumentstatetracker4.b[k1].a(k2++)) { + ++l2; + } else { + worldgenmonumentpieces_worldgenmonumentstatetracker4.c[k1] = true; + worldgenmonumentpieces_worldgenmonumentstatetracker4.b[k1].c[l1] = true; + } + } + } + } + + arraylist.add(worldgenmonumentpieces_worldgenmonumentstatetracker); + arraylist.add(worldgenmonumentpieces_worldgenmonumentstatetracker1); + arraylist.add(worldgenmonumentpieces_worldgenmonumentstatetracker2); + return arraylist; + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + int i = Math.max(world.F(), 64) - this.l.b; + + this.a(world, structureboundingbox, 0, 0, 0, 58, i, 58, false); + this.a(false, 0, world, random, structureboundingbox); + this.a(true, 33, world, random, structureboundingbox); + this.b(world, random, structureboundingbox); + this.c(world, random, structureboundingbox); + this.d(world, random, structureboundingbox); + this.e(world, random, structureboundingbox); + this.f(world, random, structureboundingbox); + this.g(world, random, structureboundingbox); + + int j; + + for (j = 0; j < 7; ++j) { + int k = 0; + + while (k < 7) { + if (k == 0 && j == 3) { + k = 6; + } + + int l = j * 9; + int i1 = k * 9; + + for (int j1 = 0; j1 < 4; ++j1) { + for (int k1 = 0; k1 < 4; ++k1) { + this.a(world, WorldGenMonumentPiece1.b, l + j1, 0, i1 + k1, structureboundingbox); + this.b(world, WorldGenMonumentPiece1.b, l + j1, -1, i1 + k1, structureboundingbox); + } + } + + if (j != 0 && j != 6) { + k += 6; + } else { + ++k; + } + } + } + + for (j = 0; j < 5; ++j) { + this.a(world, structureboundingbox, -1 - j, j * 2, -1 - j, -1 - j, 23, 58 + j, false); + this.a(world, structureboundingbox, 58 + j, j * 2, -1 - j, 58 + j, 23, 58 + j, false); + this.a(world, structureboundingbox, j, j * 2, -1 - j, 57 + j, 23, -1 - j, false); + this.a(world, structureboundingbox, j, j * 2, 58 + j, 57 + j, 23, 58 + j, false); + } + + for (WorldGenMonumentPiece worldgenmonumentpieces_worldgenmonumentpiece : this.q) { + if (worldgenmonumentpieces_worldgenmonumentpiece.c().a(structureboundingbox)) { + worldgenmonumentpieces_worldgenmonumentpiece.a(world, random, structureboundingbox); + } + } + + return true; + } + + private void a(boolean flag, int i, World world, Random random, StructureBoundingBox structureboundingbox) { + boolean flag1 = true; + + if (this.a(structureboundingbox, i, 0, i + 23, 20)) { + this.a(world, structureboundingbox, i, 0, 0, i + 24, 0, 20, WorldGenMonumentPiece1.a, WorldGenMonumentPiece1.a, false); + this.a(world, structureboundingbox, i, 1, 0, i + 24, 10, 20, false); + + int j; + + for (j = 0; j < 4; ++j) { + this.a(world, structureboundingbox, i + j, j + 1, j, i + j, j + 1, 20, WorldGenMonumentPiece1.b, WorldGenMonumentPiece1.b, false); + this.a(world, structureboundingbox, i + j + 7, j + 5, j + 7, i + j + 7, j + 5, 20, WorldGenMonumentPiece1.b, WorldGenMonumentPiece1.b, false); + this.a(world, structureboundingbox, i + 17 - j, j + 5, j + 7, i + 17 - j, j + 5, 20, WorldGenMonumentPiece1.b, WorldGenMonumentPiece1.b, false); + this.a(world, structureboundingbox, i + 24 - j, j + 1, j, i + 24 - j, j + 1, 20, WorldGenMonumentPiece1.b, WorldGenMonumentPiece1.b, false); + this.a(world, structureboundingbox, i + j + 1, j + 1, j, i + 23 - j, j + 1, j, WorldGenMonumentPiece1.b, WorldGenMonumentPiece1.b, false); + this.a(world, structureboundingbox, i + j + 8, j + 5, j + 7, i + 16 - j, j + 5, j + 7, WorldGenMonumentPiece1.b, WorldGenMonumentPiece1.b, false); + } + + this.a(world, structureboundingbox, i + 4, 4, 4, i + 6, 4, 20, WorldGenMonumentPiece1.a, WorldGenMonumentPiece1.a, false); + this.a(world, structureboundingbox, i + 7, 4, 4, i + 17, 4, 6, WorldGenMonumentPiece1.a, WorldGenMonumentPiece1.a, false); + this.a(world, structureboundingbox, i + 18, 4, 4, i + 20, 4, 20, WorldGenMonumentPiece1.a, WorldGenMonumentPiece1.a, false); + this.a(world, structureboundingbox, i + 11, 8, 11, i + 13, 8, 20, WorldGenMonumentPiece1.a, WorldGenMonumentPiece1.a, false); + this.a(world, WorldGenMonumentPiece1.d, i + 12, 9, 12, structureboundingbox); + this.a(world, WorldGenMonumentPiece1.d, i + 12, 9, 15, structureboundingbox); + this.a(world, WorldGenMonumentPiece1.d, i + 12, 9, 18, structureboundingbox); + j = flag ? i + 19 : i + 5; + int k = flag ? i + 5 : i + 19; + + int l; + + for (l = 20; l >= 5; l -= 3) { + this.a(world, WorldGenMonumentPiece1.d, j, 5, l, structureboundingbox); + } + + for (l = 19; l >= 7; l -= 3) { + this.a(world, WorldGenMonumentPiece1.d, k, 5, l, structureboundingbox); + } + + for (l = 0; l < 4; ++l) { + int i1 = flag ? i + (24 - (17 - l * 3)) : i + 17 - l * 3; + + this.a(world, WorldGenMonumentPiece1.d, i1, 5, 5, structureboundingbox); + } + + this.a(world, WorldGenMonumentPiece1.d, k, 5, 5, structureboundingbox); + this.a(world, structureboundingbox, i + 11, 1, 12, i + 13, 7, 12, WorldGenMonumentPiece1.a, WorldGenMonumentPiece1.a, false); + this.a(world, structureboundingbox, i + 12, 1, 11, i + 12, 7, 13, WorldGenMonumentPiece1.a, WorldGenMonumentPiece1.a, false); + } + + } + + private void b(World world, Random random, StructureBoundingBox structureboundingbox) { + if (this.a(structureboundingbox, 22, 5, 35, 17)) { + this.a(world, structureboundingbox, 25, 0, 0, 32, 8, 20, false); + + for (int i = 0; i < 4; ++i) { + this.a(world, structureboundingbox, 24, 2, 5 + i * 4, 24, 4, 5 + i * 4, WorldGenMonumentPiece1.b, WorldGenMonumentPiece1.b, false); + this.a(world, structureboundingbox, 22, 4, 5 + i * 4, 23, 4, 5 + i * 4, WorldGenMonumentPiece1.b, WorldGenMonumentPiece1.b, false); + this.a(world, WorldGenMonumentPiece1.b, 25, 5, 5 + i * 4, structureboundingbox); + this.a(world, WorldGenMonumentPiece1.b, 26, 6, 5 + i * 4, structureboundingbox); + this.a(world, WorldGenMonumentPiece1.e, 26, 5, 5 + i * 4, structureboundingbox); + this.a(world, structureboundingbox, 33, 2, 5 + i * 4, 33, 4, 5 + i * 4, WorldGenMonumentPiece1.b, WorldGenMonumentPiece1.b, false); + this.a(world, structureboundingbox, 34, 4, 5 + i * 4, 35, 4, 5 + i * 4, WorldGenMonumentPiece1.b, WorldGenMonumentPiece1.b, false); + this.a(world, WorldGenMonumentPiece1.b, 32, 5, 5 + i * 4, structureboundingbox); + this.a(world, WorldGenMonumentPiece1.b, 31, 6, 5 + i * 4, structureboundingbox); + this.a(world, WorldGenMonumentPiece1.e, 31, 5, 5 + i * 4, structureboundingbox); + this.a(world, structureboundingbox, 27, 6, 5 + i * 4, 30, 6, 5 + i * 4, WorldGenMonumentPiece1.a, WorldGenMonumentPiece1.a, false); + } + } + + } + + private void c(World world, Random random, StructureBoundingBox structureboundingbox) { + if (this.a(structureboundingbox, 15, 20, 42, 21)) { + this.a(world, structureboundingbox, 15, 0, 21, 42, 0, 21, WorldGenMonumentPiece1.a, WorldGenMonumentPiece1.a, false); + this.a(world, structureboundingbox, 26, 1, 21, 31, 3, 21, false); + this.a(world, structureboundingbox, 21, 12, 21, 36, 12, 21, WorldGenMonumentPiece1.a, WorldGenMonumentPiece1.a, false); + this.a(world, structureboundingbox, 17, 11, 21, 40, 11, 21, WorldGenMonumentPiece1.a, WorldGenMonumentPiece1.a, false); + this.a(world, structureboundingbox, 16, 10, 21, 41, 10, 21, WorldGenMonumentPiece1.a, WorldGenMonumentPiece1.a, false); + this.a(world, structureboundingbox, 15, 7, 21, 42, 9, 21, WorldGenMonumentPiece1.a, WorldGenMonumentPiece1.a, false); + this.a(world, structureboundingbox, 16, 6, 21, 41, 6, 21, WorldGenMonumentPiece1.a, WorldGenMonumentPiece1.a, false); + this.a(world, structureboundingbox, 17, 5, 21, 40, 5, 21, WorldGenMonumentPiece1.a, WorldGenMonumentPiece1.a, false); + this.a(world, structureboundingbox, 21, 4, 21, 36, 4, 21, WorldGenMonumentPiece1.a, WorldGenMonumentPiece1.a, false); + this.a(world, structureboundingbox, 22, 3, 21, 26, 3, 21, WorldGenMonumentPiece1.a, WorldGenMonumentPiece1.a, false); + this.a(world, structureboundingbox, 31, 3, 21, 35, 3, 21, WorldGenMonumentPiece1.a, WorldGenMonumentPiece1.a, false); + this.a(world, structureboundingbox, 23, 2, 21, 25, 2, 21, WorldGenMonumentPiece1.a, WorldGenMonumentPiece1.a, false); + this.a(world, structureboundingbox, 32, 2, 21, 34, 2, 21, WorldGenMonumentPiece1.a, WorldGenMonumentPiece1.a, false); + this.a(world, structureboundingbox, 28, 4, 20, 29, 4, 21, WorldGenMonumentPiece1.b, WorldGenMonumentPiece1.b, false); + this.a(world, WorldGenMonumentPiece1.b, 27, 3, 21, structureboundingbox); + this.a(world, WorldGenMonumentPiece1.b, 30, 3, 21, structureboundingbox); + this.a(world, WorldGenMonumentPiece1.b, 26, 2, 21, structureboundingbox); + this.a(world, WorldGenMonumentPiece1.b, 31, 2, 21, structureboundingbox); + this.a(world, WorldGenMonumentPiece1.b, 25, 1, 21, structureboundingbox); + this.a(world, WorldGenMonumentPiece1.b, 32, 1, 21, structureboundingbox); + + int i; + + for (i = 0; i < 7; ++i) { + this.a(world, WorldGenMonumentPiece1.c, 28 - i, 6 + i, 21, structureboundingbox); + this.a(world, WorldGenMonumentPiece1.c, 29 + i, 6 + i, 21, structureboundingbox); + } + + for (i = 0; i < 4; ++i) { + this.a(world, WorldGenMonumentPiece1.c, 28 - i, 9 + i, 21, structureboundingbox); + this.a(world, WorldGenMonumentPiece1.c, 29 + i, 9 + i, 21, structureboundingbox); + } + + this.a(world, WorldGenMonumentPiece1.c, 28, 12, 21, structureboundingbox); + this.a(world, WorldGenMonumentPiece1.c, 29, 12, 21, structureboundingbox); + + for (i = 0; i < 3; ++i) { + this.a(world, WorldGenMonumentPiece1.c, 22 - i * 2, 8, 21, structureboundingbox); + this.a(world, WorldGenMonumentPiece1.c, 22 - i * 2, 9, 21, structureboundingbox); + this.a(world, WorldGenMonumentPiece1.c, 35 + i * 2, 8, 21, structureboundingbox); + this.a(world, WorldGenMonumentPiece1.c, 35 + i * 2, 9, 21, structureboundingbox); + } + + this.a(world, structureboundingbox, 15, 13, 21, 42, 15, 21, false); + this.a(world, structureboundingbox, 15, 1, 21, 15, 6, 21, false); + this.a(world, structureboundingbox, 16, 1, 21, 16, 5, 21, false); + this.a(world, structureboundingbox, 17, 1, 21, 20, 4, 21, false); + this.a(world, structureboundingbox, 21, 1, 21, 21, 3, 21, false); + this.a(world, structureboundingbox, 22, 1, 21, 22, 2, 21, false); + this.a(world, structureboundingbox, 23, 1, 21, 24, 1, 21, false); + this.a(world, structureboundingbox, 42, 1, 21, 42, 6, 21, false); + this.a(world, structureboundingbox, 41, 1, 21, 41, 5, 21, false); + this.a(world, structureboundingbox, 37, 1, 21, 40, 4, 21, false); + this.a(world, structureboundingbox, 36, 1, 21, 36, 3, 21, false); + this.a(world, structureboundingbox, 33, 1, 21, 34, 1, 21, false); + this.a(world, structureboundingbox, 35, 1, 21, 35, 2, 21, false); + } + + } + + private void d(World world, Random random, StructureBoundingBox structureboundingbox) { + if (this.a(structureboundingbox, 21, 21, 36, 36)) { + this.a(world, structureboundingbox, 21, 0, 22, 36, 0, 36, WorldGenMonumentPiece1.a, WorldGenMonumentPiece1.a, false); + this.a(world, structureboundingbox, 21, 1, 22, 36, 23, 36, false); + + for (int i = 0; i < 4; ++i) { + this.a(world, structureboundingbox, 21 + i, 13 + i, 21 + i, 36 - i, 13 + i, 21 + i, WorldGenMonumentPiece1.b, WorldGenMonumentPiece1.b, false); + this.a(world, structureboundingbox, 21 + i, 13 + i, 36 - i, 36 - i, 13 + i, 36 - i, WorldGenMonumentPiece1.b, WorldGenMonumentPiece1.b, false); + this.a(world, structureboundingbox, 21 + i, 13 + i, 22 + i, 21 + i, 13 + i, 35 - i, WorldGenMonumentPiece1.b, WorldGenMonumentPiece1.b, false); + this.a(world, structureboundingbox, 36 - i, 13 + i, 22 + i, 36 - i, 13 + i, 35 - i, WorldGenMonumentPiece1.b, WorldGenMonumentPiece1.b, false); + } + + this.a(world, structureboundingbox, 25, 16, 25, 32, 16, 32, WorldGenMonumentPiece1.a, WorldGenMonumentPiece1.a, false); + this.a(world, structureboundingbox, 25, 17, 25, 25, 19, 25, WorldGenMonumentPiece1.b, WorldGenMonumentPiece1.b, false); + this.a(world, structureboundingbox, 32, 17, 25, 32, 19, 25, WorldGenMonumentPiece1.b, WorldGenMonumentPiece1.b, false); + this.a(world, structureboundingbox, 25, 17, 32, 25, 19, 32, WorldGenMonumentPiece1.b, WorldGenMonumentPiece1.b, false); + this.a(world, structureboundingbox, 32, 17, 32, 32, 19, 32, WorldGenMonumentPiece1.b, WorldGenMonumentPiece1.b, false); + this.a(world, WorldGenMonumentPiece1.b, 26, 20, 26, structureboundingbox); + this.a(world, WorldGenMonumentPiece1.b, 27, 21, 27, structureboundingbox); + this.a(world, WorldGenMonumentPiece1.e, 27, 20, 27, structureboundingbox); + this.a(world, WorldGenMonumentPiece1.b, 26, 20, 31, structureboundingbox); + this.a(world, WorldGenMonumentPiece1.b, 27, 21, 30, structureboundingbox); + this.a(world, WorldGenMonumentPiece1.e, 27, 20, 30, structureboundingbox); + this.a(world, WorldGenMonumentPiece1.b, 31, 20, 31, structureboundingbox); + this.a(world, WorldGenMonumentPiece1.b, 30, 21, 30, structureboundingbox); + this.a(world, WorldGenMonumentPiece1.e, 30, 20, 30, structureboundingbox); + this.a(world, WorldGenMonumentPiece1.b, 31, 20, 26, structureboundingbox); + this.a(world, WorldGenMonumentPiece1.b, 30, 21, 27, structureboundingbox); + this.a(world, WorldGenMonumentPiece1.e, 30, 20, 27, structureboundingbox); + this.a(world, structureboundingbox, 28, 21, 27, 29, 21, 27, WorldGenMonumentPiece1.a, WorldGenMonumentPiece1.a, false); + this.a(world, structureboundingbox, 27, 21, 28, 27, 21, 29, WorldGenMonumentPiece1.a, WorldGenMonumentPiece1.a, false); + this.a(world, structureboundingbox, 28, 21, 30, 29, 21, 30, WorldGenMonumentPiece1.a, WorldGenMonumentPiece1.a, false); + this.a(world, structureboundingbox, 30, 21, 28, 30, 21, 29, WorldGenMonumentPiece1.a, WorldGenMonumentPiece1.a, false); + } + + } + + private void e(World world, Random random, StructureBoundingBox structureboundingbox) { + int i; + + if (this.a(structureboundingbox, 0, 21, 6, 58)) { + this.a(world, structureboundingbox, 0, 0, 21, 6, 0, 57, WorldGenMonumentPiece1.a, WorldGenMonumentPiece1.a, false); + this.a(world, structureboundingbox, 0, 1, 21, 6, 7, 57, false); + this.a(world, structureboundingbox, 4, 4, 21, 6, 4, 53, WorldGenMonumentPiece1.a, WorldGenMonumentPiece1.a, false); + + for (i = 0; i < 4; ++i) { + this.a(world, structureboundingbox, i, i + 1, 21, i, i + 1, 57 - i, WorldGenMonumentPiece1.b, WorldGenMonumentPiece1.b, false); + } + + for (i = 23; i < 53; i += 3) { + this.a(world, WorldGenMonumentPiece1.d, 5, 5, i, structureboundingbox); + } + + this.a(world, WorldGenMonumentPiece1.d, 5, 5, 52, structureboundingbox); + + for (i = 0; i < 4; ++i) { + this.a(world, structureboundingbox, i, i + 1, 21, i, i + 1, 57 - i, WorldGenMonumentPiece1.b, WorldGenMonumentPiece1.b, false); + } + + this.a(world, structureboundingbox, 4, 1, 52, 6, 3, 52, WorldGenMonumentPiece1.a, WorldGenMonumentPiece1.a, false); + this.a(world, structureboundingbox, 5, 1, 51, 5, 3, 53, WorldGenMonumentPiece1.a, WorldGenMonumentPiece1.a, false); + } + + if (this.a(structureboundingbox, 51, 21, 58, 58)) { + this.a(world, structureboundingbox, 51, 0, 21, 57, 0, 57, WorldGenMonumentPiece1.a, WorldGenMonumentPiece1.a, false); + this.a(world, structureboundingbox, 51, 1, 21, 57, 7, 57, false); + this.a(world, structureboundingbox, 51, 4, 21, 53, 4, 53, WorldGenMonumentPiece1.a, WorldGenMonumentPiece1.a, false); + + for (i = 0; i < 4; ++i) { + this.a(world, structureboundingbox, 57 - i, i + 1, 21, 57 - i, i + 1, 57 - i, WorldGenMonumentPiece1.b, WorldGenMonumentPiece1.b, false); + } + + for (i = 23; i < 53; i += 3) { + this.a(world, WorldGenMonumentPiece1.d, 52, 5, i, structureboundingbox); + } + + this.a(world, WorldGenMonumentPiece1.d, 52, 5, 52, structureboundingbox); + this.a(world, structureboundingbox, 51, 1, 52, 53, 3, 52, WorldGenMonumentPiece1.a, WorldGenMonumentPiece1.a, false); + this.a(world, structureboundingbox, 52, 1, 51, 52, 3, 53, WorldGenMonumentPiece1.a, WorldGenMonumentPiece1.a, false); + } + + if (this.a(structureboundingbox, 0, 51, 57, 57)) { + this.a(world, structureboundingbox, 7, 0, 51, 50, 0, 57, WorldGenMonumentPiece1.a, WorldGenMonumentPiece1.a, false); + this.a(world, structureboundingbox, 7, 1, 51, 50, 10, 57, false); + + for (i = 0; i < 4; ++i) { + this.a(world, structureboundingbox, i + 1, i + 1, 57 - i, 56 - i, i + 1, 57 - i, WorldGenMonumentPiece1.b, WorldGenMonumentPiece1.b, false); + } + } + + } + + private void f(World world, Random random, StructureBoundingBox structureboundingbox) { + int i; + + if (this.a(structureboundingbox, 7, 21, 13, 50)) { + this.a(world, structureboundingbox, 7, 0, 21, 13, 0, 50, WorldGenMonumentPiece1.a, WorldGenMonumentPiece1.a, false); + this.a(world, structureboundingbox, 7, 1, 21, 13, 10, 50, false); + this.a(world, structureboundingbox, 11, 8, 21, 13, 8, 53, WorldGenMonumentPiece1.a, WorldGenMonumentPiece1.a, false); + + for (i = 0; i < 4; ++i) { + this.a(world, structureboundingbox, i + 7, i + 5, 21, i + 7, i + 5, 54, WorldGenMonumentPiece1.b, WorldGenMonumentPiece1.b, false); + } + + for (i = 21; i <= 45; i += 3) { + this.a(world, WorldGenMonumentPiece1.d, 12, 9, i, structureboundingbox); + } + } + + if (this.a(structureboundingbox, 44, 21, 50, 54)) { + this.a(world, structureboundingbox, 44, 0, 21, 50, 0, 50, WorldGenMonumentPiece1.a, WorldGenMonumentPiece1.a, false); + this.a(world, structureboundingbox, 44, 1, 21, 50, 10, 50, false); + this.a(world, structureboundingbox, 44, 8, 21, 46, 8, 53, WorldGenMonumentPiece1.a, WorldGenMonumentPiece1.a, false); + + for (i = 0; i < 4; ++i) { + this.a(world, structureboundingbox, 50 - i, i + 5, 21, 50 - i, i + 5, 54, WorldGenMonumentPiece1.b, WorldGenMonumentPiece1.b, false); + } + + for (i = 21; i <= 45; i += 3) { + this.a(world, WorldGenMonumentPiece1.d, 45, 9, i, structureboundingbox); + } + } + + if (this.a(structureboundingbox, 8, 44, 49, 54)) { + this.a(world, structureboundingbox, 14, 0, 44, 43, 0, 50, WorldGenMonumentPiece1.a, WorldGenMonumentPiece1.a, false); + this.a(world, structureboundingbox, 14, 1, 44, 43, 10, 50, false); + + for (i = 12; i <= 45; i += 3) { + this.a(world, WorldGenMonumentPiece1.d, i, 9, 45, structureboundingbox); + this.a(world, WorldGenMonumentPiece1.d, i, 9, 52, structureboundingbox); + if (i == 12 || i == 18 || i == 24 || i == 33 || i == 39 || i == 45) { + this.a(world, WorldGenMonumentPiece1.d, i, 9, 47, structureboundingbox); + this.a(world, WorldGenMonumentPiece1.d, i, 9, 50, structureboundingbox); + this.a(world, WorldGenMonumentPiece1.d, i, 10, 45, structureboundingbox); + this.a(world, WorldGenMonumentPiece1.d, i, 10, 46, structureboundingbox); + this.a(world, WorldGenMonumentPiece1.d, i, 10, 51, structureboundingbox); + this.a(world, WorldGenMonumentPiece1.d, i, 10, 52, structureboundingbox); + this.a(world, WorldGenMonumentPiece1.d, i, 11, 47, structureboundingbox); + this.a(world, WorldGenMonumentPiece1.d, i, 11, 50, structureboundingbox); + this.a(world, WorldGenMonumentPiece1.d, i, 12, 48, structureboundingbox); + this.a(world, WorldGenMonumentPiece1.d, i, 12, 49, structureboundingbox); + } + } + + for (i = 0; i < 3; ++i) { + this.a(world, structureboundingbox, 8 + i, 5 + i, 54, 49 - i, 5 + i, 54, WorldGenMonumentPiece1.a, WorldGenMonumentPiece1.a, false); + } + + this.a(world, structureboundingbox, 11, 8, 54, 46, 8, 54, WorldGenMonumentPiece1.b, WorldGenMonumentPiece1.b, false); + this.a(world, structureboundingbox, 14, 8, 44, 43, 8, 53, WorldGenMonumentPiece1.a, WorldGenMonumentPiece1.a, false); + } + + } + + private void g(World world, Random random, StructureBoundingBox structureboundingbox) { + int i; + + if (this.a(structureboundingbox, 14, 21, 20, 43)) { + this.a(world, structureboundingbox, 14, 0, 21, 20, 0, 43, WorldGenMonumentPiece1.a, WorldGenMonumentPiece1.a, false); + this.a(world, structureboundingbox, 14, 1, 22, 20, 14, 43, false); + this.a(world, structureboundingbox, 18, 12, 22, 20, 12, 39, WorldGenMonumentPiece1.a, WorldGenMonumentPiece1.a, false); + this.a(world, structureboundingbox, 18, 12, 21, 20, 12, 21, WorldGenMonumentPiece1.b, WorldGenMonumentPiece1.b, false); + + for (i = 0; i < 4; ++i) { + this.a(world, structureboundingbox, i + 14, i + 9, 21, i + 14, i + 9, 43 - i, WorldGenMonumentPiece1.b, WorldGenMonumentPiece1.b, false); + } + + for (i = 23; i <= 39; i += 3) { + this.a(world, WorldGenMonumentPiece1.d, 19, 13, i, structureboundingbox); + } + } + + if (this.a(structureboundingbox, 37, 21, 43, 43)) { + this.a(world, structureboundingbox, 37, 0, 21, 43, 0, 43, WorldGenMonumentPiece1.a, WorldGenMonumentPiece1.a, false); + this.a(world, structureboundingbox, 37, 1, 22, 43, 14, 43, false); + this.a(world, structureboundingbox, 37, 12, 22, 39, 12, 39, WorldGenMonumentPiece1.a, WorldGenMonumentPiece1.a, false); + this.a(world, structureboundingbox, 37, 12, 21, 39, 12, 21, WorldGenMonumentPiece1.b, WorldGenMonumentPiece1.b, false); + + for (i = 0; i < 4; ++i) { + this.a(world, structureboundingbox, 43 - i, i + 9, 21, 43 - i, i + 9, 43 - i, WorldGenMonumentPiece1.b, WorldGenMonumentPiece1.b, false); + } + + for (i = 23; i <= 39; i += 3) { + this.a(world, WorldGenMonumentPiece1.d, 38, 13, i, structureboundingbox); + } + } + + if (this.a(structureboundingbox, 15, 37, 42, 43)) { + this.a(world, structureboundingbox, 21, 0, 37, 36, 0, 43, WorldGenMonumentPiece1.a, WorldGenMonumentPiece1.a, false); + this.a(world, structureboundingbox, 21, 1, 37, 36, 14, 43, false); + this.a(world, structureboundingbox, 21, 12, 37, 36, 12, 39, WorldGenMonumentPiece1.a, WorldGenMonumentPiece1.a, false); + + for (i = 0; i < 4; ++i) { + this.a(world, structureboundingbox, 15 + i, i + 9, 43 - i, 42 - i, i + 9, 43 - i, WorldGenMonumentPiece1.b, WorldGenMonumentPiece1.b, false); + } + + for (i = 21; i <= 36; i += 3) { + this.a(world, WorldGenMonumentPiece1.d, i, 13, 38, structureboundingbox); + } + } + + } + } + + public abstract static class WorldGenMonumentPiece extends StructurePiece { + + protected static final IBlockData a = Blocks.PRISMARINE.fromLegacyData(BlockPrismarine.b); + protected static final IBlockData b = Blocks.PRISMARINE.fromLegacyData(BlockPrismarine.N); + protected static final IBlockData c = Blocks.PRISMARINE.fromLegacyData(BlockPrismarine.O); + protected static final IBlockData d = WorldGenMonumentPiece.b; + protected static final IBlockData e = Blocks.SEA_LANTERN.getBlockData(); + protected static final IBlockData f = Blocks.WATER.getBlockData(); + protected static final int g = b(2, 0, 0); + protected static final int h = b(2, 2, 0); + protected static final int i = b(0, 1, 0); + protected static final int j = b(4, 1, 0); + protected WorldGenMonumentStateTracker k; + + protected static int b(int i, int j, int k) { + return j * 25 + k * 5 + i; + } + + public WorldGenMonumentPiece() { + super(0); + } + + public WorldGenMonumentPiece(int i) { + super(i); + } + + public WorldGenMonumentPiece(EnumDirection enumdirection, StructureBoundingBox structureboundingbox) { + super(1); + this.m = enumdirection; + this.l = structureboundingbox; + } + + protected WorldGenMonumentPiece(int i, EnumDirection enumdirection, WorldGenMonumentStateTracker worldgenmonumentpieces_worldgenmonumentstatetracker, int j, int k, int l) { + super(i); + this.m = enumdirection; + this.k = worldgenmonumentpieces_worldgenmonumentstatetracker; + int i1 = worldgenmonumentpieces_worldgenmonumentstatetracker.a; + int j1 = i1 % 5; + int k1 = i1 / 5 % 5; + int l1 = i1 / 25; + + if (enumdirection != EnumDirection.NORTH && enumdirection != EnumDirection.SOUTH) { + this.l = new StructureBoundingBox(0, 0, 0, l * 8 - 1, k * 4 - 1, j * 8 - 1); + } else { + this.l = new StructureBoundingBox(0, 0, 0, j * 8 - 1, k * 4 - 1, l * 8 - 1); + } + + switch (SyntheticClass_1.a[enumdirection.ordinal()]) { + case 1: + this.l.a(j1 * 8, l1 * 4, -(k1 + l) * 8 + 1); + break; + + case 2: + this.l.a(j1 * 8, l1 * 4, k1 * 8); + break; + + case 3: + this.l.a(-(k1 + l) * 8 + 1, l1 * 4, j1 * 8); + break; + + default: + this.l.a(k1 * 8, l1 * 4, j1 * 8); + } + + } + + protected void a(NBTTagCompound nbttagcompound) { + } + + protected void b(NBTTagCompound nbttagcompound) { + } + + protected void a(World world, StructureBoundingBox structureboundingbox, int i, int j, int k, int l, int i1, int j1, boolean flag) { + for (int k1 = j; k1 <= i1; ++k1) { + for (int l1 = i; l1 <= l; ++l1) { + for (int i2 = k; i2 <= j1; ++i2) { + if (!flag || this.a(world, l1, k1, i2, structureboundingbox).getBlock().getMaterial() != Material.AIR) { + if (this.d(k1) >= world.F()) { + this.a(world, Blocks.AIR.getBlockData(), l1, k1, i2, structureboundingbox); + } else { + this.a(world, WorldGenMonumentPiece.f, l1, k1, i2, structureboundingbox); + } + } + } + } + } + + } + + protected void a(World world, StructureBoundingBox structureboundingbox, int i, int j, boolean flag) { + if (flag) { + this.a(world, structureboundingbox, i + 0, 0, j + 0, i + 2, 0, j + 8 - 1, WorldGenMonumentPiece.a, WorldGenMonumentPiece.a, false); + this.a(world, structureboundingbox, i + 5, 0, j + 0, i + 8 - 1, 0, j + 8 - 1, WorldGenMonumentPiece.a, WorldGenMonumentPiece.a, false); + this.a(world, structureboundingbox, i + 3, 0, j + 0, i + 4, 0, j + 2, WorldGenMonumentPiece.a, WorldGenMonumentPiece.a, false); + this.a(world, structureboundingbox, i + 3, 0, j + 5, i + 4, 0, j + 8 - 1, WorldGenMonumentPiece.a, WorldGenMonumentPiece.a, false); + this.a(world, structureboundingbox, i + 3, 0, j + 2, i + 4, 0, j + 2, WorldGenMonumentPiece.b, WorldGenMonumentPiece.b, false); + this.a(world, structureboundingbox, i + 3, 0, j + 5, i + 4, 0, j + 5, WorldGenMonumentPiece.b, WorldGenMonumentPiece.b, false); + this.a(world, structureboundingbox, i + 2, 0, j + 3, i + 2, 0, j + 4, WorldGenMonumentPiece.b, WorldGenMonumentPiece.b, false); + this.a(world, structureboundingbox, i + 5, 0, j + 3, i + 5, 0, j + 4, WorldGenMonumentPiece.b, WorldGenMonumentPiece.b, false); + } else { + this.a(world, structureboundingbox, i + 0, 0, j + 0, i + 8 - 1, 0, j + 8 - 1, WorldGenMonumentPiece.a, WorldGenMonumentPiece.a, false); + } + + } + + protected void a(World world, StructureBoundingBox structureboundingbox, int i, int j, int k, int l, int i1, int j1, IBlockData iblockdata) { + for (int k1 = j; k1 <= i1; ++k1) { + for (int l1 = i; l1 <= l; ++l1) { + for (int i2 = k; i2 <= j1; ++i2) { + if (this.a(world, l1, k1, i2, structureboundingbox) == WorldGenMonumentPiece.f) { + this.a(world, iblockdata, l1, k1, i2, structureboundingbox); + } + } + } + } + + } + + protected boolean a(StructureBoundingBox structureboundingbox, int i, int j, int k, int l) { + int i1 = this.a(i, j); + int j1 = this.b(i, j); + int k1 = this.a(k, l); + int l1 = this.b(k, l); + + return structureboundingbox.a(Math.min(i1, k1), Math.min(j1, l1), Math.max(i1, k1), Math.max(j1, l1)); + } + + protected boolean a(World world, StructureBoundingBox structureboundingbox, int i, int j, int k) { + int l = this.a(i, k); + int i1 = this.d(j); + int j1 = this.b(i, k); + + if (structureboundingbox.b(l, i1, j1)) { + EntityGuardian entityguardian = new EntityGuardian(world); + + entityguardian.setElder(true); + entityguardian.heal(entityguardian.getMaxHealth()); + entityguardian.setPositionRotation((double) l + 0.5D, i1, (double) j1 + 0.5D, 0.0F, 0.0F); + entityguardian.prepare(world.E(MathHelper.floor(entityguardian.locX), MathHelper.floor(entityguardian.locY), MathHelper.floor(entityguardian.locZ)), (GroupDataEntity) null); + world.addEntity(entityguardian); + return true; + } else { + return false; + } + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenMushrooms.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenMushrooms.java new file mode 100644 index 0000000..d9d03c7 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenMushrooms.java @@ -0,0 +1,24 @@ +package net.minecraft.server; + +import java.util.Random; + +public class WorldGenMushrooms extends WorldGenerator { + + private BlockPlant a; + + public WorldGenMushrooms(BlockPlant blockplant) { + this.a = blockplant; + } + + public boolean generate(World world, Random random, BlockPosition blockposition) { + for (int i = 0; i < 64; ++i) { + BlockPosition blockposition1 = blockposition.a(random.nextInt(8) - random.nextInt(8), random.nextInt(4) - random.nextInt(4), random.nextInt(8) - random.nextInt(8)); + + if (world.isEmpty(blockposition1) && (!world.worldProvider.o() || blockposition1.getY() < 255) && this.a.f(world, blockposition1, this.a.getBlockData())) { + world.setTypeAndData(blockposition1, this.a.getBlockData(), 2); + } + } + + return true; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenNether.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenNether.java new file mode 100644 index 0000000..940fbcc --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenNether.java @@ -0,0 +1,64 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; + +import java.util.List; +import java.util.Random; + +public class WorldGenNether extends StructureGenerator { + + private final List d = Lists.newArrayList(); + + public WorldGenNether() { + this.d.add(new BiomeBase.BiomeMeta(EntityBlaze.class, 10, 2, 3)); + this.d.add(new BiomeBase.BiomeMeta(EntityPigZombie.class, 5, 4, 4)); + this.d.add(new BiomeBase.BiomeMeta(EntitySkeleton.class, 10, 4, 4)); + this.d.add(new BiomeBase.BiomeMeta(EntityMagmaCube.class, 3, 4, 4)); + } + + public String a() { + return "Fortress"; + } + + public List b() { + return this.d; + } + + protected boolean a(int i, int j) { + int k = i >> 4; + int l = j >> 4; + + this.b.setSeed((long) (k ^ l << 4) ^ this.c.getSeed()); + this.b.nextInt(); + return this.b.nextInt(3) == 0 && (i == (k << 4) + 4 + this.b.nextInt(8) && j == (l << 4) + 4 + this.b.nextInt(8)); + } + + protected StructureStart b(int i, int j) { + return new WorldGenNetherStart(this.c, this.b, i, j); + } + + public static class WorldGenNetherStart extends StructureStart { + + public WorldGenNetherStart() { + } + + public WorldGenNetherStart(World world, Random random, int i, int j) { + super(i, j); + WorldGenNetherPieces.WorldGenNetherPiece15 worldgennetherpieces_worldgennetherpiece15 = new WorldGenNetherPieces.WorldGenNetherPiece15(random, (i << 4) + 2, (j << 4) + 2); + + this.a.add(worldgennetherpieces_worldgennetherpiece15); + worldgennetherpieces_worldgennetherpiece15.a(worldgennetherpieces_worldgennetherpiece15, this.a, random); + List list = worldgennetherpieces_worldgennetherpiece15.e; + + while (!list.isEmpty()) { + int k = random.nextInt(list.size()); + StructurePiece structurepiece = list.remove(k); + + structurepiece.a(worldgennetherpieces_worldgennetherpiece15, this.a, random); + } + + this.c(); + this.a(world, random, 48, 70); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenNetherPieces.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenNetherPieces.java new file mode 100644 index 0000000..c8a34d4 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenNetherPieces.java @@ -0,0 +1,1256 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; + +import java.util.Iterator; +import java.util.List; +import java.util.Random; + +public class WorldGenNetherPieces { + + private static final WorldGenNetherPieceWeight[] a = {new WorldGenNetherPieceWeight(WorldGenNetherPiece3.class, 30, 0, true), new WorldGenNetherPieceWeight(WorldGenNetherPiece1.class, 10, 4), new WorldGenNetherPieceWeight(WorldGenNetherPiece13.class, 10, 4), new WorldGenNetherPieceWeight(WorldGenNetherPiece14.class, 10, 3), new WorldGenNetherPieceWeight(WorldGenNetherPiece12.class, 5, 2), new WorldGenNetherPieceWeight(WorldGenNetherPiece6.class, 5, 1)}; + private static final WorldGenNetherPieceWeight[] b = {new WorldGenNetherPieceWeight(WorldGenNetherPiece9.class, 25, 0, true), new WorldGenNetherPieceWeight(WorldGenNetherPiece7.class, 15, 5), new WorldGenNetherPieceWeight(WorldGenNetherPiece10.class, 5, 10), new WorldGenNetherPieceWeight(WorldGenNetherPiece8.class, 5, 10), new WorldGenNetherPieceWeight(WorldGenNetherPiece4.class, 10, 3, true), new WorldGenNetherPieceWeight(WorldGenNetherPiece5.class, 7, 2), new WorldGenNetherPieceWeight(WorldGenNetherPiece11.class, 5, 2)}; + + public static void a() { + WorldGenFactory.a(WorldGenNetherPiece1.class, "NeBCr"); + WorldGenFactory.a(WorldGenNetherPiece2.class, "NeBEF"); + WorldGenFactory.a(WorldGenNetherPiece3.class, "NeBS"); + WorldGenFactory.a(WorldGenNetherPiece4.class, "NeCCS"); + WorldGenFactory.a(WorldGenNetherPiece5.class, "NeCTB"); + WorldGenFactory.a(WorldGenNetherPiece6.class, "NeCE"); + WorldGenFactory.a(WorldGenNetherPiece7.class, "NeSCSC"); + WorldGenFactory.a(WorldGenNetherPiece8.class, "NeSCLT"); + WorldGenFactory.a(WorldGenNetherPiece9.class, "NeSC"); + WorldGenFactory.a(WorldGenNetherPiece10.class, "NeSCRT"); + WorldGenFactory.a(WorldGenNetherPiece11.class, "NeCSR"); + WorldGenFactory.a(WorldGenNetherPiece12.class, "NeMT"); + WorldGenFactory.a(WorldGenNetherPiece13.class, "NeRC"); + WorldGenFactory.a(WorldGenNetherPiece14.class, "NeSR"); + WorldGenFactory.a(WorldGenNetherPiece15.class, "NeStart"); + } + + private static WorldGenNetherPiece b(WorldGenNetherPieceWeight worldgennetherpieces_worldgennetherpieceweight, List list, Random random, int i, int j, int k, EnumDirection enumdirection, int l) { + Class oclass = worldgennetherpieces_worldgennetherpieceweight.a; + Object object = null; + + if (oclass == WorldGenNetherPiece3.class) { + object = WorldGenNetherPiece3.a(list, random, i, j, k, enumdirection, l); + } else if (oclass == WorldGenNetherPiece1.class) { + object = WorldGenNetherPiece1.a(list, random, i, j, k, enumdirection, l); + } else if (oclass == WorldGenNetherPiece13.class) { + object = WorldGenNetherPiece13.a(list, random, i, j, k, enumdirection, l); + } else if (oclass == WorldGenNetherPiece14.class) { + object = WorldGenNetherPiece14.a(list, random, i, j, k, l, enumdirection); + } else if (oclass == WorldGenNetherPiece12.class) { + object = WorldGenNetherPiece12.a(list, random, i, j, k, l, enumdirection); + } else if (oclass == WorldGenNetherPiece6.class) { + object = WorldGenNetherPiece6.a(list, random, i, j, k, enumdirection, l); + } else if (oclass == WorldGenNetherPiece9.class) { + object = WorldGenNetherPiece9.a(list, random, i, j, k, enumdirection, l); + } else if (oclass == WorldGenNetherPiece10.class) { + object = WorldGenNetherPiece10.a(list, random, i, j, k, enumdirection, l); + } else if (oclass == WorldGenNetherPiece8.class) { + object = WorldGenNetherPiece8.a(list, random, i, j, k, enumdirection, l); + } else if (oclass == WorldGenNetherPiece4.class) { + object = WorldGenNetherPiece4.a(list, random, i, j, k, enumdirection, l); + } else if (oclass == WorldGenNetherPiece5.class) { + object = WorldGenNetherPiece5.a(list, random, i, j, k, enumdirection, l); + } else if (oclass == WorldGenNetherPiece7.class) { + object = WorldGenNetherPiece7.a(list, random, i, j, k, enumdirection, l); + } else if (oclass == WorldGenNetherPiece11.class) { + object = WorldGenNetherPiece11.a(list, random, i, j, k, enumdirection, l); + } + + return (WorldGenNetherPiece) object; + } + + static class SyntheticClass_1 { + + static final int[] a = new int[EnumDirection.values().length]; + + static { + try { + SyntheticClass_1.a[EnumDirection.NORTH.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.a[EnumDirection.SOUTH.ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.a[EnumDirection.WEST.ordinal()] = 3; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.a[EnumDirection.EAST.ordinal()] = 4; + } catch (NoSuchFieldError ignored) { + } + + } + } + + public static class WorldGenNetherPiece5 extends WorldGenNetherPiece { + + public WorldGenNetherPiece5() { + } + + public WorldGenNetherPiece5(int i, Random random, StructureBoundingBox structureboundingbox, EnumDirection enumdirection) { + super(i); + this.m = enumdirection; + this.l = structureboundingbox; + } + + public void a(StructurePiece structurepiece, List list, Random random) { + byte b0 = 1; + + if (this.m == EnumDirection.WEST || this.m == EnumDirection.NORTH) { + b0 = 5; + } + + this.b((WorldGenNetherPiece15) structurepiece, list, random, 0, b0, random.nextInt(8) > 0); + this.c((WorldGenNetherPiece15) structurepiece, list, random, 0, b0, random.nextInt(8) > 0); + } + + public static WorldGenNetherPiece5 a(List list, Random random, int i, int j, int k, EnumDirection enumdirection, int l) { + StructureBoundingBox structureboundingbox = StructureBoundingBox.a(i, j, k, -3, 0, 0, 9, 7, 9, enumdirection); + + return a(structureboundingbox) && StructurePiece.a(list, structureboundingbox) == null ? new WorldGenNetherPiece5(l, random, structureboundingbox, enumdirection) : null; + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + this.a(world, structureboundingbox, 0, 0, 0, 8, 1, 8, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 0, 2, 0, 8, 5, 8, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, 0, 6, 0, 8, 6, 5, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 0, 2, 0, 2, 5, 0, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 6, 2, 0, 8, 5, 0, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 1, 3, 0, 1, 4, 0, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + this.a(world, structureboundingbox, 7, 3, 0, 7, 4, 0, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + this.a(world, structureboundingbox, 0, 2, 4, 8, 2, 8, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 1, 1, 4, 2, 2, 4, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, 6, 1, 4, 7, 2, 4, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, 0, 3, 8, 8, 3, 8, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + this.a(world, structureboundingbox, 0, 3, 6, 0, 3, 7, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + this.a(world, structureboundingbox, 8, 3, 6, 8, 3, 7, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + this.a(world, structureboundingbox, 0, 3, 4, 0, 5, 5, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 8, 3, 4, 8, 5, 5, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 1, 3, 5, 2, 5, 5, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 6, 3, 5, 7, 5, 5, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 1, 4, 5, 1, 5, 5, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + this.a(world, structureboundingbox, 7, 4, 5, 7, 5, 5, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + + for (int i = 0; i <= 5; ++i) { + for (int j = 0; j <= 8; ++j) { + this.b(world, Blocks.NETHER_BRICK.getBlockData(), j, -1, i, structureboundingbox); + } + } + + return true; + } + } + + public static class WorldGenNetherPiece4 extends WorldGenNetherPiece { + + public WorldGenNetherPiece4() { + } + + public WorldGenNetherPiece4(int i, Random random, StructureBoundingBox structureboundingbox, EnumDirection enumdirection) { + super(i); + this.m = enumdirection; + this.l = structureboundingbox; + } + + public void a(StructurePiece structurepiece, List list, Random random) { + this.a((WorldGenNetherPiece15) structurepiece, list, random, 1, 0, true); + } + + public static WorldGenNetherPiece4 a(List list, Random random, int i, int j, int k, EnumDirection enumdirection, int l) { + StructureBoundingBox structureboundingbox = StructureBoundingBox.a(i, j, k, -1, -7, 0, 5, 14, 10, enumdirection); + + return a(structureboundingbox) && StructurePiece.a(list, structureboundingbox) == null ? new WorldGenNetherPiece4(l, random, structureboundingbox, enumdirection) : null; + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + int i = this.a(Blocks.NETHER_BRICK_STAIRS, 2); + + for (int j = 0; j <= 9; ++j) { + int k = Math.max(1, 7 - j); + int l = Math.min(Math.max(k + 5, 14 - j), 13); + int i1 = j; + + this.a(world, structureboundingbox, 0, 0, j, 4, k, j, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 1, k + 1, j, 3, l - 1, j, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + if (j <= 6) { + this.a(world, Blocks.NETHER_BRICK_STAIRS.fromLegacyData(i), 1, k + 1, j, structureboundingbox); + this.a(world, Blocks.NETHER_BRICK_STAIRS.fromLegacyData(i), 2, k + 1, j, structureboundingbox); + this.a(world, Blocks.NETHER_BRICK_STAIRS.fromLegacyData(i), 3, k + 1, j, structureboundingbox); + } + + this.a(world, structureboundingbox, 0, l, j, 4, l, j, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 0, k + 1, j, 0, l - 1, j, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 4, k + 1, j, 4, l - 1, j, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + if ((j & 1) == 0) { + this.a(world, structureboundingbox, 0, k + 2, j, 0, k + 3, j, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + this.a(world, structureboundingbox, 4, k + 2, j, 4, k + 3, j, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + } + + for (int j1 = 0; j1 <= 4; ++j1) { + this.b(world, Blocks.NETHER_BRICK.getBlockData(), j1, -1, i1, structureboundingbox); + } + } + + return true; + } + } + + public static class WorldGenNetherPiece8 extends WorldGenNetherPiece { + + private boolean b; + + public WorldGenNetherPiece8() { + } + + public WorldGenNetherPiece8(int i, Random random, StructureBoundingBox structureboundingbox, EnumDirection enumdirection) { + super(i); + this.m = enumdirection; + this.l = structureboundingbox; + this.b = random.nextInt(3) == 0; + } + + protected void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + this.b = nbttagcompound.getBoolean("Chest"); + } + + protected void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + nbttagcompound.setBoolean("Chest", this.b); + } + + public void a(StructurePiece structurepiece, List list, Random random) { + this.b((WorldGenNetherPiece15) structurepiece, list, random, 0, 1, true); + } + + public static WorldGenNetherPiece8 a(List list, Random random, int i, int j, int k, EnumDirection enumdirection, int l) { + StructureBoundingBox structureboundingbox = StructureBoundingBox.a(i, j, k, -1, 0, 0, 5, 7, 5, enumdirection); + + return a(structureboundingbox) && StructurePiece.a(list, structureboundingbox) == null ? new WorldGenNetherPiece8(l, random, structureboundingbox, enumdirection) : null; + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + this.a(world, structureboundingbox, 0, 0, 0, 4, 1, 4, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 0, 2, 0, 4, 5, 4, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, 4, 2, 0, 4, 5, 4, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 4, 3, 1, 4, 4, 1, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + this.a(world, structureboundingbox, 4, 3, 3, 4, 4, 3, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + this.a(world, structureboundingbox, 0, 2, 0, 0, 5, 0, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 0, 2, 4, 3, 5, 4, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 1, 3, 4, 1, 4, 4, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 3, 3, 4, 3, 4, 4, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + if (this.b && structureboundingbox.b(this.a(3, 3), this.d(2), this.b(3, 3))) { + this.b = false; + this.a(world, structureboundingbox, random, 3, 2, 3, WorldGenNetherPiece8.a, 2 + random.nextInt(4)); + } + + this.a(world, structureboundingbox, 0, 6, 0, 4, 6, 4, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + + for (int i = 0; i <= 4; ++i) { + for (int j = 0; j <= 4; ++j) { + this.b(world, Blocks.NETHER_BRICK.getBlockData(), i, -1, j, structureboundingbox); + } + } + + return true; + } + } + + public static class WorldGenNetherPiece10 extends WorldGenNetherPiece { + + private boolean b; + + public WorldGenNetherPiece10() { + } + + public WorldGenNetherPiece10(int i, Random random, StructureBoundingBox structureboundingbox, EnumDirection enumdirection) { + super(i); + this.m = enumdirection; + this.l = structureboundingbox; + this.b = random.nextInt(3) == 0; + } + + protected void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + this.b = nbttagcompound.getBoolean("Chest"); + } + + protected void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + nbttagcompound.setBoolean("Chest", this.b); + } + + public void a(StructurePiece structurepiece, List list, Random random) { + this.c((WorldGenNetherPiece15) structurepiece, list, random, 0, 1, true); + } + + public static WorldGenNetherPiece10 a(List list, Random random, int i, int j, int k, EnumDirection enumdirection, int l) { + StructureBoundingBox structureboundingbox = StructureBoundingBox.a(i, j, k, -1, 0, 0, 5, 7, 5, enumdirection); + + return a(structureboundingbox) && StructurePiece.a(list, structureboundingbox) == null ? new WorldGenNetherPiece10(l, random, structureboundingbox, enumdirection) : null; + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + this.a(world, structureboundingbox, 0, 0, 0, 4, 1, 4, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 0, 2, 0, 4, 5, 4, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, 0, 2, 0, 0, 5, 4, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 0, 3, 1, 0, 4, 1, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + this.a(world, structureboundingbox, 0, 3, 3, 0, 4, 3, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + this.a(world, structureboundingbox, 4, 2, 0, 4, 5, 0, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 1, 2, 4, 4, 5, 4, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 1, 3, 4, 1, 4, 4, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 3, 3, 4, 3, 4, 4, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + if (this.b && structureboundingbox.b(this.a(1, 3), this.d(2), this.b(1, 3))) { + this.b = false; + this.a(world, structureboundingbox, random, 1, 2, 3, WorldGenNetherPiece10.a, 2 + random.nextInt(4)); + } + + this.a(world, structureboundingbox, 0, 6, 0, 4, 6, 4, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + + for (int i = 0; i <= 4; ++i) { + for (int j = 0; j <= 4; ++j) { + this.b(world, Blocks.NETHER_BRICK.getBlockData(), i, -1, j, structureboundingbox); + } + } + + return true; + } + } + + public static class WorldGenNetherPiece7 extends WorldGenNetherPiece { + + public WorldGenNetherPiece7() { + } + + public WorldGenNetherPiece7(int i, Random random, StructureBoundingBox structureboundingbox, EnumDirection enumdirection) { + super(i); + this.m = enumdirection; + this.l = structureboundingbox; + } + + public void a(StructurePiece structurepiece, List list, Random random) { + this.a((WorldGenNetherPiece15) structurepiece, list, random, 1, 0, true); + this.b((WorldGenNetherPiece15) structurepiece, list, random, 0, 1, true); + this.c((WorldGenNetherPiece15) structurepiece, list, random, 0, 1, true); + } + + public static WorldGenNetherPiece7 a(List list, Random random, int i, int j, int k, EnumDirection enumdirection, int l) { + StructureBoundingBox structureboundingbox = StructureBoundingBox.a(i, j, k, -1, 0, 0, 5, 7, 5, enumdirection); + + return a(structureboundingbox) && StructurePiece.a(list, structureboundingbox) == null ? new WorldGenNetherPiece7(l, random, structureboundingbox, enumdirection) : null; + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + this.a(world, structureboundingbox, 0, 0, 0, 4, 1, 4, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 0, 2, 0, 4, 5, 4, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, 0, 2, 0, 0, 5, 0, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 4, 2, 0, 4, 5, 0, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 0, 2, 4, 0, 5, 4, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 4, 2, 4, 4, 5, 4, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 0, 6, 0, 4, 6, 4, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + + for (int i = 0; i <= 4; ++i) { + for (int j = 0; j <= 4; ++j) { + this.b(world, Blocks.NETHER_BRICK.getBlockData(), i, -1, j, structureboundingbox); + } + } + + return true; + } + } + + public static class WorldGenNetherPiece9 extends WorldGenNetherPiece { + + public WorldGenNetherPiece9() { + } + + public WorldGenNetherPiece9(int i, Random random, StructureBoundingBox structureboundingbox, EnumDirection enumdirection) { + super(i); + this.m = enumdirection; + this.l = structureboundingbox; + } + + public void a(StructurePiece structurepiece, List list, Random random) { + this.a((WorldGenNetherPiece15) structurepiece, list, random, 1, 0, true); + } + + public static WorldGenNetherPiece9 a(List list, Random random, int i, int j, int k, EnumDirection enumdirection, int l) { + StructureBoundingBox structureboundingbox = StructureBoundingBox.a(i, j, k, -1, 0, 0, 5, 7, 5, enumdirection); + + return a(structureboundingbox) && StructurePiece.a(list, structureboundingbox) == null ? new WorldGenNetherPiece9(l, random, structureboundingbox, enumdirection) : null; + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + this.a(world, structureboundingbox, 0, 0, 0, 4, 1, 4, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 0, 2, 0, 4, 5, 4, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, 0, 2, 0, 0, 5, 4, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 4, 2, 0, 4, 5, 4, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 0, 3, 1, 0, 4, 1, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + this.a(world, structureboundingbox, 0, 3, 3, 0, 4, 3, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + this.a(world, structureboundingbox, 4, 3, 1, 4, 4, 1, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + this.a(world, structureboundingbox, 4, 3, 3, 4, 4, 3, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + this.a(world, structureboundingbox, 0, 6, 0, 4, 6, 4, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + + for (int i = 0; i <= 4; ++i) { + for (int j = 0; j <= 4; ++j) { + this.b(world, Blocks.NETHER_BRICK.getBlockData(), i, -1, j, structureboundingbox); + } + } + + return true; + } + } + + public static class WorldGenNetherPiece11 extends WorldGenNetherPiece { + + public WorldGenNetherPiece11() { + } + + public WorldGenNetherPiece11(int i, Random random, StructureBoundingBox structureboundingbox, EnumDirection enumdirection) { + super(i); + this.m = enumdirection; + this.l = structureboundingbox; + } + + public void a(StructurePiece structurepiece, List list, Random random) { + this.a((WorldGenNetherPiece15) structurepiece, list, random, 5, 3, true); + this.a((WorldGenNetherPiece15) structurepiece, list, random, 5, 11, true); + } + + public static WorldGenNetherPiece11 a(List list, Random random, int i, int j, int k, EnumDirection enumdirection, int l) { + StructureBoundingBox structureboundingbox = StructureBoundingBox.a(i, j, k, -5, -3, 0, 13, 14, 13, enumdirection); + + return a(structureboundingbox) && StructurePiece.a(list, structureboundingbox) == null ? new WorldGenNetherPiece11(l, random, structureboundingbox, enumdirection) : null; + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + this.a(world, structureboundingbox, 0, 3, 0, 12, 4, 12, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 0, 5, 0, 12, 13, 12, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, 0, 5, 0, 1, 12, 12, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 11, 5, 0, 12, 12, 12, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 2, 5, 11, 4, 12, 12, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 8, 5, 11, 10, 12, 12, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 5, 9, 11, 7, 12, 12, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 2, 5, 0, 4, 12, 1, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 8, 5, 0, 10, 12, 1, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 5, 9, 0, 7, 12, 1, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 2, 11, 2, 10, 12, 10, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + + int i; + + for (i = 1; i <= 11; i += 2) { + this.a(world, structureboundingbox, i, 10, 0, i, 11, 0, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + this.a(world, structureboundingbox, i, 10, 12, i, 11, 12, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + this.a(world, structureboundingbox, 0, 10, i, 0, 11, i, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + this.a(world, structureboundingbox, 12, 10, i, 12, 11, i, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + this.a(world, Blocks.NETHER_BRICK.getBlockData(), i, 13, 0, structureboundingbox); + this.a(world, Blocks.NETHER_BRICK.getBlockData(), i, 13, 12, structureboundingbox); + this.a(world, Blocks.NETHER_BRICK.getBlockData(), 0, 13, i, structureboundingbox); + this.a(world, Blocks.NETHER_BRICK.getBlockData(), 12, 13, i, structureboundingbox); + this.a(world, Blocks.NETHER_BRICK_FENCE.getBlockData(), i + 1, 13, 0, structureboundingbox); + this.a(world, Blocks.NETHER_BRICK_FENCE.getBlockData(), i + 1, 13, 12, structureboundingbox); + this.a(world, Blocks.NETHER_BRICK_FENCE.getBlockData(), 0, 13, i + 1, structureboundingbox); + this.a(world, Blocks.NETHER_BRICK_FENCE.getBlockData(), 12, 13, i + 1, structureboundingbox); + } + + this.a(world, Blocks.NETHER_BRICK_FENCE.getBlockData(), 0, 13, 0, structureboundingbox); + this.a(world, Blocks.NETHER_BRICK_FENCE.getBlockData(), 0, 13, 12, structureboundingbox); + this.a(world, Blocks.NETHER_BRICK_FENCE.getBlockData(), 0, 13, 0, structureboundingbox); + this.a(world, Blocks.NETHER_BRICK_FENCE.getBlockData(), 12, 13, 0, structureboundingbox); + + for (i = 3; i <= 9; i += 2) { + this.a(world, structureboundingbox, 1, 7, i, 1, 8, i, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + this.a(world, structureboundingbox, 11, 7, i, 11, 8, i, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + } + + i = this.a(Blocks.NETHER_BRICK_STAIRS, 3); + + int j; + int k; + int l; + + for (j = 0; j <= 6; ++j) { + k = j + 4; + + for (l = 5; l <= 7; ++l) { + this.a(world, Blocks.NETHER_BRICK_STAIRS.fromLegacyData(i), l, 5 + j, k, structureboundingbox); + } + + if (k >= 5 && k <= 8) { + this.a(world, structureboundingbox, 5, 5, k, 7, j + 4, k, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + } else if (k >= 9 && k <= 10) { + this.a(world, structureboundingbox, 5, 8, k, 7, j + 4, k, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + } + + if (j >= 1) { + this.a(world, structureboundingbox, 5, 6 + j, k, 7, 9 + j, k, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + } + } + + for (j = 5; j <= 7; ++j) { + this.a(world, Blocks.NETHER_BRICK_STAIRS.fromLegacyData(i), j, 12, 11, structureboundingbox); + } + + this.a(world, structureboundingbox, 5, 6, 7, 5, 7, 7, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + this.a(world, structureboundingbox, 7, 6, 7, 7, 7, 7, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + this.a(world, structureboundingbox, 5, 13, 12, 7, 13, 12, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, 2, 5, 2, 3, 5, 3, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 2, 5, 9, 3, 5, 10, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 2, 5, 4, 2, 5, 8, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 9, 5, 2, 10, 5, 3, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 9, 5, 9, 10, 5, 10, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 10, 5, 4, 10, 5, 8, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + j = this.a(Blocks.NETHER_BRICK_STAIRS, 0); + k = this.a(Blocks.NETHER_BRICK_STAIRS, 1); + this.a(world, Blocks.NETHER_BRICK_STAIRS.fromLegacyData(k), 4, 5, 2, structureboundingbox); + this.a(world, Blocks.NETHER_BRICK_STAIRS.fromLegacyData(k), 4, 5, 3, structureboundingbox); + this.a(world, Blocks.NETHER_BRICK_STAIRS.fromLegacyData(k), 4, 5, 9, structureboundingbox); + this.a(world, Blocks.NETHER_BRICK_STAIRS.fromLegacyData(k), 4, 5, 10, structureboundingbox); + this.a(world, Blocks.NETHER_BRICK_STAIRS.fromLegacyData(j), 8, 5, 2, structureboundingbox); + this.a(world, Blocks.NETHER_BRICK_STAIRS.fromLegacyData(j), 8, 5, 3, structureboundingbox); + this.a(world, Blocks.NETHER_BRICK_STAIRS.fromLegacyData(j), 8, 5, 9, structureboundingbox); + this.a(world, Blocks.NETHER_BRICK_STAIRS.fromLegacyData(j), 8, 5, 10, structureboundingbox); + this.a(world, structureboundingbox, 3, 4, 4, 4, 4, 8, Blocks.SOUL_SAND.getBlockData(), Blocks.SOUL_SAND.getBlockData(), false); + this.a(world, structureboundingbox, 8, 4, 4, 9, 4, 8, Blocks.SOUL_SAND.getBlockData(), Blocks.SOUL_SAND.getBlockData(), false); + this.a(world, structureboundingbox, 3, 5, 4, 4, 5, 8, Blocks.NETHER_WART.getBlockData(), Blocks.NETHER_WART.getBlockData(), false); + this.a(world, structureboundingbox, 8, 5, 4, 9, 5, 8, Blocks.NETHER_WART.getBlockData(), Blocks.NETHER_WART.getBlockData(), false); + this.a(world, structureboundingbox, 4, 2, 0, 8, 2, 12, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 0, 2, 4, 12, 2, 8, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 4, 0, 0, 8, 1, 3, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 4, 0, 9, 8, 1, 12, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 0, 0, 4, 3, 1, 8, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 9, 0, 4, 12, 1, 8, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + + int i1; + + for (l = 4; l <= 8; ++l) { + for (i1 = 0; i1 <= 2; ++i1) { + this.b(world, Blocks.NETHER_BRICK.getBlockData(), l, -1, i1, structureboundingbox); + this.b(world, Blocks.NETHER_BRICK.getBlockData(), l, -1, 12 - i1, structureboundingbox); + } + } + + for (l = 0; l <= 2; ++l) { + for (i1 = 4; i1 <= 8; ++i1) { + this.b(world, Blocks.NETHER_BRICK.getBlockData(), l, -1, i1, structureboundingbox); + this.b(world, Blocks.NETHER_BRICK.getBlockData(), 12 - l, -1, i1, structureboundingbox); + } + } + + return true; + } + } + + public static class WorldGenNetherPiece6 extends WorldGenNetherPiece { + + public WorldGenNetherPiece6() { + } + + public WorldGenNetherPiece6(int i, Random random, StructureBoundingBox structureboundingbox, EnumDirection enumdirection) { + super(i); + this.m = enumdirection; + this.l = structureboundingbox; + } + + public void a(StructurePiece structurepiece, List list, Random random) { + this.a((WorldGenNetherPiece15) structurepiece, list, random, 5, 3, true); + } + + public static WorldGenNetherPiece6 a(List list, Random random, int i, int j, int k, EnumDirection enumdirection, int l) { + StructureBoundingBox structureboundingbox = StructureBoundingBox.a(i, j, k, -5, -3, 0, 13, 14, 13, enumdirection); + + return a(structureboundingbox) && StructurePiece.a(list, structureboundingbox) == null ? new WorldGenNetherPiece6(l, random, structureboundingbox, enumdirection) : null; + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + this.a(world, structureboundingbox, 0, 3, 0, 12, 4, 12, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 0, 5, 0, 12, 13, 12, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, 0, 5, 0, 1, 12, 12, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 11, 5, 0, 12, 12, 12, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 2, 5, 11, 4, 12, 12, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 8, 5, 11, 10, 12, 12, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 5, 9, 11, 7, 12, 12, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 2, 5, 0, 4, 12, 1, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 8, 5, 0, 10, 12, 1, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 5, 9, 0, 7, 12, 1, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 2, 11, 2, 10, 12, 10, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 5, 8, 0, 7, 8, 0, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + + int i; + + for (i = 1; i <= 11; i += 2) { + this.a(world, structureboundingbox, i, 10, 0, i, 11, 0, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + this.a(world, structureboundingbox, i, 10, 12, i, 11, 12, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + this.a(world, structureboundingbox, 0, 10, i, 0, 11, i, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + this.a(world, structureboundingbox, 12, 10, i, 12, 11, i, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + this.a(world, Blocks.NETHER_BRICK.getBlockData(), i, 13, 0, structureboundingbox); + this.a(world, Blocks.NETHER_BRICK.getBlockData(), i, 13, 12, structureboundingbox); + this.a(world, Blocks.NETHER_BRICK.getBlockData(), 0, 13, i, structureboundingbox); + this.a(world, Blocks.NETHER_BRICK.getBlockData(), 12, 13, i, structureboundingbox); + this.a(world, Blocks.NETHER_BRICK_FENCE.getBlockData(), i + 1, 13, 0, structureboundingbox); + this.a(world, Blocks.NETHER_BRICK_FENCE.getBlockData(), i + 1, 13, 12, structureboundingbox); + this.a(world, Blocks.NETHER_BRICK_FENCE.getBlockData(), 0, 13, i + 1, structureboundingbox); + this.a(world, Blocks.NETHER_BRICK_FENCE.getBlockData(), 12, 13, i + 1, structureboundingbox); + } + + this.a(world, Blocks.NETHER_BRICK_FENCE.getBlockData(), 0, 13, 0, structureboundingbox); + this.a(world, Blocks.NETHER_BRICK_FENCE.getBlockData(), 0, 13, 12, structureboundingbox); + this.a(world, Blocks.NETHER_BRICK_FENCE.getBlockData(), 0, 13, 0, structureboundingbox); + this.a(world, Blocks.NETHER_BRICK_FENCE.getBlockData(), 12, 13, 0, structureboundingbox); + + for (i = 3; i <= 9; i += 2) { + this.a(world, structureboundingbox, 1, 7, i, 1, 8, i, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + this.a(world, structureboundingbox, 11, 7, i, 11, 8, i, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + } + + this.a(world, structureboundingbox, 4, 2, 0, 8, 2, 12, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 0, 2, 4, 12, 2, 8, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 4, 0, 0, 8, 1, 3, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 4, 0, 9, 8, 1, 12, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 0, 0, 4, 3, 1, 8, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 9, 0, 4, 12, 1, 8, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + + int j; + + for (i = 4; i <= 8; ++i) { + for (j = 0; j <= 2; ++j) { + this.b(world, Blocks.NETHER_BRICK.getBlockData(), i, -1, j, structureboundingbox); + this.b(world, Blocks.NETHER_BRICK.getBlockData(), i, -1, 12 - j, structureboundingbox); + } + } + + for (i = 0; i <= 2; ++i) { + for (j = 4; j <= 8; ++j) { + this.b(world, Blocks.NETHER_BRICK.getBlockData(), i, -1, j, structureboundingbox); + this.b(world, Blocks.NETHER_BRICK.getBlockData(), 12 - i, -1, j, structureboundingbox); + } + } + + this.a(world, structureboundingbox, 5, 5, 5, 7, 5, 7, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 6, 1, 6, 6, 4, 6, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, Blocks.NETHER_BRICK.getBlockData(), 6, 0, 6, structureboundingbox); + this.a(world, Blocks.FLOWING_LAVA.getBlockData(), 6, 5, 6, structureboundingbox); + + int x = a(6, 6), y = d(5), z = b(6, 6); + if (structureboundingbox.b(x, y, z)) { + world.a(Blocks.FLOWING_LAVA, new BlockPosition(x, y, z), random); + } + + return true; + } + } + + public static class WorldGenNetherPiece12 extends WorldGenNetherPiece { + + private boolean b; + + public WorldGenNetherPiece12() { + } + + public WorldGenNetherPiece12(int i, Random random, StructureBoundingBox structureboundingbox, EnumDirection enumdirection) { + super(i); + this.m = enumdirection; + this.l = structureboundingbox; + } + + protected void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + this.b = nbttagcompound.getBoolean("Mob"); + } + + protected void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + nbttagcompound.setBoolean("Mob", this.b); + } + + public static WorldGenNetherPiece12 a(List list, Random random, int i, int j, int k, int l, EnumDirection enumdirection) { + StructureBoundingBox structureboundingbox = StructureBoundingBox.a(i, j, k, -2, 0, 0, 7, 8, 9, enumdirection); + + return a(structureboundingbox) && StructurePiece.a(list, structureboundingbox) == null ? new WorldGenNetherPiece12(l, random, structureboundingbox, enumdirection) : null; + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + this.a(world, structureboundingbox, 0, 2, 0, 6, 7, 7, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, 1, 0, 0, 5, 1, 7, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 1, 2, 1, 5, 2, 7, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 1, 3, 2, 5, 3, 7, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 1, 4, 3, 5, 4, 7, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 1, 2, 0, 1, 4, 2, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 5, 2, 0, 5, 4, 2, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 1, 5, 2, 1, 5, 3, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 5, 5, 2, 5, 5, 3, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 0, 5, 3, 0, 5, 8, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 6, 5, 3, 6, 5, 8, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 1, 5, 8, 5, 5, 8, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, Blocks.NETHER_BRICK_FENCE.getBlockData(), 1, 6, 3, structureboundingbox); + this.a(world, Blocks.NETHER_BRICK_FENCE.getBlockData(), 5, 6, 3, structureboundingbox); + this.a(world, structureboundingbox, 0, 6, 3, 0, 6, 8, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + this.a(world, structureboundingbox, 6, 6, 3, 6, 6, 8, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + this.a(world, structureboundingbox, 1, 6, 8, 5, 7, 8, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + this.a(world, structureboundingbox, 2, 8, 8, 4, 8, 8, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + if (!this.b) { + int x = a(3, 5), y = d(5), z = b(3, 5); + if (structureboundingbox.b(x, y, z)) { + BlockPosition blockposition = new BlockPosition(x, y, z); + this.b = true; + world.setTypeAndData(blockposition, Blocks.MOB_SPAWNER.getBlockData(), 2); + TileEntity tileentity = world.getTileEntity(blockposition); + + if (tileentity instanceof TileEntityMobSpawner) { + ((TileEntityMobSpawner) tileentity).getSpawner().setMobName("Blaze"); + } + } + } + + for (int i = 0; i <= 6; ++i) { + for (int j = 0; j <= 6; ++j) { + this.b(world, Blocks.NETHER_BRICK.getBlockData(), i, -1, j, structureboundingbox); + } + } + + return true; + } + } + + public static class WorldGenNetherPiece14 extends WorldGenNetherPiece { + + public WorldGenNetherPiece14() { + } + + public WorldGenNetherPiece14(int i, Random random, StructureBoundingBox structureboundingbox, EnumDirection enumdirection) { + super(i); + this.m = enumdirection; + this.l = structureboundingbox; + } + + public void a(StructurePiece structurepiece, List list, Random random) { + this.c((WorldGenNetherPiece15) structurepiece, list, random, 6, 2, false); + } + + public static WorldGenNetherPiece14 a(List list, Random random, int i, int j, int k, int l, EnumDirection enumdirection) { + StructureBoundingBox structureboundingbox = StructureBoundingBox.a(i, j, k, -2, 0, 0, 7, 11, 7, enumdirection); + + return a(structureboundingbox) && StructurePiece.a(list, structureboundingbox) == null ? new WorldGenNetherPiece14(l, random, structureboundingbox, enumdirection) : null; + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + this.a(world, structureboundingbox, 0, 0, 0, 6, 1, 6, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 0, 2, 0, 6, 10, 6, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, 0, 2, 0, 1, 8, 0, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 5, 2, 0, 6, 8, 0, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 0, 2, 1, 0, 8, 6, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 6, 2, 1, 6, 8, 6, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 1, 2, 6, 5, 8, 6, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 0, 3, 2, 0, 5, 4, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + this.a(world, structureboundingbox, 6, 3, 2, 6, 5, 2, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + this.a(world, structureboundingbox, 6, 3, 4, 6, 5, 4, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + this.a(world, Blocks.NETHER_BRICK.getBlockData(), 5, 2, 5, structureboundingbox); + this.a(world, structureboundingbox, 4, 2, 5, 4, 3, 5, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 3, 2, 5, 3, 4, 5, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 2, 2, 5, 2, 5, 5, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 1, 2, 5, 1, 6, 5, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 1, 7, 1, 5, 7, 4, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 6, 8, 2, 6, 8, 4, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, 2, 6, 0, 4, 8, 0, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 2, 5, 0, 4, 5, 0, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + + for (int i = 0; i <= 6; ++i) { + for (int j = 0; j <= 6; ++j) { + this.b(world, Blocks.NETHER_BRICK.getBlockData(), i, -1, j, structureboundingbox); + } + } + + return true; + } + } + + public static class WorldGenNetherPiece13 extends WorldGenNetherPiece { + + public WorldGenNetherPiece13() { + } + + public WorldGenNetherPiece13(int i, Random random, StructureBoundingBox structureboundingbox, EnumDirection enumdirection) { + super(i); + this.m = enumdirection; + this.l = structureboundingbox; + } + + public void a(StructurePiece structurepiece, List list, Random random) { + this.a((WorldGenNetherPiece15) structurepiece, list, random, 2, 0, false); + this.b((WorldGenNetherPiece15) structurepiece, list, random, 0, 2, false); + this.c((WorldGenNetherPiece15) structurepiece, list, random, 0, 2, false); + } + + public static WorldGenNetherPiece13 a(List list, Random random, int i, int j, int k, EnumDirection enumdirection, int l) { + StructureBoundingBox structureboundingbox = StructureBoundingBox.a(i, j, k, -2, 0, 0, 7, 9, 7, enumdirection); + + return a(structureboundingbox) && StructurePiece.a(list, structureboundingbox) == null ? new WorldGenNetherPiece13(l, random, structureboundingbox, enumdirection) : null; + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + this.a(world, structureboundingbox, 0, 0, 0, 6, 1, 6, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 0, 2, 0, 6, 7, 6, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, 0, 2, 0, 1, 6, 0, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 0, 2, 6, 1, 6, 6, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 5, 2, 0, 6, 6, 0, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 5, 2, 6, 6, 6, 6, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 0, 2, 0, 0, 6, 1, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 0, 2, 5, 0, 6, 6, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 6, 2, 0, 6, 6, 1, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 6, 2, 5, 6, 6, 6, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 2, 6, 0, 4, 6, 0, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 2, 5, 0, 4, 5, 0, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + this.a(world, structureboundingbox, 2, 6, 6, 4, 6, 6, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 2, 5, 6, 4, 5, 6, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + this.a(world, structureboundingbox, 0, 6, 2, 0, 6, 4, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 0, 5, 2, 0, 5, 4, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + this.a(world, structureboundingbox, 6, 6, 2, 6, 6, 4, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 6, 5, 2, 6, 5, 4, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + + for (int i = 0; i <= 6; ++i) { + for (int j = 0; j <= 6; ++j) { + this.b(world, Blocks.NETHER_BRICK.getBlockData(), i, -1, j, structureboundingbox); + } + } + + return true; + } + } + + public static class WorldGenNetherPiece1 extends WorldGenNetherPiece { + + public WorldGenNetherPiece1() { + } + + public WorldGenNetherPiece1(int i, Random random, StructureBoundingBox structureboundingbox, EnumDirection enumdirection) { + super(i); + this.m = enumdirection; + this.l = structureboundingbox; + } + + protected WorldGenNetherPiece1(Random random, int i, int j) { + super(0); + this.m = EnumDirection.EnumDirectionLimit.HORIZONTAL.a(random); + switch (SyntheticClass_1.a[this.m.ordinal()]) { + case 1: + case 2: + this.l = new StructureBoundingBox(i, 64, j, i + 19 - 1, 73, j + 19 - 1); + break; + + default: + this.l = new StructureBoundingBox(i, 64, j, i + 19 - 1, 73, j + 19 - 1); + } + + } + + public void a(StructurePiece structurepiece, List list, Random random) { + this.a((WorldGenNetherPiece15) structurepiece, list, random, 8, 3, false); + this.b((WorldGenNetherPiece15) structurepiece, list, random, 3, 8, false); + this.c((WorldGenNetherPiece15) structurepiece, list, random, 3, 8, false); + } + + public static WorldGenNetherPiece1 a(List list, Random random, int i, int j, int k, EnumDirection enumdirection, int l) { + StructureBoundingBox structureboundingbox = StructureBoundingBox.a(i, j, k, -8, -3, 0, 19, 10, 19, enumdirection); + + return a(structureboundingbox) && StructurePiece.a(list, structureboundingbox) == null ? new WorldGenNetherPiece1(l, random, structureboundingbox, enumdirection) : null; + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + this.a(world, structureboundingbox, 7, 3, 0, 11, 4, 18, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 0, 3, 7, 18, 4, 11, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 8, 5, 0, 10, 7, 18, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, 0, 5, 8, 18, 7, 10, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, 7, 5, 0, 7, 5, 7, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 7, 5, 11, 7, 5, 18, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 11, 5, 0, 11, 5, 7, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 11, 5, 11, 11, 5, 18, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 0, 5, 7, 7, 5, 7, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 11, 5, 7, 18, 5, 7, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 0, 5, 11, 7, 5, 11, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 11, 5, 11, 18, 5, 11, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 7, 2, 0, 11, 2, 5, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 7, 2, 13, 11, 2, 18, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 7, 0, 0, 11, 1, 3, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 7, 0, 15, 11, 1, 18, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + + int i; + int j; + + for (i = 7; i <= 11; ++i) { + for (j = 0; j <= 2; ++j) { + this.b(world, Blocks.NETHER_BRICK.getBlockData(), i, -1, j, structureboundingbox); + this.b(world, Blocks.NETHER_BRICK.getBlockData(), i, -1, 18 - j, structureboundingbox); + } + } + + this.a(world, structureboundingbox, 0, 2, 7, 5, 2, 11, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 13, 2, 7, 18, 2, 11, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 0, 0, 7, 3, 1, 11, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 15, 0, 7, 18, 1, 11, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + + for (i = 0; i <= 2; ++i) { + for (j = 7; j <= 11; ++j) { + this.b(world, Blocks.NETHER_BRICK.getBlockData(), i, -1, j, structureboundingbox); + this.b(world, Blocks.NETHER_BRICK.getBlockData(), 18 - i, -1, j, structureboundingbox); + } + } + + return true; + } + } + + public static class WorldGenNetherPiece2 extends WorldGenNetherPiece { + + private int b; + + public WorldGenNetherPiece2() { + } + + public WorldGenNetherPiece2(int i, Random random, StructureBoundingBox structureboundingbox, EnumDirection enumdirection) { + super(i); + this.m = enumdirection; + this.l = structureboundingbox; + this.b = random.nextInt(); + } + + public static WorldGenNetherPiece2 a(List list, Random random, int i, int j, int k, EnumDirection enumdirection, int l) { + StructureBoundingBox structureboundingbox = StructureBoundingBox.a(i, j, k, -1, -3, 0, 5, 10, 8, enumdirection); + + return a(structureboundingbox) && StructurePiece.a(list, structureboundingbox) == null ? new WorldGenNetherPiece2(l, random, structureboundingbox, enumdirection) : null; + } + + protected void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + this.b = nbttagcompound.getInt("Seed"); + } + + protected void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + nbttagcompound.setInt("Seed", this.b); + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + Random random1 = new Random(this.b); + + int i; + int j; + int k; + + for (i = 0; i <= 4; ++i) { + for (j = 3; j <= 4; ++j) { + k = random1.nextInt(8); + this.a(world, structureboundingbox, i, j, 0, i, j, k, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + } + } + + i = random1.nextInt(8); + this.a(world, structureboundingbox, 0, 5, 0, 0, 5, i, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + i = random1.nextInt(8); + this.a(world, structureboundingbox, 4, 5, 0, 4, 5, i, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + + for (i = 0; i <= 4; ++i) { + j = random1.nextInt(5); + this.a(world, structureboundingbox, i, 2, 0, i, 2, j, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + } + + for (i = 0; i <= 4; ++i) { + for (j = 0; j <= 1; ++j) { + k = random1.nextInt(3); + this.a(world, structureboundingbox, i, j, 0, i, j, k, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + } + } + + return true; + } + } + + public static class WorldGenNetherPiece3 extends WorldGenNetherPiece { + + public WorldGenNetherPiece3() { + } + + public WorldGenNetherPiece3(int i, Random random, StructureBoundingBox structureboundingbox, EnumDirection enumdirection) { + super(i); + this.m = enumdirection; + this.l = structureboundingbox; + } + + public void a(StructurePiece structurepiece, List list, Random random) { + this.a((WorldGenNetherPiece15) structurepiece, list, random, 1, 3, false); + } + + public static WorldGenNetherPiece3 a(List list, Random random, int i, int j, int k, EnumDirection enumdirection, int l) { + StructureBoundingBox structureboundingbox = StructureBoundingBox.a(i, j, k, -1, -3, 0, 5, 10, 19, enumdirection); + + return a(structureboundingbox) && StructurePiece.a(list, structureboundingbox) == null ? new WorldGenNetherPiece3(l, random, structureboundingbox, enumdirection) : null; + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + this.a(world, structureboundingbox, 0, 3, 0, 4, 4, 18, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 1, 5, 0, 3, 7, 18, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, 0, 5, 0, 0, 5, 18, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 4, 5, 0, 4, 5, 18, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 0, 2, 0, 4, 2, 5, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 0, 2, 13, 4, 2, 18, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 0, 0, 0, 4, 1, 3, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + this.a(world, structureboundingbox, 0, 0, 15, 4, 1, 18, Blocks.NETHER_BRICK.getBlockData(), Blocks.NETHER_BRICK.getBlockData(), false); + + for (int i = 0; i <= 4; ++i) { + for (int j = 0; j <= 2; ++j) { + this.b(world, Blocks.NETHER_BRICK.getBlockData(), i, -1, j, structureboundingbox); + this.b(world, Blocks.NETHER_BRICK.getBlockData(), i, -1, 18 - j, structureboundingbox); + } + } + + this.a(world, structureboundingbox, 0, 1, 1, 0, 4, 1, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + this.a(world, structureboundingbox, 0, 3, 4, 0, 4, 4, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + this.a(world, structureboundingbox, 0, 3, 14, 0, 4, 14, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + this.a(world, structureboundingbox, 0, 1, 17, 0, 4, 17, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + this.a(world, structureboundingbox, 4, 1, 1, 4, 4, 1, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + this.a(world, structureboundingbox, 4, 3, 4, 4, 4, 4, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + this.a(world, structureboundingbox, 4, 3, 14, 4, 4, 14, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + this.a(world, structureboundingbox, 4, 1, 17, 4, 4, 17, Blocks.NETHER_BRICK_FENCE.getBlockData(), Blocks.NETHER_BRICK_FENCE.getBlockData(), false); + return true; + } + } + + public static class WorldGenNetherPiece15 extends WorldGenNetherPiece1 { + + public WorldGenNetherPieceWeight b; + public List c; + public List d; + public List e = Lists.newArrayList(); + + public WorldGenNetherPiece15() { + } + + public WorldGenNetherPiece15(Random random, int i, int j) { + super(random, i, j); + this.c = Lists.newArrayList(); + WorldGenNetherPieceWeight[] aworldgennetherpieces_worldgennetherpieceweight = WorldGenNetherPieces.a; + int k = aworldgennetherpieces_worldgennetherpieceweight.length; + + int l; + WorldGenNetherPieceWeight worldgennetherpieces_worldgennetherpieceweight; + + for (l = 0; l < k; ++l) { + worldgennetherpieces_worldgennetherpieceweight = aworldgennetherpieces_worldgennetherpieceweight[l]; + worldgennetherpieces_worldgennetherpieceweight.c = 0; + this.c.add(worldgennetherpieces_worldgennetherpieceweight); + } + + this.d = Lists.newArrayList(); + aworldgennetherpieces_worldgennetherpieceweight = WorldGenNetherPieces.b; + k = aworldgennetherpieces_worldgennetherpieceweight.length; + + for (l = 0; l < k; ++l) { + worldgennetherpieces_worldgennetherpieceweight = aworldgennetherpieces_worldgennetherpieceweight[l]; + worldgennetherpieces_worldgennetherpieceweight.c = 0; + this.d.add(worldgennetherpieces_worldgennetherpieceweight); + } + + } + + protected void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + } + + protected void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + } + } + + abstract static class WorldGenNetherPiece extends StructurePiece { + + protected static final List a = Lists.newArrayList(new StructurePieceTreasure(Items.DIAMOND, 0, 1, 3, 5), new StructurePieceTreasure(Items.IRON_INGOT, 0, 1, 5, 5), new StructurePieceTreasure(Items.GOLD_INGOT, 0, 1, 3, 15), new StructurePieceTreasure(Items.GOLDEN_SWORD, 0, 1, 1, 5), new StructurePieceTreasure(Items.GOLDEN_CHESTPLATE, 0, 1, 1, 5), new StructurePieceTreasure(Items.FLINT_AND_STEEL, 0, 1, 1, 5), new StructurePieceTreasure(Items.NETHER_WART, 0, 3, 7, 5), new StructurePieceTreasure(Items.SADDLE, 0, 1, 1, 10), new StructurePieceTreasure(Items.GOLDEN_HORSE_ARMOR, 0, 1, 1, 8), new StructurePieceTreasure(Items.IRON_HORSE_ARMOR, 0, 1, 1, 5), new StructurePieceTreasure(Items.DIAMOND_HORSE_ARMOR, 0, 1, 1, 3), new StructurePieceTreasure(Item.getItemOf(Blocks.OBSIDIAN), 0, 2, 4, 2)); + + public WorldGenNetherPiece() { + } + + protected WorldGenNetherPiece(int i) { + super(i); + } + + protected void b(NBTTagCompound nbttagcompound) { + } + + protected void a(NBTTagCompound nbttagcompound) { + } + + private int a(List list) { + boolean flag = false; + int i = 0; + + WorldGenNetherPieceWeight worldgennetherpieces_worldgennetherpieceweight; + + for (Iterator iterator = list.iterator(); iterator.hasNext(); i += worldgennetherpieces_worldgennetherpieceweight.b) { + worldgennetherpieces_worldgennetherpieceweight = (WorldGenNetherPieceWeight) iterator.next(); + if (worldgennetherpieces_worldgennetherpieceweight.d > 0 && worldgennetherpieces_worldgennetherpieceweight.c < worldgennetherpieces_worldgennetherpieceweight.d) { + flag = true; + } + } + + return flag ? i : -1; + } + + private WorldGenNetherPiece a(WorldGenNetherPiece15 worldgennetherpieces_worldgennetherpiece15, List list, List list1, Random random, int i, int j, int k, EnumDirection enumdirection, int l) { + int i1 = this.a(list); + boolean flag = i1 > 0 && l <= 30; + int j1 = 0; + + while (j1 < 5 && flag) { + ++j1; + int k1 = random.nextInt(i1); + Iterator iterator = list.iterator(); + + while (iterator.hasNext()) { + WorldGenNetherPieceWeight worldgennetherpieces_worldgennetherpieceweight = (WorldGenNetherPieceWeight) iterator.next(); + + k1 -= worldgennetherpieces_worldgennetherpieceweight.b; + if (k1 < 0) { + if (!worldgennetherpieces_worldgennetherpieceweight.a(l) || worldgennetherpieces_worldgennetherpieceweight == worldgennetherpieces_worldgennetherpiece15.b && !worldgennetherpieces_worldgennetherpieceweight.e) { + break; + } + + WorldGenNetherPiece worldgennetherpieces_worldgennetherpiece = WorldGenNetherPieces.b(worldgennetherpieces_worldgennetherpieceweight, list1, random, i, j, k, enumdirection, l); + + if (worldgennetherpieces_worldgennetherpiece != null) { + ++worldgennetherpieces_worldgennetherpieceweight.c; + worldgennetherpieces_worldgennetherpiece15.b = worldgennetherpieces_worldgennetherpieceweight; + if (!worldgennetherpieces_worldgennetherpieceweight.a()) { + list.remove(worldgennetherpieces_worldgennetherpieceweight); + } + + return worldgennetherpieces_worldgennetherpiece; + } + } + } + } + + return WorldGenNetherPiece2.a(list1, random, i, j, k, enumdirection, l); + } + + private StructurePiece a(WorldGenNetherPiece15 worldgennetherpieces_worldgennetherpiece15, List list, Random random, int i, int j, int k, EnumDirection enumdirection, int l, boolean flag) { + if (Math.abs(i - worldgennetherpieces_worldgennetherpiece15.c().a) <= 112 && Math.abs(k - worldgennetherpieces_worldgennetherpiece15.c().c) <= 112) { + List list1 = worldgennetherpieces_worldgennetherpiece15.c; + + if (flag) { + list1 = worldgennetherpieces_worldgennetherpiece15.d; + } + + WorldGenNetherPiece worldgennetherpieces_worldgennetherpiece = this.a(worldgennetherpieces_worldgennetherpiece15, list1, list, random, i, j, k, enumdirection, l + 1); + + if (worldgennetherpieces_worldgennetherpiece != null) { + list.add(worldgennetherpieces_worldgennetherpiece); + worldgennetherpieces_worldgennetherpiece15.e.add(worldgennetherpieces_worldgennetherpiece); + } + + return worldgennetherpieces_worldgennetherpiece; + } else { + return WorldGenNetherPiece2.a(list, random, i, j, k, enumdirection, l); + } + } + + protected StructurePiece a(WorldGenNetherPiece15 worldgennetherpieces_worldgennetherpiece15, List list, Random random, int i, int j, boolean flag) { + if (this.m != null) { + switch (SyntheticClass_1.a[this.m.ordinal()]) { + case 1: + return this.a(worldgennetherpieces_worldgennetherpiece15, list, random, this.l.a + i, this.l.b + j, this.l.c - 1, this.m, this.d(), flag); + + case 2: + return this.a(worldgennetherpieces_worldgennetherpiece15, list, random, this.l.a + i, this.l.b + j, this.l.f + 1, this.m, this.d(), flag); + + case 3: + return this.a(worldgennetherpieces_worldgennetherpiece15, list, random, this.l.a - 1, this.l.b + j, this.l.c + i, this.m, this.d(), flag); + + case 4: + return this.a(worldgennetherpieces_worldgennetherpiece15, list, random, this.l.d + 1, this.l.b + j, this.l.c + i, this.m, this.d(), flag); + } + } + + return null; + } + + protected StructurePiece b(WorldGenNetherPiece15 worldgennetherpieces_worldgennetherpiece15, List list, Random random, int i, int j, boolean flag) { + if (this.m != null) { + switch (SyntheticClass_1.a[this.m.ordinal()]) { + case 1: + return this.a(worldgennetherpieces_worldgennetherpiece15, list, random, this.l.a - 1, this.l.b + i, this.l.c + j, EnumDirection.WEST, this.d(), flag); + + case 2: + return this.a(worldgennetherpieces_worldgennetherpiece15, list, random, this.l.a - 1, this.l.b + i, this.l.c + j, EnumDirection.WEST, this.d(), flag); + + case 3: + return this.a(worldgennetherpieces_worldgennetherpiece15, list, random, this.l.a + j, this.l.b + i, this.l.c - 1, EnumDirection.NORTH, this.d(), flag); + + case 4: + return this.a(worldgennetherpieces_worldgennetherpiece15, list, random, this.l.a + j, this.l.b + i, this.l.c - 1, EnumDirection.NORTH, this.d(), flag); + } + } + + return null; + } + + protected StructurePiece c(WorldGenNetherPiece15 worldgennetherpieces_worldgennetherpiece15, List list, Random random, int i, int j, boolean flag) { + if (this.m != null) { + switch (SyntheticClass_1.a[this.m.ordinal()]) { + case 1: + return this.a(worldgennetherpieces_worldgennetherpiece15, list, random, this.l.d + 1, this.l.b + i, this.l.c + j, EnumDirection.EAST, this.d(), flag); + + case 2: + return this.a(worldgennetherpieces_worldgennetherpiece15, list, random, this.l.d + 1, this.l.b + i, this.l.c + j, EnumDirection.EAST, this.d(), flag); + + case 3: + return this.a(worldgennetherpieces_worldgennetherpiece15, list, random, this.l.a + j, this.l.b + i, this.l.f + 1, EnumDirection.SOUTH, this.d(), flag); + + case 4: + return this.a(worldgennetherpieces_worldgennetherpiece15, list, random, this.l.a + j, this.l.b + i, this.l.f + 1, EnumDirection.SOUTH, this.d(), flag); + } + } + + return null; + } + + protected static boolean a(StructureBoundingBox structureboundingbox) { + return structureboundingbox != null && structureboundingbox.b > 10; + } + } + + static class WorldGenNetherPieceWeight { + + public Class a; + public final int b; + public int c; + public int d; + public boolean e; + + public WorldGenNetherPieceWeight(Class oclass, int i, int j, boolean flag) { + this.a = oclass; + this.b = i; + this.d = j; + this.e = flag; + } + + public WorldGenNetherPieceWeight(Class oclass, int i, int j) { + this(oclass, i, j, false); + } + + public boolean a(int i) { + return this.d == 0 || this.c < this.d; + } + + public boolean a() { + return this.d == 0 || this.c < this.d; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenPackedIce1.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenPackedIce1.java new file mode 100644 index 0000000..16516d1 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenPackedIce1.java @@ -0,0 +1,45 @@ +package net.minecraft.server; + +import java.util.Random; + +public class WorldGenPackedIce1 extends WorldGenerator { + + private final Block a = Blocks.PACKED_ICE; + private final int b; + + public WorldGenPackedIce1(int i) { + this.b = i; + } + + public boolean generate(World world, Random random, BlockPosition blockposition) { + while (world.isEmpty(blockposition) && blockposition.getY() > 2) { + blockposition = blockposition.down(); + } + + if (world.getType(blockposition).getBlock() != Blocks.SNOW) { + return false; + } else { + int i = random.nextInt(this.b - 2) + 2; + byte b0 = 1; + + for (int j = blockposition.getX() - i; j <= blockposition.getX() + i; ++j) { + for (int k = blockposition.getZ() - i; k <= blockposition.getZ() + i; ++k) { + int l = j - blockposition.getX(); + int i1 = k - blockposition.getZ(); + + if (l * l + i1 * i1 <= i * i) { + for (int j1 = blockposition.getY() - b0; j1 <= blockposition.getY() + b0; ++j1) { + Block block = world.getType(j, j1, k).getBlock(); + + if (block == Blocks.DIRT || block == Blocks.SNOW || block == Blocks.ICE) { + world.setTypeAndData(new BlockPosition(j, j1, k), this.a.getBlockData(), 2); + } + } + } + } + } + + return true; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenPackedIce2.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenPackedIce2.java new file mode 100644 index 0000000..43c1b3f --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenPackedIce2.java @@ -0,0 +1,101 @@ +package net.minecraft.server; + +import java.util.Random; + +public class WorldGenPackedIce2 extends WorldGenerator { + + public WorldGenPackedIce2() { + } + + public boolean generate(World world, Random random, BlockPosition blockposition) { + while (world.isEmpty(blockposition) && blockposition.getY() > 2) { + blockposition = blockposition.down(); + } + + if (world.getType(blockposition).getBlock() != Blocks.SNOW) { + return false; + } else { + blockposition = blockposition.up(random.nextInt(4)); + int i = random.nextInt(4) + 7; + int j = i / 4 + random.nextInt(2); + + if (j > 1 && random.nextInt(60) == 0) { + blockposition = blockposition.up(10 + random.nextInt(30)); + } + + int k; + int l; + + for (k = 0; k < i; ++k) { + float f = (1.0F - (float) k / (float) i) * (float) j; + + l = MathHelper.f(f); + + for (int i1 = -l; i1 <= l; ++i1) { + float f1 = (float) MathHelper.a(i1) - 0.25F; + + for (int j1 = -l; j1 <= l; ++j1) { + float f2 = (float) MathHelper.a(j1) - 0.25F; + + if ((i1 == 0 && j1 == 0 || f1 * f1 + f2 * f2 <= f * f) && (i1 != -l && i1 != l && j1 != -l && j1 != l || random.nextFloat() <= 0.75F)) { + Block block = world.getType(blockposition.a(i1, k, j1)).getBlock(); + + if (block.getMaterial() == Material.AIR || block == Blocks.DIRT || block == Blocks.SNOW || block == Blocks.ICE) { + world.setTypeUpdate(blockposition.a(i1, k, j1), Blocks.PACKED_ICE.getBlockData()); // Spigot + } + + if (k != 0 && l > 1) { + block = world.getType(blockposition.a(i1, -k, j1)).getBlock(); + if (block.getMaterial() == Material.AIR || block == Blocks.DIRT || block == Blocks.SNOW || block == Blocks.ICE) { + world.setTypeUpdate(blockposition.a(i1, -k, j1), Blocks.PACKED_ICE.getBlockData()); // Spigot + } + } + } + } + } + } + + k = j - 1; + if (k < 0) { + k = 0; + } else if (k > 1) { + k = 1; + } + + for (int k1 = -k; k1 <= k; ++k1) { + l = -k; + + while (l <= k) { + BlockPosition blockposition1 = blockposition.a(k1, -1, l); + int l1 = 50; + + if (Math.abs(k1) == 1 && Math.abs(l) == 1) { + l1 = random.nextInt(5); + } + + while (true) { + if (blockposition1.getY() > 50) { + Block block1 = world.getType(blockposition1).getBlock(); + + if (block1.getMaterial() == Material.AIR || block1 == Blocks.DIRT || block1 == Blocks.SNOW || block1 == Blocks.ICE || block1 == Blocks.PACKED_ICE) { + world.setTypeUpdate(blockposition1, Blocks.PACKED_ICE.getBlockData()); // Spigot + blockposition1 = blockposition1.down(); + --l1; + if (l1 <= 0) { + blockposition1 = blockposition1.down(random.nextInt(5) + 1); + l1 = random.nextInt(5); + } + continue; + } + } + + ++l; + break; + } + } + } + + return true; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenPumpkin.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenPumpkin.java new file mode 100644 index 0000000..2ae1472 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenPumpkin.java @@ -0,0 +1,21 @@ +package net.minecraft.server; + +import java.util.Random; + +public class WorldGenPumpkin extends WorldGenerator { + + public WorldGenPumpkin() { + } + + public boolean generate(World world, Random random, BlockPosition blockposition) { + for (int i = 0; i < 64; ++i) { + BlockPosition blockposition1 = blockposition.a(random.nextInt(8) - random.nextInt(8), random.nextInt(4) - random.nextInt(4), random.nextInt(8) - random.nextInt(8)); + + if (world.isEmpty(blockposition1) && world.getType(blockposition1.getX(), blockposition1.getY() - 1, blockposition1.getZ()).getBlock() == Blocks.GRASS && Blocks.PUMPKIN.canPlace(world, blockposition1)) { + world.setTypeAndData(blockposition1, Blocks.PUMPKIN.getBlockData().set(BlockPumpkin.FACING, EnumDirection.EnumDirectionLimit.HORIZONTAL.a(random)), 2); + } + } + + return true; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenReed.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenReed.java new file mode 100644 index 0000000..cc234b6 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenReed.java @@ -0,0 +1,34 @@ +package net.minecraft.server; + +import java.util.Random; + +public class WorldGenReed extends WorldGenerator { + + public WorldGenReed() { + } + + public boolean generate(World world, Random random, BlockPosition blockposition) { + for (int i = 0; i < 20; ++i) { + BlockPosition blockposition1 = blockposition.a(random.nextInt(4) - random.nextInt(4), 0, random.nextInt(4) - random.nextInt(4)); + + if (world.isEmpty(blockposition1)) { + BlockPosition blockposition2 = blockposition1.down(); + + if (world.getType(blockposition2.getX() - 1, blockposition2.getY(), blockposition2.getZ()).getBlock().getMaterial() == Material.WATER || + world.getType(blockposition2.getX() + 1, blockposition2.getY(), blockposition2.getZ()).getBlock().getMaterial() == Material.WATER || + world.getType(blockposition2.getX(), blockposition2.getY(), blockposition2.getZ() - 1).getBlock().getMaterial() == Material.WATER || + world.getType(blockposition2.getX(), blockposition2.getY(), blockposition2.getZ() + 1).getBlock().getMaterial() == Material.WATER) { + int j = 2 + random.nextInt(random.nextInt(3) + 1); + + for (int k = 0; k < j; ++k) { + if (Blocks.REEDS.e(world, blockposition1)) { + world.setTypeAndData(blockposition1.up(k), Blocks.REEDS.getBlockData(), 2); + } + } + } + } + } + + return true; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenRegistration.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenRegistration.java new file mode 100644 index 0000000..227feec --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenRegistration.java @@ -0,0 +1,652 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; + +import java.util.List; +import java.util.Random; + +public class WorldGenRegistration { + + public static void a() { + WorldGenFactory.a(WorldGenPyramidPiece.class, "TeDP"); + WorldGenFactory.a(WorldGenJungleTemple.class, "TeJP"); + WorldGenFactory.a(WorldGenWitchHut.class, "TeSH"); + } + + static class SyntheticClass_1 { + + static final int[] a = new int[EnumDirection.values().length]; + + static { + try { + SyntheticClass_1.a[EnumDirection.NORTH.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.a[EnumDirection.SOUTH.ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + } + + } + } + + public static class WorldGenWitchHut extends WorldGenScatteredPiece { + + private boolean e; + + public WorldGenWitchHut() { + } + + public WorldGenWitchHut(Random random, int i, int j) { + super(random, i, 64, j, 7, 7, 9); + } + + protected void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + nbttagcompound.setBoolean("Witch", this.e); + } + + protected void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + this.e = nbttagcompound.getBoolean("Witch"); + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + if (!this.a(world, structureboundingbox, 0)) { + return false; + } else { + this.a(world, structureboundingbox, 1, 1, 1, 5, 1, 7, Blocks.PLANKS.fromLegacyData(BlockWood.EnumLogVariant.SPRUCE.a()), Blocks.PLANKS.fromLegacyData(BlockWood.EnumLogVariant.SPRUCE.a()), false); + this.a(world, structureboundingbox, 1, 4, 2, 5, 4, 7, Blocks.PLANKS.fromLegacyData(BlockWood.EnumLogVariant.SPRUCE.a()), Blocks.PLANKS.fromLegacyData(BlockWood.EnumLogVariant.SPRUCE.a()), false); + this.a(world, structureboundingbox, 2, 1, 0, 4, 1, 0, Blocks.PLANKS.fromLegacyData(BlockWood.EnumLogVariant.SPRUCE.a()), Blocks.PLANKS.fromLegacyData(BlockWood.EnumLogVariant.SPRUCE.a()), false); + this.a(world, structureboundingbox, 2, 2, 2, 3, 3, 2, Blocks.PLANKS.fromLegacyData(BlockWood.EnumLogVariant.SPRUCE.a()), Blocks.PLANKS.fromLegacyData(BlockWood.EnumLogVariant.SPRUCE.a()), false); + this.a(world, structureboundingbox, 1, 2, 3, 1, 3, 6, Blocks.PLANKS.fromLegacyData(BlockWood.EnumLogVariant.SPRUCE.a()), Blocks.PLANKS.fromLegacyData(BlockWood.EnumLogVariant.SPRUCE.a()), false); + this.a(world, structureboundingbox, 5, 2, 3, 5, 3, 6, Blocks.PLANKS.fromLegacyData(BlockWood.EnumLogVariant.SPRUCE.a()), Blocks.PLANKS.fromLegacyData(BlockWood.EnumLogVariant.SPRUCE.a()), false); + this.a(world, structureboundingbox, 2, 2, 7, 4, 3, 7, Blocks.PLANKS.fromLegacyData(BlockWood.EnumLogVariant.SPRUCE.a()), Blocks.PLANKS.fromLegacyData(BlockWood.EnumLogVariant.SPRUCE.a()), false); + this.a(world, structureboundingbox, 1, 0, 2, 1, 3, 2, Blocks.LOG.getBlockData(), Blocks.LOG.getBlockData(), false); + this.a(world, structureboundingbox, 5, 0, 2, 5, 3, 2, Blocks.LOG.getBlockData(), Blocks.LOG.getBlockData(), false); + this.a(world, structureboundingbox, 1, 0, 7, 1, 3, 7, Blocks.LOG.getBlockData(), Blocks.LOG.getBlockData(), false); + this.a(world, structureboundingbox, 5, 0, 7, 5, 3, 7, Blocks.LOG.getBlockData(), Blocks.LOG.getBlockData(), false); + this.a(world, Blocks.FENCE.getBlockData(), 2, 3, 2, structureboundingbox); + this.a(world, Blocks.FENCE.getBlockData(), 3, 3, 7, structureboundingbox); + this.a(world, Blocks.AIR.getBlockData(), 1, 3, 4, structureboundingbox); + this.a(world, Blocks.AIR.getBlockData(), 5, 3, 4, structureboundingbox); + this.a(world, Blocks.AIR.getBlockData(), 5, 3, 5, structureboundingbox); + this.a(world, Blocks.FLOWER_POT.getBlockData().set(BlockFlowerPot.CONTENTS, BlockFlowerPot.EnumFlowerPotContents.MUSHROOM_RED), 1, 3, 5, structureboundingbox); + this.a(world, Blocks.CRAFTING_TABLE.getBlockData(), 3, 2, 6, structureboundingbox); + this.a(world, Blocks.cauldron.getBlockData(), 4, 2, 6, structureboundingbox); + this.a(world, Blocks.FENCE.getBlockData(), 1, 2, 1, structureboundingbox); + this.a(world, Blocks.FENCE.getBlockData(), 5, 2, 1, structureboundingbox); + int i = this.a(Blocks.OAK_STAIRS, 3); + int j = this.a(Blocks.OAK_STAIRS, 1); + int k = this.a(Blocks.OAK_STAIRS, 0); + int l = this.a(Blocks.OAK_STAIRS, 2); + + this.a(world, structureboundingbox, 0, 4, 1, 6, 4, 1, Blocks.SPRUCE_STAIRS.fromLegacyData(i), Blocks.SPRUCE_STAIRS.fromLegacyData(i), false); + this.a(world, structureboundingbox, 0, 4, 2, 0, 4, 7, Blocks.SPRUCE_STAIRS.fromLegacyData(k), Blocks.SPRUCE_STAIRS.fromLegacyData(k), false); + this.a(world, structureboundingbox, 6, 4, 2, 6, 4, 7, Blocks.SPRUCE_STAIRS.fromLegacyData(j), Blocks.SPRUCE_STAIRS.fromLegacyData(j), false); + this.a(world, structureboundingbox, 0, 4, 8, 6, 4, 8, Blocks.SPRUCE_STAIRS.fromLegacyData(l), Blocks.SPRUCE_STAIRS.fromLegacyData(l), false); + + int i1; + int j1; + + for (i1 = 2; i1 <= 7; i1 += 5) { + for (j1 = 1; j1 <= 5; j1 += 4) { + this.b(world, Blocks.LOG.getBlockData(), j1, -1, i1, structureboundingbox); + } + } + + if (!this.e) { + i1 = this.a(2, 5); + j1 = this.d(2); + int k1 = this.b(2, 5); + + if (structureboundingbox.b(i1, j1, k1)) { + this.e = true; + EntityWitch entitywitch = new EntityWitch(world); + + entitywitch.setPositionRotation((double) i1 + 0.5D, j1, (double) k1 + 0.5D, 0.0F, 0.0F); + entitywitch.prepare(world.E(i1, j1, k1), null); + world.addEntity(entitywitch, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.CHUNK_GEN); // CraftBukkit - add SpawnReason + } + } + + return true; + } + } + } + + public static class WorldGenJungleTemple extends WorldGenScatteredPiece { + + private boolean e; + private boolean f; + private boolean g; + private boolean h; + private static final List i = Lists.newArrayList(new StructurePieceTreasure(Items.DIAMOND, 0, 1, 3, 3), new StructurePieceTreasure(Items.IRON_INGOT, 0, 1, 5, 10), new StructurePieceTreasure(Items.GOLD_INGOT, 0, 2, 7, 15), new StructurePieceTreasure(Items.EMERALD, 0, 1, 3, 2), new StructurePieceTreasure(Items.BONE, 0, 4, 6, 20), new StructurePieceTreasure(Items.ROTTEN_FLESH, 0, 3, 7, 16), new StructurePieceTreasure(Items.SADDLE, 0, 1, 1, 3), new StructurePieceTreasure(Items.IRON_HORSE_ARMOR, 0, 1, 1, 1), new StructurePieceTreasure(Items.GOLDEN_HORSE_ARMOR, 0, 1, 1, 1), new StructurePieceTreasure(Items.DIAMOND_HORSE_ARMOR, 0, 1, 1, 1)); + private static final List j = Lists.newArrayList(new StructurePieceTreasure(Items.ARROW, 0, 2, 7, 30)); + private static final WorldGenJungleTemple$WorldGenJungleTemplePiece k = new WorldGenJungleTemple$WorldGenJungleTemplePiece(null); + + public WorldGenJungleTemple() { + } + + public WorldGenJungleTemple(Random random, int i, int j) { + super(random, i, 64, j, 12, 10, 15); + } + + protected void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + nbttagcompound.setBoolean("placedMainChest", this.e); + nbttagcompound.setBoolean("placedHiddenChest", this.f); + nbttagcompound.setBoolean("placedTrap1", this.g); + nbttagcompound.setBoolean("placedTrap2", this.h); + } + + protected void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + this.e = nbttagcompound.getBoolean("placedMainChest"); + this.f = nbttagcompound.getBoolean("placedHiddenChest"); + this.g = nbttagcompound.getBoolean("placedTrap1"); + this.h = nbttagcompound.getBoolean("placedTrap2"); + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + if (!this.a(world, structureboundingbox, 0)) { + return false; + } else { + int i = this.a(Blocks.STONE_STAIRS, 3); + int j = this.a(Blocks.STONE_STAIRS, 2); + int k = this.a(Blocks.STONE_STAIRS, 0); + int l = this.a(Blocks.STONE_STAIRS, 1); + + this.a(world, structureboundingbox, 0, -4, 0, this.a - 1, 0, this.c - 1, false, random, WorldGenJungleTemple.k); + this.a(world, structureboundingbox, 2, 1, 2, 9, 2, 2, false, random, WorldGenJungleTemple.k); + this.a(world, structureboundingbox, 2, 1, 12, 9, 2, 12, false, random, WorldGenJungleTemple.k); + this.a(world, structureboundingbox, 2, 1, 3, 2, 2, 11, false, random, WorldGenJungleTemple.k); + this.a(world, structureboundingbox, 9, 1, 3, 9, 2, 11, false, random, WorldGenJungleTemple.k); + this.a(world, structureboundingbox, 1, 3, 1, 10, 6, 1, false, random, WorldGenJungleTemple.k); + this.a(world, structureboundingbox, 1, 3, 13, 10, 6, 13, false, random, WorldGenJungleTemple.k); + this.a(world, structureboundingbox, 1, 3, 2, 1, 6, 12, false, random, WorldGenJungleTemple.k); + this.a(world, structureboundingbox, 10, 3, 2, 10, 6, 12, false, random, WorldGenJungleTemple.k); + this.a(world, structureboundingbox, 2, 3, 2, 9, 3, 12, false, random, WorldGenJungleTemple.k); + this.a(world, structureboundingbox, 2, 6, 2, 9, 6, 12, false, random, WorldGenJungleTemple.k); + this.a(world, structureboundingbox, 3, 7, 3, 8, 7, 11, false, random, WorldGenJungleTemple.k); + this.a(world, structureboundingbox, 4, 8, 4, 7, 8, 10, false, random, WorldGenJungleTemple.k); + this.a(world, structureboundingbox, 3, 1, 3, 8, 2, 11); + this.a(world, structureboundingbox, 4, 3, 6, 7, 3, 9); + this.a(world, structureboundingbox, 2, 4, 2, 9, 5, 12); + this.a(world, structureboundingbox, 4, 6, 5, 7, 6, 9); + this.a(world, structureboundingbox, 5, 7, 6, 6, 7, 8); + this.a(world, structureboundingbox, 5, 1, 2, 6, 2, 2); + this.a(world, structureboundingbox, 5, 2, 12, 6, 2, 12); + this.a(world, structureboundingbox, 5, 5, 1, 6, 5, 1); + this.a(world, structureboundingbox, 5, 5, 13, 6, 5, 13); + this.a(world, Blocks.AIR.getBlockData(), 1, 5, 5, structureboundingbox); + this.a(world, Blocks.AIR.getBlockData(), 10, 5, 5, structureboundingbox); + this.a(world, Blocks.AIR.getBlockData(), 1, 5, 9, structureboundingbox); + this.a(world, Blocks.AIR.getBlockData(), 10, 5, 9, structureboundingbox); + + int i1; + + for (i1 = 0; i1 <= 14; i1 += 14) { + this.a(world, structureboundingbox, 2, 4, i1, 2, 5, i1, false, random, WorldGenJungleTemple.k); + this.a(world, structureboundingbox, 4, 4, i1, 4, 5, i1, false, random, WorldGenJungleTemple.k); + this.a(world, structureboundingbox, 7, 4, i1, 7, 5, i1, false, random, WorldGenJungleTemple.k); + this.a(world, structureboundingbox, 9, 4, i1, 9, 5, i1, false, random, WorldGenJungleTemple.k); + } + + this.a(world, structureboundingbox, 5, 6, 0, 6, 6, 0, false, random, WorldGenJungleTemple.k); + + for (i1 = 0; i1 <= 11; i1 += 11) { + for (int j1 = 2; j1 <= 12; j1 += 2) { + this.a(world, structureboundingbox, i1, 4, j1, i1, 5, j1, false, random, WorldGenJungleTemple.k); + } + + this.a(world, structureboundingbox, i1, 6, 5, i1, 6, 5, false, random, WorldGenJungleTemple.k); + this.a(world, structureboundingbox, i1, 6, 9, i1, 6, 9, false, random, WorldGenJungleTemple.k); + } + + this.a(world, structureboundingbox, 2, 7, 2, 2, 9, 2, false, random, WorldGenJungleTemple.k); + this.a(world, structureboundingbox, 9, 7, 2, 9, 9, 2, false, random, WorldGenJungleTemple.k); + this.a(world, structureboundingbox, 2, 7, 12, 2, 9, 12, false, random, WorldGenJungleTemple.k); + this.a(world, structureboundingbox, 9, 7, 12, 9, 9, 12, false, random, WorldGenJungleTemple.k); + this.a(world, structureboundingbox, 4, 9, 4, 4, 9, 4, false, random, WorldGenJungleTemple.k); + this.a(world, structureboundingbox, 7, 9, 4, 7, 9, 4, false, random, WorldGenJungleTemple.k); + this.a(world, structureboundingbox, 4, 9, 10, 4, 9, 10, false, random, WorldGenJungleTemple.k); + this.a(world, structureboundingbox, 7, 9, 10, 7, 9, 10, false, random, WorldGenJungleTemple.k); + this.a(world, structureboundingbox, 5, 9, 7, 6, 9, 7, false, random, WorldGenJungleTemple.k); + this.a(world, Blocks.STONE_STAIRS.fromLegacyData(i), 5, 9, 6, structureboundingbox); + this.a(world, Blocks.STONE_STAIRS.fromLegacyData(i), 6, 9, 6, structureboundingbox); + this.a(world, Blocks.STONE_STAIRS.fromLegacyData(j), 5, 9, 8, structureboundingbox); + this.a(world, Blocks.STONE_STAIRS.fromLegacyData(j), 6, 9, 8, structureboundingbox); + this.a(world, Blocks.STONE_STAIRS.fromLegacyData(i), 4, 0, 0, structureboundingbox); + this.a(world, Blocks.STONE_STAIRS.fromLegacyData(i), 5, 0, 0, structureboundingbox); + this.a(world, Blocks.STONE_STAIRS.fromLegacyData(i), 6, 0, 0, structureboundingbox); + this.a(world, Blocks.STONE_STAIRS.fromLegacyData(i), 7, 0, 0, structureboundingbox); + this.a(world, Blocks.STONE_STAIRS.fromLegacyData(i), 4, 1, 8, structureboundingbox); + this.a(world, Blocks.STONE_STAIRS.fromLegacyData(i), 4, 2, 9, structureboundingbox); + this.a(world, Blocks.STONE_STAIRS.fromLegacyData(i), 4, 3, 10, structureboundingbox); + this.a(world, Blocks.STONE_STAIRS.fromLegacyData(i), 7, 1, 8, structureboundingbox); + this.a(world, Blocks.STONE_STAIRS.fromLegacyData(i), 7, 2, 9, structureboundingbox); + this.a(world, Blocks.STONE_STAIRS.fromLegacyData(i), 7, 3, 10, structureboundingbox); + this.a(world, structureboundingbox, 4, 1, 9, 4, 1, 9, false, random, WorldGenJungleTemple.k); + this.a(world, structureboundingbox, 7, 1, 9, 7, 1, 9, false, random, WorldGenJungleTemple.k); + this.a(world, structureboundingbox, 4, 1, 10, 7, 2, 10, false, random, WorldGenJungleTemple.k); + this.a(world, structureboundingbox, 5, 4, 5, 6, 4, 5, false, random, WorldGenJungleTemple.k); + this.a(world, Blocks.STONE_STAIRS.fromLegacyData(k), 4, 4, 5, structureboundingbox); + this.a(world, Blocks.STONE_STAIRS.fromLegacyData(l), 7, 4, 5, structureboundingbox); + + for (i1 = 0; i1 < 4; ++i1) { + this.a(world, Blocks.STONE_STAIRS.fromLegacyData(j), 5, -i1, 6 + i1, structureboundingbox); + this.a(world, Blocks.STONE_STAIRS.fromLegacyData(j), 6, -i1, 6 + i1, structureboundingbox); + this.a(world, structureboundingbox, 5, -i1, 7 + i1, 6, -i1, 9 + i1); + } + + this.a(world, structureboundingbox, 1, -3, 12, 10, -1, 13); + this.a(world, structureboundingbox, 1, -3, 1, 3, -1, 13); + this.a(world, structureboundingbox, 1, -3, 1, 9, -1, 5); + + for (i1 = 1; i1 <= 13; i1 += 2) { + this.a(world, structureboundingbox, 1, -3, i1, 1, -2, i1, false, random, WorldGenJungleTemple.k); + } + + for (i1 = 2; i1 <= 12; i1 += 2) { + this.a(world, structureboundingbox, 1, -1, i1, 3, -1, i1, false, random, WorldGenJungleTemple.k); + } + + this.a(world, structureboundingbox, 2, -2, 1, 5, -2, 1, false, random, WorldGenJungleTemple.k); + this.a(world, structureboundingbox, 7, -2, 1, 9, -2, 1, false, random, WorldGenJungleTemple.k); + this.a(world, structureboundingbox, 6, -3, 1, 6, -3, 1, false, random, WorldGenJungleTemple.k); + this.a(world, structureboundingbox, 6, -1, 1, 6, -1, 1, false, random, WorldGenJungleTemple.k); + this.a(world, Blocks.TRIPWIRE_HOOK.fromLegacyData(this.a(Blocks.TRIPWIRE_HOOK, EnumDirection.EAST.b())).set(BlockTripwireHook.ATTACHED, Boolean.TRUE), 1, -3, 8, structureboundingbox); + this.a(world, Blocks.TRIPWIRE_HOOK.fromLegacyData(this.a(Blocks.TRIPWIRE_HOOK, EnumDirection.WEST.b())).set(BlockTripwireHook.ATTACHED, Boolean.TRUE), 4, -3, 8, structureboundingbox); + this.a(world, Blocks.TRIPWIRE.getBlockData().set(BlockTripwire.ATTACHED, true), 2, -3, 8, structureboundingbox); + this.a(world, Blocks.TRIPWIRE.getBlockData().set(BlockTripwire.ATTACHED, true), 3, -3, 8, structureboundingbox); + this.a(world, Blocks.REDSTONE_WIRE.getBlockData(), 5, -3, 7, structureboundingbox); + this.a(world, Blocks.REDSTONE_WIRE.getBlockData(), 5, -3, 6, structureboundingbox); + this.a(world, Blocks.REDSTONE_WIRE.getBlockData(), 5, -3, 5, structureboundingbox); + this.a(world, Blocks.REDSTONE_WIRE.getBlockData(), 5, -3, 4, structureboundingbox); + this.a(world, Blocks.REDSTONE_WIRE.getBlockData(), 5, -3, 3, structureboundingbox); + this.a(world, Blocks.REDSTONE_WIRE.getBlockData(), 5, -3, 2, structureboundingbox); + this.a(world, Blocks.REDSTONE_WIRE.getBlockData(), 5, -3, 1, structureboundingbox); + this.a(world, Blocks.REDSTONE_WIRE.getBlockData(), 4, -3, 1, structureboundingbox); + this.a(world, Blocks.MOSSY_COBBLESTONE.getBlockData(), 3, -3, 1, structureboundingbox); + if (!this.g) { + this.g = this.a(world, structureboundingbox, random, 3, -2, 1, EnumDirection.NORTH.a(), WorldGenJungleTemple.j, 2); + } + + this.a(world, Blocks.VINE.fromLegacyData(15), 3, -2, 2, structureboundingbox); + this.a(world, Blocks.TRIPWIRE_HOOK.fromLegacyData(this.a(Blocks.TRIPWIRE_HOOK, EnumDirection.NORTH.b())).set(BlockTripwireHook.ATTACHED, true), 7, -3, 1, structureboundingbox); + this.a(world, Blocks.TRIPWIRE_HOOK.fromLegacyData(this.a(Blocks.TRIPWIRE_HOOK, EnumDirection.SOUTH.b())).set(BlockTripwireHook.ATTACHED, true), 7, -3, 5, structureboundingbox); + this.a(world, Blocks.TRIPWIRE.getBlockData().set(BlockTripwire.ATTACHED, true), 7, -3, 2, structureboundingbox); + this.a(world, Blocks.TRIPWIRE.getBlockData().set(BlockTripwire.ATTACHED, true), 7, -3, 3, structureboundingbox); + this.a(world, Blocks.TRIPWIRE.getBlockData().set(BlockTripwire.ATTACHED, true), 7, -3, 4, structureboundingbox); + this.a(world, Blocks.REDSTONE_WIRE.getBlockData(), 8, -3, 6, structureboundingbox); + this.a(world, Blocks.REDSTONE_WIRE.getBlockData(), 9, -3, 6, structureboundingbox); + this.a(world, Blocks.REDSTONE_WIRE.getBlockData(), 9, -3, 5, structureboundingbox); + this.a(world, Blocks.MOSSY_COBBLESTONE.getBlockData(), 9, -3, 4, structureboundingbox); + this.a(world, Blocks.REDSTONE_WIRE.getBlockData(), 9, -2, 4, structureboundingbox); + if (!this.h) { + this.h = this.a(world, structureboundingbox, random, 9, -2, 3, EnumDirection.WEST.a(), WorldGenJungleTemple.j, 2); + } + + this.a(world, Blocks.VINE.fromLegacyData(15), 8, -1, 3, structureboundingbox); + this.a(world, Blocks.VINE.fromLegacyData(15), 8, -2, 3, structureboundingbox); + if (!this.e) { + this.e = this.a(world, structureboundingbox, random, 8, -3, 3, StructurePieceTreasure.a(WorldGenJungleTemple.i, Items.ENCHANTED_BOOK.b(random)), 2 + random.nextInt(5)); + } + + this.a(world, Blocks.MOSSY_COBBLESTONE.getBlockData(), 9, -3, 2, structureboundingbox); + this.a(world, Blocks.MOSSY_COBBLESTONE.getBlockData(), 8, -3, 1, structureboundingbox); + this.a(world, Blocks.MOSSY_COBBLESTONE.getBlockData(), 4, -3, 5, structureboundingbox); + this.a(world, Blocks.MOSSY_COBBLESTONE.getBlockData(), 5, -2, 5, structureboundingbox); + this.a(world, Blocks.MOSSY_COBBLESTONE.getBlockData(), 5, -1, 5, structureboundingbox); + this.a(world, Blocks.MOSSY_COBBLESTONE.getBlockData(), 6, -3, 5, structureboundingbox); + this.a(world, Blocks.MOSSY_COBBLESTONE.getBlockData(), 7, -2, 5, structureboundingbox); + this.a(world, Blocks.MOSSY_COBBLESTONE.getBlockData(), 7, -1, 5, structureboundingbox); + this.a(world, Blocks.MOSSY_COBBLESTONE.getBlockData(), 8, -3, 5, structureboundingbox); + this.a(world, structureboundingbox, 9, -1, 1, 9, -1, 5, false, random, WorldGenJungleTemple.k); + this.a(world, structureboundingbox, 8, -3, 8, 10, -1, 10); + this.a(world, Blocks.STONEBRICK.fromLegacyData(BlockSmoothBrick.P), 8, -2, 11, structureboundingbox); + this.a(world, Blocks.STONEBRICK.fromLegacyData(BlockSmoothBrick.P), 9, -2, 11, structureboundingbox); + this.a(world, Blocks.STONEBRICK.fromLegacyData(BlockSmoothBrick.P), 10, -2, 11, structureboundingbox); + this.a(world, Blocks.LEVER.fromLegacyData(BlockLever.a(EnumDirection.fromType1(this.a(Blocks.LEVER, EnumDirection.NORTH.a())))), 8, -2, 12, structureboundingbox); + this.a(world, Blocks.LEVER.fromLegacyData(BlockLever.a(EnumDirection.fromType1(this.a(Blocks.LEVER, EnumDirection.NORTH.a())))), 9, -2, 12, structureboundingbox); + this.a(world, Blocks.LEVER.fromLegacyData(BlockLever.a(EnumDirection.fromType1(this.a(Blocks.LEVER, EnumDirection.NORTH.a())))), 10, -2, 12, structureboundingbox); + this.a(world, structureboundingbox, 8, -3, 8, 8, -3, 10, false, random, WorldGenJungleTemple.k); + this.a(world, structureboundingbox, 10, -3, 8, 10, -3, 10, false, random, WorldGenJungleTemple.k); + this.a(world, Blocks.MOSSY_COBBLESTONE.getBlockData(), 10, -2, 9, structureboundingbox); + this.a(world, Blocks.REDSTONE_WIRE.getBlockData(), 8, -2, 9, structureboundingbox); + this.a(world, Blocks.REDSTONE_WIRE.getBlockData(), 8, -2, 10, structureboundingbox); + this.a(world, Blocks.REDSTONE_WIRE.getBlockData(), 10, -1, 9, structureboundingbox); + this.a(world, Blocks.STICKY_PISTON.fromLegacyData(EnumDirection.UP.a()), 9, -2, 8, structureboundingbox); + this.a(world, Blocks.STICKY_PISTON.fromLegacyData(this.a(Blocks.STICKY_PISTON, EnumDirection.WEST.a())), 10, -2, 8, structureboundingbox); + this.a(world, Blocks.STICKY_PISTON.fromLegacyData(this.a(Blocks.STICKY_PISTON, EnumDirection.WEST.a())), 10, -1, 8, structureboundingbox); + this.a(world, Blocks.UNPOWERED_REPEATER.fromLegacyData(this.a(Blocks.UNPOWERED_REPEATER, EnumDirection.NORTH.b())), 10, -2, 10, structureboundingbox); + if (!this.f) { + this.f = this.a(world, structureboundingbox, random, 9, -3, 10, StructurePieceTreasure.a(WorldGenJungleTemple.i, Items.ENCHANTED_BOOK.b(random)), 2 + random.nextInt(5)); + } + + return true; + } + } + + static class WorldGenJungleTemple$WorldGenJungleTemplePiece extends StructurePieceBlockSelector { + + private WorldGenJungleTemple$WorldGenJungleTemplePiece() { + } + + public void a(Random random, int i, int j, int k, boolean flag) { + if (random.nextFloat() < 0.4F) { + this.a = Blocks.COBBLESTONE.getBlockData(); + } else { + this.a = Blocks.MOSSY_COBBLESTONE.getBlockData(); + } + + } + + WorldGenJungleTemple$WorldGenJungleTemplePiece(SyntheticClass_1 worldgenregistration_syntheticclass_1) { + this(); + } + } + } + + public static class WorldGenPyramidPiece extends WorldGenScatteredPiece { + + private final boolean[] e = new boolean[4]; + private static final List f = Lists.newArrayList(new StructurePieceTreasure(Items.DIAMOND, 0, 1, 3, 3), new StructurePieceTreasure(Items.IRON_INGOT, 0, 1, 5, 10), new StructurePieceTreasure(Items.GOLD_INGOT, 0, 2, 7, 15), new StructurePieceTreasure(Items.EMERALD, 0, 1, 3, 2), new StructurePieceTreasure(Items.BONE, 0, 4, 6, 20), new StructurePieceTreasure(Items.ROTTEN_FLESH, 0, 3, 7, 16), new StructurePieceTreasure(Items.SADDLE, 0, 1, 1, 3), new StructurePieceTreasure(Items.IRON_HORSE_ARMOR, 0, 1, 1, 1), new StructurePieceTreasure(Items.GOLDEN_HORSE_ARMOR, 0, 1, 1, 1), new StructurePieceTreasure(Items.DIAMOND_HORSE_ARMOR, 0, 1, 1, 1)); + + public WorldGenPyramidPiece() { + } + + public WorldGenPyramidPiece(Random random, int i, int j) { + super(random, i, 64, j, 21, 15, 21); + } + + protected void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + nbttagcompound.setBoolean("hasPlacedChest0", this.e[0]); + nbttagcompound.setBoolean("hasPlacedChest1", this.e[1]); + nbttagcompound.setBoolean("hasPlacedChest2", this.e[2]); + nbttagcompound.setBoolean("hasPlacedChest3", this.e[3]); + } + + protected void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + this.e[0] = nbttagcompound.getBoolean("hasPlacedChest0"); + this.e[1] = nbttagcompound.getBoolean("hasPlacedChest1"); + this.e[2] = nbttagcompound.getBoolean("hasPlacedChest2"); + this.e[3] = nbttagcompound.getBoolean("hasPlacedChest3"); + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + this.a(world, structureboundingbox, 0, -4, 0, this.a - 1, 0, this.c - 1, Blocks.SANDSTONE.getBlockData(), Blocks.SANDSTONE.getBlockData(), false); + + int i; + + for (i = 1; i <= 9; ++i) { + this.a(world, structureboundingbox, i, i, i, this.a - 1 - i, i, this.c - 1 - i, Blocks.SANDSTONE.getBlockData(), Blocks.SANDSTONE.getBlockData(), false); + this.a(world, structureboundingbox, i + 1, i, i + 1, this.a - 2 - i, i, this.c - 2 - i, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + } + + int j; + + for (i = 0; i < this.a; ++i) { + for (j = 0; j < this.c; ++j) { + byte b0 = -5; + + this.b(world, Blocks.SANDSTONE.getBlockData(), i, b0, j, structureboundingbox); + } + } + + i = this.a(Blocks.SANDSTONE_STAIRS, 3); + j = this.a(Blocks.SANDSTONE_STAIRS, 2); + int k = this.a(Blocks.SANDSTONE_STAIRS, 0); + int l = this.a(Blocks.SANDSTONE_STAIRS, 1); + int i1 = ~EnumColor.ORANGE.getInvColorIndex() & 15; + int j1 = ~EnumColor.BLUE.getInvColorIndex() & 15; + + this.a(world, structureboundingbox, 0, 0, 0, 4, 9, 4, Blocks.SANDSTONE.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, 1, 10, 1, 3, 10, 3, Blocks.SANDSTONE.getBlockData(), Blocks.SANDSTONE.getBlockData(), false); + this.a(world, Blocks.SANDSTONE_STAIRS.fromLegacyData(i), 2, 10, 0, structureboundingbox); + this.a(world, Blocks.SANDSTONE_STAIRS.fromLegacyData(j), 2, 10, 4, structureboundingbox); + this.a(world, Blocks.SANDSTONE_STAIRS.fromLegacyData(k), 0, 10, 2, structureboundingbox); + this.a(world, Blocks.SANDSTONE_STAIRS.fromLegacyData(l), 4, 10, 2, structureboundingbox); + this.a(world, structureboundingbox, this.a - 5, 0, 0, this.a - 1, 9, 4, Blocks.SANDSTONE.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, this.a - 4, 10, 1, this.a - 2, 10, 3, Blocks.SANDSTONE.getBlockData(), Blocks.SANDSTONE.getBlockData(), false); + this.a(world, Blocks.SANDSTONE_STAIRS.fromLegacyData(i), this.a - 3, 10, 0, structureboundingbox); + this.a(world, Blocks.SANDSTONE_STAIRS.fromLegacyData(j), this.a - 3, 10, 4, structureboundingbox); + this.a(world, Blocks.SANDSTONE_STAIRS.fromLegacyData(k), this.a - 5, 10, 2, structureboundingbox); + this.a(world, Blocks.SANDSTONE_STAIRS.fromLegacyData(l), this.a - 1, 10, 2, structureboundingbox); + this.a(world, structureboundingbox, 8, 0, 0, 12, 4, 4, Blocks.SANDSTONE.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, 9, 1, 0, 11, 3, 4, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()), 9, 1, 1, structureboundingbox); + this.a(world, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()), 9, 2, 1, structureboundingbox); + this.a(world, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()), 9, 3, 1, structureboundingbox); + this.a(world, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()), 10, 3, 1, structureboundingbox); + this.a(world, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()), 11, 3, 1, structureboundingbox); + this.a(world, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()), 11, 2, 1, structureboundingbox); + this.a(world, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()), 11, 1, 1, structureboundingbox); + this.a(world, structureboundingbox, 4, 1, 1, 8, 3, 3, Blocks.SANDSTONE.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, 4, 1, 2, 8, 2, 2, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, 12, 1, 1, 16, 3, 3, Blocks.SANDSTONE.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, 12, 1, 2, 16, 2, 2, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, 5, 4, 5, this.a - 6, 4, this.c - 6, Blocks.SANDSTONE.getBlockData(), Blocks.SANDSTONE.getBlockData(), false); + this.a(world, structureboundingbox, 9, 4, 9, 11, 4, 11, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, 8, 1, 8, 8, 3, 8, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()), Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()), false); + this.a(world, structureboundingbox, 12, 1, 8, 12, 3, 8, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()), Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()), false); + this.a(world, structureboundingbox, 8, 1, 12, 8, 3, 12, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()), Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()), false); + this.a(world, structureboundingbox, 12, 1, 12, 12, 3, 12, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()), Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()), false); + this.a(world, structureboundingbox, 1, 1, 5, 4, 4, 11, Blocks.SANDSTONE.getBlockData(), Blocks.SANDSTONE.getBlockData(), false); + this.a(world, structureboundingbox, this.a - 5, 1, 5, this.a - 2, 4, 11, Blocks.SANDSTONE.getBlockData(), Blocks.SANDSTONE.getBlockData(), false); + this.a(world, structureboundingbox, 6, 7, 9, 6, 7, 11, Blocks.SANDSTONE.getBlockData(), Blocks.SANDSTONE.getBlockData(), false); + this.a(world, structureboundingbox, this.a - 7, 7, 9, this.a - 7, 7, 11, Blocks.SANDSTONE.getBlockData(), Blocks.SANDSTONE.getBlockData(), false); + this.a(world, structureboundingbox, 5, 5, 9, 5, 7, 11, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()), Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()), false); + this.a(world, structureboundingbox, this.a - 6, 5, 9, this.a - 6, 7, 11, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()), Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()), false); + this.a(world, Blocks.AIR.getBlockData(), 5, 5, 10, structureboundingbox); + this.a(world, Blocks.AIR.getBlockData(), 5, 6, 10, structureboundingbox); + this.a(world, Blocks.AIR.getBlockData(), 6, 6, 10, structureboundingbox); + this.a(world, Blocks.AIR.getBlockData(), this.a - 6, 5, 10, structureboundingbox); + this.a(world, Blocks.AIR.getBlockData(), this.a - 6, 6, 10, structureboundingbox); + this.a(world, Blocks.AIR.getBlockData(), this.a - 7, 6, 10, structureboundingbox); + this.a(world, structureboundingbox, 2, 4, 4, 2, 6, 4, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, this.a - 3, 4, 4, this.a - 3, 6, 4, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, Blocks.SANDSTONE_STAIRS.fromLegacyData(i), 2, 4, 5, structureboundingbox); + this.a(world, Blocks.SANDSTONE_STAIRS.fromLegacyData(i), 2, 3, 4, structureboundingbox); + this.a(world, Blocks.SANDSTONE_STAIRS.fromLegacyData(i), this.a - 3, 4, 5, structureboundingbox); + this.a(world, Blocks.SANDSTONE_STAIRS.fromLegacyData(i), this.a - 3, 3, 4, structureboundingbox); + this.a(world, structureboundingbox, 1, 1, 3, 2, 2, 3, Blocks.SANDSTONE.getBlockData(), Blocks.SANDSTONE.getBlockData(), false); + this.a(world, structureboundingbox, this.a - 3, 1, 3, this.a - 2, 2, 3, Blocks.SANDSTONE.getBlockData(), Blocks.SANDSTONE.getBlockData(), false); + this.a(world, Blocks.SANDSTONE_STAIRS.getBlockData(), 1, 1, 2, structureboundingbox); + this.a(world, Blocks.SANDSTONE_STAIRS.getBlockData(), this.a - 2, 1, 2, structureboundingbox); + this.a(world, Blocks.STONE_SLAB.fromLegacyData(BlockDoubleStepAbstract.EnumStoneSlabVariant.SAND.a()), 1, 2, 2, structureboundingbox); + this.a(world, Blocks.STONE_SLAB.fromLegacyData(BlockDoubleStepAbstract.EnumStoneSlabVariant.SAND.a()), this.a - 2, 2, 2, structureboundingbox); + this.a(world, Blocks.SANDSTONE_STAIRS.fromLegacyData(l), 2, 1, 2, structureboundingbox); + this.a(world, Blocks.SANDSTONE_STAIRS.fromLegacyData(k), this.a - 3, 1, 2, structureboundingbox); + this.a(world, structureboundingbox, 4, 3, 5, 4, 3, 18, Blocks.SANDSTONE.getBlockData(), Blocks.SANDSTONE.getBlockData(), false); + this.a(world, structureboundingbox, this.a - 5, 3, 5, this.a - 5, 3, 17, Blocks.SANDSTONE.getBlockData(), Blocks.SANDSTONE.getBlockData(), false); + this.a(world, structureboundingbox, 3, 1, 5, 4, 2, 16, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, this.a - 6, 1, 5, this.a - 5, 2, 16, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + + int k1; + + for (k1 = 5; k1 <= 17; k1 += 2) { + this.a(world, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()), 4, 1, k1, structureboundingbox); + this.a(world, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.CHISELED.a()), 4, 2, k1, structureboundingbox); + this.a(world, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()), this.a - 5, 1, k1, structureboundingbox); + this.a(world, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.CHISELED.a()), this.a - 5, 2, k1, structureboundingbox); + } + + this.a(world, Blocks.STAINED_HARDENED_CLAY.fromLegacyData(i1), 10, 0, 7, structureboundingbox); + this.a(world, Blocks.STAINED_HARDENED_CLAY.fromLegacyData(i1), 10, 0, 8, structureboundingbox); + this.a(world, Blocks.STAINED_HARDENED_CLAY.fromLegacyData(i1), 9, 0, 9, structureboundingbox); + this.a(world, Blocks.STAINED_HARDENED_CLAY.fromLegacyData(i1), 11, 0, 9, structureboundingbox); + this.a(world, Blocks.STAINED_HARDENED_CLAY.fromLegacyData(i1), 8, 0, 10, structureboundingbox); + this.a(world, Blocks.STAINED_HARDENED_CLAY.fromLegacyData(i1), 12, 0, 10, structureboundingbox); + this.a(world, Blocks.STAINED_HARDENED_CLAY.fromLegacyData(i1), 7, 0, 10, structureboundingbox); + this.a(world, Blocks.STAINED_HARDENED_CLAY.fromLegacyData(i1), 13, 0, 10, structureboundingbox); + this.a(world, Blocks.STAINED_HARDENED_CLAY.fromLegacyData(i1), 9, 0, 11, structureboundingbox); + this.a(world, Blocks.STAINED_HARDENED_CLAY.fromLegacyData(i1), 11, 0, 11, structureboundingbox); + this.a(world, Blocks.STAINED_HARDENED_CLAY.fromLegacyData(i1), 10, 0, 12, structureboundingbox); + this.a(world, Blocks.STAINED_HARDENED_CLAY.fromLegacyData(i1), 10, 0, 13, structureboundingbox); + this.a(world, Blocks.STAINED_HARDENED_CLAY.fromLegacyData(j1), 10, 0, 10, structureboundingbox); + + for (k1 = 0; k1 <= this.a - 1; k1 += this.a - 1) { + this.a(world, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()), k1, 2, 1, structureboundingbox); + this.a(world, Blocks.STAINED_HARDENED_CLAY.fromLegacyData(i1), k1, 2, 2, structureboundingbox); + this.a(world, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()), k1, 2, 3, structureboundingbox); + this.a(world, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()), k1, 3, 1, structureboundingbox); + this.a(world, Blocks.STAINED_HARDENED_CLAY.fromLegacyData(i1), k1, 3, 2, structureboundingbox); + this.a(world, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()), k1, 3, 3, structureboundingbox); + this.a(world, Blocks.STAINED_HARDENED_CLAY.fromLegacyData(i1), k1, 4, 1, structureboundingbox); + this.a(world, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.CHISELED.a()), k1, 4, 2, structureboundingbox); + this.a(world, Blocks.STAINED_HARDENED_CLAY.fromLegacyData(i1), k1, 4, 3, structureboundingbox); + this.a(world, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()), k1, 5, 1, structureboundingbox); + this.a(world, Blocks.STAINED_HARDENED_CLAY.fromLegacyData(i1), k1, 5, 2, structureboundingbox); + this.a(world, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()), k1, 5, 3, structureboundingbox); + this.a(world, Blocks.STAINED_HARDENED_CLAY.fromLegacyData(i1), k1, 6, 1, structureboundingbox); + this.a(world, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.CHISELED.a()), k1, 6, 2, structureboundingbox); + this.a(world, Blocks.STAINED_HARDENED_CLAY.fromLegacyData(i1), k1, 6, 3, structureboundingbox); + this.a(world, Blocks.STAINED_HARDENED_CLAY.fromLegacyData(i1), k1, 7, 1, structureboundingbox); + this.a(world, Blocks.STAINED_HARDENED_CLAY.fromLegacyData(i1), k1, 7, 2, structureboundingbox); + this.a(world, Blocks.STAINED_HARDENED_CLAY.fromLegacyData(i1), k1, 7, 3, structureboundingbox); + this.a(world, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()), k1, 8, 1, structureboundingbox); + this.a(world, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()), k1, 8, 2, structureboundingbox); + this.a(world, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()), k1, 8, 3, structureboundingbox); + } + + for (k1 = 2; k1 <= this.a - 3; k1 += this.a - 3 - 2) { + this.a(world, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()), k1 - 1, 2, 0, structureboundingbox); + this.a(world, Blocks.STAINED_HARDENED_CLAY.fromLegacyData(i1), k1, 2, 0, structureboundingbox); + this.a(world, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()), k1 + 1, 2, 0, structureboundingbox); + this.a(world, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()), k1 - 1, 3, 0, structureboundingbox); + this.a(world, Blocks.STAINED_HARDENED_CLAY.fromLegacyData(i1), k1, 3, 0, structureboundingbox); + this.a(world, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()), k1 + 1, 3, 0, structureboundingbox); + this.a(world, Blocks.STAINED_HARDENED_CLAY.fromLegacyData(i1), k1 - 1, 4, 0, structureboundingbox); + this.a(world, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.CHISELED.a()), k1, 4, 0, structureboundingbox); + this.a(world, Blocks.STAINED_HARDENED_CLAY.fromLegacyData(i1), k1 + 1, 4, 0, structureboundingbox); + this.a(world, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()), k1 - 1, 5, 0, structureboundingbox); + this.a(world, Blocks.STAINED_HARDENED_CLAY.fromLegacyData(i1), k1, 5, 0, structureboundingbox); + this.a(world, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()), k1 + 1, 5, 0, structureboundingbox); + this.a(world, Blocks.STAINED_HARDENED_CLAY.fromLegacyData(i1), k1 - 1, 6, 0, structureboundingbox); + this.a(world, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.CHISELED.a()), k1, 6, 0, structureboundingbox); + this.a(world, Blocks.STAINED_HARDENED_CLAY.fromLegacyData(i1), k1 + 1, 6, 0, structureboundingbox); + this.a(world, Blocks.STAINED_HARDENED_CLAY.fromLegacyData(i1), k1 - 1, 7, 0, structureboundingbox); + this.a(world, Blocks.STAINED_HARDENED_CLAY.fromLegacyData(i1), k1, 7, 0, structureboundingbox); + this.a(world, Blocks.STAINED_HARDENED_CLAY.fromLegacyData(i1), k1 + 1, 7, 0, structureboundingbox); + this.a(world, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()), k1 - 1, 8, 0, structureboundingbox); + this.a(world, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()), k1, 8, 0, structureboundingbox); + this.a(world, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()), k1 + 1, 8, 0, structureboundingbox); + } + + this.a(world, structureboundingbox, 8, 4, 0, 12, 6, 0, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()), Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()), false); + this.a(world, Blocks.AIR.getBlockData(), 8, 6, 0, structureboundingbox); + this.a(world, Blocks.AIR.getBlockData(), 12, 6, 0, structureboundingbox); + this.a(world, Blocks.STAINED_HARDENED_CLAY.fromLegacyData(i1), 9, 5, 0, structureboundingbox); + this.a(world, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.CHISELED.a()), 10, 5, 0, structureboundingbox); + this.a(world, Blocks.STAINED_HARDENED_CLAY.fromLegacyData(i1), 11, 5, 0, structureboundingbox); + this.a(world, structureboundingbox, 8, -14, 8, 12, -11, 12, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()), Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()), false); + this.a(world, structureboundingbox, 8, -10, 8, 12, -10, 12, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.CHISELED.a()), Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.CHISELED.a()), false); + this.a(world, structureboundingbox, 8, -9, 8, 12, -9, 12, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()), Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()), false); + this.a(world, structureboundingbox, 8, -8, 8, 12, -1, 12, Blocks.SANDSTONE.getBlockData(), Blocks.SANDSTONE.getBlockData(), false); + this.a(world, structureboundingbox, 9, -11, 9, 11, -1, 11, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, Blocks.STONE_PRESSURE_PLATE.getBlockData(), 10, -11, 10, structureboundingbox); + this.a(world, structureboundingbox, 9, -13, 9, 11, -13, 11, Blocks.TNT.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, Blocks.AIR.getBlockData(), 8, -11, 10, structureboundingbox); + this.a(world, Blocks.AIR.getBlockData(), 8, -10, 10, structureboundingbox); + this.a(world, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.CHISELED.a()), 7, -10, 10, structureboundingbox); + this.a(world, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()), 7, -11, 10, structureboundingbox); + this.a(world, Blocks.AIR.getBlockData(), 12, -11, 10, structureboundingbox); + this.a(world, Blocks.AIR.getBlockData(), 12, -10, 10, structureboundingbox); + this.a(world, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.CHISELED.a()), 13, -10, 10, structureboundingbox); + this.a(world, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()), 13, -11, 10, structureboundingbox); + this.a(world, Blocks.AIR.getBlockData(), 10, -11, 8, structureboundingbox); + this.a(world, Blocks.AIR.getBlockData(), 10, -10, 8, structureboundingbox); + this.a(world, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.CHISELED.a()), 10, -10, 7, structureboundingbox); + this.a(world, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()), 10, -11, 7, structureboundingbox); + this.a(world, Blocks.AIR.getBlockData(), 10, -11, 12, structureboundingbox); + this.a(world, Blocks.AIR.getBlockData(), 10, -10, 12, structureboundingbox); + this.a(world, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.CHISELED.a()), 10, -10, 13, structureboundingbox); + this.a(world, Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()), 10, -11, 13, structureboundingbox); + + for (EnumDirection enumdirection : EnumDirection.EnumDirectionLimit.HORIZONTAL) { + if (!this.e[enumdirection.b()]) { + int l1 = enumdirection.getAdjacentX() * 2; + int i2 = enumdirection.getAdjacentZ() * 2; + + this.e[enumdirection.b()] = this.a(world, structureboundingbox, random, 10 + l1, -11, 10 + i2, StructurePieceTreasure.a(WorldGenPyramidPiece.f, Items.ENCHANTED_BOOK.b(random)), 2 + random.nextInt(5)); + } + } + + return true; + } + } + + abstract static class WorldGenScatteredPiece extends StructurePiece { + + protected int a; + protected int b; + protected int c; + protected int d = -1; + + public WorldGenScatteredPiece() { + } + + protected WorldGenScatteredPiece(Random random, int i, int j, int k, int l, int i1, int j1) { + super(0); + this.a = l; + this.b = i1; + this.c = j1; + this.m = EnumDirection.EnumDirectionLimit.HORIZONTAL.a(random); + switch (SyntheticClass_1.a[this.m.ordinal()]) { + case 1: + case 2: + this.l = new StructureBoundingBox(i, j, k, i + l - 1, j + i1 - 1, k + j1 - 1); + break; + + default: + this.l = new StructureBoundingBox(i, j, k, i + j1 - 1, j + i1 - 1, k + l - 1); + } + + } + + protected void a(NBTTagCompound nbttagcompound) { + nbttagcompound.setInt("Width", this.a); + nbttagcompound.setInt("Height", this.b); + nbttagcompound.setInt("Depth", this.c); + nbttagcompound.setInt("HPos", this.d); + } + + protected void b(NBTTagCompound nbttagcompound) { + this.a = nbttagcompound.getInt("Width"); + this.b = nbttagcompound.getInt("Height"); + this.c = nbttagcompound.getInt("Depth"); + this.d = nbttagcompound.getInt("HPos"); + } + + protected boolean a(World world, StructureBoundingBox structureboundingbox, int i) { + if (this.d >= 0) { + return true; + } else { + int j = 0; + int k = 0; + + for (int l = this.l.c; l <= this.l.f; ++l) { + for (int i1 = this.l.a; i1 <= this.l.d; ++i1) { + if (structureboundingbox.b(i1, 64, l)) { + j += Math.max(world.r(i1, l).getY(), world.worldProvider.getSeaLevel()); + ++k; + } + } + } + + if (k == 0) { + return false; + } else { + this.d = j / k; + this.l.a(0, this.d - this.l.b + i, 0); + return true; + } + } + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenSand.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenSand.java new file mode 100644 index 0000000..5f8c07e --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenSand.java @@ -0,0 +1,42 @@ +package net.minecraft.server; + +import java.util.Random; + +public class WorldGenSand extends WorldGenerator { + + private final Block a; + private final int b; + + public WorldGenSand(Block block, int i) { + this.a = block; + this.b = i; + } + + public boolean generate(World world, Random random, BlockPosition blockposition) { + if (world.getType(blockposition).getBlock().getMaterial() != Material.WATER) { + return false; + } else { + int i = random.nextInt(this.b - 2) + 2; + byte b0 = 2; + + for (int j = blockposition.getX() - i; j <= blockposition.getX() + i; ++j) { + for (int k = blockposition.getZ() - i; k <= blockposition.getZ() + i; ++k) { + int l = j - blockposition.getX(); + int i1 = k - blockposition.getZ(); + + if (l * l + i1 * i1 <= i * i) { + for (int j1 = blockposition.getY() - b0; j1 <= blockposition.getY() + b0; ++j1) { + Block block = world.getType(j, j1, k).getBlock(); + + if (block == Blocks.DIRT || block == Blocks.GRASS) { + world.setTypeAndData(new BlockPosition(j, j1, k), this.a.getBlockData(), 2); + } + } + } + } + } + + return true; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenStronghold.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenStronghold.java new file mode 100644 index 0000000..9f465e8 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenStronghold.java @@ -0,0 +1,143 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Random; + +public class WorldGenStronghold extends StructureGenerator { + + private final List d; + private boolean f; + private ChunkCoordIntPair[] g; + private double h; + private int i; + + public WorldGenStronghold() { + this.g = new ChunkCoordIntPair[3]; + this.h = 32.0D; + this.i = 3; + this.d = Lists.newArrayList(); + + for (BiomeBase biomebase : BiomeBase.getBiomes()) { + if (biomebase != null && biomebase.an > 0.0F) { + this.d.add(biomebase); + } + } + + } + + public WorldGenStronghold(Map map) { + this(); + + for (Entry entry : map.entrySet()) { + + switch (entry.getKey()) { + case "distance": + this.h = MathHelper.a(entry.getValue(), this.h, 1.0D); + break; + case "count": + this.g = new ChunkCoordIntPair[MathHelper.a(entry.getValue(), this.g.length, 1)]; + break; + case "spread": + this.i = MathHelper.a(entry.getValue(), this.i, 1); + break; + } + } + + } + + public String a() { + return "Stronghold"; + } + + protected boolean a(int i, int j) { + if (!this.f) { + Random random = new Random(); + + random.setSeed(this.c.getSeed()); + double d0 = random.nextDouble() * 3.141592653589793D * 2.0D; + int k = 1; + + for (int l = 0; l < this.g.length; ++l) { + double d1 = (1.25D * (double) k + random.nextDouble()) * this.h * (double) k; + int i1 = (int) Math.round(Math.cos(d0) * d1); + int j1 = (int) Math.round(Math.sin(d0) * d1); + BlockPosition blockposition = this.c.getWorldChunkManager().a((i1 << 4) + 8, (j1 << 4) + 8, 112, this.d, random); + + if (blockposition != null) { + i1 = blockposition.getX() >> 4; + j1 = blockposition.getZ() >> 4; + } + + this.g[l] = new ChunkCoordIntPair(i1, j1); + d0 += 6.283185307179586D * (double) k / (double) this.i; + if (l == this.i) { + k += 2 + random.nextInt(5); + this.i += 1 + random.nextInt(2); + } + } + + this.f = true; + } + + for (ChunkCoordIntPair chunkcoordintpair : g) { + if (i == chunkcoordintpair.x && j == chunkcoordintpair.z) { + return true; + } + } + + return false; + } + + protected List z_() { + ArrayList arraylist = Lists.newArrayList(); + + for (ChunkCoordIntPair chunkcoordintpair : g) { + if (chunkcoordintpair != null) { + arraylist.add(chunkcoordintpair.a(64)); + } + } + + return arraylist; + } + + protected StructureStart b(int i, int j) { + WorldGenStronghold2Start worldgenstronghold_worldgenstronghold2start; + + for (worldgenstronghold_worldgenstronghold2start = new WorldGenStronghold2Start(this.c, this.b, i, j); worldgenstronghold_worldgenstronghold2start.b().isEmpty() || ((WorldGenStrongholdPieces.WorldGenStrongholdStart) worldgenstronghold_worldgenstronghold2start.b().get(0)).b == null; worldgenstronghold_worldgenstronghold2start = new WorldGenStronghold2Start(this.c, this.b, i, j)) { + + } + + return worldgenstronghold_worldgenstronghold2start; + } + + public static class WorldGenStronghold2Start extends StructureStart { + + public WorldGenStronghold2Start() { + } + + public WorldGenStronghold2Start(World world, Random random, int i, int j) { + super(i, j); + WorldGenStrongholdPieces.b(); + WorldGenStrongholdPieces.WorldGenStrongholdStart worldgenstrongholdpieces_worldgenstrongholdstart = new WorldGenStrongholdPieces.WorldGenStrongholdStart(0, random, (i << 4) + 2, (j << 4) + 2); + + this.a.add(worldgenstrongholdpieces_worldgenstrongholdstart); + worldgenstrongholdpieces_worldgenstrongholdstart.a(worldgenstrongholdpieces_worldgenstrongholdstart, this.a, random); + List list = worldgenstrongholdpieces_worldgenstrongholdstart.c; + + while (!list.isEmpty()) { + int k = random.nextInt(list.size()); + StructurePiece structurepiece = list.remove(k); + + structurepiece.a(worldgenstrongholdpieces_worldgenstrongholdstart, this.a, random); + } + + this.c(); + this.a(world, random, 10); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenStrongholdPieces.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenStrongholdPieces.java new file mode 100644 index 0000000..ce4c41e --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenStrongholdPieces.java @@ -0,0 +1,1423 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; + +import java.util.Iterator; +import java.util.List; +import java.util.Random; + +public class WorldGenStrongholdPieces { + + private static final WorldGenStrongholdPieceWeight[] b = {new WorldGenStrongholdPieceWeight(WorldGenStrongholdStairs.class, 40, 0), new WorldGenStrongholdPieceWeight(WorldGenStrongholdPrison.class, 5, 5), new WorldGenStrongholdPieceWeight(WorldGenStrongholdLeftTurn.class, 20, 0), new WorldGenStrongholdPieceWeight(WorldGenStrongholdRightTurn.class, 20, 0), new WorldGenStrongholdPieceWeight(WorldGenStrongholdRoomCrossing.class, 10, 6), new WorldGenStrongholdPieceWeight(WorldGenStrongholdStairsStraight.class, 5, 5), new WorldGenStrongholdPieceWeight(WorldGenStrongholdStairs2.class, 5, 5), new WorldGenStrongholdPieceWeight(WorldGenStrongholdCrossing.class, 5, 4), new WorldGenStrongholdPieceWeight(WorldGenStrongholdChestCorridor.class, 5, 4), new WorldGenStrongholdPieceWeight(WorldGenStrongholdLibrary.class, 10, 2) { + public boolean a(int i) { + return super.a(i) && i > 4; + } + }, new WorldGenStrongholdPieceWeight(WorldGenStrongholdPortalRoom.class, 20, 1) { + public boolean a(int i) { + return super.a(i) && i > 5; + } + }}; + private static List c; + private static Class d; + static int a; + private static final WorldGenStrongholdStones e = new WorldGenStrongholdStones(null); + + public static void a() { + WorldGenFactory.a(WorldGenStrongholdChestCorridor.class, "SHCC"); + WorldGenFactory.a(WorldGenStrongholdCorridor.class, "SHFC"); + WorldGenFactory.a(WorldGenStrongholdCrossing.class, "SH5C"); + WorldGenFactory.a(WorldGenStrongholdLeftTurn.class, "SHLT"); + WorldGenFactory.a(WorldGenStrongholdLibrary.class, "SHLi"); + WorldGenFactory.a(WorldGenStrongholdPortalRoom.class, "SHPR"); + WorldGenFactory.a(WorldGenStrongholdPrison.class, "SHPH"); + WorldGenFactory.a(WorldGenStrongholdRightTurn.class, "SHRT"); + WorldGenFactory.a(WorldGenStrongholdRoomCrossing.class, "SHRC"); + WorldGenFactory.a(WorldGenStrongholdStairs2.class, "SHSD"); + WorldGenFactory.a(WorldGenStrongholdStart.class, "SHStart"); + WorldGenFactory.a(WorldGenStrongholdStairs.class, "SHS"); + WorldGenFactory.a(WorldGenStrongholdStairsStraight.class, "SHSSD"); + } + + public static void b() { + WorldGenStrongholdPieces.c = Lists.newArrayList(); + + for (WorldGenStrongholdPieceWeight worldgenstrongholdpieces_worldgenstrongholdpieceweight : WorldGenStrongholdPieces.b) { + worldgenstrongholdpieces_worldgenstrongholdpieceweight.c = 0; + WorldGenStrongholdPieces.c.add(worldgenstrongholdpieces_worldgenstrongholdpieceweight); + } + + WorldGenStrongholdPieces.d = null; + } + + private static boolean d() { + boolean flag = false; + + WorldGenStrongholdPieces.a = 0; + + WorldGenStrongholdPieceWeight worldgenstrongholdpieces_worldgenstrongholdpieceweight; + + for (Iterator iterator = WorldGenStrongholdPieces.c.iterator(); iterator.hasNext(); WorldGenStrongholdPieces.a += worldgenstrongholdpieces_worldgenstrongholdpieceweight.b) { + worldgenstrongholdpieces_worldgenstrongholdpieceweight = iterator.next(); + if (worldgenstrongholdpieces_worldgenstrongholdpieceweight.d > 0 && worldgenstrongholdpieces_worldgenstrongholdpieceweight.c < worldgenstrongholdpieces_worldgenstrongholdpieceweight.d) { + flag = true; + } + } + + return flag; + } + + private static WorldGenStrongholdPiece a(Class oclass, List list, Random random, int i, int j, int k, EnumDirection enumdirection, int l) { + Object object = null; + + if (oclass == WorldGenStrongholdStairs.class) { + object = WorldGenStrongholdStairs.a(list, random, i, j, k, enumdirection, l); + } else if (oclass == WorldGenStrongholdPrison.class) { + object = WorldGenStrongholdPrison.a(list, random, i, j, k, enumdirection, l); + } else if (oclass == WorldGenStrongholdLeftTurn.class) { + object = WorldGenStrongholdLeftTurn.a(list, random, i, j, k, enumdirection, l); + } else if (oclass == WorldGenStrongholdRightTurn.class) { + object = WorldGenStrongholdRightTurn.a(list, random, i, j, k, enumdirection, l); + } else if (oclass == WorldGenStrongholdRoomCrossing.class) { + object = WorldGenStrongholdRoomCrossing.a(list, random, i, j, k, enumdirection, l); + } else if (oclass == WorldGenStrongholdStairsStraight.class) { + object = WorldGenStrongholdStairsStraight.a(list, random, i, j, k, enumdirection, l); + } else if (oclass == WorldGenStrongholdStairs2.class) { + object = WorldGenStrongholdStairs2.a(list, random, i, j, k, enumdirection, l); + } else if (oclass == WorldGenStrongholdCrossing.class) { + object = WorldGenStrongholdCrossing.a(list, random, i, j, k, enumdirection, l); + } else if (oclass == WorldGenStrongholdChestCorridor.class) { + object = WorldGenStrongholdChestCorridor.a(list, random, i, j, k, enumdirection, l); + } else if (oclass == WorldGenStrongholdLibrary.class) { + object = WorldGenStrongholdLibrary.a(list, random, i, j, k, enumdirection, l); + } else if (oclass == WorldGenStrongholdPortalRoom.class) { + object = WorldGenStrongholdPortalRoom.a(list, random, i, j, k, enumdirection, l); + } + + return (WorldGenStrongholdPiece) object; + } + + private static WorldGenStrongholdPiece b(WorldGenStrongholdStart worldgenstrongholdpieces_worldgenstrongholdstart, List list, Random random, int i, int j, int k, EnumDirection enumdirection, int l) { + if (!d()) { + return null; + } else { + if (WorldGenStrongholdPieces.d != null) { + WorldGenStrongholdPiece worldgenstrongholdpieces_worldgenstrongholdpiece = a(WorldGenStrongholdPieces.d, list, random, i, j, k, enumdirection, l); + + WorldGenStrongholdPieces.d = null; + if (worldgenstrongholdpieces_worldgenstrongholdpiece != null) { + return worldgenstrongholdpieces_worldgenstrongholdpiece; + } + } + + int i1 = 0; + + while (i1 < 5) { + ++i1; + int j1 = random.nextInt(WorldGenStrongholdPieces.a); + + for (WorldGenStrongholdPieceWeight worldgenstrongholdpieces_worldgenstrongholdpieceweight : WorldGenStrongholdPieces.c) { + j1 -= worldgenstrongholdpieces_worldgenstrongholdpieceweight.b; + if (j1 < 0) { + if (!worldgenstrongholdpieces_worldgenstrongholdpieceweight.a(l) || worldgenstrongholdpieces_worldgenstrongholdpieceweight == worldgenstrongholdpieces_worldgenstrongholdstart.a) { + break; + } + + WorldGenStrongholdPiece worldgenstrongholdpieces_worldgenstrongholdpiece1 = a(worldgenstrongholdpieces_worldgenstrongholdpieceweight.a, list, random, i, j, k, enumdirection, l); + + if (worldgenstrongholdpieces_worldgenstrongholdpiece1 != null) { + ++worldgenstrongholdpieces_worldgenstrongholdpieceweight.c; + worldgenstrongholdpieces_worldgenstrongholdstart.a = worldgenstrongholdpieces_worldgenstrongholdpieceweight; + if (!worldgenstrongholdpieces_worldgenstrongholdpieceweight.a()) { + WorldGenStrongholdPieces.c.remove(worldgenstrongholdpieces_worldgenstrongholdpieceweight); + } + + return worldgenstrongholdpieces_worldgenstrongholdpiece1; + } + } + } + } + + StructureBoundingBox structureboundingbox = WorldGenStrongholdCorridor.a(list, random, i, j, k, enumdirection); + + if (structureboundingbox != null && structureboundingbox.b > 1) { + return new WorldGenStrongholdCorridor(l, random, structureboundingbox, enumdirection); + } else { + return null; + } + } + } + + private static StructurePiece c(WorldGenStrongholdStart worldgenstrongholdpieces_worldgenstrongholdstart, List list, Random random, int i, int j, int k, EnumDirection enumdirection, int l) { + if (l > 50) { + return null; + } else if (Math.abs(i - worldgenstrongholdpieces_worldgenstrongholdstart.c().a) <= 112 && Math.abs(k - worldgenstrongholdpieces_worldgenstrongholdstart.c().c) <= 112) { + WorldGenStrongholdPiece worldgenstrongholdpieces_worldgenstrongholdpiece = b(worldgenstrongholdpieces_worldgenstrongholdstart, list, random, i, j, k, enumdirection, l + 1); + + if (worldgenstrongholdpieces_worldgenstrongholdpiece != null) { + list.add(worldgenstrongholdpieces_worldgenstrongholdpiece); + worldgenstrongholdpieces_worldgenstrongholdstart.c.add(worldgenstrongholdpieces_worldgenstrongholdpiece); + } + + return worldgenstrongholdpieces_worldgenstrongholdpiece; + } else { + return null; + } + } + + static class SyntheticClass_1 { + + static final int[] a; + static final int[] b = new int[EnumDirection.values().length]; + + static { + try { + SyntheticClass_1.b[EnumDirection.NORTH.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.b[EnumDirection.SOUTH.ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.b[EnumDirection.WEST.ordinal()] = 3; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.b[EnumDirection.EAST.ordinal()] = 4; + } catch (NoSuchFieldError ignored) { + } + + a = new int[WorldGenStrongholdPiece.WorldGenStrongholdPiece$WorldGenStrongholdDoorType.values().length]; + + try { + SyntheticClass_1.a[WorldGenStrongholdPiece.WorldGenStrongholdPiece$WorldGenStrongholdDoorType.OPENING.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.a[WorldGenStrongholdPiece.WorldGenStrongholdPiece$WorldGenStrongholdDoorType.WOOD_DOOR.ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.a[WorldGenStrongholdPiece.WorldGenStrongholdPiece$WorldGenStrongholdDoorType.GRATES.ordinal()] = 3; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.a[WorldGenStrongholdPiece.WorldGenStrongholdPiece$WorldGenStrongholdDoorType.IRON_DOOR.ordinal()] = 4; + } catch (NoSuchFieldError ignored) { + } + + } + } + + static class WorldGenStrongholdStones extends StructurePiece.StructurePieceBlockSelector { + + private WorldGenStrongholdStones() { + } + + public void a(Random random, int i, int j, int k, boolean flag) { + if (flag) { + float f = random.nextFloat(); + + if (f < 0.2F) { + this.a = Blocks.STONEBRICK.fromLegacyData(BlockSmoothBrick.O); + } else if (f < 0.5F) { + this.a = Blocks.STONEBRICK.fromLegacyData(BlockSmoothBrick.N); + } else if (f < 0.55F) { + this.a = Blocks.MONSTER_EGG.fromLegacyData(BlockMonsterEggs.EnumMonsterEggVarient.STONEBRICK.a()); + } else { + this.a = Blocks.STONEBRICK.getBlockData(); + } + } else { + this.a = Blocks.AIR.getBlockData(); + } + + } + + WorldGenStrongholdStones(Object object) { + this(); + } + } + + public static class WorldGenStrongholdPortalRoom extends WorldGenStrongholdPiece { + + private boolean a; + + public WorldGenStrongholdPortalRoom() { + } + + public WorldGenStrongholdPortalRoom(int i, Random random, StructureBoundingBox structureboundingbox, EnumDirection enumdirection) { + super(i); + this.m = enumdirection; + this.l = structureboundingbox; + } + + protected void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + nbttagcompound.setBoolean("Mob", this.a); + } + + protected void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + this.a = nbttagcompound.getBoolean("Mob"); + } + + public void a(StructurePiece structurepiece, List list, Random random) { + if (structurepiece != null) { + ((WorldGenStrongholdStart) structurepiece).b = this; + } + + } + + public static WorldGenStrongholdPortalRoom a(List list, Random random, int i, int j, int k, EnumDirection enumdirection, int l) { + StructureBoundingBox structureboundingbox = StructureBoundingBox.a(i, j, k, -4, -1, 0, 11, 8, 16, enumdirection); + + return a(structureboundingbox) && StructurePiece.a(list, structureboundingbox) == null ? new WorldGenStrongholdPortalRoom(l, random, structureboundingbox, enumdirection) : null; + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + this.a(world, structureboundingbox, 0, 0, 0, 10, 7, 15, false, random, WorldGenStrongholdPieces.e); + this.a(world, random, structureboundingbox, WorldGenStrongholdPiece$WorldGenStrongholdDoorType.GRATES, 4, 1, 0); + byte b0 = 6; + + this.a(world, structureboundingbox, 1, b0, 1, 1, b0, 14, false, random, WorldGenStrongholdPieces.e); + this.a(world, structureboundingbox, 9, b0, 1, 9, b0, 14, false, random, WorldGenStrongholdPieces.e); + this.a(world, structureboundingbox, 2, b0, 1, 8, b0, 2, false, random, WorldGenStrongholdPieces.e); + this.a(world, structureboundingbox, 2, b0, 14, 8, b0, 14, false, random, WorldGenStrongholdPieces.e); + this.a(world, structureboundingbox, 1, 1, 1, 2, 1, 4, false, random, WorldGenStrongholdPieces.e); + this.a(world, structureboundingbox, 8, 1, 1, 9, 1, 4, false, random, WorldGenStrongholdPieces.e); + this.a(world, structureboundingbox, 1, 1, 1, 1, 1, 3, Blocks.FLOWING_LAVA.getBlockData(), Blocks.FLOWING_LAVA.getBlockData(), false); + this.a(world, structureboundingbox, 9, 1, 1, 9, 1, 3, Blocks.FLOWING_LAVA.getBlockData(), Blocks.FLOWING_LAVA.getBlockData(), false); + this.a(world, structureboundingbox, 3, 1, 8, 7, 1, 12, false, random, WorldGenStrongholdPieces.e); + this.a(world, structureboundingbox, 4, 1, 9, 6, 1, 11, Blocks.FLOWING_LAVA.getBlockData(), Blocks.FLOWING_LAVA.getBlockData(), false); + + int i; + + for (i = 3; i < 14; i += 2) { + this.a(world, structureboundingbox, 0, 3, i, 0, 4, i, Blocks.IRON_BARS.getBlockData(), Blocks.IRON_BARS.getBlockData(), false); + this.a(world, structureboundingbox, 10, 3, i, 10, 4, i, Blocks.IRON_BARS.getBlockData(), Blocks.IRON_BARS.getBlockData(), false); + } + + for (i = 2; i < 9; i += 2) { + this.a(world, structureboundingbox, i, 3, 15, i, 4, 15, Blocks.IRON_BARS.getBlockData(), Blocks.IRON_BARS.getBlockData(), false); + } + + i = this.a(Blocks.STONE_BRICK_STAIRS, 3); + this.a(world, structureboundingbox, 4, 1, 5, 6, 1, 7, false, random, WorldGenStrongholdPieces.e); + this.a(world, structureboundingbox, 4, 2, 6, 6, 2, 7, false, random, WorldGenStrongholdPieces.e); + this.a(world, structureboundingbox, 4, 3, 7, 6, 3, 7, false, random, WorldGenStrongholdPieces.e); + + int j; + + for (j = 4; j <= 6; ++j) { + this.a(world, Blocks.STONE_BRICK_STAIRS.fromLegacyData(i), j, 1, 4, structureboundingbox); + this.a(world, Blocks.STONE_BRICK_STAIRS.fromLegacyData(i), j, 2, 5, structureboundingbox); + this.a(world, Blocks.STONE_BRICK_STAIRS.fromLegacyData(i), j, 3, 6, structureboundingbox); + } + + j = EnumDirection.NORTH.b(); + int k = EnumDirection.SOUTH.b(); + int l = EnumDirection.EAST.b(); + int i1 = EnumDirection.WEST.b(); + + if (this.m != null) { + switch (WorldGenStrongholdPieces.SyntheticClass_1.b[this.m.ordinal()]) { + case 2: + j = EnumDirection.SOUTH.b(); + k = EnumDirection.NORTH.b(); + break; + + case 3: + j = EnumDirection.WEST.b(); + k = EnumDirection.EAST.b(); + l = EnumDirection.SOUTH.b(); + i1 = EnumDirection.NORTH.b(); + break; + + case 4: + j = EnumDirection.EAST.b(); + k = EnumDirection.WEST.b(); + l = EnumDirection.SOUTH.b(); + i1 = EnumDirection.NORTH.b(); + } + } + + this.a(world, Blocks.END_PORTAL_FRAME.fromLegacyData(j).set(BlockEnderPortalFrame.EYE, random.nextFloat() > 0.9F), 4, 3, 8, structureboundingbox); + this.a(world, Blocks.END_PORTAL_FRAME.fromLegacyData(j).set(BlockEnderPortalFrame.EYE, random.nextFloat() > 0.9F), 5, 3, 8, structureboundingbox); + this.a(world, Blocks.END_PORTAL_FRAME.fromLegacyData(j).set(BlockEnderPortalFrame.EYE, random.nextFloat() > 0.9F), 6, 3, 8, structureboundingbox); + this.a(world, Blocks.END_PORTAL_FRAME.fromLegacyData(k).set(BlockEnderPortalFrame.EYE, random.nextFloat() > 0.9F), 4, 3, 12, structureboundingbox); + this.a(world, Blocks.END_PORTAL_FRAME.fromLegacyData(k).set(BlockEnderPortalFrame.EYE, random.nextFloat() > 0.9F), 5, 3, 12, structureboundingbox); + this.a(world, Blocks.END_PORTAL_FRAME.fromLegacyData(k).set(BlockEnderPortalFrame.EYE, random.nextFloat() > 0.9F), 6, 3, 12, structureboundingbox); + this.a(world, Blocks.END_PORTAL_FRAME.fromLegacyData(l).set(BlockEnderPortalFrame.EYE, random.nextFloat() > 0.9F), 3, 3, 9, structureboundingbox); + this.a(world, Blocks.END_PORTAL_FRAME.fromLegacyData(l).set(BlockEnderPortalFrame.EYE, random.nextFloat() > 0.9F), 3, 3, 10, structureboundingbox); + this.a(world, Blocks.END_PORTAL_FRAME.fromLegacyData(l).set(BlockEnderPortalFrame.EYE, random.nextFloat() > 0.9F), 3, 3, 11, structureboundingbox); + this.a(world, Blocks.END_PORTAL_FRAME.fromLegacyData(i1).set(BlockEnderPortalFrame.EYE, random.nextFloat() > 0.9F), 7, 3, 9, structureboundingbox); + this.a(world, Blocks.END_PORTAL_FRAME.fromLegacyData(i1).set(BlockEnderPortalFrame.EYE, random.nextFloat() > 0.9F), 7, 3, 10, structureboundingbox); + this.a(world, Blocks.END_PORTAL_FRAME.fromLegacyData(i1).set(BlockEnderPortalFrame.EYE, random.nextFloat() > 0.9F), 7, 3, 11, structureboundingbox); + if (!this.a) { + int j1 = this.d(3); + int x = a(5, 6), z = b(5, 6); + if (structureboundingbox.b(x, j1, z)) { + BlockPosition blockposition = new BlockPosition(x, j1, z); + this.a = true; + world.setTypeAndData(blockposition, Blocks.MOB_SPAWNER.getBlockData(), 2); + TileEntity tileentity = world.getTileEntity(blockposition); + + if (tileentity instanceof TileEntityMobSpawner) { + ((TileEntityMobSpawner) tileentity).getSpawner().setMobName("Silverfish"); + } + } + } + + return true; + } + } + + public static class WorldGenStrongholdCrossing extends WorldGenStrongholdPiece { + + private boolean a; + private boolean b; + private boolean c; + private boolean e; + + public WorldGenStrongholdCrossing() { + } + + public WorldGenStrongholdCrossing(int i, Random random, StructureBoundingBox structureboundingbox, EnumDirection enumdirection) { + super(i); + this.m = enumdirection; + this.d = this.a(random); + this.l = structureboundingbox; + this.a = random.nextBoolean(); + this.b = random.nextBoolean(); + this.c = random.nextBoolean(); + this.e = random.nextInt(3) > 0; + } + + protected void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + nbttagcompound.setBoolean("leftLow", this.a); + nbttagcompound.setBoolean("leftHigh", this.b); + nbttagcompound.setBoolean("rightLow", this.c); + nbttagcompound.setBoolean("rightHigh", this.e); + } + + protected void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + this.a = nbttagcompound.getBoolean("leftLow"); + this.b = nbttagcompound.getBoolean("leftHigh"); + this.c = nbttagcompound.getBoolean("rightLow"); + this.e = nbttagcompound.getBoolean("rightHigh"); + } + + public void a(StructurePiece structurepiece, List list, Random random) { + int i = 3; + int j = 5; + + if (this.m == EnumDirection.WEST || this.m == EnumDirection.NORTH) { + i = 8 - i; + j = 8 - j; + } + + this.a((WorldGenStrongholdStart) structurepiece, list, random, 5, 1); + if (this.a) { + this.b((WorldGenStrongholdStart) structurepiece, list, random, i, 1); + } + + if (this.b) { + this.b((WorldGenStrongholdStart) structurepiece, list, random, j, 7); + } + + if (this.c) { + this.c((WorldGenStrongholdStart) structurepiece, list, random, i, 1); + } + + if (this.e) { + this.c((WorldGenStrongholdStart) structurepiece, list, random, j, 7); + } + + } + + public static WorldGenStrongholdCrossing a(List list, Random random, int i, int j, int k, EnumDirection enumdirection, int l) { + StructureBoundingBox structureboundingbox = StructureBoundingBox.a(i, j, k, -4, -3, 0, 10, 9, 11, enumdirection); + + return a(structureboundingbox) && StructurePiece.a(list, structureboundingbox) == null ? new WorldGenStrongholdCrossing(l, random, structureboundingbox, enumdirection) : null; + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + if (this.a(world, structureboundingbox)) { + return false; + } else { + this.a(world, structureboundingbox, 0, 0, 0, 9, 8, 10, true, random, WorldGenStrongholdPieces.e); + this.a(world, random, structureboundingbox, this.d, 4, 3, 0); + if (this.a) { + this.a(world, structureboundingbox, 0, 3, 1, 0, 5, 3, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + } + + if (this.c) { + this.a(world, structureboundingbox, 9, 3, 1, 9, 5, 3, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + } + + if (this.b) { + this.a(world, structureboundingbox, 0, 5, 7, 0, 7, 9, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + } + + if (this.e) { + this.a(world, structureboundingbox, 9, 5, 7, 9, 7, 9, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + } + + this.a(world, structureboundingbox, 5, 1, 10, 7, 3, 10, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, 1, 2, 1, 8, 2, 6, false, random, WorldGenStrongholdPieces.e); + this.a(world, structureboundingbox, 4, 1, 5, 4, 4, 9, false, random, WorldGenStrongholdPieces.e); + this.a(world, structureboundingbox, 8, 1, 5, 8, 4, 9, false, random, WorldGenStrongholdPieces.e); + this.a(world, structureboundingbox, 1, 4, 7, 3, 4, 9, false, random, WorldGenStrongholdPieces.e); + this.a(world, structureboundingbox, 1, 3, 5, 3, 3, 6, false, random, WorldGenStrongholdPieces.e); + this.a(world, structureboundingbox, 1, 3, 4, 3, 3, 4, Blocks.STONE_SLAB.getBlockData(), Blocks.STONE_SLAB.getBlockData(), false); + this.a(world, structureboundingbox, 1, 4, 6, 3, 4, 6, Blocks.STONE_SLAB.getBlockData(), Blocks.STONE_SLAB.getBlockData(), false); + this.a(world, structureboundingbox, 5, 1, 7, 7, 1, 8, false, random, WorldGenStrongholdPieces.e); + this.a(world, structureboundingbox, 5, 1, 9, 7, 1, 9, Blocks.STONE_SLAB.getBlockData(), Blocks.STONE_SLAB.getBlockData(), false); + this.a(world, structureboundingbox, 5, 2, 7, 7, 2, 7, Blocks.STONE_SLAB.getBlockData(), Blocks.STONE_SLAB.getBlockData(), false); + this.a(world, structureboundingbox, 4, 5, 7, 4, 5, 9, Blocks.STONE_SLAB.getBlockData(), Blocks.STONE_SLAB.getBlockData(), false); + this.a(world, structureboundingbox, 8, 5, 7, 8, 5, 9, Blocks.STONE_SLAB.getBlockData(), Blocks.STONE_SLAB.getBlockData(), false); + this.a(world, structureboundingbox, 5, 5, 7, 7, 5, 9, Blocks.DOUBLE_STONE_SLAB.getBlockData(), Blocks.DOUBLE_STONE_SLAB.getBlockData(), false); + this.a(world, Blocks.TORCH.getBlockData(), 6, 5, 6, structureboundingbox); + return true; + } + } + } + + public static class WorldGenStrongholdLibrary extends WorldGenStrongholdPiece { + + private static final List a = Lists.newArrayList(new StructurePieceTreasure(Items.BOOK, 0, 1, 3, 20), new StructurePieceTreasure(Items.PAPER, 0, 2, 7, 20), new StructurePieceTreasure(Items.MAP, 0, 1, 1, 1), new StructurePieceTreasure(Items.COMPASS, 0, 1, 1, 1)); + private boolean b; + + public WorldGenStrongholdLibrary() { + } + + public WorldGenStrongholdLibrary(int i, Random random, StructureBoundingBox structureboundingbox, EnumDirection enumdirection) { + super(i); + this.m = enumdirection; + this.d = this.a(random); + this.l = structureboundingbox; + this.b = structureboundingbox.d() > 6; + } + + protected void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + nbttagcompound.setBoolean("Tall", this.b); + } + + protected void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + this.b = nbttagcompound.getBoolean("Tall"); + } + + public static WorldGenStrongholdLibrary a(List list, Random random, int i, int j, int k, EnumDirection enumdirection, int l) { + StructureBoundingBox structureboundingbox = StructureBoundingBox.a(i, j, k, -4, -1, 0, 14, 11, 15, enumdirection); + + if (!a(structureboundingbox) || StructurePiece.a(list, structureboundingbox) != null) { + structureboundingbox = StructureBoundingBox.a(i, j, k, -4, -1, 0, 14, 6, 15, enumdirection); + if (!a(structureboundingbox) || StructurePiece.a(list, structureboundingbox) != null) { + return null; + } + } + + return new WorldGenStrongholdLibrary(l, random, structureboundingbox, enumdirection); + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + if (this.a(world, structureboundingbox)) { + return false; + } else { + byte b0 = 11; + + if (!this.b) { + b0 = 6; + } + + this.a(world, structureboundingbox, 0, 0, 0, 13, b0 - 1, 14, true, random, WorldGenStrongholdPieces.e); + this.a(world, random, structureboundingbox, this.d, 4, 1, 0); + this.a(world, structureboundingbox, random, 0.07F, 2, 1, 1, 11, 4, 13, Blocks.WEB.getBlockData(), Blocks.WEB.getBlockData(), false); + + int i; + + for (i = 1; i <= 13; ++i) { + if ((i - 1) % 4 == 0) { + this.a(world, structureboundingbox, 1, 1, i, 1, 4, i, Blocks.PLANKS.getBlockData(), Blocks.PLANKS.getBlockData(), false); + this.a(world, structureboundingbox, 12, 1, i, 12, 4, i, Blocks.PLANKS.getBlockData(), Blocks.PLANKS.getBlockData(), false); + this.a(world, Blocks.TORCH.getBlockData(), 2, 3, i, structureboundingbox); + this.a(world, Blocks.TORCH.getBlockData(), 11, 3, i, structureboundingbox); + if (this.b) { + this.a(world, structureboundingbox, 1, 6, i, 1, 9, i, Blocks.PLANKS.getBlockData(), Blocks.PLANKS.getBlockData(), false); + this.a(world, structureboundingbox, 12, 6, i, 12, 9, i, Blocks.PLANKS.getBlockData(), Blocks.PLANKS.getBlockData(), false); + } + } else { + this.a(world, structureboundingbox, 1, 1, i, 1, 4, i, Blocks.BOOKSHELF.getBlockData(), Blocks.BOOKSHELF.getBlockData(), false); + this.a(world, structureboundingbox, 12, 1, i, 12, 4, i, Blocks.BOOKSHELF.getBlockData(), Blocks.BOOKSHELF.getBlockData(), false); + if (this.b) { + this.a(world, structureboundingbox, 1, 6, i, 1, 9, i, Blocks.BOOKSHELF.getBlockData(), Blocks.BOOKSHELF.getBlockData(), false); + this.a(world, structureboundingbox, 12, 6, i, 12, 9, i, Blocks.BOOKSHELF.getBlockData(), Blocks.BOOKSHELF.getBlockData(), false); + } + } + } + + for (i = 3; i < 12; i += 2) { + this.a(world, structureboundingbox, 3, 1, i, 4, 3, i, Blocks.BOOKSHELF.getBlockData(), Blocks.BOOKSHELF.getBlockData(), false); + this.a(world, structureboundingbox, 6, 1, i, 7, 3, i, Blocks.BOOKSHELF.getBlockData(), Blocks.BOOKSHELF.getBlockData(), false); + this.a(world, structureboundingbox, 9, 1, i, 10, 3, i, Blocks.BOOKSHELF.getBlockData(), Blocks.BOOKSHELF.getBlockData(), false); + } + + if (this.b) { + this.a(world, structureboundingbox, 1, 5, 1, 3, 5, 13, Blocks.PLANKS.getBlockData(), Blocks.PLANKS.getBlockData(), false); + this.a(world, structureboundingbox, 10, 5, 1, 12, 5, 13, Blocks.PLANKS.getBlockData(), Blocks.PLANKS.getBlockData(), false); + this.a(world, structureboundingbox, 4, 5, 1, 9, 5, 2, Blocks.PLANKS.getBlockData(), Blocks.PLANKS.getBlockData(), false); + this.a(world, structureboundingbox, 4, 5, 12, 9, 5, 13, Blocks.PLANKS.getBlockData(), Blocks.PLANKS.getBlockData(), false); + this.a(world, Blocks.PLANKS.getBlockData(), 9, 5, 11, structureboundingbox); + this.a(world, Blocks.PLANKS.getBlockData(), 8, 5, 11, structureboundingbox); + this.a(world, Blocks.PLANKS.getBlockData(), 9, 5, 10, structureboundingbox); + this.a(world, structureboundingbox, 3, 6, 2, 3, 6, 12, Blocks.FENCE.getBlockData(), Blocks.FENCE.getBlockData(), false); + this.a(world, structureboundingbox, 10, 6, 2, 10, 6, 10, Blocks.FENCE.getBlockData(), Blocks.FENCE.getBlockData(), false); + this.a(world, structureboundingbox, 4, 6, 2, 9, 6, 2, Blocks.FENCE.getBlockData(), Blocks.FENCE.getBlockData(), false); + this.a(world, structureboundingbox, 4, 6, 12, 8, 6, 12, Blocks.FENCE.getBlockData(), Blocks.FENCE.getBlockData(), false); + this.a(world, Blocks.FENCE.getBlockData(), 9, 6, 11, structureboundingbox); + this.a(world, Blocks.FENCE.getBlockData(), 8, 6, 11, structureboundingbox); + this.a(world, Blocks.FENCE.getBlockData(), 9, 6, 10, structureboundingbox); + i = this.a(Blocks.LADDER, 3); + this.a(world, Blocks.LADDER.fromLegacyData(i), 10, 1, 13, structureboundingbox); + this.a(world, Blocks.LADDER.fromLegacyData(i), 10, 2, 13, structureboundingbox); + this.a(world, Blocks.LADDER.fromLegacyData(i), 10, 3, 13, structureboundingbox); + this.a(world, Blocks.LADDER.fromLegacyData(i), 10, 4, 13, structureboundingbox); + this.a(world, Blocks.LADDER.fromLegacyData(i), 10, 5, 13, structureboundingbox); + this.a(world, Blocks.LADDER.fromLegacyData(i), 10, 6, 13, structureboundingbox); + this.a(world, Blocks.LADDER.fromLegacyData(i), 10, 7, 13, structureboundingbox); + byte b1 = 7; + byte b2 = 7; + + this.a(world, Blocks.FENCE.getBlockData(), b1 - 1, 9, b2, structureboundingbox); + this.a(world, Blocks.FENCE.getBlockData(), b1, 9, b2, structureboundingbox); + this.a(world, Blocks.FENCE.getBlockData(), b1 - 1, 8, b2, structureboundingbox); + this.a(world, Blocks.FENCE.getBlockData(), b1, 8, b2, structureboundingbox); + this.a(world, Blocks.FENCE.getBlockData(), b1 - 1, 7, b2, structureboundingbox); + this.a(world, Blocks.FENCE.getBlockData(), b1, 7, b2, structureboundingbox); + this.a(world, Blocks.FENCE.getBlockData(), b1 - 2, 7, b2, structureboundingbox); + this.a(world, Blocks.FENCE.getBlockData(), b1 + 1, 7, b2, structureboundingbox); + this.a(world, Blocks.FENCE.getBlockData(), b1 - 1, 7, b2 - 1, structureboundingbox); + this.a(world, Blocks.FENCE.getBlockData(), b1 - 1, 7, b2 + 1, structureboundingbox); + this.a(world, Blocks.FENCE.getBlockData(), b1, 7, b2 - 1, structureboundingbox); + this.a(world, Blocks.FENCE.getBlockData(), b1, 7, b2 + 1, structureboundingbox); + this.a(world, Blocks.TORCH.getBlockData(), b1 - 2, 8, b2, structureboundingbox); + this.a(world, Blocks.TORCH.getBlockData(), b1 + 1, 8, b2, structureboundingbox); + this.a(world, Blocks.TORCH.getBlockData(), b1 - 1, 8, b2 - 1, structureboundingbox); + this.a(world, Blocks.TORCH.getBlockData(), b1 - 1, 8, b2 + 1, structureboundingbox); + this.a(world, Blocks.TORCH.getBlockData(), b1, 8, b2 - 1, structureboundingbox); + this.a(world, Blocks.TORCH.getBlockData(), b1, 8, b2 + 1, structureboundingbox); + } + + this.a(world, structureboundingbox, random, 3, 3, 5, StructurePieceTreasure.a(WorldGenStrongholdLibrary.a, Items.ENCHANTED_BOOK.a(random, 1, 5, 2)), 1 + random.nextInt(4)); + if (this.b) { + this.a(world, Blocks.AIR.getBlockData(), 12, 9, 1, structureboundingbox); + this.a(world, structureboundingbox, random, 12, 8, 1, StructurePieceTreasure.a(WorldGenStrongholdLibrary.a, Items.ENCHANTED_BOOK.a(random, 1, 5, 2)), 1 + random.nextInt(4)); + } + + return true; + } + } + } + + public static class WorldGenStrongholdPrison extends WorldGenStrongholdPiece { + + public WorldGenStrongholdPrison() { + } + + public WorldGenStrongholdPrison(int i, Random random, StructureBoundingBox structureboundingbox, EnumDirection enumdirection) { + super(i); + this.m = enumdirection; + this.d = this.a(random); + this.l = structureboundingbox; + } + + public void a(StructurePiece structurepiece, List list, Random random) { + this.a((WorldGenStrongholdStart) structurepiece, list, random, 1, 1); + } + + public static WorldGenStrongholdPrison a(List list, Random random, int i, int j, int k, EnumDirection enumdirection, int l) { + StructureBoundingBox structureboundingbox = StructureBoundingBox.a(i, j, k, -1, -1, 0, 9, 5, 11, enumdirection); + + return a(structureboundingbox) && StructurePiece.a(list, structureboundingbox) == null ? new WorldGenStrongholdPrison(l, random, structureboundingbox, enumdirection) : null; + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + if (this.a(world, structureboundingbox)) { + return false; + } else { + this.a(world, structureboundingbox, 0, 0, 0, 8, 4, 10, true, random, WorldGenStrongholdPieces.e); + this.a(world, random, structureboundingbox, this.d, 1, 1, 0); + this.a(world, structureboundingbox, 1, 1, 10, 3, 3, 10, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, 4, 1, 1, 4, 3, 1, false, random, WorldGenStrongholdPieces.e); + this.a(world, structureboundingbox, 4, 1, 3, 4, 3, 3, false, random, WorldGenStrongholdPieces.e); + this.a(world, structureboundingbox, 4, 1, 7, 4, 3, 7, false, random, WorldGenStrongholdPieces.e); + this.a(world, structureboundingbox, 4, 1, 9, 4, 3, 9, false, random, WorldGenStrongholdPieces.e); + this.a(world, structureboundingbox, 4, 1, 4, 4, 3, 6, Blocks.IRON_BARS.getBlockData(), Blocks.IRON_BARS.getBlockData(), false); + this.a(world, structureboundingbox, 5, 1, 5, 7, 3, 5, Blocks.IRON_BARS.getBlockData(), Blocks.IRON_BARS.getBlockData(), false); + this.a(world, Blocks.IRON_BARS.getBlockData(), 4, 3, 2, structureboundingbox); + this.a(world, Blocks.IRON_BARS.getBlockData(), 4, 3, 8, structureboundingbox); + this.a(world, Blocks.IRON_DOOR.fromLegacyData(this.a(Blocks.IRON_DOOR, 3)), 4, 1, 2, structureboundingbox); + this.a(world, Blocks.IRON_DOOR.fromLegacyData(this.a(Blocks.IRON_DOOR, 3) + 8), 4, 2, 2, structureboundingbox); + this.a(world, Blocks.IRON_DOOR.fromLegacyData(this.a(Blocks.IRON_DOOR, 3)), 4, 1, 8, structureboundingbox); + this.a(world, Blocks.IRON_DOOR.fromLegacyData(this.a(Blocks.IRON_DOOR, 3) + 8), 4, 2, 8, structureboundingbox); + return true; + } + } + } + + public static class WorldGenStrongholdRoomCrossing extends WorldGenStrongholdPiece { + + private static final List b = Lists.newArrayList(new StructurePieceTreasure(Items.IRON_INGOT, 0, 1, 5, 10), new StructurePieceTreasure(Items.GOLD_INGOT, 0, 1, 3, 5), new StructurePieceTreasure(Items.REDSTONE, 0, 4, 9, 5), new StructurePieceTreasure(Items.COAL, 0, 3, 8, 10), new StructurePieceTreasure(Items.BREAD, 0, 1, 3, 15), new StructurePieceTreasure(Items.APPLE, 0, 1, 3, 15), new StructurePieceTreasure(Items.IRON_PICKAXE, 0, 1, 1, 1)); + protected int a; + + public WorldGenStrongholdRoomCrossing() { + } + + public WorldGenStrongholdRoomCrossing(int i, Random random, StructureBoundingBox structureboundingbox, EnumDirection enumdirection) { + super(i); + this.m = enumdirection; + this.d = this.a(random); + this.l = structureboundingbox; + this.a = random.nextInt(5); + } + + protected void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + nbttagcompound.setInt("Type", this.a); + } + + protected void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + this.a = nbttagcompound.getInt("Type"); + } + + public void a(StructurePiece structurepiece, List list, Random random) { + this.a((WorldGenStrongholdStart) structurepiece, list, random, 4, 1); + this.b((WorldGenStrongholdStart) structurepiece, list, random, 1, 4); + this.c((WorldGenStrongholdStart) structurepiece, list, random, 1, 4); + } + + public static WorldGenStrongholdRoomCrossing a(List list, Random random, int i, int j, int k, EnumDirection enumdirection, int l) { + StructureBoundingBox structureboundingbox = StructureBoundingBox.a(i, j, k, -4, -1, 0, 11, 7, 11, enumdirection); + + return a(structureboundingbox) && StructurePiece.a(list, structureboundingbox) == null ? new WorldGenStrongholdRoomCrossing(l, random, structureboundingbox, enumdirection) : null; + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + if (this.a(world, structureboundingbox)) { + return false; + } else { + this.a(world, structureboundingbox, 0, 0, 0, 10, 6, 10, true, random, WorldGenStrongholdPieces.e); + this.a(world, random, structureboundingbox, this.d, 4, 1, 0); + this.a(world, structureboundingbox, 4, 1, 10, 6, 3, 10, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, 0, 1, 4, 0, 3, 6, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, 10, 1, 4, 10, 3, 6, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + int i; + + switch (this.a) { + case 0: + this.a(world, Blocks.STONEBRICK.getBlockData(), 5, 1, 5, structureboundingbox); + this.a(world, Blocks.STONEBRICK.getBlockData(), 5, 2, 5, structureboundingbox); + this.a(world, Blocks.STONEBRICK.getBlockData(), 5, 3, 5, structureboundingbox); + this.a(world, Blocks.TORCH.getBlockData(), 4, 3, 5, structureboundingbox); + this.a(world, Blocks.TORCH.getBlockData(), 6, 3, 5, structureboundingbox); + this.a(world, Blocks.TORCH.getBlockData(), 5, 3, 4, structureboundingbox); + this.a(world, Blocks.TORCH.getBlockData(), 5, 3, 6, structureboundingbox); + this.a(world, Blocks.STONE_SLAB.getBlockData(), 4, 1, 4, structureboundingbox); + this.a(world, Blocks.STONE_SLAB.getBlockData(), 4, 1, 5, structureboundingbox); + this.a(world, Blocks.STONE_SLAB.getBlockData(), 4, 1, 6, structureboundingbox); + this.a(world, Blocks.STONE_SLAB.getBlockData(), 6, 1, 4, structureboundingbox); + this.a(world, Blocks.STONE_SLAB.getBlockData(), 6, 1, 5, structureboundingbox); + this.a(world, Blocks.STONE_SLAB.getBlockData(), 6, 1, 6, structureboundingbox); + this.a(world, Blocks.STONE_SLAB.getBlockData(), 5, 1, 4, structureboundingbox); + this.a(world, Blocks.STONE_SLAB.getBlockData(), 5, 1, 6, structureboundingbox); + break; + + case 1: + for (i = 0; i < 5; ++i) { + this.a(world, Blocks.STONEBRICK.getBlockData(), 3, 1, 3 + i, structureboundingbox); + this.a(world, Blocks.STONEBRICK.getBlockData(), 7, 1, 3 + i, structureboundingbox); + this.a(world, Blocks.STONEBRICK.getBlockData(), 3 + i, 1, 3, structureboundingbox); + this.a(world, Blocks.STONEBRICK.getBlockData(), 3 + i, 1, 7, structureboundingbox); + } + + this.a(world, Blocks.STONEBRICK.getBlockData(), 5, 1, 5, structureboundingbox); + this.a(world, Blocks.STONEBRICK.getBlockData(), 5, 2, 5, structureboundingbox); + this.a(world, Blocks.STONEBRICK.getBlockData(), 5, 3, 5, structureboundingbox); + this.a(world, Blocks.FLOWING_WATER.getBlockData(), 5, 4, 5, structureboundingbox); + break; + + case 2: + for (i = 1; i <= 9; ++i) { + this.a(world, Blocks.COBBLESTONE.getBlockData(), 1, 3, i, structureboundingbox); + this.a(world, Blocks.COBBLESTONE.getBlockData(), 9, 3, i, structureboundingbox); + } + + for (i = 1; i <= 9; ++i) { + this.a(world, Blocks.COBBLESTONE.getBlockData(), i, 3, 1, structureboundingbox); + this.a(world, Blocks.COBBLESTONE.getBlockData(), i, 3, 9, structureboundingbox); + } + + this.a(world, Blocks.COBBLESTONE.getBlockData(), 5, 1, 4, structureboundingbox); + this.a(world, Blocks.COBBLESTONE.getBlockData(), 5, 1, 6, structureboundingbox); + this.a(world, Blocks.COBBLESTONE.getBlockData(), 5, 3, 4, structureboundingbox); + this.a(world, Blocks.COBBLESTONE.getBlockData(), 5, 3, 6, structureboundingbox); + this.a(world, Blocks.COBBLESTONE.getBlockData(), 4, 1, 5, structureboundingbox); + this.a(world, Blocks.COBBLESTONE.getBlockData(), 6, 1, 5, structureboundingbox); + this.a(world, Blocks.COBBLESTONE.getBlockData(), 4, 3, 5, structureboundingbox); + this.a(world, Blocks.COBBLESTONE.getBlockData(), 6, 3, 5, structureboundingbox); + + for (i = 1; i <= 3; ++i) { + this.a(world, Blocks.COBBLESTONE.getBlockData(), 4, i, 4, structureboundingbox); + this.a(world, Blocks.COBBLESTONE.getBlockData(), 6, i, 4, structureboundingbox); + this.a(world, Blocks.COBBLESTONE.getBlockData(), 4, i, 6, structureboundingbox); + this.a(world, Blocks.COBBLESTONE.getBlockData(), 6, i, 6, structureboundingbox); + } + + this.a(world, Blocks.TORCH.getBlockData(), 5, 3, 5, structureboundingbox); + + for (i = 2; i <= 8; ++i) { + this.a(world, Blocks.PLANKS.getBlockData(), 2, 3, i, structureboundingbox); + this.a(world, Blocks.PLANKS.getBlockData(), 3, 3, i, structureboundingbox); + if (i <= 3 || i >= 7) { + this.a(world, Blocks.PLANKS.getBlockData(), 4, 3, i, structureboundingbox); + this.a(world, Blocks.PLANKS.getBlockData(), 5, 3, i, structureboundingbox); + this.a(world, Blocks.PLANKS.getBlockData(), 6, 3, i, structureboundingbox); + } + + this.a(world, Blocks.PLANKS.getBlockData(), 7, 3, i, structureboundingbox); + this.a(world, Blocks.PLANKS.getBlockData(), 8, 3, i, structureboundingbox); + } + + this.a(world, Blocks.LADDER.fromLegacyData(this.a(Blocks.LADDER, EnumDirection.WEST.a())), 9, 1, 3, structureboundingbox); + this.a(world, Blocks.LADDER.fromLegacyData(this.a(Blocks.LADDER, EnumDirection.WEST.a())), 9, 2, 3, structureboundingbox); + this.a(world, Blocks.LADDER.fromLegacyData(this.a(Blocks.LADDER, EnumDirection.WEST.a())), 9, 3, 3, structureboundingbox); + this.a(world, structureboundingbox, random, 3, 4, 8, StructurePieceTreasure.a(WorldGenStrongholdRoomCrossing.b, Items.ENCHANTED_BOOK.b(random)), 1 + random.nextInt(4)); + } + + return true; + } + } + } + + public static class WorldGenStrongholdRightTurn extends WorldGenStrongholdLeftTurn { + + public WorldGenStrongholdRightTurn() { + } + + public void a(StructurePiece structurepiece, List list, Random random) { + if (this.m != EnumDirection.NORTH && this.m != EnumDirection.EAST) { + this.b((WorldGenStrongholdStart) structurepiece, list, random, 1, 1); + } else { + this.c((WorldGenStrongholdStart) structurepiece, list, random, 1, 1); + } + + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + if (this.a(world, structureboundingbox)) { + return false; + } else { + this.a(world, structureboundingbox, 0, 0, 0, 4, 4, 4, true, random, WorldGenStrongholdPieces.e); + this.a(world, random, structureboundingbox, this.d, 1, 1, 0); + if (this.m != EnumDirection.NORTH && this.m != EnumDirection.EAST) { + this.a(world, structureboundingbox, 0, 1, 1, 0, 3, 3, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + } else { + this.a(world, structureboundingbox, 4, 1, 1, 4, 3, 3, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + } + + return true; + } + } + } + + public static class WorldGenStrongholdLeftTurn extends WorldGenStrongholdPiece { + + public WorldGenStrongholdLeftTurn() { + } + + public WorldGenStrongholdLeftTurn(int i, Random random, StructureBoundingBox structureboundingbox, EnumDirection enumdirection) { + super(i); + this.m = enumdirection; + this.d = this.a(random); + this.l = structureboundingbox; + } + + public void a(StructurePiece structurepiece, List list, Random random) { + if (this.m != EnumDirection.NORTH && this.m != EnumDirection.EAST) { + this.c((WorldGenStrongholdStart) structurepiece, list, random, 1, 1); + } else { + this.b((WorldGenStrongholdStart) structurepiece, list, random, 1, 1); + } + + } + + public static WorldGenStrongholdLeftTurn a(List list, Random random, int i, int j, int k, EnumDirection enumdirection, int l) { + StructureBoundingBox structureboundingbox = StructureBoundingBox.a(i, j, k, -1, -1, 0, 5, 5, 5, enumdirection); + + return a(structureboundingbox) && StructurePiece.a(list, structureboundingbox) == null ? new WorldGenStrongholdLeftTurn(l, random, structureboundingbox, enumdirection) : null; + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + if (this.a(world, structureboundingbox)) { + return false; + } else { + this.a(world, structureboundingbox, 0, 0, 0, 4, 4, 4, true, random, WorldGenStrongholdPieces.e); + this.a(world, random, structureboundingbox, this.d, 1, 1, 0); + if (this.m != EnumDirection.NORTH && this.m != EnumDirection.EAST) { + this.a(world, structureboundingbox, 4, 1, 1, 4, 3, 3, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + } else { + this.a(world, structureboundingbox, 0, 1, 1, 0, 3, 3, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + } + + return true; + } + } + } + + public static class WorldGenStrongholdStairsStraight extends WorldGenStrongholdPiece { + + public WorldGenStrongholdStairsStraight() { + } + + public WorldGenStrongholdStairsStraight(int i, Random random, StructureBoundingBox structureboundingbox, EnumDirection enumdirection) { + super(i); + this.m = enumdirection; + this.d = this.a(random); + this.l = structureboundingbox; + } + + public void a(StructurePiece structurepiece, List list, Random random) { + this.a((WorldGenStrongholdStart) structurepiece, list, random, 1, 1); + } + + public static WorldGenStrongholdStairsStraight a(List list, Random random, int i, int j, int k, EnumDirection enumdirection, int l) { + StructureBoundingBox structureboundingbox = StructureBoundingBox.a(i, j, k, -1, -7, 0, 5, 11, 8, enumdirection); + + return a(structureboundingbox) && StructurePiece.a(list, structureboundingbox) == null ? new WorldGenStrongholdStairsStraight(l, random, structureboundingbox, enumdirection) : null; + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + if (this.a(world, structureboundingbox)) { + return false; + } else { + this.a(world, structureboundingbox, 0, 0, 0, 4, 10, 7, true, random, WorldGenStrongholdPieces.e); + this.a(world, random, structureboundingbox, this.d, 1, 7, 0); + this.a(world, random, structureboundingbox, WorldGenStrongholdPiece$WorldGenStrongholdDoorType.OPENING, 1, 1, 7); + int i = this.a(Blocks.STONE_STAIRS, 2); + + for (int j = 0; j < 6; ++j) { + this.a(world, Blocks.STONE_STAIRS.fromLegacyData(i), 1, 6 - j, 1 + j, structureboundingbox); + this.a(world, Blocks.STONE_STAIRS.fromLegacyData(i), 2, 6 - j, 1 + j, structureboundingbox); + this.a(world, Blocks.STONE_STAIRS.fromLegacyData(i), 3, 6 - j, 1 + j, structureboundingbox); + if (j < 5) { + this.a(world, Blocks.STONEBRICK.getBlockData(), 1, 5 - j, 1 + j, structureboundingbox); + this.a(world, Blocks.STONEBRICK.getBlockData(), 2, 5 - j, 1 + j, structureboundingbox); + this.a(world, Blocks.STONEBRICK.getBlockData(), 3, 5 - j, 1 + j, structureboundingbox); + } + } + + return true; + } + } + } + + public static class WorldGenStrongholdChestCorridor extends WorldGenStrongholdPiece { + + private static final List a = Lists.newArrayList(new StructurePieceTreasure(Items.ENDER_PEARL, 0, 1, 1, 10), new StructurePieceTreasure(Items.DIAMOND, 0, 1, 3, 3), new StructurePieceTreasure(Items.IRON_INGOT, 0, 1, 5, 10), new StructurePieceTreasure(Items.GOLD_INGOT, 0, 1, 3, 5), new StructurePieceTreasure(Items.REDSTONE, 0, 4, 9, 5), new StructurePieceTreasure(Items.BREAD, 0, 1, 3, 15), new StructurePieceTreasure(Items.APPLE, 0, 1, 3, 15), new StructurePieceTreasure(Items.IRON_PICKAXE, 0, 1, 1, 5), new StructurePieceTreasure(Items.IRON_SWORD, 0, 1, 1, 5), new StructurePieceTreasure(Items.IRON_CHESTPLATE, 0, 1, 1, 5), new StructurePieceTreasure(Items.IRON_HELMET, 0, 1, 1, 5), new StructurePieceTreasure(Items.IRON_LEGGINGS, 0, 1, 1, 5), new StructurePieceTreasure(Items.IRON_BOOTS, 0, 1, 1, 5), new StructurePieceTreasure(Items.GOLDEN_APPLE, 0, 1, 1, 1), new StructurePieceTreasure(Items.SADDLE, 0, 1, 1, 1), new StructurePieceTreasure(Items.IRON_HORSE_ARMOR, 0, 1, 1, 1), new StructurePieceTreasure(Items.GOLDEN_HORSE_ARMOR, 0, 1, 1, 1), new StructurePieceTreasure(Items.DIAMOND_HORSE_ARMOR, 0, 1, 1, 1)); + private boolean b; + + public WorldGenStrongholdChestCorridor() { + } + + public WorldGenStrongholdChestCorridor(int i, Random random, StructureBoundingBox structureboundingbox, EnumDirection enumdirection) { + super(i); + this.m = enumdirection; + this.d = this.a(random); + this.l = structureboundingbox; + } + + protected void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + nbttagcompound.setBoolean("Chest", this.b); + } + + protected void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + this.b = nbttagcompound.getBoolean("Chest"); + } + + public void a(StructurePiece structurepiece, List list, Random random) { + this.a((WorldGenStrongholdStart) structurepiece, list, random, 1, 1); + } + + public static WorldGenStrongholdChestCorridor a(List list, Random random, int i, int j, int k, EnumDirection enumdirection, int l) { + StructureBoundingBox structureboundingbox = StructureBoundingBox.a(i, j, k, -1, -1, 0, 5, 5, 7, enumdirection); + + return a(structureboundingbox) && StructurePiece.a(list, structureboundingbox) == null ? new WorldGenStrongholdChestCorridor(l, random, structureboundingbox, enumdirection) : null; + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + if (this.a(world, structureboundingbox)) { + return false; + } else { + this.a(world, structureboundingbox, 0, 0, 0, 4, 4, 6, true, random, WorldGenStrongholdPieces.e); + this.a(world, random, structureboundingbox, this.d, 1, 1, 0); + this.a(world, random, structureboundingbox, WorldGenStrongholdPiece$WorldGenStrongholdDoorType.OPENING, 1, 1, 6); + this.a(world, structureboundingbox, 3, 1, 2, 3, 1, 4, Blocks.STONEBRICK.getBlockData(), Blocks.STONEBRICK.getBlockData(), false); + this.a(world, Blocks.STONE_SLAB.fromLegacyData(BlockDoubleStepAbstract.EnumStoneSlabVariant.SMOOTHBRICK.a()), 3, 1, 1, structureboundingbox); + this.a(world, Blocks.STONE_SLAB.fromLegacyData(BlockDoubleStepAbstract.EnumStoneSlabVariant.SMOOTHBRICK.a()), 3, 1, 5, structureboundingbox); + this.a(world, Blocks.STONE_SLAB.fromLegacyData(BlockDoubleStepAbstract.EnumStoneSlabVariant.SMOOTHBRICK.a()), 3, 2, 2, structureboundingbox); + this.a(world, Blocks.STONE_SLAB.fromLegacyData(BlockDoubleStepAbstract.EnumStoneSlabVariant.SMOOTHBRICK.a()), 3, 2, 4, structureboundingbox); + + for (int i = 2; i <= 4; ++i) { + this.a(world, Blocks.STONE_SLAB.fromLegacyData(BlockDoubleStepAbstract.EnumStoneSlabVariant.SMOOTHBRICK.a()), 2, 1, i, structureboundingbox); + } + + if (!this.b && structureboundingbox.b(this.a(3, 3), this.d(2), this.b(3, 3))) { + this.b = true; + this.a(world, structureboundingbox, random, 3, 2, 3, StructurePieceTreasure.a(WorldGenStrongholdChestCorridor.a, Items.ENCHANTED_BOOK.b(random)), 2 + random.nextInt(2)); + } + + return true; + } + } + } + + public static class WorldGenStrongholdStairs extends WorldGenStrongholdPiece { + + private boolean a; + private boolean b; + + public WorldGenStrongholdStairs() { + } + + public WorldGenStrongholdStairs(int i, Random random, StructureBoundingBox structureboundingbox, EnumDirection enumdirection) { + super(i); + this.m = enumdirection; + this.d = this.a(random); + this.l = structureboundingbox; + this.a = random.nextInt(2) == 0; + this.b = random.nextInt(2) == 0; + } + + protected void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + nbttagcompound.setBoolean("Left", this.a); + nbttagcompound.setBoolean("Right", this.b); + } + + protected void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + this.a = nbttagcompound.getBoolean("Left"); + this.b = nbttagcompound.getBoolean("Right"); + } + + public void a(StructurePiece structurepiece, List list, Random random) { + this.a((WorldGenStrongholdStart) structurepiece, list, random, 1, 1); + if (this.a) { + this.b((WorldGenStrongholdStart) structurepiece, list, random, 1, 2); + } + + if (this.b) { + this.c((WorldGenStrongholdStart) structurepiece, list, random, 1, 2); + } + + } + + public static WorldGenStrongholdStairs a(List list, Random random, int i, int j, int k, EnumDirection enumdirection, int l) { + StructureBoundingBox structureboundingbox = StructureBoundingBox.a(i, j, k, -1, -1, 0, 5, 5, 7, enumdirection); + + return a(structureboundingbox) && StructurePiece.a(list, structureboundingbox) == null ? new WorldGenStrongholdStairs(l, random, structureboundingbox, enumdirection) : null; + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + if (this.a(world, structureboundingbox)) { + return false; + } else { + this.a(world, structureboundingbox, 0, 0, 0, 4, 4, 6, true, random, WorldGenStrongholdPieces.e); + this.a(world, random, structureboundingbox, this.d, 1, 1, 0); + this.a(world, random, structureboundingbox, WorldGenStrongholdPiece$WorldGenStrongholdDoorType.OPENING, 1, 1, 6); + this.a(world, structureboundingbox, random, 0.1F, 1, 2, 1, Blocks.TORCH.getBlockData()); + this.a(world, structureboundingbox, random, 0.1F, 3, 2, 1, Blocks.TORCH.getBlockData()); + this.a(world, structureboundingbox, random, 0.1F, 1, 2, 5, Blocks.TORCH.getBlockData()); + this.a(world, structureboundingbox, random, 0.1F, 3, 2, 5, Blocks.TORCH.getBlockData()); + if (this.a) { + this.a(world, structureboundingbox, 0, 1, 2, 0, 3, 4, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + } + + if (this.b) { + this.a(world, structureboundingbox, 4, 1, 2, 4, 3, 4, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + } + + return true; + } + } + } + + public static class WorldGenStrongholdStart extends WorldGenStrongholdStairs2 { + + public WorldGenStrongholdPieceWeight a; + public WorldGenStrongholdPortalRoom b; + public List c = Lists.newArrayList(); + + public WorldGenStrongholdStart() { + } + + public WorldGenStrongholdStart(int i, Random random, int j, int k) { + super(0, random, j, k); + } + + public BlockPosition a() { + return this.b != null ? this.b.a() : super.a(); + } + } + + public static class WorldGenStrongholdStairs2 extends WorldGenStrongholdPiece { + + private boolean a; + + public WorldGenStrongholdStairs2() { + } + + public WorldGenStrongholdStairs2(int i, Random random, int j, int k) { + super(i); + this.a = true; + this.m = EnumDirection.EnumDirectionLimit.HORIZONTAL.a(random); + this.d = WorldGenStrongholdPiece$WorldGenStrongholdDoorType.OPENING; + switch (WorldGenStrongholdPieces.SyntheticClass_1.b[this.m.ordinal()]) { + case 1: + case 2: + + default: + this.l = new StructureBoundingBox(j, 64, k, j + 5 - 1, 74, k + 5 - 1); + } + + } + + public WorldGenStrongholdStairs2(int i, Random random, StructureBoundingBox structureboundingbox, EnumDirection enumdirection) { + super(i); + this.a = false; + this.m = enumdirection; + this.d = this.a(random); + this.l = structureboundingbox; + } + + protected void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + nbttagcompound.setBoolean("Source", this.a); + } + + protected void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + this.a = nbttagcompound.getBoolean("Source"); + } + + public void a(StructurePiece structurepiece, List list, Random random) { + if (this.a) { + WorldGenStrongholdPieces.d = WorldGenStrongholdCrossing.class; + } + + this.a((WorldGenStrongholdStart) structurepiece, list, random, 1, 1); + } + + public static WorldGenStrongholdStairs2 a(List list, Random random, int i, int j, int k, EnumDirection enumdirection, int l) { + StructureBoundingBox structureboundingbox = StructureBoundingBox.a(i, j, k, -1, -7, 0, 5, 11, 5, enumdirection); + + return a(structureboundingbox) && StructurePiece.a(list, structureboundingbox) == null ? new WorldGenStrongholdStairs2(l, random, structureboundingbox, enumdirection) : null; + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + if (this.a(world, structureboundingbox)) { + return false; + } else { + this.a(world, structureboundingbox, 0, 0, 0, 4, 10, 4, true, random, WorldGenStrongholdPieces.e); + this.a(world, random, structureboundingbox, this.d, 1, 7, 0); + this.a(world, random, structureboundingbox, WorldGenStrongholdPiece$WorldGenStrongholdDoorType.OPENING, 1, 1, 4); + this.a(world, Blocks.STONEBRICK.getBlockData(), 2, 6, 1, structureboundingbox); + this.a(world, Blocks.STONEBRICK.getBlockData(), 1, 5, 1, structureboundingbox); + this.a(world, Blocks.STONE_SLAB.fromLegacyData(BlockDoubleStepAbstract.EnumStoneSlabVariant.STONE.a()), 1, 6, 1, structureboundingbox); + this.a(world, Blocks.STONEBRICK.getBlockData(), 1, 5, 2, structureboundingbox); + this.a(world, Blocks.STONEBRICK.getBlockData(), 1, 4, 3, structureboundingbox); + this.a(world, Blocks.STONE_SLAB.fromLegacyData(BlockDoubleStepAbstract.EnumStoneSlabVariant.STONE.a()), 1, 5, 3, structureboundingbox); + this.a(world, Blocks.STONEBRICK.getBlockData(), 2, 4, 3, structureboundingbox); + this.a(world, Blocks.STONEBRICK.getBlockData(), 3, 3, 3, structureboundingbox); + this.a(world, Blocks.STONE_SLAB.fromLegacyData(BlockDoubleStepAbstract.EnumStoneSlabVariant.STONE.a()), 3, 4, 3, structureboundingbox); + this.a(world, Blocks.STONEBRICK.getBlockData(), 3, 3, 2, structureboundingbox); + this.a(world, Blocks.STONEBRICK.getBlockData(), 3, 2, 1, structureboundingbox); + this.a(world, Blocks.STONE_SLAB.fromLegacyData(BlockDoubleStepAbstract.EnumStoneSlabVariant.STONE.a()), 3, 3, 1, structureboundingbox); + this.a(world, Blocks.STONEBRICK.getBlockData(), 2, 2, 1, structureboundingbox); + this.a(world, Blocks.STONEBRICK.getBlockData(), 1, 1, 1, structureboundingbox); + this.a(world, Blocks.STONE_SLAB.fromLegacyData(BlockDoubleStepAbstract.EnumStoneSlabVariant.STONE.a()), 1, 2, 1, structureboundingbox); + this.a(world, Blocks.STONEBRICK.getBlockData(), 1, 1, 2, structureboundingbox); + this.a(world, Blocks.STONE_SLAB.fromLegacyData(BlockDoubleStepAbstract.EnumStoneSlabVariant.STONE.a()), 1, 1, 3, structureboundingbox); + return true; + } + } + } + + public static class WorldGenStrongholdCorridor extends WorldGenStrongholdPiece { + + private int a; + + public WorldGenStrongholdCorridor() { + } + + public WorldGenStrongholdCorridor(int i, Random random, StructureBoundingBox structureboundingbox, EnumDirection enumdirection) { + super(i); + this.m = enumdirection; + this.l = structureboundingbox; + this.a = enumdirection != EnumDirection.NORTH && enumdirection != EnumDirection.SOUTH ? structureboundingbox.c() : structureboundingbox.e(); + } + + protected void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + nbttagcompound.setInt("Steps", this.a); + } + + protected void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + this.a = nbttagcompound.getInt("Steps"); + } + + public static StructureBoundingBox a(List list, Random random, int i, int j, int k, EnumDirection enumdirection) { + boolean flag = true; + StructureBoundingBox structureboundingbox = StructureBoundingBox.a(i, j, k, -1, -1, 0, 5, 5, 4, enumdirection); + StructurePiece structurepiece = StructurePiece.a(list, structureboundingbox); + + if (structurepiece == null) { + return null; + } else { + if (structurepiece.c().b == structureboundingbox.b) { + for (int l = 3; l >= 1; --l) { + structureboundingbox = StructureBoundingBox.a(i, j, k, -1, -1, 0, 5, 5, l - 1, enumdirection); + if (!structurepiece.c().a(structureboundingbox)) { + return StructureBoundingBox.a(i, j, k, -1, -1, 0, 5, 5, l, enumdirection); + } + } + } + + return null; + } + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + if (this.a(world, structureboundingbox)) { + return false; + } else { + for (int i = 0; i < this.a; ++i) { + this.a(world, Blocks.STONEBRICK.getBlockData(), 0, 0, i, structureboundingbox); + this.a(world, Blocks.STONEBRICK.getBlockData(), 1, 0, i, structureboundingbox); + this.a(world, Blocks.STONEBRICK.getBlockData(), 2, 0, i, structureboundingbox); + this.a(world, Blocks.STONEBRICK.getBlockData(), 3, 0, i, structureboundingbox); + this.a(world, Blocks.STONEBRICK.getBlockData(), 4, 0, i, structureboundingbox); + + for (int j = 1; j <= 3; ++j) { + this.a(world, Blocks.STONEBRICK.getBlockData(), 0, j, i, structureboundingbox); + this.a(world, Blocks.AIR.getBlockData(), 1, j, i, structureboundingbox); + this.a(world, Blocks.AIR.getBlockData(), 2, j, i, structureboundingbox); + this.a(world, Blocks.AIR.getBlockData(), 3, j, i, structureboundingbox); + this.a(world, Blocks.STONEBRICK.getBlockData(), 4, j, i, structureboundingbox); + } + + this.a(world, Blocks.STONEBRICK.getBlockData(), 0, 4, i, structureboundingbox); + this.a(world, Blocks.STONEBRICK.getBlockData(), 1, 4, i, structureboundingbox); + this.a(world, Blocks.STONEBRICK.getBlockData(), 2, 4, i, structureboundingbox); + this.a(world, Blocks.STONEBRICK.getBlockData(), 3, 4, i, structureboundingbox); + this.a(world, Blocks.STONEBRICK.getBlockData(), 4, 4, i, structureboundingbox); + } + + return true; + } + } + } + + abstract static class WorldGenStrongholdPiece extends StructurePiece { + + protected WorldGenStrongholdPiece$WorldGenStrongholdDoorType d; + + public WorldGenStrongholdPiece() { + this.d = WorldGenStrongholdPiece$WorldGenStrongholdDoorType.OPENING; + } + + protected WorldGenStrongholdPiece(int i) { + super(i); + this.d = WorldGenStrongholdPiece$WorldGenStrongholdDoorType.OPENING; + } + + protected void a(NBTTagCompound nbttagcompound) { + nbttagcompound.setString("EntryDoor", this.d.name()); + } + + protected void b(NBTTagCompound nbttagcompound) { + this.d = WorldGenStrongholdPiece$WorldGenStrongholdDoorType.valueOf(nbttagcompound.getString("EntryDoor")); + } + + protected void a(World world, Random random, StructureBoundingBox structureboundingbox, WorldGenStrongholdPiece$WorldGenStrongholdDoorType worldgenstrongholdpieces_worldgenstrongholdpiece_worldgenstrongholdpiece$worldgenstrongholddoortype, int i, int j, int k) { + switch (SyntheticClass_1.a[worldgenstrongholdpieces_worldgenstrongholdpiece_worldgenstrongholdpiece$worldgenstrongholddoortype.ordinal()]) { + case 1: + default: + this.a(world, structureboundingbox, i, j, k, i + 3 - 1, j + 3 - 1, k, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + break; + + case 2: + this.a(world, Blocks.STONEBRICK.getBlockData(), i, j, k, structureboundingbox); + this.a(world, Blocks.STONEBRICK.getBlockData(), i, j + 1, k, structureboundingbox); + this.a(world, Blocks.STONEBRICK.getBlockData(), i, j + 2, k, structureboundingbox); + this.a(world, Blocks.STONEBRICK.getBlockData(), i + 1, j + 2, k, structureboundingbox); + this.a(world, Blocks.STONEBRICK.getBlockData(), i + 2, j + 2, k, structureboundingbox); + this.a(world, Blocks.STONEBRICK.getBlockData(), i + 2, j + 1, k, structureboundingbox); + this.a(world, Blocks.STONEBRICK.getBlockData(), i + 2, j, k, structureboundingbox); + this.a(world, Blocks.WOODEN_DOOR.getBlockData(), i + 1, j, k, structureboundingbox); + this.a(world, Blocks.WOODEN_DOOR.fromLegacyData(8), i + 1, j + 1, k, structureboundingbox); + break; + + case 3: + this.a(world, Blocks.AIR.getBlockData(), i + 1, j, k, structureboundingbox); + this.a(world, Blocks.AIR.getBlockData(), i + 1, j + 1, k, structureboundingbox); + this.a(world, Blocks.IRON_BARS.getBlockData(), i, j, k, structureboundingbox); + this.a(world, Blocks.IRON_BARS.getBlockData(), i, j + 1, k, structureboundingbox); + this.a(world, Blocks.IRON_BARS.getBlockData(), i, j + 2, k, structureboundingbox); + this.a(world, Blocks.IRON_BARS.getBlockData(), i + 1, j + 2, k, structureboundingbox); + this.a(world, Blocks.IRON_BARS.getBlockData(), i + 2, j + 2, k, structureboundingbox); + this.a(world, Blocks.IRON_BARS.getBlockData(), i + 2, j + 1, k, structureboundingbox); + this.a(world, Blocks.IRON_BARS.getBlockData(), i + 2, j, k, structureboundingbox); + break; + + case 4: + this.a(world, Blocks.STONEBRICK.getBlockData(), i, j, k, structureboundingbox); + this.a(world, Blocks.STONEBRICK.getBlockData(), i, j + 1, k, structureboundingbox); + this.a(world, Blocks.STONEBRICK.getBlockData(), i, j + 2, k, structureboundingbox); + this.a(world, Blocks.STONEBRICK.getBlockData(), i + 1, j + 2, k, structureboundingbox); + this.a(world, Blocks.STONEBRICK.getBlockData(), i + 2, j + 2, k, structureboundingbox); + this.a(world, Blocks.STONEBRICK.getBlockData(), i + 2, j + 1, k, structureboundingbox); + this.a(world, Blocks.STONEBRICK.getBlockData(), i + 2, j, k, structureboundingbox); + this.a(world, Blocks.IRON_DOOR.getBlockData(), i + 1, j, k, structureboundingbox); + this.a(world, Blocks.IRON_DOOR.fromLegacyData(8), i + 1, j + 1, k, structureboundingbox); + this.a(world, Blocks.STONE_BUTTON.fromLegacyData(this.a(Blocks.STONE_BUTTON, 4)), i + 2, j + 1, k + 1, structureboundingbox); + this.a(world, Blocks.STONE_BUTTON.fromLegacyData(this.a(Blocks.STONE_BUTTON, 3)), i + 2, j + 1, k - 1, structureboundingbox); + } + + } + + protected WorldGenStrongholdPiece$WorldGenStrongholdDoorType a(Random random) { + int i = random.nextInt(5); + + switch (i) { + case 0: + case 1: + default: + return WorldGenStrongholdPiece$WorldGenStrongholdDoorType.OPENING; + + case 2: + return WorldGenStrongholdPiece$WorldGenStrongholdDoorType.WOOD_DOOR; + + case 3: + return WorldGenStrongholdPiece$WorldGenStrongholdDoorType.GRATES; + + case 4: + return WorldGenStrongholdPiece$WorldGenStrongholdDoorType.IRON_DOOR; + } + } + + protected StructurePiece a(WorldGenStrongholdStart worldgenstrongholdpieces_worldgenstrongholdstart, List list, Random random, int i, int j) { + if (this.m != null) { + switch (WorldGenStrongholdPieces.SyntheticClass_1.b[this.m.ordinal()]) { + case 1: + return WorldGenStrongholdPieces.c(worldgenstrongholdpieces_worldgenstrongholdstart, list, random, this.l.a + i, this.l.b + j, this.l.c - 1, this.m, this.d()); + + case 2: + return WorldGenStrongholdPieces.c(worldgenstrongholdpieces_worldgenstrongholdstart, list, random, this.l.a + i, this.l.b + j, this.l.f + 1, this.m, this.d()); + + case 3: + return WorldGenStrongholdPieces.c(worldgenstrongholdpieces_worldgenstrongholdstart, list, random, this.l.a - 1, this.l.b + j, this.l.c + i, this.m, this.d()); + + case 4: + return WorldGenStrongholdPieces.c(worldgenstrongholdpieces_worldgenstrongholdstart, list, random, this.l.d + 1, this.l.b + j, this.l.c + i, this.m, this.d()); + } + } + + return null; + } + + protected StructurePiece b(WorldGenStrongholdStart worldgenstrongholdpieces_worldgenstrongholdstart, List list, Random random, int i, int j) { + if (this.m != null) { + switch (WorldGenStrongholdPieces.SyntheticClass_1.b[this.m.ordinal()]) { + case 1: + + case 2: + return WorldGenStrongholdPieces.c(worldgenstrongholdpieces_worldgenstrongholdstart, list, random, this.l.a - 1, this.l.b + i, this.l.c + j, EnumDirection.WEST, this.d()); + + case 3: + + case 4: + return WorldGenStrongholdPieces.c(worldgenstrongholdpieces_worldgenstrongholdstart, list, random, this.l.a + j, this.l.b + i, this.l.c - 1, EnumDirection.NORTH, this.d()); + } + } + + return null; + } + + protected StructurePiece c(WorldGenStrongholdStart worldgenstrongholdpieces_worldgenstrongholdstart, List list, Random random, int i, int j) { + if (this.m != null) { + switch (WorldGenStrongholdPieces.SyntheticClass_1.b[this.m.ordinal()]) { + case 1: + + case 2: + return WorldGenStrongholdPieces.c(worldgenstrongholdpieces_worldgenstrongholdstart, list, random, this.l.d + 1, this.l.b + i, this.l.c + j, EnumDirection.EAST, this.d()); + + case 3: + + case 4: + return WorldGenStrongholdPieces.c(worldgenstrongholdpieces_worldgenstrongholdstart, list, random, this.l.a + j, this.l.b + i, this.l.f + 1, EnumDirection.SOUTH, this.d()); + } + } + + return null; + } + + protected static boolean a(StructureBoundingBox structureboundingbox) { + return structureboundingbox != null && structureboundingbox.b > 10; + } + + public enum WorldGenStrongholdPiece$WorldGenStrongholdDoorType { + + OPENING, WOOD_DOOR, GRATES, IRON_DOOR; + + WorldGenStrongholdPiece$WorldGenStrongholdDoorType() { + } + } + } + + static class WorldGenStrongholdPieceWeight { + + public Class a; + public final int b; + public int c; + public int d; + + public WorldGenStrongholdPieceWeight(Class oclass, int i, int j) { + this.a = oclass; + this.b = i; + this.d = j; + } + + public boolean a(int i) { + return this.d == 0 || this.c < this.d; + } + + public boolean a() { + return this.d == 0 || this.c < this.d; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenSwampTree.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenSwampTree.java new file mode 100644 index 0000000..64f77f3 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenSwampTree.java @@ -0,0 +1,155 @@ +package net.minecraft.server; + +import java.util.Random; + +public class WorldGenSwampTree extends WorldGenTreeAbstract { + + private static final IBlockData a = Blocks.LOG.getBlockData().set(BlockLog1.VARIANT, BlockWood.EnumLogVariant.OAK); + private static final IBlockData b = Blocks.LEAVES.getBlockData().set(BlockLeaves1.VARIANT, BlockWood.EnumLogVariant.OAK).set(BlockLeaves1.CHECK_DECAY, Boolean.FALSE); + + public WorldGenSwampTree() { + super(false); + } + + public boolean generate(World world, Random random, BlockPosition blockposition) { + int i; + + for (i = random.nextInt(4) + 5; world.getType(blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()).getBlock().getMaterial() == Material.WATER; blockposition = blockposition.down()) { + } + + boolean flag = true; + + if (blockposition.getY() >= 1 && blockposition.getY() + i + 1 <= 256) { + int j; + int k; + + for (int l = blockposition.getY(); l <= blockposition.getY() + 1 + i; ++l) { + byte b0 = 1; + + if (l == blockposition.getY()) { + b0 = 0; + } + + if (l >= blockposition.getY() + 1 + i - 2) { + b0 = 3; + } + + for (j = blockposition.getX() - b0; j <= blockposition.getX() + b0 && flag; ++j) { + for (k = blockposition.getZ() - b0; k <= blockposition.getZ() + b0 && flag; ++k) { + if (l >= 0 && l < 256) { + Block block = world.getType(j, l, k).getBlock(); + + if (block.getMaterial() != Material.AIR && block.getMaterial() != Material.LEAVES) { + if (block != Blocks.WATER && block != Blocks.FLOWING_WATER) { + flag = false; + } else if (l > blockposition.getY()) { + flag = false; + } + } + } else { + flag = false; + } + } + } + } + + if (!flag) { + return false; + } else { + Block block1 = world.getType(blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()).getBlock(); + + if ((block1 == Blocks.GRASS || block1 == Blocks.DIRT) && blockposition.getY() < 256 - i - 1) { + this.a(world, blockposition.down()); + + int i1; + BlockPosition blockposition1; + int j1; + int k1; + int l1; + + for (j1 = blockposition.getY() - 3 + i; j1 <= blockposition.getY() + i; ++j1) { + k1 = j1 - (blockposition.getY() + i); + j = 2 - k1 / 2; + + for (k = blockposition.getX() - j; k <= blockposition.getX() + j; ++k) { + l1 = k - blockposition.getX(); + + for (i1 = blockposition.getZ() - j; i1 <= blockposition.getZ() + j; ++i1) { + int i2 = i1 - blockposition.getZ(); + + if (Math.abs(l1) != j || Math.abs(i2) != j || random.nextInt(2) != 0 && k1 != 0) { + blockposition1 = new BlockPosition(k, j1, i1); + if (!world.getType(blockposition1).getBlock().o()) { + this.a(world, blockposition1, WorldGenSwampTree.b); + } + } + } + } + } + + for (j1 = 0; j1 < i; ++j1) { + Block block2 = world.getType(blockposition.up(j1)).getBlock(); + + if (block2.getMaterial() == Material.AIR || block2.getMaterial() == Material.LEAVES || block2 == Blocks.FLOWING_WATER || block2 == Blocks.WATER) { + this.a(world, blockposition.up(j1), WorldGenSwampTree.a); + } + } + + for (j1 = blockposition.getY() - 3 + i; j1 <= blockposition.getY() + i; ++j1) { + k1 = j1 - (blockposition.getY() + i); + j = 2 - k1 / 2; + BlockPosition.MutableBlockPosition blockposition_mutableblockposition1 = new BlockPosition.MutableBlockPosition(); + + for (l1 = blockposition.getX() - j; l1 <= blockposition.getX() + j; ++l1) { + for (i1 = blockposition.getZ() - j; i1 <= blockposition.getZ() + j; ++i1) { + blockposition_mutableblockposition1.c(l1, j1, i1); + if (world.getType(blockposition_mutableblockposition1).getBlock().getMaterial() == Material.LEAVES) { + BlockPosition blockposition2 = blockposition_mutableblockposition1.west(); + + blockposition1 = blockposition_mutableblockposition1.east(); + BlockPosition blockposition3 = blockposition_mutableblockposition1.north(); + BlockPosition blockposition4 = blockposition_mutableblockposition1.south(); + + if (random.nextInt(4) == 0 && world.getType(blockposition2).getBlock().getMaterial() == Material.AIR) { + this.a(world, blockposition2, BlockVine.EAST); + } + + if (random.nextInt(4) == 0 && world.getType(blockposition1).getBlock().getMaterial() == Material.AIR) { + this.a(world, blockposition1, BlockVine.WEST); + } + + if (random.nextInt(4) == 0 && world.getType(blockposition3).getBlock().getMaterial() == Material.AIR) { + this.a(world, blockposition3, BlockVine.SOUTH); + } + + if (random.nextInt(4) == 0 && world.getType(blockposition4).getBlock().getMaterial() == Material.AIR) { + this.a(world, blockposition4, BlockVine.NORTH); + } + } + } + } + } + + return true; + } else { + return false; + } + } + } else { + return false; + } + } + + private void a(World world, BlockPosition blockposition, BlockStateBoolean blockstateboolean) { + IBlockData iblockdata = Blocks.VINE.getBlockData().set(blockstateboolean, true); + + this.a(world, blockposition, iblockdata); + int i = 4; + + for (blockposition = blockposition.down(); world.getType(blockposition).getBlock().getMaterial() == Material.AIR && i > 0; --i) { + this.a(world, blockposition, iblockdata); + blockposition = blockposition.down(); + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenTaiga1.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenTaiga1.java new file mode 100644 index 0000000..79913d3 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenTaiga1.java @@ -0,0 +1,97 @@ +package net.minecraft.server; + +import java.util.Random; + +public class WorldGenTaiga1 extends WorldGenTreeAbstract { + + private static final IBlockData a = Blocks.LOG.getBlockData().set(BlockLog1.VARIANT, BlockWood.EnumLogVariant.SPRUCE); + private static final IBlockData b = Blocks.LEAVES.getBlockData().set(BlockLeaves1.VARIANT, BlockWood.EnumLogVariant.SPRUCE).set(BlockLeaves.CHECK_DECAY, Boolean.FALSE); + + public WorldGenTaiga1() { + super(false); + } + + public boolean generate(World world, Random random, BlockPosition blockposition) { + int i = random.nextInt(5) + 7; + int j = i - random.nextInt(2) - 3; + int k = i - j; + int l = 1 + random.nextInt(k + 1); + boolean flag = true; + + if (blockposition.getY() >= 1 && blockposition.getY() + i + 1 <= 256) { + int i1; + int j1; + int k1; + + for (int l1 = blockposition.getY(); l1 <= blockposition.getY() + 1 + i && flag; ++l1) { + + if (l1 - blockposition.getY() < j) { + k1 = 0; + } else { + k1 = l; + } + + for (i1 = blockposition.getX() - k1; i1 <= blockposition.getX() + k1 && flag; ++i1) { + for (j1 = blockposition.getZ() - k1; j1 <= blockposition.getZ() + k1 && flag; ++j1) { + if (l1 >= 0 && l1 < 256) { + if (!this.a(world.getType(i1, l1, j1).getBlock())) { + flag = false; + } + } else { + flag = false; + } + } + } + } + + if (!flag) { + return false; + } else { + Block block = world.getType(blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()).getBlock(); + + if ((block == Blocks.GRASS || block == Blocks.DIRT) && blockposition.getY() < 256 - i - 1) { + this.a(world, blockposition.down()); + k1 = 0; + + int i2; + + for (i2 = blockposition.getY() + i; i2 >= blockposition.getY() + j; --i2) { + for (i1 = blockposition.getX() - k1; i1 <= blockposition.getX() + k1; ++i1) { + j1 = i1 - blockposition.getX(); + + for (int j2 = blockposition.getZ() - k1; j2 <= blockposition.getZ() + k1; ++j2) { + int k2 = j2 - blockposition.getZ(); + + if (Math.abs(j1) != k1 || Math.abs(k2) != k1 || k1 <= 0) { + if (!world.getType(i1, i2, j2).getBlock().o()) { + this.a(world, new BlockPosition(i1, i2, j2), WorldGenTaiga1.b); + } + } + } + } + + if (k1 >= 1 && i2 == blockposition.getY() + j + 1) { + --k1; + } else if (k1 < l) { + ++k1; + } + } + + for (i2 = 0; i2 < i - 1; ++i2) { + Block block1 = world.getType(blockposition.up(i2)).getBlock(); + + if (block1.getMaterial() == Material.AIR || block1.getMaterial() == Material.LEAVES) { + this.a(world, blockposition.up(i2), WorldGenTaiga1.a); + } + } + + return true; + } else { + return false; + } + } + } else { + return false; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenTaiga2.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenTaiga2.java new file mode 100644 index 0000000..acf5c13 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenTaiga2.java @@ -0,0 +1,110 @@ +package net.minecraft.server; + +import java.util.Random; + +public class WorldGenTaiga2 extends WorldGenTreeAbstract { + + private static final IBlockData a = Blocks.LOG.getBlockData().set(BlockLog1.VARIANT, BlockWood.EnumLogVariant.SPRUCE); + private static final IBlockData b = Blocks.LEAVES.getBlockData().set(BlockLeaves1.VARIANT, BlockWood.EnumLogVariant.SPRUCE).set(BlockLeaves.CHECK_DECAY, Boolean.FALSE); + + public WorldGenTaiga2(boolean flag) { + super(flag); + } + + public boolean generate(World world, Random random, BlockPosition blockposition) { + int i = random.nextInt(4) + 6; + int j = 1 + random.nextInt(2); + int k = i - j; + int l = 2 + random.nextInt(2); + boolean flag = true; + + if (blockposition.getY() >= 1 && blockposition.getY() + i + 1 <= 256) { + int i1; + int j1; + + for (int k1 = blockposition.getY(); k1 <= blockposition.getY() + 1 + i && flag; ++k1) { + + if (k1 - blockposition.getY() < j) { + j1 = 0; + } else { + j1 = l; + } + + for (int l1 = blockposition.getX() - j1; l1 <= blockposition.getX() + j1 && flag; ++l1) { + for (i1 = blockposition.getZ() - j1; i1 <= blockposition.getZ() + j1 && flag; ++i1) { + if (k1 >= 0 && k1 < 256) { + Block block = world.getType(l1, k1, i1).getBlock(); + + if (block.getMaterial() != Material.AIR && block.getMaterial() != Material.LEAVES) { + flag = false; + } + } else { + flag = false; + } + } + } + } + + if (!flag) { + return false; + } else { + Block block1 = world.getType(blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()).getBlock(); + + if ((block1 == Blocks.GRASS || block1 == Blocks.DIRT || block1 == Blocks.FARMLAND) && blockposition.getY() < 256 - i - 1) { + this.a(world, blockposition.down()); + j1 = random.nextInt(2); + int i2 = 1; + byte b0 = 0; + + int j2; + + for (i1 = 0; i1 <= k; ++i1) { + j2 = blockposition.getY() + i - i1; + + for (int k2 = blockposition.getX() - j1; k2 <= blockposition.getX() + j1; ++k2) { + int l2 = k2 - blockposition.getX(); + + for (int i3 = blockposition.getZ() - j1; i3 <= blockposition.getZ() + j1; ++i3) { + int j3 = i3 - blockposition.getZ(); + + if (Math.abs(l2) != j1 || Math.abs(j3) != j1 || j1 <= 0) { + if (!world.getType(k2, j2, i3).getBlock().o()) { + this.a(world, new BlockPosition(k2, j2, i3), WorldGenTaiga2.b); + } + } + } + } + + if (j1 >= i2) { + j1 = b0; + b0 = 1; + ++i2; + if (i2 > l) { + i2 = l; + } + } else { + ++j1; + } + } + + i1 = random.nextInt(3); + + for (j2 = 0; j2 < i - i1; ++j2) { + BlockPosition position = blockposition.up(j2); + Block block2 = world.getType(position).getBlock(); + + if (block2.getMaterial() == Material.AIR || block2.getMaterial() == Material.LEAVES) { + this.a(world, position, WorldGenTaiga2.a); + } + } + + return true; + } else { + return false; + } + } + } else { + return false; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenTaigaStructure.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenTaigaStructure.java new file mode 100644 index 0000000..d073489 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenTaigaStructure.java @@ -0,0 +1,57 @@ +package net.minecraft.server; + +import java.util.Random; + +public class WorldGenTaigaStructure extends WorldGenerator { + + private final Block a; + private final int b; + + public WorldGenTaigaStructure(Block block, int i) { + super(false); + this.a = block; + this.b = i; + } + + public boolean generate(World world, Random random, BlockPosition blockposition) { + while (true) { + if (blockposition.getY() > 3) { + label47: + { + Block block = world.getType(blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()).getBlock(); + if (block.getMaterial() != Material.AIR) { + if (block == Blocks.GRASS || block == Blocks.DIRT || block == Blocks.STONE) { + break label47; + } + } + + blockposition = blockposition.down(); + continue; + } + } + + if (blockposition.getY() <= 3) { + return false; + } + + int i = this.b; + + for (int j = 0; i >= 0 && j < 3; ++j) { + int k = i + random.nextInt(2); + int l = i + random.nextInt(2); + int i1 = i + random.nextInt(2); + float f = (float) (k + l + i1) * 0.333F + 0.5F; + + for (BlockPosition blockposition1 : BlockPosition.a(blockposition.a(-k, -l, -i1), blockposition.a(k, l, i1))) { + if (blockposition1.i(blockposition) <= (double) (f * f)) { + world.setTypeAndData(blockposition1, this.a.getBlockData(), 4); + } + } + + blockposition = blockposition.a(-(i + 1) + random.nextInt(2 + i * 2), -random.nextInt(2), -(i + 1) + random.nextInt(2 + i * 2)); + } + + return true; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenTallPlant.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenTallPlant.java new file mode 100644 index 0000000..8bd5f47 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenTallPlant.java @@ -0,0 +1,30 @@ +package net.minecraft.server; + +import java.util.Random; + +public class WorldGenTallPlant extends WorldGenerator { + + private BlockTallPlant.EnumTallFlowerVariants a; + + public WorldGenTallPlant() { + } + + public void a(BlockTallPlant.EnumTallFlowerVariants blocktallplant_enumtallflowervariants) { + this.a = blocktallplant_enumtallflowervariants; + } + + public boolean generate(World world, Random random, BlockPosition blockposition) { + boolean flag = false; + + for (int i = 0; i < 64; ++i) { + BlockPosition blockposition1 = blockposition.a(random.nextInt(8) - random.nextInt(8), random.nextInt(4) - random.nextInt(4), random.nextInt(8) - random.nextInt(8)); + + if (world.isEmpty(blockposition1) && (!world.worldProvider.o() || blockposition1.getY() < 254) && Blocks.DOUBLE_PLANT.canPlace(world, blockposition1)) { + Blocks.DOUBLE_PLANT.a(world, blockposition1, this.a, 2); + flag = true; + } + } + + return flag; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenTreeAbstract.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenTreeAbstract.java new file mode 100644 index 0000000..9e7b788 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenTreeAbstract.java @@ -0,0 +1,26 @@ +package net.minecraft.server; + +import java.util.Random; + +public abstract class WorldGenTreeAbstract extends WorldGenerator { + + public WorldGenTreeAbstract(boolean flag) { + super(flag); + } + + protected boolean a(Block block) { + Material material = block.getMaterial(); + + return material == Material.AIR || material == Material.LEAVES || block == Blocks.GRASS || block == Blocks.DIRT || block == Blocks.LOG || block == Blocks.LOG2 || block == Blocks.SAPLING || block == Blocks.VINE; + } + + public void a(World world, Random random, BlockPosition blockposition) { + } + + protected void a(World world, BlockPosition blockposition) { + if (world.getType(blockposition).getBlock() != Blocks.DIRT) { + this.a(world, blockposition, Blocks.DIRT.getBlockData()); + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenTrees.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenTrees.java new file mode 100644 index 0000000..1e69468 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenTrees.java @@ -0,0 +1,198 @@ +package net.minecraft.server; + +import java.util.Random; + +public class WorldGenTrees extends WorldGenTreeAbstract { + + private static final IBlockData a = Blocks.LOG.getBlockData().set(BlockLog1.VARIANT, BlockWood.EnumLogVariant.OAK); + private static final IBlockData b = Blocks.LEAVES.getBlockData().set(BlockLeaves1.VARIANT, BlockWood.EnumLogVariant.OAK).set(BlockLeaves.CHECK_DECAY, Boolean.FALSE); + private final int c; + private final boolean d; + private final IBlockData e; + private final IBlockData f; + + public WorldGenTrees(boolean flag) { + this(flag, 4, WorldGenTrees.a, WorldGenTrees.b, false); + } + + public WorldGenTrees(boolean flag, int i, IBlockData iblockdata, IBlockData iblockdata1, boolean flag1) { + super(flag); + this.c = i; + this.e = iblockdata; + this.f = iblockdata1; + this.d = flag1; + } + + public boolean generate(World world, Random random, BlockPosition blockposition) { + int yHeight = random.nextInt(3) + this.c; + boolean flag = true; + + if (blockposition.getY() >= 1 && blockposition.getY() + yHeight + 1 <= 256) { + byte b0; + int j; + int k; + + for (int l = blockposition.getY(); l <= blockposition.getY() + 1 + yHeight; ++l) { + b0 = 1; + if (l == blockposition.getY()) { + b0 = 0; + } + + if (l >= blockposition.getY() + 1 + yHeight - 2) { + b0 = 2; + } + + for (j = blockposition.getX() - b0; j <= blockposition.getX() + b0 && flag; ++j) { + for (k = blockposition.getZ() - b0; k <= blockposition.getZ() + b0 && flag; ++k) { + if (l >= 0 && l < 256) { + if (!this.a(world.getType(j, l, k).getBlock())) { + flag = false; + } + } else { + flag = false; + } + } + } + } + + if (!flag) { + return false; + } else { + Block block = world.getType(blockposition.getX(), blockposition.getY() - 1, blockposition.getZ()).getBlock(); + + if ((block == Blocks.GRASS || block == Blocks.DIRT || block == Blocks.FARMLAND) && blockposition.getY() < 256 - yHeight - 1) { + this.a(world, blockposition.down()); + b0 = 3; + byte b1 = 0; + + int i1; + int j1; + int k1; + BlockPosition blockposition1; + + for (j = blockposition.getY() - b0 + yHeight; j <= blockposition.getY() + yHeight; ++j) { + k = j - (blockposition.getY() + yHeight); + i1 = b1 + 1 - k / 2; + + for (int l1 = blockposition.getX() - i1; l1 <= blockposition.getX() + i1; ++l1) { + j1 = l1 - blockposition.getX(); + + for (k1 = blockposition.getZ() - i1; k1 <= blockposition.getZ() + i1; ++k1) { + int i2 = k1 - blockposition.getZ(); + + if (Math.abs(j1) != i1 || Math.abs(i2) != i1 || random.nextInt(2) != 0 && k != 0) { + blockposition1 = new BlockPosition(l1, j, k1); + Block block1 = world.getType(blockposition1).getBlock(); + + if (block1.getMaterial() == Material.AIR || block1.getMaterial() == Material.LEAVES || block1.getMaterial() == Material.REPLACEABLE_PLANT) { + this.a(world, blockposition1, this.f); + } + } + } + } + } + + for (j = 0; j < yHeight; ++j) { + Block block2 = world.getType(blockposition.up(j)).getBlock(); + + if (block2.getMaterial() == Material.AIR || block2.getMaterial() == Material.LEAVES || block2.getMaterial() == Material.REPLACEABLE_PLANT) { + this.a(world, blockposition.up(j), this.e); + if (this.d && j > 0) { + if (random.nextInt(3) > 0 && world.isEmpty(blockposition.a(-1, j, 0))) { + this.a(world, blockposition.a(-1, j, 0), BlockVine.EAST); + } + + if (random.nextInt(3) > 0 && world.isEmpty(blockposition.a(1, j, 0))) { + this.a(world, blockposition.a(1, j, 0), BlockVine.WEST); + } + + if (random.nextInt(3) > 0 && world.isEmpty(blockposition.a(0, j, -1))) { + this.a(world, blockposition.a(0, j, -1), BlockVine.SOUTH); + } + + if (random.nextInt(3) > 0 && world.isEmpty(blockposition.a(0, j, 1))) { + this.a(world, blockposition.a(0, j, 1), BlockVine.NORTH); + } + } + } + } + + if (this.d) { + for (j = blockposition.getY() - 3 + yHeight; j <= blockposition.getY() + yHeight; ++j) { + k = j - (blockposition.getY() + yHeight); + i1 = 2 - k / 2; + BlockPosition.MutableBlockPosition blockposition_mutableblockposition1 = new BlockPosition.MutableBlockPosition(); + + for (j1 = blockposition.getX() - i1; j1 <= blockposition.getX() + i1; ++j1) { + for (k1 = blockposition.getZ() - i1; k1 <= blockposition.getZ() + i1; ++k1) { + blockposition_mutableblockposition1.c(j1, j, k1); + if (world.getType(blockposition_mutableblockposition1).getBlock().getMaterial() == Material.LEAVES) { + BlockPosition blockposition2 = blockposition_mutableblockposition1.west(); + + blockposition1 = blockposition_mutableblockposition1.east(); + BlockPosition blockposition3 = blockposition_mutableblockposition1.north(); + BlockPosition blockposition4 = blockposition_mutableblockposition1.south(); + + if (random.nextInt(4) == 0 && world.getType(blockposition2).getBlock().getMaterial() == Material.AIR) { + this.b(world, blockposition2, BlockVine.EAST); + } + + if (random.nextInt(4) == 0 && world.getType(blockposition1).getBlock().getMaterial() == Material.AIR) { + this.b(world, blockposition1, BlockVine.WEST); + } + + if (random.nextInt(4) == 0 && world.getType(blockposition3).getBlock().getMaterial() == Material.AIR) { + this.b(world, blockposition3, BlockVine.SOUTH); + } + + if (random.nextInt(4) == 0 && world.getType(blockposition4).getBlock().getMaterial() == Material.AIR) { + this.b(world, blockposition4, BlockVine.NORTH); + } + } + } + } + } + + if (random.nextInt(5) == 0 && yHeight > 5) { + for (j = 0; j < 2; ++j) { + + for (EnumDirection enumdirection : EnumDirection.EnumDirectionLimit.HORIZONTAL) { + if (random.nextInt(4 - j) == 0) { + EnumDirection enumdirection1 = enumdirection.opposite(); + + this.a(world, random.nextInt(3), blockposition.a(enumdirection1.getAdjacentX(), yHeight - 5 + j, enumdirection1.getAdjacentZ()), enumdirection); + } + } + } + } + } + + return true; + } else { + return false; + } + } + } else { + return false; + } + } + + private void a(World world, int i, BlockPosition blockposition, EnumDirection enumdirection) { + this.a(world, blockposition, Blocks.COCOA.getBlockData().set(BlockCocoa.AGE, i).set(BlockCocoa.FACING, enumdirection)); + } + + private void a(World world, BlockPosition blockposition, BlockStateBoolean blockstateboolean) { + this.a(world, blockposition, Blocks.VINE.getBlockData().set(blockstateboolean, true)); + } + + private void b(World world, BlockPosition blockposition, BlockStateBoolean blockstateboolean) { + this.a(world, blockposition, blockstateboolean); + int i = 4; + + for (blockposition = blockposition.down(); world.getType(blockposition).getBlock().getMaterial() == Material.AIR && i > 0; --i) { + this.a(world, blockposition, blockstateboolean); + blockposition = blockposition.down(); + } + + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenVillage.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenVillage.java new file mode 100644 index 0000000..57fb75b --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenVillage.java @@ -0,0 +1,127 @@ +package net.minecraft.server; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Random; + +public class WorldGenVillage extends StructureGenerator { + + public static final List d = Arrays.asList(BiomeBase.PLAINS, BiomeBase.DESERT, BiomeBase.SAVANNA); + private int f; + private int g; + private final int h; + + public WorldGenVillage() { + this.g = 32; + this.h = 8; + } + + public WorldGenVillage(Map map) { + this(); + + for (Entry entry : map.entrySet()) { + if (entry.getKey().equals("size")) { + this.f = MathHelper.a(entry.getValue(), this.f, 0); + } else if (entry.getKey().equals("distance")) { + this.g = MathHelper.a(entry.getValue(), this.g, this.h + 1); + } + } + + } + + public String a() { + return "Village"; + } + + protected boolean a(int i, int j) { + int k = i; + int l = j; + + if (i < 0) { + i -= this.g - 1; + } + + if (j < 0) { + j -= this.g - 1; + } + + int i1 = i / this.g; + int j1 = j / this.g; + Random random = this.c.a(i1, j1, this.c.spigotConfig.villageSeed); // Spigot + + i1 *= this.g; + j1 *= this.g; + i1 += random.nextInt(this.g - this.h); + j1 += random.nextInt(this.g - this.h); + if (k == i1 && l == j1) { + return c.getWorldChunkManager().a(k * 16 + 8, l * 16 + 8, 0, WorldGenVillage.d); + } + + return false; + } + + protected StructureStart b(int i, int j) { + return new WorldGenVillageStart(this.c, this.b, i, j, this.f); + } + + public static class WorldGenVillageStart extends StructureStart { + + private boolean c; + + public WorldGenVillageStart() { + } + + public WorldGenVillageStart(World world, Random random, int i, int j, int k) { + super(i, j); + List list = WorldGenVillagePieces.a(random, k); + WorldGenVillagePieces.WorldGenVillageStartPiece worldgenvillagepieces_worldgenvillagestartpiece = new WorldGenVillagePieces.WorldGenVillageStartPiece(world.getWorldChunkManager(), 0, random, (i << 4) + 2, (j << 4) + 2, list, k); + + this.a.add(worldgenvillagepieces_worldgenvillagestartpiece); + worldgenvillagepieces_worldgenvillagestartpiece.a(worldgenvillagepieces_worldgenvillagestartpiece, this.a, random); + List list1 = worldgenvillagepieces_worldgenvillagestartpiece.g; + List list2 = worldgenvillagepieces_worldgenvillagestartpiece.f; + + int l; + + while (!list1.isEmpty() || !list2.isEmpty()) { + StructurePiece structurepiece; + + if (list1.isEmpty()) { + l = random.nextInt(list2.size()); + structurepiece = list2.remove(l); + } else { + l = random.nextInt(list1.size()); + structurepiece = list1.remove(l); + } + structurepiece.a(worldgenvillagepieces_worldgenvillagestartpiece, this.a, random); + } + + this.c(); + l = 0; + + for (StructurePiece structurepiece1 : this.a) { + if (!(structurepiece1 instanceof WorldGenVillagePieces.WorldGenVillageRoadPiece)) { + ++l; + } + } + + this.c = l > 2; + } + + public boolean d() { + return this.c; + } + + public void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + nbttagcompound.setBoolean("Valid", this.c); + } + + public void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + this.c = nbttagcompound.getBoolean("Valid"); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenVillagePieces.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenVillagePieces.java new file mode 100644 index 0000000..0d1f966 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenVillagePieces.java @@ -0,0 +1,1647 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Random; + +public class WorldGenVillagePieces { + + public static void a() { + WorldGenFactory.a(WorldGenVillageLibrary.class, "ViBH"); + WorldGenFactory.a(WorldGenVillageFarm2.class, "ViDF"); + WorldGenFactory.a(WorldGenVillageFarm.class, "ViF"); + WorldGenFactory.a(WorldGenVillageLight.class, "ViL"); + WorldGenFactory.a(WorldGenVillageButcher.class, "ViPH"); + WorldGenFactory.a(WorldGenVillageHouse.class, "ViSH"); + WorldGenFactory.a(WorldGenVillageHut.class, "ViSmH"); + WorldGenFactory.a(WorldGenVillageTemple.class, "ViST"); + WorldGenFactory.a(WorldGenVillageBlacksmith.class, "ViS"); + WorldGenFactory.a(WorldGenVillageStartPiece.class, "ViStart"); + WorldGenFactory.a(WorldGenVillageRoad.class, "ViSR"); + WorldGenFactory.a(WorldGenVillageHouse2.class, "ViTRH"); + WorldGenFactory.a(WorldGenVillageWell.class, "ViW"); + } + + public static List a(Random random, int i) { + ArrayList arraylist = Lists.newArrayList(); + + arraylist.add(new WorldGenVillagePieceWeight(WorldGenVillageHouse.class, 4, MathHelper.nextInt(random, 2 + i, 4 + i * 2))); + arraylist.add(new WorldGenVillagePieceWeight(WorldGenVillageTemple.class, 20, MathHelper.nextInt(random, i, 1 + i))); + arraylist.add(new WorldGenVillagePieceWeight(WorldGenVillageLibrary.class, 20, MathHelper.nextInt(random, i, 2 + i))); + arraylist.add(new WorldGenVillagePieceWeight(WorldGenVillageHut.class, 3, MathHelper.nextInt(random, 2 + i, 5 + i * 3))); + arraylist.add(new WorldGenVillagePieceWeight(WorldGenVillageButcher.class, 15, MathHelper.nextInt(random, i, 2 + i))); + arraylist.add(new WorldGenVillagePieceWeight(WorldGenVillageFarm2.class, 3, MathHelper.nextInt(random, 1 + i, 4 + i))); + arraylist.add(new WorldGenVillagePieceWeight(WorldGenVillageFarm.class, 3, MathHelper.nextInt(random, 2 + i, 4 + i * 2))); + arraylist.add(new WorldGenVillagePieceWeight(WorldGenVillageBlacksmith.class, 15, MathHelper.nextInt(random, 0, 1 + i))); + arraylist.add(new WorldGenVillagePieceWeight(WorldGenVillageHouse2.class, 8, MathHelper.nextInt(random, i, 3 + i * 2))); + + arraylist.removeIf(worldGenVillagePieceWeight -> worldGenVillagePieceWeight.d == 0); + + return arraylist; + } + + private static int a(List list) { + boolean flag = false; + int i = 0; + + WorldGenVillagePieceWeight worldgenvillagepieces_worldgenvillagepieceweight; + + for (Iterator iterator = list.iterator(); iterator.hasNext(); i += worldgenvillagepieces_worldgenvillagepieceweight.b) { + worldgenvillagepieces_worldgenvillagepieceweight = iterator.next(); + if (worldgenvillagepieces_worldgenvillagepieceweight.d > 0 && worldgenvillagepieces_worldgenvillagepieceweight.c < worldgenvillagepieces_worldgenvillagepieceweight.d) { + flag = true; + } + } + + return flag ? i : -1; + } + + private static WorldGenVillagePiece a(WorldGenVillageStartPiece worldgenvillagepieces_worldgenvillagestartpiece, WorldGenVillagePieceWeight worldgenvillagepieces_worldgenvillagepieceweight, List list, Random random, int i, int j, int k, EnumDirection enumdirection, int l) { + Class oclass = worldgenvillagepieces_worldgenvillagepieceweight.a; + WorldGenVillagePiece object = null; + + if (oclass == WorldGenVillageHouse.class) { + object = WorldGenVillageHouse.a(worldgenvillagepieces_worldgenvillagestartpiece, list, random, i, j, k, enumdirection, l); + } else if (oclass == WorldGenVillageTemple.class) { + object = WorldGenVillageTemple.a(worldgenvillagepieces_worldgenvillagestartpiece, list, random, i, j, k, enumdirection, l); + } else if (oclass == WorldGenVillageLibrary.class) { + object = WorldGenVillageLibrary.a(worldgenvillagepieces_worldgenvillagestartpiece, list, random, i, j, k, enumdirection, l); + } else if (oclass == WorldGenVillageHut.class) { + object = WorldGenVillageHut.a(worldgenvillagepieces_worldgenvillagestartpiece, list, random, i, j, k, enumdirection, l); + } else if (oclass == WorldGenVillageButcher.class) { + object = WorldGenVillageButcher.a(worldgenvillagepieces_worldgenvillagestartpiece, list, random, i, j, k, enumdirection, l); + } else if (oclass == WorldGenVillageFarm2.class) { + object = WorldGenVillageFarm2.a(worldgenvillagepieces_worldgenvillagestartpiece, list, random, i, j, k, enumdirection, l); + } else if (oclass == WorldGenVillageFarm.class) { + object = WorldGenVillageFarm.a(worldgenvillagepieces_worldgenvillagestartpiece, list, random, i, j, k, enumdirection, l); + } else if (oclass == WorldGenVillageBlacksmith.class) { + object = WorldGenVillageBlacksmith.a(worldgenvillagepieces_worldgenvillagestartpiece, list, random, i, j, k, enumdirection, l); + } else if (oclass == WorldGenVillageHouse2.class) { + object = WorldGenVillageHouse2.a(worldgenvillagepieces_worldgenvillagestartpiece, list, random, i, j, k, enumdirection, l); + } + + return object; + } + + private static WorldGenVillagePiece c(WorldGenVillageStartPiece worldgenvillagepieces_worldgenvillagestartpiece, List list, Random random, int i, int j, int k, EnumDirection enumdirection, int l) { + int i1 = a(worldgenvillagepieces_worldgenvillagestartpiece.e); + + if (i1 <= 0) { + return null; + } else { + int j1 = 0; + + while (j1 < 5) { + ++j1; + int k1 = random.nextInt(i1); + + for (WorldGenVillagePieceWeight worldgenvillagepieces_worldgenvillagepieceweight : worldgenvillagepieces_worldgenvillagestartpiece.e) { + k1 -= worldgenvillagepieces_worldgenvillagepieceweight.b; + if (k1 < 0) { + if (!worldgenvillagepieces_worldgenvillagepieceweight.a(l) || worldgenvillagepieces_worldgenvillagepieceweight == worldgenvillagepieces_worldgenvillagestartpiece.d && worldgenvillagepieces_worldgenvillagestartpiece.e.size() > 1) { + break; + } + + WorldGenVillagePiece worldgenvillagepieces_worldgenvillagepiece = a(worldgenvillagepieces_worldgenvillagestartpiece, worldgenvillagepieces_worldgenvillagepieceweight, list, random, i, j, k, enumdirection, l); + + if (worldgenvillagepieces_worldgenvillagepiece != null) { + ++worldgenvillagepieces_worldgenvillagepieceweight.c; + worldgenvillagepieces_worldgenvillagestartpiece.d = worldgenvillagepieces_worldgenvillagepieceweight; + if (!worldgenvillagepieces_worldgenvillagepieceweight.a()) { + worldgenvillagepieces_worldgenvillagestartpiece.e.remove(worldgenvillagepieces_worldgenvillagepieceweight); + } + + return worldgenvillagepieces_worldgenvillagepiece; + } + } + } + } + + StructureBoundingBox structureboundingbox = WorldGenVillageLight.a(worldgenvillagepieces_worldgenvillagestartpiece, list, random, i, j, k, enumdirection); + + if (structureboundingbox != null) { + return new WorldGenVillageLight(worldgenvillagepieces_worldgenvillagestartpiece, l, random, structureboundingbox, enumdirection); + } else { + return null; + } + } + } + + private static StructurePiece d(WorldGenVillageStartPiece worldgenvillagepieces_worldgenvillagestartpiece, List list, Random random, int i, int j, int k, EnumDirection enumdirection, int l) { + if (l > 50) { + return null; + } else if (Math.abs(i - worldgenvillagepieces_worldgenvillagestartpiece.c().a) <= 112 && Math.abs(k - worldgenvillagepieces_worldgenvillagestartpiece.c().c) <= 112) { + WorldGenVillagePiece worldgenvillagepieces_worldgenvillagepiece = c(worldgenvillagepieces_worldgenvillagestartpiece, list, random, i, j, k, enumdirection, l + 1); + + if (worldgenvillagepieces_worldgenvillagepiece != null) { + int i1 = (worldgenvillagepieces_worldgenvillagepiece.l.a + worldgenvillagepieces_worldgenvillagepiece.l.d) / 2; + int j1 = (worldgenvillagepieces_worldgenvillagepiece.l.c + worldgenvillagepieces_worldgenvillagepiece.l.f) / 2; + int k1 = worldgenvillagepieces_worldgenvillagepiece.l.d - worldgenvillagepieces_worldgenvillagepiece.l.a; + int l1 = worldgenvillagepieces_worldgenvillagepiece.l.f - worldgenvillagepieces_worldgenvillagepiece.l.c; + int i2 = Math.max(k1, l1); + + if (worldgenvillagepieces_worldgenvillagestartpiece.e().a(i1, j1, i2 / 2 + 4, WorldGenVillage.d)) { + list.add(worldgenvillagepieces_worldgenvillagepiece); + worldgenvillagepieces_worldgenvillagestartpiece.f.add(worldgenvillagepieces_worldgenvillagepiece); + return worldgenvillagepieces_worldgenvillagepiece; + } + } + + return null; + } else { + return null; + } + } + + private static StructurePiece e(WorldGenVillageStartPiece worldgenvillagepieces_worldgenvillagestartpiece, List list, Random random, int i, int j, int k, EnumDirection enumdirection, int l) { + if (l > 3 + worldgenvillagepieces_worldgenvillagestartpiece.c) { + return null; + } else if (Math.abs(i - worldgenvillagepieces_worldgenvillagestartpiece.c().a) <= 112 && Math.abs(k - worldgenvillagepieces_worldgenvillagestartpiece.c().c) <= 112) { + StructureBoundingBox structureboundingbox = WorldGenVillageRoad.a(worldgenvillagepieces_worldgenvillagestartpiece, list, random, i, j, k, enumdirection); + + if (structureboundingbox != null && structureboundingbox.b > 10) { + WorldGenVillageRoad worldgenvillagepieces_worldgenvillageroad = new WorldGenVillageRoad(worldgenvillagepieces_worldgenvillagestartpiece, l, random, structureboundingbox, enumdirection); + int i1 = (worldgenvillagepieces_worldgenvillageroad.l.a + worldgenvillagepieces_worldgenvillageroad.l.d) / 2; + int j1 = (worldgenvillagepieces_worldgenvillageroad.l.c + worldgenvillagepieces_worldgenvillageroad.l.f) / 2; + int k1 = worldgenvillagepieces_worldgenvillageroad.l.d - worldgenvillagepieces_worldgenvillageroad.l.a; + int l1 = worldgenvillagepieces_worldgenvillageroad.l.f - worldgenvillagepieces_worldgenvillageroad.l.c; + int i2 = Math.max(k1, l1); + + if (worldgenvillagepieces_worldgenvillagestartpiece.e().a(i1, j1, i2 / 2 + 4, WorldGenVillage.d)) { + list.add(worldgenvillagepieces_worldgenvillageroad); + worldgenvillagepieces_worldgenvillagestartpiece.g.add(worldgenvillagepieces_worldgenvillageroad); + return worldgenvillagepieces_worldgenvillageroad; + } + } + + return null; + } else { + return null; + } + } + + static class SyntheticClass_1 { + + static final int[] a = new int[EnumDirection.values().length]; + + static { + try { + SyntheticClass_1.a[EnumDirection.NORTH.ordinal()] = 1; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.a[EnumDirection.SOUTH.ordinal()] = 2; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.a[EnumDirection.WEST.ordinal()] = 3; + } catch (NoSuchFieldError ignored) { + } + + try { + SyntheticClass_1.a[EnumDirection.EAST.ordinal()] = 4; + } catch (NoSuchFieldError ignored) { + } + + } + } + + public static class WorldGenVillageLight extends WorldGenVillagePiece { + + public WorldGenVillageLight() { + } + + public WorldGenVillageLight(WorldGenVillageStartPiece worldgenvillagepieces_worldgenvillagestartpiece, int i, Random random, StructureBoundingBox structureboundingbox, EnumDirection enumdirection) { + super(worldgenvillagepieces_worldgenvillagestartpiece, i); + this.m = enumdirection; + this.l = structureboundingbox; + } + + public static StructureBoundingBox a(WorldGenVillageStartPiece worldgenvillagepieces_worldgenvillagestartpiece, List list, Random random, int i, int j, int k, EnumDirection enumdirection) { + StructureBoundingBox structureboundingbox = StructureBoundingBox.a(i, j, k, 0, 0, 0, 3, 4, 2, enumdirection); + + return StructurePiece.a(list, structureboundingbox) != null ? null : structureboundingbox; + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + if (this.h < 0) { + this.h = this.b(world, structureboundingbox); + if (this.h < 0) { + return true; + } + + this.l.a(0, this.h - this.l.e + 4 - 1, 0); + } + + this.a(world, structureboundingbox, 0, 0, 0, 2, 3, 1, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, Blocks.FENCE.getBlockData(), 1, 0, 0, structureboundingbox); + this.a(world, Blocks.FENCE.getBlockData(), 1, 1, 0, structureboundingbox); + this.a(world, Blocks.FENCE.getBlockData(), 1, 2, 0, structureboundingbox); + this.a(world, Blocks.WOOL.fromLegacyData(EnumColor.WHITE.getInvColorIndex()), 1, 3, 0, structureboundingbox); + boolean flag = this.m == EnumDirection.EAST || this.m == EnumDirection.NORTH; + + this.a(world, Blocks.TORCH.getBlockData().set(BlockTorch.FACING, this.m.e()), flag ? 2 : 0, 3, 0, structureboundingbox); + this.a(world, Blocks.TORCH.getBlockData().set(BlockTorch.FACING, this.m), 1, 3, 1, structureboundingbox); + this.a(world, Blocks.TORCH.getBlockData().set(BlockTorch.FACING, this.m.f()), flag ? 0 : 2, 3, 0, structureboundingbox); + this.a(world, Blocks.TORCH.getBlockData().set(BlockTorch.FACING, this.m.opposite()), 1, 3, -1, structureboundingbox); + return true; + } + } + + public static class WorldGenVillageFarm2 extends WorldGenVillagePiece { + + private Block a; + private Block b; + private Block c; + private Block d; + + public WorldGenVillageFarm2() { + } + + public WorldGenVillageFarm2(WorldGenVillageStartPiece worldgenvillagepieces_worldgenvillagestartpiece, int i, Random random, StructureBoundingBox structureboundingbox, EnumDirection enumdirection) { + super(worldgenvillagepieces_worldgenvillagestartpiece, i); + this.m = enumdirection; + this.l = structureboundingbox; + this.a = this.a(random); + this.b = this.a(random); + this.c = this.a(random); + this.d = this.a(random); + } + + protected void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + nbttagcompound.setInt("CA", Block.REGISTRY.b(this.a)); + nbttagcompound.setInt("CB", Block.REGISTRY.b(this.b)); + nbttagcompound.setInt("CC", Block.REGISTRY.b(this.c)); + nbttagcompound.setInt("CD", Block.REGISTRY.b(this.d)); + } + + protected void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + this.a = Block.getById(nbttagcompound.getInt("CA")); + this.b = Block.getById(nbttagcompound.getInt("CB")); + this.c = Block.getById(nbttagcompound.getInt("CC")); + this.d = Block.getById(nbttagcompound.getInt("CD")); + } + + private Block a(Random random) { + switch (random.nextInt(5)) { + case 0: + return Blocks.CARROTS; + + case 1: + return Blocks.POTATOES; + + default: + return Blocks.WHEAT; + } + } + + public static WorldGenVillageFarm2 a(WorldGenVillageStartPiece worldgenvillagepieces_worldgenvillagestartpiece, List list, Random random, int i, int j, int k, EnumDirection enumdirection, int l) { + StructureBoundingBox structureboundingbox = StructureBoundingBox.a(i, j, k, 0, 0, 0, 13, 4, 9, enumdirection); + + return a(structureboundingbox) && StructurePiece.a(list, structureboundingbox) == null ? new WorldGenVillageFarm2(worldgenvillagepieces_worldgenvillagestartpiece, l, random, structureboundingbox, enumdirection) : null; + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + if (this.h < 0) { + this.h = this.b(world, structureboundingbox); + if (this.h < 0) { + return true; + } + + this.l.a(0, this.h - this.l.e + 4 - 1, 0); + } + + this.a(world, structureboundingbox, 0, 1, 0, 12, 4, 8, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, 1, 0, 1, 2, 0, 7, Blocks.FARMLAND.getBlockData(), Blocks.FARMLAND.getBlockData(), false); + this.a(world, structureboundingbox, 4, 0, 1, 5, 0, 7, Blocks.FARMLAND.getBlockData(), Blocks.FARMLAND.getBlockData(), false); + this.a(world, structureboundingbox, 7, 0, 1, 8, 0, 7, Blocks.FARMLAND.getBlockData(), Blocks.FARMLAND.getBlockData(), false); + this.a(world, structureboundingbox, 10, 0, 1, 11, 0, 7, Blocks.FARMLAND.getBlockData(), Blocks.FARMLAND.getBlockData(), false); + this.a(world, structureboundingbox, 0, 0, 0, 0, 0, 8, Blocks.LOG.getBlockData(), Blocks.LOG.getBlockData(), false); + this.a(world, structureboundingbox, 6, 0, 0, 6, 0, 8, Blocks.LOG.getBlockData(), Blocks.LOG.getBlockData(), false); + this.a(world, structureboundingbox, 12, 0, 0, 12, 0, 8, Blocks.LOG.getBlockData(), Blocks.LOG.getBlockData(), false); + this.a(world, structureboundingbox, 1, 0, 0, 11, 0, 0, Blocks.LOG.getBlockData(), Blocks.LOG.getBlockData(), false); + this.a(world, structureboundingbox, 1, 0, 8, 11, 0, 8, Blocks.LOG.getBlockData(), Blocks.LOG.getBlockData(), false); + this.a(world, structureboundingbox, 3, 0, 1, 3, 0, 7, Blocks.WATER.getBlockData(), Blocks.WATER.getBlockData(), false); + this.a(world, structureboundingbox, 9, 0, 1, 9, 0, 7, Blocks.WATER.getBlockData(), Blocks.WATER.getBlockData(), false); + + int i; + + for (i = 1; i <= 7; ++i) { + this.a(world, this.a.fromLegacyData(MathHelper.nextInt(random, 2, 7)), 1, 1, i, structureboundingbox); + this.a(world, this.a.fromLegacyData(MathHelper.nextInt(random, 2, 7)), 2, 1, i, structureboundingbox); + this.a(world, this.b.fromLegacyData(MathHelper.nextInt(random, 2, 7)), 4, 1, i, structureboundingbox); + this.a(world, this.b.fromLegacyData(MathHelper.nextInt(random, 2, 7)), 5, 1, i, structureboundingbox); + this.a(world, this.c.fromLegacyData(MathHelper.nextInt(random, 2, 7)), 7, 1, i, structureboundingbox); + this.a(world, this.c.fromLegacyData(MathHelper.nextInt(random, 2, 7)), 8, 1, i, structureboundingbox); + this.a(world, this.d.fromLegacyData(MathHelper.nextInt(random, 2, 7)), 10, 1, i, structureboundingbox); + this.a(world, this.d.fromLegacyData(MathHelper.nextInt(random, 2, 7)), 11, 1, i, structureboundingbox); + } + + for (i = 0; i < 9; ++i) { + for (int j = 0; j < 13; ++j) { + this.b(world, j, 4, i, structureboundingbox); + this.b(world, Blocks.DIRT.getBlockData(), j, -1, i, structureboundingbox); + } + } + + return true; + } + } + + public static class WorldGenVillageFarm extends WorldGenVillagePiece { + + private Block a; + private Block b; + + public WorldGenVillageFarm() { + } + + public WorldGenVillageFarm(WorldGenVillageStartPiece worldgenvillagepieces_worldgenvillagestartpiece, int i, Random random, StructureBoundingBox structureboundingbox, EnumDirection enumdirection) { + super(worldgenvillagepieces_worldgenvillagestartpiece, i); + this.m = enumdirection; + this.l = structureboundingbox; + this.a = this.a(random); + this.b = this.a(random); + } + + protected void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + nbttagcompound.setInt("CA", Block.REGISTRY.b(this.a)); + nbttagcompound.setInt("CB", Block.REGISTRY.b(this.b)); + } + + protected void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + this.a = Block.getById(nbttagcompound.getInt("CA")); + this.b = Block.getById(nbttagcompound.getInt("CB")); + } + + private Block a(Random random) { + switch (random.nextInt(5)) { + case 0: + return Blocks.CARROTS; + + case 1: + return Blocks.POTATOES; + + default: + return Blocks.WHEAT; + } + } + + public static WorldGenVillageFarm a(WorldGenVillageStartPiece worldgenvillagepieces_worldgenvillagestartpiece, List list, Random random, int i, int j, int k, EnumDirection enumdirection, int l) { + StructureBoundingBox structureboundingbox = StructureBoundingBox.a(i, j, k, 0, 0, 0, 7, 4, 9, enumdirection); + + return a(structureboundingbox) && StructurePiece.a(list, structureboundingbox) == null ? new WorldGenVillageFarm(worldgenvillagepieces_worldgenvillagestartpiece, l, random, structureboundingbox, enumdirection) : null; + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + if (this.h < 0) { + this.h = this.b(world, structureboundingbox); + if (this.h < 0) { + return true; + } + + this.l.a(0, this.h - this.l.e + 4 - 1, 0); + } + + this.a(world, structureboundingbox, 0, 1, 0, 6, 4, 8, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, 1, 0, 1, 2, 0, 7, Blocks.FARMLAND.getBlockData(), Blocks.FARMLAND.getBlockData(), false); + this.a(world, structureboundingbox, 4, 0, 1, 5, 0, 7, Blocks.FARMLAND.getBlockData(), Blocks.FARMLAND.getBlockData(), false); + this.a(world, structureboundingbox, 0, 0, 0, 0, 0, 8, Blocks.LOG.getBlockData(), Blocks.LOG.getBlockData(), false); + this.a(world, structureboundingbox, 6, 0, 0, 6, 0, 8, Blocks.LOG.getBlockData(), Blocks.LOG.getBlockData(), false); + this.a(world, structureboundingbox, 1, 0, 0, 5, 0, 0, Blocks.LOG.getBlockData(), Blocks.LOG.getBlockData(), false); + this.a(world, structureboundingbox, 1, 0, 8, 5, 0, 8, Blocks.LOG.getBlockData(), Blocks.LOG.getBlockData(), false); + this.a(world, structureboundingbox, 3, 0, 1, 3, 0, 7, Blocks.WATER.getBlockData(), Blocks.WATER.getBlockData(), false); + + int i; + + for (i = 1; i <= 7; ++i) { + this.a(world, this.a.fromLegacyData(MathHelper.nextInt(random, 2, 7)), 1, 1, i, structureboundingbox); + this.a(world, this.a.fromLegacyData(MathHelper.nextInt(random, 2, 7)), 2, 1, i, structureboundingbox); + this.a(world, this.b.fromLegacyData(MathHelper.nextInt(random, 2, 7)), 4, 1, i, structureboundingbox); + this.a(world, this.b.fromLegacyData(MathHelper.nextInt(random, 2, 7)), 5, 1, i, structureboundingbox); + } + + for (i = 0; i < 9; ++i) { + for (int j = 0; j < 7; ++j) { + this.b(world, j, 4, i, structureboundingbox); + this.b(world, Blocks.DIRT.getBlockData(), j, -1, i, structureboundingbox); + } + } + + return true; + } + } + + public static class WorldGenVillageBlacksmith extends WorldGenVillagePiece { + + private static final List a = Lists.newArrayList(new StructurePieceTreasure(Items.DIAMOND, 0, 1, 3, 3), new StructurePieceTreasure(Items.IRON_INGOT, 0, 1, 5, 10), new StructurePieceTreasure(Items.GOLD_INGOT, 0, 1, 3, 5), new StructurePieceTreasure(Items.BREAD, 0, 1, 3, 15), new StructurePieceTreasure(Items.APPLE, 0, 1, 3, 15), new StructurePieceTreasure(Items.IRON_PICKAXE, 0, 1, 1, 5), new StructurePieceTreasure(Items.IRON_SWORD, 0, 1, 1, 5), new StructurePieceTreasure(Items.IRON_CHESTPLATE, 0, 1, 1, 5), new StructurePieceTreasure(Items.IRON_HELMET, 0, 1, 1, 5), new StructurePieceTreasure(Items.IRON_LEGGINGS, 0, 1, 1, 5), new StructurePieceTreasure(Items.IRON_BOOTS, 0, 1, 1, 5), new StructurePieceTreasure(Item.getItemOf(Blocks.OBSIDIAN), 0, 3, 7, 5), new StructurePieceTreasure(Item.getItemOf(Blocks.SAPLING), 0, 3, 7, 5), new StructurePieceTreasure(Items.SADDLE, 0, 1, 1, 3), new StructurePieceTreasure(Items.IRON_HORSE_ARMOR, 0, 1, 1, 1), new StructurePieceTreasure(Items.GOLDEN_HORSE_ARMOR, 0, 1, 1, 1), new StructurePieceTreasure(Items.DIAMOND_HORSE_ARMOR, 0, 1, 1, 1)); + private boolean b; + + public WorldGenVillageBlacksmith() { + } + + public WorldGenVillageBlacksmith(WorldGenVillageStartPiece worldgenvillagepieces_worldgenvillagestartpiece, int i, Random random, StructureBoundingBox structureboundingbox, EnumDirection enumdirection) { + super(worldgenvillagepieces_worldgenvillagestartpiece, i); + this.m = enumdirection; + this.l = structureboundingbox; + } + + public static WorldGenVillageBlacksmith a(WorldGenVillageStartPiece worldgenvillagepieces_worldgenvillagestartpiece, List list, Random random, int i, int j, int k, EnumDirection enumdirection, int l) { + StructureBoundingBox structureboundingbox = StructureBoundingBox.a(i, j, k, 0, 0, 0, 10, 6, 7, enumdirection); + + return a(structureboundingbox) && StructurePiece.a(list, structureboundingbox) == null ? new WorldGenVillageBlacksmith(worldgenvillagepieces_worldgenvillagestartpiece, l, random, structureboundingbox, enumdirection) : null; + } + + protected void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + nbttagcompound.setBoolean("Chest", this.b); + } + + protected void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + this.b = nbttagcompound.getBoolean("Chest"); + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + if (this.h < 0) { + this.h = this.b(world, structureboundingbox); + if (this.h < 0) { + return true; + } + + this.l.a(0, this.h - this.l.e + 6 - 1, 0); + } + + this.a(world, structureboundingbox, 0, 1, 0, 9, 4, 6, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, 0, 0, 0, 9, 0, 6, Blocks.COBBLESTONE.getBlockData(), Blocks.COBBLESTONE.getBlockData(), false); + this.a(world, structureboundingbox, 0, 4, 0, 9, 4, 6, Blocks.COBBLESTONE.getBlockData(), Blocks.COBBLESTONE.getBlockData(), false); + this.a(world, structureboundingbox, 0, 5, 0, 9, 5, 6, Blocks.STONE_SLAB.getBlockData(), Blocks.STONE_SLAB.getBlockData(), false); + this.a(world, structureboundingbox, 1, 5, 1, 8, 5, 5, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, 1, 1, 0, 2, 3, 0, Blocks.PLANKS.getBlockData(), Blocks.PLANKS.getBlockData(), false); + this.a(world, structureboundingbox, 0, 1, 0, 0, 4, 0, Blocks.LOG.getBlockData(), Blocks.LOG.getBlockData(), false); + this.a(world, structureboundingbox, 3, 1, 0, 3, 4, 0, Blocks.LOG.getBlockData(), Blocks.LOG.getBlockData(), false); + this.a(world, structureboundingbox, 0, 1, 6, 0, 4, 6, Blocks.LOG.getBlockData(), Blocks.LOG.getBlockData(), false); + this.a(world, Blocks.PLANKS.getBlockData(), 3, 3, 1, structureboundingbox); + this.a(world, structureboundingbox, 3, 1, 2, 3, 3, 2, Blocks.PLANKS.getBlockData(), Blocks.PLANKS.getBlockData(), false); + this.a(world, structureboundingbox, 4, 1, 3, 5, 3, 3, Blocks.PLANKS.getBlockData(), Blocks.PLANKS.getBlockData(), false); + this.a(world, structureboundingbox, 0, 1, 1, 0, 3, 5, Blocks.PLANKS.getBlockData(), Blocks.PLANKS.getBlockData(), false); + this.a(world, structureboundingbox, 1, 1, 6, 5, 3, 6, Blocks.PLANKS.getBlockData(), Blocks.PLANKS.getBlockData(), false); + this.a(world, structureboundingbox, 5, 1, 0, 5, 3, 0, Blocks.FENCE.getBlockData(), Blocks.FENCE.getBlockData(), false); + this.a(world, structureboundingbox, 9, 1, 0, 9, 3, 0, Blocks.FENCE.getBlockData(), Blocks.FENCE.getBlockData(), false); + this.a(world, structureboundingbox, 6, 1, 4, 9, 4, 6, Blocks.COBBLESTONE.getBlockData(), Blocks.COBBLESTONE.getBlockData(), false); + this.a(world, Blocks.FLOWING_LAVA.getBlockData(), 7, 1, 5, structureboundingbox); + this.a(world, Blocks.FLOWING_LAVA.getBlockData(), 8, 1, 5, structureboundingbox); + this.a(world, Blocks.IRON_BARS.getBlockData(), 9, 2, 5, structureboundingbox); + this.a(world, Blocks.IRON_BARS.getBlockData(), 9, 2, 4, structureboundingbox); + this.a(world, structureboundingbox, 7, 2, 4, 8, 2, 5, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, Blocks.COBBLESTONE.getBlockData(), 6, 1, 3, structureboundingbox); + this.a(world, Blocks.FURNACE.getBlockData(), 6, 2, 3, structureboundingbox); + this.a(world, Blocks.FURNACE.getBlockData(), 6, 3, 3, structureboundingbox); + this.a(world, Blocks.DOUBLE_STONE_SLAB.getBlockData(), 8, 1, 1, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 0, 2, 2, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 0, 2, 4, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 2, 2, 6, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 4, 2, 6, structureboundingbox); + this.a(world, Blocks.FENCE.getBlockData(), 2, 1, 4, structureboundingbox); + this.a(world, Blocks.WOODEN_PRESSURE_PLATE.getBlockData(), 2, 2, 4, structureboundingbox); + this.a(world, Blocks.PLANKS.getBlockData(), 1, 1, 5, structureboundingbox); + this.a(world, Blocks.OAK_STAIRS.fromLegacyData(this.a(Blocks.OAK_STAIRS, 3)), 2, 1, 5, structureboundingbox); + this.a(world, Blocks.OAK_STAIRS.fromLegacyData(this.a(Blocks.OAK_STAIRS, 1)), 1, 1, 4, structureboundingbox); + if (!this.b && structureboundingbox.b(this.a(5, 5), this.d(1), this.b(5, 5))) { + this.b = true; + this.a(world, structureboundingbox, random, 5, 1, 5, WorldGenVillageBlacksmith.a, 3 + random.nextInt(6)); + } + + int i; + + for (i = 6; i <= 8; ++i) { + if (this.a(world, i, 0, -1, structureboundingbox).getBlock().getMaterial() == Material.AIR && this.a(world, i, -1, -1, structureboundingbox).getBlock().getMaterial() != Material.AIR) { + this.a(world, Blocks.STONE_STAIRS.fromLegacyData(this.a(Blocks.STONE_STAIRS, 3)), i, 0, -1, structureboundingbox); + } + } + + for (i = 0; i < 7; ++i) { + for (int j = 0; j < 10; ++j) { + this.b(world, j, 6, i, structureboundingbox); + this.b(world, Blocks.COBBLESTONE.getBlockData(), j, -1, i, structureboundingbox); + } + } + + this.a(world, structureboundingbox, 7, 1, 1, 1); + return true; + } + + protected int c(int i, int j) { + return 3; + } + } + + public static class WorldGenVillageHouse2 extends WorldGenVillagePiece { + + public WorldGenVillageHouse2() { + } + + public WorldGenVillageHouse2(WorldGenVillageStartPiece worldgenvillagepieces_worldgenvillagestartpiece, int i, Random random, StructureBoundingBox structureboundingbox, EnumDirection enumdirection) { + super(worldgenvillagepieces_worldgenvillagestartpiece, i); + this.m = enumdirection; + this.l = structureboundingbox; + } + + public static WorldGenVillageHouse2 a(WorldGenVillageStartPiece worldgenvillagepieces_worldgenvillagestartpiece, List list, Random random, int i, int j, int k, EnumDirection enumdirection, int l) { + StructureBoundingBox structureboundingbox = StructureBoundingBox.a(i, j, k, 0, 0, 0, 9, 7, 12, enumdirection); + + return a(structureboundingbox) && StructurePiece.a(list, structureboundingbox) == null ? new WorldGenVillageHouse2(worldgenvillagepieces_worldgenvillagestartpiece, l, random, structureboundingbox, enumdirection) : null; + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + if (this.h < 0) { + this.h = this.b(world, structureboundingbox); + if (this.h < 0) { + return true; + } + + this.l.a(0, this.h - this.l.e + 7 - 1, 0); + } + + this.a(world, structureboundingbox, 1, 1, 1, 7, 4, 4, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, 2, 1, 6, 8, 4, 10, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, 2, 0, 5, 8, 0, 10, Blocks.PLANKS.getBlockData(), Blocks.PLANKS.getBlockData(), false); + this.a(world, structureboundingbox, 1, 0, 1, 7, 0, 4, Blocks.PLANKS.getBlockData(), Blocks.PLANKS.getBlockData(), false); + this.a(world, structureboundingbox, 0, 0, 0, 0, 3, 5, Blocks.COBBLESTONE.getBlockData(), Blocks.COBBLESTONE.getBlockData(), false); + this.a(world, structureboundingbox, 8, 0, 0, 8, 3, 10, Blocks.COBBLESTONE.getBlockData(), Blocks.COBBLESTONE.getBlockData(), false); + this.a(world, structureboundingbox, 1, 0, 0, 7, 2, 0, Blocks.COBBLESTONE.getBlockData(), Blocks.COBBLESTONE.getBlockData(), false); + this.a(world, structureboundingbox, 1, 0, 5, 2, 1, 5, Blocks.COBBLESTONE.getBlockData(), Blocks.COBBLESTONE.getBlockData(), false); + this.a(world, structureboundingbox, 2, 0, 6, 2, 3, 10, Blocks.COBBLESTONE.getBlockData(), Blocks.COBBLESTONE.getBlockData(), false); + this.a(world, structureboundingbox, 3, 0, 10, 7, 3, 10, Blocks.COBBLESTONE.getBlockData(), Blocks.COBBLESTONE.getBlockData(), false); + this.a(world, structureboundingbox, 1, 2, 0, 7, 3, 0, Blocks.PLANKS.getBlockData(), Blocks.PLANKS.getBlockData(), false); + this.a(world, structureboundingbox, 1, 2, 5, 2, 3, 5, Blocks.PLANKS.getBlockData(), Blocks.PLANKS.getBlockData(), false); + this.a(world, structureboundingbox, 0, 4, 1, 8, 4, 1, Blocks.PLANKS.getBlockData(), Blocks.PLANKS.getBlockData(), false); + this.a(world, structureboundingbox, 0, 4, 4, 3, 4, 4, Blocks.PLANKS.getBlockData(), Blocks.PLANKS.getBlockData(), false); + this.a(world, structureboundingbox, 0, 5, 2, 8, 5, 3, Blocks.PLANKS.getBlockData(), Blocks.PLANKS.getBlockData(), false); + this.a(world, Blocks.PLANKS.getBlockData(), 0, 4, 2, structureboundingbox); + this.a(world, Blocks.PLANKS.getBlockData(), 0, 4, 3, structureboundingbox); + this.a(world, Blocks.PLANKS.getBlockData(), 8, 4, 2, structureboundingbox); + this.a(world, Blocks.PLANKS.getBlockData(), 8, 4, 3, structureboundingbox); + this.a(world, Blocks.PLANKS.getBlockData(), 8, 4, 4, structureboundingbox); + int i = this.a(Blocks.OAK_STAIRS, 3); + int j = this.a(Blocks.OAK_STAIRS, 2); + + int k; + int l; + + for (k = -1; k <= 2; ++k) { + for (l = 0; l <= 8; ++l) { + this.a(world, Blocks.OAK_STAIRS.fromLegacyData(i), l, 4 + k, k, structureboundingbox); + if ((k > -1 || l <= 1) && (k > 0 || l <= 3) && (k > 1 || l <= 4 || l >= 6)) { + this.a(world, Blocks.OAK_STAIRS.fromLegacyData(j), l, 4 + k, 5 - k, structureboundingbox); + } + } + } + + this.a(world, structureboundingbox, 3, 4, 5, 3, 4, 10, Blocks.PLANKS.getBlockData(), Blocks.PLANKS.getBlockData(), false); + this.a(world, structureboundingbox, 7, 4, 2, 7, 4, 10, Blocks.PLANKS.getBlockData(), Blocks.PLANKS.getBlockData(), false); + this.a(world, structureboundingbox, 4, 5, 4, 4, 5, 10, Blocks.PLANKS.getBlockData(), Blocks.PLANKS.getBlockData(), false); + this.a(world, structureboundingbox, 6, 5, 4, 6, 5, 10, Blocks.PLANKS.getBlockData(), Blocks.PLANKS.getBlockData(), false); + this.a(world, structureboundingbox, 5, 6, 3, 5, 6, 10, Blocks.PLANKS.getBlockData(), Blocks.PLANKS.getBlockData(), false); + k = this.a(Blocks.OAK_STAIRS, 0); + + int i1; + + for (l = 4; l >= 1; --l) { + this.a(world, Blocks.PLANKS.getBlockData(), l, 2 + l, 7 - l, structureboundingbox); + + for (i1 = 8 - l; i1 <= 10; ++i1) { + this.a(world, Blocks.OAK_STAIRS.fromLegacyData(k), l, 2 + l, i1, structureboundingbox); + } + } + + l = this.a(Blocks.OAK_STAIRS, 1); + this.a(world, Blocks.PLANKS.getBlockData(), 6, 6, 3, structureboundingbox); + this.a(world, Blocks.PLANKS.getBlockData(), 7, 5, 4, structureboundingbox); + this.a(world, Blocks.OAK_STAIRS.fromLegacyData(l), 6, 6, 4, structureboundingbox); + + int j1; + + for (i1 = 6; i1 <= 8; ++i1) { + for (j1 = 5; j1 <= 10; ++j1) { + this.a(world, Blocks.OAK_STAIRS.fromLegacyData(l), i1, 12 - i1, j1, structureboundingbox); + } + } + + this.a(world, Blocks.LOG.getBlockData(), 0, 2, 1, structureboundingbox); + this.a(world, Blocks.LOG.getBlockData(), 0, 2, 4, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 0, 2, 2, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 0, 2, 3, structureboundingbox); + this.a(world, Blocks.LOG.getBlockData(), 4, 2, 0, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 5, 2, 0, structureboundingbox); + this.a(world, Blocks.LOG.getBlockData(), 6, 2, 0, structureboundingbox); + this.a(world, Blocks.LOG.getBlockData(), 8, 2, 1, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 8, 2, 2, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 8, 2, 3, structureboundingbox); + this.a(world, Blocks.LOG.getBlockData(), 8, 2, 4, structureboundingbox); + this.a(world, Blocks.PLANKS.getBlockData(), 8, 2, 5, structureboundingbox); + this.a(world, Blocks.LOG.getBlockData(), 8, 2, 6, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 8, 2, 7, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 8, 2, 8, structureboundingbox); + this.a(world, Blocks.LOG.getBlockData(), 8, 2, 9, structureboundingbox); + this.a(world, Blocks.LOG.getBlockData(), 2, 2, 6, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 2, 2, 7, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 2, 2, 8, structureboundingbox); + this.a(world, Blocks.LOG.getBlockData(), 2, 2, 9, structureboundingbox); + this.a(world, Blocks.LOG.getBlockData(), 4, 4, 10, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 5, 4, 10, structureboundingbox); + this.a(world, Blocks.LOG.getBlockData(), 6, 4, 10, structureboundingbox); + this.a(world, Blocks.PLANKS.getBlockData(), 5, 5, 10, structureboundingbox); + this.a(world, Blocks.AIR.getBlockData(), 2, 1, 0, structureboundingbox); + this.a(world, Blocks.AIR.getBlockData(), 2, 2, 0, structureboundingbox); + this.a(world, Blocks.TORCH.getBlockData().set(BlockTorch.FACING, this.m), 2, 3, 1, structureboundingbox); + this.a(world, structureboundingbox, random, 2, 1, 0, EnumDirection.fromType2(this.a(Blocks.WOODEN_DOOR, 1))); + this.a(world, structureboundingbox, 1, 0, -1, 3, 2, -1, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + if (this.a(world, 2, 0, -1, structureboundingbox).getBlock().getMaterial() == Material.AIR && this.a(world, 2, -1, -1, structureboundingbox).getBlock().getMaterial() != Material.AIR) { + this.a(world, Blocks.STONE_STAIRS.fromLegacyData(this.a(Blocks.STONE_STAIRS, 3)), 2, 0, -1, structureboundingbox); + } + + for (i1 = 0; i1 < 5; ++i1) { + for (j1 = 0; j1 < 9; ++j1) { + this.b(world, j1, 7, i1, structureboundingbox); + this.b(world, Blocks.COBBLESTONE.getBlockData(), j1, -1, i1, structureboundingbox); + } + } + + for (i1 = 5; i1 < 11; ++i1) { + for (j1 = 2; j1 < 9; ++j1) { + this.b(world, j1, 7, i1, structureboundingbox); + this.b(world, Blocks.COBBLESTONE.getBlockData(), j1, -1, i1, structureboundingbox); + } + } + + this.a(world, structureboundingbox, 4, 1, 2, 2); + return true; + } + } + + public static class WorldGenVillageButcher extends WorldGenVillagePiece { + + public WorldGenVillageButcher() { + } + + public WorldGenVillageButcher(WorldGenVillageStartPiece worldgenvillagepieces_worldgenvillagestartpiece, int i, Random random, StructureBoundingBox structureboundingbox, EnumDirection enumdirection) { + super(worldgenvillagepieces_worldgenvillagestartpiece, i); + this.m = enumdirection; + this.l = structureboundingbox; + } + + public static WorldGenVillageButcher a(WorldGenVillageStartPiece worldgenvillagepieces_worldgenvillagestartpiece, List list, Random random, int i, int j, int k, EnumDirection enumdirection, int l) { + StructureBoundingBox structureboundingbox = StructureBoundingBox.a(i, j, k, 0, 0, 0, 9, 7, 11, enumdirection); + + return a(structureboundingbox) && StructurePiece.a(list, structureboundingbox) == null ? new WorldGenVillageButcher(worldgenvillagepieces_worldgenvillagestartpiece, l, random, structureboundingbox, enumdirection) : null; + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + if (this.h < 0) { + this.h = this.b(world, structureboundingbox); + if (this.h < 0) { + return true; + } + + this.l.a(0, this.h - this.l.e + 7 - 1, 0); + } + + this.a(world, structureboundingbox, 1, 1, 1, 7, 4, 4, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, 2, 1, 6, 8, 4, 10, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, 2, 0, 6, 8, 0, 10, Blocks.DIRT.getBlockData(), Blocks.DIRT.getBlockData(), false); + this.a(world, Blocks.COBBLESTONE.getBlockData(), 6, 0, 6, structureboundingbox); + this.a(world, structureboundingbox, 2, 1, 6, 2, 1, 10, Blocks.FENCE.getBlockData(), Blocks.FENCE.getBlockData(), false); + this.a(world, structureboundingbox, 8, 1, 6, 8, 1, 10, Blocks.FENCE.getBlockData(), Blocks.FENCE.getBlockData(), false); + this.a(world, structureboundingbox, 3, 1, 10, 7, 1, 10, Blocks.FENCE.getBlockData(), Blocks.FENCE.getBlockData(), false); + this.a(world, structureboundingbox, 1, 0, 1, 7, 0, 4, Blocks.PLANKS.getBlockData(), Blocks.PLANKS.getBlockData(), false); + this.a(world, structureboundingbox, 0, 0, 0, 0, 3, 5, Blocks.COBBLESTONE.getBlockData(), Blocks.COBBLESTONE.getBlockData(), false); + this.a(world, structureboundingbox, 8, 0, 0, 8, 3, 5, Blocks.COBBLESTONE.getBlockData(), Blocks.COBBLESTONE.getBlockData(), false); + this.a(world, structureboundingbox, 1, 0, 0, 7, 1, 0, Blocks.COBBLESTONE.getBlockData(), Blocks.COBBLESTONE.getBlockData(), false); + this.a(world, structureboundingbox, 1, 0, 5, 7, 1, 5, Blocks.COBBLESTONE.getBlockData(), Blocks.COBBLESTONE.getBlockData(), false); + this.a(world, structureboundingbox, 1, 2, 0, 7, 3, 0, Blocks.PLANKS.getBlockData(), Blocks.PLANKS.getBlockData(), false); + this.a(world, structureboundingbox, 1, 2, 5, 7, 3, 5, Blocks.PLANKS.getBlockData(), Blocks.PLANKS.getBlockData(), false); + this.a(world, structureboundingbox, 0, 4, 1, 8, 4, 1, Blocks.PLANKS.getBlockData(), Blocks.PLANKS.getBlockData(), false); + this.a(world, structureboundingbox, 0, 4, 4, 8, 4, 4, Blocks.PLANKS.getBlockData(), Blocks.PLANKS.getBlockData(), false); + this.a(world, structureboundingbox, 0, 5, 2, 8, 5, 3, Blocks.PLANKS.getBlockData(), Blocks.PLANKS.getBlockData(), false); + this.a(world, Blocks.PLANKS.getBlockData(), 0, 4, 2, structureboundingbox); + this.a(world, Blocks.PLANKS.getBlockData(), 0, 4, 3, structureboundingbox); + this.a(world, Blocks.PLANKS.getBlockData(), 8, 4, 2, structureboundingbox); + this.a(world, Blocks.PLANKS.getBlockData(), 8, 4, 3, structureboundingbox); + int i = this.a(Blocks.OAK_STAIRS, 3); + int j = this.a(Blocks.OAK_STAIRS, 2); + + int k; + int l; + + for (k = -1; k <= 2; ++k) { + for (l = 0; l <= 8; ++l) { + this.a(world, Blocks.OAK_STAIRS.fromLegacyData(i), l, 4 + k, k, structureboundingbox); + this.a(world, Blocks.OAK_STAIRS.fromLegacyData(j), l, 4 + k, 5 - k, structureboundingbox); + } + } + + this.a(world, Blocks.LOG.getBlockData(), 0, 2, 1, structureboundingbox); + this.a(world, Blocks.LOG.getBlockData(), 0, 2, 4, structureboundingbox); + this.a(world, Blocks.LOG.getBlockData(), 8, 2, 1, structureboundingbox); + this.a(world, Blocks.LOG.getBlockData(), 8, 2, 4, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 0, 2, 2, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 0, 2, 3, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 8, 2, 2, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 8, 2, 3, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 2, 2, 5, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 3, 2, 5, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 5, 2, 0, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 6, 2, 5, structureboundingbox); + this.a(world, Blocks.FENCE.getBlockData(), 2, 1, 3, structureboundingbox); + this.a(world, Blocks.WOODEN_PRESSURE_PLATE.getBlockData(), 2, 2, 3, structureboundingbox); + this.a(world, Blocks.PLANKS.getBlockData(), 1, 1, 4, structureboundingbox); + this.a(world, Blocks.OAK_STAIRS.fromLegacyData(this.a(Blocks.OAK_STAIRS, 3)), 2, 1, 4, structureboundingbox); + this.a(world, Blocks.OAK_STAIRS.fromLegacyData(this.a(Blocks.OAK_STAIRS, 1)), 1, 1, 3, structureboundingbox); + this.a(world, structureboundingbox, 5, 0, 1, 7, 0, 3, Blocks.DOUBLE_STONE_SLAB.getBlockData(), Blocks.DOUBLE_STONE_SLAB.getBlockData(), false); + this.a(world, Blocks.DOUBLE_STONE_SLAB.getBlockData(), 6, 1, 1, structureboundingbox); + this.a(world, Blocks.DOUBLE_STONE_SLAB.getBlockData(), 6, 1, 2, structureboundingbox); + this.a(world, Blocks.AIR.getBlockData(), 2, 1, 0, structureboundingbox); + this.a(world, Blocks.AIR.getBlockData(), 2, 2, 0, structureboundingbox); + this.a(world, Blocks.TORCH.getBlockData().set(BlockTorch.FACING, this.m), 2, 3, 1, structureboundingbox); + this.a(world, structureboundingbox, random, 2, 1, 0, EnumDirection.fromType2(this.a(Blocks.WOODEN_DOOR, 1))); + if (this.a(world, 2, 0, -1, structureboundingbox).getBlock().getMaterial() == Material.AIR && this.a(world, 2, -1, -1, structureboundingbox).getBlock().getMaterial() != Material.AIR) { + this.a(world, Blocks.STONE_STAIRS.fromLegacyData(this.a(Blocks.STONE_STAIRS, 3)), 2, 0, -1, structureboundingbox); + } + + this.a(world, Blocks.AIR.getBlockData(), 6, 1, 5, structureboundingbox); + this.a(world, Blocks.AIR.getBlockData(), 6, 2, 5, structureboundingbox); + this.a(world, Blocks.TORCH.getBlockData().set(BlockTorch.FACING, this.m.opposite()), 6, 3, 4, structureboundingbox); + this.a(world, structureboundingbox, random, 6, 1, 5, EnumDirection.fromType2(this.a(Blocks.WOODEN_DOOR, 1))); + + for (k = 0; k < 5; ++k) { + for (l = 0; l < 9; ++l) { + this.b(world, l, 7, k, structureboundingbox); + this.b(world, Blocks.COBBLESTONE.getBlockData(), l, -1, k, structureboundingbox); + } + } + + this.a(world, structureboundingbox, 4, 1, 2, 2); + return true; + } + + protected int c(int i, int j) { + return i == 0 ? 4 : super.c(i, j); + } + } + + public static class WorldGenVillageHut extends WorldGenVillagePiece { + + private boolean a; + private int b; + + public WorldGenVillageHut() { + } + + public WorldGenVillageHut(WorldGenVillageStartPiece worldgenvillagepieces_worldgenvillagestartpiece, int i, Random random, StructureBoundingBox structureboundingbox, EnumDirection enumdirection) { + super(worldgenvillagepieces_worldgenvillagestartpiece, i); + this.m = enumdirection; + this.l = structureboundingbox; + this.a = random.nextBoolean(); + this.b = random.nextInt(3); + } + + protected void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + nbttagcompound.setInt("T", this.b); + nbttagcompound.setBoolean("C", this.a); + } + + protected void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + this.b = nbttagcompound.getInt("T"); + this.a = nbttagcompound.getBoolean("C"); + } + + public static WorldGenVillageHut a(WorldGenVillageStartPiece worldgenvillagepieces_worldgenvillagestartpiece, List list, Random random, int i, int j, int k, EnumDirection enumdirection, int l) { + StructureBoundingBox structureboundingbox = StructureBoundingBox.a(i, j, k, 0, 0, 0, 4, 6, 5, enumdirection); + + return a(structureboundingbox) && StructurePiece.a(list, structureboundingbox) == null ? new WorldGenVillageHut(worldgenvillagepieces_worldgenvillagestartpiece, l, random, structureboundingbox, enumdirection) : null; + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + if (this.h < 0) { + this.h = this.b(world, structureboundingbox); + if (this.h < 0) { + return true; + } + + this.l.a(0, this.h - this.l.e + 6 - 1, 0); + } + + this.a(world, structureboundingbox, 1, 1, 1, 3, 5, 4, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, 0, 0, 0, 3, 0, 4, Blocks.COBBLESTONE.getBlockData(), Blocks.COBBLESTONE.getBlockData(), false); + this.a(world, structureboundingbox, 1, 0, 1, 2, 0, 3, Blocks.DIRT.getBlockData(), Blocks.DIRT.getBlockData(), false); + if (this.a) { + this.a(world, structureboundingbox, 1, 4, 1, 2, 4, 3, Blocks.LOG.getBlockData(), Blocks.LOG.getBlockData(), false); + } else { + this.a(world, structureboundingbox, 1, 5, 1, 2, 5, 3, Blocks.LOG.getBlockData(), Blocks.LOG.getBlockData(), false); + } + + this.a(world, Blocks.LOG.getBlockData(), 1, 4, 0, structureboundingbox); + this.a(world, Blocks.LOG.getBlockData(), 2, 4, 0, structureboundingbox); + this.a(world, Blocks.LOG.getBlockData(), 1, 4, 4, structureboundingbox); + this.a(world, Blocks.LOG.getBlockData(), 2, 4, 4, structureboundingbox); + this.a(world, Blocks.LOG.getBlockData(), 0, 4, 1, structureboundingbox); + this.a(world, Blocks.LOG.getBlockData(), 0, 4, 2, structureboundingbox); + this.a(world, Blocks.LOG.getBlockData(), 0, 4, 3, structureboundingbox); + this.a(world, Blocks.LOG.getBlockData(), 3, 4, 1, structureboundingbox); + this.a(world, Blocks.LOG.getBlockData(), 3, 4, 2, structureboundingbox); + this.a(world, Blocks.LOG.getBlockData(), 3, 4, 3, structureboundingbox); + this.a(world, structureboundingbox, 0, 1, 0, 0, 3, 0, Blocks.LOG.getBlockData(), Blocks.LOG.getBlockData(), false); + this.a(world, structureboundingbox, 3, 1, 0, 3, 3, 0, Blocks.LOG.getBlockData(), Blocks.LOG.getBlockData(), false); + this.a(world, structureboundingbox, 0, 1, 4, 0, 3, 4, Blocks.LOG.getBlockData(), Blocks.LOG.getBlockData(), false); + this.a(world, structureboundingbox, 3, 1, 4, 3, 3, 4, Blocks.LOG.getBlockData(), Blocks.LOG.getBlockData(), false); + this.a(world, structureboundingbox, 0, 1, 1, 0, 3, 3, Blocks.PLANKS.getBlockData(), Blocks.PLANKS.getBlockData(), false); + this.a(world, structureboundingbox, 3, 1, 1, 3, 3, 3, Blocks.PLANKS.getBlockData(), Blocks.PLANKS.getBlockData(), false); + this.a(world, structureboundingbox, 1, 1, 0, 2, 3, 0, Blocks.PLANKS.getBlockData(), Blocks.PLANKS.getBlockData(), false); + this.a(world, structureboundingbox, 1, 1, 4, 2, 3, 4, Blocks.PLANKS.getBlockData(), Blocks.PLANKS.getBlockData(), false); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 0, 2, 2, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 3, 2, 2, structureboundingbox); + if (this.b > 0) { + this.a(world, Blocks.FENCE.getBlockData(), this.b, 1, 3, structureboundingbox); + this.a(world, Blocks.WOODEN_PRESSURE_PLATE.getBlockData(), this.b, 2, 3, structureboundingbox); + } + + this.a(world, Blocks.AIR.getBlockData(), 1, 1, 0, structureboundingbox); + this.a(world, Blocks.AIR.getBlockData(), 1, 2, 0, structureboundingbox); + this.a(world, structureboundingbox, random, 1, 1, 0, EnumDirection.fromType2(this.a(Blocks.WOODEN_DOOR, 1))); + if (this.a(world, 1, 0, -1, structureboundingbox).getBlock().getMaterial() == Material.AIR && this.a(world, 1, -1, -1, structureboundingbox).getBlock().getMaterial() != Material.AIR) { + this.a(world, Blocks.STONE_STAIRS.fromLegacyData(this.a(Blocks.STONE_STAIRS, 3)), 1, 0, -1, structureboundingbox); + } + + for (int i = 0; i < 5; ++i) { + for (int j = 0; j < 4; ++j) { + this.b(world, j, 6, i, structureboundingbox); + this.b(world, Blocks.COBBLESTONE.getBlockData(), j, -1, i, structureboundingbox); + } + } + + this.a(world, structureboundingbox, 1, 1, 2, 1); + return true; + } + } + + public static class WorldGenVillageLibrary extends WorldGenVillagePiece { + + public WorldGenVillageLibrary() { + } + + public WorldGenVillageLibrary(WorldGenVillageStartPiece worldgenvillagepieces_worldgenvillagestartpiece, int i, Random random, StructureBoundingBox structureboundingbox, EnumDirection enumdirection) { + super(worldgenvillagepieces_worldgenvillagestartpiece, i); + this.m = enumdirection; + this.l = structureboundingbox; + } + + public static WorldGenVillageLibrary a(WorldGenVillageStartPiece worldgenvillagepieces_worldgenvillagestartpiece, List list, Random random, int i, int j, int k, EnumDirection enumdirection, int l) { + StructureBoundingBox structureboundingbox = StructureBoundingBox.a(i, j, k, 0, 0, 0, 9, 9, 6, enumdirection); + + return a(structureboundingbox) && StructurePiece.a(list, structureboundingbox) == null ? new WorldGenVillageLibrary(worldgenvillagepieces_worldgenvillagestartpiece, l, random, structureboundingbox, enumdirection) : null; + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + if (this.h < 0) { + this.h = this.b(world, structureboundingbox); + if (this.h < 0) { + return true; + } + + this.l.a(0, this.h - this.l.e + 9 - 1, 0); + } + + this.a(world, structureboundingbox, 1, 1, 1, 7, 5, 4, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, 0, 0, 0, 8, 0, 5, Blocks.COBBLESTONE.getBlockData(), Blocks.COBBLESTONE.getBlockData(), false); + this.a(world, structureboundingbox, 0, 5, 0, 8, 5, 5, Blocks.COBBLESTONE.getBlockData(), Blocks.COBBLESTONE.getBlockData(), false); + this.a(world, structureboundingbox, 0, 6, 1, 8, 6, 4, Blocks.COBBLESTONE.getBlockData(), Blocks.COBBLESTONE.getBlockData(), false); + this.a(world, structureboundingbox, 0, 7, 2, 8, 7, 3, Blocks.COBBLESTONE.getBlockData(), Blocks.COBBLESTONE.getBlockData(), false); + int i = this.a(Blocks.OAK_STAIRS, 3); + int j = this.a(Blocks.OAK_STAIRS, 2); + + int k; + int l; + + for (k = -1; k <= 2; ++k) { + for (l = 0; l <= 8; ++l) { + this.a(world, Blocks.OAK_STAIRS.fromLegacyData(i), l, 6 + k, k, structureboundingbox); + this.a(world, Blocks.OAK_STAIRS.fromLegacyData(j), l, 6 + k, 5 - k, structureboundingbox); + } + } + + this.a(world, structureboundingbox, 0, 1, 0, 0, 1, 5, Blocks.COBBLESTONE.getBlockData(), Blocks.COBBLESTONE.getBlockData(), false); + this.a(world, structureboundingbox, 1, 1, 5, 8, 1, 5, Blocks.COBBLESTONE.getBlockData(), Blocks.COBBLESTONE.getBlockData(), false); + this.a(world, structureboundingbox, 8, 1, 0, 8, 1, 4, Blocks.COBBLESTONE.getBlockData(), Blocks.COBBLESTONE.getBlockData(), false); + this.a(world, structureboundingbox, 2, 1, 0, 7, 1, 0, Blocks.COBBLESTONE.getBlockData(), Blocks.COBBLESTONE.getBlockData(), false); + this.a(world, structureboundingbox, 0, 2, 0, 0, 4, 0, Blocks.COBBLESTONE.getBlockData(), Blocks.COBBLESTONE.getBlockData(), false); + this.a(world, structureboundingbox, 0, 2, 5, 0, 4, 5, Blocks.COBBLESTONE.getBlockData(), Blocks.COBBLESTONE.getBlockData(), false); + this.a(world, structureboundingbox, 8, 2, 5, 8, 4, 5, Blocks.COBBLESTONE.getBlockData(), Blocks.COBBLESTONE.getBlockData(), false); + this.a(world, structureboundingbox, 8, 2, 0, 8, 4, 0, Blocks.COBBLESTONE.getBlockData(), Blocks.COBBLESTONE.getBlockData(), false); + this.a(world, structureboundingbox, 0, 2, 1, 0, 4, 4, Blocks.PLANKS.getBlockData(), Blocks.PLANKS.getBlockData(), false); + this.a(world, structureboundingbox, 1, 2, 5, 7, 4, 5, Blocks.PLANKS.getBlockData(), Blocks.PLANKS.getBlockData(), false); + this.a(world, structureboundingbox, 8, 2, 1, 8, 4, 4, Blocks.PLANKS.getBlockData(), Blocks.PLANKS.getBlockData(), false); + this.a(world, structureboundingbox, 1, 2, 0, 7, 4, 0, Blocks.PLANKS.getBlockData(), Blocks.PLANKS.getBlockData(), false); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 4, 2, 0, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 5, 2, 0, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 6, 2, 0, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 4, 3, 0, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 5, 3, 0, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 6, 3, 0, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 0, 2, 2, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 0, 2, 3, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 0, 3, 2, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 0, 3, 3, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 8, 2, 2, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 8, 2, 3, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 8, 3, 2, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 8, 3, 3, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 2, 2, 5, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 3, 2, 5, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 5, 2, 5, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 6, 2, 5, structureboundingbox); + this.a(world, structureboundingbox, 1, 4, 1, 7, 4, 1, Blocks.PLANKS.getBlockData(), Blocks.PLANKS.getBlockData(), false); + this.a(world, structureboundingbox, 1, 4, 4, 7, 4, 4, Blocks.PLANKS.getBlockData(), Blocks.PLANKS.getBlockData(), false); + this.a(world, structureboundingbox, 1, 3, 4, 7, 3, 4, Blocks.BOOKSHELF.getBlockData(), Blocks.BOOKSHELF.getBlockData(), false); + this.a(world, Blocks.PLANKS.getBlockData(), 7, 1, 4, structureboundingbox); + this.a(world, Blocks.OAK_STAIRS.fromLegacyData(this.a(Blocks.OAK_STAIRS, 0)), 7, 1, 3, structureboundingbox); + k = this.a(Blocks.OAK_STAIRS, 3); + this.a(world, Blocks.OAK_STAIRS.fromLegacyData(k), 6, 1, 4, structureboundingbox); + this.a(world, Blocks.OAK_STAIRS.fromLegacyData(k), 5, 1, 4, structureboundingbox); + this.a(world, Blocks.OAK_STAIRS.fromLegacyData(k), 4, 1, 4, structureboundingbox); + this.a(world, Blocks.OAK_STAIRS.fromLegacyData(k), 3, 1, 4, structureboundingbox); + this.a(world, Blocks.FENCE.getBlockData(), 6, 1, 3, structureboundingbox); + this.a(world, Blocks.WOODEN_PRESSURE_PLATE.getBlockData(), 6, 2, 3, structureboundingbox); + this.a(world, Blocks.FENCE.getBlockData(), 4, 1, 3, structureboundingbox); + this.a(world, Blocks.WOODEN_PRESSURE_PLATE.getBlockData(), 4, 2, 3, structureboundingbox); + this.a(world, Blocks.CRAFTING_TABLE.getBlockData(), 7, 1, 1, structureboundingbox); + this.a(world, Blocks.AIR.getBlockData(), 1, 1, 0, structureboundingbox); + this.a(world, Blocks.AIR.getBlockData(), 1, 2, 0, structureboundingbox); + this.a(world, structureboundingbox, random, 1, 1, 0, EnumDirection.fromType2(this.a(Blocks.WOODEN_DOOR, 1))); + if (this.a(world, 1, 0, -1, structureboundingbox).getBlock().getMaterial() == Material.AIR && this.a(world, 1, -1, -1, structureboundingbox).getBlock().getMaterial() != Material.AIR) { + this.a(world, Blocks.STONE_STAIRS.fromLegacyData(this.a(Blocks.STONE_STAIRS, 3)), 1, 0, -1, structureboundingbox); + } + + for (l = 0; l < 6; ++l) { + for (int i1 = 0; i1 < 9; ++i1) { + this.b(world, i1, 9, l, structureboundingbox); + this.b(world, Blocks.COBBLESTONE.getBlockData(), i1, -1, l, structureboundingbox); + } + } + + this.a(world, structureboundingbox, 2, 1, 2, 1); + return true; + } + + protected int c(int i, int j) { + return 1; + } + } + + public static class WorldGenVillageTemple extends WorldGenVillagePiece { + + public WorldGenVillageTemple() { + } + + public WorldGenVillageTemple(WorldGenVillageStartPiece worldgenvillagepieces_worldgenvillagestartpiece, int i, Random random, StructureBoundingBox structureboundingbox, EnumDirection enumdirection) { + super(worldgenvillagepieces_worldgenvillagestartpiece, i); + this.m = enumdirection; + this.l = structureboundingbox; + } + + public static WorldGenVillageTemple a(WorldGenVillageStartPiece worldgenvillagepieces_worldgenvillagestartpiece, List list, Random random, int i, int j, int k, EnumDirection enumdirection, int l) { + StructureBoundingBox structureboundingbox = StructureBoundingBox.a(i, j, k, 0, 0, 0, 5, 12, 9, enumdirection); + + return a(structureboundingbox) && StructurePiece.a(list, structureboundingbox) == null ? new WorldGenVillageTemple(worldgenvillagepieces_worldgenvillagestartpiece, l, random, structureboundingbox, enumdirection) : null; + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + if (this.h < 0) { + this.h = this.b(world, structureboundingbox); + if (this.h < 0) { + return true; + } + + this.l.a(0, this.h - this.l.e + 12 - 1, 0); + } + + this.a(world, structureboundingbox, 1, 1, 1, 3, 3, 7, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, 1, 5, 1, 3, 9, 3, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + this.a(world, structureboundingbox, 1, 0, 0, 3, 0, 8, Blocks.COBBLESTONE.getBlockData(), Blocks.COBBLESTONE.getBlockData(), false); + this.a(world, structureboundingbox, 1, 1, 0, 3, 10, 0, Blocks.COBBLESTONE.getBlockData(), Blocks.COBBLESTONE.getBlockData(), false); + this.a(world, structureboundingbox, 0, 1, 1, 0, 10, 3, Blocks.COBBLESTONE.getBlockData(), Blocks.COBBLESTONE.getBlockData(), false); + this.a(world, structureboundingbox, 4, 1, 1, 4, 10, 3, Blocks.COBBLESTONE.getBlockData(), Blocks.COBBLESTONE.getBlockData(), false); + this.a(world, structureboundingbox, 0, 0, 4, 0, 4, 7, Blocks.COBBLESTONE.getBlockData(), Blocks.COBBLESTONE.getBlockData(), false); + this.a(world, structureboundingbox, 4, 0, 4, 4, 4, 7, Blocks.COBBLESTONE.getBlockData(), Blocks.COBBLESTONE.getBlockData(), false); + this.a(world, structureboundingbox, 1, 1, 8, 3, 4, 8, Blocks.COBBLESTONE.getBlockData(), Blocks.COBBLESTONE.getBlockData(), false); + this.a(world, structureboundingbox, 1, 5, 4, 3, 10, 4, Blocks.COBBLESTONE.getBlockData(), Blocks.COBBLESTONE.getBlockData(), false); + this.a(world, structureboundingbox, 1, 5, 5, 3, 5, 7, Blocks.COBBLESTONE.getBlockData(), Blocks.COBBLESTONE.getBlockData(), false); + this.a(world, structureboundingbox, 0, 9, 0, 4, 9, 4, Blocks.COBBLESTONE.getBlockData(), Blocks.COBBLESTONE.getBlockData(), false); + this.a(world, structureboundingbox, 0, 4, 0, 4, 4, 4, Blocks.COBBLESTONE.getBlockData(), Blocks.COBBLESTONE.getBlockData(), false); + this.a(world, Blocks.COBBLESTONE.getBlockData(), 0, 11, 2, structureboundingbox); + this.a(world, Blocks.COBBLESTONE.getBlockData(), 4, 11, 2, structureboundingbox); + this.a(world, Blocks.COBBLESTONE.getBlockData(), 2, 11, 0, structureboundingbox); + this.a(world, Blocks.COBBLESTONE.getBlockData(), 2, 11, 4, structureboundingbox); + this.a(world, Blocks.COBBLESTONE.getBlockData(), 1, 1, 6, structureboundingbox); + this.a(world, Blocks.COBBLESTONE.getBlockData(), 1, 1, 7, structureboundingbox); + this.a(world, Blocks.COBBLESTONE.getBlockData(), 2, 1, 7, structureboundingbox); + this.a(world, Blocks.COBBLESTONE.getBlockData(), 3, 1, 6, structureboundingbox); + this.a(world, Blocks.COBBLESTONE.getBlockData(), 3, 1, 7, structureboundingbox); + this.a(world, Blocks.STONE_STAIRS.fromLegacyData(this.a(Blocks.STONE_STAIRS, 3)), 1, 1, 5, structureboundingbox); + this.a(world, Blocks.STONE_STAIRS.fromLegacyData(this.a(Blocks.STONE_STAIRS, 3)), 2, 1, 6, structureboundingbox); + this.a(world, Blocks.STONE_STAIRS.fromLegacyData(this.a(Blocks.STONE_STAIRS, 3)), 3, 1, 5, structureboundingbox); + this.a(world, Blocks.STONE_STAIRS.fromLegacyData(this.a(Blocks.STONE_STAIRS, 1)), 1, 2, 7, structureboundingbox); + this.a(world, Blocks.STONE_STAIRS.fromLegacyData(this.a(Blocks.STONE_STAIRS, 0)), 3, 2, 7, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 0, 2, 2, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 0, 3, 2, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 4, 2, 2, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 4, 3, 2, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 0, 6, 2, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 0, 7, 2, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 4, 6, 2, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 4, 7, 2, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 2, 6, 0, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 2, 7, 0, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 2, 6, 4, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 2, 7, 4, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 0, 3, 6, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 4, 3, 6, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 2, 3, 8, structureboundingbox); + this.a(world, Blocks.TORCH.getBlockData().set(BlockTorch.FACING, this.m.opposite()), 2, 4, 7, structureboundingbox); + this.a(world, Blocks.TORCH.getBlockData().set(BlockTorch.FACING, this.m.e()), 1, 4, 6, structureboundingbox); + this.a(world, Blocks.TORCH.getBlockData().set(BlockTorch.FACING, this.m.f()), 3, 4, 6, structureboundingbox); + this.a(world, Blocks.TORCH.getBlockData().set(BlockTorch.FACING, this.m), 2, 4, 5, structureboundingbox); + int i = this.a(Blocks.LADDER, 4); + + int j; + + for (j = 1; j <= 9; ++j) { + this.a(world, Blocks.LADDER.fromLegacyData(i), 3, j, 3, structureboundingbox); + } + + this.a(world, Blocks.AIR.getBlockData(), 2, 1, 0, structureboundingbox); + this.a(world, Blocks.AIR.getBlockData(), 2, 2, 0, structureboundingbox); + this.a(world, structureboundingbox, random, 2, 1, 0, EnumDirection.fromType2(this.a(Blocks.WOODEN_DOOR, 1))); + if (this.a(world, 2, 0, -1, structureboundingbox).getBlock().getMaterial() == Material.AIR && this.a(world, 2, -1, -1, structureboundingbox).getBlock().getMaterial() != Material.AIR) { + this.a(world, Blocks.STONE_STAIRS.fromLegacyData(this.a(Blocks.STONE_STAIRS, 3)), 2, 0, -1, structureboundingbox); + } + + for (j = 0; j < 9; ++j) { + for (int k = 0; k < 5; ++k) { + this.b(world, k, 12, j, structureboundingbox); + this.b(world, Blocks.COBBLESTONE.getBlockData(), k, -1, j, structureboundingbox); + } + } + + this.a(world, structureboundingbox, 2, 1, 2, 1); + return true; + } + + protected int c(int i, int j) { + return 2; + } + } + + public static class WorldGenVillageHouse extends WorldGenVillagePiece { + + private boolean a; + + public WorldGenVillageHouse() { + } + + public WorldGenVillageHouse(WorldGenVillageStartPiece worldgenvillagepieces_worldgenvillagestartpiece, int i, Random random, StructureBoundingBox structureboundingbox, EnumDirection enumdirection) { + super(worldgenvillagepieces_worldgenvillagestartpiece, i); + this.m = enumdirection; + this.l = structureboundingbox; + this.a = random.nextBoolean(); + } + + protected void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + nbttagcompound.setBoolean("Terrace", this.a); + } + + protected void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + this.a = nbttagcompound.getBoolean("Terrace"); + } + + public static WorldGenVillageHouse a(WorldGenVillageStartPiece worldgenvillagepieces_worldgenvillagestartpiece, List list, Random random, int i, int j, int k, EnumDirection enumdirection, int l) { + StructureBoundingBox structureboundingbox = StructureBoundingBox.a(i, j, k, 0, 0, 0, 5, 6, 5, enumdirection); + + return StructurePiece.a(list, structureboundingbox) != null ? null : new WorldGenVillageHouse(worldgenvillagepieces_worldgenvillagestartpiece, l, random, structureboundingbox, enumdirection); + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + if (this.h < 0) { + this.h = this.b(world, structureboundingbox); + if (this.h < 0) { + return true; + } + + this.l.a(0, this.h - this.l.e + 6 - 1, 0); + } + + this.a(world, structureboundingbox, 0, 0, 0, 4, 0, 4, Blocks.COBBLESTONE.getBlockData(), Blocks.COBBLESTONE.getBlockData(), false); + this.a(world, structureboundingbox, 0, 4, 0, 4, 4, 4, Blocks.LOG.getBlockData(), Blocks.LOG.getBlockData(), false); + this.a(world, structureboundingbox, 1, 4, 1, 3, 4, 3, Blocks.PLANKS.getBlockData(), Blocks.PLANKS.getBlockData(), false); + this.a(world, Blocks.COBBLESTONE.getBlockData(), 0, 1, 0, structureboundingbox); + this.a(world, Blocks.COBBLESTONE.getBlockData(), 0, 2, 0, structureboundingbox); + this.a(world, Blocks.COBBLESTONE.getBlockData(), 0, 3, 0, structureboundingbox); + this.a(world, Blocks.COBBLESTONE.getBlockData(), 4, 1, 0, structureboundingbox); + this.a(world, Blocks.COBBLESTONE.getBlockData(), 4, 2, 0, structureboundingbox); + this.a(world, Blocks.COBBLESTONE.getBlockData(), 4, 3, 0, structureboundingbox); + this.a(world, Blocks.COBBLESTONE.getBlockData(), 0, 1, 4, structureboundingbox); + this.a(world, Blocks.COBBLESTONE.getBlockData(), 0, 2, 4, structureboundingbox); + this.a(world, Blocks.COBBLESTONE.getBlockData(), 0, 3, 4, structureboundingbox); + this.a(world, Blocks.COBBLESTONE.getBlockData(), 4, 1, 4, structureboundingbox); + this.a(world, Blocks.COBBLESTONE.getBlockData(), 4, 2, 4, structureboundingbox); + this.a(world, Blocks.COBBLESTONE.getBlockData(), 4, 3, 4, structureboundingbox); + this.a(world, structureboundingbox, 0, 1, 1, 0, 3, 3, Blocks.PLANKS.getBlockData(), Blocks.PLANKS.getBlockData(), false); + this.a(world, structureboundingbox, 4, 1, 1, 4, 3, 3, Blocks.PLANKS.getBlockData(), Blocks.PLANKS.getBlockData(), false); + this.a(world, structureboundingbox, 1, 1, 4, 3, 3, 4, Blocks.PLANKS.getBlockData(), Blocks.PLANKS.getBlockData(), false); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 0, 2, 2, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 2, 2, 4, structureboundingbox); + this.a(world, Blocks.GLASS_PANE.getBlockData(), 4, 2, 2, structureboundingbox); + this.a(world, Blocks.PLANKS.getBlockData(), 1, 1, 0, structureboundingbox); + this.a(world, Blocks.PLANKS.getBlockData(), 1, 2, 0, structureboundingbox); + this.a(world, Blocks.PLANKS.getBlockData(), 1, 3, 0, structureboundingbox); + this.a(world, Blocks.PLANKS.getBlockData(), 2, 3, 0, structureboundingbox); + this.a(world, Blocks.PLANKS.getBlockData(), 3, 3, 0, structureboundingbox); + this.a(world, Blocks.PLANKS.getBlockData(), 3, 2, 0, structureboundingbox); + this.a(world, Blocks.PLANKS.getBlockData(), 3, 1, 0, structureboundingbox); + if (this.a(world, 2, 0, -1, structureboundingbox).getBlock().getMaterial() == Material.AIR && this.a(world, 2, -1, -1, structureboundingbox).getBlock().getMaterial() != Material.AIR) { + this.a(world, Blocks.STONE_STAIRS.fromLegacyData(this.a(Blocks.STONE_STAIRS, 3)), 2, 0, -1, structureboundingbox); + } + + this.a(world, structureboundingbox, 1, 1, 1, 3, 3, 3, Blocks.AIR.getBlockData(), Blocks.AIR.getBlockData(), false); + if (this.a) { + this.a(world, Blocks.FENCE.getBlockData(), 0, 5, 0, structureboundingbox); + this.a(world, Blocks.FENCE.getBlockData(), 1, 5, 0, structureboundingbox); + this.a(world, Blocks.FENCE.getBlockData(), 2, 5, 0, structureboundingbox); + this.a(world, Blocks.FENCE.getBlockData(), 3, 5, 0, structureboundingbox); + this.a(world, Blocks.FENCE.getBlockData(), 4, 5, 0, structureboundingbox); + this.a(world, Blocks.FENCE.getBlockData(), 0, 5, 4, structureboundingbox); + this.a(world, Blocks.FENCE.getBlockData(), 1, 5, 4, structureboundingbox); + this.a(world, Blocks.FENCE.getBlockData(), 2, 5, 4, structureboundingbox); + this.a(world, Blocks.FENCE.getBlockData(), 3, 5, 4, structureboundingbox); + this.a(world, Blocks.FENCE.getBlockData(), 4, 5, 4, structureboundingbox); + this.a(world, Blocks.FENCE.getBlockData(), 4, 5, 1, structureboundingbox); + this.a(world, Blocks.FENCE.getBlockData(), 4, 5, 2, structureboundingbox); + this.a(world, Blocks.FENCE.getBlockData(), 4, 5, 3, structureboundingbox); + this.a(world, Blocks.FENCE.getBlockData(), 0, 5, 1, structureboundingbox); + this.a(world, Blocks.FENCE.getBlockData(), 0, 5, 2, structureboundingbox); + this.a(world, Blocks.FENCE.getBlockData(), 0, 5, 3, structureboundingbox); + } + + int i; + + if (this.a) { + i = this.a(Blocks.LADDER, 3); + this.a(world, Blocks.LADDER.fromLegacyData(i), 3, 1, 3, structureboundingbox); + this.a(world, Blocks.LADDER.fromLegacyData(i), 3, 2, 3, structureboundingbox); + this.a(world, Blocks.LADDER.fromLegacyData(i), 3, 3, 3, structureboundingbox); + this.a(world, Blocks.LADDER.fromLegacyData(i), 3, 4, 3, structureboundingbox); + } + + this.a(world, Blocks.TORCH.getBlockData().set(BlockTorch.FACING, this.m), 2, 3, 1, structureboundingbox); + + for (i = 0; i < 5; ++i) { + for (int j = 0; j < 5; ++j) { + this.b(world, j, 6, i, structureboundingbox); + this.b(world, Blocks.COBBLESTONE.getBlockData(), j, -1, i, structureboundingbox); + } + } + + this.a(world, structureboundingbox, 1, 1, 2, 1); + return true; + } + } + + public static class WorldGenVillageRoad extends WorldGenVillageRoadPiece { + + private int a; + + public WorldGenVillageRoad() { + } + + public WorldGenVillageRoad(WorldGenVillageStartPiece worldgenvillagepieces_worldgenvillagestartpiece, int i, Random random, StructureBoundingBox structureboundingbox, EnumDirection enumdirection) { + super(worldgenvillagepieces_worldgenvillagestartpiece, i); + this.m = enumdirection; + this.l = structureboundingbox; + this.a = Math.max(structureboundingbox.c(), structureboundingbox.e()); + } + + protected void a(NBTTagCompound nbttagcompound) { + super.a(nbttagcompound); + nbttagcompound.setInt("Length", this.a); + } + + protected void b(NBTTagCompound nbttagcompound) { + super.b(nbttagcompound); + this.a = nbttagcompound.getInt("Length"); + } + + public void a(StructurePiece structurepiece, List list, Random random) { + boolean flag = false; + + int i; + StructurePiece structurepiece1; + + for (i = random.nextInt(5); i < this.a - 8; i += 2 + random.nextInt(5)) { + structurepiece1 = this.a((WorldGenVillageStartPiece) structurepiece, list, random, 0, i); + if (structurepiece1 != null) { + i += Math.max(structurepiece1.l.c(), structurepiece1.l.e()); + flag = true; + } + } + + for (i = random.nextInt(5); i < this.a - 8; i += 2 + random.nextInt(5)) { + structurepiece1 = this.b((WorldGenVillageStartPiece) structurepiece, list, random, 0, i); + if (structurepiece1 != null) { + i += Math.max(structurepiece1.l.c(), structurepiece1.l.e()); + flag = true; + } + } + + if (flag && random.nextInt(3) > 0 && this.m != null) { + switch (SyntheticClass_1.a[this.m.ordinal()]) { + case 1: + WorldGenVillagePieces.e((WorldGenVillageStartPiece) structurepiece, list, random, this.l.a - 1, this.l.b, this.l.c, EnumDirection.WEST, this.d()); + break; + + case 2: + WorldGenVillagePieces.e((WorldGenVillageStartPiece) structurepiece, list, random, this.l.a - 1, this.l.b, this.l.f - 2, EnumDirection.WEST, this.d()); + break; + + case 3: + WorldGenVillagePieces.e((WorldGenVillageStartPiece) structurepiece, list, random, this.l.a, this.l.b, this.l.c - 1, EnumDirection.NORTH, this.d()); + break; + + case 4: + WorldGenVillagePieces.e((WorldGenVillageStartPiece) structurepiece, list, random, this.l.d - 2, this.l.b, this.l.c - 1, EnumDirection.NORTH, this.d()); + } + } + + if (flag && random.nextInt(3) > 0 && this.m != null) { + switch (SyntheticClass_1.a[this.m.ordinal()]) { + case 1: + WorldGenVillagePieces.e((WorldGenVillageStartPiece) structurepiece, list, random, this.l.d + 1, this.l.b, this.l.c, EnumDirection.EAST, this.d()); + break; + + case 2: + WorldGenVillagePieces.e((WorldGenVillageStartPiece) structurepiece, list, random, this.l.d + 1, this.l.b, this.l.f - 2, EnumDirection.EAST, this.d()); + break; + + case 3: + WorldGenVillagePieces.e((WorldGenVillageStartPiece) structurepiece, list, random, this.l.a, this.l.b, this.l.f + 1, EnumDirection.SOUTH, this.d()); + break; + + case 4: + WorldGenVillagePieces.e((WorldGenVillageStartPiece) structurepiece, list, random, this.l.d - 2, this.l.b, this.l.f + 1, EnumDirection.SOUTH, this.d()); + } + } + + } + + public static StructureBoundingBox a(WorldGenVillageStartPiece worldgenvillagepieces_worldgenvillagestartpiece, List list, Random random, int i, int j, int k, EnumDirection enumdirection) { + for (int l = 7 * MathHelper.nextInt(random, 3, 5); l >= 7; l -= 7) { + StructureBoundingBox structureboundingbox = StructureBoundingBox.a(i, j, k, 0, 0, 0, 3, 3, l, enumdirection); + + if (StructurePiece.a(list, structureboundingbox) == null) { + return structureboundingbox; + } + } + + return null; + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + IBlockData iblockdata = this.a(Blocks.GRAVEL.getBlockData()); + IBlockData iblockdata1 = this.a(Blocks.COBBLESTONE.getBlockData()); + + for (int i = this.l.a; i <= this.l.d; ++i) { + for (int j = this.l.c; j <= this.l.f; ++j) { + if (structureboundingbox.b(i, 64, j)) { + BlockPosition blockposition = world.r(i, j).down(); + world.setTypeAndData(blockposition, iblockdata, 2); + world.setTypeAndData(blockposition.down(), iblockdata1, 2); + } + } + } + + return true; + } + } + + public abstract static class WorldGenVillageRoadPiece extends WorldGenVillagePiece { + + public WorldGenVillageRoadPiece() { + } + + protected WorldGenVillageRoadPiece(WorldGenVillageStartPiece worldgenvillagepieces_worldgenvillagestartpiece, int i) { + super(worldgenvillagepieces_worldgenvillagestartpiece, i); + } + } + + public static class WorldGenVillageStartPiece extends WorldGenVillageWell { + + public WorldChunkManager a; + public boolean b; + public int c; + public WorldGenVillagePieceWeight d; + public List e; + public List f = Lists.newArrayList(); + public List g = Lists.newArrayList(); + + public WorldGenVillageStartPiece() { + } + + public WorldGenVillageStartPiece(WorldChunkManager worldchunkmanager, int i, Random random, int j, int k, List list, int l) { + super(null, 0, random, j, k); + this.a = worldchunkmanager; + this.e = list; + this.c = l; + BiomeBase biomebase = worldchunkmanager.getBiome(j, k, BiomeBase.ad); + + this.b = biomebase == BiomeBase.DESERT || biomebase == BiomeBase.DESERT_HILLS; + this.a(this.b); + } + + public WorldChunkManager e() { + return this.a; + } + } + + public static class WorldGenVillageWell extends WorldGenVillagePiece { + + public WorldGenVillageWell() { + } + + public WorldGenVillageWell(WorldGenVillageStartPiece worldgenvillagepieces_worldgenvillagestartpiece, int i, Random random, int j, int k) { + super(worldgenvillagepieces_worldgenvillagestartpiece, i); + this.m = EnumDirection.EnumDirectionLimit.HORIZONTAL.a(random); + switch (SyntheticClass_1.a[this.m.ordinal()]) { + case 1: + case 2: + this.l = new StructureBoundingBox(j, 64, k, j + 6 - 1, 78, k + 6 - 1); + break; + + default: + this.l = new StructureBoundingBox(j, 64, k, j + 6 - 1, 78, k + 6 - 1); + } + + } + + public void a(StructurePiece structurepiece, List list, Random random) { + WorldGenVillagePieces.e((WorldGenVillageStartPiece) structurepiece, list, random, this.l.a - 1, this.l.e - 4, this.l.c + 1, EnumDirection.WEST, this.d()); + WorldGenVillagePieces.e((WorldGenVillageStartPiece) structurepiece, list, random, this.l.d + 1, this.l.e - 4, this.l.c + 1, EnumDirection.EAST, this.d()); + WorldGenVillagePieces.e((WorldGenVillageStartPiece) structurepiece, list, random, this.l.a + 1, this.l.e - 4, this.l.c - 1, EnumDirection.NORTH, this.d()); + WorldGenVillagePieces.e((WorldGenVillageStartPiece) structurepiece, list, random, this.l.a + 1, this.l.e - 4, this.l.f + 1, EnumDirection.SOUTH, this.d()); + } + + public boolean a(World world, Random random, StructureBoundingBox structureboundingbox) { + if (this.h < 0) { + this.h = this.b(world, structureboundingbox); + if (this.h < 0) { + return true; + } + + this.l.a(0, this.h - this.l.e + 3, 0); + } + + this.a(world, structureboundingbox, 1, 0, 1, 4, 12, 4, Blocks.COBBLESTONE.getBlockData(), Blocks.FLOWING_WATER.getBlockData(), false); + this.a(world, Blocks.AIR.getBlockData(), 2, 12, 2, structureboundingbox); + this.a(world, Blocks.AIR.getBlockData(), 3, 12, 2, structureboundingbox); + this.a(world, Blocks.AIR.getBlockData(), 2, 12, 3, structureboundingbox); + this.a(world, Blocks.AIR.getBlockData(), 3, 12, 3, structureboundingbox); + this.a(world, Blocks.FENCE.getBlockData(), 1, 13, 1, structureboundingbox); + this.a(world, Blocks.FENCE.getBlockData(), 1, 14, 1, structureboundingbox); + this.a(world, Blocks.FENCE.getBlockData(), 4, 13, 1, structureboundingbox); + this.a(world, Blocks.FENCE.getBlockData(), 4, 14, 1, structureboundingbox); + this.a(world, Blocks.FENCE.getBlockData(), 1, 13, 4, structureboundingbox); + this.a(world, Blocks.FENCE.getBlockData(), 1, 14, 4, structureboundingbox); + this.a(world, Blocks.FENCE.getBlockData(), 4, 13, 4, structureboundingbox); + this.a(world, Blocks.FENCE.getBlockData(), 4, 14, 4, structureboundingbox); + this.a(world, structureboundingbox, 1, 15, 1, 4, 15, 4, Blocks.COBBLESTONE.getBlockData(), Blocks.COBBLESTONE.getBlockData(), false); + + for (int i = 0; i <= 5; ++i) { + for (int j = 0; j <= 5; ++j) { + if (j == 0 || j == 5 || i == 0 || i == 5) { + this.a(world, Blocks.GRAVEL.getBlockData(), j, 11, i, structureboundingbox); + this.b(world, j, 12, i, structureboundingbox); + } + } + } + + return true; + } + } + + abstract static class WorldGenVillagePiece extends StructurePiece { + + protected int h = -1; + private int a; + private boolean b; + + public WorldGenVillagePiece() { + } + + protected WorldGenVillagePiece(WorldGenVillageStartPiece worldgenvillagepieces_worldgenvillagestartpiece, int i) { + super(i); + if (worldgenvillagepieces_worldgenvillagestartpiece != null) { + this.b = worldgenvillagepieces_worldgenvillagestartpiece.b; + } + + } + + protected void a(NBTTagCompound nbttagcompound) { + nbttagcompound.setInt("HPos", this.h); + nbttagcompound.setInt("VCount", this.a); + nbttagcompound.setBoolean("Desert", this.b); + } + + protected void b(NBTTagCompound nbttagcompound) { + this.h = nbttagcompound.getInt("HPos"); + this.a = nbttagcompound.getInt("VCount"); + this.b = nbttagcompound.getBoolean("Desert"); + } + + protected StructurePiece a(WorldGenVillageStartPiece worldgenvillagepieces_worldgenvillagestartpiece, List list, Random random, int i, int j) { + if (this.m != null) { + switch (SyntheticClass_1.a[this.m.ordinal()]) { + case 1: + return WorldGenVillagePieces.d(worldgenvillagepieces_worldgenvillagestartpiece, list, random, this.l.a - 1, this.l.b + i, this.l.c + j, EnumDirection.WEST, this.d()); + + case 2: + return WorldGenVillagePieces.d(worldgenvillagepieces_worldgenvillagestartpiece, list, random, this.l.a - 1, this.l.b + i, this.l.c + j, EnumDirection.WEST, this.d()); + + case 3: + return WorldGenVillagePieces.d(worldgenvillagepieces_worldgenvillagestartpiece, list, random, this.l.a + j, this.l.b + i, this.l.c - 1, EnumDirection.NORTH, this.d()); + + case 4: + return WorldGenVillagePieces.d(worldgenvillagepieces_worldgenvillagestartpiece, list, random, this.l.a + j, this.l.b + i, this.l.c - 1, EnumDirection.NORTH, this.d()); + } + } + + return null; + } + + protected StructurePiece b(WorldGenVillageStartPiece worldgenvillagepieces_worldgenvillagestartpiece, List list, Random random, int i, int j) { + if (this.m != null) { + switch (SyntheticClass_1.a[this.m.ordinal()]) { + case 1: + return WorldGenVillagePieces.d(worldgenvillagepieces_worldgenvillagestartpiece, list, random, this.l.d + 1, this.l.b + i, this.l.c + j, EnumDirection.EAST, this.d()); + + case 2: + return WorldGenVillagePieces.d(worldgenvillagepieces_worldgenvillagestartpiece, list, random, this.l.d + 1, this.l.b + i, this.l.c + j, EnumDirection.EAST, this.d()); + + case 3: + return WorldGenVillagePieces.d(worldgenvillagepieces_worldgenvillagestartpiece, list, random, this.l.a + j, this.l.b + i, this.l.f + 1, EnumDirection.SOUTH, this.d()); + + case 4: + return WorldGenVillagePieces.d(worldgenvillagepieces_worldgenvillagestartpiece, list, random, this.l.a + j, this.l.b + i, this.l.f + 1, EnumDirection.SOUTH, this.d()); + } + } + + return null; + } + + protected int b(World world, StructureBoundingBox structureboundingbox) { + int i = 0; + int j = 0; + + for (int k = this.l.c; k <= this.l.f; ++k) { + for (int l = this.l.a; l <= this.l.d; ++l) { + if (structureboundingbox.b(l, 64, k)) { + i += Math.max(world.r(l, k).getY(), world.worldProvider.getSeaLevel()); + ++j; + } + } + } + + if (j == 0) { + return -1; + } else { + return i / j; + } + } + + protected static boolean a(StructureBoundingBox structureboundingbox) { + return structureboundingbox != null && structureboundingbox.b > 10; + } + + protected void a(World world, StructureBoundingBox structureboundingbox, int i, int j, int k, int l) { + if (this.a < l) { + for (int i1 = this.a; i1 < l; ++i1) { + int j1 = this.a(i + i1, k); + int k1 = this.d(j); + int l1 = this.b(i + i1, k); + + if (!structureboundingbox.b(j1, k1, l1)) { + break; + } + + ++this.a; + EntityVillager entityvillager = new EntityVillager(world); + + entityvillager.setPositionRotation((double) j1 + 0.5D, k1, (double) l1 + 0.5D, 0.0F, 0.0F); + entityvillager.prepare(world.E(MathHelper.floor(entityvillager.locX), MathHelper.floor(entityvillager.locY), MathHelper.floor(entityvillager.locZ)), null); + entityvillager.setProfession(this.c(i1, entityvillager.getProfession())); + world.addEntity(entityvillager, org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.CHUNK_GEN); // CraftBukkit - add SpawnReason + } + + } + } + + protected int c(int i, int j) { + return j; + } + + protected IBlockData a(IBlockData iblockdata) { + if (this.b) { + if (iblockdata.getBlock() == Blocks.LOG || iblockdata.getBlock() == Blocks.LOG2) { + return Blocks.SANDSTONE.getBlockData(); + } + + if (iblockdata.getBlock() == Blocks.COBBLESTONE) { + return Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.DEFAULT.a()); + } + + if (iblockdata.getBlock() == Blocks.PLANKS) { + return Blocks.SANDSTONE.fromLegacyData(BlockSandStone.EnumSandstoneVariant.SMOOTH.a()); + } + + if (iblockdata.getBlock() == Blocks.OAK_STAIRS) { + return Blocks.SANDSTONE_STAIRS.getBlockData().set(BlockStairs.FACING, iblockdata.get(BlockStairs.FACING)); + } + + if (iblockdata.getBlock() == Blocks.STONE_STAIRS) { + return Blocks.SANDSTONE_STAIRS.getBlockData().set(BlockStairs.FACING, iblockdata.get(BlockStairs.FACING)); + } + + if (iblockdata.getBlock() == Blocks.GRAVEL) { + return Blocks.SANDSTONE.getBlockData(); + } + } + + return iblockdata; + } + + protected void a(World world, IBlockData iblockdata, int i, int j, int k, StructureBoundingBox structureboundingbox) { + IBlockData iblockdata1 = this.a(iblockdata); + + super.a(world, iblockdata1, i, j, k, structureboundingbox); + } + + protected void a(World world, StructureBoundingBox structureboundingbox, int i, int j, int k, int l, int i1, int j1, IBlockData iblockdata, IBlockData iblockdata1, boolean flag) { + IBlockData iblockdata2 = this.a(iblockdata); + IBlockData iblockdata3 = this.a(iblockdata1); + + super.a(world, structureboundingbox, i, j, k, l, i1, j1, iblockdata2, iblockdata3, flag); + } + + protected void b(World world, IBlockData iblockdata, int i, int j, int k, StructureBoundingBox structureboundingbox) { + IBlockData iblockdata1 = this.a(iblockdata); + + super.b(world, iblockdata1, i, j, k, structureboundingbox); + } + + protected void a(boolean flag) { + this.b = flag; + } + } + + public static class WorldGenVillagePieceWeight { + + public Class a; + public final int b; + public int c; + public int d; + + public WorldGenVillagePieceWeight(Class oclass, int i, int j) { + this.a = oclass; + this.b = i; + this.d = j; + } + + public boolean a(int i) { + return this.d == 0 || this.c < this.d; + } + + public boolean a() { + return this.d == 0 || this.c < this.d; + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenVines.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenVines.java new file mode 100644 index 0000000..256f35e --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenVines.java @@ -0,0 +1,28 @@ +package net.minecraft.server; + +import java.util.Random; + +public class WorldGenVines extends WorldGenerator { + + public WorldGenVines() { + } + + public boolean generate(World world, Random random, BlockPosition blockposition) { + for (; blockposition.getY() < 128; blockposition = blockposition.up()) { + if (world.isEmpty(blockposition)) { + for (EnumDirection enumdirection : EnumDirection.EnumDirectionLimit.HORIZONTAL.a()) { + if (Blocks.VINE.canPlace(world, blockposition, enumdirection)) { + IBlockData iblockdata = Blocks.VINE.getBlockData().set(BlockVine.NORTH, enumdirection == EnumDirection.NORTH).set(BlockVine.EAST, enumdirection == EnumDirection.EAST).set(BlockVine.SOUTH, enumdirection == EnumDirection.SOUTH).set(BlockVine.WEST, enumdirection == EnumDirection.WEST); + + world.setTypeAndData(blockposition, iblockdata, 2); + break; + } + } + } else { + blockposition = blockposition.a(random.nextInt(4) - random.nextInt(4), 0, random.nextInt(4) - random.nextInt(4)); + } + } + + return true; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenWaterLily.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenWaterLily.java new file mode 100644 index 0000000..51b3f2d --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenWaterLily.java @@ -0,0 +1,24 @@ +package net.minecraft.server; + +import java.util.Random; + +public class WorldGenWaterLily extends WorldGenerator { + + public WorldGenWaterLily() { + } + + public boolean generate(World world, Random random, BlockPosition blockposition) { + for (int i = 0; i < 10; ++i) { + int j = blockposition.getX() + random.nextInt(8) - random.nextInt(8); + int k = blockposition.getY() + random.nextInt(4) - random.nextInt(4); + int l = blockposition.getZ() + random.nextInt(8) - random.nextInt(8); + + BlockPosition position = new BlockPosition(j, k, l); + if (world.isEmpty(j, k, l) && Blocks.WATERLILY.canPlace(world, position)) { + world.setTypeAndData(position, Blocks.WATERLILY.getBlockData(), 2); + } + } + + return true; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldGenerator.java b/azurite-server/src/main/java/net/minecraft/server/WorldGenerator.java new file mode 100644 index 0000000..aaad894 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldGenerator.java @@ -0,0 +1,29 @@ +package net.minecraft.server; + +import java.util.Random; + +public abstract class WorldGenerator { + + private final boolean a; + + public WorldGenerator() { + this(false); + } + + public WorldGenerator(boolean flag) { + this.a = flag; + } + + public abstract boolean generate(World world, Random random, BlockPosition blockposition); + + public void e() { + } + + protected void a(World world, BlockPosition blockposition, IBlockData iblockdata) { + if (this.a) { + world.setTypeAndData(blockposition, iblockdata, 3); + } else { + world.setTypeAndData(blockposition, iblockdata, 2); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldLoader.java b/azurite-server/src/main/java/net/minecraft/server/WorldLoader.java new file mode 100644 index 0000000..95de8e6 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldLoader.java @@ -0,0 +1,114 @@ +package net.minecraft.server; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.io.File; +import java.nio.file.Files; +import java.util.Objects; + +public class WorldLoader implements Convertable { + + private static final Logger b = LogManager.getLogger(); + protected final File a; + + public WorldLoader(File file) { + if (!file.exists()) { + file.mkdirs(); + } + + this.a = file; + } + + public void d() { + } + + public WorldData c(String s) { + File file = new File(this.a, s); + + if (file.exists()) { + File file1 = new File(file, "level.dat"); + NBTTagCompound nbttagcompound; + NBTTagCompound nbttagcompound1; + + if (file1.exists()) { + try { + nbttagcompound = NBTCompressedStreamTools.a(Files.newInputStream(file1.toPath())); + nbttagcompound1 = nbttagcompound.getCompound("Data"); + return new WorldData(nbttagcompound1); + } catch (Exception exception) { + WorldLoader.b.error("Exception reading " + file1, exception); + } + } + + file1 = new File(file, "level.dat_old"); + if (file1.exists()) { + try { + nbttagcompound = NBTCompressedStreamTools.a(Files.newInputStream(file1.toPath())); + nbttagcompound1 = nbttagcompound.getCompound("Data"); + return new WorldData(nbttagcompound1); + } catch (Exception exception1) { + WorldLoader.b.error("Exception reading " + file1, exception1); + } + } + + } + return null; + } + + public boolean e(String s) { + File file = new File(this.a, s); + + if (!file.exists()) { + return true; + } else { + WorldLoader.b.info("Deleting level " + s); + + for (int i = 1; i <= 5; ++i) { + WorldLoader.b.info("Attempt " + i + "..."); + if (a(Objects.requireNonNull(file.listFiles()))) { + break; + } + + WorldLoader.b.warn("Unsuccessful in deleting contents."); + if (i < 5) { + try { + Thread.sleep(500L); + } catch (InterruptedException ignored) { + } + } + } + + return file.delete(); + } + } + + protected static boolean a(File[] afile) { + for (File file : afile) { + WorldLoader.b.debug("Deleting " + file); + if (file.isDirectory() && !a(Objects.requireNonNull(file.listFiles()))) { + WorldLoader.b.warn("Couldn't delete directory " + file); + return false; + } + + if (!file.delete()) { + WorldLoader.b.warn("Couldn't delete file " + file); + return false; + } + } + + return true; + } + + public IDataManager a(String s, boolean flag) { + return new WorldNBTStorage(this.a, s, flag); + } + + public boolean isConvertable(String s) { + return false; + } + + public boolean convert(String s, IProgressUpdate iprogressupdate) { + return false; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldLoaderServer.java b/azurite-server/src/main/java/net/minecraft/server/WorldLoaderServer.java new file mode 100644 index 0000000..2227f4c --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldLoaderServer.java @@ -0,0 +1,174 @@ +package net.minecraft.server; + +import com.google.common.collect.Lists; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.io.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; + +public class WorldLoaderServer extends WorldLoader { + + private static final Logger b = LogManager.getLogger(); + + public WorldLoaderServer(File file) { + super(file); + } + + protected int c() { + return 19133; + } + + public void d() { + RegionFileCache.a(); + } + + public IDataManager a(String s, boolean flag) { + return new ServerNBTManager(this.a, s, flag); + } + + public boolean isConvertable(String s) { + WorldData worlddata = this.c(s); + + return worlddata != null && worlddata.l() != this.c(); + } + + public boolean convert(String s, IProgressUpdate iprogressupdate) { + iprogressupdate.a(0); + ArrayList arraylist = Lists.newArrayList(); + ArrayList arraylist1 = Lists.newArrayList(); + ArrayList arraylist2 = Lists.newArrayList(); + File file = new File(this.a, s); + File file1 = new File(file, "DIM-1"); + File file2 = new File(file, "DIM1"); + + WorldLoaderServer.b.info("Scanning folders..."); + this.a(file, arraylist); + if (file1.exists()) { + this.a(file1, arraylist1); + } + + if (file2.exists()) { + this.a(file2, arraylist2); + } + + int i = arraylist.size() + arraylist1.size() + arraylist2.size(); + + WorldLoaderServer.b.info("Total conversion count is {}", i); + WorldData worlddata = this.c(s); + WorldChunkManager chunkManager; + + if (worlddata.getType() == WorldType.FLAT) { + chunkManager = new WorldChunkManagerHell(BiomeBase.PLAINS, 0.5F); + } else { + chunkManager = new WorldChunkManager(worlddata.getSeed(), worlddata.getType(), worlddata.getGeneratorOptions(), MinecraftServer.getServer().getWorld()); + } + + this.a(new File(file, "region"), arraylist, chunkManager, 0, i, iprogressupdate); + this.a(new File(file1, "region"),arraylist1, new WorldChunkManagerHell(BiomeBase.HELL, 0.0F), arraylist.size(), i, iprogressupdate); + this.a(new File(file2, "region"), arraylist2, new WorldChunkManagerHell(BiomeBase.SKY, 0.0F), arraylist.size() + arraylist1.size(), i, iprogressupdate); + worlddata.e(19133); + if (worlddata.getType() == WorldType.NORMAL_1_1) { + worlddata.a(WorldType.NORMAL); + } + + this.g(s); + IDataManager idatamanager = this.a(s, false); + + idatamanager.saveWorldData(worlddata); + return true; + } + + private void g(String s) { + File file = new File(this.a, s); + + if (!file.exists()) { + WorldLoaderServer.b.warn("Unable to create level.dat_mcr backup"); + } else { + File file1 = new File(file, "level.dat"); + + if (!file1.exists()) { + WorldLoaderServer.b.warn("Unable to create level.dat_mcr backup"); + } else { + File file2 = new File(file, "level.dat_mcr"); + + if (!file1.renameTo(file2)) { + WorldLoaderServer.b.warn("Unable to create level.dat_mcr backup"); + } + + } + } + } + + private void a(File file, Iterable iterable, WorldChunkManager worldchunkmanager, int i, int j, IProgressUpdate iprogressupdate) { + for (File file1 : iterable) { + this.a(file, file1, worldchunkmanager, i, j, iprogressupdate); + ++i; + int k = (int) Math.round(100.0D * (double) i / (double) j); + + iprogressupdate.a(k); + } + + } + + private void a(File file, File file1, WorldChunkManager worldchunkmanager, int i, int j, IProgressUpdate iprogressupdate) { + try { + String s = file1.getName(); + RegionFile regionfile = new RegionFile(file1); + RegionFile regionfile1 = new RegionFile(new File(file, s.substring(0, s.length() - ".mcr".length()) + ".mca")); + + for (int k = 0; k < 32; ++k) { + int l; + + for (l = 0; l < 32; ++l) { + if (regionfile.c(k, l) && !regionfile1.c(k, l)) { + DataInputStream datainputstream = regionfile.a(k, l); + + if (datainputstream == null) { + WorldLoaderServer.b.warn("Failed to fetch input stream"); + } else { + NBTTagCompound nbttagcompound = NBTCompressedStreamTools.a(datainputstream); + + datainputstream.close(); + NBTTagCompound nbttagcompound1 = nbttagcompound.getCompound("Level"); + OldChunkLoader.OldChunk oldchunkloader_oldchunk = OldChunkLoader.a(nbttagcompound1); + NBTTagCompound nbttagcompound2 = new NBTTagCompound(); + NBTTagCompound nbttagcompound3 = new NBTTagCompound(); + + nbttagcompound2.set("Level", nbttagcompound3); + OldChunkLoader.a(oldchunkloader_oldchunk, nbttagcompound3, worldchunkmanager); + DataOutputStream dataoutputstream = regionfile1.b(k, l); + + NBTCompressedStreamTools.a(nbttagcompound2, (DataOutput) dataoutputstream); + dataoutputstream.close(); + } + } + } + + l = (int) Math.round(100.0D * (double) (i * 1024) / (double) (j * 1024)); + int i1 = (int) Math.round(100.0D * (double) ((k + 1) * 32 + i * 1024) / (double) (j * 1024)); + + if (i1 > l) { + iprogressupdate.a(i1); + } + } + + regionfile.c(); + regionfile1.c(); + } catch (IOException ioexception) { + ioexception.printStackTrace(); + } + + } + + private void a(File file, Collection collection) { + File file1 = new File(file, "region"); + File[] afile = file1.listFiles((file2, s) -> s.endsWith(".mcr")); + + if (afile != null) { + Collections.addAll(collection, afile); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldManager.java b/azurite-server/src/main/java/net/minecraft/server/WorldManager.java new file mode 100644 index 0000000..9ba895f --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldManager.java @@ -0,0 +1,100 @@ +package net.minecraft.server; + +import dev.azurite.spigot.configs.AzuriteConfig; +import org.bukkit.event.world.WorldEffectEvent; + +public class WorldManager implements IWorldAccess { + + private final MinecraftServer a; + private final WorldServer world; + + public WorldManager(MinecraftServer minecraftserver, WorldServer worldserver) { + this.a = minecraftserver; + this.world = worldserver; + } + + @Override + public void a(int i, boolean flag, double d0, double d1, double d2, double d3, double d4, double d5, int... aint) { + } + + @Override + public void a(Entity entity) { + this.world.getTracker().track(entity); + } + + @Override + public void b(Entity entity) { + boolean tnt = entity instanceof EntityTNTPrimed, sand = entity instanceof EntityFallingBlock; + if (!((AzuriteConfig.hideTntEntity.getValue() && tnt) || (AzuriteConfig.hideSandEntity.getValue() && sand))) + world.getTracker().untrackEntity(entity); + if (!tnt && !sand) + world.getScoreboard().a(entity); + } + + @Override + public void a(String s, double d0, double d1, double d2, float f, float f1) { + this.world.playerMap.sendPacketNearby(null, d0, d1, d2, (f > 1.0F) ? (16.0F * f) : 16.0D, new PacketPlayOutNamedSoundEffect(s, d0, d1, d2, f, f1)); + } + + // Beanes - add self variable + @Override + public void a(String s, double d0, double d1, double d2, float f, float f1, boolean self) { + this.world.playerMap.sendPacketNearby(null, d0, d1, d2, (f > 1.0F) ? (16.0F * f) : 16.0D, new PacketPlayOutNamedSoundEffect(s, d0, d1, d2, f, f1), self); + } + + @Override + public void a(EntityHuman entityhuman, String s, double d0, double d1, double d2, float f, float f1) { + this.world.playerMap.sendPacketNearby((EntityPlayer) entityhuman, d0, d1, d2, f > 1.0F ? (double) (16.0F * f) : 16.0D, new PacketPlayOutNamedSoundEffect(s, d0, d1, d2, f, f1)); + } + + @Override + public void a(EntityHuman entityhuman, String s, double d0, double d1, double d2, float f, float f1, boolean self) { + this.world.playerMap.sendPacketNearby((EntityPlayer) entityhuman, d0, d1, d2, f > 1.0F ? (double) (16.0F * f) : 16.0D, new PacketPlayOutNamedSoundEffect(s, d0, d1, d2, f, f1), self); + } + + @Override + public void a(int i, int j, int k, int l, int i1, int j1) { + } + + @Override + public void a(int x, int y, int z) { + this.world.getPlayerChunkMap().flagDirty(x, y, z); + } + + @Override + public void a(BlockPosition blockposition) { + this.world.getPlayerChunkMap().flagDirty(blockposition); + } + + @Override + public void b(BlockPosition blockposition) { + } + + @Override + public void a(String s, BlockPosition blockposition) { + } + + @Override + public void a(EntityHuman entityhuman, int i, BlockPosition blockposition, int j) { + if (WorldEffectEvent.getHandlerList().getRegisteredListeners().length > 0) { + new WorldEffectEvent(this.world.getWorld(), i, blockposition.getX(), blockposition.getY(), blockposition.getZ(), j, false).callEvent(); + } + this.world.playerMap.sendPacketNearby((EntityPlayer) entityhuman, blockposition.getX(), blockposition.getY(), blockposition.getZ(), 64.0D, new PacketPlayOutWorldEvent(i, blockposition, j, false)); + } + + @Override + public void a(int i, BlockPosition blockposition, int j) { + if (WorldEffectEvent.getHandlerList().getRegisteredListeners().length > 0) { + new WorldEffectEvent(this.world.getWorld(), i, blockposition.getX(), blockposition.getY(), blockposition.getZ(), j, true).callEvent(); + } + + this.a.getPlayerList().sendAll(new PacketPlayOutWorldEvent(i, blockposition, j, true)); + } + + @Override + public void b(int i, BlockPosition blockposition, int j) { + Entity entity = this.world.a(i); + EntityPlayer player = entity instanceof EntityPlayer ? (EntityPlayer) entity : null; + this.world.playerMap.sendPacketNearby(player, blockposition.getX(), blockposition.getY(), blockposition.getZ(), 32.0D, new PacketPlayOutBlockBreakAnimation(i, blockposition, j)); + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldMap.java b/azurite-server/src/main/java/net/minecraft/server/WorldMap.java new file mode 100644 index 0000000..7c74e22 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldMap.java @@ -0,0 +1,307 @@ +package net.minecraft.server; + +import com.google.common.base.Charsets; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.CraftWorld; +import org.bukkit.craftbukkit.map.CraftMapView; + +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.WeakHashMap; + +public class WorldMap extends PersistentBase { + + public int centerX; + public int centerZ; + public byte map; + public byte scale; + public byte[] colors = new byte[16384]; + public List g = Lists.newArrayList(); + public Map i = new WeakHashMap<>(); // Vortex + public Map decorations = Maps.newLinkedHashMap(); // Spigot + + // CraftBukkit start + public final CraftMapView mapView; + private final CraftServer server; + private UUID uniqueId = null; + // CraftBukkit end + + public WorldMap(String s) { + super(s); + // CraftBukkit start + mapView = new CraftMapView(this); + server = (CraftServer) org.bukkit.Bukkit.getServer(); + // CraftBukkit end + } + + public void a(double d0, double d1, int i) { + int j = 128 * (1 << i); + int k = MathHelper.floor((d0 + 64.0D) / (double) j); + int l = MathHelper.floor((d1 + 64.0D) / (double) j); + + this.centerX = k * j + j / 2 - 64; + this.centerZ = l * j + j / 2 - 64; + } + + public void a(NBTTagCompound nbttagcompound) { + // CraftBukkit start + byte dimension = nbttagcompound.getByte("dimension"); + + if (dimension >= 10) { + long least = nbttagcompound.getLong("UUIDLeast"); + long most = nbttagcompound.getLong("UUIDMost"); + + if (least != 0L && most != 0L) { + this.uniqueId = new UUID(most, least); + + CraftWorld world = (CraftWorld) server.getWorld(this.uniqueId); + // Check if the stored world details are correct. + if (world == null) { + /* All Maps which do not have their valid world loaded are set to a dimension which hopefully won't be reached. + This is to prevent them being corrupted with the wrong map data. */ + dimension = 127; + } else { + dimension = (byte) world.getHandle().dimension; + } + } + } + + this.map = dimension; + // CraftBukkit end + this.centerX = nbttagcompound.getInt("xCenter"); + this.centerZ = nbttagcompound.getInt("zCenter"); + this.scale = nbttagcompound.getByte("scale"); + this.scale = (byte) MathHelper.clamp(this.scale, 0, 4); + short short0 = nbttagcompound.getShort("width"); + short short1 = nbttagcompound.getShort("height"); + + if (short0 == 128 && short1 == 128) { + this.colors = nbttagcompound.getByteArray("colors"); + } else { + byte[] abyte = nbttagcompound.getByteArray("colors"); + + this.colors = new byte[16384]; + int i = (128 - short0) / 2; + int j = (128 - short1) / 2; + + for (int k = 0; k < short1; ++k) { + int l = k + j; + + for (int i1 = 0; i1 < short0; ++i1) { + int j1 = i1 + i; + + this.colors[j1 + l * 128] = abyte[i1 + k * short0]; + } + } + } + + } + + public void b(NBTTagCompound nbttagcompound) { + // CraftBukkit start + if (this.map >= 10) { + if (this.uniqueId == null) { + for (org.bukkit.World world : server.getWorlds()) { + CraftWorld cWorld = (CraftWorld) world; + if (cWorld.getHandle().dimension == this.map) { + this.uniqueId = cWorld.getUID(); + break; + } + } + } + /* Perform a second check to see if a matching world was found, this is a necessary + change incase Maps are forcefully unlinked from a World and lack a UID.*/ + if (this.uniqueId != null) { + nbttagcompound.setLong("UUIDLeast", this.uniqueId.getLeastSignificantBits()); + nbttagcompound.setLong("UUIDMost", this.uniqueId.getMostSignificantBits()); + } + } + // CraftBukkit end + nbttagcompound.setByte("dimension", this.map); + nbttagcompound.setInt("xCenter", this.centerX); + nbttagcompound.setInt("zCenter", this.centerZ); + nbttagcompound.setByte("scale", this.scale); + nbttagcompound.setShort("width", (short) 128); + nbttagcompound.setShort("height", (short) 128); + nbttagcompound.setByteArray("colors", this.colors); + } + + public void a(EntityHuman entityhuman, ItemStack itemstack) { + if (!this.i.containsKey(entityhuman)) { + WorldMapHumanTracker worldmap_worldmaphumantracker = new WorldMapHumanTracker(entityhuman); + + this.i.put(entityhuman, worldmap_worldmaphumantracker); + this.g.add(worldmap_worldmaphumantracker); + } + + if (!entityhuman.inventory.c(itemstack)) { + this.decorations.remove(entityhuman.getUniqueID()); // Spigot + } + + for (int i = 0; i < this.g.size(); ++i) { + WorldMapHumanTracker worldmap_worldmaphumantracker1 = this.g.get(i); + + if (!worldmap_worldmaphumantracker1.trackee.dead && (worldmap_worldmaphumantracker1.trackee.inventory.c(itemstack) || itemstack.y())) { + if (!itemstack.y() && worldmap_worldmaphumantracker1.trackee.dimension == this.map) { + this.a(0, worldmap_worldmaphumantracker1.trackee.world, worldmap_worldmaphumantracker1.trackee.getUniqueID(), worldmap_worldmaphumantracker1.trackee.locX, worldmap_worldmaphumantracker1.trackee.locZ, worldmap_worldmaphumantracker1.trackee.yaw); // Spigot + } + } else { + this.i.remove(worldmap_worldmaphumantracker1.trackee); + this.g.remove(worldmap_worldmaphumantracker1); + } + } + + if (itemstack.y()) { + EntityItemFrame entityitemframe = itemstack.z(); + BlockPosition blockposition = entityitemframe.getBlockPosition(); + + this.a(1, entityhuman.world, UUID.nameUUIDFromBytes(("frame-" + entityitemframe.getId()).getBytes(Charsets.US_ASCII)), blockposition.getX(), blockposition.getZ(), entityitemframe.direction.b() * 90); // Spigot + } + + if (itemstack.hasTag() && itemstack.getTag().hasKeyOfType("Decorations", 9)) { + NBTTagList nbttaglist = itemstack.getTag().getList("Decorations", 10); + + for (int j = 0; j < nbttaglist.size(); ++j) { + NBTTagCompound nbttagcompound = nbttaglist.get(j); + + // Spigot - start + UUID uuid = UUID.nameUUIDFromBytes(nbttagcompound.getString("id").getBytes(Charsets.US_ASCII)); + if (!this.decorations.containsKey(uuid)) { + this.a(nbttagcompound.getByte("type"), entityhuman.world, uuid, nbttagcompound.getDouble("x"), nbttagcompound.getDouble("z"), nbttagcompound.getDouble("rot")); + // Spigot - end + } + } + } + + } + + private void a(int i, World world, UUID s, double d0, double d1, double d2) { + int j = 1 << this.scale; + float f = (float) (d0 - (double) this.centerX) / (float) j; + float f1 = (float) (d1 - (double) this.centerZ) / (float) j; + byte b0 = (byte) ((int) ((double) (f * 2.0F) + 0.5D)); + byte b1 = (byte) ((int) ((double) (f1 * 2.0F) + 0.5D)); + byte b2 = 63; + byte b3; + + if (f >= (float) (-b2) && f1 >= (float) (-b2) && f <= (float) b2 && f1 <= (float) b2) { + d2 += d2 < 0.0D ? -8.0D : 8.0D; + b3 = (byte) ((int) (d2 * 16.0D / 360.0D)); + if (this.map < 0) { + int k = (int) (world.getWorldData().getDayTime() / 10L); + + b3 = (byte) (k * k * 34187121 + k * 121 >> 15 & 15); + } + } else { + if (Math.abs(f) >= 320.0F || Math.abs(f1) >= 320.0F) { + this.decorations.remove(s); + return; + } + + i = 6; + b3 = 0; + if (f <= (float) (-b2)) { + b0 = (byte) ((int) ((double) (b2 * 2) + 2.5D)); + } + + if (f1 <= (float) (-b2)) { + b1 = (byte) ((int) ((double) (b2 * 2) + 2.5D)); + } + + if (f >= (float) b2) { + b0 = (byte) (b2 * 2 + 1); + } + + if (f1 >= (float) b2) { + b1 = (byte) (b2 * 2 + 1); + } + } + + this.decorations.put(s, new MapIcon((byte) i, b0, b1, b3)); + } + + public Packet a(ItemStack itemstack, World world, EntityHuman entityhuman) { + WorldMapHumanTracker worldmap_worldmaphumantracker = this.i.get(entityhuman); + + return worldmap_worldmaphumantracker == null ? null : worldmap_worldmaphumantracker.a(itemstack); + } + + public void flagDirty(int i, int j) { + super.c(); + + for (WorldMapHumanTracker worldMapHumanTracker : this.g) { + worldMapHumanTracker.a(i, j); + } + + } + + public WorldMapHumanTracker a(EntityHuman entityhuman) { + WorldMapHumanTracker worldmap_worldmaphumantracker = this.i.get(entityhuman); + + if (worldmap_worldmaphumantracker == null) { + worldmap_worldmaphumantracker = new WorldMapHumanTracker(entityhuman); + this.i.put(entityhuman, worldmap_worldmaphumantracker); + this.g.add(worldmap_worldmaphumantracker); + } + + return worldmap_worldmaphumantracker; + } + + public class WorldMapHumanTracker { + + public final EntityHuman trackee; + private boolean d = true; + private int e = 0; + private int f = 0; + private int g = 127; + private int h = 127; + private int i; + public int b; + + public WorldMapHumanTracker(EntityHuman entityhuman) { + this.trackee = entityhuman; + } + + public Packet a(ItemStack itemstack) { + // CraftBukkit start + org.bukkit.craftbukkit.map.RenderData render = WorldMap.this.mapView.render((org.bukkit.craftbukkit.entity.CraftPlayer) this.trackee.getBukkitEntity()); // CraftBukkit + + java.util.Collection icons = new java.util.ArrayList<>(); + + for ( org.bukkit.map.MapCursor cursor : render.cursors) { + + if (cursor.isVisible()) { + icons.add(new MapIcon(cursor.getRawType(), cursor.getX(), cursor.getY(), cursor.getDirection())); + } + } + + if (this.d) { + this.d = false; + return new PacketPlayOutMap(itemstack.getData(), WorldMap.this.scale, icons, render.buffer, this.e, this.f, this.g + 1 - this.e, this.h + 1 - this.f); + } else { + return this.i++ % 5 == 0 ? new PacketPlayOutMap(itemstack.getData(), WorldMap.this.scale, icons, render.buffer, 0, 0, 0, 0) : null; + } + // CraftBukkit end + } + + public void a(int i, int j) { + if (this.d) { + this.e = Math.min(this.e, i); + this.f = Math.min(this.f, j); + this.g = Math.max(this.g, i); + this.h = Math.max(this.h, j); + } else { + this.d = true; + this.e = i; + this.f = j; + this.g = i; + this.h = j; + } + + } + } + +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldNBTStorage.java b/azurite-server/src/main/java/net/minecraft/server/WorldNBTStorage.java new file mode 100644 index 0000000..92c13a9 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldNBTStorage.java @@ -0,0 +1,285 @@ +package net.minecraft.server; + +import com.eatthepath.uuid.FastUUID; +import dev.azurite.spigot.Azurite; +import dev.azurite.spigot.async.tasks.PlayerDataSaveJob; +import dev.azurite.spigot.async.tasks.WorldDataSaveJob; +import dev.azurite.spigot.configs.AzuriteConfig; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.bukkit.craftbukkit.entity.CraftPlayer; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.UUID; + +public class WorldNBTStorage implements IDataManager, IPlayerFileData { + + private static final Logger a = LogManager.getLogger(); + private final File baseDir; + private final File playerDir; + private final File dataDir; + private final long sessionId = MinecraftServer.az(); + private final String f; + private UUID uuid = null; // CraftBukkit + + public WorldNBTStorage(File file, String s, boolean flag) { + this.baseDir = new File(file, s); + this.baseDir.mkdirs(); + this.playerDir = new File(this.baseDir, "playerdata"); + this.dataDir = new File(this.baseDir, "data"); + this.dataDir.mkdirs(); + this.f = s; + + if (flag) { + this.playerDir.mkdirs(); + } + + this.h(); + } + + private void h() { + try { + File file = new File(this.baseDir, "session.lock"); + + try (DataOutputStream dataoutputstream = new DataOutputStream(Files.newOutputStream(file.toPath()))) { + dataoutputstream.writeLong(this.sessionId); + } + + } catch (IOException ioexception) { + ioexception.printStackTrace(); + throw new RuntimeException("Failed to check session lock for world located at " + this.baseDir + ", aborting. Stop the server and delete the session.lock in this world to prevent further issues."); // Spigot + } + } + + public File getDirectory() { + return this.baseDir; + } + + public void checkSession() throws ExceptionWorldConflict { + try { + File file = new File(baseDir, "session.lock"); + + try (DataInputStream datainputstream = new DataInputStream(Files.newInputStream(file.toPath()))) { + if (datainputstream.readLong() != sessionId) { + throw new ExceptionWorldConflict("The save for world located at " + baseDir + " is being accessed from another location, aborting"); // Spigot + } + } + + } catch (IOException ioexception) { + throw new ExceptionWorldConflict("Failed to check session lock for world located at " + baseDir + ", aborting. Stop the server and delete the session.lock in this world to prevent further issues."); // Spigot + } + } + + public IChunkLoader createChunkLoader(WorldProvider worldprovider) { + throw new RuntimeException("Old Chunk Storage is no longer supported."); + } + + public WorldData getWorldData() { + File file = new File(this.baseDir, "level.dat"); + NBTTagCompound nbttagcompound; + NBTTagCompound nbttagcompound1; + + if (file.exists()) { + try { + nbttagcompound = NBTCompressedStreamTools.a(Files.newInputStream(file.toPath())); + nbttagcompound1 = nbttagcompound.getCompound("Data"); + return new WorldData(nbttagcompound1); + } catch (Exception exception) { + exception.printStackTrace(); + } + } + + file = new File(this.baseDir, "level.dat_old"); + if (file.exists()) { + try { + nbttagcompound = NBTCompressedStreamTools.a(Files.newInputStream(file.toPath())); + nbttagcompound1 = nbttagcompound.getCompound("Data"); + return new WorldData(nbttagcompound1); + } catch (Exception exception1) { + exception1.printStackTrace(); + } + } + + return null; + } + + public void saveWorldData(WorldData worlddata) { + this.saveWorldData(worlddata, new NBTTagCompound()); + } + + public void saveWorldData(WorldData worlddata, NBTTagCompound nbttagcompound) { + if (AzuriteConfig.asyncWorldDataSave.getValue()) { + Azurite.getInstance().getThreadingManager().getAsyncExecutor().queueFileTask(new WorldDataSaveJob(worlddata, nbttagcompound, baseDir)); + return; + } + new WorldDataSaveJob(worlddata, nbttagcompound, baseDir).run(); + } + + private final PlayerCache dataCache = new PlayerCache<>(); + + public void save(EntityHuman entityhuman) { + if (AzuriteConfig.savePlayerData.getValue()) { + try { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + + entityhuman.e(nbttagcompound); + + File file1 = new File(this.playerDir, FastUUID.toString(entityhuman.getUniqueID()) + ".dat"); + synchronized (this.dataCache) { + this.dataCache.put(file1, nbttagcompound); + } + this.saveData(file1, nbttagcompound); + } catch (Exception exception) { + WorldNBTStorage.a.warn("Failed to save player data for {}", entityhuman.getName()); + } + } + } + + private void saveData(File file, NBTTagCompound compound) { + if (AzuriteConfig.asyncPlayerDataSave.getValue()) { + Azurite.getInstance().getThreadingManager().getAsyncExecutor().queueFileTask(new PlayerDataSaveJob(file, compound)); + return; + } + new PlayerDataSaveJob(file, compound).run(); + } + + public NBTTagCompound load(EntityHuman entityhuman) { + NBTTagCompound nbttagcompound = null; + + try { + File file = new File(this.playerDir, FastUUID.toString(entityhuman.getUniqueID()) + ".dat"); + // Spigot Start + boolean usingWrongFile = false; + boolean normalFile = file.isFile(); // Vortex - Remove file.exists + + NBTTagCompound playerdata; + synchronized (this.dataCache) { + playerdata = this.dataCache.get(file); + } + + if (org.bukkit.Bukkit.getOnlineMode() && !normalFile && playerdata == null) // Paper - Check online mode first // Akarin - ensures normal file + { + file = new File(this.playerDir, FastUUID.toString(UUID.nameUUIDFromBytes(("OfflinePlayer:" + entityhuman.getName()).getBytes(StandardCharsets.UTF_8))) + ".dat"); + synchronized (this.dataCache) { + playerdata = this.dataCache.get(file); + } + if (file.exists()) { + usingWrongFile = true; + org.bukkit.Bukkit.getServer().getLogger().warning("Using offline mode UUID file for player " + entityhuman.getName() + " as it is the only copy we can find."); + } + } + // Spigot End + + if (playerdata != null) { + nbttagcompound = playerdata; + } else if (normalFile) { + nbttagcompound = NBTCompressedStreamTools.a(Files.newInputStream(file.toPath())); + } + // Spigot Start + if (usingWrongFile) { + file.renameTo(new File(file.getPath() + ".offline-read")); + } + + + } catch (Exception exception) { + WorldNBTStorage.a.warn("Failed to load player data for " + entityhuman.getName()); + } + + if (nbttagcompound != null) { + // CraftBukkit start + if (entityhuman instanceof EntityPlayer) { + CraftPlayer player = (CraftPlayer) entityhuman.getBukkitEntity(); + // Only update first played if it is older than the one we have + long modified = new File(this.playerDir, FastUUID.toString(entityhuman.getUniqueID()) + ".dat").lastModified(); + if (modified < player.getFirstPlayed()) { + player.setFirstPlayed(modified); + } + } + // CraftBukkit end + + entityhuman.f(nbttagcompound); + } + + return nbttagcompound; + } + + // CraftBukkit start + public NBTTagCompound getPlayerData(String s) { + try { + File file1 = new File(this.playerDir, s + ".dat"); + + if (file1.exists()) { + return NBTCompressedStreamTools.a(Files.newInputStream(file1.toPath())); + } + } catch (Exception exception) { + a.warn("Failed to load player data for " + s); + } + + return null; + } + // CraftBukkit end + + public IPlayerFileData getPlayerFileData() { + return this; + } + + public String[] getSeenPlayers() { + String[] astring = this.playerDir.list(); + + if (astring == null) { + astring = new String[0]; + } + + for (int i = 0; i < astring.length; ++i) { + if (astring[i].endsWith(".dat")) { + astring[i] = astring[i].substring(0, astring[i].length() - 4); + } + } + + return astring; + } + + public void a() { + } + + public File getDataFile(String s) { + return new File(this.dataDir, s + ".dat"); + } + + public String g() { + return this.f; + } + + // CraftBukkit start + public UUID getUUID() { + if (uuid != null) return uuid; + File file1 = new File(this.baseDir, "uid.dat"); + if (file1.exists()) { + try (DataInputStream dis = new DataInputStream(Files.newInputStream(file1.toPath()))) { + return uuid = new UUID(dis.readLong(), dis.readLong()); + } catch (IOException ex) { + a.warn("Failed to read {}, generating new random UUID", file1, ex); + } + // NOOP + } + uuid = UUID.randomUUID(); + try (DataOutputStream dos = new DataOutputStream(Files.newOutputStream(file1.toPath()))) { + dos.writeLong(uuid.getMostSignificantBits()); + dos.writeLong(uuid.getLeastSignificantBits()); + } catch (IOException ex) { + a.warn("Failed to write {}", file1, ex); + } + // NOOP + return uuid; + } + + public File getPlayerDir() { + return playerDir; + } + // CraftBukkit end +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldProvider.java b/azurite-server/src/main/java/net/minecraft/server/WorldProvider.java new file mode 100644 index 0000000..ac945b6 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldProvider.java @@ -0,0 +1,143 @@ +package net.minecraft.server; + +import dev.azurite.spigot.utils.ChunkProviderVoid; +import dev.azurite.spigot.utils.VoidChunkGenerator; + +public abstract class WorldProvider { + + public static final float[] a = {1.0F, 0.75F, 0.5F, 0.25F, 0.0F, 0.25F, 0.5F, 0.75F}; + protected World b; + private WorldType type; + private String i; + protected WorldChunkManager c; + protected boolean d; + protected boolean e; + protected final float[] f = new float[16]; + protected int dimension; + + public WorldProvider() { + } + + public final void a(World world) { + this.b = world; + this.type = world.getWorldData().getType(); + this.i = world.getWorldData().getGeneratorOptions(); + this.b(); + this.a(); + } + + protected void a() { + float f = 0.0F; + + for (int i = 0; i <= 15; ++i) { + float f1 = 1.0F - (float) i / 15.0F; + + this.f[i] = (1.0F - f1) / (f1 * 3.0F + 1.0F) * (1.0F - f) + f; + } + + } + + protected void b() { + WorldType worldtype = this.b.getWorldData().getType(); + + if (worldtype == WorldType.FLAT) { + WorldGenFlatInfo worldgenflatinfo = WorldGenFlatInfo.a(this.b.getWorldData().getGeneratorOptions()); + + this.c = new WorldChunkManagerHell(BiomeBase.getBiome(worldgenflatinfo.a(), BiomeBase.ad), 0.5F); + } else if (worldtype == WorldType.DEBUG_ALL_BLOCK_STATES) { + this.c = new WorldChunkManagerHell(BiomeBase.PLAINS, 0.0F); + } else { + this.c = new WorldChunkManager(this.b); + } + + } + + public IChunkProvider getChunkProvider() { + if (this.type == WorldType.VOID) { + return new ChunkProviderVoid(this.b); + } + + if (this.type == WorldType.FLAT) { + return new ChunkProviderFlat(this.b, this.b.getSeed(), this.b.getWorldData().shouldGenerateMapFeatures(), this.i); + } + if (this.type == WorldType.DEBUG_ALL_BLOCK_STATES) { + return new ChunkProviderDebug(this.b); + } + return new ChunkProviderGenerate(this.b, this.b.getSeed(), this.b.getWorldData().shouldGenerateMapFeatures(), this.i); + } + + public boolean canSpawn(int i, int j) { + return this.b.c1(i, j) == Blocks.GRASS; + } + + public float a(long i, float f) { + int j = (int) (i % 24000L); + float f1 = ((float) j + f) / 24000.0F - 0.25F; + + if (f1 < 0.0F) { + ++f1; + } + + if (f1 > 1.0F) { + --f1; + } + + float f2 = f1; + + f1 = 1.0F - (float) ((Math.cos((double) f1 * 3.141592653589793D) + 1.0D) / 2.0D); + f1 = f2 + (f1 - f2) / 3.0F; + return f1; + } + + public int a(long i) { + return (int) (i / 24000L % 8L + 8L) % 8; + } + + public boolean d() { + return true; + } + + public boolean e() { + return true; + } + + public static WorldProvider byDimension(int i) { + return i == -1 ? new WorldProviderHell() : (i == 0 ? new WorldProviderNormal() : (i == 1 ? new WorldProviderTheEnd() : null)); + } + + public BlockPosition h() { + return null; + } + + public int getSeaLevel() { + return this.type == WorldType.FLAT ? 4 : this.b.F() + 1; + } + + public abstract String getName(); + + public abstract String getSuffix(); + + public WorldChunkManager m() { + return this.c; + } + + public boolean n() { + return this.d; + } + + public boolean o() { + return this.e; + } + + public float[] p() { + return this.f; + } + + public int getDimension() { + return this.dimension; + } + + public WorldBorder getWorldBorder() { + return new WorldBorder(); + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldProviderHell.java b/azurite-server/src/main/java/net/minecraft/server/WorldProviderHell.java new file mode 100644 index 0000000..1145ed2 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldProviderHell.java @@ -0,0 +1,64 @@ +package net.minecraft.server; + +public class WorldProviderHell extends WorldProvider { + + public WorldProviderHell() {} + + public void b() { + this.c = new WorldChunkManagerHell(BiomeBase.HELL, 0.0F); + this.d = true; + this.e = true; + this.dimension = -1; + } + + protected void a() { + float f = 0.1F; + + for (int i = 0; i <= 15; ++i) { + float f1 = 1.0F - (float) i / 15.0F; + + this.f[i] = (1.0F - f1) / (f1 * 3.0F + 1.0F) * (1.0F - f) + f; + } + + } + + public IChunkProvider getChunkProvider() { + return new ChunkProviderHell(this.b, this.b.getWorldData().shouldGenerateMapFeatures(), this.b.getSeed()); + } + + public boolean d() { + return false; + } + + public boolean canSpawn(int i, int j) { + return false; + } + + public float a(long i, float f) { + return 0.5F; + } + + public boolean e() { + return false; + } + + public String getName() { + return "Nether"; + } + + public String getSuffix() { + return "_nether"; + } + + public WorldBorder getWorldBorder() { + return new WorldBorder() { + public double getCenterX() { + return super.getCenterX() / 8.0D; + } + + public double getCenterZ() { + return super.getCenterZ() / 8.0D; + } + }; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldProviderNormal.java b/azurite-server/src/main/java/net/minecraft/server/WorldProviderNormal.java new file mode 100644 index 0000000..2bf28f2 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldProviderNormal.java @@ -0,0 +1,14 @@ +package net.minecraft.server; + +public class WorldProviderNormal extends WorldProvider { + + public WorldProviderNormal() {} + + public String getName() { + return "Overworld"; + } + + public String getSuffix() { + return ""; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldProviderTheEnd.java b/azurite-server/src/main/java/net/minecraft/server/WorldProviderTheEnd.java new file mode 100644 index 0000000..17b3e13 --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldProviderTheEnd.java @@ -0,0 +1,48 @@ +package net.minecraft.server; + +public class WorldProviderTheEnd extends WorldProvider { + + public WorldProviderTheEnd() {} + + public void b() { + this.c = new WorldChunkManagerHell(BiomeBase.SKY, 0.0F); + this.dimension = 1; + this.e = true; + } + + public IChunkProvider getChunkProvider() { + return new ChunkProviderTheEnd(this.b, this.b.getSeed()); + } + + public float a(long i, float f) { + return 0.0F; + } + + public boolean e() { + return false; + } + + public boolean d() { + return false; + } + + public boolean canSpawn(int i, int j) { + return this.b.c(new BlockPosition(i, 0, j)).getMaterial().isSolid(); + } + + public BlockPosition h() { + return new BlockPosition(100, 50, 0); + } + + public int getSeaLevel() { + return 50; + } + + public String getName() { + return "The End"; + } + + public String getSuffix() { + return "_end"; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldServer.java b/azurite-server/src/main/java/net/minecraft/server/WorldServer.java new file mode 100644 index 0000000..91bd4fc --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldServer.java @@ -0,0 +1,1056 @@ +package net.minecraft.server; + +import com.google.common.base.Predicate; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import com.google.common.util.concurrent.ListenableFuture; +import dev.azurite.spigot.configs.AzuriteConfig; +import dev.azurite.spigot.utils.ChunkProviderVoid; +import dev.azurite.spigot.utils.Utils; +import dev.azurite.spigot.utils.VoidChunkGenerator; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.bukkit.Location; +import org.bukkit.WeatherType; +import org.bukkit.block.BlockState; +import org.bukkit.craftbukkit.util.HashTreeSet; +import org.bukkit.event.block.BlockFormEvent; +import org.bukkit.event.weather.LightningStrikeEvent; + +import java.util.*; +import java.util.logging.Level; + +public class WorldServer extends World implements IAsyncTaskHandler { + + private static final Logger a = LogManager.getLogger(); + private static final List U = Lists.newArrayList(new StructurePieceTreasure(Items.STICK, 0, 1, 3, 10), new StructurePieceTreasure(Item.getItemOf(Blocks.PLANKS), 0, 1, 3, 10), new StructurePieceTreasure(Item.getItemOf(Blocks.LOG), 0, 1, 3, 10), new StructurePieceTreasure(Items.STONE_AXE, 0, 1, 1, 3), new StructurePieceTreasure(Items.WOODEN_AXE, 0, 1, 1, 5), new StructurePieceTreasure(Items.STONE_PICKAXE, 0, 1, 1, 3), new StructurePieceTreasure(Items.WOODEN_PICKAXE, 0, 1, 1, 5), new StructurePieceTreasure(Items.APPLE, 0, 2, 3, 5), new StructurePieceTreasure(Items.BREAD, 0, 2, 3, 3), new StructurePieceTreasure(Item.getItemOf(Blocks.LOG2), 0, 1, 3, 10)); + // CraftBukkit start + public final int dimension; + protected final VillageSiege siegeManager = new VillageSiege(this); + private final MinecraftServer server; + private final PlayerChunkMap manager; + private final HashTreeSet M = new HashTreeSet<>(); // CraftBukkit - HashTreeSet + private final Map entitiesByUUID = Maps.newHashMap(); + private final PortalTravelAgent Q; + private final SpawnerCreature R = new SpawnerCreature(); + private final BlockActionDataList[] S = new BlockActionDataList[]{new BlockActionDataList(null), new BlockActionDataList(null)}; + private final List V = Lists.newArrayList(); + public EntityTracker tracker; + public ChunkProviderServer chunkProviderServer; + public boolean savingDisabled; + private boolean O; + private int T; + + // Vortex - obf helper + public WorldServer(MinecraftServer minecraftserver, IDataManager idatamanager, WorldData worlddata, int i, MethodProfiler methodprofiler) { + this(minecraftserver, idatamanager, null, i, methodprofiler, null, null, false); + } + // Vortex end + + public WorldServer(MinecraftServer minecraftserver, IDataManager idatamanager, WorldData worlddata, int i, MethodProfiler methodprofiler, org.bukkit.World.Environment env, org.bukkit.generator.ChunkGenerator gen) { + this(minecraftserver, idatamanager, worlddata, i, methodprofiler, env, gen, false); + } + + // Add env and gen to constructor + public WorldServer(MinecraftServer minecraftserver, IDataManager idatamanager, WorldData worlddata, int i, MethodProfiler methodprofiler, org.bukkit.World.Environment env, org.bukkit.generator.ChunkGenerator gen, boolean shouldGenerateConfig) { + super(idatamanager, worlddata, WorldProvider.byDimension(env.getId()), methodprofiler, false, gen, env, shouldGenerateConfig); + this.dimension = i; + this.pvpMode = minecraftserver.getPVP(); + worlddata.world = this; + this.server = minecraftserver; + this.tracker = new EntityTracker(this); + this.manager = new PlayerChunkMap(this, spigotConfig.viewDistance); // Spigot + this.worldProvider.a(this); + this.chunkProvider = this.k(); + this.Q = ((org.bukkit.craftbukkit.CraftTravelAgent) new org.bukkit.craftbukkit.CraftTravelAgent(this).setSearchRadius(paperSpigotConfig.portalSearchRadius)); // CraftBukkit // Paper - configurable search radius + this.B(); + this.C(); + this.getWorldBorder().a(minecraftserver.aI()); + } + + public World b() { + this.worldMaps = new PersistentCollection(this.dataManager); + String s = PersistentVillage.a(this.worldProvider); + PersistentVillage persistentvillage = (PersistentVillage) this.worldMaps.get(PersistentVillage.class, s); + + if (persistentvillage == null) { + this.villages = new PersistentVillage(this); + this.worldMaps.a(s, this.villages); + } else { + this.villages = persistentvillage; + this.villages.a(this); + } + + if (getServer().getScoreboardManager() == null) { // CraftBukkit + this.scoreboard = new ScoreboardServer(this.server); + PersistentScoreboard persistentscoreboard = (PersistentScoreboard) this.worldMaps.get(PersistentScoreboard.class, "scoreboard"); + + if (persistentscoreboard == null) { + persistentscoreboard = new PersistentScoreboard(); + this.worldMaps.a("scoreboard", persistentscoreboard); + } + + persistentscoreboard.a(this.scoreboard); + ((ScoreboardServer) this.scoreboard).a(persistentscoreboard); + // CraftBukkit start + } else { + this.scoreboard = getServer().getScoreboardManager().getMainScoreboard().getHandle(); + } + // CraftBukkit end + this.getWorldBorder().setCenter(this.worldData.C(), this.worldData.D()); + this.getWorldBorder().setDamageAmount(this.worldData.I()); + this.getWorldBorder().setDamageBuffer(this.worldData.H()); + this.getWorldBorder().setWarningDistance(this.worldData.J()); + this.getWorldBorder().setWarningTime(this.worldData.K()); + if (this.worldData.F() > 0L) { + this.getWorldBorder().transitionSizeBetween(this.worldData.E(), this.worldData.G(), this.worldData.F()); + } else { + this.getWorldBorder().setSize(this.worldData.E()); + } + + // CraftBukkit start + if (generator != null) { + getWorld().getPopulators().addAll(generator.getDefaultPopulators(getWorld())); + } + // CraftBukkit end + + return this; + } + + // CraftBukkit start + @Override + public TileEntity getTileEntity(BlockPosition pos) { + return getTileEntity(null, pos, getType(pos).getBlock()); + } + + @Override + public TileEntity getTileEntity(Chunk chunk, BlockPosition pos) { + return getTileEntity(chunk, pos, getType(pos).getBlock()); + } + + @Override + public TileEntity getTileEntity(Chunk chunk, BlockPosition pos, Block type) { // Lags with getCubes for pistons having to push sand + TileEntity result = super.getTileEntity(chunk, pos); + if (result instanceof TileEntityPiston) { + return result; + } + if (type == Blocks.CHEST || type == Blocks.TRAPPED_CHEST) { // Spigot + if (!(result instanceof TileEntityChest)) { + result = fixTileEntity(pos, type, result); + } + } else if (type == Blocks.HOPPER) { // Moved Hoppers from bottom to top b/c they're so common + if (!(result instanceof TileEntityHopper)) { + result = fixTileEntity(pos, type, result); + } + } else if (type == Blocks.FURNACE) { + if (!(result instanceof TileEntityFurnace)) { + result = fixTileEntity(pos, type, result); + } + } else if (type == Blocks.DROPPER) { + if (!(result instanceof TileEntityDropper)) { + result = fixTileEntity(pos, type, result); + } + } else if (type == Blocks.DISPENSER) { + if (!(result instanceof TileEntityDispenser)) { + result = fixTileEntity(pos, type, result); + } + } else if (type == Blocks.JUKEBOX) { + if (!(result instanceof BlockJukeBox.TileEntityRecordPlayer)) { + result = fixTileEntity(pos, type, result); + } + } else if (type == Blocks.NOTEBLOCK) { + if (!(result instanceof TileEntityNote)) { + result = fixTileEntity(pos, type, result); + } + } else if (type == Blocks.MOB_SPAWNER) { + if (!(result instanceof TileEntityMobSpawner)) { + result = fixTileEntity(pos, type, result); + } + } else if ((type == Blocks.STANDING_SIGN) || (type == Blocks.WALL_SIGN)) { + if (!(result instanceof TileEntitySign)) { + result = fixTileEntity(pos, type, result); + } + } else if (type == Blocks.ENDER_CHEST) { + if (!(result instanceof TileEntityEnderChest)) { + result = fixTileEntity(pos, type, result); + } + } else if (type == Blocks.BREWING_STAND) { + if (!(result instanceof TileEntityBrewingStand)) { + result = fixTileEntity(pos, type, result); + } + } else if (type == Blocks.BEACON) { + if (!(result instanceof TileEntityBeacon)) { + result = fixTileEntity(pos, type, result); + } + } + + return result; + } + + private TileEntity fixTileEntity(BlockPosition pos, Block type, TileEntity found) { + this.getServer().getLogger().log(Level.SEVERE, "Block at {0},{1},{2} is {3} but has {4}" + ". " + + "Bukkit will attempt to fix this, but there may be additional damage that we cannot recover.", new Object[]{pos.getX(), pos.getY(), pos.getZ(), Objects.requireNonNull(org.bukkit.Material.getMaterial(Block.getId(type))).toString(), found}); + + if (type instanceof IContainer) { + TileEntity replacement = ((IContainer) type).a(this, type.toLegacyData(type.getBlockData())); + replacement.world = this; + this.setTileEntity(pos, replacement); + return replacement; + } else { + this.getServer().getLogger().severe("Don't know how to fix for this type... Can't do anything! :("); + return found; + } + } + + private boolean canSpawn(int x, int z) { + if (generator != null) { + return generator.canSpawn(getWorld(), x, z); + } else { + return worldProvider.canSpawn(x, z); + } + } + // CraftBukkit end + + public void doTick() { + if (AzuriteConfig.tickWeather.getValue()) + super.doTick(); + + if (AzuriteConfig.tickBiomeCache.getValue()) + worldProvider.m().b(); + + boolean dayLightCycle = getGameRules().getBoolean("doDaylightCycle"); + if (AzuriteConfig.checkPlayerSleep.getValue() && everyoneDeeplySleeping()) { + if (dayLightCycle) { + long i = worldData.getDayTime() + 24000L; + worldData.setDayTime(i - i % 24000L); + } + e(); + } + + long time = worldData.getTime(); + if (AzuriteConfig.naturalMobSpawn.getValue() && (allowMonsters || allowAnimals) && !players.isEmpty()) { + R.a(this, + allowMonsters && (ticksPerMonsterSpawns != 0 && time % ticksPerMonsterSpawns == 0L), + allowAnimals && (ticksPerAnimalSpawns != 0 && time % ticksPerAnimalSpawns == 0L), + worldData.getTime() % 400L == 0L); + } + + if (AzuriteConfig.chunkUnloading.getValue()) { + chunkProvider.unloadChunks(); + } + + int j = a(1.0F); + if (j != ab()) { + c(j); + } + + worldData.setTime(time + 1L); + if (dayLightCycle) + worldData.setDayTime(worldData.getDayTime() + 1L); + + if (AzuriteConfig.tickBlocks.getValue()) + a(false); + + if (AzuriteConfig.tickChunks.getValue()) + h(); + + spigotConfig.antiXrayInstance.flushUpdates(this); // PaperSpigot + manager.flush(); + + if (AzuriteConfig.tickVillages.getValue()) { + villages.tick(); + siegeManager.a(); + } + + Q.a(getTime()); + ak(); + + if (AzuriteConfig.chunkUnloading.getValue()) + getWorld().processChunkGC(); // CraftBukkit + } + + // Beanes - method to flush world changes + public void flushWorldChanges() { + manager.flush(); + } + + // Azurite start + public BiomeBase.BiomeMeta a(List mobs) { + return mobs != null && !mobs.isEmpty() ? WeightedRandom.a(random, mobs) : null; + } + + public boolean a(List mobs, BiomeBase.BiomeMeta biomebase_biomemeta) { + return mobs != null && !mobs.isEmpty() && mobs.contains(biomebase_biomemeta); + } + // Azurite end + + public BiomeBase.BiomeMeta a(EnumCreatureType enumcreaturetype, BlockPosition blockposition) { + List list = this.N().getMobsFor(enumcreaturetype, blockposition); + return list != null && !list.isEmpty() ? WeightedRandom.a(random, list) : null; + } + + public boolean a(EnumCreatureType enumcreaturetype, BiomeBase.BiomeMeta biomebase_biomemeta, BlockPosition blockposition) { + List list = this.N().getMobsFor(enumcreaturetype, blockposition); + return list != null && !list.isEmpty() && list.contains(biomebase_biomemeta); + } + + public void everyoneSleeping() { + if (!AzuriteConfig.checkPlayerSleep.getValue()) return; + O = false; + if (!players.isEmpty()) { + int i = 0; + int j = 0; + + for (EntityHuman entityhuman : players) { + if (entityhuman.isSpectator()) { + ++i; + } else if (entityhuman.isSleeping() || entityhuman.fauxSleeping) { + ++j; + } + } + + O = j > 0 && j >= players.size() - i; + } + } + + protected void e() { + O = false; + + for (EntityHuman entityhuman : this.players) { + if (entityhuman.isSleeping()) { + entityhuman.a(false, false, true); + } + } + + ag(); + } + + private void ag() { + worldData.setStorm(false); + // CraftBukkit start + // If we stop due to everyone sleeping we should reset the weather duration to some other random value. + // Not that everyone ever manages to get the whole server to sleep at the same time.... + if (!worldData.hasStorm()) { + worldData.setWeatherDuration(0); + } + // CraftBukkit end + worldData.setThundering(false); + // CraftBukkit start + // If we stop due to everyone sleeping we should reset the weather duration to some other random value. + // Not that everyone ever manages to get the whole server to sleep at the same time.... + if (!worldData.isThundering()) { + worldData.setThunderDuration(0); + } + // CraftBukkit end + } + + public boolean everyoneDeeplySleeping() { + if (O) { + Iterator iterator = players.iterator(); + + // CraftBukkit - This allows us to assume that some people are in bed but not really, allowing time to pass in spite of AFKers + boolean foundActualSleepers = false; + + EntityHuman entityhuman; + + do { + if (!iterator.hasNext()) { + return foundActualSleepers; + } + + entityhuman = iterator.next(); + + // CraftBukkit start + if (entityhuman.isDeeplySleeping()) { + foundActualSleepers = true; + } + } while (!entityhuman.isSpectator() || entityhuman.isDeeplySleeping() || entityhuman.fauxSleeping); + // CraftBukkit end + + } + return false; + } + + protected void h() { + super.h(); + int randomTickSpeed = getRandomTickSpeed(); + boolean triggerFormEvent = BlockFormEvent.getHandlerList().getRegisteredListeners().length > 0; + boolean isRaining = S(); + boolean isThundering = R(); + + for (int chunkI = 0; chunkI < chunkTickList.size(); chunkI++) { + Chunk chunk = chunkTickList.get(chunkI); + + int worldX = chunk.locX * 16, worldZ = chunk.locZ * 16; + + chunk.m(); + chunk.b(false); + + if (!paperSpigotConfig.disableThunder && isRaining && isThundering && simpleRandom.nextInt(100000) == 0) { + m = m * 3 + 1013904223; + + int i = m >> 2; + BlockPosition blockposition = a(worldX + (i & 0xF), worldZ + (i >> 8 & 0xF)); + if (isRainingAt(blockposition)) { + strikeLightning(new EntityLightning(this, blockposition.getX(), blockposition.getY(), blockposition.getZ())); + } + } + + if (!paperSpigotConfig.disableIceAndSnow && simpleRandom.nextInt(16) == 0) { + m = m * 3 + 1013904223; + + int i = m >> 2; + + int xSection = i & 0xF; + int zSection = i >> 8 & 0xF; + int y = chunk.getPrecipitationHeight(xSection, zSection); + int yDown = y - 1; + + int x = xSection | worldX; + int z = zSection | worldZ; + + BiomeBase biome = chunk.getBiome(x, z, this.worldProvider.m()); + + if (canBlockFreeze(chunk, biome, x, yDown, z)) { + BlockState blockState = getWorld().getBlockAt(x, yDown, z).getState(); + blockState.setTypeId(Block.getId(Blocks.ICE)); + + if (triggerFormEvent) { + BlockFormEvent iceBlockForm = new BlockFormEvent(blockState.getBlock(), blockState); + getServer().getPluginManager().callEvent(iceBlockForm); + if (!iceBlockForm.isCancelled()) + blockState.update(true); + } + } + + if (isRaining) { + if (canSnowAt(chunk, biome, x, y, z, true)) { + BlockState blockState = getWorld().getBlockAt(x, y, z).getState(); + blockState.setTypeId(Block.getId(Blocks.SNOW_LAYER)); + + if (triggerFormEvent) { + BlockFormEvent snow = new BlockFormEvent(blockState.getBlock(), blockState); + getServer().getPluginManager().callEvent(snow); + if (!snow.isCancelled()) + blockState.update(true); + } + } + + if (biome.e()) { + getType(x, yDown, z).getBlock().k(this, new BlockPosition(x, yDown, z)); + } + } + } + + if (randomTickSpeed > 0) { + for (ChunkSection section : chunk.getSections()) { + if (section != null && section.getTickList() != null) { + int tickingBlocks = section.getTickingBlockCount(); + + if (tickingBlocks == 0) continue; + + for (int l1 = 0; l1 < randomTickSpeed; l1++) { + int index = simpleRandom.nextInt() & ((16 * 16 * 16) - 1); + + if (index >= tickingBlocks) { + continue; + } + + // Azurite - Add a check for some plugins that replace chunk sections through reflection + // but does not call recalcBlockCounts causing tick list to be the incorrect size + short loc; + + try { + + loc = section.getTickList().getRaw(index); + + } catch (ArrayIndexOutOfBoundsException e) { + section.recalcBlockCounts(); + break; + } + + IBlockData iblockdata = section.getType(loc); + Block block = iblockdata.getBlock(); + + // Vortex - optimize ticking + block.optimizedTick(chunk, (loc & 15) | worldX, ((loc >> 8) & 15) | section.getYPosition(), ((loc >> 4) & 15) | worldZ, iblockdata, random); + } + } + } + } + } + + if (spigotConfig.clearChunksOnTick) + chunkTickList.clear(); + } + + protected BlockPosition a(BlockPosition blockposition) { + return a(blockposition.getX(), blockposition.getZ()); + } + + protected BlockPosition a(int x, int z) { + BlockPosition blockposition1 = q(x, z); + AxisAlignedBB axisalignedbb = new AxisAlignedBB(blockposition1.getX(), blockposition1.getY(), blockposition1.getZ(), blockposition1.getX(), getHeight(), blockposition1.getZ()).grow(3.0D, 3.0D, 3.0D); + List list = a(EntityLiving.class, axisalignedbb, (Predicate) entityliving -> entityliving != null && entityliving.isAlive() && WorldServer.this.i(entityliving.getChunkCoordinates())); + return !list.isEmpty() ? list.get(random.nextInt(list.size())).getChunkCoordinates() : blockposition1; + } + + public boolean a(BlockPosition blockposition, Block block) { + return V.contains(new NextTickListEntry(blockposition, block)); + } + + public void a(BlockPosition blockposition, Block block, int i) { + a(blockposition, block, i, 0); + } + + public void a(BlockPosition blockposition, Block block, int i, int j) { + a(blockposition, null, block, i, j); + } + + public void a(BlockPosition blockposition, Chunk chunk, Block block, int i, int j) { + // Beanes - don't add pending updates if ticking blcoks is disabled + if (!AzuriteConfig.tickBlocks.getValue()) { + return; + } + + NextTickListEntry nextticklistentry = new NextTickListEntry(blockposition, block); + + if (e && block.getMaterial() != Material.AIR) { + if (block.N()) { + if (areChunksLoadedBetween(blockposition.a(-8, -8, -8), blockposition.a(8, 8, 8))) { + if (chunk == null) + chunk = getChunkAtWorldCoords(blockposition); + IBlockData iblockdata = getType(chunk, blockposition); + Block iblock = iblockdata.getBlock(); + if (iblock.getMaterial() != Material.AIR && iblock == nextticklistentry.a()) { + iblock.b(this, blockposition, iblockdata, random); + } + } + return; + } + i = 1; + } + + if (chunk == null) + chunk = getChunkIfLoaded(blockposition.getX() >> 4, blockposition.getZ() >> 4); + + if (chunk != null) { + if (block.getMaterial() != Material.AIR) { + nextticklistentry.a(i + this.worldData.getTime()); + nextticklistentry.a(j); + } + if (!M.contains(nextticklistentry)) + M.add(nextticklistentry); + } + } + + public void b(BlockPosition blockposition, Block block, int i, int j) { + // Beanes - don't add pending updates if ticking blcoks is disabled + if (!AzuriteConfig.tickBlocks.getValue()) { + return; + } + + NextTickListEntry nextticklistentry = new NextTickListEntry(blockposition, block); + nextticklistentry.a(j); + if (block.getMaterial() != Material.AIR) + nextticklistentry.a(i + worldData.getTime()); + if (!M.contains(nextticklistentry)) + M.add(nextticklistentry); + } + + public boolean a(boolean flag) { + int i = M.size(); + if (i > paperSpigotConfig.tickNextTickCap) + i = paperSpigotConfig.tickNextTickCap; + + NextTickListEntry nextticklistentry; + for (int j = 0; j < i; ++j) { + nextticklistentry = this.M.first(); + if (!flag && nextticklistentry.b > this.worldData.getTime()) + break; + M.remove(nextticklistentry); + V.add(nextticklistentry); + } + + if (paperSpigotConfig.tickNextTickListCapIgnoresRedstone) { + Iterator iterator1 = M.iterator(); + while (iterator1.hasNext()) { + nextticklistentry = iterator1.next(); + if (!flag && nextticklistentry.b > worldData.getTime()) + break; + Block block = nextticklistentry.a(); + if (block.isPowerSource() || block instanceof IContainer || block instanceof BlockFalling) { + iterator1.remove(); + V.add(nextticklistentry); + } + } + } + + Iterator iterator = V.iterator(); + Chunk chunk = null; // Azurite - Improve block ticking chunk lookups + while (iterator.hasNext()) { + nextticklistentry = iterator.next(); + iterator.remove(); + BlockPosition position = nextticklistentry.a; + int chunkX = position.getX() >> 4; + int chunkZ = position.getZ() >> 4; + if (Utils.isInvalidChunk(chunk, chunkX, chunkZ)) + chunk = getChunkIfLoaded(chunkX, chunkZ); + if (chunk != null) { + IBlockData iblockdata = getType(chunk, position); + Block block = iblockdata.getBlock(); + if (block.getMaterial() != Material.AIR && Block.a(block, nextticklistentry.a())) { + try { + block.b(this, position, iblockdata, random); + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.a(throwable, "Exception while ticking a block"); + CrashReportSystemDetails crashreportsystemdetails = crashreport.a("Block being ticked"); + CrashReportSystemDetails.a(crashreportsystemdetails, position, iblockdata); + throw new ReportedException(crashreport); + } + } + } else { + a(position, nextticklistentry.a(), 0); + } + } + dispatch(); + V.clear(); + return !M.isEmpty(); + } + + public List a(Chunk chunk, boolean flag) { + ChunkCoordIntPair chunkcoordintpair = chunk.j(); + int i = (chunkcoordintpair.x << 4) - 2, k = (chunkcoordintpair.z << 4) - 2; + return a(new StructureBoundingBox(i, 0, k, i + 16 + 2, 256, k + 16 + 2), flag); + } + + public List a(StructureBoundingBox structureboundingbox, boolean flag) { + List arraylist = null; + for (int i = 0; i < 2; ++i) { + Iterator iterator; + if (i == 0) { + iterator = M.iterator(); + } else { + iterator = V.iterator(); + } + while (iterator.hasNext()) { + NextTickListEntry nextticklistentry = iterator.next(); + BlockPosition blockposition = nextticklistentry.a; + if (blockposition.getX() >= structureboundingbox.a && blockposition.getX() < structureboundingbox.d && blockposition.getZ() >= structureboundingbox.c && blockposition.getZ() < structureboundingbox.f) { + if (flag) + iterator.remove(); + if (arraylist == null) + arraylist = Lists.newArrayList(); + arraylist.add(nextticklistentry); + } + } + } + return arraylist; + } + + protected IChunkProvider k() { + IChunkLoader ichunkloader = this.dataManager.createChunkLoader(this.worldProvider); + + // CraftBukkit start + org.bukkit.craftbukkit.generator.InternalChunkGenerator gen; + + if (AzuriteConfig.forceVoidChunks.getValue() || this.worldData.getType() == WorldType.VOID) { + gen = new VoidChunkGenerator(this, this.getSeed()); + } else if (this.generator != null) { + gen = new org.bukkit.craftbukkit.generator.CustomChunkGenerator(this, this.getSeed(), this.generator); + } else if (this.worldProvider instanceof WorldProviderHell) { + gen = new org.bukkit.craftbukkit.generator.NetherChunkGenerator(this, this.getSeed()); + } else if (this.worldProvider instanceof WorldProviderTheEnd) { + gen = new org.bukkit.craftbukkit.generator.SkyLandsChunkGenerator(this, this.getSeed()); + } else { + gen = new org.bukkit.craftbukkit.generator.NormalChunkGenerator(this, this.getSeed()); + } + + this.chunkProviderServer = new ChunkProviderServer(this, ichunkloader, gen); + // CraftBukkit end + return this.chunkProviderServer; + } + + public List getTileEntities(int i, int j, int k, int l, int i1, int j1) { + List arraylist = Lists.newArrayList(); + + int minX = i >> 4, minZ = k >> 4, maxX = (l - 1) >> 4, maxZ = (j1 - 1) >> 4; // Vortex - less calc + // CraftBukkit start - Get tile entities from chunks instead of world + for (int chunkX = minX; chunkX <= maxX; chunkX++) { + for (int chunkZ = minZ; chunkZ <= maxZ; chunkZ++) { + Chunk chunk = getChunkAt(chunkX, chunkZ); + if (chunk != null) + for (TileEntity tileentity : chunk.tileEntities.values()) { + if (tileentity.position.getX() >= i && + tileentity.position.getY() >= j && + tileentity.position.getZ() >= k && + tileentity.position.getX() < l && + tileentity.position.getY() < i1 && + tileentity.position.getZ() < j1) { + arraylist.add(tileentity); + } + } + } + } + + return arraylist; + } + + public boolean a(EntityHuman entityhuman, BlockPosition blockposition) { + return !this.server.a(this, blockposition, entityhuman) && this.getWorldBorder().a(blockposition); + } + + public void a(WorldSettings worldsettings) { + if (!worldData.w()) { + try { + b(worldsettings); + super.a(worldsettings); + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.a(throwable, "Exception initializing level"); + try { + a(crashreport); + } catch (Throwable ignored) { + } + throw new ReportedException(crashreport); + } + worldData.d(true); + } + } + + private void b(WorldSettings worldsettings) { + if (!this.worldProvider.e()) { + this.worldData.setSpawn(BlockPosition.ZERO.up(this.worldProvider.getSeaLevel())); + } else { + this.isLoading = true; + WorldChunkManager worldchunkmanager = this.worldProvider.m(); + List list = worldchunkmanager.a(); + Random random = new Random(getSeed()); + BlockPosition blockposition = worldchunkmanager.a(0, 0, 256, list, random); + int i = 0; + int j = this.worldProvider.getSeaLevel(); + int k = 0; + if (this.generator != null) { + Random rand = new Random(getSeed()); + Location spawn = this.generator.getFixedSpawnLocation(getWorld(), rand); + if (spawn != null) { + if (spawn.getWorld() != getWorld()) + throw new IllegalStateException("Cannot set spawn point for " + this.worldData.getName() + " to be in another world (" + spawn.getWorld().getName() + ")"); + this.worldData.setSpawn(new BlockPosition(spawn.getBlockX(), spawn.getBlockY(), spawn.getBlockZ())); + this.isLoading = false; + return; + } + } + if (blockposition != null) { + i = blockposition.getX(); + k = blockposition.getZ(); + } else { + a.warn("Unable to find spawn biome"); + } + int l = 0; + while (!canSpawn(i, k)) { + i += random.nextInt(64) - random.nextInt(64); + k += random.nextInt(64) - random.nextInt(64); + ++l; + if (l == 1000) + break; + } + this.worldData.setSpawn(new BlockPosition(i, j, k)); + this.isLoading = false; + if (worldsettings.c()) + l(); + } + } + + protected void l() { + WorldGenBonusChest worldgenbonuschest = new WorldGenBonusChest(WorldServer.U, 10); + + for (int i = 0; i < 10; ++i) { + int j = this.worldData.c() + random.nextInt(6) - random.nextInt(6); + int k = this.worldData.e() + random.nextInt(6) - random.nextInt(6); + BlockPosition blockposition = this.r(j, k).up(); + + if (worldgenbonuschest.generate(this, random, blockposition)) { + break; + } + } + + } + + public BlockPosition getDimensionSpawn() { + return this.worldProvider.h(); + } + + public void saveOnlyLevel(IProgressUpdate iprogressupdate) throws ExceptionWorldConflict { + if (this.chunkProvider.canSave()) { + if (iprogressupdate != null) { + iprogressupdate.a("Saving level"); + } + this.a(); + } + } + + public boolean saveOnlyChunks(boolean flag, IProgressUpdate iprogressupdate) { + if (this.chunkProvider.canSave()) { + if (iprogressupdate != null) { + iprogressupdate.c("Saving chunks"); + } + return this.chunkProvider.saveChunks(flag, iprogressupdate); + } + return true; + } + + public void unloadOnlyUnusedChunks() { + if (this.chunkProvider.canSave()) { + for (Chunk chunk : chunkProviderServer.a()) { + if (chunk != null && !this.manager.a(chunk.locX, chunk.locZ)) { + this.chunkProviderServer.queueUnload(chunk.locX, chunk.locZ); + } + } + } + } + + public void save(boolean flag, IProgressUpdate iprogressupdate) throws ExceptionWorldConflict { + if (this.chunkProvider.canSave()) { + org.bukkit.Bukkit.getPluginManager().callEvent(new org.bukkit.event.world.WorldSaveEvent(getWorld())); + this.saveOnlyLevel(iprogressupdate); + this.saveOnlyChunks(flag, iprogressupdate); + this.unloadOnlyUnusedChunks(); + } + } + + public void flushSave() { + if (this.chunkProvider.canSave()) { + this.chunkProvider.c(); + } + } + + protected void a() throws ExceptionWorldConflict { + this.checkSession(); + WorldBorder b = getWorldBorder(); + worldData.a(b.getSize()); + worldData.d(b.getCenterX()); + worldData.c(b.getCenterZ()); + worldData.e(b.getDamageBuffer()); + worldData.f(b.getDamageAmount()); + worldData.j(b.getWarningDistance()); + worldData.k(b.getWarningTime()); + worldData.b(b.j()); + worldData.e(b.i()); + // CraftBukkit start - save worldMaps once, rather than once per shared world + if (!(this instanceof SecondaryWorldServer)) { + this.worldMaps.a(); + } + this.dataManager.saveWorldData(this.worldData, this.server.getPlayerList().t()); + // CraftBukkit end + } + + protected void a(Entity entity) { + super.a(entity); + this.entitiesById.a(entity.getId(), entity); + if (!(entity instanceof EntityTNTPrimed || entity instanceof EntityFallingBlock)) { + this.entitiesByUUID.put(entity.getUniqueID(), entity); + Entity[] aentity = entity.aB(); + + if (aentity != null) { + for (Entity value : aentity) { + this.entitiesById.a(value.getId(), value); + } + } + } + } + + protected void b(Entity entity) { + super.b(entity); + this.entitiesById.d(entity.getId()); + if (!(entity instanceof EntityTNTPrimed || entity instanceof EntityFallingBlock)) { + this.entitiesByUUID.remove(entity.getUniqueID()); + Entity[] aentity = entity.aB(); + + if (aentity != null) { + for (Entity value : aentity) { + this.entitiesById.d(value.getId()); + } + } + } + } + + public boolean strikeLightning(Entity entity) { + // CraftBukkit start + LightningStrikeEvent lightning = new LightningStrikeEvent(this.getWorld(), (org.bukkit.entity.LightningStrike) entity.getBukkitEntity()); + this.getServer().getPluginManager().callEvent(lightning); + + if (lightning.isCancelled()) { + return false; + } + if (super.strikeLightning(entity)) { + this.server.getPlayerList().sendPacketNearby(entity.locX, entity.locY, entity.locZ, 512.0D, dimension, new PacketPlayOutSpawnEntityWeather(entity)); + // CraftBukkit end + return true; + } else { + return false; + } + } + + public void broadcastEntityEffect(Entity entity, byte b0) { + this.getTracker().sendPacketToEntity(entity, new PacketPlayOutEntityStatus(entity, b0)); + } + + public Explosion createExplosion(Entity entity, double d0, double d1, double d2, float f, boolean flag, boolean flag1) { + // CraftBukkit start + Explosion explosion = super.createExplosion(entity, d0, d1, d2, f, flag, flag1); + + if (explosion.wasCanceled) { + return explosion; + } + + if (!flag1) { + explosion.clearBlocks(); + } + + if (AzuriteConfig.explosionParticles.getValue()) + for (EntityHuman entityhuman : players) { + if (entityhuman.e(d0, d1, d2) < 4096.0D) + entityhuman.sendPacket(new PacketPlayOutExplosion(d0, d1, d2, f, explosion.getBlocks(), explosion.b().get(entityhuman))); + } + + return explosion; + } + + public void playBlockAction(BlockPosition blockposition, Block block, int i, int j) { + BlockActionData blockactiondata = new BlockActionData(blockposition, block, i, j); + Iterator iterator = this.S[this.T].iterator(); + + BlockActionData blockactiondata1; + + do { + if (!iterator.hasNext()) { + this.S[this.T].add(blockactiondata); + return; + } + + blockactiondata1 = iterator.next(); + } while (!blockactiondata1.equals(blockactiondata)); + + } + + private void ak() { + while (!S[T].isEmpty()) { + int i = T; + + T ^= 1; + + for (BlockActionData blockactiondata : S[i]) { + if (a(blockactiondata)) { + if (AzuriteConfig.hidePistonAnimations.getValue() && blockactiondata.d() instanceof BlockPiston || blockactiondata.d() instanceof BlockPistonExtension) + continue; + server.getPlayerList().sendPacketNearby(blockactiondata.a().getX(), blockactiondata.a().getY(), blockactiondata.a().getZ(), 64.0D, dimension, new PacketPlayOutBlockAction(blockactiondata.a(), blockactiondata.d(), blockactiondata.b(), blockactiondata.c())); + } + } + + S[i].clear(); + } + } + + private boolean a(BlockActionData blockactiondata) { + IBlockData iblockdata = this.getType(blockactiondata.a()); + Block block = iblockdata.getBlock(); + return block == blockactiondata.d() && block.a(this, blockactiondata.a(), iblockdata, blockactiondata.b(), blockactiondata.c()); + } + + public void saveLevel() { + this.dataManager.a(); + } + + protected void p() { + boolean flag = this.S(); + + super.p(); + + if (flag != this.S()) { + // Only send weather packets to those affected + for (EntityHuman player : this.players) { + if (player.world == this) { + ((EntityPlayer) player).setPlayerWeather((!flag ? WeatherType.DOWNFALL : WeatherType.CLEAR), false); + } + } + } + for (EntityHuman player : this.players) { + if (player.world == this) { + ((EntityPlayer) player).updateWeather(this.o, this.p, this.q, this.r); + } + } + // CraftBukkit end + } + + protected int q() { + return this.server.getPlayerList().s(); + } + + public MinecraftServer getMinecraftServer() { + return this.server; + } + + public EntityTracker getTracker() { + return this.tracker; + } + + public PlayerChunkMap getPlayerChunkMap() { + return this.manager; + } + + public PortalTravelAgent getTravelAgent() { + return this.Q; + } + + public void a(EnumParticle enumparticle, double d0, double d1, double d2, int i, double d3, double d4, double d5, double d6, int... aint) { + this.a(enumparticle, false, d0, d1, d2, i, d3, d4, d5, d6, aint); + } + + public void a(EnumParticle enumparticle, boolean flag, double d0, double d1, double d2, int i, double d3, double d4, double d5, double d6, int... aint) { + // CraftBukkit - visibility api support + sendParticles(null, enumparticle, flag, d0, d1, d2, i, d3, d4, d5, d6, aint); + } + + public void sendParticles(EntityPlayer sender, EnumParticle enumparticle, boolean flag, double d0, double d1, double d2, int i, double d3, double d4, double d5, double d6, int... aint) { + // CraftBukkit end + PacketPlayOutWorldParticles packetplayoutworldparticles = new PacketPlayOutWorldParticles(enumparticle, flag, (float) d0, (float) d1, (float) d2, (float) d3, (float) d4, (float) d5, (float) d6, i, aint); + for (EntityHuman p : players) { + EntityPlayer entityplayer = (EntityPlayer) p; + if (sender != null && !entityplayer.getBukkitEntity().canSee(sender.getBukkitEntity())) + continue; // CraftBukkit + double d7 = entityplayer.getChunkCoordinates().c(d0, d1, d2); + + if (d7 <= 256.0D || flag && d7 <= 65536.0D) { + entityplayer.playerConnection.sendPacket(packetplayoutworldparticles); + } + } + } + + public Entity getEntity(UUID uuid) { + return this.entitiesByUUID.get(uuid); + } + + @Override + public ListenableFuture postToMainThread(Runnable paramRunnable) { + return this.server.postToMainThread(paramRunnable); + } + + @Override + public void postToMainThreadRunnable(Runnable runnable) { + this.server.postToMainThreadRunnable(runnable); + } + + public boolean isMainThread() { + return this.server.isMainThread(); + } + + static class BlockActionDataList extends ArrayList { + + private BlockActionDataList() { + } + + BlockActionDataList(Object object) { + this(); + } + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldSettings.java b/azurite-server/src/main/java/net/minecraft/server/WorldSettings.java new file mode 100644 index 0000000..8a9cbde --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldSettings.java @@ -0,0 +1,139 @@ +package net.minecraft.server; + +public final class WorldSettings { + private final long a; + + private final EnumGamemode b; + + private final boolean c; + + private final boolean d; + + private final WorldType e; + + private boolean g; + + public enum EnumGamemode { + NOT_SET(-1, ""), + SURVIVAL(0, "survival"), + CREATIVE(1, "creative"), + ADVENTURE(2, "adventure"), + SPECTATOR(3, "spectator"); + + final int f; + + final String g; + + EnumGamemode(int param1Int1, String param1String1) { + this.f = param1Int1; + this.g = param1String1; + } + + public int getId() { + return this.f; + } + + public String b() { + return this.g; + } + + public void a(PlayerAbilities param1PlayerAbilities) { + if (this == CREATIVE) { + param1PlayerAbilities.canFly = true; + param1PlayerAbilities.canInstantlyBuild = true; + param1PlayerAbilities.isInvulnerable = true; + } else if (this == SPECTATOR) { + param1PlayerAbilities.canFly = true; + param1PlayerAbilities.canInstantlyBuild = false; + param1PlayerAbilities.isInvulnerable = true; + param1PlayerAbilities.isFlying = true; + } else { + param1PlayerAbilities.canFly = false; + param1PlayerAbilities.canInstantlyBuild = false; + param1PlayerAbilities.isInvulnerable = false; + param1PlayerAbilities.isFlying = false; + } + param1PlayerAbilities.mayBuild = !c(); + } + + public boolean c() { + return (this == ADVENTURE || this == SPECTATOR); + } + + public boolean d() { + return (this == CREATIVE); + } + + public boolean e() { + return (this == SURVIVAL || this == ADVENTURE); + } + + public static EnumGamemode getById(int param1Int) { + for (EnumGamemode enumGamemode : values()) { + if (enumGamemode.f == param1Int) + return enumGamemode; + } + return SURVIVAL; + } + } + + private String h = ""; + + public WorldSettings(long paramLong, EnumGamemode paramEnumGamemode, boolean paramBoolean1, boolean paramBoolean2, WorldType paramWorldType) { + this.a = paramLong; + this.b = paramEnumGamemode; + this.c = paramBoolean1; + this.d = paramBoolean2; + this.e = paramWorldType; + } + + public WorldSettings(WorldData paramWorldData) { + this(paramWorldData.getSeed(), paramWorldData.getGameType(), paramWorldData.shouldGenerateMapFeatures(), paramWorldData.isHardcore(), paramWorldData.getType()); + } + + public WorldSettings a() { + this.g = true; + return this; + } + + public WorldSettings setGeneratorSettings(String paramString) { + this.h = paramString; + return this; + } + + public boolean c() { + return this.g; + } + + public long d() { + return this.a; + } + + public EnumGamemode e() { + return this.b; + } + + public boolean f() { + return this.d; + } + + public boolean g() { + return this.c; + } + + public WorldType h() { + return this.e; + } + + public boolean i() { + return false; + } + + public static EnumGamemode a(int paramInt) { + return EnumGamemode.getById(paramInt); + } + + public String j() { + return this.h; + } +} diff --git a/azurite-server/src/main/java/net/minecraft/server/WorldType.java b/azurite-server/src/main/java/net/minecraft/server/WorldType.java new file mode 100644 index 0000000..898906a --- /dev/null +++ b/azurite-server/src/main/java/net/minecraft/server/WorldType.java @@ -0,0 +1,72 @@ +package net.minecraft.server; + +public class WorldType { + + public static final WorldType[] types = new WorldType[16]; + public static final WorldType NORMAL = (new WorldType(0, "default", 1)).i(); + public static final WorldType FLAT = new WorldType(1, "flat"); + public static final WorldType LARGE_BIOMES = new WorldType(2, "largeBiomes"); + public static final WorldType AMPLIFIED = (new WorldType(3, "amplified")).j(); + public static final WorldType CUSTOMIZED = new WorldType(4, "customized"); + public static final WorldType DEBUG_ALL_BLOCK_STATES = new WorldType(5, "debug_all_block_states"); + public static final WorldType NORMAL_1_1 = (new WorldType(8, "default_1_1", 0)).a(false); + public static final WorldType VOID = new WorldType(9, "void"); + private final int i; + private final String name; + private final int version; + private boolean m; + + private WorldType(int i, String s) { + this(i, s, 0); + } + + private WorldType(int i, String s, int j) { + this.name = s; + this.version = j; + this.i = i; + WorldType.types[i] = this; + } + + public String name() { + return this.name; + } + + public int getVersion() { + return this.version; + } + + public WorldType a(int i) { + return this == WorldType.NORMAL && i == 0 ? WorldType.NORMAL_1_1 : this; + } + + private WorldType a(boolean flag) { + return this; + } + + private WorldType i() { + this.m = true; + return this; + } + + public boolean f() { + return this.m; + } + + public static WorldType getType(String s) { + for (int i = 0; i < WorldType.types.length; ++i) { + if (WorldType.types[i] != null && WorldType.types[i].name.equalsIgnoreCase(s)) { + return WorldType.types[i]; + } + } + + return null; + } + + public int g() { + return this.i; + } + + private WorldType j() { + return this; + } +} diff --git a/azurite-server/src/main/java/net/techcable/tacospigot/BlockStateRegistry.java b/azurite-server/src/main/java/net/techcable/tacospigot/BlockStateRegistry.java new file mode 100644 index 0000000..6f04ad6 --- /dev/null +++ b/azurite-server/src/main/java/net/techcable/tacospigot/BlockStateRegistry.java @@ -0,0 +1,40 @@ +package net.techcable.tacospigot; + +import net.minecraft.server.IBlockState; + +import java.util.Arrays; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.atomic.AtomicInteger; + +public class BlockStateRegistry { + private BlockStateRegistry() { + } // Utility class + + private static final ConcurrentMap, Integer> idsByObj = new ConcurrentHashMap<>(); + private static volatile IBlockState[] byId = new IBlockState[0]; + private static final AtomicInteger nextId = new AtomicInteger(); + + public static int getId(IBlockState s) { + return idsByObj.computeIfAbsent(s, (state) -> { + int id = nextId.getAndIncrement(); + synchronized (BlockStateRegistry.class) { + if (id >= byId.length) { + byId = Arrays.copyOf(byId, id + 1); + } + byId[id] = state; + } + return id; + }); + } + + public static IBlockState getById(int id) { + if (id < 0) { + throw new IllegalArgumentException("Negative id: " + id); + } else if (id < byId.length) { + return byId[id]; + } else { + return null; + } + } +} diff --git a/azurite-server/src/main/java/net/techcable/tacospigot/HopperHelper.java b/azurite-server/src/main/java/net/techcable/tacospigot/HopperHelper.java new file mode 100644 index 0000000..98ede2f --- /dev/null +++ b/azurite-server/src/main/java/net/techcable/tacospigot/HopperHelper.java @@ -0,0 +1,157 @@ +package net.techcable.tacospigot; + +import dev.azurite.spigot.configs.AzuriteConfig; +import net.minecraft.server.*; +import org.bukkit.event.inventory.InventoryMoveItemEvent; + +public class HopperHelper { + + public static TileEntityHopper getHopper(World world, BlockPosition pos) { + int x = pos.getX(), y = pos.getY(), z = pos.getZ(); + IBlockData iblockdata = null; + if (world.captureTreeGeneration) { + iblockdata = world.getCapturedBlockType(x, y, z); + } + + if (iblockdata == null && !world.isValidLocation(x, y, z)) + return null; + + Chunk chunk = world.getChunkAtWorldCoords(x, z); + Block block = chunk.getBlockData(x, y, z).getBlock(); + if (block != Blocks.HOPPER) return null; + + TileEntity tileEntity = world.getTileEntity(chunk, pos, block); + if (tileEntity instanceof TileEntityHopper) { + return (TileEntityHopper) tileEntity; + } + return null; + } + + public static IInventory getInventory(World world, BlockPosition position) { + if (!world.isValidLocation(position.getX(), position.getY(), position.getZ())) + return null; + Chunk chunk = world.getChunkIfLoaded(position.getX() >> 4, position.getZ() >> 4); + if (chunk == null) + return null; + Block block = world.getType(chunk, position).getBlock(); + if (block instanceof BlockChest) { + return ((BlockChest) block).f(world, position); + } else if (block.isTileEntity()) { + TileEntity tile = world.getTileEntity(position); + + if (tile instanceof TileEntityContainer) { + return (IInventory) tile; + } + } + return null; + } + + // Beanes - cached hoppers + public static IInventory getInventoryForPulling(World world, BlockPosition position, TileEntityHopper toCache) { + if (!world.isValidLocation(position.getX(), position.getY(), position.getZ())) + return null; + Chunk chunk = world.getChunkIfLoaded(position.getX() >> 4, position.getZ() >> 4); + if (chunk == null) + return null; + Block block = world.getType(chunk, position).getBlock(); + if (block instanceof BlockChest) { + if (AzuriteConfig.optimizeHoppers.getValue()) { + TileEntity tile = world.getTileEntity(position); + ((TileEntityContainer) tile).setAsPull(toCache); + } + + return ((BlockChest) block).f(world, position); + } else if (block.isTileEntity()) { + TileEntity tile = world.getTileEntity(position); + + if (AzuriteConfig.optimizeHoppers.getValue()) { + if (tile instanceof TileEntityContainer) { + ((TileEntityContainer) tile).setAsPull(toCache); + return (IInventory) tile; + } + } else { + if (tile instanceof IInventory) return (IInventory) tile; + } + } + return null; + } + + public static IInventory getInventoryForPullingOptimizedPath(World world, BlockPosition position, TileEntityHopper toCache) { + if (!world.isValidLocation(position.getX(), position.getY(), position.getZ())) + return null; + Chunk chunk = world.getChunkIfLoaded(position.getX() >> 4, position.getZ() >> 4); + if (chunk == null) + return null; + Block block = world.getType(chunk, position).getBlock(); + if (block instanceof BlockChest) { + TileEntity tile = world.getTileEntity(position); + ((TileEntityContainer) tile).setAsPull(toCache); + + return ((BlockChest) block).f(world, position); + } else if (block.isTileEntity()) { + TileEntity tile = world.getTileEntity(position); + + if (tile instanceof TileEntityContainer) { + ((TileEntityContainer) tile).setAsPull(toCache); + return (IInventory) tile; + } + } + return null; + } + + public static IInventory getInventoryForPushing(World world, BlockPosition position, TileEntityHopper toCache) { + if (!world.isValidLocation(position.getX(), position.getY(), position.getZ())) + return null; + Chunk chunk = world.getChunkIfLoaded(position.getX() >> 4, position.getZ() >> 4); + if (chunk == null) + return null; + Block block = world.getType(chunk, position).getBlock(); + if (block instanceof BlockChest) { + if (AzuriteConfig.optimizeHoppers.getValue()) { + TileEntity tile = world.getTileEntity(position); + ((TileEntityContainer) tile).addAsPush(toCache); + } + + return ((BlockChest) block).f(world, position); + } else if (block.isTileEntity()) { + TileEntity tile = world.getTileEntity(position); + + if (AzuriteConfig.optimizeHoppers.getValue()) { + if (tile instanceof TileEntityContainer) { + ((TileEntityContainer) tile).addAsPush(toCache); + return (IInventory) tile; + } + } else { + if (tile instanceof IInventory) return (IInventory) tile; + } + } + return null; + } + + public static IInventory getInventoryForPushingOptimizedPath(World world, BlockPosition position, TileEntityHopper toCache) { + if (!world.isValidLocation(position.getX(), position.getY(), position.getZ())) + return null; + Chunk chunk = world.getChunkIfLoaded(position.getX() >> 4, position.getZ() >> 4); + if (chunk == null) + return null; + Block block = world.getType(chunk, position).getBlock(); + if (block instanceof BlockChest) { + TileEntity tile = world.getTileEntity(position); + ((TileEntityContainer) tile).addAsPush(toCache); + + return ((BlockChest) block).f(world, position); + } else if (block.isTileEntity()) { + TileEntity tile = world.getTileEntity(position); + + if (tile instanceof TileEntityContainer) { + ((TileEntityContainer) tile).addAsPush(toCache); + return (IInventory) tile; + } + } + return null; + } + + public static boolean isFireInventoryMoveItemEvent(IHopper hopper) { + return AzuriteConfig.fireHopperMoveItemEvent.getValue() && InventoryMoveItemEvent.getHandlerList().getRegisteredListeners().length > 0; + } +} diff --git a/azurite-server/src/main/java/net/techcable/tacospigot/HopperPusher.java b/azurite-server/src/main/java/net/techcable/tacospigot/HopperPusher.java new file mode 100644 index 0000000..35f4cd8 --- /dev/null +++ b/azurite-server/src/main/java/net/techcable/tacospigot/HopperPusher.java @@ -0,0 +1,47 @@ +package net.techcable.tacospigot; + +import net.minecraft.server.*; + +public interface HopperPusher { + + // Vortex - Optimized finding hoppers + default TileEntityHopper findHopper() { + int y1 = MathHelper.floor(getY()); + for (int y = y1; y > y1 - 2; y--) { + TileEntityHopper hopper = HopperHelper.getHopper(this.getWorld(), new BlockPosition(getX(), y, getZ())); + + if (hopper != null) { + if (y1 - y < 2) { + return hopper; + } + } + } + return null; + } + + boolean acceptItem(TileEntityHopper hopper); + + default boolean tryPutInHopper() { + TileEntityHopper hopper = findHopper(); + return hopper != null && hopper.canAcceptItems() && acceptItem(hopper); + } + + AxisAlignedBB getBoundingBox(); + + World getWorld(); + + // Default implementations for entities + + default double getX() { + return ((Entity) this).locX; + } + + default double getY() { + return ((Entity) this).locY; + } + + default double getZ() { + return ((Entity) this).locZ; + } + +} diff --git a/azurite-server/src/main/java/net/techcable/tacospigot/ImmutableArrayMap.java b/azurite-server/src/main/java/net/techcable/tacospigot/ImmutableArrayMap.java new file mode 100644 index 0000000..3a3bb56 --- /dev/null +++ b/azurite-server/src/main/java/net/techcable/tacospigot/ImmutableArrayMap.java @@ -0,0 +1,154 @@ +package net.techcable.tacospigot; + +import com.google.common.base.Preconditions; +import com.google.common.collect.Maps; + +import java.util.*; +import java.util.function.BiConsumer; + +public class ImmutableArrayMap extends AbstractMap implements Map { + private final Indexer indexer; + private final int offset; + private final Object[] data; + private final Object[] outlyingData; + private final Entry[] entries; + private final int[] outlyingIds; + + private final int size; + + @SuppressWarnings("Convert2Lambda") // The comparator is anonomous for performance reasons + public ImmutableArrayMap(Indexer getId, Map map) { + Preconditions.checkNotNull(getId, "Null getId function"); + Preconditions.checkNotNull(map, "Null map"); + this.indexer = getId; + this.size = map.size(); + this.keyComparator = new Comparator() { + @Override + public int compare(K o1, K o2) { + return Integer.compare(indexer.getId(o1), indexer.getId(o2)); + } + }; + Entry[] entries = new Entry[size]; + Iterator> iterator = map.entrySet().iterator(); + for (int i = 0; i < entries.length; i++) { + Preconditions.checkArgument(iterator.hasNext(), "Expected %s entries but only got %s", size, i + 1); + Entry entry = iterator.next(); + entries[i] = Maps.immutableEntry(entry.getKey(), entry.getValue()); + } + Arrays.sort(entries, (entry1, entry2) -> keyComparator.compare(entry1.getKey(), entry2.getKey())); + Preconditions.checkArgument(!iterator.hasNext(), "Got more than expected %s entries", size); + int[] ids = Arrays.stream(entries).map(Entry::getKey).mapToInt(indexer::getId).toArray(); // Don't worry, its sorted by key id ;) + int[] largestRangeOfSequentialValues = calculateLargestRangeOfSequentialValues(ids); + int minIndex = largestRangeOfSequentialValues == null ? -1 : largestRangeOfSequentialValues[0]; + int maxIndex = largestRangeOfSequentialValues == null ? -1 : largestRangeOfSequentialValues[1]; + int sequentalRangeSize = largestRangeOfSequentialValues == null ? 0 : largestRangeOfSequentialValues[2]; + this.data = new Object[sequentalRangeSize]; + this.outlyingIds = new int[size - sequentalRangeSize]; + this.outlyingData = new Object[size - sequentalRangeSize]; + this.offset = sequentalRangeSize == 0 ? 0 : ids[minIndex]; + this.entries = entries; + int outlyingIndex = 0; + for (int i = 0; i < entries.length; i++) { + Entry entry = entries[i]; + K key = entry.getKey(); + V value = entry.getValue(); + int id = indexer.getId(key); + Preconditions.checkArgument(id >= 0, "Negative id for %s: %s", key, id); + if (i >= minIndex && i < maxIndex) { + int index = id - offset; + data[index] = value; + } else { + int index = outlyingIndex++; + outlyingIds[index] = id; + outlyingData[index] = value; + } + } + } + + private final Comparator keyComparator; + + @Override + public int size() { + return size; + } + + @Override + public boolean containsKey(Object key) { + return get(key) != null; + } + + @Override + public V get(Object key) { + int id = indexer.getId((K) key); + int index = id - offset; + if (index >= 0 && index < data.length) { + return (V) data[index]; + } + int outlyingIndex = Arrays.binarySearch(outlyingIds, id); + if (outlyingIndex >= 0 && outlyingIndex < outlyingData.length) { + return (V) outlyingData[outlyingIndex]; + } else { + return null; + } + } + + @Override + public Set> entrySet() { + return new AbstractSet>() { + @Override + public Iterator> iterator() { + return Arrays.asList(entries).iterator(); + } + + @Override + public int size() { + return size; + } + }; + } + + @Override + public void forEach(BiConsumer action) { + for (Entry entry : entries) { + action.accept(entry.getKey(), entry.getValue()); + } + } + + @Override + public void clear() { + throw new UnsupportedOperationException(); + } + + @Override + public V put(K key, V value) { + throw new UnsupportedOperationException(); + } + + @Override + public V remove(Object key) { + throw new UnsupportedOperationException(); + } + + private static int[] calculateLargestRangeOfSequentialValues(int[] ids) { + int largestRangeSize = 0; + int[] largestRange = new int[3]; + for (int minIndex = 0; minIndex < ids.length; minIndex++) { + final int min = ids[minIndex]; + int lastNum = min; + int maxIndex; + for (maxIndex = minIndex + 1; maxIndex < ids.length; maxIndex++) { + final int max = ids[maxIndex]; + if (lastNum + 1 != max) break; // The number is not sequential + lastNum = max; + } + int rangeSize = maxIndex - minIndex; + if (rangeSize > largestRangeSize) { + largestRange[0] = minIndex; + largestRange[1] = maxIndex; + largestRange[2] = rangeSize; + largestRangeSize = rangeSize; + } + } + return largestRangeSize == 0 ? null : largestRange; + } +} diff --git a/azurite-server/src/main/java/net/techcable/tacospigot/ImmutableArrayTable.java b/azurite-server/src/main/java/net/techcable/tacospigot/ImmutableArrayTable.java new file mode 100644 index 0000000..42c30d6 --- /dev/null +++ b/azurite-server/src/main/java/net/techcable/tacospigot/ImmutableArrayTable.java @@ -0,0 +1,184 @@ +package net.techcable.tacospigot; + +import com.google.common.base.Preconditions; +import com.google.common.collect.Collections2; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Table; +import com.google.common.collect.Tables; + +import javax.annotation.Nullable; +import java.util.*; +import java.util.function.ToIntBiFunction; + +public class ImmutableArrayTable implements Table { + private final ImmutableArrayMap> rowMap; + private final ImmutableMap> columnMap; + private final int size; + + public ImmutableArrayTable(Indexer rowIndexer, ToIntBiFunction columnGetId, Table table) { + Preconditions.checkNotNull(table, "Null table"); + ImmutableMap.Builder> rowMapBuilder = ImmutableMap.builder(); + for (Map.Entry> rowEntry : table.rowMap().entrySet()) { + R row = rowEntry.getKey(); + Preconditions.checkNotNull(row, "Null row"); + ImmutableMap.Builder rowMapEntryBuilder = ImmutableMap.builder(); + for (Map.Entry rowEntryEntry : rowEntry.getValue().entrySet()) { + rowMapEntryBuilder.put(rowEntryEntry); + } + rowMapBuilder.put(row, new ImmutableArrayMap<>((c) -> columnGetId.applyAsInt(row, c), rowMapEntryBuilder.build())); + } + this.rowMap = new ImmutableArrayMap<>(rowIndexer, rowMapBuilder.build()); + Map> columnMapBuilder = new HashMap<>(); + int size = 0; + for (Cell cell : cellSet()) { + C column = cell.getColumnKey(); + V value = cell.getValue(); + Preconditions.checkNotNull(column, "Null column"); + Preconditions.checkNotNull(value, "Null value"); + Map columnEntry = columnMapBuilder.computeIfAbsent(column, (c) -> new HashMap<>()); + columnEntry.put(cell.getRowKey(), cell.getValue()); + size++; + } + this.size = size; + this.columnMap = ImmutableMap.copyOf(columnMapBuilder); + } + + @Override + public boolean contains(@Nullable Object rowKey, @Nullable Object columnKey) { + Map rowEntry = rowMap.get(rowKey); + return rowEntry != null && rowEntry.containsKey(columnKey); + } + + @Override + public boolean containsRow(@Nullable Object rowKey) { + return rowMap.containsKey(rowKey); + } + + @Override + public boolean containsColumn(@Nullable Object columnKey) { + return columnMap.containsKey(columnKey); + } + + @Override + public boolean containsValue(@Nullable Object value) { + Preconditions.checkNotNull(value, "Null value"); + for (V v : values()) { + if (v.equals(value)) return true; + } + return false; + } + + @Override + public V get(@Nullable Object rowKey, @Nullable Object columnKey) { + Map rowEntry = rowMap.get(rowKey); + return rowEntry != null ? rowEntry.get(columnKey) : null; + } + + @Override + public boolean isEmpty() { + return size() == 0; + } + + @Override + public int size() { + return size; + } + + @Override + public Map row(R rowKey) { + return rowMap.get(rowKey); + } + + @Override + public Map column(C columnKey) { + return columnMap.get(columnKey); + } + + @Override + public Set> cellSet() { + return new AbstractSet>() { + @Override + public Iterator> iterator() { + return new CellIterator(); + } + + @Override + public int size() { + return ImmutableArrayTable.this.size(); + } + }; + } + + @Override + public Set rowKeySet() { + return rowMap.keySet(); + } + + @Override + public Set columnKeySet() { + return columnMap.keySet(); + } + + @Override + public Collection values() { + return Collections2.transform(cellSet(), Cell::getValue); + } + + @Override + public Map> rowMap() { + return rowMap; + } + + @Override + public Map> columnMap() { + return columnMap; + } + + private class CellIterator implements Iterator> { + final Iterator>> rowIterator = rowMap.entrySet().iterator(); + Map.Entry> rowEntry; + Iterator> columnIterator = Collections.emptyIterator(); + + @Override + public boolean hasNext() { + return rowIterator.hasNext() || columnIterator.hasNext(); + } + + @Override + public Cell next() { + if (!columnIterator.hasNext()) { + rowEntry = rowIterator.next(); + columnIterator = rowEntry.getValue().entrySet().iterator(); + } + Map.Entry columnEntry = columnIterator.next(); + return Tables.immutableCell(rowEntry.getKey(), columnEntry.getKey(), columnEntry.getValue()); + } + + @Override + public void remove() { + throw new UnsupportedOperationException(); + } + } + + // Mutators + @Override + public void clear() { + throw new UnsupportedOperationException(); + } + + + @Override + public V put(R rowKey, C columnKey, V value) { + throw new UnsupportedOperationException(); + } + + @Override + public void putAll(Table table) { + throw new UnsupportedOperationException(); + } + + @Override + public V remove(@Nullable Object rowKey, @Nullable Object columnKey) { + throw new UnsupportedOperationException(); + } +} diff --git a/azurite-server/src/main/java/net/techcable/tacospigot/Indexer.java b/azurite-server/src/main/java/net/techcable/tacospigot/Indexer.java new file mode 100644 index 0000000..0417be3 --- /dev/null +++ b/azurite-server/src/main/java/net/techcable/tacospigot/Indexer.java @@ -0,0 +1,5 @@ +package net.techcable.tacospigot; + +public interface Indexer { + int getId(T t); +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftArt.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftArt.java new file mode 100644 index 0000000..6f94348 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftArt.java @@ -0,0 +1,74 @@ +package org.bukkit.craftbukkit; + +import net.minecraft.server.EntityPainting.EnumArt; +import org.bukkit.Art; + +// Safety class, will break if either side changes +public class CraftArt { + + public static Art NotchToBukkit(EnumArt art) { + switch (art) { + case KEBAB: return Art.KEBAB; + case AZTEC: return Art.AZTEC; + case ALBAN: return Art.ALBAN; + case AZTEC_2: return Art.AZTEC2; + case BOMB: return Art.BOMB; + case PLANT: return Art.PLANT; + case WASTELAND: return Art.WASTELAND; + case POOL: return Art.POOL; + case COURBET: return Art.COURBET; + case SEA: return Art.SEA; + case SUNSET: return Art.SUNSET; + case CREEBET: return Art.CREEBET; + case WANDERER: return Art.WANDERER; + case GRAHAM: return Art.GRAHAM; + case MATCH: return Art.MATCH; + case BUST: return Art.BUST; + case STAGE: return Art.STAGE; + case VOID: return Art.VOID; + case SKULL_AND_ROSES: return Art.SKULL_AND_ROSES; + case FIGHTERS: return Art.FIGHTERS; + case POINTER: return Art.POINTER; + case PIGSCENE: return Art.PIGSCENE; + case BURNING_SKULL: return Art.BURNINGSKULL; + case SKELETON: return Art.SKELETON; + case DONKEY_KONG: return Art.DONKEYKONG; + case WITHER: return Art.WITHER; + default: + throw new AssertionError(art); + } + } + + public static EnumArt BukkitToNotch(Art art) { + switch (art) { + case KEBAB: return EnumArt.KEBAB; + case AZTEC: return EnumArt.AZTEC; + case ALBAN: return EnumArt.ALBAN; + case AZTEC2: return EnumArt.AZTEC_2; + case BOMB: return EnumArt.BOMB; + case PLANT: return EnumArt.PLANT; + case WASTELAND: return EnumArt.WASTELAND; + case POOL: return EnumArt.POOL; + case COURBET: return EnumArt.COURBET; + case SEA: return EnumArt.SEA; + case SUNSET: return EnumArt.SUNSET; + case CREEBET: return EnumArt.CREEBET; + case WANDERER: return EnumArt.WANDERER; + case GRAHAM: return EnumArt.GRAHAM; + case MATCH: return EnumArt.MATCH; + case BUST: return EnumArt.BUST; + case STAGE: return EnumArt.STAGE; + case VOID: return EnumArt.VOID; + case SKULL_AND_ROSES: return EnumArt.SKULL_AND_ROSES; + case FIGHTERS: return EnumArt.FIGHTERS; + case POINTER: return EnumArt.POINTER; + case PIGSCENE: return EnumArt.PIGSCENE; + case BURNINGSKULL: return EnumArt.BURNING_SKULL; + case SKELETON: return EnumArt.SKELETON; + case DONKEYKONG: return EnumArt.DONKEY_KONG; + case WITHER: return EnumArt.WITHER; + default: + throw new AssertionError(art); + } + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftChunk.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftChunk.java new file mode 100644 index 0000000..97aaa54 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftChunk.java @@ -0,0 +1,387 @@ +package org.bukkit.craftbukkit; + +import dev.azurite.spigot.api.chunk.ChunkSectionSnapshot; +import net.minecraft.server.*; +import org.bukkit.Chunk; +import org.bukkit.ChunkSnapshot; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.block.BlockState; +import org.bukkit.craftbukkit.block.CraftBlock; +import org.bukkit.craftbukkit.entity.CraftHumanEntity; +import org.bukkit.entity.Entity; +import org.bukkit.entity.HumanEntity; + +import java.lang.ref.WeakReference; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Map; + +public class CraftChunk implements Chunk { + private static final byte[] emptyData = new byte[2048]; + private static final short[] emptyBlockIDs = new short[4096]; + private static final byte[] emptySkyLight = new byte[2048]; + + static { + Arrays.fill(emptySkyLight, (byte) 0xFF); + } + + private final WorldServer worldServer; + private final int x; + private final int z; + private WeakReference weakChunk; + + public CraftChunk(net.minecraft.server.Chunk chunk) { + if (!(chunk instanceof EmptyChunk)) { + this.weakChunk = new WeakReference<>(chunk); + } + + worldServer = (WorldServer) getHandle().world; + x = getHandle().locX; + z = getHandle().locZ; + } + + public int getEntityCount() { + int count = 0; + net.minecraft.server.Chunk chunk = getHandle(); + for (int i = 0; i < 16; i++) { + count += chunk.entitySlices[i].size(); + } + return count; + } + + public static ChunkSnapshot getEmptyChunkSnapshot(int x, int z, CraftWorld world, boolean includeBiome, boolean includeBiomeTempRain) { + BiomeBase[] biome = null; + double[] biomeTemp = null; + double[] biomeRain = null; + + if (includeBiome || includeBiomeTempRain) { + WorldChunkManager wcm = world.getHandle().getWorldChunkManager(); + + if (includeBiome) { + biome = new BiomeBase[256]; + for (int i = 0; i < 256; i++) { + biome[i] = world.getHandle().getBiome((x << 4) + (i & 0xF), 0, (z << 4) + (i >> 4)); + } + } + + if (includeBiomeTempRain) { + biomeTemp = new double[256]; + biomeRain = new double[256]; + float[] dat = getTemperatures(wcm, x << 4, z << 4); + + for (int i = 0; i < 256; i++) { + biomeTemp[i] = dat[i]; + } + + dat = wcm.getWetness(null, x << 4, z << 4, 16, 16); + + for (int i = 0; i < 256; i++) { + biomeRain[i] = dat[i]; + } + } + } + + /* Fill with empty data */ + int hSection = world.getMaxHeight() >> 4; + short[][] blockIDs = new short[hSection][]; + byte[][] skyLight = new byte[hSection][]; + byte[][] emitLight = new byte[hSection][]; + byte[][] blockData = new byte[hSection][]; + boolean[] empty = new boolean[hSection]; + + for (int i = 0; i < hSection; i++) { + blockIDs[i] = emptyBlockIDs; + skyLight[i] = emptySkyLight; + emitLight[i] = emptyData; + blockData[i] = emptyData; + empty[i] = true; + } + + return new CraftChunkSnapshot(x, z, world.getName(), world.getFullTime(), blockIDs, blockData, skyLight, emitLight, empty, new int[256], biome, biomeTemp, biomeRain); + } + + private static float[] getTemperatures(WorldChunkManager chunkmanager, int chunkX, int chunkZ) { + BiomeBase[] biomes = chunkmanager.getBiomes(null, chunkX, chunkZ, 16, 16); + float[] temps = new float[biomes.length]; + + for (int i = 0; i < biomes.length; i++) { + float temp = biomes[i].temperature; // Vanilla of olde: ((int) biomes[i].temperature * 65536.0F) / 65536.0F + + if (temp > 1F) { + temp = 1F; + } + + temps[i] = temp; + } + + return temps; + } + + public World getWorld() { + return worldServer.getWorld(); + } + + public CraftWorld getCraftWorld() { + return (CraftWorld) getWorld(); + } + + public net.minecraft.server.Chunk getHandle() { + net.minecraft.server.Chunk c = weakChunk.get(); + + if (c == null) { + c = worldServer.getChunkAt(x, z); + + if (!(c instanceof EmptyChunk)) { + weakChunk = new WeakReference<>(c); + } + } + + return c; + } + + void breakLink() { + weakChunk.clear(); + } + + public int getX() { + return x; + } + + public int getZ() { + return z; + } + + @Override + public String toString() { + return "CraftChunk{" + "x=" + getX() + "z=" + getZ() + '}'; + } + + public Block getBlock(int x, int y, int z) { + return new CraftBlock(this, (getX() << 4) | (x & 0xF), y, (getZ() << 4) | (z & 0xF)); + } + + public Entity[] getEntities() { + int count = 0, index = 0; + net.minecraft.server.Chunk chunk = getHandle(); + + for (int i = 0; i < 16; i++) { + count += chunk.entitySlices[i].size(); + } + + Entity[] entities = new Entity[count]; + + for (int i = 0; i < 16; i++) { + + for (net.minecraft.server.Entity entity : chunk.entitySlices[i]) { + if (entity != null) + entities[index++] = entity.getBukkitEntity(); + } + } + + return entities; + } + + public BlockState[] getTileEntities() { + int index = 0; + net.minecraft.server.Chunk chunk = getHandle(); + + BlockState[] entities = new BlockState[chunk.tileEntities.size()]; + + for (Object obj : chunk.tileEntities.keySet().toArray()) { + if (!(obj instanceof BlockPosition)) { + continue; + } + + BlockPosition position = (BlockPosition) obj; + entities[index++] = worldServer.getWorld().getBlockAt(position.getX(), position.getY(), position.getZ()).getState(); + } + + return entities; + } + + public boolean isLoaded() { + return getWorld().isChunkLoaded(this); + } + + public boolean load() { + return getWorld().loadChunk(getX(), getZ(), true); + } + + public boolean load(boolean generate) { + return getWorld().loadChunk(getX(), getZ(), generate); + } + + public boolean unload() { + return getWorld().unloadChunk(getX(), getZ()); + } + + public boolean unload(boolean save) { + return getWorld().unloadChunk(getX(), getZ(), save); + } + + public boolean unload(boolean save, boolean safe) { + return getWorld().unloadChunk(getX(), getZ(), save, safe); + } + + public ChunkSnapshot getChunkSnapshot() { + return getChunkSnapshot(true, false, false); + } + + public ChunkSnapshot getChunkSnapshot(boolean includeMaxBlockY, boolean includeBiome, boolean includeBiomeTempRain) { + net.minecraft.server.Chunk chunk = getHandle(); + + ChunkSection[] cs = chunk.getSections(); + short[][] sectionBlockIDs = new short[cs.length][]; + byte[][] sectionBlockData = new byte[cs.length][]; + byte[][] sectionSkyLights = new byte[cs.length][]; + byte[][] sectionEmitLights = new byte[cs.length][]; + boolean[] sectionEmpty = new boolean[cs.length]; + + for (int i = 0; i < cs.length; i++) { + if (cs[i] == null) { // Section is empty? + sectionBlockIDs[i] = emptyBlockIDs; + sectionBlockData[i] = emptyData; + sectionSkyLights[i] = emptySkyLight; + sectionEmitLights[i] = emptyData; + sectionEmpty[i] = true; + } else { // Not empty + short[] blockids = new short[4096]; + char[] baseids = cs[i].getIdArray(); + byte[] dataValues = sectionBlockData[i] = new byte[2048]; + + // Copy base IDs + for (int j = 0; j < 4096; j++) { + if (baseids[j] == 0) continue; + IBlockData blockData = net.minecraft.server.Block.d.a(baseids[j]); + if (blockData == null) continue; + blockids[j] = (short) net.minecraft.server.Block.getId(blockData.getBlock()); + int data = blockData.getBlock().toLegacyData(blockData); + int jj = j >> 1; + if ((j & 1) == 0) { + dataValues[jj] = (byte) ((dataValues[jj] & 0xF0) | (data & 0xF)); + } else { + dataValues[jj] = (byte) ((dataValues[jj] & 0xF) | ((data & 0xF) << 4)); + } + } + + sectionBlockIDs[i] = blockids; + + if (cs[i].getSkyLightArray() == null) { + sectionSkyLights[i] = emptyData; + } else { + sectionSkyLights[i] = new byte[2048]; + System.arraycopy(cs[i].getSkyLightArray().a(), 0, sectionSkyLights[i], 0, 2048); + } + sectionEmitLights[i] = new byte[2048]; + System.arraycopy(cs[i].getEmittedLightArray().a(), 0, sectionEmitLights[i], 0, 2048); + } + } + + int[] hmap = null; + + if (includeMaxBlockY) { + hmap = new int[256]; // Get copy of height map + System.arraycopy(chunk.heightMap, 0, hmap, 0, 256); + } + + BiomeBase[] biome = null; + double[] biomeTemp = null; + double[] biomeRain = null; + + if (includeBiome || includeBiomeTempRain) { + WorldChunkManager wcm = chunk.world.getWorldChunkManager(); + + if (includeBiome) { + biome = new BiomeBase[256]; + for (int i = 0; i < 256; i++) { + biome[i] = chunk.getBiome(i & 0xF, i >> 4, wcm); + } + } + + if (includeBiomeTempRain) { + biomeTemp = new double[256]; + biomeRain = new double[256]; + float[] dat = getTemperatures(wcm, getX() << 4, getZ() << 4); + + for (int i = 0; i < 256; i++) { + biomeTemp[i] = dat[i]; + } + + dat = wcm.getWetness(null, getX() << 4, getZ() << 4, 16, 16); + + for (int i = 0; i < 256; i++) { + biomeRain[i] = dat[i]; + } + } + } + + World world = getWorld(); + return new CraftChunkSnapshot(getX(), getZ(), world.getName(), world.getFullTime(), sectionBlockIDs, sectionBlockData, sectionSkyLights, sectionEmitLights, sectionEmpty, hmap, biome, biomeTemp, biomeRain); + } + + @Override + public dev.azurite.spigot.api.chunk.ChunkSnapshot takeSnapshot() { + net.minecraft.server.Chunk handle = getHandle(); + dev.azurite.spigot.api.chunk.CraftChunkSnapshot snap = new dev.azurite.spigot.api.chunk.CraftChunkSnapshot(); + + // save chunk sections to snapshot + for (int i = 0; i < 16; i++) { + ChunkSection section = handle.getSections()[i]; + if (section != null) { + snap.getSections()[i] = section.createSnapshot(); + } + } + + // save tile entities to snapshot + for ( Map.Entry entry : handle.tileEntities.entrySet()) { + NBTTagCompound nbt = new NBTTagCompound(); + entry.getValue().b(nbt); // writeToNBT + snap.getTileEntities().add(nbt); + } + return snap; + } + + @Override + public void restoreSnapshot(dev.azurite.spigot.api.chunk.ChunkSnapshot snapshot) { + dev.azurite.spigot.api.chunk.CraftChunkSnapshot snap = (dev.azurite.spigot.api.chunk.CraftChunkSnapshot) snapshot; + net.minecraft.server.Chunk handle = getHandle(); + + // add chunk sections from snapshot + for (int i = 0; i < 16; i++) { + ChunkSectionSnapshot section = snap.getSections()[i]; + if (section == null) { + handle.getSections()[i] = null; + } else { + handle.getSections()[i] = new ChunkSection(i << 4, !this.worldServer.worldProvider.o(), handle.getWorld().shouldSectionsHaveTickList()); + handle.getSections()[i].restoreSnapshot(section); + } + } + + // clear tile entities currently in the chunk + for (TileEntity tileEntity : handle.tileEntities.values()) { + if (tileEntity instanceof IInventory) { + for ( HumanEntity h : new ArrayList<>(((IInventory) tileEntity).getViewers())) { + if (h instanceof CraftHumanEntity) { + ((CraftHumanEntity) h).getHandle().closeInventory(); + } + } + } + worldServer.a(tileEntity); + } + handle.tileEntities.clear(); + + // add tile entities from snapshot + for (NBTTagCompound nbt : snap.getTileEntities()) { + // deserialize nbt to new tile entity instance + TileEntity tileEntity = TileEntity.c(nbt); + // move the tile entity into this chunk's space + tileEntity.position.setX((tileEntity.position.getX() & 15) | handle.locX << 4); + tileEntity.position.setZ((tileEntity.position.getZ() & 15) | handle.locZ << 4); + // add it + handle.a(tileEntity); + } + handle.q = true; // needs saving flag + worldServer.getPlayerChunkMap().resend(x, z); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftChunkSnapshot.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftChunkSnapshot.java new file mode 100644 index 0000000..273b854 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftChunkSnapshot.java @@ -0,0 +1,96 @@ +package org.bukkit.craftbukkit; + +import net.minecraft.server.BiomeBase; +import org.bukkit.ChunkSnapshot; +import org.bukkit.block.Biome; +import org.bukkit.craftbukkit.block.CraftBlock; + +/** + * Represents a static, thread-safe snapshot of chunk of blocks + * Purpose is to allow clean, efficient copy of a chunk data to be made, and then handed off for processing in another thread (e.g. map rendering) + */ +public class CraftChunkSnapshot implements ChunkSnapshot { + private final int x, z; + private final String worldname; + private final short[][] blockids; /* Block IDs, by section */ + private final byte[][] blockdata; + private final byte[][] skylight; + private final byte[][] emitlight; + private final boolean[] empty; + private final int[] hmap; // Height map + private final long captureFulltime; + private final BiomeBase[] biome; + private final double[] biomeTemp; + private final double[] biomeRain; + + CraftChunkSnapshot(int x, int z, String wname, long wtime, short[][] sectionBlockIDs, byte[][] sectionBlockData, byte[][] sectionSkyLights, byte[][] sectionEmitLights, boolean[] sectionEmpty, int[] hmap, BiomeBase[] biome, double[] biomeTemp, double[] biomeRain) { + this.x = x; + this.z = z; + this.worldname = wname; + this.captureFulltime = wtime; + this.blockids = sectionBlockIDs; + this.blockdata = sectionBlockData; + this.skylight = sectionSkyLights; + this.emitlight = sectionEmitLights; + this.empty = sectionEmpty; + this.hmap = hmap; + this.biome = biome; + this.biomeTemp = biomeTemp; + this.biomeRain = biomeRain; + } + + public int getX() { + return x; + } + + public int getZ() { + return z; + } + + public String getWorldName() { + return worldname; + } + + public final int getBlockTypeId(int x, int y, int z) { + return blockids[y >> 4][((y & 0xF) << 8) | (z << 4) | x]; + } + + public final int getBlockData(int x, int y, int z) { + int off = ((y & 0xF) << 7) | (z << 3) | (x >> 1); + return (blockdata[y >> 4][off] >> ((x & 1) << 2)) & 0xF; + } + + public final int getBlockSkyLight(int x, int y, int z) { + int off = ((y & 0xF) << 7) | (z << 3) | (x >> 1); + return (skylight[y >> 4][off] >> ((x & 1) << 2)) & 0xF; + } + + public final int getBlockEmittedLight(int x, int y, int z) { + int off = ((y & 0xF) << 7) | (z << 3) | (x >> 1); + return (emitlight[y >> 4][off] >> ((x & 1) << 2)) & 0xF; + } + + public final int getHighestBlockYAt(int x, int z) { + return hmap[z << 4 | x]; + } + + public final Biome getBiome(int x, int z) { + return CraftBlock.biomeBaseToBiome(biome[z << 4 | x]); + } + + public final double getRawBiomeTemperature(int x, int z) { + return biomeTemp[z << 4 | x]; + } + + public final double getRawBiomeRainfall(int x, int z) { + return biomeRain[z << 4 | x]; + } + + public final long getCaptureFullTime() { + return captureFulltime; + } + + public final boolean isSectionEmpty(int sy) { + return empty[sy]; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftCrashReport.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftCrashReport.java new file mode 100644 index 0000000..de84dbc --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftCrashReport.java @@ -0,0 +1,41 @@ +package org.bukkit.craftbukkit; + +import net.minecraft.server.MinecraftServer; +import org.bukkit.Bukkit; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.PluginDescriptionFile; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.Arrays; +import java.util.Map; +import java.util.concurrent.Callable; + +public class CraftCrashReport implements Callable { + + public String call() throws Exception { + StringWriter value = new StringWriter(); + try { + value.append("\n Running: ").append(Bukkit.getName()).append(" version ").append(Bukkit.getVersion()).append(" (Implementing API version ").append(Bukkit.getBukkitVersion()).append(") ").append(String.valueOf(MinecraftServer.getServer().getOnlineMode())); + value.append("\n Plugins: {"); + for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) { + PluginDescriptionFile description = plugin.getDescription(); + value.append(' ').append(description.getFullName()).append(' ').append(description.getMain()).append(' ').append(Arrays.toString(description.getAuthors().toArray())).append(','); + } + value.append("}\n Warnings: ").append(Bukkit.getWarningState().name()); + value.append("\n Reload Count: ").append(String.valueOf(MinecraftServer.getServer().server.reloadCount)); + value.append("\n Threads: {"); + for (Map.Entry entry : Thread.getAllStackTraces().entrySet()) { + value.append(' ').append(entry.getKey().getState().name()).append(' ').append(entry.getKey().getName()).append(": ").append(Arrays.toString(entry.getValue())).append(','); + } + value.append("}\n ").append(Bukkit.getScheduler().toString()); + } catch (Throwable t) { + value.append("\n Failed to handle CraftCrashReport:\n"); + PrintWriter writer = new PrintWriter(value); + t.printStackTrace(writer); + writer.flush(); + } + return value.toString(); + } + +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftEffect.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftEffect.java new file mode 100644 index 0000000..13f9e9d --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftEffect.java @@ -0,0 +1,66 @@ +package org.bukkit.craftbukkit; + +import org.apache.commons.lang.Validate; +import org.bukkit.Effect; +import org.bukkit.Material; +import org.bukkit.block.BlockFace; +import org.bukkit.potion.Potion; + +public class CraftEffect { + public static int getDataValue(Effect effect, T data) { + int datavalue; + switch(effect) { + case POTION_BREAK: + datavalue = ((Potion) data).toDamageValue() & 0x3F; + break; + case RECORD_PLAY: + Validate.isTrue(((Material) data).isRecord(), "Invalid record type!"); + datavalue = ((Material) data).getId(); + break; + case SMOKE: + switch((BlockFace) data) { // TODO: Verify (Where did these values come from...?) + case SOUTH_EAST: + datavalue = 0; + break; + case SOUTH: + datavalue = 1; + break; + case SOUTH_WEST: + datavalue = 2; + break; + case EAST: + datavalue = 3; + break; + case UP: + case SELF: + datavalue = 4; + break; + case WEST: + datavalue = 5; + break; + case NORTH_EAST: + datavalue = 6; + break; + case NORTH: + datavalue = 7; + break; + case NORTH_WEST: + datavalue = 8; + break; + default: + throw new IllegalArgumentException("Bad smoke direction!"); + } + break; + case STEP_SOUND: + Validate.isTrue(((Material) data).isBlock(), "Material is not a block!"); + datavalue = ((Material) data).getId(); + break; + case ITEM_BREAK: + datavalue = ((Material) data).getId(); + break; + default: + datavalue = 0; + } + return datavalue; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftEquipmentSlot.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftEquipmentSlot.java new file mode 100644 index 0000000..a33f446 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftEquipmentSlot.java @@ -0,0 +1,35 @@ +package org.bukkit.craftbukkit; + +import org.bukkit.inventory.EquipmentSlot; + +public class CraftEquipmentSlot { + + private static final int[] slots = new int[EquipmentSlot.values().length]; + private static final EquipmentSlot[] enums = new EquipmentSlot[EquipmentSlot.values().length]; + + static { + set(EquipmentSlot.HAND, 0); + set(EquipmentSlot.FEET, 1); + set(EquipmentSlot.LEGS, 2); + set(EquipmentSlot.CHEST, 3); + set(EquipmentSlot.HEAD, 4); + } + + private static void set(EquipmentSlot type, int value) { + slots[type.ordinal()] = value; + if (value < enums.length) { + enums[value] = type; + } + } + + public static EquipmentSlot getSlot(int magic) { + if (magic > 0 && magic < enums.length) { + return enums[magic]; + } + return null; + } + + public static int getSlotIndex(EquipmentSlot slot) { + return slots[slot.ordinal()]; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftIpBanEntry.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftIpBanEntry.java new file mode 100644 index 0000000..040a779 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftIpBanEntry.java @@ -0,0 +1,87 @@ +package org.bukkit.craftbukkit; + +import net.minecraft.server.IpBanEntry; +import net.minecraft.server.IpBanList; +import org.bukkit.Bukkit; + +import java.io.IOException; +import java.util.Date; +import java.util.logging.Level; + +public final class CraftIpBanEntry implements org.bukkit.BanEntry { + private final IpBanList list; + private final String target; + private Date created; + private String source; + private Date expiration; + private String reason; + + public CraftIpBanEntry(String target, IpBanEntry entry, IpBanList list) { + this.list = list; + this.target = target; + this.created = entry.getCreated() != null ? new Date(entry.getCreated().getTime()) : null; + this.source = entry.getSource(); + this.expiration = entry.getExpires() != null ? new Date(entry.getExpires().getTime()) : null; + this.reason = entry.getReason(); + } + + @Override + public String getTarget() { + return this.target; + } + + @Override + public Date getCreated() { + return this.created == null ? null : (Date) this.created.clone(); + } + + @Override + public void setCreated(Date created) { + this.created = created; + } + + @Override + public String getSource() { + return this.source; + } + + @Override + public void setSource(String source) { + this.source = source; + } + + @Override + public Date getExpiration() { + return this.expiration == null ? null : (Date) this.expiration.clone(); + } + + @Override + public void setExpiration(Date expiration) { + if (expiration != null && expiration.getTime() == new Date(0, 0, 0, 0, 0, 0).getTime()) { + expiration = null; // Forces "forever" + } + + this.expiration = expiration; + } + + @Override + public String getReason() { + return this.reason; + } + + @Override + public void setReason(String reason) { + this.reason = reason; + } + + @Override + public void save() { + IpBanEntry entry = new IpBanEntry(target, this.created, this.source, this.expiration, this.reason); + this.list.add(entry); + try { + this.list.save(); + } catch (IOException ex) { + Bukkit.getLogger().log(Level.SEVERE, "Failed to save banned-ips.json, {0}", ex.getMessage()); + } + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftIpBanList.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftIpBanList.java new file mode 100644 index 0000000..eb96f04 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftIpBanList.java @@ -0,0 +1,77 @@ +package org.bukkit.craftbukkit; + +import com.google.common.collect.ImmutableSet; +import net.minecraft.server.IpBanEntry; +import net.minecraft.server.IpBanList; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.util.Date; +import java.util.Set; +import java.util.logging.Level; + +public class CraftIpBanList implements org.bukkit.BanList { + private final IpBanList list; + + public CraftIpBanList(IpBanList list) { + this.list = list; + } + + @Override + public org.bukkit.BanEntry getBanEntry(String target) { + Validate.notNull(target, "Target cannot be null"); + + IpBanEntry entry = list.get(target); + if (entry == null) { + return null; + } + + return new CraftIpBanEntry(target, entry, list); + } + + @Override + public org.bukkit.BanEntry addBan(String target, String reason, Date expires, String source) { + Validate.notNull(target, "Ban target cannot be null"); + + IpBanEntry entry = new IpBanEntry(target, new Date(), + StringUtils.isBlank(source) ? null : source, expires, + StringUtils.isBlank(reason) ? null : reason); + + list.add(entry); + + try { + list.save(); + } catch (IOException ex) { + Bukkit.getLogger().log(Level.SEVERE, "Failed to save banned-ips.json, {0}", ex.getMessage()); + } + + return new CraftIpBanEntry(target, entry, list); + } + + @Override + public Set getBanEntries() { + ImmutableSet.Builder builder = ImmutableSet.builder(); + for (String target : list.getEntries()) { + builder.add(new CraftIpBanEntry(target, list.get(target), list)); + } + + return builder.build(); + } + + @Override + public boolean isBanned(String target) { + Validate.notNull(target, "Target cannot be null"); + + return list.isBanned(InetSocketAddress.createUnresolved(target, 0)); + } + + @Override + public void pardon(String target) { + Validate.notNull(target, "Target cannot be null"); + + list.remove(target); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftOfflinePlayer.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftOfflinePlayer.java new file mode 100644 index 0000000..aa35c63 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftOfflinePlayer.java @@ -0,0 +1,255 @@ +package org.bukkit.craftbukkit; + +import com.eatthepath.uuid.FastUUID; +import com.mojang.authlib.GameProfile; +import net.minecraft.server.NBTTagCompound; +import net.minecraft.server.WorldNBTStorage; +import org.bukkit.*; +import org.bukkit.configuration.serialization.ConfigurationSerializable; +import org.bukkit.configuration.serialization.SerializableAs; +import org.bukkit.entity.Player; +import org.bukkit.metadata.MetadataValue; +import org.bukkit.plugin.Plugin; + +import java.io.File; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +@SerializableAs("Player") +public class CraftOfflinePlayer implements OfflinePlayer, ConfigurationSerializable { + private final GameProfile profile; + private final CraftServer server; + private final WorldNBTStorage storage; + + protected CraftOfflinePlayer(CraftServer server, GameProfile profile) { + this.server = server; + this.profile = profile; + this.storage = (WorldNBTStorage) (server.console.worlds.get(0).getDataManager()); + } + + public GameProfile getProfile() { + return profile; + } + + public boolean isOnline() { + return getPlayer() != null; + } + + public String getName() { + Player player = getPlayer(); + if (player != null) { + return player.getName(); + } + + // This might not match lastKnownName but if not it should be more correct + if (profile.getName() != null) { + return profile.getName(); + } + + NBTTagCompound data = getBukkitData(); + + if (data != null) { + if (data.hasKey("lastKnownName")) { + return data.getString("lastKnownName"); + } + } + + return null; + } + + public UUID getUniqueId() { + return profile.getId(); + } + + public Server getServer() { + return server; + } + + public boolean isOp() { + return server.getHandle().isOp(profile); + } + + public void setOp(boolean value) { + if (value == isOp()) { + return; + } + + if (value) { + server.getHandle().addOp(profile); + } else { + server.getHandle().removeOp(profile); + } + } + + public boolean isBanned() { + if (getName() == null) { + return false; + } + + return server.getBanList(BanList.Type.NAME).isBanned(getName()); + } + + public void setBanned(boolean value) { + if (getName() == null) { + return; + } + + if (value) { + server.getBanList(BanList.Type.NAME).addBan(getName(), null, null, null); + } else { + server.getBanList(BanList.Type.NAME).pardon(getName()); + } + } + + public boolean isWhitelisted() { + return server.getHandle().getWhitelist().isWhitelisted(profile); + } + + public void setWhitelisted(boolean value) { + if (value) { + server.getHandle().addWhitelist(profile); + } else { + server.getHandle().removeWhitelist(profile); + } + } + + public Map serialize() { + Map result = new LinkedHashMap<>(); + + result.put("UUID", profile.getId().toString()); + + return result; + } + + public static OfflinePlayer deserialize(Map args) { + // Backwards comparability + if (args.get("name") != null) { + return Bukkit.getServer().getOfflinePlayer((String) args.get("name")); + } + + return Bukkit.getServer().getOfflinePlayer(FastUUID.parseUUID((String) args.get("UUID"))); + } + + @Override + public String toString() { + return getClass().getSimpleName() + "[UUID=" + profile.getId() + "]"; + } + + public Player getPlayer() { + return server.getPlayer(getUniqueId()); + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof OfflinePlayer)) { + return false; + } + + OfflinePlayer other = (OfflinePlayer) obj; + if ((this.getUniqueId() == null) || (other.getUniqueId() == null)) { + return false; + } + + return this.getUniqueId().equals(other.getUniqueId()); + } + + @Override + public int hashCode() { + int hash = 5; + hash = 97 * hash + (this.getUniqueId() != null ? this.getUniqueId().hashCode() : 0); + return hash; + } + + private NBTTagCompound getData() { + return storage.getPlayerData(getUniqueId().toString()); + } + + private NBTTagCompound getBukkitData() { + NBTTagCompound result = getData(); + + if (result != null) { + if (!result.hasKey("bukkit")) { + result.set("bukkit", new NBTTagCompound()); + } + result = result.getCompound("bukkit"); + } + + return result; + } + + private File getDataFile() { + return new File(storage.getPlayerDir(), getUniqueId() + ".dat"); + } + + public long getFirstPlayed() { + Player player = getPlayer(); + if (player != null) return player.getFirstPlayed(); + + NBTTagCompound data = getBukkitData(); + + if (data != null) { + if (data.hasKey("firstPlayed")) { + return data.getLong("firstPlayed"); + } else { + File file = getDataFile(); + return file.lastModified(); + } + } else { + return 0; + } + } + + public long getLastPlayed() { + Player player = getPlayer(); + if (player != null) return player.getLastPlayed(); + + NBTTagCompound data = getBukkitData(); + + if (data != null) { + if (data.hasKey("lastPlayed")) { + return data.getLong("lastPlayed"); + } else { + File file = getDataFile(); + return file.lastModified(); + } + } else { + return 0; + } + } + + public boolean hasPlayedBefore() { + return getData() != null; + } + + public Location getBedSpawnLocation() { + NBTTagCompound data = getData(); + if (data == null) return null; + + if (data.hasKey("SpawnX") && data.hasKey("SpawnY") && data.hasKey("SpawnZ")) { + String spawnWorld = data.getString("SpawnWorld"); + if (spawnWorld.equals("")) { + spawnWorld = server.getWorlds().get(0).getName(); + } + return new Location(server.getWorld(spawnWorld), data.getInt("SpawnX"), data.getInt("SpawnY"), data.getInt("SpawnZ")); + } + return null; + } + + public void setMetadata(String metadataKey, MetadataValue metadataValue) { + server.getPlayerMetadata().setMetadata(this, metadataKey, metadataValue); + } + + public List getMetadata(String metadataKey) { + return server.getPlayerMetadata().getMetadata(this, metadataKey); + } + + public boolean hasMetadata(String metadataKey) { + return server.getPlayerMetadata().hasMetadata(this, metadataKey); + } + + public void removeMetadata(String metadataKey, Plugin plugin) { + server.getPlayerMetadata().removeMetadata(this, metadataKey, plugin); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftProfileBanEntry.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftProfileBanEntry.java new file mode 100644 index 0000000..97a8236 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftProfileBanEntry.java @@ -0,0 +1,89 @@ +package org.bukkit.craftbukkit; + +import com.mojang.authlib.GameProfile; +import net.minecraft.server.GameProfileBanEntry; +import net.minecraft.server.GameProfileBanList; +import org.bukkit.Bukkit; + +import java.io.IOException; +import java.util.Calendar; +import java.util.Date; +import java.util.logging.Level; + +public final class CraftProfileBanEntry implements org.bukkit.BanEntry { + private final GameProfileBanList list; + private final GameProfile profile; + private Date created; + private String source; + private Date expiration; + private String reason; + + public CraftProfileBanEntry(GameProfile profile, GameProfileBanEntry entry, GameProfileBanList list) { + this.list = list; + this.profile = profile; + this.created = entry.getCreated() != null ? new Date(entry.getCreated().getTime()) : null; + this.source = entry.getSource(); + this.expiration = entry.getExpires() != null ? new Date(entry.getExpires().getTime()) : null; + this.reason = entry.getReason(); + } + + @Override + public String getTarget() { + return this.profile.getName(); + } + + @Override + public Date getCreated() { + return this.created == null ? null : (Date) this.created.clone(); + } + + @Override + public void setCreated(Date created) { + this.created = created; + } + + @Override + public String getSource() { + return this.source; + } + + @Override + public void setSource(String source) { + this.source = source; + } + + @Override + public Date getExpiration() { + return this.expiration == null ? null : (Date) this.expiration.clone(); + } + + @Override + public void setExpiration(Date expiration) { + if (expiration != null && expiration.getTime() == new Date(0, Calendar.JANUARY, 0, 0, 0, 0).getTime()) { + expiration = null; // Forces "forever" + } + + this.expiration = expiration; + } + + @Override + public String getReason() { + return this.reason; + } + + @Override + public void setReason(String reason) { + this.reason = reason; + } + + @Override + public void save() { + GameProfileBanEntry entry = new GameProfileBanEntry(profile, this.created, this.source, this.expiration, this.reason); + this.list.add(entry); + try { + this.list.save(); + } catch (IOException ex) { + Bukkit.getLogger().log(Level.SEVERE, "Failed to save banned-players.json, {0}", ex.getMessage()); + } + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftProfileBanList.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftProfileBanList.java new file mode 100644 index 0000000..4272a8e --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftProfileBanList.java @@ -0,0 +1,96 @@ +package org.bukkit.craftbukkit; + +import com.google.common.collect.ImmutableSet; +import com.mojang.authlib.GameProfile; +import net.minecraft.server.GameProfileBanEntry; +import net.minecraft.server.GameProfileBanList; +import net.minecraft.server.MinecraftServer; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; + +import java.io.IOException; +import java.util.Date; +import java.util.Set; +import java.util.logging.Level; + +public class CraftProfileBanList implements org.bukkit.BanList { + private final GameProfileBanList list; + + public CraftProfileBanList(GameProfileBanList list){ + this.list = list; + } + + @Override + public org.bukkit.BanEntry getBanEntry(String target) { + Validate.notNull(target, "Target cannot be null"); + + GameProfile profile = MinecraftServer.getServer().getUserCache().getProfile(target); + if (profile == null) { + return null; + } + + GameProfileBanEntry entry = list.get(profile); + if (entry == null) { + return null; + } + + return new CraftProfileBanEntry(profile, entry, list); + } + + @Override + public org.bukkit.BanEntry addBan(String target, String reason, Date expires, String source) { + Validate.notNull(target, "Ban target cannot be null"); + + GameProfile profile = MinecraftServer.getServer().getUserCache().getProfile(target); + if (profile == null) { + return null; + } + + GameProfileBanEntry entry = new GameProfileBanEntry(profile, new Date(), + StringUtils.isBlank(source) ? null : source, expires, + StringUtils.isBlank(reason) ? null : reason); + + list.add(entry); + + try { + list.save(); + } catch (IOException ex) { + Bukkit.getLogger().log(Level.SEVERE, "Failed to save banned-players.json, {0}", ex.getMessage()); + } + + return new CraftProfileBanEntry(profile, entry, list); + } + + @Override + public Set getBanEntries() { + ImmutableSet.Builder builder = ImmutableSet.builder(); + + for (GameProfileBanEntry entry : list.getValues()) { + GameProfile profile = entry.getKey(); + builder.add(new CraftProfileBanEntry(profile, entry, list)); + } + + return builder.build(); + } + + @Override + public boolean isBanned(String target) { + Validate.notNull(target, "Target cannot be null"); + + GameProfile profile = MinecraftServer.getServer().getUserCache().getProfile(target); + if (profile == null) { + return false; + } + + return list.isBanned(profile); + } + + @Override + public void pardon(String target) { + Validate.notNull(target, "Target cannot be null"); + + GameProfile profile = MinecraftServer.getServer().getUserCache().getProfile(target); + list.remove(profile); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftServer.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftServer.java new file mode 100644 index 0000000..a5c72c9 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftServer.java @@ -0,0 +1,1848 @@ +package org.bukkit.craftbukkit; + +import com.avaje.ebean.config.DataSourceConfig; +import com.avaje.ebean.config.ServerConfig; +import com.avaje.ebean.config.dbplatform.SQLitePlatform; +import com.avaje.ebeaninternal.server.lib.sql.TransactionIsolation; +import com.eatthepath.uuid.FastUUID; +import com.google.common.base.Charsets; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Lists; +import com.google.common.collect.MapMaker; +import com.mojang.authlib.GameProfile; +import dev.azurite.spigot.configs.AzuriteConfig; +import dev.azurite.spigot.utils.JavaUtils; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.ByteBufOutputStream; +import io.netty.buffer.Unpooled; +import io.netty.handler.codec.base64.Base64; +import net.md_5.bungee.api.chat.BaseComponent; +import net.minecraft.server.WorldType; +import net.minecraft.server.*; +import org.apache.commons.lang.Validate; +import org.bukkit.*; +import org.bukkit.World; +import org.bukkit.Warning.WarningState; +import org.bukkit.World.Environment; +import org.bukkit.command.CommandException; +import org.bukkit.command.*; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.configuration.serialization.ConfigurationSerialization; +import org.bukkit.conversations.Conversable; +import org.bukkit.craftbukkit.command.VanillaCommandWrapper; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.craftbukkit.generator.CraftChunkData; +import org.bukkit.craftbukkit.help.SimpleHelpMap; +import org.bukkit.craftbukkit.inventory.*; +import org.bukkit.craftbukkit.map.CraftMapView; +import org.bukkit.craftbukkit.metadata.EntityMetadataStore; +import org.bukkit.craftbukkit.metadata.PlayerMetadataStore; +import org.bukkit.craftbukkit.metadata.WorldMetadataStore; +import org.bukkit.craftbukkit.potion.CraftPotionBrewer; +import org.bukkit.craftbukkit.scheduler.CraftScheduler; +import org.bukkit.craftbukkit.scoreboard.CraftScoreboardManager; +import org.bukkit.craftbukkit.util.CraftIconCache; +import org.bukkit.craftbukkit.util.CraftMagicNumbers; +import org.bukkit.craftbukkit.util.DatFileFilter; +import org.bukkit.craftbukkit.util.Versioning; +import org.bukkit.craftbukkit.util.permissions.CraftDefaultPermissions; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryType; +import org.bukkit.event.player.PlayerChatTabCompleteEvent; +import org.bukkit.event.world.WorldInitEvent; +import org.bukkit.event.world.WorldLoadEvent; +import org.bukkit.event.world.WorldUnloadEvent; +import org.bukkit.generator.ChunkGenerator; +import org.bukkit.help.HelpMap; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.*; +import org.bukkit.permissions.Permissible; +import org.bukkit.permissions.Permission; +import org.bukkit.plugin.*; +import org.bukkit.plugin.java.JavaPluginLoader; +import org.bukkit.plugin.messaging.Messenger; +import org.bukkit.plugin.messaging.StandardMessenger; +import org.bukkit.potion.Potion; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.scheduler.BukkitWorker; +import org.bukkit.util.StringUtil; +import org.bukkit.util.permissions.DefaultPermissions; +import org.spigotmc.SpigotConfig; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.SafeConstructor; +import org.yaml.snakeyaml.error.MarkedYAMLException; + +import javax.imageio.ImageIO; +import java.awt.image.BufferedImage; +import java.io.*; +import java.util.*; +import java.util.logging.Level; +import java.util.logging.Logger; + +public final class CraftServer implements Server { + private static final Player[] EMPTY_PLAYER_ARRAY = new Player[0]; + + static { + ConfigurationSerialization.registerClass(CraftOfflinePlayer.class); + CraftItemFactory.instance(); + } + + final MinecraftServer console; + private final DedicatedPlayerList playerList; + private final String serverName = AzuriteConfig.serverBranding.getValue(); + private final String serverVersion; + private final String bukkitVersion = Versioning.getBukkitVersion(); + private final Logger logger = Logger.getLogger("Minecraft"); + private final ServicesManager servicesManager = new SimpleServicesManager(); + private final CraftScheduler scheduler = new CraftScheduler(); + private final SimpleCommandMap commandMap = new SimpleCommandMap(this); + private final SimpleHelpMap helpMap = new SimpleHelpMap(this); + private final StandardMessenger messenger = new StandardMessenger(); + private final PluginManager pluginManager = new SimplePluginManager(this, commandMap); + private final Map worlds = new LinkedHashMap<>(); + private final Yaml yaml = new Yaml(new SafeConstructor()); + private final Map offlinePlayers = new MapMaker().weakValues().makeMap(); + private final EntityMetadataStore entityMetadata = new EntityMetadataStore(); + private final PlayerMetadataStore playerMetadata = new PlayerMetadataStore(); + private final WorldMetadataStore worldMetadata = new WorldMetadataStore(); + private final BooleanWrapper online = new BooleanWrapper(); + + private final List playerView; + public int chunkGCPeriod; + public int chunkGCLoadThresh; + public CraftScoreboardManager scoreboardManager; + public boolean playerCommandState; + public int reloadCount; + private YamlConfiguration configuration; + private final Spigot spigot = new Spigot() { + + // PaperSpigot start - Add getTPS (Further improve tick loop) + @Override + public double[] getTPS() { + return new double[]{ + MinecraftServer.getServer().tps1.getAverage(), + MinecraftServer.getServer().tps5.getAverage(), + MinecraftServer.getServer().tps15.getAverage() + }; + } + // PaperSpigot end + + @Deprecated + @Override + public YamlConfiguration getConfig() { + return getBukkitConfig(); + } + + @Override + public YamlConfiguration getBukkitConfig() { + return configuration; + } + + @Override + public YamlConfiguration getSpigotConfig() { + return org.spigotmc.SpigotConfig.config; + } + + @Override + public YamlConfiguration getPaperSpigotConfig() { + return org.github.paperspigot.PaperSpigotConfig.config; + } + + @Override + public void restart() { + org.spigotmc.RestartCommand.restart(); + } + + @Override + public void broadcast(BaseComponent component) { + for (Player player : getOnlinePlayers()) { + player.spigot().sendMessage(component); + } + } + + @Override + public void broadcast(BaseComponent... components) { + for (Player player : getOnlinePlayers()) { + player.spigot().sendMessage(components); + } + } + }; + private YamlConfiguration commandsConfiguration; + private int monsterSpawn; + private int animalSpawn; + private int waterAnimalSpawn; + private int ambientSpawn; + private File container; + private WarningState warningState; + private boolean printSaveWarning; + private CraftIconCache icon; + private boolean overrideAllCommandBlockCommands; + + public CraftServer(MinecraftServer console, PlayerList playerList) { + this.console = console; + this.playerList = (DedicatedPlayerList) playerList; + this.playerView = Collections.unmodifiableList(Lists.transform(playerList.players, EntityPlayer::getBukkitEntity)); + this.serverVersion = CraftServer.class.getPackage().getImplementationVersion(); + online.value = console.getPropertyManager().getBoolean("online-mode", true); + + Bukkit.setServer(this); + + // Register all the Enchantments and PotionTypes now so we can stop new registration immediately after + Enchantment.DAMAGE_ALL.getClass(); + org.bukkit.enchantments.Enchantment.stopAcceptingRegistrations(); + + Potion.setPotionBrewer(new CraftPotionBrewer()); + MobEffectList.BLINDNESS.getClass(); + PotionEffectType.stopAcceptingRegistrations(); + // Ugly hack :( + + if (!Main.useConsole) { + getLogger().info("Console input is disabled due to --noconsole command argument"); + } + + configuration = YamlConfiguration.loadConfiguration(getConfigFile()); + configuration.options().copyDefaults(true); + configuration.setDefaults(YamlConfiguration.loadConfiguration(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("configurations/bukkit.yml"), Charsets.UTF_8))); + ConfigurationSection legacyAlias = null; + if (!configuration.isString("aliases")) { + legacyAlias = configuration.getConfigurationSection("aliases"); + configuration.set("aliases", "now-in-commands.yml"); + } + saveConfig(); + if (getCommandsConfigFile().isFile()) { + legacyAlias = null; + } + commandsConfiguration = YamlConfiguration.loadConfiguration(getCommandsConfigFile()); + commandsConfiguration.options().copyDefaults(true); + commandsConfiguration.setDefaults(YamlConfiguration.loadConfiguration(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("configurations/commands.yml"), Charsets.UTF_8))); + saveCommandsConfig(); + + // Migrate aliases from old file and add previously implicit $1- to pass all arguments + if (legacyAlias != null) { + ConfigurationSection aliases = commandsConfiguration.createSection("aliases"); + for (String key : legacyAlias.getKeys(false)) { + ArrayList commands = new ArrayList<>(); + + if (legacyAlias.isList(key)) { + for (String command : legacyAlias.getStringList(key)) { + commands.add(command + " $1-"); + } + } else { + commands.add(legacyAlias.getString(key) + " $1-"); + } + + aliases.set(key, commands); + } + } + + saveCommandsConfig(); + overrideAllCommandBlockCommands = commandsConfiguration.getStringList("command-block-overrides").contains("*"); + monsterSpawn = configuration.getInt("spawn-limits.monsters"); + animalSpawn = configuration.getInt("spawn-limits.animals"); + waterAnimalSpawn = configuration.getInt("spawn-limits.water-animals"); + ambientSpawn = configuration.getInt("spawn-limits.ambient"); + console.autosavePeriod = configuration.getInt("ticks-per.autosave"); + warningState = WarningState.value(configuration.getString("settings.deprecated-verbose")); + chunkGCPeriod = configuration.getInt("chunk-gc.period-in-ticks"); + chunkGCLoadThresh = configuration.getInt("chunk-gc.load-threshold"); + loadIcon(); + + // Spigot Start - Moved to old location of new DedicatedPlayerList in DedicatedServer + // loadPlugins(); + // enablePlugins(PluginLoadOrder.STARTUP); + // Spigot End + } + + static CraftIconCache loadServerIcon0(File file) throws Exception { + return loadServerIcon0(ImageIO.read(file)); + } + + static CraftIconCache loadServerIcon0(BufferedImage image) throws Exception { + ByteBuf bytebuf = Unpooled.buffer(); + + ByteBuf faviconBuffer = null; // KigPaper + try { + Validate.isTrue(image.getWidth() == 64, "Must be 64 pixels wide"); + Validate.isTrue(image.getHeight() == 64, "Must be 64 pixels high"); + ImageIO.write(image, "PNG", new ByteBufOutputStream(bytebuf)); + //ByteBuf bytebuf1 = Base64.encode(bytebuf); // KigPaper + faviconBuffer = Base64.encode(bytebuf); + + return new CraftIconCache("data:image/png;base64," + faviconBuffer.toString(Charsets.UTF_8)); + } catch (Exception exception) { + MinecraftServer.LOGGER.error("Couldn't load server icon", exception); + } finally { + bytebuf.release(); + // KigPaper start + if(faviconBuffer != null) faviconBuffer.release(); + // KigPaper end + } + + return null; + } + + public boolean getCommandBlockOverride(String command) { + return overrideAllCommandBlockCommands || commandsConfiguration.getStringList("command-block-overrides").contains(command); + } + + private File getConfigFile() { + return (File) console.options.valueOf("bukkit-settings"); + } + + private File getCommandsConfigFile() { + return (File) console.options.valueOf("commands-settings"); + } + + @Override + public int setMaxPlayers(int maxPlayers) { + this.playerList.maxPlayers = maxPlayers; + return maxPlayers; + } + + private void saveConfig() { + try { + configuration.save(getConfigFile()); + } catch (IOException ex) { + Logger.getLogger(CraftServer.class.getName()).log(Level.SEVERE, "Could not save " + getConfigFile(), ex); + } + } + + private void saveCommandsConfig() { + try { + commandsConfiguration.save(getCommandsConfigFile()); + } catch (IOException ex) { + Logger.getLogger(CraftServer.class.getName()).log(Level.SEVERE, "Could not save " + getCommandsConfigFile(), ex); + } + } + + public void loadPlugins() { + pluginManager.registerInterface(JavaPluginLoader.class); + + File pluginFolder = (File) console.options.valueOf("plugins"); + + if (pluginFolder.exists()) { + Plugin[] plugins = pluginManager.loadPlugins(pluginFolder); + for (Plugin plugin : plugins) { + try { + String message = String.format("Loading %s", plugin.getDescription().getFullName()); + plugin.getLogger().info(message); + plugin.onLoad(); + } catch (Throwable ex) { + Logger.getLogger(CraftServer.class.getName()).log(Level.SEVERE, ex.getMessage() + " initializing " + plugin.getDescription().getFullName() + " (Is it up to date?)", ex); + } + } + } else { + pluginFolder.mkdir(); + } + } + + public void enablePlugins(PluginLoadOrder type) { + if (type == PluginLoadOrder.STARTUP) { + helpMap.clear(); + helpMap.initializeGeneralTopics(); + } + + Plugin[] plugins = pluginManager.getPlugins(); + + for (Plugin plugin : plugins) { + if ((!plugin.isEnabled()) && (plugin.getDescription().getLoad() == type)) { + loadPlugin(plugin); + } + } + + if (type == PluginLoadOrder.POSTWORLD) { + // Spigot start - Allow vanilla commands to be forced to be the main command + setVanillaCommands(true); + commandMap.setFallbackCommands(); + setVanillaCommands(false); + // Spigot end + commandMap.registerServerAliases(); + loadCustomPermissions(); + DefaultPermissions.registerCorePermissions(); + CraftDefaultPermissions.registerCorePermissions(); + helpMap.initializeCommands(); + } + } + + public void disablePlugins() { + pluginManager.disablePlugins(); + } + + private void setVanillaCommands(boolean first) { // Spigot + Map commands = new CommandDispatcher().getCommands(); + for (ICommand cmd : commands.values()) { + // Spigot start + VanillaCommandWrapper wrapper = new VanillaCommandWrapper((CommandAbstract) cmd, LocaleI18n.get(cmd.getUsage(null))); + if (org.spigotmc.SpigotConfig.replaceCommands.contains(wrapper.getName())) { + if (first) { + commandMap.register("minecraft", wrapper); + } + } else if (!first) { + commandMap.register("minecraft", wrapper); + } + // Spigot end + } + } + + private void loadPlugin(Plugin plugin) { + try { + pluginManager.enablePlugin(plugin); + + List perms = plugin.getDescription().getPermissions(); + + for (Permission perm : perms) { + try { + pluginManager.addPermission(perm); + } catch (IllegalArgumentException ex) { + getLogger().log(Level.WARNING, "Plugin " + plugin.getDescription().getFullName() + " tried to register permission '" + perm.getName() + "' but it's already registered", ex); + } + } + } catch (Throwable ex) { + Logger.getLogger(CraftServer.class.getName()).log(Level.SEVERE, ex.getMessage() + " loading " + plugin.getDescription().getFullName() + " (Is it up to date?)", ex); + } + } + + @Override + public String getName() { + return serverName; + } + + @Override + public String getVersion() { + return serverVersion + " (MC: " + console.getVersion() + ")"; + } + + @Override + public String getBukkitVersion() { + return bukkitVersion; + } + + @Override + @Deprecated + @SuppressWarnings("unchecked") + public Player[] _INVALID_getOnlinePlayers() { + return getOnlinePlayers().toArray(EMPTY_PLAYER_ARRAY); + } + + @Override + public List getOnlinePlayers() { + return this.playerView; + } + + @Override + @Deprecated + public Player getPlayer(final String name) { + Validate.notNull(name, "Name cannot be null"); + + Player found = getPlayerExact(name); + // Try for an exact match first. + if (found != null) { + return found; + } + + String lowerName = name.toLowerCase(); + int delta = Integer.MAX_VALUE; + for (Player player : getOnlinePlayers()) { + if (player.getName().toLowerCase().startsWith(lowerName)) { + int curDelta = Math.abs(player.getName().length() - lowerName.length()); + if (curDelta < delta) { + found = player; + delta = curDelta; + } + if (curDelta == 0) break; + } + } + return found; + } + + @Override + @Deprecated + public Player getPlayerExact(String name) { + Validate.notNull(name, "Name cannot be null"); + + EntityPlayer player = playerList.getPlayer(name); + return (player != null) ? player.getBukkitEntity() : null; + } + + @Override + public Player getPlayer(UUID id) { + EntityPlayer player = playerList.a(id); + + if (player != null) { + return player.getBukkitEntity(); + } + + return null; + } + + @Override + public int broadcastMessage(String message) { + return broadcast(message, BROADCAST_CHANNEL_USERS); + } + + public Player getPlayer(final EntityPlayer entity) { + return entity.getBukkitEntity(); + } + + @Override + @Deprecated + public List matchPlayer(String partialName) { + Validate.notNull(partialName, "PartialName cannot be null"); + + List matchedPlayers = new ArrayList<>(); + + for (Player iterPlayer : this.getOnlinePlayers()) { + String iterPlayerName = iterPlayer.getName(); + + if (partialName.equalsIgnoreCase(iterPlayerName)) { + // Exact match + matchedPlayers.clear(); + matchedPlayers.add(iterPlayer); + break; + } + if (iterPlayerName.toLowerCase().contains(partialName.toLowerCase())) { + // Partial match + matchedPlayers.add(iterPlayer); + } + } + + return matchedPlayers; + } + + @Override + public int getMaxPlayers() { + return playerList.getMaxPlayers(); + } + + // NOTE: These are dependent on the corrisponding call in MinecraftServer + // so if that changes this will need to as well + @Override + public int getPort() { + return this.getConfigInt("server-port", 25565); + } + + @Override + public int getViewDistance() { + return getConfigInt("view-distance", 5); + } + + @Override + public String getIp() { + return this.getConfigString("server-ip", ""); + } + + @Override + public String getServerName() { + return this.getConfigString("server-name", "Unknown Server"); + } + + @Override + public String getServerId() { + return this.getConfigString("server-id", "unnamed"); + } + + @Override + public String getWorldType() { + return this.getConfigString("level-type", "DEFAULT"); + } + + @Override + public boolean getGenerateStructures() { + return this.getConfigBoolean("generate-structures", true); + } + + @Override + public boolean getAllowEnd() { + return this.configuration.getBoolean("settings.allow-end"); + } + + @Override + public boolean getAllowNether() { + return this.getConfigBoolean("allow-nether", true); + } + + public boolean getWarnOnOverload() { + return this.configuration.getBoolean("settings.warn-on-overload"); + } + + public boolean getQueryPlugins() { + return this.configuration.getBoolean("settings.query-plugins"); + } + + @Override + public boolean hasWhitelist() { + return this.getConfigBoolean("white-list", false); + } + + // End Temporary calls + + // NOTE: Temporary calls through to server.properies until its replaced + private String getConfigString(String variable, String defaultValue) { + return this.console.getPropertyManager().getString(variable, defaultValue); + } + + private int getConfigInt(String variable, int defaultValue) { + return this.console.getPropertyManager().getInt(variable, defaultValue); + } + + private boolean getConfigBoolean(String variable, boolean defaultValue) { + return this.console.getPropertyManager().getBoolean(variable, defaultValue); + } + + @Override + public String getUpdateFolder() { + return this.configuration.getString("settings.update-folder", "update"); + } + + @Override + public File getUpdateFolderFile() { + return new File((File) console.options.valueOf("plugins"), this.configuration.getString("settings.update-folder", "update")); + } + + @Override + public long getConnectionThrottle() { + // Spigot Start - Automatically set connection throttle for bungee configurations + if (org.spigotmc.SpigotConfig.bungee) { + return -1; + } else { + return this.configuration.getInt("settings.connection-throttle"); + } + // Spigot End + } + + @Override + public int getTicksPerAnimalSpawns() { + return this.configuration.getInt("ticks-per.animal-spawns"); + } + + @Override + public int getTicksPerMonsterSpawns() { + return this.configuration.getInt("ticks-per.monster-spawns"); + } + + @Override + public PluginManager getPluginManager() { + return pluginManager; + } + + @Override + public CraftScheduler getScheduler() { + return scheduler; + } + + @Override + public ServicesManager getServicesManager() { + return servicesManager; + } + + @Override + public List getWorlds() { + return new ArrayList<>(worlds.values()); + } + + public DedicatedPlayerList getHandle() { + return playerList; + } + + // NOTE: Should only be called from DedicatedServer.ah() + public boolean dispatchServerCommand(CommandSender sender, ServerCommand serverCommand) { + if (sender instanceof Conversable) { + Conversable conversable = (Conversable) sender; + + if (conversable.isConversing()) { + conversable.acceptConversationInput(serverCommand.command); + return true; + } + } + try { + this.playerCommandState = true; + return dispatchCommand(sender, serverCommand.command); + } catch (Exception ex) { + getLogger().log(Level.WARNING, "Unexpected exception while parsing console command \"" + serverCommand.command + '"', ex); + return false; + } finally { + this.playerCommandState = false; + } + } + + @Override + public boolean dispatchCommand(CommandSender sender, String commandLine) { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(commandLine, "CommandLine cannot be null"); + + // PaperSpigot Start + if (!Bukkit.isPrimaryThread()) { + final CommandSender fSender = sender; + final String fCommandLine = commandLine; + Bukkit.getLogger().log(Level.SEVERE, "Command Dispatched Async: " + commandLine); + Bukkit.getLogger().log(Level.SEVERE, "Please notify author of plugin causing this execution to fix this bug! see: http://bit.ly/1oSiM6C", new Throwable()); + org.bukkit.craftbukkit.util.Waitable wait = new org.bukkit.craftbukkit.util.Waitable() { + @Override + protected Boolean evaluate() { + return dispatchCommand(fSender, fCommandLine); + } + }; + MinecraftServer.getServer().postToMainThreadRunnable(wait); + try { + return wait.get(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); // This is proper habit for java. If we aren't handling it, pass it on! + } catch (Exception e) { + throw new RuntimeException("Exception processing dispatch command", e.getCause()); + } + } + // PaperSpigot End + + if (commandMap.dispatch(sender, commandLine)) { + return true; + } + + sender.sendMessage(org.spigotmc.SpigotConfig.unknownCommandMessage); + + return false; + } + + @Override + public void reload() { + reloadCount++; + configuration = YamlConfiguration.loadConfiguration(getConfigFile()); + commandsConfiguration = YamlConfiguration.loadConfiguration(getCommandsConfigFile()); + PropertyManager config = new PropertyManager(console.options); + + ((DedicatedServer) console).propertyManager = config; + + boolean animals = config.getBoolean("spawn-animals", console.getSpawnAnimals()); + boolean monsters = config.getBoolean("spawn-monsters", console.worlds.get(0).getDifficulty() != EnumDifficulty.PEACEFUL); + EnumDifficulty difficulty = EnumDifficulty.getById(config.getInt("difficulty", console.worlds.get(0).getDifficulty().ordinal())); + + online.value = config.getBoolean("online-mode", console.getOnlineMode()); + console.setSpawnAnimals(config.getBoolean("spawn-animals", console.getSpawnAnimals())); + console.setPVP(config.getBoolean("pvp", console.getPVP())); + console.setAllowFlight(config.getBoolean("allow-flight", console.getAllowFlight())); + console.setMotd(config.getString("motd", console.getMotd())); + monsterSpawn = configuration.getInt("spawn-limits.monsters"); + animalSpawn = configuration.getInt("spawn-limits.animals"); + waterAnimalSpawn = configuration.getInt("spawn-limits.water-animals"); + ambientSpawn = configuration.getInt("spawn-limits.ambient"); + warningState = WarningState.value(configuration.getString("settings.deprecated-verbose")); + printSaveWarning = false; + console.autosavePeriod = configuration.getInt("ticks-per.autosave"); + chunkGCPeriod = configuration.getInt("chunk-gc.period-in-ticks"); + chunkGCLoadThresh = configuration.getInt("chunk-gc.load-threshold"); + loadIcon(); + + try { + playerList.getIPBans().load(); + } catch (IOException ex) { + logger.log(Level.WARNING, "Failed to load banned-ips.json, " + ex.getMessage()); + } + try { + playerList.getProfileBans().load(); + } catch (IOException ex) { + logger.log(Level.WARNING, "Failed to load banned-players.json, " + ex.getMessage()); + } + + org.spigotmc.SpigotConfig.init((File) console.options.valueOf("spigot-settings")); // Spigot + org.github.paperspigot.PaperSpigotConfig.init((File) console.options.valueOf("spigot-settings")); // PaperSpigot + + for (WorldServer world : console.worlds) { + world.worldData.setDifficulty(difficulty); + world.setSpawnFlags(monsters, animals); + if (this.getTicksPerAnimalSpawns() < 0) { + world.ticksPerAnimalSpawns = 400; + } else { + world.ticksPerAnimalSpawns = this.getTicksPerAnimalSpawns(); + } + + if (this.getTicksPerMonsterSpawns() < 0) { + world.ticksPerMonsterSpawns = 200; + } else { + world.ticksPerMonsterSpawns = this.getTicksPerMonsterSpawns(); + } + world.spigotConfig.init(); // Spigot + world.paperSpigotConfig.init(); // PaperSpigot + } + + pluginManager.clearPlugins(); + commandMap.clearCommands(); + resetRecipes(); + SpigotConfig.registerCommands(); // Spigot + + overrideAllCommandBlockCommands = commandsConfiguration.getStringList("command-block-overrides").contains("*"); + + int pollCount = 0; + + // Wait for at most 2.5 seconds for plugins to close their threads + while (pollCount < 50 && !getScheduler().getActiveWorkers().isEmpty()) { + try { + Thread.sleep(50); + } catch (InterruptedException ignored) { + } + pollCount++; + } + + List overdueWorkers = getScheduler().getActiveWorkers(); + for (BukkitWorker worker : overdueWorkers) { + Plugin plugin = worker.getOwner(); + String author = ""; + if (plugin.getDescription().getAuthors().size() > 0) { + author = plugin.getDescription().getAuthors().get(0); + } + getLogger().log(Level.SEVERE, String.format( + "Nag author: '%s' of '%s' about the following: %s", + author, + plugin.getDescription().getName(), + "This plugin is not properly shutting down its async tasks when it is being reloaded. This may cause conflicts with the newly loaded version of the plugin" + )); + } + loadPlugins(); + enablePlugins(PluginLoadOrder.STARTUP); + enablePlugins(PluginLoadOrder.POSTWORLD); + } + + @Override + public void reloadConfigs() { + configuration = YamlConfiguration.loadConfiguration(getConfigFile()); + commandsConfiguration = YamlConfiguration.loadConfiguration(getCommandsConfigFile()); + PropertyManager config = new PropertyManager(console.options); + + ((DedicatedServer) console).propertyManager = config; + + boolean animals = config.getBoolean("spawn-animals", console.getSpawnAnimals()); + boolean monsters = config.getBoolean("spawn-monsters", console.worlds.get(0).getDifficulty() != EnumDifficulty.PEACEFUL); + EnumDifficulty difficulty = EnumDifficulty.getById(config.getInt("difficulty", console.worlds.get(0).getDifficulty().ordinal())); + + online.value = config.getBoolean("online-mode", console.getOnlineMode()); + console.setSpawnAnimals(config.getBoolean("spawn-animals", console.getSpawnAnimals())); + console.setPVP(config.getBoolean("pvp", console.getPVP())); + console.setAllowFlight(config.getBoolean("allow-flight", console.getAllowFlight())); + console.setMotd(config.getString("motd", console.getMotd())); + monsterSpawn = configuration.getInt("spawn-limits.monsters"); + animalSpawn = configuration.getInt("spawn-limits.animals"); + waterAnimalSpawn = configuration.getInt("spawn-limits.water-animals"); + ambientSpawn = configuration.getInt("spawn-limits.ambient"); + warningState = WarningState.value(configuration.getString("settings.deprecated-verbose")); + printSaveWarning = false; + console.autosavePeriod = configuration.getInt("ticks-per.autosave"); + chunkGCPeriod = configuration.getInt("chunk-gc.period-in-ticks"); + chunkGCLoadThresh = configuration.getInt("chunk-gc.load-threshold"); + loadIcon(); + + try { + playerList.getIPBans().load(); + } catch (IOException ex) { + logger.log(Level.WARNING, "Failed to load banned-ips.json, " + ex.getMessage()); + } + try { + playerList.getProfileBans().load(); + } catch (IOException ex) { + logger.log(Level.WARNING, "Failed to load banned-players.json, " + ex.getMessage()); + } + + org.spigotmc.SpigotConfig.init((File) console.options.valueOf("spigot-settings")); // Spigot + org.github.paperspigot.PaperSpigotConfig.init((File) console.options.valueOf("paper-settings")); // PaperSpigot + + for (WorldServer world : console.worlds) { + world.worldData.setDifficulty(difficulty); + world.setSpawnFlags(monsters, animals); + if (this.getTicksPerAnimalSpawns() < 0) { + world.ticksPerAnimalSpawns = 400; + } else { + world.ticksPerAnimalSpawns = this.getTicksPerAnimalSpawns(); + } + + if (this.getTicksPerMonsterSpawns() < 0) { + world.ticksPerMonsterSpawns = 200; + } else { + world.ticksPerMonsterSpawns = this.getTicksPerMonsterSpawns(); + } + world.spigotConfig.init(); // Spigot + world.paperSpigotConfig.init(); // PaperSpigot + } + } + + private void loadIcon() { + icon = new CraftIconCache(null); + try { + final File file = new File(new File("."), "server-icon.png"); + if (file.isFile()) { + icon = loadServerIcon0(file); + } + } catch (Exception ex) { + getLogger().log(Level.WARNING, "Couldn't load server icon", ex); + } + } + + @SuppressWarnings({"unchecked", "finally"}) + private void loadCustomPermissions() { + File file = new File(configuration.getString("settings.permissions-file")); + FileInputStream stream; + + try { + stream = new FileInputStream(file); + } catch (FileNotFoundException ex) { + try { + file.createNewFile(); + } finally { + return; + } + } + + Map> perms; + + try { + perms = (Map>) yaml.load(stream); + } catch (MarkedYAMLException ex) { + getLogger().log(Level.WARNING, "Server permissions file " + file + " is not valid YAML: " + ex); + return; + } catch (Throwable ex) { + getLogger().log(Level.WARNING, "Server permissions file " + file + " is not valid YAML.", ex); + return; + } finally { + try { + stream.close(); + } catch (IOException ignored) { + } + } + + if (perms == null) { + return; + } + + List permsList = Permission.loadPermissions(perms, "Permission node '%s' in " + file + " is invalid", Permission.DEFAULT_PERMISSION); + + for (Permission perm : permsList) { + try { + pluginManager.addPermission(perm); + } catch (IllegalArgumentException ex) { + getLogger().log(Level.SEVERE, "Permission in " + file + " was already defined", ex); + } + } + } + + @Override + public String toString() { + return "CraftServer{" + "serverName=" + serverName + ",serverVersion=" + serverVersion + ",minecraftVersion=" + console.getVersion() + '}'; + } + + public World createWorld(String name, World.Environment environment) { + return WorldCreator.name(name).environment(environment).createWorld(); + } + + public World createWorld(String name, World.Environment environment, long seed) { + return WorldCreator.name(name).environment(environment).seed(seed).createWorld(); + } + + public World createWorld(String name, Environment environment, ChunkGenerator generator) { + return WorldCreator.name(name).environment(environment).generator(generator).createWorld(); + } + + public World createWorld(String name, Environment environment, long seed, ChunkGenerator generator) { + return WorldCreator.name(name).environment(environment).seed(seed).generator(generator).createWorld(); + } + + @Override + public World createWorld(WorldCreator creator) { + Validate.notNull(creator, "Creator may not be null"); + + String name = creator.name(); + ChunkGenerator generator = creator.generator(); + File folder = new File(getWorldContainer(), name); + World world = getWorld(name); + WorldType type = WorldType.getType(creator.type().getName()); + boolean generateStructures = creator.generateStructures(); + + if (world != null) { + return world; + } + + if ((folder.exists()) && (!folder.isDirectory())) { + throw new IllegalArgumentException("File exists with the name '" + name + "' and isn't a folder"); + } + + if (generator == null) { + generator = getGenerator(name); + } + + Convertable converter = new WorldLoaderServer(getWorldContainer()); + if (converter.isConvertable(name)) { + getLogger().info("Converting world '" + name + "'"); + converter.convert(name, new IProgressUpdate() { + private long b = System.currentTimeMillis(); + + public void a(String s) { + } + + public void a(int i) { + if (System.currentTimeMillis() - this.b >= 1000L) { + this.b = System.currentTimeMillis(); + MinecraftServer.LOGGER.info("Converting... " + i + "%"); + } + + } + + public void c(String s) { + } + }); + } + + int dimension = CraftWorld.CUSTOM_DIMENSION_OFFSET + console.worlds.size(); + boolean used = false; + do { + for (WorldServer server : console.worlds) { + used = server.dimension == dimension; + if (used) { + dimension++; + break; + } + } + } while (used); + + IDataManager sdm = new ServerNBTManager(getWorldContainer(), name, true); + WorldData worlddata = sdm.getWorldData(); + if (worlddata == null) { + WorldSettings worldSettings = new WorldSettings(creator.seed(), WorldSettings.EnumGamemode.getById(getDefaultGameMode().getValue()), generateStructures, false, type); + worldSettings.setGeneratorSettings(creator.generatorSettings()); + worlddata = new WorldData(worldSettings, name); + } + worlddata.checkName(name); // CraftBukkit - Migration did not rewrite the level.dat; This forces 1.8 to take the last loaded world as respawn (in this case the end) + WorldServer internal = (WorldServer) new WorldServer(console, sdm, worlddata, dimension, getServer().methodProfiler, creator.environment(), generator, false).b(); + + if (!(worlds.containsKey(name.toLowerCase()))) { + return null; + } + + internal.scoreboard = getScoreboardManager().getMainScoreboard().getHandle(); + + internal.tracker = new EntityTracker(internal); + internal.addIWorldAccess(new WorldManager(console, internal)); + internal.worldData.setDifficulty(EnumDifficulty.EASY); + internal.setSpawnFlags(true, true); + console.worlds.add(internal); + + if (generator != null) { + internal.getWorld().getPopulators().addAll(generator.getDefaultPopulators(internal.getWorld())); + } + + pluginManager.callEvent(new WorldInitEvent(internal.getWorld())); + + if (internal.getWorld().getKeepSpawnInMemory()) { + short short1 = 196; + long i = System.currentTimeMillis(); + for (int j = -short1; j <= short1; j += 16) { + for (int k = -short1; k <= short1; k += 16) { + long l = System.currentTimeMillis(); + + if (l < i) { + i = l; + } + + if (l > i + 1000L) { + int i1 = (short1 * 2 + 1) * (short1 * 2 + 1); + int j1 = (j + short1) * (short1 * 2 + 1) + k + 1; + + System.out.println("Preparing spawn area for " + name + ", " + (j1 * 100 / i1) + "%"); + i = l; + } + + BlockPosition chunkcoordinates = internal.getSpawn(); + internal.chunkProviderServer.getChunkAt(chunkcoordinates.getX() + j >> 4, chunkcoordinates.getZ() + k >> 4, () -> { + }); + } + } + } + pluginManager.callEvent(new WorldLoadEvent(internal.getWorld())); + return internal.getWorld(); + } + + @Override + public boolean unloadWorld(String name, boolean save) { + return unloadWorld(getWorld(name), save); + } + + @Override + public boolean unloadWorld(World world, boolean save) { + if (world == null) { + return false; + } + + WorldServer handle = ((CraftWorld) world).getHandle(); + + if (!(console.worlds.contains(handle))) { + return false; + } + + if (!(handle.dimension > 1)) { + return false; + } + + if (!handle.players.isEmpty()) { + return false; + } + + WorldUnloadEvent e = new WorldUnloadEvent(handle.getWorld()); + pluginManager.callEvent(e); + + if (e.isCancelled()) { + return false; + } + + if (save) { + try { + handle.save(true, null); + handle.saveLevel(); + } catch (ExceptionWorldConflict ex) { + getLogger().log(Level.SEVERE, null, ex); + } + } + + worlds.remove(world.getName().toLowerCase()); + console.worlds.remove(handle); + + File parentFolder = world.getWorldFolder().getAbsoluteFile(); + + // Synchronized because access to RegionFileCache.a is guarded by this lock. + synchronized (RegionFileCache.class) { + // RegionFileCache.a should be RegionFileCache.cache + Iterator> i = RegionFileCache.a.entrySet().iterator(); + while (i.hasNext()) { + Map.Entry entry = i.next(); + File child = entry.getKey().getAbsoluteFile(); + while (child != null) { + if (child.equals(parentFolder)) { + i.remove(); + try { + entry.getValue().c(); // Should be RegionFile.close(); + } catch (IOException ex) { + getLogger().log(Level.SEVERE, null, ex); + } + break; + } + child = child.getParentFile(); + } + } + } + + return true; + } + + public MinecraftServer getServer() { + return console; + } + + @Override + public World getWorld(String name) { + Validate.notNull(name, "Name cannot be null"); + + return worlds.get(name.toLowerCase()); + } + + @Override + public World getWorld(UUID uid) { + for (World world : worlds.values()) { + if (world.getUID().equals(uid)) { + return world; + } + } + return null; + } + + public void addWorld(World world) { + // SWM start + if (com.grinderwolf.swm.clsm.ClassModifier.skipWorldAdd(((CraftWorld) world).getHandle())) { + return; + } + // SWM end + + // Check if a World already exists with the UID. + if (getWorld(world.getUID()) != null) { + System.out.println("World " + world.getName() + " is a duplicate of another world and has been prevented from loading. Please delete the uid.dat file from " + world.getName() + "'s world directory if you want to be able to load the duplicate world."); + return; + } + worlds.put(world.getName().toLowerCase(), world); + } + + @Override + public Logger getLogger() { + return logger; + } + + @Override + public PluginCommand getPluginCommand(String name) { + Command command = commandMap.getCommand(name); + + if (command instanceof PluginCommand) { + return (PluginCommand) command; + } else { + return null; + } + } + + @Override + public void savePlayers() { + checkSaveState(); + playerList.savePlayers(); + } + + @Override + public void configureDbConfig(ServerConfig config) { + Validate.notNull(config, "Config cannot be null"); + + DataSourceConfig ds = new DataSourceConfig(); + ds.setDriver(configuration.getString("database.driver")); + ds.setUrl(configuration.getString("database.url")); + ds.setUsername(configuration.getString("database.username")); + ds.setPassword(configuration.getString("database.password")); + ds.setIsolationLevel(TransactionIsolation.getLevel(configuration.getString("database.isolation"))); + + if (ds.getDriver().contains("sqlite")) { + config.setDatabasePlatform(new SQLitePlatform()); + config.getDatabasePlatform().getDbDdlSyntax().setIdentity(""); + } + + config.setDataSourceConfig(ds); + } + + @Override + public boolean addRecipe(Recipe recipe) { + CraftRecipe toAdd; + if (recipe instanceof CraftRecipe) { + toAdd = (CraftRecipe) recipe; + } else { + if (recipe instanceof ShapedRecipe) { + toAdd = CraftShapedRecipe.fromBukkitRecipe((ShapedRecipe) recipe); + } else if (recipe instanceof ShapelessRecipe) { + toAdd = CraftShapelessRecipe.fromBukkitRecipe((ShapelessRecipe) recipe); + } else if (recipe instanceof FurnaceRecipe) { + toAdd = CraftFurnaceRecipe.fromBukkitRecipe((FurnaceRecipe) recipe); + } else { + return false; + } + } + toAdd.addToCraftingManager(); + CraftingManager.getInstance().sort(); + return true; + } + + @Override + public List getRecipesFor(ItemStack result) { + Validate.notNull(result, "Result cannot be null"); + + List results = new ArrayList<>(); + Iterator iter = recipeIterator(); + while (iter.hasNext()) { + Recipe recipe = iter.next(); + ItemStack stack = recipe.getResult(); + if (stack.getType() != result.getType()) { + continue; + } + if (result.getDurability() == -1 || result.getDurability() == stack.getDurability()) { + results.add(recipe); + } + } + return results; + } + + @Override + public Iterator recipeIterator() { + return new RecipeIterator(); + } + + @Override + public void clearRecipes() { + CraftingManager.getInstance().recipes.clear(); + RecipesFurnace.getInstance().recipes.clear(); + RecipesFurnace.getInstance().customRecipes.clear(); + } + + @Override + public void resetRecipes() { + CraftingManager.getInstance().recipes = new CraftingManager().recipes; + RecipesFurnace.getInstance().recipes = new RecipesFurnace().recipes; + RecipesFurnace.getInstance().customRecipes.clear(); + } + + @Override + public Map getCommandAliases() { + ConfigurationSection section = commandsConfiguration.getConfigurationSection("aliases"); + Map result = new LinkedHashMap<>(); + + if (section != null) { + for (String key : section.getKeys(false)) { + List commands; + + if (section.isList(key)) { + commands = section.getStringList(key); + } else { + commands = ImmutableList.of(section.getString(key)); + } + + result.put(key, commands.toArray(new String[0])); + } + } + + return result; + } + + public void removeBukkitSpawnRadius() { + configuration.set("settings.spawn-radius", null); + saveConfig(); + } + + public int getBukkitSpawnRadius() { + return configuration.getInt("settings.spawn-radius", -1); + } + + @Override + public String getShutdownMessage() { + return configuration.getString("settings.shutdown-message"); + } + + @Override + public int getSpawnRadius() { + return ((DedicatedServer) console).propertyManager.getInt("spawn-protection", 16); + } + + @Override + public void setSpawnRadius(int value) { + configuration.set("settings.spawn-radius", value); + saveConfig(); + } + + @Override + public boolean getOnlineMode() { + return online.value; + } + + @Override + public boolean getAllowFlight() { + return console.getAllowFlight(); + } + + @Override + public boolean isHardcore() { + return console.isHardcore(); + } + + @Override + public boolean useExactLoginLocation() { + return configuration.getBoolean("settings.use-exact-login-location"); + } + + public ChunkGenerator getGenerator(String world) { + ConfigurationSection section = configuration.getConfigurationSection("worlds"); + ChunkGenerator result = null; + + if (section != null) { + section = section.getConfigurationSection(world); + + if (section != null) { + String name = section.getString("generator"); + + if ((name != null) && (!name.equals(""))) { + String[] split = name.split(":", 2); + String id = (split.length > 1) ? split[1] : null; + Plugin plugin = pluginManager.getPlugin(split[0]); + + if (plugin == null) { + getLogger().severe("Could not set generator for default world '" + world + "': Plugin '" + split[0] + "' does not exist"); + } else if (!plugin.isEnabled()) { + getLogger().severe("Could not set generator for default world '" + world + "': Plugin '" + plugin.getDescription().getFullName() + "' is not enabled yet (is it load:STARTUP?)"); + } else { + try { + result = plugin.getDefaultWorldGenerator(world, id); + if (result == null) { + getLogger().severe("Could not set generator for default world '" + world + "': Plugin '" + plugin.getDescription().getFullName() + "' lacks a default world generator"); + } + } catch (Throwable t) { + plugin.getLogger().log(Level.SEVERE, "Could not set generator for default world '" + world + "': Plugin '" + plugin.getDescription().getFullName(), t); + } + } + } + } + } + + return result; + } + + @Override + @Deprecated + public CraftMapView getMap(short id) { + PersistentCollection collection = console.worlds.get(0).worldMaps; + WorldMap worldmap = (WorldMap) collection.get(WorldMap.class, "map_" + id); + if (worldmap == null) { + return null; + } + return worldmap.mapView; + } + + @Override + public CraftMapView createMap(World world) { + Validate.notNull(world, "World cannot be null"); + + net.minecraft.server.ItemStack stack = new net.minecraft.server.ItemStack(Items.MAP, 1, -1); + WorldMap worldmap = Items.FILLED_MAP.getSavedMap(stack, ((CraftWorld) world).getHandle()); + return worldmap.mapView; + } + + @Override + public void shutdown() { + console.safeShutdown(); + } + // Paper end + + @Override + public int broadcast(String message, String permission) { + int count = 0; + Set permissibles = getPluginManager().getPermissionSubscriptions(permission); + + for (Permissible permissible : permissibles) { + if (permissible instanceof CommandSender && permissible.hasPermission(permission)) { + CommandSender user = (CommandSender) permissible; + user.sendMessage(message); + count++; + } + } + + return count; + } + + // Paper start + @Override + public void broadcast(BaseComponent component) { + for (Player player : getOnlinePlayers()) { + player.sendMessage(component); + } + } + + @Override + public void broadcast(BaseComponent... components) { + for (Player player : getOnlinePlayers()) { + player.sendMessage(components); + } + } + + @Override + @Deprecated + public OfflinePlayer getOfflinePlayer(String name) { + Validate.notNull(name, "Name cannot be null"); + com.google.common.base.Preconditions.checkArgument(!org.apache.commons.lang.StringUtils.isBlank(name), "Name cannot be blank"); // Spigot + + OfflinePlayer result = getPlayerExact(name); + if (result == null) { + // Spigot Start + GameProfile profile = null; + // Only fetch an online UUID in online mode + if (MinecraftServer.getServer().getOnlineMode() || org.spigotmc.SpigotConfig.bungee) { + profile = MinecraftServer.getServer().getUserCache().getProfile(name); + } + // Spigot end + if (profile == null) { + // Make an OfflinePlayer using an offline mode UUID since the name has no profile + result = getOfflinePlayer(new GameProfile(UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(Charsets.UTF_8)), name)); + } else { + // Use the GameProfile even when we get a UUID so we ensure we still have a name + result = getOfflinePlayer(profile); + } + } else { + offlinePlayers.remove(result.getUniqueId()); + } + + return result; + } + + @Override + public OfflinePlayer getOfflinePlayer(UUID id) { + Validate.notNull(id, "UUID cannot be null"); + + OfflinePlayer result = getPlayer(id); + if (result == null) { + result = offlinePlayers.get(id); + if (result == null) { + result = new CraftOfflinePlayer(this, new GameProfile(id, null)); + offlinePlayers.put(id, result); + } + } else { + offlinePlayers.remove(id); + } + + return result; + } + + public OfflinePlayer getOfflinePlayer(GameProfile profile) { + OfflinePlayer player = new CraftOfflinePlayer(this, profile); + offlinePlayers.put(profile.getId(), player); + return player; + } + + @Override + public Set getIPBans() { + return new HashSet<>(Arrays.asList(playerList.getIPBans().getEntries())); + } + + @Override + public void banIP(String address) { + Validate.notNull(address, "Address cannot be null."); + + this.getBanList(org.bukkit.BanList.Type.IP).addBan(address, null, null, null); + } + + @Override + public void unbanIP(String address) { + Validate.notNull(address, "Address cannot be null."); + + this.getBanList(org.bukkit.BanList.Type.IP).pardon(address); + } + + @Override + public Set getBannedPlayers() { + Set result = new HashSet<>(); + + for (JsonListEntry entry : playerList.getProfileBans().getValues()) { + result.add(getOfflinePlayer(entry.getKey())); + } + + return result; + } + + @Override + public BanList getBanList(BanList.Type type) { + Validate.notNull(type, "Type cannot be null"); + + switch (type) { + case IP: + return new CraftIpBanList(playerList.getIPBans()); + case NAME: + default: + return new CraftProfileBanList(playerList.getProfileBans()); + } + } + + @Override + public void setWhitelist(boolean value) { + playerList.setHasWhitelist(value); + console.getPropertyManager().setProperty("white-list", value); + } + + @Override + public Set getWhitelistedPlayers() { + Set result = new LinkedHashSet<>(); + + for (JsonListEntry entry : playerList.getWhitelist().getValues()) { + result.add(getOfflinePlayer(entry.getKey())); + } + + return result; + } + + @Override + public Set getOperators() { + Set result = new HashSet<>(); + + for (JsonListEntry entry : playerList.getOPs().getValues()) { + result.add(getOfflinePlayer(entry.getKey())); + } + + return result; + } + + @Override + public void reloadWhitelist() { + playerList.reloadWhitelist(); + } + + @Override + public GameMode getDefaultGameMode() { + return GameMode.getByValue(console.worlds.get(0).getWorldData().getGameType().getId()); + } + + @Override + public void setDefaultGameMode(GameMode mode) { + Validate.notNull(mode, "Mode cannot be null"); + + for (World world : getWorlds()) { + ((CraftWorld) world).getHandle().worldData.setGameType(WorldSettings.EnumGamemode.getById(mode.getValue())); + } + } + + @Override + public ConsoleCommandSender getConsoleSender() { + return console.console; + } + + public EntityMetadataStore getEntityMetadata() { + return entityMetadata; + } + + public PlayerMetadataStore getPlayerMetadata() { + return playerMetadata; + } + + public WorldMetadataStore getWorldMetadata() { + return worldMetadata; + } + + @Override + public File getWorldContainer() { + if (this.getServer().universe != null) { + return this.getServer().universe; + } + + if (container == null) { + container = new File(configuration.getString("settings.world-container", ".")); + } + + return container; + } + + @Override + public OfflinePlayer[] getOfflinePlayers() { + WorldNBTStorage storage = (WorldNBTStorage) console.worlds.get(0).getDataManager(); + String[] files = storage.getPlayerDir().list(new DatFileFilter()); + Set players = new HashSet<>(); + + for (String file : files) { + try { + players.add(getOfflinePlayer(FastUUID.parseUUID(file.substring(0, file.length() - 4)))); + } catch (IllegalArgumentException ex) { + // Who knows what is in this directory, just ignore invalid files + } + } + + players.addAll(getOnlinePlayers()); + + return players.toArray(new OfflinePlayer[0]); + } + + @Override + public Messenger getMessenger() { + return messenger; + } + + @Override + public void sendPluginMessage(Plugin source, String channel, byte[] message) { + StandardMessenger.validatePluginMessage(getMessenger(), source, channel, message); + + for (Player player : getOnlinePlayers()) { + player.sendPluginMessage(source, channel, message); + } + } + + @Override + public Set getListeningPluginChannels() { + Set result = new HashSet<>(); + + for (Player player : getOnlinePlayers()) { + result.addAll(player.getListeningPluginChannels()); + } + + return result; + } + + @Override + public Inventory createInventory(InventoryHolder owner, InventoryType type) { + // TODO: Create the appropriate type, rather than Custom? + return new CraftInventoryCustom(owner, type); + } + + @Override + public Inventory createInventory(InventoryHolder owner, InventoryType type, String title) { + return new CraftInventoryCustom(owner, type, title); + } + + @Override + public Inventory createInventory(InventoryHolder owner, int size) throws IllegalArgumentException { + Validate.isTrue(size % 9 == 0, "Chests must have a size that is a multiple of 9!"); + return new CraftInventoryCustom(owner, size); + } + + @Override + public Inventory createInventory(InventoryHolder owner, int size, String title) throws IllegalArgumentException { + Validate.isTrue(size % 9 == 0, "Chests must have a size that is a multiple of 9!"); + return new CraftInventoryCustom(owner, size, title); + } + + @Override + public HelpMap getHelpMap() { + return helpMap; + } + + @Override // Paper - add override + public SimpleCommandMap getCommandMap() { + return commandMap; + } + + @Override + public int getMonsterSpawnLimit() { + return monsterSpawn; + } + + @Override + public int getAnimalSpawnLimit() { + return animalSpawn; + } + + @Override + public int getWaterAnimalSpawnLimit() { + return waterAnimalSpawn; + } + + @Override + public int getAmbientSpawnLimit() { + return ambientSpawn; + } + + public boolean isPrimaryThread() { + return console.primaryThread == null || Thread.currentThread().equals(console.primaryThread); + } + + @Override + public String getMotd() { + return console.getMotd(); + } + // PaperSpigot end + + @Override + public WarningState getWarningState() { + return warningState; + } + + public List tabComplete(net.minecraft.server.ICommandListener sender, String message) { + return tabComplete(sender, message, null); // PaperSpigot - location tab-completes. Original code here moved below + } + // PaperSpigot end + + // PaperSpigot start - add BlockPosition support + /* + this code is copied, except for the noted change, from the original tabComplete(net.minecraft.server.ICommandListener sender, String message) method + */ + public List tabComplete(net.minecraft.server.ICommandListener sender, String message, BlockPosition blockPosition) { + if (!(sender instanceof EntityPlayer)) { + return ImmutableList.of(); + } + + Player player = ((EntityPlayer) sender).getBukkitEntity(); + if (message.startsWith("/")) { + return tabCompleteCommand(player, message, blockPosition); + } else { + return tabCompleteChat(player, message); + } + } + + public List tabCompleteCommand(Player player, String message) { + return tabCompleteCommand(player, message, null); // PaperSpigot - location tab-completes. Original code here moved below + } + + // PaperSpigot start - add BlockPosition support + /* + this code is copied, except for the noted change, from the original tabCompleteCommand(Player player, String message) method + */ + public List tabCompleteCommand(Player player, String message, BlockPosition blockPosition) { + // Spigot Start + if ((org.spigotmc.SpigotConfig.tabComplete < 0 || message.length() <= org.spigotmc.SpigotConfig.tabComplete) && !message.contains(" ")) { + return ImmutableList.of(); + } + // Spigot End + + List completions = null; + try { + // send location info if present + // completions = getCommandMap().tabComplete(player, message.substring(1)); + if (blockPosition == null || !((CraftWorld) player.getWorld()).getHandle().paperSpigotConfig.allowBlockLocationTabCompletion) { + completions = getCommandMap().tabComplete(player, message.substring(1)); + } else { + completions = getCommandMap().tabComplete(player, message.substring(1), new Location(player.getWorld(), blockPosition.getX(), blockPosition.getY(), blockPosition.getZ())); + } + } catch (CommandException ex) { + player.sendMessage(ChatColor.RED + "An internal error occurred while attempting to tab-complete this command"); + getLogger().log(Level.SEVERE, "Exception when " + player.getName() + " attempted to tab complete " + message, ex); + } + + return completions == null ? ImmutableList.of() : completions; + } + + public List tabCompleteChat(Player player, String message) { + List completions = new ArrayList<>(); + PlayerChatTabCompleteEvent event = new PlayerChatTabCompleteEvent(player, message, completions); + String token = event.getLastToken(); + for (Player p : getOnlinePlayers()) { + if (player.canSee(p) && StringUtil.startsWithIgnoreCase(p.getName(), token)) + completions.add(p.getName()); + continue; + } + pluginManager.callEvent(event); + + // Sanity + completions.removeIf(Objects::isNull); + completions.sort(String.CASE_INSENSITIVE_ORDER); + return completions; + } + + @Override + public CraftItemFactory getItemFactory() { + return CraftItemFactory.instance(); + } + + @Override + public CraftScoreboardManager getScoreboardManager() { + return scoreboardManager; + } + + public void checkSaveState() { + if (this.playerCommandState || this.printSaveWarning || this.console.autosavePeriod <= 0) { + return; + } + this.printSaveWarning = true; + getLogger().log(Level.WARNING, "A manual (plugin-induced) save has been detected while server is configured to auto-save. This may affect performance.", warningState == WarningState.ON ? new Throwable() : null); + } + + @Override + public CraftIconCache getServerIcon() { + return icon; + } + + @Override + public CraftIconCache loadServerIcon(File file) throws Exception { + Validate.notNull(file, "File cannot be null"); + if (!file.isFile()) { + throw new IllegalArgumentException(file + " is not a file"); + } + return loadServerIcon0(file); + } + + @Override + public CraftIconCache loadServerIcon(BufferedImage image) throws Exception { + Validate.notNull(image, "Image cannot be null"); + return loadServerIcon0(image); + } + + @Override + public int getIdleTimeout() { + return console.getIdleTimeout(); + } + + @Override + public void setIdleTimeout(int threshold) { + console.setIdleTimeout(threshold); + } + + @Override + public ChunkGenerator.ChunkData createChunkData(World world) { + return new CraftChunkData(world); + } + + @Deprecated + @Override + public UnsafeValues getUnsafe() { + return CraftMagicNumbers.INSTANCE; + } + + public Spigot spigot() { + return spigot; + } + + private final class BooleanWrapper { + private boolean value = true; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftSound.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftSound.java new file mode 100644 index 0000000..2472565 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftSound.java @@ -0,0 +1,291 @@ +package org.bukkit.craftbukkit; + +import org.apache.commons.lang.Validate; +import org.bukkit.Sound; + +import static org.bukkit.Sound.*; + +public class CraftSound { + private static final String[] sounds = new String[Sound.values().length]; + + static { + // Ambient + set(AMBIENCE_CAVE, "ambient.cave.cave"); + set(AMBIENCE_RAIN, "ambient.weather.rain"); + set(AMBIENCE_THUNDER, "ambient.weather.thunder"); + // Damage + set(HURT_FLESH, "game.neutral.hurt"); + set(FALL_BIG, "game.neutral.hurt.fall.big"); + set(FALL_SMALL, "game.neutral.hurt.fall.small"); + // Dig Sounds + set(DIG_WOOL, "dig.cloth"); + set(DIG_GRASS, "dig.grass"); + set(DIG_GRAVEL, "dig.gravel"); + set(DIG_SAND, "dig.sand"); + set(DIG_SNOW, "dig.snow"); + set(DIG_STONE, "dig.stone"); + set(DIG_WOOD, "dig.wood"); + // Fire + set(FIRE, "fire.fire"); + set(FIRE_IGNITE, "fire.ignite"); + // Fireworks + set(FIREWORK_BLAST, "fireworks.blast"); + set(FIREWORK_BLAST2, "fireworks.blast_far"); + set(FIREWORK_LARGE_BLAST, "fireworks.largeBlast"); + set(FIREWORK_LARGE_BLAST2, "fireworks.largeBlast_far"); + set(FIREWORK_TWINKLE, "fireworks.twinkle"); + set(FIREWORK_TWINKLE2, "fireworks.twinkle_far"); + set(FIREWORK_LAUNCH, "fireworks.launch"); + // Liquid + set(SPLASH2, "game.neutral.swim.splash"); + set(SWIM, "game.neutral.swim"); + set(WATER, "liquid.water"); + set(LAVA, "liquid.lava"); + set(LAVA_POP, "liquid.lavapop"); + // Minecart + set(MINECART_BASE, "minecart.base"); + set(MINECART_INSIDE, "minecart.inside"); + // Mob + set(BAT_DEATH, "mob.bat.death"); + set(BAT_HURT, "mob.bat.hurt"); + set(BAT_IDLE, "mob.bat.idle"); + set(BAT_LOOP, "mob.bat.loop"); + set(BAT_TAKEOFF, "mob.bat.takeoff"); + set(BLAZE_BREATH, "mob.blaze.breathe"); + set(BLAZE_DEATH, "mob.blaze.death"); + set(BLAZE_HIT, "mob.blaze.hit"); + set(CAT_HISS, "mob.cat.hiss"); + set(CAT_HIT, "mob.cat.hitt"); + set(CAT_MEOW, "mob.cat.meow"); + set(CAT_PURR, "mob.cat.purr"); + set(CAT_PURREOW, "mob.cat.purreow"); + set(CHICKEN_IDLE, "mob.chicken.say"); + set(CHICKEN_HURT, "mob.chicken.hurt"); + set(CHICKEN_EGG_POP, "mob.chicken.plop"); + set(CHICKEN_WALK, "mob.chicken.step"); + set(COW_HURT, "mob.cow.hurt"); + set(COW_IDLE, "mob.cow.say"); + set(COW_WALK, "mob.cow.step"); + set(CREEPER_DEATH, "mob.creeper.death"); + set(CREEPER_HISS, "mob.creeper.say"); + set(ENDERDRAGON_DEATH, "mob.enderdragon.end"); + set(ENDERDRAGON_GROWL, "mob.enderdragon.growl"); + set(ENDERDRAGON_HIT, "mob.enderdragon.hit"); + set(ENDERDRAGON_WINGS, "mob.enderdragon.wings"); + set(ENDERMAN_DEATH, "mob.endermen.death"); + set(ENDERMAN_HIT, "mob.endermen.hit"); + set(ENDERMAN_IDLE, "mob.endermen.idle"); + set(ENDERMAN_TELEPORT, "mob.endermen.portal"); + set(ENDERMAN_SCREAM, "mob.endermen.scream"); + set(ENDERMAN_STARE, "mob.endermen.stare"); + set(GHAST_SCREAM2, "mob.ghast.affectionate_scream"); + set(GHAST_CHARGE, "mob.ghast.charge"); + set(GHAST_DEATH, "mob.ghast.death"); + set(GHAST_FIREBALL, "mob.ghast.fireball"); + set(GHAST_MOAN, "mob.ghast.moan"); + set(GHAST_SCREAM, "mob.ghast.scream"); + set(HORSE_ANGRY, "mob.horse.angry"); + set(HORSE_ARMOR, "mob.horse.armor"); + set(HORSE_BREATHE, "mob.horse.breathe"); + set(HORSE_DEATH, "mob.horse.death"); + set(HORSE_GALLOP, "mob.horse.gallop"); + set(HORSE_HIT, "mob.horse.hit"); + set(HORSE_IDLE, "mob.horse.idle"); + set(HORSE_JUMP, "mob.horse.jump"); + set(HORSE_LAND, "mob.horse.land"); + set(HORSE_SADDLE, "mob.horse.leather"); + set(HORSE_SOFT, "mob.horse.soft"); + set(HORSE_WOOD, "mob.horse.wood"); + set(DONKEY_ANGRY, "mob.horse.donkey.angry"); + set(DONKEY_DEATH, "mob.horse.donkey.death"); + set(DONKEY_HIT, "mob.horse.donkey.hit"); + set(DONKEY_IDLE, "mob.horse.donkey.idle"); + set(HORSE_SKELETON_DEATH, "mob.horse.skeleton.death"); + set(HORSE_SKELETON_HIT, "mob.horse.skeleton.hit"); + set(HORSE_SKELETON_IDLE, "mob.horse.skeleton.idle"); + set(HORSE_ZOMBIE_DEATH, "mob.horse.zombie.death"); + set(HORSE_ZOMBIE_HIT, "mob.horse.zombie.hit"); + set(HORSE_ZOMBIE_IDLE, "mob.horse.zombie.idle"); + set(IRONGOLEM_DEATH, "mob.irongolem.death"); + set(IRONGOLEM_HIT, "mob.irongolem.hit"); + set(IRONGOLEM_THROW, "mob.irongolem.throw"); + set(IRONGOLEM_WALK, "mob.irongolem.walk"); + set(MAGMACUBE_WALK, "mob.magmacube.small"); + set(MAGMACUBE_WALK2, "mob.magmacube.big"); + set(MAGMACUBE_JUMP, "mob.magmacube.jump"); + set(PIG_IDLE, "mob.pig.say"); + set(PIG_DEATH, "mob.pig.death"); + set(PIG_WALK, "mob.pig.step"); + set(SHEEP_IDLE, "mob.sheep.say"); + set(SHEEP_SHEAR, "mob.sheep.shear"); + set(SHEEP_WALK, "mob.sheep.step"); + set(SILVERFISH_HIT, "mob.silverfish.hit"); + set(SILVERFISH_KILL, "mob.silverfish.kill"); + set(SILVERFISH_IDLE, "mob.silverfish.say"); + set(SILVERFISH_WALK, "mob.silverfish.step"); + set(SKELETON_IDLE, "mob.skeleton.say"); + set(SKELETON_DEATH, "mob.skeleton.death"); + set(SKELETON_HURT, "mob.skeleton.hurt"); + set(SKELETON_WALK, "mob.skeleton.step"); + set(SLIME_ATTACK, "mob.slime.attack"); + set(SLIME_WALK, "mob.slime.small"); + set(SLIME_WALK2, "mob.slime.big"); + set(SPIDER_IDLE, "mob.spider.say"); + set(SPIDER_DEATH, "mob.spider.death"); + set(SPIDER_WALK, "mob.spider.step"); + set(VILLAGER_DEATH, "mob.villager.death"); + set(VILLAGER_HAGGLE, "mob.villager.haggle"); + set(VILLAGER_HIT, "mob.villager.hit"); + set(VILLAGER_IDLE, "mob.villager.idle"); + set(VILLAGER_NO, "mob.villager.no"); + set(VILLAGER_YES, "mob.villager.yes"); + set(WITHER_DEATH, "mob.wither.death"); + set(WITHER_HURT, "mob.wither.hurt"); + set(WITHER_IDLE, "mob.wither.idle"); + set(WITHER_SHOOT, "mob.wither.shoot"); + set(WITHER_SPAWN, "mob.wither.spawn"); + set(WOLF_BARK, "mob.wolf.bark"); + set(WOLF_DEATH, "mob.wolf.death"); + set(WOLF_GROWL, "mob.wolf.growl"); + set(WOLF_HOWL, "mob.wolf.howl"); + set(WOLF_HURT, "mob.wolf.hurt"); + set(WOLF_PANT, "mob.wolf.panting"); + set(WOLF_SHAKE, "mob.wolf.shake"); + set(WOLF_WALK, "mob.wolf.step"); + set(WOLF_WHINE, "mob.wolf.whine"); + set(ZOMBIE_METAL, "mob.zombie.metal"); + set(ZOMBIE_WOOD, "mob.zombie.wood"); + set(ZOMBIE_WOODBREAK, "mob.zombie.woodbreak"); + set(ZOMBIE_IDLE, "mob.zombie.say"); + set(ZOMBIE_DEATH, "mob.zombie.death"); + set(ZOMBIE_HURT, "mob.zombie.hurt"); + set(ZOMBIE_INFECT, "mob.zombie.infect"); + set(ZOMBIE_UNFECT, "mob.zombie.unfect"); + set(ZOMBIE_REMEDY, "mob.zombie.remedy"); + set(ZOMBIE_WALK, "mob.zombie.step"); + set(ZOMBIE_PIG_IDLE, "mob.zombiepig.zpig"); + set(ZOMBIE_PIG_ANGRY, "mob.zombiepig.zpigangry"); + set(ZOMBIE_PIG_DEATH, "mob.zombiepig.zpigdeath"); + set(ZOMBIE_PIG_HURT, "mob.zombiepig.zpighurt"); + // Note (blocks) + set(NOTE_BASS_GUITAR, "note.bassattack"); + set(NOTE_SNARE_DRUM, "note.snare"); + set(NOTE_PLING, "note.pling"); + set(NOTE_BASS, "note.bass"); + set(NOTE_PIANO, "note.harp"); + set(NOTE_BASS_DRUM, "note.bd"); + set(NOTE_STICKS, "note.hat"); + // Portal + set(PORTAL, "portal.portal"); + set(PORTAL_TRAVEL, "portal.travel"); + set(PORTAL_TRIGGER, "portal.trigger"); + // Random + set(ANVIL_BREAK, "random.anvil_break"); + set(ANVIL_LAND, "random.anvil_land"); + set(ANVIL_USE, "random.anvil_use"); + set(SHOOT_ARROW, "random.bow"); + set(ARROW_HIT, "random.bowhit"); + set(ITEM_BREAK, "random.break"); + set(BURP, "random.burp"); + set(CHEST_CLOSE, "random.chestclosed"); + set(CHEST_OPEN, "random.chestopen"); + set(CLICK, "random.click"); + set(DOOR_CLOSE, "random.door_close"); + set(DOOR_OPEN, "random.door_open"); + set(DRINK, "random.drink"); + set(EAT, "random.eat"); + set(EXPLODE, "random.explode"); + set(FIZZ, "random.fizz"); + set(FUSE, "creeper.primed"); + set(GLASS, "dig.glass"); + set(LEVEL_UP, "random.levelup"); + set(ORB_PICKUP, "random.orb"); + set(ITEM_PICKUP, "random.pop"); + set(SPLASH, "random.splash"); + set(SUCCESSFUL_HIT, "random.successful_hit"); + set(WOOD_CLICK, "random.wood_click"); + // Step + set(STEP_WOOL, "step.cloth"); + set(STEP_GRASS, "step.grass"); + set(STEP_GRAVEL, "step.gravel"); + set(STEP_LADDER, "step.ladder"); + set(STEP_SAND, "step.sand"); + set(STEP_SNOW, "step.snow"); + set(STEP_STONE, "step.stone"); + set(STEP_WOOD, "step.wood"); + // Tile + set(PISTON_EXTEND, "tile.piston.out"); + set(PISTON_RETRACT, "tile.piston.in"); + // Beanes start - add missing sound + set(UI_BUTTON_CLICK, "gui.button.press"); + set(RECORD_11, "records.11"); + set(RECORD_13, "records.13"); + set(RECORD_BLOCKS, "records.blocks"); + set(RECORD_CAT, "records.cat"); + set(RECORD_CHIRP, "records.chirp"); + set(RECORD_FAR, "records.far"); + set(RECORD_MALL, "records.mall"); + set(RECORD_MELLOHI, "records.mellohi"); + set(RECORD_STAL, "records.stal"); + set(RECORD_STRAD, "records.strad"); + set(RECORD_WAIT, "records.wait"); + set(RECORD_WARD, "records.ward"); + + set(MUSIC_GAME, "music.game"); + set(MUSIC_CREATIVE, "music.game.creative"); + set(MUSIC_END, "music.game.end"); + set(MUSIC_CREDITS, "music.game.end.credits"); + set(MUSIC_DRAGON, "music.game.end.dragon"); + set(MUSIC_NETHER, "music.game.nether"); + set(MUSIC_MENU, "music.menu"); + + set(ITEM_FIRECHARGE_USE, "item.fireCharge.use"); + + set(GUARDIAN_ATTACK, "mob.guardian.attack"); + set(GUARDIAN_IDLE, "mob.guardian.idle"); + set(GUARDIAN_IDLE_LAND, "mob.guardian.land.idle"); + set(GUARDIAN_IDLE_ELDER, "mob.guardian.elder.idle"); + set(GUARDIAN_HIT, "mob.guardian.hit"); + set(GUARDIAN_HIT_LAND, "mob.guardian.land.hit"); + set(GUARDIAN_HIT_ELDER, "mob.guardian.elder.hit"); + set(GUARDIAN_DEATH, "mob.guardian.death"); + set(GUARDIAN_DEATH_LAND, "mob.guardian.land.death"); + set(GUARDIAN_DEATH_ELDER, "mob.guardian.elder.death"); + set(GUARDIAN_FLOP, "mob.guardian.flop"); + set(GUARDIAN_CURSE, "mob.guardian.curse"); + + + set(RABBIT_DEATH, "mob.rabbit.death"); + set(RABBIT_HOP, "mob.rabbit.hop"); + set(RABBIT_HURT, "mob.rabbit.hurt"); + set(RABBIT_IDLE, "mob.rabbit.idle"); + + set(HOSTILE_DIE, "game.hostile.die"); + set(HOSTILE_HURT, "game.hostile.hurt"); + set(HOSTILE_HURT_FALL_BIG, "game.hostile.hurt.fall.big"); + set(HOSTILE_HURT_FALL_SMALL, "game.hostile.hurt.fall.small"); + set(HOSTILE_SWIM, "game.hostile.swim"); + set(HOSTILE_SWIM_SPLASH, "game.hostile.swim.splash"); + set(NEUTRAL_DIE, "game.neutral.die"); + set(PLAYER_DIE, "game.player.die"); + set(PLAYER_HURT, "game.player.hurt"); + set(PLAYER_HURT_FALL_BIG, "game.player.hurt.fall.big"); + set(PLAYER_HURT_FALL_SMALL, "game.player.hurt.fall.small"); + set(PLAYER_SWIM, "game.player.swim"); + set(PLAYER_SWIM_SPLASH, "game.player.swim.splash"); + set(POTION_SMASH, "game.potion.smash"); + set(TNT_PRIMED, "game.tnt.primed"); + // Beanes end + } + + private static void set(Sound sound, String key) { + sounds[sound.ordinal()] = key; + } + + public static String getSound(final Sound sound) { + Validate.notNull(sound, "Sound cannot be null"); + return sounds[sound.ordinal()]; + } + + private CraftSound() {} +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftStatistic.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftStatistic.java new file mode 100644 index 0000000..ba05fac --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftStatistic.java @@ -0,0 +1,146 @@ +package org.bukkit.craftbukkit; + +import com.google.common.base.CaseFormat; +import com.google.common.collect.BiMap; +import com.google.common.collect.ImmutableBiMap; +import com.google.common.collect.ImmutableMap; +import net.minecraft.server.*; +import net.minecraft.server.EntityTypes.MonsterEggInfo; +import org.bukkit.Achievement; +import org.bukkit.Material; +import org.bukkit.Statistic; +import org.bukkit.entity.EntityType; + +public class CraftStatistic { + private static final BiMap statistics; + private static final BiMap achievements; + + static { + ImmutableMap specialCases = ImmutableMap. builder() + .put("achievement.buildWorkBench", Achievement.BUILD_WORKBENCH) + .put("achievement.diamonds", Achievement.GET_DIAMONDS) + .put("achievement.portal", Achievement.NETHER_PORTAL) + .put("achievement.ghast", Achievement.GHAST_RETURN) + .put("achievement.theEnd", Achievement.END_PORTAL) + .put("achievement.theEnd2", Achievement.THE_END) + .put("achievement.blazeRod", Achievement.GET_BLAZE_ROD) + .put("achievement.potion", Achievement.BREW_POTION) + .build(); + ImmutableBiMap.Builder statisticBuilder = ImmutableBiMap.builder(); + ImmutableBiMap.Builder achievementBuilder = ImmutableBiMap.builder(); + for (Statistic statistic : Statistic.values()) { + if (statistic == Statistic.PLAY_ONE_TICK) { + statisticBuilder.put("stat.playOneMinute", statistic); + } else { + statisticBuilder.put("stat." + CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, statistic.name()), statistic); + } + } + for (Achievement achievement : Achievement.values()) { + if (specialCases.containsValue(achievement)) { + continue; + } + achievementBuilder.put("achievement." + CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, achievement.name()), achievement); + } + + achievementBuilder.putAll(specialCases); + + statistics = statisticBuilder.build(); + achievements = achievementBuilder.build(); + } + + private CraftStatistic() {} + + public static org.bukkit.Achievement getBukkitAchievement(net.minecraft.server.Achievement achievement) { + return getBukkitAchievementByName(achievement.name); + } + + public static org.bukkit.Achievement getBukkitAchievementByName(String name) { + return achievements.get(name); + } + + public static org.bukkit.Statistic getBukkitStatistic(net.minecraft.server.Statistic statistic) { + return getBukkitStatisticByName(statistic.name); + } + + public static org.bukkit.Statistic getBukkitStatisticByName(String name) { + if (name.startsWith("stat.killEntity")) { + name = "stat.killEntity"; + } + if (name.startsWith("stat.entityKilledBy")) { + name = "stat.entityKilledBy"; + } + if (name.startsWith("stat.breakItem")) { + name = "stat.breakItem"; + } + if (name.startsWith("stat.useItem")) { + name = "stat.useItem"; + } + if (name.startsWith("stat.mineBlock")) { + name = "stat.mineBlock"; + } + if (name.startsWith("stat.craftItem")) { + name = "stat.craftItem"; + } + return statistics.get(name); + } + + public static net.minecraft.server.Statistic getNMSStatistic(org.bukkit.Statistic statistic) { + return StatisticList.getStatistic(statistics.inverse().get(statistic)); + } + + public static net.minecraft.server.Achievement getNMSAchievement(org.bukkit.Achievement achievement) { + return (net.minecraft.server.Achievement) StatisticList.getStatistic(achievements.inverse().get(achievement)); + } + + public static net.minecraft.server.Statistic getMaterialStatistic(org.bukkit.Statistic stat, Material material) { + try { + if (stat == Statistic.MINE_BLOCK) { + return StatisticList.MINE_BLOCK_COUNT[material.getId()]; + } + if (stat == Statistic.CRAFT_ITEM) { + return StatisticList.CRAFT_BLOCK_COUNT[material.getId()]; + } + if (stat == Statistic.USE_ITEM) { + return StatisticList.USE_ITEM_COUNT[material.getId()]; + } + if (stat == Statistic.BREAK_ITEM) { + return StatisticList.BREAK_ITEM_COUNT[material.getId()]; + } + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + return null; + } + + public static net.minecraft.server.Statistic getEntityStatistic(org.bukkit.Statistic stat, EntityType entity) { + MonsterEggInfo monsteregginfo = EntityTypes.eggInfo.get(Integer.valueOf(entity.getTypeId())); + + if (monsteregginfo != null) { + return monsteregginfo.killEntityStatistic; + } + return null; + } + + public static EntityType getEntityTypeFromStatistic(net.minecraft.server.Statistic statistic) { + String statisticString = statistic.name; + return EntityType.fromName(statisticString.substring(statisticString.lastIndexOf(".") + 1)); + } + + public static Material getMaterialFromStatistic(net.minecraft.server.Statistic statistic) { + String statisticString = statistic.name; + String val = statisticString.substring(statisticString.lastIndexOf(".") + 1); + Item item = Item.REGISTRY.get(new MinecraftKey(val)); + if (item != null) { + return Material.getMaterial(Item.getId(item)); + } + Block block = Block.REGISTRY.get(new MinecraftKey(val)); + if (block != null) { + return Material.getMaterial(Block.getId(block)); + } + try { + return Material.getMaterial(Integer.parseInt(val)); + } catch (NumberFormatException e) { + return null; + } + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftTravelAgent.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftTravelAgent.java new file mode 100644 index 0000000..a5daf94 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftTravelAgent.java @@ -0,0 +1,94 @@ +package org.bukkit.craftbukkit; + +import net.minecraft.server.BlockPosition; +import net.minecraft.server.PortalTravelAgent; +import net.minecraft.server.WorldServer; +import org.bukkit.Location; +import org.bukkit.TravelAgent; + +public class CraftTravelAgent extends PortalTravelAgent implements TravelAgent { + + public static TravelAgent DEFAULT = null; + + private int searchRadius = 128; + private int creationRadius = 16; + private boolean canCreatePortal = true; + + public CraftTravelAgent(WorldServer worldserver) { + super(worldserver); + if (DEFAULT == null && worldserver.dimension == 0) { + DEFAULT = this; + } + } + + @Override + public Location findOrCreate(Location target) { + WorldServer worldServer = ((CraftWorld) target.getWorld()).getHandle(); + boolean before = worldServer.chunkProviderServer.forceChunkLoad; + worldServer.chunkProviderServer.forceChunkLoad = true; + + Location found = this.findPortal(target); + if (found == null) { + if (this.getCanCreatePortal() && this.createPortal(target)) { + found = this.findPortal(target); + } else { + found = target; // fallback to original if unable to find or create + } + } + + worldServer.chunkProviderServer.forceChunkLoad = before; + return found; + } + + @Override + public Location findPortal(Location location) { + PortalTravelAgent pta = ((CraftWorld) location.getWorld()).getHandle().getTravelAgent(); + + // Migot start + BlockPosition found = pta.findPortal(location.getX(), location.getY(), location.getZ(), 10); + if (found == null) { + found = pta.findPortal(location.getX(), location.getY(), location.getZ(), this.getSearchRadius()); + } + // Migot end + + return found != null ? new Location(location.getWorld(), found.getX(), found.getY(), found.getZ(), location.getYaw(), location.getPitch()) : null; + } + + @Override + public boolean createPortal(Location location) { + PortalTravelAgent pta = ((CraftWorld) location.getWorld()).getHandle().getTravelAgent(); + return pta.createPortal(location.getX(), location.getY(), location.getZ(), this.getCreationRadius()); + } + + @Override + public TravelAgent setSearchRadius(int radius) { + this.searchRadius = radius; + return this; + } + + @Override + public int getSearchRadius() { + return this.searchRadius; + } + + @Override + public TravelAgent setCreationRadius(int radius) { + this.creationRadius = radius < 2 ? 0 : radius; + return this; + } + + @Override + public int getCreationRadius() { + return this.creationRadius; + } + + @Override + public boolean getCanCreatePortal() { + return this.canCreatePortal; + } + + @Override + public void setCanCreatePortal(boolean create) { + this.canCreatePortal = create; + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftWorld.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftWorld.java new file mode 100644 index 0000000..e54a193 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftWorld.java @@ -0,0 +1,1473 @@ +package org.bukkit.craftbukkit; + +import com.google.common.base.Preconditions; +import net.minecraft.server.*; +import org.apache.commons.lang.Validate; +import org.bukkit.Chunk; +import org.bukkit.ChunkSnapshot; +import org.bukkit.World; +import org.bukkit.WorldBorder; +import org.bukkit.*; +import org.bukkit.block.Biome; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.block.BlockState; +import org.bukkit.craftbukkit.block.CraftBlock; +import org.bukkit.craftbukkit.block.CraftBlockState; +import org.bukkit.craftbukkit.entity.CraftItem; +import org.bukkit.craftbukkit.entity.CraftLightningStrike; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.craftbukkit.metadata.SpecializedBlockMetadataStore; +import org.bukkit.craftbukkit.util.CraftMagicNumbers; +import org.bukkit.craftbukkit.util.LongHash; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Item; +import org.bukkit.entity.*; +import org.bukkit.entity.minecart.PoweredMinecart; +import org.bukkit.entity.minecart.StorageMinecart; +import org.bukkit.entity.minecart.*; +import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason; +import org.bukkit.event.world.SpawnChangeEvent; +import org.bukkit.generator.BlockPopulator; +import org.bukkit.generator.ChunkGenerator; +import org.bukkit.inventory.ItemStack; +import org.bukkit.metadata.MetadataValue; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.messaging.StandardMessenger; +import org.bukkit.util.Vector; +import org.github.paperspigot.exception.ServerInternalException; + +import java.io.File; +import java.util.*; + +public class CraftWorld implements World { + public static final int CUSTOM_DIMENSION_OFFSET = 10; + private static final Random rand = new Random(); + private final WorldServer world; + private final CraftServer server = (CraftServer) Bukkit.getServer(); + private final ChunkGenerator generator; + private final List populators = new ArrayList<>(); + private final SpecializedBlockMetadataStore blockMetadata = new SpecializedBlockMetadataStore(this); // Azurite - better block metadata store + private WorldBorder worldBorder; + private Environment environment; + private int monsterSpawn = -1; + private int animalSpawn = -1; + private int waterAnimalSpawn = -1; + private int ambientSpawn = -1; + private int chunkLoadCount = 0; + private int chunkGCTickCount; + + public CraftWorld(WorldServer world, ChunkGenerator gen, Environment env) { + this.world = world; + this.generator = gen; + + environment = env; + + if (server.chunkGCPeriod > 0) { + chunkGCTickCount = rand.nextInt(server.chunkGCPeriod); + } + } + + private static void randomLocationWithinBlock(Location loc, double xs, double ys, double zs) { + double prevX = loc.getX(); + double prevY = loc.getY(); + double prevZ = loc.getZ(); + loc.add(xs, ys, zs); + if (loc.getX() < Math.floor(prevX)) { + loc.setX(Math.floor(prevX)); + } + if (loc.getX() >= Math.ceil(prevX)) { + loc.setX(Math.ceil(prevX - 0.01)); + } + if (loc.getY() < Math.floor(prevY)) { + loc.setY(Math.floor(prevY)); + } + if (loc.getY() >= Math.ceil(prevY)) { + loc.setY(Math.ceil(prevY - 0.01)); + } + if (loc.getZ() < Math.floor(prevZ)) { + loc.setZ(Math.floor(prevZ)); + } + if (loc.getZ() >= Math.ceil(prevZ)) { + loc.setZ(Math.ceil(prevZ - 0.01)); + } + } + + public Block getBlockAt(int x, int y, int z) { + return getChunkAt(x >> 4, z >> 4).getBlock(x & 0xF, y, z & 0xF); + } + + public int getBlockTypeIdAt(int x, int y, int z) { + return CraftMagicNumbers.getId(world.getType(x, y, z).getBlock()); + } + + public int getHighestBlockYAt(int x, int z) { + if (!isChunkLoaded(x >> 4, z >> 4)) { + loadChunk(x >> 4, z >> 4); + } + + return world.getHighestBlockYAt(x, z, true); + } + + public Location getSpawnLocation() { + BlockPosition spawn = world.getSpawn(); + return new Location(this, spawn.getX(), spawn.getY(), spawn.getZ()); + } + + public boolean setSpawnLocation(int x, int y, int z) { + try { + Location previousLocation = getSpawnLocation(); + world.worldData.setSpawn(new BlockPosition(x, y, z)); + + // Notify anyone who's listening. + SpawnChangeEvent event = new SpawnChangeEvent(this, previousLocation); + server.getPluginManager().callEvent(event); + + return true; + } catch (Exception e) { + return false; + } + } + + // PaperSpigot start - Async chunk load API + public void getChunkAtAsync(final int x, final int z, final ChunkLoadCallback callback) { + final ChunkProviderServer cps = this.world.chunkProviderServer; + cps.getChunkAt(x, z, () -> callback.onLoad(cps.getChunkAt(x, z).bukkitChunk)); + } + + public void getChunkAtAsync(Block block, ChunkLoadCallback callback) { + getChunkAtAsync(block.getX() >> 4, block.getZ() >> 4, callback); + } + // PaperSpigot end + + public void getChunkAtAsync(Location location, ChunkLoadCallback callback) { + getChunkAtAsync(location.getBlockX() >> 4, location.getBlockZ() >> 4, callback); + } + + public Chunk getChunkAt(int x, int z) { + return this.world.chunkProviderServer.getChunkAt(x, z).bukkitChunk; + } + + public Chunk getChunkAt(Block block) { + return getChunkAt(block.getX() >> 4, block.getZ() >> 4); + } + + public boolean isChunkLoaded(int x, int z) { + return world.chunkProviderServer.isChunkLoaded(x, z); + } + + public Chunk[] getLoadedChunks() { + Object[] chunks = world.chunkProviderServer.chunks.values().toArray(); + org.bukkit.Chunk[] craftChunks = new CraftChunk[chunks.length]; + + for (int i = 0; i < chunks.length; i++) { + net.minecraft.server.Chunk chunk = (net.minecraft.server.Chunk) chunks[i]; + craftChunks[i] = chunk.bukkitChunk; + } + + return craftChunks; + } + + public void loadChunk(int x, int z) { + loadChunk(x, z, true); + } + + public boolean unloadChunk(Chunk chunk) { + return unloadChunk(chunk.getX(), chunk.getZ()); + } + + public boolean unloadChunk(int x, int z) { + return unloadChunk(x, z, true); + } + + public boolean unloadChunk(int x, int z, boolean save) { + return unloadChunk(x, z, save, false); + } + + public boolean unloadChunkRequest(int x, int z) { + return unloadChunkRequest(x, z, true); + } + + public boolean unloadChunkRequest(int x, int z, boolean safe) { + org.spigotmc.AsyncCatcher.catchOp("chunk unload"); // Spigot + if (safe && isChunkInUse(x, z)) { + return false; + } + + world.chunkProviderServer.queueUnload(x, z); + + return true; + } + + public boolean unloadChunk(int x, int z, boolean save, boolean safe) { + org.spigotmc.AsyncCatcher.catchOp("chunk unload"); // Spigot + if (safe && isChunkInUse(x, z)) { + return false; + } + + long hash = LongHash.toLong(x, z); + net.minecraft.server.Chunk chunk = world.chunkProviderServer.getChunkIfLoaded(hash); + // PaperSpigot start - Don't create a chunk just to unload it + if (chunk == null) { // Vortex + return false; + } + // PaperSpigot end + if (chunk.mustSave) { // If chunk had previously been queued to save, must do save to avoid loss of that data + save = true; + } + + chunk.removeEntities(); // Always remove entities - even if discarding, need to get them out of world table + + if (save && !(chunk instanceof EmptyChunk)) { + world.chunkProviderServer.saveChunk(chunk); + world.chunkProviderServer.saveChunkNOP(chunk); + } + + world.chunkProviderServer.unloadQueue.remove(hash); + world.chunkProviderServer.chunks.remove(hash); + world.chunkTickList.remove(hash); // Beanes - optimized chunk ticking + + return true; + } + + public boolean regenerateChunk(int x, int z) { + long hash = LongHash.toLong(x, z); + unloadChunk(x, z, false, false); + world.chunkProviderServer.unloadQueue.remove(hash); + + net.minecraft.server.Chunk chunk; + + if (world.chunkProviderServer.chunkProvider == null) { + chunk = world.chunkProviderServer.emptyChunk; + } else { + chunk = world.chunkProviderServer.chunkProvider.getOrCreateChunk(hash, x, z); + } + + chunkLoadPostProcess(chunk, x, z); + + refreshChunk(x, z); + + return chunk != null; + } + + public boolean refreshChunk(int x, int z) { + if (!isChunkLoaded(x, z)) { + return false; + } + + int px = x << 4; + int pz = z << 4; + + // If there are more than 64 updates to a chunk at once, it will update all 'touched' sections within the chunk + // And will include biome data if all sections have been 'touched' + // This flags 65 blocks distributed across all the sections of the chunk, so that everything is sent, including biomes + int height = getMaxHeight() / 16; + for (int idx = 0; idx < 64; idx++) { + world.notify(px + (idx / height), ((idx % height) * 16), pz); // Azurite - reduce block position usage + } + world.notify(px + 15, (height * 16) - 1, pz + 15); + return true; + } + + public boolean isChunkInUse(int x, int z) { + return world.getPlayerChunkMap().isChunkInUse(x, z); + } + + public boolean loadChunk(int x, int z, boolean generate) { + org.spigotmc.AsyncCatcher.catchOp("chunk load"); // Spigot + chunkLoadCount++; + if (generate) { + // Use the default variant of loadChunk when generate == true. + return world.chunkProviderServer.getChunkAt(x, z) != null; + } + + long hash = LongHash.toLong(x, z); + world.chunkProviderServer.unloadQueue.remove(hash); + net.minecraft.server.Chunk chunk = world.chunkProviderServer.chunks.get(hash); + + if (chunk == null) { + chunk = world.chunkProviderServer.loadChunk(x, z); + + chunkLoadPostProcess(chunk, x, z); + } + return chunk != null; + } + + private void chunkLoadPostProcess(net.minecraft.server.Chunk chunk, int cx, int cz) { + if (chunk != null) { + world.chunkProviderServer.chunks.put(chunk.chunkHashKey, chunk); + + chunk.addEntities(); + + // Update neighbor counts + for (int x = -2; x < 3; x++) { + for (int z = -2; z < 3; z++) { + if (x == 0 && z == 0) { + continue; + } + + net.minecraft.server.Chunk neighbor = world.chunkProviderServer.getChunkIfLoaded(chunk.locX + x, chunk.locZ + z); + if (neighbor != null) { + neighbor.setNeighborLoaded(-x, -z); + chunk.setNeighborLoaded(x, z); + } + } + } + // CraftBukkit end + + chunk.loadNearby(world.chunkProviderServer, world.chunkProviderServer, cx, cz); + } + } + + public boolean isChunkLoaded(Chunk chunk) { + return isChunkLoaded(chunk.getX(), chunk.getZ()); + } + + public void loadChunk(Chunk chunk) { + loadChunk(chunk.getX(), chunk.getZ()); + ((CraftChunk) getChunkAt(chunk.getX(), chunk.getZ())).getHandle().bukkitChunk = chunk; + } + + public WorldServer getHandle() { + return world; + } + + public Item dropItem(Location loc, ItemStack item) { + return this.dropItem(loc, item, null); + } + + public Item dropItem(Location loc, ItemStack item, net.minecraft.server.Entity owner) { + Validate.notNull(item, "Cannot drop a Null item."); + Validate.isTrue(item.getTypeId() != 0, "Cannot drop AIR."); + EntityItem entity = new EntityItem(world, loc.getX(), loc.getY(), loc.getZ(), CraftItemStack.asNMSCopy(item)); + entity.reEncodeByServerValues(); // Beanes - improve item tracking + entity.owner = owner; + entity.pickupDelay = 10; + world.addEntity(entity); + // TODO this is inconsistent with how Entity.getBukkitEntity() works. + // However, this entity is not at the moment backed by a server entity class so it may be left. + return new CraftItem(world.getServer(), entity); + } + + public Item dropItemNaturally(Location loc, ItemStack item) { + return dropItemNaturally(loc, item, null); + } + + public Item dropItemNaturally(Location loc, ItemStack item, net.minecraft.server.Entity owner) { + double xs = world.random.nextFloat() * 0.7F - 0.35D; + double ys = world.random.nextFloat() * 0.7F - 0.35D; + double zs = world.random.nextFloat() * 0.7F - 0.35D; + loc = loc.clone(); + // Makes sure the new item is created within the block the location points to. + // This prevents item spill in 1-block wide farms. + randomLocationWithinBlock(loc, xs, ys, zs); + return dropItem(loc, item, owner); + } + + public Arrow spawnArrow(Location loc, Vector velocity, float speed, float spread) { + Validate.notNull(loc, "Can not spawn arrow with a null location"); + Validate.notNull(velocity, "Can not spawn arrow with a null velocity"); + + EntityArrow arrow = new EntityArrow(world); + arrow.setPositionRotation(loc.getX(), loc.getY(), loc.getZ(), loc.getYaw(), loc.getPitch()); + arrow.shoot(velocity.getX(), velocity.getY(), velocity.getZ(), speed, spread); + world.addEntity(arrow); + return (Arrow) arrow.getBukkitEntity(); + } + + @Deprecated + public LivingEntity spawnCreature(Location loc, CreatureType creatureType) { + return spawnCreature(loc, creatureType.toEntityType()); + } + + @Deprecated + public LivingEntity spawnCreature(Location loc, EntityType creatureType) { + Validate.isTrue(creatureType.isAlive(), "EntityType not instance of LivingEntity"); + return (LivingEntity) spawnEntity(loc, creatureType); + } + + public Entity spawnEntity(Location loc, EntityType entityType) { + return spawn(loc, entityType.getEntityClass()); + } + + public LightningStrike strikeLightning(Location loc) { + EntityLightning lightning = new EntityLightning(world, loc.getX(), loc.getY(), loc.getZ()); + world.strikeLightning(lightning); + return new CraftLightningStrike(server, lightning); + } + + public LightningStrike strikeLightningEffect(Location loc) { + EntityLightning lightning = new EntityLightning(world, loc.getX(), loc.getY(), loc.getZ(), true); + world.strikeLightning(lightning); + return new CraftLightningStrike(server, lightning); + } + + public boolean generateTree(Location loc, TreeType type) { + net.minecraft.server.WorldGenerator gen; + switch (type) { + case BIG_TREE: + gen = new WorldGenBigTree(true); + break; + case BIRCH: + gen = new WorldGenForest(true, false); + break; + case REDWOOD: + gen = new WorldGenTaiga2(true); + break; + case TALL_REDWOOD: + gen = new WorldGenTaiga1(); + break; + case JUNGLE: + IBlockData iblockdata1 = Blocks.LOG.getBlockData().set(BlockLog1.VARIANT, BlockWood.EnumLogVariant.JUNGLE); + IBlockData iblockdata2 = Blocks.LEAVES.getBlockData().set(BlockLeaves1.VARIANT, BlockWood.EnumLogVariant.JUNGLE).set(BlockLeaves.CHECK_DECAY, false); + gen = new WorldGenJungleTree(true, 10, 20, iblockdata1, iblockdata2); // Magic values as in BlockSapling + break; + case SMALL_JUNGLE: + iblockdata1 = Blocks.LOG.getBlockData().set(BlockLog1.VARIANT, BlockWood.EnumLogVariant.JUNGLE); + iblockdata2 = Blocks.LEAVES.getBlockData().set(BlockLeaves1.VARIANT, BlockWood.EnumLogVariant.JUNGLE).set(BlockLeaves.CHECK_DECAY, false); + gen = new WorldGenTrees(true, 4 + rand.nextInt(7), iblockdata1, iblockdata2, false); + break; + case COCOA_TREE: + iblockdata1 = Blocks.LOG.getBlockData().set(BlockLog1.VARIANT, BlockWood.EnumLogVariant.JUNGLE); + iblockdata2 = Blocks.LEAVES.getBlockData().set(BlockLeaves1.VARIANT, BlockWood.EnumLogVariant.JUNGLE).set(BlockLeaves.CHECK_DECAY, false); + gen = new WorldGenTrees(true, 4 + rand.nextInt(7), iblockdata1, iblockdata2, true); + break; + case JUNGLE_BUSH: + iblockdata1 = Blocks.LOG.getBlockData().set(BlockLog1.VARIANT, BlockWood.EnumLogVariant.JUNGLE); + iblockdata2 = Blocks.LEAVES.getBlockData().set(BlockLeaves1.VARIANT, BlockWood.EnumLogVariant.OAK).set(BlockLeaves.CHECK_DECAY, false); + gen = new WorldGenGroundBush(iblockdata1, iblockdata2); + break; + case RED_MUSHROOM: + gen = new WorldGenHugeMushroom(Blocks.RED_MUSHROOM_BLOCK); + break; + case BROWN_MUSHROOM: + gen = new WorldGenHugeMushroom(Blocks.BROWN_MUSHROOM_BLOCK); + break; + case SWAMP: + gen = new WorldGenSwampTree(); + break; + case ACACIA: + gen = new WorldGenAcaciaTree(true); + break; + case DARK_OAK: + gen = new WorldGenForestTree(true); + break; + case MEGA_REDWOOD: + gen = new WorldGenMegaTree(false, rand.nextBoolean()); + break; + case TALL_BIRCH: + gen = new WorldGenForest(true, true); + break; + case TREE: + default: + gen = new WorldGenTrees(true); + break; + } + + return gen.generate(world, rand, new BlockPosition(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); + } + + public boolean generateTree(Location loc, TreeType type, BlockChangeDelegate delegate) { + world.captureTreeGeneration = true; + world.captureBlockStates = true; + boolean grownTree = generateTree(loc, type); + world.captureBlockStates = false; + world.captureTreeGeneration = false; + if (grownTree) { // Copy block data to delegate + for (BlockState blockstate : world.capturedBlockStates) { + int x = blockstate.getX(); + int y = blockstate.getY(); + int z = blockstate.getZ(); + BlockPosition position = new BlockPosition(x, y, z); + net.minecraft.server.Block oldBlock = world.getType(position).getBlock(); + int typeId = blockstate.getTypeId(); + int data = blockstate.getRawData(); + int flag = ((CraftBlockState) blockstate).getFlag(); + delegate.setTypeIdAndData(x, y, z, typeId, data); + net.minecraft.server.Block newBlock = world.getType(position).getBlock(); + world.notifyAndUpdatePhysics(position, null, oldBlock, newBlock, flag); + } + world.capturedBlockStates.clear(); + return true; + } else { + world.capturedBlockStates.clear(); + return false; + } + } + + public TileEntity getTileEntityAt(int x, int y, int z) { + return world.getTileEntity(new BlockPosition(x, y, z)); + } + + public String getName() { + return world.worldData.getName(); + } + + @Deprecated + public long getId() { + return world.worldData.getSeed(); + } + + public UUID getUID() { + return world.getDataManager().getUUID(); + } + + @Override + public String toString() { + return "CraftWorld{name=" + getName() + '}'; + } + + public long getTime() { + long time = getFullTime() % 24000; + if (time < 0) time += 24000; + return time; + } + + public void setTime(long time) { + long margin = (time - getFullTime()) % 24000; + if (margin < 0) margin += 24000; + setFullTime(getFullTime() + margin); + } + + public long getFullTime() { + return world.getDayTime(); + } + + public void setFullTime(long time) { + world.setDayTime(time); + + // Forces the client to update to the new time immediately + for (Player p : getPlayers()) { + CraftPlayer cp = (CraftPlayer) p; + if (cp.getHandle().playerConnection == null) continue; + + cp.getHandle().playerConnection.sendPacket(new PacketPlayOutUpdateTime(cp.getHandle().world.getTime(), cp.getHandle().getPlayerTime(), cp.getHandle().world.getGameRules().getBoolean("doDaylightCycle"))); + } + } + + public boolean createExplosion(double x, double y, double z, float power) { + return createExplosion(x, y, z, power, false, true); + } + + public boolean createExplosion(double x, double y, double z, float power, boolean setFire) { + return createExplosion(x, y, z, power, setFire, true); + } + + public boolean createExplosion(double x, double y, double z, float power, boolean setFire, boolean breakBlocks) { + return !world.createExplosion(null, x, y, z, power, setFire, breakBlocks).wasCanceled; + } + + public boolean createExplosion(Location loc, float power) { + return createExplosion(loc, power, false); + } + + public boolean createExplosion(Location loc, float power, boolean setFire) { + return createExplosion(loc.getX(), loc.getY(), loc.getZ(), power, setFire); + } + + public Environment getEnvironment() { + return environment; + } + + public void setEnvironment(Environment env) { + if (environment != env) { + environment = env; + world.worldProvider = WorldProvider.byDimension(environment.getId()); + } + } + + public Block getBlockAt(Location location) { + return getBlockAt(location.getBlockX(), location.getBlockY(), location.getBlockZ()); + } + + public int getBlockTypeIdAt(Location location) { + return getBlockTypeIdAt(location.getBlockX(), location.getBlockY(), location.getBlockZ()); + } + + public int getHighestBlockYAt(Location location) { + return getHighestBlockYAt(location.getBlockX(), location.getBlockZ()); + } + + public Chunk getChunkAt(Location location) { + return getChunkAt(location.getBlockX() >> 4, location.getBlockZ() >> 4); + } + + public ChunkGenerator getGenerator() { + return generator; + } + + public List getPopulators() { + return populators; + } + + public Block getHighestBlockAt(int x, int z) { + return getBlockAt(x, getHighestBlockYAt(x, z), z); + } + + public Block getHighestBlockAt(Location location) { + return getHighestBlockAt(location.getBlockX(), location.getBlockZ()); + } + + public Biome getBiome(int x, int z) { + return CraftBlock.biomeBaseToBiome(this.world.getBiome(x, 0, z)); + } + + public void setBiome(int x, int z, Biome bio) { + BiomeBase bb = CraftBlock.biomeToBiomeBase(bio); + if (this.world.isLoaded(x, 0, z)) { + net.minecraft.server.Chunk chunk = this.world.getChunkAtWorldCoords(x, z); + + if (chunk != null) { + byte[] biomevals = chunk.getBiomeIndex(); + biomevals[((z & 0xF) << 4) | (x & 0xF)] = (byte) bb.id; + } + } + } + + public double getTemperature(int x, int z) { + return this.world.getBiome(x, 0, z).temperature; + } + + public double getHumidity(int x, int z) { + return this.world.getBiome(x, 0, z).humidity; + } + + public List getEntities() { + List list = new ArrayList<>(); + + for (net.minecraft.server.Entity mcEnt : world.entityList) { + Entity bukkitEntity = mcEnt.getBukkitEntity(); + + // Assuming that bukkitEntity isn't null + if (bukkitEntity != null) { + list.add(bukkitEntity); + } + } + + return list; + } + + public List getLivingEntities() { + List list = new ArrayList<>(); + + for (net.minecraft.server.Entity mcEnt : world.entityList) { + Entity bukkitEntity = mcEnt.getBukkitEntity(); + + // Assuming that bukkitEntity isn't null + if (bukkitEntity instanceof LivingEntity) { + list.add((LivingEntity) bukkitEntity); + } + } + + return list; + } + + @SuppressWarnings("unchecked") + @Deprecated + public Collection getEntitiesByClass(Class... classes) { + return (Collection) getEntitiesByClasses(classes); + } + + @SuppressWarnings("unchecked") + public Collection getEntitiesByClass(Class clazz) { + Collection list = new ArrayList<>(); + + for (net.minecraft.server.Entity entity : world.entityList) { + Entity bukkitEntity = entity.getBukkitEntity(); + + if (bukkitEntity == null) { + continue; + } + + Class bukkitClass = bukkitEntity.getClass(); + + if (clazz.isAssignableFrom(bukkitClass)) { + list.add((T) bukkitEntity); + } + } + + return list; + } + + public Collection getEntitiesByClasses(Class... classes) { + Collection list = new ArrayList<>(); + + for (net.minecraft.server.Entity entity : world.entityList) { + Entity bukkitEntity = entity.getBukkitEntity(); + + if (bukkitEntity == null) { + continue; + } + + Class bukkitClass = bukkitEntity.getClass(); + + for (Class clazz : classes) { + if (clazz.isAssignableFrom(bukkitClass)) { + list.add(bukkitEntity); + break; + } + } + } + + return list; + } + + @Override + public Collection getNearbyEntities(Location location, double x, double y, double z) { + if (location == null || !location.getWorld().equals(this)) { + return Collections.emptyList(); + } + + AxisAlignedBB bb = new AxisAlignedBB(location.getX() - x, location.getY() - y, location.getZ() - z, location.getX() + x, location.getY() + y, location.getZ() + z); + List entityList = getHandle().a((net.minecraft.server.Entity) null, bb, null); // PAIL : rename + List bukkitEntityList = new ArrayList<>(entityList.size()); + for (net.minecraft.server.Entity entity : entityList) { + bukkitEntityList.add(entity.getBukkitEntity()); + } + return bukkitEntityList; + } + + public List getPlayers() { + List list = new ArrayList<>(world.players.size()); + + for (EntityHuman human : world.players) { + HumanEntity bukkitEntity = human.getBukkitEntity(); + + if (bukkitEntity instanceof Player) { + list.add((Player) bukkitEntity); + } + } + + return list; + } + + public void save() { + // Spigot start + save(true); + } + + public void save(boolean forceSave) { + // Spigot end + this.server.checkSaveState(); + try { + boolean oldSave = world.savingDisabled; + + world.savingDisabled = false; + world.save(forceSave, null); // Spigot + + world.savingDisabled = oldSave; + } catch (ExceptionWorldConflict ex) { + ex.printStackTrace(); + ServerInternalException.reportInternalException(ex); // Paper + } + } + + public boolean isAutoSave() { + return !world.savingDisabled; + } + + public void setAutoSave(boolean value) { + world.savingDisabled = !value; + } + + public Difficulty getDifficulty() { + return Difficulty.getByValue(this.getHandle().getDifficulty().ordinal()); + } + + public void setDifficulty(Difficulty difficulty) { + this.getHandle().worldData.setDifficulty(EnumDifficulty.getById(difficulty.getValue())); + } + + public SpecializedBlockMetadataStore getBlockMetadata() { + return blockMetadata; + } + + public boolean hasStorm() { + return world.worldData.hasStorm(); + } + + public void setStorm(boolean hasStorm) { + world.worldData.setStorm(hasStorm); + } + + public int getWeatherDuration() { + return world.worldData.getWeatherDuration(); + } + + public void setWeatherDuration(int duration) { + world.worldData.setWeatherDuration(duration); + } + + public boolean isThundering() { + return world.worldData.isThundering(); + } + + public void setThundering(boolean thundering) { + world.worldData.setThundering(thundering); + } + + public int getThunderDuration() { + return world.worldData.getThunderDuration(); + } + + public void setThunderDuration(int duration) { + world.worldData.setThunderDuration(duration); + } + + public long getSeed() { + return world.worldData.getSeed(); + } + + public boolean getPVP() { + return world.pvpMode; + } + + public void setPVP(boolean pvp) { + world.pvpMode = pvp; + } + + public void playEffect(Player player, Effect effect, int data) { + playEffect(player.getLocation(), effect, data, 0); + } + + public void playEffect(Location location, Effect effect, int data) { + playEffect(location, effect, data, 64); + } + + public void playEffect(Location loc, Effect effect, T data) { + playEffect(loc, effect, data, 64); + } + + public void playEffect(Location loc, Effect effect, T data, int radius) { + if (data != null) { + Validate.isTrue(data.getClass().isAssignableFrom(effect.getData()), "Wrong kind of data for this effect!"); + } else { + Validate.isTrue(effect.getData() == null, "Wrong kind of data for this effect!"); + } + + if (data != null && data.getClass().equals(org.bukkit.material.MaterialData.class)) { + org.bukkit.material.MaterialData materialData = (org.bukkit.material.MaterialData) data; + Validate.isTrue(materialData.getItemType().isBlock(), "Material must be block"); + spigot().playEffect(loc, effect, materialData.getItemType().getId(), materialData.getData(), 0, 0, 0, 1, 1, radius); + } else { + int dataValue = data == null ? 0 : CraftEffect.getDataValue(effect, data); + playEffect(loc, effect, dataValue, radius); + } + } + + public void playEffect(Location location, Effect effect, int data, int radius) { + spigot().playEffect(location, effect, data, 0, 0, 0, 0, 1, 1, radius); + } + + public T spawn(Location location, Class clazz) throws IllegalArgumentException { + return spawn(location, clazz, SpawnReason.CUSTOM); + } + + public FallingBlock spawnFallingBlock(Location location, org.bukkit.Material material, byte data) throws IllegalArgumentException { + Validate.notNull(location, "Location cannot be null"); + Validate.notNull(material, "Material cannot be null"); + Validate.isTrue(material.isBlock(), "Material must be a block"); + + double x = location.getBlockX() + 0.5; + double y = location.getBlockY() + 0.5; + double z = location.getBlockZ() + 0.5; + + // PaperSpigot start - Add FallingBlock source location API + location = location.clone(); + EntityFallingBlock entity = new EntityFallingBlock(location, world, x, y, z, net.minecraft.server.Block.getById(material.getId()).fromLegacyData(data)); + // PaperSpigot end + entity.ticksLived = 1; + + world.addEntity(entity, SpawnReason.CUSTOM); + return (FallingBlock) entity.getBukkitEntity(); + } + + public FallingBlock spawnFallingBlock(Location location, int blockId, byte blockData) throws IllegalArgumentException { + return spawnFallingBlock(location, org.bukkit.Material.getMaterial(blockId), blockData); + } + + public net.minecraft.server.Entity createEntity(Location location, Class clazz) throws IllegalArgumentException { + if (location == null || clazz == null) { + throw new IllegalArgumentException("Location or entity class cannot be null"); + } + + net.minecraft.server.Entity entity = null; + + double x = location.getX(); + double y = location.getY(); + double z = location.getZ(); + float pitch = location.getPitch(); + float yaw = location.getYaw(); + + // order is important for some of these + if (Boat.class.isAssignableFrom(clazz)) { + entity = new EntityBoat(world, x, y, z); + } else if (FallingBlock.class.isAssignableFrom(clazz)) { + x = location.getBlockX(); + y = location.getBlockY(); + z = location.getBlockZ(); + IBlockData blockData = world.getType(MathHelper.floor(x), MathHelper.floor(y), MathHelper.floor(z)); + int type = CraftMagicNumbers.getId(blockData.getBlock()); + int data = blockData.getBlock().toLegacyData(blockData); + // PaperSpigot start - Add FallingBlock source location API + location = location.clone(); + entity = new EntityFallingBlock(location, world, x + 0.5, y + 0.5, z + 0.5, net.minecraft.server.Block.getById(type).fromLegacyData(data)); + // PaperSpigot end + } else if (Projectile.class.isAssignableFrom(clazz)) { + if (Snowball.class.isAssignableFrom(clazz)) { + entity = new EntitySnowball(world, x, y, z); + } else if (Egg.class.isAssignableFrom(clazz)) { + entity = new EntityEgg(world, x, y, z); + } else if (Arrow.class.isAssignableFrom(clazz)) { + entity = new EntityArrow(world); + entity.setPositionRotation(x, y, z, 0, 0); + } else if (ThrownExpBottle.class.isAssignableFrom(clazz)) { + entity = new EntityThrownExpBottle(world); + entity.setPositionRotation(x, y, z, 0, 0); + } else if (EnderPearl.class.isAssignableFrom(clazz)) { + entity = new EntityEnderPearl(world); + entity.setPositionRotation(x, y, z, 0, 0); + } else if (ThrownPotion.class.isAssignableFrom(clazz)) { + entity = new EntityPotion(world, x, y, z, CraftItemStack.asNMSCopy(new ItemStack(org.bukkit.Material.POTION, 1))); + } else if (Fireball.class.isAssignableFrom(clazz)) { + if (SmallFireball.class.isAssignableFrom(clazz)) { + entity = new EntitySmallFireball(world); + } else if (WitherSkull.class.isAssignableFrom(clazz)) { + entity = new EntityWitherSkull(world); + } else { + entity = new EntityLargeFireball(world); + } + entity.setPositionRotation(x, y, z, yaw, pitch); + Vector direction = location.getDirection().multiply(10); + ((EntityFireball) entity).setDirection(direction.getX(), direction.getY(), direction.getZ()); + } + } else if (Minecart.class.isAssignableFrom(clazz)) { + if (PoweredMinecart.class.isAssignableFrom(clazz)) { + entity = new EntityMinecartFurnace(world, x, y, z); + } else if (StorageMinecart.class.isAssignableFrom(clazz)) { + entity = new EntityMinecartChest(world, x, y, z); + } else if (ExplosiveMinecart.class.isAssignableFrom(clazz)) { + entity = new EntityMinecartTNT(world, x, y, z); + } else if (HopperMinecart.class.isAssignableFrom(clazz)) { + entity = new EntityMinecartHopper(world, x, y, z); + } else if (SpawnerMinecart.class.isAssignableFrom(clazz)) { + entity = new EntityMinecartMobSpawner(world, x, y, z); + } else { // Default to rideable minecart for pre-rideable compatibility + entity = new EntityMinecartRideable(world, x, y, z); + } + } else if (EnderSignal.class.isAssignableFrom(clazz)) { + entity = new EntityEnderSignal(world, x, y, z); + } else if (EnderCrystal.class.isAssignableFrom(clazz)) { + entity = new EntityEnderCrystal(world); + entity.setPositionRotation(x, y, z, 0, 0); + } else if (LivingEntity.class.isAssignableFrom(clazz)) { + if (Chicken.class.isAssignableFrom(clazz)) { + entity = new EntityChicken(world); + } else if (Cow.class.isAssignableFrom(clazz)) { + if (MushroomCow.class.isAssignableFrom(clazz)) { + entity = new EntityMushroomCow(world); + } else { + entity = new EntityCow(world); + } + } else if (Golem.class.isAssignableFrom(clazz)) { + if (Snowman.class.isAssignableFrom(clazz)) { + entity = new EntitySnowman(world); + } else if (IronGolem.class.isAssignableFrom(clazz)) { + entity = new EntityIronGolem(world); + } + } else if (Creeper.class.isAssignableFrom(clazz)) { + entity = new EntityCreeper(world); + } else if (Ghast.class.isAssignableFrom(clazz)) { + entity = new EntityGhast(world); + } else if (Pig.class.isAssignableFrom(clazz)) { + entity = new EntityPig(world); + } else if (Player.class.isAssignableFrom(clazz)) { + // need a net server handler for this one + } else if (Sheep.class.isAssignableFrom(clazz)) { + entity = new EntitySheep(world); + } else if (Horse.class.isAssignableFrom(clazz)) { + entity = new EntityHorse(world); + } else if (Skeleton.class.isAssignableFrom(clazz)) { + entity = new EntitySkeleton(world); + } else if (Slime.class.isAssignableFrom(clazz)) { + if (MagmaCube.class.isAssignableFrom(clazz)) { + entity = new EntityMagmaCube(world); + } else { + entity = new EntitySlime(world); + } + } else if (Spider.class.isAssignableFrom(clazz)) { + if (CaveSpider.class.isAssignableFrom(clazz)) { + entity = new EntityCaveSpider(world); + } else { + entity = new EntitySpider(world); + } + } else if (Squid.class.isAssignableFrom(clazz)) { + entity = new EntitySquid(world); + } else if (Tameable.class.isAssignableFrom(clazz)) { + if (Wolf.class.isAssignableFrom(clazz)) { + entity = new EntityWolf(world); + } else if (Ocelot.class.isAssignableFrom(clazz)) { + entity = new EntityOcelot(world); + } + } else if (PigZombie.class.isAssignableFrom(clazz)) { + entity = new EntityPigZombie(world); + } else if (Zombie.class.isAssignableFrom(clazz)) { + entity = new EntityZombie(world); + } else if (Giant.class.isAssignableFrom(clazz)) { + entity = new EntityGiantZombie(world); + } else if (Silverfish.class.isAssignableFrom(clazz)) { + entity = new EntitySilverfish(world); + } else if (Enderman.class.isAssignableFrom(clazz)) { + entity = new EntityEnderman(world); + } else if (Blaze.class.isAssignableFrom(clazz)) { + entity = new EntityBlaze(world); + } else if (Villager.class.isAssignableFrom(clazz)) { + entity = new EntityVillager(world); + } else if (Witch.class.isAssignableFrom(clazz)) { + entity = new EntityWitch(world); + } else if (Wither.class.isAssignableFrom(clazz)) { + entity = new EntityWither(world); + } else if (ComplexLivingEntity.class.isAssignableFrom(clazz)) { + if (EnderDragon.class.isAssignableFrom(clazz)) { + entity = new EntityEnderDragon(world); + } + } else if (Ambient.class.isAssignableFrom(clazz)) { + if (Bat.class.isAssignableFrom(clazz)) { + entity = new EntityBat(world); + } + } else if (Rabbit.class.isAssignableFrom(clazz)) { + entity = new EntityRabbit(world); + } else if (Endermite.class.isAssignableFrom(clazz)) { + entity = new EntityEndermite(world); + } else if (Guardian.class.isAssignableFrom(clazz)) { + entity = new EntityGuardian(world); + } else if (ArmorStand.class.isAssignableFrom(clazz)) { + entity = new EntityArmorStand(world, x, y, z); + } + + if (entity != null) { + entity.setLocation(x, y, z, yaw, pitch); + } + } else if (Hanging.class.isAssignableFrom(clazz)) { + Block block = getBlockAt(location); + BlockFace face = BlockFace.SELF; + + int width = 16; // 1 full block, also painting smallest size. + int height = 16; // 1 full block, also painting smallest size. + + if (ItemFrame.class.isAssignableFrom(clazz)) { + width = 12; + height = 12; + } else if (LeashHitch.class.isAssignableFrom(clazz)) { + width = 9; + height = 9; + } + + BlockFace[] faces = new BlockFace[]{BlockFace.EAST, BlockFace.NORTH, BlockFace.WEST, BlockFace.SOUTH}; + final BlockPosition pos = new BlockPosition((int) x, (int) y, (int) z); + for (BlockFace dir : faces) { + net.minecraft.server.Block nmsBlock = CraftMagicNumbers.getBlock(block.getRelative(dir)); + if (nmsBlock.getMaterial().isBuildable() || BlockDiodeAbstract.d(nmsBlock)) { + boolean taken = false; + AxisAlignedBB bb = EntityHanging.calculateBoundingBox(pos, CraftBlock.blockFaceToNotch(dir).opposite(), width, height); + List list = world.getEntities(null, bb); + for (Iterator it = list.iterator(); !taken && it.hasNext(); ) { + net.minecraft.server.Entity e = it.next(); + if (e instanceof EntityHanging) { + taken = true; // Hanging entities do not like hanging entities which intersect them. + } + } + + if (!taken) { + face = dir; + break; + } + } + } + + EnumDirection dir = CraftBlock.blockFaceToNotch(face).opposite(); + + if (Painting.class.isAssignableFrom(clazz)) { + entity = new EntityPainting(world, new BlockPosition((int) x, (int) y, (int) z), dir); + } else if (ItemFrame.class.isAssignableFrom(clazz)) { + entity = new EntityItemFrame(world, new BlockPosition((int) x, (int) y, (int) z), dir); + } else if (LeashHitch.class.isAssignableFrom(clazz)) { + entity = new EntityLeash(world, new BlockPosition((int) x, (int) y, (int) z)); + entity.attachedToPlayer = true; + } + + if (entity != null && !((EntityHanging) entity).survives()) { + throw new IllegalArgumentException("Cannot spawn hanging entity for " + clazz.getName() + " at " + location); + } + } else if (TNTPrimed.class.isAssignableFrom(clazz)) { + org.bukkit.Location loc = new org.bukkit.Location(world.getWorld(), x, y, z); // PaperSpigot + entity = new EntityTNTPrimed(loc, world, x, y, z, null); + } else if (ExperienceOrb.class.isAssignableFrom(clazz)) { + entity = new EntityExperienceOrb(world, x, y, z, 0); + } else if (Weather.class.isAssignableFrom(clazz)) { + // not sure what this can do + if (LightningStrike.class.isAssignableFrom(clazz)) { + entity = new EntityLightning(world, x, y, z); + // what is this, I don't even + } + } else if (Firework.class.isAssignableFrom(clazz)) { + entity = new EntityFireworks(world, x, y, z, null); + } + + if (entity != null) { + // Spigot start + if (entity instanceof EntityOcelot) { + ((EntityOcelot) entity).spawnBonus = false; + } + // Spigot end + return entity; + } + + throw new IllegalArgumentException("Cannot spawn an entity for " + clazz.getName()); + } + + @SuppressWarnings("unchecked") + public T addEntity(net.minecraft.server.Entity entity, SpawnReason reason) throws IllegalArgumentException { + Preconditions.checkArgument(entity != null, "Cannot spawn null entity"); + + if (entity instanceof EntityInsentient) { + ((EntityInsentient) entity).prepare(getHandle().E(MathHelper.floor(entity.locX), MathHelper.floor(entity.locY), MathHelper.floor(entity.locZ)), null); + } + + world.addEntity(entity, reason); + return (T) entity.getBukkitEntity(); + } + + public T spawn(Location location, Class clazz, SpawnReason reason) throws IllegalArgumentException { + net.minecraft.server.Entity entity = createEntity(location, clazz); + + return addEntity(entity, reason); + } + + public ChunkSnapshot getEmptyChunkSnapshot(int x, int z, boolean includeBiome, boolean includeBiomeTempRain) { + return CraftChunk.getEmptyChunkSnapshot(x, z, this, includeBiome, includeBiomeTempRain); + } + + public void setSpawnFlags(boolean allowMonsters, boolean allowAnimals) { + world.setSpawnFlags(allowMonsters, allowAnimals); + } + + public boolean getAllowAnimals() { + return world.allowAnimals; + } + + public boolean getAllowMonsters() { + return world.allowMonsters; + } + + public int getMaxHeight() { + return world.getHeight(); + } + + public int getSeaLevel() { + return 64; + } + + public boolean getKeepSpawnInMemory() { + return world.keepSpawnInMemory; + } + + public void setKeepSpawnInMemory(boolean keepLoaded) { + world.keepSpawnInMemory = keepLoaded; + // Grab the worlds spawn chunk + BlockPosition chunkcoordinates = this.world.getSpawn(); + int chunkCoordX = chunkcoordinates.getX() >> 4; + int chunkCoordZ = chunkcoordinates.getZ() >> 4; + // Cycle through the 25x25 Chunks around it to load/unload the chunks. + for (int x = -12; x <= 12; x++) { + for (int z = -12; z <= 12; z++) { + if (keepLoaded) { + loadChunk(chunkCoordX + x, chunkCoordZ + z); + } else { + if (isChunkLoaded(chunkCoordX + x, chunkCoordZ + z)) { + if (this.getHandle().getChunkAt(chunkCoordX + x, chunkCoordZ + z) instanceof EmptyChunk) { + unloadChunk(chunkCoordX + x, chunkCoordZ + z, false); + } else { + unloadChunk(chunkCoordX + x, chunkCoordZ + z); + } + } + } + } + } + } + + @Override + public int hashCode() { + return getUID().hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + + final CraftWorld other = (CraftWorld) obj; + + return this.getUID() == other.getUID(); + } + + public File getWorldFolder() { + return world.getDataManager().getDirectory(); + } + + public void sendPluginMessage(Plugin source, String channel, byte[] message) { + StandardMessenger.validatePluginMessage(server.getMessenger(), source, channel, message); + + for (Player player : getPlayers()) { + player.sendPluginMessage(source, channel, message); + } + } + + public Set getListeningPluginChannels() { + Set result = new HashSet<>(); + + for (Player player : getPlayers()) { + result.addAll(player.getListeningPluginChannels()); + } + + return result; + } + + public org.bukkit.WorldType getWorldType() { + return org.bukkit.WorldType.getByName(world.getWorldData().getType().name()); + } + + public boolean canGenerateStructures() { + return world.getWorldData().shouldGenerateMapFeatures(); + } + + public long getTicksPerAnimalSpawns() { + return world.ticksPerAnimalSpawns; + } + + public void setTicksPerAnimalSpawns(int ticksPerAnimalSpawns) { + world.ticksPerAnimalSpawns = ticksPerAnimalSpawns; + } + + public long getTicksPerMonsterSpawns() { + return world.ticksPerMonsterSpawns; + } + + public void setTicksPerMonsterSpawns(int ticksPerMonsterSpawns) { + world.ticksPerMonsterSpawns = ticksPerMonsterSpawns; + } + + public void setMetadata(String metadataKey, MetadataValue newMetadataValue) { + server.getWorldMetadata().setMetadata(this, metadataKey, newMetadataValue); + } + + public List getMetadata(String metadataKey) { + return server.getWorldMetadata().getMetadata(this, metadataKey); + } + + public boolean hasMetadata(String metadataKey) { + return server.getWorldMetadata().hasMetadata(this, metadataKey); + } + + public void removeMetadata(String metadataKey, Plugin owningPlugin) { + server.getWorldMetadata().removeMetadata(this, metadataKey, owningPlugin); + } + + public int getMonsterSpawnLimit() { + if (monsterSpawn < 0) { + return server.getMonsterSpawnLimit(); + } + + return monsterSpawn; + } + + public void setMonsterSpawnLimit(int limit) { + monsterSpawn = limit; + } + + public int getAnimalSpawnLimit() { + if (animalSpawn < 0) { + return server.getAnimalSpawnLimit(); + } + + return animalSpawn; + } + + public void setAnimalSpawnLimit(int limit) { + animalSpawn = limit; + } + + public int getWaterAnimalSpawnLimit() { + if (waterAnimalSpawn < 0) { + return server.getWaterAnimalSpawnLimit(); + } + + return waterAnimalSpawn; + } + + public void setWaterAnimalSpawnLimit(int limit) { + waterAnimalSpawn = limit; + } + + public int getAmbientSpawnLimit() { + if (ambientSpawn < 0) { + return server.getAmbientSpawnLimit(); + } + + return ambientSpawn; + } + + public void setAmbientSpawnLimit(int limit) { + ambientSpawn = limit; + } + + + public void playSound(Location loc, Sound sound, float volume, float pitch) { + if (loc == null || sound == null) return; + + double x = loc.getX(); + double y = loc.getY(); + double z = loc.getZ(); + + getHandle().makeSound(x, y, z, CraftSound.getSound(sound), volume, pitch); + } + + public String getGameRuleValue(String rule) { + return getHandle().getGameRules().get(rule); + } + + public boolean setGameRuleValue(String rule, String value) { + // No null values allowed + if (rule == null || value == null) return false; + + if (!isGameRule(rule)) return false; + + getHandle().getGameRules().set(rule, value); + return true; + } + + public String[] getGameRules() { + return getHandle().getGameRules().getGameRules(); + } + + public boolean isGameRule(String rule) { + return getHandle().getGameRules().contains(rule); + } + + @Override + public WorldBorder getWorldBorder() { + if (this.worldBorder == null) { + this.worldBorder = new CraftWorldBorder(this); + } + + return this.worldBorder; + } + + public void processChunkGC() { + chunkGCTickCount++; + + int chunkGCLoadThreshold = server.chunkGCLoadThresh; + if (chunkLoadCount > chunkGCLoadThreshold && chunkGCLoadThreshold > 0) { + chunkLoadCount = 0; + } else if (chunkGCTickCount >= server.chunkGCPeriod && server.chunkGCPeriod > 0) { + chunkGCTickCount = 0; + } else { + return; + } + + ChunkProviderServer cps = world.chunkProviderServer; + for (net.minecraft.server.Chunk chunk : cps.chunks.values()) { + // If in use, skip it + if (isChunkInUse(chunk.locX, chunk.locZ)) { + continue; + } + + // Already unloading? + if (cps.unloadQueue.contains(chunk.chunkHashKey)) { + continue; + } + + // Add unload request + cps.queueUnload(chunk.chunkHashKey, chunk.locX, chunk.locZ); + } + } + + public Spigot spigot() { + return spigot; + } // Spigot start + + private final Spigot spigot = new Spigot() { + @Override + public void playEffect(Location location, Effect effect, int id, int data, float offsetX, float offsetY, float offsetZ, float speed, int particleCount, int radius) { + Validate.notNull(location, "Location cannot be null"); + Validate.notNull(effect, "Effect cannot be null"); + Validate.notNull(location.getWorld(), "World cannot be null"); + Packet packet; + if (effect.getType() != Effect.Type.PARTICLE) { + int packetData = effect.getId(); + packet = new PacketPlayOutWorldEvent(packetData, new BlockPosition(location.getBlockX(), location.getBlockY(), location.getBlockZ()), id, false); + } else { + net.minecraft.server.EnumParticle particle = null; + int[] extra = null; + for (net.minecraft.server.EnumParticle p : net.minecraft.server.EnumParticle.values()) { + if (effect.getName().startsWith(p.b().replace("_", ""))) { + particle = p; + if (effect.getData() != null) { + if (effect.getData().equals(org.bukkit.Material.class)) { + extra = new int[]{id}; + } else { + extra = new int[]{(data << 12) | (id & 0xFFF)}; + } + } + break; + } + } + if (extra == null) { + extra = new int[0]; + } + packet = new PacketPlayOutWorldParticles(particle, true, (float) location.getX(), (float) location.getY(), (float) location.getZ(), offsetX, offsetY, offsetZ, speed, particleCount, extra); + } + int distance; + radius *= radius; + for (Player player : getPlayers()) { + if (((CraftPlayer) player).getHandle().playerConnection == null) { + continue; + } + if (!location.getWorld().equals(player.getWorld())) { + continue; + } + distance = (int) player.getLocation().distanceSquared(location); + if (distance <= radius) { + ((CraftPlayer) player).getHandle().playerConnection.sendPacket(packet); + } + } + } + + @Override + public void playEffect(Location location, Effect effect) { + CraftWorld.this.playEffect(location, effect, 0); + } + + @Override + public LightningStrike strikeLightning(Location loc, boolean isSilent) { + EntityLightning lightning = new EntityLightning(world, loc.getX(), loc.getY(), loc.getZ(), false, isSilent); + world.strikeLightning(lightning); + return new CraftLightningStrike(server, lightning); + } + + @Override + public LightningStrike strikeLightningEffect(Location loc, boolean isSilent) { + EntityLightning lightning = new EntityLightning(world, loc.getX(), loc.getY(), loc.getZ(), true, isSilent); + world.strikeLightning(lightning); + return new CraftLightningStrike(server, lightning); + } + }; + + + // Spigot end +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftWorldBorder.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftWorldBorder.java new file mode 100644 index 0000000..e5395a1 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/CraftWorldBorder.java @@ -0,0 +1,111 @@ +package org.bukkit.craftbukkit; + +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.WorldBorder; + +public class CraftWorldBorder implements WorldBorder { + + private final World world; + private final net.minecraft.server.WorldBorder handle; + + public CraftWorldBorder(CraftWorld world) { + this.world = world; + this.handle = world.getHandle().getWorldBorder(); + } + + @Override + public void reset() { + this.setSize(6.0E7D); + this.setDamageAmount(0.2D); + this.setDamageBuffer(5.0D); + this.setWarningDistance(5); + this.setWarningTime(15); + this.setCenter(0, 0); + } + + @Override + public double getSize() { + return this.handle.getSize(); + } + + @Override + public void setSize(double newSize) { + this.setSize(newSize, 0L); + } + + @Override + public void setSize(double newSize, long time) { + // PAIL: TODO: Magic Values + newSize = Math.min(6.0E7D, Math.max(1.0D, newSize)); + time = Math.min(9223372036854775L, Math.max(0L, time)); + + if (time > 0L) { + this.handle.transitionSizeBetween(this.handle.getSize(), newSize, time * 1000L); + } else { + this.handle.setSize(newSize); + } + } + + @Override + public Location getCenter() { + double x = this.handle.getCenterX(); + double z = this.handle.getCenterZ(); + + return new Location(this.world, x, 0, z); + } + + @Override + public void setCenter(double x, double z) { + // PAIL: TODO: Magic Values + x = Math.min(3.0E7D, Math.max(-3.0E7D, x)); + z = Math.min(3.0E7D, Math.max(-3.0E7D, z)); + + this.handle.setCenter(x, z); + } + + @Override + public void setCenter(Location location) { + this.setCenter(location.getX(), location.getZ()); + } + + @Override + public double getDamageBuffer() { + return this.handle.getDamageBuffer(); + } + + @Override + public void setDamageBuffer(double blocks) { + this.handle.setDamageBuffer(blocks); + } + + @Override + public double getDamageAmount() { + return this.handle.getDamageAmount(); + } + + @Override + public void setDamageAmount(double damage) { + this.handle.setDamageAmount(damage); + } + + @Override + public int getWarningTime() { + return this.handle.getWarningTime(); + } + + @Override + public void setWarningTime(int time) { + this.handle.setWarningTime(time); + } + + @Override + public int getWarningDistance() { + return this.handle.getWarningDistance(); + } + + @Override + public void setWarningDistance(int distance) { + this.handle.setWarningDistance(distance); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/Main.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/Main.java new file mode 100644 index 0000000..9f582bd --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/Main.java @@ -0,0 +1,224 @@ +package org.bukkit.craftbukkit; + +import dev.azurite.spigot.Azurite; +import dev.azurite.spigot.configs.AzuriteConfig; +import joptsimple.OptionParser; +import joptsimple.OptionSet; +import net.minecraft.server.MinecraftServer; +import net.minecrell.terminalconsole.TerminalConsoleAppender; + +import java.io.File; +import java.io.IOException; +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; + +public class Main { + public static boolean useJline = true; + public static boolean useConsole = true; + + public static void main(String[] args) { + if (System.getProperty("jdk.nio.maxCachedBufferSize") == null) System.setProperty("jdk.nio.maxCachedBufferSize", "262144"); // PandaSpigot - cap per-thread NIO cache size + System.setProperty("org.jline.terminal.disableDeprecatedProviderWarning", "true"); // Beanes - disable jansi warning + + OptionParser parser = new OptionParser() { + { + acceptsAll(asList("?", "help"), "Show the help"); + + acceptsAll(asList("c", "config"), "Properties file to use") + .withRequiredArg() + .ofType(File.class) + .defaultsTo(new File("server.properties")) + .describedAs("Properties file"); + + acceptsAll(asList("P", "plugins"), "Plugin directory to use") + .withRequiredArg() + .ofType(File.class) + .defaultsTo(new File("plugins")) + .describedAs("Plugin directory"); + + acceptsAll(asList("h", "host", "server-ip"), "Host to listen on") + .withRequiredArg() + .ofType(String.class) + .describedAs("Hostname or IP"); + + acceptsAll(asList("W", "world-dir", "universe", "world-container"), "World container") + .withRequiredArg() + .ofType(File.class) + .describedAs("Directory containing worlds"); + + acceptsAll(asList("w", "world", "level-name"), "World name") + .withRequiredArg() + .ofType(String.class) + .describedAs("World name"); + + acceptsAll(asList("p", "port", "server-port"), "Port to listen on") + .withRequiredArg() + .ofType(Integer.class) + .describedAs("Port"); + + acceptsAll(asList("o", "online-mode"), "Whether to use online authentication") + .withRequiredArg() + .ofType(Boolean.class) + .describedAs("Authentication"); + + acceptsAll(asList("s", "size", "max-players"), "Maximum amount of players") + .withRequiredArg() + .ofType(Integer.class) + .describedAs("Server size"); + + acceptsAll(asList("d", "date-format"), "Format of the date to display in the console (for log entries)") + .withRequiredArg() + .ofType(SimpleDateFormat.class) + .describedAs("Log date format"); + + acceptsAll(asList("log-pattern"), "Specfies the log filename pattern") + .withRequiredArg() + .ofType(String.class) + .defaultsTo("server.log") + .describedAs("Log filename"); + + acceptsAll(asList("log-limit"), "Limits the maximum size of the log file (0 = unlimited)") + .withRequiredArg() + .ofType(Integer.class) + .defaultsTo(0) + .describedAs("Max log size"); + + acceptsAll(asList("log-count"), "Specified how many log files to cycle through") + .withRequiredArg() + .ofType(Integer.class) + .defaultsTo(1) + .describedAs("Log count"); + + acceptsAll(asList("log-append"), "Whether to append to the log file") + .withRequiredArg() + .ofType(Boolean.class) + .defaultsTo(true) + .describedAs("Log append"); + + acceptsAll(asList("log-strip-color"), "Strips color codes from log file"); + + acceptsAll(asList("b", "bukkit-settings"), "File for bukkit settings") + .withRequiredArg() + .ofType(File.class) + .defaultsTo(new File("bukkit.yml")) + .describedAs("Yml file"); + + acceptsAll(asList("C", "commands-settings"), "File for command settings") + .withRequiredArg() + .ofType(File.class) + .defaultsTo(new File("commands.yml")) + .describedAs("Yml file"); + + acceptsAll(asList("nojline"), "Disables jline and emulates the vanilla console"); + + acceptsAll(asList("noconsole"), "Disables the console"); + + acceptsAll(asList("v", "version"), "Show the CraftBukkit Version"); + + acceptsAll(asList("demo"), "Demo mode"); + + // Spigot Start + acceptsAll(asList("S", "spigot-settings"), "File for spigot settings") + .withRequiredArg() + .ofType(File.class) + .defaultsTo(new File("spigot.yml")) + .describedAs("Yml file"); + // Spigot End + + // PaperSpigot Start + acceptsAll(asList("paper", "paper-settings"), "File for paperspigot settings") + .withRequiredArg() + .ofType(File.class) + .defaultsTo(new File("paper.yml")) + .describedAs("Yml file"); + // PaperSpigot End + + // Vortex Start + acceptsAll(asList("vortex", "vortex-settings"), "File for vortexspigot settings") + .withRequiredArg() + .ofType(File.class) + .defaultsTo(new File("vortex.yml")) + .describedAs("Yml file"); + + acceptsAll(asList("lang", "lang-settings"), "File for vortexspigot language") + .withRequiredArg() + .ofType(File.class) + .defaultsTo(new File("lang.yml")) + .describedAs("Yml file"); + + acceptsAll(asList("pearl", "pearl-settings"), "File for vortexpearls settings") + .withRequiredArg() + .ofType(File.class) + .defaultsTo(new File("pearls.yml")) + .describedAs("Yml file"); + + acceptsAll(asList("knockback", "knockback-settings"), "File for knockback settings") + .withRequiredArg() + .ofType(File.class) + .defaultsTo(new File("knockback.yml")) + .describedAs("Yml file"); + // Vortex End + } + }; + + OptionSet options = null; + + try { + options = parser.parse(args); + } catch (joptsimple.OptionException ex) { + Logger.getLogger(Main.class.getName()).log(Level.SEVERE, ex.getLocalizedMessage()); + } + + if (System.getProperty("jdk.nio.maxCachedBufferSize") == null) + System.setProperty("jdk.nio.maxCachedBufferSize", "262144"); // cap per-thread NIO cache size + + if ((options == null) || (options.has("?"))) { + try { + parser.printHelpOn(System.out); + } catch (IOException ex) { + Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); + } + } else if (options.has("v")) { + System.out.println(CraftServer.class.getPackage().getImplementationVersion()); + } else { + // Do you love Java using + and ! as string based identifiers? I sure do! + String path = new File(".").getAbsolutePath(); + if (path.contains("!") || path.contains("+")) { + System.err.println("Cannot run server in a directory with ! or + in the pathname. Please rename the affected folders and try again."); + return; + } + + try { + if (options.has("nojline")) { + System.setProperty(TerminalConsoleAppender.JLINE_OVERRIDE_PROPERTY, "false"); + useJline = false; + } + + if (options.has("noconsole")) { + useConsole = false; + useJline = false; // Paper + System.setProperty(TerminalConsoleAppender.JLINE_OVERRIDE_PROPERTY, "false"); // Paper + } + + new Azurite(); + + // Beanes - set netty allocator + System.setProperty("io.netty.allocator.type", AzuriteConfig.adaptiveAllocator.getValue() ? "adaptive" : "pooled"); + + System.setProperty("library.jansi.version", "Azurite"); // Paper - set meaningless jansi version to prevent git builds from crashing on Windows + System.out.println("Loading libraries, please wait..."); + MinecraftServer.main(options); + + } catch (Throwable t) { + t.printStackTrace(); + } + } + } + + private static List asList(String... params) { + return Arrays.asList(params); + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/Overridden.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/Overridden.java new file mode 100644 index 0000000..1c19c69 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/Overridden.java @@ -0,0 +1,14 @@ +package org.bukkit.craftbukkit; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Indicates a method needs to be overridden in sub classes + */ +@Target({ElementType.CONSTRUCTOR, ElementType.METHOD}) +@Retention(RetentionPolicy.RUNTIME) +public @interface Overridden { +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/TrigMath.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/TrigMath.java new file mode 100644 index 0000000..6d613c5 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/TrigMath.java @@ -0,0 +1,47 @@ +package org.bukkit.craftbukkit; + +/** + * Credits for this class goes to user aioobe on stackoverflow.com + * Source: http://stackoverflow.com/questions/4454630/j2me-calculate-the-the-distance-between-2-latitude-and-longitude + */ +public class TrigMath { + + static final double sq2p1 = 2.414213562373095048802e0; + static final double sq2m1 = .414213562373095048802e0; + static final double p4 = .161536412982230228262e2; + static final double p3 = .26842548195503973794141e3; + static final double p2 = .11530293515404850115428136e4; + static final double p1 = .178040631643319697105464587e4; + static final double p0 = .89678597403663861959987488e3; + static final double q4 = .5895697050844462222791e2; + static final double q3 = .536265374031215315104235e3; + static final double q2 = .16667838148816337184521798e4; + static final double q1 = .207933497444540981287275926e4; + static final double q0 = .89678597403663861962481162e3; + static final double PIO2 = 1.5707963267948966135E0; + + private static double mxatan(double arg) { + double argsq = arg * arg, value; + + value = ((((p4 * argsq + p3) * argsq + p2) * argsq + p1) * argsq + p0); + value = value / (((((argsq + q4) * argsq + q3) * argsq + q2) * argsq + q1) * argsq + q0); + return value * arg; + } + + private static double msatan(double arg) { + return arg < sq2m1 ? mxatan(arg) + : arg > sq2p1 ? PIO2 - mxatan(1 / arg) + : PIO2 / 2 + mxatan((arg - 1) / (arg + 1)); + } + + public static double atan(double arg) { + return arg > 0 ? msatan(arg) : -msatan(-arg); + } + + public static double atan2(double arg1, double arg2) { + if (arg1 + arg2 == arg1) + return arg1 >= 0 ? PIO2 : -PIO2; + arg1 = atan(arg1 / arg2); + return arg2 < 0 ? arg1 <= 0 ? arg1 + Math.PI : arg1 - Math.PI : arg1; + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/block/CraftBanner.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/block/CraftBanner.java new file mode 100644 index 0000000..a7324f6 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/block/CraftBanner.java @@ -0,0 +1,121 @@ +package org.bukkit.craftbukkit.block; + +import net.minecraft.server.NBTTagCompound; +import net.minecraft.server.NBTTagList; +import net.minecraft.server.TileEntityBanner; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.block.Banner; +import org.bukkit.block.Block; +import org.bukkit.block.banner.Pattern; +import org.bukkit.block.banner.PatternType; +import org.bukkit.craftbukkit.CraftWorld; + +import java.util.ArrayList; +import java.util.List; + +public class CraftBanner extends CraftBlockState implements Banner { + + private final TileEntityBanner banner; + private DyeColor base; + private List patterns = new ArrayList(); + + public CraftBanner(final Block block) { + super(block); + + CraftWorld world = (CraftWorld) block.getWorld(); + banner = (TileEntityBanner) world.getTileEntityAt(getX(), getY(), getZ()); + + base = DyeColor.getByDyeData((byte) banner.color); + + if (banner.patterns != null) { + for (int i = 0; i < banner.patterns.size(); i++) { + NBTTagCompound p = banner.patterns.get(i); + patterns.add(new Pattern(DyeColor.getByDyeData((byte) p.getInt("Color")), PatternType.getByIdentifier(p.getString("Pattern")))); + } + } + } + + public CraftBanner(final Material material, final TileEntityBanner te) { + super(material); + banner = te; + + base = DyeColor.getByDyeData((byte) banner.color); + + if (banner.patterns != null) { + for (int i = 0; i < banner.patterns.size(); i++) { + NBTTagCompound p = banner.patterns.get(i); + patterns.add(new Pattern(DyeColor.getByDyeData((byte) p.getInt("Color")), PatternType.getByIdentifier(p.getString("Pattern")))); + } + } + } + + @Override + public DyeColor getBaseColor() { + return this.base; + } + + @Override + public void setBaseColor(DyeColor color) { + this.base = color; + } + + @Override + public List getPatterns() { + return new ArrayList<>(patterns); + } + + @Override + public void setPatterns(List patterns) { + this.patterns = new ArrayList<>(patterns); + } + + @Override + public void addPattern(Pattern pattern) { + this.patterns.add(pattern); + } + + @Override + public Pattern getPattern(int i) { + return this.patterns.get(i); + } + + @Override + public Pattern removePattern(int i) { + return this.patterns.remove(i); + } + + @Override + public void setPattern(int i, Pattern pattern) { + this.patterns.set(i, pattern); + } + + @Override + public int numberOfPatterns() { + return patterns.size(); + } + + @Override + public boolean update(boolean force, boolean applyPhysics) { + boolean result = super.update(force, applyPhysics); + + if (result) { + banner.color = base.getDyeData(); + + NBTTagList newPatterns = new NBTTagList(); + + for (Pattern p : patterns) { + NBTTagCompound compound = new NBTTagCompound(); + compound.setInt("Color", p.getColor().getDyeData()); + compound.setString("Pattern", p.getPattern().getIdentifier()); + newPatterns.add(compound); + } + + banner.patterns = newPatterns; + + banner.update(); + } + + return result; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/block/CraftBeacon.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/block/CraftBeacon.java new file mode 100644 index 0000000..9b37361 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/block/CraftBeacon.java @@ -0,0 +1,48 @@ +package org.bukkit.craftbukkit.block; + +import net.minecraft.server.TileEntityBeacon; +import org.bukkit.Material; +import org.bukkit.block.Beacon; +import org.bukkit.block.Block; +import org.bukkit.craftbukkit.CraftWorld; +import org.bukkit.craftbukkit.inventory.CraftInventoryBeacon; +import org.bukkit.inventory.Inventory; + +public class CraftBeacon extends CraftBlockState implements Beacon { + private final CraftWorld world; + private final TileEntityBeacon beacon; + + public CraftBeacon(final Block block) { + super(block); + + world = (CraftWorld) block.getWorld(); + beacon = (TileEntityBeacon) world.getTileEntityAt(getX(), getY(), getZ()); + } + + public CraftBeacon(final Material material, final TileEntityBeacon te) { + super(material); + world = null; + beacon = te; + } + + public Inventory getInventory() { + return new CraftInventoryBeacon(beacon); + } + + @Override + public boolean update(boolean force, boolean applyPhysics) { + boolean result = super.update(force, applyPhysics); + + if (result) { + beacon.update(); + } + + return result; + } + + @Override + public TileEntityBeacon getTileEntity() { + return beacon; + } +} + diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/block/CraftBlock.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/block/CraftBlock.java new file mode 100644 index 0000000..ecd38a5 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/block/CraftBlock.java @@ -0,0 +1,576 @@ +package org.bukkit.craftbukkit.block; + +import net.minecraft.server.*; +import org.bukkit.Chunk; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.block.BlockState; +import org.bukkit.block.*; +import org.bukkit.craftbukkit.CraftChunk; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.craftbukkit.util.CraftMagicNumbers; +import org.bukkit.inventory.ItemStack; +import org.bukkit.metadata.MetadataValue; +import org.bukkit.plugin.Plugin; +import org.bukkit.util.BlockVector; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +public class CraftBlock implements Block { + private final CraftChunk chunk; + private final int x; + private final int y; + private final int z; + private static final Biome[] BIOME_MAPPING; + private static final BiomeBase[] BIOMEBASE_MAPPING; + + public CraftBlock(CraftChunk chunk, int x, int y, int z) { + this.x = x; + this.y = y; + this.z = z; + this.chunk = chunk; + } + + private net.minecraft.server.Block getNMSBlock() { + return CraftMagicNumbers.getBlock(this); // TODO: UPDATE THIS + } + + private static net.minecraft.server.Block getNMSBlock(int type) { + return CraftMagicNumbers.getBlock(type); + } + + public World getWorld() { + return chunk.getWorld(); + } + + public Location getLocation() { + return new Location(getWorld(), x, y, z); + } + + public Location getLocation(Location loc) { + if (loc != null) { + loc.setWorld(getWorld()); + loc.setX(x); + loc.setY(y); + loc.setZ(z); + loc.setYaw(0); + loc.setPitch(0); + } + + return loc; + } + + public BlockVector getVector() { + return new BlockVector(x, y, z); + } + + public int getX() { + return x; + } + + public int getY() { + return y; + } + + public int getZ() { + return z; + } + + public Chunk getChunk() { + return chunk; + } + + public void setData(final byte data) { + setData(data, 3); + } + + public void setData(final byte data, boolean applyPhysics) { + if (applyPhysics) { + setData(data, 3); + } else { + setData(data, 2); + } + } + + private void setData(final byte data, int flag) { + net.minecraft.server.World world = chunk.getHandle().getWorld(); + BlockPosition position = new BlockPosition(x, y, z); + IBlockData blockData = world.getType(position); + world.setTypeAndData(chunk.getHandle(), position, blockData.getBlock().fromLegacyData(data), flag, true, false); + } + + @Override + public int getDurability() { + return chunk.getHandle().getWorld().getDurability(chunk.getHandle(), x, y, z); + } + + @Override + public void setDurability(int durability) { + chunk.getHandle().getWorld().setDurability(chunk.getHandle(), x, y, z, durability); + } + + public byte getData() { + IBlockData blockData = chunk.getHandle().getBlockData(x, y, z); + return (byte) blockData.getBlock().toLegacyData(blockData); + } + + public void setType(final Material type) { + setType(type, true); + } + + @Override + public void setType(Material type, boolean applyPhysics) { + setTypeId(type.getId(), applyPhysics); + } + + public boolean setTypeId(final int type) { + return setTypeId(type, true); + } + + public boolean setTypeId(final int type, final boolean applyPhysics) { + net.minecraft.server.Block block = getNMSBlock(type); + return setTypeIdAndData(type, (byte) block.toLegacyData(block.getBlockData()), applyPhysics); + } + + public boolean setTypeIdAndData(final int type, final byte data, final boolean applyPhysics) { + IBlockData blockData = getNMSBlock(type).fromLegacyData(data); + BlockPosition position = new BlockPosition(x, y, z); + if (applyPhysics) { + return chunk.getHandle().getWorld().setTypeAndData(chunk.getHandle(), position, blockData, 3, true, false); + } else { + boolean success = chunk.getHandle().getWorld().setTypeAndData(chunk.getHandle(), position, blockData, 2, true, false); + if (success) { + chunk.getHandle().getWorld().notify(position); + } + return success; + } + } + + public Material getType() { + return Material.getMaterial(getTypeId()); + } + + @Deprecated + @Override + public int getTypeId() { + return CraftMagicNumbers.getId(chunk.getHandle().getTypeAbs(this.x, this.y, this.z)); + } + + public byte getLightLevel() { + return (byte) chunk.getHandle().getWorld().getLightLevel(this.x, this.y, this.z); + } + + public byte getLightFromSky() { + return (byte) chunk.getHandle().getBrightness(EnumSkyBlock.SKY, this.x, this.y, this.z); + } + + public byte getLightFromBlocks() { + return (byte) chunk.getHandle().getBrightness(EnumSkyBlock.BLOCK, this.x, this.y, this.z); + } + + + public Block getFace(final BlockFace face) { + return getRelative(face, 1); + } + + public Block getFace(final BlockFace face, final int distance) { + return getRelative(face, distance); + } + + public Block getRelative(final int modX, final int modY, final int modZ) { + return getWorld().getBlockAt(getX() + modX, getY() + modY, getZ() + modZ); + } + + public Block getRelative(BlockFace face) { + return getRelative(face, 1); + } + + public Block getRelative(BlockFace face, int distance) { + return getRelative(face.getModX() * distance, face.getModY() * distance, face.getModZ() * distance); + } + + public BlockFace getFace(final Block block) { + BlockFace[] values = BlockFace.values(); + + for (BlockFace face : values) { + if ((this.getX() + face.getModX() == block.getX()) && + (this.getY() + face.getModY() == block.getY()) && + (this.getZ() + face.getModZ() == block.getZ()) + ) { + return face; + } + } + + return null; + } + + @Override + public String toString() { + return "CraftBlock{" + "chunk=" + chunk + ",x=" + x + ",y=" + y + ",z=" + z + ",type=" + getType() + ",data=" + getData() + '}'; + } + + public static BlockFace notchToBlockFace(EnumDirection notch) { + if (notch == null) return BlockFace.SELF; + switch (notch) { + case DOWN: + return BlockFace.DOWN; + case UP: + return BlockFace.UP; + case NORTH: + return BlockFace.NORTH; + case SOUTH: + return BlockFace.SOUTH; + case WEST: + return BlockFace.WEST; + case EAST: + return BlockFace.EAST; + default: + return BlockFace.SELF; + } + } + + public static EnumDirection blockFaceToNotch(BlockFace face) { + switch (face) { + case DOWN: + return EnumDirection.DOWN; + case UP: + return EnumDirection.UP; + case NORTH: + return EnumDirection.NORTH; + case SOUTH: + return EnumDirection.SOUTH; + case WEST: + return EnumDirection.WEST; + case EAST: + return EnumDirection.EAST; + default: + return null; + } + } + + public BlockState getState() { + Material material = getType(); + + switch (material) { + case SIGN: + case SIGN_POST: + case WALL_SIGN: + return new CraftSign(this); + case CHEST: + case TRAPPED_CHEST: + return new CraftChest(this); + case BURNING_FURNACE: + case FURNACE: + return new CraftFurnace(this); + case DISPENSER: + return new CraftDispenser(this); + case DROPPER: + return new CraftDropper(this); + case HOPPER: + return new CraftHopper(this); + case MOB_SPAWNER: + return new CraftCreatureSpawner(this); + case NOTE_BLOCK: + return new CraftNoteBlock(this); + case JUKEBOX: + return new CraftJukebox(this); + case BREWING_STAND: + return new CraftBrewingStand(this); + case SKULL: + return new CraftSkull(this); + case COMMAND: + return new CraftCommandBlock(this); + case BEACON: + return new CraftBeacon(this); + case BANNER: + case WALL_BANNER: + case STANDING_BANNER: + return new CraftBanner(this); + default: + return new CraftBlockState(this); + } + } + + public Biome getBiome() { + return getWorld().getBiome(x, z); + } + + public void setBiome(Biome bio) { + getWorld().setBiome(x, z, bio); + } + + public static Biome biomeBaseToBiome(BiomeBase base) { + if (base == null) { + return null; + } + + return BIOME_MAPPING[base.id]; + } + + public static BiomeBase biomeToBiomeBase(Biome bio) { + if (bio == null) { + return null; + } + return BIOMEBASE_MAPPING[bio.ordinal()]; + } + + public double getTemperature() { + return getWorld().getTemperature(x, z); + } + + public double getHumidity() { + return getWorld().getHumidity(x, z); + } + + public boolean isBlockPowered() { + return chunk.getHandle().getWorld().getBlockPower(new BlockPosition(x, y, z)) > 0; + } + + public boolean isBlockIndirectlyPowered() { + return chunk.getHandle().getWorld().isBlockIndirectlyPowered(new BlockPosition(x, y, z)); + } + + @Override + public boolean equals(Object o) { + if (o == this) return true; + if (!(o instanceof CraftBlock)) return false; + CraftBlock other = (CraftBlock) o; + + return this.x == other.x && this.y == other.y && this.z == other.z && this.getWorld().equals(other.getWorld()); + } + + @Override + public int hashCode() { + return this.y << 24 ^ this.x ^ this.z ^ this.getWorld().hashCode(); + } + + public boolean isBlockFacePowered(BlockFace face) { + return chunk.getHandle().getWorld().isBlockFacePowered(new BlockPosition(x, y, z), blockFaceToNotch(face)); + } + + public boolean isBlockFaceIndirectlyPowered(BlockFace face) { + int power = chunk.getHandle().getWorld().getBlockFacePower(new BlockPosition(x, y, z), blockFaceToNotch(face)); + + Block relative = getRelative(face); + if (relative.getType() == Material.REDSTONE_WIRE) { + return Math.max(power, relative.getData()) > 0; + } + + return power > 0; + } + + public int getBlockPower(BlockFace face) { + int power = 0; + BlockRedstoneWire wire = Blocks.REDSTONE_WIRE; + net.minecraft.server.World world = chunk.getHandle().getWorld(); + if ((face == BlockFace.DOWN || face == BlockFace.SELF) && world.isBlockFacePowered(new BlockPosition(x, y - 1, z), EnumDirection.DOWN)) + power = wire.getPower(world, new BlockPosition(x, y - 1, z), power); + if ((face == BlockFace.UP || face == BlockFace.SELF) && world.isBlockFacePowered(new BlockPosition(x, y + 1, z), EnumDirection.UP)) + power = wire.getPower(world, new BlockPosition(x, y + 1, z), power); + if ((face == BlockFace.EAST || face == BlockFace.SELF) && world.isBlockFacePowered(new BlockPosition(x + 1, y, z), EnumDirection.EAST)) + power = wire.getPower(world, new BlockPosition(x + 1, y, z), power); + if ((face == BlockFace.WEST || face == BlockFace.SELF) && world.isBlockFacePowered(new BlockPosition(x - 1, y, z), EnumDirection.WEST)) + power = wire.getPower(world, new BlockPosition(x - 1, y, z), power); + if ((face == BlockFace.NORTH || face == BlockFace.SELF) && world.isBlockFacePowered(new BlockPosition(x, y, z - 1), EnumDirection.NORTH)) + power = wire.getPower(world, new BlockPosition(x, y, z - 1), power); + if ((face == BlockFace.SOUTH || face == BlockFace.SELF) && world.isBlockFacePowered(new BlockPosition(x, y, z + 1), EnumDirection.SOUTH)) + power = wire.getPower(world, new BlockPosition(x, y, z - 1), power); + return power > 0 ? power : (face == BlockFace.SELF ? isBlockIndirectlyPowered() : isBlockFaceIndirectlyPowered(face)) ? 15 : 0; + } + + public int getBlockPower() { + return getBlockPower(BlockFace.SELF); + } + + public boolean isEmpty() { + return getType() == Material.AIR; + } + + public boolean isLiquid() { + return (getType() == Material.WATER) || (getType() == Material.STATIONARY_WATER) || (getType() == Material.LAVA) || (getType() == Material.STATIONARY_LAVA); + } + + public PistonMoveReaction getPistonMoveReaction() { + return PistonMoveReaction.getById(getNMSBlock().getMaterial().getPushReaction()); + } + + private boolean itemCausesDrops(ItemStack item) { + net.minecraft.server.Block block = this.getNMSBlock(); + net.minecraft.server.Item itemType = item != null ? net.minecraft.server.Item.getById(item.getTypeId()) : null; + return block != null && (block.getMaterial().isAlwaysDestroyable() || (itemType != null && itemType.canDestroySpecialBlock(block))); + } + + public boolean breakNaturally() { + // Order matters here, need to drop before setting to air so skulls can get their data + net.minecraft.server.Block block = this.getNMSBlock(); + byte data = getData(); + boolean result = false; + + if (block != null && block != Blocks.AIR) { + block.dropNaturally(chunk.getHandle().getWorld(), new BlockPosition(x, y, z), block.fromLegacyData(data), 1.0F, 0); + result = true; + } + + setTypeId(Material.AIR.getId()); + return result; + } + + public boolean breakNaturally(ItemStack item) { + if (itemCausesDrops(item)) { + return breakNaturally(); + } else { + return setTypeId(Material.AIR.getId()); + } + } + + public Collection getDrops() { + List drops = new ArrayList<>(); + + net.minecraft.server.Block block = this.getNMSBlock(); + if (block != Blocks.AIR) { + byte data = getData(); + // based on nms.Block.dropNaturally + int count = block.getDropCount(0, chunk.getHandle().getWorld().random); + for (int i = 0; i < count; ++i) { + Item item = block.getDropType(block.fromLegacyData(data), chunk.getHandle().getWorld().random, 0); + if (item != null) { + // Skulls are special, their data is based on the tile entity + if (Blocks.SKULL == block) { + BlockPosition position = new BlockPosition(x, y, z); + net.minecraft.server.ItemStack nmsStack = new net.minecraft.server.ItemStack(item, 1, block.getDropData(chunk.getHandle().getWorld(), position)); + TileEntitySkull tileentityskull = (TileEntitySkull) chunk.getHandle().getWorld().getTileEntity(position); + + if (tileentityskull.getSkullType() == 3 && tileentityskull.getGameProfile() != null) { + nmsStack.setTag(new NBTTagCompound()); + NBTTagCompound nbttagcompound = new NBTTagCompound(); + + GameProfileSerializer.serialize(nbttagcompound, tileentityskull.getGameProfile()); + nmsStack.getTag().set("SkullOwner", nbttagcompound); + } + + drops.add(CraftItemStack.asBukkitCopy(nmsStack)); + // We don't want to drop cocoa blocks, we want to drop cocoa beans. + } else if (Blocks.COCOA == block) { + int age = block.fromLegacyData(data).get(BlockCocoa.AGE); + int dropAmount = (age >= 2 ? 3 : 1); + for (int j = 0; j < dropAmount; ++j) { + drops.add(new ItemStack(Material.INK_SACK, 1, (short) 3)); + } + } else { + drops.add(new ItemStack(org.bukkit.craftbukkit.util.CraftMagicNumbers.getMaterial(item), 1, (short) block.getDropData(block.fromLegacyData(data)))); + } + } + } + } + return drops; + } + + public Collection getDrops(ItemStack item) { + if (itemCausesDrops(item)) { + return getDrops(); + } else { + return Collections.emptyList(); + } + } + + /* Build biome index based lookup table for BiomeBase to Biome mapping */ + static { + BIOME_MAPPING = new Biome[BiomeBase.getBiomes().length]; + BIOMEBASE_MAPPING = new BiomeBase[Biome.values().length]; + BIOME_MAPPING[BiomeBase.OCEAN.id] = Biome.OCEAN; + BIOME_MAPPING[BiomeBase.PLAINS.id] = Biome.PLAINS; + BIOME_MAPPING[BiomeBase.DESERT.id] = Biome.DESERT; + BIOME_MAPPING[BiomeBase.EXTREME_HILLS.id] = Biome.EXTREME_HILLS; + BIOME_MAPPING[BiomeBase.FOREST.id] = Biome.FOREST; + BIOME_MAPPING[BiomeBase.TAIGA.id] = Biome.TAIGA; + BIOME_MAPPING[BiomeBase.SWAMPLAND.id] = Biome.SWAMPLAND; + BIOME_MAPPING[BiomeBase.RIVER.id] = Biome.RIVER; + BIOME_MAPPING[BiomeBase.HELL.id] = Biome.HELL; + BIOME_MAPPING[BiomeBase.SKY.id] = Biome.SKY; + BIOME_MAPPING[BiomeBase.FROZEN_OCEAN.id] = Biome.FROZEN_OCEAN; + BIOME_MAPPING[BiomeBase.FROZEN_RIVER.id] = Biome.FROZEN_RIVER; + BIOME_MAPPING[BiomeBase.ICE_PLAINS.id] = Biome.ICE_PLAINS; + BIOME_MAPPING[BiomeBase.ICE_MOUNTAINS.id] = Biome.ICE_MOUNTAINS; + BIOME_MAPPING[BiomeBase.MUSHROOM_ISLAND.id] = Biome.MUSHROOM_ISLAND; + BIOME_MAPPING[BiomeBase.MUSHROOM_SHORE.id] = Biome.MUSHROOM_SHORE; + BIOME_MAPPING[BiomeBase.BEACH.id] = Biome.BEACH; + BIOME_MAPPING[BiomeBase.DESERT_HILLS.id] = Biome.DESERT_HILLS; + BIOME_MAPPING[BiomeBase.FOREST_HILLS.id] = Biome.FOREST_HILLS; + BIOME_MAPPING[BiomeBase.TAIGA_HILLS.id] = Biome.TAIGA_HILLS; + BIOME_MAPPING[BiomeBase.SMALL_MOUNTAINS.id] = Biome.SMALL_MOUNTAINS; + BIOME_MAPPING[BiomeBase.JUNGLE.id] = Biome.JUNGLE; + BIOME_MAPPING[BiomeBase.JUNGLE_HILLS.id] = Biome.JUNGLE_HILLS; + BIOME_MAPPING[BiomeBase.JUNGLE_EDGE.id] = Biome.JUNGLE_EDGE; + BIOME_MAPPING[BiomeBase.DEEP_OCEAN.id] = Biome.DEEP_OCEAN; + BIOME_MAPPING[BiomeBase.STONE_BEACH.id] = Biome.STONE_BEACH; + BIOME_MAPPING[BiomeBase.COLD_BEACH.id] = Biome.COLD_BEACH; + BIOME_MAPPING[BiomeBase.BIRCH_FOREST.id] = Biome.BIRCH_FOREST; + BIOME_MAPPING[BiomeBase.BIRCH_FOREST_HILLS.id] = Biome.BIRCH_FOREST_HILLS; + BIOME_MAPPING[BiomeBase.ROOFED_FOREST.id] = Biome.ROOFED_FOREST; + BIOME_MAPPING[BiomeBase.COLD_TAIGA.id] = Biome.COLD_TAIGA; + BIOME_MAPPING[BiomeBase.COLD_TAIGA_HILLS.id] = Biome.COLD_TAIGA_HILLS; + BIOME_MAPPING[BiomeBase.MEGA_TAIGA.id] = Biome.MEGA_TAIGA; + BIOME_MAPPING[BiomeBase.MEGA_TAIGA_HILLS.id] = Biome.MEGA_TAIGA_HILLS; + BIOME_MAPPING[BiomeBase.EXTREME_HILLS_PLUS.id] = Biome.EXTREME_HILLS_PLUS; + BIOME_MAPPING[BiomeBase.SAVANNA.id] = Biome.SAVANNA; + BIOME_MAPPING[BiomeBase.SAVANNA_PLATEAU.id] = Biome.SAVANNA_PLATEAU; + BIOME_MAPPING[BiomeBase.MESA.id] = Biome.MESA; + BIOME_MAPPING[BiomeBase.MESA_PLATEAU_F.id] = Biome.MESA_PLATEAU_FOREST; + BIOME_MAPPING[BiomeBase.MESA_PLATEAU.id] = Biome.MESA_PLATEAU; + + // Extended Biomes + BIOME_MAPPING[BiomeBase.PLAINS.id + 128] = Biome.SUNFLOWER_PLAINS; + BIOME_MAPPING[BiomeBase.DESERT.id + 128] = Biome.DESERT_MOUNTAINS; + BIOME_MAPPING[BiomeBase.FOREST.id + 128] = Biome.FLOWER_FOREST; + BIOME_MAPPING[BiomeBase.TAIGA.id + 128] = Biome.TAIGA_MOUNTAINS; + BIOME_MAPPING[BiomeBase.SWAMPLAND.id + 128] = Biome.SWAMPLAND_MOUNTAINS; + BIOME_MAPPING[BiomeBase.ICE_PLAINS.id + 128] = Biome.ICE_PLAINS_SPIKES; + BIOME_MAPPING[BiomeBase.JUNGLE.id + 128] = Biome.JUNGLE_MOUNTAINS; + BIOME_MAPPING[BiomeBase.JUNGLE_EDGE.id + 128] = Biome.JUNGLE_EDGE_MOUNTAINS; + BIOME_MAPPING[BiomeBase.COLD_TAIGA.id + 128] = Biome.COLD_TAIGA_MOUNTAINS; + BIOME_MAPPING[BiomeBase.SAVANNA.id + 128] = Biome.SAVANNA_MOUNTAINS; + BIOME_MAPPING[BiomeBase.SAVANNA_PLATEAU.id + 128] = Biome.SAVANNA_PLATEAU_MOUNTAINS; + BIOME_MAPPING[BiomeBase.MESA.id + 128] = Biome.MESA_BRYCE; + BIOME_MAPPING[BiomeBase.MESA_PLATEAU_F.id + 128] = Biome.MESA_PLATEAU_FOREST_MOUNTAINS; + BIOME_MAPPING[BiomeBase.MESA_PLATEAU.id + 128] = Biome.MESA_PLATEAU_MOUNTAINS; + BIOME_MAPPING[BiomeBase.BIRCH_FOREST.id + 128] = Biome.BIRCH_FOREST_MOUNTAINS; + BIOME_MAPPING[BiomeBase.BIRCH_FOREST_HILLS.id + 128] = Biome.BIRCH_FOREST_HILLS_MOUNTAINS; + BIOME_MAPPING[BiomeBase.ROOFED_FOREST.id + 128] = Biome.ROOFED_FOREST_MOUNTAINS; + BIOME_MAPPING[BiomeBase.MEGA_TAIGA.id + 128] = Biome.MEGA_SPRUCE_TAIGA; + BIOME_MAPPING[BiomeBase.EXTREME_HILLS.id + 128] = Biome.EXTREME_HILLS_MOUNTAINS; + BIOME_MAPPING[BiomeBase.EXTREME_HILLS_PLUS.id + 128] = Biome.EXTREME_HILLS_PLUS_MOUNTAINS; + BIOME_MAPPING[BiomeBase.MEGA_TAIGA_HILLS.id + 128] = Biome.MEGA_SPRUCE_TAIGA_HILLS; + + /* Sanity check - we should have a record for each record in the BiomeBase.a table */ + /* Helps avoid missed biomes when we upgrade bukkit to new code with new biomes */ + for (int i = 0; i < BIOME_MAPPING.length; i++) { + if ((BiomeBase.getBiome(i) != null) && (BIOME_MAPPING[i] == null)) { + throw new IllegalArgumentException("Missing Biome mapping for BiomeBase[" + i + ", " + BiomeBase.getBiome(i) + "]"); + } + if (BIOME_MAPPING[i] != null) { /* Build reverse mapping for setBiome */ + BIOMEBASE_MAPPING[BIOME_MAPPING[i].ordinal()] = BiomeBase.getBiome(i); + } + } + } + + public void setMetadata(String metadataKey, MetadataValue newMetadataValue) { + chunk.getCraftWorld().getBlockMetadata().setMetadata(this, metadataKey, newMetadataValue); + } + + public List getMetadata(String metadataKey) { + return chunk.getCraftWorld().getBlockMetadata().getMetadata(this, metadataKey); + } + + public boolean hasMetadata(String metadataKey) { + return chunk.getCraftWorld().getBlockMetadata().hasMetadata(this, metadataKey); + } + + public void removeMetadata(String metadataKey, Plugin owningPlugin) { + chunk.getCraftWorld().getBlockMetadata().removeMetadata(this, metadataKey, owningPlugin); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/block/CraftBlockState.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/block/CraftBlockState.java new file mode 100644 index 0000000..b0d9202 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/block/CraftBlockState.java @@ -0,0 +1,274 @@ +package org.bukkit.craftbukkit.block; + +import net.minecraft.server.BlockPosition; +import net.minecraft.server.TileEntity; +import org.bukkit.Chunk; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.block.BlockState; +import org.bukkit.craftbukkit.CraftChunk; +import org.bukkit.craftbukkit.CraftWorld; +import org.bukkit.material.MaterialData; +import org.bukkit.metadata.MetadataValue; +import org.bukkit.plugin.Plugin; + +import java.util.List; +import java.util.Objects; + +public class CraftBlockState implements BlockState { + private final CraftWorld world; + private final CraftChunk chunk; + private final int x; + private final int y; + private final int z; + protected int type; + protected MaterialData data; + protected int flag; + protected final byte light; + + public CraftBlockState(final Block block) { + this.world = (CraftWorld) block.getWorld(); + this.x = block.getX(); + this.y = block.getY(); + this.z = block.getZ(); + this.type = block.getTypeId(); + this.light = block.getLightLevel(); + this.chunk = (CraftChunk) block.getChunk(); + this.flag = 3; + + createData(block.getData()); + } + + public CraftBlockState(final Block block, int flag) { + this(block); + this.flag = flag; + } + + public CraftBlockState(Material material) { + world = null; + type = material.getId(); + light = 0; + chunk = null; + x = y = z = 0; + } + + public static CraftBlockState getBlockState(net.minecraft.server.World world, int x, int y, int z) { + return new CraftBlockState(world.getWorld().getBlockAt(x, y, z)); + } + + public static CraftBlockState getBlockState(net.minecraft.server.World world, int x, int y, int z, int flag) { + return new CraftBlockState(world.getWorld().getBlockAt(x, y, z), flag); + } + + public World getWorld() { + requirePlaced(); + return world; + } + + public int getX() { + return x; + } + + public int getY() { + return y; + } + + public int getZ() { + return z; + } + + public Chunk getChunk() { + requirePlaced(); + return chunk; + } + + public void setData(final MaterialData data) { + Material mat = getType(); + + if (mat == null) { + this.data = data; + } else { + if ((data.getClass() == mat.getData()) || (data.getClass() == MaterialData.class)) { + this.data = data; + } else { + throw new IllegalArgumentException("Provided data is not of type " + + mat.getData().getName() + ", found " + data.getClass().getName()); + } + } + } + + public MaterialData getData() { + return data; + } + + public void setType(final Material type) { + setTypeId(type.getId()); + } + + public boolean setTypeId(final int type) { + if (this.type != type) { + this.type = type; + + createData((byte) 0); + } + return true; + } + + public Material getType() { + return Material.getMaterial(getTypeId()); + } + + public void setFlag(int flag) { + this.flag = flag; + } + + public int getFlag() { + return flag; + } + + public int getTypeId() { + return type; + } + + public byte getLightLevel() { + return light; + } + + public Block getBlock() { + requirePlaced(); + return world.getBlockAt(x, y, z); + } + + public boolean update() { + return update(false); + } + + public boolean update(boolean force) { + return update(force, true); + } + + public boolean update(boolean force, boolean applyPhysics) { + requirePlaced(); + Block block = getBlock(); + + if (block.getType() != getType()) { + if (!force) { + return false; + } + } + + block.setTypeIdAndData(getTypeId(), getRawData(), applyPhysics); + world.getHandle().notify(x, y, z); + return true; + } + + private void createData(final byte data) { + Material mat = getType(); + if (mat == null) { + this.data = new MaterialData(type, data); + } else { + this.data = mat.getNewData(data); + } + } + + public byte getRawData() { + return data.getData(); + } + + public Location getLocation() { + return new Location(world, x, y, z); + } + + public Location getLocation(Location loc) { + if (loc != null) { + loc.setWorld(world); + loc.setX(x); + loc.setY(y); + loc.setZ(z); + loc.setYaw(0); + loc.setPitch(0); + } + + return loc; + } + + public void setRawData(byte data) { + this.data.setData(data); + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final CraftBlockState other = (CraftBlockState) obj; + if (!Objects.equals(this.world, other.world)) { + return false; + } + if (this.x != other.x) { + return false; + } + if (this.y != other.y) { + return false; + } + if (this.z != other.z) { + return false; + } + if (this.type != other.type) { + return false; + } + return Objects.equals(this.data, other.data); + } + + @Override + public int hashCode() { + int hash = 7; + hash = 73 * hash + (this.world != null ? this.world.hashCode() : 0); + hash = 73 * hash + this.x; + hash = 73 * hash + this.y; + hash = 73 * hash + this.z; + hash = 73 * hash + this.type; + hash = 73 * hash + (this.data != null ? this.data.hashCode() : 0); + return hash; + } + + public TileEntity getTileEntity() { + return null; + } + + public void setMetadata(String metadataKey, MetadataValue newMetadataValue) { + requirePlaced(); + chunk.getCraftWorld().getBlockMetadata().setMetadata(getBlock(), metadataKey, newMetadataValue); + } + + public List getMetadata(String metadataKey) { + requirePlaced(); + return chunk.getCraftWorld().getBlockMetadata().getMetadata(getBlock(), metadataKey); + } + + public boolean hasMetadata(String metadataKey) { + requirePlaced(); + return chunk.getCraftWorld().getBlockMetadata().hasMetadata(getBlock(), metadataKey); + } + + public void removeMetadata(String metadataKey, Plugin owningPlugin) { + requirePlaced(); + chunk.getCraftWorld().getBlockMetadata().removeMetadata(getBlock(), metadataKey, owningPlugin); + } + + @Override + public boolean isPlaced() { + return world != null; + } + + protected void requirePlaced() { + if (!isPlaced()) { + throw new IllegalStateException("The blockState must be placed to call this method"); + } + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/block/CraftBrewingStand.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/block/CraftBrewingStand.java new file mode 100644 index 0000000..a910da2 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/block/CraftBrewingStand.java @@ -0,0 +1,52 @@ +package org.bukkit.craftbukkit.block; + +import net.minecraft.server.TileEntityBrewingStand; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.BrewingStand; +import org.bukkit.craftbukkit.CraftWorld; +import org.bukkit.craftbukkit.inventory.CraftInventoryBrewer; +import org.bukkit.inventory.BrewerInventory; + +public class CraftBrewingStand extends CraftBlockState implements BrewingStand { + private final TileEntityBrewingStand brewingStand; + + public CraftBrewingStand(Block block) { + super(block); + + brewingStand = (TileEntityBrewingStand) ((CraftWorld) block.getWorld()).getTileEntityAt(getX(), getY(), getZ()); + } + + public CraftBrewingStand(final Material material, final TileEntityBrewingStand te) { + super(material); + brewingStand = te; + } + + public BrewerInventory getInventory() { + return new CraftInventoryBrewer(brewingStand); + } + + @Override + public boolean update(boolean force, boolean applyPhysics) { + boolean result = super.update(force, applyPhysics); + + if (result) { + brewingStand.update(); + } + + return result; + } + + public int getBrewingTime() { + return brewingStand.brewTime; + } + + public void setBrewingTime(int brewTime) { + brewingStand.brewTime = brewTime; + } + + @Override + public TileEntityBrewingStand getTileEntity() { + return brewingStand; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/block/CraftChest.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/block/CraftChest.java new file mode 100644 index 0000000..207db95 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/block/CraftChest.java @@ -0,0 +1,86 @@ +package org.bukkit.craftbukkit.block; + +import net.minecraft.server.BlockPosition; +import net.minecraft.server.TileEntityChest; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.Chest; +import org.bukkit.craftbukkit.CraftWorld; +import org.bukkit.craftbukkit.inventory.CraftInventory; +import org.bukkit.craftbukkit.inventory.CraftInventoryDoubleChest; +import org.bukkit.inventory.Inventory; + +public class CraftChest extends CraftBlockState implements Chest { + private final CraftWorld world; + private final TileEntityChest chest; + + public CraftChest(final Block block) { + super(block); + + world = (CraftWorld) block.getWorld(); + chest = (TileEntityChest) world.getTileEntityAt(getX(), getY(), getZ()); + } + + public CraftChest(final Material material, final TileEntityChest te) { + super(material); + chest = te; + world = null; + } + + public Inventory getBlockInventory() { + return new CraftInventory(chest); + } + + public Inventory getInventory() { + int x = getX(); + int y = getY(); + int z = getZ(); + // The logic here is basically identical to the logic in BlockChest.interact + CraftInventory inventory = new CraftInventory(chest); + if (!isPlaced()) { + return inventory; + } + int id; + if (world.getBlockTypeIdAt(x, y, z) == Material.CHEST.getId()) { + id = Material.CHEST.getId(); + } else if (world.getBlockTypeIdAt(x, y, z) == Material.TRAPPED_CHEST.getId()) { + id = Material.TRAPPED_CHEST.getId(); + } else { + throw new IllegalStateException("CraftChest is not a chest but is instead " + world.getBlockAt(x, y, z)); + } + + if (world.getBlockTypeIdAt(x - 1, y, z) == id) { + CraftInventory left = new CraftInventory((TileEntityChest)world.getHandle().getTileEntity(new BlockPosition(x - 1, y, z))); + inventory = new CraftInventoryDoubleChest(left, inventory); + } + if (world.getBlockTypeIdAt(x + 1, y, z) == id) { + CraftInventory right = new CraftInventory((TileEntityChest) world.getHandle().getTileEntity(new BlockPosition(x + 1, y, z))); + inventory = new CraftInventoryDoubleChest(inventory, right); + } + if (world.getBlockTypeIdAt(x, y, z - 1) == id) { + CraftInventory left = new CraftInventory((TileEntityChest) world.getHandle().getTileEntity(new BlockPosition(x, y, z - 1))); + inventory = new CraftInventoryDoubleChest(left, inventory); + } + if (world.getBlockTypeIdAt(x, y, z + 1) == id) { + CraftInventory right = new CraftInventory((TileEntityChest) world.getHandle().getTileEntity(new BlockPosition(x, y, z + 1))); + inventory = new CraftInventoryDoubleChest(inventory, right); + } + return inventory; + } + + @Override + public boolean update(boolean force, boolean applyPhysics) { + boolean result = super.update(force, applyPhysics); + + if (result) { + chest.update(); + } + + return result; + } + + @Override + public TileEntityChest getTileEntity() { + return chest; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/block/CraftCommandBlock.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/block/CraftCommandBlock.java new file mode 100644 index 0000000..9bbc790 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/block/CraftCommandBlock.java @@ -0,0 +1,61 @@ +package org.bukkit.craftbukkit.block; + +import net.minecraft.server.TileEntityCommand; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.CommandBlock; +import org.bukkit.craftbukkit.CraftWorld; + +public class CraftCommandBlock extends CraftBlockState implements CommandBlock { + private final TileEntityCommand commandBlock; + private String command; + private String name; + + public CraftCommandBlock(Block block) { + super(block); + + CraftWorld world = (CraftWorld) block.getWorld(); + commandBlock = (TileEntityCommand) world.getTileEntityAt(getX(), getY(), getZ()); + command = commandBlock.getCommandBlock().getCommand(); + name = commandBlock.getCommandBlock().getName(); + } + + public CraftCommandBlock(final Material material, final TileEntityCommand te) { + super(material); + commandBlock = te; + command = commandBlock.getCommandBlock().getCommand(); + name = commandBlock.getCommandBlock().getName(); + } + + public String getCommand() { + return command; + } + + public void setCommand(String command) { + this.command = command != null ? command : ""; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name != null ? name : "@"; + } + + public boolean update(boolean force, boolean applyPhysics) { + boolean result = super.update(force, applyPhysics); + + if (result) { + commandBlock.getCommandBlock().setCommand(command); + commandBlock.getCommandBlock().setName(name); + } + + return result; + } + + @Override + public TileEntityCommand getTileEntity() { + return commandBlock; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/block/CraftCreatureSpawner.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/block/CraftCreatureSpawner.java new file mode 100644 index 0000000..6d82637 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/block/CraftCreatureSpawner.java @@ -0,0 +1,82 @@ +package org.bukkit.craftbukkit.block; + +import net.minecraft.server.TileEntityMobSpawner; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.CreatureSpawner; +import org.bukkit.craftbukkit.CraftWorld; +import org.bukkit.entity.CreatureType; +import org.bukkit.entity.EntityType; + +public class CraftCreatureSpawner extends CraftBlockState implements CreatureSpawner { + private final TileEntityMobSpawner spawner; + + public CraftCreatureSpawner(final Block block) { + super(block); + + spawner = (TileEntityMobSpawner) ((CraftWorld) block.getWorld()).getTileEntityAt(getX(), getY(), getZ()); + } + + public CraftCreatureSpawner(final Material material, TileEntityMobSpawner te) { + super(material); + spawner = te; + } + + @Deprecated + public CreatureType getCreatureType() { + return CreatureType.fromName(spawner.getSpawner().getMobName()); + } + + public EntityType getSpawnedType() { + return EntityType.fromName(spawner.getSpawner().getMobName()); + } + + @Deprecated + public void setCreatureType(CreatureType creatureType) { + spawner.getSpawner().setMobName(creatureType.getName()); + } + + public void setSpawnedType(EntityType entityType) { + if (entityType == null || entityType.getName() == null) { + throw new IllegalArgumentException("Can't spawn EntityType " + entityType + " from mobspawners!"); + } + + spawner.getSpawner().setMobName(entityType.getName()); + } + + @Deprecated + public String getCreatureTypeId() { + return spawner.getSpawner().getMobName(); + } + + @Deprecated + public void setCreatureTypeId(String creatureName) { + setCreatureTypeByName(creatureName); + } + + public String getCreatureTypeName() { + return spawner.getSpawner().getMobName(); + } + + public void setCreatureTypeByName(String creatureType) { + // Verify input + EntityType type = EntityType.fromName(creatureType); + if (type == null) { + return; + } + setSpawnedType(type); + } + + public int getDelay() { + return spawner.getSpawner().spawnDelay; + } + + public void setDelay(int delay) { + spawner.getSpawner().spawnDelay = delay; + } + + @Override + public TileEntityMobSpawner getTileEntity() { + return spawner; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/block/CraftDispenser.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/block/CraftDispenser.java new file mode 100644 index 0000000..695cc9d --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/block/CraftDispenser.java @@ -0,0 +1,75 @@ +package org.bukkit.craftbukkit.block; + +import net.minecraft.server.BlockDispenser; +import net.minecraft.server.BlockPosition; +import net.minecraft.server.Blocks; +import net.minecraft.server.TileEntityDispenser; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.Dispenser; +import org.bukkit.craftbukkit.CraftWorld; +import org.bukkit.craftbukkit.inventory.CraftInventory; +import org.bukkit.craftbukkit.projectiles.CraftBlockProjectileSource; +import org.bukkit.inventory.Inventory; +import org.bukkit.projectiles.BlockProjectileSource; + +public class CraftDispenser extends CraftBlockState implements Dispenser { + private final CraftWorld world; + private final TileEntityDispenser dispenser; + + public CraftDispenser(final Block block) { + super(block); + + world = (CraftWorld) block.getWorld(); + dispenser = (TileEntityDispenser) world.getTileEntityAt(getX(), getY(), getZ()); + } + + public CraftDispenser(final Material material, final TileEntityDispenser te) { + super(material); + world = null; + dispenser = te; + } + + public Inventory getInventory() { + return new CraftInventory(dispenser); + } + + public BlockProjectileSource getBlockProjectileSource() { + Block block = getBlock(); + + if (block.getType() != Material.DISPENSER) { + return null; + } + + return new CraftBlockProjectileSource(dispenser); + } + + public boolean dispense() { + Block block = getBlock(); + + if (block.getType() == Material.DISPENSER) { + BlockDispenser dispense = (BlockDispenser) Blocks.DISPENSER; + + dispense.dispense(world.getHandle(), new BlockPosition(getX(), getY(), getZ())); + return true; + } else { + return false; + } + } + + @Override + public boolean update(boolean force, boolean applyPhysics) { + boolean result = super.update(force, applyPhysics); + + if (result) { + dispenser.update(); + } + + return result; + } + + @Override + public TileEntityDispenser getTileEntity() { + return dispenser; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/block/CraftDropper.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/block/CraftDropper.java new file mode 100644 index 0000000..2f3602a --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/block/CraftDropper.java @@ -0,0 +1,60 @@ +package org.bukkit.craftbukkit.block; + +import net.minecraft.server.BlockDropper; +import net.minecraft.server.BlockPosition; +import net.minecraft.server.Blocks; +import net.minecraft.server.TileEntityDropper; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.Dropper; +import org.bukkit.craftbukkit.CraftWorld; +import org.bukkit.craftbukkit.inventory.CraftInventory; +import org.bukkit.inventory.Inventory; + +public class CraftDropper extends CraftBlockState implements Dropper { + private final CraftWorld world; + private final TileEntityDropper dropper; + + public CraftDropper(final Block block) { + super(block); + + world = (CraftWorld) block.getWorld(); + dropper = (TileEntityDropper) world.getTileEntityAt(getX(), getY(), getZ()); + } + + public CraftDropper(final Material material, TileEntityDropper te) { + super(material); + world = null; + dropper = te; + } + + public Inventory getInventory() { + return new CraftInventory(dropper); + } + + public void drop() { + Block block = getBlock(); + + if (block.getType() == Material.DROPPER) { + BlockDropper drop = (BlockDropper) Blocks.DROPPER; + + drop.dispense(world.getHandle(), new BlockPosition(getX(), getY(), getZ())); + } + } + + @Override + public boolean update(boolean force, boolean applyPhysics) { + boolean result = super.update(force, applyPhysics); + + if (result) { + dropper.update(); + } + + return result; + } + + @Override + public TileEntityDropper getTileEntity() { + return dropper; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/block/CraftFurnace.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/block/CraftFurnace.java new file mode 100644 index 0000000..9d86d2d --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/block/CraftFurnace.java @@ -0,0 +1,54 @@ +package org.bukkit.craftbukkit.block; + +import net.minecraft.server.TileEntityFurnace; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.Furnace; +import org.bukkit.craftbukkit.CraftWorld; +import org.bukkit.craftbukkit.inventory.CraftInventoryFurnace; +import org.bukkit.inventory.FurnaceInventory; + +public class CraftFurnace extends CraftBlockState implements Furnace { + private final TileEntityFurnace furnace; + + public CraftFurnace(Block block) { + super(block); + this.furnace = (TileEntityFurnace)((CraftWorld)block.getWorld()).getTileEntityAt(getX(), getY(), getZ()); + } + + public CraftFurnace(Material material, TileEntityFurnace te) { + super(material); + this.furnace = te; + } + + public FurnaceInventory getInventory() { + return new CraftInventoryFurnace(this.furnace); + } + + public boolean update(boolean force, boolean applyPhysics) { + boolean result = super.update(force, applyPhysics); + if (result) + this.furnace.update(); + return result; + } + + public short getBurnTime() { + return (short)this.furnace.burnTime; + } + + public void setBurnTime(short burnTime) { + this.furnace.burnTime = burnTime; + } + + public short getCookTime() { + return (short)this.furnace.cookTime; + } + + public void setCookTime(short cookTime) { + this.furnace.cookTime = cookTime; + } + + public TileEntityFurnace getTileEntity() { + return this.furnace; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/block/CraftHopper.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/block/CraftHopper.java new file mode 100644 index 0000000..db844a3 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/block/CraftHopper.java @@ -0,0 +1,45 @@ +package org.bukkit.craftbukkit.block; + +import net.minecraft.server.TileEntityHopper; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.Hopper; +import org.bukkit.craftbukkit.CraftWorld; +import org.bukkit.craftbukkit.inventory.CraftInventory; +import org.bukkit.inventory.Inventory; + +public class CraftHopper extends CraftBlockState implements Hopper { + private final TileEntityHopper hopper; + + public CraftHopper(final Block block) { + super(block); + + hopper = (TileEntityHopper) ((CraftWorld) block.getWorld()).getTileEntityAt(getX(), getY(), getZ()); + } + + public CraftHopper(final Material material, final TileEntityHopper te) { + super(material); + + hopper = te; + } + + public Inventory getInventory() { + return new CraftInventory(hopper); + } + + @Override + public boolean update(boolean force, boolean applyPhysics) { + boolean result = super.update(force, applyPhysics); + + if (result) { + hopper.update(); + } + + return result; + } + + @Override + public TileEntityHopper getTileEntity() { + return hopper; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/block/CraftJukebox.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/block/CraftJukebox.java new file mode 100644 index 0000000..a25b3c5 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/block/CraftJukebox.java @@ -0,0 +1,80 @@ +package org.bukkit.craftbukkit.block; + +import net.minecraft.server.BlockJukeBox; +import net.minecraft.server.BlockJukeBox.TileEntityRecordPlayer; +import net.minecraft.server.BlockPosition; +import net.minecraft.server.Blocks; +import net.minecraft.server.ItemStack; +import org.bukkit.Effect; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.Jukebox; +import org.bukkit.craftbukkit.CraftWorld; +import org.bukkit.craftbukkit.util.CraftMagicNumbers; + +public class CraftJukebox extends CraftBlockState implements Jukebox { + private final CraftWorld world; + private final TileEntityRecordPlayer jukebox; + + public CraftJukebox(final Block block) { + super(block); + + world = (CraftWorld) block.getWorld(); + jukebox = (TileEntityRecordPlayer) world.getTileEntityAt(getX(), getY(), getZ()); + } + + public CraftJukebox(final Material material, TileEntityRecordPlayer te) { + super(material); + world = null; + jukebox = te; + } + + @Override + public Material getPlaying() { + ItemStack record = jukebox.getRecord(); + if (record == null) { + return Material.AIR; + } + return CraftMagicNumbers.getMaterial(record.getItem()); + } + + @Override + public void setPlaying(Material record) { + if (record == null || CraftMagicNumbers.getItem(record) == null) { + record = Material.AIR; + jukebox.setRecord(null); + } else { + jukebox.setRecord(new ItemStack(CraftMagicNumbers.getItem(record), 1)); + } + if (!isPlaced()) { + return; + } + jukebox.update(); + if (record == Material.AIR) { + world.getHandle().setTypeAndData(new BlockPosition(getX(), getY(), getZ()), + Blocks.JUKEBOX.getBlockData() + .set(BlockJukeBox.HAS_RECORD, false), 3); + } else { + world.getHandle().setTypeAndData(new BlockPosition(getX(), getY(), getZ()), + Blocks.JUKEBOX.getBlockData() + .set(BlockJukeBox.HAS_RECORD, true), 3); + } + world.playEffect(getLocation(), Effect.RECORD_PLAY, record.getId()); + } + + public boolean isPlaying() { + return getRawData() == 1; + } + + public boolean eject() { + requirePlaced(); + boolean result = isPlaying(); + ((BlockJukeBox) Blocks.JUKEBOX).dropRecord(world.getHandle(), new BlockPosition(getX(), getY(), getZ()), null); + return result; + } + + @Override + public TileEntityRecordPlayer getTileEntity() { + return jukebox; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/block/CraftNoteBlock.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/block/CraftNoteBlock.java new file mode 100644 index 0000000..0c84444 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/block/CraftNoteBlock.java @@ -0,0 +1,85 @@ +package org.bukkit.craftbukkit.block; + +import net.minecraft.server.BlockPosition; +import net.minecraft.server.TileEntityNote; +import org.bukkit.Instrument; +import org.bukkit.Material; +import org.bukkit.Note; +import org.bukkit.block.Block; +import org.bukkit.block.NoteBlock; +import org.bukkit.craftbukkit.CraftWorld; +import org.bukkit.craftbukkit.util.CraftMagicNumbers; + +public class CraftNoteBlock extends CraftBlockState implements NoteBlock { + private final CraftWorld world; + private final TileEntityNote note; + + public CraftNoteBlock(final Block block) { + super(block); + + world = (CraftWorld) block.getWorld(); + note = (TileEntityNote) world.getTileEntityAt(getX(), getY(), getZ()); + } + + public CraftNoteBlock(final Material material, final TileEntityNote te) { + super(material); + world = null; + note = te; + } + + public Note getNote() { + return new Note(note.note); + } + + public byte getRawNote() { + return note.note; + } + + public void setNote(Note n) { + note.note = n.getId(); + } + + public void setRawNote(byte n) { + note.note = n; + } + + public boolean play() { + Block block = getBlock(); + + if (block.getType() == Material.NOTE_BLOCK) { + note.play(world.getHandle(), new BlockPosition(getX(), getY(), getZ())); + return true; + } else { + return false; + } + } + + @Override + public boolean play(byte instrument, byte note) { + Block block = getBlock(); + + if (block.getType() == Material.NOTE_BLOCK) { + world.getHandle().playBlockAction(new BlockPosition(getX(), getY(), getZ()), CraftMagicNumbers.getBlock(block), instrument, note); + return true; + } else { + return false; + } + } + + @Override + public boolean play(Instrument instrument, Note note) { + Block block = getBlock(); + + if (block.getType() == Material.NOTE_BLOCK) { + world.getHandle().playBlockAction(new BlockPosition(getX(), getY(), getZ()), CraftMagicNumbers.getBlock(block), instrument.getType(), note.getId()); + return true; + } else { + return false; + } + } + + @Override + public TileEntityNote getTileEntity() { + return note; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/block/CraftSign.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/block/CraftSign.java new file mode 100644 index 0000000..43adfcc --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/block/CraftSign.java @@ -0,0 +1,93 @@ +package org.bukkit.craftbukkit.block; + +import net.minecraft.server.ChatComponentText; +import net.minecraft.server.IChatBaseComponent; +import net.minecraft.server.TileEntitySign; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.Sign; +import org.bukkit.craftbukkit.CraftWorld; +import org.bukkit.craftbukkit.util.CraftChatMessage; + +public class CraftSign extends CraftBlockState implements Sign { + private final TileEntitySign sign; + private final String[] lines; + + public CraftSign(final Block block) { + super(block); + + CraftWorld world = (CraftWorld) block.getWorld(); + sign = (TileEntitySign) world.getTileEntityAt(getX(), getY(), getZ()); + // Spigot start + if (sign == null) { + lines = new String[]{"", "", "", ""}; + return; + } + // Spigot end + lines = new String[sign.lines.length]; + System.arraycopy(revertComponents(sign.lines), 0, lines, 0, lines.length); + } + + public CraftSign(final Material material, final TileEntitySign te) { + super(material); + sign = te; + lines = new String[sign.lines.length]; + System.arraycopy(revertComponents(sign.lines), 0, lines, 0, lines.length); + } + + public String[] getLines() { + return lines; + } + + public String getLine(int index) throws IndexOutOfBoundsException { + return lines[index]; + } + + public void setLine(int index, String line) throws IndexOutOfBoundsException { + lines[index] = line; + } + + @Override + public boolean update(boolean force, boolean applyPhysics) { + boolean result = super.update(force, applyPhysics); + + if (result) { + IChatBaseComponent[] newLines = sanitizeLines(lines); + System.arraycopy(newLines, 0, sign.lines, 0, 4); + sign.update(); + } + + return result; + } + + public static IChatBaseComponent[] sanitizeLines(String[] lines) { + IChatBaseComponent[] components = new IChatBaseComponent[4]; + + for (int i = 0; i < 4; i++) { + if (i < lines.length && lines[i] != null) { + components[i] = CraftChatMessage.fromString(lines[i])[0]; + } else { + components[i] = new ChatComponentText(""); + } + } + + return components; + } + + public static String[] revertComponents(IChatBaseComponent[] components) { + String[] lines = new String[components.length]; + for (int i = 0; i < lines.length; i++) { + lines[i] = revertComponent(components[i]); + } + return lines; + } + + private static String revertComponent(IChatBaseComponent component) { + return CraftChatMessage.fromComponent(component); + } + + @Override + public TileEntitySign getTileEntity() { + return sign; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/block/CraftSkull.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/block/CraftSkull.java new file mode 100644 index 0000000..ddd0909 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/block/CraftSkull.java @@ -0,0 +1,216 @@ +package org.bukkit.craftbukkit.block; + +import com.mojang.authlib.GameProfile; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.TileEntitySkull; +import org.bukkit.Material; +import org.bukkit.SkullType; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.block.Skull; +import org.bukkit.craftbukkit.CraftWorld; + +public class CraftSkull extends CraftBlockState implements Skull { + private static final int MAX_OWNER_LENGTH = 16; + private final TileEntitySkull skull; + private GameProfile profile; + private SkullType skullType; + private byte rotation; + + public CraftSkull(final Block block) { + super(block); + + CraftWorld world = (CraftWorld) block.getWorld(); + skull = (TileEntitySkull) world.getTileEntityAt(getX(), getY(), getZ()); + profile = skull.getGameProfile(); + skullType = getSkullType(skull.getSkullType()); + rotation = (byte) skull.getRotation(); + } + + public CraftSkull(final Material material, final TileEntitySkull te) { + super(material); + skull = te; + profile = skull.getGameProfile(); + skullType = getSkullType(skull.getSkullType()); + rotation = (byte) skull.getRotation(); + } + + static SkullType getSkullType(int id) { + switch (id) { + default: + case 0: + return SkullType.SKELETON; + case 1: + return SkullType.WITHER; + case 2: + return SkullType.ZOMBIE; + case 3: + return SkullType.PLAYER; + case 4: + return SkullType.CREEPER; + } + } + + static int getSkullType(SkullType type) { + switch(type) { + default: + case SKELETON: + return 0; + case WITHER: + return 1; + case ZOMBIE: + return 2; + case PLAYER: + return 3; + case CREEPER: + return 4; + } + } + + static byte getBlockFace(BlockFace rotation) { + switch (rotation) { + case NORTH: + return 0; + case NORTH_NORTH_EAST: + return 1; + case NORTH_EAST: + return 2; + case EAST_NORTH_EAST: + return 3; + case EAST: + return 4; + case EAST_SOUTH_EAST: + return 5; + case SOUTH_EAST: + return 6; + case SOUTH_SOUTH_EAST: + return 7; + case SOUTH: + return 8; + case SOUTH_SOUTH_WEST: + return 9; + case SOUTH_WEST: + return 10; + case WEST_SOUTH_WEST: + return 11; + case WEST: + return 12; + case WEST_NORTH_WEST: + return 13; + case NORTH_WEST: + return 14; + case NORTH_NORTH_WEST: + return 15; + default: + throw new IllegalArgumentException("Invalid BlockFace rotation: " + rotation); + } + } + + static BlockFace getBlockFace(byte rotation) { + switch (rotation) { + case 0: + return BlockFace.NORTH; + case 1: + return BlockFace.NORTH_NORTH_EAST; + case 2: + return BlockFace.NORTH_EAST; + case 3: + return BlockFace.EAST_NORTH_EAST; + case 4: + return BlockFace.EAST; + case 5: + return BlockFace.EAST_SOUTH_EAST; + case 6: + return BlockFace.SOUTH_EAST; + case 7: + return BlockFace.SOUTH_SOUTH_EAST; + case 8: + return BlockFace.SOUTH; + case 9: + return BlockFace.SOUTH_SOUTH_WEST; + case 10: + return BlockFace.SOUTH_WEST; + case 11: + return BlockFace.WEST_SOUTH_WEST; + case 12: + return BlockFace.WEST; + case 13: + return BlockFace.WEST_NORTH_WEST; + case 14: + return BlockFace.NORTH_WEST; + case 15: + return BlockFace.NORTH_NORTH_WEST; + default: + throw new AssertionError(rotation); + } + } + + public boolean hasOwner() { + return profile != null; + } + + public String getOwner() { + return hasOwner() ? profile.getName() : null; + } + + public boolean setOwner(String name) { + if (name == null || name.length() > MAX_OWNER_LENGTH) { + return false; + } + + GameProfile profile = MinecraftServer.getServer().getUserCache().getProfile(name); + if (profile == null) { + return false; + } + + if (skullType != SkullType.PLAYER) { + skullType = SkullType.PLAYER; + } + + this.profile = profile; + return true; + } + + public BlockFace getRotation() { + return getBlockFace(rotation); + } + + public void setRotation(BlockFace rotation) { + this.rotation = getBlockFace(rotation); + } + + public SkullType getSkullType() { + return skullType; + } + + public void setSkullType(SkullType skullType) { + this.skullType = skullType; + + if (skullType != SkullType.PLAYER) { + profile = null; + } + } + + @Override + public boolean update(boolean force, boolean applyPhysics) { + boolean result = super.update(force, applyPhysics); + + if (result) { + if (skullType == SkullType.PLAYER) { + skull.setGameProfile(profile); + } else { + skull.setSkullType(getSkullType(skullType)); + } + + skull.setRotation(rotation); + skull.update(); + } + + return result; + } + + @Override + public TileEntitySkull getTileEntity() { + return skull; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/chunkio/ChunkIOExecutor.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/chunkio/ChunkIOExecutor.java new file mode 100644 index 0000000..ada28e5 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/chunkio/ChunkIOExecutor.java @@ -0,0 +1,35 @@ +package org.bukkit.craftbukkit.chunkio; + +import dev.azurite.spigot.configs.AzuriteConfig; +import net.minecraft.server.Chunk; +import net.minecraft.server.ChunkProviderServer; +import net.minecraft.server.ChunkRegionLoader; +import net.minecraft.server.World; +import org.bukkit.craftbukkit.util.AsynchronousExecutor; + +public class ChunkIOExecutor { + + private static final int BASE_THREADS = AzuriteConfig.chunkLoadingThreads.getValue(); // PaperSpigot - Bumped value + private static final AsynchronousExecutor instance = new AsynchronousExecutor<>(new ChunkIOProvider(), BASE_THREADS); + + public static Chunk syncChunkLoad(World world, ChunkRegionLoader loader, ChunkProviderServer provider, int x, int z) { + return instance.getSkipQueue(new QueuedChunk(x, z, loader, world, provider)); + } + + public static void queueChunkLoad(World world, ChunkRegionLoader loader, ChunkProviderServer provider, int x, int z, Runnable runnable) { + instance.add(new QueuedChunk(x, z, loader, world, provider), runnable); + } + + // Abuses the fact that hashCode and equals for QueuedChunk only use world and coords + public static void dropQueuedChunkLoad(World world, int x, int z, Runnable runnable) { + instance.drop(new QueuedChunk(x, z, null, world, null), runnable); + } + + public static void adjustPoolSize(int players) { + instance.setActiveThreads(Math.max(AzuriteConfig.chunkLoadingThreads.getValue(), (int) Math.ceil((double) players / AzuriteConfig.playersPerThread.getValue()))); + } + + public static void tick() { + instance.finishActive(); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/chunkio/ChunkIOProvider.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/chunkio/ChunkIOProvider.java new file mode 100644 index 0000000..6edc519 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/chunkio/ChunkIOProvider.java @@ -0,0 +1,83 @@ +package org.bukkit.craftbukkit.chunkio; + +import net.minecraft.server.Chunk; +import net.minecraft.server.ChunkProviderServer; +import net.minecraft.server.NBTTagCompound; +import org.bukkit.Server; +import org.bukkit.craftbukkit.util.AsynchronousExecutor; +import org.bukkit.craftbukkit.util.LongHash; +import org.jetbrains.annotations.NotNull; + +import java.io.IOException; +import java.util.concurrent.atomic.AtomicInteger; + +class ChunkIOProvider implements AsynchronousExecutor.CallBackProvider { + private final AtomicInteger threadNumber = new AtomicInteger(1); + + // async stuff + public Chunk callStage1(QueuedChunk queuedChunk) throws RuntimeException { + try { + Object[] data = queuedChunk.loader.loadChunk(queuedChunk.world, queuedChunk.x, queuedChunk.z); + + if (data != null) { + queuedChunk.compound = (NBTTagCompound) data[1]; + return (Chunk) data[0]; + } + + return null; + } catch (IOException ex) { + throw new RuntimeException(ex); + } + } + + // sync stuff + public void callStage2(QueuedChunk queuedChunk, Chunk chunk) throws RuntimeException { + ChunkProviderServer cps = queuedChunk.provider; + if (chunk == null) { + // If the chunk loading failed just do it synchronously (may generate) + cps.originalGetChunkAt(queuedChunk.x, queuedChunk.z); + return; + } + + queuedChunk.loader.loadEntities(chunk, queuedChunk.compound.getCompound("Level"), queuedChunk.world); + chunk.setLastSaved(cps.world.getTime()); + cps.chunks.put(LongHash.toLong(queuedChunk.x, queuedChunk.z), chunk); + chunk.addEntities(); + + if (cps.chunkProvider != null) { + cps.chunkProvider.recreateStructures(chunk, queuedChunk.x, queuedChunk.z); + } + + Server server = cps.world.getServer(); + if (server != null) { + server.getPluginManager().callEvent(new org.bukkit.event.world.ChunkLoadEvent(chunk.bukkitChunk, false)); + } + + // Update neighbor counts + for (int x = -2; x < 3; x++) { + for (int z = -2; z < 3; z++) { + if (x == 0 && z == 0) { + continue; + } + + Chunk neighbor = cps.getChunkIfLoaded(chunk.locX + x, chunk.locZ + z); + if (neighbor != null) { + neighbor.setNeighborLoaded(-x, -z); + chunk.setNeighborLoaded(x, z); + } + } + } + + chunk.loadNearby(cps, cps, queuedChunk.x, queuedChunk.z); + } + + public void callStage3(QueuedChunk queuedChunk, Chunk chunk, Runnable runnable) throws RuntimeException { + runnable.run(); + } + + public Thread newThread(@NotNull Runnable runnable) { + Thread thread = new Thread(runnable, "Chunk I/O Executor Thread-" + threadNumber.getAndIncrement()); + thread.setDaemon(true); + return thread; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/chunkio/QueuedChunk.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/chunkio/QueuedChunk.java new file mode 100644 index 0000000..842d424 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/chunkio/QueuedChunk.java @@ -0,0 +1,38 @@ +package org.bukkit.craftbukkit.chunkio; + +import net.minecraft.server.ChunkProviderServer; +import net.minecraft.server.ChunkRegionLoader; +import net.minecraft.server.NBTTagCompound; +import net.minecraft.server.World; + +class QueuedChunk { + final int x; + final int z; + final ChunkRegionLoader loader; + final World world; + final ChunkProviderServer provider; + NBTTagCompound compound; + + public QueuedChunk(int x, int z, ChunkRegionLoader loader, World world, ChunkProviderServer provider) { + this.x = x; + this.z = z; + this.loader = loader; + this.world = world; + this.provider = provider; + } + + @Override + public int hashCode() { + return (x * 31 + z * 29) ^ world.hashCode(); + } + + @Override + public boolean equals(Object object) { + if (object instanceof QueuedChunk) { + QueuedChunk other = (QueuedChunk) object; + return x == other.x && z == other.z && world == other.world; + } + + return false; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/command/ConsoleCommandCompleter.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/command/ConsoleCommandCompleter.java new file mode 100644 index 0000000..3f5c764 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/command/ConsoleCommandCompleter.java @@ -0,0 +1,51 @@ +package org.bukkit.craftbukkit.command; + +import net.minecraft.server.DedicatedServer; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.util.Waitable; +import org.jline.reader.Candidate; +import org.jline.reader.Completer; +import org.jline.reader.LineReader; +import org.jline.reader.ParsedLine; + +import java.util.List; +import java.util.concurrent.ExecutionException; +import java.util.logging.Level; + +public class ConsoleCommandCompleter implements Completer { + private final DedicatedServer server; + + public ConsoleCommandCompleter(DedicatedServer server) { + this.server = server; + } + + public void complete(LineReader reader, ParsedLine line, List candidates) { + final CraftServer server = this.server.server; + final String buffer = line.line(); + Waitable> waitable = new Waitable>() { + @Override + protected List evaluate() { + return server.getCommandMap().tabComplete(server.getConsoleSender(), buffer); + } + }; + server.getServer().processQueue.add(waitable); + try { + List offers = waitable.get(); + if (offers == null) { + return; + } + + for (String completion : offers) { + if (completion.isEmpty()) { + continue; + } + candidates.add(new Candidate(completion)); + } + + } catch (ExecutionException e) { + server.getLogger().log(Level.WARNING, "Unhandled exception when tab completing", e); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/command/CraftBlockCommandSender.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/command/CraftBlockCommandSender.java new file mode 100644 index 0000000..37f217d --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/command/CraftBlockCommandSender.java @@ -0,0 +1,58 @@ +package org.bukkit.craftbukkit.command; + +import net.minecraft.server.CommandBlockListenerAbstract; +import net.minecraft.server.IChatBaseComponent; +import net.minecraft.server.ICommandListener; +import org.bukkit.block.Block; +import org.bukkit.command.BlockCommandSender; +import org.bukkit.craftbukkit.util.CraftChatMessage; + +import java.text.MessageFormat; + +/** + * Represents input from a command block + */ +public class CraftBlockCommandSender extends ServerCommandSender implements BlockCommandSender { + private final CommandBlockListenerAbstract commandBlock; + + public CraftBlockCommandSender(CommandBlockListenerAbstract commandBlockListenerAbstract) { + super(); + this.commandBlock = commandBlockListenerAbstract; + } + + public Block getBlock() { + return commandBlock.getWorld().getWorld().getBlockAt(commandBlock.getChunkCoordinates().getX(), commandBlock.getChunkCoordinates().getY(), commandBlock.getChunkCoordinates().getZ()); + } + + public void sendMessage(String message) { + for (IChatBaseComponent component : CraftChatMessage.fromString(message)) { + commandBlock.sendMessage(component); + } + } + + public void sendMessage(String[] messages) { + for (String message : messages) { + sendMessage(message); + } + } + + public void sendFormattedMessage(final String message, final Object... args) { + this.sendMessage(MessageFormat.format(message, args)); + } + + public String getName() { + return commandBlock.getName(); + } + + public boolean isOp() { + return true; + } + + public void setOp(boolean value) { + throw new UnsupportedOperationException("Cannot change operator status of a block"); + } + + public ICommandListener getTileEntity() { + return commandBlock; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/command/CraftConsoleCommandSender.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/command/CraftConsoleCommandSender.java new file mode 100644 index 0000000..ca7d7e6 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/command/CraftConsoleCommandSender.java @@ -0,0 +1,72 @@ +package org.bukkit.craftbukkit.command; + +import org.bukkit.ChatColor; +import org.bukkit.command.ConsoleCommandSender; +import org.bukkit.conversations.Conversation; +import org.bukkit.conversations.ConversationAbandonedEvent; +import org.bukkit.conversations.ManuallyAbandonedConversationCanceller; +import org.bukkit.craftbukkit.conversations.ConversationTracker; + +import java.text.MessageFormat; + +/** + * Represents CLI input from a console + */ +public class CraftConsoleCommandSender extends ServerCommandSender implements ConsoleCommandSender { + + protected final ConversationTracker conversationTracker = new ConversationTracker(); + + protected CraftConsoleCommandSender() { + super(); + } + + public void sendMessage(String message) { + sendRawMessage(message); + } + + public void sendRawMessage(String message) { + System.out.println(ChatColor.stripColor(message)); + } + + public void sendMessage(String[] messages) { + for (String message : messages) { + sendMessage(message); + } + } + + public void sendFormattedMessage(final String message, final Object... args) { + this.sendMessage(MessageFormat.format(message, args)); + } + + public String getName() { + return "CONSOLE"; + } + + public boolean isOp() { + return true; + } + + public void setOp(boolean value) { + throw new UnsupportedOperationException("Cannot change operator status of server console"); + } + + public boolean beginConversation(Conversation conversation) { + return conversationTracker.beginConversation(conversation); + } + + public void abandonConversation(Conversation conversation) { + conversationTracker.abandonConversation(conversation, new ConversationAbandonedEvent(conversation, new ManuallyAbandonedConversationCanceller())); + } + + public void abandonConversation(Conversation conversation, ConversationAbandonedEvent details) { + conversationTracker.abandonConversation(conversation, details); + } + + public void acceptConversationInput(String input) { + conversationTracker.acceptConversationInput(input); + } + + public boolean isConversing() { + return conversationTracker.isConversing(); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/command/CraftRemoteConsoleCommandSender.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/command/CraftRemoteConsoleCommandSender.java new file mode 100644 index 0000000..b16d3e6 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/command/CraftRemoteConsoleCommandSender.java @@ -0,0 +1,44 @@ +package org.bukkit.craftbukkit.command; + +import net.minecraft.server.ChatComponentText; +import net.minecraft.server.RemoteControlCommandListener; +import org.bukkit.command.RemoteConsoleCommandSender; + +import java.text.MessageFormat; + +public class CraftRemoteConsoleCommandSender extends ServerCommandSender implements RemoteConsoleCommandSender { + public CraftRemoteConsoleCommandSender() { + super(); + } + + @Override + public void sendMessage(String message) { + RemoteControlCommandListener.getInstance().sendMessage(new ChatComponentText(message + "\n")); // Send a newline after each message, to preserve formatting. + } + + @Override + public void sendMessage(String[] messages) { + for (String message : messages) { + sendMessage(message); + } + } + + public void sendFormattedMessage(final String message, final Object... args) { + this.sendMessage(MessageFormat.format(message, args)); + } + + @Override + public String getName() { + return "Rcon"; + } + + @Override + public boolean isOp() { + return true; + } + + @Override + public void setOp(boolean value) { + throw new UnsupportedOperationException("Cannot change operator status of remote controller."); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/command/ProxiedNativeCommandSender.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/command/ProxiedNativeCommandSender.java new file mode 100644 index 0000000..e65a980 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/command/ProxiedNativeCommandSender.java @@ -0,0 +1,130 @@ +package org.bukkit.craftbukkit.command; + +import net.minecraft.server.ICommandListener; +import org.bukkit.Server; +import org.bukkit.command.CommandSender; +import org.bukkit.command.ProxiedCommandSender; +import org.bukkit.permissions.Permission; +import org.bukkit.permissions.PermissionAttachment; +import org.bukkit.permissions.PermissionAttachmentInfo; +import org.bukkit.plugin.Plugin; + +import java.text.MessageFormat; +import java.util.Set; + +public class ProxiedNativeCommandSender implements ProxiedCommandSender { + + private final ICommandListener orig; + private final CommandSender caller; + private final CommandSender callee; + + public ProxiedNativeCommandSender(ICommandListener orig, CommandSender caller, CommandSender callee) { + this.orig = orig; + this.caller = caller; + this.callee = callee; + } + + public ICommandListener getHandle() { + return orig; + } + + @Override + public CommandSender getCaller() { + return caller; + } + + @Override + public CommandSender getCallee() { + return callee; + } + + @Override + public void sendMessage(String message) { + getCaller().sendMessage(message); + } + + @Override + public void sendMessage(String[] messages) { + getCaller().sendMessage(messages); + } + + public void sendFormattedMessage(final String message, final Object... args) { + this.sendMessage(MessageFormat.format(message, args)); + } + + @Override + public Server getServer() { + return getCallee().getServer(); + } + + @Override + public String getName() { + return getCallee().getName(); + } + + @Override + public boolean isPermissionSet(String name) { + return getCaller().isPermissionSet(name); + } + + @Override + public boolean isPermissionSet(Permission perm) { + return getCaller().isPermissionSet(perm); + } + + @Override + public boolean hasPermission(String name) { + return getCaller().hasPermission(name); + } + + @Override + public boolean hasPermission(Permission perm) { + return getCaller().hasPermission(perm); + } + + @Override + public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value) { + return getCaller().addAttachment(plugin, name, value); + } + + @Override + public PermissionAttachment addAttachment(Plugin plugin) { + return getCaller().addAttachment(plugin); + } + + @Override + public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value, int ticks) { + return getCaller().addAttachment(plugin, name, value, ticks); + } + + @Override + public PermissionAttachment addAttachment(Plugin plugin, int ticks) { + return getCaller().addAttachment(plugin, ticks); + } + + @Override + public void removeAttachment(PermissionAttachment attachment) { + getCaller().removeAttachment(attachment); + } + + @Override + public void recalculatePermissions() { + getCaller().recalculatePermissions(); + } + + @Override + public Set getEffectivePermissions() { + return getCaller().getEffectivePermissions(); + } + + @Override + public boolean isOp() { + return getCaller().isOp(); + } + + @Override + public void setOp(boolean value) { + getCaller().setOp(value); + } + +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/command/ServerCommandSender.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/command/ServerCommandSender.java new file mode 100644 index 0000000..b339cf3 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/command/ServerCommandSender.java @@ -0,0 +1,80 @@ +package org.bukkit.craftbukkit.command; + +import org.bukkit.Bukkit; +import org.bukkit.Server; +import org.bukkit.command.CommandSender; +import org.bukkit.permissions.PermissibleBase; +import org.bukkit.permissions.Permission; +import org.bukkit.permissions.PermissionAttachment; +import org.bukkit.permissions.PermissionAttachmentInfo; +import org.bukkit.plugin.Plugin; + +import java.util.Set; + +public abstract class ServerCommandSender implements CommandSender { + private static PermissibleBase blockPermInst; + private final PermissibleBase perm; + + public ServerCommandSender() { + if (this instanceof CraftBlockCommandSender) { + if (blockPermInst == null) { + blockPermInst = new PermissibleBase(this); + } + this.perm = blockPermInst; + } else { + this.perm = new PermissibleBase(this); + } + } + + public boolean isPermissionSet(String name) { + return perm.isPermissionSet(name); + } + + public boolean isPermissionSet(Permission perm) { + return this.perm.isPermissionSet(perm); + } + + public boolean hasPermission(String name) { + return perm.hasPermission(name); + } + + public boolean hasPermission(Permission perm) { + return this.perm.hasPermission(perm); + } + + public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value) { + return perm.addAttachment(plugin, name, value); + } + + public PermissionAttachment addAttachment(Plugin plugin) { + return perm.addAttachment(plugin); + } + + public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value, int ticks) { + return perm.addAttachment(plugin, name, value, ticks); + } + + public PermissionAttachment addAttachment(Plugin plugin, int ticks) { + return perm.addAttachment(plugin, ticks); + } + + public void removeAttachment(PermissionAttachment attachment) { + perm.removeAttachment(attachment); + } + + public void recalculatePermissions() { + perm.recalculatePermissions(); + } + + public Set getEffectivePermissions() { + return perm.getEffectivePermissions(); + } + + public boolean isPlayer() { + return false; + } + + public Server getServer() { + return Bukkit.getServer(); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/command/VanillaCommandWrapper.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/command/VanillaCommandWrapper.java new file mode 100644 index 0000000..e25ae48 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/command/VanillaCommandWrapper.java @@ -0,0 +1,193 @@ +package org.bukkit.craftbukkit.command; + +import net.minecraft.server.CommandException; +import net.minecraft.server.*; +import org.apache.commons.lang.Validate; +import org.apache.logging.log4j.Level; +import org.bukkit.Location; +import org.bukkit.command.*; +import org.bukkit.command.defaults.VanillaCommand; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.entity.CraftMinecartCommand; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.entity.Player; +import org.bukkit.entity.minecart.CommandMinecart; + +import java.util.List; + +public final class VanillaCommandWrapper extends VanillaCommand { + protected final CommandAbstract vanillaCommand; + + public VanillaCommandWrapper(CommandAbstract vanillaCommand) { + super(vanillaCommand.getCommand()); + this.vanillaCommand = vanillaCommand; + } + + public VanillaCommandWrapper(CommandAbstract vanillaCommand, String usage) { + super(vanillaCommand.getCommand(), "A Mojang provided command.", usage, vanillaCommand.b()); // PandaSpigot + this.vanillaCommand = vanillaCommand; + this.setPermission("minecraft.command." + vanillaCommand.getCommand()); + } + + @Override + public boolean execute(CommandSender sender, String commandLabel, String[] args) { + if (!testPermission(sender)) return true; + + ICommandListener icommandlistener = getListener(sender); + dispatchVanillaCommand(sender, icommandlistener, args); + return true; + } + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { + return tabComplete(sender, alias, args, null); // PaperSpigot - location tab-completes. Original code moved below + } + + // PaperSpigot start - location tab-completes + /* + this code is copied, except for the noted change, from the original tabComplete(CommandSender sender, String alias, String[] args) method + */ + @Override + public List tabComplete(CommandSender sender, String alias, String[] args, Location location) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + if (location == null) { // PaperSpigot use location information if available + // Beanes - use player location if no block target is set + BlockPosition blockPos; + if (sender instanceof Player) { + Player player = (Player) sender; + blockPos = new BlockPosition(player.getLocation().getBlockX(), player.getLocation().getBlockY(), player.getLocation().getBlockZ()); + } else { + blockPos = new BlockPosition(0, 0, 0); + } + return vanillaCommand.tabComplete(getListener(sender), args, blockPos); + } else { + return vanillaCommand.tabComplete(getListener(sender), args, new BlockPosition(location.getBlockX(), location.getBlockY(), location.getBlockZ())); + } + } + // PaperSpigot end + + public static CommandSender lastSender = null; // Nasty :( + + public int dispatchVanillaCommand(CommandSender bSender, ICommandListener icommandlistener, String[] as) { + // Copied from net.minecraft.server.CommandHandler + int i = getPlayerListSize(as); + int j = 0; + // Some commands use the worldserver variable but we leave it full of null values, + // so we must temporarily populate it with the world of the commandsender + WorldServer[] prev = MinecraftServer.getServer().worldServer; + MinecraftServer server = MinecraftServer.getServer(); + server.worldServer = new WorldServer[server.worlds.size()]; + server.worldServer[0] = (WorldServer) icommandlistener.getWorld(); + int bpos = 0; + for (int pos = 1; pos < server.worldServer.length; pos++) { + WorldServer world = server.worlds.get(bpos++); + if (server.worldServer[0] == world) { + pos--; + continue; + } + server.worldServer[pos] = world; + } + + try { + if (vanillaCommand.canUse(icommandlistener)) { + if (i > -1) { + List list = PlayerSelector.getPlayers(icommandlistener, as[i], Entity.class); + String s2 = as[i]; + + icommandlistener.a(CommandObjectiveExecutor.EnumCommandResult.AFFECTED_ENTITIES, list.size()); + + for (Entity entity : list) { + CommandSender oldSender = lastSender; + lastSender = bSender; + try { + as[i] = entity.getUniqueID().toString(); + vanillaCommand.execute(icommandlistener, as); + j++; + } catch (ExceptionUsage exceptionusage) { + ChatMessage chatmessage = new ChatMessage("commands.generic.usage", new ChatMessage(exceptionusage.getMessage(), exceptionusage.getArgs())); + chatmessage.getChatModifier().setColor(EnumChatFormat.RED); + icommandlistener.sendMessage(chatmessage); + } catch (CommandException commandexception) { + // Beanes - change 3rd argument to 0 (from 1) to fix exceptions not being sent to players + CommandAbstract.a(icommandlistener, vanillaCommand, 0, commandexception.getMessage(), commandexception.getArgs()); + } finally { + lastSender = oldSender; + } + } + as[i] = s2; + } else { + icommandlistener.a(CommandObjectiveExecutor.EnumCommandResult.AFFECTED_ENTITIES, 1); + vanillaCommand.execute(icommandlistener, as); + j++; + } + } else { + ChatMessage chatmessage = new ChatMessage("commands.generic.permission"); + chatmessage.getChatModifier().setColor(EnumChatFormat.RED); + icommandlistener.sendMessage(chatmessage); + } + } catch (ExceptionUsage exceptionusage) { + ChatMessage chatmessage1 = new ChatMessage("commands.generic.usage", new ChatMessage(exceptionusage.getMessage(), exceptionusage.getArgs())); + chatmessage1.getChatModifier().setColor(EnumChatFormat.RED); + icommandlistener.sendMessage(chatmessage1); + } catch (CommandException commandexception) { + // Beanes - change 3rd argument to 0 (from 1) to fix exceptions not being sent to players + CommandAbstract.a(icommandlistener, vanillaCommand, 0, commandexception.getMessage(), commandexception.getArgs()); + } catch (Throwable throwable) { + ChatMessage chatmessage3 = new ChatMessage("commands.generic.exception"); + chatmessage3.getChatModifier().setColor(EnumChatFormat.RED); + icommandlistener.sendMessage(chatmessage3); + if (icommandlistener.f() instanceof EntityMinecartCommandBlock) { + MinecraftServer.LOGGER.log(Level.WARN, String.format("MinecartCommandBlock at (%d,%d,%d) failed to handle command", icommandlistener.getChunkCoordinates().getX(), icommandlistener.getChunkCoordinates().getY(), icommandlistener.getChunkCoordinates().getZ()), throwable); + } else if(icommandlistener instanceof CommandBlockListenerAbstract) { + CommandBlockListenerAbstract listener = (CommandBlockListenerAbstract) icommandlistener; + MinecraftServer.LOGGER.log(Level.WARN, String.format("CommandBlock at (%d,%d,%d) failed to handle command", listener.getChunkCoordinates().getX(), listener.getChunkCoordinates().getY(), listener.getChunkCoordinates().getZ()), throwable); + } else { + MinecraftServer.LOGGER.log(Level.WARN, "Unknown CommandBlock failed to handle command", throwable); + } + } finally { + icommandlistener.a(CommandObjectiveExecutor.EnumCommandResult.SUCCESS_COUNT, j); // PandaSpigot - Fix selectors in SuccessCount + MinecraftServer.getServer().worldServer = prev; + } + return j; + } + + private ICommandListener getListener(CommandSender sender) { + if (sender instanceof Player) { + return ((CraftPlayer) sender).getHandle(); + } + if (sender instanceof BlockCommandSender) { + return ((CraftBlockCommandSender) sender).getTileEntity(); + } + if (sender instanceof CommandMinecart) { + return ((EntityMinecartCommandBlock) ((CraftMinecartCommand) sender).getHandle()).getCommandBlock(); + } + if (sender instanceof RemoteConsoleCommandSender) { + return RemoteControlCommandListener.getInstance(); + } + if (sender instanceof ConsoleCommandSender) { + return ((CraftServer) sender.getServer()).getServer(); + } + if (sender instanceof ProxiedCommandSender) { + return ((ProxiedNativeCommandSender) sender).getHandle(); + } + throw new IllegalArgumentException("Cannot make " + sender + " a vanilla command listener"); + } + + private int getPlayerListSize(String[] as) { + for (int i = 0; i < as.length; i++) { + if (vanillaCommand.isListStart(as, i) && PlayerSelector.isList(as[i])) { + return i; + } + } + return -1; + } + + public static String[] dropFirstArgument(String[] as) { + String[] as1 = new String[as.length - 1]; + System.arraycopy(as, 1, as1, 0, as.length - 1); + + return as1; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/conversations/ConversationTracker.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/conversations/ConversationTracker.java new file mode 100644 index 0000000..eda3c10 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/conversations/ConversationTracker.java @@ -0,0 +1,67 @@ +package org.bukkit.craftbukkit.conversations; + +import org.bukkit.Bukkit; +import org.bukkit.conversations.Conversation; +import org.bukkit.conversations.ConversationAbandonedEvent; +import org.bukkit.conversations.ManuallyAbandonedConversationCanceller; + +import java.util.LinkedList; +import java.util.logging.Level; + +/** + */ +public class ConversationTracker { + + private LinkedList conversationQueue = new LinkedList<>(); + + public synchronized boolean beginConversation(Conversation conversation) { + if (!conversationQueue.contains(conversation)) { + conversationQueue.addLast(conversation); + if (conversationQueue.getFirst() == conversation) { + conversation.begin(); + conversation.outputNextPrompt(); + return true; + } + } + return true; + } + + public synchronized void abandonConversation(Conversation conversation, ConversationAbandonedEvent details) { + if (!conversationQueue.isEmpty()) { + if (conversationQueue.getFirst() == conversation) { + conversation.abandon(details); + } + conversationQueue.remove(conversation); + if (!conversationQueue.isEmpty()) { + conversationQueue.getFirst().outputNextPrompt(); + } + } + } + + public synchronized void abandonAllConversations() { + + LinkedList oldQueue = conversationQueue; + conversationQueue = new LinkedList<>(); + for (Conversation conversation : oldQueue) { + try { + conversation.abandon(new ConversationAbandonedEvent(conversation, new ManuallyAbandonedConversationCanceller())); + } catch (Throwable t) { + Bukkit.getLogger().log(Level.SEVERE, "Unexpected exception while abandoning a conversation", t); + } + } + } + + public synchronized void acceptConversationInput(String input) { + if (isConversing()) { + conversationQueue.getFirst().acceptInput(input); + } + } + + public synchronized boolean isConversing() { + return !conversationQueue.isEmpty(); + } + + public synchronized boolean isConversingModaly() { + return isConversing() && conversationQueue.getFirst().isModal(); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/enchantments/CraftEnchantment.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/enchantments/CraftEnchantment.java new file mode 100644 index 0000000..8a55949 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/enchantments/CraftEnchantment.java @@ -0,0 +1,141 @@ +package org.bukkit.craftbukkit.enchantments; + +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.enchantments.EnchantmentTarget; +import org.bukkit.enchantments.EnchantmentWrapper; +import org.bukkit.inventory.ItemStack; + +public class CraftEnchantment extends Enchantment { + private final net.minecraft.server.Enchantment target; + + public CraftEnchantment(net.minecraft.server.Enchantment target) { + super(target.id); + this.target = target; + } + + @Override + public int getMaxLevel() { + return target.getMaxLevel(); + } + + @Override + public int getStartLevel() { + return target.getStartLevel(); + } + + @Override + public EnchantmentTarget getItemTarget() { + switch (target.slot) { + case ALL: + return EnchantmentTarget.ALL; + case ARMOR: + return EnchantmentTarget.ARMOR; + case ARMOR_FEET: + return EnchantmentTarget.ARMOR_FEET; + case ARMOR_HEAD: + return EnchantmentTarget.ARMOR_HEAD; + case ARMOR_LEGS: + return EnchantmentTarget.ARMOR_LEGS; + case ARMOR_TORSO: + return EnchantmentTarget.ARMOR_TORSO; + case DIGGER: + return EnchantmentTarget.TOOL; + case WEAPON: + return EnchantmentTarget.WEAPON; + case BOW: + return EnchantmentTarget.BOW; + case FISHING_ROD: + return EnchantmentTarget.FISHING_ROD; + default: + return null; + } + } + + @Override + public boolean canEnchantItem(ItemStack item) { + return target.canEnchant(CraftItemStack.asNMSCopy(item)); + } + + @Override + public String getName() { + switch (target.id) { + case 0: + return "PROTECTION_ENVIRONMENTAL"; + case 1: + return "PROTECTION_FIRE"; + case 2: + return "PROTECTION_FALL"; + case 3: + return "PROTECTION_EXPLOSIONS"; + case 4: + return "PROTECTION_PROJECTILE"; + case 5: + return "OXYGEN"; + case 6: + return "WATER_WORKER"; + case 7: + return "THORNS"; + case 8: + return "DEPTH_STRIDER"; + case 16: + return "DAMAGE_ALL"; + case 17: + return "DAMAGE_UNDEAD"; + case 18: + return "DAMAGE_ARTHROPODS"; + case 19: + return "KNOCKBACK"; + case 20: + return "FIRE_ASPECT"; + case 21: + return "LOOT_BONUS_MOBS"; + case 32: + return "DIG_SPEED"; + case 33: + return "SILK_TOUCH"; + case 34: + return "DURABILITY"; + case 35: + return "LOOT_BONUS_BLOCKS"; + case 48: + return "ARROW_DAMAGE"; + case 49: + return "ARROW_KNOCKBACK"; + case 50: + return "ARROW_FIRE"; + case 51: + return "ARROW_INFINITE"; + case 61: + return "LUCK"; + case 62: + return "LURE"; + default: + return "UNKNOWN_ENCHANT_" + target.id; + } + } + + public static net.minecraft.server.Enchantment getRaw(Enchantment enchantment) { + if (enchantment instanceof EnchantmentWrapper) { + enchantment = ((EnchantmentWrapper) enchantment).getEnchantment(); + } + + if (enchantment instanceof CraftEnchantment) { + return ((CraftEnchantment) enchantment).target; + } + + return null; + } + + @Override + public boolean conflictsWith(Enchantment other) { + if (other instanceof EnchantmentWrapper) { + other = ((EnchantmentWrapper) other).getEnchantment(); + } + if (!(other instanceof CraftEnchantment)) { + return false; + } + CraftEnchantment ench = (CraftEnchantment) other; + return !target.a(ench.target); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/AbstractProjectile.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/AbstractProjectile.java new file mode 100644 index 0000000..7c16255 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/AbstractProjectile.java @@ -0,0 +1,23 @@ +package org.bukkit.craftbukkit.entity; + +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.Projectile; + +public abstract class AbstractProjectile extends CraftEntity implements Projectile { + + private boolean doesBounce; + + public AbstractProjectile(CraftServer server, net.minecraft.server.Entity entity) { + super(server, entity); + doesBounce = false; + } + + public boolean doesBounce() { + return doesBounce; + } + + public void setBounce(boolean doesBounce) { + this.doesBounce = doesBounce; + } + +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftAgeable.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftAgeable.java new file mode 100644 index 0000000..2e27071 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftAgeable.java @@ -0,0 +1,66 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityAgeable; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.Ageable; + +public class CraftAgeable extends CraftCreature implements Ageable { + public CraftAgeable(CraftServer server, EntityAgeable entity) { + super(server, entity); + } + + public int getAge() { + return getHandle().getAge(); + } + + public void setAge(int age) { + getHandle().setAgeRaw(age); + } + + public void setAgeLock(boolean lock) { + getHandle().ageLocked = lock; + } + + public boolean getAgeLock() { + return getHandle().ageLocked; + } + + public void setBaby() { + if (isAdult()) { + setAge(-24000); + } + } + + public void setAdult() { + if (!isAdult()) { + setAge(0); + } + } + + public boolean isAdult() { + return getAge() >= 0; + } + + + public boolean canBreed() { + return getAge() == 0; + } + + public void setBreed(boolean breed) { + if (breed) { + setAge(0); + } else if (isAdult()) { + setAge(6000); + } + } + + @Override + public EntityAgeable getHandle() { + return (EntityAgeable) entity; + } + + @Override + public String toString() { + return "CraftAgeable"; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftAmbient.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftAmbient.java new file mode 100644 index 0000000..086980e --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftAmbient.java @@ -0,0 +1,26 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityAmbient; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.Ambient; +import org.bukkit.entity.EntityType; + +public class CraftAmbient extends CraftLivingEntity implements Ambient { + public CraftAmbient(CraftServer server, EntityAmbient entity) { + super(server, entity); + } + + @Override + public EntityAmbient getHandle() { + return (EntityAmbient) entity; + } + + @Override + public String toString() { + return "CraftAmbient"; + } + + public EntityType getType() { + return EntityType.UNKNOWN; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftAnimals.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftAnimals.java new file mode 100644 index 0000000..4b9b078 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftAnimals.java @@ -0,0 +1,22 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityAnimal; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.Animals; + +public class CraftAnimals extends CraftAgeable implements Animals { + + public CraftAnimals(CraftServer server, EntityAnimal entity) { + super(server, entity); + } + + @Override + public EntityAnimal getHandle() { + return (EntityAnimal) entity; + } + + @Override + public String toString() { + return "CraftAnimals"; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftArmorStand.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftArmorStand.java new file mode 100644 index 0000000..09443fe --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftArmorStand.java @@ -0,0 +1,219 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityArmorStand; +import net.minecraft.server.Vector3f; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.ArmorStand; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.EulerAngle; + +public class CraftArmorStand extends CraftLivingEntity implements ArmorStand { + + public CraftArmorStand(CraftServer server, EntityArmorStand entity) { + super(server, entity); + } + + @Override + public String toString() { + return "CraftArmorStand"; + } + + @Override + public EntityType getType() { + return EntityType.ARMOR_STAND; + } + + @Override + public EntityArmorStand getHandle() { + return (EntityArmorStand) super.getHandle(); + } + + @Override + public ItemStack getItemInHand() { + return getEquipment().getItemInHand(); + } + + @Override + public void setItemInHand(ItemStack item) { + getEquipment().setItemInHand(item); + } + + @Override + public ItemStack getBoots() { + return getEquipment().getBoots(); + } + + @Override + public void setBoots(ItemStack item) { + getEquipment().setBoots(item); + } + + @Override + public ItemStack getLeggings() { + return getEquipment().getLeggings(); + } + + @Override + public void setLeggings(ItemStack item) { + getEquipment().setLeggings(item); + } + + @Override + public ItemStack getChestplate() { + return getEquipment().getChestplate(); + } + + @Override + public void setChestplate(ItemStack item) { + getEquipment().setChestplate(item); + } + + @Override + public ItemStack getHelmet() { + return getEquipment().getHelmet(); + } + + @Override + public void setHelmet(ItemStack item) { + getEquipment().setHelmet(item); + } + + @Override + public EulerAngle getBodyPose() { + return fromNMS(getHandle().bodyPose); + } + + @Override + public void setBodyPose(EulerAngle pose) { + getHandle().setBodyPose(toNMS(pose)); + } + + @Override + public EulerAngle getLeftArmPose() { + return fromNMS(getHandle().leftArmPose); + } + + @Override + public void setLeftArmPose(EulerAngle pose) { + getHandle().setLeftArmPose(toNMS(pose)); + } + + @Override + public EulerAngle getRightArmPose() { + return fromNMS(getHandle().rightArmPose); + } + + @Override + public void setRightArmPose(EulerAngle pose) { + getHandle().setRightArmPose(toNMS(pose)); + } + + @Override + public EulerAngle getLeftLegPose() { + return fromNMS(getHandle().leftLegPose); + } + + @Override + public void setLeftLegPose(EulerAngle pose) { + getHandle().setLeftLegPose(toNMS(pose)); + } + + @Override + public EulerAngle getRightLegPose() { + return fromNMS(getHandle().rightLegPose); + } + + @Override + public void setRightLegPose(EulerAngle pose) { + getHandle().setRightLegPose(toNMS(pose)); + } + + @Override + public EulerAngle getHeadPose() { + return fromNMS(getHandle().headPose); + } + + @Override + public void setHeadPose(EulerAngle pose) { + getHandle().setHeadPose(toNMS(pose)); + } + + @Override + public boolean hasBasePlate() { + return !getHandle().hasBasePlate(); + } + + @Override + public void setBasePlate(boolean basePlate) { + getHandle().setBasePlate(!basePlate); + } + + @Override + public boolean hasGravity() { + return !getHandle().hasGravity(); + } + + @Override + public void setGravity(boolean gravity) { + getHandle().setGravity(!gravity); + } + + @Override + public boolean isVisible() { + return !getHandle().isInvisible(); + } + + @Override + public void setVisible(boolean visible) { + getHandle().setInvisible(!visible); + } + + @Override + public boolean hasArms() { + return getHandle().hasArms(); + } + + @Override + public void setArms(boolean arms) { + getHandle().setArms(arms); + } + + @Override + public boolean isSmall() { + return getHandle().isSmall(); + } + + @Override + public void setSmall(boolean small) { + getHandle().setSmall(small); + } + + private static EulerAngle fromNMS(Vector3f old) { + return new EulerAngle( + Math.toRadians(old.getX()), + Math.toRadians(old.getY()), + Math.toRadians(old.getZ()) + ); + } + + private static Vector3f toNMS(EulerAngle old) { + return new Vector3f( + (float) Math.toDegrees(old.getX()), + (float) Math.toDegrees(old.getY()), + (float) Math.toDegrees(old.getZ()) + ); + } + + @Override + public boolean isMarker() { + // PAIL + return getHandle().s(); + } + + @Override + public void setMarker(boolean marker) { + // PAIL + getHandle().n(marker); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftArrow.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftArrow.java new file mode 100644 index 0000000..b5cd0a3 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftArrow.java @@ -0,0 +1,95 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityArrow; +import org.apache.commons.lang.Validate; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.Arrow; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.projectiles.ProjectileSource; + +public class CraftArrow extends AbstractProjectile implements Arrow { + + public CraftArrow(CraftServer server, EntityArrow entity) { + super(server, entity); + } + + public void setKnockbackStrength(int knockbackStrength) { + Validate.isTrue(knockbackStrength >= 0, "Knockback cannot be negative"); + getHandle().setKnockbackStrength(knockbackStrength); + } + + public int getKnockbackStrength() { + return getHandle().knockbackStrength; + } + + public boolean isCritical() { + return getHandle().isCritical(); + } + + public void setCritical(boolean critical) { + getHandle().setCritical(critical); + } + + public ProjectileSource getShooter() { + return getHandle().projectileSource; + } + + public void setShooter(ProjectileSource shooter) { + if (shooter instanceof LivingEntity) { + getHandle().shooter = ((CraftLivingEntity) shooter).getHandle(); + } else { + getHandle().shooter = null; + } + getHandle().projectileSource = shooter; + } + + @Override + public EntityArrow getHandle() { + return (EntityArrow) entity; + } + + @Override + public String toString() { + return "CraftArrow"; + } + + public EntityType getType() { + return EntityType.ARROW; + } + + @Deprecated + public LivingEntity _INVALID_getShooter() { + if (getHandle().shooter == null) { + return null; + } + return (LivingEntity) getHandle().shooter.getBukkitEntity(); + } + + @Deprecated + public void _INVALID_setShooter(LivingEntity shooter) { + getHandle().shooter = ((CraftLivingEntity) shooter).getHandle(); + } + + // Spigot start + private final Arrow.Spigot spigot = new Arrow.Spigot() + { + @Override + public double getDamage() + { + return getHandle().j(); + } + + @Override + public void setDamage(double damage) + { + getHandle().b( damage ); + } + }; + + public Arrow.Spigot spigot() + { + return spigot; + } + // Spigot end +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftBat.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftBat.java new file mode 100644 index 0000000..76ada1c --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftBat.java @@ -0,0 +1,36 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityBat; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.Bat; +import org.bukkit.entity.EntityType; + +public class CraftBat extends CraftAmbient implements Bat { + public CraftBat(CraftServer server, EntityBat entity) { + super(server, entity); + } + + @Override + public EntityBat getHandle() { + return (EntityBat) entity; + } + + @Override + public String toString() { + return "CraftBat"; + } + + public EntityType getType() { + return EntityType.BAT; + } + + @Override + public boolean isAwake() { + return !getHandle().isAsleep(); + } + + @Override + public void setAwake(boolean state) { + getHandle().setAsleep(!state); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftBlaze.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftBlaze.java new file mode 100644 index 0000000..b1efeb7 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftBlaze.java @@ -0,0 +1,26 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityBlaze; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.Blaze; +import org.bukkit.entity.EntityType; + +public class CraftBlaze extends CraftMonster implements Blaze { + public CraftBlaze(CraftServer server, EntityBlaze entity) { + super(server, entity); + } + + @Override + public EntityBlaze getHandle() { + return (EntityBlaze) entity; + } + + @Override + public String toString() { + return "CraftBlaze"; + } + + public EntityType getType() { + return EntityType.BLAZE; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftBoat.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftBoat.java new file mode 100644 index 0000000..103b9d4 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftBoat.java @@ -0,0 +1,63 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityBoat; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.Boat; +import org.bukkit.entity.EntityType; + +public class CraftBoat extends CraftVehicle implements Boat { + + public CraftBoat(CraftServer server, EntityBoat entity) { + super(server, entity); + } + + public double getMaxSpeed() { + return getHandle().maxSpeed; + } + + public void setMaxSpeed(double speed) { + if (speed >= 0D) { + getHandle().maxSpeed = speed; + } + } + + public double getOccupiedDeceleration() { + return getHandle().occupiedDeceleration; + } + + public void setOccupiedDeceleration(double speed) { + if (speed >= 0D) { + getHandle().occupiedDeceleration = speed; + } + } + + public double getUnoccupiedDeceleration() { + return getHandle().unoccupiedDeceleration; + } + + public void setUnoccupiedDeceleration(double speed) { + getHandle().unoccupiedDeceleration = speed; + } + + public boolean getWorkOnLand() { + return getHandle().landBoats; + } + + public void setWorkOnLand(boolean workOnLand) { + getHandle().landBoats = workOnLand; + } + + @Override + public EntityBoat getHandle() { + return (EntityBoat) entity; + } + + @Override + public String toString() { + return "CraftBoat"; + } + + public EntityType getType() { + return EntityType.BOAT; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftCaveSpider.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftCaveSpider.java new file mode 100644 index 0000000..a1fe8dd --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftCaveSpider.java @@ -0,0 +1,26 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityCaveSpider; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.CaveSpider; +import org.bukkit.entity.EntityType; + +public class CraftCaveSpider extends CraftSpider implements CaveSpider { + public CraftCaveSpider(CraftServer server, EntityCaveSpider entity) { + super(server, entity); + } + + @Override + public EntityCaveSpider getHandle() { + return (EntityCaveSpider) entity; + } + + @Override + public String toString() { + return "CraftCaveSpider"; + } + + public EntityType getType() { + return EntityType.CAVE_SPIDER; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftChicken.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftChicken.java new file mode 100644 index 0000000..440c3f1 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftChicken.java @@ -0,0 +1,27 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityChicken; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.Chicken; +import org.bukkit.entity.EntityType; + +public class CraftChicken extends CraftAnimals implements Chicken { + + public CraftChicken(CraftServer server, EntityChicken entity) { + super(server, entity); + } + + @Override + public EntityChicken getHandle() { + return (EntityChicken) entity; + } + + @Override + public String toString() { + return "CraftChicken"; + } + + public EntityType getType() { + return EntityType.CHICKEN; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftComplexLivingEntity.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftComplexLivingEntity.java new file mode 100644 index 0000000..cc115cc --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftComplexLivingEntity.java @@ -0,0 +1,21 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityLiving; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.ComplexLivingEntity; + +public abstract class CraftComplexLivingEntity extends CraftLivingEntity implements ComplexLivingEntity { + public CraftComplexLivingEntity(CraftServer server, EntityLiving entity) { + super(server, entity); + } + + @Override + public EntityLiving getHandle() { + return (EntityLiving) entity; + } + + @Override + public String toString() { + return "CraftComplexLivingEntity"; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftComplexPart.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftComplexPart.java new file mode 100644 index 0000000..eb1ce79 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftComplexPart.java @@ -0,0 +1,43 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityComplexPart; +import net.minecraft.server.EntityEnderDragon; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.ComplexEntityPart; +import org.bukkit.entity.ComplexLivingEntity; +import org.bukkit.entity.EntityType; +import org.bukkit.event.entity.EntityDamageEvent; + +public class CraftComplexPart extends CraftEntity implements ComplexEntityPart { + public CraftComplexPart(CraftServer server, EntityComplexPart entity) { + super(server, entity); + } + + public ComplexLivingEntity getParent() { + return (ComplexLivingEntity) ((EntityEnderDragon) getHandle().owner).getBukkitEntity(); + } + + @Override + public void setLastDamageCause(EntityDamageEvent cause) { + getParent().setLastDamageCause(cause); + } + + @Override + public EntityDamageEvent getLastDamageCause() { + return getParent().getLastDamageCause(); + } + + @Override + public EntityComplexPart getHandle() { + return (EntityComplexPart) entity; + } + + @Override + public String toString() { + return "CraftComplexPart"; + } + + public EntityType getType() { + return EntityType.COMPLEX_PART; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftCow.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftCow.java new file mode 100644 index 0000000..3675ea8 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftCow.java @@ -0,0 +1,27 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityCow; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.Cow; +import org.bukkit.entity.EntityType; + +public class CraftCow extends CraftAnimals implements Cow { + + public CraftCow(CraftServer server, EntityCow entity) { + super(server, entity); + } + + @Override + public EntityCow getHandle() { + return (EntityCow) entity; + } + + @Override + public String toString() { + return "CraftCow"; + } + + public EntityType getType() { + return EntityType.COW; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftCreature.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftCreature.java new file mode 100644 index 0000000..09d4214 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftCreature.java @@ -0,0 +1,37 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityCreature; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.Creature; +import org.bukkit.entity.LivingEntity; + +public class CraftCreature extends CraftLivingEntity implements Creature { + public CraftCreature(CraftServer server, EntityCreature entity) { + super(server, entity); + } + + public void setTarget(LivingEntity target) { + EntityCreature entity = getHandle(); + if (target == null) { + entity.setGoalTarget(null, null, false); + } else if (target instanceof CraftLivingEntity) { + entity.setGoalTarget(((CraftLivingEntity) target).getHandle(), null, false); + } + } + + public CraftLivingEntity getTarget() { + if (getHandle().getGoalTarget() == null) return null; + + return (CraftLivingEntity) getHandle().getGoalTarget().getBukkitEntity(); + } + + @Override + public EntityCreature getHandle() { + return (EntityCreature) entity; + } + + @Override + public String toString() { + return "CraftCreature"; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftCreeper.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftCreeper.java new file mode 100644 index 0000000..25f68d7 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftCreeper.java @@ -0,0 +1,53 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityCreeper; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.Creeper; +import org.bukkit.entity.EntityType; +import org.bukkit.event.entity.CreeperPowerEvent; + +public class CraftCreeper extends CraftMonster implements Creeper { + + public CraftCreeper(CraftServer server, EntityCreeper entity) { + super(server, entity); + } + + public boolean isPowered() { + return getHandle().isPowered(); + } + + public void setPowered(boolean powered) { + CraftServer server = this.server; + Creeper entity = (Creeper) this.getHandle().getBukkitEntity(); + + if (powered) { + CreeperPowerEvent event = new CreeperPowerEvent(entity, CreeperPowerEvent.PowerCause.SET_ON); + server.getPluginManager().callEvent(event); + + if (!event.isCancelled()) { + getHandle().setPowered(true); + } + } else { + CreeperPowerEvent event = new CreeperPowerEvent(entity, CreeperPowerEvent.PowerCause.SET_OFF); + server.getPluginManager().callEvent(event); + + if (!event.isCancelled()) { + getHandle().setPowered(false); + } + } + } + + @Override + public EntityCreeper getHandle() { + return (EntityCreeper) entity; + } + + @Override + public String toString() { + return "CraftCreeper"; + } + + public EntityType getType() { + return EntityType.CREEPER; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftEgg.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftEgg.java new file mode 100644 index 0000000..60c5188 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftEgg.java @@ -0,0 +1,26 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityEgg; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.Egg; +import org.bukkit.entity.EntityType; + +public class CraftEgg extends CraftProjectile implements Egg { + public CraftEgg(CraftServer server, EntityEgg entity) { + super(server, entity); + } + + @Override + public EntityEgg getHandle() { + return (EntityEgg) entity; + } + + @Override + public String toString() { + return "CraftEgg"; + } + + public EntityType getType() { + return EntityType.EGG; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderCrystal.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderCrystal.java new file mode 100644 index 0000000..2bcf3a1 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderCrystal.java @@ -0,0 +1,26 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityEnderCrystal; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.EnderCrystal; +import org.bukkit.entity.EntityType; + +public class CraftEnderCrystal extends CraftEntity implements EnderCrystal { + public CraftEnderCrystal(CraftServer server, EntityEnderCrystal entity) { + super(server, entity); + } + + @Override + public EntityEnderCrystal getHandle() { + return (EntityEnderCrystal) entity; + } + + @Override + public String toString() { + return "CraftEnderCrystal"; + } + + public EntityType getType() { + return EntityType.ENDER_CRYSTAL; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderDragon.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderDragon.java new file mode 100644 index 0000000..2c05804 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderDragon.java @@ -0,0 +1,42 @@ +package org.bukkit.craftbukkit.entity; + +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.ImmutableSet.Builder; +import net.minecraft.server.EntityComplexPart; +import net.minecraft.server.EntityEnderDragon; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.ComplexEntityPart; +import org.bukkit.entity.EnderDragon; +import org.bukkit.entity.EntityType; + +import java.util.Set; + +public class CraftEnderDragon extends CraftComplexLivingEntity implements EnderDragon { + public CraftEnderDragon(CraftServer server, EntityEnderDragon entity) { + super(server, entity); + } + + public Set getParts() { + Builder builder = ImmutableSet.builder(); + + for (EntityComplexPart part : getHandle().children) { + builder.add((ComplexEntityPart) part.getBukkitEntity()); + } + + return builder.build(); + } + + @Override + public EntityEnderDragon getHandle() { + return (EntityEnderDragon) entity; + } + + @Override + public String toString() { + return "CraftEnderDragon"; + } + + public EntityType getType() { + return EntityType.ENDER_DRAGON; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderDragonPart.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderDragonPart.java new file mode 100644 index 0000000..736a460 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderDragonPart.java @@ -0,0 +1,87 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityComplexPart; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.EnderDragon; +import org.bukkit.entity.EnderDragonPart; +import org.bukkit.entity.Entity; +import org.bukkit.util.NumberConversions; + +public class CraftEnderDragonPart extends CraftComplexPart implements EnderDragonPart { + public CraftEnderDragonPart(CraftServer server, EntityComplexPart entity) { + super(server, entity); + } + + @Override + public EnderDragon getParent() { + return (EnderDragon) super.getParent(); + } + + @Override + public EntityComplexPart getHandle() { + return (EntityComplexPart) entity; + } + + @Override + public String toString() { + return "CraftEnderDragonPart"; + } + + public void damage(double amount) { + getParent().damage(amount); + } + + public void damage(double amount, Entity source) { + getParent().damage(amount, source); + } + + public double getHealth() { + return getParent().getHealth(); + } + + public void setHealth(double health) { + getParent().setHealth(health); + } + + public double getMaxHealth() { + return getParent().getMaxHealth(); + } + + public void setMaxHealth(double health) { + getParent().setMaxHealth(health); + } + + public void resetMaxHealth() { + getParent().resetMaxHealth(); + } + + @Deprecated + public void _INVALID_damage(int amount) { + damage(amount); + } + + @Deprecated + public void _INVALID_damage(int amount, Entity source) { + damage(amount, source); + } + + @Deprecated + public int _INVALID_getHealth() { + return NumberConversions.ceil(getHealth()); + } + + @Deprecated + public void _INVALID_setHealth(int health) { + setHealth(health); + } + + @Deprecated + public int _INVALID_getMaxHealth() { + return NumberConversions.ceil(getMaxHealth()); + } + + @Deprecated + public void _INVALID_setMaxHealth(int health) { + setMaxHealth(health); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderPearl.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderPearl.java new file mode 100644 index 0000000..f42f9ab --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderPearl.java @@ -0,0 +1,26 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityEnderPearl; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.EnderPearl; +import org.bukkit.entity.EntityType; + +public class CraftEnderPearl extends CraftProjectile implements EnderPearl { + public CraftEnderPearl(CraftServer server, EntityEnderPearl entity) { + super(server, entity); + } + + @Override + public EntityEnderPearl getHandle() { + return (EntityEnderPearl) entity; + } + + @Override + public String toString() { + return "CraftEnderPearl"; + } + + public EntityType getType() { + return EntityType.ENDER_PEARL; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderSignal.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderSignal.java new file mode 100644 index 0000000..e3a5081 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderSignal.java @@ -0,0 +1,26 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityEnderSignal; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.EnderSignal; +import org.bukkit.entity.EntityType; + +public class CraftEnderSignal extends CraftEntity implements EnderSignal { + public CraftEnderSignal(CraftServer server, EntityEnderSignal entity) { + super(server, entity); + } + + @Override + public EntityEnderSignal getHandle() { + return (EntityEnderSignal) entity; + } + + @Override + public String toString() { + return "CraftEnderSignal"; + } + + public EntityType getType() { + return EntityType.ENDER_SIGNAL; + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderman.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderman.java new file mode 100644 index 0000000..84cd9e3 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftEnderman.java @@ -0,0 +1,38 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityEnderman; +import net.minecraft.server.IBlockData; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.util.CraftMagicNumbers; +import org.bukkit.entity.Enderman; +import org.bukkit.entity.EntityType; +import org.bukkit.material.MaterialData; + +public class CraftEnderman extends CraftMonster implements Enderman { + public CraftEnderman(CraftServer server, EntityEnderman entity) { + super(server, entity); + } + + public MaterialData getCarriedMaterial() { + IBlockData blockData = getHandle().getCarried(); + return CraftMagicNumbers.getMaterial(blockData.getBlock()).getNewData((byte) blockData.getBlock().toLegacyData(blockData)); + } + + public void setCarriedMaterial(MaterialData data) { + getHandle().setCarried(CraftMagicNumbers.getBlock(data.getItemTypeId()).fromLegacyData(data.getData())); + } + + @Override + public EntityEnderman getHandle() { + return (EntityEnderman) entity; + } + + @Override + public String toString() { + return "CraftEnderman"; + } + + public EntityType getType() { + return EntityType.ENDERMAN; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftEndermite.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftEndermite.java new file mode 100644 index 0000000..4fd49ea --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftEndermite.java @@ -0,0 +1,23 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityEndermite; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.Endermite; +import org.bukkit.entity.EntityType; + +public class CraftEndermite extends CraftMonster implements Endermite { + + public CraftEndermite(CraftServer server, EntityEndermite entity) { + super(server, entity); + } + + @Override + public String toString() { + return "CraftEndermite"; + } + + @Override + public EntityType getType() { + return EntityType.ENDERMITE; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftEntity.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftEntity.java new file mode 100644 index 0000000..c2085c6 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftEntity.java @@ -0,0 +1,583 @@ +package org.bukkit.craftbukkit.entity; + +import com.google.common.base.Preconditions; +import net.minecraft.server.*; +import org.bukkit.EntityEffect; +import org.bukkit.Location; +import org.bukkit.Server; +import org.bukkit.World; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; +import org.bukkit.metadata.MetadataValue; +import org.bukkit.permissions.*; +import org.bukkit.plugin.Plugin; +import org.bukkit.util.Vector; +import org.github.paperspigot.PaperSpigotConfig; + +import java.util.List; +import java.util.Set; +import java.util.UUID; + +public abstract class CraftEntity implements org.bukkit.entity.Entity { + private static final PermissibleBase perm = new PermissibleBase(new ServerOperator() { + public boolean isOp() { + return false; + } + + public void setOp(boolean value) {} + }); + + protected final CraftServer server; + protected Entity entity; + private EntityDamageEvent lastDamageEvent; + + public CraftEntity(final CraftServer server, final Entity entity) { + this.server = server; + this.entity = entity; + } + + public static CraftEntity getEntity(CraftServer server, Entity entity) { + /** + * Order is *EXTREMELY* important -- keep it right! =D + */ + // Vortex - Cannons first + if (entity instanceof EntityTNTPrimed) { return new CraftTNTPrimed(server, (EntityTNTPrimed) entity); } + else if (entity instanceof EntityFallingBlock) { return new CraftFallingSand(server, (EntityFallingBlock) entity); } + + else if (entity instanceof EntityLiving) { + // Players + if (entity instanceof EntityHuman) { + if (entity instanceof EntityPlayer) { return new CraftPlayer(server, (EntityPlayer) entity); } + else { return new CraftHumanEntity(server, (EntityHuman) entity); } + } + // Water Animals + else if (entity instanceof EntityWaterAnimal) { + if (entity instanceof EntitySquid) { return new CraftSquid(server, (EntitySquid) entity); } + else { return new CraftWaterMob(server, (EntityWaterAnimal) entity); } + } + else if (entity instanceof EntityCreature) { + // Animals + if (entity instanceof EntityAnimal) { + if (entity instanceof EntityChicken) { return new CraftChicken(server, (EntityChicken) entity); } + else if (entity instanceof EntityCow) { + if (entity instanceof EntityMushroomCow) { return new CraftMushroomCow(server, (EntityMushroomCow) entity); } + else { return new CraftCow(server, (EntityCow) entity); } + } + else if (entity instanceof EntityPig) { return new CraftPig(server, (EntityPig) entity); } + else if (entity instanceof EntityTameableAnimal) { + if (entity instanceof EntityWolf) { return new CraftWolf(server, (EntityWolf) entity); } + else if (entity instanceof EntityOcelot) { return new CraftOcelot(server, (EntityOcelot) entity); } + } + else if (entity instanceof EntitySheep) { return new CraftSheep(server, (EntitySheep) entity); } + else if (entity instanceof EntityHorse) { return new CraftHorse(server, (EntityHorse) entity); } + else if (entity instanceof EntityRabbit) { return new CraftRabbit(server, (EntityRabbit) entity); } + else { return new CraftAnimals(server, (EntityAnimal) entity); } + } + // Monsters + else if (entity instanceof EntityMonster) { + if (entity instanceof EntityZombie) { + if (entity instanceof EntityPigZombie) { return new CraftPigZombie(server, (EntityPigZombie) entity); } + else { return new CraftZombie(server, (EntityZombie) entity); } + } + else if (entity instanceof EntityCreeper) { return new CraftCreeper(server, (EntityCreeper) entity); } + else if (entity instanceof EntityEnderman) { return new CraftEnderman(server, (EntityEnderman) entity); } + else if (entity instanceof EntitySilverfish) { return new CraftSilverfish(server, (EntitySilverfish) entity); } + else if (entity instanceof EntityGiantZombie) { return new CraftGiant(server, (EntityGiantZombie) entity); } + else if (entity instanceof EntitySkeleton) { return new CraftSkeleton(server, (EntitySkeleton) entity); } + else if (entity instanceof EntityBlaze) { return new CraftBlaze(server, (EntityBlaze) entity); } + else if (entity instanceof EntityWitch) { return new CraftWitch(server, (EntityWitch) entity); } + else if (entity instanceof EntityWither) { return new CraftWither(server, (EntityWither) entity); } + else if (entity instanceof EntitySpider) { + if (entity instanceof EntityCaveSpider) { return new CraftCaveSpider(server, (EntityCaveSpider) entity); } + else { return new CraftSpider(server, (EntitySpider) entity); } + } + else if (entity instanceof EntityEndermite) { return new CraftEndermite(server, (EntityEndermite) entity); } + else if (entity instanceof EntityGuardian) { return new CraftGuardian(server, (EntityGuardian) entity); } + + else { return new CraftMonster(server, (EntityMonster) entity); } + } + else if (entity instanceof EntityGolem) { + if (entity instanceof EntitySnowman) { return new CraftSnowman(server, (EntitySnowman) entity); } + else if (entity instanceof EntityIronGolem) { return new CraftIronGolem(server, (EntityIronGolem) entity); } + } + else if (entity instanceof EntityVillager) { return new CraftVillager(server, (EntityVillager) entity); } + else { return new CraftCreature(server, (EntityCreature) entity); } + } + // Slimes are a special (and broken) case + else if (entity instanceof EntitySlime) { + if (entity instanceof EntityMagmaCube) { return new CraftMagmaCube(server, (EntityMagmaCube) entity); } + else { return new CraftSlime(server, (EntitySlime) entity); } + } + // Flying + else if (entity instanceof EntityFlying) { + if (entity instanceof EntityGhast) { return new CraftGhast(server, (EntityGhast) entity); } + else { return new CraftFlying(server, (EntityFlying) entity); } + } + else if (entity instanceof EntityEnderDragon) { + return new CraftEnderDragon(server, (EntityEnderDragon) entity); + } + // Ambient + else if (entity instanceof EntityAmbient) { + if (entity instanceof EntityBat) { return new CraftBat(server, (EntityBat) entity); } + else { return new CraftAmbient(server, (EntityAmbient) entity); } + } + else if (entity instanceof EntityArmorStand) { return new CraftArmorStand(server, (EntityArmorStand) entity); } + else { return new CraftLivingEntity(server, (EntityLiving) entity); } + } + else if (entity instanceof EntityComplexPart) { + EntityComplexPart part = (EntityComplexPart) entity; + if (part.owner instanceof EntityEnderDragon) { return new CraftEnderDragonPart(server, (EntityComplexPart) entity); } + else { return new CraftComplexPart(server, (EntityComplexPart) entity); } + } + else if (entity instanceof EntityExperienceOrb) { return new CraftExperienceOrb(server, (EntityExperienceOrb) entity); } + else if (entity instanceof EntityArrow) { return new CraftArrow(server, (EntityArrow) entity); } + else if (entity instanceof EntityBoat) { return new CraftBoat(server, (EntityBoat) entity); } + else if (entity instanceof EntityProjectile) { + if (entity instanceof EntityEgg) { return new CraftEgg(server, (EntityEgg) entity); } + else if (entity instanceof EntitySnowball) { return new CraftSnowball(server, (EntitySnowball) entity); } + else if (entity instanceof EntityPotion) { return new CraftThrownPotion(server, (EntityPotion) entity); } + else if (entity instanceof EntityEnderPearl) { return new CraftEnderPearl(server, (EntityEnderPearl) entity); } + else if (entity instanceof EntityThrownExpBottle) { return new CraftThrownExpBottle(server, (EntityThrownExpBottle) entity); } + } + else if (entity instanceof EntityFireball) { + if (entity instanceof EntitySmallFireball) { return new CraftSmallFireball(server, (EntitySmallFireball) entity); } + else if (entity instanceof EntityLargeFireball) { return new CraftLargeFireball(server, (EntityLargeFireball) entity); } + else if (entity instanceof EntityWitherSkull) { return new CraftWitherSkull(server, (EntityWitherSkull) entity); } + else { return new CraftFireball(server, (EntityFireball) entity); } + } + else if (entity instanceof EntityEnderSignal) { return new CraftEnderSignal(server, (EntityEnderSignal) entity); } + else if (entity instanceof EntityEnderCrystal) { return new CraftEnderCrystal(server, (EntityEnderCrystal) entity); } + else if (entity instanceof EntityFishingHook) { return new CraftFish(server, (EntityFishingHook) entity); } + else if (entity instanceof EntityItem) { return new CraftItem(server, (EntityItem) entity); } + else if (entity instanceof EntityWeather) { + if (entity instanceof EntityLightning) { return new CraftLightningStrike(server, (EntityLightning) entity); } + else { return new CraftWeather(server, (EntityWeather) entity); } + } + else if (entity instanceof EntityMinecartAbstract) { + if (entity instanceof EntityMinecartFurnace) { return new CraftMinecartFurnace(server, (EntityMinecartFurnace) entity); } + else if (entity instanceof EntityMinecartChest) { return new CraftMinecartChest(server, (EntityMinecartChest) entity); } + else if (entity instanceof EntityMinecartTNT) { return new CraftMinecartTNT(server, (EntityMinecartTNT) entity); } + else if (entity instanceof EntityMinecartHopper) { return new CraftMinecartHopper(server, (EntityMinecartHopper) entity); } + else if (entity instanceof EntityMinecartMobSpawner) { return new CraftMinecartMobSpawner(server, (EntityMinecartMobSpawner) entity); } + else if (entity instanceof EntityMinecartRideable) { return new CraftMinecartRideable(server, (EntityMinecartRideable) entity); } + else if (entity instanceof EntityMinecartCommandBlock) { return new CraftMinecartCommand(server, (EntityMinecartCommandBlock) entity); } + } else if (entity instanceof EntityHanging) { + if (entity instanceof EntityPainting) { return new CraftPainting(server, (EntityPainting) entity); } + else if (entity instanceof EntityItemFrame) { return new CraftItemFrame(server, (EntityItemFrame) entity); } + else if (entity instanceof EntityLeash) { return new CraftLeash(server, (EntityLeash) entity); } + else { return new CraftHanging(server, (EntityHanging) entity); } + } + else if (entity instanceof EntityFireworks) { return new CraftFirework(server, (EntityFireworks) entity); } + + throw new AssertionError("Unknown entity " + (entity == null ? null : entity.getClass())); + } + + public Location getLocation() { + return new Location(getWorld(), entity.locX, entity.locY, entity.locZ, entity.yaw, entity.pitch); + } + + public Location getLocation(Location loc) { + if (loc != null) { + loc.setWorld(getWorld()); + loc.setX(entity.locX); + loc.setY(entity.locY); + loc.setZ(entity.locZ); + loc.setYaw(entity.yaw); + loc.setPitch(entity.pitch); + } + + return loc; + } + + public Vector getVelocity() { + return new Vector(entity.motX, entity.motY, entity.motZ); + } + + public void setVelocity(Vector vel) { + // Paper start - warn server owners when plugins try to set super high velocities + if (PaperSpigotConfig.warnForExcessiveVelocity) { + if(vel.getX() > 4 || vel.getX() < -4 || vel.getY() > 4 || vel.getY() < -4 || vel.getZ() > 4 || vel.getZ() < -4) { + getServer().getLogger().warning("Excessive velocity set detected: tried to set velocity of entity #"+getEntityId()+" to ("+vel.getX()+","+vel.getY()+","+vel.getZ()+")."); + Thread.dumpStack(); + } + } + // Paper end + + entity.motX = vel.getX(); + entity.motY = vel.getY(); + entity.motZ = vel.getZ(); + entity.velocityChanged = true; + } + + public boolean isOnGround() { + if (entity instanceof EntityArrow) { + return ((EntityArrow) entity).isInGround(); + } + return entity.onGround; + } + + public World getWorld() { + return entity.world.getWorld(); + } + + public boolean teleport(Location location) { + return teleport(location, TeleportCause.PLUGIN); + } + + public boolean teleport(Location location, TeleportCause cause) { + if (entity.passenger != null || entity.dead) { + return false; + } + + // If this entity is riding another entity, we must dismount before teleporting. + entity.mount(null); + + // Spigot start + if (!location.getWorld().equals(getWorld())) { + entity.teleportTo(location, cause.equals(TeleportCause.NETHER_PORTAL)); + return true; + } + + // entity.world = ((CraftWorld) location.getWorld()).getHandle(); + // Spigot end + entity.setLocation(location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch()); + entity.world.entityJoinedWorld(entity, false); // PaperSpigot - Fix issues with entities not being switched to their new chunk + // entity.setLocation() throws no event, and so cannot be cancelled + return true; + } + + public boolean teleport(org.bukkit.entity.Entity destination) { + return teleport(destination.getLocation()); + } + + public boolean teleport(org.bukkit.entity.Entity destination, TeleportCause cause) { + return teleport(destination.getLocation(), cause); + } + + public List getNearbyEntities(double x, double y, double z) { + List notchEntityList = entity.world.a(entity, entity.getBoundingBox().grow(x, y, z), null); + List bukkitEntityList = new java.util.ArrayList<>(notchEntityList.size()); + + for (Entity e : notchEntityList) { + bukkitEntityList.add(e.getBukkitEntity()); + } + return bukkitEntityList; + } + + public int getEntityId() { + return entity.getId(); + } + + public int getFireTicks() { + return entity.fireTicks; + } + + public int getMaxFireTicks() { + return entity.maxFireTicks; + } + + public void setFireTicks(int ticks) { + entity.fireTicks = ticks; + } + + public void remove() { + entity.dead = true; + } + + public boolean isDead() { + return !entity.isAlive(); + } + + public boolean isValid() { + return entity.isAlive() && entity.valid; + } + + public Server getServer() { + return server; + } + + public Vector getMomentum() { + return getVelocity(); + } + + public void setMomentum(Vector value) { + setVelocity(value); + } + + public org.bukkit.entity.Entity getPassenger() { + return isEmpty() ? null : getHandle().passenger.getBukkitEntity(); + } + + public boolean setPassenger(org.bukkit.entity.Entity passenger) { + Preconditions.checkArgument(!this.equals(passenger), "Entity cannot ride itself."); + if (passenger instanceof CraftEntity) { + ((CraftEntity) passenger).getHandle().mount(getHandle()); + return true; + } else { + return false; + } + } + + public boolean isEmpty() { + return getHandle().passenger == null; + } + + public boolean eject() { + if (getHandle().passenger == null) { + return false; + } + + getHandle().passenger.mount(null); + return true; + } + + public float getFallDistance() { + return getHandle().fallDistance; + } + + public void setFallDistance(float distance) { + getHandle().fallDistance = distance; + } + + public void setLastDamageCause(EntityDamageEvent event) { + lastDamageEvent = event; + } + + public EntityDamageEvent getLastDamageCause() { + return lastDamageEvent; + } + + public UUID getUniqueId() { + return getHandle().getUniqueID(); + } + + public int getTicksLived() { + return getHandle().ticksLived; + } + + public void setTicksLived(int value) { + if (value <= 0) { + throw new IllegalArgumentException("Age must be at least 1 tick"); + } + getHandle().ticksLived = value; + } + + public Entity getHandle() { + return entity; + } + + public void playEffect(EntityEffect type) { + this.getHandle().world.broadcastEntityEffect(getHandle(), type.getData()); + } + + public void setHandle(final Entity entity) { + this.entity = entity; + } + + @Override + public String toString() { + return "CraftEntity{" + "id=" + getEntityId() + '}'; + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final CraftEntity other = (CraftEntity) obj; + return (this.getEntityId() == other.getEntityId()); + } + + @Override + public int hashCode() { + int hash = 7; + hash = 29 * hash + this.getEntityId(); + return hash; + } + + public void setMetadata(String metadataKey, MetadataValue newMetadataValue) { + server.getEntityMetadata().setMetadata(this, metadataKey, newMetadataValue); + } + + public List getMetadata(String metadataKey) { + return server.getEntityMetadata().getMetadata(this, metadataKey); + } + + public boolean hasMetadata(String metadataKey) { + return server.getEntityMetadata().hasMetadata(this, metadataKey); + } + + public void removeMetadata(String metadataKey, Plugin owningPlugin) { + server.getEntityMetadata().removeMetadata(this, metadataKey, owningPlugin); + } + + public boolean isInsideVehicle() { + return getHandle().vehicle != null; + } + + public boolean leaveVehicle() { + if (getHandle().vehicle == null) { + return false; + } + + getHandle().mount(null); + return true; + } + + public org.bukkit.entity.Entity getVehicle() { + if (getHandle().vehicle == null) { + return null; + } + + return getHandle().vehicle.getBukkitEntity(); + } + + @Override + public void setCustomName(String name) { + if (name == null) { + name = ""; + } + + getHandle().setCustomName(name); + } + + @Override + public String getCustomName() { + String name = getHandle().getCustomName(); + + if (name == null || name.length() == 0) { + return null; + } + + return name; + } + + @Override + public void setCustomNameVisible(boolean flag) { + getHandle().setCustomNameVisible(flag); + } + + @Override + public boolean isCustomNameVisible() { + return getHandle().getCustomNameVisible(); + } + + @Override + public void sendMessage(String message) { + + } + + @Override + public void sendMessage(String[] messages) { + + } + + @Override + public String getName() { + return getHandle().getName(); + } + + public boolean isPermissionSet(String name) { + return perm.isPermissionSet(name); + } + + public boolean isPermissionSet(Permission perm) { + return CraftEntity.perm.isPermissionSet(perm); + } + + public boolean hasPermission(String name) { + return perm.hasPermission(name); + } + + public boolean hasPermission(Permission perm) { + return CraftEntity.perm.hasPermission(perm); + } + + public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value) { + return perm.addAttachment(plugin, name, value); + } + + public PermissionAttachment addAttachment(Plugin plugin) { + return perm.addAttachment(plugin); + } + + public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value, int ticks) { + return perm.addAttachment(plugin, name, value, ticks); + } + + public PermissionAttachment addAttachment(Plugin plugin, int ticks) { + return perm.addAttachment(plugin, ticks); + } + + public void removeAttachment(PermissionAttachment attachment) { + perm.removeAttachment(attachment); + } + + public void recalculatePermissions() { + perm.recalculatePermissions(); + } + + public Set getEffectivePermissions() { + return perm.getEffectivePermissions(); + } + + public boolean isOp() { + return perm.isOp(); + } + + public void setOp(boolean value) { + perm.setOp(value); + } + + // Spigot start + private final Spigot spigot = new Spigot() + { + @Override + public boolean isInvulnerable() + { + return getHandle().isInvulnerable(net.minecraft.server.DamageSource.GENERIC); + } + }; + + public Spigot spigot() + { + return spigot; + } + // Spigot end + + // Rivals start + @Override + public boolean isCollidable() { + return getHandle().collidable; + } + + @Override + public void setCollidable(boolean collidable) { + getHandle().collidable = collidable; + } + + @Override + public boolean isDisableKnockback() { + return getHandle().disableKnockback; + } + + @Override + public void setDisableKnockback(boolean disableKnockback) { + getHandle().disableKnockback = disableKnockback; + } + + @Override + public boolean isDisableWaterMovement() { + return getHandle().disableWaterMovement; + } + + @Override + public void setDisableWaterMovement(boolean disableWaterMovement) { + getHandle().disableWaterMovement = disableWaterMovement; + } + // Rivals end +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftExperienceOrb.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftExperienceOrb.java new file mode 100644 index 0000000..3a09cab --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftExperienceOrb.java @@ -0,0 +1,34 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityExperienceOrb; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.ExperienceOrb; + +public class CraftExperienceOrb extends CraftEntity implements ExperienceOrb { + public CraftExperienceOrb(CraftServer server, EntityExperienceOrb entity) { + super(server, entity); + } + + public int getExperience() { + return getHandle().value; + } + + public void setExperience(int value) { + getHandle().value = value; + } + + @Override + public EntityExperienceOrb getHandle() { + return (EntityExperienceOrb) entity; + } + + @Override + public String toString() { + return "CraftExperienceOrb"; + } + + public EntityType getType() { + return EntityType.EXPERIENCE_ORB; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftFallingSand.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftFallingSand.java new file mode 100644 index 0000000..14c7443 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftFallingSand.java @@ -0,0 +1,66 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityFallingBlock; +import org.bukkit.Material; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.util.CraftMagicNumbers; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.FallingSand; + +public class CraftFallingSand extends CraftEntity implements FallingSand { + + public CraftFallingSand(CraftServer server, EntityFallingBlock entity) { + super(server, entity); + } + + @Override + public EntityFallingBlock getHandle() { + return (EntityFallingBlock) entity; + } + + @Override + public String toString() { + return "CraftFallingSand"; + } + + public EntityType getType() { + return EntityType.FALLING_BLOCK; + } + + public Material getMaterial() { + return Material.getMaterial(getBlockId()); + } + + public int getBlockId() { + return CraftMagicNumbers.getId(getHandle().getBlock().getBlock()); + } + + public byte getBlockData() { + return (byte) getHandle().getBlock().getBlock().toLegacyData(getHandle().getBlock()); + } + + public boolean getDropItem() { + return getHandle().dropItem; + } + + public void setDropItem(boolean drop) { + getHandle().dropItem = drop; + } + + @Override + public boolean canHurtEntities() { + return getHandle().hurtEntities; + } + + @Override + public void setHurtEntities(boolean hurtEntities) { + getHandle().hurtEntities = hurtEntities; + } + + // PaperSpigot start - Add FallingBlock source location API + @Override + public org.bukkit.Location getSourceLoc() { + return getHandle().sourceLoc; + } + // PaperSpigot end +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftFireball.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftFireball.java new file mode 100644 index 0000000..27926a5 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftFireball.java @@ -0,0 +1,88 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityFireball; +import net.minecraft.server.MathHelper; +import org.apache.commons.lang.Validate; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Fireball; +import org.bukkit.entity.LivingEntity; +import org.bukkit.projectiles.ProjectileSource; +import org.bukkit.util.Vector; + +public class CraftFireball extends AbstractProjectile implements Fireball { + public CraftFireball(CraftServer server, EntityFireball entity) { + super(server, entity); + } + + public float getYield() { + return getHandle().bukkitYield; + } + + public boolean isIncendiary() { + return getHandle().isIncendiary; + } + + public void setIsIncendiary(boolean isIncendiary) { + getHandle().isIncendiary = isIncendiary; + } + + public void setYield(float yield) { + getHandle().bukkitYield = yield; + } + + public ProjectileSource getShooter() { + return getHandle().projectileSource; + } + + public void setShooter(ProjectileSource shooter) { + if (shooter instanceof CraftLivingEntity) { + getHandle().shooter = ((CraftLivingEntity) shooter).getHandle(); + } else { + getHandle().shooter = null; + } + getHandle().projectileSource = shooter; + } + + public Vector getDirection() { + return new Vector(getHandle().dirX, getHandle().dirY, getHandle().dirZ); + } + + public void setDirection(Vector direction) { + Validate.notNull(direction, "Direction can not be null"); + double x = direction.getX(); + double y = direction.getY(); + double z = direction.getZ(); + double magnitude = (double) MathHelper.sqrt(x * x + y * y + z * z); + getHandle().dirX = x / magnitude; + getHandle().dirY = y / magnitude; + getHandle().dirZ = z / magnitude; + } + + @Override + public EntityFireball getHandle() { + return (EntityFireball) entity; + } + + @Override + public String toString() { + return "CraftFireball"; + } + + public EntityType getType() { + return EntityType.UNKNOWN; + } + + @Deprecated + public void _INVALID_setShooter(LivingEntity shooter) { + setShooter(shooter); + } + + @Deprecated + public LivingEntity _INVALID_getShooter() { + if (getHandle().shooter != null) { + return (LivingEntity) getHandle().shooter.getBukkitEntity(); + } + return null; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftFirework.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftFirework.java new file mode 100644 index 0000000..01a4ce0 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftFirework.java @@ -0,0 +1,73 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityFireworks; +import net.minecraft.server.ItemStack; +import net.minecraft.server.Items; +import org.bukkit.Material; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Firework; +import org.bukkit.inventory.meta.FireworkMeta; + +import java.util.Random; + +public class CraftFirework extends CraftEntity implements Firework { + private static final int FIREWORK_ITEM_INDEX = 8; + + private final Random random = new Random(); + private final CraftItemStack item; + + public CraftFirework(CraftServer server, EntityFireworks entity) { + super(server, entity); + + ItemStack item = getHandle().getDataWatcher().getItemStack(FIREWORK_ITEM_INDEX); + + if (item == null) { + item = new ItemStack(Items.FIREWORKS); + getHandle().getDataWatcher().watch(FIREWORK_ITEM_INDEX, item); + } + + this.item = CraftItemStack.asCraftMirror(item); + + // Ensure the item is a firework... + if (this.item.getType() != Material.FIREWORK) { + this.item.setType(Material.FIREWORK); + } + } + + @Override + public EntityFireworks getHandle() { + return (EntityFireworks) entity; + } + + @Override + public String toString() { + return "CraftFirework"; + } + + @Override + public EntityType getType() { + return EntityType.FIREWORK; + } + + @Override + public FireworkMeta getFireworkMeta() { + return (FireworkMeta) item.getItemMeta(); + } + + @Override + public void setFireworkMeta(FireworkMeta meta) { + item.setItemMeta(meta); + + // Copied from EntityFireworks constructor, update firework lifetime/power + getHandle().expectedLifespan = 10 * (1 + meta.getPower()) + random.nextInt(6) + random.nextInt(7); + + getHandle().getDataWatcher().update(FIREWORK_ITEM_INDEX); + } + + @Override + public void detonate() { + getHandle().expectedLifespan = 0; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftFish.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftFish.java new file mode 100644 index 0000000..569961d --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftFish.java @@ -0,0 +1,74 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityFishingHook; +import net.minecraft.server.EntityHuman; +import net.minecraft.server.MathHelper; +import org.apache.commons.lang.Validate; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Fish; +import org.bukkit.entity.LivingEntity; +import org.bukkit.projectiles.ProjectileSource; + +public class CraftFish extends AbstractProjectile implements Fish { + private double biteChance = -1; + + public CraftFish(CraftServer server, EntityFishingHook entity) { + super(server, entity); + } + + public ProjectileSource getShooter() { + if (getHandle().owner != null) { + return getHandle().owner.getBukkitEntity(); + } + + return null; + } + + public void setShooter(ProjectileSource shooter) { + if (shooter instanceof CraftHumanEntity) { + getHandle().owner = (EntityHuman) ((CraftHumanEntity) shooter).entity; + } + } + + @Override + public EntityFishingHook getHandle() { + return (EntityFishingHook) entity; + } + + @Override + public String toString() { + return "CraftFish"; + } + + public EntityType getType() { + return EntityType.FISHING_HOOK; + } + + public double getBiteChance() { + EntityFishingHook hook = getHandle(); + + if (this.biteChance == -1) { + if (hook.world.isRainingAt(MathHelper.floor(hook.locX), MathHelper.floor(hook.locY) + 1, MathHelper.floor(hook.locZ))) { + return 1/300.0; + } + return 1/500.0; + } + return this.biteChance; + } + + public void setBiteChance(double chance) { + Validate.isTrue(chance >= 0 && chance <= 1, "The bite chance must be between 0 and 1."); + this.biteChance = chance; + } + + @Deprecated + public LivingEntity _INVALID_getShooter() { + return (LivingEntity) getShooter(); + } + + @Deprecated + public void _INVALID_setShooter(LivingEntity shooter) { + setShooter(shooter); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftFlying.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftFlying.java new file mode 100644 index 0000000..f374c7b --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftFlying.java @@ -0,0 +1,22 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityFlying; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.Flying; + +public class CraftFlying extends CraftLivingEntity implements Flying { + + public CraftFlying(CraftServer server, EntityFlying entity) { + super(server, entity); + } + + @Override + public EntityFlying getHandle() { + return (EntityFlying) entity; + } + + @Override + public String toString() { + return "CraftFlying"; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftGhast.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftGhast.java new file mode 100644 index 0000000..c661673 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftGhast.java @@ -0,0 +1,27 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityGhast; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Ghast; + +public class CraftGhast extends CraftFlying implements Ghast { + + public CraftGhast(CraftServer server, EntityGhast entity) { + super(server, entity); + } + + @Override + public EntityGhast getHandle() { + return (EntityGhast) entity; + } + + @Override + public String toString() { + return "CraftGhast"; + } + + public EntityType getType() { + return EntityType.GHAST; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftGiant.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftGiant.java new file mode 100644 index 0000000..8e27e7b --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftGiant.java @@ -0,0 +1,27 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityGiantZombie; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Giant; + +public class CraftGiant extends CraftMonster implements Giant { + + public CraftGiant(CraftServer server, EntityGiantZombie entity) { + super(server, entity); + } + + @Override + public EntityGiantZombie getHandle() { + return (EntityGiantZombie) entity; + } + + @Override + public String toString() { + return "CraftGiant"; + } + + public EntityType getType() { + return EntityType.GIANT; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftGolem.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftGolem.java new file mode 100644 index 0000000..1fef5e0 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftGolem.java @@ -0,0 +1,21 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityGolem; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.Golem; + +public class CraftGolem extends CraftCreature implements Golem { + public CraftGolem(CraftServer server, EntityGolem entity) { + super(server, entity); + } + + @Override + public EntityGolem getHandle() { + return (EntityGolem) entity; + } + + @Override + public String toString() { + return "CraftGolem"; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftGuardian.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftGuardian.java new file mode 100644 index 0000000..3a0ce67 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftGuardian.java @@ -0,0 +1,56 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityGuardian; +import net.minecraft.server.GenericAttributes; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Guardian; + +public class CraftGuardian extends CraftMonster implements Guardian { + + public CraftGuardian(CraftServer server, EntityGuardian entity) { + super(server, entity); + } + + @Override + public String toString() { + return "CraftGuardian"; + } + + @Override + public EntityType getType() { + return EntityType.GUARDIAN; + } + + @Override + public boolean isElder() { + return ((EntityGuardian)entity).isElder(); + } + + @Override + public void setElder( boolean shouldBeElder ) { + EntityGuardian entityGuardian = (EntityGuardian) entity; + + if (!isElder() && shouldBeElder) { + entityGuardian.setElder(true); + } else if (isElder() && !shouldBeElder) { + entityGuardian.setElder(false); + + // Since minecraft does not reset the elder Guardian to a guardian we have to do that + entity.setSize(0.85F, 0.85F); + + // Since aW() calls its supers it will try to re register attributes which is invalid + // check these on update + entityGuardian.getAttributeInstance(GenericAttributes.ATTACK_DAMAGE).setValue(6.0D); + entityGuardian.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).setValue(0.5D); + entityGuardian.getAttributeInstance(GenericAttributes.FOLLOW_RANGE).setValue(16.0D); + entityGuardian.getAttributeInstance(GenericAttributes.maxHealth).setValue(30.0D); + + // Update pathfinding (random stroll back to 80) + entityGuardian.goalRandomStroll.setTimeBetweenMovement(80); + + // Tell minecraft that we need persistence since the guardian changed + entityGuardian.initAttributes(); + } + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftHanging.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftHanging.java new file mode 100644 index 0000000..f36e7ee --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftHanging.java @@ -0,0 +1,78 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityHanging; +import net.minecraft.server.EnumDirection; +import org.bukkit.block.BlockFace; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Hanging; + +public class CraftHanging extends CraftEntity implements Hanging { + public CraftHanging(CraftServer server, EntityHanging entity) { + super(server, entity); + } + + public BlockFace getAttachedFace() { + return getFacing().getOppositeFace(); + } + + public void setFacingDirection(BlockFace face) { + setFacingDirection(face, false); + } + + public boolean setFacingDirection(BlockFace face, boolean force) { + EntityHanging hanging = getHandle(); + EnumDirection dir = hanging.direction; + switch (face) { + case SOUTH: + default: + getHandle().setDirection(EnumDirection.SOUTH); + break; + case WEST: + getHandle().setDirection(EnumDirection.WEST); + break; + case NORTH: + getHandle().setDirection(EnumDirection.NORTH); + break; + case EAST: + getHandle().setDirection(EnumDirection.EAST); + break; + } + if (!force && !hanging.survives()) { + // Revert since it doesn't fit + hanging.setDirection(dir); + return false; + } + return true; + } + + public BlockFace getFacing() { + EnumDirection direction = this.getHandle().direction; + if (direction == null) return BlockFace.SELF; + switch (direction) { + case SOUTH: + default: + return BlockFace.SOUTH; + case WEST: + return BlockFace.WEST; + case NORTH: + return BlockFace.NORTH; + case EAST: + return BlockFace.EAST; + } + } + + @Override + public EntityHanging getHandle() { + return (EntityHanging) entity; + } + + @Override + public String toString() { + return "CraftHanging"; + } + + public EntityType getType() { + return EntityType.UNKNOWN; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftHorse.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftHorse.java new file mode 100644 index 0000000..7dfd3f9 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftHorse.java @@ -0,0 +1,147 @@ +package org.bukkit.craftbukkit.entity; + +import com.eatthepath.uuid.FastUUID; +import net.minecraft.server.EntityHorse; +import org.apache.commons.lang.Validate; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.inventory.CraftInventoryHorse; +import org.bukkit.entity.AnimalTamer; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Horse; +import org.bukkit.inventory.HorseInventory; + +import java.util.UUID; + +public class CraftHorse extends CraftAnimals implements Horse { + + public CraftHorse(CraftServer server, EntityHorse entity) { + super(server, entity); + } + + @Override + public EntityHorse getHandle() { + return (EntityHorse) entity; + } + + public Variant getVariant() { + return Variant.values()[getHandle().getType()]; + } + + public void setVariant(Variant variant) { + Validate.notNull(variant, "Variant cannot be null"); + getHandle().setType(variant.ordinal()); + } + + public Color getColor() { + return Color.values()[getHandle().getVariant() & 0xFF]; + } + + public void setColor(Color color) { + Validate.notNull(color, "Color cannot be null"); + getHandle().setVariant(color.ordinal() & 0xFF | getStyle().ordinal() << 8); + } + + public Style getStyle() { + return Style.values()[getHandle().getVariant() >>> 8]; + } + + public void setStyle(Style style) { + Validate.notNull(style, "Style cannot be null"); + getHandle().setVariant(getColor().ordinal() & 0xFF | style.ordinal() << 8); + } + + public boolean isCarryingChest() { + return getHandle().hasChest(); + } + + public void setCarryingChest(boolean chest) { + if (chest == isCarryingChest()) return; + getHandle().setHasChest(chest); + getHandle().loadChest(); + } + + public int getDomestication() { + return getHandle().getTemper(); + } + + public void setDomestication(int value) { + Validate.isTrue(value >= 0, "Domestication cannot be less than zero"); + Validate.isTrue(value <= getMaxDomestication(), "Domestication cannot be greater than the max domestication"); + getHandle().setTemper(value); + } + + public int getMaxDomestication() { + return getHandle().getMaxDomestication(); + } + + public void setMaxDomestication(int value) { + Validate.isTrue(value > 0, "Max domestication cannot be zero or less"); + getHandle().maxDomestication = value; + } + + public double getJumpStrength() { + return getHandle().getJumpStrength(); + } + + public void setJumpStrength(double strength) { + Validate.isTrue(strength >= 0, "Jump strength cannot be less than zero"); + getHandle().getAttributeInstance(EntityHorse.attributeJumpStrength).setValue(strength); + } + + @Override + public boolean isTamed() { + return getHandle().isTame(); + } + + @Override + public void setTamed(boolean tamed) { + getHandle().setTame(tamed); + } + + @Override + public AnimalTamer getOwner() { + if (getOwnerUUID() == null) return null; + return getServer().getOfflinePlayer(getOwnerUUID()); + } + + @Override + public void setOwner(AnimalTamer owner) { + if (owner != null) { + setTamed(true); + getHandle().setGoalTarget(null, null, false); + setOwnerUUID(owner.getUniqueId()); + } else { + setTamed(false); + setOwnerUUID(null); + } + } + + public UUID getOwnerUUID() { + try { + return FastUUID.parseUUID(getHandle().getOwnerUUID()); + } catch (IllegalArgumentException ex) { + return null; + } + } + + public void setOwnerUUID(UUID uuid) { + if (uuid == null) { + getHandle().setOwnerUUID(""); + } else { + getHandle().setOwnerUUID(FastUUID.toString(uuid)); + } + } + + public HorseInventory getInventory() { + return new CraftInventoryHorse(getHandle().inventoryChest); + } + + @Override + public String toString() { + return "CraftHorse{variant=" + getVariant() + ", owner=" + getOwner() + '}'; + } + + public EntityType getType() { + return EntityType.HORSE; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftHumanEntity.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftHumanEntity.java new file mode 100644 index 0000000..3de6333 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftHumanEntity.java @@ -0,0 +1,366 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.*; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.event.CraftEventFactory; +import org.bukkit.craftbukkit.inventory.*; +import org.bukkit.entity.HumanEntity; +import org.bukkit.event.inventory.InventoryType; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.PlayerInventory; +import org.bukkit.inventory.*; +import org.bukkit.permissions.PermissibleBase; +import org.bukkit.permissions.Permission; +import org.bukkit.permissions.PermissionAttachment; +import org.bukkit.permissions.PermissionAttachmentInfo; +import org.bukkit.plugin.Plugin; + +import java.util.Set; + +public class CraftHumanEntity extends CraftLivingEntity implements HumanEntity { + private CraftInventoryPlayer inventory; + private final CraftInventory enderChest; + protected final PermissibleBase perm = new PermissibleBase(this); + private boolean op; + private GameMode mode; + + public CraftHumanEntity(final CraftServer server, final EntityHuman entity) { + super(server, entity); + mode = server.getDefaultGameMode(); + this.inventory = new CraftInventoryPlayer(entity.inventory); + enderChest = new CraftInventory(entity.getEnderChest()); + } + + public String getName() { + return getHandle().getName(); + } + + public PlayerInventory getInventory() { + return inventory; + } + + public EntityEquipment getEquipment() { + return inventory; + } + + public Inventory getEnderChest() { + return enderChest; + } + + public ItemStack getItemInHand() { + return getInventory().getItemInHand(); + } + + public void setItemInHand(ItemStack item) { + getInventory().setItemInHand(item); + } + + public ItemStack getItemOnCursor() { + return CraftItemStack.asCraftMirror(getHandle().inventory.getCarried()); + } + + public void setItemOnCursor(ItemStack item) { + net.minecraft.server.ItemStack stack = CraftItemStack.asNMSCopy(item); + getHandle().inventory.setCarried(stack); + if (this instanceof CraftPlayer) { + ((EntityPlayer) getHandle()).broadcastCarriedItem(); // Send set slot for cursor + } + } + + public boolean isSleeping() { + return getHandle().sleeping; + } + + public int getSleepTicks() { + return getHandle().sleepTicks; + } + + public boolean isOp() { + return this.op; + } + + public boolean isPermissionSet(String name) { + return this.perm.isPermissionSet(name); + } + + public boolean isPermissionSet(Permission perm) { + return this.perm.isPermissionSet(perm); + } + + public boolean hasPermission(String name) { + return this.perm.hasPermission(name); + } + + public boolean hasPermission(Permission perm) { + return this.perm.hasPermission(perm); + } + + public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value) { + return this.perm.addAttachment(plugin, name, value); + } + + public PermissionAttachment addAttachment(Plugin plugin) { + return this.perm.addAttachment(plugin); + } + + public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value, int ticks) { + return this.perm.addAttachment(plugin, name, value, ticks); + } + + public PermissionAttachment addAttachment(Plugin plugin, int ticks) { + return this.perm.addAttachment(plugin, ticks); + } + + public void removeAttachment(PermissionAttachment attachment) { + this.perm.removeAttachment(attachment); + } + + public void recalculatePermissions() { + this.perm.recalculatePermissions(); + } + + public void setOp(boolean value) { + this.op = value; + this.perm.recalculatePermissions(); + } + + public Set getEffectivePermissions() { + return this.perm.getEffectivePermissions(); + } + + public GameMode getGameMode() { + return mode; + } + + public void setGameMode(GameMode mode) { + if (mode == null) { + throw new IllegalArgumentException("Mode cannot be null"); + } + + this.mode = mode; + } + + @Override + public EntityHuman getHandle() { + return (EntityHuman) entity; + } + + public void setHandle(final EntityHuman entity) { + super.setHandle(entity); + this.inventory = new CraftInventoryPlayer(entity.inventory); + } + + @Override + public String toString() { + return "CraftHumanEntity{" + "id=" + getEntityId() + "name=" + getName() + '}'; + } + + public InventoryView getOpenInventory() { + return getHandle().activeContainer.getBukkitView(); + } + + public InventoryView openInventory(Inventory inventory) { + if(!(getHandle() instanceof EntityPlayer)) return null; + EntityPlayer player = (EntityPlayer) getHandle(); + InventoryType type = inventory.getType(); + Container formerContainer = getHandle().activeContainer; + + IInventory iinventory = (inventory instanceof CraftInventory) ? ((CraftInventory) inventory).getInventory() : new org.bukkit.craftbukkit.inventory.InventoryWrapper(inventory); + + switch (type) { + case PLAYER: + case CHEST: + case ENDER_CHEST: + getHandle().openContainer(iinventory); + break; + case DISPENSER: + if (iinventory instanceof TileEntityDispenser) { + getHandle().openContainer(iinventory); + } else { + openCustomInventory(inventory, player, "minecraft:dispenser"); + } + break; + case DROPPER: + if (iinventory instanceof TileEntityDropper) { + getHandle().openContainer(iinventory); + } else { + openCustomInventory(inventory, player, "minecraft:dropper"); + } + break; + case FURNACE: + if (iinventory instanceof TileEntityFurnace) { + getHandle().openContainer(iinventory); + } else { + openCustomInventory(inventory, player, "minecraft:furnace"); + } + break; + case WORKBENCH: + openCustomInventory(inventory, player, "minecraft:crafting_table"); + break; + case BREWING: + if (iinventory instanceof TileEntityBrewingStand) { + getHandle().openContainer(iinventory); + } else { + openCustomInventory(inventory, player, "minecraft:brewing_stand"); + } + break; + case ENCHANTING: + openCustomInventory(inventory, player, "minecraft:enchanting_table"); + break; + case HOPPER: + if (iinventory instanceof TileEntityHopper) { + getHandle().openContainer(iinventory); + } else if (iinventory instanceof EntityMinecartHopper) { + getHandle().openContainer(iinventory); + } else { + openCustomInventory(inventory, player, "minecraft:hopper"); + } + break; + case BEACON: + if (iinventory instanceof TileEntityBeacon) { + getHandle().openContainer(iinventory); + } else { + openCustomInventory(inventory, player, "minecraft:beacon"); + } + break; + case ANVIL: + if (iinventory instanceof BlockAnvil.TileEntityContainerAnvil) { + getHandle().openTileEntity((BlockAnvil.TileEntityContainerAnvil) iinventory); + } else { + openCustomInventory(inventory, player, "minecraft:anvil"); + } + break; + case CREATIVE: + case CRAFTING: + throw new IllegalArgumentException("Can't open a " + type + " inventory!"); + } + if (getHandle().activeContainer == formerContainer) { + return null; + } + getHandle().activeContainer.checkReachable = false; + return getHandle().activeContainer.getBukkitView(); + } + + private void openCustomInventory(Inventory inventory, EntityPlayer player, String windowType) { + if (player.playerConnection == null) return; + Container container = new CraftContainer(inventory, this, player.nextContainerCounter()); + + container = CraftEventFactory.callInventoryOpenEvent(player, container); + if(container == null) return; + + String title = container.getBukkitView().getTitle(); + int size = container.getBukkitView().getTopInventory().getSize(); + + // Special cases + if (windowType.equals("minecraft:crafting_table") + || windowType.equals("minecraft:anvil") + || windowType.equals("minecraft:enchanting_table") + ) { + size = 0; + } + + player.playerConnection.sendPacket(new PacketPlayOutOpenWindow(container.windowId, windowType, new ChatComponentText(title), size)); + + // Beanes - update slots to latest + // Without this you get + // - Window items + // - Set slot (removed with this patch) + // even though the window items cover everything + container.updateSlotsToLatest(); + + getHandle().activeContainer = container; + getHandle().activeContainer.addSlotListener(player); + } + + public InventoryView openWorkbench(Location location, boolean force) { + if (!force) { + Block block = location.getBlock(); + if (block.getType() != Material.WORKBENCH) { + return null; + } + } + if (location == null) { + location = getLocation(); + } + getHandle().openTileEntity(new BlockWorkbench.TileEntityContainerWorkbench(getHandle().world, new BlockPosition(location.getBlockX(), location.getBlockY(), location.getBlockZ()))); + if (force) { + getHandle().activeContainer.checkReachable = false; + } + return getHandle().activeContainer.getBukkitView(); + } + + public InventoryView openEnchanting(Location location, boolean force) { + if (!force) { + Block block = location.getBlock(); + if (block.getType() != Material.ENCHANTMENT_TABLE) { + return null; + } + } + if (location == null) { + location = getLocation(); + } + + // If there isn't an enchant table we can force create one, won't be very useful though. + TileEntity container = getHandle().world.getTileEntity(new BlockPosition(location.getBlockX(), location.getBlockY(), location.getBlockZ())); + if (container == null && force) { + container = new TileEntityEnchantTable(); + } + getHandle().openTileEntity((ITileEntityContainer) container); + + if (force) { + getHandle().activeContainer.checkReachable = false; + } + return getHandle().activeContainer.getBukkitView(); + } + + public void openInventory(InventoryView inventory) { + if (!(getHandle() instanceof EntityPlayer)) return; // TODO: NPC support? + if (((EntityPlayer) getHandle()).playerConnection == null) return; + if (getHandle().activeContainer != getHandle().defaultContainer) { + // fire INVENTORY_CLOSE if one already open + ((EntityPlayer)getHandle()).playerConnection.a(new PacketPlayInCloseWindow(getHandle().activeContainer.windowId)); + } + EntityPlayer player = (EntityPlayer) getHandle(); + Container container; + if (inventory instanceof CraftInventoryView) { + container = ((CraftInventoryView) inventory).getHandle(); + } else { + container = new CraftContainer(inventory, player.nextContainerCounter()); + } + + // Trigger an INVENTORY_OPEN event + container = CraftEventFactory.callInventoryOpenEvent(player, container); + if (container == null) { + return; + } + + // Now open the window + InventoryType type = inventory.getType(); + String windowType = CraftContainer.getNotchInventoryType(type); + String title = inventory.getTitle(); + int size = inventory.getTopInventory().getSize(); + player.playerConnection.sendPacket(new PacketPlayOutOpenWindow(container.windowId, windowType, new ChatComponentText(title), size)); + player.activeContainer = container; + player.activeContainer.addSlotListener(player); + } + + public void closeInventory() { + getHandle().closeInventory(); + } + + public boolean isBlocking() { + return getHandle().isBlocking(); + } + + public boolean setWindowProperty(InventoryView.Property prop, int value) { + return false; + } + + public int getExpToLevel() { + return getHandle().getExpToLevel(); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftIronGolem.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftIronGolem.java new file mode 100644 index 0000000..ddee207 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftIronGolem.java @@ -0,0 +1,35 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityIronGolem; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.IronGolem; + +public class CraftIronGolem extends CraftGolem implements IronGolem { + public CraftIronGolem(CraftServer server, EntityIronGolem entity) { + super(server, entity); + } + + @Override + public EntityIronGolem getHandle() { + return (EntityIronGolem) entity; + } + + @Override + public String toString() { + return "CraftIronGolem"; + } + + public boolean isPlayerCreated() { + return getHandle().isPlayerCreated(); + } + + public void setPlayerCreated(boolean playerCreated) { + getHandle().setPlayerCreated(playerCreated); + } + + @Override + public EntityType getType() { + return EntityType.IRON_GOLEM; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftItem.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftItem.java new file mode 100644 index 0000000..22d2cb5 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftItem.java @@ -0,0 +1,55 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.Entity; +import net.minecraft.server.EntityItem; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Item; +import org.bukkit.inventory.ItemStack; + +public class CraftItem extends CraftEntity implements Item { + private final EntityItem item; + + public CraftItem(CraftServer server, Entity entity, EntityItem item) { + super(server, entity); + this.item = item; + } + + public CraftItem(CraftServer server, EntityItem entity) { + this(server, entity, entity); + } + + public ItemStack getItemStack() { + return CraftItemStack.asCraftMirror(item.getItemStack()); + } + + public void setItemStack(ItemStack stack) { + item.setItemStack(CraftItemStack.asNMSCopy(stack)); + } + + public int getPickupDelay() { + return item.pickupDelay; + } + + public void setPickupDelay(int delay) { + item.pickupDelay = Math.min(delay, Short.MAX_VALUE); + } + + @Override + public String toString() { + return "CraftItem"; + } + + public EntityType getType() { + return EntityType.DROPPED_ITEM; + } + + public org.bukkit.entity.Entity getOwner() { + return (this.item.owner == null) ? null : this.item.owner.getBukkitEntity(); + } + + public void setOwner(org.bukkit.entity.Entity entity) { + this.item.owner = ((CraftEntity)entity).getHandle(); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftItemFrame.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftItemFrame.java new file mode 100644 index 0000000..acb8670 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftItemFrame.java @@ -0,0 +1,127 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.*; +import org.apache.commons.lang.Validate; +import org.bukkit.Rotation; +import org.bukkit.block.BlockFace; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.CraftWorld; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.ItemFrame; + +public class CraftItemFrame extends CraftHanging implements ItemFrame { + public CraftItemFrame(CraftServer server, EntityItemFrame entity) { + super(server, entity); + } + + public boolean setFacingDirection(BlockFace face, boolean force) { + if (!super.setFacingDirection(face, force)) { + return false; + } + + update(); + + return true; + } + + private void update() { + EntityItemFrame old = this.getHandle(); + + WorldServer world = ((CraftWorld) getWorld()).getHandle(); + BlockPosition position = old.getBlockPosition(); + EnumDirection direction = old.getDirection(); + ItemStack item = old.getItem() != null ? old.getItem().cloneItemStack() : null; + + old.die(); + + EntityItemFrame frame = new EntityItemFrame(world,position,direction); + frame.setItem(item); + world.addEntity(frame); + this.entity = frame; + } + + + public void setItem(org.bukkit.inventory.ItemStack item) { + if (item == null || item.getTypeId() == 0) { + getHandle().setItem(null); + } else { + getHandle().setItem(CraftItemStack.asNMSCopy(item)); + } + } + + public org.bukkit.inventory.ItemStack getItem() { + return CraftItemStack.asBukkitCopy(getHandle().getItem()); + } + + public Rotation getRotation() { + return toBukkitRotation(getHandle().getRotation()); + } + + Rotation toBukkitRotation(int value) { + // Translate NMS rotation integer to Bukkit API + switch (value) { + case 0: + return Rotation.NONE; + case 1: + return Rotation.CLOCKWISE_45; + case 2: + return Rotation.CLOCKWISE; + case 3: + return Rotation.CLOCKWISE_135; + case 4: + return Rotation.FLIPPED; + case 5: + return Rotation.FLIPPED_45; + case 6: + return Rotation.COUNTER_CLOCKWISE; + case 7: + return Rotation.COUNTER_CLOCKWISE_45; + default: + throw new AssertionError("Unknown rotation " + value + " for " + getHandle()); + } + } + + public void setRotation(Rotation rotation) { + Validate.notNull(rotation, "Rotation cannot be null"); + getHandle().setRotation(toInteger(rotation)); + } + + static int toInteger(Rotation rotation) { + // Translate Bukkit API rotation to NMS integer + switch (rotation) { + case NONE: + return 0; + case CLOCKWISE_45: + return 1; + case CLOCKWISE: + return 2; + case CLOCKWISE_135: + return 3; + case FLIPPED: + return 4; + case FLIPPED_45: + return 5; + case COUNTER_CLOCKWISE: + return 6; + case COUNTER_CLOCKWISE_45: + return 7; + default: + throw new IllegalArgumentException(rotation + " is not applicable to an ItemFrame"); + } + } + + @Override + public EntityItemFrame getHandle() { + return (EntityItemFrame) entity; + } + + @Override + public String toString() { + return "CraftItemFrame{item=" + getItem() + ", rotation=" + getRotation() + "}"; + } + + public EntityType getType() { + return EntityType.ITEM_FRAME; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftLargeFireball.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftLargeFireball.java new file mode 100644 index 0000000..ca03794 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftLargeFireball.java @@ -0,0 +1,32 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityLargeFireball; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.LargeFireball; + +public class CraftLargeFireball extends CraftFireball implements LargeFireball { + public CraftLargeFireball(CraftServer server, EntityLargeFireball entity) { + super(server, entity); + } + + @Override + public void setYield(float yield) { + super.setYield(yield); + getHandle().yield = (int) yield; + } + + @Override + public EntityLargeFireball getHandle() { + return (EntityLargeFireball) entity; + } + + @Override + public String toString() { + return "CraftLargeFireball"; + } + + public EntityType getType() { + return EntityType.FIREBALL; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftLeash.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftLeash.java new file mode 100644 index 0000000..1959a1a --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftLeash.java @@ -0,0 +1,26 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityLeash; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.LeashHitch; + +public class CraftLeash extends CraftHanging implements LeashHitch { + public CraftLeash(CraftServer server, EntityLeash entity) { + super(server, entity); + } + + @Override + public EntityLeash getHandle() { + return (EntityLeash) entity; + } + + @Override + public String toString() { + return "CraftLeash"; + } + + public EntityType getType() { + return EntityType.LEASH_HITCH; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftLightningStrike.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftLightningStrike.java new file mode 100644 index 0000000..0bacc83 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftLightningStrike.java @@ -0,0 +1,46 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityLightning; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.LightningStrike; + +public class CraftLightningStrike extends CraftEntity implements LightningStrike { + public CraftLightningStrike(final CraftServer server, final EntityLightning entity) { + super(server, entity); + } + + public boolean isEffect() { + return ((EntityLightning) super.getHandle()).isEffect; + } + + @Override + public EntityLightning getHandle() { + return (EntityLightning) entity; + } + + @Override + public String toString() { + return "CraftLightningStrike"; + } + + public EntityType getType() { + return EntityType.LIGHTNING; + } + + // Spigot start + private final LightningStrike.Spigot spigot = new LightningStrike.Spigot() { + + @Override + public boolean isSilent() + { + return getHandle().isSilent; + } + }; + + @Override + public LightningStrike.Spigot spigot() { + return spigot; + } + // Spigot end +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftLivingEntity.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftLivingEntity.java new file mode 100644 index 0000000..4aad6e6 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftLivingEntity.java @@ -0,0 +1,474 @@ +package org.bukkit.craftbukkit.entity; + +import dev.azurite.spigot.configs.AzuriteConfig; +import net.minecraft.server.*; +import org.apache.commons.lang.Validate; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.CraftWorld; +import org.bukkit.craftbukkit.inventory.CraftEntityEquipment; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.entity.Entity; +import org.bukkit.entity.*; +import org.bukkit.event.entity.PotionEffectAddEvent; +import org.bukkit.event.player.PlayerTeleportEvent; +import org.bukkit.inventory.EntityEquipment; +import org.bukkit.inventory.ItemStack; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.util.BlockIterator; +import org.bukkit.util.NumberConversions; +import org.bukkit.util.Vector; + +import java.util.*; + +public class CraftLivingEntity extends CraftEntity implements LivingEntity { + private CraftEntityEquipment equipment; + + public CraftLivingEntity(final CraftServer server, final EntityLiving entity) { + super(server, entity); + + if (entity instanceof EntityInsentient || entity instanceof EntityArmorStand) { + equipment = new CraftEntityEquipment(this); + } + } + + public double getHealth() { + return Math.min(Math.max(0, getHandle().getHealth()), getMaxHealth()); + } + + public void setHealth(double health) { + if (health < 0.0D || health > getMaxHealth()) + throw new IllegalArgumentException("Health must be between 0 and " + getMaxHealth() + ", but was " + health + ". (attribute base value: " + + getHandle().getAttributeInstance(GenericAttributes.maxHealth).b() + ((this instanceof CraftPlayer) ? (", player: " + + getName() + ')') : Character.valueOf(')'))); + + boolean die = this.entity instanceof EntityPlayer && health == 0.0D; + + // Azurite - auto respawn needs the order of this to be changed + if (AzuriteConfig.autoRespawnPlayer.getValue()) { + getHandle().setHealth((float) health); + if (die) { + ((EntityPlayer) this.entity).die(DamageSource.GENERIC); + } + } else { + if (die) { + ((EntityPlayer) this.entity).die(DamageSource.GENERIC); + } + getHandle().setHealth((float) health); + } + } + + public double getMaxHealth() { + return getHandle().getMaxHealth(); + } + + public void setMaxHealth(double amount) { + Validate.isTrue(amount > 0, "Max health must be greater than 0"); + + getHandle().getAttributeInstance(GenericAttributes.maxHealth).setValue(amount); + + if (getHealth() > amount) { + setHealth(amount); + } + } + + public void resetMaxHealth() { + setMaxHealth(getHandle().getMaxHealth()); + } + + @Deprecated + public Egg throwEgg() { + return launchProjectile(Egg.class); + } + + @Deprecated + public Snowball throwSnowball() { + return launchProjectile(Snowball.class); + } + + public double getEyeHeight() { + return getHandle().getHeadHeight(); + } + + public double getEyeHeight(boolean ignoreSneaking) { + return getEyeHeight(); + } + + private List getLineOfSight(HashSet transparent, int maxDistance, int maxLength) { + if (maxDistance > 120) { + maxDistance = 120; + } + ArrayList blocks = new ArrayList<>(); + Iterator itr = new BlockIterator(this, maxDistance); + while (itr.hasNext()) { + Block block = itr.next(); + blocks.add(block); + if (maxLength != 0 && blocks.size() > maxLength) { + blocks.remove(0); + } + int id = block.getTypeId(); + if (transparent == null) { + if (id != 0) { + break; + } + } else { + if (!transparent.contains((byte) id)) { + break; + } + } + } + return blocks; + } + + private List getLineOfSight(Set transparent, int maxDistance, int maxLength) { + if (maxDistance > 120) { + maxDistance = 120; + } + ArrayList blocks = new ArrayList<>(); + Iterator itr = new BlockIterator(this, maxDistance); + while (itr.hasNext()) { + Block block = itr.next(); + blocks.add(block); + if (maxLength != 0 && blocks.size() > maxLength) { + blocks.remove(0); + } + Material material = block.getType(); + if (transparent == null) { + if (!material.equals(Material.AIR)) { + break; + } + } else { + if (!transparent.contains(material)) { + break; + } + } + } + return blocks; + } + + public List getLineOfSight(HashSet transparent, int maxDistance) { + return getLineOfSight(transparent, maxDistance, 0); + } + + public List getLineOfSight(Set transparent, int maxDistance) { + return getLineOfSight(transparent, maxDistance, 0); + } + + public Block getTargetBlock(HashSet transparent, int maxDistance) { + List blocks = getLineOfSight(transparent, maxDistance, 1); + return blocks.get(0); + } + + public Block getTargetBlock(Set transparent, int maxDistance) { + List blocks = getLineOfSight(transparent, maxDistance, 1); + return blocks.get(0); + } + + public List getLastTwoTargetBlocks(HashSet transparent, int maxDistance) { + return getLineOfSight(transparent, maxDistance, 2); + } + + public List getLastTwoTargetBlocks(Set transparent, int maxDistance) { + return getLineOfSight(transparent, maxDistance, 2); + } + + @Deprecated + public Arrow shootArrow() { + return launchProjectile(Arrow.class); + } + + public int getRemainingAir() { + return getHandle().getAirTicks(); + } + + public void setRemainingAir(int ticks) { + getHandle().setAirTicks(ticks); + } + + public int getMaximumAir() { + return getHandle().maxAirTicks; + } + + public void setMaximumAir(int ticks) { + getHandle().maxAirTicks = ticks; + } + + public void damage(double amount) { + damage(amount, null); + } + + public void damage(double amount, org.bukkit.entity.Entity source) { + DamageSource reason = DamageSource.GENERIC; + + if (source instanceof HumanEntity) { + reason = DamageSource.playerAttack(((CraftHumanEntity) source).getHandle()); + } else if (source instanceof LivingEntity) { + reason = DamageSource.mobAttack(((CraftLivingEntity) source).getHandle()); + } + + entity.damageEntity(reason, (float) amount); + } + + public Location getEyeLocation() { + Location loc = getLocation(); + loc.setY(loc.getY() + getEyeHeight()); + return loc; + } + + public int getMaximumNoDamageTicks() { + return getHandle().maxNoDamageTicks; + } + + public void setMaximumNoDamageTicks(int ticks) { + getHandle().maxNoDamageTicks = ticks; + } + + public double getLastDamage() { + return getHandle().lastDamage; + } + + public void setLastDamage(double damage) { + getHandle().lastDamage = (float) damage; + } + + public int getNoDamageTicks() { + return getHandle().noDamageTicks; + } + + public void setNoDamageTicks(int ticks) { + getHandle().noDamageTicks = ticks; + getHandle().noDamageTime = System.currentTimeMillis() + (ticks * 50L); // Beanes - no damage time + } + + @Override + public EntityLiving getHandle() { + return (EntityLiving) entity; + } + + public void setHandle(final EntityLiving entity) { + super.setHandle(entity); + } + + @Override + public String toString() { + return "CraftLivingEntity{" + "id=" + getEntityId() + '}'; + } + + public Player getKiller() { + return getHandle().killer == null ? null : (Player) getHandle().killer.getBukkitEntity(); + } + + public boolean addPotionEffect(PotionEffect effect) { + return addPotionEffect(effect, false); + } + + public boolean addPotionEffect(PotionEffect effect, boolean force) { + return addPotionEffect(effect, force, PotionEffectAddEvent.EffectCause.PLUGIN); + } + + public boolean addPotionEffect(PotionEffect effect, boolean force, PotionEffectAddEvent.EffectCause cause) { + if (hasPotionEffect(effect.getType())) { + if (!force) + return false; + removePotionEffect(effect.getType()); + } + getHandle().addEffect(new MobEffect(effect.getType().getId(), effect.getDuration(), effect.getAmplifier(), effect.isAmbient(), effect.hasParticles()), cause); + return true; + } + + public boolean addPotionEffects(Collection effects) { + boolean success = true; + for (PotionEffect effect : effects) + success &= addPotionEffect(effect); + return success; + } + + public boolean hasPotionEffect(PotionEffectType type) { + return getHandle().hasEffect(MobEffectList.byId[type.getId()]); + } + + public void removePotionEffect(PotionEffectType type) { + getHandle().removeEffect(type.getId()); + } + + public Collection getActivePotionEffects() { + List effects = new ArrayList<>(); + for (MobEffect handle : getHandle().effects.values()) { + effects.add(new PotionEffect(PotionEffectType.getById(handle.getEffectId()), handle.getDuration(), handle.getAmplifier(), handle.isAmbient(), handle.isShowParticles())); + } + return effects; + } + + public T launchProjectile(Class projectile) { + return launchProjectile(projectile, null); + } + + @SuppressWarnings("unchecked") + public T launchProjectile(Class projectile, Vector velocity) { + net.minecraft.server.World world = ((CraftWorld) getWorld()).getHandle(); + net.minecraft.server.Entity launch = null; + + if (Snowball.class.isAssignableFrom(projectile)) { + launch = new EntitySnowball(world, getHandle()); + } else if (Egg.class.isAssignableFrom(projectile)) { + launch = new EntityEgg(world, getHandle()); + } else if (EnderPearl.class.isAssignableFrom(projectile)) { + launch = new EntityEnderPearl(world, getHandle()); + } else if (Arrow.class.isAssignableFrom(projectile)) { + launch = new EntityArrow(world, getHandle(), 1); + } else if (ThrownPotion.class.isAssignableFrom(projectile)) { + launch = new EntityPotion(world, getHandle(), CraftItemStack.asNMSCopy(new ItemStack(Material.POTION, 1))); + } else if (ThrownExpBottle.class.isAssignableFrom(projectile)) { + launch = new EntityThrownExpBottle(world, getHandle()); + } else if (Fish.class.isAssignableFrom(projectile) && getHandle() instanceof EntityHuman) { + launch = new EntityFishingHook(world, (EntityHuman) getHandle()); + } else if (Fireball.class.isAssignableFrom(projectile)) { + Location location = getEyeLocation(); + Vector direction = location.getDirection().multiply(10); + + if (SmallFireball.class.isAssignableFrom(projectile)) { + launch = new EntitySmallFireball(world, getHandle(), direction.getX(), direction.getY(), direction.getZ()); + } else if (WitherSkull.class.isAssignableFrom(projectile)) { + launch = new EntityWitherSkull(world, getHandle(), direction.getX(), direction.getY(), direction.getZ()); + } else { + launch = new EntityLargeFireball(world, getHandle(), direction.getX(), direction.getY(), direction.getZ()); + } + + launch.projectileSource = this; + launch.setPositionRotation(location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch()); + } + + Validate.notNull(launch, "Projectile not supported"); + + if (velocity != null) { + ((T) launch.getBukkitEntity()).setVelocity(velocity); + } + + world.addEntity(launch); + return (T) launch.getBukkitEntity(); + } + + public EntityType getType() { + return EntityType.UNKNOWN; + } + + public boolean hasLineOfSight(Entity other) { + return getHandle().hasLineOfSight(((CraftEntity) other).getHandle()); + } + + public boolean getRemoveWhenFarAway() { + return getHandle() instanceof EntityInsentient && !((EntityInsentient) getHandle()).persistent; + } + + public void setRemoveWhenFarAway(boolean remove) { + if (getHandle() instanceof EntityInsentient) { + ((EntityInsentient) getHandle()).persistent = !remove; + } + } + + public EntityEquipment getEquipment() { + return equipment; + } + + public void setCanPickupItems(boolean pickup) { + if (getHandle() instanceof EntityInsentient) { + ((EntityInsentient) getHandle()).canPickUpLoot = pickup; + } + } + + public boolean getCanPickupItems() { + return getHandle() instanceof EntityInsentient && ((EntityInsentient) getHandle()).canPickUpLoot; + } + + @Override + public boolean teleport(Location location, PlayerTeleportEvent.TeleportCause cause) { + if (getHealth() == 0) { + return false; + } + + return super.teleport(location, cause); + } + + public boolean isLeashed() { + if (!(getHandle() instanceof EntityInsentient)) { + return false; + } + return ((EntityInsentient) getHandle()).getLeashHolder() != null; + } + + public Entity getLeashHolder() throws IllegalStateException { + if (!isLeashed()) { + throw new IllegalStateException("Entity not leashed"); + } + return ((EntityInsentient) getHandle()).getLeashHolder().getBukkitEntity(); + } + + private boolean unleash() { + if (!isLeashed()) { + return false; + } + ((EntityInsentient) getHandle()).unleash(true, false); + return true; + } + + public boolean setLeashHolder(Entity holder) { + if ((getHandle() instanceof EntityWither) || !(getHandle() instanceof EntityInsentient)) { + return false; + } + + if (holder == null) { + return unleash(); + } + + if (holder.isDead()) { + return false; + } + + unleash(); + ((EntityInsentient) getHandle()).setLeashHolder(((CraftEntity) holder).getHandle(), true); + return true; + } + + @Deprecated + public int _INVALID_getLastDamage() { + return NumberConversions.ceil(getLastDamage()); + } + + @Deprecated + public void _INVALID_setLastDamage(int damage) { + setLastDamage(damage); + } + + @Deprecated + public void _INVALID_damage(int amount) { + damage(amount); + } + + @Deprecated + public void _INVALID_damage(int amount, Entity source) { + damage(amount, source); + } + + @Deprecated + public int _INVALID_getHealth() { + return NumberConversions.ceil(getHealth()); + } + + @Deprecated + public void _INVALID_setHealth(int health) { + setHealth(health); + } + + @Deprecated + public int _INVALID_getMaxHealth() { + return NumberConversions.ceil(getMaxHealth()); + } + + @Deprecated + public void _INVALID_setMaxHealth(int health) { + setMaxHealth(health); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftMagmaCube.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftMagmaCube.java new file mode 100644 index 0000000..92d36ce --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftMagmaCube.java @@ -0,0 +1,26 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityMagmaCube; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.MagmaCube; + +public class CraftMagmaCube extends CraftSlime implements MagmaCube { + + public CraftMagmaCube(CraftServer server, EntityMagmaCube entity) { + super(server, entity); + } + + public EntityMagmaCube getHandle() { + return (EntityMagmaCube) entity; + } + + @Override + public String toString() { + return "CraftMagmaCube"; + } + + public EntityType getType() { + return EntityType.MAGMA_CUBE; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecart.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecart.java new file mode 100644 index 0000000..c31ecd1 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecart.java @@ -0,0 +1,98 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.Blocks; +import net.minecraft.server.EntityMinecartAbstract; +import net.minecraft.server.IBlockData; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.util.CraftMagicNumbers; +import org.bukkit.entity.Minecart; +import org.bukkit.material.MaterialData; +import org.bukkit.util.NumberConversions; +import org.bukkit.util.Vector; + +public abstract class CraftMinecart extends CraftVehicle implements Minecart { + public CraftMinecart(CraftServer server, EntityMinecartAbstract entity) { + super(server, entity); + } + + public void setDamage(double damage) { + getHandle().setDamage((float) damage); + } + + public double getDamage() { + return getHandle().getDamage(); + } + + public double getMaxSpeed() { + return getHandle().maxSpeed; + } + + public void setMaxSpeed(double speed) { + if (speed >= 0D) { + getHandle().maxSpeed = speed; + } + } + + public boolean isSlowWhenEmpty() { + return getHandle().slowWhenEmpty; + } + + public void setSlowWhenEmpty(boolean slow) { + getHandle().slowWhenEmpty = slow; + } + + public Vector getFlyingVelocityMod() { + return getHandle().getFlyingVelocityMod(); + } + + public void setFlyingVelocityMod(Vector flying) { + getHandle().setFlyingVelocityMod(flying); + } + + public Vector getDerailedVelocityMod() { + return getHandle().getDerailedVelocityMod(); + } + + public void setDerailedVelocityMod(Vector derailed) { + getHandle().setDerailedVelocityMod(derailed); + } + + @Override + public EntityMinecartAbstract getHandle() { + return (EntityMinecartAbstract) entity; + } + + @Deprecated + public void _INVALID_setDamage(int damage) { + setDamage(damage); + } + + @Deprecated + public int _INVALID_getDamage() { + return NumberConversions.ceil(getDamage()); + } + + public void setDisplayBlock(MaterialData material) { + if(material != null) { + IBlockData block = CraftMagicNumbers.getBlock(material.getItemTypeId()).fromLegacyData(material.getData()); + this.getHandle().setDisplayBlock(block); + } else { + // Set block to air (default) and set the flag to not have a display block. + this.getHandle().setDisplayBlock(Blocks.AIR.getBlockData()); + this.getHandle().a(false); + } + } + + public MaterialData getDisplayBlock() { + IBlockData blockData = getHandle().getDisplayBlock(); + return CraftMagicNumbers.getMaterial(blockData.getBlock()).getNewData((byte) blockData.getBlock().toLegacyData(blockData)); + } + + public void setDisplayBlockOffset(int offset) { + getHandle().SetDisplayBlockOffset(offset); + } + + public int getDisplayBlockOffset() { + return getHandle().getDisplayBlockOffset(); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartChest.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartChest.java new file mode 100644 index 0000000..5c0fa99 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartChest.java @@ -0,0 +1,31 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityMinecartChest; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.inventory.CraftInventory; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.StorageMinecart; +import org.bukkit.inventory.Inventory; + +@SuppressWarnings("deprecation") +public class CraftMinecartChest extends CraftMinecart implements StorageMinecart { + private final CraftInventory inventory; + + public CraftMinecartChest(CraftServer server, EntityMinecartChest entity) { + super(server, entity); + inventory = new CraftInventory(entity); + } + + public Inventory getInventory() { + return inventory; + } + + @Override + public String toString() { + return "CraftMinecartChest{" + "inventory=" + inventory + '}'; + } + + public EntityType getType() { + return EntityType.MINECART_CHEST; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartCommand.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartCommand.java new file mode 100644 index 0000000..5e4982e --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartCommand.java @@ -0,0 +1,126 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityMinecartCommandBlock; +import org.bukkit.Bukkit; +import org.bukkit.Server; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.minecart.CommandMinecart; +import org.bukkit.permissions.PermissibleBase; +import org.bukkit.permissions.Permission; +import org.bukkit.permissions.PermissionAttachment; +import org.bukkit.permissions.PermissionAttachmentInfo; +import org.bukkit.plugin.Plugin; + +import java.util.Set; + +public class CraftMinecartCommand extends CraftMinecart implements CommandMinecart { + private final PermissibleBase perm = new PermissibleBase(this); + + public CraftMinecartCommand(CraftServer server, EntityMinecartCommandBlock entity) { + super(server, entity); + } + + @Override + public String getCommand() { + return ((EntityMinecartCommandBlock) getHandle()).getCommandBlock().getCommand(); + } + + @Override + public void setCommand(String command) { + ((EntityMinecartCommandBlock) getHandle()).getCommandBlock().setCommand(command != null ? command : ""); + } + + @Override + public void setName(String name) { + ((EntityMinecartCommandBlock) getHandle()).getCommandBlock().setName(name != null ? name : "@"); + } + + @Override + public EntityType getType() { + return EntityType.MINECART_COMMAND; + } + + @Override + public void sendMessage(String message) { + } + + @Override + public void sendMessage(String[] messages) { + } + + @Override + public String getName() { + return ((EntityMinecartCommandBlock) getHandle()).getCommandBlock().getName(); + } + + @Override + public boolean isOp() { + return true; + } + + @Override + public void setOp(boolean value) { + throw new UnsupportedOperationException("Cannot change operator status of a minecart"); + } + + @Override + public boolean isPermissionSet(String name) { + return perm.isPermissionSet(name); + } + + @Override + public boolean isPermissionSet(Permission perm) { + return this.perm.isPermissionSet(perm); + } + + @Override + public boolean hasPermission(String name) { + return perm.hasPermission(name); + } + + @Override + public boolean hasPermission(Permission perm) { + return this.perm.hasPermission(perm); + } + + @Override + public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value) { + return perm.addAttachment(plugin, name, value); + } + + @Override + public PermissionAttachment addAttachment(Plugin plugin) { + return perm.addAttachment(plugin); + } + + @Override + public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value, int ticks) { + return perm.addAttachment(plugin, name, value, ticks); + } + + @Override + public PermissionAttachment addAttachment(Plugin plugin, int ticks) { + return perm.addAttachment(plugin, ticks); + } + + @Override + public void removeAttachment(PermissionAttachment attachment) { + perm.removeAttachment(attachment); + } + + @Override + public void recalculatePermissions() { + perm.recalculatePermissions(); + } + + @Override + public Set getEffectivePermissions() { + return perm.getEffectivePermissions(); + } + + @Override + public Server getServer() { + return Bukkit.getServer(); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartFurnace.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartFurnace.java new file mode 100644 index 0000000..45ac5a0 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartFurnace.java @@ -0,0 +1,22 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityMinecartFurnace; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.PoweredMinecart; + +@SuppressWarnings("deprecation") +public class CraftMinecartFurnace extends CraftMinecart implements PoweredMinecart { + public CraftMinecartFurnace(CraftServer server, EntityMinecartFurnace entity) { + super(server, entity); + } + + @Override + public String toString() { + return "CraftMinecartFurnace"; + } + + public EntityType getType() { + return EntityType.MINECART_FURNACE; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartHopper.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartHopper.java new file mode 100644 index 0000000..2b0c885 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartHopper.java @@ -0,0 +1,30 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityMinecartHopper; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.inventory.CraftInventory; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.minecart.HopperMinecart; +import org.bukkit.inventory.Inventory; + +final class CraftMinecartHopper extends CraftMinecart implements HopperMinecart { + private final CraftInventory inventory; + + CraftMinecartHopper(CraftServer server, EntityMinecartHopper entity) { + super(server, entity); + inventory = new CraftInventory(entity); + } + + @Override + public String toString() { + return "CraftMinecartHopper{" + "inventory=" + inventory + '}'; + } + + public EntityType getType() { + return EntityType.MINECART_HOPPER; + } + + public Inventory getInventory() { + return inventory; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartMobSpawner.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartMobSpawner.java new file mode 100644 index 0000000..6b7e363 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartMobSpawner.java @@ -0,0 +1,21 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityMinecartMobSpawner; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.minecart.SpawnerMinecart; + +final class CraftMinecartMobSpawner extends CraftMinecart implements SpawnerMinecart { + CraftMinecartMobSpawner(CraftServer server, EntityMinecartMobSpawner entity) { + super(server, entity); + } + + @Override + public String toString() { + return "CraftMinecartMobSpawner"; + } + + public EntityType getType() { + return EntityType.MINECART_MOB_SPAWNER; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartRideable.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartRideable.java new file mode 100644 index 0000000..4394ed1 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartRideable.java @@ -0,0 +1,21 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityMinecartAbstract; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.minecart.RideableMinecart; + +public class CraftMinecartRideable extends CraftMinecart implements RideableMinecart { + public CraftMinecartRideable(CraftServer server, EntityMinecartAbstract entity) { + super(server, entity); + } + + @Override + public String toString() { + return "CraftMinecartRideable"; + } + + public EntityType getType() { + return EntityType.MINECART; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartTNT.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartTNT.java new file mode 100644 index 0000000..641f9c8 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartTNT.java @@ -0,0 +1,21 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityMinecartTNT; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.minecart.ExplosiveMinecart; + +final class CraftMinecartTNT extends CraftMinecart implements ExplosiveMinecart { + CraftMinecartTNT(CraftServer server, EntityMinecartTNT entity) { + super(server, entity); + } + + @Override + public String toString() { + return "CraftMinecartTNT"; + } + + public EntityType getType() { + return EntityType.MINECART_TNT; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftMonster.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftMonster.java new file mode 100644 index 0000000..6bfb4bc --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftMonster.java @@ -0,0 +1,22 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityMonster; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.Monster; + +public class CraftMonster extends CraftCreature implements Monster { + + public CraftMonster(CraftServer server, EntityMonster entity) { + super(server, entity); + } + + @Override + public EntityMonster getHandle() { + return (EntityMonster) entity; + } + + @Override + public String toString() { + return "CraftMonster"; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftMushroomCow.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftMushroomCow.java new file mode 100644 index 0000000..c1ae676 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftMushroomCow.java @@ -0,0 +1,26 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityMushroomCow; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.MushroomCow; + +public class CraftMushroomCow extends CraftCow implements MushroomCow { + public CraftMushroomCow(CraftServer server, EntityMushroomCow entity) { + super(server, entity); + } + + @Override + public EntityMushroomCow getHandle() { + return (EntityMushroomCow) entity; + } + + @Override + public String toString() { + return "CraftMushroomCow"; + } + + public EntityType getType() { + return EntityType.MUSHROOM_COW; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftOcelot.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftOcelot.java new file mode 100644 index 0000000..37cc315 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftOcelot.java @@ -0,0 +1,32 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityOcelot; +import org.apache.commons.lang.Validate; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Ocelot; + +public class CraftOcelot extends CraftTameableAnimal implements Ocelot { + public CraftOcelot(CraftServer server, EntityOcelot wolf) { + super(server, wolf); + } + + @Override + public EntityOcelot getHandle() { + return (EntityOcelot) entity; + } + + public Type getCatType() { + return Type.getType(getHandle().getCatType()); + } + + public void setCatType(Type type) { + Validate.notNull(type, "Cat type cannot be null"); + getHandle().setCatType(type.getId()); + } + + @Override + public EntityType getType() { + return EntityType.OCELOT; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftPainting.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftPainting.java new file mode 100644 index 0000000..7c22130 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftPainting.java @@ -0,0 +1,78 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityPainting; +import net.minecraft.server.EntityPainting.EnumArt; +import net.minecraft.server.WorldServer; +import org.bukkit.Art; +import org.bukkit.block.BlockFace; +import org.bukkit.craftbukkit.CraftArt; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.CraftWorld; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Painting; + +public class CraftPainting extends CraftHanging implements Painting { + + public CraftPainting(CraftServer server, EntityPainting entity) { + super(server, entity); + } + + public Art getArt() { + EnumArt art = getHandle().art; + return CraftArt.NotchToBukkit(art); + } + + public boolean setArt(Art art) { + return setArt(art, false); + } + + public boolean setArt(Art art, boolean force) { + EntityPainting painting = this.getHandle(); + EnumArt oldArt = painting.art; + painting.art = CraftArt.BukkitToNotch(art); + painting.setDirection(painting.direction); + if (!force && !painting.survives()) { + // Revert painting since it doesn't fit + painting.art = oldArt; + painting.setDirection(painting.direction); + return false; + } + this.update(); + return true; + } + + public boolean setFacingDirection(BlockFace face, boolean force) { + if (super.setFacingDirection(face, force)) { + update(); + return true; + } + + return false; + } + + private void update() { + WorldServer world = ((CraftWorld) getWorld()).getHandle(); + EntityPainting painting = new EntityPainting(world); + painting.blockPosition = getHandle().blockPosition; + painting.art = getHandle().art; + painting.setDirection(getHandle().direction); + getHandle().die(); + getHandle().velocityChanged = true; // because this occurs when the painting is broken, so it might be important + world.addEntity(painting); + this.entity = painting; + } + + @Override + public EntityPainting getHandle() { + return (EntityPainting) entity; + } + + @Override + public String toString() { + return "CraftPainting{art=" + getArt() + "}"; + } + + public EntityType getType() { + return EntityType.PAINTING; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftPig.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftPig.java new file mode 100644 index 0000000..415ddde --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftPig.java @@ -0,0 +1,33 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityPig; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Pig; + +public class CraftPig extends CraftAnimals implements Pig { + public CraftPig(CraftServer server, EntityPig entity) { + super(server, entity); + } + + public boolean hasSaddle() { + return getHandle().hasSaddle(); + } + + public void setSaddle(boolean saddled) { + getHandle().setSaddle(saddled); + } + + public EntityPig getHandle() { + return (EntityPig) entity; + } + + @Override + public String toString() { + return "CraftPig"; + } + + public EntityType getType() { + return EntityType.PIG; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftPigZombie.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftPigZombie.java new file mode 100644 index 0000000..fab5749 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftPigZombie.java @@ -0,0 +1,43 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityPigZombie; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.PigZombie; + +public class CraftPigZombie extends CraftZombie implements PigZombie { + + public CraftPigZombie(CraftServer server, EntityPigZombie entity) { + super(server, entity); + } + + public int getAnger() { + return getHandle().angerLevel; + } + + public void setAnger(int level) { + getHandle().angerLevel = level; + } + + public void setAngry(boolean angry) { + setAnger(angry ? 400 : 0); + } + + public boolean isAngry() { + return getAnger() > 0; + } + + @Override + public EntityPigZombie getHandle() { + return (EntityPigZombie) entity; + } + + @Override + public String toString() { + return "CraftPigZombie"; + } + + public EntityType getType() { + return EntityType.PIG_ZOMBIE; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftPlayer.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftPlayer.java new file mode 100644 index 0000000..87172b9 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftPlayer.java @@ -0,0 +1,1690 @@ +package org.bukkit.craftbukkit.entity; + +import com.google.common.base.Preconditions; +import com.google.common.collect.ImmutableSet; +import com.mojang.authlib.GameProfile; +import dev.azurite.spigot.Azurite; +import dev.azurite.spigot.api.knockback.IKnockback; +import dev.azurite.spigot.configs.AzuriteConfig; +import dev.azurite.spigot.knockback.Knockback; +import io.netty.buffer.Unpooled; +import net.md_5.bungee.api.chat.BaseComponent; +import net.minecraft.server.*; +import net.minecraft.server.PacketPlayOutTitle.EnumTitleAction; +import org.apache.commons.lang.NotImplementedException; +import org.apache.commons.lang.Validate; +import org.bukkit.Achievement; +import org.bukkit.Material; +import org.bukkit.Statistic; +import org.bukkit.*; +import org.bukkit.World; +import org.bukkit.Statistic.Type; +import org.bukkit.configuration.serialization.DelegateDeserialization; +import org.bukkit.conversations.Conversation; +import org.bukkit.conversations.ConversationAbandonedEvent; +import org.bukkit.conversations.ManuallyAbandonedConversationCanceller; +import org.bukkit.craftbukkit.*; +import org.bukkit.craftbukkit.block.CraftSign; +import org.bukkit.craftbukkit.conversations.ConversationTracker; +import org.bukkit.craftbukkit.map.CraftMapView; +import org.bukkit.craftbukkit.map.RenderData; +import org.bukkit.craftbukkit.scoreboard.CraftScoreboard; +import org.bukkit.craftbukkit.util.CraftChatMessage; +import org.bukkit.craftbukkit.util.CraftMagicNumbers; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import org.bukkit.event.player.*; +import org.bukkit.inventory.InventoryView.Property; +import org.bukkit.map.MapCursor; +import org.bukkit.map.MapView; +import org.bukkit.metadata.MetadataValue; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.messaging.StandardMessenger; +import org.bukkit.scoreboard.Scoreboard; +import org.bukkit.util.Vector; +import org.github.paperspigot.Title; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.SocketAddress; +import java.nio.charset.StandardCharsets; +import java.text.MessageFormat; +import java.util.*; +import java.util.logging.Level; +import java.util.logging.Logger; + +@DelegateDeserialization(CraftOfflinePlayer.class) +public class CraftPlayer extends CraftHumanEntity implements Player { + private long firstPlayed; + private long lastPlayed = 0; + private boolean hasPlayedBefore = false; + private final ConversationTracker conversationTracker = new ConversationTracker(); + private final Set channels = new HashSet<>(); + private final Set hiddenPlayers = new HashSet<>(); + private int hash = 0; + private double health = 20; + private boolean scaledHealth = false; + private double healthScale = 20; + + public CraftPlayer(CraftServer server, EntityPlayer entity) { + super(server, entity); + firstPlayed = System.currentTimeMillis(); + } + + public void sendPacket(Object packet) { + if (packet instanceof Packet) + getHandle().playerConnection.sendPacket((Packet) packet); + } + + @Override + public void setKnockbackProfile(IKnockback knockbackProfile) { + getHandle().setKnockbackProfile((Knockback) knockbackProfile); + } + + @Override + public IKnockback getKnockbackProfile() { + return getHandle().getKnockbackProfile(); + } + + @Override + public void setVelocity(Vector vel) { + if (!AzuriteConfig.kohiVelocityPatch.getValue()) { + super.setVelocity(vel); + return; + } + + // To be consistent with old behavior, set the velocity before firing the event + setVelocityDirect(vel); + + PlayerVelocityEvent event = new PlayerVelocityEvent(this, vel.clone()); + getServer().getPluginManager().callEvent(event); + + if (!event.isCancelled()) { + // Set the velocity again in case it was changed by event handlers + setVelocityDirect(event.getVelocity()); + + // Send the new velocity to the player's client immediately, so it isn't affected by + // any movement packets from this player that may be processed before the end of the tick. + // Without this, player velocity changes tend to be very inconsistent. + getHandle().playerConnection.sendPacket(new PacketPlayOutEntityVelocity(getHandle())); + } + + // Note that cancelling the event does not restore the old velocity, it only prevents + // the packet from sending. Again, this is to be consistent with old behavior. + } + + public void setVelocityDirect(Vector vel) { + this.setVelocityDirect(vel, false); + } + + public void setVelocityDirect(Vector vel, boolean changeFallDistance) { + entity.motX = vel.getX(); + entity.motY = vel.getY(); + entity.motZ = vel.getZ(); + if (changeFallDistance && entity.motY > 0) // Azurite - Wtf Vortex? + entity.fallDistance = 0.0f; + } + + public GameProfile getProfile() { + return getHandle().getProfile(); + } + + public boolean isOp() { + return this.server.getHandle().isOp(getProfile()); + } + + public void setOp(boolean value) { + if (value == isOp()) + return; + if (value) { + this.server.getHandle().addOp(getProfile()); + } else { + this.server.getHandle().removeOp(getProfile()); + } + this.perm.recalculatePermissions(); + } + + public boolean isOnline() { + return server.getPlayer(getUniqueId()) != null; + } + + public InetSocketAddress getAddress() { + if (getHandle().playerConnection == null) { + return null; + } + + SocketAddress addr = getHandle().playerConnection.networkManager.getSocketAddress(); + if (addr instanceof InetSocketAddress) { + return (InetSocketAddress) addr; + } else { + return null; + } + } + + @Override + public double getEyeHeight() { + return getEyeHeight(false); + } + + @Override + public double getEyeHeight(boolean ignoreSneaking) { + if (ignoreSneaking) { + return 1.62D; + } else { + if (isSneaking()) { + return 1.54D; + } else { + return 1.62D; + } + } + } + + @Override + public void sendRawMessage(String message) { + if (getHandle().playerConnection == null) { + return; + } + + for (IChatBaseComponent component : CraftChatMessage.fromString(message)) { + getHandle().playerConnection.sendPacket(new PacketPlayOutChat(component)); + } + } + + @Override + public void sendMessage(String message) { + if (!conversationTracker.isConversingModaly()) { + this.sendRawMessage(message); + } + } + + @Override + public void sendMessage(String[] messages) { + for (String message : messages) { + sendMessage(message); + } + } + + // Paper start + @Override + public void sendMessage(BaseComponent component) { + sendMessage(new BaseComponent[]{component}); + } + + @Override + public void sendMessage(BaseComponent... components) { + if (getHandle().playerConnection == null) { + return; + } + + PacketPlayOutChat packet = new PacketPlayOutChat(); + packet.components = components; + packet.serializeJson(); // Beanes - only serialize chat json once + getHandle().playerConnection.sendPacket(packet); + } + + public void sendFormattedMessage(String message, final Object... params) { + if (this.getHandle().playerConnection == null) { + return; + } + + message = MessageFormat.format(message, params); + for (final IChatBaseComponent component : CraftChatMessage.fromString(message)) { + getHandle().playerConnection.sendPacket(new PacketPlayOutChat(component)); + } + } + + @Override + public void setPlayerListHeaderFooter(BaseComponent[] header, BaseComponent[] footer) { + PacketPlayOutPlayerListHeaderFooter packet = new PacketPlayOutPlayerListHeaderFooter(); + packet.header = header; + packet.footer = footer; + packet.serialize(); + getHandle().playerConnection.sendPacket(packet); + } + + @Override + public void setPlayerListHeaderFooter(BaseComponent header, BaseComponent footer) { + this.setPlayerListHeaderFooter(header == null ? null : new BaseComponent[]{header}, + footer == null ? null : new BaseComponent[]{footer}); + } + + + @Override + public void setTitleTimes(int fadeInTicks, int stayTicks, int fadeOutTicks) { + getHandle().playerConnection.sendPacket( + new PacketPlayOutTitle(PacketPlayOutTitle.EnumTitleAction.TIMES, (BaseComponent[]) null, fadeInTicks, + stayTicks, fadeOutTicks)); + } + + @Override + public void setSubtitle(BaseComponent[] subtitle) { + getHandle().playerConnection + .sendPacket(new PacketPlayOutTitle(PacketPlayOutTitle.EnumTitleAction.SUBTITLE, subtitle, 0, 0, 0)); + } + + @Override + public void setSubtitle(BaseComponent subtitle) { + setSubtitle(new BaseComponent[]{subtitle}); + } + + @Override + public void showTitle(BaseComponent[] title) { + getHandle().playerConnection + .sendPacket(new PacketPlayOutTitle(PacketPlayOutTitle.EnumTitleAction.TITLE, title, 0, 0, 0)); + } + + @Override + public void showTitle(BaseComponent title) { + showTitle(new BaseComponent[]{title}); + } + + @Override + public void showTitle(BaseComponent[] title, BaseComponent[] subtitle, int fadeInTicks, int stayTicks, + int fadeOutTicks) { + setTitleTimes(fadeInTicks, stayTicks, fadeOutTicks); + setSubtitle(subtitle); + showTitle(title); + } + + @Override + public void showTitle(BaseComponent title, BaseComponent subtitle, int fadeInTicks, int stayTicks, + int fadeOutTicks) { + setTitleTimes(fadeInTicks, stayTicks, fadeOutTicks); + setSubtitle(subtitle); + showTitle(title); + } + + @Override + public void sendTitle(Title title) { + Preconditions.checkNotNull(title, "Title is null"); + setTitleTimes(title.getFadeIn(), title.getStay(), title.getFadeOut()); + setSubtitle(title.getSubtitle() == null ? new BaseComponent[0] : title.getSubtitle()); + showTitle(title.getTitle()); + } + + @Override + public void updateTitle(Title title) { + Preconditions.checkNotNull(title, "Title is null"); + setTitleTimes(title.getFadeIn(), title.getStay(), title.getFadeOut()); + if (title.getSubtitle() != null) { + setSubtitle(title.getSubtitle()); + } + showTitle(title.getTitle()); + } + + @Override + public void hideTitle() { + getHandle().playerConnection.sendPacket( + new PacketPlayOutTitle(PacketPlayOutTitle.EnumTitleAction.CLEAR, (BaseComponent[]) null, 0, 0, 0)); + } + // Paper end + + @Override + public String getDisplayName() { + return getHandle().displayName; + } + + @Override + public void setDisplayName(final String name) { + getHandle().displayName = name == null ? getName() : name; + } + + @Override + public String getPlayerListName() { + return getHandle().listName == null ? getName() : CraftChatMessage.fromComponent(getHandle().listName); + } + + @Override + public void setPlayerListName(String name) { + if (name == null) { + name = getName(); + } + getHandle().listName = name.equals(getName()) ? null : CraftChatMessage.fromString(name)[0]; + for (EntityPlayer player : this.server.getHandle().players) { + if (player.getBukkitEntity().canSee(this)) + player.playerConnection.sendPacket(new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.UPDATE_DISPLAY_NAME, getHandle())); + } + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof OfflinePlayer)) { + return false; + } + OfflinePlayer other = (OfflinePlayer) obj; + if ((this.getUniqueId() == null) || (other.getUniqueId() == null)) { + return false; + } + + boolean uuidEquals = this.getUniqueId().equals(other.getUniqueId()); + boolean idEquals = true; + + if (other instanceof CraftPlayer) { + idEquals = this.getEntityId() == ((CraftPlayer) other).getEntityId(); + } + + return uuidEquals && idEquals; + } + + @Override + public void kickPlayer(String message) { + org.spigotmc.AsyncCatcher.catchOp("player kick"); // Spigot + if (getHandle().playerConnection == null) { + return; + } + + getHandle().playerConnection.disconnect(message == null ? "" : message); + } + + @Override + public void setCompassTarget(Location loc) { + if (getHandle().playerConnection == null) { + return; + } + + // Do not directly assign here, from the packethandler we'll assign it. + getHandle().playerConnection.sendPacket(new PacketPlayOutSpawnPosition(new BlockPosition(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()))); + } + + @Override + public Location getCompassTarget() { + return getHandle().compassTarget; + } + + @Override + public void chat(String msg) { + if (getHandle().playerConnection == null) { + return; + } + + getHandle().playerConnection.chat(msg, false); + } + + @Override + public boolean performCommand(String command) { + return server.dispatchCommand(this, command); + } + + @Override + public void playNote(Location loc, byte instrument, byte note) { + if (getHandle().playerConnection == null) { + return; + } + + String instrumentName = null; + switch (instrument) { + case 0: + instrumentName = "harp"; + break; + case 1: + instrumentName = "bd"; + break; + case 2: + instrumentName = "snare"; + break; + case 3: + instrumentName = "hat"; + break; + case 4: + instrumentName = "bassattack"; + break; + } + + float f = (float) Math.pow(2.0D, (note - 12.0D) / 12.0D); + getHandle().playerConnection.sendPacket( + new PacketPlayOutNamedSoundEffect("note." + instrumentName, loc.getBlockX(), loc.getBlockY(), + loc.getBlockZ(), 3.0f, f)); + } + + @Override + public void playNote(Location loc, Instrument instrument, Note note) { + if (getHandle().playerConnection == null) { + return; + } + + String instrumentName = null; + switch (instrument.ordinal()) { + case 0: + instrumentName = "harp"; + break; + case 1: + instrumentName = "bd"; + break; + case 2: + instrumentName = "snare"; + break; + case 3: + instrumentName = "hat"; + break; + case 4: + instrumentName = "bassattack"; + break; + } + float f = (float) Math.pow(2.0D, (note.getId() - 12.0D) / 12.0D); + getHandle().playerConnection.sendPacket( + new PacketPlayOutNamedSoundEffect("note." + instrumentName, loc.getBlockX(), loc.getBlockY(), + loc.getBlockZ(), 3.0f, f)); + } + + @Override + public void playSound(Location loc, Sound sound, float volume, float pitch) { + if (sound == null) { + return; + } + playSound(loc, CraftSound.getSound(sound), volume, pitch); + } + + @Override + public void playSound(Location loc, String sound, float volume, float pitch) { + if (loc == null || sound == null || getHandle().playerConnection == null) { + return; + } + + double x = loc.getBlockX() + 0.5; + double y = loc.getBlockY() + 0.5; + double z = loc.getBlockZ() + 0.5; + + PacketPlayOutNamedSoundEffect packet = new PacketPlayOutNamedSoundEffect(sound, x, y, z, volume, pitch); + getHandle().playerConnection.sendPacket(packet); + } + + @Override + public void playEffect(Location loc, Effect effect, int data) { + if (getHandle().playerConnection == null) { + return; + } + + spigot().playEffect(loc, effect, data, 0, 0, 0, 0, 1, 1, 64); // Spigot + } + + @Override + public void playEffect(Location loc, Effect effect, T data) { + if (data != null) { + Validate.isTrue(data.getClass().isAssignableFrom(effect.getData()), "Wrong kind of data for this effect!"); + } else { + Validate.isTrue(effect.getData() == null, "Wrong kind of data for this effect!"); + } + + int datavalue = data == null ? 0 : CraftEffect.getDataValue(effect, data); + playEffect(loc, effect, datavalue); + } + + @Override + public void sendBlockChange(Location loc, Material material, byte data) { + sendBlockChange(loc, material.getId(), data); + } + + @Override + public void sendBlockChange(Location loc, int material, byte data) { + if (getHandle().playerConnection == null) { + return; + } + + PacketPlayOutBlockChange packet = new PacketPlayOutBlockChange(((CraftWorld) loc.getWorld()).getHandle(), new BlockPosition(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); + packet.block = CraftMagicNumbers.getBlock(material).fromLegacyData(data); + getHandle().playerConnection.sendPacket(packet); + } + + @Override + public void sendSignChange(Location loc, String[] lines) { + if (getHandle().playerConnection == null) { + return; + } + + if (lines == null) { + lines = new String[4]; + } + + Validate.notNull(loc, "Location can not be null"); + if (lines.length < 4) { + throw new IllegalArgumentException("Must have at least 4 lines"); + } + + IChatBaseComponent[] components = CraftSign.sanitizeLines(lines); + + getHandle().playerConnection.sendPacket(new PacketPlayOutUpdateSign(getHandle().world, new BlockPosition(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()), components)); + } + + @Override + public boolean sendChunkChange(Location loc, int sx, int sy, int sz, byte[] data) { + if (getHandle().playerConnection == null) { + return false; + } + + throw new NotImplementedException("Chunk changes do not yet work"); // TODO: Chunk changes. + } + + @Override + public void sendActionBar(String message) { + getHandle().playerConnection.sendPacket(new PacketPlayOutChat(new ChatComponentText(message), (byte) 2)); + } + + @Override + public void sendMap(MapView map) { + if (getHandle().playerConnection == null) { + return; + } + + RenderData data = ((CraftMapView) map).render(this); + Collection icons = new ArrayList<>(); + for (MapCursor cursor : data.cursors) { + if (cursor.isVisible()) { + icons.add(new MapIcon(cursor.getRawType(), cursor.getX(), cursor.getY(), cursor.getDirection())); + } + } + + PacketPlayOutMap packet = new PacketPlayOutMap(map.getId(), map.getScale().getValue(), icons, data.buffer, + 0, 0, + 0, 0); + getHandle().playerConnection.sendPacket(packet); + } + + @Override + public boolean teleport(Location location, PlayerTeleportEvent.TeleportCause cause) { + EntityPlayer entity = getHandle(); + + if (getHealth() == 0 || entity.dead) { + return false; + } + + if (entity.playerConnection == null || entity.playerConnection.isDisconnected()) { + return false; + } + + if (entity.passenger != null) { + return false; + } + + // From = Players current Location + Location from = this.getLocation(); + // To = Players new Location if Teleport is Successful + Location to = location; + // Create & Call the Teleport Event. + PlayerTeleportEvent event = new PlayerTeleportEvent(this, from, to, cause); + server.getPluginManager().callEvent(event); + + // Return False to inform the Plugin that the Teleport was unsuccessful/cancelled. + if (event.isCancelled()) { + return false; + } + + // If this player is riding another entity, we must dismount before teleporting. + entity.mount(null); + + // Update the From Location + from = event.getFrom(); + // Grab the new To Location dependent on whether the event was cancelled. + to = event.getTo(); + // Grab the To and From World Handles. + WorldServer fromWorld = ((CraftWorld) from.getWorld()).getHandle(); + WorldServer toWorld = ((CraftWorld) to.getWorld()).getHandle(); + + // Close any foreign inventory + if (getHandle().activeContainer != getHandle().defaultContainer) { + getHandle().closeInventory(); + } + + // Check if the fromWorld and toWorld are the same. + if (fromWorld == toWorld) { + entity.playerConnection.teleport(to); + } else { + server.getHandle().moveToWorld(entity, toWorld.dimension, true, to, false); + } + return true; + } + + @Override + public void setSneaking(boolean sneak) { + getHandle().setSneaking(sneak); + } + + @Override + public boolean isSneaking() { + return getHandle().isSneaking(); + } + + @Override + public boolean isSprinting() { + return getHandle().isSprinting(); + } + + @Override + public void setSprinting(boolean sprinting) { + getHandle().setSprinting(sprinting); + } + + @Override + public void loadData() { + server.getHandle().playerFileData.load(getHandle()); + } + + @Override + public void saveData() { + server.getHandle().playerFileData.save(getHandle()); + } + + @Deprecated + @Override + public void updateInventory() { + getHandle().updateInventory(getHandle().activeContainer); + } + + @Override + public void setSleepingIgnored(boolean isSleeping) { + getHandle().fauxSleeping = isSleeping; + ((CraftWorld) getWorld()).getHandle().checkSleepStatus(); + } + + @Override + public boolean isSleepingIgnored() { + return getHandle().fauxSleeping; + } + + @Override + public void awardAchievement(Achievement achievement) { + Validate.notNull(achievement, "Achievement cannot be null"); + if (achievement.hasParent() && !hasAchievement(achievement.getParent())) { + awardAchievement(achievement.getParent()); + } + getHandle().getStatisticManager().setStatistic(getHandle(), CraftStatistic.getNMSAchievement(achievement), 1); + getHandle().getStatisticManager().updateStatistics(getHandle()); + } + + @Override + public void removeAchievement(Achievement achievement) { + Validate.notNull(achievement, "Achievement cannot be null"); + for (Achievement achieve : Achievement.values()) { + if (achieve.getParent() == achievement && hasAchievement(achieve)) { + removeAchievement(achieve); + } + } + getHandle().getStatisticManager().setStatistic(getHandle(), CraftStatistic.getNMSAchievement(achievement), 0); + } + + @Override + public boolean hasAchievement(Achievement achievement) { + Validate.notNull(achievement, "Achievement cannot be null"); + return getHandle().getStatisticManager().hasAchievement(CraftStatistic.getNMSAchievement(achievement)); + } + + @Override + public void incrementStatistic(Statistic statistic) { + incrementStatistic(statistic, 1); + } + + @Override + public void decrementStatistic(Statistic statistic) { + decrementStatistic(statistic, 1); + } + + @Override + public int getStatistic(Statistic statistic) { + Validate.notNull(statistic, "Statistic cannot be null"); + Validate.isTrue(statistic.getType() == Type.UNTYPED, "Must supply additional paramater for this statistic"); + return getHandle().getStatisticManager().getStatisticValue(CraftStatistic.getNMSStatistic(statistic)); + } + + @Override + public void incrementStatistic(Statistic statistic, int amount) { + Validate.isTrue(amount > 0, "Amount must be greater than 0"); + setStatistic(statistic, getStatistic(statistic) + amount); + } + + @Override + public void decrementStatistic(Statistic statistic, int amount) { + Validate.isTrue(amount > 0, "Amount must be greater than 0"); + setStatistic(statistic, getStatistic(statistic) - amount); + } + + @Override + public void setStatistic(Statistic statistic, int newValue) { + Validate.notNull(statistic, "Statistic cannot be null"); + Validate.isTrue(statistic.getType() == Type.UNTYPED, "Must supply additional paramater for this statistic"); + Validate.isTrue(newValue >= 0, "Value must be greater than or equal to 0"); + net.minecraft.server.Statistic nmsStatistic = CraftStatistic.getNMSStatistic(statistic); + getHandle().getStatisticManager().setStatistic(getHandle(), nmsStatistic, newValue); + } + + @Override + public void incrementStatistic(Statistic statistic, Material material) { + incrementStatistic(statistic, material, 1); + } + + @Override + public void decrementStatistic(Statistic statistic, Material material) { + decrementStatistic(statistic, material, 1); + } + + @Override + public int getStatistic(Statistic statistic, Material material) { + Validate.notNull(statistic, "Statistic cannot be null"); + Validate.notNull(material, "Material cannot be null"); + Validate.isTrue(statistic.getType() == Type.BLOCK || statistic.getType() == Type.ITEM, + "This statistic does not take a Material parameter"); + net.minecraft.server.Statistic nmsStatistic = CraftStatistic.getMaterialStatistic(statistic, material); + Validate.notNull(nmsStatistic, "The supplied Material does not have a corresponding statistic"); + return getHandle().getStatisticManager().getStatisticValue(nmsStatistic); + } + + @Override + public void incrementStatistic(Statistic statistic, Material material, int amount) { + Validate.isTrue(amount > 0, "Amount must be greater than 0"); + setStatistic(statistic, material, getStatistic(statistic, material) + amount); + } + + @Override + public void decrementStatistic(Statistic statistic, Material material, int amount) { + Validate.isTrue(amount > 0, "Amount must be greater than 0"); + setStatistic(statistic, material, getStatistic(statistic, material) - amount); + } + + @Override + public void setStatistic(Statistic statistic, Material material, int newValue) { + Validate.notNull(statistic, "Statistic cannot be null"); + Validate.notNull(material, "Material cannot be null"); + Validate.isTrue(newValue >= 0, "Value must be greater than or equal to 0"); + Validate.isTrue(statistic.getType() == Type.BLOCK || statistic.getType() == Type.ITEM, + "This statistic does not take a Material parameter"); + net.minecraft.server.Statistic nmsStatistic = CraftStatistic.getMaterialStatistic(statistic, material); + Validate.notNull(nmsStatistic, "The supplied Material does not have a corresponding statistic"); + getHandle().getStatisticManager().setStatistic(getHandle(), nmsStatistic, newValue); + } + + @Override + public void incrementStatistic(Statistic statistic, EntityType entityType) { + incrementStatistic(statistic, entityType, 1); + } + + @Override + public void decrementStatistic(Statistic statistic, EntityType entityType) { + decrementStatistic(statistic, entityType, 1); + } + + @Override + public int getStatistic(Statistic statistic, EntityType entityType) { + Validate.notNull(statistic, "Statistic cannot be null"); + Validate.notNull(entityType, "EntityType cannot be null"); + Validate.isTrue(statistic.getType() == Type.ENTITY, "This statistic does not take an EntityType parameter"); + net.minecraft.server.Statistic nmsStatistic = CraftStatistic.getEntityStatistic(statistic, entityType); + Validate.notNull(nmsStatistic, "The supplied EntityType does not have a corresponding statistic"); + return getHandle().getStatisticManager().getStatisticValue(nmsStatistic); + } + + @Override + public void incrementStatistic(Statistic statistic, EntityType entityType, int amount) { + Validate.isTrue(amount > 0, "Amount must be greater than 0"); + setStatistic(statistic, entityType, getStatistic(statistic, entityType) + amount); + } + + @Override + public void decrementStatistic(Statistic statistic, EntityType entityType, int amount) { + Validate.isTrue(amount > 0, "Amount must be greater than 0"); + setStatistic(statistic, entityType, getStatistic(statistic, entityType) - amount); + } + + @Override + public void setStatistic(Statistic statistic, EntityType entityType, int newValue) { + Validate.notNull(statistic, "Statistic cannot be null"); + Validate.notNull(entityType, "EntityType cannot be null"); + Validate.isTrue(newValue >= 0, "Value must be greater than or equal to 0"); + Validate.isTrue(statistic.getType() == Type.ENTITY, "This statistic does not take an EntityType parameter"); + net.minecraft.server.Statistic nmsStatistic = CraftStatistic.getEntityStatistic(statistic, entityType); + Validate.notNull(nmsStatistic, "The supplied EntityType does not have a corresponding statistic"); + getHandle().getStatisticManager().setStatistic(getHandle(), nmsStatistic, newValue); + } + + @Override + public void setPlayerTime(long time, boolean relative) { + getHandle().timeOffset = time; + getHandle().relativeTime = relative; + } + + @Override + public long getPlayerTimeOffset() { + return getHandle().timeOffset; + } + + @Override + public long getPlayerTime() { + return getHandle().getPlayerTime(); + } + + @Override + public boolean isPlayerTimeRelative() { + return getHandle().relativeTime; + } + + @Override + public void resetPlayerTime() { + setPlayerTime(0, true); + } + + @Override + public void setPlayerWeather(WeatherType type) { + getHandle().setPlayerWeather(type, true); + } + + @Override + public WeatherType getPlayerWeather() { + return getHandle().getPlayerWeather(); + } + + @Override + public void resetPlayerWeather() { + getHandle().resetPlayerWeather(); + } + + @Override + public boolean isBanned() { + return server.getBanList(BanList.Type.NAME).isBanned(getName()); + } + + @Override + public void setBanned(boolean value) { + if (value) { + server.getBanList(BanList.Type.NAME).addBan(getName(), null, null, null); + } else { + server.getBanList(BanList.Type.NAME).pardon(getName()); + } + } + + @Override + public boolean isWhitelisted() { + return server.getHandle().getWhitelist().isWhitelisted(getProfile()); + } + + @Override + public void setWhitelisted(boolean value) { + if (value) { + server.getHandle().addWhitelist(getProfile()); + } else { + server.getHandle().removeWhitelist(getProfile()); + } + } + + @Override + public void setGameMode(GameMode mode) { + if (getHandle().playerConnection == null) { + return; + } + + if (mode == null) { + throw new IllegalArgumentException("Mode cannot be null"); + } + + if (mode != getGameMode()) { + PlayerGameModeChangeEvent event = new PlayerGameModeChangeEvent(this, mode); + server.getPluginManager().callEvent(event); + if (event.isCancelled()) { + return; + } + + getHandle().setSpectatorTarget(getHandle()); + getHandle().playerInteractManager.setGameMode(WorldSettings.EnumGamemode.getById(mode.getValue())); + getHandle().fallDistance = 0; + getHandle().playerConnection.sendPacket(new PacketPlayOutGameStateChange(3, mode.getValue())); + } + } + + @Override + public GameMode getGameMode() { + return GameMode.getByValue(getHandle().playerInteractManager.getGameMode().getId()); + } + + @Override + public void giveExp(int exp) { + getHandle().giveExp(exp); + } + + @Override + public void giveExpLevels(int levels) { + getHandle().levelDown(levels); + } + + @Override + public float getExp() { + return getHandle().exp; + } + + @Override + public void setExp(float exp) { + getHandle().exp = exp; + getHandle().lastSentExp = -1; + } + + @Override + public int getLevel() { + return getHandle().expLevel; + } + + @Override + public void setLevel(int level) { + getHandle().expLevel = level; + getHandle().lastSentExp = -1; + } + + @Override + public int getTotalExperience() { + return getHandle().expTotal; + } + + @Override + public void setTotalExperience(int exp) { + getHandle().expTotal = exp; + } + + @Override + public float getExhaustion() { + return getHandle().getFoodData().exhaustionLevel; + } + + @Override + public void setExhaustion(float value) { + getHandle().getFoodData().exhaustionLevel = value; + } + + @Override + public float getSaturation() { + return getHandle().getFoodData().saturationLevel; + } + + @Override + public void setSaturation(float value) { + getHandle().getFoodData().saturationLevel = value; + } + + @Override + public int getFoodLevel() { + return getHandle().getFoodData().foodLevel; + } + + @Override + public void setFoodLevel(int value) { + getHandle().getFoodData().foodLevel = value; + } + + @Override + public Location getBedSpawnLocation() { + World world = getServer().getWorld(getHandle().spawnWorld); + BlockPosition bed = getHandle().getBed(); + + if (world != null && bed != null) { + bed = EntityHuman.getBed(((CraftWorld) world).getHandle(), bed, getHandle().isRespawnForced()); + if (bed != null) { + return new Location(world, bed.getX(), bed.getY(), bed.getZ()); + } + } + return null; + } + + @Override + public void setBedSpawnLocation(Location location) { + setBedSpawnLocation(location, false); + } + + @Override + public void setBedSpawnLocation(Location location, boolean override) { + if (location == null) { + getHandle().setRespawnPosition(null, override); + } else { + getHandle().setRespawnPosition( + new BlockPosition(location.getBlockX(), location.getBlockY(), location.getBlockZ()), override); + getHandle().spawnWorld = location.getWorld().getName(); + } + } + + @Override + public void hidePlayer(Player player) { + Validate.notNull(player, "hidden player cannot be null"); + if (getHandle().playerConnection == null || equals(player) || hiddenPlayers.contains(player.getUniqueId())) { + return; + } + hiddenPlayers.add(player.getUniqueId()); + EntityTracker tracker = ((WorldServer) this.entity.world).tracker; + EntityPlayer other = ((CraftPlayer) player).getHandle(); + EntityTrackerEntry entry = tracker.trackedEntities.get(other.getId()); + if (entry != null) + entry.clear(getHandle()); + getHandle().playerConnection.sendPacket(new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.REMOVE_PLAYER, other)); + } + + @Override + public void showPlayer(Player player) { + Validate.notNull(player, "shown player cannot be null"); + if (getHandle().playerConnection == null || equals(player) || !hiddenPlayers.contains(player.getUniqueId())) { + return; + } + hiddenPlayers.remove(player.getUniqueId()); + + EntityTracker tracker = ((WorldServer) entity.world).tracker; + EntityPlayer entityPlayer = getHandle(); + EntityPlayer other = ((CraftPlayer) player).getHandle(); + + entityPlayer.playerConnection.writePacketLazily(new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.ADD_PLAYER, other)); + + EntityTrackerEntry entry = tracker.trackedEntities.get(other.getId()); + if (entry != null && !entry.trackedPlayers.contains(getHandle())) { + entry.updatePlayer(getHandle()); + } + } + + @Override + public boolean canSee(Player player) { + return !hiddenPlayers.contains(player.getUniqueId()); + } + + @Override + public Map serialize() { + Map result = new LinkedHashMap<>(); + + result.put("name", getName()); + + return result; + } + + @Override + public Player getPlayer() { + return this; + } + + @Override + public EntityPlayer getHandle() { + return (EntityPlayer) entity; + } + + public void setHandle(final EntityPlayer entity) { + super.setHandle(entity); + } + + @Override + public String toString() { + return "CraftPlayer{" + "name=" + getName() + '}'; + } + + @Override + public int hashCode() { + if (hash == 0 || hash == 485) { + hash = 97 * 5 + (this.getUniqueId() != null ? this.getUniqueId().hashCode() : 0); + } + return hash; + } + + @Override + public long getFirstPlayed() { + return firstPlayed; + } + + @Override + public long getLastPlayed() { + return lastPlayed; + } + + @Override + public boolean hasPlayedBefore() { + return hasPlayedBefore; + } + + public void setFirstPlayed(long firstPlayed) { + this.firstPlayed = firstPlayed; + } + + public void readExtraData(NBTTagCompound nbttagcompound) { + hasPlayedBefore = true; + if (nbttagcompound.hasKey("bukkit")) { + NBTTagCompound data = nbttagcompound.getCompound("bukkit"); + + if (data.hasKey("firstPlayed")) { + firstPlayed = data.getLong("firstPlayed"); + lastPlayed = data.getLong("lastPlayed"); + } + + if (data.hasKey("newExp")) { + EntityPlayer handle = getHandle(); + handle.newExp = data.getInt("newExp"); + handle.newTotalExp = data.getInt("newTotalExp"); + handle.newLevel = data.getInt("newLevel"); + handle.expToDrop = data.getInt("expToDrop"); + handle.keepLevel = data.getBoolean("keepLevel"); + } + + if (data.hasKey("profile")) { + this.setKnockbackProfile(Azurite.getInstance().getKnockbackManager().getByName(data.getString("profile"))); + } + } + } + + public void setExtraData(NBTTagCompound nbttagcompound) { + if (!nbttagcompound.hasKey("bukkit")) { + nbttagcompound.set("bukkit", new NBTTagCompound()); + } + + NBTTagCompound data = nbttagcompound.getCompound("bukkit"); + EntityPlayer handle = getHandle(); + data.setInt("newExp", handle.newExp); + data.setInt("newTotalExp", handle.newTotalExp); + data.setInt("newLevel", handle.newLevel); + data.setInt("expToDrop", handle.expToDrop); + data.setBoolean("keepLevel", handle.keepLevel); + data.setLong("firstPlayed", getFirstPlayed()); + data.setLong("lastPlayed", System.currentTimeMillis()); + data.setString("lastKnownName", handle.getName()); + + // Only store knockback profiles if a custom one was set + Knockback knockback = getHandle().knockbackProfile; + + if (knockback != null) { + data.setString("profile", knockback.getName()); + } + } + + @Override + public boolean beginConversation(Conversation conversation) { + return conversationTracker.beginConversation(conversation); + } + + @Override + public void abandonConversation(Conversation conversation) { + conversationTracker.abandonConversation(conversation, + new ConversationAbandonedEvent(conversation, new ManuallyAbandonedConversationCanceller())); + } + + @Override + public void abandonConversation(Conversation conversation, ConversationAbandonedEvent details) { + conversationTracker.abandonConversation(conversation, details); + } + + @Override + public void acceptConversationInput(String input) { + conversationTracker.acceptConversationInput(input); + } + + @Override + public boolean isConversing() { + return conversationTracker.isConversing(); + } + + @Override + public void sendPluginMessage(Plugin source, String channel, byte[] message) { + StandardMessenger.validatePluginMessage(server.getMessenger(), source, channel, message); + if (getHandle().playerConnection == null) { + return; + } + + if (channels.contains(channel)) { + PacketPlayOutCustomPayload packet = new PacketPlayOutCustomPayload(channel, + new PacketDataSerializer(Unpooled.wrappedBuffer(message))); + getHandle().playerConnection.sendPacket(packet); + } + } + + @Override + public void setTexturePack(String url) { + setResourcePack(url); + } + + @Override + public void setResourcePack(String url) { + Validate.notNull(url, "Resource pack URL cannot be null"); + + getHandle().setResourcePack(url, "null"); + } + + public void addChannel(String channel) { + com.google.common.base.Preconditions + .checkState(channels.size() < 128, "Too many channels registered"); // Spigot + if (channels.add(channel)) { + server.getPluginManager().callEvent(new PlayerRegisterChannelEvent(this, channel)); + } + } + + public void removeChannel(String channel) { + if (channels.remove(channel)) { + server.getPluginManager().callEvent(new PlayerUnregisterChannelEvent(this, channel)); + } + } + + @Override + public Set getListeningPluginChannels() { + return ImmutableSet.copyOf(channels); + } + + public void sendSupportedChannels() { + if (getHandle().playerConnection == null) { + return; + } + Set listening = server.getMessenger().getIncomingChannels(); + + if (!listening.isEmpty()) { + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + + for (String channel : listening) { + try { + stream.write(channel.getBytes(StandardCharsets.UTF_8)); + stream.write((byte) 0); + } catch (IOException ex) { + Logger.getLogger(CraftPlayer.class.getName()) + .log(Level.SEVERE, "Could not send Plugin Channel REGISTER to " + getName(), ex); + } + } + + getHandle().playerConnection.sendPacket(new PacketPlayOutCustomPayload("REGISTER", + new PacketDataSerializer(Unpooled.wrappedBuffer(stream.toByteArray())))); + } + } + + @Override + public EntityType getType() { + return EntityType.PLAYER; + } + + @Override + public void setMetadata(String metadataKey, MetadataValue newMetadataValue) { + server.getPlayerMetadata().setMetadata(this, metadataKey, newMetadataValue); + } + + @Override + public List getMetadata(String metadataKey) { + return server.getPlayerMetadata().getMetadata(this, metadataKey); + } + + @Override + public boolean hasMetadata(String metadataKey) { + return server.getPlayerMetadata().hasMetadata(this, metadataKey); + } + + @Override + public void removeMetadata(String metadataKey, Plugin owningPlugin) { + server.getPlayerMetadata().removeMetadata(this, metadataKey, owningPlugin); + } + + @Override + public boolean setWindowProperty(Property prop, int value) { + Container container = getHandle().activeContainer; + if (container.getBukkitView().getType() != prop.getType()) { + return false; + } + getHandle().setContainerData(container, prop.getId(), value); + return true; + } + + public void disconnect(String reason) { + conversationTracker.abandonAllConversations(); + perm.clearPermissions(); + } + + @Override + public boolean isFlying() { + return getHandle().abilities.isFlying; + } + + @Override + public void setFlying(boolean value) { + boolean needsUpdate = getHandle().abilities.isFlying != value; // PaperSpigot - Only refresh abilities if needed // PandaSpigot - Fix GH-37 + if (!getAllowFlight() && value) { + throw new IllegalArgumentException("Cannot make player fly if getAllowFlight() is false"); + } + + getHandle().abilities.isFlying = value; + if (needsUpdate) { + getHandle().updateAbilities(); // PaperSpigot - Only refresh abilities if needed + } + } + + @Override + public boolean getAllowFlight() { + return getHandle().abilities.canFly; + } + + @Override + public void setAllowFlight(boolean value) { + if (isFlying() && !value) { + getHandle().abilities.isFlying = false; + } + + getHandle().abilities.canFly = value; + getHandle().updateAbilities(); + } + + @Override + public int getNoDamageTicks() { + if (getHandle().invulnerableTicks > 0) { + return Math.max(getHandle().invulnerableTicks, getHandle().noDamageTicks); + } else { + return getHandle().noDamageTicks; + } + } + + @Override + public void setFlySpeed(float value) { + validateSpeed(value); + EntityPlayer player = getHandle(); + player.abilities.flySpeed = Math.max(value, 0.0001f) / 2f; // Spigot + player.updateAbilities(); + + } + + @Override + public void setWalkSpeed(float value) { + validateSpeed(value); + EntityPlayer player = getHandle(); + player.abilities.walkSpeed = Math.max(value, 0.0001f) / 2f; // Spigot + player.updateAbilities(); + } + + @Override + public float getFlySpeed() { + return getHandle().abilities.flySpeed * 2f; + } + + @Override + public float getWalkSpeed() { + return getHandle().abilities.walkSpeed * 2f; + } + + private void validateSpeed(float value) { + if (value < 0) { + if (value < -1f) { + throw new IllegalArgumentException(value + " is too low"); + } + } else { + if (value > 1f) { + throw new IllegalArgumentException(value + " is too high"); + } + } + } + + @Override + public void setMaxHealth(double amount) { + super.setMaxHealth(amount); + this.health = Math.min(health, amount); + getHandle().triggerHealthUpdate(); + } + + @Override + public void resetMaxHealth() { + super.resetMaxHealth(); + getHandle().triggerHealthUpdate(); + } + + @Override + public CraftScoreboard getScoreboard() { + return this.server.getScoreboardManager().getPlayerBoard(this); + } + + @Override + public void setScoreboard(Scoreboard scoreboard) { + Validate.notNull(scoreboard, "Scoreboard cannot be null"); + PlayerConnection playerConnection = getHandle().playerConnection; + if (playerConnection == null) { + throw new IllegalStateException("Cannot set scoreboard yet"); + } + + this.server.getScoreboardManager().setPlayerBoard(this, scoreboard); + } + + @Override + public void setHealthScale(double value) { + Validate.isTrue((float) value > 0F, "Must be greater than 0"); + healthScale = value; + scaledHealth = true; + updateScaledHealth(); + } + + @Override + public double getHealthScale() { + return healthScale; + } + + @Override + public void setHealthScaled(boolean scale) { + if (scaledHealth != (scaledHealth = scale)) { + updateScaledHealth(); + } + } + + @Override + public boolean isHealthScaled() { + return scaledHealth; + } + + public float getScaledHealth() { + return (float) (isHealthScaled() ? getHealth() * getHealthScale() / getMaxHealth() : getHealth()); + } + + @Override + public double getHealth() { + return health; + } + + public void setRealHealth(double health) { + this.health = health; + } + + public void updateScaledHealth() { + AttributeMapServer attributemapserver = (AttributeMapServer) getHandle().getAttributeMap(); + Set set = attributemapserver.getAttributes(); + + injectScaledMaxHealth(set, true); + + // Beanes - reduce packets + float hp = getScaledHealth(); + if (hp > 0.0F) { + getHandle().getDataWatcher().setWithoutUpdate(6, hp); + } else { + getHandle().getDataWatcher().watch(6, hp); + } + + getHandle().updateHealthAndFood(); + + PacketPlayOutUpdateAttributes packet = new PacketPlayOutUpdateAttributes(getHandle().getId(), set); + + // Beanes - better slowdown + if (Azurite.getInstance().getBetterSlowdown().handleAttributes(getUniqueId(), packet)) { + getHandle().playerConnection.sendPacket(packet); + } + + + set.clear(); + getHandle().maxHealthCache = getMaxHealth(); + } + + public void injectScaledMaxHealth(Collection collection, boolean force) { + if (!scaledHealth && !force) { + return; + } + for (Object genericInstance : collection) { + IAttribute attribute = ((AttributeInstance) genericInstance).getAttribute(); + if (attribute.getName().equals("generic.maxHealth")) { + collection.remove(genericInstance); + break; + } + } + // Spigot start + double healthMod = scaledHealth ? healthScale : getMaxHealth(); + if (healthMod >= Float.MAX_VALUE || healthMod <= 0) { + healthMod = 20; // Reset health + getServer().getLogger().warning(getName() + " tried to crash the server with a large health attribute"); + } + collection.add(new AttributeModifiable(getHandle().getAttributeMap(), + (new AttributeRanged(null, "generic.maxHealth", healthMod, 0.0D, Float.MAX_VALUE)).a("Max Health") + .a(true))); + // Spigot end + } + + @Override + public org.bukkit.entity.Entity getSpectatorTarget() { + Entity followed = getHandle().C(); // PAIL + return followed == getHandle() ? null : followed.getBukkitEntity(); + } + + @Override + public void setSpectatorTarget(org.bukkit.entity.Entity entity) { + Preconditions.checkArgument(getGameMode() == GameMode.SPECTATOR, "Player must be in spectator mode"); + getHandle().setSpectatorTarget((entity == null) ? null : ((CraftEntity) entity).getHandle()); + } + + @Override + public void sendTitle(String title, String subtitle) { + if (title != null) { + PacketPlayOutTitle packetTitle = new PacketPlayOutTitle(EnumTitleAction.TITLE, + CraftChatMessage.fromString(title)[0]); + getHandle().playerConnection.sendPacket(packetTitle); + } + + if (subtitle != null) { + PacketPlayOutTitle packetSubtitle = new PacketPlayOutTitle(EnumTitleAction.SUBTITLE, + CraftChatMessage.fromString(subtitle)[0]); + getHandle().playerConnection.sendPacket(packetSubtitle); + } + } + + @Override + public void resetTitle() { + PacketPlayOutTitle packetReset = new PacketPlayOutTitle(EnumTitleAction.RESET, null); + getHandle().playerConnection.sendPacket(packetReset); + } + + // Spigot start + private final Player.Spigot spigot = new Player.Spigot() { + + @Override + public InetSocketAddress getRawAddress() { + return (InetSocketAddress) getHandle().playerConnection.networkManager.getRawAddress(); + } + + @Override + public boolean getCollidesWithEntities() { + return getHandle().collidesWithEntities; + } + + @Override + public void setCollidesWithEntities(boolean collides) { + getHandle().collidesWithEntities = collides; + getHandle().k = collides; // First boolean of Entity + } + + @Override + public void respawn() { + if (getHealth() <= 0 && isOnline()) { + server.getServer().getPlayerList().moveToWorld(getHandle(), 0, false); + } + } + + @Override + public void playEffect(Location location, Effect effect, int id, int data, float offsetX, float offsetY, + float offsetZ, float speed, int particleCount, int radius) { + Validate.notNull(location, "Location cannot be null"); + Validate.notNull(effect, "Effect cannot be null"); + Validate.notNull(location.getWorld(), "World cannot be null"); + Packet packet; + if (effect.getType() != Effect.Type.PARTICLE) { + int packetData = effect.getId(); + packet = new PacketPlayOutWorldEvent(packetData, new BlockPosition(location.getBlockX(), location.getBlockY(), location.getBlockZ()), id, + false); + } else { + EnumParticle particle; + int[] extra = null; + if ((particle = EnumParticle.EFFECT_TO_PARTICLE.get(effect)) != null && effect.getData() != null) { + if (effect.getData().equals(Material.class)) { + extra = new int[]{id}; + } else { + extra = new int[]{data << 12 | id & 0xFFF}; + } + } + if (extra == null) { + extra = EnumParticle.EMPTY_ARRAY; + } + packet = new PacketPlayOutWorldParticles(particle, true, (float) location.getX(), + (float) location.getY(), (float) location.getZ(), offsetX, offsetY, offsetZ, speed, + particleCount, extra); + } + int distance; + radius *= radius; + if (getHandle().playerConnection == null) { + return; + } + if (!location.getWorld().equals(getWorld())) { + return; + } + + distance = (int) getLocation().distanceSquared(location); + if (distance <= radius) { + getHandle().playerConnection.sendPacket(packet); + } + } + + @Override + public String getLocale() { + return getHandle().locale; + } + + @Override + public Set getHiddenPlayers() { + Set players = new HashSet<>(); + + for (UUID uuid : hiddenPlayers) { + players.add(getServer().getPlayer(uuid)); + } + + return Collections.unmodifiableSet(players); + } + + @Override + public void sendMessage(BaseComponent component) { + sendMessage(new BaseComponent[]{component}); + } + + @Override + public void sendMessage(BaseComponent... components) { + if (getHandle().playerConnection == null) { + return; + } + + PacketPlayOutChat packet = new PacketPlayOutChat(); + packet.components = components; + packet.serializeJson(); // Beanes - only serialize chat json once + getHandle().playerConnection.sendPacket(packet); + } + + // PaperSpigot start - Implement affects spawning API + @Override + public boolean getAffectsSpawning() { + return getHandle().affectsSpawning; + } + + @Override + public void setAffectsSpawning(boolean affects) { + getHandle().affectsSpawning = affects; + } + // PaperSpigot end + + // PaperSpigot start - Player view distance API + @Override + public int getViewDistance() { + return getHandle().viewDistance; + } + + @Override + public void setViewDistance(int viewDistance) { + ((WorldServer) getHandle().world).getPlayerChunkMap().updateViewDistance(getHandle(), viewDistance); + } + // PaperSpigot end + + @Override + public int getPing() { + return getHandle().ping; + } + }; + + public Player.Spigot spigot() { + return spigot; + } + // Spigot end + + @Override + public int getPing() { + return getHandle().ping; + } + +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftProjectile.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftProjectile.java new file mode 100644 index 0000000..67122c6 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftProjectile.java @@ -0,0 +1,61 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityLiving; +import net.minecraft.server.EntityProjectile; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Projectile; +import org.bukkit.projectiles.ProjectileSource; + +public abstract class CraftProjectile extends AbstractProjectile implements Projectile { + public CraftProjectile(CraftServer server, net.minecraft.server.Entity entity) { + super(server, entity); + } + + public ProjectileSource getShooter() { + return getHandle().projectileSource; + } + + public void setShooter(ProjectileSource shooter) { + if (shooter instanceof CraftLivingEntity) { + getHandle().shooter = (EntityLiving) ((CraftLivingEntity) shooter).entity; + if (shooter instanceof CraftHumanEntity) { + getHandle().shooterName = ((CraftHumanEntity) shooter).getName(); + } + } else { + getHandle().shooter = null; + getHandle().shooterName = null; + } + getHandle().projectileSource = shooter; + } + + @Override + public EntityProjectile getHandle() { + return (EntityProjectile) entity; + } + + @Override + public String toString() { + return "CraftProjectile"; + } + + + @Deprecated + public LivingEntity _INVALID_getShooter() { + if (getHandle().shooter == null) { + return null; + } + return (LivingEntity) getHandle().shooter.getBukkitEntity(); + } + + @Deprecated + public void _INVALID_setShooter(LivingEntity shooter) { + if (shooter == null) { + return; + } + getHandle().shooter = ((CraftLivingEntity) shooter).getHandle(); + if (shooter instanceof CraftHumanEntity) { + getHandle().shooterName = shooter.getName(); + } + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftRabbit.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftRabbit.java new file mode 100644 index 0000000..0beaf09 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftRabbit.java @@ -0,0 +1,85 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityRabbit; +import net.minecraft.server.PathfinderGoalSelector; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Rabbit; + +public class CraftRabbit extends CraftAnimals implements Rabbit { + + public CraftRabbit(CraftServer server, EntityRabbit entity) { + super(server, entity); + } + + @Override + public EntityRabbit getHandle() { + return (EntityRabbit) entity; + } + + @Override + public String toString() { + return "CraftRabbit{RabbitType=" + getRabbitType() + "}"; + } + + @Override + public EntityType getType() { + return EntityType.RABBIT; + } + + @Override + public Type getRabbitType() { + int type = getHandle().getRabbitType(); + return CraftMagicMapping.fromMagic(type); + } + + @Override + public void setRabbitType(Type type) { + EntityRabbit entity = getHandle(); + if (getRabbitType() == Type.THE_KILLER_BUNNY) { + // Reset goals and target finders. + entity.goalSelector = new PathfinderGoalSelector(null); + entity.targetSelector = new PathfinderGoalSelector(null); + entity.initializePathFinderGoals(); + } + + entity.setRabbitType(CraftMagicMapping.toMagic(type)); + } + + private static class CraftMagicMapping { + + private static final int[] types = new int[Type.values().length]; + private static final Type[] reverse = new Type[Type.values().length]; + + static { + set(Type.BROWN, 0); + set(Type.WHITE, 1); + set(Type.BLACK, 2); + set(Type.BLACK_AND_WHITE, 3); + set(Type.GOLD, 4); + set(Type.SALT_AND_PEPPER, 5); + set(Type.THE_KILLER_BUNNY, 99); + } + + private static void set(Type type, int value) { + types[type.ordinal()] = value; + if (value < reverse.length) { + reverse[value] = type; + } + } + + public static Type fromMagic(int magic) { + if (magic >= 0 && magic < reverse.length) { + return reverse[magic]; + } else if (magic == 99) { + return Type.THE_KILLER_BUNNY; + } else { + return null; + } + } + + public static int toMagic(Type type) { + return types[type.ordinal()]; + } + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftSheep.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftSheep.java new file mode 100644 index 0000000..107881a --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftSheep.java @@ -0,0 +1,44 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntitySheep; +import net.minecraft.server.EnumColor; +import org.bukkit.DyeColor; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Sheep; + +public class CraftSheep extends CraftAnimals implements Sheep { + public CraftSheep(CraftServer server, EntitySheep entity) { + super(server, entity); + } + + public DyeColor getColor() { + return DyeColor.getByWoolData((byte) getHandle().getColor().getColorIndex()); + } + + public void setColor(DyeColor color) { + getHandle().setColor(EnumColor.fromColorIndex(color.getWoolData())); + } + + public boolean isSheared() { + return getHandle().isSheared(); + } + + public void setSheared(boolean flag) { + getHandle().setSheared(flag); + } + + @Override + public EntitySheep getHandle() { + return (EntitySheep) entity; + } + + @Override + public String toString() { + return "CraftSheep"; + } + + public EntityType getType() { + return EntityType.SHEEP; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftSilverfish.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftSilverfish.java new file mode 100644 index 0000000..fe18098 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftSilverfish.java @@ -0,0 +1,26 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntitySilverfish; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Silverfish; + +public class CraftSilverfish extends CraftMonster implements Silverfish { + public CraftSilverfish(CraftServer server, EntitySilverfish entity) { + super(server, entity); + } + + @Override + public EntitySilverfish getHandle() { + return (EntitySilverfish) entity; + } + + @Override + public String toString() { + return "CraftSilverfish"; + } + + public EntityType getType() { + return EntityType.SILVERFISH; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftSkeleton.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftSkeleton.java new file mode 100644 index 0000000..05e0d76 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftSkeleton.java @@ -0,0 +1,37 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntitySkeleton; +import org.apache.commons.lang.Validate; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Skeleton; + +public class CraftSkeleton extends CraftMonster implements Skeleton { + + public CraftSkeleton(CraftServer server, EntitySkeleton entity) { + super(server, entity); + } + + @Override + public EntitySkeleton getHandle() { + return (EntitySkeleton) entity; + } + + @Override + public String toString() { + return "CraftSkeleton"; + } + + public EntityType getType() { + return EntityType.SKELETON; + } + + public SkeletonType getSkeletonType() { + return SkeletonType.getType(getHandle().getSkeletonType()); + } + + public void setSkeletonType(SkeletonType type) { + Validate.notNull(type); + getHandle().setSkeletonType(type.getId()); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftSlime.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftSlime.java new file mode 100644 index 0000000..00020db --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftSlime.java @@ -0,0 +1,35 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntitySlime; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Slime; + +public class CraftSlime extends CraftLivingEntity implements Slime { + + public CraftSlime(CraftServer server, EntitySlime entity) { + super(server, entity); + } + + public int getSize() { + return getHandle().getSize(); + } + + public void setSize(int size) { + getHandle().setSize(size); + } + + @Override + public EntitySlime getHandle() { + return (EntitySlime) entity; + } + + @Override + public String toString() { + return "CraftSlime"; + } + + public EntityType getType() { + return EntityType.SLIME; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftSmallFireball.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftSmallFireball.java new file mode 100644 index 0000000..7200970 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftSmallFireball.java @@ -0,0 +1,26 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntitySmallFireball; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.SmallFireball; + +public class CraftSmallFireball extends CraftFireball implements SmallFireball { + public CraftSmallFireball(CraftServer server, EntitySmallFireball entity) { + super(server, entity); + } + + @Override + public EntitySmallFireball getHandle() { + return (EntitySmallFireball) entity; + } + + @Override + public String toString() { + return "CraftSmallFireball"; + } + + public EntityType getType() { + return EntityType.SMALL_FIREBALL; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftSnowball.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftSnowball.java new file mode 100644 index 0000000..44de749 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftSnowball.java @@ -0,0 +1,26 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntitySnowball; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Snowball; + +public class CraftSnowball extends CraftProjectile implements Snowball { + public CraftSnowball(CraftServer server, EntitySnowball entity) { + super(server, entity); + } + + @Override + public EntitySnowball getHandle() { + return (EntitySnowball) entity; + } + + @Override + public String toString() { + return "CraftSnowball"; + } + + public EntityType getType() { + return EntityType.SNOWBALL; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftSnowman.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftSnowman.java new file mode 100644 index 0000000..319a3f3 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftSnowman.java @@ -0,0 +1,26 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntitySnowman; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Snowman; + +public class CraftSnowman extends CraftGolem implements Snowman { + public CraftSnowman(CraftServer server, EntitySnowman entity) { + super(server, entity); + } + + @Override + public EntitySnowman getHandle() { + return (EntitySnowman) entity; + } + + @Override + public String toString() { + return "CraftSnowman"; + } + + public EntityType getType() { + return EntityType.SNOWMAN; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftSpider.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftSpider.java new file mode 100644 index 0000000..8412397 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftSpider.java @@ -0,0 +1,27 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntitySpider; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Spider; + +public class CraftSpider extends CraftMonster implements Spider { + + public CraftSpider(CraftServer server, EntitySpider entity) { + super(server, entity); + } + + @Override + public EntitySpider getHandle() { + return (EntitySpider) entity; + } + + @Override + public String toString() { + return "CraftSpider"; + } + + public EntityType getType() { + return EntityType.SPIDER; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftSquid.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftSquid.java new file mode 100644 index 0000000..cb81d91 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftSquid.java @@ -0,0 +1,27 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntitySquid; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Squid; + +public class CraftSquid extends CraftWaterMob implements Squid { + + public CraftSquid(CraftServer server, EntitySquid entity) { + super(server, entity); + } + + @Override + public EntitySquid getHandle() { + return (EntitySquid) entity; + } + + @Override + public String toString() { + return "CraftSquid"; + } + + public EntityType getType() { + return EntityType.SQUID; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftTNTPrimed.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftTNTPrimed.java new file mode 100644 index 0000000..72df176 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftTNTPrimed.java @@ -0,0 +1,74 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityLiving; +import net.minecraft.server.EntityTNTPrimed; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.TNTPrimed; + +public class CraftTNTPrimed extends CraftEntity implements TNTPrimed { + + public CraftTNTPrimed(CraftServer server, EntityTNTPrimed entity) { + super(server, entity); + } + + public float getYield() { + return getHandle().yield; + } + + public boolean isIncendiary() { + return getHandle().isIncendiary; + } + + public void setIsIncendiary(boolean isIncendiary) { + getHandle().isIncendiary = isIncendiary; + } + + public void setYield(float yield) { + getHandle().yield = yield; + } + + public int getFuseTicks() { + return getHandle().fuseTicks; + } + + public void setFuseTicks(int fuseTicks) { + getHandle().fuseTicks = fuseTicks; + } + + @Override + public EntityTNTPrimed getHandle() { + return (EntityTNTPrimed) entity; + } + + @Override + public String toString() { + return "CraftTNTPrimed"; + } + + public EntityType getType() { + return EntityType.PRIMED_TNT; + } + + public Entity getSource() { + EntityLiving source = getHandle().getSource(); + + if (source != null) { + Entity bukkitEntity = source.getBukkitEntity(); + + if (bukkitEntity.isValid()) { + return bukkitEntity; + } + } + + return null; + } + + // PaperSpigot start + @Override + public org.bukkit.Location getSourceLoc() { + return getHandle().sourceLoc; + } + // PaperSpigot end +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftTameableAnimal.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftTameableAnimal.java new file mode 100644 index 0000000..8feac2a --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftTameableAnimal.java @@ -0,0 +1,85 @@ +package org.bukkit.craftbukkit.entity; + +import com.eatthepath.uuid.FastUUID; +import net.minecraft.server.EntityTameableAnimal; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.AnimalTamer; +import org.bukkit.entity.Creature; +import org.bukkit.entity.Tameable; + +import java.util.UUID; + +public class CraftTameableAnimal extends CraftAnimals implements Tameable, Creature { + public CraftTameableAnimal(CraftServer server, EntityTameableAnimal entity) { + super(server, entity); + } + + @Override + public EntityTameableAnimal getHandle() { + return (EntityTameableAnimal)super.getHandle(); + } + + public UUID getOwnerUUID() { + try { + return FastUUID.parseUUID(getHandle().getOwnerUUID()); + } catch (IllegalArgumentException ex) { + return null; + } + } + + public void setOwnerUUID(UUID uuid) { + if (uuid == null) { + getHandle().setOwnerUUID(""); + } else { + getHandle().setOwnerUUID(uuid.toString()); + } + } + + public AnimalTamer getOwner() { + if (getOwnerUUID() == null) { + return null; + } + + AnimalTamer owner = getServer().getPlayer(getOwnerUUID()); + if (owner == null) { + owner = getServer().getOfflinePlayer(getOwnerUUID()); + } + + return owner; + } + + public boolean isTamed() { + return getHandle().isTamed(); + } + + public void setOwner(AnimalTamer tamer) { + if (tamer != null) { + setTamed(true); + getHandle().setGoalTarget(null, null, false); + setOwnerUUID(tamer.getUniqueId()); + } else { + setTamed(false); + setOwnerUUID(null); + } + } + + public void setTamed(boolean tame) { + getHandle().setTamed(tame); + if (!tame) { + setOwnerUUID(null); + } + } + + public boolean isSitting() { + return getHandle().isSitting(); + } + + public void setSitting(boolean sitting) { + getHandle().getGoalSit().setSitting(sitting); + } + + @Override + public String toString() { + return getClass().getSimpleName() + "{owner=" + getOwner() + ",tamed=" + isTamed() + "}"; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftThrownExpBottle.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftThrownExpBottle.java new file mode 100644 index 0000000..fb3416e --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftThrownExpBottle.java @@ -0,0 +1,26 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityThrownExpBottle; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.ThrownExpBottle; + +public class CraftThrownExpBottle extends CraftProjectile implements ThrownExpBottle { + public CraftThrownExpBottle(CraftServer server, EntityThrownExpBottle entity) { + super(server, entity); + } + + @Override + public EntityThrownExpBottle getHandle() { + return (EntityThrownExpBottle) entity; + } + + @Override + public String toString() { + return "EntityThrownExpBottle"; + } + + public EntityType getType() { + return EntityType.THROWN_EXP_BOTTLE; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftThrownPotion.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftThrownPotion.java new file mode 100644 index 0000000..c1c41de --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftThrownPotion.java @@ -0,0 +1,57 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityPotion; +import org.apache.commons.lang.Validate; +import org.bukkit.Material; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.ThrownPotion; +import org.bukkit.inventory.ItemStack; +import org.bukkit.potion.Potion; +import org.bukkit.potion.PotionEffect; + +import java.util.Collection; + +public class CraftThrownPotion extends CraftProjectile implements ThrownPotion { + public CraftThrownPotion(CraftServer server, EntityPotion entity) { + super(server, entity); + } + + // TODO: This one does not handle custom NBT potion effects does it? + // In that case this method could be said to be misleading or incorrect + public Collection getEffects() { + return Potion.getBrewer().getEffectsFromDamage(getHandle().getPotionValue()); + } + + public ItemStack getItem() { + // We run this method once since it will set the item stack if there is none. + getHandle().getPotionValue(); + + return CraftItemStack.asBukkitCopy(getHandle().item); + } + + public void setItem(ItemStack item) { + // The ItemStack must not be null. + Validate.notNull(item, "ItemStack cannot be null."); + + // The ItemStack must be a potion. + Validate.isTrue(item.getType() == Material.POTION, "ItemStack must be a potion. This item stack was " + item.getType() + "."); + + getHandle().item = CraftItemStack.asNMSCopy(item); + } + + @Override + public EntityPotion getHandle() { + return (EntityPotion) entity; + } + + @Override + public String toString() { + return "CraftThrownPotion"; + } + + public EntityType getType() { + return EntityType.SPLASH_POTION; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftVehicle.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftVehicle.java new file mode 100644 index 0000000..8e4af46 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftVehicle.java @@ -0,0 +1,15 @@ +package org.bukkit.craftbukkit.entity; + +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.Vehicle; + +public abstract class CraftVehicle extends CraftEntity implements Vehicle { + public CraftVehicle(CraftServer server, net.minecraft.server.Entity entity) { + super(server, entity); + } + + @Override + public String toString() { + return "CraftVehicle{passenger=" + getPassenger() + '}'; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftVillager.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftVillager.java new file mode 100644 index 0000000..6fe21cc --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftVillager.java @@ -0,0 +1,44 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityVillager; +import org.apache.commons.lang.Validate; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.inventory.CraftInventory; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Villager; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryHolder; + +public class CraftVillager extends CraftAgeable implements Villager, InventoryHolder { + public CraftVillager(CraftServer server, EntityVillager entity) { + super(server, entity); + } + + @Override + public EntityVillager getHandle() { + return (EntityVillager) entity; + } + + @Override + public String toString() { + return "CraftVillager"; + } + + public EntityType getType() { + return EntityType.VILLAGER; + } + + public Profession getProfession() { + return Profession.getProfession(getHandle().getProfession()); + } + + public void setProfession(Profession profession) { + Validate.notNull(profession); + getHandle().setProfession(profession.getId()); + } + + @Override + public Inventory getInventory() { + return new CraftInventory(getHandle().inventory); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftWaterMob.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftWaterMob.java new file mode 100644 index 0000000..c47d06d --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftWaterMob.java @@ -0,0 +1,22 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityWaterAnimal; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.WaterMob; + +public class CraftWaterMob extends CraftLivingEntity implements WaterMob { + + public CraftWaterMob(CraftServer server, EntityWaterAnimal entity) { + super(server, entity); + } + + @Override + public EntityWaterAnimal getHandle() { + return (EntityWaterAnimal) entity; + } + + @Override + public String toString() { + return "CraftWaterMob"; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftWeather.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftWeather.java new file mode 100644 index 0000000..91a7493 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftWeather.java @@ -0,0 +1,26 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityWeather; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Weather; + +public class CraftWeather extends CraftEntity implements Weather { + public CraftWeather(final CraftServer server, final EntityWeather entity) { + super(server, entity); + } + + @Override + public EntityWeather getHandle() { + return (EntityWeather) entity; + } + + @Override + public String toString() { + return "CraftWeather"; + } + + public EntityType getType() { + return EntityType.WEATHER; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftWitch.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftWitch.java new file mode 100644 index 0000000..267700d --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftWitch.java @@ -0,0 +1,26 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityWitch; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Witch; + +public class CraftWitch extends CraftMonster implements Witch { + public CraftWitch(CraftServer server, EntityWitch entity) { + super(server, entity); + } + + @Override + public EntityWitch getHandle() { + return (EntityWitch) entity; + } + + @Override + public String toString() { + return "CraftWitch"; + } + + public EntityType getType() { + return EntityType.WITCH; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftWither.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftWither.java new file mode 100644 index 0000000..1905c0d --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftWither.java @@ -0,0 +1,26 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityWither; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Wither; + +public class CraftWither extends CraftMonster implements Wither { + public CraftWither(CraftServer server, EntityWither entity) { + super(server, entity); + } + + @Override + public EntityWither getHandle() { + return (EntityWither) entity; + } + + @Override + public String toString() { + return "CraftWither"; + } + + public EntityType getType() { + return EntityType.WITHER; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftWitherSkull.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftWitherSkull.java new file mode 100644 index 0000000..563177e --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftWitherSkull.java @@ -0,0 +1,36 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityWitherSkull; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.WitherSkull; + +public class CraftWitherSkull extends CraftFireball implements WitherSkull { + public CraftWitherSkull(CraftServer server, EntityWitherSkull entity) { + super(server, entity); + } + + @Override + public void setCharged(boolean charged) { + getHandle().setCharged(charged); + } + + @Override + public boolean isCharged() { + return getHandle().isCharged(); + } + + @Override + public EntityWitherSkull getHandle() { + return (EntityWitherSkull) entity; + } + + @Override + public String toString() { + return "CraftWitherSkull"; + } + + public EntityType getType() { + return EntityType.WITHER_SKULL; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftWolf.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftWolf.java new file mode 100644 index 0000000..55ce37c --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftWolf.java @@ -0,0 +1,40 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityWolf; +import net.minecraft.server.EnumColor; +import org.bukkit.DyeColor; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Wolf; + +public class CraftWolf extends CraftTameableAnimal implements Wolf { + public CraftWolf(CraftServer server, EntityWolf wolf) { + super(server, wolf); + } + + public boolean isAngry() { + return getHandle().isAngry(); + } + + public void setAngry(boolean angry) { + getHandle().setAngry(angry); + } + + @Override + public EntityWolf getHandle() { + return (EntityWolf) entity; + } + + @Override + public EntityType getType() { + return EntityType.WOLF; + } + + public DyeColor getCollarColor() { + return DyeColor.getByWoolData((byte) getHandle().getCollarColor().getColorIndex()); + } + + public void setCollarColor(DyeColor color) { + getHandle().setCollarColor(EnumColor.fromColorIndex(color.getWoolData())); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftZombie.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftZombie.java new file mode 100644 index 0000000..387db55 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/entity/CraftZombie.java @@ -0,0 +1,43 @@ +package org.bukkit.craftbukkit.entity; + +import net.minecraft.server.EntityZombie; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Zombie; + +public class CraftZombie extends CraftMonster implements Zombie { + + public CraftZombie(CraftServer server, EntityZombie entity) { + super(server, entity); + } + + @Override + public EntityZombie getHandle() { + return (EntityZombie) entity; + } + + @Override + public String toString() { + return "CraftZombie"; + } + + public EntityType getType() { + return EntityType.ZOMBIE; + } + + public boolean isBaby() { + return getHandle().isBaby(); + } + + public void setBaby(boolean flag) { + getHandle().setBaby(flag); + } + + public boolean isVillager() { + return getHandle().isVillager(); + } + + public void setVillager(boolean flag) { + getHandle().setVillager(flag); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/event/CraftEventFactory.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/event/CraftEventFactory.java new file mode 100644 index 0000000..9449c77 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/event/CraftEventFactory.java @@ -0,0 +1,1019 @@ +package org.bukkit.craftbukkit.event; + +import com.google.common.base.Function; +import com.google.common.base.Functions; +import dev.azurite.spigot.configs.AzuriteConfig; +import net.minecraft.server.Entity; +import net.minecraft.server.*; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Server; +import org.bukkit.Statistic.Type; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.block.BlockState; +import org.bukkit.block.CreatureSpawner; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.CraftStatistic; +import org.bukkit.craftbukkit.CraftWorld; +import org.bukkit.craftbukkit.block.CraftBlock; +import org.bukkit.craftbukkit.block.CraftBlockState; +import org.bukkit.craftbukkit.entity.CraftEntity; +import org.bukkit.craftbukkit.entity.CraftLivingEntity; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.craftbukkit.inventory.CraftInventoryCrafting; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.craftbukkit.inventory.CraftMetaBook; +import org.bukkit.craftbukkit.util.CraftDamageSource; +import org.bukkit.craftbukkit.util.CraftMagicNumbers; +import org.bukkit.entity.*; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.block.*; +import org.bukkit.event.block.BlockIgniteEvent.IgniteCause; +import org.bukkit.event.entity.*; +import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason; +import org.bukkit.event.entity.EntityDamageEvent.DamageCause; +import org.bukkit.event.entity.EntityDamageEvent.DamageModifier; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.event.inventory.InventoryOpenEvent; +import org.bukkit.event.inventory.PrepareItemCraftEvent; +import org.bukkit.event.player.*; +import org.bukkit.event.server.ServerListPingEvent; +import org.bukkit.inventory.InventoryView; +import org.bukkit.inventory.meta.BookMeta; +import org.bukkit.util.Vector; + +import java.net.InetAddress; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; + +public class CraftEventFactory { + public static final DamageSource MELTING = CraftDamageSource.copyOf(DamageSource.BURN); + public static final DamageSource POISON = CraftDamageSource.copyOf(DamageSource.MAGIC); + private static final Function ZERO = Functions.constant(-0.0); + public static org.bukkit.block.Block blockDamage; // For use in EntityDamageByBlockEvent + public static Entity entityDamage; // For use in EntityDamageByEntityEvent + + // helper methods + private static boolean canBuild(CraftWorld world, Player player, int x, int z) { + WorldServer worldServer = world.getHandle(); + int spawnSize = Bukkit.getServer().getSpawnRadius(); + + if (world.getHandle().dimension != 0) return true; + if (spawnSize <= 0) return true; + if (((CraftServer) Bukkit.getServer()).getHandle().getOPs().isEmpty()) return true; + if (player.isOp()) return true; + + BlockPosition chunkcoordinates = worldServer.getSpawn(); + + int distanceFromSpawn = Math.max(Math.abs(x - chunkcoordinates.getX()), Math.abs(z - chunkcoordinates.getY())); + return distanceFromSpawn > spawnSize; + } + + public static T callEvent(T event) { + Bukkit.getServer().getPluginManager().callEvent(event); + return event; + } + + /** + * Block place methods + */ + public static BlockMultiPlaceEvent callBlockMultiPlaceEvent(World world, EntityHuman who, List blockStates, int clickedX, int clickedY, int clickedZ) { + CraftWorld craftWorld = world.getWorld(); + CraftServer craftServer = world.getServer(); + Player player = (who == null) ? null : (Player) who.getBukkitEntity(); + + Block blockClicked = craftWorld.getBlockAt(clickedX, clickedY, clickedZ); + + boolean canBuild = true; + for (BlockState blockState : blockStates) { + if (!canBuild(craftWorld, player, blockState.getX(), blockState.getZ())) { + canBuild = false; + break; + } + } + + BlockMultiPlaceEvent event = new BlockMultiPlaceEvent(blockStates, blockClicked, player.getItemInHand(), player, canBuild); + craftServer.getPluginManager().callEvent(event); + + return event; + } + + public static BlockPlaceEvent callBlockPlaceEvent(World world, EntityHuman who, BlockState replacedBlockState, int clickedX, int clickedY, int clickedZ) { + CraftWorld craftWorld = world.getWorld(); + CraftServer craftServer = world.getServer(); + + Player player = (who == null) ? null : (Player) who.getBukkitEntity(); + + Block blockClicked = craftWorld.getBlockAt(clickedX, clickedY, clickedZ); + Block placedBlock = replacedBlockState.getBlock(); + + boolean canBuild = canBuild(craftWorld, player, placedBlock.getX(), placedBlock.getZ()); + + BlockPlaceEvent event = new BlockPlaceEvent(placedBlock, replacedBlockState, blockClicked, player.getItemInHand(), player, canBuild); + craftServer.getPluginManager().callEvent(event); + + return event; + } + + /** + * Mob spawner event + */ + public static SpawnerSpawnEvent callSpawnerSpawnEvent(Entity spawnee, int spawnerX, int spawnerY, int spawnerZ) { + org.bukkit.craftbukkit.entity.CraftEntity entity = spawnee.getBukkitEntity(); + BlockState state = entity.getWorld().getBlockAt(spawnerX, spawnerY, spawnerZ).getState(); + + if (!(state instanceof CreatureSpawner)) { + state = null; + } + + SpawnerSpawnEvent event = new SpawnerSpawnEvent(entity, (CreatureSpawner) state); + entity.getServer().getPluginManager().callEvent(event); + return event; + } + + /** + * Bucket methods + */ + public static PlayerBucketEmptyEvent callPlayerBucketEmptyEvent(EntityHuman who, int clickedX, int clickedY, int clickedZ, EnumDirection clickedFace, ItemStack itemInHand) { + return (PlayerBucketEmptyEvent) getPlayerBucketEvent(false, who, clickedX, clickedY, clickedZ, clickedFace, itemInHand, Items.BUCKET); + } + + public static PlayerBucketFillEvent callPlayerBucketFillEvent(EntityHuman who, int clickedX, int clickedY, int clickedZ, EnumDirection clickedFace, ItemStack itemInHand, net.minecraft.server.Item bucket) { + return (PlayerBucketFillEvent) getPlayerBucketEvent(true, who, clickedX, clickedY, clickedZ, clickedFace, itemInHand, bucket); + } + + private static PlayerEvent getPlayerBucketEvent(boolean isFilling, EntityHuman who, int clickedX, int clickedY, int clickedZ, EnumDirection clickedFace, ItemStack itemstack, net.minecraft.server.Item item) { + Player player = (who == null) ? null : (Player) who.getBukkitEntity(); + CraftItemStack itemInHand = CraftItemStack.asNewCraftStack(item); + Material bucket = CraftMagicNumbers.getMaterial(itemstack.getItem()); + + CraftWorld craftWorld = (CraftWorld) player.getWorld(); + CraftServer craftServer = (CraftServer) player.getServer(); + + Block blockClicked = craftWorld.getBlockAt(clickedX, clickedY, clickedZ); + BlockFace blockFace = CraftBlock.notchToBlockFace(clickedFace); + + PlayerEvent event = null; + if (isFilling) { + event = new PlayerBucketFillEvent(player, blockClicked, blockFace, bucket, itemInHand); + ((PlayerBucketFillEvent) event).setCancelled(!canBuild(craftWorld, player, clickedX, clickedZ)); + } else { + event = new PlayerBucketEmptyEvent(player, blockClicked, blockFace, bucket, itemInHand); + ((PlayerBucketEmptyEvent) event).setCancelled(!canBuild(craftWorld, player, clickedX, clickedZ)); + } + + craftServer.getPluginManager().callEvent(event); + + return event; + } + + /** + * Player Interact event + */ + public static PlayerInteractEvent callPlayerInteractEvent(EntityHuman who, Action action, ItemStack itemstack) { + if (action != Action.LEFT_CLICK_AIR && action != Action.RIGHT_CLICK_AIR) { + throw new IllegalArgumentException(String.format("%s performing %s with %s", who, action, itemstack)); // Spigot + } + return callPlayerInteractEvent(who, action, null, null, EnumDirection.SOUTH, itemstack, false); // SPIGOT-2380 - Change BlockPosition to null + } + + public static PlayerInteractEvent callPlayerInteractEvent(EntityHuman who, Action action, BlockPosition position, EnumDirection direction, ItemStack itemstack) { + return callPlayerInteractEvent(who, action, position, direction, itemstack, false); + } + + public static PlayerInteractEvent callPlayerInteractEvent(EntityHuman who, Action action, BlockPosition position, EnumDirection direction, ItemStack itemstack, boolean cancelledBlock) { + return callPlayerInteractEvent(who, action, who.getBukkitEntity().getWorld().getBlockAt(position.getX(), position.getY(), position.getZ()), position, direction, itemstack, cancelledBlock); + } + + public static PlayerInteractEvent callPlayerInteractEvent(EntityHuman who, Action action, Block blockClicked, BlockPosition position, EnumDirection direction, ItemStack itemstack, boolean cancelledBlock) { + Player player = (who == null) ? null : (Player) who.getBukkitEntity(); + CraftItemStack itemInHand = CraftItemStack.asCraftMirror(itemstack); + BlockFace blockFace = CraftBlock.notchToBlockFace(direction); + + // SPIGOT-2380 - Change BlockPosition to null + if (position != null && position.getY() > 255) { + blockClicked = null; + switch (action) { + case LEFT_CLICK_BLOCK: + action = Action.LEFT_CLICK_AIR; + break; + case RIGHT_CLICK_BLOCK: + action = Action.RIGHT_CLICK_AIR; + break; + } + } + + if (itemInHand.getType() == Material.AIR || itemInHand.getAmount() == 0) { + itemInHand = null; + } + + PlayerInteractEvent event = new PlayerInteractEvent(player, action, itemInHand, blockClicked, blockFace); + if (cancelledBlock) { + event.setUseInteractedBlock(Event.Result.DENY); + } + Bukkit.getServer().getPluginManager().callEvent(event); + + if (AzuriteConfig.fixFreecamCegging.getValue() && event.getAction() == Action.RIGHT_CLICK_BLOCK && !event.isCancelled() && blockClicked != null) { + if ((event.getItem() != null && event.getItem().getType() == Material.MONSTER_EGG) || blockClicked.getState() instanceof org.bukkit.inventory.InventoryHolder) { + Vector origin = player.getEyeLocation().toVector(); + Vector eyeDirection = player.getEyeLocation().getDirection(); + Block rayTraced = null; + double d; + for (d = 0.0D; d <= 5.0D; d += 0.01D) { + Block currentBlock; + Location currentLoc; + Material currentMat = (currentBlock = (currentLoc = origin.clone().add(eyeDirection.clone().multiply(d)).toLocation(player.getWorld())).getBlock()).getType(); + if (isSolidBlock(currentBlock, currentMat, currentLoc)) { + rayTraced = currentBlock; + break; + } + } + if (!blockClicked.equals(rayTraced)) { + event.setCancelled(true); + } + } + } + return event; + } + + private static boolean isSolidBlock(Block block, Material material, Location location) { + if (material == Material.AIR || block.isLiquid() || block.getState() instanceof org.bukkit.block.Sign || block.getState().getData() instanceof org.bukkit.material.Stairs) + return false; + BoundingBox aabb = new BoundingBox(block); + return (!(location.getX() < aabb.getMin().getX()) && !(location.getX() > aabb.getMax().getX())) && (!(location.getY() < aabb.getMin().getY()) && !(location.getY() > aabb.getMax().getY())) && (!(location.getZ() < aabb.getMin().getZ()) && !(location.getZ() > aabb.getMax().getZ())); + } + + /** + * EntityShootBowEvent + */ + public static EntityShootBowEvent callEntityShootBowEvent(EntityLiving who, ItemStack itemstack, EntityArrow entityArrow, float force) { + return callEntityShootBowEvent(who, itemstack, entityArrow, force, 0); + } + + /** + * EntityShootBowEvent + */ + public static EntityShootBowEvent callEntityShootBowEvent(EntityLiving who, ItemStack itemstack, EntityArrow entityArrow, float force, int ticksInUse) { + LivingEntity shooter = (LivingEntity) who.getBukkitEntity(); + CraftItemStack itemInHand = CraftItemStack.asCraftMirror(itemstack); + Arrow arrow = (Arrow) entityArrow.getBukkitEntity(); + + if (itemInHand.getType() == Material.AIR || itemInHand.getAmount() == 0) { + itemInHand = null; + } + + EntityShootBowEvent event = new EntityShootBowEvent(shooter, itemInHand, arrow, force, ticksInUse); + Bukkit.getPluginManager().callEvent(event); + + return event; + } + + /** + * BlockDamageEvent + */ + public static BlockDamageEvent callBlockDamageEvent(EntityHuman who, Block block, ItemStack itemstack, boolean instaBreak) { + Player player = (who == null) ? null : (Player) who.getBukkitEntity(); + BlockDamageEvent event = new BlockDamageEvent(player, block, CraftItemStack.asCraftMirror(itemstack), instaBreak); + player.getServer().getPluginManager().callEvent(event); + return event; + } + + /** + * CreatureSpawnEvent + */ + public static CreatureSpawnEvent callCreatureSpawnEvent(EntityLiving entityliving, SpawnReason spawnReason) { + LivingEntity entity = (LivingEntity) entityliving.getBukkitEntity(); + CraftServer craftServer = (CraftServer) entity.getServer(); + + CreatureSpawnEvent event = new CreatureSpawnEvent(entity, spawnReason); + craftServer.getPluginManager().callEvent(event); + return event; + } + + /** + * EntityTameEvent + */ + public static EntityTameEvent callEntityTameEvent(EntityInsentient entity, EntityHuman tamer) { + org.bukkit.entity.Entity bukkitEntity = entity.getBukkitEntity(); + org.bukkit.entity.AnimalTamer bukkitTamer = (tamer != null ? tamer.getBukkitEntity() : null); + CraftServer craftServer = (CraftServer) bukkitEntity.getServer(); + + entity.persistent = true; + + EntityTameEvent event = new EntityTameEvent((LivingEntity) bukkitEntity, bukkitTamer); + craftServer.getPluginManager().callEvent(event); + return event; + } + + /** + * ItemSpawnEvent + */ + public static ItemSpawnEvent callItemSpawnEvent(EntityItem entityitem) { + org.bukkit.entity.Item entity = (org.bukkit.entity.Item) entityitem.getBukkitEntity(); + CraftServer craftServer = (CraftServer) entity.getServer(); + + ItemSpawnEvent event = new ItemSpawnEvent(entity, entity.getLocation()); + + craftServer.getPluginManager().callEvent(event); + return event; + } + + /** + * ItemDespawnEvent + */ + public static ItemDespawnEvent callItemDespawnEvent(EntityItem entityitem) { + org.bukkit.entity.Item entity = (org.bukkit.entity.Item) entityitem.getBukkitEntity(); + + ItemDespawnEvent event = new ItemDespawnEvent(entity, entity.getLocation()); + + entity.getServer().getPluginManager().callEvent(event); + return event; + } + + /** + * ItemMergeEvent + */ + public static ItemMergeEvent callItemMergeEvent(EntityItem merging, EntityItem mergingWith) { + org.bukkit.entity.Item entityMerging = (org.bukkit.entity.Item) merging.getBukkitEntity(); + org.bukkit.entity.Item entityMergingWith = (org.bukkit.entity.Item) mergingWith.getBukkitEntity(); + + ItemMergeEvent event = new ItemMergeEvent(entityMerging, entityMergingWith); + + Bukkit.getPluginManager().callEvent(event); + return event; + } + + /** + * PotionSplashEvent + */ + public static PotionSplashEvent callPotionSplashEvent(EntityPotion potion, Map affectedEntities) { + ThrownPotion thrownPotion = (ThrownPotion) potion.getBukkitEntity(); + + PotionSplashEvent event = new PotionSplashEvent(thrownPotion, affectedEntities); + Bukkit.getPluginManager().callEvent(event); + return event; + } + + /** + * BlockFadeEvent + */ + public static BlockFadeEvent callBlockFadeEvent(Block block, net.minecraft.server.Block type) { + BlockState state = block.getState(); + state.setTypeId(net.minecraft.server.Block.getId(type)); + + BlockFadeEvent event = new BlockFadeEvent(block, state); + Bukkit.getPluginManager().callEvent(event); + return event; + } + + public static void handleBlockSpreadEvent(Block block, Block source, net.minecraft.server.Block type, int data) { + BlockState state = block.getState(); + state.setTypeId(net.minecraft.server.Block.getId(type)); + state.setRawData((byte) data); + + BlockSpreadEvent event = new BlockSpreadEvent(block, source, state); + Bukkit.getPluginManager().callEvent(event); + + if (!event.isCancelled()) { + state.update(true); + } + } + + public static EntityDeathEvent callEntityDeathEvent(EntityLiving victim) { + return callEntityDeathEvent(victim, new ArrayList<>(0)); + } + + public static EntityDeathEvent callEntityDeathEvent(EntityLiving victim, List drops) { + CraftLivingEntity entity = (CraftLivingEntity) victim.getBukkitEntity(); + EntityDeathEvent event = new EntityDeathEvent(entity, drops, victim.getExpReward()); + CraftWorld world = (CraftWorld) entity.getWorld(); + Bukkit.getServer().getPluginManager().callEvent(event); + + victim.expToDrop = event.getDroppedExp(); + + for (org.bukkit.inventory.ItemStack stack : event.getDrops()) { + if (stack == null || stack.getType() == Material.AIR || stack.getAmount() == 0) continue; + + world.dropItemNaturally(entity.getLocation(), stack, victim); + } + + return event; + } + + public static PlayerDeathEvent callPlayerDeathEvent(EntityPlayer victim, List drops, String deathMessage, boolean keepInventory) { + CraftPlayer entity = victim.getBukkitEntity(); + PlayerDeathEvent event = new PlayerDeathEvent(entity, drops, victim.getExpReward(), 0, deathMessage); + event.setKeepInventory(keepInventory); + CraftWorld world = (CraftWorld) entity.getWorld(); + Bukkit.getServer().getPluginManager().callEvent(event); + + victim.keepLevel = event.getKeepLevel(); + victim.newLevel = event.getNewLevel(); + victim.newTotalExp = event.getNewTotalExp(); + victim.expToDrop = event.getDroppedExp(); + victim.newExp = event.getNewExp(); + + if (event.getKeepInventory()) { + return event; + } + + for (org.bukkit.inventory.ItemStack stack : event.getDrops()) { + if (stack == null || stack.getType() == Material.AIR) continue; + + world.dropItemNaturally(entity.getLocation(), stack, victim); + } + + return event; + } + + /** + * Server methods + */ + public static ServerListPingEvent callServerListPingEvent(Server craftServer, InetAddress address, String motd, int numPlayers, int maxPlayers) { + ServerListPingEvent event = new ServerListPingEvent(address, motd, numPlayers, maxPlayers); + craftServer.getPluginManager().callEvent(event); + return event; + } + + private static EntityDamageEvent handleEntityDamageEvent(Entity entity, DamageSource source, Map modifiers, Map> modifierFunctions) { + return handleEntityDamageEvent(entity, source, modifiers, modifierFunctions, false); + } + + private static EntityDamageEvent handleEntityDamageEvent(Entity entity, DamageSource source, Map modifiers, Map> modifierFunctions, boolean upgrade) { + if (source.isExplosion()) { + DamageCause damageCause; + Entity damager = entityDamage; + entityDamage = null; + EntityDamageEvent event; + if (damager == null) { + event = new EntityDamageByBlockEvent(null, entity.getBukkitEntity(), DamageCause.BLOCK_EXPLOSION, modifiers, modifierFunctions, upgrade); + } else if (entity instanceof EntityEnderDragon && ((EntityEnderDragon) entity).target == damager) { + event = new EntityDamageEvent(entity.getBukkitEntity(), DamageCause.ENTITY_EXPLOSION, modifiers, modifierFunctions, upgrade); + } else { + if (damager instanceof org.bukkit.entity.TNTPrimed) { + damageCause = DamageCause.BLOCK_EXPLOSION; + } else { + damageCause = DamageCause.ENTITY_EXPLOSION; + } + event = new EntityDamageByEntityEvent(damager.getBukkitEntity(), entity.getBukkitEntity(), damageCause, modifiers, modifierFunctions, upgrade); + } + + callEvent(event); + + if (!event.isCancelled()) { + event.getEntity().setLastDamageCause(event); + } + return event; + } else if (source instanceof EntityDamageSource) { + Entity damager = source.getEntity(); + DamageCause cause = DamageCause.ENTITY_ATTACK; + + if (source instanceof EntityDamageSourceIndirect) { + damager = ((EntityDamageSourceIndirect) source).getProximateDamageSource(); + if (damager.getBukkitEntity() instanceof ThrownPotion) { + cause = DamageCause.MAGIC; + } else if (damager.getBukkitEntity() instanceof Projectile) { + cause = DamageCause.PROJECTILE; + } + } else if ("thorns".equals(source.translationIndex)) { + cause = DamageCause.THORNS; + } + + return callEntityDamageEvent(damager, entity, cause, modifiers, modifierFunctions, upgrade); + } else if (source == DamageSource.OUT_OF_WORLD) { + EntityDamageEvent event = callEvent(new EntityDamageByBlockEvent(null, entity.getBukkitEntity(), DamageCause.VOID, modifiers, modifierFunctions, upgrade)); + if (!event.isCancelled()) { + event.getEntity().setLastDamageCause(event); + } + return event; + } else if (source == DamageSource.LAVA) { + EntityDamageEvent event = callEvent(new EntityDamageByBlockEvent(null, entity.getBukkitEntity(), DamageCause.LAVA, modifiers, modifierFunctions, upgrade)); + if (!event.isCancelled()) { + event.getEntity().setLastDamageCause(event); + } + return event; + } else if (blockDamage != null) { + DamageCause cause; + Block damager = blockDamage; + blockDamage = null; + if (source == DamageSource.CACTUS) { + cause = DamageCause.CONTACT; + } else { + throw new RuntimeException(String.format("Unhandled damage of %s by %s from %s", entity, damager, source.translationIndex)); // Spigot + } + EntityDamageEvent event = callEvent(new EntityDamageByBlockEvent(damager, entity.getBukkitEntity(), cause, modifiers, modifierFunctions, upgrade)); + if (!event.isCancelled()) { + event.getEntity().setLastDamageCause(event); + } + return event; + } else if (entityDamage != null) { + DamageCause cause; + CraftEntity damager = entityDamage.getBukkitEntity(); + entityDamage = null; + if (source == DamageSource.ANVIL || source == DamageSource.FALLING_BLOCK) { + cause = DamageCause.FALLING_BLOCK; + } else if (damager instanceof LightningStrike) { + cause = DamageCause.LIGHTNING; + } else if (source == DamageSource.FALL) { + cause = DamageCause.FALL; + } else { + throw new RuntimeException(String.format("Unhandled damage of %s by %s from %s", entity, damager.getHandle(), source.translationIndex)); // Spigot + } + EntityDamageEvent event = callEvent(new EntityDamageByEntityEvent(damager, entity.getBukkitEntity(), cause, modifiers, modifierFunctions, upgrade)); + if (!event.isCancelled()) { + event.getEntity().setLastDamageCause(event); + } + return event; + } + + DamageCause cause = null; + if (source == DamageSource.FIRE) { + cause = DamageCause.FIRE; + } else if (source == DamageSource.STARVE) { + cause = DamageCause.STARVATION; + } else if (source == DamageSource.WITHER) { + cause = DamageCause.WITHER; + } else if (source == DamageSource.STUCK) { + cause = DamageCause.SUFFOCATION; + } else if (source == DamageSource.DROWN) { + cause = DamageCause.DROWNING; + } else if (source == DamageSource.BURN) { + cause = DamageCause.FIRE_TICK; + } else if (source == MELTING) { + cause = DamageCause.MELTING; + } else if (source == POISON) { + cause = DamageCause.POISON; + } else if (source == DamageSource.MAGIC) { + cause = DamageCause.MAGIC; + } else if (source == DamageSource.FALL) { + cause = DamageCause.FALL; + } else if (source == DamageSource.GENERIC) { + return new EntityDamageEvent(entity.getBukkitEntity(), null, modifiers, modifierFunctions, upgrade); + } + + if (cause != null) { + return callEntityDamageEvent(null, entity, cause, modifiers, modifierFunctions, upgrade); + } + + throw new RuntimeException(String.format("Unhandled damage of %s from %s", entity, source.translationIndex)); // Spigot + } + + private static EntityDamageEvent callEntityDamageEvent(Entity damager, Entity damagee, DamageCause cause, Map modifiers, Map> modifierFunctions) { + return callEntityDamageEvent(damager, damagee, cause, modifiers, modifierFunctions, false); + } + + private static EntityDamageEvent callEntityDamageEvent(Entity damager, Entity damagee, DamageCause cause, Map modifiers, Map> modifierFunctions, boolean upgrade) { + EntityDamageEvent event; + if (damager != null) { + event = new EntityDamageByEntityEvent(damager.getBukkitEntity(), damagee.getBukkitEntity(), cause, modifiers, modifierFunctions, upgrade); + } else { + event = new EntityDamageEvent(damagee.getBukkitEntity(), cause, modifiers, modifierFunctions, upgrade); + } + + callEvent(event); + + if (!event.isCancelled()) { + event.getEntity().setLastDamageCause(event); + } + + return event; + } + + public static EntityDamageEvent handleLivingEntityDamageEvent(Entity damagee, DamageSource source, double rawDamage, double hardHatModifier, double blockingModifier, double armorModifier, double resistanceModifier, double magicModifier, double absorptionModifier, Function hardHat, Function blocking, Function armor, Function resistance, Function magic, Function absorption) { + return handleLivingEntityDamageEvent(damagee, source, rawDamage, hardHatModifier, blockingModifier, armorModifier, resistanceModifier, magicModifier, absorptionModifier, hardHat, blocking, armor, resistance, magic, absorption, false); + } + + public static EntityDamageEvent handleLivingEntityDamageEvent(Entity damagee, DamageSource source, double rawDamage, double hardHatModifier, double blockingModifier, double armorModifier, double resistanceModifier, double magicModifier, double absorptionModifier, Function hardHat, Function blocking, Function armor, Function resistance, Function magic, Function absorption, boolean upgrade) { + Map modifiers = new EnumMap<>(DamageModifier.class); + Map> modifierFunctions = new EnumMap<>(DamageModifier.class); + modifiers.put(DamageModifier.BASE, rawDamage); + modifierFunctions.put(DamageModifier.BASE, ZERO); + if (source == DamageSource.FALLING_BLOCK || source == DamageSource.ANVIL) { + modifiers.put(DamageModifier.HARD_HAT, hardHatModifier); + modifierFunctions.put(DamageModifier.HARD_HAT, hardHat); + } + if (damagee instanceof EntityHuman) { + modifiers.put(DamageModifier.BLOCKING, blockingModifier); + modifierFunctions.put(DamageModifier.BLOCKING, blocking); + } + modifiers.put(DamageModifier.ARMOR, armorModifier); + modifierFunctions.put(DamageModifier.ARMOR, armor); + modifiers.put(DamageModifier.RESISTANCE, resistanceModifier); + modifierFunctions.put(DamageModifier.RESISTANCE, resistance); + modifiers.put(DamageModifier.MAGIC, magicModifier); + modifierFunctions.put(DamageModifier.MAGIC, magic); + modifiers.put(DamageModifier.ABSORPTION, absorptionModifier); + modifierFunctions.put(DamageModifier.ABSORPTION, absorption); + + return handleEntityDamageEvent(damagee, source, modifiers, modifierFunctions, upgrade); + } + + // Non-Living Entities such as EntityEnderCrystal and EntityFireball need to call this + public static boolean handleNonLivingEntityDamageEvent(Entity entity, DamageSource source, double damage) { + return handleNonLivingEntityDamageEvent(entity, source, damage, true); + } + + public static boolean handleNonLivingEntityDamageEvent(Entity entity, DamageSource source, double damage, boolean cancelOnZeroDamage) { + if (entity instanceof EntityEnderCrystal && !(source instanceof EntityDamageSource)) { + return false; + } + + final EnumMap modifiers = new EnumMap<>(DamageModifier.class); + final EnumMap> functions = new EnumMap<>(DamageModifier.class); + + modifiers.put(DamageModifier.BASE, damage); + functions.put(DamageModifier.BASE, ZERO); + + final EntityDamageEvent event = handleEntityDamageEvent(entity, source, modifiers, functions); + return event.isCancelled() || (cancelOnZeroDamage && event.getDamage() == 0); + } + + public static PlayerLevelChangeEvent callPlayerLevelChangeEvent(Player player, int oldLevel, int newLevel) { + PlayerLevelChangeEvent event = new PlayerLevelChangeEvent(player, oldLevel, newLevel); + Bukkit.getPluginManager().callEvent(event); + return event; + } + + public static PlayerExpChangeEvent callPlayerExpChangeEvent(EntityHuman entity, int expAmount) { + Player player = (Player) entity.getBukkitEntity(); + PlayerExpChangeEvent event = new PlayerExpChangeEvent(player, expAmount); + Bukkit.getPluginManager().callEvent(event); + return event; + } + + public static void handleBlockGrowEvent(World world, int x, int y, int z, net.minecraft.server.Block type, int data) { + Block block = world.getWorld().getBlockAt(x, y, z); + CraftBlockState state = (CraftBlockState) block.getState(); + state.setTypeId(net.minecraft.server.Block.getId(type)); + state.setRawData((byte) data); + + BlockGrowEvent event = new BlockGrowEvent(block, state); + Bukkit.getPluginManager().callEvent(event); + + if (!event.isCancelled()) { + state.update(true); + } + } + + public static FoodLevelChangeEvent callFoodLevelChangeEvent(EntityHuman entity, int level) { + FoodLevelChangeEvent event = new FoodLevelChangeEvent(entity.getBukkitEntity(), level); + entity.getBukkitEntity().getServer().getPluginManager().callEvent(event); + return event; + } + + public static PigZapEvent callPigZapEvent(Entity pig, Entity lightning, Entity pigzombie) { + PigZapEvent event = new PigZapEvent((Pig) pig.getBukkitEntity(), (LightningStrike) lightning.getBukkitEntity(), (PigZombie) pigzombie.getBukkitEntity()); + pig.getBukkitEntity().getServer().getPluginManager().callEvent(event); + return event; + } + + public static HorseJumpEvent callHorseJumpEvent(Entity horse, float power) { + HorseJumpEvent event = new HorseJumpEvent((Horse) horse.getBukkitEntity(), power); + horse.getBukkitEntity().getServer().getPluginManager().callEvent(event); + return event; + } + + public static EntityChangeBlockEvent callEntityChangeBlockEvent(org.bukkit.entity.Entity entity, Block block, Material material) { + return callEntityChangeBlockEvent(entity, block, material, 0); + } + + public static EntityChangeBlockEvent callEntityChangeBlockEvent(Entity entity, Block block, Material material) { + return callEntityChangeBlockEvent(entity.getBukkitEntity(), block, material, 0); + } + + public static EntityChangeBlockEvent callEntityChangeBlockEvent(Entity entity, Block block, Material material, boolean cancelled) { + return callEntityChangeBlockEvent(entity.getBukkitEntity(), block, material, 0, cancelled); + } + + public static EntityChangeBlockEvent callEntityChangeBlockEvent(Entity entity, int x, int y, int z, net.minecraft.server.Block type, int data) { + Block block = entity.world.getWorld().getBlockAt(x, y, z); + Material material = CraftMagicNumbers.getMaterial(type); + + return callEntityChangeBlockEvent(entity.getBukkitEntity(), block, material, data); + } + + public static EntityChangeBlockEvent callEntityChangeBlockEvent(Entity entity, BlockPosition p, net.minecraft.server.Block type, int data) { + return callEntityChangeBlockEvent(entity, p.getX(), p.getY(), p.getZ(), type, data); + } + + public static EntityChangeBlockEvent callEntityChangeBlockEvent(org.bukkit.entity.Entity entity, Block block, Material material, int data) { + return callEntityChangeBlockEvent(entity, block, material, data, false); + } + + public static EntityChangeBlockEvent callEntityChangeBlockEvent(org.bukkit.entity.Entity entity, Block block, Material material, int data, boolean cancelled) { + EntityChangeBlockEvent event = new EntityChangeBlockEvent(entity, block, material, (byte) data); + event.setCancelled(cancelled); + entity.getServer().getPluginManager().callEvent(event); + return event; + } + + public static CreeperPowerEvent callCreeperPowerEvent(Entity creeper, Entity lightning, CreeperPowerEvent.PowerCause cause) { + CreeperPowerEvent event = new CreeperPowerEvent((Creeper) creeper.getBukkitEntity(), (LightningStrike) lightning.getBukkitEntity(), cause); + creeper.getBukkitEntity().getServer().getPluginManager().callEvent(event); + return event; + } + + public static EntityTargetEvent callEntityTargetEvent(Entity entity, Entity target, EntityTargetEvent.TargetReason reason) { + EntityTargetEvent event = new EntityTargetEvent(entity.getBukkitEntity(), target == null ? null : target.getBukkitEntity(), reason); + entity.getBukkitEntity().getServer().getPluginManager().callEvent(event); + return event; + } + + public static EntityTargetLivingEntityEvent callEntityTargetLivingEvent(Entity entity, EntityLiving target, EntityTargetEvent.TargetReason reason) { + EntityTargetLivingEntityEvent event = new EntityTargetLivingEntityEvent(entity.getBukkitEntity(), (LivingEntity) target.getBukkitEntity(), reason); + entity.getBukkitEntity().getServer().getPluginManager().callEvent(event); + return event; + } + + public static EntityBreakDoorEvent callEntityBreakDoorEvent(Entity entity, int x, int y, int z) { + org.bukkit.entity.Entity entity1 = entity.getBukkitEntity(); + Block block = entity1.getWorld().getBlockAt(x, y, z); + + EntityBreakDoorEvent event = new EntityBreakDoorEvent((LivingEntity) entity1, block); + entity1.getServer().getPluginManager().callEvent(event); + + return event; + } + + public static Container callInventoryOpenEvent(EntityPlayer player, Container container) { + return callInventoryOpenEvent(player, container, false); + } + + public static Container callInventoryOpenEvent(EntityPlayer player, Container container, boolean cancelled) { + if (player.activeContainer != player.defaultContainer) { // fire INVENTORY_CLOSE if one already open + player.playerConnection.a(new PacketPlayInCloseWindow(player.activeContainer.windowId)); + } + + CraftServer server = player.world.getServer(); + CraftPlayer craftPlayer = player.getBukkitEntity(); + player.activeContainer.transferTo(container, craftPlayer); + + InventoryOpenEvent event = new InventoryOpenEvent(container.getBukkitView()); + event.setCancelled(cancelled); + server.getPluginManager().callEvent(event); + + if (event.isCancelled()) { + container.transferTo(player.activeContainer, craftPlayer); + return null; + } + + return container; + } + + public static ItemStack callPreCraftEvent(InventoryCrafting matrix, ItemStack result, InventoryView lastCraftView, boolean isRepair) { + CraftInventoryCrafting inventory = new CraftInventoryCrafting(matrix, matrix.resultInventory); + inventory.setResult(CraftItemStack.asCraftMirror(result)); + + PrepareItemCraftEvent event = new PrepareItemCraftEvent(inventory, lastCraftView, isRepair); + Bukkit.getPluginManager().callEvent(event); + + org.bukkit.inventory.ItemStack bitem = event.getInventory().getResult(); + + return CraftItemStack.asNMSCopy(bitem); + } + + public static ProjectileLaunchEvent callProjectileLaunchEvent(Entity entity) { + Projectile bukkitEntity = (Projectile) entity.getBukkitEntity(); + ProjectileLaunchEvent event = new ProjectileLaunchEvent(bukkitEntity); + Bukkit.getPluginManager().callEvent(event); + return event; + } + + public static ProjectileHitEvent callProjectileHitEvent(Entity entity) { + ProjectileHitEvent event = new ProjectileHitEvent((Projectile) entity.getBukkitEntity()); + entity.world.getServer().getPluginManager().callEvent(event); + return event; + } + + public static ExpBottleEvent callExpBottleEvent(Entity entity, int exp) { + ThrownExpBottle bottle = (ThrownExpBottle) entity.getBukkitEntity(); + ExpBottleEvent event = new ExpBottleEvent(bottle, exp); + Bukkit.getPluginManager().callEvent(event); + return event; + } + + public static BlockRedstoneEvent callRedstoneChange(World world, int x, int y, int z, int oldCurrent, int newCurrent) { + BlockRedstoneEvent event = new BlockRedstoneEvent(world.getWorld().getBlockAt(x, y, z), oldCurrent, newCurrent); + world.getServer().getPluginManager().callEvent(event); + return event; + } + + public static NotePlayEvent callNotePlayEvent(World world, int x, int y, int z, byte instrument, byte note) { + NotePlayEvent event = new NotePlayEvent(world.getWorld().getBlockAt(x, y, z), org.bukkit.Instrument.getByType(instrument), new org.bukkit.Note(note)); + world.getServer().getPluginManager().callEvent(event); + return event; + } + + public static void callPlayerItemBreakEvent(EntityHuman human, ItemStack brokenItem) { + CraftItemStack item = CraftItemStack.asCraftMirror(brokenItem); + PlayerItemBreakEvent event = new PlayerItemBreakEvent((Player) human.getBukkitEntity(), item); + Bukkit.getPluginManager().callEvent(event); + } + + public static BlockIgniteEvent callBlockIgniteEvent(World world, int x, int y, int z, Explosion explosion) { + CraftWorld craftWorld = world.getWorld(); + CraftEntity craftEntity = (explosion.source == null) ? null : explosion.source.getBukkitEntity(); + BlockIgniteEvent event = new BlockIgniteEvent(craftWorld.getBlockAt(x, y, z), BlockIgniteEvent.IgniteCause.EXPLOSION, craftEntity); + world.getServer().getPluginManager().callEvent(event); + return event; + } + + public static BlockIgniteEvent callBlockIgniteEvent(World world, int x, int y, int z, int igniterX, int igniterY, int igniterZ) { + org.bukkit.World bukkitWorld = world.getWorld(); + Block igniter = bukkitWorld.getBlockAt(igniterX, igniterY, igniterZ); + IgniteCause cause; + switch (igniter.getType()) { + case LAVA: + case STATIONARY_LAVA: + cause = IgniteCause.LAVA; + break; + case DISPENSER: + cause = IgniteCause.FLINT_AND_STEEL; + break; + case FIRE: // Fire or any other unknown block counts as SPREAD. + default: + cause = IgniteCause.SPREAD; + } + + BlockIgniteEvent event = new BlockIgniteEvent(bukkitWorld.getBlockAt(x, y, z), cause, igniter); + world.getServer().getPluginManager().callEvent(event); + return event; + } + + public static BlockIgniteEvent callBlockIgniteEvent(World world, int x, int y, int z, Entity igniter) { + org.bukkit.World bukkitWorld = world.getWorld(); + org.bukkit.entity.Entity bukkitIgniter = igniter.getBukkitEntity(); + IgniteCause cause; + switch (bukkitIgniter.getType()) { + case ENDER_CRYSTAL: + cause = IgniteCause.ENDER_CRYSTAL; + break; + case LIGHTNING: + cause = IgniteCause.LIGHTNING; + break; + case SMALL_FIREBALL: + case FIREBALL: + cause = IgniteCause.FIREBALL; + break; + default: + cause = IgniteCause.FLINT_AND_STEEL; + } + + BlockIgniteEvent event = new BlockIgniteEvent(bukkitWorld.getBlockAt(x, y, z), cause, bukkitIgniter); + world.getServer().getPluginManager().callEvent(event); + return event; + } + + public static BlockIgniteEvent callBlockIgniteEvent(World world, Chunk chunk, int x, int y, int z, Explosion explosion) { + org.bukkit.World bukkitWorld = world.getWorld(); + org.bukkit.entity.Entity igniter = explosion.source == null ? null : explosion.source.getBukkitEntity(); + + BlockIgniteEvent event = new BlockIgniteEvent(chunk.bukkitChunk.getBlock(x, y, z), IgniteCause.EXPLOSION, igniter); + world.getServer().getPluginManager().callEvent(event); + return event; + } + + public static BlockIgniteEvent callBlockIgniteEvent(World world, int x, int y, int z, IgniteCause cause, Entity igniter) { + BlockIgniteEvent event = new BlockIgniteEvent(world.getWorld().getBlockAt(x, y, z), cause, igniter.getBukkitEntity()); + world.getServer().getPluginManager().callEvent(event); + return event; + } + + public static void handleInventoryCloseEvent(EntityHuman human) { + InventoryCloseEvent event = new InventoryCloseEvent(human.activeContainer.getBukkitView()); + human.world.getServer().getPluginManager().callEvent(event); + human.activeContainer.transferTo(human.defaultContainer, human.getBukkitEntity()); + } + + public static void handleEditBookEvent(EntityPlayer player, ItemStack newBookItem) { + int itemInHandIndex = player.inventory.itemInHandIndex; + + PlayerEditBookEvent editBookEvent = new PlayerEditBookEvent(player.getBukkitEntity(), player.inventory.itemInHandIndex, (BookMeta) CraftItemStack.getItemMeta(player.inventory.getItemInHand()), (BookMeta) CraftItemStack.getItemMeta(newBookItem), newBookItem.getItem() == Items.WRITTEN_BOOK); + player.world.getServer().getPluginManager().callEvent(editBookEvent); + ItemStack itemInHand = player.inventory.getItem(itemInHandIndex); + + // If they've got the same item in their hand, it'll need to be updated. + if (itemInHand != null && itemInHand.getItem() == Items.WRITABLE_BOOK) { + if (!editBookEvent.isCancelled()) { + if (editBookEvent.isSigning()) { + itemInHand.setItem(Items.WRITTEN_BOOK); + } + CraftMetaBook meta = (CraftMetaBook) editBookEvent.getNewBookMeta(); + List pages = meta.pages; + for (int i = 0; i < pages.size(); i++) { + pages.set(i, stripEvents(pages.get(i))); + } + CraftItemStack.setItemMeta(itemInHand, meta); + } + + // Client will have updated its idea of the book item; we need to overwrite that + Slot slot = player.activeContainer.getSlot(player.inventory, itemInHandIndex); + player.playerConnection.sendPacket(new PacketPlayOutSetSlot(player.activeContainer.windowId, slot.rawSlotIndex, itemInHand)); + } + } + + private static IChatBaseComponent stripEvents(IChatBaseComponent c) { + ChatModifier modi = c.getChatModifier(); + if (modi != null) { + modi.setChatClickable(null); + modi.setChatHoverable(null); + } + c.setChatModifier(modi); + if (c instanceof ChatMessage) { + ChatMessage cm = (ChatMessage) c; + Object[] oo = cm.j(); + for (int i = 0; i < oo.length; i++) { + Object o = oo[i]; + if (o instanceof IChatBaseComponent) { + oo[i] = stripEvents((IChatBaseComponent) o); + } + } + } + List ls = c.a(); + if (ls != null) { + for (int i = 0; i < ls.size(); i++) { + ls.set(i, stripEvents(ls.get(i))); + } + } + return c; + } + + public static PlayerUnleashEntityEvent callPlayerUnleashEntityEvent(EntityInsentient entity, EntityHuman player) { + PlayerUnleashEntityEvent event = new PlayerUnleashEntityEvent(entity.getBukkitEntity(), (Player) player.getBukkitEntity()); + entity.world.getServer().getPluginManager().callEvent(event); + return event; + } + + public static PlayerLeashEntityEvent callPlayerLeashEntityEvent(EntityInsentient entity, Entity leashHolder, EntityHuman player) { + PlayerLeashEntityEvent event = new PlayerLeashEntityEvent(entity.getBukkitEntity(), leashHolder.getBukkitEntity(), (Player) player.getBukkitEntity()); + entity.world.getServer().getPluginManager().callEvent(event); + return event; + } + + public static Cancellable handleStatisticsIncrease(EntityHuman entityHuman, net.minecraft.server.Statistic statistic, int current, int incrementation) { + Player player = ((EntityPlayer) entityHuman).getBukkitEntity(); + Event event; + if (statistic instanceof net.minecraft.server.Achievement) { + if (current != 0) { + return null; + } + event = new PlayerAchievementAwardedEvent(player, CraftStatistic.getBukkitAchievement((net.minecraft.server.Achievement) statistic)); + } else { + org.bukkit.Statistic stat = CraftStatistic.getBukkitStatistic(statistic); + if (stat == null) { + System.err.println("Unhandled statistic: " + statistic); + return null; + } + switch (stat) { + case FALL_ONE_CM: + case BOAT_ONE_CM: + case CLIMB_ONE_CM: + case DIVE_ONE_CM: + case FLY_ONE_CM: + case HORSE_ONE_CM: + case MINECART_ONE_CM: + case PIG_ONE_CM: + case PLAY_ONE_TICK: + case SWIM_ONE_CM: + case WALK_ONE_CM: + case SPRINT_ONE_CM: + case CROUCH_ONE_CM: + case TIME_SINCE_DEATH: + // Do not process event for these - too spammy + return null; + default: + } + if (stat.getType() == Type.UNTYPED) { + event = new PlayerStatisticIncrementEvent(player, stat, current, current + incrementation); + } else if (stat.getType() == Type.ENTITY) { + EntityType entityType = CraftStatistic.getEntityTypeFromStatistic(statistic); + event = new PlayerStatisticIncrementEvent(player, stat, current, current + incrementation, entityType); + } else { + Material material = CraftStatistic.getMaterialFromStatistic(statistic); + event = new PlayerStatisticIncrementEvent(player, stat, current, current + incrementation, material); + } + } + entityHuman.world.getServer().getPluginManager().callEvent(event); + return (Cancellable) event; + } + + public static FireworkExplodeEvent callFireworkExplodeEvent(EntityFireworks firework) { + FireworkExplodeEvent event = new FireworkExplodeEvent((Firework) firework.getBukkitEntity()); + firework.world.getServer().getPluginManager().callEvent(event); + return event; + } + + // PaperSpigot start - Add PlayerLocaleChangeEvent + public static PlayerLocaleChangeEvent callPlayerLocaleChangeEvent(EntityHuman who, String oldLocale, String newLocale) { + Player player = (Player) who.getBukkitEntity(); + PlayerLocaleChangeEvent event = new PlayerLocaleChangeEvent(player, oldLocale, newLocale); + Bukkit.getPluginManager().callEvent(event); + return event; + } + // PaperSpigot end +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/generator/CraftChunkData.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/generator/CraftChunkData.java new file mode 100644 index 0000000..6fff040 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/generator/CraftChunkData.java @@ -0,0 +1,200 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package org.bukkit.craftbukkit.generator; + +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.generator.ChunkGenerator; +import org.bukkit.material.MaterialData; + +import java.util.Arrays; + +/** + * Data to be used for the block types and data in a newly generated chunk. + */ +public final class CraftChunkData implements ChunkGenerator.ChunkData { + private final int maxHeight; + private final char[][] sections; + + public CraftChunkData(World world) { + this(world.getMaxHeight()); + } + + /* pp for tests */ CraftChunkData(int maxHeight) { + if (maxHeight > 256) { + throw new IllegalArgumentException("World height exceeded max chunk height"); + } + this.maxHeight = maxHeight; + // Minecraft hardcodes this to 16 chunk sections. + sections = new char[16][]; + } + + @Override + public int getMaxHeight() { + return maxHeight; + } + + @Override + public void setBlock(int x, int y, int z, Material material) { + setBlock(x, y, z, material.getId()); + } + + @Override + public void setBlock(int x, int y, int z, MaterialData material) { + setBlock(x, y, z, material.getItemTypeId(), material.getData()); + } + + @Override + public void setRegion(int xMin, int yMin, int zMin, int xMax, int yMax, int zMax, Material material) { + setRegion(xMin, yMin, zMin, xMax, yMax, zMax, material.getId()); + } + + @Override + public void setRegion(int xMin, int yMin, int zMin, int xMax, int yMax, int zMax, MaterialData material) { + setRegion(xMin, yMin, zMin, xMax, yMax, zMax, material.getItemTypeId(), material.getData()); + } + + @Override + public Material getType(int x, int y, int z) { + return Material.getMaterial(getTypeId(x, y, z)); + } + + @Override + public MaterialData getTypeAndData(int x, int y, int z) { + return getType(x, y, z).getNewData(getData(x, y, z)); + } + + @Override + public void setRegion(int xMin, int yMin, int zMin, int xMax, int yMax, int zMax, int blockId) { + setRegion(xMin, yMin, zMin, xMax, yMax, zMax, blockId, (byte) 0); + } + + @Override + public void setRegion(int xMin, int yMin, int zMin, int xMax, int yMax, int zMax, int blockId, int data) { + // Clamp to sane values. + if (xMin > 0xf || yMin >= maxHeight || zMin > 0xf) { + return; + } + if (xMin < 0) { + xMin = 0; + } + if (yMin < 0) { + yMin = 0; + } + if (zMin < 0) { + zMin = 0; + } + if (xMax > 0x10) { + xMax = 0x10; + } + if (yMax > maxHeight) { + yMax = maxHeight; + } + if (zMax > 0x10) { + zMax = 0x10; + } + if (xMin >= xMax || yMin >= yMax || zMin >= zMax) { + return; + } + char typeChar = (char) ((blockId << 4) | data); + if (xMin == 0 && xMax == 0x10) { + if (zMin == 0 && zMax == 0x10) { + for (int y = yMin & 0xf0; y < yMax; y += 0x10) { + char[] section = getChunkSection(y, true); + if (y <= yMin) { + if (y + 0x10 > yMax) { + // First and last chunk section + Arrays.fill(section, (yMin & 0xf) << 8, (yMax & 0xf) << 8, typeChar); + } else { + // First chunk section + Arrays.fill(section, (yMin & 0xf) << 8, 0x1000, typeChar); + } + } else if (y + 0x10 > yMax) { + // Last chunk section + Arrays.fill(section, 0, (yMax & 0xf) << 8, typeChar); + } else { + // Full chunk section + Arrays.fill(section, 0, 0x1000, typeChar); + } + } + } else { + for (int y = yMin; y < yMax; y++) { + char[] section = getChunkSection(y, true); + int offsetBase = (y & 0xf) << 8; + int min = offsetBase | (zMin << 4); + // Need to add zMax as it can be 16, which overlaps the y coordinate bits + int max = offsetBase + (zMax << 4); + Arrays.fill(section, min, max, typeChar); + } + } + } else { + for (int y = yMin; y < yMax; y++) { + char[] section = getChunkSection(y, true); + int offsetBase = (y & 0xf) << 8; + for (int z = zMin; z < zMax; z++) { + int offset = offsetBase | (z << 4); + // Need to add xMax as it can be 16, which overlaps the z coordinate bits + Arrays.fill(section, offset | xMin, offset + xMax, typeChar); + } + } + } + } + + @Override + public void setBlock(int x, int y, int z, int blockId) { + setBlock(x, y, z, blockId, (byte) 0); + } + + @Override + public void setBlock(int x, int y, int z, int blockId, byte data) { + setBlock(x, y, z, (char) (blockId << 4 | data)); + } + + @Override + public int getTypeId(int x, int y, int z) { + if (x != (x & 0xf) || y < 0 || y >= maxHeight || z != (z & 0xf)) { + return 0; + } + char[] section = getChunkSection(y, false); + if (section == null) { + return 0; + } else { + return section[(y & 0xf) << 8 | z << 4 | x] >> 4; + } + } + + @Override + public byte getData(int x, int y, int z) { + if (x != (x & 0xf) || y < 0 || y >= maxHeight || z != (z & 0xf)) { + return (byte) 0; + } + char[] section = getChunkSection(y, false); + if (section == null) { + return (byte) 0; + } else { + return (byte) (section[(y & 0xf) << 8 | z << 4 | x] & 0xf); + } + } + + private void setBlock(int x, int y, int z, char type) { + if (x != (x & 0xf) || y < 0 || y >= maxHeight || z != (z & 0xf)) { + return; + } + char[] section = getChunkSection(y, true); + section[(y & 0xf) << 8 | z << 4 | x] = type; + } + + private char[] getChunkSection(int y, boolean create) { + char[] section = sections[y >> 4]; + if (create && section == null) { + sections[y >> 4] = section = new char[0x1000]; + } + return section; + } + + char[][] getRawChunkData() { + return sections; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/generator/CustomChunkGenerator.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/generator/CustomChunkGenerator.java new file mode 100644 index 0000000..86fb197 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/generator/CustomChunkGenerator.java @@ -0,0 +1,263 @@ +package org.bukkit.craftbukkit.generator; + +import net.minecraft.server.*; +import org.bukkit.block.Biome; +import org.bukkit.craftbukkit.block.CraftBlock; +import org.bukkit.generator.BlockPopulator; +import org.bukkit.generator.ChunkGenerator; + +import java.util.List; +import java.util.Random; + +public class CustomChunkGenerator extends InternalChunkGenerator { + private final ChunkGenerator generator; + private final WorldServer world; + private final Random random; + private final WorldGenStronghold strongholdGen = new WorldGenStronghold(); + + private static class CustomBiomeGrid implements BiomeGrid { + BiomeBase[] biome; + + public Biome getBiome(int x, int z) { + return CraftBlock.biomeBaseToBiome(biome[(z << 4) | x]); + } + + public void setBiome(int x, int z, Biome bio) { + biome[(z << 4) | x] = CraftBlock.biomeToBiomeBase(bio); + } + } + + public CustomChunkGenerator(World world, long seed, ChunkGenerator generator) { + this.world = (WorldServer) world; + this.generator = generator; + + random = new Random(seed); + } + + public boolean isChunkLoaded(int x, int z) { + return true; + } + + public Chunk getOrCreateChunk(int x, int z) { + random.setSeed((long) x * 341873128712L + (long) z * 132897987541L); + + Chunk chunk; + + // Get default biome data for chunk + CustomBiomeGrid biomegrid = new CustomBiomeGrid(); + biomegrid.biome = new BiomeBase[256]; + world.getWorldChunkManager().getBiomeBlock(biomegrid.biome, x << 4, z << 4, 16, 16); + + // Try ChunkData method (1.8+) + CraftChunkData data = (CraftChunkData) generator.generateChunkData(this.world.getWorld(), random, x, z, biomegrid); + if (data != null) { + char[][] sections = data.getRawChunkData(); + chunk = new Chunk(this.world, x, z); + + ChunkSection[] csect = chunk.getSections(); + int scnt = Math.min(csect.length, sections.length); + + // Loop through returned sections + for (int sec = 0; sec < scnt; sec++) { + if(sections[sec] == null) { + continue; + } + char[] section = sections[sec]; + char emptyTest = 0; + for (int i = 0; i < 4096; i++) { + // Filter invalid block id & data values. + if (Block.d.a(section[i]) == null) { + section[i] = 0; + } + emptyTest |= section[i]; + } + // Build chunk section + if (emptyTest != 0) { + csect[sec] = new ChunkSection(sec << 4, true, section, world.shouldSectionsHaveTickList()); + } + } + } + else { + // Try extended block method (1.2+) + short[][] xbtypes = generator.generateExtBlockSections(this.world.getWorld(), random, x, z, biomegrid); + if (xbtypes != null) { + chunk = new Chunk(this.world, x, z); + + ChunkSection[] csect = chunk.getSections(); + int scnt = Math.min(csect.length, xbtypes.length); + + // Loop through returned sections + for (int sec = 0; sec < scnt; sec++) { + if (xbtypes[sec] == null) { + continue; + } + char[] secBlkID = new char[4096]; // Allocate blk ID bytes + short[] bdata = xbtypes[sec]; + for (int i = 0; i < bdata.length; i++) { + Block b = Block.getById(bdata[i]); + secBlkID[i] = (char) Block.d.b(b.getBlockData()); + } + // Build chunk section + csect[sec] = new ChunkSection(sec << 4, true, secBlkID, world.shouldSectionsHaveTickList()); + } + } + else { // Else check for byte-per-block section data + byte[][] btypes = generator.generateBlockSections(this.world.getWorld(), random, x, z, biomegrid); + + if (btypes != null) { + chunk = new Chunk(this.world, x, z); + + ChunkSection[] csect = chunk.getSections(); + int scnt = Math.min(csect.length, btypes.length); + + for (int sec = 0; sec < scnt; sec++) { + if (btypes[sec] == null) { + continue; + } + + char[] secBlkID = new char[4096]; // Allocate block ID bytes + for (int i = 0; i < secBlkID.length; i++) { + Block b = Block.getById(btypes[sec][i] & 0xFF); + secBlkID[i] = (char) Block.d.b(b.getBlockData()); + } + csect[sec] = new ChunkSection(sec << 4, true, secBlkID, world.shouldSectionsHaveTickList()); + } + } + else { // Else, fall back to pre 1.2 method + @SuppressWarnings("deprecation") + byte[] types = generator.generate(this.world.getWorld(), random, x, z); + int ydim = types.length / 256; + int scnt = ydim / 16; + + chunk = new Chunk(this.world, x, z); // Create empty chunk + + ChunkSection[] csect = chunk.getSections(); + + scnt = Math.min(scnt, csect.length); + // Loop through sections + for (int sec = 0; sec < scnt; sec++) { + ChunkSection cs = null; // Add sections when needed + char[] csbytes = null; + + for (int cy = 0; cy < 16; cy++) { + int cyoff = cy | (sec << 4); + + for (int cx = 0; cx < 16; cx++) { + int cxyoff = (cx * ydim * 16) + cyoff; + + for (int cz = 0; cz < 16; cz++) { + byte blk = types[cxyoff + (cz * ydim)]; + + if (blk != 0) { // If non-empty + if (cs == null) { // If no section yet, get one + cs = csect[sec] = new ChunkSection(sec << 4, true, world.shouldSectionsHaveTickList()); + csbytes = cs.getIdArray(); + } + + Block b = Block.getById(blk & 0xFF); + csbytes[(cy << 8) | (cz << 4) | cx] = (char) Block.d.b(b.getBlockData()); + } + } + } + } + // If section built, finish prepping its state + if (cs != null) { + cs.recalcBlockCounts(); + } + } + } + } + } + // Set biome grid + byte[] biomeIndex = chunk.getBiomeIndex(); + for (int i = 0; i < biomeIndex.length; i++) { + biomeIndex[i] = (byte) (biomegrid.biome[i].id & 0xFF); + } + // Initialize lighting + chunk.initLighting(); + + return chunk; + } + + @Override + public Chunk getChunkAt(BlockPosition blockPosition) { + return getChunkAt(blockPosition.getX() >> 4, blockPosition.getZ() >> 4); + } + + public void getChunkAt(IChunkProvider icp, int i, int i1) { + // Nothing! + } + + @Override + public boolean a(IChunkProvider iChunkProvider, Chunk chunk, int i, int i1) { + return false; + } + + public boolean saveChunks(boolean bln, IProgressUpdate ipu) { + return true; + } + + public boolean unloadChunks() { + return false; + } + + public boolean canSave() { + return true; + } + + @SuppressWarnings("deprecation") + public byte[] generate(org.bukkit.World world, Random random, int x, int z) { + return generator.generate(world, random, x, z); + } + + public byte[][] generateBlockSections(org.bukkit.World world, Random random, int x, int z, BiomeGrid biomes) { + return generator.generateBlockSections(world, random, x, z, biomes); + } + + public short[][] generateExtBlockSections(org.bukkit.World world, Random random, int x, int z, BiomeGrid biomes) { + return generator.generateExtBlockSections(world, random, x, z, biomes); + } + + public Chunk getChunkAt(int x, int z) { + return getOrCreateChunk(x, z); + } + + @Override + public boolean canSpawn(org.bukkit.World world, int x, int z) { + return generator.canSpawn(world, x, z); + } + + @Override + public List getDefaultPopulators(org.bukkit.World world) { + return generator.getDefaultPopulators(world); + } + + @Override + public List getMobsFor(EnumCreatureType type, BlockPosition position) { + BiomeBase biomebase = world.getBiome(position); + + return biomebase == null ? null : biomebase.getMobs(type); + } + + @Override + public BlockPosition findNearestMapFeature(World world, String type, BlockPosition position) { + return "Stronghold".equals(type) ? this.strongholdGen.getNearestGeneratedFeature(world, position) : null; + } + + public void recreateStructures(int i, int j) {} + + public int getLoadedChunks() { + return 0; + } + + @Override + public void recreateStructures(Chunk chunk, int i, int i1) { + + } + + public String getName() { + return "CustomChunkGenerator"; + } + + public void c() {} +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/generator/InternalChunkGenerator.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/generator/InternalChunkGenerator.java new file mode 100644 index 0000000..19565e5 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/generator/InternalChunkGenerator.java @@ -0,0 +1,8 @@ +package org.bukkit.craftbukkit.generator; + +import net.minecraft.server.IChunkProvider; +import org.bukkit.generator.ChunkGenerator; + +// Do not implement functions to this class, add to NormalChunkGenerator +public abstract class InternalChunkGenerator extends ChunkGenerator implements IChunkProvider { +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/generator/NetherChunkGenerator.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/generator/NetherChunkGenerator.java new file mode 100644 index 0000000..59d7bbe --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/generator/NetherChunkGenerator.java @@ -0,0 +1,12 @@ +package org.bukkit.craftbukkit.generator; + +import net.minecraft.server.World; + +/** + * This class is useless. Just fyi. + */ +public class NetherChunkGenerator extends NormalChunkGenerator { + public NetherChunkGenerator(World world, long seed) { + super(world, seed); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/generator/NormalChunkGenerator.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/generator/NormalChunkGenerator.java new file mode 100644 index 0000000..584f06a --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/generator/NormalChunkGenerator.java @@ -0,0 +1,103 @@ +package org.bukkit.craftbukkit.generator; + +import dev.azurite.spigot.configs.AzuriteConfig; +import dev.azurite.spigot.utils.ChunkProviderVoid; +import net.minecraft.server.*; +import org.bukkit.craftbukkit.CraftWorld; +import org.bukkit.generator.BlockPopulator; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +public class NormalChunkGenerator extends InternalChunkGenerator { + private final IChunkProvider provider; + + public NormalChunkGenerator(World world, long seed) { + provider = AzuriteConfig.forceVoidChunks.getValue() ? new ChunkProviderVoid(world) : world.worldProvider.getChunkProvider(); + } + + @Override + public byte[] generate(org.bukkit.World world, Random random, int x, int z) { + throw new UnsupportedOperationException("Not supported."); + } + + @Override + public boolean canSpawn(org.bukkit.World world, int x, int z) { + return ((CraftWorld) world).getHandle().worldProvider.canSpawn(x, z); + } + + @Override + public List getDefaultPopulators(org.bukkit.World world) { + return new ArrayList(); + } + + @Override + public boolean isChunkLoaded(int i, int i1) { + return provider.isChunkLoaded(i, i1); + } + + @Override + public Chunk getOrCreateChunk(int i, int i1) { + return provider.getOrCreateChunk(i, i1); + } + + @Override + public Chunk getChunkAt(BlockPosition blockPosition) { + return provider.getChunkAt(blockPosition); + } + + @Override + public void getChunkAt(IChunkProvider icp, int i, int i1) { + provider.getChunkAt(icp, i, i1); + } + + @Override + public boolean a(IChunkProvider iChunkProvider, Chunk chunk, int i, int i1) { + return provider.a(provider, chunk, i, i1); + } + + @Override + public boolean saveChunks(boolean bln, IProgressUpdate ipu) { + return provider.saveChunks(bln, ipu); + } + + @Override + public boolean unloadChunks() { + return provider.unloadChunks(); + } + + @Override + public boolean canSave() { + return provider.canSave(); + } + + @Override + public List getMobsFor(EnumCreatureType ect, BlockPosition position) { + return provider.getMobsFor(ect, position); + } + + @Override + public BlockPosition findNearestMapFeature(World world, String string, BlockPosition position) { + return provider.findNearestMapFeature(world, string, position); + } + + // n.m.s implementations always return 0. (The true implementation is in ChunkProviderServer) + @Override + public int getLoadedChunks() { + return 0; + } + + @Override + public void recreateStructures(Chunk chunk, int i, int i1) { + provider.recreateStructures(chunk, i, i1); + } + + @Override + public String getName() { + return "NormalWorldGenerator"; + } + + @Override + public void c() {} +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/generator/SkyLandsChunkGenerator.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/generator/SkyLandsChunkGenerator.java new file mode 100644 index 0000000..e327996 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/generator/SkyLandsChunkGenerator.java @@ -0,0 +1,12 @@ +package org.bukkit.craftbukkit.generator; + +import net.minecraft.server.World; + +/** + * This class is useless. Just fyi. + */ +public class SkyLandsChunkGenerator extends NormalChunkGenerator { + public SkyLandsChunkGenerator(World world, long seed) { + super(world, seed); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/help/CommandAliasHelpTopic.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/help/CommandAliasHelpTopic.java new file mode 100644 index 0000000..9f2238c --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/help/CommandAliasHelpTopic.java @@ -0,0 +1,46 @@ +package org.bukkit.craftbukkit.help; + +import org.apache.commons.lang.Validate; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.help.HelpMap; +import org.bukkit.help.HelpTopic; + +public class CommandAliasHelpTopic extends HelpTopic { + + private final String aliasFor; + private final HelpMap helpMap; + + public CommandAliasHelpTopic(String alias, String aliasFor, HelpMap helpMap) { + this.aliasFor = aliasFor.startsWith("/") ? aliasFor : "/" + aliasFor; + this.helpMap = helpMap; + this.name = alias.startsWith("/") ? alias : "/" + alias; + Validate.isTrue(!this.name.equals(this.aliasFor), "Command " + this.name + " cannot be alias for itself"); + this.shortText = ChatColor.YELLOW + "Alias for " + ChatColor.WHITE + this.aliasFor; + } + + @Override + public String getFullText(CommandSender forWho) { + StringBuilder sb = new StringBuilder(shortText); + HelpTopic aliasForTopic = helpMap.getHelpTopic(aliasFor); + if (aliasForTopic != null) { + sb.append("\n"); + sb.append(aliasForTopic.getFullText(forWho)); + } + return sb.toString(); + } + + @Override + public boolean canSee(CommandSender commandSender) { + if (amendedPermission == null) { + HelpTopic aliasForTopic = helpMap.getHelpTopic(aliasFor); + if (aliasForTopic != null) { + return aliasForTopic.canSee(commandSender); + } else { + return false; + } + } else { + return commandSender.hasPermission(amendedPermission); + } + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/help/CustomHelpTopic.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/help/CustomHelpTopic.java new file mode 100644 index 0000000..6dee229 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/help/CustomHelpTopic.java @@ -0,0 +1,31 @@ +package org.bukkit.craftbukkit.help; + +import org.bukkit.command.CommandSender; +import org.bukkit.command.ConsoleCommandSender; +import org.bukkit.help.HelpTopic; + +/** + * This is a help topic implementation for general topics registered in the help.yml file. + */ +public class CustomHelpTopic extends HelpTopic { + private final String permissionNode; + + public CustomHelpTopic(String name, String shortText, String fullText, String permissionNode) { + this.permissionNode = permissionNode; + this.name = name; + this.shortText = shortText; + this.fullText = shortText + "\n" + fullText; + } + + public boolean canSee(CommandSender sender) { + if (sender instanceof ConsoleCommandSender) { + return true; + } + + if (!permissionNode.equals("")) { + return sender.hasPermission(permissionNode); + } else { + return true; + } + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/help/CustomIndexHelpTopic.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/help/CustomIndexHelpTopic.java new file mode 100644 index 0000000..2089a5f --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/help/CustomIndexHelpTopic.java @@ -0,0 +1,40 @@ +package org.bukkit.craftbukkit.help; + +import org.bukkit.command.CommandSender; +import org.bukkit.help.HelpMap; +import org.bukkit.help.HelpTopic; +import org.bukkit.help.IndexHelpTopic; + +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; + +/** + */ +public class CustomIndexHelpTopic extends IndexHelpTopic { + private List futureTopics; + private final HelpMap helpMap; + + public CustomIndexHelpTopic(HelpMap helpMap, String name, String shortText, String permission, List futureTopics, String preamble) { + super(name, shortText, permission, new HashSet(), preamble); + this.helpMap = helpMap; + this.futureTopics = futureTopics; + } + + @Override + public String getFullText(CommandSender sender) { + if (futureTopics != null) { + List topics = new LinkedList(); + for (String futureTopic : futureTopics) { + HelpTopic topic = helpMap.getHelpTopic(futureTopic); + if (topic != null) { + topics.add(topic); + } + } + setTopicsCollection(topics); + futureTopics = null; + } + + return super.getFullText(sender); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/help/HelpTopicAmendment.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/help/HelpTopicAmendment.java new file mode 100644 index 0000000..4f0e00e --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/help/HelpTopicAmendment.java @@ -0,0 +1,50 @@ +package org.bukkit.craftbukkit.help; + +/** + * A HelpTopicAmendment represents the contents of a topic amendment from the help.yml + */ +public class HelpTopicAmendment { + private final String topicName; + private final String shortText; + private final String fullText; + private final String permission; + + public HelpTopicAmendment(String topicName, String shortText, String fullText, String permission) { + this.fullText = fullText; + this.shortText = shortText; + this.topicName = topicName; + this.permission = permission; + } + + /** + * Gets the amended full text + * @return the full text + */ + public String getFullText() { + return fullText; + } + + /** + * Gets the amended short text + * @return the short text + */ + public String getShortText() { + return shortText; + } + + /** + * Gets the name of the topic being amended + * @return the topic name + */ + public String getTopicName() { + return topicName; + } + + /** + * Gets the amended permission + * @return the permission + */ + public String getPermission() { + return permission; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/help/HelpYamlReader.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/help/HelpYamlReader.java new file mode 100644 index 0000000..4b710c1 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/help/HelpYamlReader.java @@ -0,0 +1,118 @@ +package org.bukkit.craftbukkit.help; + +import com.google.common.base.Charsets; +import org.bukkit.ChatColor; +import org.bukkit.Server; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.help.HelpTopic; + +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.LinkedList; +import java.util.List; +import java.util.logging.Level; + +/** + * HelpYamlReader is responsible for processing the contents of the help.yml file. + */ +public class HelpYamlReader { + + private YamlConfiguration helpYaml; + private final char ALT_COLOR_CODE = '&'; + private final Server server; + + public HelpYamlReader(Server server) { + this.server = server; + + File helpYamlFile = new File("help.yml"); + YamlConfiguration defaultConfig = YamlConfiguration.loadConfiguration(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("configurations/help.yml"), Charsets.UTF_8)); + + try { + helpYaml = YamlConfiguration.loadConfiguration(helpYamlFile); + helpYaml.options().copyDefaults(true); + helpYaml.setDefaults(defaultConfig); + + try { + if (!helpYamlFile.exists()) { + helpYaml.save(helpYamlFile); + } + } catch (IOException ex) { + server.getLogger().log(Level.SEVERE, "Could not save " + helpYamlFile, ex); + } + } catch (Exception ex) { + server.getLogger().severe("Failed to load help.yml. Verify the yaml indentation is correct. Reverting to default help.yml."); + helpYaml = defaultConfig; + } + } + + /** + * Extracts a list of all general help topics from help.yml + * + * @return A list of general topics. + */ + public List getGeneralTopics() { + List topics = new LinkedList(); + ConfigurationSection generalTopics = helpYaml.getConfigurationSection("general-topics"); + if (generalTopics != null) { + for (String topicName : generalTopics.getKeys(false)) { + ConfigurationSection section = generalTopics.getConfigurationSection(topicName); + String shortText = ChatColor.translateAlternateColorCodes(ALT_COLOR_CODE, section.getString("shortText", "")); + String fullText = ChatColor.translateAlternateColorCodes(ALT_COLOR_CODE, section.getString("fullText", "")); + String permission = section.getString("permission", ""); + topics.add(new CustomHelpTopic(topicName, shortText, fullText, permission)); + } + } + return topics; + } + + /** + * Extracts a list of all index topics from help.yml + * + * @return A list of index topics. + */ + public List getIndexTopics() { + List topics = new LinkedList(); + ConfigurationSection indexTopics = helpYaml.getConfigurationSection("index-topics"); + if (indexTopics != null) { + for (String topicName : indexTopics.getKeys(false)) { + ConfigurationSection section = indexTopics.getConfigurationSection(topicName); + String shortText = ChatColor.translateAlternateColorCodes(ALT_COLOR_CODE, section.getString("shortText", "")); + String preamble = ChatColor.translateAlternateColorCodes(ALT_COLOR_CODE, section.getString("preamble", "")); + String permission = ChatColor.translateAlternateColorCodes(ALT_COLOR_CODE, section.getString("permission", "")); + List commands = section.getStringList("commands"); + topics.add(new CustomIndexHelpTopic(server.getHelpMap(), topicName, shortText, permission, commands, preamble)); + } + } + return topics; + } + + /** + * Extracts a list of topic amendments from help.yml + * + * @return A list of amendments. + */ + public List getTopicAmendments() { + List amendments = new LinkedList(); + ConfigurationSection commandTopics = helpYaml.getConfigurationSection("amended-topics"); + if (commandTopics != null) { + for (String topicName : commandTopics.getKeys(false)) { + ConfigurationSection section = commandTopics.getConfigurationSection(topicName); + String description = ChatColor.translateAlternateColorCodes(ALT_COLOR_CODE, section.getString("shortText", "")); + String usage = ChatColor.translateAlternateColorCodes(ALT_COLOR_CODE, section.getString("fullText", "")); + String permission = section.getString("permission", ""); + amendments.add(new HelpTopicAmendment(topicName, description, usage, permission)); + } + } + return amendments; + } + + public List getIgnoredPlugins() { + return helpYaml.getStringList("ignore-plugins"); + } + + public boolean commandTopicsInMasterIndex() { + return helpYaml.getBoolean("command-topics-in-master-index", true); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/help/MultipleCommandAliasHelpTopic.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/help/MultipleCommandAliasHelpTopic.java new file mode 100644 index 0000000..6f4b22b --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/help/MultipleCommandAliasHelpTopic.java @@ -0,0 +1,54 @@ +package org.bukkit.craftbukkit.help; + +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.command.ConsoleCommandSender; +import org.bukkit.command.MultipleCommandAlias; +import org.bukkit.help.HelpTopic; + +/** + * This is a help topic implementation for {@link MultipleCommandAlias} commands. + */ +public class MultipleCommandAliasHelpTopic extends HelpTopic { + + private final MultipleCommandAlias alias; + + public MultipleCommandAliasHelpTopic(MultipleCommandAlias alias) { + this.alias = alias; + + name = "/" + alias.getLabel(); + + // Build short text + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < alias.getCommands().length; i++) { + if (i != 0) { + sb.append(ChatColor.GOLD + " > " + ChatColor.WHITE); + } + sb.append("/"); + sb.append(alias.getCommands()[i].getLabel()); + } + shortText = sb.toString(); + + // Build full text + fullText = ChatColor.GOLD + "Alias for: " + ChatColor.WHITE + getShortText(); + } + + public boolean canSee(CommandSender sender) { + if (amendedPermission == null) { + if (sender instanceof ConsoleCommandSender) { + return true; + } + + for (Command command : alias.getCommands()) { + if (!command.testPermissionSilent(sender)) { + return false; + } + } + + return true; + } else { + return sender.hasPermission(amendedPermission); + } + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/help/MultipleCommandAliasHelpTopicFactory.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/help/MultipleCommandAliasHelpTopicFactory.java new file mode 100644 index 0000000..36ddc97 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/help/MultipleCommandAliasHelpTopicFactory.java @@ -0,0 +1,15 @@ +package org.bukkit.craftbukkit.help; + +import org.bukkit.command.MultipleCommandAlias; +import org.bukkit.help.HelpTopic; +import org.bukkit.help.HelpTopicFactory; + +/** + * This class creates {@link MultipleCommandAliasHelpTopic} help topics from {@link MultipleCommandAlias} commands. + */ +public class MultipleCommandAliasHelpTopicFactory implements HelpTopicFactory { + + public HelpTopic createTopic(MultipleCommandAlias multipleCommandAlias) { + return new MultipleCommandAliasHelpTopic(multipleCommandAlias); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/help/SimpleHelpMap.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/help/SimpleHelpMap.java new file mode 100644 index 0000000..249ed27 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/help/SimpleHelpMap.java @@ -0,0 +1,218 @@ +package org.bukkit.craftbukkit.help; + +import com.google.common.base.Predicate; +import com.google.common.base.Predicates; +import com.google.common.collect.Collections2; +import org.bukkit.command.*; +import org.bukkit.command.defaults.BukkitCommand; +import org.bukkit.command.defaults.VanillaCommand; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.craftbukkit.command.VanillaCommandWrapper; +import org.bukkit.help.*; + +import java.util.*; + +/** + * Standard implementation of {@link HelpMap} for CraftBukkit servers. + */ +public class SimpleHelpMap implements HelpMap { + + private HelpTopic defaultTopic; + private final Map helpTopics; + private final Map> topicFactoryMap; + private final CraftServer server; + private HelpYamlReader yaml; + + @SuppressWarnings("unchecked") + public SimpleHelpMap(CraftServer server) { + this.helpTopics = new TreeMap(HelpTopicComparator.topicNameComparatorInstance()); // Using a TreeMap for its explicit sorting on key + this.topicFactoryMap = new HashMap>(); + this.server = server; + this.yaml = new HelpYamlReader(server); + + Predicate indexFilter = Predicates.not(Predicates.instanceOf(CommandAliasHelpTopic.class)); + if (!yaml.commandTopicsInMasterIndex()) { + indexFilter = Predicates.and(indexFilter, Predicates.not(new IsCommandTopicPredicate())); + } + + this.defaultTopic = new IndexHelpTopic("Index", null, null, Collections2.filter(helpTopics.values(), indexFilter), "Use /help [n] to get page n of help."); + + registerHelpTopicFactory(MultipleCommandAlias.class, new MultipleCommandAliasHelpTopicFactory()); + } + + public synchronized HelpTopic getHelpTopic(String topicName) { + if (topicName.equals("")) { + return defaultTopic; + } + + if (helpTopics.containsKey(topicName)) { + return helpTopics.get(topicName); + } + + return null; + } + + public Collection getHelpTopics() { + return helpTopics.values(); + } + + public synchronized void addTopic(HelpTopic topic) { + // Existing topics take priority + if (!helpTopics.containsKey(topic.getName())) { + helpTopics.put(topic.getName(), topic); + } + } + + public synchronized void clear() { + helpTopics.clear(); + } + + public List getIgnoredPlugins() { + return yaml.getIgnoredPlugins(); + } + + /** + * Reads the general topics from help.yml and adds them to the help index. + */ + public synchronized void initializeGeneralTopics() { + yaml = new HelpYamlReader(server); + + // Initialize general help topics from the help.yml file + for (HelpTopic topic : yaml.getGeneralTopics()) { + addTopic(topic); + } + + // Initialize index help topics from the help.yml file + for (HelpTopic topic : yaml.getIndexTopics()) { + if (topic.getName().equals("Default")) { + defaultTopic = topic; + } else { + addTopic(topic); + } + } + } + + /** + * Processes all the commands registered in the server and creates help topics for them. + */ + public synchronized void initializeCommands() { + // ** Load topics from highest to lowest priority order ** + Set ignoredPlugins = new HashSet(yaml.getIgnoredPlugins()); + + // Don't load any automatic help topics if All is ignored + if (ignoredPlugins.contains("All")) { + return; + } + + // Initialize help topics from the server's command map + outer: for (Command command : server.getCommandMap().getCommands()) { + if (commandInIgnoredPlugin(command, ignoredPlugins)) { + continue; + } + + // Register a topic + for (Class c : topicFactoryMap.keySet()) { + if (c.isAssignableFrom(command.getClass())) { + HelpTopic t = topicFactoryMap.get(c).createTopic(command); + if (t != null) addTopic(t); + continue outer; + } + if (command instanceof PluginCommand && c.isAssignableFrom(((PluginCommand)command).getExecutor().getClass())) { + HelpTopic t = topicFactoryMap.get(c).createTopic(command); + if (t != null) addTopic(t); + continue outer; + } + } + addTopic(new GenericCommandHelpTopic(command)); + } + + // Initialize command alias help topics + for (Command command : server.getCommandMap().getCommands()) { + if (commandInIgnoredPlugin(command, ignoredPlugins)) { + continue; + } + for (String alias : command.getAliases()) { + // Only register if this command owns the alias + if (server.getCommandMap().getCommand(alias) == command) { + addTopic(new CommandAliasHelpTopic("/" + alias, "/" + command.getLabel(), this)); + } + } + } + + // Add alias sub-index + Collection filteredTopics = Collections2.filter(helpTopics.values(), Predicates.instanceOf(CommandAliasHelpTopic.class)); + if (!filteredTopics.isEmpty()) { + addTopic(new IndexHelpTopic("Aliases", "Lists command aliases", null, filteredTopics)); + } + + // Initialize plugin-level sub-topics + Map> pluginIndexes = new HashMap>(); + fillPluginIndexes(pluginIndexes, server.getCommandMap().getCommands()); + + for (Map.Entry> entry : pluginIndexes.entrySet()) { + addTopic(new IndexHelpTopic(entry.getKey(), "All commands for " + entry.getKey(), null, entry.getValue(), "Below is a list of all " + entry.getKey() + " commands:")); + } + + // Amend help topics from the help.yml file + for (HelpTopicAmendment amendment : yaml.getTopicAmendments()) { + if (helpTopics.containsKey(amendment.getTopicName())) { + helpTopics.get(amendment.getTopicName()).amendTopic(amendment.getShortText(), amendment.getFullText()); + if (amendment.getPermission() != null) { + helpTopics.get(amendment.getTopicName()).amendCanSee(amendment.getPermission()); + } + } + } + } + + private void fillPluginIndexes(Map> pluginIndexes, Collection commands) { + for (Command command : commands) { + String pluginName = getCommandPluginName(command); + if (pluginName != null) { + HelpTopic topic = getHelpTopic("/" + command.getLabel()); + if (topic != null) { + if (!pluginIndexes.containsKey(pluginName)) { + pluginIndexes.put(pluginName, new TreeSet(HelpTopicComparator.helpTopicComparatorInstance())); //keep things in topic order + } + pluginIndexes.get(pluginName).add(topic); + } + } + } + } + + private String getCommandPluginName(Command command) { + if (command instanceof VanillaCommandWrapper) { + return "Minecraft"; + } + if (command instanceof BukkitCommand || command instanceof VanillaCommand) { + return "Bukkit"; + } + if (command instanceof PluginIdentifiableCommand) { + return ((PluginIdentifiableCommand)command).getPlugin().getName(); + } + return null; + } + + private boolean commandInIgnoredPlugin(Command command, Set ignoredPlugins) { + if ((command instanceof BukkitCommand || command instanceof VanillaCommand) && ignoredPlugins.contains("Bukkit")) { + return true; + } + if (command instanceof PluginIdentifiableCommand && ignoredPlugins.contains(((PluginIdentifiableCommand)command).getPlugin().getName())) { + return true; + } + return false; + } + + public void registerHelpTopicFactory(Class commandClass, HelpTopicFactory factory) { + if (!Command.class.isAssignableFrom(commandClass) && !CommandExecutor.class.isAssignableFrom(commandClass)) { + throw new IllegalArgumentException("commandClass must implement either Command or CommandExecutor!"); + } + topicFactoryMap.put(commandClass, factory); + } + + private class IsCommandTopicPredicate implements Predicate { + + public boolean apply(HelpTopic topic) { + return topic.getName().charAt(0) == '/'; + } + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftContainer.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftContainer.java new file mode 100644 index 0000000..9dc1b14 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftContainer.java @@ -0,0 +1,353 @@ +package org.bukkit.craftbukkit.inventory; + +import net.minecraft.server.*; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.entity.HumanEntity; +import org.bukkit.event.inventory.InventoryType; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryView; + +public class CraftContainer extends Container { + private final InventoryView view; + private InventoryType cachedType; + private String cachedTitle; + private final int cachedSize; + + public CraftContainer(InventoryView view, int id) { + this.view = view; + this.windowId = id; + // TODO: Do we need to check that it really is a CraftInventory? + IInventory top = ((CraftInventory)view.getTopInventory()).getInventory(); + IInventory bottom = ((CraftInventory)view.getBottomInventory()).getInventory(); + cachedType = view.getType(); + cachedTitle = view.getTitle(); + cachedSize = getSize(); + setupSlots(top, bottom); + } + + public CraftContainer(final Inventory inventory, final HumanEntity player, int id) { + this(new InventoryView() { + @Override + public Inventory getTopInventory() { + return inventory; + } + + @Override + public Inventory getBottomInventory() { + return player.getInventory(); + } + + @Override + public HumanEntity getPlayer() { + return player; + } + + @Override + public InventoryType getType() { + return inventory.getType(); + } + }, id); + } + + @Override + public InventoryView getBukkitView() { + return view; + } + + private int getSize() { + return view.getTopInventory().getSize(); + } + + @Override + public boolean c(EntityHuman entityhuman) { + if (cachedType == view.getType() && cachedSize == getSize() && cachedTitle.equals(view.getTitle())) { + return true; + } + // If the window type has changed for some reason, update the player + // This method will be called every tick or something, so it's + // as good a place as any to put something like this. + boolean typeChanged = (cachedType != view.getType()); + cachedType = view.getType(); + cachedTitle = view.getTitle(); + if (view.getPlayer() instanceof CraftPlayer) { + CraftPlayer player = (CraftPlayer) view.getPlayer(); + String type = getNotchInventoryType(cachedType); + IInventory top = ((CraftInventory)view.getTopInventory()).getInventory(); + IInventory bottom = ((CraftInventory)view.getBottomInventory()).getInventory(); + this.b.clear(); + this.c.clear(); + if (typeChanged) { + setupSlots(top, bottom); + } + int size = getSize(); + player.getHandle().playerConnection.sendPacket(new PacketPlayOutOpenWindow(this.windowId, type, new ChatComponentText(cachedTitle), size)); + player.updateInventory(); + } + return true; + } + + public static String getNotchInventoryType(InventoryType type) { + switch(type) { + case WORKBENCH: + return "minecraft:crafting_table"; + case FURNACE: + return "minecraft:furnace"; + case DISPENSER: + return "minecraft:dispenser"; + // PandaSpigot start - Fix custom dropper inventory + case DROPPER: + return "minecraft:dropper"; + // PandaSpigot end + case ENCHANTING: + return "minecraft:enchanting_table"; + case BREWING: + return "minecraft:brewing_stand"; + case BEACON: + return "minecraft:beacon"; + case ANVIL: + return "minecraft:anvil"; + case HOPPER: + return "minecraft:hopper"; + default: + return "minecraft:chest"; + } + } + + private void setupSlots(IInventory top, IInventory bottom) { + switch(cachedType) { + case CREATIVE: + break; // TODO: This should be an error? + case PLAYER: + case CHEST: + setupChest(top, bottom); + break; + case DISPENSER: + case DROPPER: // PandaSpigot - Fix custom dropper inventory + setupDispenser(top, bottom); + break; + case FURNACE: + setupFurnace(top, bottom); + break; + case CRAFTING: // TODO: This should be an error? + case WORKBENCH: + setupWorkbench(top, bottom); + break; + case ENCHANTING: + setupEnchanting(top, bottom); + break; + case BREWING: + setupBrewing(top, bottom); + break; + // PandaSpigot start - Fix custom beacon and anvil inventories + case BEACON: + setupBeacon(top, bottom); + break; + case ANVIL: + setupAnvil(top, bottom); + break; + // PandaSpigot end + case HOPPER: + setupHopper(top, bottom); + break; + } + } + + private void setupChest(IInventory top, IInventory bottom) { + int rows = top.getSize() / 9; + int row; + int col; + // This code copied from ContainerChest + int i = (rows - 4) * 18; + for (row = 0; row < rows; ++row) { + for (col = 0; col < 9; ++col) { + this.a(new Slot(top, col + row * 9, 8 + col * 18, 18 + row * 18)); + } + } + + for (row = 0; row < 3; ++row) { + for (col = 0; col < 9; ++col) { + this.a(new Slot(bottom, col + row * 9 + 9, 8 + col * 18, 103 + row * 18 + i)); + } + } + + for (col = 0; col < 9; ++col) { + this.a(new Slot(bottom, col, 8 + col * 18, 161 + i)); + } + // End copy from ContainerChest + } + + private void setupWorkbench(IInventory top, IInventory bottom) { + // This code copied from ContainerWorkbench + this.a(new Slot(top, 0, 124, 35)); + + int row; + int col; + + for (row = 0; row < 3; ++row) { + for (col = 0; col < 3; ++col) { + this.a(new Slot(top, 1 + col + row * 3, 30 + col * 18, 17 + row * 18)); + } + } + + for (row = 0; row < 3; ++row) { + for (col = 0; col < 9; ++col) { + this.a(new Slot(bottom, col + row * 9 + 9, 8 + col * 18, 84 + row * 18)); + } + } + + for (col = 0; col < 9; ++col) { + this.a(new Slot(bottom, col, 8 + col * 18, 142)); + } + // End copy from ContainerWorkbench + } + + private void setupFurnace(IInventory top, IInventory bottom) { + // This code copied from ContainerFurnace + this.a(new Slot(top, 0, 56, 17)); + this.a(new Slot(top, 1, 56, 53)); + this.a(new Slot(top, 2, 116, 35)); + + int row; + int col; + + for (row = 0; row < 3; ++row) { + for (col = 0; col < 9; ++col) { + this.a(new Slot(bottom, col + row * 9 + 9, 8 + col * 18, 84 + row * 18)); + } + } + + for (col = 0; col < 9; ++col) { + this.a(new Slot(bottom, col, 8 + col * 18, 142)); + } + // End copy from ContainerFurnace + } + + private void setupDispenser(IInventory top, IInventory bottom) { + // This code copied from ContainerDispenser + int row; + int col; + + for (row = 0; row < 3; ++row) { + for (col = 0; col < 3; ++col) { + this.a(new Slot(top, col + row * 3, 61 + col * 18, 17 + row * 18)); + } + } + + for (row = 0; row < 3; ++row) { + for (col = 0; col < 9; ++col) { + this.a(new Slot(bottom, col + row * 9 + 9, 8 + col * 18, 84 + row * 18)); + } + } + + for (col = 0; col < 9; ++col) { + this.a(new Slot(bottom, col, 8 + col * 18, 142)); + } + // End copy from ContainerDispenser + } + + private void setupEnchanting(IInventory top, IInventory bottom) { + // PandaSpigot start - Fix enchant table custom inventory + this.a((new Slot(top, 0, 15, 47))); + this.a((new Slot(top, 1, 35, 47))); + // PandaSpigot end + + int row; + + for (row = 0; row < 3; ++row) { + for (int i1 = 0; i1 < 9; ++i1) { + this.a(new Slot(bottom, i1 + row * 9 + 9, 8 + i1 * 18, 84 + row * 18)); + } + } + + for (row = 0; row < 9; ++row) { + this.a(new Slot(bottom, row, 8 + row * 18, 142)); + } + // End copy from ContainerEnchantTable + } + + private void setupBrewing(IInventory top, IInventory bottom) { + // This code copied from ContainerBrewingStand + this.a(new Slot(top, 0, 56, 46)); + this.a(new Slot(top, 1, 79, 53)); + this.a(new Slot(top, 2, 102, 46)); + this.a(new Slot(top, 3, 79, 17)); + + int i; + + for (i = 0; i < 3; ++i) { + for (int j = 0; j < 9; ++j) { + this.a(new Slot(bottom, j + i * 9 + 9, 8 + j * 18, 84 + i * 18)); + } + } + + for (i = 0; i < 9; ++i) { + this.a(new Slot(bottom, i, 8 + i * 18, 142)); + } + // End copy from ContainerBrewingStand + } + + // PandaSpigot start - Fix custom beacon and anvil inventories + // This code copied from ContainerBeacon + private void setupBeacon(IInventory top, IInventory bottom) { + this.a(new Slot(top, 0, 136, 110)); + + int i; + + for (i = 0; i < 3; ++i) { + for (int j = 0; j < 9; ++j) { + this.a(new Slot(bottom, j + i * 9 + 9, 36 + j * 18, 137 + i * 18)); + } + } + + for (i = 0; i < 9; ++i) { + this.a(new Slot(bottom, i, 36 + i * 18, 195)); + } + } + + // This code copied from ContainerAnvil + private void setupAnvil(IInventory top, IInventory bottom) { + this.a(new Slot(top, 0, 27, 47)); + this.a(new Slot(top, 1, 76, 47)); + this.a(new Slot(top, 2, 134, 47)); + + int i; + + for (i = 0; i < 3; ++i) { + for (int j = 0; j < 9; ++j) { + this.a(new Slot(bottom, j + i * 9 + 9, 8 + j * 18, 84 + i * 18)); + } + } + + for (i = 0; i < 9; ++i) { + this.a(new Slot(bottom, i, 8 + i * 18, 142)); + } + } + // PandaSpigot end + + + private void setupHopper(IInventory top, IInventory bottom) { + // This code copied from ContainerHopper + byte b0 = 51; + + int i; + + for (i = 0; i < top.getSize(); ++i) { + this.a(new Slot(top, i, 44 + i * 18, 20)); + } + + for (i = 0; i < 3; ++i) { + for (int j = 0; j < 9; ++j) { + this.a(new Slot(bottom, j + i * 9 + 9, 8 + j * 18, i * 18 + b0)); + } + } + + for (i = 0; i < 9; ++i) { + this.a(new Slot(bottom, i, 8 + i * 18, 58 + b0)); + } + // End copy from ContainerHopper + } + + public boolean a(EntityHuman entity) { + return true; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftEntityEquipment.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftEntityEquipment.java new file mode 100644 index 0000000..c43ea8c --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftEntityEquipment.java @@ -0,0 +1,143 @@ +package org.bukkit.craftbukkit.inventory; + +import net.minecraft.server.EntityInsentient; +import org.bukkit.craftbukkit.entity.CraftLivingEntity; +import org.bukkit.entity.Entity; +import org.bukkit.inventory.EntityEquipment; +import org.bukkit.inventory.ItemStack; + +public class CraftEntityEquipment implements EntityEquipment { + private static final int WEAPON_SLOT = 0; + private static final int HELMET_SLOT = 4; + private static final int CHEST_SLOT = 3; + private static final int LEG_SLOT = 2; + private static final int BOOT_SLOT = 1; + private static final int INVENTORY_SLOTS = 5; + + private final CraftLivingEntity entity; + + public CraftEntityEquipment(CraftLivingEntity entity) { + this.entity = entity; + } + + public ItemStack getItemInHand() { + return getEquipment(WEAPON_SLOT); + } + + public void setItemInHand(ItemStack stack) { + setEquipment(WEAPON_SLOT, stack); + } + + public ItemStack getHelmet() { + return getEquipment(HELMET_SLOT); + } + + public void setHelmet(ItemStack helmet) { + setEquipment(HELMET_SLOT, helmet); + } + + public ItemStack getChestplate() { + return getEquipment(CHEST_SLOT); + } + + public void setChestplate(ItemStack chestplate) { + setEquipment(CHEST_SLOT, chestplate); + } + + public ItemStack getLeggings() { + return getEquipment(LEG_SLOT); + } + + public void setLeggings(ItemStack leggings) { + setEquipment(LEG_SLOT, leggings); + } + + public ItemStack getBoots() { + return getEquipment(BOOT_SLOT); + } + + public void setBoots(ItemStack boots) { + setEquipment(BOOT_SLOT, boots); + } + + public ItemStack[] getArmorContents() { + ItemStack[] armor = new ItemStack[INVENTORY_SLOTS - 1]; + for(int slot = WEAPON_SLOT + 1; slot < INVENTORY_SLOTS; slot++) { + armor[slot - 1] = getEquipment(slot); + } + return armor; + } + + public void setArmorContents(ItemStack[] items) { + for(int slot = WEAPON_SLOT + 1; slot < INVENTORY_SLOTS; slot++) { + ItemStack equipment = items != null && slot <= items.length ? items[slot - 1] : null; + setEquipment(slot, equipment); + } + } + + private ItemStack getEquipment(int slot) { + return CraftItemStack.asBukkitCopy(entity.getHandle().getEquipment(slot)); + } + + private void setEquipment(int slot, ItemStack stack) { + entity.getHandle().setEquipment(slot, CraftItemStack.asNMSCopy(stack)); + } + + public void clear() { + for(int i = 0; i < INVENTORY_SLOTS; i++) { + setEquipment(i, null); + } + } + + public Entity getHolder() { + return entity; + } + + public float getItemInHandDropChance() { + return getDropChance(WEAPON_SLOT); + } + + public void setItemInHandDropChance(float chance) { + setDropChance(WEAPON_SLOT, chance); + } + + public float getHelmetDropChance() { + return getDropChance(HELMET_SLOT); + } + + public void setHelmetDropChance(float chance) { + setDropChance(HELMET_SLOT, chance); + } + + public float getChestplateDropChance() { + return getDropChance(CHEST_SLOT); + } + + public void setChestplateDropChance(float chance) { + setDropChance(CHEST_SLOT, chance); + } + + public float getLeggingsDropChance() { + return getDropChance(LEG_SLOT); + } + + public void setLeggingsDropChance(float chance) { + setDropChance(LEG_SLOT, chance); + } + + public float getBootsDropChance() { + return getDropChance(BOOT_SLOT); + } + + public void setBootsDropChance(float chance) { + setDropChance(BOOT_SLOT, chance); + } + + private void setDropChance(int slot, float chance) { + ((EntityInsentient) entity.getHandle()).dropChances[slot] = chance - 0.1F; + } + + private float getDropChance(int slot) { + return ((EntityInsentient) entity.getHandle()).dropChances[slot] + 0.1F; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftFurnaceRecipe.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftFurnaceRecipe.java new file mode 100644 index 0000000..d0b5a9e --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftFurnaceRecipe.java @@ -0,0 +1,25 @@ +package org.bukkit.craftbukkit.inventory; + +import net.minecraft.server.RecipesFurnace; +import org.bukkit.inventory.FurnaceRecipe; +import org.bukkit.inventory.ItemStack; + +public class CraftFurnaceRecipe extends FurnaceRecipe implements CraftRecipe { + public CraftFurnaceRecipe(ItemStack result, ItemStack source) { + super(result, source.getType(), source.getDurability()); + } + + public static CraftFurnaceRecipe fromBukkitRecipe(FurnaceRecipe recipe) { + if (recipe instanceof CraftFurnaceRecipe) { + return (CraftFurnaceRecipe) recipe; + } + return new CraftFurnaceRecipe(recipe.getResult(), recipe.getInput()); + } + + @Override + public void addToCraftingManager() { + ItemStack result = this.getResult(); + ItemStack input = this.getInput(); + RecipesFurnace.getInstance().registerRecipe(CraftItemStack.asNMSCopy(input), CraftItemStack.asNMSCopy(result)); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventory.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventory.java new file mode 100644 index 0000000..a6addce --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventory.java @@ -0,0 +1,472 @@ +package org.bukkit.craftbukkit.inventory; + +import net.minecraft.server.*; +import org.apache.commons.lang.Validate; +import org.bukkit.Material; +import org.bukkit.entity.HumanEntity; +import org.bukkit.event.inventory.InventoryType; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryHolder; +import org.bukkit.inventory.ItemStack; + +import java.util.HashMap; +import java.util.List; +import java.util.ListIterator; + +public class CraftInventory implements Inventory { + protected final IInventory inventory; + + public CraftInventory(IInventory inventory) { + this.inventory = inventory; + } + + public IInventory getInventory() { + return inventory; + } + + public int getSize() { + return getInventory().getSize(); + } + + public String getName() { + return getInventory().getName(); + } + + public ItemStack getItem(int index) { + net.minecraft.server.ItemStack item = getInventory().getItem(index); + return item == null ? null : CraftItemStack.asCraftMirror(item); + } + + public ItemStack[] getContents() { + ItemStack[] items = new ItemStack[getSize()]; + net.minecraft.server.ItemStack[] mcItems = getInventory().getContents(); + + int size = Math.min(items.length, mcItems.length); + for (int i = 0; i < size; i++) { + net.minecraft.server.ItemStack mcItem = mcItems[i]; + items[i] = mcItem == null ? null : CraftItemStack.asCraftMirror(mcItem); + } + return items; + } + + public void setContents(ItemStack[] items) { + if (getInventory().getContents().length < items.length) { + throw new IllegalArgumentException("Invalid inventory size; expected " + getInventory().getContents().length + " or less"); + } + + net.minecraft.server.ItemStack[] mcItems = getInventory().getContents(); + + for (int i = 0; i < mcItems.length; i++) { + if (i >= items.length) { + mcItems[i] = null; + } else { + mcItems[i] = CraftItemStack.asNMSCopy(items[i]); + } + } + } + + public void setItem(int index, ItemStack item) { + getInventory().setItem(index, ((item == null || item.getTypeId() == 0) ? null : CraftItemStack.asNMSCopy(item))); + } + + public boolean contains(int materialId) { + for (ItemStack item : getContents()) { + if (item != null && item.getTypeId() == materialId) { + return true; + } + } + return false; + } + + public boolean contains(Material material) { + Validate.notNull(material, "Material cannot be null"); + return contains(material.getId()); + } + + public boolean contains(ItemStack item) { + if (item == null) { + return false; + } + for (ItemStack i : getContents()) { + if (item.equals(i)) { + return true; + } + } + return false; + } + + public boolean contains(int materialId, int amount) { + if (amount <= 0) { + return true; + } + for (ItemStack item : getContents()) { + if (item != null && item.getTypeId() == materialId) { + if ((amount -= item.getAmount()) <= 0) { + return true; + } + } + } + return false; + } + + public boolean contains(Material material, int amount) { + Validate.notNull(material, "Material cannot be null"); + return contains(material.getId(), amount); + } + + public boolean contains(ItemStack item, int amount) { + if (item == null) { + return false; + } + if (amount <= 0) { + return true; + } + for (ItemStack i : getContents()) { + if (item.equals(i) && --amount <= 0) { + return true; + } + } + return false; + } + + public boolean containsAtLeast(ItemStack item, int amount) { + if (item == null) { + return false; + } + if (amount <= 0) { + return true; + } + for (ItemStack i : getContents()) { + if (item.isSimilar(i) && (amount -= i.getAmount()) <= 0) { + return true; + } + } + return false; + } + + public HashMap all(int materialId) { + HashMap slots = new HashMap<>(); + + ItemStack[] inventory = getContents(); + for (int i = 0; i < inventory.length; i++) { + ItemStack item = inventory[i]; + if (item != null && item.getTypeId() == materialId) { + slots.put(i, item); + } + } + return slots; + } + + public HashMap all(Material material) { + Validate.notNull(material, "Material cannot be null"); + return all(material.getId()); + } + + public HashMap all(ItemStack item) { + HashMap slots = new HashMap<>(); + if (item != null) { + ItemStack[] inventory = getContents(); + for (int i = 0; i < inventory.length; i++) { + if (item.equals(inventory[i])) { + slots.put(i, inventory[i]); + } + } + } + return slots; + } + + public int first(int materialId) { + ItemStack[] inventory = getContents(); + for (int i = 0; i < inventory.length; i++) { + ItemStack item = inventory[i]; + if (item != null && item.getTypeId() == materialId) { + return i; + } + } + return -1; + } + + public int first(Material material) { + Validate.notNull(material, "Material cannot be null"); + return first(material.getId()); + } + + public int first(ItemStack item) { + return first(item, true); + } + + private int first(ItemStack item, boolean withAmount) { + if (item == null) { + return -1; + } + ItemStack[] inventory = getContents(); + for (int i = 0; i < inventory.length; i++) { + if (inventory[i] == null) continue; + + if (withAmount ? item.equals(inventory[i]) : item.isSimilar(inventory[i])) { + return i; + } + } + return -1; + } + + public int firstEmpty() { + ItemStack[] inventory = getContents(); + for (int i = 0; i < inventory.length; i++) { + if (inventory[i] == null) { + return i; + } + } + return -1; + } + + public int firstPartial(int materialId) { + ItemStack[] inventory = getContents(); + for (int i = 0; i < inventory.length; i++) { + ItemStack item = inventory[i]; + if (item != null && item.getTypeId() == materialId && item.getAmount() < item.getMaxStackSize()) { + return i; + } + } + return -1; + } + + public int firstPartial(Material material) { + Validate.notNull(material, "Material cannot be null"); + return firstPartial(material.getId()); + } + + private int firstPartial(ItemStack item) { + ItemStack[] inventory = getContents(); + ItemStack filteredItem = CraftItemStack.asCraftCopy(item); + if (item == null) { + return -1; + } + for (int i = 0; i < inventory.length; i++) { + ItemStack cItem = inventory[i]; + if (cItem != null && cItem.getAmount() < cItem.getMaxStackSize() && cItem.isSimilar(filteredItem)) { + return i; + } + } + return -1; + } + + public HashMap addItem(ItemStack... items) { + Validate.noNullElements(items, "Item cannot be null"); + HashMap leftover = new HashMap<>(); + + /* TODO: some optimization + * - Create a 'firstPartial' with a 'fromIndex' + * - Record the lastPartial per Material + * - Cache firstEmpty result + */ + + for (int i = 0; i < items.length; i++) { + ItemStack item = items[i]; + while (true) { + // Do we already have a stack of it? + int firstPartial = firstPartial(item); + + // Drat! no partial stack + if (firstPartial == -1) { + // Find a free spot! + int firstFree = firstEmpty(); + + if (firstFree == -1) { + // No space at all! + leftover.put(i, item); + break; + } else { + // More than a single stack! + if (item.getAmount() > getMaxItemStack()) { + CraftItemStack stack = CraftItemStack.asCraftCopy(item); + stack.setAmount(getMaxItemStack()); + setItem(firstFree, stack); + item.setAmount(item.getAmount() - getMaxItemStack()); + } else { + // Just store it + setItem(firstFree, item); + break; + } + } + } else { + // So, apparently it might only partially fit, well lets do just that + ItemStack partialItem = getItem(firstPartial); + + int amount = item.getAmount(); + int partialAmount = partialItem.getAmount(); + int maxAmount = partialItem.getMaxStackSize(); + + // Check if it fully fits + if (amount + partialAmount <= maxAmount) { + partialItem.setAmount(amount + partialAmount); + // To make sure the packet is sent to the client + setItem(firstPartial, partialItem); + break; + } + + // It fits partially + partialItem.setAmount(maxAmount); + // To make sure the packet is sent to the client + setItem(firstPartial, partialItem); + item.setAmount(amount + partialAmount - maxAmount); + } + } + } + return leftover; + } + + public HashMap removeItem(ItemStack... items) { + Validate.notNull(items, "Items cannot be null"); + HashMap leftover = new HashMap<>(); + + // TODO: optimization + + for (int i = 0; i < items.length; i++) { + ItemStack item = items[i]; + int toDelete = item.getAmount(); + + while (true) { + int first = first(item, false); + + // Drat! we don't have this type in the inventory + if (first == -1) { + item.setAmount(toDelete); + leftover.put(i, item); + break; + } else { + ItemStack itemStack = getItem(first); + int amount = itemStack.getAmount(); + + if (amount <= toDelete) { + toDelete -= amount; + // clear the slot, all used up + clear(first); + } else { + // split the stack and store + itemStack.setAmount(amount - toDelete); + setItem(first, itemStack); + toDelete = 0; + } + } + + // Bail when done + if (toDelete <= 0) { + break; + } + } + } + return leftover; + } + + private int getMaxItemStack() { + return getInventory().getMaxStackSize(); + } + + public void remove(int materialId) { + ItemStack[] items = getContents(); + for (int i = 0; i < items.length; i++) { + if (items[i] != null && items[i].getTypeId() == materialId) { + clear(i); + } + } + } + + public void remove(Material material) { + Validate.notNull(material, "Material cannot be null"); + remove(material.getId()); + } + + public void remove(ItemStack item) { + ItemStack[] items = getContents(); + for (int i = 0; i < items.length; i++) { + if (items[i] != null && items[i].equals(item)) { + clear(i); + } + } + } + + public void clear(int index) { + setItem(index, null); + } + + public void clear() { + for (int i = 0; i < getSize(); i++) { + clear(i); + } + } + + public ListIterator iterator() { + return new InventoryIterator(this); + } + + public ListIterator iterator(int index) { + if (index < 0) { + index += getSize() + 1; // ie, with -1, previous() will return the last element + } + return new InventoryIterator(this, index); + } + + public List getViewers() { + return this.inventory.getViewers(); + } + + public String getTitle() { + return inventory.getName(); + } + + public InventoryType getType() { + // Thanks to Droppers extending Dispensers, order is important. + if (inventory instanceof InventoryCrafting) { + return inventory.getSize() >= 9 ? InventoryType.WORKBENCH : InventoryType.CRAFTING; + } else if (inventory instanceof PlayerInventory) { + return InventoryType.PLAYER; + } else if (inventory instanceof TileEntityDropper) { + return InventoryType.DROPPER; + } else if (inventory instanceof TileEntityDispenser) { + return InventoryType.DISPENSER; + } else if (inventory instanceof TileEntityFurnace) { + return InventoryType.FURNACE; + } else if (this instanceof CraftInventoryEnchanting) { + return InventoryType.ENCHANTING; + } else if (inventory instanceof TileEntityBrewingStand) { + return InventoryType.BREWING; + } else if (inventory instanceof CraftInventoryCustom.MinecraftInventory) { + return ((CraftInventoryCustom.MinecraftInventory) inventory).getType(); + } else if (inventory instanceof InventoryEnderChest) { + return InventoryType.ENDER_CHEST; + } else if (inventory instanceof InventoryMerchant) { + return InventoryType.MERCHANT; + } else if (inventory instanceof TileEntityBeacon) { + return InventoryType.BEACON; + } else if (this instanceof CraftInventoryAnvil) { + return InventoryType.ANVIL; + } else if (inventory instanceof IHopper) { + return InventoryType.HOPPER; + } else { + return InventoryType.CHEST; + } + } + + public InventoryHolder getHolder() { + return inventory.getOwner(); + } + + public int getMaxStackSize() { + return inventory.getMaxStackSize(); + } + + public void setMaxStackSize(int size) { + inventory.setMaxStackSize(size); + } + + @Override + public int hashCode() { + return inventory.hashCode(); + } + + @Override + public boolean equals(final Object obj) { + return obj instanceof CraftInventory && ((CraftInventory) obj).inventory.equals(this.inventory); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryAnvil.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryAnvil.java new file mode 100644 index 0000000..f499946 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryAnvil.java @@ -0,0 +1,47 @@ +package org.bukkit.craftbukkit.inventory; + +import net.minecraft.server.IInventory; +import org.bukkit.inventory.AnvilInventory; +import org.bukkit.inventory.ItemStack; + +public class CraftInventoryAnvil extends CraftInventory implements AnvilInventory { + private final IInventory resultInventory; + + public CraftInventoryAnvil(IInventory inventory, IInventory resultInventory) { + super(inventory); + this.resultInventory = resultInventory; + } + + public IInventory getResultInventory() { + return resultInventory; + } + + public IInventory getIngredientsInventory() { + return inventory; + } + + @Override + public ItemStack getItem(int slot) { + if (slot < getIngredientsInventory().getSize()) { + net.minecraft.server.ItemStack item = getIngredientsInventory().getItem(slot); + return item == null ? null : CraftItemStack.asCraftMirror(item); + } else { + net.minecraft.server.ItemStack item = getResultInventory().getItem(slot - getIngredientsInventory().getSize()); + return item == null ? null : CraftItemStack.asCraftMirror(item); + } + } + + @Override + public void setItem(int index, ItemStack item) { + if (index < getIngredientsInventory().getSize()) { + getIngredientsInventory().setItem(index, (item == null ? null : CraftItemStack.asNMSCopy(item))); + } else { + getResultInventory().setItem((index - getIngredientsInventory().getSize()), (item == null ? null : CraftItemStack.asNMSCopy(item))); + } + } + + @Override + public int getSize() { + return getResultInventory().getSize() + getIngredientsInventory().getSize(); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryBeacon.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryBeacon.java new file mode 100644 index 0000000..43c4107 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryBeacon.java @@ -0,0 +1,19 @@ +package org.bukkit.craftbukkit.inventory; + +import net.minecraft.server.TileEntityBeacon; +import org.bukkit.inventory.BeaconInventory; +import org.bukkit.inventory.ItemStack; + +public class CraftInventoryBeacon extends CraftInventory implements BeaconInventory { + public CraftInventoryBeacon(TileEntityBeacon beacon) { + super(beacon); + } + + public void setItem(ItemStack item) { + setItem(0, item); + } + + public ItemStack getItem() { + return getItem(0); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryBrewer.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryBrewer.java new file mode 100644 index 0000000..54d3554 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryBrewer.java @@ -0,0 +1,25 @@ +package org.bukkit.craftbukkit.inventory; + +import net.minecraft.server.IInventory; +import org.bukkit.block.BrewingStand; +import org.bukkit.inventory.BrewerInventory; +import org.bukkit.inventory.ItemStack; + +public class CraftInventoryBrewer extends CraftInventory implements BrewerInventory { + public CraftInventoryBrewer(IInventory inventory) { + super(inventory); + } + + public ItemStack getIngredient() { + return getItem(3); + } + + public void setIngredient(ItemStack ingredient) { + setItem(3, ingredient); + } + + @Override + public BrewingStand getHolder() { + return (BrewingStand) inventory.getOwner(); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryCrafting.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryCrafting.java new file mode 100644 index 0000000..eb482ae --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryCrafting.java @@ -0,0 +1,137 @@ +package org.bukkit.craftbukkit.inventory; + +import net.minecraft.server.IInventory; +import net.minecraft.server.IRecipe; +import net.minecraft.server.InventoryCrafting; +import org.bukkit.inventory.CraftingInventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.Recipe; +import org.bukkit.util.Java15Compat; + +public class CraftInventoryCrafting extends CraftInventory implements CraftingInventory { + private final IInventory resultInventory; + + public CraftInventoryCrafting(InventoryCrafting inventory, IInventory resultInventory) { + super(inventory); + this.resultInventory = resultInventory; + } + + public IInventory getResultInventory() { + return resultInventory; + } + + public IInventory getMatrixInventory() { + return inventory; + } + + @Override + public int getSize() { + return getResultInventory().getSize() + getMatrixInventory().getSize(); + } + + @Override + public void setContents(ItemStack[] items) { + int resultLen = getResultInventory().getContents().length; + int len = getMatrixInventory().getContents().length + resultLen; + if (len > items.length) { + throw new IllegalArgumentException("Invalid inventory size; expected " + len + " or less"); + } + setContents(items[0], Java15Compat.Arrays_copyOfRange(items, 1, items.length)); + } + + @Override + public ItemStack[] getContents() { + ItemStack[] items = new ItemStack[getSize()]; + net.minecraft.server.ItemStack[] mcResultItems = getResultInventory().getContents(); + + int i = 0; + for (i = 0; i < mcResultItems.length; i++ ) { + items[i] = CraftItemStack.asCraftMirror(mcResultItems[i]); + } + + net.minecraft.server.ItemStack[] mcItems = getMatrixInventory().getContents(); + + for (int j = 0; j < mcItems.length; j++) { + items[i + j] = CraftItemStack.asCraftMirror(mcItems[j]); + } + + return items; + } + + public void setContents(ItemStack result, ItemStack[] contents) { + setResult(result); + setMatrix(contents); + } + + @Override + public CraftItemStack getItem(int index) { + if (index < getResultInventory().getSize()) { + net.minecraft.server.ItemStack item = getResultInventory().getItem(index); + return item == null ? null : CraftItemStack.asCraftMirror(item); + } else { + net.minecraft.server.ItemStack item = getMatrixInventory().getItem(index - getResultInventory().getSize()); + return item == null ? null : CraftItemStack.asCraftMirror(item); + } + } + + @Override + public void setItem(int index, ItemStack item) { + if (index < getResultInventory().getSize()) { + getResultInventory().setItem(index, (item == null ? null : CraftItemStack.asNMSCopy(item))); + } else { + getMatrixInventory().setItem((index - getResultInventory().getSize()), (item == null ? null : CraftItemStack.asNMSCopy(item))); + } + } + + public ItemStack[] getMatrix() { + ItemStack[] items = new ItemStack[getSize()]; + net.minecraft.server.ItemStack[] matrix = getMatrixInventory().getContents(); + + for (int i = 0; i < matrix.length; i++ ) { + items[i] = CraftItemStack.asCraftMirror(matrix[i]); + } + + return items; + } + + public ItemStack getResult() { + net.minecraft.server.ItemStack item = getResultInventory().getItem(0); + if(item != null) return CraftItemStack.asCraftMirror(item); + return null; + } + + public void setMatrix(ItemStack[] contents) { + if (getMatrixInventory().getContents().length > contents.length) { + throw new IllegalArgumentException("Invalid inventory size; expected " + getMatrixInventory().getContents().length + " or less"); + } + + net.minecraft.server.ItemStack[] mcItems = getMatrixInventory().getContents(); + + for (int i = 0; i < mcItems.length; i++ ) { + if (i < contents.length) { + ItemStack item = contents[i]; + if (item == null || item.getTypeId() <= 0) { + mcItems[i] = null; + } else { + mcItems[i] = CraftItemStack.asNMSCopy(item); + } + } else { + mcItems[i] = null; + } + } + } + + public void setResult(ItemStack item) { + net.minecraft.server.ItemStack[] contents = getResultInventory().getContents(); + if (item == null || item.getTypeId() <= 0) { + contents[0] = null; + } else { + contents[0] = CraftItemStack.asNMSCopy(item); + } + } + + public Recipe getRecipe() { + IRecipe recipe = ((InventoryCrafting)getInventory()).currentRecipe; + return recipe == null ? null : recipe.toBukkitRecipe(); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryCustom.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryCustom.java new file mode 100644 index 0000000..91b99d1 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryCustom.java @@ -0,0 +1,192 @@ +package org.bukkit.craftbukkit.inventory; + +import net.minecraft.server.*; +import org.apache.commons.lang.Validate; +import org.bukkit.craftbukkit.entity.CraftHumanEntity; +import org.bukkit.entity.HumanEntity; +import org.bukkit.event.inventory.InventoryType; +import org.bukkit.inventory.InventoryHolder; + +import java.util.ArrayList; +import java.util.List; + +public class CraftInventoryCustom extends CraftInventory { + public CraftInventoryCustom(InventoryHolder owner, InventoryType type) { + super(new MinecraftInventory(owner, type)); + } + + public CraftInventoryCustom(InventoryHolder owner, InventoryType type, String title) { + super(new MinecraftInventory(owner, type, title)); + } + + public CraftInventoryCustom(InventoryHolder owner, int size) { + super(new MinecraftInventory(owner, size)); + } + + public CraftInventoryCustom(InventoryHolder owner, int size, String title) { + super(new MinecraftInventory(owner, size, title)); + } + + static class MinecraftInventory implements IInventory { + private final ItemStack[] items; + private int maxStack = MAX_STACK; + private final List viewers; + private final String title; + private InventoryType type; + private final InventoryHolder owner; + + public MinecraftInventory(InventoryHolder owner, InventoryType type) { + this(owner, type.getDefaultSize(), type.getDefaultTitle()); + this.type = type; + } + + public MinecraftInventory(InventoryHolder owner, InventoryType type, String title) { + this(owner, type.getDefaultSize(), title); + this.type = type; + } + + public MinecraftInventory(InventoryHolder owner, int size) { + this(owner, size, "Chest"); + } + + public MinecraftInventory(InventoryHolder owner, int size, String title) { + Validate.notNull(title, "Title cannot be null"); + this.items = new ItemStack[size]; + this.title = title; + this.viewers = new ArrayList<>(); + this.owner = owner; + this.type = InventoryType.CHEST; + } + + public int getSize() { + return items.length; + } + + public ItemStack getItem(int i) { + return items[i]; + } + + public ItemStack splitStack(int i, int j) { + ItemStack stack = this.getItem(i); + ItemStack result; + if (stack == null) return null; + if (stack.count <= j) { + this.setItem(i, null); + result = stack; + } else { + result = CraftItemStack.copyNMSStack(stack, j); + stack.count -= j; + } + this.update(); + return result; + } + + public ItemStack splitWithoutUpdate(int i) { + ItemStack stack = this.getItem(i); + ItemStack result; + if (stack == null) return null; + if (stack.count <= 1) { + this.setItem(i, null); + result = stack; + } else { + result = CraftItemStack.copyNMSStack(stack, 1); + stack.count -= 1; + } + return result; + } + + public void setItem(int i, ItemStack itemstack) { + items[i] = itemstack; + if (itemstack != null && this.getMaxStackSize() > 0 && itemstack.count > this.getMaxStackSize()) { + itemstack.count = this.getMaxStackSize(); + } + } + + public int getMaxStackSize() { + return maxStack; + } + + public void setMaxStackSize(int size) { + maxStack = size; + } + + public void update() {} + + public boolean a(EntityHuman entityhuman) { + return true; + } + + public ItemStack[] getContents() { + return items; + } + + public void onOpen(CraftHumanEntity who) { + viewers.add(who); + } + + public void onClose(CraftHumanEntity who) { + viewers.remove(who); + } + + public List getViewers() { + return viewers; + } + + public InventoryType getType() { + return type; + } + + public InventoryHolder getOwner() { + return owner; + } + + public boolean b(int i, ItemStack itemstack) { + return true; + } + + @Override + public void startOpen(EntityHuman entityHuman) { + + } + + @Override + public void closeContainer(EntityHuman entityHuman) { + + } + + @Override + public int getProperty(int i) { + return 0; + } + + @Override + public void b(int i, int i1) { + + } + + @Override + public int g() { + return 0; + } + + @Override + public void l() { + + } + + @Override + public String getName() { + return title; + } + + @Override + public boolean hasCustomName() { + return title != null; + } + + @Override + public IChatBaseComponent getScoreboardDisplayName() { + return new ChatComponentText(title); + } + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryDoubleChest.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryDoubleChest.java new file mode 100644 index 0000000..241388b --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryDoubleChest.java @@ -0,0 +1,60 @@ +package org.bukkit.craftbukkit.inventory; + +import net.minecraft.server.ITileInventory; +import net.minecraft.server.InventoryLargeChest; +import org.bukkit.block.DoubleChest; +import org.bukkit.inventory.DoubleChestInventory; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; + +public class CraftInventoryDoubleChest extends CraftInventory implements DoubleChestInventory { + private final CraftInventory left; + private final CraftInventory right; + + public CraftInventoryDoubleChest(CraftInventory left, CraftInventory right) { + super(new InventoryLargeChest("Large chest", (ITileInventory) left.getInventory(), (ITileInventory) right.getInventory())); + this.left = left; + this.right = right; + } + + public CraftInventoryDoubleChest(InventoryLargeChest largeChest) { + super(largeChest); + if (largeChest.left instanceof InventoryLargeChest) { + left = new CraftInventoryDoubleChest((InventoryLargeChest) largeChest.left); + } else { + left = new CraftInventory(largeChest.left); + } + if (largeChest.right instanceof InventoryLargeChest) { + right = new CraftInventoryDoubleChest((InventoryLargeChest) largeChest.right); + } else { + right = new CraftInventory(largeChest.right); + } + } + + public Inventory getLeftSide() { + return left; + } + + public Inventory getRightSide() { + return right; + } + + @Override + public void setContents(ItemStack[] items) { + if (getInventory().getContents().length < items.length) { + throw new IllegalArgumentException("Invalid inventory size; expected " + getInventory().getContents().length + " or less"); + } + ItemStack[] leftItems = new ItemStack[left.getSize()], rightItems = new ItemStack[right.getSize()]; + System.arraycopy(items, 0, leftItems, 0, Math.min(left.getSize(),items.length)); + left.setContents(leftItems); + if (items.length >= left.getSize()) { + System.arraycopy(items, left.getSize(), rightItems, 0, Math.min(right.getSize(), items.length - left.getSize())); + right.setContents(rightItems); + } + } + + @Override + public DoubleChest getHolder() { + return new DoubleChest(this); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryEnchanting.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryEnchanting.java new file mode 100644 index 0000000..2efe090 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryEnchanting.java @@ -0,0 +1,36 @@ +package org.bukkit.craftbukkit.inventory; + +import net.minecraft.server.InventorySubcontainer; +import org.bukkit.inventory.EnchantingInventory; +import org.bukkit.inventory.ItemStack; + +public class CraftInventoryEnchanting extends CraftInventory implements EnchantingInventory { + public CraftInventoryEnchanting(InventorySubcontainer inventory) { + super(inventory); + } + + @Override + public void setItem(ItemStack item) { + setItem(0,item); + } + + @Override + public ItemStack getItem() { + return getItem(0); + } + + @Override + public InventorySubcontainer getInventory() { + return (InventorySubcontainer)inventory; + } + + @Override + public void setSecondary(ItemStack item) { + setItem(1, item); + } + + @Override + public ItemStack getSecondary() { + return getItem(1); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryFurnace.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryFurnace.java new file mode 100644 index 0000000..8fd083f --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryFurnace.java @@ -0,0 +1,41 @@ +package org.bukkit.craftbukkit.inventory; + +import net.minecraft.server.TileEntityFurnace; +import org.bukkit.block.Furnace; +import org.bukkit.inventory.FurnaceInventory; +import org.bukkit.inventory.ItemStack; + +public class CraftInventoryFurnace extends CraftInventory implements FurnaceInventory { + public CraftInventoryFurnace(TileEntityFurnace inventory) { + super(inventory); + } + + public ItemStack getResult() { + return getItem(2); + } + + public ItemStack getFuel() { + return getItem(1); + } + + public ItemStack getSmelting() { + return getItem(0); + } + + public void setFuel(ItemStack stack) { + setItem(1,stack); + } + + public void setResult(ItemStack stack) { + setItem(2,stack); + } + + public void setSmelting(ItemStack stack) { + setItem(0,stack); + } + + @Override + public Furnace getHolder() { + return (Furnace) inventory.getOwner(); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryHorse.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryHorse.java new file mode 100644 index 0000000..5adbd74 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryHorse.java @@ -0,0 +1,28 @@ +package org.bukkit.craftbukkit.inventory; + +import net.minecraft.server.IInventory; +import org.bukkit.inventory.HorseInventory; +import org.bukkit.inventory.ItemStack; + +public class CraftInventoryHorse extends CraftInventory implements HorseInventory { + + public CraftInventoryHorse(IInventory inventory) { + super(inventory); + } + + public ItemStack getSaddle() { + return getItem(0); + } + + public ItemStack getArmor() { + return getItem(1); + } + + public void setSaddle(ItemStack stack) { + setItem(0, stack); + } + + public void setArmor(ItemStack stack) { + setItem(1, stack); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryMerchant.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryMerchant.java new file mode 100644 index 0000000..7f89c2a --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryMerchant.java @@ -0,0 +1,10 @@ +package org.bukkit.craftbukkit.inventory; + +import net.minecraft.server.InventoryMerchant; +import org.bukkit.inventory.MerchantInventory; + +public class CraftInventoryMerchant extends CraftInventory implements MerchantInventory { + public CraftInventoryMerchant(InventoryMerchant merchant) { + super(merchant); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryPlayer.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryPlayer.java new file mode 100644 index 0000000..5fc06c6 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryPlayer.java @@ -0,0 +1,215 @@ +package org.bukkit.craftbukkit.inventory; + +import net.minecraft.server.EntityPlayer; +import net.minecraft.server.PacketPlayOutHeldItemSlot; +import net.minecraft.server.PacketPlayOutSetSlot; +import net.minecraft.server.PlayerInventory; +import org.apache.commons.lang.Validate; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.entity.HumanEntity; +import org.bukkit.inventory.EntityEquipment; +import org.bukkit.inventory.ItemStack; + +public class CraftInventoryPlayer extends CraftInventory implements org.bukkit.inventory.PlayerInventory, EntityEquipment { + public CraftInventoryPlayer(net.minecraft.server.PlayerInventory inventory) { + super(inventory); + } + + @Override + public PlayerInventory getInventory() { + return (PlayerInventory) inventory; + } + + @Override + public int getSize() { + return super.getSize() - 4; + } + + public ItemStack getItemInHand() { + return CraftItemStack.asCraftMirror(getInventory().getItemInHand()); + } + + public void setItemInHand(ItemStack stack) { + setItem(getHeldItemSlot(), stack); + } + + @Override + public void setItem(int index, ItemStack item) { + super.setItem(index, item); + if (this.getHolder() == null) return; + EntityPlayer player = ((CraftPlayer) this.getHolder()).getHandle(); + if (player.playerConnection == null) return; + // PacketPlayOutSetSlot places the items differently than setItem() + // + // Between, and including, index 9 (the first index outside of the hotbar) and index 35 (the last index before + // armor slots) both PacketPlayOutSetSlot and setItem() places the items in the player's inventory the same way. + // Index 9 starts at the upper left corner of the inventory and moves to the right as it increases. When it + // reaches the end of the line it goes back to the left side of the new line in the inventory. Basically, it + // follows the path your eyes would follow as you read a book. + // + // The player's hotbar is indexed 0-8 in setItem(). The order goes: 0-8 hotbar, 9-35 normal inventory, 36 boots, + // 37 leggings, 38 chestplate, and 39 helmet. For indexes > 39 an ArrayIndexOutOfBoundsException will be thrown. + // + // PacketPlayOutSetSlot works very differently. Slots 0-8 are as follows: 0 crafting output, 1-4 crafting input, + // 5 helmet, 6 chestplate, 7 leggings, and 8 boots. Then, 9-35 work exactly the same as setItem(). The hotbar + // for PacketPlayOutSetSlot starts at index 36, and continues to index 44. Items placed where index is < 0 or + // > 44 have no action. Basically, the upper part of the player's inventory (crafting area and armor slots) is + // the first "row" of 9 slots for PacketPlayOutSetSlot. From there the rows work as normal, from left to right + // all the way down, including the hotbar. + // + // With this in mind, we have to modify the index we give PacketPlayOutSetSlot to match the index we intended + // with setItem(). First, if the index is 0-8, we need to add 36, or 4 rows worth of slots, to the index. This + // will push the item down to the correct spot in the hotbar. + // + // Now when index is > 35 (if index > 39 an ArrayIndexOutOfBoundsException will be thrown, so we need not worry + // about it) then we need to reset the index, and then count backwards from the "top" of the inventory. That is + // to say, we first find (index - 36), which will give us the index required for the armor slots. Now, we need + // to reverse the order of the index from 8. That means we need 0 to correspond to 8, 1 to correspond to 7, + // 2 to correspond to 6, and 3 to correspond to 5. We do this simply by taking the result of (index - 36) and + // subtracting that value from 8. + if (index < PlayerInventory.getHotbarSize()) + index = index + 36; + else if (index > 35) + index = 8 - (index - 36); + player.playerConnection.sendPacket(new PacketPlayOutSetSlot(player.defaultContainer.windowId, index, CraftItemStack.asNMSCopy(item))); + } + + public int getHeldItemSlot() { + return getInventory().itemInHandIndex; + } + + public void setHeldItemSlot(int slot) { + Validate.isTrue(slot >= 0 && slot < PlayerInventory.getHotbarSize(), "Slot is not between 0 and 8 inclusive"); + this.getInventory().itemInHandIndex = slot; + ((CraftPlayer) this.getHolder()).getHandle().playerConnection.sendPacket(new PacketPlayOutHeldItemSlot(slot)); + } + + public ItemStack getHelmet() { + return getItem(getSize() + 3); + } + + public ItemStack getChestplate() { + return getItem(getSize() + 2); + } + + public ItemStack getLeggings() { + return getItem(getSize() + 1); + } + + public ItemStack getBoots() { + return getItem(getSize()); + } + + public void setHelmet(ItemStack helmet) { + setItem(getSize() + 3, helmet); + } + + public void setChestplate(ItemStack chestplate) { + setItem(getSize() + 2, chestplate); + } + + public void setLeggings(ItemStack leggings) { + setItem(getSize() + 1, leggings); + } + + public void setBoots(ItemStack boots) { + setItem(getSize(), boots); + } + + public ItemStack[] getArmorContents() { + net.minecraft.server.ItemStack[] mcItems = getInventory().getArmorContents(); + ItemStack[] ret = new ItemStack[mcItems.length]; + + for (int i = 0; i < mcItems.length; i++) { + ret[i] = CraftItemStack.asCraftMirror(mcItems[i]); + } + return ret; + } + + public void setArmorContents(ItemStack[] items) { + int cnt = getSize(); + + if (items == null) { + items = new ItemStack[4]; + } + for (ItemStack item : items) { + if (item == null || item.getTypeId() == 0) { + clear(cnt++); + } else { + setItem(cnt++, item); + } + } + } + + public int clear(int id, int data) { + int count = 0; + ItemStack[] items = getContents(); + ItemStack[] armor = getArmorContents(); + int armorSlot = getSize(); + + for (int i = 0; i < items.length; i++) { + ItemStack item = items[i]; + if (item == null) continue; + if (id > -1 && item.getTypeId() != id) continue; + if (data > -1 && item.getData().getData() != data) continue; + + count += item.getAmount(); + setItem(i, null); + } + + for (ItemStack item : armor) { + if (item == null) continue; + if (id > -1 && item.getTypeId() != id) continue; + if (data > -1 && item.getData().getData() != data) continue; + + count += item.getAmount(); + setItem(armorSlot++, null); + } + return count; + } + + @Override + public HumanEntity getHolder() { + return (HumanEntity) inventory.getOwner(); + } + + public float getItemInHandDropChance() { + return 1; + } + + public void setItemInHandDropChance(float chance) { + throw new UnsupportedOperationException(); + } + + public float getHelmetDropChance() { + return 1; + } + + public void setHelmetDropChance(float chance) { + throw new UnsupportedOperationException(); + } + + public float getChestplateDropChance() { + return 1; + } + + public void setChestplateDropChance(float chance) { + throw new UnsupportedOperationException(); + } + + public float getLeggingsDropChance() { + return 1; + } + + public void setLeggingsDropChance(float chance) { + throw new UnsupportedOperationException(); + } + + public float getBootsDropChance() { + return 1; + } + + public void setBootsDropChance(float chance) { + throw new UnsupportedOperationException(); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryView.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryView.java new file mode 100644 index 0000000..93c6a24 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryView.java @@ -0,0 +1,141 @@ +package org.bukkit.craftbukkit.inventory; + +import net.minecraft.server.Container; +import org.bukkit.GameMode; +import org.bukkit.craftbukkit.entity.CraftHumanEntity; +import org.bukkit.entity.HumanEntity; +import org.bukkit.event.inventory.InventoryType; +import org.bukkit.event.inventory.InventoryType.SlotType; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryView; +import org.bukkit.inventory.ItemStack; + +public class CraftInventoryView extends InventoryView { + private final Container container; + private final CraftHumanEntity player; + private final CraftInventory viewing; + + public CraftInventoryView(HumanEntity player, Inventory viewing, Container container) { + // TODO: Should we make sure it really IS a CraftHumanEntity first? And a CraftInventory? + this.player = (CraftHumanEntity) player; + this.viewing = (CraftInventory) viewing; + this.container = container; + } + + @Override + public Inventory getTopInventory() { + return viewing; + } + + @Override + public Inventory getBottomInventory() { + return player.getInventory(); + } + + @Override + public HumanEntity getPlayer() { + return player; + } + + @Override + public InventoryType getType() { + InventoryType type = viewing.getType(); + if (type == InventoryType.CRAFTING && player.getGameMode() == GameMode.CREATIVE) { + return InventoryType.CREATIVE; + } + return type; + } + + @Override + public void setItem(int slot, ItemStack item) { + net.minecraft.server.ItemStack stack = CraftItemStack.asNMSCopy(item); + if (slot != -999) { + container.getSlot(slot).set(stack); + } else { + player.getHandle().drop(stack, false); + } + } + + @Override + public ItemStack getItem(int slot) { + if (slot == -999) { + return null; + } + return CraftItemStack.asCraftMirror(container.getSlot(slot).getItem()); + } + + public boolean isInTop(int rawSlot) { + return rawSlot < viewing.getSize(); + } + + public Container getHandle() { + return container; + } + + public static SlotType getSlotType(InventoryView inventory, int slot) { + SlotType type = SlotType.CONTAINER; + if (slot >= 0 && slot < inventory.getTopInventory().getSize()) { + switch(inventory.getType()) { + case FURNACE: + if (slot == 2) { + type = SlotType.RESULT; + } else if(slot == 1) { + type = SlotType.FUEL; + } else { + type = SlotType.CRAFTING; + } + break; + case BREWING: + if (slot == 3) { + type = SlotType.FUEL; + } else { + type = SlotType.CRAFTING; + } + break; + case ENCHANTING: + type = SlotType.CRAFTING; + break; + case WORKBENCH: + case CRAFTING: + if (slot == 0) { + type = SlotType.RESULT; + } else { + type = SlotType.CRAFTING; + } + break; + case MERCHANT: + if (slot == 2) { + type = SlotType.RESULT; + } else { + type = SlotType.CRAFTING; + } + break; + case BEACON: + type = SlotType.CRAFTING; + break; + case ANVIL: + if (slot == 2) { + type = SlotType.RESULT; + } else { + type = SlotType.CRAFTING; + } + break; + default: + // Nothing to do, it's a CONTAINER slot + } + } else { + if (slot == -999) { + type = SlotType.OUTSIDE; + } else if (inventory.getType() == InventoryType.CRAFTING) { + if (slot < 9) { + type = SlotType.ARMOR; + } else if (slot > 35) { + type = SlotType.QUICKBAR; + } + } else if (slot >= (inventory.countSlots() - 9)) { + type = SlotType.QUICKBAR; + } + } + return type; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemFactory.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemFactory.java new file mode 100644 index 0000000..1ca1dda --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemFactory.java @@ -0,0 +1,164 @@ +package org.bukkit.craftbukkit.inventory; + +import com.google.common.collect.ImmutableSet; +import org.apache.commons.lang.Validate; +import org.bukkit.Color; +import org.bukkit.Material; +import org.bukkit.configuration.serialization.ConfigurationSerialization; +import org.bukkit.inventory.ItemFactory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.Collection; + +public final class CraftItemFactory implements ItemFactory { + static final Color DEFAULT_LEATHER_COLOR = Color.fromRGB(0xA06540); + static final Collection KNOWN_NBT_ATTRIBUTE_NAMES; + private static final CraftItemFactory instance; + + static { + instance = new CraftItemFactory(); + ConfigurationSerialization.registerClass(SerializableMeta.class); + KNOWN_NBT_ATTRIBUTE_NAMES = ImmutableSet.builder() + .add("generic.attackDamage") + .add("generic.followRange") + .add("generic.knockbackResistance") + .add("generic.maxHealth") + .add("generic.movementSpeed") + .add("horse.jumpStrength") + .add("zombie.spawnReinforcements") + .build(); + } + + private CraftItemFactory() { + } + + public boolean isApplicable(ItemMeta meta, ItemStack itemstack) { + if (itemstack == null) { + return false; + } + return isApplicable(meta, itemstack.getType()); + } + + public boolean isApplicable(ItemMeta meta, Material type) { + if (type == null || meta == null) { + return false; + } + if (!(meta instanceof CraftMetaItem)) { + throw new IllegalArgumentException("Meta of " + meta.getClass().toString() + " not created by " + CraftItemFactory.class.getName()); + } + + return ((CraftMetaItem) meta).applicableTo(type); + } + + public ItemMeta getItemMeta(Material material) { + Validate.notNull(material, "Material cannot be null"); + return getItemMeta(material, null); + } + + private ItemMeta getItemMeta(Material material, CraftMetaItem meta) { + switch (material) { + case AIR: + return null; + case WRITTEN_BOOK: + return meta instanceof CraftMetaBookSigned ? meta : new CraftMetaBookSigned(meta); + case BOOK_AND_QUILL: + return meta != null && meta.getClass().equals(CraftMetaBook.class) ? meta : new CraftMetaBook(meta); + case SKULL_ITEM: + return meta instanceof CraftMetaSkull ? meta : new CraftMetaSkull(meta); + case LEATHER_HELMET: + case LEATHER_CHESTPLATE: + case LEATHER_LEGGINGS: + case LEATHER_BOOTS: + return meta instanceof CraftMetaLeatherArmor ? meta : new CraftMetaLeatherArmor(meta); + case POTION: + return meta instanceof CraftMetaPotion ? meta : new CraftMetaPotion(meta); + case MAP: + return meta instanceof CraftMetaMap ? meta : new CraftMetaMap(meta); + case FIREWORK: + return meta instanceof CraftMetaFirework ? meta : new CraftMetaFirework(meta); + case FIREWORK_CHARGE: + return meta instanceof CraftMetaCharge ? meta : new CraftMetaCharge(meta); + case ENCHANTED_BOOK: + return meta instanceof CraftMetaEnchantedBook ? meta : new CraftMetaEnchantedBook(meta); + case BANNER: + return meta instanceof CraftMetaBanner ? meta : new CraftMetaBanner(meta); + case FURNACE: + case CHEST: + case TRAPPED_CHEST: + case JUKEBOX: + case DISPENSER: + case DROPPER: + case SIGN: + case MOB_SPAWNER: + case NOTE_BLOCK: + case PISTON_BASE: + case BREWING_STAND_ITEM: + case ENCHANTMENT_TABLE: + case COMMAND: + case BEACON: + case DAYLIGHT_DETECTOR: + case DAYLIGHT_DETECTOR_INVERTED: + case HOPPER: + case REDSTONE_COMPARATOR: + case FLOWER_POT_ITEM: + return new CraftMetaBlockState(meta, material); + default: + return new CraftMetaItem(meta); + } + } + + public boolean equals(ItemMeta meta1, ItemMeta meta2) { + if (meta1 == meta2) { + return true; + } + if (meta1 != null && !(meta1 instanceof CraftMetaItem)) { + throw new IllegalArgumentException("First meta of " + meta1.getClass().getName() + " does not belong to " + CraftItemFactory.class.getName()); + } + if (meta2 != null && !(meta2 instanceof CraftMetaItem)) { + throw new IllegalArgumentException("Second meta " + meta2.getClass().getName() + " does not belong to " + CraftItemFactory.class.getName()); + } + if (meta1 == null) { + return ((CraftMetaItem) meta2).isEmpty(); + } + if (meta2 == null) { + return ((CraftMetaItem) meta1).isEmpty(); + } + + return equals((CraftMetaItem) meta1, (CraftMetaItem) meta2); + } + + boolean equals(CraftMetaItem meta1, CraftMetaItem meta2) { + /* + * This couldn't be done inside of the objects themselves, else force recursion. + * This is a fairly clean way of implementing it, by dividing the methods into purposes and letting each method perform its own function. + * + * The common and uncommon were split, as both could have variables not applicable to the other, like a skull and book. + * Each object needs its chance to say "hey wait a minute, we're not equal," but without the redundancy of using the 1.equals(2) && 2.equals(1) checking the 'commons' twice. + * + * Doing it this way fills all conditions of the .equals() method. + */ + return meta1.equalsCommon(meta2) && meta1.notUncommon(meta2) && meta2.notUncommon(meta1); + } + + public static CraftItemFactory instance() { + return instance; + } + + public ItemMeta asMetaFor(ItemMeta meta, ItemStack stack) { + Validate.notNull(stack, "Stack cannot be null"); + return asMetaFor(meta, stack.getType()); + } + + public ItemMeta asMetaFor(ItemMeta meta, Material material) { + Validate.notNull(material, "Material cannot be null"); + if (!(meta instanceof CraftMetaItem)) { + throw new IllegalArgumentException("Meta of " + (meta != null ? meta.getClass().toString() : "null") + " not created by " + CraftItemFactory.class.getName()); + } + return getItemMeta(material, (CraftMetaItem) meta); + } + + public Color getDefaultLeatherColor() { + return DEFAULT_LEATHER_COLOR; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemStack.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemStack.java new file mode 100644 index 0000000..a7341b1 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemStack.java @@ -0,0 +1,434 @@ +package org.bukkit.craftbukkit.inventory; + +import com.google.common.collect.ImmutableMap; +import net.minecraft.server.EnchantmentManager; +import net.minecraft.server.Item; +import net.minecraft.server.NBTTagCompound; +import net.minecraft.server.NBTTagList; +import org.apache.commons.lang.Validate; +import org.bukkit.Material; +import org.bukkit.configuration.serialization.DelegateDeserialization; +import org.bukkit.craftbukkit.util.CraftMagicNumbers; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.Map; + +import static org.bukkit.craftbukkit.inventory.CraftMetaItem.*; + +@DelegateDeserialization(ItemStack.class) +public final class CraftItemStack extends ItemStack { + + public static net.minecraft.server.ItemStack asNMSCopy(ItemStack original) { + if (original instanceof CraftItemStack) { + CraftItemStack stack = (CraftItemStack) original; + return stack.handle == null ? null : stack.handle.cloneItemStack(); + } + if (original == null || original.getTypeId() <= 0) { + return null; + } + + Item item = CraftMagicNumbers.getItem(original.getType()); + + if (item == null) { + return null; + } + + net.minecraft.server.ItemStack stack = new net.minecraft.server.ItemStack(item, original.getAmount(), original.getDurability()); + if (original.hasItemMeta()) { + setItemMeta(stack, original.getItemMeta()); + } + return stack; + } + + public static net.minecraft.server.ItemStack copyNMSStack(net.minecraft.server.ItemStack original, int amount) { + net.minecraft.server.ItemStack stack = original.cloneItemStack(); + stack.count = amount; + return stack; + } + + /** + * Copies the NMS stack to return as a strictly-Bukkit stack + */ + public static ItemStack asBukkitCopy(net.minecraft.server.ItemStack original) { + if (original == null) { + return new ItemStack(Material.AIR); + } + ItemStack stack = new ItemStack(CraftMagicNumbers.getMaterial(original.getItem()), original.count, (short) original.getData()); + if (hasItemMeta(original)) { + stack.setItemMeta(getItemMeta(original)); + } + return stack; + } + + public static CraftItemStack asCraftMirror(net.minecraft.server.ItemStack original) { + return new CraftItemStack(original); + } + + public static CraftItemStack asCraftCopy(ItemStack original) { + if (original instanceof CraftItemStack) { + CraftItemStack stack = (CraftItemStack) original; + return new CraftItemStack(stack.handle == null ? null : stack.handle.cloneItemStack()); + } + return new CraftItemStack(original); + } + + public static CraftItemStack asNewCraftStack(Item item) { + return asNewCraftStack(item, 1); + } + + public static CraftItemStack asNewCraftStack(Item item, int amount) { + return new CraftItemStack(CraftMagicNumbers.getMaterial(item), amount, (short) 0, null); + } + + public net.minecraft.server.ItemStack handle; // PandaSpigot - public + + /** + * Mirror + */ + private CraftItemStack(net.minecraft.server.ItemStack item) { + this.handle = item; + } + + private CraftItemStack(ItemStack item) { + this(item.getTypeId(), item.getAmount(), item.getDurability(), item.hasItemMeta() ? item.getItemMeta() : null); + } + + private CraftItemStack(Material type, int amount, short durability, ItemMeta itemMeta) { + setType(type); + setAmount(amount); + setDurability(durability); + setItemMeta(itemMeta); + } + + private CraftItemStack(int typeId, int amount, short durability, ItemMeta itemMeta) { + this(Material.getMaterial(typeId), amount, durability, itemMeta); + + } + + @Override + public int getTypeId() { + return handle != null ? CraftMagicNumbers.getId(handle.getItem()) : 0; + } + + @Override + public void setTypeId(int type) { + if (getTypeId() == type) { + return; + } else if (type == 0) { + handle = null; + } else if (CraftMagicNumbers.getItem(type) == null) { // :( + handle = null; + } else if (handle == null) { + handle = new net.minecraft.server.ItemStack(CraftMagicNumbers.getItem(type), 1, 0); + } else { + handle.setItem(CraftMagicNumbers.getItem(type)); + if (hasItemMeta()) { + // This will create the appropriate item meta, which will contain all the data we intend to keep + setItemMeta(handle, getItemMeta(handle)); + } + } + setData(null); + } + + @Override + public int getAmount() { + return handle != null ? handle.count : 0; + } + + @Override + public void setAmount(int amount) { + if (handle == null) { + return; + } + if (amount == 0) { + handle = null; + } else { + handle.count = amount; + } + } + + @Override + public void setDurability(final short durability) { + // Ignore damage if item is null + if (handle != null) { + handle.setData(durability); + } + } + + @Override + public short getDurability() { + if (handle != null) { + return (short) handle.getData(); + } else { + return -1; + } + } + + @Override + public int getMaxStackSize() { + return (handle == null) ? Material.AIR.getMaxStackSize() : handle.getItem().getMaxStackSize(); + } + + @Override + public void addUnsafeEnchantment(Enchantment ench, int level) { + Validate.notNull(ench, "Cannot add null enchantment"); + + if (!makeTag(handle)) { + return; + } + NBTTagList list = getEnchantmentList(handle); + if (list == null) { + list = new NBTTagList(); + handle.getTag().set(ENCHANTMENTS.NBT, list); + } + int size = list.size(); + + for (int i = 0; i < size; i++) { + NBTTagCompound tag = list.get(i); + short id = tag.getShort(ENCHANTMENTS_ID.NBT); + if (id == ench.getId()) { + tag.setShort(ENCHANTMENTS_LVL.NBT, (short) level); + return; + } + } + NBTTagCompound tag = new NBTTagCompound(); + tag.setShort(ENCHANTMENTS_ID.NBT, (short) ench.getId()); + tag.setShort(ENCHANTMENTS_LVL.NBT, (short) level); + list.add(tag); + } + + static boolean makeTag(net.minecraft.server.ItemStack item) { + if (item == null) { + return false; + } + + if (item.getTag() == null) { + item.setTag(new NBTTagCompound()); + } + + return true; + } + + @Override + public boolean containsEnchantment(Enchantment ench) { + return getEnchantmentLevel(ench) > 0; + } + + @Override + public int getEnchantmentLevel(Enchantment ench) { + Validate.notNull(ench, "Cannot find null enchantment"); + if (handle == null) { + return 0; + } + return EnchantmentManager.getEnchantmentLevel(ench.getId(), handle); + } + + @Override + public int removeEnchantment(Enchantment ench) { + Validate.notNull(ench, "Cannot remove null enchantment"); + + NBTTagList list = getEnchantmentList(handle), listCopy; + if (list == null) { + return 0; + } + int index = Integer.MIN_VALUE; + int level = Integer.MIN_VALUE; + int size = list.size(); + + for (int i = 0; i < size; i++) { + NBTTagCompound enchantment = list.get(i); + int id = 0xffff & enchantment.getShort(ENCHANTMENTS_ID.NBT); + if (id == ench.getId()) { + index = i; + level = 0xffff & enchantment.getShort(ENCHANTMENTS_LVL.NBT); + break; + } + } + + if (index == Integer.MIN_VALUE) { + return 0; + } + if (size == 1) { + handle.getTag().remove(ENCHANTMENTS.NBT); + if (handle.getTag().isEmpty()) { + handle.setTag(null); + } + return level; + } + + // This is workaround for not having an index removal + listCopy = new NBTTagList(); + for (int i = 0; i < size; i++) { + if (i != index) { + listCopy.add(list.get(i)); + } + } + handle.getTag().set(ENCHANTMENTS.NBT, listCopy); + + return level; + } + + @Override + public Map getEnchantments() { + return getEnchantments(handle); + } + + static Map getEnchantments(net.minecraft.server.ItemStack item) { + NBTTagList list = (item != null && item.hasEnchantments()) ? item.getEnchantments() : null; + + if (list == null || list.size() == 0) { + return ImmutableMap.of(); + } + + ImmutableMap.Builder result = ImmutableMap.builder(); + + for (int i = 0; i < list.size(); i++) { + int id = 0xffff & list.get(i).getShort(ENCHANTMENTS_ID.NBT); + int level = 0xffff & list.get(i).getShort(ENCHANTMENTS_LVL.NBT); + + result.put(Enchantment.getById(id), level); + } + + return result.build(); + } + + static NBTTagList getEnchantmentList(net.minecraft.server.ItemStack item) { + return (item != null && item.hasEnchantments()) ? item.getEnchantments() : null; + } + + @Override + public CraftItemStack clone() { + CraftItemStack itemStack = (CraftItemStack) super.clone(); + if (this.handle != null) { + itemStack.handle = this.handle.cloneItemStack(); + } + return itemStack; + } + + @Override + public ItemMeta getItemMeta() { + return getItemMeta(handle); + } + + public static ItemMeta getItemMeta(net.minecraft.server.ItemStack item) { + if (!hasItemMeta(item)) { + return CraftItemFactory.instance().getItemMeta(getType(item)); + } + switch (getType(item)) { + case WRITTEN_BOOK: + return new CraftMetaBookSigned(item.getTag()); + case BOOK_AND_QUILL: + return new CraftMetaBook(item.getTag()); + case SKULL_ITEM: + return new CraftMetaSkull(item.getTag()); + case LEATHER_HELMET: + case LEATHER_CHESTPLATE: + case LEATHER_LEGGINGS: + case LEATHER_BOOTS: + return new CraftMetaLeatherArmor(item.getTag()); + case POTION: + return new CraftMetaPotion(item.getTag()); + case MAP: + return new CraftMetaMap(item.getTag()); + case FIREWORK: + return new CraftMetaFirework(item.getTag()); + case FIREWORK_CHARGE: + return new CraftMetaCharge(item.getTag()); + case ENCHANTED_BOOK: + return new CraftMetaEnchantedBook(item.getTag()); + case BANNER: + return new CraftMetaBanner(item.getTag()); + case FURNACE: + case CHEST: + case TRAPPED_CHEST: + case JUKEBOX: + case DISPENSER: + case DROPPER: + case SIGN: + case MOB_SPAWNER: + case NOTE_BLOCK: + case PISTON_BASE: + case BREWING_STAND_ITEM: + case ENCHANTMENT_TABLE: + case COMMAND: + case BEACON: + case DAYLIGHT_DETECTOR: + case DAYLIGHT_DETECTOR_INVERTED: + case HOPPER: + case REDSTONE_COMPARATOR: + case FLOWER_POT_ITEM: + return new CraftMetaBlockState(item.getTag(), CraftMagicNumbers.getMaterial(item.getItem())); + default: + return new CraftMetaItem(item.getTag()); + } + } + + static Material getType(net.minecraft.server.ItemStack item) { + Material material = Material.getMaterial(item == null ? 0 : CraftMagicNumbers.getId(item.getItem())); + return material == null ? Material.AIR : material; + } + + @Override + public boolean setItemMeta(ItemMeta itemMeta) { + return setItemMeta(handle, itemMeta); + } + + public static boolean setItemMeta(net.minecraft.server.ItemStack item, ItemMeta itemMeta) { + if (item == null) { + return false; + } + if (CraftItemFactory.instance().equals(itemMeta, null)) { + item.setTag(null); + return true; + } + if (!CraftItemFactory.instance().isApplicable(itemMeta, getType(item))) { + return false; + } + + itemMeta = CraftItemFactory.instance().asMetaFor(itemMeta, getType(item)); + if (itemMeta == null) return true; + + NBTTagCompound tag = new NBTTagCompound(); + item.setTag(tag); + + ((CraftMetaItem) itemMeta).applyToItem(tag); + + return true; + } + + @Override + public boolean isSimilar(ItemStack stack) { + if (stack == null) { + return false; + } + if (stack == this) { + return true; + } + if (!(stack instanceof CraftItemStack)) { + return stack.getClass() == ItemStack.class && stack.isSimilar(this); + } + + CraftItemStack that = (CraftItemStack) stack; + if (handle == that.handle) { + return true; + } + if (handle == null || that.handle == null) { + return false; + } + if (!(that.getTypeId() == getTypeId() && getDurability() == that.getDurability())) { + return false; + } + return hasItemMeta() ? that.hasItemMeta() && handle.getTag().equals(that.handle.getTag()) : !that.hasItemMeta(); + } + + @Override + public boolean hasItemMeta() { + return hasItemMeta(handle); + } + + static boolean hasItemMeta(net.minecraft.server.ItemStack item) { + return !(item == null || item.getTag() == null || item.getTag().isEmpty()); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBanner.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBanner.java new file mode 100644 index 0000000..5f336b7 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBanner.java @@ -0,0 +1,211 @@ +package org.bukkit.craftbukkit.inventory; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import net.minecraft.server.NBTTagCompound; +import net.minecraft.server.NBTTagList; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.block.banner.Pattern; +import org.bukkit.block.banner.PatternType; +import org.bukkit.configuration.serialization.DelegateDeserialization; +import org.bukkit.inventory.meta.BannerMeta; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +@DelegateDeserialization(SerializableMeta.class) +public class CraftMetaBanner extends CraftMetaItem implements BannerMeta { + + static final ItemMetaKey BASE = new ItemMetaKey("Base", "base-color"); + static final ItemMetaKey PATTERNS = new ItemMetaKey("Patterns", "patterns"); + static final ItemMetaKey COLOR = new ItemMetaKey("Color", "color"); + static final ItemMetaKey PATTERN = new ItemMetaKey("Pattern", "pattern"); + + private DyeColor base; + private List patterns = new ArrayList<>(); + + CraftMetaBanner(CraftMetaItem meta) { + super(meta); + + if (!(meta instanceof CraftMetaBanner)) { + return; + } + + CraftMetaBanner banner = (CraftMetaBanner) meta; + base = banner.base; + patterns = new ArrayList<>(banner.patterns); + } + + CraftMetaBanner(NBTTagCompound tag) { + super(tag); + + if (!tag.hasKey("BlockEntityTag")) { + return; + } + + NBTTagCompound entityTag = tag.getCompound("BlockEntityTag"); + + base = entityTag.hasKey(BASE.NBT) ? DyeColor.getByDyeData((byte) entityTag.getInt(BASE.NBT)) : null; + + if (entityTag.hasKey(PATTERNS.NBT)) { + NBTTagList patterns = entityTag.getList(PATTERNS.NBT, 10); + for (int i = 0; i < Math.min(patterns.size(), 20); i++) { + NBTTagCompound p = patterns.get(i); + DyeColor color = DyeColor.getByDyeData((byte) p.getInt(COLOR.NBT)); + PatternType pattern = PatternType.getByIdentifier(p.getString(PATTERN.NBT)); + + if (color != null && pattern != null) { + this.patterns.add(new Pattern(color, pattern)); + } + } + } + } + + CraftMetaBanner(Map map) { + super(map); + + String baseStr = SerializableMeta.getString(map, BASE.BUKKIT, true); + if (baseStr != null) { + base = DyeColor.valueOf(baseStr); + } + + Iterable rawPatternList = SerializableMeta.getObject(Iterable.class, map, PATTERNS.BUKKIT, true); + if (rawPatternList == null) { + return; + } + + for (Object obj : rawPatternList) { + if (!(obj instanceof Pattern)) { + throw new IllegalArgumentException("Object in pattern list is not valid. " + obj.getClass()); + } + addPattern((Pattern) obj); + } + } + + @Override + void applyToItem(NBTTagCompound tag) { + super.applyToItem(tag); + + NBTTagCompound entityTag = new NBTTagCompound(); + if (base != null) { + entityTag.setInt(BASE.NBT, base.getDyeData()); + } + + NBTTagList newPatterns = new NBTTagList(); + + for (Pattern p : patterns) { + NBTTagCompound compound = new NBTTagCompound(); + compound.setInt(COLOR.NBT, p.getColor().getDyeData()); + compound.setString(PATTERN.NBT, p.getPattern().getIdentifier()); + newPatterns.add(compound); + } + entityTag.set(PATTERNS.NBT, newPatterns); + + tag.set("BlockEntityTag", entityTag); + } + + @Override + public DyeColor getBaseColor() { + return base; + } + + @Override + public void setBaseColor(DyeColor color) { + base = color; + } + + @Override + public List getPatterns() { + return new ArrayList<>(patterns); + } + + @Override + public void setPatterns(List patterns) { + this.patterns = new ArrayList<>(patterns); + } + + @Override + public void addPattern(Pattern pattern) { + patterns.add(pattern); + } + + @Override + public Pattern getPattern(int i) { + return patterns.get(i); + } + + @Override + public Pattern removePattern(int i) { + return patterns.remove(i); + } + + @Override + public void setPattern(int i, Pattern pattern) { + patterns.set(i, pattern); + } + + @Override + public int numberOfPatterns() { + return patterns.size(); + } + + @Override + ImmutableMap.Builder serialize(ImmutableMap.Builder builder) { + super.serialize(builder); + + if (base != null) { + builder.put(BASE.BUKKIT, base.toString()); + } + + if (!patterns.isEmpty()) { + builder.put(PATTERNS.BUKKIT, ImmutableList.copyOf(patterns)); + } + + return builder; + } + + @Override + int applyHash() { + final int original; + int hash = original = super.applyHash(); + if (base != null) { + hash = 31 * hash + base.hashCode(); + } + if (!patterns.isEmpty()) { + hash = 31 * hash + patterns.hashCode(); + } + return original != hash ? CraftMetaBanner.class.hashCode() ^ hash : hash; + } + + @Override + public boolean equalsCommon(CraftMetaItem meta) { + if (!super.equalsCommon(meta)) { + return false; + } + if (meta instanceof CraftMetaBanner) { + CraftMetaBanner that = (CraftMetaBanner) meta; + + return base == that.base && patterns.equals(that.patterns); + } + return true; + } + + @Override + boolean notUncommon(CraftMetaItem meta) { + return super.notUncommon(meta) && (meta instanceof CraftMetaBanner || (patterns.isEmpty() && base == null)); + } + + + @Override + boolean isEmpty() { + return super.isEmpty() && patterns.isEmpty() && base == null; + } + + + @Override + boolean applicableTo(Material type) { + return type == Material.BANNER; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBlockState.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBlockState.java new file mode 100644 index 0000000..820bac9 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBlockState.java @@ -0,0 +1,309 @@ +package org.bukkit.craftbukkit.inventory; + +import com.google.common.base.Objects; +import com.google.common.collect.ImmutableMap; +import net.minecraft.server.*; +import org.apache.commons.lang.Validate; +import org.bukkit.Material; +import org.bukkit.block.BlockState; +import org.bukkit.configuration.serialization.DelegateDeserialization; +import org.bukkit.craftbukkit.block.*; +import org.bukkit.inventory.meta.BlockStateMeta; + +import java.util.Map; + +@DelegateDeserialization(SerializableMeta.class) +public class CraftMetaBlockState extends CraftMetaItem implements BlockStateMeta { + + @ItemMetaKey.Specific(ItemMetaKey.Specific.To.NBT) + static final ItemMetaKey BLOCK_ENTITY_TAG = new ItemMetaKey("BlockEntityTag"); + + final Material material; + NBTTagCompound blockEntityTag; + + CraftMetaBlockState(CraftMetaItem meta, Material material) { + super(meta); + this.material = material; + + if (!(meta instanceof CraftMetaBlockState) + || ((CraftMetaBlockState) meta).material != material + || material == Material.SIGN + || material == Material.COMMAND) { + blockEntityTag = null; + return; + } + + CraftMetaBlockState te = (CraftMetaBlockState) meta; + this.blockEntityTag = te.blockEntityTag; + } + + CraftMetaBlockState(NBTTagCompound tag, Material material) { + super(tag); + this.material = material; + + if (tag.hasKeyOfType(BLOCK_ENTITY_TAG.NBT, 10)) { + blockEntityTag = tag.getCompound(BLOCK_ENTITY_TAG.NBT); + } else { + blockEntityTag = null; + } + } + + CraftMetaBlockState(Map map) { + super(map); + String matName = SerializableMeta.getString(map, "blockMaterial", true); + Material m = Material.getMaterial(matName); + if (m != null) { + material = m; + } else { + material = Material.AIR; + } + } + + @Override + void applyToItem(NBTTagCompound tag) { + super.applyToItem(tag); + + if (blockEntityTag != null) { + tag.set(BLOCK_ENTITY_TAG.NBT, blockEntityTag); + } + } + + @Override + void deserializeInternal(NBTTagCompound tag) { + if (tag.hasKeyOfType(BLOCK_ENTITY_TAG.NBT, 10)) { + blockEntityTag = tag.getCompound(BLOCK_ENTITY_TAG.NBT); + } + } + + @Override + void serializeInternal(final Map internalTags) { + if (blockEntityTag != null) { + internalTags.put(BLOCK_ENTITY_TAG.NBT, blockEntityTag); + } + } + + @Override + ImmutableMap.Builder serialize(ImmutableMap.Builder builder) { + super.serialize(builder); + builder.put("blockMaterial", material.name()); + return builder; + } + + @Override + int applyHash() { + final int original; + int hash = original = super.applyHash(); + if (blockEntityTag != null) { + hash = 61 * hash + this.blockEntityTag.hashCode(); + } + return original != hash ? CraftMetaBlockState.class.hashCode() ^ hash : hash; + } + + @Override + public boolean equalsCommon(CraftMetaItem meta) { + if (!super.equalsCommon(meta)) { + return false; + } + if (meta instanceof CraftMetaBlockState) { + CraftMetaBlockState that = (CraftMetaBlockState) meta; + + return Objects.equal(this.blockEntityTag, that.blockEntityTag); + } + return true; + } + + @Override + boolean notUncommon(CraftMetaItem meta) { + return super.notUncommon(meta) && (meta instanceof CraftMetaBlockState || blockEntityTag == null); + } + + @Override + boolean isEmpty() { + return super.isEmpty() && blockEntityTag == null; + } + + @Override + boolean applicableTo(Material type) { + switch(type){ + case FURNACE: + case CHEST: + case TRAPPED_CHEST: + case JUKEBOX: + case DISPENSER: + case DROPPER: + case SIGN: + case MOB_SPAWNER: + case NOTE_BLOCK: + case PISTON_BASE: + case BREWING_STAND_ITEM: + case ENCHANTMENT_TABLE: + case COMMAND: + case BEACON: + case DAYLIGHT_DETECTOR: + case DAYLIGHT_DETECTOR_INVERTED: + case HOPPER: + case REDSTONE_COMPARATOR: + case FLOWER_POT_ITEM: + return true; + } + return false; + } + + @Override + public boolean hasBlockState() { + return blockEntityTag != null; + } + + @Override + public BlockState getBlockState() { + TileEntity te = blockEntityTag == null ? null : TileEntity.c(blockEntityTag); + + switch (material) { + case SIGN: + case SIGN_POST: + case WALL_SIGN: + if (te == null) { + te = new TileEntitySign(); + } + return new CraftSign(material, (TileEntitySign) te); + case CHEST: + case TRAPPED_CHEST: + if (te == null) { + te = new TileEntityChest(); + } + return new CraftChest(material, (TileEntityChest) te); + case BURNING_FURNACE: + case FURNACE: + if (te == null) { + te = new TileEntityFurnace(); + } + return new CraftFurnace(material, (TileEntityFurnace) te); + case DISPENSER: + if (te == null) { + te = new TileEntityDispenser(); + } + return new CraftDispenser(material, (TileEntityDispenser) te); + case DROPPER: + if (te == null) { + te = new TileEntityDispenser(); + } + return new CraftDropper(material, (TileEntityDropper) te); + case HOPPER: + if (te == null) { + te = new TileEntityHopper(); + } + return new CraftHopper(material, (TileEntityHopper) te); + case MOB_SPAWNER: + if (te == null) { + te = new TileEntityMobSpawner(); + } + return new CraftCreatureSpawner(material, (TileEntityMobSpawner) te); + case NOTE_BLOCK: + if (te == null) { + te = new TileEntityNote(); + } + return new CraftNoteBlock(material, (TileEntityNote) te); + case JUKEBOX: + if (te == null) { + te = new BlockJukeBox.TileEntityRecordPlayer(); + } + return new CraftJukebox(material, (BlockJukeBox.TileEntityRecordPlayer) te); + case BREWING_STAND: + if (te == null) { + te = new TileEntityBrewingStand(); + } + return new CraftBrewingStand(material, (TileEntityBrewingStand) te); + case SKULL: + if (te == null) { + te = new TileEntitySkull(); + } + return new CraftSkull(material, (TileEntitySkull) te); + case COMMAND: + if (te == null) { + te = new TileEntityCommand(); + } + return new CraftCommandBlock(material, (TileEntityCommand) te); + case BEACON: + if (te == null) { + te = new TileEntityBeacon(); + } + return new CraftBeacon(material, (TileEntityBeacon) te); + case BANNER: + case WALL_BANNER: + case STANDING_BANNER: + if (te == null) { + te = new TileEntityBanner(); + } + return new CraftBanner(material, (TileEntityBanner) te); + default: + throw new IllegalStateException("Missing blockState for " + material); + } + } + + @Override + public void setBlockState(BlockState blockState) { + Validate.notNull(blockState, "blockState must not be null"); + TileEntity te = ((CraftBlockState) blockState).getTileEntity(); + Validate.notNull(te, "Invalid blockState"); + + boolean valid; + switch (material) { + case SIGN: + case SIGN_POST: + case WALL_SIGN: + valid = te instanceof TileEntitySign; + break; + case CHEST: + case TRAPPED_CHEST: + valid = te instanceof TileEntityChest; + break; + case BURNING_FURNACE: + case FURNACE: + valid = te instanceof TileEntityFurnace; + break; + case DISPENSER: + valid = te instanceof TileEntityDispenser; + break; + case DROPPER: + valid = te instanceof TileEntityDropper; + break; + case HOPPER: + valid = te instanceof TileEntityHopper; + break; + case MOB_SPAWNER: + valid = te instanceof TileEntityMobSpawner; + break; + case NOTE_BLOCK: + valid = te instanceof TileEntityNote; + break; + case JUKEBOX: + valid = te instanceof BlockJukeBox.TileEntityRecordPlayer; + break; + case BREWING_STAND: + valid = te instanceof TileEntityBrewingStand; + break; + case SKULL: + valid = te instanceof TileEntitySkull; + break; + case COMMAND: + valid = te instanceof TileEntityCommand; + break; + case BEACON: + valid = te instanceof TileEntityBeacon; + break; + case BANNER: + case WALL_BANNER: + case STANDING_BANNER: + valid = te instanceof TileEntityBanner; + break; + default: + valid = false; + break; + } + + Validate.isTrue(valid, "Invalid blockState for " + material); + + blockEntityTag = new NBTTagCompound(); + te.b(blockEntityTag); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBook.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBook.java new file mode 100644 index 0000000..9f2edb8 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBook.java @@ -0,0 +1,334 @@ +package org.bukkit.craftbukkit.inventory; + +import com.google.common.base.Strings; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap.Builder; +import net.minecraft.server.IChatBaseComponent; +import net.minecraft.server.IChatBaseComponent.ChatSerializer; +import net.minecraft.server.NBTTagCompound; +import net.minecraft.server.NBTTagList; +import net.minecraft.server.NBTTagString; +import org.apache.commons.lang.Validate; +import org.bukkit.Material; +import org.bukkit.configuration.serialization.DelegateDeserialization; +import org.bukkit.craftbukkit.util.CraftChatMessage; +import org.bukkit.inventory.meta.BookMeta; + +import java.util.AbstractList; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import static org.spigotmc.ValidateUtils.limit; +// Spigot end + +@DelegateDeserialization(SerializableMeta.class) +public class CraftMetaBook extends CraftMetaItem implements BookMeta { + static final ItemMetaKey BOOK_TITLE = new ItemMetaKey("title"); + static final ItemMetaKey BOOK_AUTHOR = new ItemMetaKey("author"); + static final ItemMetaKey BOOK_PAGES = new ItemMetaKey("pages"); + static final ItemMetaKey RESOLVED = new ItemMetaKey("resolved"); + static final ItemMetaKey GENERATION = new ItemMetaKey("generation"); + static final int MAX_PAGE_LENGTH = Short.MAX_VALUE; // TODO: Check me + static final int MAX_TITLE_LENGTH = 0xffff; + + protected String title; + protected String author; + public List pages = new ArrayList<>(); + protected Integer generation; + + CraftMetaBook(CraftMetaItem meta) { + super(meta); + + if (meta instanceof CraftMetaBook) { + CraftMetaBook bookMeta = (CraftMetaBook) meta; + this.title = bookMeta.title; + this.author = bookMeta.author; + pages.addAll(bookMeta.pages); + this.generation = bookMeta.generation; + } + } + + CraftMetaBook(NBTTagCompound tag) { + this(tag, true); + } + + CraftMetaBook(NBTTagCompound tag, boolean handlePages) { + super(tag); + + if (tag.hasKey(BOOK_TITLE.NBT)) { + this.title = limit( tag.getString(BOOK_TITLE.NBT), 1024 ); // Spigot + } + + if (tag.hasKey(BOOK_AUTHOR.NBT)) { + this.author = limit( tag.getString(BOOK_AUTHOR.NBT), 1024 ); // Spigot + } + + boolean resolved = false; + if (tag.hasKey(RESOLVED.NBT)) { + resolved = tag.getBoolean(RESOLVED.NBT); + } + + if (tag.hasKey(GENERATION.NBT)) { + generation = tag.getInt(GENERATION.NBT); + } + + if (tag.hasKey(BOOK_PAGES.NBT) && handlePages) { + NBTTagList pages = tag.getList(BOOK_PAGES.NBT, 8); + + for (int i = 0; i < pages.size(); i++) { + String page = pages.getString(i); + if (resolved) { + try { + this.pages.add(ChatSerializer.a(page)); + continue; + } catch (Exception e) { + // Ignore and treat as an old book + } + } + addPage( limit( page, 2048 ) ); // Spigot + } + } + } + + CraftMetaBook(Map map) { + super(map); + + setAuthor(SerializableMeta.getString(map, BOOK_AUTHOR.BUKKIT, true)); + + setTitle(SerializableMeta.getString(map, BOOK_TITLE.BUKKIT, true)); + + Iterable pages = SerializableMeta.getObject(Iterable.class, map, BOOK_PAGES.BUKKIT, true); + if(pages != null) { + for (Object page : pages) { + if (page instanceof String) { + addPage((String) page); + } + } + } + + generation = SerializableMeta.getObject(Integer.class, map, GENERATION.BUKKIT, true); + } + + @Override + void applyToItem(NBTTagCompound itemData) { + applyToItem(itemData, true); + } + + void applyToItem(NBTTagCompound itemData, boolean handlePages) { + super.applyToItem(itemData); + + if (hasTitle()) { + itemData.setString(BOOK_TITLE.NBT, this.title); + } + + if (hasAuthor()) { + itemData.setString(BOOK_AUTHOR.NBT, this.author); + } + + if (handlePages) { + if (hasPages()) { + NBTTagList list = new NBTTagList(); + for (IChatBaseComponent page : pages) { + list.add(new NBTTagString(CraftChatMessage.fromComponent(page))); + } + itemData.set(BOOK_PAGES.NBT, list); + } + + itemData.remove(RESOLVED.NBT); + } + + if (generation != null) { + itemData.setInt(GENERATION.NBT, generation); + } + } + + @Override + boolean isEmpty() { + return super.isEmpty() && isBookEmpty(); + } + + boolean isBookEmpty() { + return !(hasPages() || hasAuthor() || hasTitle()); + } + + @Override + boolean applicableTo(Material type) { + switch (type) { + case WRITTEN_BOOK: + case BOOK_AND_QUILL: + return true; + default: + return false; + } + } + + public boolean hasAuthor() { + return !Strings.isNullOrEmpty(author); + } + + public boolean hasTitle() { + return !Strings.isNullOrEmpty(title); + } + + public boolean hasPages() { + return !pages.isEmpty(); + } + + public String getTitle() { + return this.title; + } + + public boolean setTitle(final String title) { + if (title == null) { + this.title = null; + return true; + } else if (title.length() > MAX_TITLE_LENGTH) { + return false; + } + + this.title = title; + return true; + } + + public String getAuthor() { + return this.author; + } + + public void setAuthor(final String author) { + this.author = author; + } + + public String getPage(final int page) { + Validate.isTrue(isValidPage(page), "Invalid page number"); + return CraftChatMessage.fromComponent(pages.get(page - 1)); + } + + public void setPage(final int page, final String text) { + if (!isValidPage(page)) { + throw new IllegalArgumentException("Invalid page number " + page + "/" + pages.size()); + } + + String newText = text == null ? "" : text.length() > MAX_PAGE_LENGTH ? text.substring(0, MAX_PAGE_LENGTH) : text; + pages.set(page - 1, CraftChatMessage.fromString(newText, true)[0]); + } + + public void setPages(final String... pages) { + this.pages.clear(); + + addPage(pages); + } + + public void addPage(final String... pages) { + for (String page : pages) { + if (page == null) { + page = ""; + } else if (page.length() > MAX_PAGE_LENGTH) { + page = page.substring(0, MAX_PAGE_LENGTH); + } + + this.pages.add(CraftChatMessage.fromString(page, true)[0]); + } + } + + public int getPageCount() { + return pages.size(); + } + + public List getPages() { + final List copy = ImmutableList.copyOf(pages); + return new AbstractList() { + + @Override + public String get(int index) { + return CraftChatMessage.fromComponent(copy.get(index)); + } + + @Override + public int size() { + return copy.size(); + } + }; + } + + public void setPages(List pages) { + this.pages.clear(); + for (String page : pages) { + addPage(page); + } + } + + private boolean isValidPage(int page) { + return page > 0 && page <= pages.size(); + } + + @Override + public CraftMetaBook clone() { + CraftMetaBook meta = (CraftMetaBook) super.clone(); + meta.pages = new ArrayList<>(pages); + return meta; + } + + @Override + int applyHash() { + final int original; + int hash = original = super.applyHash(); + if (hasTitle()) { + hash = 61 * hash + this.title.hashCode(); + } + if (hasAuthor()) { + hash = 61 * hash + 13 * this.author.hashCode(); + } + if (hasPages()) { + hash = 61 * hash + 17 * this.pages.hashCode(); + } + return original != hash ? CraftMetaBook.class.hashCode() ^ hash : hash; + } + + @Override + boolean equalsCommon(CraftMetaItem meta) { + if (!super.equalsCommon(meta)) { + return false; + } + if (meta instanceof CraftMetaBook) { + CraftMetaBook that = (CraftMetaBook) meta; + + return (hasTitle() ? that.hasTitle() && this.title.equals(that.title) : !that.hasTitle()) + && (hasAuthor() ? that.hasAuthor() && this.author.equals(that.author) : !that.hasAuthor()) + && (hasPages() ? that.hasPages() && this.pages.equals(that.pages) : !that.hasPages()); + } + return true; + } + + @Override + boolean notUncommon(CraftMetaItem meta) { + return super.notUncommon(meta) && (meta instanceof CraftMetaBook || isBookEmpty()); + } + + @Override + Builder serialize(Builder builder) { + super.serialize(builder); + + if (hasTitle()) { + builder.put(BOOK_TITLE.BUKKIT, title); + } + + if (hasAuthor()) { + builder.put(BOOK_AUTHOR.BUKKIT, author); + } + + if (hasPages()) { + List pagesString = new ArrayList<>(); + for (IChatBaseComponent comp : pages) { + pagesString.add(CraftChatMessage.fromComponent(comp)); + } + builder.put(BOOK_PAGES.BUKKIT, pagesString); + } + + if (generation != null) { + builder.put(GENERATION.BUKKIT, generation); + } + + return builder; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBookSigned.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBookSigned.java new file mode 100644 index 0000000..319ada8 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBookSigned.java @@ -0,0 +1,127 @@ +package org.bukkit.craftbukkit.inventory; + +import com.google.common.collect.ImmutableMap.Builder; +import net.minecraft.server.IChatBaseComponent; +import net.minecraft.server.IChatBaseComponent.ChatSerializer; +import net.minecraft.server.NBTTagCompound; +import net.minecraft.server.NBTTagList; +import net.minecraft.server.NBTTagString; +import org.bukkit.Material; +import org.bukkit.configuration.serialization.DelegateDeserialization; +import org.bukkit.inventory.meta.BookMeta; + +import java.util.Map; + +@DelegateDeserialization(SerializableMeta.class) +class CraftMetaBookSigned extends CraftMetaBook implements BookMeta { + + CraftMetaBookSigned(CraftMetaItem meta) { + super(meta); + } + + CraftMetaBookSigned(NBTTagCompound tag) { + super(tag, false); + + boolean resolved = true; + if (tag.hasKey(RESOLVED.NBT)) { + resolved = tag.getBoolean(RESOLVED.NBT); + } + + if (tag.hasKey(BOOK_PAGES.NBT)) { + NBTTagList pages = tag.getList(BOOK_PAGES.NBT, 8); + + for (int i = 0; i < pages.size(); i++) { + String page = pages.getString(i); + if (resolved) { + try { + this.pages.add(ChatSerializer.a(page)); + continue; + } catch (Exception e) { + // Ignore and treat as an old book + } + } + addPage(page); + } + } + } + + CraftMetaBookSigned(Map map) { + super(map); + } + + @Override + void applyToItem(NBTTagCompound itemData) { + super.applyToItem(itemData, false); + + if (hasTitle()) { + itemData.setString(BOOK_TITLE.NBT, this.title); + } else { + itemData.setString(BOOK_TITLE.NBT, " "); + } + + if (hasAuthor()) { + itemData.setString(BOOK_AUTHOR.NBT, this.author); + } else { + itemData.setString(BOOK_AUTHOR.NBT, " "); + } + + if (hasPages()) { + NBTTagList list = new NBTTagList(); + for (IChatBaseComponent page : pages) { + list.add(new NBTTagString( + ChatSerializer.a(page) + )); + } + itemData.set(BOOK_PAGES.NBT, list); + } + itemData.setBoolean(RESOLVED.NBT, true); + + if (generation != null) { + itemData.setInt(GENERATION.NBT, generation); + } else { + itemData.setInt(GENERATION.NBT, 0); + } + } + + @Override + boolean isEmpty() { + return super.isEmpty(); + } + + @Override + boolean applicableTo(Material type) { + switch (type) { + case WRITTEN_BOOK: + case BOOK_AND_QUILL: + return true; + default: + return false; + } + } + + @Override + public CraftMetaBookSigned clone() { + return (CraftMetaBookSigned) super.clone(); + } + + @Override + int applyHash() { + return super.applyHash(); + } + + @Override + boolean equalsCommon(CraftMetaItem meta) { + return super.equalsCommon(meta); + } + + @Override + boolean notUncommon(CraftMetaItem meta) { + return super.notUncommon(meta) && (meta instanceof CraftMetaBookSigned || isBookEmpty()); + } + + @Override + Builder serialize(Builder builder) { + super.serialize(builder); + return builder; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaCharge.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaCharge.java new file mode 100644 index 0000000..7418f2f --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaCharge.java @@ -0,0 +1,127 @@ +package org.bukkit.craftbukkit.inventory; + +import com.google.common.collect.ImmutableMap.Builder; +import net.minecraft.server.NBTTagCompound; +import org.bukkit.FireworkEffect; +import org.bukkit.Material; +import org.bukkit.configuration.serialization.DelegateDeserialization; +import org.bukkit.inventory.meta.FireworkEffectMeta; + +import java.util.Map; + +@DelegateDeserialization(SerializableMeta.class) +class CraftMetaCharge extends CraftMetaItem implements FireworkEffectMeta { + static final ItemMetaKey EXPLOSION = new ItemMetaKey("Explosion", "firework-effect"); + + private FireworkEffect effect; + + CraftMetaCharge(CraftMetaItem meta) { + super(meta); + + if (meta instanceof CraftMetaCharge) { + effect = ((CraftMetaCharge) meta).effect; + } + } + + CraftMetaCharge(Map map) { + super(map); + + setEffect(SerializableMeta.getObject(FireworkEffect.class, map, EXPLOSION.BUKKIT, true)); + } + + CraftMetaCharge(NBTTagCompound tag) { + super(tag); + + if (tag.hasKey(EXPLOSION.NBT)) { + try { + effect = CraftMetaFirework.getEffect(tag.getCompound(EXPLOSION.NBT)); + } catch (IllegalArgumentException ex) { + // Ignore invalid effects + } + } + } + + @Override + public void setEffect(FireworkEffect effect) { + this.effect = effect; + } + + @Override + public boolean hasEffect() { + return effect != null; + } + + @Override + public FireworkEffect getEffect() { + return effect; + } + + @Override + void applyToItem(NBTTagCompound itemTag) { + super.applyToItem(itemTag); + + if (hasEffect()) { + itemTag.set(EXPLOSION.NBT, CraftMetaFirework.getExplosion(effect)); + } + } + + @Override + boolean applicableTo(Material type) { + return type == Material.FIREWORK_CHARGE; + } + + @Override + boolean isEmpty() { + return super.isEmpty() && !hasChargeMeta(); + } + + boolean hasChargeMeta() { + return hasEffect(); + } + + @Override + boolean equalsCommon(CraftMetaItem meta) { + if (!super.equalsCommon(meta)) { + return false; + } + if (meta instanceof CraftMetaCharge) { + CraftMetaCharge that = (CraftMetaCharge) meta; + + return (hasEffect() ? that.hasEffect() && this.effect.equals(that.effect) : !that.hasEffect()); + } + return true; + } + + @Override + boolean notUncommon(CraftMetaItem meta) { + return super.notUncommon(meta) && (meta instanceof CraftMetaCharge || !hasChargeMeta()); + } + + @Override + int applyHash() { + final int original; + int hash = original = super.applyHash(); + + if (hasEffect()) { + hash = 61 * hash + effect.hashCode(); + } + + return hash != original ? CraftMetaCharge.class.hashCode() ^ hash : hash; + } + + @Override + public CraftMetaCharge clone() { + return (CraftMetaCharge) super.clone(); + } + + @Override + Builder serialize(Builder builder) { + super.serialize(builder); + + if (hasEffect()) { + builder.put(EXPLOSION.BUKKIT, effect); + } + + return builder; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaEnchantedBook.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaEnchantedBook.java new file mode 100644 index 0000000..1acc997 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaEnchantedBook.java @@ -0,0 +1,160 @@ +package org.bukkit.craftbukkit.inventory; + +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableMap.Builder; +import net.minecraft.server.NBTTagCompound; +import org.bukkit.Material; +import org.bukkit.configuration.serialization.DelegateDeserialization; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.meta.EnchantmentStorageMeta; + +import java.util.HashMap; +import java.util.Map; + +@DelegateDeserialization(SerializableMeta.class) +class CraftMetaEnchantedBook extends CraftMetaItem implements EnchantmentStorageMeta { + static final ItemMetaKey STORED_ENCHANTMENTS = new ItemMetaKey("StoredEnchantments", "stored-enchants"); + + private Map enchantments; + + CraftMetaEnchantedBook(CraftMetaItem meta) { + super(meta); + + if (!(meta instanceof CraftMetaEnchantedBook)) { + return; + } + + CraftMetaEnchantedBook that = (CraftMetaEnchantedBook) meta; + + if (that.hasEnchants()) { + this.enchantments = new HashMap<>(that.enchantments); + } + } + + CraftMetaEnchantedBook(NBTTagCompound tag) { + super(tag); + + if (!tag.hasKey(STORED_ENCHANTMENTS.NBT)) { + return; + } + + enchantments = buildEnchantments(tag, STORED_ENCHANTMENTS); + } + + CraftMetaEnchantedBook(Map map) { + super(map); + + enchantments = buildEnchantments(map, STORED_ENCHANTMENTS); + } + + @Override + void applyToItem(NBTTagCompound itemTag) { + super.applyToItem(itemTag); + + applyEnchantments(enchantments, itemTag, STORED_ENCHANTMENTS); + } + + @Override + boolean applicableTo(Material type) { + return type == Material.ENCHANTED_BOOK; + } + + @Override + boolean isEmpty() { + return super.isEmpty() && isEnchantedEmpty(); + } + + @Override + boolean equalsCommon(CraftMetaItem meta) { + if (!super.equalsCommon(meta)) { + return false; + } + if (meta instanceof CraftMetaEnchantedBook) { + CraftMetaEnchantedBook that = (CraftMetaEnchantedBook) meta; + + return (hasStoredEnchants() ? that.hasStoredEnchants() && this.enchantments.equals(that.enchantments) : !that.hasStoredEnchants()); + } + return true; + } + + @Override + boolean notUncommon(CraftMetaItem meta) { + return super.notUncommon(meta) && (meta instanceof CraftMetaEnchantedBook || isEnchantedEmpty()); + } + + @Override + int applyHash() { + final int original; + int hash = original = super.applyHash(); + + if (hasStoredEnchants()) { + hash = 61 * hash + enchantments.hashCode(); + } + + return original != hash ? CraftMetaEnchantedBook.class.hashCode() ^ hash : hash; + } + + @Override + public CraftMetaEnchantedBook clone() { + CraftMetaEnchantedBook meta = (CraftMetaEnchantedBook) super.clone(); + + if (this.enchantments != null) { + meta.enchantments = new HashMap<>(this.enchantments); + } + + return meta; + } + + @Override + Builder serialize(Builder builder) { + super.serialize(builder); + + serializeEnchantments(enchantments, builder, STORED_ENCHANTMENTS); + + return builder; + } + + boolean isEnchantedEmpty() { + return !hasStoredEnchants(); + } + + public boolean hasStoredEnchant(Enchantment ench) { + return hasStoredEnchants() && enchantments.containsKey(ench); + } + + public int getStoredEnchantLevel(Enchantment ench) { + Integer level = hasStoredEnchants() ? enchantments.get(ench) : null; + if (level == null) { + return 0; + } + return level; + } + + public Map getStoredEnchants() { + return hasStoredEnchants() ? ImmutableMap.copyOf(enchantments) : ImmutableMap.of(); + } + + public boolean addStoredEnchant(Enchantment ench, int level, boolean ignoreRestrictions) { + if (enchantments == null) { + enchantments = new HashMap<>(4); + } + + if (ignoreRestrictions || level >= ench.getStartLevel() && level <= ench.getMaxLevel()) { + Integer old = enchantments.put(ench, level); + return old == null || old != level; + } + return false; + } + + public boolean removeStoredEnchant(Enchantment ench) { + return hasStoredEnchants() && enchantments.remove(ench) != null; + } + + public boolean hasStoredEnchants() { + return !(enchantments == null || enchantments.isEmpty()); + } + + public boolean hasConflictingStoredEnchant(Enchantment ench) { + return checkConflictingEnchants(enchantments, ench); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaFirework.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaFirework.java new file mode 100644 index 0000000..f4a6f06 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaFirework.java @@ -0,0 +1,382 @@ +package org.bukkit.craftbukkit.inventory; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap.Builder; +import net.minecraft.server.NBTTagCompound; +import net.minecraft.server.NBTTagList; +import org.apache.commons.lang.Validate; +import org.bukkit.Color; +import org.bukkit.FireworkEffect; +import org.bukkit.FireworkEffect.Type; +import org.bukkit.Material; +import org.bukkit.configuration.serialization.DelegateDeserialization; +import org.bukkit.craftbukkit.inventory.CraftMetaItem.ItemMetaKey.Specific; +import org.bukkit.craftbukkit.inventory.CraftMetaItem.ItemMetaKey.Specific.To; +import org.bukkit.inventory.meta.FireworkMeta; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; + +@DelegateDeserialization(SerializableMeta.class) +class CraftMetaFirework extends CraftMetaItem implements FireworkMeta { + /* + "Fireworks", "Explosion", "Explosions", "Flight", "Type", "Trail", "Flicker", "Colors", "FadeColors"; + + Fireworks + - Compound: Fireworks + -- Byte: Flight + -- List: Explosions + --- Compound: Explosion + ---- IntArray: Colors + ---- Byte: Type + ---- Boolean: Trail + ---- Boolean: Flicker + ---- IntArray: FadeColors + */ + + @Specific(To.NBT) + static final ItemMetaKey FIREWORKS = new ItemMetaKey("Fireworks"); + static final ItemMetaKey FLIGHT = new ItemMetaKey("Flight", "power"); + static final ItemMetaKey EXPLOSIONS = new ItemMetaKey("Explosions", "firework-effects"); + @Specific(To.NBT) + static final ItemMetaKey EXPLOSION_COLORS = new ItemMetaKey("Colors"); + @Specific(To.NBT) + static final ItemMetaKey EXPLOSION_TYPE = new ItemMetaKey("Type"); + @Specific(To.NBT) + static final ItemMetaKey EXPLOSION_TRAIL = new ItemMetaKey("Trail"); + @Specific(To.NBT) + static final ItemMetaKey EXPLOSION_FLICKER = new ItemMetaKey("Flicker"); + @Specific(To.NBT) + static final ItemMetaKey EXPLOSION_FADE = new ItemMetaKey("FadeColors"); + + private List effects; + private int power; + + CraftMetaFirework(CraftMetaItem meta) { + super(meta); + + if (!(meta instanceof CraftMetaFirework)) { + return; + } + + CraftMetaFirework that = (CraftMetaFirework) meta; + + this.power = that.power; + + if (that.hasEffects()) { + this.effects = new ArrayList<>(that.effects); + } + } + + CraftMetaFirework(NBTTagCompound tag) { + super(tag); + + if (!tag.hasKey(FIREWORKS.NBT)) { + return; + } + + NBTTagCompound fireworks = tag.getCompound(FIREWORKS.NBT); + + power = 0xff & fireworks.getByte(FLIGHT.NBT); + + if (!fireworks.hasKey(EXPLOSIONS.NBT)) { + return; + } + + NBTTagList fireworkEffects = fireworks.getList(EXPLOSIONS.NBT, 10); + List effects = this.effects = new ArrayList<>(fireworkEffects.size()); + + for (int i = 0; i < fireworkEffects.size(); i++) { + try { + effects.add(getEffect(fireworkEffects.get(i))); + } catch (IllegalArgumentException ex) { + // Ignore invalid effects + } + } + } + + static FireworkEffect getEffect(NBTTagCompound explosion) { + FireworkEffect.Builder effect = FireworkEffect.builder() + .flicker(explosion.getBoolean(EXPLOSION_FLICKER.NBT)) + .trail(explosion.getBoolean(EXPLOSION_TRAIL.NBT)) + .with(getEffectType(0xff & explosion.getByte(EXPLOSION_TYPE.NBT))); + + for (int color : explosion.getIntArray(EXPLOSION_COLORS.NBT)) { + effect.withColor(Color.fromRGB(color)); + } + + for (int color : explosion.getIntArray(EXPLOSION_FADE.NBT)) { + effect.withFade(Color.fromRGB(color)); + } + + return effect.build(); + } + + static NBTTagCompound getExplosion(FireworkEffect effect) { + NBTTagCompound explosion = new NBTTagCompound(); + + if (effect.hasFlicker()) { + explosion.setBoolean(EXPLOSION_FLICKER.NBT, true); + } + + if (effect.hasTrail()) { + explosion.setBoolean(EXPLOSION_TRAIL.NBT, true); + } + + addColors(explosion, EXPLOSION_COLORS, effect.getColors()); + addColors(explosion, EXPLOSION_FADE, effect.getFadeColors()); + + explosion.setByte(EXPLOSION_TYPE.NBT, (byte) getNBT(effect.getType())); + + return explosion; + } + + static int getNBT(Type type) { + switch (type) { + case BALL: + return 0; + case BALL_LARGE: + return 1; + case STAR: + return 2; + case CREEPER: + return 3; + case BURST: + return 4; + default: + throw new IllegalStateException(type.toString()); // Spigot + } + } + + static Type getEffectType(int nbt) { + switch (nbt) { + case 0: + return Type.BALL; + case 1: + return Type.BALL_LARGE; + case 2: + return Type.STAR; + case 3: + return Type.CREEPER; + case 4: + return Type.BURST; + default: + throw new IllegalStateException(Integer.toString(nbt)); // Spigot + } + } + + CraftMetaFirework(Map map) { + super(map); + + Integer power = SerializableMeta.getObject(Integer.class, map, FLIGHT.BUKKIT, true); + if (power != null) { + setPower(power); + } + + Iterable effects = SerializableMeta.getObject(Iterable.class, map, EXPLOSIONS.BUKKIT, true); + safelyAddEffects(effects); + } + + public boolean hasEffects() { + return !(effects == null || effects.isEmpty()); + } + + void safelyAddEffects(Iterable collection) { + if (collection == null || (collection instanceof Collection && ((Collection) collection).isEmpty())) { + return; + } + + List effects = this.effects; + if (effects == null) { + effects = this.effects = new ArrayList<>(); + } + + for (Object obj : collection) { + if (obj instanceof FireworkEffect) { + effects.add((FireworkEffect) obj); + } else { + throw new IllegalArgumentException(obj + " in " + collection + " is not a FireworkEffect"); + } + } + } + + @Override + void applyToItem(NBTTagCompound itemTag) { + super.applyToItem(itemTag); + if (isFireworkEmpty()) { + return; + } + + NBTTagCompound fireworks = itemTag.getCompound(FIREWORKS.NBT); + itemTag.set(FIREWORKS.NBT, fireworks); + + if (hasEffects()) { + NBTTagList effects = new NBTTagList(); + for (FireworkEffect effect : this.effects) { + effects.add(getExplosion(effect)); + } + + if (effects.size() > 0) { + fireworks.set(EXPLOSIONS.NBT, effects); + } + } + + if (hasPower()) { + fireworks.setByte(FLIGHT.NBT, (byte) power); + } + } + + static void addColors(NBTTagCompound compound, ItemMetaKey key, List colors) { + if (colors.isEmpty()) { + return; + } + + final int[] colorArray = new int[colors.size()]; + int i = 0; + for (Color color : colors) { + colorArray[i++] = color.asRGB(); + } + + compound.setIntArray(key.NBT, colorArray); + } + + @Override + boolean applicableTo(Material type) { + return type == Material.FIREWORK; + } + + @Override + boolean isEmpty() { + return super.isEmpty() && isFireworkEmpty(); + } + + boolean isFireworkEmpty() { + return !(hasEffects() || hasPower()); + } + + boolean hasPower() { + return power != 0; + } + + @Override + boolean equalsCommon(CraftMetaItem meta) { + if (!super.equalsCommon(meta)) { + return false; + } + + if (meta instanceof CraftMetaFirework) { + CraftMetaFirework that = (CraftMetaFirework) meta; + + return (hasPower() ? that.hasPower() && this.power == that.power : !that.hasPower()) + && (hasEffects() ? that.hasEffects() && this.effects.equals(that.effects) : !that.hasEffects()); + } + + return true; + } + + @Override + boolean notUncommon(CraftMetaItem meta) { + return super.notUncommon(meta) && (meta instanceof CraftMetaFirework || isFireworkEmpty()); + } + + @Override + int applyHash() { + final int original; + int hash = original = super.applyHash(); + if (hasPower()) { + hash = 61 * hash + power; + } + if (hasEffects()) { + hash = 61 * hash + 13 * effects.hashCode(); + } + return hash != original ? CraftMetaFirework.class.hashCode() ^ hash : hash; + } + + @Override + Builder serialize(Builder builder) { + super.serialize(builder); + + if (hasEffects()) { + builder.put(EXPLOSIONS.BUKKIT, ImmutableList.copyOf(effects)); + } + + if (hasPower()) { + builder.put(FLIGHT.BUKKIT, power); + } + + return builder; + } + + @Override + public CraftMetaFirework clone() { + CraftMetaFirework meta = (CraftMetaFirework) super.clone(); + + if (this.effects != null) { + meta.effects = new ArrayList<>(this.effects); + } + + return meta; + } + + public void addEffect(FireworkEffect effect) { + Validate.notNull(effect, "Effect cannot be null"); + if (this.effects == null) { + this.effects = new ArrayList<>(); + } + this.effects.add(effect); + } + + public void addEffects(FireworkEffect... effects) { + Validate.notNull(effects, "Effects cannot be null"); + if (effects.length == 0) { + return; + } + + List list = this.effects; + if (list == null) { + list = this.effects = new ArrayList<>(); + } + + for (FireworkEffect effect : effects) { + Validate.notNull(effect, "Effect cannot be null"); + list.add(effect); + } + } + + public void addEffects(Iterable effects) { + Validate.notNull(effects, "Effects cannot be null"); + safelyAddEffects(effects); + } + + public List getEffects() { + return this.effects == null ? ImmutableList.of() : ImmutableList.copyOf(this.effects); + } + + public int getEffectsSize() { + return this.effects == null ? 0 : this.effects.size(); + } + + public void removeEffect(int index) { + if (this.effects == null) { + throw new IndexOutOfBoundsException("Index: " + index + ", Size: 0"); + } else { + this.effects.remove(index); + } + } + + public void clearEffects() { + this.effects = null; + } + + public int getPower() { + return this.power; + } + + public void setPower(int power) { + Validate.isTrue(power >= 0, "Power cannot be less than zero: ", power); + Validate.isTrue(power < 0x80, "Power cannot be more than 127: ", power); + this.power = power; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaItem.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaItem.java new file mode 100644 index 0000000..c17a0fb --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaItem.java @@ -0,0 +1,906 @@ +package org.bukkit.craftbukkit.inventory; + +import com.google.common.base.Strings; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Sets; +import it.unimi.dsi.fastutil.objects.Object2DoubleMap; +import it.unimi.dsi.fastutil.objects.Object2DoubleOpenHashMap; +import net.minecraft.server.*; +import org.bukkit.Material; +import org.bukkit.configuration.serialization.DelegateDeserialization; +import org.bukkit.craftbukkit.Overridden; +import org.bukkit.craftbukkit.inventory.CraftMetaItem.ItemMetaKey.Specific; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.ItemFlag; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.inventory.meta.Repairable; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import java.util.*; +import java.util.logging.Level; +import java.util.logging.Logger; + +import static org.spigotmc.ValidateUtils.limit; +// Spigot end + +/** + * Children must include the following: + * + *
  • Constructor(CraftMetaItem meta) + *
  • Constructor(NBTTagCompound tag) + *
  • Constructor(Map map) + *

    + *
  • void applyToItem(NBTTagCompound tag) + *
  • boolean applicableTo(Material type) + *

    + *
  • boolean equalsCommon(CraftMetaItem meta) + *
  • boolean notUncommon(CraftMetaItem meta) + *

    + *
  • boolean isEmpty() + *
  • boolean is{Type}Empty() + *

    + *
  • int applyHash() + *
  • public Class clone() + *

    + *
  • Builder serialize(Builder builder) + *
  • SerializableMeta.Deserializers deserializer() + */ +@DelegateDeserialization(SerializableMeta.class) +class CraftMetaItem implements ItemMeta, Repairable { + + static class ItemMetaKey { + + @Retention(RetentionPolicy.SOURCE) + @Target(ElementType.FIELD) + @interface Specific { + enum To { + BUKKIT, + NBT, + } + To value(); + } + + final String BUKKIT; + final String NBT; + + ItemMetaKey(final String both) { + this(both, both); + } + + ItemMetaKey(final String nbt, final String bukkit) { + this.NBT = nbt; + this.BUKKIT = bukkit; + } + } + + static final ItemMetaKey NAME = new ItemMetaKey("Name", "display-name"); + @Specific(Specific.To.NBT) + static final ItemMetaKey DISPLAY = new ItemMetaKey("display"); + static final ItemMetaKey LORE = new ItemMetaKey("Lore", "lore"); + static final ItemMetaKey ENCHANTMENTS = new ItemMetaKey("ench", "enchants"); + @Specific(Specific.To.NBT) + static final ItemMetaKey ENCHANTMENTS_ID = new ItemMetaKey("id"); + @Specific(Specific.To.NBT) + static final ItemMetaKey ENCHANTMENTS_LVL = new ItemMetaKey("lvl"); + static final ItemMetaKey REPAIR = new ItemMetaKey("RepairCost", "repair-cost"); + @Specific(Specific.To.NBT) + static final ItemMetaKey ATTRIBUTES = new ItemMetaKey("AttributeModifiers"); + @Specific(Specific.To.NBT) + static final ItemMetaKey ATTRIBUTES_IDENTIFIER = new ItemMetaKey("AttributeName"); + @Specific(Specific.To.NBT) + static final ItemMetaKey ATTRIBUTES_NAME = new ItemMetaKey("Name"); + @Specific(Specific.To.NBT) + static final ItemMetaKey ATTRIBUTES_VALUE = new ItemMetaKey("Amount"); + @Specific(Specific.To.NBT) + static final ItemMetaKey ATTRIBUTES_TYPE = new ItemMetaKey("Operation"); + @Specific(Specific.To.NBT) + static final ItemMetaKey ATTRIBUTES_UUID_HIGH = new ItemMetaKey("UUIDMost"); + @Specific(Specific.To.NBT) + static final ItemMetaKey ATTRIBUTES_UUID_LOW = new ItemMetaKey("UUIDLeast"); + @Specific(Specific.To.NBT) + static final ItemMetaKey HIDEFLAGS = new ItemMetaKey("HideFlags", "ItemFlags"); + @Specific(Specific.To.NBT) + static final ItemMetaKey UNBREAKABLE = new ItemMetaKey("Unbreakable"); // Spigot + + private String displayName; + private List lore; + private Map enchantments; + private int repairCost; + private int hideFlag; + + private static final Set HANDLED_TAGS = Sets.newHashSet(); + + private final Map unhandledTags = new HashMap<>(); + + CraftMetaItem(CraftMetaItem meta) { + if (meta == null) { + return; + } + + this.displayName = meta.displayName; + + if (meta.hasLore()) { + this.lore = new ArrayList<>(meta.lore); + } + + if (meta.enchantments != null) { // Spigot + this.enchantments = new HashMap<>(meta.enchantments); + } + + this.repairCost = meta.repairCost; + this.hideFlag = meta.hideFlag; + this.unhandledTags.putAll(meta.unhandledTags); + spigot.setUnbreakable( meta.spigot.isUnbreakable() ); // Spigot + } + + CraftMetaItem(NBTTagCompound tag) { + if (tag.hasKey(DISPLAY.NBT)) { + NBTTagCompound display = tag.getCompound(DISPLAY.NBT); + + if (display.hasKey(NAME.NBT)) { + displayName = limit( display.getString(NAME.NBT), 1024 ); // Spigot + } + + if (display.hasKey(LORE.NBT)) { + NBTTagList list = display.getList(LORE.NBT, 8); + lore = new ArrayList<>(list.size()); + + for (int index = 0; index < list.size(); index++) { + String line = limit( list.getString(index), 1024 ); // Spigot + lore.add(line); + } + } + } + + this.enchantments = buildEnchantments(tag, ENCHANTMENTS); + + if (tag.hasKey(REPAIR.NBT)) { + repairCost = tag.getInt(REPAIR.NBT); + } + + if (tag.hasKey(HIDEFLAGS.NBT)) { + hideFlag = tag.getInt(HIDEFLAGS.NBT); + } + + if (tag.get(ATTRIBUTES.NBT) instanceof NBTTagList) { + NBTTagList save = null; + NBTTagList nbttaglist = tag.getList(ATTRIBUTES.NBT, 10); + + // Spigot start + Object2DoubleMap attributeTracker = new Object2DoubleOpenHashMap<>(); + Object2DoubleMap attributeTrackerX = new Object2DoubleOpenHashMap<>(); + Map attributesByName = new HashMap<>(); + attributeTracker.put( "generic.maxHealth", 20.0 ); + attributesByName.put( "generic.maxHealth", GenericAttributes.maxHealth ); + attributeTracker.put( "generic.followRange", 32.0 ); + attributesByName.put( "generic.followRange", GenericAttributes.FOLLOW_RANGE ); + attributeTracker.put( "generic.knockbackResistance", 0.0 ); + attributesByName.put( "generic.knockbackResistance", GenericAttributes.c ); + attributeTracker.put( "generic.movementSpeed", 0.7 ); + attributesByName.put( "generic.movementSpeed", GenericAttributes.MOVEMENT_SPEED ); + attributeTracker.put( "generic.attackDamage", 1.0 ); + attributesByName.put( "generic.attackDamage", GenericAttributes.ATTACK_DAMAGE ); + NBTTagList oldList = nbttaglist; + nbttaglist = new NBTTagList(); + + List op0 = new ArrayList<>(); + List op1 = new ArrayList<>(); + List op2 = new ArrayList<>(); + + for ( int i = 0; i < oldList.size(); ++i ) + { + NBTTagCompound nbttagcompound = oldList.get( i ); + if ( nbttagcompound == null ) continue; + + if ( !nbttagcompound.hasKeyOfType(ATTRIBUTES_UUID_HIGH.NBT, 99) ) + { + continue; + } + if ( !nbttagcompound.hasKeyOfType(ATTRIBUTES_UUID_LOW.NBT, 99) ) + { + continue; + } + if ( !( nbttagcompound.get( ATTRIBUTES_IDENTIFIER.NBT ) instanceof NBTTagString ) || !CraftItemFactory.KNOWN_NBT_ATTRIBUTE_NAMES.contains( nbttagcompound.getString( ATTRIBUTES_IDENTIFIER.NBT ) ) ) + { + continue; + } + if ( !( nbttagcompound.get( ATTRIBUTES_NAME.NBT ) instanceof NBTTagString ) || nbttagcompound.getString( ATTRIBUTES_NAME.NBT ).isEmpty() ) + { + continue; + } + if ( !nbttagcompound.hasKeyOfType(ATTRIBUTES_VALUE.NBT, 99) ) + { + continue; + } + if ( !nbttagcompound.hasKeyOfType(ATTRIBUTES_TYPE.NBT, 99) || nbttagcompound.getInt( ATTRIBUTES_TYPE.NBT ) < 0 || nbttagcompound.getInt( ATTRIBUTES_TYPE.NBT ) > 2 ) + { + continue; + } + + switch ( nbttagcompound.getInt( ATTRIBUTES_TYPE.NBT ) ) + { + case 0: + op0.add( nbttagcompound ); + break; + case 1: + op1.add( nbttagcompound ); + break; + case 2: + op2.add( nbttagcompound ); + break; + } + } + for ( NBTTagCompound nbtTagCompound : op0 ) + { + String name = nbtTagCompound.getString( ATTRIBUTES_IDENTIFIER.NBT ); + if ( attributeTracker.containsKey( name ) ) + { + double val = attributeTracker.getDouble( name ); + val += nbtTagCompound.getDouble( ATTRIBUTES_VALUE.NBT ); + if ( val != attributesByName.get( name ).a( val ) ) + { + continue; + } + attributeTracker.put( name, val ); + } + nbttaglist.add( nbtTagCompound ); + } + for ( String name : attributeTracker.keySet() ) + { + attributeTrackerX.put( name, attributeTracker.getDouble( name ) ); + } + for ( NBTTagCompound nbtTagCompound : op1 ) + { + String name = nbtTagCompound.getString( ATTRIBUTES_IDENTIFIER.NBT ); + if ( attributeTracker.containsKey( name ) ) + { + double val = attributeTracker.getDouble( name ); + double valX = attributeTrackerX.getDouble( name ); + val += valX * nbtTagCompound.getDouble( ATTRIBUTES_VALUE.NBT ); + if ( val != attributesByName.get( name ).a( val ) ) + { + continue; + } + attributeTracker.put( name, val ); + } + nbttaglist.add( nbtTagCompound ); + } + for ( NBTTagCompound nbtTagCompound : op2 ) + { + String name = nbtTagCompound.getString( ATTRIBUTES_IDENTIFIER.NBT ); + if ( attributeTracker.containsKey( name ) ) + { + double val = attributeTracker.getDouble( name ); + val += val * nbtTagCompound.getDouble( ATTRIBUTES_VALUE.NBT ); + if ( val != attributesByName.get( name ).a( val ) ) + { + continue; + } + attributeTracker.put( name, val ); + } + nbttaglist.add( nbtTagCompound ); + } + + // Spigot end + + for (int i = 0; i < nbttaglist.size(); ++i) { + if (nbttaglist.get(i) == null) { + continue; + } + NBTTagCompound nbttagcompound = nbttaglist.get(i); + + if (!nbttagcompound.hasKeyOfType(ATTRIBUTES_UUID_HIGH.NBT, 99)) { + continue; + } + if (!nbttagcompound.hasKeyOfType(ATTRIBUTES_UUID_LOW.NBT, 99)) { + continue; + } + if (!(nbttagcompound.get(ATTRIBUTES_IDENTIFIER.NBT) instanceof NBTTagString) || !CraftItemFactory.KNOWN_NBT_ATTRIBUTE_NAMES.contains(nbttagcompound.getString(ATTRIBUTES_IDENTIFIER.NBT))) { + continue; + } + if (!(nbttagcompound.get(ATTRIBUTES_NAME.NBT) instanceof NBTTagString) || nbttagcompound.getString(ATTRIBUTES_NAME.NBT).isEmpty()) { + continue; + } + if (!nbttagcompound.hasKeyOfType(ATTRIBUTES_VALUE.NBT, 99)) { + continue; + } + if (!nbttagcompound.hasKeyOfType(ATTRIBUTES_TYPE.NBT, 99) || nbttagcompound.getInt(ATTRIBUTES_TYPE.NBT) < 0 || nbttagcompound.getInt(ATTRIBUTES_TYPE.NBT) > 2) { + continue; + } + + if (save == null) { + save = new NBTTagList(); + } + + NBTTagCompound entry = new NBTTagCompound(); + entry.set(ATTRIBUTES_UUID_HIGH.NBT, nbttagcompound.get(ATTRIBUTES_UUID_HIGH.NBT)); + entry.set(ATTRIBUTES_UUID_LOW.NBT, nbttagcompound.get(ATTRIBUTES_UUID_LOW.NBT)); + entry.set(ATTRIBUTES_IDENTIFIER.NBT, nbttagcompound.get(ATTRIBUTES_IDENTIFIER.NBT)); + entry.set(ATTRIBUTES_NAME.NBT, nbttagcompound.get(ATTRIBUTES_NAME.NBT)); + entry.set(ATTRIBUTES_VALUE.NBT, nbttagcompound.get(ATTRIBUTES_VALUE.NBT)); + entry.set(ATTRIBUTES_TYPE.NBT, nbttagcompound.get(ATTRIBUTES_TYPE.NBT)); + save.add(entry); + } + + unhandledTags.put(ATTRIBUTES.NBT, save); + } + + Set keys = tag.c(); + for (String key : keys) { + if (!getHandledTags().contains(key)) { + unhandledTags.put(key, tag.get(key)); + } + } + // Spigot start + if ( tag.hasKey( UNBREAKABLE.NBT ) ) + { + spigot.setUnbreakable( tag.getBoolean( UNBREAKABLE.NBT ) ); + } + // Spigot end + } + + static Map buildEnchantments(NBTTagCompound tag, ItemMetaKey key) { + if (!tag.hasKey(key.NBT)) { + return null; + } + + NBTTagList ench = tag.getList(key.NBT, 10); + Map enchantments = new HashMap<>(ench.size()); + + for (int i = 0; i < ench.size(); i++) { + int id = 0xffff & ench.get(i).getShort(ENCHANTMENTS_ID.NBT); + int level = 0xffff & ench.get(i).getShort(ENCHANTMENTS_LVL.NBT); + + // Spigot start - skip invalid enchantments + Enchantment e = Enchantment.getById(id); + if (e == null) continue; + // Spigot end + enchantments.put(e, level); + } + + return enchantments; + } + + CraftMetaItem(Map map) { + setDisplayName(SerializableMeta.getString(map, NAME.BUKKIT, true)); + + Iterable lore = SerializableMeta.getObject(Iterable.class, map, LORE.BUKKIT, true); + if (lore != null) { + safelyAdd(lore, this.lore = new ArrayList<>(), Integer.MAX_VALUE); + } + + enchantments = buildEnchantments(map, ENCHANTMENTS); + + Integer repairCost = SerializableMeta.getObject(Integer.class, map, REPAIR.BUKKIT, true); + if (repairCost != null) { + setRepairCost(repairCost); + } + + Set hideFlags = SerializableMeta.getObject(Set.class, map, HIDEFLAGS.BUKKIT, true); + if (hideFlags != null) { + for (Object hideFlagObject : hideFlags) { + String hideFlagString = (String) hideFlagObject; + try { + ItemFlag hideFlatEnum = ItemFlag.valueOf(hideFlagString); + addItemFlags(hideFlatEnum); + } catch (IllegalArgumentException ex) { + // Ignore when we got a old String which does not map to a Enum value anymore + } + } + } + + // Spigot start + Boolean unbreakable = SerializableMeta.getObject( Boolean.class, map, UNBREAKABLE.BUKKIT, true ); + if ( unbreakable != null ) + { + spigot.setUnbreakable( unbreakable ); + } + // Spigot end + + String internal = SerializableMeta.getString(map, "internal", true); + if (internal != null) { + ByteArrayInputStream buf = new ByteArrayInputStream(Base64.getDecoder().decode(internal)); + try { + NBTTagCompound tag = NBTCompressedStreamTools.a(buf); + deserializeInternal(tag); + Set keys = tag.c(); + for (String key : keys) { + if (!getHandledTags().contains(key)) { + unhandledTags.put(key, tag.get(key)); + } + } + } catch (IOException ex) { + Logger.getLogger(CraftMetaItem.class.getName()).log(Level.SEVERE, null, ex); + } + } + } + + void deserializeInternal(NBTTagCompound tag) { + } + + static Map buildEnchantments(Map map, ItemMetaKey key) { + Map ench = SerializableMeta.getObject(Map.class, map, key.BUKKIT, true); + if (ench == null) { + return null; + } + + Map enchantments = new HashMap<>(ench.size()); + for (Map.Entry entry : ench.entrySet()) { + Enchantment enchantment = Enchantment.getByName(entry.getKey().toString()); + + if ((enchantment != null) && (entry.getValue() instanceof Integer)) { + enchantments.put(enchantment, (Integer) entry.getValue()); + } + } + + return enchantments; + } + + @Overridden + void applyToItem(NBTTagCompound itemTag) { + if (hasDisplayName()) { + setDisplayTag(itemTag, NAME.NBT, new NBTTagString(displayName)); + } + + if (hasLore()) { + setDisplayTag(itemTag, LORE.NBT, createStringList(lore)); + } + + if (hideFlag != 0) { + itemTag.setInt(HIDEFLAGS.NBT, hideFlag); + } + + applyEnchantments(enchantments, itemTag, ENCHANTMENTS); + + // Spigot start + if ( spigot.isUnbreakable() ) + { + itemTag.setBoolean( UNBREAKABLE.NBT, true ); + } + // Spigot end + + + if (hasRepairCost()) { + itemTag.setInt(REPAIR.NBT, repairCost); + } + + for (Map.Entry e : unhandledTags.entrySet()) { + itemTag.set(e.getKey(), e.getValue()); + } + } + + static NBTTagList createStringList(List list) { + if (list == null || list.isEmpty()) { + return null; + } + + NBTTagList tagList = new NBTTagList(); + for (String value : list) { + tagList.add(new NBTTagString(value)); + } + + return tagList; + } + + static void applyEnchantments(Map enchantments, NBTTagCompound tag, ItemMetaKey key) { + if (enchantments == null /*|| enchantments.size() == 0*/) { // Spigot - remove size check + return; + } + + NBTTagList list = new NBTTagList(); + + for (Map.Entry entry : enchantments.entrySet()) { + NBTTagCompound subtag = new NBTTagCompound(); + + subtag.setShort(ENCHANTMENTS_ID.NBT, (short) entry.getKey().getId()); + subtag.setShort(ENCHANTMENTS_LVL.NBT, entry.getValue().shortValue()); + + list.add(subtag); + } + + tag.set(key.NBT, list); + } + + void setDisplayTag(NBTTagCompound tag, String key, NBTBase value) { + final NBTTagCompound display = tag.getCompound(DISPLAY.NBT); + + if (!tag.hasKey(DISPLAY.NBT)) { + tag.set(DISPLAY.NBT, display); + } + + display.set(key, value); + } + + @Overridden + boolean applicableTo(Material type) { + return type != Material.AIR; + } + + @Overridden + boolean isEmpty() { + return !(hasDisplayName() || hasEnchants() || hasLore() || hasRepairCost() || !unhandledTags.isEmpty() || hideFlag != 0 || spigot.isUnbreakable()); // Spigot + } + + public String getDisplayName() { + return displayName; + } + + public final void setDisplayName(String name) { + this.displayName = name; + } + + public boolean hasDisplayName() { + return !Strings.isNullOrEmpty(displayName); + } + + public boolean hasLore() { + return this.lore != null && !this.lore.isEmpty(); + } + + public boolean hasRepairCost() { + return repairCost > 0; + } + + public boolean hasEnchant(Enchantment ench) { + return hasEnchants() && enchantments.containsKey(ench); + } + + public int getEnchantLevel(Enchantment ench) { + Integer level = hasEnchants() ? enchantments.get(ench) : null; + if (level == null) { + return 0; + } + return level; + } + + public Map getEnchants() { + return hasEnchants() ? ImmutableMap.copyOf(enchantments) : ImmutableMap.of(); + } + + public boolean addEnchant(Enchantment ench, int level, boolean ignoreRestrictions) { + if (enchantments == null) { + enchantments = new HashMap<>(4); + } + + if (ignoreRestrictions || level >= ench.getStartLevel() && level <= ench.getMaxLevel()) { + Integer old = enchantments.put(ench, level); + return old == null || old != level; + } + return false; + } + + public boolean removeEnchant(Enchantment ench) { + // Spigot start + boolean b = hasEnchants() && enchantments.remove( ench ) != null; + if ( enchantments != null && enchantments.isEmpty() ) + { + this.enchantments = null; + } + return b; + // Spigot end + } + + public boolean hasEnchants() { + return !(enchantments == null || enchantments.isEmpty()); + } + + public boolean hasConflictingEnchant(Enchantment ench) { + return checkConflictingEnchants(enchantments, ench); + } + + @Override + public void addItemFlags(ItemFlag... hideFlags) { + for (ItemFlag f : hideFlags) { + this.hideFlag |= getBitModifier(f); + } + } + + @Override + public void removeItemFlags(ItemFlag... hideFlags) { + for (ItemFlag f : hideFlags) { + this.hideFlag &= ~getBitModifier(f); + } + } + + @Override + public Set getItemFlags() { + Set currentFlags = EnumSet.noneOf(ItemFlag.class); + + for (ItemFlag f : ItemFlag.values()) { + if (hasItemFlag(f)) { + currentFlags.add(f); + } + } + + return currentFlags; + } + + @Override + public boolean hasItemFlag(ItemFlag flag) { + int bitModifier = getBitModifier(flag); + return (this.hideFlag & bitModifier) == bitModifier; + } + + private byte getBitModifier(ItemFlag hideFlag) { + return (byte) (1 << hideFlag.ordinal()); + } + + public List getLore() { + return this.lore == null ? null : new ArrayList<>(this.lore); + } + + public void setLore(List lore) { // too tired to think if .clone is better + if (lore == null) { + this.lore = null; + } else { + if (this.lore == null) { + safelyAdd(lore, this.lore = new ArrayList<>(lore.size()), Integer.MAX_VALUE); + } else { + this.lore.clear(); + safelyAdd(lore, this.lore, Integer.MAX_VALUE); + } + } + } + + public int getRepairCost() { + return repairCost; + } + + public void setRepairCost(int cost) { // TODO: Does this have limits? + repairCost = cost; + } + + @Override + public final boolean equals(Object object) { + if (object == null) { + return false; + } + if (object == this) { + return true; + } + if (!(object instanceof CraftMetaItem)) { + return false; + } + return CraftItemFactory.instance().equals(this, (ItemMeta) object); + } + + /** + * This method is almost as weird as notUncommon. + * Only return false if your common internals are unequal. + * Checking your own internals is redundant if you are not common, as notUncommon is meant for checking those 'not common' variables. + */ + @Overridden + boolean equalsCommon(CraftMetaItem that) { + return ((this.hasDisplayName() ? that.hasDisplayName() && this.displayName.equals(that.displayName) : !that.hasDisplayName())) + && (this.hasEnchants() ? that.hasEnchants() && this.enchantments.equals(that.enchantments) : !that.hasEnchants()) + && (this.hasLore() ? that.hasLore() && this.lore.equals(that.lore) : !that.hasLore()) + && (this.hasRepairCost() ? that.hasRepairCost() && this.repairCost == that.repairCost : !that.hasRepairCost()) + && (this.unhandledTags.equals(that.unhandledTags)) + && (this.hideFlag == that.hideFlag) + && (this.spigot.isUnbreakable() == that.spigot.isUnbreakable()); // Spigot + } + + /** + * This method is a bit weird... + * Return true if you are a common class OR your uncommon parts are empty. + * Empty uncommon parts implies the NBT data would be equivalent if both were applied to an item + */ + @Overridden + boolean notUncommon(CraftMetaItem meta) { + return true; + } + + @Override + public final int hashCode() { + return applyHash(); + } + + @Overridden + int applyHash() { + int hash = 3; + hash = 61 * hash + (hasDisplayName() ? this.displayName.hashCode() : 0); + hash = 61 * hash + (hasLore() ? this.lore.hashCode() : 0); + hash = 61 * hash + (hasEnchants() ? this.enchantments.hashCode() : 0); + hash = 61 * hash + (hasRepairCost() ? this.repairCost : 0); + hash = 61 * hash + unhandledTags.hashCode(); + hash = 61 * hash + hideFlag; + hash = 61 * hash + (spigot.isUnbreakable() ? 1231 : 1237); // Spigot + return hash; + } + + @Overridden + @Override + public CraftMetaItem clone() { + try { + CraftMetaItem clone = (CraftMetaItem) super.clone(); + if (this.lore != null) { + clone.lore = new ArrayList<>(this.lore); + } + if (this.enchantments != null) { + clone.enchantments = new HashMap<>(this.enchantments); + } + clone.hideFlag = this.hideFlag; + return clone; + } catch (CloneNotSupportedException e) { + throw new Error(e); + } + } + + public final Map serialize() { + ImmutableMap.Builder map = ImmutableMap.builder(); + map.put(SerializableMeta.TYPE_FIELD, SerializableMeta.classMap.get(getClass())); + serialize(map); + return map.build(); + } + + @Overridden + ImmutableMap.Builder serialize(ImmutableMap.Builder builder) { + if (hasDisplayName()) { + builder.put(NAME.BUKKIT, displayName); + } + + if (hasLore()) { + builder.put(LORE.BUKKIT, ImmutableList.copyOf(lore)); + } + + serializeEnchantments(enchantments, builder, ENCHANTMENTS); + + if (hasRepairCost()) { + builder.put(REPAIR.BUKKIT, repairCost); + } + + // Spigot start + if ( spigot.isUnbreakable() ) + { + builder.put( UNBREAKABLE.BUKKIT, true ); + } + // Spigot end + + + Set hideFlags = new HashSet<>(); + for (ItemFlag hideFlagEnum : getItemFlags()) { + hideFlags.add(hideFlagEnum.name()); + } + if (!hideFlags.isEmpty()) { + builder.put(HIDEFLAGS.BUKKIT, hideFlags); + } + + final Map internalTags = new HashMap<>(unhandledTags); + serializeInternal(internalTags); + if (!internalTags.isEmpty()) { + NBTTagCompound internal = new NBTTagCompound(); + for (Map.Entry e : internalTags.entrySet()) { + internal.set(e.getKey(), e.getValue()); + } + try { + ByteArrayOutputStream buf = new ByteArrayOutputStream(); + NBTCompressedStreamTools.a(internal, buf); + builder.put("internal", Base64.getEncoder().encode(buf.toByteArray())); + } catch (IOException ex) { + Logger.getLogger(CraftMetaItem.class.getName()).log(Level.SEVERE, null, ex); + } + } + + return builder; + } + + void serializeInternal(final Map unhandledTags) { + } + + static void serializeEnchantments(Map enchantments, ImmutableMap.Builder builder, ItemMetaKey key) { + if (enchantments == null || enchantments.isEmpty()) { + return; + } + + ImmutableMap.Builder enchants = ImmutableMap.builder(); + for (Map.Entry enchant : enchantments.entrySet()) { + enchants.put(enchant.getKey().getName(), enchant.getValue()); + } + + builder.put(key.BUKKIT, enchants.build()); + } + + static void safelyAdd(Iterable addFrom, Collection addTo, int maxItemLength) { + if (addFrom == null) { + return; + } + + for (Object object : addFrom) { + if (!(object instanceof String)) { + if (object != null) { + throw new IllegalArgumentException(addFrom + " cannot contain non-string " + object.getClass().getName()); + } + + addTo.add(""); + } else { + String page = object.toString(); + + if (page.length() > maxItemLength) { + page = page.substring(0, maxItemLength); + } + + addTo.add(page); + } + } + } + + static boolean checkConflictingEnchants(Map enchantments, Enchantment ench) { + if (enchantments == null || enchantments.isEmpty()) { + return false; + } + + for (Enchantment enchant : enchantments.keySet()) { + if (enchant.conflictsWith(ench)) { + return true; + } + } + + return false; + } + + @Override + public final String toString() { + return SerializableMeta.classMap.get(getClass()) + "_META:" + serialize(); // TODO: cry + } + + public static Set getHandledTags() { + synchronized (HANDLED_TAGS) { + if (HANDLED_TAGS.isEmpty()) { + HANDLED_TAGS.addAll(Arrays.asList( + UNBREAKABLE.NBT, // Spigot + DISPLAY.NBT, + REPAIR.NBT, + ENCHANTMENTS.NBT, + HIDEFLAGS.NBT, + CraftMetaMap.MAP_SCALING.NBT, + CraftMetaPotion.POTION_EFFECTS.NBT, + CraftMetaSkull.SKULL_OWNER.NBT, + CraftMetaSkull.SKULL_PROFILE.NBT, + CraftMetaBlockState.BLOCK_ENTITY_TAG.NBT, + CraftMetaBook.BOOK_TITLE.NBT, + CraftMetaBook.BOOK_AUTHOR.NBT, + CraftMetaBook.BOOK_PAGES.NBT, + CraftMetaBook.RESOLVED.NBT, + CraftMetaBook.GENERATION.NBT, + CraftMetaFirework.FIREWORKS.NBT, + CraftMetaEnchantedBook.STORED_ENCHANTMENTS.NBT, + CraftMetaCharge.EXPLOSION.NBT, + CraftMetaBlockState.BLOCK_ENTITY_TAG.NBT + )); + } + return HANDLED_TAGS; + } + } + + // Spigot start + private final Spigot spigot = new Spigot() + { + private boolean unbreakable; + + @Override + public void setUnbreakable(boolean setUnbreakable) + { + unbreakable = setUnbreakable; + } + + @Override + public boolean isUnbreakable() + { + return unbreakable; + } + }; + + @Override + public Spigot spigot() + { + return spigot; + } + // Spigot end +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaLeatherArmor.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaLeatherArmor.java new file mode 100644 index 0000000..94e7f19 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaLeatherArmor.java @@ -0,0 +1,132 @@ +package org.bukkit.craftbukkit.inventory; + +import com.google.common.collect.ImmutableMap.Builder; +import net.minecraft.server.NBTTagCompound; +import net.minecraft.server.NBTTagInt; +import org.bukkit.Color; +import org.bukkit.Material; +import org.bukkit.configuration.serialization.DelegateDeserialization; +import org.bukkit.inventory.meta.LeatherArmorMeta; + +import java.util.Map; + +import static org.bukkit.craftbukkit.inventory.CraftItemFactory.DEFAULT_LEATHER_COLOR; + +@DelegateDeserialization(SerializableMeta.class) +class CraftMetaLeatherArmor extends CraftMetaItem implements LeatherArmorMeta { + static final ItemMetaKey COLOR = new ItemMetaKey("color"); + + private Color color = DEFAULT_LEATHER_COLOR; + + CraftMetaLeatherArmor(CraftMetaItem meta) { + super(meta); + if (!(meta instanceof CraftMetaLeatherArmor)) { + return; + } + + CraftMetaLeatherArmor armorMeta = (CraftMetaLeatherArmor) meta; + this.color = armorMeta.color; + } + + CraftMetaLeatherArmor(NBTTagCompound tag) { + super(tag); + if (tag.hasKey(DISPLAY.NBT)) { + NBTTagCompound display = tag.getCompound(DISPLAY.NBT); + if (display.hasKey(COLOR.NBT)) { + color = Color.fromRGB(display.getInt(COLOR.NBT)); + } + } + } + + CraftMetaLeatherArmor(Map map) { + super(map); + setColor(SerializableMeta.getObject(Color.class, map, COLOR.BUKKIT, true)); + } + + @Override + void applyToItem(NBTTagCompound itemTag) { + super.applyToItem(itemTag); + + if (hasColor()) { + setDisplayTag(itemTag, COLOR.NBT, new NBTTagInt(color.asRGB())); + } + } + + @Override + boolean isEmpty() { + return super.isEmpty() && isLeatherArmorEmpty(); + } + + boolean isLeatherArmorEmpty() { + return !(hasColor()); + } + + @Override + boolean applicableTo(Material type) { + switch(type) { + case LEATHER_HELMET: + case LEATHER_CHESTPLATE: + case LEATHER_LEGGINGS: + case LEATHER_BOOTS: + return true; + default: + return false; + } + } + + @Override + public CraftMetaLeatherArmor clone() { + return (CraftMetaLeatherArmor) super.clone(); + } + + public Color getColor() { + return color; + } + + public void setColor(Color color) { + this.color = color == null ? DEFAULT_LEATHER_COLOR : color; + } + + boolean hasColor() { + return !DEFAULT_LEATHER_COLOR.equals(color); + } + + @Override + Builder serialize(Builder builder) { + super.serialize(builder); + + if (hasColor()) { + builder.put(COLOR.BUKKIT, color); + } + + return builder; + } + + @Override + boolean equalsCommon(CraftMetaItem meta) { + if (!super.equalsCommon(meta)) { + return false; + } + if (meta instanceof CraftMetaLeatherArmor) { + CraftMetaLeatherArmor that = (CraftMetaLeatherArmor) meta; + + return color.equals(that.color); + } + return true; + } + + @Override + boolean notUncommon(CraftMetaItem meta) { + return super.notUncommon(meta) && (meta instanceof CraftMetaLeatherArmor || isLeatherArmorEmpty()); + } + + @Override + int applyHash() { + final int original; + int hash = original = super.applyHash(); + if (hasColor()) { + hash ^= color.hashCode(); + } + return original != hash ? CraftMetaSkull.class.hashCode() ^ hash : hash; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaMap.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaMap.java new file mode 100644 index 0000000..8537425 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaMap.java @@ -0,0 +1,127 @@ +package org.bukkit.craftbukkit.inventory; + +import com.google.common.collect.ImmutableMap; +import net.minecraft.server.NBTTagCompound; +import org.bukkit.Material; +import org.bukkit.configuration.serialization.DelegateDeserialization; +import org.bukkit.inventory.meta.MapMeta; + +import java.util.Map; + +@DelegateDeserialization(SerializableMeta.class) +class CraftMetaMap extends CraftMetaItem implements MapMeta { + static final ItemMetaKey MAP_SCALING = new ItemMetaKey("map_is_scaling", "scaling"); + static final byte SCALING_EMPTY = (byte) 0; + static final byte SCALING_TRUE = (byte) 1; + static final byte SCALING_FALSE = (byte) 2; + + private byte scaling = SCALING_EMPTY; + + CraftMetaMap(CraftMetaItem meta) { + super(meta); + + if (!(meta instanceof CraftMetaMap)) { + return; + } + + CraftMetaMap map = (CraftMetaMap) meta; + this.scaling = map.scaling; + } + + CraftMetaMap(NBTTagCompound tag) { + super(tag); + + if (tag.hasKey(MAP_SCALING.NBT)) { + this.scaling = tag.getBoolean(MAP_SCALING.NBT) ? SCALING_TRUE : SCALING_FALSE; + } + } + + CraftMetaMap(Map map) { + super(map); + + Boolean scaling = SerializableMeta.getObject(Boolean.class, map, MAP_SCALING.BUKKIT, true); + if (scaling != null) { + setScaling(scaling); + } + } + + @Override + void applyToItem(NBTTagCompound tag) { + super.applyToItem(tag); + + if (hasScaling()) { + tag.setBoolean(MAP_SCALING.NBT, isScaling()); + } + } + + @Override + boolean applicableTo(Material type) { + return type == Material.MAP; + } + + @Override + boolean isEmpty() { + return super.isEmpty() && isMapEmpty(); + } + + boolean isMapEmpty() { + return !hasScaling(); + } + + boolean hasScaling() { + return scaling != SCALING_EMPTY; + } + + public boolean isScaling() { + return scaling == SCALING_TRUE; + } + + public void setScaling(boolean scaling) { + this.scaling = scaling ? SCALING_TRUE : SCALING_FALSE; + } + + @Override + boolean equalsCommon(CraftMetaItem meta) { + if (!super.equalsCommon(meta)) { + return false; + } + if (meta instanceof CraftMetaMap) { + CraftMetaMap that = (CraftMetaMap) meta; + + return (this.scaling == that.scaling); + } + return true; + } + + @Override + boolean notUncommon(CraftMetaItem meta) { + return super.notUncommon(meta) && (meta instanceof CraftMetaMap || isMapEmpty()); + } + + @Override + int applyHash() { + final int original; + int hash = original = super.applyHash(); + + if (hasScaling()) { + hash ^= 0x22222222 << (isScaling() ? 1 : -1); + } + + return original != hash ? CraftMetaMap.class.hashCode() ^ hash : hash; + } + + public CraftMetaMap clone() { + return (CraftMetaMap) super.clone(); + } + + @Override + ImmutableMap.Builder serialize(ImmutableMap.Builder builder) { + super.serialize(builder); + + if (hasScaling()) { + builder.put(MAP_SCALING.BUKKIT, isScaling()); + } + + return builder; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaPotion.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaPotion.java new file mode 100644 index 0000000..4fe71c8 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaPotion.java @@ -0,0 +1,251 @@ +package org.bukkit.craftbukkit.inventory; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap.Builder; +import net.minecraft.server.NBTTagCompound; +import net.minecraft.server.NBTTagList; +import org.apache.commons.lang.Validate; +import org.bukkit.Material; +import org.bukkit.configuration.serialization.DelegateDeserialization; +import org.bukkit.inventory.meta.PotionMeta; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +@DelegateDeserialization(SerializableMeta.class) +class CraftMetaPotion extends CraftMetaItem implements PotionMeta { + static final ItemMetaKey AMPLIFIER = new ItemMetaKey("Amplifier", "amplifier"); + static final ItemMetaKey AMBIENT = new ItemMetaKey("Ambient", "ambient"); + static final ItemMetaKey DURATION = new ItemMetaKey("Duration", "duration"); + static final ItemMetaKey SHOW_PARTICLES = new ItemMetaKey("ShowParticles", "has-particles"); + static final ItemMetaKey POTION_EFFECTS = new ItemMetaKey("CustomPotionEffects", "custom-effects"); + static final ItemMetaKey ID = new ItemMetaKey("Id", "potion-id"); + + private List customEffects; + + CraftMetaPotion(CraftMetaItem meta) { + super(meta); + if (!(meta instanceof CraftMetaPotion)) { + return; + } + CraftMetaPotion potionMeta = (CraftMetaPotion) meta; + if (potionMeta.hasCustomEffects()) { + this.customEffects = new ArrayList<>(potionMeta.customEffects); + } + } + + CraftMetaPotion(NBTTagCompound tag) { + super(tag); + + if (tag.hasKey(POTION_EFFECTS.NBT)) { + NBTTagList list = tag.getList(POTION_EFFECTS.NBT, 10); + int length = list.size(); + customEffects = new ArrayList<>(length); + + for (int i = 0; i < length; i++) { + NBTTagCompound effect = list.get(i); + PotionEffectType type = PotionEffectType.getById(effect.getByte(ID.NBT)); + int amp = effect.getByte(AMPLIFIER.NBT); + int duration = effect.getInt(DURATION.NBT); + boolean ambient = effect.getBoolean(AMBIENT.NBT); + boolean particles = effect.getBoolean(SHOW_PARTICLES.NBT); + customEffects.add(new PotionEffect(type, duration, amp, ambient, particles)); + } + } + } + + CraftMetaPotion(Map map) { + super(map); + + Iterable rawEffectList = SerializableMeta.getObject(Iterable.class, map, POTION_EFFECTS.BUKKIT, true); + if (rawEffectList == null) { + return; + } + + for (Object obj : rawEffectList) { + if (!(obj instanceof PotionEffect)) { + throw new IllegalArgumentException("Object in effect list is not valid. " + obj.getClass()); + } + addCustomEffect((PotionEffect) obj, true); + } + } + + @Override + void applyToItem(NBTTagCompound tag) { + super.applyToItem(tag); + if (customEffects != null) { + NBTTagList effectList = new NBTTagList(); + tag.set(POTION_EFFECTS.NBT, effectList); + + for (PotionEffect effect : customEffects) { + NBTTagCompound effectData = new NBTTagCompound(); + effectData.setByte(ID.NBT, (byte) effect.getType().getId()); + effectData.setByte(AMPLIFIER.NBT, (byte) effect.getAmplifier()); + effectData.setInt(DURATION.NBT, effect.getDuration()); + effectData.setBoolean(AMBIENT.NBT, effect.isAmbient()); + effectData.setBoolean(SHOW_PARTICLES.NBT, effect.hasParticles()); + effectList.add(effectData); + } + } + } + + @Override + boolean isEmpty() { + return super.isEmpty() && isPotionEmpty(); + } + + boolean isPotionEmpty() { + return !(hasCustomEffects()); + } + + @Override + boolean applicableTo(Material type) { + return type == Material.POTION; + } + + @Override + public CraftMetaPotion clone() { + CraftMetaPotion clone = (CraftMetaPotion) super.clone(); + if (this.customEffects != null) { + clone.customEffects = new ArrayList<>(this.customEffects); + } + return clone; + } + + public boolean hasCustomEffects() { + return customEffects != null; + } + + public List getCustomEffects() { + if (hasCustomEffects()) { + return ImmutableList.copyOf(customEffects); + } + return ImmutableList.of(); + } + + public boolean addCustomEffect(PotionEffect effect, boolean overwrite) { + Validate.notNull(effect, "Potion effect must not be null"); + + int index = indexOfEffect(effect.getType()); + if (index != -1) { + if (overwrite) { + PotionEffect old = customEffects.get(index); + if (old.getAmplifier() == effect.getAmplifier() && old.getDuration() == effect.getDuration() && old.isAmbient() == effect.isAmbient()) { + return false; + } + customEffects.set(index, effect); + return true; + } else { + return false; + } + } else { + if (customEffects == null) { + customEffects = new ArrayList<>(); + } + customEffects.add(effect); + return true; + } + } + + public boolean removeCustomEffect(PotionEffectType type) { + Validate.notNull(type, "Potion effect type must not be null"); + + if (!hasCustomEffects()) { + return false; + } + + boolean changed = false; + Iterator iterator = customEffects.iterator(); + while (iterator.hasNext()) { + PotionEffect effect = iterator.next(); + if (effect.getType() == type) { + iterator.remove(); + changed = true; + } + } + if (customEffects.isEmpty()) { + customEffects = null; + } + return changed; + } + + public boolean hasCustomEffect(PotionEffectType type) { + Validate.notNull(type, "Potion effect type must not be null"); + return indexOfEffect(type) != -1; + } + + public boolean setMainEffect(PotionEffectType type) { + Validate.notNull(type, "Potion effect type must not be null"); + int index = indexOfEffect(type); + if (index == -1 || index == 0) { + return false; + } + + PotionEffect old = customEffects.get(0); + customEffects.set(0, customEffects.get(index)); + customEffects.set(index, old); + return true; + } + + private int indexOfEffect(PotionEffectType type) { + if (!hasCustomEffects()) { + return -1; + } + + for (int i = 0; i < customEffects.size(); i++) { + if (customEffects.get(i).getType().equals(type)) { + return i; + } + } + return -1; + } + + public boolean clearCustomEffects() { + boolean changed = hasCustomEffects(); + customEffects = null; + return changed; + } + + @Override + int applyHash() { + final int original; + int hash = original = super.applyHash(); + if (hasCustomEffects()) { + hash = 73 * hash + customEffects.hashCode(); + } + return original != hash ? CraftMetaPotion.class.hashCode() ^ hash : hash; + } + + @Override + public boolean equalsCommon(CraftMetaItem meta) { + if (!super.equalsCommon(meta)) { + return false; + } + if (meta instanceof CraftMetaPotion) { + CraftMetaPotion that = (CraftMetaPotion) meta; + + return (this.hasCustomEffects() ? that.hasCustomEffects() && this.customEffects.equals(that.customEffects) : !that.hasCustomEffects()); + } + return true; + } + + @Override + boolean notUncommon(CraftMetaItem meta) { + return super.notUncommon(meta) && (meta instanceof CraftMetaPotion || isPotionEmpty()); + } + + @Override + Builder serialize(Builder builder) { + super.serialize(builder); + + if (hasCustomEffects()) { + builder.put(POTION_EFFECTS.BUKKIT, ImmutableList.copyOf(this.customEffects)); + } + + return builder; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaSkull.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaSkull.java new file mode 100644 index 0000000..ce54ca4 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaSkull.java @@ -0,0 +1,161 @@ +package org.bukkit.craftbukkit.inventory; + +import com.google.common.collect.ImmutableMap.Builder; +import com.mojang.authlib.GameProfile; +import net.minecraft.server.*; +import org.bukkit.Material; +import org.bukkit.configuration.serialization.DelegateDeserialization; +import org.bukkit.inventory.meta.SkullMeta; + +import java.util.Map; + +@DelegateDeserialization(SerializableMeta.class) +class CraftMetaSkull extends CraftMetaItem implements SkullMeta { + + @ItemMetaKey.Specific(ItemMetaKey.Specific.To.NBT) + static final ItemMetaKey SKULL_PROFILE = new ItemMetaKey("SkullProfile"); + + static final ItemMetaKey SKULL_OWNER = new ItemMetaKey("SkullOwner", "skull-owner"); + static final int MAX_OWNER_LENGTH = 16; + + private GameProfile profile; + + CraftMetaSkull(CraftMetaItem meta) { + super(meta); + if (!(meta instanceof CraftMetaSkull)) { + return; + } + CraftMetaSkull skullMeta = (CraftMetaSkull) meta; + this.profile = skullMeta.profile; + } + + CraftMetaSkull(NBTTagCompound tag) { + super(tag); + + if (tag.hasKeyOfType(SKULL_OWNER.NBT, 10)) { + profile = GameProfileSerializer.deserialize(tag.getCompound(SKULL_OWNER.NBT)); + } else if (tag.hasKeyOfType(SKULL_OWNER.NBT, 8) && !tag.getString(SKULL_OWNER.NBT).isEmpty()) { + profile = new GameProfile(null, tag.getString(SKULL_OWNER.NBT)); + } + } + + CraftMetaSkull(Map map) { + super(map); + if (profile == null) { + setOwner(SerializableMeta.getString(map, SKULL_OWNER.BUKKIT, true)); + } + } + + @Override + void deserializeInternal(NBTTagCompound tag) { + if (tag.hasKeyOfType(SKULL_PROFILE.NBT, 10)) { + profile = GameProfileSerializer.deserialize(tag.getCompound(SKULL_PROFILE.NBT)); + } + } + + @Override + void serializeInternal(final Map internalTags) { + if (profile != null) { + NBTTagCompound nbtData = new NBTTagCompound(); + GameProfileSerializer.serialize(nbtData, profile); + internalTags.put(SKULL_PROFILE.NBT, nbtData); + } + } + + @Override + void applyToItem(final NBTTagCompound tag) { // Spigot - make final + super.applyToItem(tag); + + if (profile != null) { + NBTTagCompound owner = new NBTTagCompound(); + GameProfileSerializer.serialize(owner, profile); + tag.set(SKULL_OWNER.NBT, owner); + // Spigot start - do an async lookup of the profile. + // Unfortunately there is not way to refresh the holding + // inventory, so that responsibility is left to the user. + net.minecraft.server.TileEntitySkull.b(profile, input -> { + NBTTagCompound owner1 = new NBTTagCompound(); + GameProfileSerializer.serialize(owner1, input); + tag.set(SKULL_OWNER.NBT, owner1); + return false; + }); + // Spigot end + } + } + + @Override + boolean isEmpty() { + return super.isEmpty() && isSkullEmpty(); + } + + boolean isSkullEmpty() { + return profile == null; + } + + @Override + boolean applicableTo(Material type) { + return type == Material.SKULL_ITEM; + } + + @Override + public CraftMetaSkull clone() { + return (CraftMetaSkull) super.clone(); + } + + public boolean hasOwner() { + return profile != null && profile.getName() != null; + } + + public String getOwner() { + return hasOwner() ? profile.getName() : null; + } + + public boolean setOwner(String name) { + if (name != null && name.length() > MAX_OWNER_LENGTH) + return false; + if (name == null) { + this.profile = null; + } else { + EntityPlayer player = MinecraftServer.getServer().getPlayerList().getPlayer(name); + this.profile = (player != null) ? player.getProfile() : new GameProfile(null, name); + } + return true; + } + + @Override + int applyHash() { + final int original; + int hash = original = super.applyHash(); + if (hasOwner()) { + hash = 61 * hash + profile.hashCode(); + } + return original != hash ? CraftMetaSkull.class.hashCode() ^ hash : hash; + } + + @Override + boolean equalsCommon(CraftMetaItem meta) { + if (!super.equalsCommon(meta)) { + return false; + } + if (meta instanceof CraftMetaSkull) { + CraftMetaSkull that = (CraftMetaSkull) meta; + + return (this.hasOwner() ? that.hasOwner() && this.profile.equals(that.profile) : !that.hasOwner()); + } + return true; + } + + @Override + boolean notUncommon(CraftMetaItem meta) { + return super.notUncommon(meta) && (meta instanceof CraftMetaSkull || isSkullEmpty()); + } + + @Override + Builder serialize(Builder builder) { + super.serialize(builder); + if (hasOwner()) { + return builder.put(SKULL_OWNER.BUKKIT, this.profile.getName()); + } + return builder; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftRecipe.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftRecipe.java new file mode 100644 index 0000000..d3e03e2 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftRecipe.java @@ -0,0 +1,7 @@ +package org.bukkit.craftbukkit.inventory; + +import org.bukkit.inventory.Recipe; + +public interface CraftRecipe extends Recipe { + void addToCraftingManager(); +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftShapedRecipe.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftShapedRecipe.java new file mode 100644 index 0000000..befd44d --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftShapedRecipe.java @@ -0,0 +1,64 @@ +package org.bukkit.craftbukkit.inventory; + +import net.minecraft.server.CraftingManager; +import net.minecraft.server.ShapedRecipes; +import org.bukkit.craftbukkit.util.CraftMagicNumbers; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.ShapedRecipe; + +import java.util.Map; + +public class CraftShapedRecipe extends ShapedRecipe implements CraftRecipe { + // TODO: Could eventually use this to add a matches() method or some such + private ShapedRecipes recipe; + + public CraftShapedRecipe(ItemStack result) { + super(result); + } + + public CraftShapedRecipe(ItemStack result, ShapedRecipes recipe) { + this(result); + this.recipe = recipe; + } + + public static CraftShapedRecipe fromBukkitRecipe(ShapedRecipe recipe) { + if (recipe instanceof CraftShapedRecipe) { + return (CraftShapedRecipe) recipe; + } + CraftShapedRecipe ret = new CraftShapedRecipe(recipe.getResult()); + String[] shape = recipe.getShape(); + ret.shape(shape); + Map ingredientMap = recipe.getIngredientMap(); + for (char c : ingredientMap.keySet()) { + ItemStack stack = ingredientMap.get(c); + if (stack != null) { + ret.setIngredient(c, stack.getType(), stack.getDurability()); + } + } + return ret; + } + + public void addToCraftingManager() { + Object[] data; + String[] shape = this.getShape(); + Map ingred = this.getIngredientMap(); + int datalen = shape.length; + datalen += ingred.size() * 2; + int i = 0; + data = new Object[datalen]; + for (; i < shape.length; i++) { + data[i] = shape[i]; + } + for (char c : ingred.keySet()) { + ItemStack mdata = ingred.get(c); + if (mdata == null) continue; + data[i] = c; + i++; + int id = mdata.getTypeId(); + short dmg = mdata.getDurability(); + data[i] = new net.minecraft.server.ItemStack(CraftMagicNumbers.getItem(id), 1, dmg); + i++; + } + CraftingManager.getInstance().registerShapedRecipe(CraftItemStack.asNMSCopy(this.getResult()), data); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftShapelessRecipe.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftShapelessRecipe.java new file mode 100644 index 0000000..a9987ef --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/CraftShapelessRecipe.java @@ -0,0 +1,45 @@ +package org.bukkit.craftbukkit.inventory; + +import net.minecraft.server.CraftingManager; +import net.minecraft.server.ShapelessRecipes; +import org.bukkit.craftbukkit.util.CraftMagicNumbers; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.ShapelessRecipe; + +import java.util.List; + +public class CraftShapelessRecipe extends ShapelessRecipe implements CraftRecipe { + + public CraftShapelessRecipe(ItemStack result) { + super(result); + } + + public CraftShapelessRecipe(ItemStack result, ShapelessRecipes recipe) { + this(result); + // TODO: Could eventually use this to add a matches() method or some such + } + + public static CraftShapelessRecipe fromBukkitRecipe(ShapelessRecipe recipe) { + if (recipe instanceof CraftShapelessRecipe) { + return (CraftShapelessRecipe) recipe; + } + CraftShapelessRecipe ret = new CraftShapelessRecipe(recipe.getResult()); + for (ItemStack ingred : recipe.getIngredientList()) { + ret.addIngredient(ingred.getType(), ingred.getDurability()); + } + return ret; + } + + public void addToCraftingManager() { + List ingred = this.getIngredientList(); + Object[] data = new Object[ingred.size()]; + int i = 0; + for (ItemStack mdata : ingred) { + int id = mdata.getTypeId(); + short dmg = mdata.getDurability(); + data[i] = new net.minecraft.server.ItemStack(CraftMagicNumbers.getItem(id), 1, dmg); + i++; + } + CraftingManager.getInstance().registerShapelessRecipe(CraftItemStack.asNMSCopy(this.getResult()), data); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/InventoryIterator.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/InventoryIterator.java new file mode 100644 index 0000000..29258b2 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/InventoryIterator.java @@ -0,0 +1,64 @@ +package org.bukkit.craftbukkit.inventory; + +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; + +import java.util.ListIterator; + +public class InventoryIterator implements ListIterator { + private final Inventory inventory; + private int nextIndex; + private Boolean lastDirection; // true = forward, false = backward, null = haven't moved yet + + InventoryIterator(Inventory craftInventory) { + this.inventory = craftInventory; + this.nextIndex = 0; + } + + InventoryIterator(Inventory craftInventory, int index) { + this.inventory = craftInventory; + this.nextIndex = index; + } + + public boolean hasNext() { + return nextIndex < inventory.getSize(); + } + + public ItemStack next() { + lastDirection = true; + return inventory.getItem(nextIndex++); + } + + public int nextIndex() { + return nextIndex; + } + + public boolean hasPrevious() { + return nextIndex > 0; + } + + public ItemStack previous() { + lastDirection = false; + return inventory.getItem(--nextIndex); + } + + public int previousIndex() { + return nextIndex - 1; + } + + public void set(ItemStack item) { + if (lastDirection == null) { + throw new IllegalStateException("No current item!"); + } + int i = lastDirection ? nextIndex - 1 : nextIndex; + inventory.setItem(i, item); + } + + public void add(ItemStack item) { + throw new UnsupportedOperationException("Can't change the size of an inventory!"); + } + + public void remove() { + throw new UnsupportedOperationException("Can't change the size of an inventory!"); + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/InventoryWrapper.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/InventoryWrapper.java new file mode 100644 index 0000000..1471d8f --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/InventoryWrapper.java @@ -0,0 +1,174 @@ +package org.bukkit.craftbukkit.inventory; + +import net.minecraft.server.EntityHuman; +import net.minecraft.server.IChatBaseComponent; +import net.minecraft.server.IInventory; +import net.minecraft.server.ItemStack; +import org.bukkit.craftbukkit.entity.CraftHumanEntity; +import org.bukkit.craftbukkit.util.CraftChatMessage; +import org.bukkit.entity.HumanEntity; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryHolder; + +import java.util.ArrayList; +import java.util.List; + +public class InventoryWrapper implements IInventory { + + private final Inventory inventory; + private final List viewers = new ArrayList<>(); + + public InventoryWrapper(Inventory inventory) { + this.inventory = inventory; + } + + @Override + public int getSize() { + return inventory.getSize(); + } + + @Override + public ItemStack getItem(int i) { + return CraftItemStack.asNMSCopy(inventory.getItem(i)); + } + + @Override + public ItemStack splitStack(int i, int j) { + // Copied from CraftItemStack + ItemStack stack = getItem(i); + ItemStack result; + if (stack == null) { + return null; + } + if (stack.count <= j) { + this.setItem(i, null); + result = stack; + } else { + result = CraftItemStack.copyNMSStack(stack, j); + stack.count -= j; + } + this.update(); + return result; + } + + @Override + public ItemStack splitWithoutUpdate(int i) { + // Copied from CraftItemStack + ItemStack stack = getItem(i); + ItemStack result; + if (stack == null) { + return null; + } + if (stack.count <= 1) { + this.setItem(i, null); + result = stack; + } else { + result = CraftItemStack.copyNMSStack(stack, 1); + stack.count -= 1; + } + return result; + } + + @Override + public void setItem(int i, ItemStack itemstack) { + inventory.setItem(i, CraftItemStack.asBukkitCopy(itemstack)); + } + + @Override + public int getMaxStackSize() { + return inventory.getMaxStackSize(); + } + + @Override + public void update() { + } + + @Override + public boolean a(EntityHuman entityhuman) { + return true; + } + + @Override + public void startOpen(EntityHuman entityhuman) { + } + + @Override + public void closeContainer(EntityHuman entityhuman) { + } + + @Override + public boolean b(int i, ItemStack itemstack) { + return true; + } + + @Override + public int getProperty(int i) { + return 0; + } + + @Override + public void b(int i, int j) { + } + + @Override + public int g() { + return 0; + } + + @Override + public void l() { + inventory.clear(); + } + + @Override + public ItemStack[] getContents() { + int size = getSize(); + ItemStack[] items = new ItemStack[size]; + + for (int i = 0; i < size; i++) { + items[i] = getItem(i); + } + + return items; + } + + @Override + public void onOpen(CraftHumanEntity who) { + viewers.add(who); + } + + @Override + public void onClose(CraftHumanEntity who) { + viewers.remove(who); + } + + @Override + public List getViewers() { + return viewers; + } + + @Override + public InventoryHolder getOwner() { + return inventory.getHolder(); + } + + @Override + public void setMaxStackSize(int size) { + inventory.setMaxStackSize(size); + } + + @Override + public String getName() { + return inventory.getName(); + } + + @Override + public boolean hasCustomName() { + return getName() != null; + } + + @Override + public IChatBaseComponent getScoreboardDisplayName() { + return CraftChatMessage.fromString(getName())[0]; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/RecipeIterator.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/RecipeIterator.java new file mode 100644 index 0000000..7430208 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/RecipeIterator.java @@ -0,0 +1,52 @@ +package org.bukkit.craftbukkit.inventory; + +import net.minecraft.server.CraftingManager; +import net.minecraft.server.IRecipe; +import net.minecraft.server.RecipesFurnace; +import org.bukkit.inventory.Recipe; + +import java.util.Iterator; + +public class RecipeIterator implements Iterator { + private final Iterator recipes; + private final Iterator smeltingCustom; + private final Iterator smeltingVanilla; + private Iterator removeFrom = null; + + public RecipeIterator() { + this.recipes = CraftingManager.getInstance().getRecipes().iterator(); + this.smeltingCustom = RecipesFurnace.getInstance().customRecipes.keySet().iterator(); + this.smeltingVanilla = RecipesFurnace.getInstance().recipes.keySet().iterator(); + } + + public boolean hasNext() { + return recipes.hasNext() || smeltingCustom.hasNext() || smeltingVanilla.hasNext(); + } + + public Recipe next() { + if (recipes.hasNext()) { + removeFrom = recipes; + return recipes.next().toBukkitRecipe(); + } else { + net.minecraft.server.ItemStack item; + if (smeltingCustom.hasNext()) { + removeFrom = smeltingCustom; + item = smeltingCustom.next(); + } else { + removeFrom = smeltingVanilla; + item = smeltingVanilla.next(); + } + + CraftItemStack stack = CraftItemStack.asCraftMirror(RecipesFurnace.getInstance().getResult(item)); + + return new CraftFurnaceRecipe(stack, CraftItemStack.asCraftMirror(item)); + } + } + + public void remove() { + if (removeFrom == null) { + throw new IllegalStateException(); + } + removeFrom.remove(); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/SerializableMeta.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/SerializableMeta.java new file mode 100644 index 0000000..a86fa91 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/inventory/SerializableMeta.java @@ -0,0 +1,97 @@ +package org.bukkit.craftbukkit.inventory; + +import com.google.common.collect.ImmutableMap; +import org.apache.commons.lang.Validate; +import org.bukkit.configuration.serialization.ConfigurationSerializable; +import org.bukkit.configuration.serialization.SerializableAs; +import org.bukkit.inventory.meta.ItemMeta; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.util.Map; +import java.util.NoSuchElementException; + +@SerializableAs("ItemMeta") +public class SerializableMeta implements ConfigurationSerializable { + static final String TYPE_FIELD = "meta-type"; + + static final ImmutableMap, String> classMap; + static final ImmutableMap> constructorMap; + + static { + classMap = ImmutableMap., String>builder() + .put(CraftMetaBanner.class, "BANNER") + .put(CraftMetaBlockState.class, "TILE_ENTITY") + .put(CraftMetaBook.class, "BOOK") + .put(CraftMetaBookSigned.class, "BOOK_SIGNED") + .put(CraftMetaSkull.class, "SKULL") + .put(CraftMetaLeatherArmor.class, "LEATHER_ARMOR") + .put(CraftMetaMap.class, "MAP") + .put(CraftMetaPotion.class, "POTION") + .put(CraftMetaEnchantedBook.class, "ENCHANTED") + .put(CraftMetaFirework.class, "FIREWORK") + .put(CraftMetaCharge.class, "FIREWORK_EFFECT") + .put(CraftMetaItem.class, "UNSPECIFIC") + .build(); + + final ImmutableMap.Builder> classConstructorBuilder = ImmutableMap.builder(); + for (Map.Entry, String> mapping : classMap.entrySet()) { + try { + classConstructorBuilder.put(mapping.getValue(), mapping.getKey().getDeclaredConstructor(Map.class)); + } catch (NoSuchMethodException e) { + throw new AssertionError(e); + } + } + constructorMap = classConstructorBuilder.build(); + } + + private SerializableMeta() { + } + + public static ItemMeta deserialize(Map map) throws Throwable { + Validate.notNull(map, "Cannot deserialize null map"); + + String type = getString(map, TYPE_FIELD, false); + Constructor constructor = constructorMap.get(type); + + if (constructor == null) { + throw new IllegalArgumentException(type + " is not a valid " + TYPE_FIELD); + } + + try { + return constructor.newInstance(map); + } catch (final InstantiationException | IllegalAccessException e) { + throw new AssertionError(e); + } catch (final InvocationTargetException e) { + throw e.getCause(); + } + } + + static String getString(Map map, Object field, boolean nullable) { + return getObject(String.class, map, field, nullable); + } + + static boolean getBoolean(Map map, Object field) { + Boolean value = getObject(Boolean.class, map, field, true); + return value != null && value; + } + + static T getObject(Class clazz, Map map, Object field, boolean nullable) { + final Object object = map.get(field); + + if (clazz.isInstance(object)) { + return clazz.cast(object); + } + if (object == null) { + if (!nullable) { + throw new NoSuchElementException(map + " does not contain " + field); + } + return null; + } + throw new IllegalArgumentException(field + "(" + object + ") is not a valid " + clazz); + } + + public Map serialize() { + throw new AssertionError(); + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/map/CraftMapCanvas.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/map/CraftMapCanvas.java new file mode 100644 index 0000000..26b633e --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/map/CraftMapCanvas.java @@ -0,0 +1,111 @@ +package org.bukkit.craftbukkit.map; + +import org.bukkit.map.MapCanvas; +import org.bukkit.map.MapCursorCollection; +import org.bukkit.map.MapFont; +import org.bukkit.map.MapFont.CharacterSprite; +import org.bukkit.map.MapPalette; + +import java.awt.*; +import java.util.Arrays; + +public class CraftMapCanvas implements MapCanvas { + + private final byte[] buffer = new byte[128 * 128]; + private final CraftMapView mapView; + private byte[] base; + private MapCursorCollection cursors = new MapCursorCollection(); + + protected CraftMapCanvas(CraftMapView mapView) { + this.mapView = mapView; + Arrays.fill(buffer, (byte) -1); + } + + public CraftMapView getMapView() { + return mapView; + } + + public MapCursorCollection getCursors() { + return cursors; + } + + public void setCursors(MapCursorCollection cursors) { + this.cursors = cursors; + } + + public void setPixel(int x, int y, byte color) { + if (x < 0 || y < 0 || x >= 128 || y >= 128) + return; + if (buffer[y * 128 + x] != color) { + buffer[y * 128 + x] = color; + mapView.worldMap.flagDirty(x, y); + } + } + + public byte getPixel(int x, int y) { + if (x < 0 || y < 0 || x >= 128 || y >= 128) + return 0; + return buffer[y * 128 + x]; + } + + public byte getBasePixel(int x, int y) { + if (x < 0 || y < 0 || x >= 128 || y >= 128) + return 0; + return base[y * 128 + x]; + } + + protected void setBase(byte[] base) { + this.base = base; + } + + protected byte[] getBuffer() { + return buffer; + } + + public void drawImage(int x, int y, Image image) { + byte[] bytes = MapPalette.imageToBytes(image); + for (int x2 = 0; x2 < image.getWidth(null); ++x2) { + for (int y2 = 0; y2 < image.getHeight(null); ++y2) { + setPixel(x + x2, y + y2, bytes[y2 * image.getWidth(null) + x2]); + } + } + } + + public void drawText(int x, int y, MapFont font, String text) { + int xStart = x; + byte color = MapPalette.DARK_GRAY; + if (!font.isValid(text)) { + throw new IllegalArgumentException("text contains invalid characters"); + } + + for (int i = 0; i < text.length(); ++i) { + char ch = text.charAt(i); + if (ch == '\n') { + x = xStart; + y += font.getHeight() + 1; + continue; + } else if (ch == '\u00A7') { + int j = text.indexOf(';', i); + if (j >= 0) { + try { + color = Byte.parseByte(text.substring(i + 1, j)); + i = j; + continue; + } + catch (NumberFormatException ignored) {} + } + } + + CharacterSprite sprite = font.getChar(text.charAt(i)); + for (int r = 0; r < font.getHeight(); ++r) { + for (int c = 0; c < sprite.getWidth(); ++c) { + if (sprite.get(r, c)) { + setPixel(x + c, y + r, color); + } + } + } + x += sprite.getWidth() + 1; + } + } + +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/map/CraftMapRenderer.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/map/CraftMapRenderer.java new file mode 100644 index 0000000..fc23895 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/map/CraftMapRenderer.java @@ -0,0 +1,50 @@ +package org.bukkit.craftbukkit.map; + +import net.minecraft.server.MapIcon; +import net.minecraft.server.WorldMap; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.map.MapCanvas; +import org.bukkit.map.MapCursorCollection; +import org.bukkit.map.MapRenderer; +import org.bukkit.map.MapView; + +import java.util.UUID; + +public class CraftMapRenderer extends MapRenderer { + + private final WorldMap worldMap; + + public CraftMapRenderer(CraftMapView mapView, WorldMap worldMap) { + super(false); + this.worldMap = worldMap; + } + + @Override + public void render(MapView map, MapCanvas canvas, Player player) { + // Map + for (int x = 0; x < 128; ++x) { + for (int y = 0; y < 128; ++y) { + canvas.setPixel(x, y, worldMap.colors[y * 128 + x]); + } + } + + // Cursors + MapCursorCollection cursors = canvas.getCursors(); + while (cursors.size() > 0) { + cursors.removeCursor(cursors.getCursor(0)); + } + + for (UUID key : worldMap.decorations.keySet()) { // Spigot string -> uuid. + // If this cursor is for a player check visibility with vanish system + Player other = Bukkit.getPlayer(key); // Spigot + if (other != null && !player.canSee(other)) { + continue; + } + + MapIcon decoration = worldMap.decorations.get(key); + cursors.addCursor(decoration.getX(), decoration.getY(), (byte) (decoration.getRotation() & 15), decoration.getType()); + } + } + +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/map/CraftMapView.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/map/CraftMapView.java new file mode 100644 index 0000000..751d208 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/map/CraftMapView.java @@ -0,0 +1,158 @@ +package org.bukkit.craftbukkit.map; + +import net.minecraft.server.WorldMap; +import org.bukkit.Bukkit; +import org.bukkit.World; +import org.bukkit.craftbukkit.CraftWorld; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.map.MapRenderer; +import org.bukkit.map.MapView; + +import java.util.*; + +public final class CraftMapView implements MapView { + + private final Map renderCache = new HashMap<>(); + private final List renderers = new ArrayList<>(); + private final Map> canvases = new HashMap<>(); + final WorldMap worldMap; + + public CraftMapView(WorldMap worldMap) { + this.worldMap = worldMap; + addRenderer(new CraftMapRenderer(this, worldMap)); + } + + public short getId() { + String text = worldMap.id; + if (text.startsWith("map_")) { + try { + return Short.parseShort(text.substring("map_".length())); + } + catch (NumberFormatException ex) { + throw new IllegalStateException("Map has non-numeric ID"); + } + } else { + throw new IllegalStateException("Map has invalid ID"); + } + } + + public boolean isVirtual() { + return renderers.size() > 0 && !(renderers.get(0) instanceof CraftMapRenderer); + } + + public Scale getScale() { + return Scale.valueOf(worldMap.scale); + } + + public void setScale(Scale scale) { + worldMap.scale = scale.getValue(); + } + + public World getWorld() { + byte dimension = worldMap.map; + for (World world : Bukkit.getServer().getWorlds()) { + if (((CraftWorld) world).getHandle().dimension == dimension) { + return world; + } + } + return null; + } + + public void setWorld(World world) { + worldMap.map = (byte) ((CraftWorld) world).getHandle().dimension; + } + + public int getCenterX() { + return worldMap.centerX; + } + + public int getCenterZ() { + return worldMap.centerZ; + } + + public void setCenterX(int x) { + worldMap.centerX = x; + } + + public void setCenterZ(int z) { + worldMap.centerZ = z; + } + + public List getRenderers() { + return new ArrayList<>(renderers); + } + + public void addRenderer(MapRenderer renderer) { + if (!renderers.contains(renderer)) { + renderers.add(renderer); + canvases.put(renderer, new HashMap<>()); + renderer.initialize(this); + } + } + + public boolean removeRenderer(MapRenderer renderer) { + if (renderers.contains(renderer)) { + renderers.remove(renderer); + for (Map.Entry entry : canvases.get(renderer).entrySet()) { + for (int x = 0; x < 128; ++x) { + for (int y = 0; y < 128; ++y) { + entry.getValue().setPixel(x, y, (byte) -1); + } + } + } + canvases.remove(renderer); + return true; + } else { + return false; + } + } + + private boolean isContextual() { + for (MapRenderer renderer : renderers) { + if (renderer.isContextual()) return true; + } + return false; + } + + public RenderData render(CraftPlayer player) { + boolean context = isContextual(); + RenderData render = renderCache.get(context ? player : null); + + if (render == null) { + render = new RenderData(); + renderCache.put(context ? player : null, render); + } + + if (context) { + renderCache.remove(null); + } + + Arrays.fill(render.buffer, (byte) 0); + render.cursors.clear(); + + for (MapRenderer renderer : renderers) { + CraftMapCanvas canvas = canvases.get(renderer).get(renderer.isContextual() ? player : null); + if (canvas == null) { + canvas = new CraftMapCanvas(this); + canvases.get(renderer).put(renderer.isContextual() ? player : null, canvas); + } + + canvas.setBase(render.buffer); + renderer.render(this, canvas, player); + + byte[] buf = canvas.getBuffer(); + for (int i = 0; i < buf.length; ++i) { + byte color = buf[i]; + // There are 143 valid color id's, 0 -> 127 and -128 -> -113 + if (color >= 0 || color <= -113) render.buffer[i] = color; + } + + for (int i = 0; i < canvas.getCursors().size(); ++i) { + render.cursors.add(canvas.getCursors().getCursor(i)); + } + } + + return render; + } + +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/map/RenderData.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/map/RenderData.java new file mode 100644 index 0000000..c2685b8 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/map/RenderData.java @@ -0,0 +1,17 @@ +package org.bukkit.craftbukkit.map; + +import org.bukkit.map.MapCursor; + +import java.util.ArrayList; + +public class RenderData { + + public final byte[] buffer; + public final ArrayList cursors; + + public RenderData() { + this.buffer = new byte[128 * 128]; + this.cursors = new ArrayList<>(); + } + +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/metadata/BlockMetadataStore.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/metadata/BlockMetadataStore.java new file mode 100644 index 0000000..af845a3 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/metadata/BlockMetadataStore.java @@ -0,0 +1,94 @@ +package org.bukkit.craftbukkit.metadata; + +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.metadata.MetadataStore; +import org.bukkit.metadata.MetadataStoreBase; +import org.bukkit.metadata.MetadataValue; +import org.bukkit.plugin.Plugin; + +import java.util.List; + +/** + * A BlockMetadataStore stores metadata values for {@link Block} objects. + */ +public class BlockMetadataStore extends MetadataStoreBase implements MetadataStore { + + private final World owningWorld; + + /** + * Initializes a BlockMetadataStore. + * @param owningWorld The world to which this BlockMetadataStore belongs. + */ + public BlockMetadataStore(World owningWorld) { + this.owningWorld = owningWorld; + } + + /** + * Generates a unique metadata key for a {@link Block} object based on its coordinates in the world. + * @see MetadataStoreBase#disambiguate(Object, String) + * @param block the block + * @param metadataKey The name identifying the metadata value + * @return a unique metadata key + */ + @Override + protected String disambiguate(Block block, String metadataKey) { + return block.getX() + ":" + block.getY() + ":" + block.getZ() + ":" + metadataKey; + } + + /** + * Retrieves the metadata for a {@link Block}, ensuring the block being asked for actually belongs to this BlockMetadataStore's + * owning world. + * @see MetadataStoreBase#getMetadata(Object, String) + */ + @Override + public List getMetadata(Block block, String metadataKey) { + if(block.getWorld() == owningWorld) { + return super.getMetadata(block, metadataKey); + } else { + throw new IllegalArgumentException("Block does not belong to world " + owningWorld.getName()); + } + } + + /** + * Tests to see if a metadata value has been added to a {@link Block}, ensuring the block being interrogated belongs + * to this BlockMetadataStore's owning world. + * @see MetadataStoreBase#hasMetadata(Object, String) + */ + @Override + public boolean hasMetadata(Block block, String metadataKey) { + if(block.getWorld() == owningWorld) { + return super.hasMetadata(block, metadataKey); + } else { + throw new IllegalArgumentException("Block does not belong to world " + owningWorld.getName()); + } + } + + /** + * Removes metadata from from a {@link Block} belonging to a given {@link Plugin}, ensuring the block being deleted from belongs + * to this BlockMetadataStore's owning world. + * @see MetadataStoreBase#removeMetadata(Object, String, org.bukkit.plugin.Plugin) + */ + @Override + public void removeMetadata(Block block, String metadataKey, Plugin owningPlugin) { + if(block.getWorld() == owningWorld) { + super.removeMetadata(block, metadataKey, owningPlugin); + } else { + throw new IllegalArgumentException("Block does not belong to world " + owningWorld.getName()); + } + } + + /** + * Sets or overwrites a metadata value on a {@link Block} from a given {@link Plugin}, ensuring the target block belongs + * to this BlockMetadataStore's owning world. + * @see MetadataStoreBase#setMetadata(Object, String, org.bukkit.metadata.MetadataValue) + */ + @Override + public void setMetadata(Block block, String metadataKey, MetadataValue newMetadataValue) { + if(block.getWorld() == owningWorld) { + super.setMetadata(block, metadataKey, newMetadataValue); + } else { + throw new IllegalArgumentException("Block does not belong to world " + owningWorld.getName()); + } + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/metadata/EntityMetadataStore.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/metadata/EntityMetadataStore.java new file mode 100644 index 0000000..35c484f --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/metadata/EntityMetadataStore.java @@ -0,0 +1,23 @@ +package org.bukkit.craftbukkit.metadata; + +import org.bukkit.entity.Entity; +import org.bukkit.metadata.MetadataStore; +import org.bukkit.metadata.MetadataStoreBase; + +/** + * An EntityMetadataStore stores metadata values for all {@link Entity} classes an their descendants. + */ +public class EntityMetadataStore extends MetadataStoreBase implements MetadataStore { + /** + * Generates a unique metadata key for an {@link Entity} UUID. + * + * @see MetadataStoreBase#disambiguate(Object, String) + * @param entity the entity + * @param metadataKey The name identifying the metadata value + * @return a unique metadata key + */ + @Override + protected String disambiguate(Entity entity, String metadataKey) { + return entity.getUniqueId().toString() + ":" + metadataKey; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/metadata/PlayerMetadataStore.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/metadata/PlayerMetadataStore.java new file mode 100644 index 0000000..d4d7f38 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/metadata/PlayerMetadataStore.java @@ -0,0 +1,23 @@ +package org.bukkit.craftbukkit.metadata; + +import org.bukkit.OfflinePlayer; +import org.bukkit.metadata.MetadataStore; +import org.bukkit.metadata.MetadataStoreBase; + +/** + * A PlayerMetadataStore stores metadata for {@link org.bukkit.entity.Player} and {@link OfflinePlayer} objects. + */ +public class PlayerMetadataStore extends MetadataStoreBase implements MetadataStore { + /** + * Generates a unique metadata key for {@link org.bukkit.entity.Player} and {@link OfflinePlayer} using the player + * name. + * @see MetadataStoreBase#disambiguate(Object, String) + * @param player the player + * @param metadataKey The name identifying the metadata value + * @return a unique metadata key + */ + @Override + protected String disambiguate(OfflinePlayer player, String metadataKey) { + return player.getName().toLowerCase() + ":" + metadataKey; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/metadata/SpecializedBlockMetadataStore.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/metadata/SpecializedBlockMetadataStore.java new file mode 100644 index 0000000..920d968 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/metadata/SpecializedBlockMetadataStore.java @@ -0,0 +1,175 @@ +package org.bukkit.craftbukkit.metadata; + +import com.google.common.base.Objects; +import com.google.common.base.Preconditions; +import com.google.common.collect.ImmutableList; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.metadata.MetadataStore; +import org.bukkit.metadata.MetadataValue; +import org.bukkit.plugin.Plugin; + +import java.util.*; + +/** + * An alternative to {@link BlockMetadataStore} that uses specialized collections and bit-packing for faster + * operations and a lower memory footprint. + * + *

    This can be a drop-in replacement, though keep in mind methods will throw an {@link IllegalArgumentException} + * if invalid block coordinates are provided. + */ +public class SpecializedBlockMetadataStore implements MetadataStore { + // Allows storing 25 bits (up to 33,554,432 - MC supports up to 30,000,000) sign + private static final int MASK_26_BITS = 0b111_111_111_111_111_111_111_111_11; + + private final Map> metadata = new HashMap<>(); + private final World owningWorld; + + // Cached key used for (synchronized) lookups, saves allocations. + // The key stored inside is usually cleared after use, so that the reference doesn't live too long. + private final StoreKey cachedKey = new StoreKey(null, 0); + + public SpecializedBlockMetadataStore(World owningWorld) { + this.owningWorld = owningWorld; + } + + @Override + public synchronized List getMetadata(Block block, String metadataKey) { + Preconditions.checkArgument(block.getWorld() == owningWorld, "block is from another world"); + + List list = Collections.emptyList(); + Map pluginMetadata = getEntry(metadataKey, block); + if (pluginMetadata == null) { + return list; + } + list = ImmutableList.copyOf(pluginMetadata.values()); + + return list; + } + + @Override + public synchronized boolean hasMetadata(Block block, String metadataKey) { + Preconditions.checkArgument(block.getWorld() == owningWorld, "block is from another world"); + Map pluginMetadata = getEntry(metadataKey, block); + return pluginMetadata != null && !pluginMetadata.isEmpty(); + } + + @Override + public synchronized void removeMetadata(Block block, String metadataKey, Plugin owningPlugin) { + Preconditions.checkArgument(block.getWorld() == owningWorld, "block is from another world"); + Preconditions.checkNotNull(owningPlugin, "plugin is null"); + + long id = getBlockId(block); + Map pluginMetadata = getEntry(metadataKey, id); + if (pluginMetadata == null) { + return; + } + // Clear empty entries + if (pluginMetadata.remove(owningPlugin) != null && pluginMetadata.isEmpty()) { + StoreKey key = getCachedKey(metadataKey, id); + this.metadata.remove(key); + key.metadataKey = null; + } + } + + @Override + public synchronized void setMetadata(Block block, String metadataKey, MetadataValue newMetadataValue) { + Preconditions.checkArgument(block.getWorld() == owningWorld, "block is from another world"); + Preconditions.checkNotNull(newMetadataValue, "value is null"); + Plugin owningPlugin = newMetadataValue.getOwningPlugin(); + Preconditions.checkNotNull(owningPlugin, "plugin is null"); + + Map entry = metadata.computeIfAbsent(new StoreKey(metadataKey, getBlockId(block)), + k -> new WeakHashMap<>(1)); + entry.put(owningPlugin, newMetadataValue); + } + + @Override + public synchronized void invalidateAll(Plugin owningPlugin) { + Preconditions.checkNotNull(owningPlugin, "plugin is null"); + for (Map values : metadata.values()) { + MetadataValue value = values.get(owningPlugin); + if (value != null) { + value.invalidate(); + } + } + } + + private Map getEntry(String key, Block block) { + return getEntry(key, getBlockId(block)); + } + + private Map getEntry(String key, long id) { + StoreKey storeKey = getCachedKey(key, id); + Map ret = metadata.get(storeKey); + storeKey.metadataKey = null; + return ret; + } + + private StoreKey getCachedKey(String metadataKey, long id) { + cachedKey.block = id; + cachedKey.metadataKey = metadataKey; + return cachedKey; + } + + static long getBlockId(Block block) { + int x = block.getX(); + int y = block.getY(); + int z = block.getZ(); + Preconditions.checkArgument(x >= -30_000_000 && x <= 30_000_000, + "block X out of range"); + Preconditions.checkArgument(y >= 0 && y <= 255, "block Y out of range"); + Preconditions.checkArgument(z >= -30_000_000 && z <= 30_000_000, + "block Z out of range"); + // X (26 bits) + Y (8 bits) + Z (26 bits) + return ((long) (x & MASK_26_BITS) << 34) | ((long) (y & 0xFF) << 26) | (z & MASK_26_BITS); + } + + /** + * Used for tests. + */ + static Location toLocation(World world, long id) { + int x = (int) (id >> 34); + int y = (int) ((id >> 26) & 0xFF); + int z = (int) id; + + // Restore sign + if ((x & (1 << 25)) > 0) { + x |= ~MASK_26_BITS; + } else { + x &= MASK_26_BITS; + } + + if ((z & (1 << 25)) > 0) { + z |= ~MASK_26_BITS; + } else { + z &= MASK_26_BITS; + } + + return new Location(world, x, y, z); + } + + private static class StoreKey { + private String metadataKey; + private long block; + + private StoreKey(String metadataKey, long block) { + this.metadataKey = metadataKey; + this.block = block; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + StoreKey storeKey = (StoreKey) o; + return block == storeKey.block && Objects.equal(metadataKey, storeKey.metadataKey); + } + + @Override + public int hashCode() { + return Objects.hashCode(metadataKey, block); + } + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/metadata/WorldMetadataStore.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/metadata/WorldMetadataStore.java new file mode 100644 index 0000000..dd37ed2 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/metadata/WorldMetadataStore.java @@ -0,0 +1,22 @@ +package org.bukkit.craftbukkit.metadata; + +import org.bukkit.World; +import org.bukkit.metadata.MetadataStore; +import org.bukkit.metadata.MetadataStoreBase; + +/** + * An WorldMetadataStore stores metadata values for {@link World} objects. + */ +public class WorldMetadataStore extends MetadataStoreBase implements MetadataStore { + /** + * Generates a unique metadata key for a {@link World} object based on the world UID. + * @see WorldMetadataStore#disambiguate(Object, String) + * @param world the world + * @param metadataKey The name identifying the metadata value + * @return a unique metadata key + */ + @Override + protected String disambiguate(World world, String metadataKey) { + return world.getUID().toString() + ":" + metadataKey; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/potion/CraftPotionBrewer.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/potion/CraftPotionBrewer.java new file mode 100644 index 0000000..9e41bec --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/potion/CraftPotionBrewer.java @@ -0,0 +1,45 @@ +package org.bukkit.craftbukkit.potion; + +import com.google.common.collect.Maps; +import net.minecraft.server.MobEffect; +import org.bukkit.potion.PotionBrewer; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; + +public class CraftPotionBrewer implements PotionBrewer { + private static final Map> cache = Maps.newHashMap(); + + public Collection getEffectsFromDamage(int damage) { + if (cache.containsKey(damage)) + return cache.get(damage); + + List mcEffects = net.minecraft.server.PotionBrewer.getEffects(damage, false); + List effects = new ArrayList<>(); + if (mcEffects == null) + return effects; + + for (Object raw : mcEffects) { + if (!(raw instanceof MobEffect)) + continue; + MobEffect mcEffect = (MobEffect) raw; + PotionEffect effect = new PotionEffect(PotionEffectType.getById(mcEffect.getEffectId()), + mcEffect.getDuration(), mcEffect.getAmplifier()); + // Minecraft PotionBrewer applies duration modifiers automatically. + effects.add(effect); + } + + cache.put(damage, effects); + + return effects; + } + + public PotionEffect createEffect(PotionEffectType potion, int duration, int amplifier) { + return new PotionEffect(potion, potion.isInstant() ? 1 : (int) (duration * potion.getDurationModifier()), + amplifier); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/potion/CraftPotionEffectType.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/potion/CraftPotionEffectType.java new file mode 100644 index 0000000..72951eb --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/potion/CraftPotionEffectType.java @@ -0,0 +1,81 @@ +package org.bukkit.craftbukkit.potion; + +import net.minecraft.server.MobEffectList; +import org.bukkit.potion.PotionEffectType; + +public class CraftPotionEffectType extends PotionEffectType { + private final MobEffectList handle; + + public CraftPotionEffectType(MobEffectList handle) { + super(handle.id); + this.handle = handle; + } + + @Override + public double getDurationModifier() { + return handle.getDurationModifier(); + } + + public MobEffectList getHandle() { + return handle; + } + + @Override + public String getName() { + switch (handle.id) { + case 1: + return "SPEED"; + case 2: + return "SLOW"; + case 3: + return "FAST_DIGGING"; + case 4: + return "SLOW_DIGGING"; + case 5: + return "INCREASE_DAMAGE"; + case 6: + return "HEAL"; + case 7: + return "HARM"; + case 8: + return "JUMP"; + case 9: + return "CONFUSION"; + case 10: + return "REGENERATION"; + case 11: + return "DAMAGE_RESISTANCE"; + case 12: + return "FIRE_RESISTANCE"; + case 13: + return "WATER_BREATHING"; + case 14: + return "INVISIBILITY"; + case 15: + return "BLINDNESS"; + case 16: + return "NIGHT_VISION"; + case 17: + return "HUNGER"; + case 18: + return "WEAKNESS"; + case 19: + return "POISON"; + case 20: + return "WITHER"; + case 21: + return "HEALTH_BOOST"; + case 22: + return "ABSORPTION"; + case 23: + return "SATURATION"; + default: + return "UNKNOWN_EFFECT_TYPE_" + handle.id; + } + } + + @Override + public boolean isInstant() { + return handle.isInstant(); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/projectiles/CraftBlockProjectileSource.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/projectiles/CraftBlockProjectileSource.java new file mode 100644 index 0000000..3240dcd --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/projectiles/CraftBlockProjectileSource.java @@ -0,0 +1,115 @@ +package org.bukkit.craftbukkit.projectiles; + +import net.minecraft.server.*; +import org.apache.commons.lang.Validate; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.entity.*; +import org.bukkit.inventory.ItemStack; +import org.bukkit.projectiles.BlockProjectileSource; +import org.bukkit.util.Vector; + +import java.util.Random; + +public class CraftBlockProjectileSource implements BlockProjectileSource { + private final TileEntityDispenser dispenserBlock; + + public CraftBlockProjectileSource(TileEntityDispenser dispenserBlock) { + this.dispenserBlock = dispenserBlock; + } + + @Override + public Block getBlock() { + return dispenserBlock.getWorld().getWorld().getBlockAt(dispenserBlock.getPosition().getX(), dispenserBlock.getPosition().getY(), dispenserBlock.getPosition().getZ()); + } + + @Override + public T launchProjectile(Class projectile) { + return launchProjectile(projectile, null); + } + + @Override + public T launchProjectile(Class projectile, Vector velocity) { + Validate.isTrue(getBlock().getType() == Material.DISPENSER, "Block is no longer dispenser"); + // Copied from BlockDispenser.dispense() + SourceBlock isourceblock = new SourceBlock(dispenserBlock.getWorld(), dispenserBlock.getPosition()); + // Copied from DispenseBehaviorProjectile + IPosition iposition = BlockDispenser.a(isourceblock); + EnumDirection enumdirection = BlockDispenser.b(isourceblock.f()); + net.minecraft.server.World world = dispenserBlock.getWorld(); + net.minecraft.server.Entity launch = null; + + if (Snowball.class.isAssignableFrom(projectile)) { + launch = new EntitySnowball(world, iposition.getX(), iposition.getY(), iposition.getZ()); + } else if (Egg.class.isAssignableFrom(projectile)) { + launch = new EntityEgg(world, iposition.getX(), iposition.getY(), iposition.getZ()); + } else if (EnderPearl.class.isAssignableFrom(projectile)) { + launch = new EntityEnderPearl(world); + launch.setPosition(iposition.getX(), iposition.getY(), iposition.getZ()); + } else if (ThrownExpBottle.class.isAssignableFrom(projectile)) { + launch = new EntityThrownExpBottle(world, iposition.getX(), iposition.getY(), iposition.getZ()); + } else if (ThrownPotion.class.isAssignableFrom(projectile)) { + launch = new EntityPotion(world, iposition.getX(), iposition.getY(), iposition.getZ(), CraftItemStack.asNMSCopy(new ItemStack(Material.POTION, 1))); + } else if (Arrow.class.isAssignableFrom(projectile)) { + launch = new EntityArrow(world, iposition.getX(), iposition.getY(), iposition.getZ()); + ((EntityArrow) launch).fromPlayer = 1; + launch.projectileSource = this; + } else if (Fireball.class.isAssignableFrom(projectile)) { + double d0 = iposition.getX() + (double) ((float) enumdirection.getAdjacentX() * 0.3F); + double d1 = iposition.getY() + (double) ((float) enumdirection.getAdjacentY() * 0.3F); + double d2 = iposition.getZ() + (double) ((float) enumdirection.getAdjacentZ() * 0.3F); + Random random = world.random; + double d3 = random.nextGaussian() * 0.05D + (double) enumdirection.getAdjacentX(); + double d4 = random.nextGaussian() * 0.05D + (double) enumdirection.getAdjacentY(); + double d5 = random.nextGaussian() * 0.05D + (double) enumdirection.getAdjacentZ(); + + if (SmallFireball.class.isAssignableFrom(projectile)) { + launch = new EntitySmallFireball(world, d0, d1, d2, d3, d4, d5); + } else if (WitherSkull.class.isAssignableFrom(projectile)) { + launch = new EntityWitherSkull(world); + launch.setPosition(d0, d1, d2); + double d6 = MathHelper.sqrt(d3 * d3 + d4 * d4 + d5 * d5); + + ((EntityFireball) launch).dirX = d3 / d6 * 0.1D; + ((EntityFireball) launch).dirY = d4 / d6 * 0.1D; + ((EntityFireball) launch).dirZ = d5 / d6 * 0.1D; + } else { + launch = new EntityLargeFireball(world); + launch.setPosition(d0, d1, d2); + double d6 = MathHelper.sqrt(d3 * d3 + d4 * d4 + d5 * d5); + + ((EntityFireball) launch).dirX = d3 / d6 * 0.1D; + ((EntityFireball) launch).dirY = d4 / d6 * 0.1D; + ((EntityFireball) launch).dirZ = d5 / d6 * 0.1D; + } + + launch.projectileSource = this; + } + + Validate.notNull(launch, "Projectile not supported"); + + if (launch instanceof IProjectile) { + if (launch instanceof EntityProjectile) { + launch.projectileSource = this; + } + // Values from DispenseBehaviorProjectile + float a = 6.0F; + float b = 1.1F; + if (launch instanceof EntityPotion) { + // Values from respective DispenseBehavior classes + a *= 0.5F; + b *= 1.25F; + } + // Copied from DispenseBehaviorProjectile + ((IProjectile) launch).shoot(enumdirection.getAdjacentX(), (float) enumdirection.getAdjacentY() + 0.1F, enumdirection.getAdjacentZ(), b, a); + } + + if (velocity != null) { + ((T) launch.getBukkitEntity()).setVelocity(velocity); + } + + world.addEntity(launch); + return (T) launch.getBukkitEntity(); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/scheduler/CraftAsyncScheduler.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/scheduler/CraftAsyncScheduler.java new file mode 100644 index 0000000..55134c8 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/scheduler/CraftAsyncScheduler.java @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2018 Daniel Ennis (Aikar) MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package org.bukkit.craftbukkit.scheduler; + +import com.google.common.util.concurrent.ThreadFactoryBuilder; +import org.bukkit.plugin.Plugin; +import org.github.paperspigot.ServerSchedulerReportingWrapper; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.concurrent.*; + +public class CraftAsyncScheduler extends CraftScheduler { + + private final Executor management = Executors.newSingleThreadExecutor(new ThreadFactoryBuilder() + .setNameFormat("Craft Async Scheduler Management Thread") + .build()); + + private final List temp = new ArrayList<>(); + + CraftAsyncScheduler() { + super(true); + executor.allowCoreThreadTimeOut(true); + executor.prestartAllCoreThreads(); + } + + @Override + public void cancelTask(int taskId) { + this.management.execute(() -> this.removeTask(taskId)); + } + + private synchronized void removeTask(int taskId) { + parsePending(); + this.pending.removeIf((task) -> { + if (task.getTaskId() == taskId) { + task.cancel0(); + return true; + } + return false; + }); + } + + @Override + public void mainThreadHeartbeat(int currentTick) { + this.currentTick = currentTick; + this.management.execute(() -> this.runTasks(currentTick)); + } + + private synchronized void runTasks(int currentTick) { + parsePending(); + while (!this.pending.isEmpty() && this.pending.peek().getNextRun() <= currentTick) { + CraftTask task = this.pending.remove(); + if (executeTask(task)) { + final long period = task.getPeriod(); + if (period > 0) { + task.setNextRun(currentTick + period); + temp.add(task); + } + } + parsePending(); + } + this.pending.addAll(temp); + temp.clear(); + } + + private boolean executeTask(CraftTask task) { + if (isValid(task)) { + this.runners.put(task.getTaskId(), task); + this.executor.execute(new ServerSchedulerReportingWrapper(task)); + return true; + } + return false; + } + + @Override + public synchronized void cancelTasks(Plugin plugin) { + parsePending(); + for (Iterator iterator = this.pending.iterator(); iterator.hasNext(); ) { + CraftTask task = iterator.next(); + if (task.getTaskId() != -1 && (plugin == null || task.getOwner().equals(plugin))) { + task.cancel0(); + iterator.remove(); + } + } + } + + /** + * Task is not cancelled + */ + static boolean isValid(CraftTask runningTask) { + return runningTask.getPeriod() >= -1L; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/scheduler/CraftAsyncTask.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/scheduler/CraftAsyncTask.java new file mode 100644 index 0000000..29bfd87 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/scheduler/CraftAsyncTask.java @@ -0,0 +1,109 @@ +package org.bukkit.craftbukkit.scheduler; + +import org.apache.commons.lang.UnhandledException; +import org.bukkit.plugin.Plugin; +import org.bukkit.scheduler.BukkitWorker; + +import java.util.Iterator; +import java.util.LinkedList; +import java.util.Map; + + +class CraftAsyncTask extends CraftTask { + + private final LinkedList workers = new LinkedList<>(); + private final Map runners; + + CraftAsyncTask(final Map runners, final Plugin plugin, final Runnable task, final int id, final long delay) { + super(plugin, task, id, delay); + this.runners = runners; + } + + @Override + public boolean isSync() { + return false; + } + + @Override + public void run() { + final Thread thread = Thread.currentThread(); + synchronized(workers) { + if (getPeriod() == -2) { + // Never continue running after cancelled. + // Checking this with the lock is important! + return; + } + workers.add( + new BukkitWorker() { + public Thread getThread() { + return thread; + } + + public int getTaskId() { + return CraftAsyncTask.this.getTaskId(); + } + + public Plugin getOwner() { + return CraftAsyncTask.this.getOwner(); + } + }); + } + Throwable thrown = null; + try { + super.run(); + } catch (final Throwable t) { + thrown = t; + throw new UnhandledException( + String.format( + "Plugin %s generated an exception while executing task %s", + getOwner().getDescription().getFullName(), + getTaskId()), + thrown); + } finally { + // Cleanup is important for any async task, otherwise ghost tasks are everywhere + synchronized(workers) { + try { + final Iterator workers = this.workers.iterator(); + boolean removed = false; + while (workers.hasNext()) { + if (workers.next().getThread() == thread) { + workers.remove(); + removed = true; // Don't throw exception + break; + } + } + if (!removed) { + throw new IllegalStateException( + String.format( + "Unable to remove worker %s on task %s for %s", + thread.getName(), + getTaskId(), + getOwner().getDescription().getFullName()), + thrown); // We don't want to lose the original exception, if any + } + } finally { + if (getPeriod() < 0 && workers.isEmpty()) { + // At this spot, we know we are the final async task being executed! + // Because we have the lock, nothing else is running or will run because delay < 0 + runners.remove(getTaskId()); + } + } + } + } + } + + LinkedList getWorkers() { + return workers; + } + + boolean cancel0() { + synchronized (workers) { + // Synchronizing here prevents race condition for a completing task + setPeriod(-2L); + if (workers.isEmpty()) { + runners.remove(getTaskId()); + } + } + return true; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/scheduler/CraftFuture.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/scheduler/CraftFuture.java new file mode 100644 index 0000000..ef5052b --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/scheduler/CraftFuture.java @@ -0,0 +1,103 @@ +package org.bukkit.craftbukkit.scheduler; + +import org.bukkit.plugin.Plugin; + +import java.util.concurrent.*; + +class CraftFuture extends CraftTask implements Future { + + private final Callable callable; + private T value; + private Exception exception = null; + + CraftFuture(final Callable callable, final Plugin plugin, final int id) { + super(plugin, null, id, -1L); + this.callable = callable; + } + + public synchronized boolean cancel(final boolean mayInterruptIfRunning) { + if (getPeriod() != -1L) { + return false; + } + setPeriod(-2L); + return true; + } + + public boolean isCancelled() { + return getPeriod() == -2L; + } + + public boolean isDone() { + final long period = this.getPeriod(); + return period != -1L && period != -3L; + } + + public T get() throws CancellationException, InterruptedException, ExecutionException { + try { + return get(0, TimeUnit.MILLISECONDS); + } catch (final TimeoutException e) { + throw new Error(e); + } + } + + public synchronized T get(long timeout, final TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { + timeout = unit.toMillis(timeout); + long period = this.getPeriod(); + long timestamp = timeout > 0 ? System.currentTimeMillis() : 0L; + while (true) { + if (period == -1L || period == -3L) { + this.wait(timeout); + period = this.getPeriod(); + if (period == -1L || period == -3L) { + if (timeout == 0L) { + continue; + } + timeout += timestamp - (timestamp = System.currentTimeMillis()); + if (timeout > 0) { + continue; + } + throw new TimeoutException(); + } + } + if (period == -2L) { + throw new CancellationException(); + } + if (period == -4L) { + if (exception == null) { + return value; + } + throw new ExecutionException(exception); + } + throw new IllegalStateException("Expected " + -1L + " to " + -4L + ", got " + period); + } + } + + @Override + public void run() { + synchronized (this) { + if (getPeriod() == -2L) { + return; + } + setPeriod(-3L); + } + try { + value = callable.call(); + } catch (final Exception e) { + exception = e; + } finally { + synchronized (this) { + setPeriod(-4L); + this.notifyAll(); + } + } + } + + synchronized boolean cancel0() { + if (getPeriod() != -1L) { + return false; + } + setPeriod(-2L); + notifyAll(); + return true; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/scheduler/CraftScheduler.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/scheduler/CraftScheduler.java new file mode 100644 index 0000000..bfc188c --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/scheduler/CraftScheduler.java @@ -0,0 +1,564 @@ +package org.bukkit.craftbukkit.scheduler; + +import com.google.common.util.concurrent.ThreadFactoryBuilder; +import org.apache.commons.lang.Validate; +import org.bukkit.plugin.IllegalPluginAccessException; +import org.bukkit.plugin.Plugin; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.scheduler.BukkitScheduler; +import org.bukkit.scheduler.BukkitTask; +import org.bukkit.scheduler.BukkitWorker; +import org.github.paperspigot.event.ServerExceptionEvent; +import org.github.paperspigot.exception.ServerSchedulerException; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.PriorityQueue; +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.logging.Level; + +/** + * The fundamental concepts for this implementation: + *

  • Main thread owns {@link #head} and {@link #currentTick}, but it may be read from any thread
  • + *
  • Main thread exclusively controls {@link #temp} and {@link #pending}. + * They are never to be accessed outside of the main thread; alternatives exist to prevent locking.
  • + *
  • {@link #head} to {@link #tail} act as a linked list/queue, with 1 consumer and infinite producers. + * Adding to the tail is atomic and very efficient; utility method is {@link #handle(CraftTask, long)} or {@link #addTask(CraftTask)}.
  • + *
  • Changing the period on a task is delicate. + * Any future task needs to notify waiting threads. + * Async tasks must be synchronized to make sure that any thread that's finishing will remove itself from {@link #runners}. + * Another utility method is provided for this,
  • + *
  • {@link #runners} provides a moderately up-to-date view of active tasks. + * If the linked head to tail set is read, all remaining tasks that were active at the time execution started will be located in runners.
  • + *
  • Async tasks are responsible for removing themselves from runners
  • + *
  • Sync tasks are only to be removed from runners on the main thread when coupled with a removal from pending and temp.
  • + *
  • Most of the design in this scheduler relies on queuing special tasks to perform any data changes on the main thread. + * When executed from inside a synchronous method, the scheduler will be updated before next execution by virtue of the frequent {@link #parsePending()} calls.
  • + */ +public class CraftScheduler implements BukkitScheduler { + + /** + * Counter for IDs. Order doesn't matter, only uniqueness. + */ + private final AtomicInteger ids = new AtomicInteger(1); + /** + * Current head of linked-list. This reference is always stale, is the live reference. + */ + private volatile CraftTask head = new CraftTask(); + /** + * Tail of a linked-list. AtomicReference only matters when adding to queue + */ + private final AtomicReference tail = new AtomicReference<>(head); + /** + * Main thread logic only + */ + final PriorityQueue pending = new PriorityQueue<>(10, // Paper + (o1, o2) -> (int) (o1.getNextRun() - o2.getNextRun())); + /** + * Main thread logic only + */ + private final List temp = new ArrayList<>(); + /** + * These are tasks that are currently active. It's provided for 'viewing' the current state. + */ + final ConcurrentHashMap runners = new ConcurrentHashMap<>(); // Paper + /** + * The sync task that is currently running on the main thread. + */ + private volatile CraftTask currentTask = null; + + volatile int currentTick = -1; // Paper + + // Azurite - Fix support for some plugins using this. + protected final ThreadPoolExecutor executor = new ThreadPoolExecutor(4, Integer.MAX_VALUE, 30L, TimeUnit.SECONDS, new SynchronousQueue<>(), new ThreadFactoryBuilder() + .setNameFormat("Craft Scheduler Thread - %1$d") + .build()); + + // Paper start + private final CraftScheduler asyncScheduler; + private final boolean isAsyncScheduler; + + public CraftScheduler() { + this(false); + } + + public CraftScheduler(boolean isAsync) { + this.isAsyncScheduler = isAsync; + if (isAsync) { + this.asyncScheduler = this; + } else { + this.asyncScheduler = new CraftAsyncScheduler(); + } + } + // Paper end + + public int scheduleSyncDelayedTask(final Plugin plugin, final Runnable task) { + return this.scheduleSyncDelayedTask(plugin, task, 0L); + } + + public BukkitTask runTask(Plugin plugin, Runnable runnable) { + return runTaskLater(plugin, runnable, 0L); + } + + @Deprecated + public int scheduleAsyncDelayedTask(final Plugin plugin, final Runnable task) { + return this.scheduleAsyncDelayedTask(plugin, task, 0L); + } + + public BukkitTask runTaskAsynchronously(Plugin plugin, Runnable runnable) { + return runTaskLaterAsynchronously(plugin, runnable, 0L); + } + + public int scheduleSyncDelayedTask(final Plugin plugin, final Runnable task, final long delay) { + return this.scheduleSyncRepeatingTask(plugin, task, delay, -1L); + } + + public BukkitTask runTaskLater(Plugin plugin, Runnable runnable, long delay) { + return runTaskTimer(plugin, runnable, delay, -1L); + } + + @Deprecated + public int scheduleAsyncDelayedTask(final Plugin plugin, final Runnable task, final long delay) { + return this.scheduleAsyncRepeatingTask(plugin, task, delay, -1L); + } + + public BukkitTask runTaskLaterAsynchronously(Plugin plugin, Runnable runnable, long delay) { + return runTaskTimerAsynchronously(plugin, runnable, delay, -1L); + } + + public int scheduleSyncRepeatingTask(final Plugin plugin, final Runnable runnable, long delay, long period) { + return runTaskTimer(plugin, runnable, delay, period).getTaskId(); + } + + public BukkitTask runTaskTimer(Plugin plugin, Runnable runnable, long delay, long period) { + validate(plugin, runnable); + if (delay < 0L) { + delay = 0; + } + if (period == 0L) { + period = 1L; + } else if (period < -1L) { + period = -1L; + } + return handle(new CraftTask(plugin, runnable, nextId(), period), delay); + } + + @Deprecated + public int scheduleAsyncRepeatingTask(final Plugin plugin, final Runnable runnable, long delay, long period) { + return runTaskTimerAsynchronously(plugin, runnable, delay, period).getTaskId(); + } + + public BukkitTask runTaskTimerAsynchronously(Plugin plugin, Runnable runnable, long delay, long period) { + validate(plugin, runnable); + if (delay < 0L) { + delay = 0; + } + if (period == 0L) { + period = 1L; + } else if (period < -1L) { + period = -1L; + } + return handle(new CraftAsyncTask(this.asyncScheduler.runners, plugin, runnable, nextId(), period), delay); // Paper + } + + public Future callSyncMethod(final Plugin plugin, final Callable task) { + validate(plugin, task); + final CraftFuture future = new CraftFuture<>(task, plugin, nextId()); + handle(future, 0L); + return future; + } + + public void cancelTask(final int taskId) { + if (taskId <= 0) { + return; + } + // Paper start + if (!this.isAsyncScheduler) { + this.asyncScheduler.cancelTask(taskId); + } + // Paper end + CraftTask task = runners.get(taskId); + if (task != null) { + task.cancel0(); + } + task = new CraftTask( + new Runnable() { + public void run() { + if (!check(CraftScheduler.this.temp)) { + check(CraftScheduler.this.pending); + } + } + + private boolean check(final Iterable collection) { + final Iterator tasks = collection.iterator(); + while (tasks.hasNext()) { + final CraftTask task = tasks.next(); + if (task.getTaskId() == taskId) { + task.cancel0(); + tasks.remove(); + if (task.isSync()) { + runners.remove(taskId); + } + return true; + } + } + return false; + } + }); // Spigot + handle(task, 0L); + for (CraftTask taskPending = head.getNext(); taskPending != null; taskPending = taskPending.getNext()) { + if (taskPending == task) { + return; + } + if (taskPending.getTaskId() == taskId) { + taskPending.cancel0(); + } + } + } + + public void cancelTasks(final Plugin plugin) { + Validate.notNull(plugin, "Cannot cancel tasks of null plugin"); + // Paper start + if (!this.isAsyncScheduler) { + this.asyncScheduler.cancelTasks(plugin); + } + // Paper end + final CraftTask task = new CraftTask( + new Runnable() { + public void run() { + check(CraftScheduler.this.pending); + check(CraftScheduler.this.temp); + } + + void check(final Iterable collection) { + final Iterator tasks = collection.iterator(); + while (tasks.hasNext()) { + final CraftTask task = tasks.next(); + if (task.getOwner().equals(plugin)) { + task.cancel0(); + tasks.remove(); + if (task.isSync()) { + runners.remove(task.getTaskId()); + } + } + } + } + }); // Spigot + handle(task, 0L); + for (CraftTask taskPending = head.getNext(); taskPending != null; taskPending = taskPending.getNext()) { + if (taskPending == task) { + return; + } + if (taskPending.getTaskId() != -1 && taskPending.getOwner().equals(plugin)) { + taskPending.cancel0(); + } + } + for (CraftTask runner : runners.values()) { + if (runner.getOwner().equals(plugin)) { + runner.cancel0(); + } + } + } + + public void cancelAllTasks() { + // Paper start + if (!isAsyncScheduler) { + this.asyncScheduler.cancelAllTasks(); + } + // Paper end + final CraftTask task = new CraftTask( + () -> { + Iterator it = CraftScheduler.this.runners.values().iterator(); + while (it.hasNext()) { + CraftTask task1 = it.next(); + task1.cancel0(); + if (task1.isSync()) { + it.remove(); + } + } + CraftScheduler.this.pending.clear(); + CraftScheduler.this.temp.clear(); + }); // Spigot + handle(task, 0L); + for (CraftTask taskPending = head.getNext(); taskPending != null; taskPending = taskPending.getNext()) { + if (taskPending == task) { + break; + } + taskPending.cancel0(); + } + for (CraftTask runner : runners.values()) { + runner.cancel0(); + } + } + + public boolean isCurrentlyRunning(final int taskId) { + // Paper start + if (!isAsyncScheduler) { + if (this.asyncScheduler.isCurrentlyRunning(taskId)) { + return true; + } + } + // Paper end + final CraftTask task = runners.get(taskId); + if (task == null) { + return false; + } + if (task.isSync()) { + return (task == currentTask); + } + final CraftAsyncTask asyncTask = (CraftAsyncTask) task; + synchronized (asyncTask.getWorkers()) { + return !asyncTask.getWorkers().isEmpty(); + } + } + + public boolean isQueued(final int taskId) { + if (taskId <= 0) { + return false; + } + // Paper start + if (!this.isAsyncScheduler && this.asyncScheduler.isQueued(taskId)) { + return true; + } + // Paper end + for (CraftTask task = head.getNext(); task != null; task = task.getNext()) { + if (task.getTaskId() == taskId) { + return task.getPeriod() >= -1L; // The task will run + } + } + CraftTask task = runners.get(taskId); + return task != null && task.getPeriod() >= -1L; + } + + public List getActiveWorkers() { + // Paper start + if (!isAsyncScheduler) { + //noinspection TailRecursion + return this.asyncScheduler.getActiveWorkers(); + } + // Paper end + final ArrayList workers = new ArrayList<>(); + for (final CraftTask taskObj : runners.values()) { + // Iterator will be a best-effort (may fail to grab very new values) if called from an async thread + if (taskObj.isSync()) { + continue; + } + final CraftAsyncTask task = (CraftAsyncTask) taskObj; + synchronized (task.getWorkers()) { + // This will never have an issue with stale threads; it's state-safe + workers.addAll(task.getWorkers()); + } + } + return workers; + } + + public List getPendingTasks() { + final ArrayList truePending = new ArrayList<>(); + for (CraftTask task = head.getNext(); task != null; task = task.getNext()) { + if (task.getTaskId() != -1) { + // -1 is special code + truePending.add(task); + } + } + + final ArrayList pending = new ArrayList<>(); + for (CraftTask task : runners.values()) { + if (task.getPeriod() >= -1L) { + pending.add(task); + } + } + + for (final CraftTask task : truePending) { + if (task.getPeriod() >= -1L && !pending.contains(task)) { + pending.add(task); + } + } + // Paper start + if (!this.isAsyncScheduler) { + pending.addAll(this.asyncScheduler.getPendingTasks()); + } + // Paper end + return pending; + } + + /** + * This method is designed to never block or wait for locks; an immediate execution of all current tasks. + */ + public void mainThreadHeartbeat(final int currentTick) { + // Paper start + if (!this.isAsyncScheduler) { + this.asyncScheduler.mainThreadHeartbeat(currentTick); + } + // Paper end + this.currentTick = currentTick; + final List temp = this.temp; + parsePending(); + while (isReady(currentTick)) { + final CraftTask task = pending.remove(); + if (task.getPeriod() < -1L) { + if (task.isSync()) { + runners.remove(task.getTaskId(), task); + } + parsePending(); + continue; + } + if (task.isSync()) { + currentTask = task; + try { + task.run(); + } catch (final Throwable throwable) { + // Paper start + String msg = String.format( + "Task #%s for %s generated an exception", + task.getTaskId(), + task.getOwner().getDescription().getFullName()); + task.getOwner().getLogger().log( + Level.WARNING, + msg, + throwable); + task.getOwner().getServer().getPluginManager().callEvent( + new ServerExceptionEvent(new ServerSchedulerException(msg, throwable, task)) + ); + // Paper end + } finally { + currentTask = null; + } + parsePending(); + } else { + //debugTail = debugTail.setNext(new CraftAsyncDebugger(currentTick + RECENT_TICKS, task.getOwner(), task.getTaskClass())); // Paper + task.getOwner().getLogger().log(Level.SEVERE, "Unexpected Async Task in the Sync Scheduler. Report this to Paper"); // Paper + // We don't need to parse pending + // (async tasks must live with race-conditions if they attempt to cancel between these few lines of code) + } + final long period = task.getPeriod(); // State consistency + if (period > 0) { + task.setNextRun(currentTick + period); + temp.add(task); + } else if (task.isSync()) { + runners.remove(task.getTaskId()); + } + } + pending.addAll(temp); + temp.clear(); + } + + private void addTask(final CraftTask task) { + final AtomicReference tail = this.tail; + CraftTask tailTask = tail.get(); + while (!tail.compareAndSet(tailTask, task)) { + tailTask = tail.get(); + } + tailTask.setNext(task); + } + + protected CraftTask handle(final CraftTask task, final long delay) { + // Paper start + if (!this.isAsyncScheduler && !task.isSync()) { + this.asyncScheduler.handle(task, delay); + return task; + } + // Paper end + task.setNextRun(currentTick + delay); + addTask(task); + return task; + } + + private static void validate(final Plugin plugin, final Object task) { + Validate.notNull(plugin, "Plugin cannot be null"); + Validate.notNull(task, "Task cannot be null"); + if (!plugin.isEnabled()) { + throw new IllegalPluginAccessException("Plugin attempted to register task while disabled"); + } + } + + private int nextId() { + return ids.incrementAndGet(); + } + + void parsePending() { + CraftTask head = this.head; + CraftTask task = head.getNext(); + CraftTask lastTask = head; + for (; task != null; task = (lastTask = task).getNext()) { + if (task.getTaskId() == -1) { + task.run(); + } else if (task.getPeriod() >= -1L) { + pending.add(task); + runners.put(task.getTaskId(), task); + } + } + // We split this because of the way things are ordered for all of the async calls in CraftScheduler + // (it prevents race-conditions) + for (task = head; task != lastTask; task = head) { + head = task.getNext(); + task.setNext(null); + } + this.head = lastTask; + } + + private boolean isReady(final int currentTick) { + return !pending.isEmpty() && pending.peek().getNextRun() <= currentTick; + } + + @Override + public String toString() { + return ""; + } + + @Deprecated + @Override + public int scheduleSyncDelayedTask(Plugin plugin, BukkitRunnable task, long delay) { + return scheduleSyncDelayedTask(plugin, (Runnable) task, delay); + } + + @Deprecated + @Override + public int scheduleSyncDelayedTask(Plugin plugin, BukkitRunnable task) { + return scheduleSyncDelayedTask(plugin, (Runnable) task); + } + + @Deprecated + @Override + public int scheduleSyncRepeatingTask(Plugin plugin, BukkitRunnable task, long delay, long period) { + return scheduleSyncRepeatingTask(plugin, (Runnable) task, delay, period); + } + + @Deprecated + @Override + public BukkitTask runTask(Plugin plugin, BukkitRunnable task) throws IllegalArgumentException { + return runTask(plugin, (Runnable) task); + } + + @Deprecated + @Override + public BukkitTask runTaskAsynchronously(Plugin plugin, BukkitRunnable task) throws IllegalArgumentException { + return runTaskAsynchronously(plugin, (Runnable) task); + } + + @Deprecated + @Override + public BukkitTask runTaskLater(Plugin plugin, BukkitRunnable task, long delay) throws IllegalArgumentException { + return runTaskLater(plugin, (Runnable) task, delay); + } + + @Deprecated + @Override + public BukkitTask runTaskLaterAsynchronously(Plugin plugin, BukkitRunnable task, long delay) throws IllegalArgumentException { + return runTaskLaterAsynchronously(plugin, (Runnable) task, delay); + } + + @Deprecated + @Override + public BukkitTask runTaskTimer(Plugin plugin, BukkitRunnable task, long delay, long period) throws IllegalArgumentException { + return runTaskTimer(plugin, (Runnable) task, delay, period); + } + + @Deprecated + @Override + public BukkitTask runTaskTimerAsynchronously(Plugin plugin, BukkitRunnable task, long delay, long period) throws IllegalArgumentException { + return runTaskTimerAsynchronously(plugin, (Runnable) task, delay, period); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/scheduler/CraftTask.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/scheduler/CraftTask.java new file mode 100644 index 0000000..6b53702 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/scheduler/CraftTask.java @@ -0,0 +1,99 @@ +package org.bukkit.craftbukkit.scheduler; + +import org.bukkit.Bukkit; +import org.bukkit.plugin.Plugin; +import org.bukkit.scheduler.BukkitTask; + + +public class CraftTask implements BukkitTask, Runnable { // Spigot + + private volatile CraftTask next = null; + /** + * -1 means no repeating
    + * -2 means cancel
    + * -3 means processing for Future
    + * -4 means done for Future
    + * Never 0
    + * >0 means number of ticks to wait between each execution + */ + private volatile long period; + private long nextRun; + public final Runnable task; //Spigot + private final Plugin plugin; + private final int id; + + CraftTask() { + this(null, null, -1, -1); + } + + CraftTask(final Runnable task) { + this(null, task, -1, -1); + } + + // Spigot start + CraftTask(final Plugin plugin, final Runnable task, final int id, final long period) { + this.plugin = plugin; + this.task = task; + this.id = id; + this.period = period; + } + + public final int getTaskId() { + return id; + } + + public final Plugin getOwner() { + return plugin; + } + + public boolean isSync() { + return true; + } + + public void run() { + task.run(); + } + + long getPeriod() { + return period; + } + + void setPeriod(long period) { + this.period = period; + } + + long getNextRun() { + return nextRun; + } + + void setNextRun(long nextRun) { + this.nextRun = nextRun; + } + + CraftTask getNext() { + return next; + } + + void setNext(CraftTask next) { + this.next = next; + } + + Class getTaskClass() { + return task.getClass(); + } + + public void cancel() { + Bukkit.getScheduler().cancelTask(id); + } + + /** + * This method properly sets the status to cancelled, synchronizing when required. + * + * @return false if it is a craft future task that has already begun execution, true otherwise + */ + boolean cancel0() { + setPeriod(-2L); + return true; + } + +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftCriteria.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftCriteria.java new file mode 100644 index 0000000..60c647b --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftCriteria.java @@ -0,0 +1,64 @@ +package org.bukkit.craftbukkit.scoreboard; + +import com.google.common.collect.ImmutableMap; +import net.minecraft.server.IScoreboardCriteria; +import net.minecraft.server.ScoreboardObjective; + +import java.util.Map; + +final class CraftCriteria { + static final Map DEFAULTS; + static final CraftCriteria DUMMY; + + static { + ImmutableMap.Builder defaults = ImmutableMap.builder(); + + for (Map.Entry entry : ((Map ) IScoreboardCriteria.criteria).entrySet()) { + String name = entry.getKey().toString(); + IScoreboardCriteria criteria = (IScoreboardCriteria) entry.getValue(); + + defaults.put(name, new CraftCriteria(criteria)); + } + + DEFAULTS = defaults.build(); + DUMMY = DEFAULTS.get("dummy"); + } + + final IScoreboardCriteria criteria; + final String bukkitName; + + private CraftCriteria(String bukkitName) { + this.bukkitName = bukkitName; + this.criteria = DUMMY.criteria; + } + + private CraftCriteria(IScoreboardCriteria criteria) { + this.criteria = criteria; + this.bukkitName = criteria.getName(); + } + + static CraftCriteria getFromNMS(ScoreboardObjective objective) { + return DEFAULTS.get(objective.getCriteria().getName()); + } + + static CraftCriteria getFromBukkit(String name) { + final CraftCriteria criteria = DEFAULTS.get(name); + if (criteria != null) { + return criteria; + } + return new CraftCriteria(name); + } + + @Override + public boolean equals(Object that) { + if (!(that instanceof CraftCriteria)) { + return false; + } + return ((CraftCriteria) that).bukkitName.equals(this.bukkitName); + } + + @Override + public int hashCode() { + return this.bukkitName.hashCode() ^ CraftCriteria.class.hashCode(); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftObjective.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftObjective.java new file mode 100644 index 0000000..72772f9 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftObjective.java @@ -0,0 +1,137 @@ +package org.bukkit.craftbukkit.scoreboard; + +import net.minecraft.server.Scoreboard; +import net.minecraft.server.ScoreboardObjective; +import org.apache.commons.lang.Validate; +import org.bukkit.OfflinePlayer; +import org.bukkit.scoreboard.DisplaySlot; +import org.bukkit.scoreboard.Objective; +import org.bukkit.scoreboard.Score; + +import java.util.Objects; + +final class CraftObjective extends CraftScoreboardComponent implements Objective { + private final ScoreboardObjective objective; + private final CraftCriteria criteria; + + CraftObjective(CraftScoreboard scoreboard, ScoreboardObjective objective) { + super(scoreboard); + this.objective = objective; + this.criteria = CraftCriteria.getFromNMS(objective); + } + + ScoreboardObjective getHandle() { + return objective; + } + + public String getName() throws IllegalStateException { + checkState(); + + return objective.getName(); + } + + public String getDisplayName() throws IllegalStateException { + checkState(); + + return objective.getDisplayName(); + } + + public void setDisplayName(String displayName) throws IllegalStateException, IllegalArgumentException { + Validate.notNull(displayName, "Display name cannot be null"); + Validate.isTrue(displayName.length() <= 32, "Display name '" + displayName + "' is longer than the limit of 32 characters"); + checkState(); + + objective.setDisplayName(displayName); + } + + public String getCriteria() throws IllegalStateException { + checkState(); + + return criteria.bukkitName; + } + + public boolean isModifiable() throws IllegalStateException { + checkState(); + + return !criteria.criteria.isReadOnly(); + } + + public void setDisplaySlot(DisplaySlot slot) throws IllegalStateException { + CraftScoreboard scoreboard = checkState(); + Scoreboard board = scoreboard.board; + ScoreboardObjective objective = this.objective; + + for (int i = 0; i < CraftScoreboardTranslations.MAX_DISPLAY_SLOT; i++) { + if (board.getObjectiveForSlot(i) == objective) { + board.setDisplaySlot(i, null); + } + } + if (slot != null) { + int slotNumber = CraftScoreboardTranslations.fromBukkitSlot(slot); + board.setDisplaySlot(slotNumber, getHandle()); + } + } + + public DisplaySlot getDisplaySlot() throws IllegalStateException { + CraftScoreboard scoreboard = checkState(); + Scoreboard board = scoreboard.board; + ScoreboardObjective objective = this.objective; + + for (int i = 0; i < CraftScoreboardTranslations.MAX_DISPLAY_SLOT; i++) { + if (board.getObjectiveForSlot(i) == objective) { + return CraftScoreboardTranslations.toBukkitSlot(i); + } + } + return null; + } + + public Score getScore(OfflinePlayer player) throws IllegalArgumentException, IllegalStateException { + Validate.notNull(player, "Player cannot be null"); + checkState(); + + return new CraftScore(this, player.getName()); + } + + public Score getScore(String entry) throws IllegalArgumentException, IllegalStateException { + Validate.notNull(entry, "Entry cannot be null"); + if (entry.length() > 40) throw new IllegalArgumentException("Entry cannot be longer than 40 characters!"); // Spigot + checkState(); + + return new CraftScore(this, entry); + } + + @Override + public void unregister() throws IllegalStateException { + checkState().board.unregisterObjective(objective); + } + + @Override + CraftScoreboard checkState() throws IllegalStateException { + if (getScoreboard().board.getObjective(objective.getName()) == null) { + throw new IllegalStateException("Unregistered scoreboard component"); + } + + return getScoreboard(); + } + + @Override + public int hashCode() { + int hash = 7; + hash = 31 * hash + (this.objective != null ? this.objective.hashCode() : 0); + return hash; + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final CraftObjective other = (CraftObjective) obj; + return Objects.equals(this.objective, other.objective); + } + + +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScore.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScore.java new file mode 100644 index 0000000..9cde16d --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScore.java @@ -0,0 +1,70 @@ +package org.bukkit.craftbukkit.scoreboard; + +import net.minecraft.server.Scoreboard; +import net.minecraft.server.ScoreboardObjective; +import net.minecraft.server.ScoreboardScore; +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.scoreboard.Objective; +import org.bukkit.scoreboard.Score; + +import java.util.Map; + +/** + * TL;DR: This class is special and lazily grabs a handle... + * ...because a handle is a full fledged (I think permanent) hashMap for the associated name. + *

    + * Also, as an added perk, a CraftScore will (intentionally) stay a valid reference so long as objective is valid. + */ +final class CraftScore implements Score { + private final String entry; + private final CraftObjective objective; + + CraftScore(CraftObjective objective, String entry) { + this.objective = objective; + this.entry = entry; + } + + public OfflinePlayer getPlayer() { + return Bukkit.getOfflinePlayer(entry); + } + + public String getEntry() { + return entry; + } + + public Objective getObjective() { + return objective; + } + + public int getScore() throws IllegalStateException { + Scoreboard board = objective.checkState().board; + + if (board.getPlayers().contains(entry)) { // Lazy + Map scores = board.getPlayerObjectives(entry); + ScoreboardScore score = scores.get(objective.getHandle()); + if (score != null) { // Lazy + return score.getScore(); + } + } + + return 0; // Lazy + } + + public void setScore(int score) throws IllegalStateException { + objective.checkState().board.getPlayerScoreForObjective(entry, objective.getHandle()).setScore(score); + } + + public CraftScoreboard getScoreboard() { + return objective.getScoreboard(); + } + + // Spigot start + @Override + public boolean isScoreSet() throws IllegalStateException { + Scoreboard board = objective.checkState().board; + + return board.getPlayers().contains(entry) && board.getPlayerObjectives(entry).containsKey(objective.getHandle()); + } + // Spigot end +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboard.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboard.java new file mode 100644 index 0000000..667f5a7 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboard.java @@ -0,0 +1,155 @@ +package org.bukkit.craftbukkit.scoreboard; + +import com.google.common.base.Function; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Iterables; +import net.minecraft.server.Scoreboard; +import net.minecraft.server.ScoreboardObjective; +import net.minecraft.server.ScoreboardTeam; +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.scoreboard.DisplaySlot; +import org.bukkit.scoreboard.Objective; +import org.bukkit.scoreboard.Score; +import org.bukkit.scoreboard.Team; + +public final class CraftScoreboard implements org.bukkit.scoreboard.Scoreboard { + final Scoreboard board; + + CraftScoreboard(Scoreboard board) { + this.board = board; + } + + public CraftObjective registerNewObjective(String name, String criteria) throws IllegalArgumentException { + Validate.notNull(name, "Objective name cannot be null"); + Validate.notNull(criteria, "Criteria cannot be null"); + Validate.isTrue(name.length() <= 16, "The name '" + name + "' is longer than the limit of 16 characters"); + Validate.isTrue(board.getObjective(name) == null, "An objective of name '" + name + "' already exists"); + + CraftCriteria craftCriteria = CraftCriteria.getFromBukkit(criteria); + ScoreboardObjective objective = board.registerObjective(name, craftCriteria.criteria); + return new CraftObjective(this, objective); + } + + public Objective getObjective(String name) throws IllegalArgumentException { + Validate.notNull(name, "Name cannot be null"); + ScoreboardObjective nms = board.getObjective(name); + return nms == null ? null : new CraftObjective(this, nms); + } + + public ImmutableSet getObjectivesByCriteria(String criteria) throws IllegalArgumentException { + Validate.notNull(criteria, "Criteria cannot be null"); + + ImmutableSet.Builder objectives = ImmutableSet.builder(); + for (ScoreboardObjective netObjective : this.board.getObjectives()) { + CraftObjective objective = new CraftObjective(this, netObjective); + if (objective.getCriteria().equals(criteria)) { + objectives.add(objective); + } + } + return objectives.build(); + } + + public ImmutableSet getObjectives() { + return ImmutableSet.copyOf(Iterables.transform(this.board.getObjectives(), (Function) input -> new CraftObjective(CraftScoreboard.this, input))); + } + + public Objective getObjective(DisplaySlot slot) throws IllegalArgumentException { + Validate.notNull(slot, "Display slot cannot be null"); + ScoreboardObjective objective = board.getObjectiveForSlot(CraftScoreboardTranslations.fromBukkitSlot(slot)); + if (objective == null) { + return null; + } + return new CraftObjective(this, objective); + } + + public ImmutableSet getScores(OfflinePlayer player) throws IllegalArgumentException { + Validate.notNull(player, "OfflinePlayer cannot be null"); + + return getScores(player.getName()); + } + + public ImmutableSet getScores(String entry) throws IllegalArgumentException { + Validate.notNull(entry, "Entry cannot be null"); + + ImmutableSet.Builder scores = ImmutableSet.builder(); + for (ScoreboardObjective objective : this.board.getObjectives()) { + scores.add(new CraftScore(new CraftObjective(this, objective), entry)); + } + return scores.build(); + } + + public void resetScores(OfflinePlayer player) throws IllegalArgumentException { + Validate.notNull(player, "OfflinePlayer cannot be null"); + + resetScores(player.getName()); + } + + public void resetScores(String entry) throws IllegalArgumentException { + Validate.notNull(entry, "Entry cannot be null"); + + for (ScoreboardObjective objective : this.board.getObjectives()) { + board.resetPlayerScores(entry, objective); + } + } + + public Team getPlayerTeam(OfflinePlayer player) throws IllegalArgumentException { + Validate.notNull(player, "OfflinePlayer cannot be null"); + + ScoreboardTeam team = board.getPlayerTeam(player.getName()); + return team == null ? null : new CraftTeam(this, team); + } + + public Team getEntryTeam(String entry) throws IllegalArgumentException { + Validate.notNull(entry, "Entry cannot be null"); + + ScoreboardTeam team = board.getPlayerTeam(entry); + return team == null ? null : new CraftTeam(this, team); + } + + public Team getTeam(String teamName) throws IllegalArgumentException { + Validate.notNull(teamName, "Team name cannot be null"); + + ScoreboardTeam team = board.getTeam(teamName); + return team == null ? null : new CraftTeam(this, team); + } + + public ImmutableSet getTeams() { + return ImmutableSet.copyOf(Iterables.transform(this.board.getTeams(), (Function) input -> new CraftTeam(CraftScoreboard.this, input))); + } + + public Team registerNewTeam(String name) throws IllegalArgumentException { + Validate.notNull(name, "Team name cannot be null"); + Validate.isTrue(name.length() <= 16, "Team name '" + name + "' is longer than the limit of 16 characters"); + Validate.isTrue(board.getTeam(name) == null, "Team name '" + name + "' is already in use"); + + return new CraftTeam(this, board.createTeam(name)); + } + + public ImmutableSet getPlayers() { + ImmutableSet.Builder players = ImmutableSet.builder(); + for (Object playerName : board.getPlayers()) { + players.add(Bukkit.getOfflinePlayer(playerName.toString())); + } + return players.build(); + } + + public ImmutableSet getEntries() { + ImmutableSet.Builder entries = ImmutableSet.builder(); + for (Object entry : board.getPlayers()) { + entries.add(entry.toString()); + } + return entries.build(); + } + + public void clearSlot(DisplaySlot slot) throws IllegalArgumentException { + Validate.notNull(slot, "Slot cannot be null"); + board.setDisplaySlot(CraftScoreboardTranslations.fromBukkitSlot(slot), null); + } + + // CraftBukkit method + public Scoreboard getHandle() { + return board; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboardComponent.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboardComponent.java new file mode 100644 index 0000000..a1cde14 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboardComponent.java @@ -0,0 +1,17 @@ +package org.bukkit.craftbukkit.scoreboard; + +abstract class CraftScoreboardComponent { + private final CraftScoreboard scoreboard; + + CraftScoreboardComponent(CraftScoreboard scoreboard) { + this.scoreboard = scoreboard; + } + + abstract CraftScoreboard checkState() throws IllegalStateException; + + public CraftScoreboard getScoreboard() { + return scoreboard; + } + + abstract void unregister() throws IllegalStateException; +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboardManager.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboardManager.java new file mode 100644 index 0000000..904e5e7 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboardManager.java @@ -0,0 +1,107 @@ +package org.bukkit.craftbukkit.scoreboard; + +import net.minecraft.server.*; +import org.apache.commons.lang.Validate; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.craftbukkit.util.WeakCollection; +import org.bukkit.entity.Player; +import org.bukkit.scoreboard.ScoreboardManager; + +import java.util.*; + +public final class CraftScoreboardManager implements ScoreboardManager { + private final CraftScoreboard mainScoreboard; + private final MinecraftServer server; + private final Collection scoreboards = new WeakCollection<>(); + private final Map playerBoards = new HashMap<>(); + + public CraftScoreboardManager(MinecraftServer minecraftserver, net.minecraft.server.Scoreboard scoreboardServer) { + mainScoreboard = new CraftScoreboard(scoreboardServer); + server = minecraftserver; + scoreboards.add(mainScoreboard); + } + + public CraftScoreboard getMainScoreboard() { + return mainScoreboard; + } + + public CraftScoreboard getNewScoreboard() { + org.spigotmc.AsyncCatcher.catchOp( "scoreboard creation"); // Spigot + CraftScoreboard scoreboard = new CraftScoreboard(new ScoreboardServer(server)); + scoreboards.add(scoreboard); + return scoreboard; + } + + // CraftBukkit method + public CraftScoreboard getPlayerBoard(CraftPlayer player) { + CraftScoreboard board = playerBoards.get(player); + return board == null ? getMainScoreboard() : board; + } + + // CraftBukkit method + public void setPlayerBoard(CraftPlayer player, org.bukkit.scoreboard.Scoreboard bukkitScoreboard) throws IllegalArgumentException { + Validate.isTrue(bukkitScoreboard instanceof CraftScoreboard, "Cannot set player scoreboard to an unregistered Scoreboard"); + + CraftScoreboard scoreboard = (CraftScoreboard) bukkitScoreboard; + net.minecraft.server.Scoreboard oldboard = getPlayerBoard(player).getHandle(); + net.minecraft.server.Scoreboard newboard = scoreboard.getHandle(); + EntityPlayer entityplayer = player.getHandle(); + + if (oldboard == newboard) { + return; + } + + if (oldboard != null) oldboard.removeViewer(entityplayer); + + if (scoreboard == mainScoreboard) { + playerBoards.remove(player); + } else { + playerBoards.put(player, scoreboard); + } + + // Old objective tracking + HashSet removed = new HashSet<>(); + for (int i = 0; i < 3; ++i) { + ScoreboardObjective scoreboardobjective = oldboard.getObjectiveForSlot(i); + if (scoreboardobjective != null && !removed.contains(scoreboardobjective)) { + entityplayer.playerConnection.sendPacket(new PacketPlayOutScoreboardObjective(scoreboardobjective, 1)); + removed.add(scoreboardobjective); + } + } + + // Old team tracking + for (ScoreboardTeam scoreboardteam : oldboard.getTeams()) { + entityplayer.playerConnection.sendPacket(new PacketPlayOutScoreboardTeam(scoreboardteam, 1)); + } + + // The above is the reverse of the below method. + server.getPlayerList().sendScoreboard((ScoreboardServer) newboard, player.getHandle()); + } + + // CraftBukkit method + public void removePlayer(Player player) { + CraftPlayer craftPlayer = (CraftPlayer) player; + CraftScoreboard scoreboard = playerBoards.remove(craftPlayer); + if (scoreboard != null) { + scoreboard.getHandle().removeViewer(craftPlayer.getHandle()); + } + } + + // CraftBukkit method + public Collection getScoreboardScores(IScoreboardCriteria criteria, String name, Collection collection) { + for (CraftScoreboard scoreboard : scoreboards) { + Scoreboard board = scoreboard.board; + for (ScoreboardObjective objective : board.getObjectivesForCriteria(criteria)) { + collection.add(board.getPlayerScoreForObjective(name, objective)); + } + } + return collection; + } + + // CraftBukkit method + public void updateAllScoresForList(IScoreboardCriteria criteria, String name, List of) { + for (ScoreboardScore score : getScoreboardScores(criteria, name, new ArrayList<>())) { + score.updateForList((List) of); + } + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboardTranslations.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboardTranslations.java new file mode 100644 index 0000000..9802064 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboardTranslations.java @@ -0,0 +1,24 @@ +package org.bukkit.craftbukkit.scoreboard; + +import com.google.common.collect.ImmutableBiMap; +import net.minecraft.server.Scoreboard; +import org.bukkit.scoreboard.DisplaySlot; + +class CraftScoreboardTranslations { + static final int MAX_DISPLAY_SLOT = 3; + static ImmutableBiMap SLOTS = ImmutableBiMap.of( + DisplaySlot.BELOW_NAME, "belowName", + DisplaySlot.PLAYER_LIST, "list", + DisplaySlot.SIDEBAR, "sidebar"); + + private CraftScoreboardTranslations() {} + + static DisplaySlot toBukkitSlot(int i) { + return SLOTS.inverse().get(Scoreboard.getSlotName(i)); + } + + static int fromBukkitSlot(DisplaySlot slot) { + return Scoreboard.getSlotForName(SLOTS.get(slot)); + } + +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftTeam.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftTeam.java new file mode 100644 index 0000000..3a459b0 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftTeam.java @@ -0,0 +1,239 @@ +package org.bukkit.craftbukkit.scoreboard; + +import com.google.common.collect.ImmutableSet; +import net.minecraft.server.ScoreboardTeam; +import net.minecraft.server.ScoreboardTeamBase.EnumNameTagVisibility; +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.scoreboard.NameTagVisibility; +import org.bukkit.scoreboard.Team; + +import java.util.Objects; +import java.util.Set; + +final class CraftTeam extends CraftScoreboardComponent implements Team { + private final ScoreboardTeam team; + + CraftTeam(CraftScoreboard scoreboard, ScoreboardTeam team) { + super(scoreboard); + this.team = team; + } + + public String getName() throws IllegalStateException { + checkState(); + + return team.getName(); + } + + public String getDisplayName() throws IllegalStateException { + checkState(); + + return team.getDisplayName(); + } + + public void setDisplayName(String displayName) throws IllegalStateException { + Validate.notNull(displayName, "Display name cannot be null"); + Validate.isTrue(displayName.length() <= 32, "Display name '" + displayName + "' is longer than the limit of 32 characters"); + checkState(); + + team.setDisplayName(displayName); + } + + public String getPrefix() throws IllegalStateException { + checkState(); + + return team.getPrefix(); + } + + public void setPrefix(String prefix) throws IllegalStateException, IllegalArgumentException { + Validate.notNull(prefix, "Prefix cannot be null"); + Validate.isTrue(prefix.length() <= 32, "Prefix '" + prefix + "' is longer than the limit of 32 characters"); + checkState(); + + team.setPrefix(prefix); + } + + public String getSuffix() throws IllegalStateException { + checkState(); + + return team.getSuffix(); + } + + public void setSuffix(String suffix) throws IllegalStateException, IllegalArgumentException { + Validate.notNull(suffix, "Suffix cannot be null"); + Validate.isTrue(suffix.length() <= 32, "Suffix '" + suffix + "' is longer than the limit of 32 characters"); + checkState(); + + team.setSuffix(suffix); + } + + public boolean allowFriendlyFire() throws IllegalStateException { + checkState(); + + return team.allowFriendlyFire(); + } + + public void setAllowFriendlyFire(boolean enabled) throws IllegalStateException { + checkState(); + + team.setAllowFriendlyFire(enabled); + } + + public boolean canSeeFriendlyInvisibles() throws IllegalStateException { + checkState(); + + return team.canSeeFriendlyInvisibles(); + } + + public void setCanSeeFriendlyInvisibles(boolean enabled) throws IllegalStateException { + checkState(); + + team.setCanSeeFriendlyInvisibles(enabled); + } + + public NameTagVisibility getNameTagVisibility() throws IllegalArgumentException { + checkState(); + + return notchToBukkit(team.getNameTagVisibility()); + } + + public void setNameTagVisibility(NameTagVisibility visibility) throws IllegalArgumentException { + checkState(); + + team.setNameTagVisibility(bukkitToNotch(visibility)); + } + + public Set getPlayers() throws IllegalStateException { + checkState(); + + ImmutableSet.Builder players = ImmutableSet.builder(); + for (String playerName : team.getPlayerNameSet()) { + players.add(Bukkit.getOfflinePlayer(playerName)); + } + return players.build(); + } + + @Override + public Set getEntries() throws IllegalStateException { + checkState(); + + ImmutableSet.Builder entries = ImmutableSet.builder(); + for (String playerName: team.getPlayerNameSet()){ + entries.add(playerName); + } + return entries.build(); + } + + public int getSize() throws IllegalStateException { + checkState(); + + return team.getPlayerNameSet().size(); + } + + public void addPlayer(OfflinePlayer player) throws IllegalStateException, IllegalArgumentException { + Validate.notNull(player, "OfflinePlayer cannot be null"); + addEntry(player.getName()); + } + + public void addEntry(String entry) throws IllegalStateException, IllegalArgumentException { + Validate.notNull(entry, "Entry cannot be null"); + CraftScoreboard scoreboard = checkState(); + + scoreboard.board.addPlayerToTeam(entry, team.getName()); + } + + public boolean removePlayer(OfflinePlayer player) throws IllegalStateException, IllegalArgumentException { + Validate.notNull(player, "OfflinePlayer cannot be null"); + return removeEntry(player.getName()); + } + + public boolean removeEntry(String entry) throws IllegalStateException, IllegalArgumentException { + Validate.notNull(entry, "Entry cannot be null"); + CraftScoreboard scoreboard = checkState(); + + if (!team.getPlayerNameSet().contains(entry)) { + return false; + } + + scoreboard.board.removePlayerFromTeam(entry, team); + return true; + } + + public boolean hasPlayer(OfflinePlayer player) throws IllegalArgumentException, IllegalStateException { + Validate.notNull(player, "OfflinePlayer cannot be null"); + return hasEntry(player.getName()); + } + + public boolean hasEntry(String entry) throws IllegalArgumentException, IllegalStateException { + checkState(); + + return team.getPlayerNameSet().contains(entry); + } + + @Override + public void unregister() throws IllegalStateException { + CraftScoreboard scoreboard = checkState(); + + scoreboard.board.removeTeam(team); + } + + public static EnumNameTagVisibility bukkitToNotch(NameTagVisibility visibility) { + switch (visibility) { + case ALWAYS: + return EnumNameTagVisibility.ALWAYS; + case NEVER: + return EnumNameTagVisibility.NEVER; + case HIDE_FOR_OTHER_TEAMS: + return EnumNameTagVisibility.HIDE_FOR_OTHER_TEAMS; + case HIDE_FOR_OWN_TEAM: + return EnumNameTagVisibility.HIDE_FOR_OWN_TEAM; + default: + throw new IllegalArgumentException("Unknown visibility level " + visibility); + } + } + + public static NameTagVisibility notchToBukkit(EnumNameTagVisibility visibility) { + switch (visibility) { + case ALWAYS: + return NameTagVisibility.ALWAYS; + case NEVER: + return NameTagVisibility.NEVER; + case HIDE_FOR_OTHER_TEAMS: + return NameTagVisibility.HIDE_FOR_OTHER_TEAMS; + case HIDE_FOR_OWN_TEAM: + return NameTagVisibility.HIDE_FOR_OWN_TEAM; + default: + throw new IllegalArgumentException("Unknown visibility level " + visibility); + } + } + + @Override + CraftScoreboard checkState() throws IllegalStateException { + if (getScoreboard().board.getTeam(team.getName()) == null) { + throw new IllegalStateException("Unregistered scoreboard component"); + } + + return getScoreboard(); + } + + @Override + public int hashCode() { + int hash = 7; + hash = 43 * hash + (this.team != null ? this.team.hashCode() : 0); + return hash; + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final CraftTeam other = (CraftTeam) obj; + return Objects.equals(this.team, other.team); + } + +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/util/AsynchronousExecutor.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/util/AsynchronousExecutor.java new file mode 100644 index 0000000..aeda700 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/util/AsynchronousExecutor.java @@ -0,0 +1,346 @@ +package org.bukkit.craftbukkit.util; + +import org.apache.commons.lang.Validate; + +import java.util.*; +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; + +/** + * Executes tasks using a multi-stage process executor. Synchronous executions are via {@link AsynchronousExecutor#finishActive()} or the {@link AsynchronousExecutor#get(Object)} methods. + *

  • Stage 1 creates the object from a parameter, and is usually called asynchronously. + *
  • Stage 2 takes the parameter and object from stage 1 and does any synchronous processing to prepare it. + *
  • Stage 3 takes the parameter and object from stage 1, as well as a callback that was registered, and performs any synchronous calculations. + * + * @param

    The type of parameter you provide to make the object that will be created. It should implement {@link Object#hashCode()} and {@link Object#equals(Object)} if you want to get the value early. + * @param The type of object you provide. This is created in stage 1, and passed to stage 2, 3, and returned if get() is called. + * @param The type of callback you provide. You may register many of these to be passed to the provider in stage 3, one at a time. + * @param A type of exception you may throw and expect to be handled by the main thread + * @author Wesley Wolfe (c) 2012, 2014 + */ +public final class AsynchronousExecutor { + + public interface CallBackProvider extends ThreadFactory { + + /** + * Normally an asynchronous call, but can be synchronous + * + * @param parameter parameter object provided + * @return the created object + */ + T callStage1(P parameter) throws E; + + /** + * Synchronous call + * + * @param parameter parameter object provided + * @param object the previously created object + */ + void callStage2(P parameter, T object) throws E; + + /** + * Synchronous call, called multiple times, once per registered callback + * + * @param parameter parameter object provided + * @param object the previously created object + * @param callback the current callback to execute + */ + void callStage3(P parameter, T object, C callback) throws E; + } + + @SuppressWarnings("rawtypes") + static final AtomicIntegerFieldUpdater STATE_FIELD = AtomicIntegerFieldUpdater.newUpdater(AsynchronousExecutor.Task.class, "state"); + + @SuppressWarnings({ "unchecked", "rawtypes" }) + private static boolean set(AsynchronousExecutor.Task $this, int expected, int value) { + return STATE_FIELD.compareAndSet($this, expected, value); + } + + class Task implements Runnable { + static final int PENDING = 0x0; + static final int STAGE_1_ASYNC = PENDING + 1; + static final int STAGE_1_SYNC = STAGE_1_ASYNC + 1; + static final int STAGE_1_COMPLETE = STAGE_1_SYNC + 1; + static final int FINISHED = STAGE_1_COMPLETE + 1; + + volatile int state = PENDING; + final P parameter; + T object; + final List callbacks = new LinkedList<>(); + E t = null; + + Task(final P parameter) { + this.parameter = parameter; + } + + public void run() { + if (initAsync()) { + finished.add(this); + } + } + + boolean initAsync() { + if (set(this, PENDING, STAGE_1_ASYNC)) { + boolean ret = true; + + try { + init(); + } finally { + if (set(this, STAGE_1_ASYNC, STAGE_1_COMPLETE)) { + // No one is/will be waiting + } else { + // We know that the sync thread will be waiting + synchronized (this) { + if (state != STAGE_1_SYNC) { + // They beat us to the synchronized block + this.notifyAll(); + } else { + // We beat them to the synchronized block + } + state = STAGE_1_COMPLETE; // They're already synchronized, atomic locks are not needed + } + // We want to return false, because we know a synchronous task already handled the finish() + ret = false; // Don't return inside finally; VERY bad practice. + } + } + + return ret; + } else { + return false; + } + } + + void initSync() { + if (set(this, PENDING, STAGE_1_COMPLETE)) { + // If we succeed that variable switch, good as done + init(); + } else if (set(this, STAGE_1_ASYNC, STAGE_1_SYNC)) { + // Async thread is running, but this shouldn't be likely; we need to sync to wait on them because of it. + synchronized (this) { + if (set(this, STAGE_1_SYNC, PENDING)) { // They might NOT synchronized yet, atomic lock IS needed + // We are the first into the lock + while (state != STAGE_1_COMPLETE) { + try { + this.wait(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException("Unable to handle interruption on " + parameter, e); + } + } + } else { + // They beat us to the synchronized block + } + } + } else { + // Async thread is not pending, the more likely situation for a task not pending + } + } + + @SuppressWarnings("unchecked") + void init() { + try { + object = provider.callStage1(parameter); + } catch (final Throwable t) { + this.t = (E) t; + } + } + + @SuppressWarnings("unchecked") + T get() throws E { + initSync(); + if (callbacks.isEmpty()) { + // 'this' is a placeholder to prevent callbacks from being empty during finish call + // See get method below + callbacks.add((C) this); + } + finish(); + return object; + } + + void finish() throws E { + switch (state) { + default: + case PENDING: + case STAGE_1_ASYNC: + case STAGE_1_SYNC: + throw new IllegalStateException("Attempting to finish unprepared(" + state + ") task(" + parameter + ")"); + case STAGE_1_COMPLETE: + try { + if (t != null) { + throw t; + } + if (callbacks.isEmpty()) { + return; + } + + final CallBackProvider provider = AsynchronousExecutor.this.provider; + final P parameter = this.parameter; + final T object = this.object; + + provider.callStage2(parameter, object); + for (C callback : callbacks) { + if (callback == this) { + // 'this' is a placeholder to prevent callbacks from being empty on a get() call + // See get method above + continue; + } + provider.callStage3(parameter, object, callback); + } + } finally { + tasks.remove(parameter); + state = FINISHED; + } + case FINISHED: + } + } + + boolean drop() { + if (set(this, PENDING, FINISHED)) { + // If we succeed that variable switch, good as forgotten + tasks.remove(parameter); + return true; + } else { + // We need the async thread to finish normally to properly dispose of the task + return false; + } + } + } + + final CallBackProvider provider; + final Queue finished = new ConcurrentLinkedQueue<>(); + final Map tasks = new HashMap<>(); + final ThreadPoolExecutor pool; + + /** + * Uses a thread pool to pass executions to the provider. + * @see AsynchronousExecutor + */ + public AsynchronousExecutor(final CallBackProvider provider, final int coreSize) { + Validate.notNull(provider, "Provider cannot be null"); + this.provider = provider; + + // We have an unbound queue size so do not need a max thread size + pool = new ThreadPoolExecutor(coreSize, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), provider); + } + + /** + * Adds a callback to the parameter provided, adding parameter to the queue if needed. + *

    + * This should always be synchronous. + */ + public void add(P parameter, C callback) { + Task task = tasks.get(parameter); + if (task == null) { + tasks.put(parameter, task = new Task(parameter)); + pool.execute(task); + } + task.callbacks.add(callback); + } + + /** + * This removes a particular callback from the specified parameter. + *

    + * If no callbacks remain for a given parameter, then the {@link CallBackProvider CallBackProvider's} stages may be omitted from execution. + * Stage 3 will have no callbacks, stage 2 will be skipped unless a {@link #get(Object)} is used, and stage 1 will be avoided on a best-effort basis. + *

    + * Subsequent calls to {@link #getSkipQueue(Object)} will always work. + *

    + * Subsequent calls to {@link #get(Object)} might work. + *

    + * This should always be synchronous + * @return true if no further execution for the parameter is possible, such that, no exceptions will be thrown in {@link #finishActive()} for the parameter, and {@link #get(Object)} will throw an {@link IllegalStateException}, false otherwise + * @throws IllegalStateException if parameter is not in the queue anymore + * @throws IllegalStateException if the callback was not specified for given parameter + */ + public boolean drop(P parameter, C callback) throws IllegalStateException { + final Task task = tasks.get(parameter); + if (task == null) { + return true; + } + if (!task.callbacks.remove(callback)) { + throw new IllegalStateException("Unknown " + callback + " for " + parameter); + } + if (task.callbacks.isEmpty()) { + return task.drop(); + } + return false; + } + + /** + * This method attempts to skip the waiting period for said parameter. + *

    + * This should always be synchronous. + * @throws IllegalStateException if the parameter is not in the queue anymore, or sometimes if called from asynchronous thread + */ + public T get(P parameter) throws E, IllegalStateException { + final Task task = tasks.get(parameter); + if (task == null) { + throw new IllegalStateException("Unknown " + parameter); + } + return task.get(); + } + + /** + * Processes a parameter as if it was in the queue, without ever passing to another thread. + */ + public T getSkipQueue(P parameter) throws E { + return skipQueue(parameter); + } + + /** + * Processes a parameter as if it was in the queue, without ever passing to another thread. + */ + public T getSkipQueue(P parameter, C callback) throws E { + final T object = skipQueue(parameter); + provider.callStage3(parameter, object, callback); + return object; + } + + /** + * Processes a parameter as if it was in the queue, without ever passing to another thread. + */ + public T getSkipQueue(P parameter, C...callbacks) throws E { + final CallBackProvider provider = this.provider; + final T object = skipQueue(parameter); + for (C callback : callbacks) { + provider.callStage3(parameter, object, callback); + } + return object; + } + + /** + * Processes a parameter as if it was in the queue, without ever passing to another thread. + */ + public T getSkipQueue(P parameter, Iterable callbacks) throws E { + final CallBackProvider provider = this.provider; + final T object = skipQueue(parameter); + for (C callback : callbacks) { + provider.callStage3(parameter, object, callback); + } + return object; + } + + private T skipQueue(P parameter) throws E { + Task task = tasks.get(parameter); + if (task != null) { + return task.get(); + } + T object = provider.callStage1(parameter); + provider.callStage2(parameter, object); + return object; + } + + /** + * This is the 'heartbeat' that should be called synchronously to finish any pending tasks + */ + public void finishActive() throws E { + final Queue finished = this.finished; + while (!finished.isEmpty()) { + finished.poll().finish(); + } + } + + public void setActiveThreads(final int coreSize) { + pool.setMaximumPoolSize(coreSize); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/util/BlockStateListPopulator.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/util/BlockStateListPopulator.java new file mode 100644 index 0000000..af2c7be --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/util/BlockStateListPopulator.java @@ -0,0 +1,66 @@ +package org.bukkit.craftbukkit.util; + +import net.minecraft.server.Block; +import net.minecraft.server.BlockPosition; +import net.minecraft.server.IBlockData; +import org.bukkit.World; +import org.bukkit.block.BlockState; + +import java.util.ArrayList; +import java.util.List; + +public class BlockStateListPopulator { + private final World world; + private final List list; + + public BlockStateListPopulator(World world) { + this(world, new ArrayList<>()); + } + + public BlockStateListPopulator(World world, List list) { + this.world = world; + this.list = list; + } + + public void setTypeAndData(int x, int y, int z, Block block, int data, int light) { + BlockState state = world.getBlockAt( + x, y, z).getState(); + state.setTypeId(Block.getId(block)); + state.setRawData((byte) data); + list.add(state); + } + public void setTypeId(int x, int y, int z, int type) { + BlockState state = world.getBlockAt(x, y, z).getState(); + state.setTypeId(type); + list.add(state); + } + + public void setTypeUpdate(int x, int y, int z, Block block) { + this.setType(x, y, z, block); + } + + public void setTypeUpdate(BlockPosition position, IBlockData data) { + setTypeAndData(position.getX(), position.getY(), position.getZ(), data.getBlock(), data.getBlock().toLegacyData(data), 0); + + } + + public void setType(int x, int y, int z, Block block) { + BlockState state = world.getBlockAt(x, y, z).getState(); + state.setTypeId(Block.getId(block)); + list.add(state); + } + + public void updateList() { + for (BlockState state : list) { + state.update(true); + } + } + + public List getList() { + return list; + } + + public World getWorld() { + return world; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/util/CraftChatMessage.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/util/CraftChatMessage.java new file mode 100644 index 0000000..5052117 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/util/CraftChatMessage.java @@ -0,0 +1,250 @@ +package org.bukkit.craftbukkit.util; + +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableMap.Builder; +import net.minecraft.server.*; +import net.minecraft.server.ChatClickable.EnumClickAction; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public final class CraftChatMessage { + + private static final Pattern LINK_PATTERN = Pattern.compile("((?:(?:https?):\\/\\/)?(?:[-\\w_\\.]{2,}\\.[a-z]{2,4}.*?(?=[\\.\\?!,;:]?(?:[" + org.bukkit.ChatColor.COLOR_CHAR + " \\n]|$))))"); + private static class StringMessage { + private static final Map formatMap; + private static final Pattern INCREMENTAL_PATTERN = Pattern.compile("(" + org.bukkit.ChatColor.COLOR_CHAR + "[0-9a-fk-or])|(\\n)|((?:(?:https?):\\/\\/)?(?:[-\\w_\\.]{2,}\\.[a-z]{2,4}.*?(?=[\\.\\?!,;:]?(?:[" + org.bukkit.ChatColor.COLOR_CHAR + " \\n]|$))))", Pattern.CASE_INSENSITIVE); + + static { + Builder builder = ImmutableMap.builder(); + for (EnumChatFormat format : EnumChatFormat.values()) { + builder.put(Character.toLowerCase(format.toString().charAt(1)), format); + } + formatMap = builder.build(); + } + + private final List list = new ArrayList<>(); + private IChatBaseComponent currentChatComponent = new ChatComponentText(""); + private ChatModifier modifier = new ChatModifier(); + private final IChatBaseComponent[] output; + private int currentIndex; + private final String message; + + private StringMessage(String message, boolean keepNewlines) { + this.message = message; + if (message == null) { + output = new IChatBaseComponent[]{currentChatComponent}; + return; + } + list.add(currentChatComponent); + + Matcher matcher = INCREMENTAL_PATTERN.matcher(message); + String match; + while (matcher.find()) { + int groupId = 0; + while ((match = matcher.group(++groupId)) == null) { + // NOOP + } + appendNewComponent(matcher.start(groupId)); + switch (groupId) { + case 1: + EnumChatFormat format = formatMap.get(match.toLowerCase().charAt(1)); + if (format == EnumChatFormat.RESET) { + modifier = new ChatModifier(); + } else if (format.isFormat()) { + switch (format) { + case BOLD: + modifier.setBold(Boolean.TRUE); + break; + case ITALIC: + modifier.setItalic(Boolean.TRUE); + break; + case STRIKETHROUGH: + modifier.setStrikethrough(Boolean.TRUE); + break; + case UNDERLINE: + modifier.setUnderline(Boolean.TRUE); + break; + case OBFUSCATED: + modifier.setRandom(Boolean.TRUE); + break; + default: + throw new AssertionError("Unexpected message format"); + } + } else { // Color resets formatting + modifier = new ChatModifier().setColor(format); + } + break; + case 2: + if (keepNewlines) { + currentChatComponent.addSibling(new ChatComponentText("\n")); + } else { + currentChatComponent = null; + } + break; + case 3: + if (!(match.startsWith("http://") || match.startsWith("https://"))) { + match = "http://" + match; + } + modifier.setChatClickable(new ChatClickable(EnumClickAction.OPEN_URL, match)); + appendNewComponent(matcher.end(groupId)); + modifier.setChatClickable(null); + } + currentIndex = matcher.end(groupId); + } + + if (currentIndex < message.length()) { + appendNewComponent(message.length()); + } + + output = list.toArray(new IChatBaseComponent[0]); + } + + private void appendNewComponent(int index) { + if (index <= currentIndex) { + return; + } + IChatBaseComponent addition = new ChatComponentText(message.substring(currentIndex, index)).setChatModifier(modifier); + currentIndex = index; + modifier = modifier.clone(); + if (currentChatComponent == null) { + currentChatComponent = new ChatComponentText(""); + list.add(currentChatComponent); + } + currentChatComponent.addSibling(addition); + } + + private IChatBaseComponent[] getOutput() { + return output; + } + } + + public static IChatBaseComponent[] fromString(String message) { + return fromString(message, false); + } + + public static IChatBaseComponent[] fromString(String message, boolean keepNewlines) { + return new StringMessage(message, keepNewlines).getOutput(); + } + + public static String fromComponent(IChatBaseComponent component) { + return fromComponent(component, EnumChatFormat.BLACK); + } + + public static String fromComponent(IChatBaseComponent component, EnumChatFormat defaultColor) { + if (component == null) return ""; + StringBuilder out = new StringBuilder(); + + long start = System.currentTimeMillis(); + + for (IChatBaseComponent c : component) { + ChatModifier modi = c.getChatModifier(); + out.append(modi.getColor() == null ? defaultColor : modi.getColor()); + if (modi.isBold()) { + out.append(EnumChatFormat.BOLD); + } + if (modi.isItalic()) { + out.append(EnumChatFormat.ITALIC); + } + if (modi.isUnderlined()) { + out.append(EnumChatFormat.UNDERLINE); + } + if (modi.isStrikethrough()) { + out.append(EnumChatFormat.STRIKETHROUGH); + } + if (modi.isRandom()) { + out.append(EnumChatFormat.OBFUSCATED); + } + out.append(c.getText()); + + //Neutron client will send a page will a long line of text, this will just escape it if + //we spend to long loading + if (System.currentTimeMillis() - start > 10L) { + System.out.println("The player below has tried to crash the server with long lines book exploit"); + } + } + return out.toString().replaceFirst("^(" + defaultColor + ")*", ""); + } + + public static IChatBaseComponent fixComponent(IChatBaseComponent component) { + Matcher matcher = LINK_PATTERN.matcher(""); + return fixComponent(component, matcher); + } + + private static IChatBaseComponent fixComponent(IChatBaseComponent component, Matcher matcher) { + if (component instanceof ChatComponentText) { + ChatComponentText text = ((ChatComponentText) component); + String msg = text.g(); + if (matcher.reset(msg).find()) { + matcher.reset(); + + ChatModifier modifier = text.getChatModifier() != null ? + text.getChatModifier() : new ChatModifier(); + List extras = new ArrayList<>(); + List extrasOld = new ArrayList<>(text.a()); + component = text = new ChatComponentText(""); + + int pos = 0; + while (matcher.find()) { + String match = matcher.group(); + + if (!(match.startsWith("http://") || match.startsWith("https://"))) { + match = "http://" + match; + } + + ChatComponentText prev = new ChatComponentText(msg.substring(pos, matcher.start())); + prev.setChatModifier(modifier); + extras.add(prev); + + ChatComponentText link = new ChatComponentText(matcher.group()); + ChatModifier linkModi = modifier.clone(); + linkModi.setChatClickable(new ChatClickable(EnumClickAction.OPEN_URL, match)); + link.setChatModifier(linkModi); + extras.add(link); + + pos = matcher.end(); + } + + ChatComponentText prev = new ChatComponentText(msg.substring(pos)); + prev.setChatModifier(modifier); + extras.add(prev); + extras.addAll(extrasOld); + + for (IChatBaseComponent c : extras) { + text.addSibling(c); + } + } + } + + List extras = component.a(); + for (int i = 0; i < extras.size(); i++) { + IChatBaseComponent comp = extras.get(i); + if (comp.getChatModifier() != null && comp.getChatModifier().h() == null) { + extras.set(i, fixComponent(comp, matcher)); + } + } + + if (component instanceof ChatMessage) { + Object[] subs = ((ChatMessage) component).j(); + for (int i = 0; i < subs.length; i++) { + Object comp = subs[i]; + if (comp instanceof IChatBaseComponent) { + IChatBaseComponent c = (IChatBaseComponent) comp; + if (c.getChatModifier() != null && c.getChatModifier().h() == null) { + subs[i] = fixComponent(c, matcher); + } + } else if (comp instanceof String && matcher.reset((String) comp).find()) { + subs[i] = fixComponent(new ChatComponentText((String) comp), matcher); + } + } + } + + return component; + } + + private CraftChatMessage() { + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/util/CraftDamageSource.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/util/CraftDamageSource.java new file mode 100644 index 0000000..a8e2b5e --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/util/CraftDamageSource.java @@ -0,0 +1,31 @@ +package org.bukkit.craftbukkit.util; + +import net.minecraft.server.DamageSource; + +// Util class to create custom DamageSources. +public final class CraftDamageSource extends DamageSource { + public static DamageSource copyOf(final DamageSource original) { + CraftDamageSource newSource = new CraftDamageSource(original.translationIndex); + + // Check ignoresArmor + if (original.ignoresArmor()) { + newSource.setIgnoreArmor(); + } + + // Check magic + if (original.isMagic()) { + newSource.setMagic(); + } + + // Check fire + if (original.isExplosion()) { + newSource.setExplosion(); + } + + return newSource; + } + + private CraftDamageSource(String identifier) { + super(identifier); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/util/CraftIconCache.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/util/CraftIconCache.java new file mode 100644 index 0000000..bd0b887 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/util/CraftIconCache.java @@ -0,0 +1,12 @@ +package org.bukkit.craftbukkit.util; + +import org.bukkit.util.CachedServerIcon; + +public class CraftIconCache implements CachedServerIcon { + public final String value; + + public String getData() { return value; } // Spigot + public CraftIconCache(final String value) { + this.value = value; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/util/CraftMagicNumbers.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/util/CraftMagicNumbers.java new file mode 100644 index 0000000..2b24cb0 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/util/CraftMagicNumbers.java @@ -0,0 +1,166 @@ +package org.bukkit.craftbukkit.util; + +import com.google.common.collect.Lists; +import net.minecraft.server.*; +import org.bukkit.Achievement; +import org.bukkit.Material; +import org.bukkit.Statistic; +import org.bukkit.UnsafeValues; +import org.bukkit.craftbukkit.CraftStatistic; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.StringUtil; + +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; + +@SuppressWarnings("deprecation") +public final class CraftMagicNumbers implements UnsafeValues { + public static final UnsafeValues INSTANCE = new CraftMagicNumbers(); + + private CraftMagicNumbers() {} + + public static Block getBlock(org.bukkit.block.Block block) { + return getBlock(block.getType()); + } + + @Deprecated + // A bad method for bad magic. + public static Block getBlock(int id) { + return getBlock(Material.getMaterial(id)); + } + + @Deprecated + // A bad method for bad magic. + public static int getId(Block block) { + return Block.getId(block); + } + + public static Material getMaterial(Block block) { + return Material.getMaterial(Block.getId(block)); + } + + public static Item getItem(Material material) { + // TODO: Don't use ID + Item item = Item.getById(material.getId()); + return item; + } + + @Deprecated + // A bad method for bad magic. + public static Item getItem(int id) { + return Item.getById(id); + } + + @Deprecated + // A bad method for bad magic. + public static int getId(Item item) { + return Item.getId(item); + } + + public static Material getMaterial(Item item) { + // TODO: Don't use ID + Material material = Material.getMaterial(Item.getId(item)); + + if (material == null) { + return Material.AIR; + } + + return material; + } + + public static Block getBlock(Material material) { + // TODO: Don't use ID + Block block = Block.getById(material.getId()); + + if (block == null) { + return Blocks.AIR; + } + + return block; + } + + @Override + public Material getMaterialFromInternalName(String name) { + return getMaterial(Item.REGISTRY.get(new MinecraftKey(name))); + } + + @Override + public List tabCompleteInternalMaterialName(String token, List completions) { + ArrayList results = Lists.newArrayList(); + for (MinecraftKey key : Item.REGISTRY.keySet()) { + results.add(key.toString()); + } + return StringUtil.copyPartialMatches(token, results, completions); + } + + @Override + public ItemStack modifyItemStack(ItemStack stack, String arguments) { + net.minecraft.server.ItemStack nmsStack = CraftItemStack.asNMSCopy(stack); + + try { + nmsStack.setTag(MojangsonParser.parse(arguments)); + } catch (MojangsonParseException ex) { + Logger.getLogger(CraftMagicNumbers.class.getName()).log(Level.SEVERE, null, ex); + } + + stack.setItemMeta(CraftItemStack.getItemMeta(nmsStack)); + + return stack; + } + + @Override + public Statistic getStatisticFromInternalName(String name) { + return CraftStatistic.getBukkitStatisticByName(name); + } + + @Override + public Achievement getAchievementFromInternalName(String name) { + return CraftStatistic.getBukkitAchievementByName(name); + } + + @Override + public List tabCompleteInternalStatisticOrAchievementName(String token, List completions) { + List matches = new ArrayList<>(); + for (net.minecraft.server.Statistic value : StatisticList.stats) { + String statistic = value.name; + if (statistic.startsWith(token)) { + matches.add(statistic); + } + } + return matches; + } + + + // PandaSpigot start + @Override + public byte[] serializeItem(ItemStack item) { + com.google.common.base.Preconditions.checkNotNull(item, "null cannot be serialized"); + com.google.common.base.Preconditions.checkArgument(item.getType() != Material.AIR, "air cannot be serialized"); + + java.io.ByteArrayOutputStream outputStream = new java.io.ByteArrayOutputStream(); + NBTTagCompound compound = (item instanceof CraftItemStack ? ((CraftItemStack) item).handle : CraftItemStack.asNMSCopy(item)).save(new NBTTagCompound()); + try { + net.minecraft.server.NBTCompressedStreamTools.writeNBT(compound, outputStream); + } catch (java.io.IOException ex) { + throw new RuntimeException(ex); + } + return outputStream.toByteArray(); + } + + @Override + public ItemStack deserializeItem(byte[] data) { + com.google.common.base.Preconditions.checkNotNull(data, "null cannot be deserialized"); + com.google.common.base.Preconditions.checkArgument(data.length > 0, "cannot deserialize nothing"); + + try { + NBTTagCompound compound = net.minecraft.server.NBTCompressedStreamTools.readNBT(new java.io.ByteArrayInputStream(data)); + return CraftItemStack.asCraftMirror(net.minecraft.server.ItemStack.createStack(compound)); + } catch (java.io.IOException ex) { + throw new RuntimeException(ex); + } + } + // PandaSpigot end +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/util/DatFileFilter.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/util/DatFileFilter.java new file mode 100644 index 0000000..712c44f --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/util/DatFileFilter.java @@ -0,0 +1,10 @@ +package org.bukkit.craftbukkit.util; + +import java.io.File; +import java.io.FilenameFilter; + +public class DatFileFilter implements FilenameFilter { + public boolean accept(File dir, String name) { + return name.endsWith(".dat"); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/util/ForwardLogHandler.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/util/ForwardLogHandler.java new file mode 100644 index 0000000..66adc00 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/util/ForwardLogHandler.java @@ -0,0 +1,52 @@ +package org.bukkit.craftbukkit.util; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.logging.ConsoleHandler; +import java.util.logging.Level; +import java.util.logging.LogRecord; + +public class ForwardLogHandler extends ConsoleHandler { + private final Map cachedLoggers = new ConcurrentHashMap<>(); + + private Logger getLogger(String name) { + Logger logger = cachedLoggers.get(name); + if (logger == null) { + logger = LogManager.getLogger(name); + cachedLoggers.put(name, logger); + } + + return logger; + } + + @Override + public void publish(LogRecord record) { + Logger logger = getLogger(String.valueOf(record.getLoggerName())); // See SPIGOT-1230 + Throwable exception = record.getThrown(); + Level level = record.getLevel(); + String message = getFormatter().formatMessage(record); + + if (level == Level.SEVERE) { + logger.error(message, exception); + } else if (level == Level.WARNING) { + logger.warn(message, exception); + } else if (level == Level.INFO) { + logger.info(message, exception); + } else if (level == Level.CONFIG) { + logger.debug(message, exception); + } else { + logger.trace(message, exception); + } + } + + @Override + public void flush() { + } + + @Override + public void close() throws SecurityException { + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/util/HashTreeSet.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/util/HashTreeSet.java new file mode 100644 index 0000000..af472cb --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/util/HashTreeSet.java @@ -0,0 +1,89 @@ +package org.bukkit.craftbukkit.util; + +import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; + +import java.util.Collection; +import java.util.Iterator; +import java.util.Set; +import java.util.TreeSet; + +public class HashTreeSet> { + + private final Set hash = new ObjectOpenHashSet<>(); // Paper - Replace java.util.HashSet with ObjectOpenHashSet + private final TreeSet tree = new TreeSet<>(); + + public HashTreeSet() { + } + + public int size() { + return hash.size(); + } + + public boolean isEmpty() { + return hash.isEmpty(); + } + + public boolean contains(V o) { + return hash.contains(o); + } + + public Iterator iterator() { + return new Iterator() { + + private final Iterator it = tree.iterator(); + private V last; + + @Override + public boolean hasNext() { + return it.hasNext(); + } + + @Override + public V next() { + return last = it.next(); + } + + @Override + public void remove() { + if (last == null) { + throw new IllegalStateException(); + } + it.remove(); + hash.remove(last); + last = null; + } + }; + } + + public Object[] toArray() { + return hash.toArray(); + } + + public Object[] toArray(Object[] a) { + return hash.toArray(a); + } + + public boolean add(V e) { + hash.add(e); + return tree.add(e); + } + + public boolean remove(V o) { + hash.remove(o); + return tree.remove(o); + } + + public boolean addAll(Collection c) { + tree.addAll(c); + return hash.addAll(c); + } + + public void clear() { + hash.clear(); + tree.clear(); + } + + public V first() { + return tree.first(); + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/util/LazyHashSet.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/util/LazyHashSet.java new file mode 100644 index 0000000..d106c0a --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/util/LazyHashSet.java @@ -0,0 +1,98 @@ +package org.bukkit.craftbukkit.util; + +import java.util.Collection; +import java.util.Iterator; +import java.util.Set; + + +public abstract class LazyHashSet implements Set { + Set reference = null; + + public int size() { + return getReference().size(); + } + + public boolean isEmpty() { + return getReference().isEmpty(); + } + + public boolean contains(Object o) { + return getReference().contains(o); + } + + public Iterator iterator() { + return getReference().iterator(); + } + + public Object[] toArray() { + return getReference().toArray(); + } + + public T[] toArray(T[] a) { + return getReference().toArray(a); + } + + public boolean add(E o) { + return getReference().add(o); + } + + public boolean remove(Object o) { + return getReference().remove(o); + } + + public boolean containsAll(Collection c) { + return getReference().containsAll(c); + } + + public boolean addAll(Collection c) { + return getReference().addAll(c); + } + + public boolean retainAll(Collection c) { + return getReference().retainAll(c); + } + + public boolean removeAll(Collection c) { + return getReference().removeAll(c); + } + + public void clear() { + getReference().clear(); + } + + public Set getReference() { + Set reference = this.reference ; + if (reference != null) { + return reference; + } + return this.reference = makeReference(); + } + + abstract Set makeReference(); + + public boolean isLazy() { + return reference == null; + } + + @Override + public int hashCode() { + return 157 * getReference().hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (obj == this) { + return true; + } + if (obj == null || this.getClass() != obj.getClass()) { + return false; + } + LazyHashSet that = (LazyHashSet) obj; + return (this.isLazy() && that.isLazy()) || this.getReference().equals(that.getReference()); + } + + @Override + public String toString() { + return getReference().toString(); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/util/LazyPlayerSet.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/util/LazyPlayerSet.java new file mode 100644 index 0000000..e4530ba --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/util/LazyPlayerSet.java @@ -0,0 +1,25 @@ +package org.bukkit.craftbukkit.util; + +import net.minecraft.server.EntityPlayer; +import net.minecraft.server.MinecraftServer; +import org.bukkit.entity.Player; + +import java.util.HashSet; +import java.util.List; + +public class LazyPlayerSet extends LazyHashSet { + + @Override + HashSet makeReference() { + if (reference != null) { + throw new IllegalStateException("Reference already created!"); + } + List players = MinecraftServer.getServer().getPlayerList().players; + HashSet reference = new HashSet<>(players.size()); + for (EntityPlayer player : players) { + reference.add(player.getBukkitEntity()); + } + return reference; + } + +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/util/LongHash.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/util/LongHash.java new file mode 100644 index 0000000..b53a2aa --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/util/LongHash.java @@ -0,0 +1,15 @@ +package org.bukkit.craftbukkit.util; + +public class LongHash { + public static long toLong(int msw, int lsw) { + return ((long) msw << 32) + lsw - Integer.MIN_VALUE; + } + + public static int msw(long l) { + return (int) (l >> 32); + } + + public static int lsw(long l) { + return (int) (l & 0xFFFFFFFFL) + Integer.MIN_VALUE; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/util/LongHashSet.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/util/LongHashSet.java new file mode 100644 index 0000000..9c6be8e --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/util/LongHashSet.java @@ -0,0 +1,300 @@ +/* + Based on CompactHashSet Copyright 2011 Ontopia Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package org.bukkit.craftbukkit.util; + +import java.util.Arrays; +import java.util.ConcurrentModificationException; +import java.util.Iterator; +import java.util.NoSuchElementException; + +public class LongHashSet { + private final static int INITIAL_SIZE = 3; + private final static double LOAD_FACTOR = 0.75; + + private final static long FREE = 0; + private final static long REMOVED = Long.MIN_VALUE; + + private int freeEntries; + private int elements; + private long[] values; + private int modCount; + + public LongHashSet() { + this(INITIAL_SIZE); + } + + public LongHashSet(int size) { + values = new long[(size==0 ? 1 : size)]; + elements = 0; + freeEntries = values.length; + modCount = 0; + } + + public Iterator iterator() { + return new Itr(); + } + + public int size() { + return elements; + } + + public boolean isEmpty() { + return elements == 0; + } + + public boolean contains(int msw, int lsw) { + return contains(LongHash.toLong(msw, lsw)); + } + + public boolean contains(long value) { + int hash = hash(value); + int index = (hash & 0x7FFFFFFF) % values.length; + int offset = 1; + + // search for the object (continue while !null and !this object) + while(values[index] != FREE && !(hash(values[index]) == hash && values[index] == value)) { + index = ((index + offset) & 0x7FFFFFFF) % values.length; + offset = offset * 2 + 1; + + if (offset == -1) { + offset = 2; + } + } + + return values[index] != FREE; + } + + public boolean add(int msw, int lsw) { + return add(LongHash.toLong(msw, lsw)); + } + + public boolean add(long value) { + int hash = hash(value); + int index = (hash & 0x7FFFFFFF) % values.length; + int offset = 1; + int deletedix = -1; + + // search for the object (continue while !null and !this object) + while(values[index] != FREE && !(hash(values[index]) == hash && values[index] == value)) { + // if there's a deleted object here we can put this object here, + // provided it's not in here somewhere else already + if (values[index] == REMOVED) { + deletedix = index; + } + + index = ((index + offset) & 0x7FFFFFFF) % values.length; + offset = offset * 2 + 1; + + if (offset == -1) { + offset = 2; + } + } + + if (values[index] == FREE) { + if (deletedix != -1) { // reusing a deleted cell + index = deletedix; + } else { + freeEntries--; + } + + modCount++; + elements++; + values[index] = value; + + if (1 - (freeEntries / (double) values.length) > LOAD_FACTOR) { + rehash(); + } + + return true; + } else { + return false; + } + } + + public void remove(int msw, int lsw) { + remove(LongHash.toLong(msw, lsw)); + } + + public boolean remove(long value) { + int hash = hash(value); + int index = (hash & 0x7FFFFFFF) % values.length; + int offset = 1; + + // search for the object (continue while !null and !this object) + while(values[index] != FREE && !(hash(values[index]) == hash && values[index] == value)) { + index = ((index + offset) & 0x7FFFFFFF) % values.length; + offset = offset * 2 + 1; + + if (offset == -1) { + offset = 2; + } + } + + if (values[index] != FREE) { + values[index] = REMOVED; + modCount++; + elements--; + return true; + } else { + return false; + } + } + + public void clear() { + elements = 0; + Arrays.fill(values, FREE); + + freeEntries = values.length; + modCount++; + } + + public long[] toArray() { + long[] result = new long[elements]; + long[] values = Arrays.copyOf(this.values, this.values.length); + int pos = 0; + + for (long value : values) { + if (value != FREE && value != REMOVED) { + result[pos++] = value; + } + } + + return result; + } + + public long popFirst() { + for (long value : values) { + if (value != FREE && value != REMOVED) { + remove(value); + return value; + } + } + + return 0; + } + + public long[] popAll() { + long[] ret = toArray(); + clear(); + return ret; + } + + // This method copied from Murmur3, written by Austin Appleby released under Public Domain + private int hash(long value) { + value ^= value >>> 33; + value *= 0xff51afd7ed558ccdL; + value ^= value >>> 33; + value *= 0xc4ceb9fe1a85ec53L; + value ^= value >>> 33; + return (int) value; + } + + private void rehash() { + int gargagecells = values.length - (elements + freeEntries); + if (gargagecells / (double) values.length > 0.05) { + rehash(values.length); + } else { + rehash(values.length * 2 + 1); + } + } + + private void rehash(int newCapacity) { + long[] newValues = new long[newCapacity]; + + for (long value : values) { + if (value == FREE || value == REMOVED) { + continue; + } + + int hash = hash(value); + int index = (hash & 0x7FFFFFFF) % newCapacity; + int offset = 1; + + // search for the object + while (newValues[index] != FREE) { + index = ((index + offset) & 0x7FFFFFFF) % newCapacity; + offset = offset * 2 + 1; + + if (offset == -1) { + offset = 2; + } + } + + newValues[index] = value; + } + + values = newValues; + freeEntries = values.length - elements; + } + + private class Itr implements Iterator { + private int index; + private int lastReturned = -1; + private int expectedModCount; + + public Itr() { + for (index = 0; index < values.length && (values[index] == FREE || values[index] == REMOVED); index++) { + // This is just to drive the index forward to the first valid entry + } + expectedModCount = modCount; + } + + public boolean hasNext() { + return index != values.length; + } + + public Long next() { + if (modCount != expectedModCount) { + throw new ConcurrentModificationException(); + } + + int length = values.length; + if (index >= length) { + lastReturned = -2; + throw new NoSuchElementException(); + } + + lastReturned = index; + for (index += 1; index < length && (values[index] == FREE || values[index] == REMOVED); index++) { + // This is just to drive the index forward to the next valid entry + } + + if (values[lastReturned] == FREE) { + return FREE; + } else { + return values[lastReturned]; + } + } + + public void remove() { + if (modCount != expectedModCount) { + throw new ConcurrentModificationException(); + } + + if (lastReturned == -1 || lastReturned == -2) { + throw new IllegalStateException(); + } + + if (values[lastReturned] != FREE && values[lastReturned] != REMOVED) { + values[lastReturned] = REMOVED; + elements--; + modCount++; + expectedModCount = modCount; + } + } + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/util/LongObjectHashMap.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/util/LongObjectHashMap.java new file mode 100644 index 0000000..9bc9926 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/util/LongObjectHashMap.java @@ -0,0 +1,412 @@ +package org.bukkit.craftbukkit.util; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; +import java.util.*; + +@SuppressWarnings("unchecked") +public class LongObjectHashMap implements Cloneable, Serializable { + static final long serialVersionUID = 2841537710170573815L; + + private static final long EMPTY_KEY = Long.MIN_VALUE; + private static final int BUCKET_SIZE = 4096; + + private transient long[][] keys; + private transient V[][] values; + private transient int modCount; + private transient int size; + + public LongObjectHashMap() { + initialize(); + } + + public LongObjectHashMap(Map map) { + this(); + putAll(map); + } + + public int size() { + return size; + } + + public boolean isEmpty() { + return size == 0; + } + + public boolean containsKey(long key) { + return get(key) != null; + } + + public boolean containsValue(V value) { + for (V val : values()) { + if (val == value || val.equals(value)) { + return true; + } + } + + return false; + } + + public V get(long key) { + int index = (int) (keyIndex(key) & (BUCKET_SIZE - 1)); + long[] inner = keys[index]; + if (inner == null) return null; + + for (int i = 0; i < inner.length; i++) { + long innerKey = inner[i]; + if (innerKey == EMPTY_KEY) { + return null; + } else if (innerKey == key) { + return values[index][i]; + } + } + + return null; + } + + public V put(long key, V value) { + int index = (int) (keyIndex(key) & (BUCKET_SIZE - 1)); + long[] innerKeys = keys[index]; + V[] innerValues = values[index]; + modCount++; + + if (innerKeys == null) { + // need to make a new chain + keys[index] = innerKeys = new long[8]; + Arrays.fill(innerKeys, EMPTY_KEY); + values[index] = innerValues = (V[]) new Object[8]; + innerKeys[0] = key; + innerValues[0] = value; + } else { + int i; + for (i = 0; i < innerKeys.length; i++) { + // found an empty spot in the chain to put this + if (innerKeys[i] == EMPTY_KEY) { + size++; + innerKeys[i] = key; + innerValues[i] = value; + return null; + } + + // found an existing entry in the chain with this key, replace it + if (innerKeys[i] == key) { + V oldValue = innerValues[i]; + innerKeys[i] = key; + innerValues[i] = value; + return oldValue; + } + } + + // chain is full, resize it and add our new entry + keys[index] = innerKeys = Arrays.copyOf(innerKeys, i << 1); + Arrays.fill(innerKeys, i, innerKeys.length, EMPTY_KEY); + values[index] = innerValues = Arrays.copyOf(innerValues, i << 1); + innerKeys[i] = key; + innerValues[i] = value; + } + size++; + + return null; + } + + public V remove(long key) { + int index = (int) (keyIndex(key) & (BUCKET_SIZE - 1)); + long[] inner = keys[index]; + if (inner == null) { + return null; + } + + for (int i = 0; i < inner.length; i++) { + // hit the end of the chain, didn't find this entry + if (inner[i] == EMPTY_KEY) { + break; + } + + if (inner[i] == key) { + V value = values[index][i]; + + for (i++; i < inner.length; i++) { + if (inner[i] == EMPTY_KEY) { + break; + } + + inner[i - 1] = inner[i]; + values[index][i - 1] = values[index][i]; + } + + inner[i - 1] = EMPTY_KEY; + values[index][i - 1] = null; + size--; + modCount++; + return value; + } + } + + return null; + } + + public void putAll(Map map) { + for (Map.Entry entry : map.entrySet()) { + put((Long) entry.getKey(), (V) entry.getValue()); + } + } + + public void clear() { + if (size == 0) { + return; + } + + modCount++; + size = 0; + Arrays.fill(keys, null); + Arrays.fill(values, null); + } + + public Set keySet() { + return new KeySet(); + } + + public Collection values() { + return new ValueCollection(); + } + + /** + * Returns a Set of Entry objects for the HashMap. This is not how the internal + * implementation is laid out so this constructs the entire Set when called. For + * this reason it should be avoided if at all possible. + * + * @return Set of Entry objects + * @deprecated + */ + @Deprecated + public Set> entrySet() { + HashSet> set = new HashSet<>(); + for (long key : keySet()) { + set.add(new Entry(key, get(key))); + } + + return set; + } + + public Object clone() throws CloneNotSupportedException { + LongObjectHashMap clone = (LongObjectHashMap) super.clone(); + // Make sure we clear any existing information from the clone + clone.clear(); + // Make sure the clone is properly setup for new entries + clone.initialize(); + + // Iterate through the data normally to do a safe clone + for (long key : keySet()) { + final V value = get(key); + clone.put(key, value); + } + + return clone; + } + + private void initialize() { + keys = new long[BUCKET_SIZE][]; + values = (V[][]) new Object[BUCKET_SIZE][]; + } + + private long keyIndex(long key) { + key ^= key >>> 33; + key *= 0xff51afd7ed558ccdL; + key ^= key >>> 33; + key *= 0xc4ceb9fe1a85ec53L; + key ^= key >>> 33; + return key; + } + + private void writeObject(ObjectOutputStream outputStream) throws IOException { + outputStream.defaultWriteObject(); + + for (long key : keySet()) { + V value = get(key); + outputStream.writeLong(key); + outputStream.writeObject(value); + } + + outputStream.writeLong(EMPTY_KEY); + outputStream.writeObject(null); + } + + private void readObject(ObjectInputStream inputStream) throws ClassNotFoundException, IOException { + inputStream.defaultReadObject(); + initialize(); + + while (true) { + long key = inputStream.readLong(); + V value = (V) inputStream.readObject(); + if (key == EMPTY_KEY && value == null) { + break; + } + + put(key, value); + } + } + + + private class ValueIterator implements Iterator { + private int count; + private int index; + private int innerIndex; + private int expectedModCount; + private long lastReturned = EMPTY_KEY; + + long prevKey = EMPTY_KEY; + V prevValue; + + ValueIterator() { + expectedModCount = LongObjectHashMap.this.modCount; + } + + public boolean hasNext() { + return count < LongObjectHashMap.this.size; + } + + public void remove() { + if (LongObjectHashMap.this.modCount != expectedModCount) { + throw new ConcurrentModificationException(); + } + + if (lastReturned == EMPTY_KEY) { + throw new IllegalStateException(); + } + + count--; + LongObjectHashMap.this.remove(lastReturned); + lastReturned = EMPTY_KEY; + expectedModCount = LongObjectHashMap.this.modCount; + } + + public V next() { + if (LongObjectHashMap.this.modCount != expectedModCount) { + throw new ConcurrentModificationException(); + } + + if (!hasNext()) { + throw new NoSuchElementException(); + } + + long[][] keys = LongObjectHashMap.this.keys; + count++; + + if (prevKey != EMPTY_KEY) { + innerIndex++; + } + + for (; index < keys.length; index++) { + if (keys[index] != null) { + for (; innerIndex < keys[index].length; innerIndex++) { + long key = keys[index][innerIndex]; + V value = values[index][innerIndex]; + if (key == EMPTY_KEY) { + break; + } + + lastReturned = key; + prevKey = key; + prevValue = value; + return prevValue; + } + innerIndex = 0; + } + } + + throw new NoSuchElementException(); + } + } + + private class KeyIterator implements Iterator { + final ValueIterator iterator; + + public KeyIterator() { + iterator = new ValueIterator(); + } + + public void remove() { + iterator.remove(); + } + + public boolean hasNext() { + return iterator.hasNext(); + } + + public Long next() { + iterator.next(); + return iterator.prevKey; + } + } + + + private class KeySet extends AbstractSet { + public void clear() { + LongObjectHashMap.this.clear(); + } + + public int size() { + return LongObjectHashMap.this.size(); + } + + public boolean contains(Object key) { + return key instanceof Long && LongObjectHashMap.this.containsKey((Long) key); + + } + + public boolean remove(Object key) { + return LongObjectHashMap.this.remove((Long) key) != null; + } + + public Iterator iterator() { + return new KeyIterator(); + } + } + + + private class ValueCollection extends AbstractCollection { + public void clear() { + LongObjectHashMap.this.clear(); + } + + public int size() { + return LongObjectHashMap.this.size(); + } + + public boolean contains(Object value) { + return LongObjectHashMap.this.containsValue((V) value); + } + + public Iterator iterator() { + return new ValueIterator(); + } + } + + + private class Entry implements Map.Entry { + private final Long key; + private V value; + + Entry(long k, V v) { + key = k; + value = v; + } + + public Long getKey() { + return key; + } + + public V getValue() { + return value; + } + + public V setValue(V v) { + V old = value; + value = v; + put(key, v); + return old; + } + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/util/MojangNameLookup.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/util/MojangNameLookup.java new file mode 100644 index 0000000..a56c173 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/util/MojangNameLookup.java @@ -0,0 +1,63 @@ +package org.bukkit.craftbukkit.util; + +import com.google.common.base.Charsets; +import com.google.gson.Gson; +import org.apache.commons.io.IOUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLConnection; +import java.util.UUID; + +public class MojangNameLookup { + private static final Logger logger = LogManager.getFormatterLogger(MojangNameLookup.class); + + public static String lookupName(UUID id) { + if (id == null) { + return null; + } + + InputStream inputStream = null; + try { + URL url = new URL("https://sessionserver.mojang.com/session/minecraft/profile/" + id.toString().replace("-", "")); + URLConnection connection = url.openConnection(); + connection.setConnectTimeout(15000); + connection.setReadTimeout(15000); + connection.setUseCaches(false); + inputStream = connection.getInputStream(); + String result = IOUtils.toString(inputStream, Charsets.UTF_8); + Gson gson = new Gson(); + Response response = gson.fromJson(result, Response.class); + if (response == null || response.name == null) { + logger.warn("Failed to lookup name from UUID"); + return null; + } + + if (response.cause != null && response.cause.length() > 0) { + logger.warn("Failed to lookup name from UUID: %s", response.errorMessage); + return null; + } + + return response.name; + } catch (MalformedURLException ex) { + logger.warn("Malformed URL in UUID lookup"); + return null; + } catch (IOException ex) { + IOUtils.closeQuietly(inputStream); + } finally { + IOUtils.closeQuietly(inputStream); + } + + return null; + } + + private static class Response { + String errorMessage; + String cause; + String name; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/util/ServerShutdownThread.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/util/ServerShutdownThread.java new file mode 100644 index 0000000..bde4225 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/util/ServerShutdownThread.java @@ -0,0 +1,27 @@ +package org.bukkit.craftbukkit.util; + +import net.minecraft.server.ExceptionWorldConflict; +import net.minecraft.server.MinecraftServer; +import net.minecrell.terminalconsole.TerminalConsoleAppender; + +public class ServerShutdownThread extends Thread { + private final MinecraftServer server; + + public ServerShutdownThread(MinecraftServer server) { + this.server = server; + } + + @Override + public void run() { + try { + server.stop(); + } catch (ExceptionWorldConflict ex) { + ex.printStackTrace(); + } finally { + try { + TerminalConsoleAppender.close(); // Paper - Use TerminalConsoleAppender + } catch (Exception ignored) { + } + } + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/util/ShortConsoleLogFormatter.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/util/ShortConsoleLogFormatter.java new file mode 100644 index 0000000..3dda93f --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/util/ShortConsoleLogFormatter.java @@ -0,0 +1,62 @@ +package org.bukkit.craftbukkit.util; + +import joptsimple.OptionException; +import joptsimple.OptionSet; +import net.minecraft.server.MinecraftServer; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.text.SimpleDateFormat; +import java.util.logging.Formatter; +import java.util.logging.LogRecord; + +public class ShortConsoleLogFormatter extends Formatter { + private final SimpleDateFormat date; + + public ShortConsoleLogFormatter(MinecraftServer server) { + OptionSet options = server.options; + SimpleDateFormat date = null; + + if (options.has("date-format")) { + try { + Object object = options.valueOf("date-format"); + + if ((object instanceof SimpleDateFormat)) { + date = (SimpleDateFormat) object; + } + } catch (OptionException ex) { + System.err.println("Given date format is not valid. Falling back to default."); + } + } else if (options.has("nojline")) { + date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + } + + if (date == null) { + date = new SimpleDateFormat("HH:mm:ss"); + } + + this.date = date; + } + + @Override + public String format(LogRecord record) { + StringBuilder builder = new StringBuilder(); + Throwable ex = record.getThrown(); + + builder.append(date.format(record.getMillis())); + builder.append(" ["); + builder.append(record.getLevel().getLocalizedName().toUpperCase()); + builder.append("] "); + builder.append(formatMessage(record)); + builder.append('\n'); + + if (ex != null) { + StringWriter writer = new StringWriter(); + ex.printStackTrace(new PrintWriter(writer)); + builder.append(writer); + } + + return builder.toString(); + } + +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/util/StructureGrowDelegate.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/util/StructureGrowDelegate.java new file mode 100644 index 0000000..db06015 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/util/StructureGrowDelegate.java @@ -0,0 +1,69 @@ +package org.bukkit.craftbukkit.util; + +import net.minecraft.server.Block; +import net.minecraft.server.Blocks; +import net.minecraft.server.World; +import org.bukkit.BlockChangeDelegate; +import org.bukkit.block.BlockState; +import org.bukkit.craftbukkit.CraftWorld; +import org.bukkit.material.MaterialData; + +import java.util.ArrayList; +import java.util.List; + +public class StructureGrowDelegate implements BlockChangeDelegate { + private final CraftWorld world; + private final List blocks = new ArrayList<>(); + + public StructureGrowDelegate(World world) { + this.world = world.getWorld(); + } + + public boolean setRawTypeId(int x, int y, int z, int type) { + return setRawTypeIdAndData(x, y, z, type, 0); + } + + public boolean setRawTypeIdAndData(int x, int y, int z, int type, int data) { + BlockState state = world.getBlockAt(x, y, z).getState(); + state.setTypeId(type); + state.setData(new MaterialData(type, (byte) data)); + blocks.add(state); + return true; + } + + public boolean setTypeId(int x, int y, int z, int typeId) { + return setRawTypeId(x, y, z, typeId); + } + + public boolean setTypeIdAndData(int x, int y, int z, int typeId, int data) { + return setRawTypeIdAndData(x, y, z, typeId, data); + } + + public int getTypeId(int x, int y, int z) { + for (BlockState state : blocks) { + if (state.getX() == x && state.getY() == y && state.getZ() == z) { + return state.getTypeId(); + } + } + + return world.getBlockTypeIdAt(x, y, z); + } + + public int getHeight() { + return world.getMaxHeight(); + } + + public List getBlocks() { + return blocks; + } + + public boolean isEmpty(int x, int y, int z) { + for (BlockState state : blocks) { + if (state.getX() == x && state.getY() == y && state.getZ() == z) { + return Block.getById(state.getTypeId()) == Blocks.AIR; + } + } + + return world.getBlockAt(x, y, z).isEmpty(); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/util/UnsafeList.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/util/UnsafeList.java new file mode 100644 index 0000000..272baa2 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/util/UnsafeList.java @@ -0,0 +1,270 @@ +package org.bukkit.craftbukkit.util; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; +import java.util.*; + +// implementation of an ArrayList that offers a getter without range checks +@SuppressWarnings("unchecked") +public class UnsafeList extends AbstractList implements List, RandomAccess, Cloneable, Serializable { + private static final long serialVersionUID = 8683452581112892191L; + + private transient Object[] data; + private int size; + private int initialCapacity; + + private Iterator[] iterPool = new Iterator[1]; + private int maxPool; + private int poolCounter; + + public UnsafeList(int capacity, int maxIterPool) { + super(); + if (capacity < 0) capacity = 32; + int rounded = Integer.highestOneBit(capacity - 1) << 1; + data = new Object[rounded]; + initialCapacity = rounded; + maxPool = maxIterPool; + iterPool[0] = new Itr(); + } + + public UnsafeList(int capacity) { + this(capacity, 5); + } + + public UnsafeList() { + this(32); + } + + public E get(int index) { + rangeCheck(index); + + return (E) data[index]; + } + + public E unsafeGet(int index) { + return (E) data[index]; + } + + public E set(int index, E element) { + rangeCheck(index); + + E old = (E) data[index]; + data[index] = element; + return old; + } + + public boolean add(E element) { + growIfNeeded(); + data[size++] = element; + return true; + } + + public void add(int index, E element) { + growIfNeeded(); + System.arraycopy(data, index, data, index + 1, size - index); + data[index] = element; + size++; + } + + public E remove(int index) { + rangeCheck(index); + + E old = (E) data[index]; + int movedCount = size - index - 1; + if (movedCount > 0) { + System.arraycopy(data, index + 1, data, index, movedCount); + } + data[--size] = null; + + return old; + } + + public boolean remove(Object o) { + int index = indexOf(o); + if (index >= 0) { + remove(index); + return true; + } + + return false; + } + + public int indexOf(Object o) { + for (int i = 0; i < size; i++) { + if (o == data[i] || o.equals(data[i])) { + return i; + } + } + + return -1; + } + + public boolean contains(Object o) { + return indexOf(o) >= 0; + } + + public void clear() { + // Create new array to reset memory usage to initial capacity + size = 0; + + // If array has grown too large create new one, otherwise just clear it + if (data.length > initialCapacity << 3) { + data = new Object[initialCapacity]; + } else { + Arrays.fill(data, null); + } + } + + // actually rounds up to nearest power of two + public void trimToSize() { + int old = data.length; + int rounded = Integer.highestOneBit(size - 1) << 1; + if (rounded < old) { + data = Arrays.copyOf(data, rounded); + } + } + + public int size() { + return size; + } + + public boolean isEmpty() { + return size == 0; + } + + public Object clone() throws CloneNotSupportedException { + UnsafeList copy = (UnsafeList) super.clone(); + copy.data = Arrays.copyOf(data, size); + copy.size = size; + copy.initialCapacity = initialCapacity; + copy.iterPool = new Iterator[1]; + copy.iterPool[0] = new Itr(); + copy.maxPool = maxPool; + copy.poolCounter = 0; + return copy; + } + + public Iterator iterator() { + // Try to find an iterator that isn't in use + for (Iterator iter : iterPool) { + if (!((Itr) iter).valid) { + Itr iterator = (Itr) iter; + iterator.reset(); + return iterator; + } + } + + // Couldn't find one, see if we can grow our pool size + if (iterPool.length < maxPool) { + Iterator[] newPool = new Iterator[iterPool.length + 1]; + System.arraycopy(iterPool, 0, newPool, 0, iterPool.length); + iterPool = newPool; + + iterPool[iterPool.length - 1] = new Itr(); + return iterPool[iterPool.length - 1]; + } + + // Still couldn't find a free one, round robin replace one with a new iterator + // This is done in the hope that the new one finishes so can be reused + poolCounter = ++poolCounter % iterPool.length; + iterPool[poolCounter] = new Itr(); + return iterPool[poolCounter]; + } + + private void rangeCheck(int index) { + if (index >= size || index < 0) { + throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size); + } + } + + private void growIfNeeded() { + if (size == data.length) { + Object[] newData = new Object[data.length << 1]; + System.arraycopy(data, 0, newData, 0, size); + data = newData; + } + } + + private void writeObject(ObjectOutputStream os) throws IOException { + os.defaultWriteObject(); + + os.writeInt(size); + os.writeInt(initialCapacity); + for (int i = 0; i < size; i++) { + os.writeObject(data[i]); + } + os.writeInt(maxPool); + } + + private void readObject(ObjectInputStream is) throws IOException, ClassNotFoundException { + is.defaultReadObject(); + + size = is.readInt(); + initialCapacity = is.readInt(); + data = new Object[Integer.highestOneBit(size - 1) << 1]; + for (int i = 0; i < size; i++) { + data[i] = is.readObject(); + } + maxPool = is.readInt(); + iterPool = new Iterator[1]; + iterPool[0] = new Itr(); + } + + public class Itr implements Iterator { + int index; + int lastRet = -1; + int expectedModCount = modCount; + public boolean valid = true; + + public void reset() { + index = 0; + lastRet = -1; + expectedModCount = modCount; + valid = true; + } + + public boolean hasNext() { + valid = index != size; + return valid; + } + + public E next() { + if (modCount != expectedModCount) { + throw new ConcurrentModificationException(); + } + + int i = index; + if (i >= size) { + throw new NoSuchElementException(); + } + + if (i >= data.length) { + throw new ConcurrentModificationException(); + } + + index = i + 1; + return (E) data[lastRet = i]; + } + + public void remove() { + if (lastRet < 0) { + throw new IllegalStateException(); + } + + if (modCount != expectedModCount) { + throw new ConcurrentModificationException(); + } + + try { + UnsafeList.this.remove(lastRet); + index = lastRet; + lastRet = -1; + expectedModCount = modCount; + } catch (IndexOutOfBoundsException ex) { + throw new ConcurrentModificationException(); + } + } + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/util/Versioning.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/util/Versioning.java new file mode 100644 index 0000000..e42933d --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/util/Versioning.java @@ -0,0 +1,7 @@ +package org.bukkit.craftbukkit.util; + +public final class Versioning { + public static String getBukkitVersion() { + return "1.8.8-R0.1-SNAPSHOT"; // Vortex - optimized getting bukkit version. LunarClientAPI fix + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/util/Waitable.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/util/Waitable.java new file mode 100644 index 0000000..5cd1154 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/util/Waitable.java @@ -0,0 +1,46 @@ +package org.bukkit.craftbukkit.util; + +import java.util.concurrent.ExecutionException; + + +public abstract class Waitable implements Runnable { + private enum Status { + WAITING, + RUNNING, + FINISHED, + } + Throwable t = null; + T value = null; + Status status = Status.WAITING; + + public final void run() { + synchronized (this) { + if (status != Status.WAITING) { + throw new IllegalStateException("Invalid state " + status); + } + status = Status.RUNNING; + } + try { + value = evaluate(); + } catch (Throwable t) { + this.t = t; + } finally { + synchronized (this) { + status = Status.FINISHED; + this.notifyAll(); + } + } + } + + protected abstract T evaluate(); + + public synchronized T get() throws InterruptedException, ExecutionException { + while (status != Status.FINISHED) { + this.wait(); + } + if (t != null) { + throw new ExecutionException(t); + } + return value; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/util/WeakCollection.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/util/WeakCollection.java new file mode 100644 index 0000000..d8ab59b --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/util/WeakCollection.java @@ -0,0 +1,164 @@ +package org.bukkit.craftbukkit.util; + +import org.apache.commons.lang.Validate; + +import java.lang.ref.WeakReference; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.NoSuchElementException; + +public final class WeakCollection implements Collection { + static final Object NO_VALUE = new Object(); + private final Collection> collection; + + public WeakCollection() { + collection = new ArrayList<>(); + } + + public boolean add(T value) { + Validate.notNull(value, "Cannot add null value"); + return collection.add(new WeakReference<>(value)); + } + + public boolean addAll(Collection collection) { + Collection> values = this.collection; + boolean ret = false; + for (T value : collection) { + Validate.notNull(value, "Cannot add null value"); + ret |= values.add(new WeakReference<>(value)); + } + return ret; + } + + public void clear() { + collection.clear(); + } + + public boolean contains(Object object) { + if (object == null) { + return false; + } + for (T compare : this) { + if (object.equals(compare)) { + return true; + } + } + return false; + } + + public boolean containsAll(Collection collection) { + return toCollection().containsAll(collection); + } + + public boolean isEmpty() { + return !iterator().hasNext(); + } + + public Iterator iterator() { + return new Iterator() { + final Iterator> it = collection.iterator(); + Object value = NO_VALUE; + + public boolean hasNext() { + Object value = this.value; + if (value != null && value != NO_VALUE) { + return true; + } + + Iterator> it = this.it; + + while (it.hasNext()) { + WeakReference ref = it.next(); + value = ref.get(); + if (value == null) { + it.remove(); + } else { + this.value = value; + return true; + } + } + return false; + } + + public T next() throws NoSuchElementException { + if (!hasNext()) { + throw new NoSuchElementException("No more elements"); + } + + @SuppressWarnings("unchecked") + T value = (T) this.value; + this.value = NO_VALUE; + return value; + } + + public void remove() throws IllegalStateException { + if (value != NO_VALUE) { + throw new IllegalStateException("No last element"); + } + + value = null; + it.remove(); + } + }; + } + + public boolean remove(Object object) { + if (object == null) { + return false; + } + + Iterator it = this.iterator(); + while (it.hasNext()) { + if (object.equals(it.next())) { + it.remove(); + return true; + } + } + return false; + } + + public boolean removeAll(Collection collection) { + Iterator it = this.iterator(); + boolean ret = false; + while (it.hasNext()) { + if (collection.contains(it.next())) { + ret = true; + it.remove(); + } + } + return ret; + } + + public boolean retainAll(Collection collection) { + Iterator it = this.iterator(); + boolean ret = false; + while (it.hasNext()) { + if (!collection.contains(it.next())) { + ret = true; + it.remove(); + } + } + return ret; + } + + public int size() { + int s = 0; + for (T ignored : this) { + s++; + } + return s; + } + + public Object[] toArray() { + return this.toArray(new Object[0]); + } + + public T[] toArray(T[] array) { + return toCollection().toArray(array); + } + + private Collection toCollection() { + return new ArrayList<>(this); + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/util/permissions/CommandPermissions.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/util/permissions/CommandPermissions.java new file mode 100644 index 0000000..c93498e --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/util/permissions/CommandPermissions.java @@ -0,0 +1,36 @@ +package org.bukkit.craftbukkit.util.permissions; + +import org.bukkit.permissions.Permission; +import org.bukkit.permissions.PermissionDefault; +import org.bukkit.util.permissions.DefaultPermissions; + +public final class CommandPermissions { + private static final String ROOT = "minecraft.command"; + private static final String PREFIX = ROOT + "."; + + private CommandPermissions() {} + + public static Permission registerPermissions(Permission parent) { + Permission commands = DefaultPermissions.registerPermission(ROOT, "Gives the user the ability to use all vanilla minecraft commands", parent); + + DefaultPermissions.registerPermission(PREFIX + "kill", "Allows the user to commit suicide", PermissionDefault.OP, commands); + DefaultPermissions.registerPermission(PREFIX + "me", "Allows the user to perform a chat action", PermissionDefault.TRUE, commands); + DefaultPermissions.registerPermission(PREFIX + "tell", "Allows the user to privately message another player", PermissionDefault.TRUE, commands); + DefaultPermissions.registerPermission(PREFIX + "say", "Allows the user to talk as the console", PermissionDefault.OP, commands); + DefaultPermissions.registerPermission(PREFIX + "give", "Allows the user to give items to players", PermissionDefault.OP, commands); + DefaultPermissions.registerPermission(PREFIX + "teleport", "Allows the user to teleport players", PermissionDefault.OP, commands); + DefaultPermissions.registerPermission(PREFIX + "kick", "Allows the user to kick players", PermissionDefault.OP, commands); + DefaultPermissions.registerPermission(PREFIX + "stop", "Allows the user to stop the server", PermissionDefault.OP, commands); + DefaultPermissions.registerPermission(PREFIX + "list", "Allows the user to list all online players", PermissionDefault.OP, commands); + DefaultPermissions.registerPermission(PREFIX + "gamemode", "Allows the user to change the gamemode of another player", PermissionDefault.OP, commands); + DefaultPermissions.registerPermission(PREFIX + "xp", "Allows the user to give themselves or others arbitrary values of experience", PermissionDefault.OP, commands); + DefaultPermissions.registerPermission(PREFIX + "toggledownfall", "Allows the user to toggle rain on/off for a given world", PermissionDefault.OP, commands); + DefaultPermissions.registerPermission(PREFIX + "defaultgamemode", "Allows the user to change the default gamemode of the server", PermissionDefault.OP, commands); + DefaultPermissions.registerPermission(PREFIX + "seed", "Allows the user to view the seed of the world", PermissionDefault.OP, commands); + DefaultPermissions.registerPermission(PREFIX + "effect", "Allows the user to add/remove effects on players", PermissionDefault.OP, commands); + DefaultPermissions.registerPermission(PREFIX + "selector", "Allows the use of selectors", PermissionDefault.OP, commands); + + commands.recalculatePermissibles(); + return commands; + } +} diff --git a/azurite-server/src/main/java/org/bukkit/craftbukkit/util/permissions/CraftDefaultPermissions.java b/azurite-server/src/main/java/org/bukkit/craftbukkit/util/permissions/CraftDefaultPermissions.java new file mode 100644 index 0000000..6bea250 --- /dev/null +++ b/azurite-server/src/main/java/org/bukkit/craftbukkit/util/permissions/CraftDefaultPermissions.java @@ -0,0 +1,16 @@ +package org.bukkit.craftbukkit.util.permissions; + +import org.bukkit.permissions.Permission; +import org.bukkit.util.permissions.DefaultPermissions; + +public final class CraftDefaultPermissions { + private static final String ROOT= "minecraft"; + + private CraftDefaultPermissions() {} + + public static void registerCorePermissions() { + Permission parent = DefaultPermissions.registerPermission(ROOT, "Gives the user the ability to use all vanilla utilities and commands"); + CommandPermissions.registerPermissions(parent); + parent.recalculatePermissibles(); + } +} diff --git a/azurite-server/src/main/java/org/github/paperspigot/PaperSpigotConfig.java b/azurite-server/src/main/java/org/github/paperspigot/PaperSpigotConfig.java new file mode 100644 index 0000000..5e9f6cb --- /dev/null +++ b/azurite-server/src/main/java/org/github/paperspigot/PaperSpigotConfig.java @@ -0,0 +1,197 @@ +package org.github.paperspigot; + +import com.google.common.base.Throwables; +import net.minecraft.server.Items; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.YamlConfiguration; + +import java.io.File; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.logging.Level; + +public class PaperSpigotConfig +{ + + private static File CONFIG_FILE; + private static final String HEADER = "This is the main configuration file for PaperSpigot.\n" + + "As you can see, there's tons to configure. Some options may impact gameplay, so use\n" + + "with caution, and make sure you know what each option does before configuring.\n" + + "\n" + + "If you need help with the configuration or have any questions related to PaperSpigot,\n" + + "join us at the IRC.\n" + + "\n" + + "IRC: #paperspigot @ irc.spi.gt ( http://irc.spi.gt/iris/?channels=PaperSpigot )\n"; + /*========================================================================*/ + public static YamlConfiguration config; + static int version; + /*========================================================================*/ + + public static void init(File configFile) + { + CONFIG_FILE = configFile; + config = new YamlConfiguration(); + try + { + config.load ( CONFIG_FILE ); + } catch ( IOException ignored ) + { + } catch ( InvalidConfigurationException ex ) + { + Bukkit.getLogger().log( Level.SEVERE, "Could not load spigot.yml, please correct your syntax errors", ex ); + throw Throwables.propagate( ex ); + } + config.options().header( HEADER ); + config.options().copyDefaults( true ); + + version = getInt( "config-version", 9 ); + set( "config-version", 9 ); + readConfig( PaperSpigotConfig.class, null ); + } + + static void readConfig(Class clazz, Object instance) + { + for ( Method method : clazz.getDeclaredMethods() ) + { + if ( Modifier.isPrivate( method.getModifiers() ) ) + { + if ( method.getParameterTypes().length == 0 && method.getReturnType() == Void.TYPE ) + { + try + { + method.setAccessible( true ); + method.invoke( instance ); + } catch ( InvocationTargetException ex ) + { + throw Throwables.propagate( ex.getCause() ); + } catch ( Exception ex ) + { + Bukkit.getLogger().log( Level.SEVERE, "Error invoking " + method, ex ); + } + } + } + } + + try + { + config.save( CONFIG_FILE ); + } catch ( IOException ex ) + { + Bukkit.getLogger().log( Level.SEVERE, "Could not save " + CONFIG_FILE, ex ); + } + } + + private static void set(String path, Object val) + { + config.set( path, val ); + } + + private static boolean getBoolean(String path, boolean def) + { + config.addDefault( path, def ); + return config.getBoolean( path, config.getBoolean( path ) ); + } + + private static double getDouble(String path, double def) + { + config.addDefault( path, def ); + return config.getDouble( path, config.getDouble( path ) ); + } + + private static float getFloat(String path, float def) + { + // TODO: Figure out why getFloat() always returns the default value. + return (float) getDouble( path, (double) def ); + } + + private static int getInt(String path, int def) + { + config.addDefault( path, def ); + return config.getInt( path, config.getInt( path ) ); + } + + private static List getList(String path, T def) + { + config.addDefault( path, def ); + return config.getList( path, config.getList( path ) ); + } + + private static String getString(String path, String def) + { + config.addDefault( path, def ); + return config.getString( path, config.getString( path ) ); + } + + public static double babyZombieMovementSpeed; + private static void babyZombieMovementSpeed() + { + babyZombieMovementSpeed = getDouble( "settings.baby-zombie-movement-speed", 0.5D ); // Player moves at 0.1F, for reference + } + + public static boolean interactLimitEnabled; + private static void interactLimitEnabled() + { + interactLimitEnabled = getBoolean( "settings.limit-player-interactions", true ); + if ( !interactLimitEnabled ) + { + Bukkit.getLogger().log( Level.INFO, "Disabling player interaction limiter, your server may be more vulnerable to malicious users" ); + } + } + + public static double strengthEffectModifier; + public static double weaknessEffectModifier; + private static void effectModifiers() + { + strengthEffectModifier = getDouble( "effect-modifiers.strength", 1.3D ); + weaknessEffectModifier = getDouble( "effect-modifiers.weakness", -0.5D ); + } + + public static Set dataValueAllowedItems; + private static void dataValueAllowedItems() + { + dataValueAllowedItems = new HashSet( getList( "data-value-allowed-items", Collections.emptyList() ) ); + } + + public static boolean stackableLavaBuckets; + public static boolean stackableWaterBuckets; + public static boolean stackableMilkBuckets; + private static void stackableBuckets() + { + stackableLavaBuckets = getBoolean( "stackable-buckets.lava", false ); + stackableWaterBuckets = getBoolean( "stackable-buckets.water", false ); + stackableMilkBuckets = getBoolean( "stackable-buckets.milk", false ); + + try { + if (stackableLavaBuckets) { + Material.LAVA_BUCKET.maxStack = Material.BUCKET.getMaxStackSize(); + Items.LAVA_BUCKET.c(Material.BUCKET.getMaxStackSize()); + } + + if (stackableWaterBuckets) { + Material.WATER_BUCKET.maxStack = Material.BUCKET.getMaxStackSize(); + Items.WATER_BUCKET.c(Material.BUCKET.getMaxStackSize()); + } + + if (stackableMilkBuckets) { + Material.MILK_BUCKET.maxStack = Material.BUCKET.getMaxStackSize(); + Items.MILK_BUCKET.c(Material.BUCKET.getMaxStackSize()); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static boolean warnForExcessiveVelocity; + private static void excessiveVelocityWarning() + { + warnForExcessiveVelocity = getBoolean("warnWhenSettingExcessiveVelocity", true); + } +} diff --git a/azurite-server/src/main/java/org/github/paperspigot/PaperSpigotWorldConfig.java b/azurite-server/src/main/java/org/github/paperspigot/PaperSpigotWorldConfig.java new file mode 100644 index 0000000..f7c3b85 --- /dev/null +++ b/azurite-server/src/main/java/org/github/paperspigot/PaperSpigotWorldConfig.java @@ -0,0 +1,390 @@ +package org.github.paperspigot; + +import org.bukkit.Bukkit; +import org.bukkit.configuration.file.YamlConfiguration; + +import java.util.List; + +public class PaperSpigotWorldConfig +{ + + private final String worldName; + private final YamlConfiguration config; + private boolean verbose; + + public PaperSpigotWorldConfig(String worldName) + { + this.worldName = worldName; + this.config = PaperSpigotConfig.config; + init(); + } + + public void init() + { + this.verbose = getBoolean( "verbose", true ); + + + PaperSpigotConfig.readConfig( PaperSpigotWorldConfig.class, this ); + } + + private void log(String s) + { + if ( verbose ) + { + Bukkit.getLogger().info( s ); + } + } + + private void set(String path, Object val) + { + config.set( "world-settings.default." + path, val ); + } + + private boolean getBoolean(String path, boolean def) + { + config.addDefault( "world-settings.default." + path, def ); + return config.getBoolean( "world-settings." + worldName + "." + path, config.getBoolean( "world-settings.default." + path ) ); + } + + private double getDouble(String path, double def) + { + config.addDefault( "world-settings.default." + path, def ); + return config.getDouble( "world-settings." + worldName + "." + path, config.getDouble( "world-settings.default." + path ) ); + } + + private int getInt(String path, int def) + { + config.addDefault( "world-settings.default." + path, def ); + return config.getInt( "world-settings." + worldName + "." + path, config.getInt( "world-settings.default." + path ) ); + } + + private float getFloat(String path, float def) + { + // TODO: Figure out why getFloat() always returns the default value. + return (float) getDouble( path, (double) def ); + } + + private List getList(String path, T def) + { + config.addDefault( "world-settings.default." + path, def ); + return (List) config.getList( "world-settings." + worldName + "." + path, config.getList( "world-settings.default." + path ) ); + } + + private String getString(String path, String def) + { + config.addDefault( "world-settings.default." + path, def ); + return config.getString( "world-settings." + worldName + "." + path, config.getString( "world-settings.default." + path ) ); + } + + public boolean allowUndeadHorseLeashing; + private void allowUndeadHorseLeashing() + { + allowUndeadHorseLeashing = getBoolean( "allow-undead-horse-leashing", false ); + } + + public double squidMinSpawnHeight; + public double squidMaxSpawnHeight; + private void squidSpawnHeight() + { + squidMinSpawnHeight = getDouble( "squid-spawn-height.minimum", 45.0D ); + squidMaxSpawnHeight = getDouble( "squid-spawn-height.maximum", 63.0D ); + } + + public float playerBlockingDamageMultiplier; + private void playerBlockingDamageMultiplier() + { + playerBlockingDamageMultiplier = getFloat( "player-blocking-damage-multiplier", 0.5F ); + } + + public int cactusMaxHeight; + public int reedMaxHeight; + private void blockGrowthHeight() + { + cactusMaxHeight = getInt( "max-growth-height.cactus", 3 ); + reedMaxHeight = getInt( "max-growth-height.reeds", 3 ); + } + + public int fishingMinTicks; + public int fishingMaxTicks; + private void fishingTickRange() + { + fishingMinTicks = getInt( "fishing-time-range.MinimumTicks", 100 ); + fishingMaxTicks = getInt( "fishing-time-range.MaximumTicks", 900 ); + } + + public float blockBreakExhaustion; + public float playerSwimmingExhaustion; + private void exhaustionValues() + { + blockBreakExhaustion = getFloat( "player-exhaustion.block-break", 0.025F ); + playerSwimmingExhaustion = getFloat( "player-exhaustion.swimming", 0.015F ); + } + + public int softDespawnDistance; + public int hardDespawnDistance; + private void despawnDistances() + { + softDespawnDistance = getInt( "despawn-ranges.soft", 32 ); // 32^2 = 1024, Minecraft Default + hardDespawnDistance = getInt( "despawn-ranges.hard", 128 ); // 128^2 = 16384, Minecraft Default; + + if ( softDespawnDistance > hardDespawnDistance ) { + softDespawnDistance = hardDespawnDistance; + } + + softDespawnDistance = softDespawnDistance*softDespawnDistance; + hardDespawnDistance = hardDespawnDistance*hardDespawnDistance; + } + + public boolean keepSpawnInMemory; + private void keepSpawnInMemory() + { + keepSpawnInMemory = getBoolean( "keep-spawn-loaded", true ); + } + + public int fallingBlockHeightNerf; + private void fallingBlockheightNerf() + { + fallingBlockHeightNerf = getInt( "falling-block-height-nerf", 0 ); + } + + public int tntEntityHeightNerf; + private void tntEntityHeightNerf() + { + tntEntityHeightNerf = getInt( "tnt-entity-height-nerf", 0 ); + } + + public int waterOverLavaFlowSpeed; + private void waterOverLavaFlowSpeed() + { + waterOverLavaFlowSpeed = getInt( "water-over-lava-flow-speed", 5 ); + } + + public boolean removeInvalidMobSpawnerTEs; + private void removeInvalidMobSpawnerTEs() + { + removeInvalidMobSpawnerTEs = getBoolean( "remove-invalid-mob-spawner-tile-entities", true ); + } + + public boolean removeUnloadedEnderPearls; + public boolean removeUnloadedTNTEntities; + public boolean removeUnloadedFallingBlocks; + private void removeUnloaded() + { + removeUnloadedEnderPearls = getBoolean( "remove-unloaded.enderpearls", true ); + removeUnloadedTNTEntities = getBoolean( "remove-unloaded.tnt-entities", false ); + removeUnloadedFallingBlocks = getBoolean( "remove-unloaded.falling-blocks", false ); + } + + public boolean boatsDropBoats; + public boolean disablePlayerCrits; + public boolean disableChestCatDetection; + private void mechanicsChanges() + { + boatsDropBoats = getBoolean( "game-mechanics.boats-drop-boats", false ); + disablePlayerCrits = getBoolean( "game-mechanics.disable-player-crits", false ); + disableChestCatDetection = getBoolean( "game-mechanics.disable-chest-cat-detection", true ); + } + + public boolean netherVoidTopDamage; + private void nethervoidTopDamage() + { + netherVoidTopDamage = getBoolean( "nether-ceiling-void-damage", false ); + } + + public int tickNextTickCap; + public boolean tickNextTickListCapIgnoresRedstone; + private void tickNextTickCap() + { + tickNextTickCap = getInt( "tick-next-tick-list-cap", 10000 ); // Higher values will be friendlier to vanilla style mechanics (to a point) but may hurt performance + tickNextTickListCapIgnoresRedstone = getBoolean( "tick-next-tick-list-cap-ignores-redstone", false ); // Redstone TickNextTicks will always bypass the preceding cap. + } + + public boolean useAsyncLighting; + private void useAsyncLighting() + { + useAsyncLighting = getBoolean( "use-async-lighting", false ); + } + + public boolean disableEndCredits; + private void disableEndCredits() + { + disableEndCredits = getBoolean( "game-mechanics.disable-end-credits", false ); + } + + public boolean loadUnloadedEnderPearls; + public boolean loadUnloadedTNTEntities; + public boolean loadUnloadedFallingBlocks; + private void loadUnloaded() + { + loadUnloadedEnderPearls = getBoolean( "load-chunks.enderpearls", true ); + loadUnloadedTNTEntities = getBoolean( "load-chunks.tnt-entities", true ); + loadUnloadedFallingBlocks = getBoolean( "load-chunks.falling-blocks", true ); + } + + public boolean generateCanyon; + public boolean generateCaves; + public boolean generateDungeon; + public boolean generateFortress; + public boolean generateMineshaft; + public boolean generateMonument; + public boolean generateStronghold; + public boolean generateTemple; + public boolean generateVillage; + public boolean generateFlatBedrock; + private void generatorSettings() + { + generateCanyon = getBoolean( "generator-settings.canyon", true ); + generateCaves = getBoolean( "generator-settings.caves", true ); + generateDungeon = getBoolean( "generator-settings.dungeon", true ); + generateFortress = getBoolean( "generator-settings.fortress", true ); + generateMineshaft = getBoolean( "generator-settings.mineshaft", true ); + generateMonument = getBoolean( "generator-settings.monument", true ); + generateStronghold = getBoolean( "generator-settings.stronghold", true ); + generateTemple = getBoolean( "generator-settings.temple", true ); + generateVillage = getBoolean( "generator-settings.village", true ); + generateFlatBedrock = getBoolean( "generator-settings.flat-bedrock", false ); + } + + public boolean fixCannons; + private void fixCannons() + { + // TODO: Remove migrations after most users have upgraded. + if ( PaperSpigotConfig.version < 9 ) + { + // Migrate default value + + boolean value = config.getBoolean( "world-settings.default.fix-cannons", false ); + if ( !value ) value = config.getBoolean( "world-settings.default.tnt-gameplay.fix-directional-bias", false ); + if ( !value ) value = !config.getBoolean( "world-settings.default.tnt-gameplay.moves-in-water", true ); + if ( !value ) value = config.getBoolean( "world-settings.default.tnt-gameplay.legacy-explosion-height", false ); + if ( value ) config.set( "world-settings.default.fix-cannons", true ); + + if ( config.contains( "world-settings.default.tnt-gameplay" ) ) + { + config.getDefaults().set( "world-settings.default.tnt-gameplay", null); + config.set( "world-settings.default.tnt-gameplay", null ); + } + + // Migrate world setting + + value = config.getBoolean( "world-settings." + worldName + ".fix-cannons", false ); + if ( !value ) value = config.getBoolean( "world-settings." + worldName + ".tnt-gameplay.fix-directional-bias", false ); + if ( !value ) value = !config.getBoolean( "world-settings." + worldName + ".tnt-gameplay.moves-in-water", true ); + if ( !value ) value = config.getBoolean( "world-settings." + worldName + ".tnt-gameplay.legacy-explosion-height", false ); + if ( value ) config.set( "world-settings." + worldName + ".fix-cannons", true ); + + if ( config.contains( "world-settings." + worldName + ".tnt-gameplay" ) ) + { + config.getDefaults().set( "world-settings." + worldName + ".tnt-gameplay", null); + config.set( "world-settings." + worldName + ".tnt-gameplay", null ); + } + } + + fixCannons = getBoolean( "fix-cannons", true ); + } + + public boolean fallingBlocksCollideWithSigns; + private void fallingBlocksCollideWithSigns() + { + fallingBlocksCollideWithSigns = getBoolean( "falling-blocks-collide-with-signs", false ); + } + + public boolean optimizeExplosions; + private void optimizeExplosions() + { + optimizeExplosions = getBoolean( "optimize-explosions", true ); + } + + public boolean fastDrainLava; + public boolean fastDrainWater; + private void fastDraining() + { + fastDrainLava = getBoolean( "fast-drain.lava", false ); + fastDrainWater = getBoolean( "fast-drain.water", false ); + } + + public int lavaFlowSpeedNormal; + public int lavaFlowSpeedNether; + private void lavaFlowSpeed() + { + lavaFlowSpeedNormal = getInt( "lava-flow-speed.normal", 30 ); + lavaFlowSpeedNether = getInt( "lava-flow-speed.nether", 10 ); + } + + public boolean disableExplosionKnockback; + private void disableExplosionKnockback() + { + disableExplosionKnockback = getBoolean( "disable-explosion-knockback", false ); + } + + public boolean disableThunder; + private void disableThunder() + { + disableThunder = getBoolean( "disable-thunder", false ); + } + + public boolean disableIceAndSnow; + private void disableIceAndSnow() + { + disableIceAndSnow = getBoolean( "disable-ice-and-snow", false ); + } + + public boolean disableMoodSounds; + private void disableMoodSounds() + { + disableMoodSounds = getBoolean( "disable-mood-sounds", false ); + } + + public int mobSpawnerTickRate; + private void mobSpawnerTickRate() + { + mobSpawnerTickRate = getInt( "mob-spawner-tick-rate", 1 ); + } + + public int containerUpdateTickRate; + private void containerUpdateTickRate() + { + containerUpdateTickRate = getInt( "container-update-tick-rate", 1 ); + } + + public float tntExplosionVolume; + private void tntExplosionVolume() + { + tntExplosionVolume = getFloat( "tnt-explosion-volume", 4.0F ); + } + + public boolean useHopperCheck; + private void useHopperCheck() + { + useHopperCheck = getBoolean( "use-hopper-check", false ); + } + + public boolean allChunksAreSlimeChunks; + private void allChunksAreSlimeChunks() + { + allChunksAreSlimeChunks = getBoolean( "all-chunks-are-slime-chunks", false ); + } + + public boolean allowBlockLocationTabCompletion; + private void allowBlockLocationTabCompletion() + { + allowBlockLocationTabCompletion = getBoolean( "allow-block-location-tab-completion", true ); + } + + public int portalSearchRadius; + private void portalSearchRadius() + { + portalSearchRadius = getInt("portal-search-radius", 128); + } + + public boolean disableTeleportationSuffocationCheck; + private void disableTeleportationSuffocationCheck() + { + disableTeleportationSuffocationCheck = getBoolean("disable-teleportation-suffocation-check", false); + } + + public boolean countAllMobsForSpawning = false; + private void countAllMobsForSpawning() { + countAllMobsForSpawning = getBoolean( "count-all-mobs-for-spawning", false ); + } +} diff --git a/azurite-server/src/main/java/org/github/paperspigot/PaperWorldEntityList.java b/azurite-server/src/main/java/org/github/paperspigot/PaperWorldEntityList.java new file mode 100644 index 0000000..24a10d8 --- /dev/null +++ b/azurite-server/src/main/java/org/github/paperspigot/PaperWorldEntityList.java @@ -0,0 +1,119 @@ +package org.github.paperspigot; + +import net.minecraft.server.*; +import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason; + +import java.util.ArrayList; +import java.util.Collection; + +public class PaperWorldEntityList extends ArrayList { + + private final WorldServer world; + private final int[] entityCounts = new int[EnumCreatureType.values().length]; + + public PaperWorldEntityList(World world) { + this.world = (WorldServer) world; + } + + @Override + public boolean addAll(Collection c) { + for (Entity e : c) { + updateEntityCount(e, 1); + } + + return super.addAll(c); + } + + @Override + public boolean removeAll(Collection c) { + for (Object e : c) { + if (e instanceof Entity && ((Entity) e).getWorld() == world) { + updateEntityCount((Entity) e, -1); + } + } + + return super.removeAll(c); + } + + @Override + public boolean add(Entity e) { + updateEntityCount(e, 1); + return super.add(e); + } + + @Override + public Entity remove(int index) { + guard(); + Entity entity = super.remove(index); + if (entity != null) updateEntityCount(entity, -1); + return entity; + } + + @Override + public boolean remove(Object o) { + guard(); + if (super.remove(o)) { + updateEntityCount((Entity) o, -1); + return true; + } + return false; + } + + private void guard() { + if (world.guardEntityList) { + throw new java.util.ConcurrentModificationException(); + } + } + + public int getCreatureCount(EnumCreatureType type) { + return entityCounts[type.ordinal()]; + } + + private void updateEntityCount(EnumCreatureType type, int amt) { + int count = entityCounts[type.ordinal()]; + + count += amt; + + if (count < 0) { + MinecraftServer.LOGGER.error("Paper - Entity count cache has gone negative"); + count = 0; + } + + entityCounts[type.ordinal()] = count; + } + + public void updateEntityCount(Entity entity, int amt) { + // Only count natural spawns so that mob + if (!(entity instanceof IAnimal) || ( + !world.paperSpigotConfig.countAllMobsForSpawning && + entity.spawnReason != SpawnReason.NATURAL && + entity.spawnReason != SpawnReason.CHUNK_GEN + )) return; + + if (entity instanceof EntityInsentient) { + EntityInsentient entityinsentient = (EntityInsentient) entity; + if (amt > 0 && entityinsentient.isTypeNotPersistent() && entityinsentient.isPersistent()) { + return; + } + } + if (amt < 0) { + if (!entity.hasBeenCounted) { + return; + } + // Only remove once, we remove from if the entity list is guarded, but may be called later + entity.hasBeenCounted = false; + } else { + if (entity.hasBeenCounted) { + return; + } + entity.hasBeenCounted = true; + } + + for (EnumCreatureType type : EnumCreatureType.values()) { + if (type.matches(entity)) { + updateEntityCount(type, amt); + break; + } + } + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/org/github/paperspigot/ServerSchedulerReportingWrapper.java b/azurite-server/src/main/java/org/github/paperspigot/ServerSchedulerReportingWrapper.java new file mode 100644 index 0000000..8b4d6ee --- /dev/null +++ b/azurite-server/src/main/java/org/github/paperspigot/ServerSchedulerReportingWrapper.java @@ -0,0 +1,38 @@ +package org.github.paperspigot; + +import com.google.common.base.Preconditions; +import org.bukkit.craftbukkit.scheduler.CraftTask; +import org.github.paperspigot.event.ServerExceptionEvent; +import org.github.paperspigot.exception.ServerSchedulerException; + +/** + * Reporting wrapper to catch exceptions not natively + */ +public class ServerSchedulerReportingWrapper implements Runnable { + + private final CraftTask internalTask; + + public ServerSchedulerReportingWrapper(CraftTask internalTask) { + this.internalTask = Preconditions.checkNotNull(internalTask, "internalTask"); + } + + @Override + public void run() { + try { + internalTask.run(); + } catch (RuntimeException e) { + internalTask.getOwner().getServer().getPluginManager().callEvent( + new ServerExceptionEvent(new ServerSchedulerException(e, internalTask)) + ); + throw e; + } catch (Throwable t) { + internalTask.getOwner().getServer().getPluginManager().callEvent( + new ServerExceptionEvent(new ServerSchedulerException(t, internalTask)) + ); //Do not rethrow, since it is not permitted with Runnable#run + } + } + + public CraftTask getInternalTask() { + return internalTask; + } +} \ No newline at end of file diff --git a/azurite-server/src/main/java/org/spigotmc/ActivationRange.java b/azurite-server/src/main/java/org/spigotmc/ActivationRange.java new file mode 100644 index 0000000..de5bfd4 --- /dev/null +++ b/azurite-server/src/main/java/org/spigotmc/ActivationRange.java @@ -0,0 +1,144 @@ +package org.spigotmc; + +import dev.azurite.spigot.optimizations.FastActivationRange; +import net.minecraft.server.*; + + +public class ActivationRange { + + /** + * Initializes an entities type on construction to specify what group this + * entity is in for activation ranges. + * + * @param entity + * @return group id + */ + public static byte initializeEntityActivationType(Entity entity) { + if (entity instanceof EntityMonster || entity instanceof EntitySlime) { + return 1; // Monster + } else if (entity instanceof EntityCreature || entity instanceof EntityAmbient) { + return 2; // Animal + } else { + return 3; // Misc + } + } + + /** + * These entities are excluded from Activation range checks. + * + * @param entity + * @return boolean If it should always tick. + */ + public static boolean initializeEntityActivationState(Entity entity, SpigotWorldConfig config) { + return (entity.activationType == 3 && config.miscActivationRange == 0) + || (entity.activationType == 2 && config.animalActivationRange == 0) + || (entity.activationType == 1 && config.monsterActivationRange == 0) + || entity instanceof EntityPlayer + || entity instanceof EntityTNTPrimed + || entity instanceof EntityArrow + || entity instanceof EntityFishingHook + || entity instanceof EntityFallingBlock + || entity instanceof EntityProjectile + || entity instanceof EntityEnderDragon + || entity instanceof EntityComplexPart + || entity instanceof EntityWither + || entity instanceof EntityFireball + || entity instanceof EntityWeather + || entity instanceof EntityEnderCrystal + || entity instanceof EntityFireworks; + } + + /** + * Find what entities are in range of the players in the world and set + * active if in range. + * + * @param world + */ + public static void activateEntities(World world) { + FastActivationRange.activateEntities(world); // Azurite + } + + /** + * If an entity is not in range, do some more checks to see if we should + * give it a shot. + * + * @param entity + * @return + */ + public static boolean checkEntityImmunities(Entity entity) { + // quick checks. + if (entity.inWater || entity.fireTicks > 0) { + return true; + } + if (!(entity instanceof EntityArrow)) { + if (!entity.onGround || entity.passenger != null + || entity.vehicle != null) { + return true; + } + } else if (!((EntityArrow) entity).inGround) { + return true; + } + // special cases. + if (entity instanceof EntityLiving) { + EntityLiving living = (EntityLiving) entity; + if ( /*TODO: Missed mapping? living.attackTicks > 0 || */ living.hurtTicks > 0 || !living.effects.isEmpty()) { + return true; + } + if (entity instanceof EntityCreature && ((EntityCreature) entity).getGoalTarget() != null) { + return true; + } + if (entity instanceof EntityVillager && ((EntityVillager) entity).cm() /* Getter for first boolean */) { + return true; + } + if (entity instanceof EntityAnimal) { + EntityAnimal animal = (EntityAnimal) entity; + if (animal.isBaby() || animal.isInLove()) { + return true; + } + if (entity instanceof EntitySheep && ((EntitySheep) entity).isSheared()) { + return true; + } + } + // isExplosive + return entity instanceof EntityCreeper && ((EntityCreeper) entity).cn(); + } + return false; + } + + /** + * Checks if the entity is active for this tick. + * + * @param entity + * @return + */ + public static boolean checkIfActive(Entity entity) { + // Never safe to skip fireworks or entities not yet added to chunk + if (!entity.isAddedToChunk() || entity instanceof EntityFireworks || entity.loadChunks) { // PaperSpigot + return true; + } + + boolean isActive = entity.activatedTick >= MinecraftServer.currentTick || entity.defaultActivationState; + + // Should this entity tick? + if (!isActive) { + if ((MinecraftServer.currentTick - entity.activatedTick - 1) % 20 == 0) { + // Check immunities every 20 ticks. + if (checkEntityImmunities(entity)) { + // Triggered some sort of immunity, give 20 full ticks before we check again. + entity.activatedTick = MinecraftServer.currentTick + 20; + } + isActive = true; + } + // Add a little performance juice to active entities. Skip 1/4 if not immune. + } else if (!entity.defaultActivationState && entity.ticksLived % 4 == 0 && !checkEntityImmunities(entity)) { + isActive = false; + } + + Chunk chunk = entity.world.getChunkIfLoaded(MathHelper.floor(entity.locX) >> 4, MathHelper.floor(entity.locZ) >> 4); + if (isActive && !(chunk != null && chunk.areNeighborsLoaded(1))) { + isActive = false; + } + return isActive; + } + +} diff --git a/azurite-server/src/main/java/org/spigotmc/AsyncCatcher.java b/azurite-server/src/main/java/org/spigotmc/AsyncCatcher.java new file mode 100644 index 0000000..7eaa5ef --- /dev/null +++ b/azurite-server/src/main/java/org/spigotmc/AsyncCatcher.java @@ -0,0 +1,15 @@ +package org.spigotmc; + +import net.minecraft.server.MinecraftServer; + +public class AsyncCatcher +{ + + public static boolean enabled = true; + + public static void catchOp(String reason) { + if (enabled && (MinecraftServer.getServer().primaryThread != null && Thread.currentThread() != MinecraftServer.getServer().primaryThread)) { + throw new IllegalStateException("Asynchronous " + reason + "!"); + } + } +} diff --git a/azurite-server/src/main/java/org/spigotmc/CaseInsensitiveHashingStrategy.java b/azurite-server/src/main/java/org/spigotmc/CaseInsensitiveHashingStrategy.java new file mode 100644 index 0000000..4070162 --- /dev/null +++ b/azurite-server/src/main/java/org/spigotmc/CaseInsensitiveHashingStrategy.java @@ -0,0 +1,18 @@ +package org.spigotmc; + +import gnu.trove.strategy.HashingStrategy; + +class CaseInsensitiveHashingStrategy implements HashingStrategy { + + static final CaseInsensitiveHashingStrategy INSTANCE = new CaseInsensitiveHashingStrategy(); + + @Override + public int computeHashCode(Object object) { + return ((String) object).toLowerCase().hashCode(); + } + + @Override + public boolean equals(Object o1, Object o2) { + return o1.equals(o2) || (o1 instanceof String && o2 instanceof String && ((String) o1).equalsIgnoreCase(((String) o2))); + } +} diff --git a/azurite-server/src/main/java/org/spigotmc/CaseInsensitiveMap.java b/azurite-server/src/main/java/org/spigotmc/CaseInsensitiveMap.java new file mode 100644 index 0000000..af26222 --- /dev/null +++ b/azurite-server/src/main/java/org/spigotmc/CaseInsensitiveMap.java @@ -0,0 +1,16 @@ +package org.spigotmc; + +import gnu.trove.map.hash.TCustomHashMap; + +import java.util.Map; + +public class CaseInsensitiveMap extends TCustomHashMap { + + public CaseInsensitiveMap() { + super(CaseInsensitiveHashingStrategy.INSTANCE); + } + + public CaseInsensitiveMap(Map map) { + super(CaseInsensitiveHashingStrategy.INSTANCE, map); + } +} diff --git a/azurite-server/src/main/java/org/spigotmc/LimitStream.java b/azurite-server/src/main/java/org/spigotmc/LimitStream.java new file mode 100644 index 0000000..6dcf65e --- /dev/null +++ b/azurite-server/src/main/java/org/spigotmc/LimitStream.java @@ -0,0 +1,40 @@ +package org.spigotmc; + +import net.minecraft.server.NBTReadLimiter; + +import java.io.FilterInputStream; +import java.io.IOException; +import java.io.InputStream; + +public class LimitStream extends FilterInputStream +{ + + private final NBTReadLimiter limit; + + public LimitStream(InputStream is, NBTReadLimiter limit) + { + super( is ); + this.limit = limit; + } + + @Override + public int read() throws IOException + { + limit.a( 8 ); + return super.read(); + } + + @Override + public int read(byte[] b) throws IOException + { + limit.a( b.length * 8L); + return super.read( b ); + } + + @Override + public int read(byte[] b, int off, int len) throws IOException + { + limit.a( len * 8L); + return super.read( b, off, len ); + } +} diff --git a/azurite-server/src/main/java/org/spigotmc/RestartCommand.java b/azurite-server/src/main/java/org/spigotmc/RestartCommand.java new file mode 100644 index 0000000..e83dcac --- /dev/null +++ b/azurite-server/src/main/java/org/spigotmc/RestartCommand.java @@ -0,0 +1,112 @@ +package org.spigotmc; + +import net.minecraft.server.EntityPlayer; +import net.minecraft.server.MinecraftServer; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; + +import java.io.File; + +public class RestartCommand extends Command +{ + + public RestartCommand(String name) + { + super( name ); + this.description = "Restarts the server"; + this.usageMessage = "/restart"; + this.setPermission( "bukkit.command.restart" ); + } + + @Override + public boolean execute(CommandSender sender, String currentAlias, String[] args) + { + if ( testPermission( sender ) ) + { + (MinecraftServer.getServer()).postToMainThreadRunnable(RestartCommand::restart); + } + return true; + } + + public static void restart() + { + restart( new File( SpigotConfig.restartScript ) ); + } + + public static void restart(final File script) + { + AsyncCatcher.enabled = false; // Disable async catcher incase it interferes with us + try + { + if ( script.isFile() ) + { + System.out.println( "Attempting to restart with " + SpigotConfig.restartScript ); + + // Disable Watchdog + WatchdogThread.doStop(); + + // Kick all players + for ( EntityPlayer p : MinecraftServer.getServer().getPlayerList().players ) + { + p.playerConnection.disconnect(SpigotConfig.restartMessage); + } + // Give the socket a chance to send the packets + try + { + Thread.sleep( 100 ); + } catch ( InterruptedException ignored) + { + } + // Close the socket so we can rebind with the new process + MinecraftServer.getServer().getServerConnection().b(); + + // Give time for it to kick in + try + { + Thread.sleep( 100 ); + } catch ( InterruptedException ignored) + { + } + + // Actually shutdown + try + { + MinecraftServer.getServer().stop(); + } catch ( Throwable ignored) + { + } + + // This will be done AFTER the server has completely halted + Thread shutdownHook = new Thread(() -> { + try + { + String os = System.getProperty( "os.name" ).toLowerCase(); + if ( os.contains( "win" ) ) + { + Runtime.getRuntime().exec( "cmd /c start " + script.getPath() ); + } else + { + Runtime.getRuntime().exec( new String[] + { + "sh", script.getPath() + } ); + } + } catch ( Exception e ) + { + e.printStackTrace(); + } + }); + + shutdownHook.setDaemon( true ); + Runtime.getRuntime().addShutdownHook( shutdownHook ); + } else + { + System.out.println( "Startup script '" + SpigotConfig.restartScript + "' does not exist! Stopping server." ); + } + System.exit( 0 ); + } catch ( Exception ex ) + { + ex.printStackTrace(); + } + } +} diff --git a/azurite-server/src/main/java/org/spigotmc/SpigotConfig.java b/azurite-server/src/main/java/org/spigotmc/SpigotConfig.java new file mode 100644 index 0000000..9f49c0f --- /dev/null +++ b/azurite-server/src/main/java/org/spigotmc/SpigotConfig.java @@ -0,0 +1,341 @@ +package org.spigotmc; + +import com.google.common.base.Throwables; +import gnu.trove.map.hash.TObjectIntHashMap; +import net.minecraft.server.AttributeRanged; +import net.minecraft.server.GenericAttributes; +import net.minecraft.server.MinecraftServer; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.YamlConfiguration; + +import java.io.File; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.*; +import java.util.concurrent.TimeUnit; +import java.util.logging.Level; + +public class SpigotConfig +{ + + private static File CONFIG_FILE; + private static final String HEADER = "This is the main configuration file for Spigot.\n" + + "As you can see, there's tons to configure. Some options may impact gameplay, so use\n" + + "with caution, and make sure you know what each option does before configuring.\n" + + "For a reference for any variable inside this file, check out the Spigot wiki at\n" + + "http://www.spigotmc.org/wiki/spigot-configuration/\n" + + "\n" + + "If you need help with the configuration or have any questions related to Spigot,\n" + + "join us at the IRC or drop by our forums and leave a post.\n" + + "\n" + + "IRC: #spigot @ irc.spi.gt ( http://www.spigotmc.org/pages/irc/ )\n" + + "Forums: http://www.spigotmc.org/\n"; + /*========================================================================*/ + public static YamlConfiguration config; + static int version; + static Map commands; + /*========================================================================*/ + // private static Metrics metrics; + + public static void init(File configFile) + { + CONFIG_FILE = configFile; + config = new YamlConfiguration(); + try + { + config.load( CONFIG_FILE ); + } catch ( IOException ignored) + { + } catch ( InvalidConfigurationException ex ) + { + Bukkit.getLogger().log( Level.SEVERE, "Could not load spigot.yml, please correct your syntax errors", ex ); + throw Throwables.propagate( ex ); + } + + config.options().header( HEADER ); + config.options().copyDefaults( true ); + + commands = new HashMap<>(); + version = getInt( "config-version", 8 ); + set( "config-version", 8 ); + readConfig( SpigotConfig.class, null ); + } + + public static void registerCommands() + { + for ( Map.Entry entry : commands.entrySet() ) + { + MinecraftServer.getServer().server.getCommandMap().register( entry.getKey(), "Spigot", entry.getValue() ); + } + + } + + static void readConfig(Class clazz, Object instance) + { + for ( Method method : clazz.getDeclaredMethods() ) + { + if ( Modifier.isPrivate( method.getModifiers() ) ) + { + if ( method.getParameterTypes().length == 0 && method.getReturnType() == Void.TYPE ) + { + try + { + method.setAccessible( true ); + method.invoke( instance ); + } catch ( InvocationTargetException ex ) + { + throw Throwables.propagate( ex.getCause() ); + } catch ( Exception ex ) + { + Bukkit.getLogger().log( Level.SEVERE, "Error invoking " + method, ex ); + } + } + } + } + + try + { + config.save( CONFIG_FILE ); + } catch ( IOException ex ) + { + Bukkit.getLogger().log( Level.SEVERE, "Could not save " + CONFIG_FILE, ex ); + } + } + + private static void set(String path, Object val) + { + config.set( path, val ); + } + + private static boolean getBoolean(String path, boolean def) + { + config.addDefault( path, def ); + return config.getBoolean( path, config.getBoolean( path ) ); + } + + private static int getInt(String path, int def) + { + config.addDefault( path, def ); + return config.getInt( path, config.getInt( path ) ); + } + + private static List getList(String path, T def) + { + config.addDefault( path, def ); + return config.getList( path, config.getList( path ) ); + } + + private static String getString(String path, String def) + { + config.addDefault( path, def ); + return config.getString( path, config.getString( path ) ); + } + + private static double getDouble(String path, double def) + { + config.addDefault( path, def ); + return config.getDouble( path, config.getDouble( path ) ); + } + + public static boolean logCommands; + private static void logCommands() + { + logCommands = getBoolean( "commands.log", true ); + } + + public static int tabComplete; + private static void tabComplete() + { + if ( version < 6 ) + { + boolean oldValue = getBoolean( "commands.tab-complete", true ); + if ( oldValue ) + { + set( "commands.tab-complete", 0 ); + } else + { + set( "commands.tab-complete", -1 ); + } + } + tabComplete = getInt( "commands.tab-complete", 0 ); + } + + public static String whitelistMessage; + public static String unknownCommandMessage; + public static String serverFullMessage; + public static String outdatedClientMessage = "Outdated client! Please use {0}"; + public static String outdatedServerMessage = "Outdated server! I\'m still on {0}"; + private static String transform(String s) + { + return ChatColor.translateAlternateColorCodes( '&', s ).replaceAll( "\\\\n", "\n" ); // PandaSpigot - Fix \n not working in configurable messages + } + private static void messages() + { + if (version < 8) + { + set( "messages.outdated-client", outdatedClientMessage ); + set( "messages.outdated-server", outdatedServerMessage ); + } + + whitelistMessage = transform( getString( "messages.whitelist", "You are not whitelisted on this server!" ) ); + unknownCommandMessage = transform( getString( "messages.unknown-command", "Unknown command. Type \"/help\" for help." ) ); + serverFullMessage = transform( getString( "messages.server-full", "The server is full!" ) ); + outdatedClientMessage = transform( getString( "messages.outdated-client", outdatedClientMessage ) ); + outdatedServerMessage = transform( getString( "messages.outdated-server", outdatedServerMessage ) ); + } + + public static int timeoutTime = 60; + public static boolean restartOnCrash = true; + public static String restartScript = "./start.sh"; + public static String restartMessage; + private static void watchdog() + { + timeoutTime = getInt( "settings.timeout-time", timeoutTime ); + restartOnCrash = getBoolean( "settings.restart-on-crash", restartOnCrash ); + restartScript = getString( "settings.restart-script", restartScript ); + restartMessage = transform( getString( "messages.restart", "Server is restarting" ) ); + commands.put( "restart", new RestartCommand( "restart" ) ); + WatchdogThread.doStart( timeoutTime, restartOnCrash ); + } + + public static boolean bungee; + private static void bungee() { + if ( version < 4 ) + { + set( "settings.bungeecord", false ); + System.out.println( "Oudated config, disabling BungeeCord support!" ); + } + bungee = getBoolean( "settings.bungeecord", false ); + } + + protected static String timeSummary(int seconds) { + String time = ""; + if (seconds > 60*60) { + time += TimeUnit.SECONDS.toHours(seconds) + "h"; + seconds /= 60; + } + + if (seconds > 0) { + time += TimeUnit.SECONDS.toMinutes(seconds) + "m"; + } + return time; + } + + public static boolean lateBind; + private static void lateBind() { + lateBind = getBoolean( "settings.late-bind", false ); + } + + public static boolean disableStatSaving; + public static TObjectIntHashMap forcedStats = new TObjectIntHashMap(); + private static void stats() + { + disableStatSaving = getBoolean( "stats.disable-saving", false ); + + if ( !config.contains( "stats.forced-stats" ) ) { + config.createSection( "stats.forced-stats" ); + } + + ConfigurationSection section = config.getConfigurationSection( "stats.forced-stats" ); + for ( String name : section.getKeys( true ) ) + { + if ( section.isInt( name ) ) + { + forcedStats.put( name, section.getInt( name ) ); + } + } + + if ( disableStatSaving && section.getInt( "achievement.openInventory", 0 ) < 1 ) + { + Bukkit.getLogger().warning( "*** WARNING *** stats.disable-saving is true but stats.forced-stats.achievement.openInventory" + + " isn't set to 1. Disabling stat saving without forcing the achievement may cause it to get stuck on the player's " + + "screen." ); + } + } + + public static int playerSample; + private static void playerSample() + { + playerSample = getInt( "settings.sample-count", 12 ); + } + + public static int playerShuffle; + private static void playerShuffle() + { + playerShuffle = getInt( "settings.player-shuffle", 0 ); + } + + public static List spamExclusions; + private static void spamExclusions() + { + spamExclusions = getList( "commands.spam-exclusions", new ArrayList<>() ); + } + + public static boolean silentCommandBlocks; + private static void silentCommandBlocks() + { + silentCommandBlocks = getBoolean( "commands.silent-commandblock-console", false ); + } + + public static boolean filterCreativeItems; + private static void filterCreativeItems() + { + filterCreativeItems = getBoolean( "settings.filter-creative-items", true ); + } + + public static Set replaceCommands; + private static void replaceCommands() + { + if ( config.contains( "replace-commands" ) ) + { + set( "commands.replace-commands", config.getStringList( "replace-commands" ) ); + config.set( "replace-commands", null ); + } + replaceCommands = new HashSet<>( (List) getList( "commands.replace-commands", + Arrays.asList( "setblock", "summon", "testforblock", "tellraw" ) ) ); + } + + public static int userCacheCap; + private static void userCacheCap() + { + userCacheCap = getInt( "settings.user-cache-size", 1000 ); + } + + public static boolean saveUserCacheOnStopOnly; + private static void saveUserCacheOnStopOnly() + { + saveUserCacheOnStopOnly = getBoolean( "settings.save-user-cache-on-stop-only", true ); // Azurite -> true by default + } + + public static int intCacheLimit; + private static void intCacheLimit() + { + intCacheLimit = getInt( "settings.int-cache-limit", 1024 ); + } + + public static double movedTooQuicklyThreshold; + private static void movedTooQuicklyThreshold() + { + movedTooQuicklyThreshold = getDouble( "settings.moved-too-quickly-threshold", 100.0D ); + } + + public static double maxHealth = 2048; + public static double movementSpeed = 2048; + public static double attackDamage = 2048; + private static void attributeMaxes() + { + maxHealth = getDouble( "settings.attribute.maxHealth.max", maxHealth ); + ( (AttributeRanged) GenericAttributes.maxHealth ).b = maxHealth; + movementSpeed = getDouble( "settings.attribute.movementSpeed.max", movementSpeed ); + ( (AttributeRanged) GenericAttributes.MOVEMENT_SPEED ).b = movementSpeed; + attackDamage = getDouble( "settings.attribute.attackDamage.max", attackDamage ); + ( (AttributeRanged) GenericAttributes.ATTACK_DAMAGE ).b = attackDamage; + } + +} diff --git a/azurite-server/src/main/java/org/spigotmc/SpigotWorldConfig.java b/azurite-server/src/main/java/org/spigotmc/SpigotWorldConfig.java new file mode 100644 index 0000000..bbdcc76 --- /dev/null +++ b/azurite-server/src/main/java/org/spigotmc/SpigotWorldConfig.java @@ -0,0 +1,289 @@ +package org.spigotmc; + +import dev.azurite.spigot.optimizations.FastAntiXray; +import org.bukkit.Bukkit; +import org.bukkit.configuration.file.YamlConfiguration; + +import java.util.Arrays; +import java.util.List; + +public class SpigotWorldConfig +{ + + private final String worldName; + private final YamlConfiguration config; + private boolean verbose; + + public SpigotWorldConfig(String worldName) + { + this.worldName = worldName; + this.config = SpigotConfig.config; + init(); + } + + public void init() + { + this.verbose = getBoolean( "verbose", true ); + + SpigotConfig.readConfig( SpigotWorldConfig.class, this ); + } + + private void log(String s) + { + if ( verbose ) + { + Bukkit.getLogger().info( s ); + } + } + + private void set(String path, Object val) + { + config.set( "world-settings.default." + path, val ); + } + + private boolean getBoolean(String path, boolean def) + { + config.addDefault( "world-settings.default." + path, def ); + return config.getBoolean( "world-settings." + worldName + "." + path, config.getBoolean( "world-settings.default." + path ) ); + } + + private double getDouble(String path, double def) + { + config.addDefault( "world-settings.default." + path, def ); + return config.getDouble( "world-settings." + worldName + "." + path, config.getDouble( "world-settings.default." + path ) ); + } + + private int getInt(String path, int def) + { + config.addDefault( "world-settings.default." + path, def ); + return config.getInt( "world-settings." + worldName + "." + path, config.getInt( "world-settings.default." + path ) ); + } + + private List getList(String path, T def) + { + config.addDefault( "world-settings.default." + path, def ); + return (List) config.getList( "world-settings." + worldName + "." + path, config.getList( "world-settings.default." + path ) ); + } + + private String getString(String path, String def) + { + config.addDefault( "world-settings.default." + path, def ); + return config.getString( "world-settings." + worldName + "." + path, config.getString( "world-settings.default." + path ) ); + } + + public int chunksPerTick; + public boolean clearChunksOnTick; + private void chunksPerTick() + { + chunksPerTick = getInt( "chunks-per-tick", 650 ); + clearChunksOnTick = getBoolean( "clear-tick-list", false ); + + } + + // Crop growth rates + public int cactusModifier; + public int caneModifier; + public int melonModifier; + public int mushroomModifier; + public int pumpkinModifier; + public int saplingModifier; + public int wheatModifier; + public int wartModifier; + private int getAndValidateGrowth(String crop) + { + int modifier = getInt( "growth." + crop.toLowerCase() + "-modifier", 100 ); + if ( modifier == 0 ) + { + modifier = 100; + } + + return modifier; + } + private void growthModifiers() + { + cactusModifier = getAndValidateGrowth( "Cactus" ); + caneModifier = getAndValidateGrowth( "Cane" ); + melonModifier = getAndValidateGrowth( "Melon" ); + mushroomModifier = getAndValidateGrowth( "Mushroom" ); + pumpkinModifier = getAndValidateGrowth( "Pumpkin" ); + saplingModifier = getAndValidateGrowth( "Sapling" ); + wheatModifier = getAndValidateGrowth( "Wheat" ); + wartModifier = getAndValidateGrowth( "NetherWart" ); + } + + public double itemMerge; + private void itemMerge() + { + itemMerge = getDouble("merge-radius.item", 2.5 ); + } + + public double expMerge; + private void expMerge() + { + expMerge = getDouble("merge-radius.exp", 3.0 ); + } + + public int viewDistance; + private void viewDistance() + { + viewDistance = getInt( "view-distance", Bukkit.getViewDistance() ); + } + + public byte mobSpawnRange; + private void mobSpawnRange() + { + mobSpawnRange = (byte) getInt( "mob-spawn-range", 4 ); + } + + public int animalActivationRange = 32; + public int monsterActivationRange = 32; + public int miscActivationRange = 16; + private void activationRange() + { + animalActivationRange = getInt( "entity-activation-range.animals", animalActivationRange ); + monsterActivationRange = getInt( "entity-activation-range.monsters", monsterActivationRange ); + miscActivationRange = getInt( "entity-activation-range.misc", miscActivationRange ); + } + + public int playerTrackingRange = 48; + public int animalTrackingRange = 48; + public int monsterTrackingRange = 48; + public int miscTrackingRange = 32; + public int otherTrackingRange = 64; + private void trackingRange() + { + playerTrackingRange = getInt( "entity-tracking-range.players", playerTrackingRange ); + animalTrackingRange = getInt( "entity-tracking-range.animals", animalTrackingRange ); + monsterTrackingRange = getInt( "entity-tracking-range.monsters", monsterTrackingRange ); + miscTrackingRange = getInt( "entity-tracking-range.misc", miscTrackingRange ); + otherTrackingRange = getInt( "entity-tracking-range.other", otherTrackingRange ); + } + + public int hopperTransfer; + public int hopperCheck; + public int hopperAmount; + private void hoppers() + { + // Set the tick delay between hopper item movements + hopperTransfer = getInt( "ticks-per.hopper-transfer", 8 ); + // Set the tick delay between checking for items after the associated + // container is empty. Default to the hopperTransfer value to prevent + // hopper sorting machines from becoming out of sync. + hopperCheck = getInt( "ticks-per.hopper-check", hopperTransfer ); + hopperAmount = getInt( "hopper-amount", 1 ); + } + + public boolean randomLightUpdates; + private void lightUpdates() + { + randomLightUpdates = getBoolean( "random-light-updates", false ); + } + + public boolean saveStructureInfo; + private void structureInfo() + { + saveStructureInfo = getBoolean( "save-structure-info", true ); + } + + public int itemDespawnRate; + private void itemDespawnRate() + { + itemDespawnRate = getInt( "item-despawn-rate", 6000 ); + } + + public int arrowDespawnRate; + private void arrowDespawnRate() + { + arrowDespawnRate = getInt( "arrow-despawn-rate", 1200 ); + } + + public boolean antiXray; + public int engineMode; + public List hiddenBlocks; + public List replaceBlocks; + public FastAntiXray antiXrayInstance; + private void antiXray() + { + antiXray = getBoolean( "anti-xray.enabled", true ); + + engineMode = getInt( "anti-xray.engine-mode", 1 ); + + if ( SpigotConfig.version < 5 ) + { + set( "anti-xray.blocks", null ); + } + hiddenBlocks = getList( "anti-xray.hide-blocks", Arrays.asList(14, 15, 16, 21, 48, 49, 54, 56, 73, 74, 82, 129, 130) ); + + replaceBlocks = getList( "anti-xray.replace-blocks", Arrays.asList(1, 5) ); + + antiXrayInstance = new FastAntiXray( this ); + } + + public boolean zombieAggressiveTowardsVillager; + private void zombieAggressiveTowardsVillager() + { + zombieAggressiveTowardsVillager = getBoolean( "zombie-aggressive-towards-villager", true ); + } + + public boolean nerfSpawnerMobs; + private void nerfSpawnerMobs() + { + nerfSpawnerMobs = getBoolean( "nerf-spawner-mobs", false ); + } + + public boolean enableZombiePigmenPortalSpawns; + private void enableZombiePigmenPortalSpawns() + { + enableZombiePigmenPortalSpawns = getBoolean( "enable-zombie-pigmen-portal-spawns", true ); + } + + public int maxBulkChunk; + private void bulkChunkCount() + { + maxBulkChunk = getInt( "max-bulk-chunks", 10 ); + } + + public int maxCollisionsPerEntity; + private void maxEntityCollision() + { + maxCollisionsPerEntity = getInt( "max-entity-collisions", 8 ); + } + + public int dragonDeathSoundRadius; + private void keepDragonDeathPerWorld() + { + dragonDeathSoundRadius = getInt( "dragon-death-sound-radius", 0 ); + } + + public int witherSpawnSoundRadius; + private void witherSpawnSoundRadius() + { + witherSpawnSoundRadius = getInt( "wither-spawn-sound-radius", 0 ); + } + + public int villageSeed; + public int largeFeatureSeed; + private void initWorldGenSeeds() + { + villageSeed = getInt( "seed-village", 10387312 ); + largeFeatureSeed = getInt( "seed-feature", 14357617 ); + } + + public float walkExhaustion; + public float sprintExhaustion; + public float combatExhaustion; + public float regenExhaustion; + private void initHunger() + { + walkExhaustion = (float) getDouble( "hunger.walk-exhaustion", 0.2 ); + sprintExhaustion = (float) getDouble( "hunger.sprint-exhaustion", 0.8 ); + combatExhaustion = (float) getDouble( "hunger.combat-exhaustion", 0.3 ); + regenExhaustion = (float) getDouble( "hunger.regen-exhaustion", 3 ); + } + + public int hangingTickFrequency; + private void hangingTickFrequency() + { + hangingTickFrequency = getInt( "hanging-tick-frequency", 100 ); + } +} diff --git a/azurite-server/src/main/java/org/spigotmc/TrackingRange.java b/azurite-server/src/main/java/org/spigotmc/TrackingRange.java new file mode 100644 index 0000000..9808831 --- /dev/null +++ b/azurite-server/src/main/java/org/spigotmc/TrackingRange.java @@ -0,0 +1,40 @@ +package org.spigotmc; + +import net.minecraft.server.*; + +public class TrackingRange +{ + + /** + * Gets the range an entity should be 'tracked' by players and visible in + * the client. + * + * @param entity + * @param defaultRange Default range defined by Mojang + * @return + */ + public static int getEntityTrackingRange(Entity entity, int defaultRange) + { + SpigotWorldConfig config = entity.world.spigotConfig; + if ( entity instanceof EntityPlayer ) + { + return config.playerTrackingRange; + } else if ( entity.activationType == 1 ) + { + return config.monsterTrackingRange; + } else if ( entity instanceof EntityGhast ) + { + return Math.max(config.monsterTrackingRange, config.monsterActivationRange); + } else if ( entity.activationType == 2 ) + { + return config.animalTrackingRange; + } else if ( entity instanceof EntityItemFrame || entity instanceof EntityPainting || entity instanceof EntityItem || entity instanceof EntityExperienceOrb ) + { + return config.miscTrackingRange; + } else + { + return config.otherTrackingRange; + } + } + +} diff --git a/azurite-server/src/main/java/org/spigotmc/ValidateUtils.java b/azurite-server/src/main/java/org/spigotmc/ValidateUtils.java new file mode 100644 index 0000000..58a9534 --- /dev/null +++ b/azurite-server/src/main/java/org/spigotmc/ValidateUtils.java @@ -0,0 +1,14 @@ +package org.spigotmc; + +public class ValidateUtils +{ + + public static String limit(String str, int limit) + { + if ( str.length() > limit ) + { + return str.substring( 0, limit ); + } + return str; + } +} diff --git a/azurite-server/src/main/java/org/spigotmc/WatchdogThread.java b/azurite-server/src/main/java/org/spigotmc/WatchdogThread.java new file mode 100644 index 0000000..7f616ff --- /dev/null +++ b/azurite-server/src/main/java/org/spigotmc/WatchdogThread.java @@ -0,0 +1,125 @@ +package org.spigotmc; + +import net.minecraft.server.MinecraftServer; +import org.bukkit.Bukkit; + +import java.lang.management.ManagementFactory; +import java.lang.management.MonitorInfo; +import java.lang.management.ThreadInfo; +import java.util.logging.Level; +import java.util.logging.Logger; + +public class WatchdogThread extends Thread +{ + + private static WatchdogThread instance; + private final long timeoutTime; + private final boolean restart; + private volatile long lastTick; + private volatile boolean stopping; + + private WatchdogThread(long timeoutTime, boolean restart) + { + super( "Paper Watchdog Thread" ); + this.timeoutTime = timeoutTime; + this.restart = restart; + } + + public static void doStart(int timeoutTime, boolean restart) + { + if ( instance == null ) + { + instance = new WatchdogThread( timeoutTime * 1000L, restart ); + instance.start(); + } + } + + public static void tick() + { + instance.lastTick = System.currentTimeMillis(); + } + + public static void doStop() + { + if ( instance != null ) + { + instance.stopping = true; + } + } + + @Override + public void run() + { + while ( !stopping ) + { + // + if ( lastTick != 0 && System.currentTimeMillis() > lastTick + timeoutTime ) + { + Logger log = Bukkit.getServer().getLogger(); + log.log( Level.SEVERE, "The server has stopped responding!" ); + log.log( Level.SEVERE, "Please report this to PaperSpigot directly!" ); + log.log( Level.SEVERE, "Be sure to include ALL relevant console errors and Minecraft crash reports" ); + log.log( Level.SEVERE, "Paper version: " + Bukkit.getServer().getVersion() ); + // + if(net.minecraft.server.World.haveWeSilencedAPhysicsCrash) + { + log.log( Level.SEVERE, "------------------------------" ); + log.log( Level.SEVERE, "During the run of the server, a physics stackoverflow was supressed" ); + log.log( Level.SEVERE, "near " + net.minecraft.server.World.blockLocation); + } + // + log.log( Level.SEVERE, "------------------------------" ); + log.log( Level.SEVERE, "Server thread dump (Look for plugins here before reporting to PaperSpigot!):" ); + dumpThread( ManagementFactory.getThreadMXBean().getThreadInfo( MinecraftServer.getServer().primaryThread.getId(), Integer.MAX_VALUE ), log ); + log.log( Level.SEVERE, "------------------------------" ); + // + log.log( Level.SEVERE, "Entire Thread Dump:" ); + ThreadInfo[] threads = ManagementFactory.getThreadMXBean().dumpAllThreads( true, true ); + for ( ThreadInfo thread : threads ) + { + dumpThread( thread, log ); + } + log.log( Level.SEVERE, "------------------------------" ); + + if ( restart ) + { + RestartCommand.restart(); + } + break; + } + + try + { + sleep( 10000 ); + } catch ( InterruptedException ex ) + { + interrupt(); + } + } + } + + private static void dumpThread(ThreadInfo thread, Logger log) + { + log.log( Level.SEVERE, "------------------------------" ); + // + log.log( Level.SEVERE, "Current Thread: " + thread.getThreadName() ); + log.log( Level.SEVERE, "\tPID: " + thread.getThreadId() + + " | Suspended: " + thread.isSuspended() + + " | Native: " + thread.isInNative() + + " | State: " + thread.getThreadState() ); + if ( thread.getLockedMonitors().length != 0 ) + { + log.log( Level.SEVERE, "\tThread is waiting on monitor(s):" ); + for ( MonitorInfo monitor : thread.getLockedMonitors() ) + { + log.log( Level.SEVERE, "\t\tLocked on:" + monitor.getLockedStackFrame() ); + } + } + log.log( Level.SEVERE, "\tStack:" ); + // + for ( StackTraceElement stack : thread.getStackTrace() ) + { + log.log( Level.SEVERE, "\t\t" + stack ); + } + } +} diff --git a/azurite-server/src/main/resources/assets/minecraft/lang/en_US.lang b/azurite-server/src/main/resources/assets/minecraft/lang/en_US.lang new file mode 100644 index 0000000..e2abdde --- /dev/null +++ b/azurite-server/src/main/resources/assets/minecraft/lang/en_US.lang @@ -0,0 +1,2678 @@ + +language.name=English +language.region=US +language.code=en_US + +gui.done=Done +gui.cancel=Cancel +gui.back=Back +gui.toTitle=Back to title screen +gui.toMenu=Back to server list +gui.up=Up +gui.down=Down +gui.yes=Yes +gui.no=No +gui.none=None +gui.all=All + +translation.test.none=Hello, world! +translation.test.complex=Prefix, %s%2$s again %s and %1$s lastly %s and also %1$s again! +translation.test.escape=%%s %%%s %%%%s %%%%%s +translation.test.invalid=hi % +translation.test.invalid2=hi % s +translation.test.args=%s %s +translation.test.world=world + +menu.game=Game menu +menu.singleplayer=Singleplayer +menu.multiplayer=Multiplayer +menu.online=Minecraft Realms +menu.options=Options... +menu.quit=Quit Game +menu.returnToMenu=Save and Quit to Title +menu.disconnect=Disconnect +menu.returnToGame=Back to Game +menu.switchingLevel=Switching worlds +menu.generatingLevel=Generating world +menu.loadingLevel=Loading world +menu.generatingTerrain=Building terrain +menu.convertingLevel=Converting world +menu.simulating=Simulating the world for a bit +menu.respawning=Respawning +menu.shareToLan=Open to LAN + +selectWorld.title=Select World +selectWorld.empty=empty +selectWorld.world=World +selectWorld.select=Play Selected World +selectWorld.create=Create New World +selectWorld.recreate=Re-Create +selectWorld.createDemo=Play New Demo World +selectWorld.delete=Delete +selectWorld.rename=Rename +selectWorld.deleteQuestion=Are you sure you want to delete this world? +selectWorld.deleteWarning=will be lost forever! (A long time!) +selectWorld.deleteButton=Delete +selectWorld.renameButton=Rename +selectWorld.renameTitle=Rename World +selectWorld.conversion=Must be converted! +selectWorld.newWorld=New World +selectWorld.newWorld.copyOf=Copy of %s +selectWorld.enterName=World Name +selectWorld.resultFolder=Will be saved in: +selectWorld.enterSeed=Seed for the World Generator +selectWorld.seedInfo=Leave blank for a random seed +selectWorld.cheats=Cheats +selectWorld.customizeType=Customize + +createWorld.customize.presets=Presets +createWorld.customize.presets.title=Select a Preset +createWorld.customize.presets.select=Use Preset +createWorld.customize.presets.share=Want to share your preset with someone? Use the below box! +createWorld.customize.presets.list=Alternatively, here's some we made earlier! +createWorld.customize.flat.title=Superflat Customization +createWorld.customize.flat.tile=Layer Material +createWorld.customize.flat.height=Height +createWorld.customize.flat.addLayer=Add Layer +createWorld.customize.flat.editLayer=Edit Layer +createWorld.customize.flat.removeLayer=Remove Layer +createWorld.customize.flat.layer.top=Top - %d +createWorld.customize.flat.layer=%d +createWorld.customize.flat.layer.bottom=Bottom - %d + +createWorld.customize.custom.page0=Basic Settings +createWorld.customize.custom.page1=Ore Settings +createWorld.customize.custom.page2=Advanced Settings (Expert Users Only!) +createWorld.customize.custom.page3=Extra Advanced Settings (Expert Users Only!) +createWorld.customize.custom.randomize=Randomize +createWorld.customize.custom.prev=Previous Page +createWorld.customize.custom.next=Next Page +createWorld.customize.custom.defaults=Defaults +createWorld.customize.custom.confirm1=This will overwrite your current +createWorld.customize.custom.confirm2=settings and cannot be undone. +createWorld.customize.custom.confirmTitle=Warning! +createWorld.customize.custom.mainNoiseScaleX=Main Noise Scale X +createWorld.customize.custom.mainNoiseScaleY=Main Noise Scale Y +createWorld.customize.custom.mainNoiseScaleZ=Main Noise Scale Z +createWorld.customize.custom.depthNoiseScaleX=Depth Noise Scale X +createWorld.customize.custom.depthNoiseScaleZ=Depth Noise Scale Z +createWorld.customize.custom.depthNoiseScaleExponent=Depth Noise Exponent +createWorld.customize.custom.baseSize=Depth Base Size +createWorld.customize.custom.coordinateScale=Coordinate Scale +createWorld.customize.custom.heightScale=Height Scale +createWorld.customize.custom.stretchY=Height Stretch +createWorld.customize.custom.upperLimitScale=Upper Limit Scale +createWorld.customize.custom.lowerLimitScale=Lower Limit Scale +createWorld.customize.custom.biomeDepthWeight=Biome Depth Weight +createWorld.customize.custom.biomeDepthOffset=Biome Depth Offset +createWorld.customize.custom.biomeScaleWeight=Biome Scale Weight +createWorld.customize.custom.biomeScaleOffset=Biome Scale Offset +createWorld.customize.custom.seaLevel=Sea Level +createWorld.customize.custom.useCaves=Caves +createWorld.customize.custom.useStrongholds=Strongholds +createWorld.customize.custom.useVillages=Villages +createWorld.customize.custom.useMineShafts=Mineshafts +createWorld.customize.custom.useTemples=Temples +createWorld.customize.custom.useMonuments=Ocean Monuments +createWorld.customize.custom.useRavines=Ravines +createWorld.customize.custom.useDungeons=Dungeons +createWorld.customize.custom.dungeonChance=Dungeon Count +createWorld.customize.custom.useWaterLakes=Water Lakes +createWorld.customize.custom.waterLakeChance=Water Lake Rarity +createWorld.customize.custom.useLavaLakes=Lava Lakes +createWorld.customize.custom.lavaLakeChance=Lava Lake Rarity +createWorld.customize.custom.useLavaOceans=Lava Oceans +createWorld.customize.custom.fixedBiome=Biome +createWorld.customize.custom.biomeSize=Biome Size +createWorld.customize.custom.riverSize=River Size + +createWorld.customize.custom.size= Spawn Size +createWorld.customize.custom.count= Spawn Tries +createWorld.customize.custom.minHeight= Min. Height +createWorld.customize.custom.maxHeight= Max. Height +createWorld.customize.custom.center= Center Height +createWorld.customize.custom.spread= Spread Height + +createWorld.customize.custom.presets.title=Customize World Presets +createWorld.customize.custom.presets=Presets +createWorld.customize.custom.preset.waterWorld=Water World +createWorld.customize.custom.preset.isleLand=Isle Land +createWorld.customize.custom.preset.caveDelight=Caver's Delight +createWorld.customize.custom.preset.mountains=Mountain Madness +createWorld.customize.custom.preset.drought=Drought +createWorld.customize.custom.preset.caveChaos=Caves of Chaos +createWorld.customize.custom.preset.goodLuck=Good Luck + +gameMode.survival=Survival Mode +gameMode.creative=Creative Mode +gameMode.adventure=Adventure Mode +gameMode.spectator=Spectator Mode +gameMode.hardcore=Hardcore Mode! +gameMode.changed=Your game mode has been updated + +selectWorld.gameMode=Game Mode +selectWorld.gameMode.survival=Survival +selectWorld.gameMode.survival.line1=Search for resources, crafting, gain +selectWorld.gameMode.survival.line2=levels, health and hunger +selectWorld.gameMode.creative=Creative +selectWorld.gameMode.creative.line1=Unlimited resources, free flying and +selectWorld.gameMode.creative.line2=destroy blocks instantly +selectWorld.gameMode.spectator=Spectator +selectWorld.gameMode.spectator.line1=You can look but don't touch +selectWorld.gameMode.spectator.line2= +selectWorld.gameMode.hardcore=Hardcore +selectWorld.gameMode.hardcore.line1=Same as survival mode, locked at hardest +selectWorld.gameMode.hardcore.line2=difficulty, and one life only +selectWorld.gameMode.adventure=Adventure +selectWorld.gameMode.adventure.line1=Same as survival mode, but blocks can't +selectWorld.gameMode.adventure.line2=be added or removed +selectWorld.moreWorldOptions=More World Options... +selectWorld.mapFeatures=Generate Structures: +selectWorld.mapFeatures.info=Villages, dungeons etc +selectWorld.mapType=World Type: +selectWorld.mapType.normal=Normal +selectWorld.allowCommands=Allow Cheats: +selectWorld.allowCommands.info=Commands like /gamemode, /xp +selectWorld.hardcoreMode=Hardcore: +selectWorld.hardcoreMode.info=World is deleted upon death +selectWorld.bonusItems=Bonus Chest: + +generator.default=Default +generator.flat=Superflat +generator.largeBiomes=Large Biomes +generator.amplified=AMPLIFIED +generator.customized=Customized +generator.debug_all_block_states=Debug Mode + +generator.amplified.info=Notice: Just for fun, requires beefy computer + +selectServer.title=Select Server +selectServer.empty=empty +selectServer.select=Join Server +selectServer.direct=Direct Connect +selectServer.edit=Edit +selectServer.delete=Delete +selectServer.add=Add server +selectServer.defaultName=Minecraft Server +selectServer.deleteQuestion=Are you sure you want to remove this server? +selectServer.deleteWarning=will be lost forever! (A long time!) +selectServer.deleteButton=Delete +selectServer.refresh=Refresh +selectServer.hiddenAddress=(Hidden) +addServer.title=Edit Server Info +addServer.enterName=Server Name +addServer.enterIp=Server Address +addServer.add=Done +addServer.hideAddress=Hide Address +addServer.resourcePack=Server Resource Packs +addServer.resourcePack.enabled=Enabled +addServer.resourcePack.disabled=Disabled +addServer.resourcePack.prompt=Prompt +lanServer.title=LAN World +lanServer.scanning=Scanning for games on your local network +lanServer.start=Start LAN World +lanServer.otherPlayers=Settings for Other Players +mcoServer.title=Minecraft Online World + +multiplayer.title=Play Multiplayer +multiplayer.connect=Connect +multiplayer.info1=Minecraft Multiplayer is currently not finished, but there +multiplayer.info2=is some buggy early testing going on. +multiplayer.ipinfo=Enter the IP of a server to connect to it: +multiplayer.texturePrompt.line1=This server recommends the use of a custom resource pack. +multiplayer.texturePrompt.line2=Would you like to download and install it automagically? +multiplayer.downloadingTerrain=Downloading terrain +multiplayer.downloadingStats=Downloading statistics & achievements... +multiplayer.stopSleeping=Leave Bed +multiplayer.player.joined=%s joined the game +multiplayer.player.joined.renamed=%s (formerly known as %s) joined the game +multiplayer.player.left=%s left the game + +chat.cannotSend=Cannot send chat message +chat.type.text=<%s> %s +chat.type.emote=* %s %s +chat.type.announcement=[%s] %s +chat.type.admin=[%s: %s] +chat.type.achievement=%s has just earned the achievement %s +chat.type.achievement.taken=%s has lost the achievement %s +chat.link.confirm=Are you sure you want to open the following website? +chat.link.warning=Never open links from people that you don't trust! +chat.copy=Copy to Clipboard +chat.link.confirmTrusted=Do you want to open this link or copy it to your clipboard? +chat.link.open=Open in browser + +chat.stream.text=(%s) <%s> %s +chat.stream.emote=(%s) * %s %s + +menu.playdemo=Play Demo World +menu.resetdemo=Reset Demo World + +demo.day.1=This demo will last five game days, do your best! +demo.day.2=Day Two +demo.day.3=Day Three +demo.day.4=Day Four +demo.day.5=This is your last day! +demo.day.warning=Your time is almost up! +demo.day.6=You have passed your fifth day, use F2 to save a screenshot of your creation +demo.reminder=The demo time has expired, buy the game to continue or start a new world! +demo.remainingTime=Remaining time: %s +demo.demoExpired=Demo time's up! +demo.help.movement=Use %1$s, %2$s, %3$s, %4$s and the mouse to move around +demo.help.movementShort=Move by pressing %1$s, %2$s, %3$s, %4$s +demo.help.movementMouse=Look around using the mouse +demo.help.jump=Jump by pressing %1$s +demo.help.inventory=Use %1$s to open your inventory +demo.help.title=Minecraft Demo Mode +demo.help.fullWrapped=This demo will last 5 ingame days (about 1 hour and 40 minutes of real time). Check the achievements for hints! Have fun! +demo.help.buy=Purchase Now! +demo.help.later=Continue Playing! + +connect.connecting=Connecting to the server... +connect.authorizing=Logging in... +connect.failed=Failed to connect to the server + +disconnect.genericReason=%s +disconnect.disconnected=Disconnected by Server +disconnect.lost=Connection Lost +disconnect.kicked=Was kicked from the game +disconnect.timeout=Timed out +disconnect.closed=Connection closed +disconnect.loginFailed=Failed to login +disconnect.loginFailedInfo=Failed to login: %s +disconnect.loginFailedInfo.serversUnavailable=The authentication servers are currently down for maintenance. +disconnect.loginFailedInfo.invalidSession=Invalid session (Try restarting your game) +disconnect.quitting=Quitting +disconnect.endOfStream=End of stream +disconnect.overflow=Buffer overflow +disconnect.spam=Kicked for spamming + +soundCategory.master=Master Volume +soundCategory.music=Music +soundCategory.record=Jukebox/Noteblocks +soundCategory.weather=Weather +soundCategory.hostile=Hostile Creatures +soundCategory.neutral=Friendly Creatures +soundCategory.player=Players +soundCategory.block=Blocks +soundCategory.ambient=Ambient/Environment + +record.nowPlaying=Now playing: %s + +options.off=OFF +options.on=ON +options.visible=Shown +options.hidden=Hidden +options.title=Options +options.controls=Controls... +options.video=Video Settings... +options.language=Language... +options.stream=Broadcast Settings... +options.sounds=Music & Sounds... +options.sounds.title=Music & Sound Options +options.languageWarning=Language translations may not be 100%% accurate +options.videoTitle=Video Settings +options.customizeTitle=Customize World Settings +options.music=Music +options.sound=Sound +options.invertMouse=Invert Mouse +options.fov=FOV +options.fov.min=Normal +options.fov.max=Quake Pro +options.saturation=Saturation +options.gamma=Brightness +options.gamma.min=Moody +options.gamma.max=Bright +options.sensitivity=Sensitivity +options.sensitivity.min=*yawn* +options.sensitivity.max=HYPERSPEED!!! +options.renderDistance=Render Distance +options.renderDistance.tiny=Tiny +options.renderDistance.short=Short +options.renderDistance.normal=Normal +options.renderDistance.far=Far +options.viewBobbing=View Bobbing +options.ao=Smooth Lighting +options.ao.off=OFF +options.ao.min=Minimum +options.ao.max=Maximum +options.anaglyph=3D Anaglyph +options.framerateLimit=Max Framerate +options.framerateLimit.max=Unlimited +options.difficulty=Difficulty +options.difficulty.peaceful=Peaceful +options.difficulty.easy=Easy +options.difficulty.normal=Normal +options.difficulty.hard=Hard +options.difficulty.hardcore=Hardcore +options.graphics=Graphics +options.graphics.fancy=Fancy +options.graphics.fast=Fast +options.guiScale=GUI Scale +options.guiScale.auto=Auto +options.guiScale.small=Small +options.guiScale.normal=Normal +options.guiScale.large=Large +options.advancedOpengl=Advanced OpenGL +options.fboEnable=Enable FBOs +options.postProcessEnable=Enable Post-Processing +options.renderClouds=Clouds +options.qualityButton=Video Quality Settings... +options.qualityVideoTitle=Video Quality Settings +options.performanceButton=Video Performance Settings... +options.performanceVideoTitle=Video Performance Settings +options.advancedButton=Advanced Video Settings... +options.advancedVideoTitle=Advanced Video Settings +options.postButton=Post-Processing Settings... +options.postVideoTitle=Post-Processing Settings +options.farWarning1=A 64 bit Java installation is recommended +options.farWarning2=for 'Far' render distance (you have 32 bit) +options.particles=Particles +options.particles.all=All +options.particles.decreased=Decreased +options.particles.minimal=Minimal +options.multiplayer.title=Multiplayer Settings... +options.chat.title=Chat Settings... +options.chat.visibility=Chat +options.chat.visibility.full=Shown +options.chat.visibility.system=Commands Only +options.chat.visibility.hidden=Hidden +options.chat.color=Colors +options.chat.opacity=Opacity +options.chat.links=Web Links +options.chat.links.prompt=Prompt on Links +options.chat.scale=Scale +options.chat.width=Width +options.chat.height.focused=Focused Height +options.chat.height.unfocused=Unfocused Height +options.skinCustomisation=Skin Customization... +options.skinCustomisation.title=Skin Customization +options.modelPart.cape=Cape +options.modelPart.hat=Hat +options.modelPart.jacket=Jacket +options.modelPart.left_sleeve=Left Sleeve +options.modelPart.right_sleeve=Right Sleeve +options.modelPart.left_pants_leg=Left Pants Leg +options.modelPart.right_pants_leg=Right Pants Leg +options.snooper=Allow Snooper +options.snooper.view=Snooper Settings... +options.snooper.title=Machine Specs Collection +options.snooper.desc=We want to collect information about your machine to help improve Minecraft by knowing what we can support and where the biggest problems are. All of this information is completely anonymous and viewable below. We promise we won't do anything bad with this data, but if you want to opt out then feel free to toggle it off! +options.resourcepack=Resource Packs... +options.fullscreen=Fullscreen +options.vsync=Use VSync +options.vbo=Use VBOs +options.touchscreen=Touchscreen Mode +options.blockAlternatives=Alternate Blocks +options.reducedDebugInfo=Reduced Debug Info +options.entityShadows=Entity Shadows + +options.mipmapLevels=Mipmap Levels +options.forceUnicodeFont=Force Unicode Font + +options.stream.title=Twitch Broadcast Settings +options.stream.bytesPerPixel=Quality +options.stream.micVolumne=Mic Volume +options.stream.micToggleBehavior=Push To +options.stream.mic_toggle.mute=Mute +options.stream.mic_toggle.talk=Talk +options.stream.systemVolume=System Volume +options.stream.kbps=Bandwidth +options.stream.fps=Framerate +options.stream.sendMetadata=Send Metadata +options.stream.compression=Compression +options.stream.compression.low=Low +options.stream.compression.medium=Medium +options.stream.compression.high=High +options.stream.estimation=Estimated resolution: %dx%d +options.stream.changes=You may need to restart your stream for these changes to take place. +options.stream.ingestSelection=Broadcast Server List +options.stream.ingest.title=Twitch Broadcast Servers +options.stream.ingest.reset=Reset Preference +options.stream.chat.title=Twitch Chat Settings +options.stream.chat.enabled=Enable +options.stream.chat.enabled.streaming=Whilst Streaming +options.stream.chat.enabled.always=Always +options.stream.chat.enabled.never=Never +options.stream.chat.userFilter=User Filter +options.stream.chat.userFilter.all=All Viewers +options.stream.chat.userFilter.subs=Subscribers +options.stream.chat.userFilter.mods=Moderators + +difficulty.lock.title=Lock World Difficulty +difficulty.lock.question=Are you sure you want to lock the difficulty of this world? This will set this world to always be %1$s, and you will never be able to change that again. + +title.oldgl1=Old graphics card detected; this may prevent you from +title.oldgl2=playing in the future as OpenGL 2.0 will be required. + +controls.title=Controls +controls.reset=Reset +controls.resetAll=Reset Keys + +key.sprint=Sprint +key.forward=Walk Forwards +key.left=Strafe Left +key.back=Walk Backwards +key.right=Strafe Right +key.jump=Jump +key.inventory=Inventory +key.drop=Drop Item +key.chat=Open Chat +key.sneak=Sneak +key.playerlist=List Players +key.attack=Attack/Destroy +key.use=Use Item/Place Block +key.pickItem=Pick Block +key.mouseButton=Button %1$s +key.command=Open Command +key.screenshot=Take Screenshot +key.togglePerspective=Toggle Perspective +key.smoothCamera=Toggle Cinematic Camera +key.fullscreen=Toggle Fullscreen +key.spectatorOutlines=Highlight Players (Spectators) +key.hotbar.1=Hotbar Slot 1 +key.hotbar.2=Hotbar Slot 2 +key.hotbar.3=Hotbar Slot 3 +key.hotbar.4=Hotbar Slot 4 +key.hotbar.5=Hotbar Slot 5 +key.hotbar.6=Hotbar Slot 6 +key.hotbar.7=Hotbar Slot 7 +key.hotbar.8=Hotbar Slot 8 +key.hotbar.9=Hotbar Slot 9 +key.streamStartStop=Start/Stop Stream +key.streamPauseUnpause=Pause/Unpause Stream +key.streamCommercial=Show Stream Commercials +key.streamToggleMic=Push To Talk/Mute + +key.categories.movement=Movement +key.categories.misc=Miscellaneous +key.categories.multiplayer=Multiplayer +key.categories.gameplay=Gameplay +key.categories.ui=Game Interface +key.categories.inventory=Inventory +key.categories.stream=Streaming + +resourcePack.openFolder=Open resource pack folder +resourcePack.title=Select Resource Packs +resourcePack.available.title=Available Resource Packs +resourcePack.selected.title=Selected Resource Packs +resourcePack.folderInfo=(Place resource pack files here) +resourcePack.incompatible=Incompatible +resourcePack.incompatible.old=(Made for an older version of Minecraft) +resourcePack.incompatible.new=(Made for a newer version of Minecraft) +resourcePack.incompatible.confirm.title=Are you sure you want to load this resource pack? +resourcePack.incompatible.confirm.old=This resource pack was made for an older version of Minecraft and may no longer work correctly. +resourcePack.incompatible.confirm.new=This resource pack was made for a newer version of Minecraft and may no longer work correctly. + +sign.edit=Edit sign message + +book.pageIndicator=Page %1$s of %2$s +book.byAuthor=by %1$s +book.signButton=Sign +book.editTitle=Enter Book Title: +book.finalizeButton=Sign and Close +book.finalizeWarning=Note! When you sign the book, it will no longer be editable. +book.generation.0=Original +book.generation.1=Copy of original +book.generation.2=Copy of a copy +book.generation.3=Tattered + +merchant.deprecated=Trade something else to unlock! + +tile.barrier.name=Barrier +tile.stone.stone.name=Stone +tile.stone.granite.name=Granite +tile.stone.graniteSmooth.name=Polished Granite +tile.stone.diorite.name=Diorite +tile.stone.dioriteSmooth.name=Polished Diorite +tile.stone.andesite.name=Andesite +tile.stone.andesiteSmooth.name=Polished Andesite +tile.hayBlock.name=Hay Bale +tile.grass.name=Grass Block +tile.dirt.name=Dirt +tile.dirt.default.name=Dirt +tile.dirt.coarse.name=Coarse Dirt +tile.dirt.podzol.name=Podzol +tile.stonebrick.name=Cobblestone +tile.wood.name=Wooden Planks +tile.wood.oak.name=Oak Wood Planks +tile.wood.spruce.name=Spruce Wood Planks +tile.wood.birch.name=Birch Wood Planks +tile.wood.jungle.name=Jungle Wood Planks +tile.wood.acacia.name=Acacia Wood Planks +tile.wood.big_oak.name=Dark Oak Wood Planks +tile.sapling.oak.name=Oak Sapling +tile.sapling.spruce.name=Spruce Sapling +tile.sapling.birch.name=Birch Sapling +tile.sapling.jungle.name=Jungle Sapling +tile.sapling.acacia.name=Acacia Sapling +tile.sapling.big_oak.name=Dark Oak Sapling +tile.deadbush.name=Dead Bush +tile.bedrock.name=Bedrock +tile.water.name=Water +tile.lava.name=Lava +tile.sand.name=Sand +tile.sand.default.name=Sand +tile.sand.red.name=Red Sand +tile.sandStone.name=Sandstone +tile.sandStone.default.name=Sandstone +tile.sandStone.chiseled.name=Chiseled Sandstone +tile.sandStone.smooth.name=Smooth Sandstone +tile.redSandStone.name=Red Sandstone +tile.redSandStone.default.name=Red Sandstone +tile.redSandStone.chiseled.name=Chiseled Red Sandstone +tile.redSandStone.smooth.name=Smooth Red Sandstone +tile.gravel.name=Gravel +tile.oreGold.name=Gold Ore +tile.oreIron.name=Iron Ore +tile.oreCoal.name=Coal Ore +tile.log.name=Wood +tile.log.oak.name=Oak Wood +tile.log.spruce.name=Spruce Wood +tile.log.birch.name=Birch Wood +tile.log.jungle.name=Jungle Wood +tile.log.acacia.name=Acacia Wood +tile.log.big_oak.name=Dark Oak Wood +tile.leaves.name=Leaves +tile.leaves.oak.name=Oak Leaves +tile.leaves.spruce.name=Spruce Leaves +tile.leaves.birch.name=Birch Leaves +tile.leaves.jungle.name=Jungle Leaves +tile.leaves.acacia.name=Acacia Leaves +tile.leaves.big_oak.name=Dark Oak Leaves +tile.tallgrass.name=Grass +tile.tallgrass.shrub.name=Shrub +tile.tallgrass.grass.name=Grass +tile.tallgrass.fern.name=Fern +tile.sponge.dry.name=Sponge +tile.sponge.wet.name=Wet Sponge +tile.glass.name=Glass +tile.stainedGlass.name=Stained Glass +tile.stainedGlass.black.name=Black Stained Glass +tile.stainedGlass.red.name=Red Stained Glass +tile.stainedGlass.green.name=Green Stained Glass +tile.stainedGlass.brown.name=Brown Stained Glass +tile.stainedGlass.blue.name=Blue Stained Glass +tile.stainedGlass.purple.name=Purple Stained Glass +tile.stainedGlass.cyan.name=Cyan Stained Glass +tile.stainedGlass.silver.name=Light Gray Stained Glass +tile.stainedGlass.gray.name=Gray Stained Glass +tile.stainedGlass.pink.name=Pink Stained Glass +tile.stainedGlass.lime.name=Lime Stained Glass +tile.stainedGlass.yellow.name=Yellow Stained Glass +tile.stainedGlass.lightBlue.name=Light Blue Stained Glass +tile.stainedGlass.magenta.name=Magenta Stained Glass +tile.stainedGlass.orange.name=Orange Stained Glass +tile.stainedGlass.white.name=White Stained Glass +tile.thinStainedGlass.name=Stained Glass Pane +tile.thinStainedGlass.black.name=Black Stained Glass Pane +tile.thinStainedGlass.red.name=Red Stained Glass Pane +tile.thinStainedGlass.green.name=Green Stained Glass Pane +tile.thinStainedGlass.brown.name=Brown Stained Glass Pane +tile.thinStainedGlass.blue.name=Blue Stained Glass Pane +tile.thinStainedGlass.purple.name=Purple Stained Glass Pane +tile.thinStainedGlass.cyan.name=Cyan Stained Glass Pane +tile.thinStainedGlass.silver.name=Light Gray Stained Glass Pane +tile.thinStainedGlass.gray.name=Gray Stained Glass Pane +tile.thinStainedGlass.pink.name=Pink Stained Glass Pane +tile.thinStainedGlass.lime.name=Lime Stained Glass Pane +tile.thinStainedGlass.yellow.name=Yellow Stained Glass Pane +tile.thinStainedGlass.lightBlue.name=Light Blue Stained Glass Pane +tile.thinStainedGlass.magenta.name=Magenta Stained Glass Pane +tile.thinStainedGlass.orange.name=Orange Stained Glass Pane +tile.thinStainedGlass.white.name=White Stained Glass Pane +tile.thinGlass.name=Glass Pane +tile.cloth.name=Wool +tile.flower1.name=Flower +tile.flower1.dandelion.name=Dandelion +tile.flower2.name=Flower +tile.flower2.poppy.name=Poppy +tile.flower2.blueOrchid.name=Blue Orchid +tile.flower2.allium.name=Allium +tile.flower2.houstonia.name=Azure Bluet +tile.flower2.tulipRed.name=Red Tulip +tile.flower2.tulipOrange.name=Orange Tulip +tile.flower2.tulipWhite.name=White Tulip +tile.flower2.tulipPink.name=Pink Tulip +tile.flower2.oxeyeDaisy.name=Oxeye Daisy +tile.doublePlant.name=Plant +tile.doublePlant.sunflower.name=Sunflower +tile.doublePlant.syringa.name=Lilac +tile.doublePlant.grass.name=Double Tallgrass +tile.doublePlant.fern.name=Large Fern +tile.doublePlant.rose.name=Rose Bush +tile.doublePlant.paeonia.name=Peony +tile.mushroom.name=Mushroom +tile.blockGold.name=Block of Gold +tile.blockIron.name=Block of Iron +tile.stoneSlab.name=Stone Slab +tile.stoneSlab.stone.name=Stone Slab +tile.stoneSlab.sand.name=Sandstone Slab +tile.stoneSlab.wood.name=Wooden Slab +tile.stoneSlab.cobble.name=Cobblestone Slab +tile.stoneSlab.brick.name=Bricks Slab +tile.stoneSlab.smoothStoneBrick.name=Stone Bricks Slab +tile.stoneSlab.netherBrick.name=Nether Brick Slab +tile.stoneSlab.quartz.name=Quartz Slab +tile.stoneSlab2.red_sandstone.name=Red Sandstone Slab +tile.woodSlab.name=Wood Slab +tile.woodSlab.oak.name=Oak Wood Slab +tile.woodSlab.spruce.name=Spruce Wood Slab +tile.woodSlab.birch.name=Birch Wood Slab +tile.woodSlab.jungle.name=Jungle Wood Slab +tile.woodSlab.acacia.name=Acacia Wood Slab +tile.woodSlab.big_oak.name=Dark Oak Wood Slab +tile.brick.name=Bricks +tile.tnt.name=TNT +tile.bookshelf.name=Bookshelf +tile.stoneMoss.name=Moss Stone +tile.obsidian.name=Obsidian +tile.torch.name=Torch +tile.fire.name=Fire +tile.mobSpawner.name=Monster Spawner +tile.stairsWood.name=Oak Wood Stairs +tile.stairsWoodSpruce.name=Spruce Wood Stairs +tile.stairsWoodBirch.name=Birch Wood Stairs +tile.stairsWoodJungle.name=Jungle Wood Stairs +tile.stairsWoodAcacia.name=Acacia Wood Stairs +tile.stairsWoodDarkOak.name=Dark Oak Wood Stairs +tile.chest.name=Chest +tile.chestTrap.name=Trapped Chest +tile.redstoneDust.name=Redstone Dust +tile.oreDiamond.name=Diamond Ore +tile.blockCoal.name=Block of Coal +tile.blockDiamond.name=Block of Diamond +tile.workbench.name=Crafting Table +tile.crops.name=Crops +tile.farmland.name=Farmland +tile.furnace.name=Furnace +tile.sign.name=Sign +tile.doorWood.name=Wooden Door +tile.ladder.name=Ladder +tile.rail.name=Rail +tile.goldenRail.name=Powered Rail +tile.activatorRail.name=Activator Rail +tile.detectorRail.name=Detector Rail +tile.stairsStone.name=Cobblestone Stairs +tile.stairsSandStone.name=Sandstone Stairs +tile.stairsRedSandStone.name=Red Sandstone Stairs +tile.lever.name=Lever +tile.pressurePlateStone.name=Stone Pressure Plate +tile.pressurePlateWood.name=Wooden Pressure Plate +tile.weightedPlate_light.name=Weighted Pressure Plate (Light) +tile.weightedPlate_heavy.name=Weighted Pressure Plate (Heavy) +tile.doorIron.name=Iron Door +tile.oreRedstone.name=Redstone Ore +tile.notGate.name=Redstone Torch +tile.button.name=Button +tile.snow.name=Snow +tile.woolCarpet.name=Carpet +tile.woolCarpet.black.name=Black Carpet +tile.woolCarpet.red.name=Red Carpet +tile.woolCarpet.green.name=Green Carpet +tile.woolCarpet.brown.name=Brown Carpet +tile.woolCarpet.blue.name=Blue Carpet +tile.woolCarpet.purple.name=Purple Carpet +tile.woolCarpet.cyan.name=Cyan Carpet +tile.woolCarpet.silver.name=Light Gray Carpet +tile.woolCarpet.gray.name=Gray Carpet +tile.woolCarpet.pink.name=Pink Carpet +tile.woolCarpet.lime.name=Lime Carpet +tile.woolCarpet.yellow.name=Yellow Carpet +tile.woolCarpet.lightBlue.name=Light Blue Carpet +tile.woolCarpet.magenta.name=Magenta Carpet +tile.woolCarpet.orange.name=Orange Carpet +tile.woolCarpet.white.name=Carpet +tile.ice.name=Ice +tile.icePacked.name=Packed Ice +tile.cactus.name=Cactus +tile.clay.name=Clay +tile.clayHardenedStained.name=Stained Clay +tile.clayHardenedStained.black.name=Black Stained Clay +tile.clayHardenedStained.red.name=Red Stained Clay +tile.clayHardenedStained.green.name=Green Stained Clay +tile.clayHardenedStained.brown.name=Brown Stained Clay +tile.clayHardenedStained.blue.name=Blue Stained Clay +tile.clayHardenedStained.purple.name=Purple Stained Clay +tile.clayHardenedStained.cyan.name=Cyan Stained Clay +tile.clayHardenedStained.silver.name=Light Gray Stained Clay +tile.clayHardenedStained.gray.name=Gray Stained Clay +tile.clayHardenedStained.pink.name=Pink Stained Clay +tile.clayHardenedStained.lime.name=Lime Stained Clay +tile.clayHardenedStained.yellow.name=Yellow Stained Clay +tile.clayHardenedStained.lightBlue.name=Light Blue Stained Clay +tile.clayHardenedStained.magenta.name=Magenta Stained Clay +tile.clayHardenedStained.orange.name=Orange Stained Clay +tile.clayHardenedStained.white.name=White Stained Clay +tile.clayHardened.name=Hardened Clay +tile.reeds.name=Sugar cane +tile.jukebox.name=Jukebox +tile.fence.name=Oak Fence +tile.spruceFence.name=Spruce Fence +tile.birchFence.name=Birch Fence +tile.jungleFence.name=Jungle Fence +tile.darkOakFence.name=Dark Oak Fence +tile.acaciaFence.name=Acacia Fence +tile.fenceGate.name=Oak Fence Gate +tile.spruceFenceGate.name=Spruce Fence Gate +tile.birchFenceGate.name=Birch Fence Gate +tile.jungleFenceGate.name=Jungle Fence Gate +tile.darkOakFenceGate.name=Dark Oak Fence Gate +tile.acaciaFenceGate.name=Acacia Fence Gate +tile.pumpkinStem.name=Pumpkin Stem +tile.pumpkin.name=Pumpkin +tile.litpumpkin.name=Jack o'Lantern +tile.hellrock.name=Netherrack +tile.hellsand.name=Soul Sand +tile.lightgem.name=Glowstone +tile.portal.name=Portal +tile.cloth.black.name=Black Wool +tile.cloth.red.name=Red Wool +tile.cloth.green.name=Green Wool +tile.cloth.brown.name=Brown Wool +tile.cloth.blue.name=Blue Wool +tile.cloth.purple.name=Purple Wool +tile.cloth.cyan.name=Cyan Wool +tile.cloth.silver.name=Light Gray Wool +tile.cloth.gray.name=Gray Wool +tile.cloth.pink.name=Pink Wool +tile.cloth.lime.name=Lime Wool +tile.cloth.yellow.name=Yellow Wool +tile.cloth.lightBlue.name=Light Blue Wool +tile.cloth.magenta.name=Magenta Wool +tile.cloth.orange.name=Orange Wool +tile.cloth.white.name=Wool +tile.oreLapis.name=Lapis Lazuli Ore +tile.blockLapis.name=Lapis Lazuli Block +tile.dispenser.name=Dispenser +tile.dropper.name=Dropper +tile.musicBlock.name=Note Block +tile.cake.name=Cake +tile.bed.name=Bed +tile.bed.occupied=This bed is occupied +tile.bed.noSleep=You can only sleep at night +tile.bed.notSafe=You may not rest now, there are monsters nearby +tile.bed.notValid=Your home bed was missing or obstructed +tile.lockedchest.name=Locked chest +tile.trapdoor.name=Wooden Trapdoor +tile.ironTrapdoor.name=Iron Trapdoor +tile.web.name=Cobweb +tile.stonebricksmooth.name=Stone Bricks +tile.stonebricksmooth.default.name=Stone Bricks +tile.stonebricksmooth.mossy.name=Mossy Stone Bricks +tile.stonebricksmooth.cracked.name=Cracked Stone Bricks +tile.stonebricksmooth.chiseled.name=Chiseled Stone Bricks +tile.monsterStoneEgg.name=Stone Monster Egg +tile.monsterStoneEgg.stone.name=Stone Monster Egg +tile.monsterStoneEgg.cobble.name=Cobblestone Monster Egg +tile.monsterStoneEgg.brick.name=Stone Brick Monster Egg +tile.monsterStoneEgg.mossybrick.name=Mossy Stone Brick Monster Egg +tile.monsterStoneEgg.crackedbrick.name=Cracked Stone Brick Monster Egg +tile.monsterStoneEgg.chiseledbrick.name=Chiseled Stone Brick Monster Egg +tile.pistonBase.name=Piston +tile.pistonStickyBase.name=Sticky Piston +tile.fenceIron.name=Iron Bars +tile.melon.name=Melon +tile.stairsBrick.name=Brick Stairs +tile.stairsStoneBrickSmooth.name=Stone Brick Stairs +tile.vine.name=Vines +tile.netherBrick.name=Nether Brick +tile.netherFence.name=Nether Brick Fence +tile.stairsNetherBrick.name=Nether Brick Stairs +tile.netherStalk.name=Nether Wart +tile.cauldron.name=Cauldron +tile.enchantmentTable.name=Enchantment Table +tile.anvil.name=Anvil +tile.anvil.intact.name=Anvil +tile.anvil.slightlyDamaged.name=Slightly Damaged Anvil +tile.anvil.veryDamaged.name=Very Damaged Anvil +tile.whiteStone.name=End Stone +tile.endPortalFrame.name=End Portal +tile.mycel.name=Mycelium +tile.waterlily.name=Lily Pad +tile.dragonEgg.name=Dragon Egg +tile.redstoneLight.name=Redstone Lamp +tile.cocoa.name=Cocoa +tile.enderChest.name=Ender Chest +tile.oreRuby.name=Ruby Ore +tile.oreEmerald.name=Emerald Ore +tile.blockEmerald.name=Block of Emerald +tile.blockRedstone.name=Block of Redstone +tile.tripWire.name=Tripwire +tile.tripWireSource.name=Tripwire Hook +tile.commandBlock.name=Command Block +tile.beacon.name=Beacon +tile.beacon.primary=Primary Power +tile.beacon.secondary=Secondary Power +tile.cobbleWall.normal.name=Cobblestone Wall +tile.cobbleWall.mossy.name=Mossy Cobblestone Wall +tile.carrots.name=Carrots +tile.potatoes.name=Potatoes +tile.daylightDetector.name=Daylight Sensor +tile.netherquartz.name=Nether Quartz Ore +tile.hopper.name=Hopper +tile.quartzBlock.name=Block of Quartz +tile.quartzBlock.default.name=Block of Quartz +tile.quartzBlock.chiseled.name=Chiseled Quartz Block +tile.quartzBlock.lines.name=Pillar Quartz Block +tile.stairsQuartz.name=Quartz Stairs +tile.slime.name=Slime Block +tile.prismarine.rough.name=Prismarine +tile.prismarine.bricks.name=Prismarine Bricks +tile.prismarine.dark.name=Dark Prismarine +tile.seaLantern.name=Sea Lantern + +item.nameTag.name=Name Tag +item.leash.name=Lead +item.shovelIron.name=Iron Shovel +item.pickaxeIron.name=Iron Pickaxe +item.hatchetIron.name=Iron Axe +item.flintAndSteel.name=Flint and Steel +item.apple.name=Apple +item.cookie.name=Cookie +item.bow.name=Bow +item.arrow.name=Arrow +item.coal.name=Coal +item.charcoal.name=Charcoal +item.diamond.name=Diamond +item.emerald.name=Emerald +item.ingotIron.name=Iron Ingot +item.ingotGold.name=Gold Ingot +item.swordIron.name=Iron Sword +item.swordWood.name=Wooden Sword +item.shovelWood.name=Wooden Shovel +item.pickaxeWood.name=Wooden Pickaxe +item.hatchetWood.name=Wooden Axe +item.swordStone.name=Stone Sword +item.shovelStone.name=Stone Shovel +item.pickaxeStone.name=Stone Pickaxe +item.hatchetStone.name=Stone Axe +item.swordDiamond.name=Diamond Sword +item.shovelDiamond.name=Diamond Shovel +item.pickaxeDiamond.name=Diamond Pickaxe +item.hatchetDiamond.name=Diamond Axe +item.stick.name=Stick +item.bowl.name=Bowl +item.mushroomStew.name=Mushroom Stew +item.swordGold.name=Golden Sword +item.shovelGold.name=Golden Shovel +item.pickaxeGold.name=Golden Pickaxe +item.hatchetGold.name=Golden Axe +item.string.name=String +item.feather.name=Feather +item.sulphur.name=Gunpowder +item.hoeWood.name=Wooden Hoe +item.hoeStone.name=Stone Hoe +item.hoeIron.name=Iron Hoe +item.hoeDiamond.name=Diamond Hoe +item.hoeGold.name=Golden Hoe +item.seeds.name=Seeds +item.seeds_pumpkin.name=Pumpkin Seeds +item.seeds_melon.name=Melon Seeds +item.melon.name=Melon +item.wheat.name=Wheat +item.bread.name=Bread +item.helmetCloth.name=Leather Cap +item.chestplateCloth.name=Leather Tunic +item.leggingsCloth.name=Leather Pants +item.bootsCloth.name=Leather Boots +item.helmetChain.name=Chain Helmet +item.chestplateChain.name=Chain Chestplate +item.leggingsChain.name=Chain Leggings +item.bootsChain.name=Chain Boots +item.helmetIron.name=Iron Helmet +item.chestplateIron.name=Iron Chestplate +item.leggingsIron.name=Iron Leggings +item.bootsIron.name=Iron Boots +item.helmetDiamond.name=Diamond Helmet +item.chestplateDiamond.name=Diamond Chestplate +item.leggingsDiamond.name=Diamond Leggings +item.bootsDiamond.name=Diamond Boots +item.helmetGold.name=Golden Helmet +item.chestplateGold.name=Golden Chestplate +item.leggingsGold.name=Golden Leggings +item.bootsGold.name=Golden Boots +item.flint.name=Flint +item.porkchopRaw.name=Raw Porkchop +item.porkchopCooked.name=Cooked Porkchop +item.chickenRaw.name=Raw Chicken +item.chickenCooked.name=Cooked Chicken +item.muttonRaw.name=Raw Mutton +item.muttonCooked.name=Cooked Mutton +item.rabbitRaw.name=Raw Rabbit +item.rabbitCooked.name=Cooked Rabbit +item.rabbitStew.name=Rabbit Stew +item.rabbitFoot.name=Rabbit's Foot +item.rabbitHide.name=Rabbit Hide +item.beefRaw.name=Raw Beef +item.beefCooked.name=Steak +item.painting.name=Painting +item.frame.name=Item Frame +item.appleGold.name=Golden Apple +item.sign.name=Sign +item.doorOak.name=Oak Door +item.doorSpruce.name=Spruce Door +item.doorBirch.name=Birch Door +item.doorJungle.name=Jungle Door +item.doorAcacia.name=Acacia Door +item.doorDarkOak.name=Dark Oak Door +item.bucket.name=Bucket +item.bucketWater.name=Water Bucket +item.bucketLava.name=Lava Bucket +item.minecart.name=Minecart +item.saddle.name=Saddle +item.doorIron.name=Iron Door +item.redstone.name=Redstone +item.snowball.name=Snowball +item.boat.name=Boat +item.leather.name=Leather +item.milk.name=Milk +item.brick.name=Brick +item.clay.name=Clay +item.reeds.name=Sugar Canes +item.paper.name=Paper +item.book.name=Book +item.slimeball.name=Slimeball +item.minecartChest.name=Minecart with Chest +item.minecartFurnace.name=Minecart with Furnace +item.minecartTnt.name=Minecart with TNT +item.minecartHopper.name=Minecart with Hopper +item.minecartCommandBlock.name=Minecart with Command Block +item.egg.name=Egg +item.compass.name=Compass +item.fishingRod.name=Fishing Rod +item.clock.name=Clock +item.yellowDust.name=Glowstone Dust +item.fish.cod.raw.name=Raw Fish +item.fish.salmon.raw.name=Raw Salmon +item.fish.pufferfish.raw.name=Pufferfish +item.fish.clownfish.raw.name=Clownfish +item.fish.cod.cooked.name=Cooked Fish +item.fish.salmon.cooked.name=Cooked Salmon +item.record.name=Music Disc +item.record.13.desc=C418 - 13 +item.record.cat.desc=C418 - cat +item.record.blocks.desc=C418 - blocks +item.record.chirp.desc=C418 - chirp +item.record.far.desc=C418 - far +item.record.mall.desc=C418 - mall +item.record.mellohi.desc=C418 - mellohi +item.record.stal.desc=C418 - stal +item.record.strad.desc=C418 - strad +item.record.ward.desc=C418 - ward +item.record.11.desc=C418 - 11 +item.record.wait.desc=C418 - wait +item.bone.name=Bone +item.dyePowder.black.name=Ink Sac +item.dyePowder.red.name=Rose Red +item.dyePowder.green.name=Cactus Green +item.dyePowder.brown.name=Cocoa Beans +item.dyePowder.blue.name=Lapis Lazuli +item.dyePowder.purple.name=Purple Dye +item.dyePowder.cyan.name=Cyan Dye +item.dyePowder.silver.name=Light Gray Dye +item.dyePowder.gray.name=Gray Dye +item.dyePowder.pink.name=Pink Dye +item.dyePowder.lime.name=Lime Dye +item.dyePowder.yellow.name=Dandelion Yellow +item.dyePowder.lightBlue.name=Light Blue Dye +item.dyePowder.magenta.name=Magenta Dye +item.dyePowder.orange.name=Orange Dye +item.dyePowder.white.name=Bone Meal +item.sugar.name=Sugar +item.cake.name=Cake +item.bed.name=Bed +item.diode.name=Redstone Repeater +item.comparator.name=Redstone Comparator +item.map.name=Map +item.leaves.name=Leaves +item.shears.name=Shears +item.rottenFlesh.name=Rotten Flesh +item.enderPearl.name=Ender Pearl +item.blazeRod.name=Blaze Rod +item.ghastTear.name=Ghast Tear +item.netherStalkSeeds.name=Nether Wart +item.potion.name=Potion +item.emptyPotion.name=Water Bottle +item.goldNugget.name=Gold Nugget +item.glassBottle.name=Glass Bottle +item.spiderEye.name=Spider Eye +item.fermentedSpiderEye.name=Fermented Spider Eye +item.blazePowder.name=Blaze Powder +item.magmaCream.name=Magma Cream +item.cauldron.name=Cauldron +item.brewingStand.name=Brewing Stand +item.eyeOfEnder.name=Eye of Ender +item.speckledMelon.name=Glistering Melon +item.monsterPlacer.name=Spawn +item.expBottle.name=Bottle o' Enchanting +item.fireball.name=Fire Charge +item.writingBook.name=Book and Quill +item.writtenBook.name=Written Book +item.ruby.name=Ruby +item.flowerPot.name=Flower Pot +item.emptyMap.name=Empty Map +item.carrots.name=Carrot +item.carrotGolden.name=Golden Carrot +item.potato.name=Potato +item.potatoBaked.name=Baked Potato +item.potatoPoisonous.name=Poisonous Potato +item.skull.skeleton.name=Skeleton Skull +item.skull.wither.name=Wither Skeleton Skull +item.skull.zombie.name=Zombie Head +item.skull.char.name=Head +item.skull.player.name=%s's Head +item.skull.creeper.name=Creeper Head +item.carrotOnAStick.name=Carrot on a Stick +item.netherStar.name=Nether Star +item.pumpkinPie.name=Pumpkin Pie +item.enchantedBook.name=Enchanted Book +item.fireworks.name=Firework Rocket +item.fireworks.flight=Flight Duration: +item.fireworksCharge.name=Firework Star +item.fireworksCharge.black=Black +item.fireworksCharge.red=Red +item.fireworksCharge.green=Green +item.fireworksCharge.brown=Brown +item.fireworksCharge.blue=Blue +item.fireworksCharge.purple=Purple +item.fireworksCharge.cyan=Cyan +item.fireworksCharge.silver=Light Gray +item.fireworksCharge.gray=Gray +item.fireworksCharge.pink=Pink +item.fireworksCharge.lime=Lime +item.fireworksCharge.yellow=Yellow +item.fireworksCharge.lightBlue=Light Blue +item.fireworksCharge.magenta=Magenta +item.fireworksCharge.orange=Orange +item.fireworksCharge.white=White +item.fireworksCharge.customColor=Custom +item.fireworksCharge.fadeTo=Fade to +item.fireworksCharge.flicker=Twinkle +item.fireworksCharge.trail=Trail +item.fireworksCharge.type.0=Small Ball +item.fireworksCharge.type.1=Large Ball +item.fireworksCharge.type.2=Star-shaped +item.fireworksCharge.type.3=Creeper-shaped +item.fireworksCharge.type.4=Burst +item.fireworksCharge.type=Unknown Shape +item.netherbrick.name=Nether Brick +item.netherquartz.name=Nether Quartz +item.armorStand.name=Armor Stand +item.horsearmormetal.name=Iron Horse Armor +item.horsearmorgold.name=Gold Horse Armor +item.horsearmordiamond.name=Diamond Horse Armor +item.prismarineShard.name=Prismarine Shard +item.prismarineCrystals.name=Prismarine Crystals + +container.inventory=Inventory +container.hopper=Item Hopper +container.crafting=Crafting +container.dispenser=Dispenser +container.dropper=Dropper +container.furnace=Furnace +container.enchant=Enchant +container.enchant.lapis.one=1 Lapis Lazuli +container.enchant.lapis.many=%d Lapis Lazuli +container.enchant.level.one=1 Enchantment Level +container.enchant.level.many=%d Enchantment Levels +container.enchant.clue=%s . . . ? +container.repair=Repair & Name +container.repair.cost=Enchantment Cost: %1$d +container.repair.expensive=Too Expensive! +container.creative=Item Selection +container.brewing=Brewing Stand +container.chest=Chest +container.chestDouble=Large Chest +container.minecart=Minecart +container.enderchest=Ender Chest +container.beacon=Beacon + +container.isLocked=%s is locked! + +item.dyed=Dyed +item.unbreakable=Unbreakable +item.canBreak=Can break: +item.canPlace=Can be placed on: + +entity.Item.name=Item +entity.XPOrb.name=Experience Orb +entity.SmallFireball.name=Small Fireball +entity.Fireball.name=Fireball +entity.ThrownPotion.name=Potion + +entity.Arrow.name=Arrow +entity.Snowball.name=Snowball +entity.Painting.name=Painting +entity.ArmorStand.name=Armor Stand + +entity.Mob.name=Mob +entity.Monster.name=Monster + +entity.Creeper.name=Creeper +entity.Skeleton.name=Skeleton +entity.Spider.name=Spider +entity.Giant.name=Giant +entity.Zombie.name=Zombie +entity.Slime.name=Slime +entity.Ghast.name=Ghast +entity.PigZombie.name=Zombie Pigman +entity.Enderman.name=Enderman +entity.Endermite.name=Endermite +entity.Silverfish.name=Silverfish +entity.CaveSpider.name=Cave Spider +entity.Blaze.name=Blaze +entity.LavaSlime.name=Magma Cube +entity.MushroomCow.name=Mooshroom +entity.Villager.name=Villager +entity.VillagerGolem.name=Iron Golem +entity.SnowMan.name=Snow Golem +entity.EnderDragon.name=Ender Dragon +entity.WitherBoss.name=Wither +entity.Witch.name=Witch +entity.Guardian.name=Guardian + +entity.Villager.farmer=Farmer +entity.Villager.fisherman=Fisherman +entity.Villager.shepherd=Shepherd +entity.Villager.fletcher=Fletcher +entity.Villager.librarian=Librarian +entity.Villager.cleric=Cleric +entity.Villager.armor=Armorer +entity.Villager.weapon=Weapon Smith +entity.Villager.tool=Tool Smith +entity.Villager.butcher=Butcher +entity.Villager.leather=Leatherworker + +entity.Pig.name=Pig +entity.Sheep.name=Sheep +entity.Cow.name=Cow +entity.Chicken.name=Chicken +entity.Squid.name=Squid +entity.Wolf.name=Wolf +entity.Ozelot.name=Ocelot +entity.Cat.name=Cat +entity.Bat.name=Bat +entity.EntityHorse.name=Horse +entity.horse.name=Horse +entity.donkey.name=Donkey +entity.mule.name=Mule +entity.skeletonhorse.name=Skeleton Horse +entity.zombiehorse.name=Zombie Horse +entity.Rabbit.name=Rabbit +entity.KillerBunny.name=The Killer Bunny + +entity.PrimedTnt.name=Block of TNT +entity.FallingSand.name=Falling Block + +entity.Minecart.name=Minecart +entity.Boat.name=Boat + +entity.generic.name=unknown + +death.fell.accident.ladder=%1$s fell off a ladder +death.fell.accident.vines=%1$s fell off some vines +death.fell.accident.water=%1$s fell out of the water +death.fell.accident.generic=%1$s fell from a high place +death.fell.killer=%1$s was doomed to fall +death.fell.assist=%1$s was doomed to fall by %2$s +death.fell.assist.item=%1$s was doomed to fall by %2$s using %3$s +death.fell.finish=%1$s fell too far and was finished by %2$s +death.fell.finish.item=%1$s fell too far and was finished by %2$s using %3$s + +death.attack.lightningBolt=%1$s was struck by lightning +death.attack.inFire=%1$s went up in flames +death.attack.inFire.player=%1$s walked into fire whilst fighting %2$s +death.attack.onFire=%1$s burned to death +death.attack.onFire.player=%1$s was burnt to a crisp whilst fighting %2$s +death.attack.lava=%1$s tried to swim in lava +death.attack.lava.player=%1$s tried to swim in lava to escape %2$s +death.attack.inWall=%1$s suffocated in a wall +death.attack.drown=%1$s drowned +death.attack.drown.player=%1$s drowned whilst trying to escape %2$s +death.attack.starve=%1$s starved to death +death.attack.cactus=%1$s was pricked to death +death.attack.cactus.player=%1$s walked into a cactus whilst trying to escape %2$s +death.attack.generic=%1$s died +death.attack.explosion=%1$s blew up +death.attack.explosion.player=%1$s was blown up by %2$s +death.attack.magic=%1$s was killed by magic +death.attack.wither=%1$s withered away +death.attack.anvil=%1$s was squashed by a falling anvil +death.attack.fallingBlock=%1$s was squashed by a falling block +death.attack.mob=%1$s was slain by %2$s +death.attack.player=%1$s was slain by %2$s +death.attack.player.item=%1$s was slain by %2$s using %3$s +death.attack.arrow=%1$s was shot by %2$s +death.attack.arrow.item=%1$s was shot by %2$s using %3$s +death.attack.fireball=%1$s was fireballed by %2$s +death.attack.fireball.item=%1$s was fireballed by %2$s using %3$s +death.attack.thrown=%1$s was pummeled by %2$s +death.attack.thrown.item=%1$s was pummeled by %2$s using %3$s +death.attack.indirectMagic=%1$s was killed by %2$s using magic +death.attack.indirectMagic.item=%1$s was killed by %2$s using %3$s +death.attack.thorns=%1$s was killed trying to hurt %2$s +death.attack.fall=%1$s hit the ground too hard +death.attack.outOfWorld=%1$s fell out of the world + +deathScreen.respawn=Respawn +deathScreen.deleteWorld=Delete world +deathScreen.titleScreen=Title screen +deathScreen.score=Score +deathScreen.title.hardcore=Game over! +deathScreen.hardcoreInfo=You cannot respawn in hardcore mode! +deathScreen.title=You died! +deathScreen.leaveServer=Leave server +deathScreen.quit.confirm=Are you sure you want to quit? + +potion.effects.whenDrank=When Applied: +potion.empty=No Effects +potion.moveSpeed=Speed +potion.moveSlowdown=Slowness +potion.digSpeed=Haste +potion.digSlowDown=Mining Fatigue +potion.damageBoost=Strength +potion.heal=Instant Health +potion.harm=Instant Damage +potion.jump=Jump Boost +potion.confusion=Nausea +potion.regeneration=Regeneration +potion.resistance=Resistance +potion.fireResistance=Fire Resistance +potion.waterBreathing=Water Breathing +potion.invisibility=Invisibility +potion.blindness=Blindness +potion.nightVision=Night Vision +potion.hunger=Hunger +potion.weakness=Weakness +potion.poison=Poison +potion.wither=Wither +potion.healthBoost=Health Boost +potion.absorption=Absorption +potion.saturation=Saturation + +potion.moveSpeed.postfix=Potion of Swiftness +potion.moveSlowdown.postfix=Potion of Slowness +potion.digSpeed.postfix=Potion of Haste +potion.digSlowDown.postfix=Potion of Dullness +potion.damageBoost.postfix=Potion of Strength +potion.weakness.postfix=Potion of Weakness +potion.heal.postfix=Potion of Healing +potion.harm.postfix=Potion of Harming +potion.jump.postfix=Potion of Leaping +potion.confusion.postfix=Potion of Nausea +potion.regeneration.postfix=Potion of Regeneration +potion.resistance.postfix=Potion of Resistance +potion.fireResistance.postfix=Potion of Fire Resistance +potion.waterBreathing.postfix=Potion of Water Breathing +potion.invisibility.postfix=Potion of Invisibility +potion.blindness.postfix=Potion of Blindness +potion.nightVision.postfix=Potion of Night Vision +potion.hunger.postfix=Potion of Hunger +potion.poison.postfix=Potion of Poison +potion.wither.postfix=Potion of Decay +potion.healthBoost.postfix=Potion of Health Boost +potion.absorption.postfix=Potion of Absorption +potion.saturation.postfix=Potion of Saturation + +potion.potency.0= +potion.potency.1=II +potion.potency.2=III +potion.potency.3=IV + +potion.prefix.grenade=Splash +potion.prefix.mundane=Mundane +potion.prefix.uninteresting=Uninteresting +potion.prefix.bland=Bland +potion.prefix.clear=Clear +potion.prefix.milky=Milky +potion.prefix.diffuse=Diffuse +potion.prefix.artless=Artless +potion.prefix.thin=Thin +potion.prefix.awkward=Awkward +potion.prefix.flat=Flat +potion.prefix.bulky=Bulky +potion.prefix.bungling=Bungling +potion.prefix.buttered=Buttered +potion.prefix.smooth=Smooth +potion.prefix.suave=Suave +potion.prefix.debonair=Debonair +potion.prefix.thick=Thick +potion.prefix.elegant=Elegant +potion.prefix.fancy=Fancy +potion.prefix.charming=Charming +potion.prefix.dashing=Dashing +potion.prefix.refined=Refined +potion.prefix.cordial=Cordial +potion.prefix.sparkling=Sparkling +potion.prefix.potent=Potent +potion.prefix.foul=Foul +potion.prefix.odorless=Odorless +potion.prefix.rank=Rank +potion.prefix.harsh=Harsh +potion.prefix.acrid=Acrid +potion.prefix.gross=Gross +potion.prefix.stinky=Stinky + +enchantment.damage.all=Sharpness +enchantment.damage.undead=Smite +enchantment.damage.arthropods=Bane of Arthropods +enchantment.knockback=Knockback +enchantment.fire=Fire Aspect +enchantment.protect.all=Protection +enchantment.protect.fire=Fire Protection +enchantment.protect.fall=Feather Falling +enchantment.protect.explosion=Blast Protection +enchantment.protect.projectile=Projectile Protection +enchantment.oxygen=Respiration +enchantment.waterWorker=Aqua Affinity +enchantment.waterWalker=Depth Strider +enchantment.digging=Efficiency +enchantment.untouching=Silk Touch +enchantment.durability=Unbreaking +enchantment.lootBonus=Looting +enchantment.lootBonusDigger=Fortune +enchantment.lootBonusFishing=Luck of the Sea +enchantment.fishingSpeed=Lure +enchantment.arrowDamage=Power +enchantment.arrowFire=Flame +enchantment.arrowKnockback=Punch +enchantment.arrowInfinite=Infinity +enchantment.thorns=Thorns + +enchantment.level.1=I +enchantment.level.2=II +enchantment.level.3=III +enchantment.level.4=IV +enchantment.level.5=V +enchantment.level.6=VI +enchantment.level.7=VII +enchantment.level.8=VIII +enchantment.level.9=IX +enchantment.level.10=X + +gui.achievements=Achievements +gui.stats=Statistics + +stats.tooltip.type.achievement=Achievement +stats.tooltip.type.statistic=Statistic +stat.generalButton=General +stat.blocksButton=Blocks +stat.itemsButton=Items +stat.mobsButton=Mobs + +stat.used=Times Used +stat.mined=Times Mined +stat.depleted=Times Depleted +stat.crafted=Times Crafted +stat.entityKills=You killed %d %s +stat.entityKilledBy=%s killed you %d time(s) +stat.entityKills.none=You have never killed %s +stat.entityKilledBy.none=You have never been killed by %s + +stat.startGame=Times played +stat.createWorld=Worlds created +stat.loadWorld=Saves loaded +stat.joinMultiplayer=Multiplayer joins +stat.leaveGame=Games quit + +stat.playOneMinute=Minutes Played +stat.timeSinceDeath=Since Last Death + +stat.walkOneCm=Distance Walked +stat.crouchOneCm=Distance Crouched +stat.sprintOneCm=Distance Sprinted +stat.fallOneCm=Distance Fallen +stat.swimOneCm=Distance Swum +stat.flyOneCm=Distance Flown +stat.climbOneCm=Distance Climbed +stat.diveOneCm=Distance Dove +stat.minecartOneCm=Distance by Minecart +stat.boatOneCm=Distance by Boat +stat.pigOneCm=Distance by Pig +stat.horseOneCm=Distance by Horse +stat.jump=Jumps +stat.drop=Items Dropped + +stat.damageDealt=Damage Dealt +stat.damageTaken=Damage Taken +stat.deaths=Number of Deaths +stat.mobKills=Mob Kills +stat.animalsBred=Animals Bred +stat.playerKills=Player Kills +stat.fishCaught=Fish Caught +stat.treasureFished=Treasure Fished +stat.junkFished=Junk Fished +stat.talkedToVillager=Talked to Villagers +stat.tradedWithVillager=Traded with Villagers + +stat.cakeSlicesEaten=Cake Slices Eaten +stat.cauldronFilled=Cauldrons Filled +stat.cauldronUsed=Water Taken from Cauldron +stat.armorCleaned=Armor Pieces Cleaned +stat.bannerCleaned=Banners Cleaned +stat.brewingstandInteraction=Interactions with Brewing Stand +stat.beaconInteraction=Interactions with Beacon +stat.dropperInspected=Droppers Searched +stat.hopperInspected=Hoppers Searched +stat.dispenserInspected=Dispensers Searched +stat.noteblockPlayed=Noteblocks played +stat.noteblockTuned=Noteblocks tuned +stat.flowerPotted=Plants potted +stat.trappedChestTriggered=Trapped Chests Triggered +stat.enderchestOpened=Ender Chests Opened +stat.itemEnchanted=Items Enchanted +stat.recordPlayed=Records Played +stat.furnaceInteraction=Interactions with Furnace +stat.workbenchInteraction=Interactions with Crafting Table +stat.chestOpened=Chests Opened + +stat.mineBlock=%1$s Mined +stat.craftItem=%1$s Crafted +stat.useItem=%1$s Used +stat.breakItem=%1$s Depleted + +achievement.get=Achievement get! + +achievement.taken=Taken! +achievement.unknown=??? + +achievement.requires=Requires '%1$s' +achievement.openInventory=Taking Inventory +achievement.openInventory.desc=Press '%1$s' to open your inventory. +achievement.mineWood=Getting Wood +achievement.mineWood.desc=Attack a tree until a block of wood pops out +achievement.buildWorkBench=Benchmarking +achievement.buildWorkBench.desc=Craft a workbench with four blocks of planks +achievement.buildPickaxe=Time to Mine! +achievement.buildPickaxe.desc=Use planks and sticks to make a pickaxe +achievement.buildFurnace=Hot Topic +achievement.buildFurnace.desc=Construct a furnace out of eight stone blocks +achievement.acquireIron=Acquire Hardware +achievement.acquireIron.desc=Smelt an iron ingot +achievement.buildHoe=Time to Farm! +achievement.buildHoe.desc=Use planks and sticks to make a hoe +achievement.makeBread=Bake Bread +achievement.makeBread.desc=Turn wheat into bread +achievement.bakeCake=The Lie +achievement.bakeCake.desc=Wheat, sugar, milk and eggs! +achievement.buildBetterPickaxe=Getting an Upgrade +achievement.buildBetterPickaxe.desc=Construct a better pickaxe +achievement.overpowered=Overpowered +achievement.overpowered.desc=Build a Notch apple +achievement.cookFish=Delicious Fish +achievement.cookFish.desc=Catch and cook fish! +achievement.onARail=On A Rail +achievement.onARail.desc=Travel by minecart at least 1 km from where you started +achievement.buildSword=Time to Strike! +achievement.buildSword.desc=Use planks and sticks to make a sword +achievement.killEnemy=Monster Hunter +achievement.killEnemy.desc=Attack and destroy a monster +achievement.killCow=Cow Tipper +achievement.killCow.desc=Harvest some leather +achievement.breedCow=Repopulation +achievement.breedCow.desc=Breed two cows with wheat +achievement.flyPig=When Pigs Fly +achievement.flyPig.desc=Fly a pig off a cliff +achievement.snipeSkeleton=Sniper Duel +achievement.snipeSkeleton.desc=Kill a skeleton with an arrow from more than 50 meters +achievement.diamonds=DIAMONDS! +achievement.diamonds.desc=Acquire diamonds with your iron tools +achievement.diamondsToYou=Diamonds to you! +achievement.diamondsToYou.desc=Throw diamonds at another player. +achievement.portal=We Need to Go Deeper +achievement.portal.desc=Build a portal to the Nether +achievement.ghast=Return to Sender +achievement.ghast.desc=Destroy a Ghast with a fireball +achievement.blazeRod=Into Fire +achievement.blazeRod.desc=Relieve a Blaze of its rod +achievement.potion=Local Brewery +achievement.potion.desc=Brew a potion +achievement.theEnd=The End? +achievement.theEnd.desc=Locate the End +achievement.theEnd2=The End. +achievement.theEnd2.desc=Defeat the Ender Dragon +achievement.spawnWither=The Beginning? +achievement.spawnWither.desc=Spawn the Wither +achievement.killWither=The Beginning. +achievement.killWither.desc=Kill the Wither +achievement.fullBeacon=Beaconator +achievement.fullBeacon.desc=Create a full beacon +achievement.exploreAllBiomes=Adventuring Time +achievement.exploreAllBiomes.desc=Discover all biomes +achievement.enchantments=Enchanter +achievement.enchantments.desc=Use a book, obsidian and diamonds to construct an enchantment table +achievement.overkill=Overkill +achievement.overkill.desc=Deal nine hearts of damage in a single hit +achievement.bookcase=Librarian +achievement.bookcase.desc=Build some bookshelves to improve your enchantment table + +commands.generic.exception=An unknown error occurred while attempting to perform this command +commands.generic.permission=You do not have permission to use this command +commands.generic.syntax=Invalid command syntax +commands.generic.player.notFound=That player cannot be found +commands.generic.entity.notFound=That entity cannot be found +commands.generic.entity.invalidUuid=The entity UUID provided is in an invalid format +commands.generic.entity.invalidType=Entity type '%s' is invalid +commands.generic.notFound=Unknown command. Try /help for a list of commands +commands.generic.parameter.invalid='%s' is not a valid parameter +commands.generic.num.invalid='%s' is not a valid number +commands.generic.boolean.invalid='%s' is not true or false +commands.generic.num.tooSmall=The number you have entered (%d) is too small, it must be at least %d +commands.generic.num.tooBig=The number you have entered (%d) is too big, it must be at most %d +commands.generic.double.tooSmall=The number you have entered (%.2f) is too small, it must be at least %.2f +commands.generic.double.tooBig=The number you have entered (%.2f) is too big, it must be at most %.2f +commands.generic.usage=Usage: %s + +commands.setidletimeout.usage=/setidletimeout +commands.setidletimeout.success=Successfully set the idle timeout to %d minutes. +commands.xp.failure.widthdrawXp=Cannot give player negative experience points +commands.xp.success=Given %d experience to %s +commands.xp.success.levels=Given %d levels to %s +commands.xp.success.negative.levels=Taken %d levels from %s +commands.xp.usage=/xp [player] OR /xp L [player] +commands.playsound.usage=/playsound [x] [y] [z] [volume] [pitch] [minimumVolume] +commands.playsound.success=Played sound '%s' to %s +commands.playsound.playerTooFar=Player %s is too far away to hear the sound +commands.give.usage=/give [amount] [data] [dataTag] +commands.give.item.notFound=There is no such item with name %d +commands.give.block.notFound=There is no such block with name %d +commands.give.success=Given %s * %d to %s +commands.give.tagError=Data tag parsing failed: %s +commands.replaceitem.usage=/replaceitem ... +commands.replaceitem.entity.usage=/replaceitem entity [amount] [data] [dataTag] +commands.replaceitem.block.usage=/replaceitem block [amount] [data] [dataTag] +commands.replaceitem.tagError=Data tag parsing failed: %s +commands.replaceitem.noContainer=Block at %d, %d, %d is not a container +commands.replaceitem.failed=Could not replace slot %d with %d * %s +commands.replaceitem.success=Replaced slot %d with %d * %s +commands.stats.usage=/stats ... +commands.stats.entity.usage=/stats entity +commands.stats.entity.set.usage=/stats entity set +commands.stats.entity.clear.usage=/stats entity clear +commands.stats.block.usage=/stats block ... +commands.stats.block.set.usage=/stats block set +commands.stats.block.clear.usage=/stats block clear +commands.stats.noCompatibleBlock=Block at %d, %d, %d can not track stats +commands.stats.failed=Invalid parameters +commands.stats.cleared=Cleared %s stats +commands.stats.success=Storing %s stats in %s on %s +commands.summon.usage=/summon [x] [y] [z] [dataTag] +commands.summon.success=Object successfully summoned +commands.summon.failed=Unable to summon object +commands.summon.tagError=Data tag parsing failed: %s +commands.summon.outOfWorld=Cannot summon the object out of the world +commands.testforblock.usage=/testforblock [dataValue] [dataTag] +commands.testforblock.failed.tile=The block at %d,%d,%d is %s (expected: %s). +commands.testforblock.failed.data=The block at %d,%d,%d had the data value of %s (expected: %s). +commands.testforblock.failed.nbt=The block at %d,%d,%d did not have the required NBT keys. +commands.testforblock.failed.tileEntity=The block at %d,%d,%d is not a tile entity and cannot support tag matching. +commands.testforblock.success=Successfully found the block at %d,%d,%d. +commands.testforblock.outOfWorld=Cannot test for block outside of the world +commands.setblock.usage=/setblock [dataValue] [oldBlockHandling] [dataTag] +commands.setblock.success=Block placed +commands.setblock.failed=Unable to place block +commands.setblock.tagError=Data tag parsing failed: %s +commands.setblock.outOfWorld=Cannot place block outside of the world +commands.setblock.notFound=There is no such block with ID/name %s +commands.setblock.noChange=The block couldn't be placed +commands.fill.usage=/fill [dataValue] [oldBlockHandling] [dataTag] +commands.fill.outOfWorld=Cannot place blocks outside of the world +commands.fill.tagError=Data tag parsing failed: %s +commands.fill.success=%d blocks filled +commands.fill.failed=No blocks filled +commands.fill.tooManyBlocks=Too many blocks in the specified area (%d > %d) +commands.clone.usage=/clone [maskMode] [cloneMode] +commands.clone.outOfWorld=Cannot access blocks outside of the world +commands.clone.noOverlap=Source and destination can not overlap +commands.clone.success=%d blocks cloned +commands.clone.failed=No blocks cloned +commands.clone.tooManyBlocks=Too many blocks in the specified area (%d > %d) +commands.compare.usage=/testforblocks [mode] +commands.compare.outOfWorld=Cannot access blocks outside of the world +commands.compare.failed=Source and destination are not identical +commands.compare.success=%d blocks compared +commands.compare.tooManyBlocks=Too many blocks in the specified area (%d > %d) +commands.blockdata.usage=/blockdata +commands.blockdata.success=Block data updated to: %s +commands.blockdata.tagError=Data tag parsing failed: %s +commands.blockdata.outOfWorld=Cannot change block outside of the world +commands.blockdata.notValid=The target block is not a data holder block +commands.blockdata.failed=The data tag did not change: %s +commands.entitydata.usage=/entitydata +commands.entitydata.success=Entity data updated to: %s +commands.entitydata.tagError=Data tag parsing failed: %s +commands.entitydata.noPlayers=%s is a player and cannot be changed +commands.entitydata.failed=The data tag did not change: %s +commands.effect.usage=/effect [seconds] [amplifier] [hideParticles] OR /effect clear +commands.effect.notFound=There is no such mob effect with ID %d +commands.effect.success=Given %1$s (ID %2$d) * %3$d to %4$s for %5$d seconds +commands.effect.success.removed=Took %1$s from %2$s +commands.effect.success.removed.all=Took all effects from %s +commands.effect.failure.notActive=Couldn't take %1$s from %2$s as they do not have the effect +commands.effect.failure.notActive.all=Couldn't take any effects from %s as they do not have any +commands.enchant.usage=/enchant [level] +commands.enchant.notFound=There is no such enchantment with ID %d +commands.enchant.noItem=The target doesn't hold an item +commands.enchant.cantEnchant=The selected enchantment can't be added to the target item +commands.enchant.cantCombine=%1$s can't be combined with %2$s +commands.enchant.success=Enchanting succeeded +commands.particle.usage=/particle [count] [mode] +commands.particle.success=Playing effect %s for %d times +commands.particle.notFound=Unknown effect name (%s) +commands.clear.usage=/clear [player] [item] [data] [maxCount] [dataTag] +commands.clear.success=Cleared the inventory of %s, removing %d items +commands.clear.testing=%s has %d items that match the criteria +commands.clear.failure=Could not clear the inventory of %s, no items to remove +commands.clear.tagError=Data tag parsing failed: %s +commands.downfall.usage=/toggledownfall +commands.downfall.success=Toggled downfall +commands.time.usage=/time +commands.time.added=Added %d to the time +commands.time.set=Set the time to %d +commands.time.query=Time is %d +commands.players.usage=/list +commands.players.list=There are %d/%d players online: +commands.banlist.ips=There are %d total banned IP addresses: +commands.banlist.players=There are %d total banned players: +commands.banlist.usage=/banlist [ips|players] +commands.kill.usage=/kill [player|entity] +commands.kill.successful=Killed %s +commands.kick.success=Kicked %s from the game +commands.kick.success.reason=Kicked %s from the game: '%s' +commands.kick.usage=/kick [reason ...] +commands.op.success=Opped %s +commands.op.failed=Could not op %s +commands.op.usage=/op +commands.deop.success=De-opped %s +commands.deop.failed=Could not de-op %s +commands.deop.usage=/deop +commands.say.usage=/say +commands.ban.success=Banned player %s +commands.ban.failed=Could not ban player %s +commands.ban.usage=/ban [reason ...] +commands.unban.success=Unbanned player %s +commands.unban.failed=Could not unban player %s +commands.unban.usage=/pardon +commands.banip.invalid=You have entered an invalid IP address or a player that is not online +commands.banip.success=Banned IP address %s +commands.banip.success.players=Banned IP address %s belonging to %s +commands.banip.usage=/ban-ip [reason ...] +commands.unbanip.invalid=You have entered an invalid IP address +commands.unbanip.success=Unbanned IP address %s +commands.unbanip.usage=/pardon-ip

    +commands.save.usage=/save-all +commands.save-on.alreadyOn=Saving is already turned on. +commands.save-on.usage=/save-on +commands.save-off.alreadyOff=Saving is already turned off. +commands.save-off.usage=/save-off +commands.save.enabled=Turned on world auto-saving +commands.save.disabled=Turned off world auto-saving +commands.save.start=Saving... +commands.save.success=Saved the world +commands.save.failed=Saving failed: %s +commands.stop.usage=/stop +commands.stop.start=Stopping the server +commands.tp.success=Teleported %s to %s +commands.tp.success.coordinates=Teleported %s to %s, %s, %s +commands.tp.usage=/tp [target player] OR /tp [target player] [ ] +commands.tp.notSameDimension=Unable to teleport because players are not in the same dimension +commands.whitelist.list=There are %d (out of %d seen) whitelisted players: +commands.whitelist.enabled=Turned on the whitelist +commands.whitelist.disabled=Turned off the whitelist +commands.whitelist.reloaded=Reloaded the whitelist +commands.whitelist.add.success=Added %s to the whitelist +commands.whitelist.add.failed=Could not add %s to the whitelist +commands.whitelist.add.usage=/whitelist add +commands.whitelist.remove.success=Removed %s from the whitelist +commands.whitelist.remove.failed=Could not remove %s from the whitelist +commands.whitelist.remove.usage=/whitelist remove +commands.whitelist.usage=/whitelist +commands.scoreboard.usage=/scoreboard ... +commands.scoreboard.noMultiWildcard=Only one user wildcard allowed +commands.scoreboard.allMatchesFailed=All matches failed +commands.scoreboard.teamNotFound=No team was found by the name '%s' +commands.scoreboard.objectiveNotFound=No objective was found by the name '%s' +commands.scoreboard.objectiveReadOnly=The objective '%s' is read-only and cannot be set +commands.scoreboard.objectives.usage=/scoreboard objectives ... +commands.scoreboard.objectives.setdisplay.usage=/scoreboard objectives setdisplay [objective] +commands.scoreboard.objectives.setdisplay.invalidSlot=No such display slot '%s' +commands.scoreboard.objectives.setdisplay.successCleared=Cleared objective display slot '%s' +commands.scoreboard.objectives.setdisplay.successSet=Set the display objective in slot '%s' to '%s' +commands.scoreboard.objectives.add.usage=/scoreboard objectives add [display name ...] +commands.scoreboard.objectives.add.wrongType=Invalid objective criteria type '%s' +commands.scoreboard.objectives.add.alreadyExists=An objective with the name '%s' already exists +commands.scoreboard.objectives.add.tooLong=The name '%s' is too long for an objective, it can be at most %d characters long +commands.scoreboard.objectives.add.displayTooLong=The display name '%s' is too long for an objective, it can be at most %d characters long +commands.scoreboard.objectives.add.success=Added new objective '%s' successfully +commands.scoreboard.objectives.remove.usage=/scoreboard objectives remove +commands.scoreboard.objectives.remove.success=Removed objective '%s' successfully +commands.scoreboard.objectives.list.count=Showing %d objective(s) on scoreboard: +commands.scoreboard.objectives.list.entry=- %s: displays as '%s' and is type '%s' +commands.scoreboard.objectives.list.empty=There are no objectives on the scoreboard +commands.scoreboard.players.usage=/scoreboard players ... +commands.scoreboard.players.name.tooLong=The name '%s' is too long for a player, it can be at most %d characters long +commands.scoreboard.players.set.success=Set score of %s for player %s to %d +commands.scoreboard.players.set.tagMismatch=The dataTag does not match for %s +commands.scoreboard.players.set.tagError=Could not parse dataTag, reason: %s +commands.scoreboard.players.set.usage=/scoreboard players set [dataTag] +commands.scoreboard.players.add.usage=/scoreboard players add [dataTag] +commands.scoreboard.players.remove.usage=/scoreboard players remove [dataTag] +commands.scoreboard.players.reset.usage=/scoreboard players reset [objective] +commands.scoreboard.players.reset.success=Reset scores of player %s +commands.scoreboard.players.resetscore.success=Reset score %s of player %s +commands.scoreboard.players.list.usage=/scoreboard players list [name] +commands.scoreboard.players.list.count=Showing %d tracked players on the scoreboard: +commands.scoreboard.players.list.empty=There are no tracked players on the scoreboard +commands.scoreboard.players.list.player.count=Showing %d tracked objective(s) for %s: +commands.scoreboard.players.list.player.entry=- %2$s: %1$d (%3$s) +commands.scoreboard.players.list.player.empty=Player %s has no scores recorded +commands.scoreboard.players.enable.usage=/scoreboard players enable +commands.scoreboard.players.enable.success=Enabled trigger %s for %s +commands.scoreboard.players.enable.noTrigger=Objective %s is not a trigger +commands.scoreboard.players.test.usage=/scoreboard players test +commands.scoreboard.players.test.notFound=No %s score for %s found +commands.scoreboard.players.test.failed=Score %d is NOT in range %d to %d +commands.scoreboard.players.test.success=Score %d is in range %d to %d +commands.scoreboard.players.operation.usage=/scoreboard players operation +commands.scoreboard.players.operation.notFound=No %s score for %s found +commands.scoreboard.players.operation.invalidOperation=Invalid operation %s +commands.scoreboard.players.operation.success=Operation applied successfully +commands.scoreboard.teams.usage=/scoreboard teams ... +commands.scoreboard.teams.add.usage=/scoreboard teams add [display name ...] +commands.scoreboard.teams.add.alreadyExists=A team with the name '%s' already exists +commands.scoreboard.teams.add.tooLong=The name '%s' is too long for a team, it can be at most %d characters long +commands.scoreboard.teams.add.displayTooLong=The display name '%s' is too long for a team, it can be at most %d characters long +commands.scoreboard.teams.add.success=Added new team '%s' successfully +commands.scoreboard.teams.list.usage=/scoreboard teams list [name] +commands.scoreboard.teams.list.count=Showing %d teams on the scoreboard: +commands.scoreboard.teams.list.entry=- %1$s: '%2$s' has %3$d players +commands.scoreboard.teams.list.empty=There are no teams registered on the scoreboard +commands.scoreboard.teams.list.player.count=Showing %d player(s) in team %s: +commands.scoreboard.teams.list.player.entry=- %2$s: %1$d (%3$s) +commands.scoreboard.teams.list.player.empty=Team %s has no players +commands.scoreboard.teams.empty.usage=/scoreboard teams empty +commands.scoreboard.teams.empty.alreadyEmpty=Team %s is already empty, cannot remove nonexistant players +commands.scoreboard.teams.empty.success=Removed all %d player(s) from team %s +commands.scoreboard.teams.remove.usage=/scoreboard teams remove +commands.scoreboard.teams.remove.success=Removed team %s +commands.scoreboard.teams.join.usage=/scoreboard teams join [player] +commands.scoreboard.teams.join.success=Added %d player(s) to team %s: %s +commands.scoreboard.teams.join.failure=Could not add %d player(s) to team %s: %s +commands.scoreboard.teams.leave.usage=/scoreboard teams leave [player] +commands.scoreboard.teams.leave.success=Removed %d player(s) from their teams: %s +commands.scoreboard.teams.leave.failure=Could not remove %d player(s) from their teams: %s +commands.scoreboard.teams.leave.noTeam=You are not in a team +commands.scoreboard.teams.option.usage=/scoreboard teams option +commands.scoreboard.teams.option.noValue=Valid values for option %s are: %s +commands.scoreboard.teams.option.success=Set option %s for team %s to %s +commands.execute.usage=/execute OR /execute detect +commands.execute.allInvocationsFailed=All invocations failed: '%s' +commands.execute.failed=Failed to execute '%s' as %s +commands.gamemode.success.self=Set own game mode to %s +commands.gamemode.success.other=Set %s's game mode to %s +commands.gamemode.usage=/gamemode [player] +commands.defaultgamemode.usage=/defaultgamemode +commands.defaultgamemode.success=The world's default game mode is now %s +commands.me.usage=/me +commands.help.header=--- Showing help page %d of %d (/help ) --- +commands.help.footer=Tip: Use the key while typing a command to auto-complete the command or its arguments +commands.help.usage=/help [page|command name] +commands.trigger.usage=/trigger +commands.trigger.invalidObjective=Invalid trigger name %s +commands.trigger.invalidMode=Invalid trigger mode %s +commands.trigger.disabled=Trigger %s is not enabled +commands.trigger.invalidPlayer=Only players can use the /trigger command +commands.trigger.success=Trigger %s changed with %s %s +commands.publish.usage=/publish +commands.publish.started=Local game hosted on port %s +commands.publish.failed=Unable to host local game +commands.debug.start=Started debug profiling +commands.debug.stop=Stopped debug profiling after %.2f seconds (%d ticks) +commands.debug.notStarted=Can't stop profiling when we haven't started yet! +commands.debug.usage=/debug +commands.chunkinfo.usage=/chunkinfo [ ] +commands.chunkinfo.location=Chunk location: (%d, %d, %d) +commands.chunkinfo.noChunk=No chunk found at chunk position %d, %d, %d +commands.chunkinfo.notEmpty=Chunk is not empty. +commands.chunkinfo.empty=Chunk is empty. +commands.chunkinfo.notCompiled=Chunk is not compiled. +commands.chunkinfo.compiled=Chunk is compiled. +commands.chunkinfo.hasNoRenderableLayers=Chunk has no renderable layers. +commands.chunkinfo.hasLayers=Chunk has layers: %s +commands.chunkinfo.isEmpty=Chunk has empty layers: %s +commands.chunkinfo.vertices=%s layer's buffer contains %d vertices +commands.chunkinfo.data=First 64 vertices are: %s +commands.tellraw.usage=/tellraw +commands.tellraw.jsonException=Invalid json: %s +commands.message.usage=/tell +commands.message.sameTarget=You can't send a private message to yourself! +commands.message.display.outgoing=You whisper to %s: %s +commands.message.display.incoming=%s whispers to you: %s +commands.difficulty.usage=/difficulty +commands.difficulty.success=Set game difficulty to %s +commands.spawnpoint.usage=/spawnpoint [player] [ ] +commands.spawnpoint.success=Set %s's spawn point to (%d, %d, %d) +commands.setworldspawn.usage=/setworldspawn [ ] +commands.setworldspawn.success=Set the world spawn point to (%d, %d, %d) +commands.gamerule.usage=/gamerule [value] +commands.gamerule.success=Game rule has been updated +commands.gamerule.norule=No game rule called '%s' is available +commands.gamerule.nopermission=Only server owners can change '%s' +commands.weather.usage=/weather [duration in seconds] +commands.weather.clear=Changing to clear weather +commands.weather.rain=Changing to rainy weather +commands.weather.thunder=Changing to rain and thunder +commands.testfor.usage=/testfor [dataTag] +commands.testfor.failure=%s did not match the required data structure +commands.testfor.success=Found %s +commands.testfor.tagError=Data tag parsing failed: %s +commands.seed.usage=/seed +commands.seed.success=Seed: %s +commands.spreadplayers.usage=/spreadplayers +commands.spreadplayers.spreading.teams=Spreading %s teams %s blocks around %s,%s (min %s blocks apart) +commands.spreadplayers.spreading.players=Spreading %s players %s blocks around %s,%s (min %s blocks apart) +commands.spreadplayers.success.teams=Successfully spread %s teams around %s,%s +commands.spreadplayers.success.players=Successfully spread %s players around %s,%s +commands.spreadplayers.info.teams=(Average distance between teams is %s blocks apart after %s iterations) +commands.spreadplayers.info.players=(Average distance between players is %s blocks apart after %s iterations) +commands.spreadplayers.failure.teams=Could not spread %s teams around %s,%s (too many players for space - try using spread of at most %s) +commands.spreadplayers.failure.players=Could not spread %s players around %s,%s (too many players for space - try using spread of at most %s) +commands.achievement.usage=/achievement [player] +commands.achievement.unknownAchievement=Unknown achievement or statistic '%s' +commands.achievement.alreadyHave=Player %s already has achievement %s +commands.achievement.dontHave=Player %s doesn't have achievement %s +commands.achievement.give.success.all=Successfully given all achievements to %s +commands.achievement.give.success.one=Successfully given %s the stat %s +commands.achievement.take.success.all=Successfully taken all achievements from %s +commands.achievement.take.success.one=Successfully taken the stat %s from %s +commands.achievement.statTooLow=Player %s does not have the stat %s +commands.worldborder.usage=/worldborder ... +commands.worldborder.add.usage=/worldborder add [timeInSeconds] +commands.worldborder.set.usage=/worldborder set [timeInSeconds] +commands.worldborder.set.success=Set world border to %s blocks wide (from %s blocks) +commands.worldborder.get.success=World border is currently %s blocks wide +commands.worldborder.setSlowly.shrink.success=Shrinking world border to %s blocks wide (down from %s blocks) over %s seconds +commands.worldborder.setSlowly.grow.success=Growing world border to %s blocks wide (up from %s blocks) over %s seconds +commands.worldborder.center.usage=/worldborder center +commands.worldborder.center.success=Set world border center to %s,%s +commands.worldborder.damage.usage=/worldborder damage +commands.worldborder.damage.buffer.usage=/worldborder damage buffer +commands.worldborder.damage.buffer.success=Set world border damage buffer to %s blocks (from %s blocks) +commands.worldborder.damage.amount.usage=/worldborder damage amount +commands.worldborder.damage.amount.success=Set world border damage amount to %s per block (from %s per block) +commands.worldborder.warning.usage=/worldborder warning +commands.worldborder.warning.time.usage=/worldborder warning time +commands.worldborder.warning.time.success=Set world border warning to %s seconds away (from %s seconds) +commands.worldborder.warning.distance.usage=/worldborder warning distance +commands.worldborder.warning.distance.success=Set world border warning to %s blocks away (from %s blocks) +commands.title.usage=/title ... +commands.title.usage.title=/title title|subtitle +commands.title.usage.clear=/title clear|reset +commands.title.usage.times=/title times +commands.title.success=Title command successfully executed + +itemGroup.buildingBlocks=Building Blocks +itemGroup.decorations=Decoration Blocks +itemGroup.redstone=Redstone +itemGroup.transportation=Transportation +itemGroup.misc=Miscellaneous +itemGroup.search=Search Items +itemGroup.food=Foodstuffs +itemGroup.tools=Tools +itemGroup.combat=Combat +itemGroup.brewing=Brewing +itemGroup.materials=Materials +itemGroup.inventory=Survival Inventory + +inventory.binSlot=Destroy Item + +advMode.setCommand=Set Console Command for Block +advMode.setCommand.success=Command set: %s +advMode.command=Console Command +advMode.nearestPlayer=Use "@p" to target nearest player +advMode.randomPlayer=Use "@r" to target random player +advMode.allPlayers=Use "@a" to target all players +advMode.allEntities=Use "@e" to target all entities +advMode.previousOutput=Previous Output + +advMode.notEnabled=Command blocks are not enabled on this server +advMode.notAllowed=Must be an opped player in creative mode + +mount.onboard=Press %1$s to dismount + +build.tooHigh=Height limit for building is %s blocks + +attribute.modifier.plus.0=+%d %s +attribute.modifier.plus.1=+%d%% %s +attribute.modifier.plus.2=+%d%% %s +attribute.modifier.take.0=-%d %s +attribute.modifier.take.1=-%d%% %s +attribute.modifier.take.2=-%d%% %s + +attribute.name.horse.jumpStrength=Horse Jump Strength +attribute.name.zombie.spawnReinforcements=Zombie Reinforcements +attribute.name.generic.maxHealth=Max Health +attribute.name.generic.followRange=Mob Follow Range +attribute.name.generic.knockbackResistance=Knockback Resistance +attribute.name.generic.movementSpeed=Speed +attribute.name.generic.attackDamage=Attack Damage + +screenshot.success=Saved screenshot as %s +screenshot.failure=Couldn't save screenshot: %s + +stream.user.mode.moderator=Moderator +stream.user.mode.moderator.self=Moderator on your channel +stream.user.mode.moderator.other=Moderator on %s's channel +stream.user.mode.broadcaster=Broadcaster +stream.user.mode.broadcaster.self=Broadcaster (You!) +stream.user.mode.broadcaster.other=Broadcaster +stream.user.mode.administrator=Twitch Administrator +stream.user.mode.staff=Twitch Staff +stream.user.mode.banned=Banned +stream.user.mode.banned.self=Banned on your channel +stream.user.mode.banned.other=Banned on %s's channel +stream.user.subscription.subscriber=Subscriber +stream.user.subscription.subscriber.self=Subscriber to your channel +stream.user.subscription.subscriber.other=Subscriber to %s's channel +stream.user.subscription.turbo=Twitch Turbo + +stream.unavailable.title=Twitch Broadcasting Unavailable +stream.unavailable.report_to_mojang=Report to Mojang + +stream.confirm_start=Are you sure you want to start broadcasting? + +stream.unavailable.account_not_bound=Before you can broadcast Minecraft through Twitch, you will need to link your Twitch account on mojang.com. Would you like to do that now? +stream.unavailable.account_not_bound.okay=Link Accounts +stream.unavailable.account_not_migrated=Before you can broadcast Minecraft through Twitch, you will need to migrate your Minecraft account to a Mojang account. Would you like to do that now? +stream.unavailable.account_not_migrated.okay=Migrate Account +stream.unavailable.failed_auth=Authentication to Twitch failed. Please go to mojang.com and rebind your Twitch account. +stream.unavailable.failed_auth.okay=Rebind Accounts +stream.unavailable.failed_auth_error=Unable to authenticate to Twitch. Please try again later. +stream.unavailable.initialization_failure=Unable to initialize the Twitch SDK. +stream.unavailable.initialization_failure.extra=(Reason: %s) +stream.unavailable.library_arch_mismatch=The custom java version used to launch Minecraft has a different architecture than the one used to run the launcher. Please make sure these are the same, either 32-bit or 64-bit for both. +stream.unavailable.library_failure=Unable to load the libraries needed for the integrated Twitch broadcasting service. +stream.unavailable.no_fbo=Your video card needs to support at least OpenGL version 3.0 or support Framebuffer Objects via an extension to use the integrated Twitch broadcasting. +stream.unavailable.no_fbo.version=You are currently using: %s +stream.unavailable.no_fbo.blend=Separate blending support via EXT is: %s +stream.unavailable.no_fbo.arb=Framebuffer object support via ARB is: %s +stream.unavailable.no_fbo.ext=Framebuffer object support via EXT is: %s +stream.unavailable.not_supported.windows=Unfortunately the integrated Twitch broadcasting requires a newer version of Windows than you are on. You must have at least Windows Vista or newer. +stream.unavailable.not_supported.mac=Unfortunately the integrated Twitch broadcasting on Mac requires a version of OSX newer than the one you are on. You must use 10.7 (Mac OS X Lion) or newer to be able to use this service. Would you like to visit apple.com to learn about upgrading? +stream.unavailable.not_supported.mac.okay=Upgrade +stream.unavailable.not_supported.other=Unfortunately the integrated Twitch broadcasting service requires Windows (Vista or newer) or Mac OS X (10.7/Lion or newer) +stream.unavailable.unknown=Unfortunately you cannot broadcast to Twitch at this time. And we don't know why :'( +stream.unavailable.unknown.chat=Could not start stream: %s + +stream.unavailable.soundflower.chat=Soundflower is required to be able to stream on Mac. %s +stream.unavailable.soundflower.chat.link=Please click here to install it. + +stream.userinfo.chatTooltip=Click to manage user +stream.userinfo.timeout=Timeout +stream.userinfo.ban=Ban +stream.userinfo.unban=Unban +stream.userinfo.mod=Promote to Moderator +stream.userinfo.unmod=Demote from Moderator + +item.banner.black.name=Black Banner +item.banner.red.name=Red Banner +item.banner.green.name=Green Banner +item.banner.brown.name=Brown Banner +item.banner.blue.name=Blue Banner +item.banner.purple.name=Purple Banner +item.banner.cyan.name=Cyan Banner +item.banner.silver.name=Light Gray Banner +item.banner.gray.name=Gray Banner +item.banner.pink.name=Pink Banner +item.banner.lime.name=Lime Banner +item.banner.yellow.name=Yellow Banner +item.banner.lightBlue.name=Light Blue Banner +item.banner.magenta.name=Magenta Banner +item.banner.orange.name=Orange Banner +item.banner.white.name=White Banner + +item.banner.square_bottom_left.black=Black Base Dexter Canton +item.banner.square_bottom_left.red=Red Base Dexter Canton +item.banner.square_bottom_left.green=Green Base Dexter Canton +item.banner.square_bottom_left.brown=Brown Base Dexter Canton +item.banner.square_bottom_left.blue=Blue Base Dexter Canton +item.banner.square_bottom_left.purple=Purple Base Dexter Canton +item.banner.square_bottom_left.cyan=Cyan Base Dexter Canton +item.banner.square_bottom_left.silver=Light Gray Base Dexter Canton +item.banner.square_bottom_left.gray=Gray Base Dexter Canton +item.banner.square_bottom_left.pink=Pink Base Dexter Canton +item.banner.square_bottom_left.lime=Lime Base Dexter Canton +item.banner.square_bottom_left.yellow=Yellow Base Dexter Canton +item.banner.square_bottom_left.lightBlue=Light Blue Base Dexter Canton +item.banner.square_bottom_left.magenta=Magenta Base Dexter Canton +item.banner.square_bottom_left.orange=Orange Base Dexter Canton +item.banner.square_bottom_left.white=White Base Dexter Canton + +item.banner.square_bottom_right.black=Black Base Sinister Canton +item.banner.square_bottom_right.red=Red Base Sinister Canton +item.banner.square_bottom_right.green=Green Base Sinister Canton +item.banner.square_bottom_right.brown=Brown Base Sinister Canton +item.banner.square_bottom_right.blue=Blue Base Sinister Canton +item.banner.square_bottom_right.purple=Purple Base Sinister Canton +item.banner.square_bottom_right.cyan=Cyan Base Sinister Canton +item.banner.square_bottom_right.silver=Light Gray Base Sinister Canton +item.banner.square_bottom_right.gray=Gray Base Sinister Canton +item.banner.square_bottom_right.pink=Pink Base Sinister Canton +item.banner.square_bottom_right.lime=Lime Base Sinister Canton +item.banner.square_bottom_right.yellow=Yellow Base Sinister Canton +item.banner.square_bottom_right.lightBlue=Light Blue Base Sinister Canton +item.banner.square_bottom_right.magenta=Magenta Base Sinister Canton +item.banner.square_bottom_right.orange=Orange Base Sinister Canton +item.banner.square_bottom_right.white=White Base Sinister Canton + +item.banner.square_top_left.black=Black Chief Dexter Canton +item.banner.square_top_left.red=Red Chief Dexter Canton +item.banner.square_top_left.green=Green Chief Dexter Canton +item.banner.square_top_left.brown=Brown Chief Dexter Canton +item.banner.square_top_left.blue=Blue Chief Dexter Canton +item.banner.square_top_left.purple=Purple Chief Dexter Canton +item.banner.square_top_left.cyan=Cyan Chief Dexter Canton +item.banner.square_top_left.silver=Light Gray Chief Dexter Canton +item.banner.square_top_left.gray=Gray Chief Dexter Canton +item.banner.square_top_left.pink=Pink Chief Dexter Canton +item.banner.square_top_left.lime=Lime Chief Dexter Canton +item.banner.square_top_left.yellow=Yellow Chief Dexter Canton +item.banner.square_top_left.lightBlue=Light Blue Chief Dexter Canton +item.banner.square_top_left.magenta=Magenta Chief Dexter Canton +item.banner.square_top_left.orange=Orange Chief Dexter Canton +item.banner.square_top_left.white=White Chief Dexter Canton + +item.banner.square_top_right.black=Black Chief Sinister Canton +item.banner.square_top_right.red=Red Chief Sinister Canton +item.banner.square_top_right.green=Green Chief Sinister Canton +item.banner.square_top_right.brown=Brown Chief Sinister Canton +item.banner.square_top_right.blue=Blue Chief Sinister Canton +item.banner.square_top_right.purple=Purple Chief Sinister Canton +item.banner.square_top_right.cyan=Cyan Chief Sinister Canton +item.banner.square_top_right.silver=Light Gray Chief Sinister Canton +item.banner.square_top_right.gray=Gray Chief Sinister Canton +item.banner.square_top_right.pink=Pink Chief Sinister Canton +item.banner.square_top_right.lime=Lime Chief Sinister Canton +item.banner.square_top_right.yellow=Yellow Chief Sinister Canton +item.banner.square_top_right.lightBlue=Light Blue Chief Sinister Canton +item.banner.square_top_right.magenta=Magenta Chief Sinister Canton +item.banner.square_top_right.orange=Orange Chief Sinister Canton +item.banner.square_top_right.white=White Chief Sinister Canton + +item.banner.stripe_bottom.black=Black Base Fess +item.banner.stripe_bottom.red=Red Base Fess +item.banner.stripe_bottom.green=Green Base Fess +item.banner.stripe_bottom.brown=Brown Base Fess +item.banner.stripe_bottom.blue=Blue Base Fess +item.banner.stripe_bottom.purple=Purple Base Fess +item.banner.stripe_bottom.cyan=Cyan Base Fess +item.banner.stripe_bottom.silver=Light Gray Base Fess +item.banner.stripe_bottom.gray=Gray Base Fess +item.banner.stripe_bottom.pink=Pink Base Fess +item.banner.stripe_bottom.lime=Lime Base Fess +item.banner.stripe_bottom.yellow=Yellow Base Fess +item.banner.stripe_bottom.lightBlue=Light Blue Base Fess +item.banner.stripe_bottom.magenta=Magenta Base Fess +item.banner.stripe_bottom.orange=Orange Base Fess +item.banner.stripe_bottom.white=White Base Fess + +item.banner.stripe_top.black=Black Chief Fess +item.banner.stripe_top.red=Red Chief Fess +item.banner.stripe_top.green=Green Chief Fess +item.banner.stripe_top.brown=Brown Chief Fess +item.banner.stripe_top.blue=Blue Chief Fess +item.banner.stripe_top.purple=Purple Chief Fess +item.banner.stripe_top.cyan=Cyan Chief Fess +item.banner.stripe_top.silver=Light Gray Chief Fess +item.banner.stripe_top.gray=Gray Chief Fess +item.banner.stripe_top.pink=Pink Chief Fess +item.banner.stripe_top.lime=Lime Chief Fess +item.banner.stripe_top.yellow=Yellow Chief Fess +item.banner.stripe_top.lightBlue=Light Blue Chief Fess +item.banner.stripe_top.magenta=Magenta Chief Fess +item.banner.stripe_top.orange=Orange Chief Fess +item.banner.stripe_top.white=White Chief Fess + +item.banner.stripe_left.black=Black Pale Dexter +item.banner.stripe_left.red=Red Pale Dexter +item.banner.stripe_left.green=Green Pale Dexter +item.banner.stripe_left.brown=Brown Pale Dexter +item.banner.stripe_left.blue=Blue Pale Dexter +item.banner.stripe_left.purple=Purple Pale Dexter +item.banner.stripe_left.cyan=Cyan Pale Dexter +item.banner.stripe_left.silver=Light Gray Pale Dexter +item.banner.stripe_left.gray=Gray Pale Dexter +item.banner.stripe_left.pink=Pink Pale Dexter +item.banner.stripe_left.lime=Lime Pale Dexter +item.banner.stripe_left.yellow=Yellow Pale Dexter +item.banner.stripe_left.lightBlue=Light Blue Pale Dexter +item.banner.stripe_left.magenta=Magenta Pale Dexter +item.banner.stripe_left.orange=Orange Pale Dexter +item.banner.stripe_left.white=White Pale Dexter + +item.banner.stripe_right.black=Black Pale Sinister +item.banner.stripe_right.red=Red Pale Sinister +item.banner.stripe_right.green=Green Pale Sinister +item.banner.stripe_right.brown=Brown Pale Sinister +item.banner.stripe_right.blue=Blue Pale Sinister +item.banner.stripe_right.purple=Purple Pale Sinister +item.banner.stripe_right.cyan=Cyan Pale Sinister +item.banner.stripe_right.silver=Light Gray Pale Sinister +item.banner.stripe_right.gray=Gray Pale Sinister +item.banner.stripe_right.pink=Pink Pale Sinister +item.banner.stripe_right.lime=Lime Pale Sinister +item.banner.stripe_right.yellow=Yellow Pale Sinister +item.banner.stripe_right.lightBlue=Light Blue Pale Sinister +item.banner.stripe_right.magenta=Magenta Pale Sinister +item.banner.stripe_right.orange=Orange Pale Sinister +item.banner.stripe_right.white=White Pale Sinister + +item.banner.stripe_center.black=Black Pale +item.banner.stripe_center.red=Red Pale +item.banner.stripe_center.green=Green Pale +item.banner.stripe_center.brown=Brown Pale +item.banner.stripe_center.blue=Blue Pale +item.banner.stripe_center.purple=Purple Pale +item.banner.stripe_center.cyan=Cyan Pale +item.banner.stripe_center.silver=Light Gray Pale +item.banner.stripe_center.gray=Gray Pale +item.banner.stripe_center.pink=Pink Pale +item.banner.stripe_center.lime=Lime Pale +item.banner.stripe_center.yellow=Yellow Pale +item.banner.stripe_center.lightBlue=Light Blue Pale +item.banner.stripe_center.magenta=Magenta Pale +item.banner.stripe_center.orange=Orange Pale +item.banner.stripe_center.white=White Pale + +item.banner.stripe_middle.black=Black Fess +item.banner.stripe_middle.red=Red Fess +item.banner.stripe_middle.green=Green Fess +item.banner.stripe_middle.brown=Brown Fess +item.banner.stripe_middle.blue=Blue Fess +item.banner.stripe_middle.purple=Purple Fess +item.banner.stripe_middle.cyan=Cyan Fess +item.banner.stripe_middle.silver=Light Gray Fess +item.banner.stripe_middle.gray=Gray Fess +item.banner.stripe_middle.pink=Pink Fess +item.banner.stripe_middle.lime=Lime Fess +item.banner.stripe_middle.yellow=Yellow Fess +item.banner.stripe_middle.lightBlue=Light Blue Fess +item.banner.stripe_middle.magenta=Magenta Fess +item.banner.stripe_middle.orange=Orange Fess +item.banner.stripe_middle.white=White Fess + +item.banner.stripe_downright.black=Black Bend +item.banner.stripe_downright.red=Red Bend +item.banner.stripe_downright.green=Green Bend +item.banner.stripe_downright.brown=Brown Bend +item.banner.stripe_downright.blue=Blue Bend +item.banner.stripe_downright.purple=Purple Bend +item.banner.stripe_downright.cyan=Cyan Bend +item.banner.stripe_downright.silver=Light Gray Bend +item.banner.stripe_downright.gray=Gray Bend +item.banner.stripe_downright.pink=Pink Bend +item.banner.stripe_downright.lime=Lime Bend +item.banner.stripe_downright.yellow=Yellow Bend +item.banner.stripe_downright.lightBlue=Light Blue Bend +item.banner.stripe_downright.magenta=Magenta Bend +item.banner.stripe_downright.orange=Orange Bend +item.banner.stripe_downright.white=White Bend + +item.banner.stripe_downleft.black=Black Bend Sinister +item.banner.stripe_downleft.red=Red Bend Sinister +item.banner.stripe_downleft.green=Green Bend Sinister +item.banner.stripe_downleft.brown=Brown Bend Sinister +item.banner.stripe_downleft.blue=Blue Bend Sinister +item.banner.stripe_downleft.purple=Purple Bend Sinister +item.banner.stripe_downleft.cyan=Cyan Bend Sinister +item.banner.stripe_downleft.silver=Light Gray Bend Sinister +item.banner.stripe_downleft.gray=Gray Bend Sinister +item.banner.stripe_downleft.pink=Pink Bend Sinister +item.banner.stripe_downleft.lime=Lime Bend Sinister +item.banner.stripe_downleft.yellow=Yellow Bend Sinister +item.banner.stripe_downleft.lightBlue=Light Blue Bend Sinister +item.banner.stripe_downleft.magenta=Magenta Bend Sinister +item.banner.stripe_downleft.orange=Orange Bend Sinister +item.banner.stripe_downleft.white=White Bend Sinister + +item.banner.small_stripes.black=Black Paly +item.banner.small_stripes.red=Red Paly +item.banner.small_stripes.green=Green Paly +item.banner.small_stripes.brown=Brown Paly +item.banner.small_stripes.blue=Blue Paly +item.banner.small_stripes.purple=Purple Paly +item.banner.small_stripes.cyan=Cyan Paly +item.banner.small_stripes.silver=Light Gray Paly +item.banner.small_stripes.gray=Gray Paly +item.banner.small_stripes.pink=Pink Paly +item.banner.small_stripes.lime=Lime Paly +item.banner.small_stripes.yellow=Yellow Paly +item.banner.small_stripes.lightBlue=Light Blue Paly +item.banner.small_stripes.magenta=Magenta Paly +item.banner.small_stripes.orange=Orange Paly +item.banner.small_stripes.white=White Paly + +item.banner.cross.black=Black Saltire +item.banner.cross.red=Red Saltire +item.banner.cross.green=Green Saltire +item.banner.cross.brown=Brown Saltire +item.banner.cross.blue=Blue Saltire +item.banner.cross.purple=Purple Saltire +item.banner.cross.cyan=Cyan Saltire +item.banner.cross.silver=Light Gray Saltire +item.banner.cross.gray=Gray Saltire +item.banner.cross.pink=Pink Saltire +item.banner.cross.lime=Lime Saltire +item.banner.cross.yellow=Yellow Saltire +item.banner.cross.lightBlue=Light Blue Saltire +item.banner.cross.magenta=Magenta Saltire +item.banner.cross.orange=Orange Saltire +item.banner.cross.white=White Saltire + +item.banner.triangle_bottom.black=Black Chevron +item.banner.triangle_bottom.red=Red Chevron +item.banner.triangle_bottom.green=Green Chevron +item.banner.triangle_bottom.brown=Brown Chevron +item.banner.triangle_bottom.blue=Blue Chevron +item.banner.triangle_bottom.purple=Purple Chevron +item.banner.triangle_bottom.cyan=Cyan Chevron +item.banner.triangle_bottom.silver=Light Gray Chevron +item.banner.triangle_bottom.gray=Gray Chevron +item.banner.triangle_bottom.pink=Pink Chevron +item.banner.triangle_bottom.lime=Lime Chevron +item.banner.triangle_bottom.yellow=Yellow Chevron +item.banner.triangle_bottom.lightBlue=Light Blue Chevron +item.banner.triangle_bottom.magenta=Magenta Chevron +item.banner.triangle_bottom.orange=Orange Chevron +item.banner.triangle_bottom.white=White Chevron + +item.banner.triangle_top.black=Black Inverted Chevron +item.banner.triangle_top.red=Red Inverted Chevron +item.banner.triangle_top.green=Green Inverted Chevron +item.banner.triangle_top.brown=Brown Inverted Chevron +item.banner.triangle_top.blue=Blue Inverted Chevron +item.banner.triangle_top.purple=Purple Inverted Chevron +item.banner.triangle_top.cyan=Cyan Inverted Chevron +item.banner.triangle_top.silver=Light Gray Inverted Chevron +item.banner.triangle_top.gray=Gray Inverted Chevron +item.banner.triangle_top.pink=Pink Inverted Chevron +item.banner.triangle_top.lime=Lime Inverted Chevron +item.banner.triangle_top.yellow=Yellow Inverted Chevron +item.banner.triangle_top.lightBlue=Light Blue Inverted Chevron +item.banner.triangle_top.magenta=Magenta Inverted Chevron +item.banner.triangle_top.orange=Orange Inverted Chevron +item.banner.triangle_top.white=White Inverted Chevron + +item.banner.triangles_bottom.black=Black Base Indented +item.banner.triangles_bottom.red=Red Base Indented +item.banner.triangles_bottom.green=Green Base Indented +item.banner.triangles_bottom.brown=Brown Base Indented +item.banner.triangles_bottom.blue=Blue Base Indented +item.banner.triangles_bottom.purple=Purple Base Indented +item.banner.triangles_bottom.cyan=Cyan Base Indented +item.banner.triangles_bottom.silver=Light Gray Base Indented +item.banner.triangles_bottom.gray=Gray Base Indented +item.banner.triangles_bottom.pink=Pink Base Indented +item.banner.triangles_bottom.lime=Lime Base Indented +item.banner.triangles_bottom.yellow=Yellow Base Indented +item.banner.triangles_bottom.lightBlue=Light Blue Base Indented +item.banner.triangles_bottom.magenta=Magenta Base Indented +item.banner.triangles_bottom.orange=Orange Base Indented +item.banner.triangles_bottom.white=White Base Indented + +item.banner.triangles_top.black=Black Chief Indented +item.banner.triangles_top.red=Red Chief Indented +item.banner.triangles_top.green=Green Chief Indented +item.banner.triangles_top.brown=Brown Chief Indented +item.banner.triangles_top.blue=Blue Chief Indented +item.banner.triangles_top.purple=Purple Chief Indented +item.banner.triangles_top.cyan=Cyan Chief Indented +item.banner.triangles_top.silver=Light Gray Chief Indented +item.banner.triangles_top.gray=Gray Chief Indented +item.banner.triangles_top.pink=Pink Chief Indented +item.banner.triangles_top.lime=Lime Chief Indented +item.banner.triangles_top.yellow=Yellow Chief Indented +item.banner.triangles_top.lightBlue=Light Blue Chief Indented +item.banner.triangles_top.magenta=Magenta Chief Indented +item.banner.triangles_top.orange=Orange Chief Indented +item.banner.triangles_top.white=White Chief Indented + +item.banner.diagonal_left.black=Black Per Bend Sinister +item.banner.diagonal_left.red=Red Per Bend Sinister +item.banner.diagonal_left.green=Green Per Bend Sinister +item.banner.diagonal_left.brown=Brown Per Bend Sinister +item.banner.diagonal_left.blue=Blue Per Bend Sinister +item.banner.diagonal_left.purple=Purple Per Bend Sinister +item.banner.diagonal_left.cyan=Cyan Per Bend Sinister +item.banner.diagonal_left.silver=Light Gray Per Bend Sinister +item.banner.diagonal_left.gray=Gray Per Bend Sinister +item.banner.diagonal_left.pink=Pink Per Bend Sinister +item.banner.diagonal_left.lime=Lime Per Bend Sinister +item.banner.diagonal_left.yellow=Yellow Per Bend Sinister +item.banner.diagonal_left.lightBlue=Light Blue Per Bend Sinister +item.banner.diagonal_left.magenta=Magenta Per Bend Sinister +item.banner.diagonal_left.orange=Orange Per Bend Sinister +item.banner.diagonal_left.white=White Per Bend Sinister + +item.banner.diagonal_right.black=Black Per Bend +item.banner.diagonal_right.red=Red Per Bend +item.banner.diagonal_right.green=Green Per Bend +item.banner.diagonal_right.brown=Brown Per Bend +item.banner.diagonal_right.blue=Blue Per Bend +item.banner.diagonal_right.purple=Purple Per Bend +item.banner.diagonal_right.cyan=Cyan Per Bend +item.banner.diagonal_right.silver=Light Gray Per Bend +item.banner.diagonal_right.gray=Gray Per Bend +item.banner.diagonal_right.pink=Pink Per Bend +item.banner.diagonal_right.lime=Lime Per Bend +item.banner.diagonal_right.yellow=Yellow Per Bend +item.banner.diagonal_right.lightBlue=Light Blue Per Bend +item.banner.diagonal_right.magenta=Magenta Per Bend +item.banner.diagonal_right.orange=Orange Per Bend +item.banner.diagonal_right.white=White Per Bend + +item.banner.diagonal_up_left.black=Black Per Bend Inverted +item.banner.diagonal_up_left.red=Red Per Bend Inverted +item.banner.diagonal_up_left.green=Green Per Bend Inverted +item.banner.diagonal_up_left.brown=Brown Per Bend Inverted +item.banner.diagonal_up_left.blue=Blue Per Bend Inverted +item.banner.diagonal_up_left.purple=Purple Per Bend Inverted +item.banner.diagonal_up_left.cyan=Cyan Per Bend Inverted +item.banner.diagonal_up_left.silver=Light Gray Per Bend Inverted +item.banner.diagonal_up_left.gray=Gray Per Bend Inverted +item.banner.diagonal_up_left.pink=Pink Per Bend Inverted +item.banner.diagonal_up_left.lime=Lime Per Bend Inverted +item.banner.diagonal_up_left.yellow=Yellow Per Bend Inverted +item.banner.diagonal_up_left.lightBlue=Light Blue Per Bend Inverted +item.banner.diagonal_up_left.magenta=Magenta Per Bend Inverted +item.banner.diagonal_up_left.orange=Orange Per Bend Inverted +item.banner.diagonal_up_left.white=White Per Bend Inverted + +item.banner.diagonal_up_right.black=Black Per Bend Sinister Inverted +item.banner.diagonal_up_right.red=Red Per Bend Sinister Inverted +item.banner.diagonal_up_right.green=Green Per Bend Sinister Inverted +item.banner.diagonal_up_right.brown=Brown Per Bend Sinister Inverted +item.banner.diagonal_up_right.blue=Blue Per Bend Sinister Inverted +item.banner.diagonal_up_right.purple=Purple Per Bend Sinister Inverted +item.banner.diagonal_up_right.cyan=Cyan Per Bend Sinister Inverted +item.banner.diagonal_up_right.silver=Light Gray Per Bend Sinister Inverted +item.banner.diagonal_up_right.gray=Gray Per Bend Sinister Inverted +item.banner.diagonal_up_right.pink=Pink Per Bend Sinister Inverted +item.banner.diagonal_up_right.lime=Lime Per Bend Sinister Inverted +item.banner.diagonal_up_right.yellow=Yellow Per Bend Sinister Inverted +item.banner.diagonal_up_right.lightBlue=Light Blue Per Bend Sinister Inverted +item.banner.diagonal_up_right.magenta=Magenta Per Bend Sinister Inverted +item.banner.diagonal_up_right.orange=Orange Per Bend Sinister Inverted +item.banner.diagonal_up_right.white=White Per Bend Sinister Inverted + +item.banner.circle.black=Black Roundel +item.banner.circle.red=Red Roundel +item.banner.circle.green=Green Roundel +item.banner.circle.brown=Brown Roundel +item.banner.circle.blue=Blue Roundel +item.banner.circle.purple=Purple Roundel +item.banner.circle.cyan=Cyan Roundel +item.banner.circle.silver=Light Gray Roundel +item.banner.circle.gray=Gray Roundel +item.banner.circle.pink=Pink Roundel +item.banner.circle.lime=Lime Roundel +item.banner.circle.yellow=Yellow Roundel +item.banner.circle.lightBlue=Light Blue Roundel +item.banner.circle.magenta=Magenta Roundel +item.banner.circle.orange=Orange Roundel +item.banner.circle.white=White Roundel + +item.banner.rhombus.black=Black Lozenge +item.banner.rhombus.red=Red Lozenge +item.banner.rhombus.green=Green Lozenge +item.banner.rhombus.brown=Brown Lozenge +item.banner.rhombus.blue=Blue Lozenge +item.banner.rhombus.purple=Purple Lozenge +item.banner.rhombus.cyan=Cyan Lozenge +item.banner.rhombus.silver=Light Gray Lozenge +item.banner.rhombus.gray=Gray Lozenge +item.banner.rhombus.pink=Pink Lozenge +item.banner.rhombus.lime=Lime Lozenge +item.banner.rhombus.yellow=Yellow Lozenge +item.banner.rhombus.lightBlue=Light Blue Lozenge +item.banner.rhombus.magenta=Magenta Lozenge +item.banner.rhombus.orange=Orange Lozenge +item.banner.rhombus.white=White Lozenge + +item.banner.half_vertical.black=Black Per Pale +item.banner.half_vertical.red=Red Per Pale +item.banner.half_vertical.green=Green Per Pale +item.banner.half_vertical.brown=Brown Per Pale +item.banner.half_vertical.blue=Blue Per Pale +item.banner.half_vertical.purple=Purple Per Pale +item.banner.half_vertical.cyan=Cyan Per Pale +item.banner.half_vertical.silver=Light Gray Per Pale +item.banner.half_vertical.gray=Gray Per Pale +item.banner.half_vertical.pink=Pink Per Pale +item.banner.half_vertical.lime=Lime Per Pale +item.banner.half_vertical.yellow=Yellow Per Pale +item.banner.half_vertical.lightBlue=Light Blue Per Pale +item.banner.half_vertical.magenta=Magenta Per Pale +item.banner.half_vertical.orange=Orange Per Pale +item.banner.half_vertical.white=White Per Pale + +item.banner.half_horizontal.black=Black Per Fess +item.banner.half_horizontal.red=Red Per Fess +item.banner.half_horizontal.green=Green Per Fess +item.banner.half_horizontal.brown=Brown Per Fess +item.banner.half_horizontal.blue=Blue Per Fess +item.banner.half_horizontal.purple=Purple Per Fess +item.banner.half_horizontal.cyan=Cyan Per Fess +item.banner.half_horizontal.silver=Light Gray Per Fess +item.banner.half_horizontal.gray=Gray Per Fess +item.banner.half_horizontal.pink=Pink Per Fess +item.banner.half_horizontal.lime=Lime Per Fess +item.banner.half_horizontal.yellow=Yellow Per Fess +item.banner.half_horizontal.lightBlue=Light Blue Per Fess +item.banner.half_horizontal.magenta=Magenta Per Fess +item.banner.half_horizontal.orange=Orange Per Fess +item.banner.half_horizontal.white=White Per Fess + +item.banner.half_vertical_right.black=Black Per Pale Inverted +item.banner.half_vertical_right.red=Red Per Pale Inverted +item.banner.half_vertical_right.green=Green Per Pale Inverted +item.banner.half_vertical_right.brown=Brown Per Pale Inverted +item.banner.half_vertical_right.blue=Blue Per Pale Inverted +item.banner.half_vertical_right.purple=Purple Per Pale Inverted +item.banner.half_vertical_right.cyan=Cyan Per Pale Inverted +item.banner.half_vertical_right.silver=Light Gray Per Pale Inverted +item.banner.half_vertical_right.gray=Gray Per Pale Inverted +item.banner.half_vertical_right.pink=Pink Per Pale Inverted +item.banner.half_vertical_right.lime=Lime Per Pale Inverted +item.banner.half_vertical_right.yellow=Yellow Per Pale Inverted +item.banner.half_vertical_right.lightBlue=Light Blue Per Pale Inverted +item.banner.half_vertical_right.magenta=Magenta Per Pale Inverted +item.banner.half_vertical_right.orange=Orange Per Pale Inverted +item.banner.half_vertical_right.white=White Per Pale Inverted + +item.banner.half_horizontal_bottom.black=Black Per Fess Inverted +item.banner.half_horizontal_bottom.red=Red Per Fess Inverted +item.banner.half_horizontal_bottom.green=Green Per Fess Inverted +item.banner.half_horizontal_bottom.brown=Brown Per Fess Inverted +item.banner.half_horizontal_bottom.blue=Blue Per Fess Inverted +item.banner.half_horizontal_bottom.purple=Purple Per Fess Inverted +item.banner.half_horizontal_bottom.cyan=Cyan Per Fess Inverted +item.banner.half_horizontal_bottom.silver=Light Gray Per Fess Inverted +item.banner.half_horizontal_bottom.gray=Gray Per Fess Inverted +item.banner.half_horizontal_bottom.pink=Pink Per Fess Inverted +item.banner.half_horizontal_bottom.lime=Lime Per Fess Inverted +item.banner.half_horizontal_bottom.yellow=Yellow Per Fess Inverted +item.banner.half_horizontal_bottom.lightBlue=Light Blue Per Fess Inverted +item.banner.half_horizontal_bottom.magenta=Magenta Per Fess Inverted +item.banner.half_horizontal_bottom.orange=Orange Per Fess Inverted +item.banner.half_horizontal_bottom.white=White Per Fess Inverted + +item.banner.creeper.black=Black Creeper Charge +item.banner.creeper.red=Red Creeper Charge +item.banner.creeper.green=Green Creeper Charge +item.banner.creeper.brown=Brown Creeper Charge +item.banner.creeper.blue=Blue Creeper Charge +item.banner.creeper.purple=Purple Creeper Charge +item.banner.creeper.cyan=Cyan Creeper Charge +item.banner.creeper.silver=Light Gray Creeper Charge +item.banner.creeper.gray=Gray Creeper Charge +item.banner.creeper.pink=Pink Creeper Charge +item.banner.creeper.lime=Lime Creeper Charge +item.banner.creeper.yellow=Yellow Creeper Charge +item.banner.creeper.lightBlue=Light Blue Creeper Charge +item.banner.creeper.magenta=Magenta Creeper Charge +item.banner.creeper.orange=Orange Creeper Charge +item.banner.creeper.white=White Creeper Charge + +item.banner.bricks.black=Black Field Masoned +item.banner.bricks.red=Red Field Masoned +item.banner.bricks.green=Green Field Masoned +item.banner.bricks.brown=Brown Field Masoned +item.banner.bricks.blue=Blue Field Masoned +item.banner.bricks.purple=Purple Field Masoned +item.banner.bricks.cyan=Cyan Field Masoned +item.banner.bricks.silver=Light Gray Field Masoned +item.banner.bricks.gray=Gray Field Masoned +item.banner.bricks.pink=Pink Field Masoned +item.banner.bricks.lime=Lime Field Masoned +item.banner.bricks.yellow=Yellow Field Masoned +item.banner.bricks.lightBlue=Light Blue Field Masoned +item.banner.bricks.magenta=Magenta Field Masoned +item.banner.bricks.orange=Orange Field Masoned +item.banner.bricks.white=White Field Masoned + +item.banner.gradient.black=Black Gradient +item.banner.gradient.red=Red Gradient +item.banner.gradient.green=Green Gradient +item.banner.gradient.brown=Brown Gradient +item.banner.gradient.blue=Blue Gradient +item.banner.gradient.purple=Purple Gradient +item.banner.gradient.cyan=Cyan Gradient +item.banner.gradient.silver=Light Gray Gradient +item.banner.gradient.gray=Gray Gradient +item.banner.gradient.pink=Pink Gradient +item.banner.gradient.lime=Lime Gradient +item.banner.gradient.yellow=Yellow Gradient +item.banner.gradient.lightBlue=Light Blue Gradient +item.banner.gradient.magenta=Magenta Gradient +item.banner.gradient.orange=Orange Gradient +item.banner.gradient.white=White Gradient + +item.banner.gradient_up.black=Black Base Gradient +item.banner.gradient_up.red=Red Base Gradient +item.banner.gradient_up.green=Green Base Gradient +item.banner.gradient_up.brown=Brown Base Gradient +item.banner.gradient_up.blue=Blue Base Gradient +item.banner.gradient_up.purple=Purple Base Gradient +item.banner.gradient_up.cyan=Cyan Base Gradient +item.banner.gradient_up.silver=Light Gray Base Gradient +item.banner.gradient_up.gray=Gray Base Gradient +item.banner.gradient_up.pink=Pink Base Gradient +item.banner.gradient_up.lime=Lime Base Gradient +item.banner.gradient_up.yellow=Yellow Base Gradient +item.banner.gradient_up.lightBlue=Light Blue Base Gradient +item.banner.gradient_up.magenta=Magenta Base Gradient +item.banner.gradient_up.orange=Orange Base Gradient +item.banner.gradient_up.white=White Base Gradient + +item.banner.skull.black=Black Skull Charge +item.banner.skull.red=Red Skull Charge +item.banner.skull.green=Green Skull Charge +item.banner.skull.brown=Brown Skull Charge +item.banner.skull.blue=Blue Skull Charge +item.banner.skull.purple=Purple Skull Charge +item.banner.skull.cyan=Cyan Skull Charge +item.banner.skull.silver=Light Gray Skull Charge +item.banner.skull.gray=Gray Skull Charge +item.banner.skull.pink=Pink Skull Charge +item.banner.skull.lime=Lime Skull Charge +item.banner.skull.yellow=Yellow Skull Charge +item.banner.skull.lightBlue=Light Blue Skull Charge +item.banner.skull.magenta=Magenta Skull Charge +item.banner.skull.orange=Orange Skull Charge +item.banner.skull.white=White Skull Charge + +item.banner.flower.black=Black Flower Charge +item.banner.flower.red=Red Flower Charge +item.banner.flower.green=Green Flower Charge +item.banner.flower.brown=Brown Flower Charge +item.banner.flower.blue=Blue Flower Charge +item.banner.flower.purple=Purple Flower Charge +item.banner.flower.cyan=Cyan Flower Charge +item.banner.flower.silver=Light Gray Flower Charge +item.banner.flower.gray=Gray Flower Charge +item.banner.flower.pink=Pink Flower Charge +item.banner.flower.lime=Lime Flower Charge +item.banner.flower.yellow=Yellow Flower Charge +item.banner.flower.lightBlue=Light Blue Flower Charge +item.banner.flower.magenta=Magenta Flower Charge +item.banner.flower.orange=Orange Flower Charge +item.banner.flower.white=White Flower Charge + +item.banner.border.black=Black Bordure +item.banner.border.red=Red Bordure +item.banner.border.green=Green Bordure +item.banner.border.brown=Brown Bordure +item.banner.border.blue=Blue Bordure +item.banner.border.purple=Purple Bordure +item.banner.border.cyan=Cyan Bordure +item.banner.border.silver=Light Gray Bordure +item.banner.border.gray=Gray Bordure +item.banner.border.pink=Pink Bordure +item.banner.border.lime=Lime Bordure +item.banner.border.yellow=Yellow Bordure +item.banner.border.lightBlue=Light Blue Bordure +item.banner.border.magenta=Magenta Bordure +item.banner.border.orange=Orange Bordure +item.banner.border.white=White Bordure + +item.banner.curly_border.black=Black Bordure Indented +item.banner.curly_border.red=Red Bordure Indented +item.banner.curly_border.green=Green Bordure Indented +item.banner.curly_border.brown=Brown Bordure Indented +item.banner.curly_border.blue=Blue Bordure Indented +item.banner.curly_border.purple=Purple Bordure Indented +item.banner.curly_border.cyan=Cyan Bordure Indented +item.banner.curly_border.silver=Light Gray Bordure Indented +item.banner.curly_border.gray=Gray Bordure Indented +item.banner.curly_border.pink=Pink Bordure Indented +item.banner.curly_border.lime=Lime Bordure Indented +item.banner.curly_border.yellow=Yellow Bordure Indented +item.banner.curly_border.lightBlue=Light Blue Bordure Indented +item.banner.curly_border.magenta=Magenta Bordure Indented +item.banner.curly_border.orange=Orange Bordure Indented +item.banner.curly_border.white=White Bordure Indented + +item.banner.mojang.black=Black Thing +item.banner.mojang.red=Red Thing +item.banner.mojang.green=Green Thing +item.banner.mojang.brown=Brown Thing +item.banner.mojang.blue=Blue Thing +item.banner.mojang.purple=Purple Thing +item.banner.mojang.cyan=Cyan Thing +item.banner.mojang.silver=Light Gray Thing +item.banner.mojang.gray=Gray Thing +item.banner.mojang.pink=Pink Thing +item.banner.mojang.lime=Lime Thing +item.banner.mojang.yellow=Yellow Thing +item.banner.mojang.lightBlue=Light Blue Thing +item.banner.mojang.magenta=Magenta Thing +item.banner.mojang.orange=Orange Thing +item.banner.mojang.white=White Thing + +item.banner.straight_cross.black=Black Cross +item.banner.straight_cross.red=Red Cross +item.banner.straight_cross.green=Green Cross +item.banner.straight_cross.brown=Brown Cross +item.banner.straight_cross.blue=Blue Cross +item.banner.straight_cross.purple=Purple Cross +item.banner.straight_cross.cyan=Cyan Cross +item.banner.straight_cross.silver=Light Gray Cross +item.banner.straight_cross.gray=Gray Cross +item.banner.straight_cross.pink=Pink Cross +item.banner.straight_cross.lime=Lime Cross +item.banner.straight_cross.yellow=Yellow Cross +item.banner.straight_cross.lightBlue=Light Blue Cross +item.banner.straight_cross.magenta=Magenta Cross +item.banner.straight_cross.orange=Orange Cross +item.banner.straight_cross.white=White Cross diff --git a/azurite-server/src/main/resources/configurations/bukkit.yml b/azurite-server/src/main/resources/configurations/bukkit.yml new file mode 100644 index 0000000..32476a1 --- /dev/null +++ b/azurite-server/src/main/resources/configurations/bukkit.yml @@ -0,0 +1,43 @@ +# This is the main configuration file for Bukkit. +# As you can see, there's actually not that much to configure without any plugins. +# For a reference for any variable inside this file, check out the Bukkit Wiki at +# http://wiki.bukkit.org/Bukkit.yml +# +# If you need help on this file, feel free to join us on irc or leave a message +# on the forums asking for advice. +# +# IRC: #spigot @ irc.spi.gt +# (If this means nothing to you, just go to http://www.spigotmc.org/pages/irc/ ) +# Forums: http://www.spigotmc.org/ +# Bug tracker: http://www.spigotmc.org/go/bugs + + +settings: + allow-end: true + warn-on-overload: true + permissions-file: permissions.yml + update-folder: update + plugin-profiling: false + connection-throttle: 4000 + query-plugins: true + deprecated-verbose: default + shutdown-message: Server closed +spawn-limits: + monsters: 70 + animals: 15 + water-animals: 5 + ambient: 15 +chunk-gc: + period-in-ticks: 600 + load-threshold: 0 +ticks-per: + animal-spawns: 400 + monster-spawns: 200 + autosave: 6000 +aliases: now-in-commands.yml +database: + username: bukkit + isolation: SERIALIZABLE + driver: org.sqlite.JDBC + password: walrus + url: jdbc:sqlite:{DIR}{NAME}.db diff --git a/azurite-server/src/main/resources/configurations/commands.yml b/azurite-server/src/main/resources/configurations/commands.yml new file mode 100644 index 0000000..733307c --- /dev/null +++ b/azurite-server/src/main/resources/configurations/commands.yml @@ -0,0 +1,16 @@ +# This is the commands configuration file for Bukkit. +# For documentation on how to make use of this file, check out the Bukkit Wiki at +# http://wiki.bukkit.org/Commands.yml +# +# If you need help on this file, feel free to join us on irc or leave a message +# on the forums asking for advice. +# +# IRC: #spigot @ irc.spi.gt +# (If this means nothing to you, just go to http://www.spigotmc.org/pages/irc/ ) +# Forums: http://www.spigotmc.org/ +# Bug tracker: http://www.spigotmc.org/go/bugs + +command-block-overrides: [] +aliases: + icanhasbukkit: + - "version $1-" diff --git a/azurite-server/src/main/resources/configurations/help.yml b/azurite-server/src/main/resources/configurations/help.yml new file mode 100644 index 0000000..15c3d07 --- /dev/null +++ b/azurite-server/src/main/resources/configurations/help.yml @@ -0,0 +1,55 @@ +# This is the help configuration file for Bukkit. +# +# By default you do not need to modify this file. Help topics for all plugin commands are automatically provided by +# or extracted from your installed plugins. You only need to modify this file if you wish to add new help pages to +# your server or override the help pages of existing plugin commands. +# +# This file is divided up into the following parts: +# -- general-topics: lists admin defined help topics +# -- index-topics: lists admin defined index topics +# -- amend-topics: lists topic amendments to apply to existing help topics +# -- ignore-plugins: lists any plugins that should be excluded from help +# +# Examples are given below. When amending command topic, the string will be replaced with the existing value +# in the help topic. Color codes can be used in topic text. The color code character is & followed by 0-F. +# ================================================================ +# +# Set this to true to list the individual command help topics in the master help. +# command-topics-in-master-index: true +# +# Each general topic will show up as a separate topic in the help index along with all the plugin command topics. +# general-topics: +# Rules: +# shortText: Rules of the server +# fullText: | +# &61. Be kind to your fellow players. +# &B2. No griefing. +# &D3. No swearing. +# permission: topics.rules +# +# Each index topic will show up as a separate sub-index in the help index along with all the plugin command topics. +# To override the default help index (displayed when the user executes /help), name the index topic "Default". +# index-topics: +# Ban Commands: +# shortText: Player banning commands +# preamble: Moderator - do not abuse these commands +# permission: op +# commands: +# - /ban +# - /ban-ip +# - /banlist +# +# Topic amendments are used to change the content of automatically generated plugin command topics. +# amended-topics: +# /stop: +# shortText: Stops the server cold....in its tracks! +# fullText: - This kills the server. +# permission: you.dont.have +# +# Any plugin in the ignored plugins list will be excluded from help. The name must match the name displayed by +# the /plugins command. Ignore "Bukkit" to remove the standard bukkit commands from the index. Ignore "All" +# to completely disable automatic help topic generation. +# ignore-plugins: +# - PluginNameOne +# - PluginNameTwo +# - PluginNameThree diff --git a/azurite-server/src/main/resources/log4j2.component.properties b/azurite-server/src/main/resources/log4j2.component.properties new file mode 100644 index 0000000..d48ffa4 --- /dev/null +++ b/azurite-server/src/main/resources/log4j2.component.properties @@ -0,0 +1,3 @@ +Log4jContextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector +log4j2.AsyncQueueFullPolicy=dev.azurite.spigot.console.LogFullPolicy +log4j.skipJansi=true \ No newline at end of file diff --git a/azurite-server/src/main/resources/log4j2.xml b/azurite-server/src/main/resources/log4j2.xml new file mode 100644 index 0000000..c2ed7e4 --- /dev/null +++ b/azurite-server/src/main/resources/log4j2.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..1f53f6d --- /dev/null +++ b/pom.xml @@ -0,0 +1,22 @@ + + 4.0.0 + + + clean package + + + dev.azurite.spigot + AzuriteSpigot + 1.0 + pom + + + azurite-server + azurite-api + + + + UTF-8 + + \ No newline at end of file